ronantakizawa/codereview-bench huggingface dataset:
Repository: trpc/trpc
File: packages/tanstack-react-query/src/internals/createOptionsProxy.ts (TypeScript)

Code before:
            procedures: opts.router._def.procedures,
            path: path,
            getRawInput: async () => input,
            ctx: ctx,
            type: type,
            signal: undefined,
          }),
        );
      }

      const untypedClient =
        opts.client instanceof TRPCUntypedClient
          ? opts.client
          : getUntypedClient(opts.client);

      return untypedClient[type](path, input, trpcOpts);
    };
  };

  return createRecursiveProxy(({ args, path: _path }) => {
    const path = [..._path];
    const utilName = path.pop() as UtilsMethods;
    const [arg1, arg2] = args as any[];

    const queryType = getQueryType(utilName);

    function getQueryKey() {
      return getQueryKeyInternal(path, arg1, queryType ?? 'any');
    }

    const contextMap: Record<UtilsMethods, () => unknown> = {
      '~types': undefined as any,

      mutationKey: () => {
        return getMutationKeyInternal(path);
      },
      queryKey: () => {
        return getQueryKey();
      },
      queryFilter: (): QueryFilters => {
        return {
          ...arg2,
          queryKey: getQueryKey(),
        };
      },
      infiniteQueryOptions: () => {
        return trpcInfiniteQueryOptions({
          opts: arg2,
          path,
          queryClient: opts.queryClient,
          queryKey: getQueryKey(),

Review comment (bug):
Have a probable small bug here where arg1 is always used for a query key... well not every method has inputs at all, some will just have options

Converted to a function so we can save compute occasionally but will need a way to differentiate a procedure from a router in queryKey etc

Code after:
          callProcedure({
            procedures: opts.router._def.procedures,
            path: path,
            getRawInput: async () => input,
            ctx: ctx,
            type: type,
            signal: undefined,
          }),
        );
      }

      const untypedClient =
        opts.client instanceof TRPCUntypedClient
          ? opts.client
          : getUntypedClient(opts.client);

      return untypedClient[type](path, input, trpcOpts);
    };
  };

  return createRecursiveProxy(({ args, path: _path }) => {
    const path = [..._path];
    const utilName = path.pop() as UtilsMethods;
    const [arg1, arg2] = args as any[];

    function getQueryKey() {
      const queryType = getQueryType(utilName);

      return getQueryKeyInternal(path, arg1, queryType ?? 'any');
    }

    const contextMap: Record<UtilsMethods, () => unknown> = {
      '~types': undefined as any,

      mutationKey: () => {
        return getMutationKeyInternal(path);
      },
      queryKey: () => {
        return getQueryKey();
      },
      queryFilter: (): QueryFilters => {
        return {
          ...arg2,
          queryKey: getQueryKey(),
        };
      },
      infiniteQueryOptions: () => {
        return trpcInfiniteQueryOptions({
          opts: arg2,
          path,
          queryClient: opts.queryClient,
Repository: trpc/trpc
File: packages/tanstack-react-query/test/queryKeyable.test.tsx (TypeScript)

Code before:

    ctx.renderApp(<Component />);
  });

  test('type inference for query filters', async () => {
    await using ctx = testContext();

    const { useTRPC } = ctx;

    function Component() {
      const trpc = useTRPC();
      const query = useQueryClient();

      const a = trpc.bluesky.post.byId.queryFilter(
        { id: '1' },
        {
          predicate(query) {
            const data = query.setData('__result');
            assertType<'__result' | undefined>(data);

            return true;
          },
        },
      );

      // Fix the lint error and typescript complains, the lint error is wrong
      // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
      const b = query.getQueryData(a.queryKey!);
      assertType<'__result' | undefined>(b);

      return 'some text';
    }

    ctx.renderApp(<Component />);
  });
});

describe('get queryKey', () => {
  test('gets various query keys', async () => {
    await using ctx = testContext();

    const { useTRPC } = ctx;

    function Component() {
      const trpc = useTRPC();
      const query = useQueryClient();

      query.setQueryData(
        trpc.bluesky.post.byId.queryKey({ id: '1' }),
        '__result',
      );

Review comment (bug):
Not sure why it's complaining here, tslint is wrong. Fix the warning and typescript complains instead

Code after:

    ctx.renderApp(<Component />);
  });

  test('type inference for query filters', async () => {
    await using ctx = testContext();

    const { useTRPC } = ctx;

    function Component() {
      const trpc = useTRPC();
      const query = useQueryClient();

      const a = trpc.bluesky.post.byId.queryFilter(
        { id: '1' },
        {
          predicate(query) {
            const data = query.setData('__result');
            assertType<'__result' | undefined>(data);

            return true;
          },
        },
      );

      // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
      const b = query.getQueryData(a.queryKey!);
      assertType<'__result' | undefined>(b);

      return 'some text';
    }

    ctx.renderApp(<Component />);
  });
});

describe('get queryKey', () => {
  test('gets various query keys', async () => {
    await using ctx = testContext();

    const { useTRPC } = ctx;

    function Component() {
      const trpc = useTRPC();
      const query = useQueryClient();

      query.setQueryData(
        trpc.bluesky.post.byId.queryKey({ id: '1' }),
        '__result',
      );
Repository: trpc/trpc
File: packages/server/src/unstable-core-do-not-import/stream/sse.test.ts (TypeScript)

Code before:
      yield tracked(String(i), i);

      await new Promise((resolve) => setTimeout(resolve, 5));
    }
  }
  type Data = inferAsyncIterableYield<ReturnType<typeof data>>;

  const written: string[] = [];

  await using server = serverResource(async (request) => {
    const url = new URL(request.url);

    const lastEventId: string | null =
      request.headers.get('last-event-id') ??
      url.searchParams.get('lastEventId') ??
      url.searchParams.get('Last-Event-Id');

    const stream = sseStreamProducer({
      data: data(lastEventId ?? undefined),
      serialize: (v) => SuperJSON.serialize(v),
    })
      .pipeThrough(
        // debug stream
        new TransformStream({
          transform: (chunk, controller) => {
            controller.enqueue(chunk);
          },
        }),
      )
      .pipeThrough(new TextDecoderStream())
      .pipeThrough(
        new TransformStream({
          transform(chunk, controller) {
            written.push(chunk);
            controller.enqueue(chunk);
          },
        }),
      );

    return new Response(stream, {
      headers: sseHeaders,
    });
  });

  const ac = new AbortController();
  const iterable = sseStreamConsumer<{
    data: Data;
    error: unknown;
    EventSource: typeof EventSourcePolyfill;
  }>({
    url: () => server.url,

Review comment (bug):
```suggestion
            // console.debug('debug', chunk);
            written.push(chunk);
            controller.enqueue(chunk);
```

Code after:
      yield tracked(String(i), i);

      await new Promise((resolve) => setTimeout(resolve, 5));
    }
  }
  type Data = inferAsyncIterableYield<ReturnType<typeof data>>;

  const written: string[] = [];

  await using server = serverResource(async (request) => {
    const url = new URL(request.url);

    const lastEventId: string | null =
      request.headers.get('last-event-id') ??
      url.searchParams.get('lastEventId') ??
      url.searchParams.get('Last-Event-Id');

    const stream = sseStreamProducer({
      data: data(lastEventId ?? undefined),
      serialize: (v) => SuperJSON.serialize(v),
    })
      .pipeThrough(new TextDecoderStream())
      .pipeThrough(
        // debug stream
        new TransformStream({
          transform(chunk, controller) {
            written.push(chunk);
            controller.enqueue(chunk);
          },
        }),
      );

    return new Response(stream, {
      headers: sseHeaders,
    });
  });

  const ac = new AbortController();
  const iterable = sseStreamConsumer<{
    data: Data;
    error: unknown;
    EventSource: typeof EventSourcePolyfill;
  }>({
    url: () => server.url,
    signal: ac.signal,
    init: () => ({
      lastEventIdQueryParameterName: 'lastEventId',
    }),
    deserialize: SuperJSON.deserialize,
    EventSource: EventSourcePolyfill,
  });
Repository: trpc/trpc
File: packages/server/src/unstable-core-do-not-import/stream/sse.test.ts (TypeScript)

Code before:
      await new Promise((resolve) => setTimeout(resolve, 5));
    }
  }
  type Data = inferAsyncIterableYield<ReturnType<typeof data>>;

  const written: string[] = [];

  await using server = serverResource(async (request) => {
    const url = new URL(request.url);

    const lastEventId: string | null =
      request.headers.get('last-event-id') ??
      url.searchParams.get('lastEventId') ??
      url.searchParams.get('Last-Event-Id');

    const stream = sseStreamProducer({
      data: data(lastEventId ?? undefined),
      serialize: (v) => SuperJSON.serialize(v),
    })
      .pipeThrough(
        // debug stream
        new TransformStream({
          transform: (chunk, controller) => {
            // console.debug('debug', chunk);
            written.push(chunk);
            controller.enqueue(chunk);
          },
        }),
      )
      .pipeThrough(new TextDecoderStream())
      .pipeThrough(
        new TransformStream({
          transform(chunk, controller) {
            written.push(chunk);
            controller.enqueue(chunk);
          },
        }),
      );

    return new Response(stream, {
      headers: sseHeaders,
    });
  });

  const ac = new AbortController();
  const iterable = sseStreamConsumer<{
    data: Data;
    error: unknown;
    EventSource: typeof EventSourcePolyfill;
  }>({
    url: () => server.url,

Review comment (suggestion):
```suggestion
            controller.enqueue(chunk);
```

Code after:
      await new Promise((resolve) => setTimeout(resolve, 5));
    }
  }
  type Data = inferAsyncIterableYield<ReturnType<typeof data>>;

  const written: string[] = [];

  await using server = serverResource(async (request) => {
    const url = new URL(request.url);

    const lastEventId: string | null =
      request.headers.get('last-event-id') ??
      url.searchParams.get('lastEventId') ??
      url.searchParams.get('Last-Event-Id');

    const stream = sseStreamProducer({
      data: data(lastEventId ?? undefined),
      serialize: (v) => SuperJSON.serialize(v),
    })
      .pipeThrough(new TextDecoderStream())
      .pipeThrough(
        // debug stream
        new TransformStream({
          transform(chunk, controller) {
            written.push(chunk);
            controller.enqueue(chunk);
          },
        }),
      );

    return new Response(stream, {
      headers: sseHeaders,
    });
  });

  const ac = new AbortController();
  const iterable = sseStreamConsumer<{
    data: Data;
    error: unknown;
    EventSource: typeof EventSourcePolyfill;
  }>({
    url: () => server.url,
    signal: ac.signal,
    init: () => ({
      lastEventIdQueryParameterName: 'lastEventId',
    }),
    deserialize: SuperJSON.deserialize,
    EventSource: EventSourcePolyfill,
  });
  let es: EventSource | null = null;
Repository: trpc/trpc
File: packages/client/src/createTRPCClient.ts (TypeScript)

Code before:
 **/
export type inferRouterClient<TRouter extends AnyRouter> = TRPCClient<TRouter>;

/**
 * @public
 * @deprecated use {@link TRPCClient} instead, will be removed in v12
 **/
export type CreateTRPCClient<TRouter extends AnyRouter> = TRPCClient<TRouter>;

const untypedClientSymbol = Symbol.for('trpc_untypedClient');

/**
 * @public
 **/
export type TRPCClient<TRouter extends AnyRouter> = DecoratedProcedureRecord<
  {
    transformer: TRouter['_def']['_config']['$types']['transformer'];
    errorShape: TRouter['_def']['_config']['$types']['errorShape'];
  },
  TRouter['_def']['record']
> & {
  [untypedClientSymbol]: TRPCUntypedClient<TRouter>;
};

/** @internal */
export type ResolverDef = {
  input: any;
  output: any;
  transformer: boolean;
  errorShape: any;
};

type coerceAsyncGeneratorToIterable<T> =
  T extends AsyncGenerator<infer $T, infer $Return, infer $Next>
    ? AsyncIterable<$T, $Return, $Next>
    : T;

/** @internal */
export type Resolver<TDef extends ResolverDef> = (
  input: TDef['input'],
  opts?: TRPCProcedureOptions,
) => Promise<coerceAsyncGeneratorToIterable<TDef['output']>>;

/** @internal */
export type SubscriptionResolver<TDef extends ResolverDef> = (
  input: TDef['input'],
  opts: Partial<
    TRPCSubscriptionObserver<TDef['output'], TRPCClientError<TDef>>
  > &
    TRPCProcedureOptions,
) => Unsubscribable;

Review comment (suggestion):
remove @internal and smurf it as `TRPCResolverDef` ?

I've been wanting this type as well sometimes

Code after:
 **/
export type inferRouterClient<TRouter extends AnyRouter> = TRPCClient<TRouter>;

/**
 * @public
 * @deprecated use {@link TRPCClient} instead, will be removed in v12
 **/
export type CreateTRPCClient<TRouter extends AnyRouter> = TRPCClient<TRouter>;

const untypedClientSymbol = Symbol.for('trpc_untypedClient');

/**
 * @public
 **/
export type TRPCClient<TRouter extends AnyRouter> = DecoratedProcedureRecord<
  {
    transformer: TRouter['_def']['_config']['$types']['transformer'];
    errorShape: TRouter['_def']['_config']['$types']['errorShape'];
  },
  TRouter['_def']['record']
> & {
  [untypedClientSymbol]: TRPCUntypedClient<TRouter>;
};

/** @internal */
export type TRPCResolverDef = {
  input: any;
  output: any;
  transformer: boolean;
  errorShape: any;
};

type coerceAsyncGeneratorToIterable<T> =
  T extends AsyncGenerator<infer $T, infer $Return, infer $Next>
    ? AsyncIterable<$T, $Return, $Next>
    : T;

/** @internal */
export type Resolver<TDef extends TRPCResolverDef> = (
  input: TDef['input'],
  opts?: TRPCProcedureOptions,
) => Promise<coerceAsyncGeneratorToIterable<TDef['output']>>;

/** @internal */
export type SubscriptionResolver<TDef extends TRPCResolverDef> = (
  input: TDef['input'],
  opts: Partial<
    TRPCSubscriptionObserver<TDef['output'], TRPCClientError<TDef>>
  > &
    TRPCProcedureOptions,
) => Unsubscribable;
Repository: trpc/trpc
File: packages/client/src/createTRPCClient.ts (TypeScript)

Code before:
 **/
export type inferRouterClient<TRouter extends AnyRouter> = TRPCClient<TRouter>;

/**
 * @public
 * @deprecated use {@link TRPCClient} instead, will be removed in v12
 **/
export type CreateTRPCClient<TRouter extends AnyRouter> = TRPCClient<TRouter>;

const untypedClientSymbol = Symbol.for('trpc_untypedClient');

/**
 * @public
 **/
export type TRPCClient<TRouter extends AnyRouter> = DecoratedProcedureRecord<
  {
    transformer: TRouter['_def']['_config']['$types']['transformer'];
    errorShape: TRouter['_def']['_config']['$types']['errorShape'];
  },
  TRouter['_def']['record']
> & {
  [untypedClientSymbol]: TRPCUntypedClient<TRouter>;
};

export type TRPCResolverDef = {
  input: any;
  output: any;
  transformer: boolean;
  errorShape: any;
};

type coerceAsyncGeneratorToIterable<T> =
  T extends AsyncGenerator<infer $T, infer $Return, infer $Next>
    ? AsyncIterable<$T, $Return, $Next>
    : T;

/** @internal */
export type Resolver<TDef extends TRPCResolverDef> = (
  input: TDef['input'],
  opts?: TRPCProcedureOptions,
) => Promise<coerceAsyncGeneratorToIterable<TDef['output']>>;

/** @internal */
export type SubscriptionResolver<TDef extends TRPCResolverDef> = (
  input: TDef['input'],
  opts: Partial<
    TRPCSubscriptionObserver<TDef['output'], TRPCClientError<TDef>>
  > &
    TRPCProcedureOptions,
) => Unsubscribable;


Review comment (suggestion):
```suggestion
/** @internal */
export type TRPCResolverDef = {
```

Code after:
 **/
export type inferRouterClient<TRouter extends AnyRouter> = TRPCClient<TRouter>;

/**
 * @public
 * @deprecated use {@link TRPCClient} instead, will be removed in v12
 **/
export type CreateTRPCClient<TRouter extends AnyRouter> = TRPCClient<TRouter>;

const untypedClientSymbol = Symbol.for('trpc_untypedClient');

/**
 * @public
 **/
export type TRPCClient<TRouter extends AnyRouter> = DecoratedProcedureRecord<
  {
    transformer: TRouter['_def']['_config']['$types']['transformer'];
    errorShape: TRouter['_def']['_config']['$types']['errorShape'];
  },
  TRouter['_def']['record']
> & {
  [untypedClientSymbol]: TRPCUntypedClient<TRouter>;
};

/** @internal */
export type TRPCResolverDef = {
  input: any;
  output: any;
  transformer: boolean;
  errorShape: any;
};

type coerceAsyncGeneratorToIterable<T> =
  T extends AsyncGenerator<infer $T, infer $Return, infer $Next>
    ? AsyncIterable<$T, $Return, $Next>
    : T;

/** @internal */
export type Resolver<TDef extends TRPCResolverDef> = (
  input: TDef['input'],
  opts?: TRPCProcedureOptions,
) => Promise<coerceAsyncGeneratorToIterable<TDef['output']>>;

/** @internal */
export type SubscriptionResolver<TDef extends TRPCResolverDef> = (
  input: TDef['input'],
  opts: Partial<
    TRPCSubscriptionObserver<TDef['output'], TRPCClientError<TDef>>
  > &
    TRPCProcedureOptions,
) => Unsubscribable;
Repository: twentyhq/twenty
File: packages/twenty-server/src/modules/contact-creation-manager/utils/filter-out-contacts-from-company-or-workspace.util.ts (TypeScript)

Code before:
import { Contact } from 'src/modules/contact-creation-manager/types/contact.type';
import { getDomainNameFromHandle } from 'src/modules/contact-creation-manager/utils/get-domain-name-from-handle.util';
import { WorkspaceMemberWorkspaceEntity } from 'src/modules/workspace-member/standard-objects/workspace-member.workspace-entity';

export function filterOutSelfAndContactsFromCompanyOrWorkspace(
  contacts: Contact[],
  connectedAccount: ConnectedAccountWorkspaceEntity,
  workspaceMembers: WorkspaceMemberWorkspaceEntity[],
): Contact[] {
  const selfDomainName = getDomainNameFromHandle(connectedAccount.handle);

  const handleAliases = connectedAccount.handleAliases?.split(',') || [];

  const workspaceMembersMap = workspaceMembers.reduce(
    (map, workspaceMember) => {
      map[workspaceMember.userEmail] = true;

      return map;
    },
    new Map<string, boolean>(),
  );

  // TODO : find a better way to enable organization1.onmicrosoft.com to add user from organization2.onmicrosoft.com
  const isDifferentDomain = (contact: Contact, selfDomainName: string) =>
    getDomainNameFromHandle(contact.handle) !== selfDomainName ||
    selfDomainName === 'onmicrosoft.com';

  return contacts.filter(
    (contact) =>
      isDifferentDomain(contact, selfDomainName) &&
      !workspaceMembersMap[contact.handle] &&
      !handleAliases.includes(contact.handle),
  );
}


Review comment (suggestion):
in this case shouldn't we check the subdomain from onmicrosoft.com?
`|| ( selfDomainName === 'onmicrosoft.com' && subdomain1 <> subdomain2)`

Code after:
import { Contact } from 'src/modules/contact-creation-manager/types/contact.type';
import { getDomainNameFromHandle } from 'src/modules/contact-creation-manager/utils/get-domain-name-from-handle.util';
import { WorkspaceMemberWorkspaceEntity } from 'src/modules/workspace-member/standard-objects/workspace-member.workspace-entity';
import { isWorkDomain } from 'src/utils/is-work-email';

export function filterOutSelfAndContactsFromCompanyOrWorkspace(
  contacts: Contact[],
  connectedAccount: ConnectedAccountWorkspaceEntity,
  workspaceMembers: WorkspaceMemberWorkspaceEntity[],
): Contact[] {
  const selfDomainName = getDomainNameFromHandle(connectedAccount.handle);

  const handleAliases = connectedAccount.handleAliases?.split(',') || [];

  const workspaceMembersMap = workspaceMembers.reduce(
    (map, workspaceMember) => {
      map[workspaceMember.userEmail] = true;

      return map;
    },
    new Map<string, boolean>(),
  );

  const isDifferentDomain = (contact: Contact, selfDomainName: string) =>
    getDomainNameFromHandle(contact.handle) !== selfDomainName;

  return contacts.filter(
    (contact) =>
      (isDifferentDomain(contact, selfDomainName) ||
        !isWorkDomain(selfDomainName)) &&
      !workspaceMembersMap[contact.handle] &&
      !handleAliases.includes(contact.handle),
  );
}
Repository: twentyhq/twenty
File: packages/twenty-server/src/engine/core-modules/graphql/hooks/use-compute-complexity.hook.ts (TypeScript)

Code before:
import { type ValidationContext } from 'graphql';
import { type Plugin } from 'graphql-yoga';

import { UserInputError } from 'src/engine/core-modules/graphql/utils/graphql-errors.util';

export const useComputeComplexity = (maximumComplexity: number): Plugin => ({
  onValidate: ({ addValidationRule }) => {
    addValidationRule((context: ValidationContext) => {
      let complexity = 0;

      return {
        Field() {
          complexity++;
        },
        Document: {
          leave() {
            if (complexity > maximumComplexity) {
              context.reportError(
                new UserInputError(
                  `Query complexity is too high: ${complexity} - Too many fields requested`,
                ),
              );
            }
          },
        },
      };
    });
  },
});


Review comment (suggestion):
Very cool!!! Could we add tests?  Not the biggest advocate for tests but it feels like the kind of thing that would deserve it

Is there a limit on the number of objects? I guess that if I do 200 joins it could break the server even if I don't fetch 2000 fields? GroupBy is also protected by this you think?  Sorry I guess you already discussed this with someone but I'm curious

Code after:
import { msg } from '@lingui/core/macro';
import { type ValidationContext } from 'graphql';
import { type Plugin } from 'graphql-yoga';

import { UserInputError } from 'src/engine/core-modules/graphql/utils/graphql-errors.util';

export const useComputeComplexity = (maximumComplexity: number): Plugin => ({
  onValidate: ({ addValidationRule }) => {
    addValidationRule((context: ValidationContext) => {
      let complexity = 0;

      return {
        Field() {
          complexity++;
        },
        Document: {
          leave() {
            if (complexity > maximumComplexity) {
              context.reportError(
                new UserInputError(
                  `Query complexity is too high: ${complexity} - Too many fields requested`,
                  {
                    userFriendlyMessage: msg`The request is too complex to process. Please try reducing the amount of data requested.`,
                  },
                ),
              );
            }
          },
        },
      };
    });