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

Code before:
  getQueryData: (queryKey: TRPCQueryKey) => unknown;

  /**
   * @link https://tanstack.com/query/v5/docs/reference/QueryClient#queryclientsetquerydata
   */
  setInfiniteQueryData: (
    queryKey: TRPCQueryKey,
    updater: Updater<
      InfiniteData<unknown> | undefined,
      InfiniteData<unknown> | undefined
    >,
    options?: SetDataOptions,
  ) => void;

  /**
   * @link https://tanstack.com/query/v5/docs/reference/QueryClient#queryclientgetquerydata
   */
  getInfiniteQueryData: (
    queryKey: TRPCQueryKey,
  ) => InfiniteData<unknown> | undefined;

  /**
   * @link https://tanstack.com/query/latest/docs/reference/QueryClient/#queryclientsetmutationdefaults
   */
  setMutationDefaults: (
    mutationKey: string[][],
    options: MutationOptions,
  ) => void;

  /**
   * @link https://tanstack.com/query/latest/docs/reference/QueryClient#queryclientgetmutationdefaults
   */
  getMutationDefaults: (mutationKey: string[][]) => MutationOptions | undefined;
}
export const TRPCContext = React.createContext?.(null as any);


Review comment (suggestion):
Not sure about this type. `string[][]` should be better than `MutationKey` from TanStack Query, which is defined as `ReadonlyArray<unknown>`. But I am not sure what the relationship between this type and `TRPCQueryKey` should be, assuming there should be a relationship

Code after:
  getQueryData: (queryKey: TRPCQueryKey) => unknown;

  /**
   * @link https://tanstack.com/query/v5/docs/reference/QueryClient#queryclientsetquerydata
   */
  setInfiniteQueryData: (
    queryKey: TRPCQueryKey,
    updater: Updater<
      InfiniteData<unknown> | undefined,
      InfiniteData<unknown> | undefined
    >,
    options?: SetDataOptions,
  ) => void;

  /**
   * @link https://tanstack.com/query/v5/docs/reference/QueryClient#queryclientgetquerydata
   */
  getInfiniteQueryData: (
    queryKey: TRPCQueryKey,
  ) => InfiniteData<unknown> | undefined;

  /**
   * @link https://tanstack.com/query/latest/docs/reference/QueryClient/#queryclientsetmutationdefaults
   */
  setMutationDefaults: (
    mutationKey: TRPCMutationKey,
    options:
      | MutationOptions
      | ((args: {
          canonicalMutationFn: (input: unknown) => Promise<unknown>;
        }) => MutationOptions),
  ) => void;

  /**
   * @link https://tanstack.com/query/latest/docs/reference/QueryClient#queryclientgetmutationdefaults
   */
  getMutationDefaults: (
    mutationKey: TRPCMutationKey,
  ) => MutationOptions | undefined;

  /**
   * @link https://tanstack.com/query/latest/docs/reference/QueryClient#queryclientismutating
   */
  isMutating: (filters: { mutationKey: TRPCMutationKey }) => number;
}
export const TRPCContext = React.createContext?.(null as any);
Repository: trpc/trpc
File: packages/react-query/src/internals/context.tsx (TypeScript)

Code before:
  getQueryData: (queryKey: TRPCQueryKey) => unknown;

  /**
   * @link https://tanstack.com/query/v5/docs/reference/QueryClient#queryclientsetquerydata
   */
  setInfiniteQueryData: (
    queryKey: TRPCQueryKey,
    updater: Updater<
      InfiniteData<unknown> | undefined,
      InfiniteData<unknown> | undefined
    >,
    options?: SetDataOptions,
  ) => void;

  /**
   * @link https://tanstack.com/query/v5/docs/reference/QueryClient#queryclientgetquerydata
   */
  getInfiniteQueryData: (
    queryKey: TRPCQueryKey,
  ) => InfiniteData<unknown> | undefined;

  /**
   * @link https://tanstack.com/query/latest/docs/reference/QueryClient/#queryclientsetmutationdefaults
   */
  setMutationDefaults: (
    mutationKey: [string[]],
    options:
      | MutationOptions
      | ((args: {
          canonicalMutationFn: (input: unknown) => Promise<unknown>;
        }) => MutationOptions),
  ) => void;

  /**
   * @link https://tanstack.com/query/latest/docs/reference/QueryClient#queryclientgetmutationdefaults
   */
  getMutationDefaults: (mutationKey: [string[]]) => MutationOptions | undefined;

  /**
   * @link https://tanstack.com/query/latest/docs/reference/QueryClient#queryclientismutating
   */
  isMutating: (filters: { mutationKey: [string[]] }) => number;
}
export const TRPCContext = React.createContext?.(null as any);


Review comment (suggestion):
iirc our mutationKeys use the same structure?

```suggestion
    mutationKey: TRPCQueryKey,
```

Code after:
  getQueryData: (queryKey: TRPCQueryKey) => unknown;

  /**
   * @link https://tanstack.com/query/v5/docs/reference/QueryClient#queryclientsetquerydata
   */
  setInfiniteQueryData: (
    queryKey: TRPCQueryKey,
    updater: Updater<
      InfiniteData<unknown> | undefined,
      InfiniteData<unknown> | undefined
    >,
    options?: SetDataOptions,
  ) => void;

  /**
   * @link https://tanstack.com/query/v5/docs/reference/QueryClient#queryclientgetquerydata
   */
  getInfiniteQueryData: (
    queryKey: TRPCQueryKey,
  ) => InfiniteData<unknown> | undefined;

  /**
   * @link https://tanstack.com/query/latest/docs/reference/QueryClient/#queryclientsetmutationdefaults
   */
  setMutationDefaults: (
    mutationKey: TRPCMutationKey,
    options:
      | MutationOptions
      | ((args: {
          canonicalMutationFn: (input: unknown) => Promise<unknown>;
        }) => MutationOptions),
  ) => void;

  /**
   * @link https://tanstack.com/query/latest/docs/reference/QueryClient#queryclientgetmutationdefaults
   */
  getMutationDefaults: (
    mutationKey: TRPCMutationKey,
  ) => MutationOptions | undefined;

  /**
   * @link https://tanstack.com/query/latest/docs/reference/QueryClient#queryclientismutating
   */
  isMutating: (filters: { mutationKey: TRPCMutationKey }) => number;
}
export const TRPCContext = React.createContext?.(null as any);
Repository: trpc/trpc
File: packages/react-query/src/internals/context.tsx (TypeScript)

Code before:
    options?: SetDataOptions,
  ) => void;

  /**
   * @link https://tanstack.com/query/v5/docs/reference/QueryClient#queryclientgetquerydata
   */
  getInfiniteQueryData: (
    queryKey: TRPCQueryKey,
  ) => InfiniteData<unknown> | undefined;

  /**
   * @link https://tanstack.com/query/latest/docs/reference/QueryClient/#queryclientsetmutationdefaults
   */
  setMutationDefaults: (
    mutationKey: [string[]],
    options:
      | MutationOptions
      | ((args: {
          canonicalMutationFn: (input: unknown) => Promise<unknown>;
        }) => MutationOptions),
  ) => void;

  /**
   * @link https://tanstack.com/query/latest/docs/reference/QueryClient#queryclientgetmutationdefaults
   */
  getMutationDefaults: (mutationKey: [string[]]) => MutationOptions | undefined;

  /**
   * @link https://tanstack.com/query/latest/docs/reference/QueryClient#queryclientismutating
   */
  isMutating: (filters: { mutationKey: [string[]] }) => number;
}
export const TRPCContext = React.createContext?.(null as any);


Review comment (suggestion):
```suggestion
  getMutationDefaults: (mutationKey: TRPCQueryKey) => MutationOptions | undefined;
```

Code after:
    options?: SetDataOptions,
  ) => void;

  /**
   * @link https://tanstack.com/query/v5/docs/reference/QueryClient#queryclientgetquerydata
   */
  getInfiniteQueryData: (
    queryKey: TRPCQueryKey,
  ) => InfiniteData<unknown> | undefined;

  /**
   * @link https://tanstack.com/query/latest/docs/reference/QueryClient/#queryclientsetmutationdefaults
   */
  setMutationDefaults: (
    mutationKey: TRPCMutationKey,
    options:
      | MutationOptions
      | ((args: {
          canonicalMutationFn: (input: unknown) => Promise<unknown>;
        }) => MutationOptions),
  ) => void;

  /**
   * @link https://tanstack.com/query/latest/docs/reference/QueryClient#queryclientgetmutationdefaults
   */
  getMutationDefaults: (
    mutationKey: TRPCMutationKey,
  ) => MutationOptions | undefined;

  /**
   * @link https://tanstack.com/query/latest/docs/reference/QueryClient#queryclientismutating
   */
  isMutating: (filters: { mutationKey: TRPCMutationKey }) => number;
}
export const TRPCContext = React.createContext?.(null as any);
Repository: trpc/trpc
File: packages/react-query/src/internals/context.tsx (TypeScript)

Code before:
   */
  getInfiniteQueryData: (
    queryKey: TRPCQueryKey,
  ) => InfiniteData<unknown> | undefined;

  /**
   * @link https://tanstack.com/query/latest/docs/reference/QueryClient/#queryclientsetmutationdefaults
   */
  setMutationDefaults: (
    mutationKey: [string[]],
    options:
      | MutationOptions
      | ((args: {
          canonicalMutationFn: (input: unknown) => Promise<unknown>;
        }) => MutationOptions),
  ) => void;

  /**
   * @link https://tanstack.com/query/latest/docs/reference/QueryClient#queryclientgetmutationdefaults
   */
  getMutationDefaults: (mutationKey: [string[]]) => MutationOptions | undefined;

  /**
   * @link https://tanstack.com/query/latest/docs/reference/QueryClient#queryclientismutating
   */
  isMutating: (filters: { mutationKey: [string[]] }) => number;
}
export const TRPCContext = React.createContext?.(null as any);


Review comment (suggestion):
```suggestion
isMutating: (filters: { mutationKey: TRPCQueryKey }) => number;
```

Code after:
   */
  getInfiniteQueryData: (
    queryKey: TRPCQueryKey,
  ) => InfiniteData<unknown> | undefined;

  /**
   * @link https://tanstack.com/query/latest/docs/reference/QueryClient/#queryclientsetmutationdefaults
   */
  setMutationDefaults: (
    mutationKey: TRPCMutationKey,
    options:
      | MutationOptions
      | ((args: {
          canonicalMutationFn: (input: unknown) => Promise<unknown>;
        }) => MutationOptions),
  ) => void;

  /**
   * @link https://tanstack.com/query/latest/docs/reference/QueryClient#queryclientgetmutationdefaults
   */
  getMutationDefaults: (
    mutationKey: TRPCMutationKey,
  ) => MutationOptions | undefined;

  /**
   * @link https://tanstack.com/query/latest/docs/reference/QueryClient#queryclientismutating
   */
  isMutating: (filters: { mutationKey: TRPCMutationKey }) => number;
}
export const TRPCContext = React.createContext?.(null as any);
Repository: trpc/trpc
File: packages/server/src/unstable-core-do-not-import/stream/sse.ts (TypeScript)

Code before:
    },
  });

  eventSource.addEventListener('message', (msg) => {
    stream.controller.enqueue(msg);
  });
  eventSource.addEventListener(SERIALIZED_ERROR_EVENT, (msg) => {
    stream.controller.enqueue(msg);
  });
  eventSource.addEventListener('error', (cause) => {
    if (eventSource.readyState === EventSource.CLOSED) {
      stream.controller.error(cause);
    }
  });

  const readable = stream.readable.pipeThrough(transform);
  return {
    [Symbol.asyncIterator]() {
      const reader = readable.getReader();

      const iterator: AsyncIterator<ConsumerStreamResult<TData>> = {
        async next() {
          const value = await reader.read();
          if (value.done) {
            return {
              value: value.value,
              done: true,
            };
          }
          return {
            value: value.value,
            done: false,
          };
        },
        async return() {
          reader.releaseLock();
          return {
            value: undefined,
            done: true,
          };
        },
      };
      return iterator;
    },
  };
}

export const sseHeaders = {
  'Content-Type': 'text/event-stream',
  'Cache-Control': 'no-cache, no-transform',
  'X-Accel-Buffering': 'no',

Review comment (suggestion):
```suggestion
              value: undefined,
```

Code after:
    },
  });

  eventSource.addEventListener('message', (msg) => {
    stream.controller.enqueue(msg);
  });
  eventSource.addEventListener(SERIALIZED_ERROR_EVENT, (msg) => {
    stream.controller.enqueue(msg);
  });
  eventSource.addEventListener('error', (cause) => {
    if (eventSource.readyState === EventSource.CLOSED) {
      stream.controller.error(cause);
    }
  });

  const readable = stream.readable.pipeThrough(transform);
  return {
    [Symbol.asyncIterator]() {
      const reader = readable.getReader();

      const iterator: AsyncIterator<ConsumerStreamResult<TData>> = {
        async next() {
          const value = await reader.read();
          if (value.done) {
            return {
              value: undefined,
              done: true,
            };
          }
          return {
            value: value.value,
            done: false,
          };
        },
        async return() {
          reader.releaseLock();
          return {
            value: undefined,
            done: true,
          };
        },
      };
      return iterator;
    },
  };
}

export const sseHeaders = {
  'Content-Type': 'text/event-stream',
  'Cache-Control': 'no-cache, no-transform',
  'X-Accel-Buffering': 'no',
Repository: trpc/trpc
File: packages/client/src/links/httpSubscriptionLink.ts (TypeScript)

Code before:
            result: {
              type: 'stopped',
            },
          });
          observer.complete();
        }).catch((error) => {
          observer.error(TRPCClientError.from(error));
        });

        return () => {
          observer.complete();
          eventSource?.close();
          unsubscribed = true;
        };
      });
    };
  };
}

/**
 * We wrap EventSource so that is can be reinitialized with new options
 */
class EventSourceWrapper implements Partial<EventSource> {
  private es: EventSource;

  private listeners: Partial<Record<keyof EventSourceEventMap, any[][]>> = {};

  constructor(url: string, options: EventSourceInit | undefined) {
    this.es = new EventSource(url, options);
  }

  restart(url: string, options: EventSourceInit | undefined) {
    for (const type in this.listeners) {
      for (const [t, l, o] of this.listeners[
        type as keyof EventSourceEventMap
      ] ?? []) {
        this.es.removeEventListener(t as string, l, o);
      }
    }
    this.es.close();
    this.es = new EventSource(url, options);
    for (const type in this.listeners) {
      for (const [t, l, o] of this.listeners[
        type as keyof EventSourceEventMap
      ] ?? []) {
        this.es.addEventListener(t as string, l, o);
      }
    }
  }

  close() {

Review comment (suggestion):
looks like this could just be

```ts
  private listeners: Array<{
    type: keyof EventSourceEventMap;
    callback: (...args: any[]) => void
    options?: x
  }>
```

Code after:
          eventSource?.close();
          unsubscribed = true;
        };
      });
    };
  };
}

function createRecreateOnErrorOpts(ev: Event): RecreateOnErrorOpt {
  if ('status' in ev && typeof ev.status === 'number') {
    return {
      type: 'http-error',
      status: ev.status,
      event: ev,
    };
  }

  return {
    type: 'raw',
    event: ev,
  };
}

/**
 * We wrap EventSource so that is can be reinitialized with new options
 */
class EventSourceWrapper implements Partial<EventSource> {
  private es: EventSource;

  private listeners: Partial<
    Record<
      keyof EventSourceEventMap,
      Parameters<EventSource['addEventListener']>[]
    >
  > = {};
  private *getAllEventListeners() {
    for (const _type in this.listeners) {
      const type = _type as keyof typeof this.listeners;
      for (const listener of this.listeners[type] ?? []) {
        yield listener;
      }
    }
  }

  constructor(url: string, options: EventSourceInit | undefined) {
    this.es = new EventSource(url, options);
  }

  restart(url: string, options: EventSourceInit | undefined) {
    for (const [type, callback, options] of this.getAllEventListeners()) {
      this.es.removeEventListener(type, callback, options);
Repository: trpc/trpc
File: packages/client/src/links/httpSubscriptionLink.ts (TypeScript)

Code before:
  get readyState() {
    return this.es.readyState;
  }

  addEventListener<TEvent extends keyof EventSourceEventMap>(
    type: TEvent,
    listener: (this: EventSource, ev: EventSourceEventMap[TEvent]) => any,
    options?: boolean | AddEventListenerOptions,
  ) {
    this.listeners[type] ??= [];
    this.listeners[type].push([type, listener, options]);

    this.es.addEventListener(type, listener, options);
  }

  removeEventListener<TEvent extends keyof EventSourceEventMap>(
    type: TEvent,
    listener: (this: EventSource, ev: EventSourceEventMap[TEvent]) => any,
    options?: boolean | EventListenerOptions,
  ) {
    this.listeners[type] ??= [];
    for (const [t, l, o] of this.listeners[type] ?? []) {
      if (t === type && l === listener) {
        this.listeners[type].splice(this.listeners[type].indexOf([t, l, o]), 1);
      }
    }

    this.es.removeEventListener(type, listener, options);
  }
}


Review comment (suggestion):
this can be simplified to something like

```ts
const idx = this.listeners.findIndex(x => /* ... */)
const listener = this.listeners[idx]
if (!listener) {
  return
}
this.es.removeEventListener(listener.type, listener.callback, listener.options)

// ... splice
```

Code after:
  }

  close() {
    this.listeners = {};
    this.es.close();
  }

  getEventSource() {
    return this.es;
  }

  get readyState() {
    return this.es.readyState;
  }

  addEventListener<TEvent extends keyof EventSourceEventMap>(
    type: TEvent,
    listener: (this: EventSource, ev: EventSourceEventMap[TEvent]) => any,
    options?: boolean | AddEventListenerOptions,
  ) {
    this.listeners[type] ??= [];
    this.listeners[type].push([type, listener as any, options]);

    this.es.addEventListener(type, listener, options);
  }

  removeEventListener<TEvent extends keyof EventSourceEventMap>(
    type: TEvent,
    listener: (this: EventSource, ev: EventSourceEventMap[TEvent]) => any,
    options?: boolean | EventListenerOptions,
  ) {
    this.listeners[type] ??= [];

    const indexToRemove = this.listeners[type]?.findIndex(
      ([_type, thisListener]) => thisListener === listener,
    );
    if (typeof indexToRemove === 'number' && indexToRemove >= 0) {
      this.listeners[type].splice(indexToRemove, 1);
    }
    this.es.removeEventListener(type, listener, options);
  }
}
Repository: trpc/trpc
File: packages/client/src/links/httpSubscriptionLink.ts (TypeScript)

Code before:
      event: ev,
    };
  }

  return {
    type: 'raw',
    event: ev,
  };
}

/**
 * We wrap EventSource so that is can be reinitialized with new options
 */
class EventSourceWrapper implements Partial<EventSource> {
  private es: EventSource;

  private listeners: Partial<
    Record<
      keyof EventSourceEventMap,
      Parameters<EventSource['addEventListener']>[]
    >
  > = {};
  private *getAllEventListeners() {
    for (const _type in this.listeners) {
      const type = _type as keyof EventSourceEventMap;
      for (const listener of this.listeners[type] ?? []) {
        yield listener;
      }
    }
  }

  constructor(url: string, options: EventSourceInit | undefined) {
    this.es = new EventSource(url, options);
  }

  restart(url: string, options: EventSourceInit | undefined) {
    for (const [type, callback, options] of this.getAllEventListeners()) {
      this.es.removeEventListener(type, callback, options);
    }

    this.es.close();
    this.es = new EventSource(url, options);

    for (const [type, callback, options] of this.getAllEventListeners()) {
      this.es.addEventListener(type, callback, options);
    }
  }

  close() {
    this.listeners = {};
    this.es.close();

Review comment (suggestion):
i'm guessing it could be
```suggestion
      const type = _type as keyof typeof this.listeners;
      for (const listener of this.listeners[type]) {
```

Code after:
      event: ev,
    };
  }

  return {
    type: 'raw',
    event: ev,
  };
}

/**
 * We wrap EventSource so that is can be reinitialized with new options
 */
class EventSourceWrapper implements Partial<EventSource> {
  private es: EventSource;

  private listeners: Partial<
    Record<
      keyof EventSourceEventMap,
      Parameters<EventSource['addEventListener']>[]
    >
  > = {};
  private *getAllEventListeners() {
    for (const _type in this.listeners) {
      const type = _type as keyof typeof this.listeners;
      for (const listener of this.listeners[type] ?? []) {
        yield listener;
      }
    }
  }

  constructor(url: string, options: EventSourceInit | undefined) {
    this.es = new EventSource(url, options);
  }

  restart(url: string, options: EventSourceInit | undefined) {
    for (const [type, callback, options] of this.getAllEventListeners()) {
      this.es.removeEventListener(type, callback, options);
    }

    this.es.close();
    this.es = new EventSource(url, options);

    for (const [type, callback, options] of this.getAllEventListeners()) {
      this.es.addEventListener(type, callback, options);
    }
  }

  close() {
    this.listeners = {};
    this.es.close();
Repository: trpc/trpc
File: packages/server/src/unstable-core-do-not-import/stream/sse.ts (TypeScript)

Code before:
        def.id = chunk.lastEventId;
      }

      controller.enqueue({
        ok: true,
        data: def as inferTrackedOutput<TData>,
      });
    },
  });

  let errorLock: Promise<void | 'CANCEL_ALL'> | undefined = undefined;
  eventSource.addEventListener('message', (msg) => {
    stream.controller.enqueue(msg);
  });
  eventSource.addEventListener(SERIALIZED_ERROR_EVENT, (msg) => {
    stream.controller.enqueue(msg);
  });
  eventSource.addEventListener('error', async (cause) => {
    // We prevent more than 1 error handler from waiting at the same time
    const result = await errorLock;
    if (result === 'CANCEL_ALL') {
      return;
    }

    const resolvable = createResolvable<void | 'CANCEL_ALL'>();
    errorLock = resolvable.promise;

    const handled = await opts.tryHandleError?.(cause);

    resolvable.resolve();

    if (handled === true) {
      return;
    }

    if (eventSource.readyState === EventSource.CLOSED) {
      stream.controller.error(cause);
    }
  });

  const readable = stream.readable.pipeThrough(transform);

  return {
    [Symbol.asyncIterator]() {
      const reader = readable.getReader();

      const iterator: AsyncIterator<ConsumerStreamResult<TData>> = {
        async next() {
          const value = await reader.read();
          if (value.done) {
            return {

Review comment (refactor):
we have a utility for this already called `createDeferred`
```suggestion
    const deferred = createDeferred<void | 'CANCEL_ALL'>();
    errorLock = deferred.promise;
```

Code after:
        def.id = chunk.lastEventId;
      }

      controller.enqueue({
        ok: true,
        data: def as inferTrackedOutput<TData>,
      });
    },
  });

  let errorLock: Promise<void | 'CANCEL_ALL'> | undefined = undefined;
  eventSource.addEventListener('message', (msg) => {
    stream.controller.enqueue(msg);
  });
  eventSource.addEventListener(SERIALIZED_ERROR_EVENT, (msg) => {
    stream.controller.enqueue(msg);
  });
  eventSource.addEventListener('error', async (cause) => {
    // We prevent more than 1 error handler from waiting at the same time
    const result = await errorLock;
    if (result === 'CANCEL_ALL') {
      return;
    }

    const resolvable = createDeferred<void | 'CANCEL_ALL'>();
    errorLock = resolvable.promise;

    const handled = await opts.tryHandleError?.(cause);

    resolvable.resolve();

    if (handled === true) {
      return;
    }

    if (eventSource.readyState === EventSource.CLOSED) {
      stream.controller.error(cause);
    }
  });

  const readable = stream.readable.pipeThrough(transform);

  return {
    [Symbol.asyncIterator]() {
      const reader = readable.getReader();

      const iterator: AsyncIterator<ConsumerStreamResult<TData>> = {
        async next() {
          const value = await reader.read();
          if (value.done) {
            return {