ronantakizawa/codereview-bench huggingface dataset:
Repository: traefik/traefik
File: pkg/server/aggregator.go (Go)

Code before:
						cp.Observability.TraceVerbosity = m.Observability.TraceVerbosity
					}

					rtName := name
					if len(eps) > 1 {
						rtName = epName + "-" + name
						modelRouterNames[name] = append(modelRouterNames[name], rtName)
					}

					rts[rtName] = cp
				} else {
					router.EntryPoints = append(router.EntryPoints, epName)

					rts[name] = router
				}
			}
		}

		for _, rt := range rts {
			if rt.ParentRefs == nil {
				continue
			}

			var parentRefs []string
			for _, ref := range rt.ParentRefs {
				// Only add the initial parent ref if it still exists (at least one entryPoint had no model).
				if _, ok := rts[ref]; ok {
					parentRefs = append(parentRefs, ref)
				}

				if names, ok := modelRouterNames[ref]; ok {
					parentRefs = append(parentRefs, names...)
				}
			}

			rt.ParentRefs = parentRefs
		}

		cfg.HTTP.Routers = rts
	}

	// Apply the default observability model to HTTP routers.
	applyDefaultObservabilityModel(cfg)

	if cfg.TCP == nil || len(cfg.TCP.Models) == 0 {
		return cfg
	}

	tcpRouters := make(map[string]*dynamic.TCPRouter)

	for name, rt := range cfg.TCP.Routers {

Review comment (suggestion):
```suggestion
				// Only add the initial parent ref if it still exists.
```

Code after:
						cp.Observability.TraceVerbosity = m.Observability.TraceVerbosity
					}

					rtName := name
					if len(eps) > 1 {
						rtName = epName + "-" + name
						modelRouterNames[name] = append(modelRouterNames[name], rtName)
					}

					rts[rtName] = cp
				} else {
					router.EntryPoints = append(router.EntryPoints, epName)

					rts[name] = router
				}
			}
		}

		for _, rt := range rts {
			if rt.ParentRefs == nil {
				continue
			}

			var parentRefs []string
			for _, ref := range rt.ParentRefs {
				// Only add the initial parent ref if it still exists.
				if _, ok := rts[ref]; ok {
					parentRefs = append(parentRefs, ref)
				}

				if names, ok := modelRouterNames[ref]; ok {
					parentRefs = append(parentRefs, names...)
				}
			}

			rt.ParentRefs = parentRefs
		}

		cfg.HTTP.Routers = rts
	}

	// Apply the default observability model to HTTP routers.
	applyDefaultObservabilityModel(cfg)

	if cfg.TCP == nil || len(cfg.TCP.Models) == 0 {
		return cfg
	}

	tcpRouters := make(map[string]*dynamic.TCPRouter)

	for name, rt := range cfg.TCP.Routers {
Repository: traefik/traefik
File: pkg/config/static/static_config_test.go (Go)

Code before:
		},
		{
			desc:      "valid path with allowed special chars",
			basePath:  "/valid/path-123",
			expectErr: false,
		},
		{
			desc:      "relative path",
			basePath:  "api/path",
			expectErr: true,
		},
		{
			desc:      "XSS payload",
			basePath:  `/api/"></script><script>alert("XSS")</script>`,
			expectErr: true,
		},
		{
			desc:      "path with spaces",
			basePath:  "/path with spaces",
			expectErr: true,
		},
		{
			desc:      "path with angle brackets",
			basePath:  "/path/<evil>",
			expectErr: true,
		},
	}

	for _, test := range tests {
		t.Run(test.desc, func(t *testing.T) {
			t.Parallel()

			cfg := &Configuration{
				API: &API{BasePath: test.basePath},
			}

			err := cfg.ValidateConfiguration()
			if test.expectErr {
				assert.Error(t, err)
			} else {
				assert.NoError(t, err)
			}
		})
	}
}


Review comment (suggestion):
```suggestion
		},
		{
			desc:      "path with query string",
			basePath:  "/api?foo=bar",
			expectErr: true,
		},
		{
			desc:      "path with fragment",
			basePath:  "/api#section",
			expectErr: true,
		},
		{
			desc:      "valid root path",
			basePath:  "/",
			expectErr: false,
		},
		{
			desc:      "path with quote",
			basePath:  "/api/'onclick=alert(1)",
			expectErr: true,
		},
		{
			desc:      "path with encoded character",
			basePath:  "/api%2Ftoto",
			expectErr: true,
		},
```

Code after:
		},
		{
			desc:      "valid path with allowed special chars",
			basePath:  "/valid/path-123",
			expectErr: false,
		},
		{
			desc:      "relative path",
			basePath:  "api/path",
			expectErr: true,
		},
		{
			desc:      "XSS payload",
			basePath:  `/api/"></script><script>alert("XSS")</script>`,
			expectErr: true,
		},
		{
			desc:      "path with spaces",
			basePath:  "/path with spaces",
			expectErr: true,
		},
		{
			desc:      "path with angle brackets",
			basePath:  "/path/<evil>",
			expectErr: true,
		},
		{
			desc:      "path with query string",
			basePath:  "/api?foo=bar",
			expectErr: true,
		},
		{
			desc:      "path with fragment",
			basePath:  "/api#section",
			expectErr: true,
		},
		{
			desc:      "valid root path",
			basePath:  "/",
			expectErr: false,
		},
		{
			desc:      "path with quote",
			basePath:  "/api/'onclick=alert(1)",
			expectErr: true,
		},
		{
			desc:      "path with encoded character",
			basePath:  "/api%2Ftoto",
			expectErr: true,
		},
Repository: transitive-bullshit/chatgpt-api
File: src/chatgpt-api.ts (TypeScript)

Code before:
                new Error(
                  `OpenAI error: ${
                    res?.detail?.message || res?.detail || 'unknown'
                  }`
                )
              )
            }

            result.detail = response

            return resolve(result)
          } catch (err) {
            return reject(err)
          }
        }
      }
    ).then((message) => {
      return this._upsertMessage(message).then(() => message)
    })

    if (timeoutMs) {
      if (abortController) {
        // This will be called when a timeout occurs in order for us to forcibly
        // ensure that the underlying HTTP request is aborted.
        ;(responseP as any).cancel = () => {
          abortController.abort()
        }
      }

      return pTimeout(responseP, {
        milliseconds: timeoutMs,
        message: 'OpenAI timed out waiting for response'
      })
    } else {
      return responseP
    }
  }

  get apiKey(): string {
    return this._apiKey
  }

  set apiKey(apiKey: string) {
    this._apiKey = apiKey
  }

  protected async _buildMessages(text: string, opts: types.SendMessageOptions) {
    const { systemMessage = this._systemMessage } = opts
    let { parentMessageId } = opts

    const userLabel = USER_LABEL_DEFAULT

Review comment (suggestion):
Mark these values as `estimated` to let user know that they did not come from OpenAI, so it means the only "theoretically" represent usage data in OpenAI account 

Code after:
              return reject(
                new Error(
                  `OpenAI error: ${
                    res?.detail?.message || res?.detail || 'unknown'
                  }`
                )
              )
            }

            result.detail = response

            return resolve(result)
          } catch (err) {
            return reject(err)
          }
        }
      }
    ).then(async (message) => {
      if (message.detail && !message.detail.usage) {
        const promptTokens = numTokens
        const completionTokens = await this._getTokenCount(message.text)
        message.detail.usage = {
          prompt_tokens: promptTokens,
          completion_tokens: completionTokens,
          total_tokens: promptTokens + completionTokens,
          estimated: true
        }
      }
      return this._upsertMessage(message).then(() => message)
    })

    if (timeoutMs) {
      if (abortController) {
        // This will be called when a timeout occurs in order for us to forcibly
        // ensure that the underlying HTTP request is aborted.
        ;(responseP as any).cancel = () => {
          abortController.abort()
        }
      }

      return pTimeout(responseP, {
        milliseconds: timeoutMs,
        message: 'OpenAI timed out waiting for response'
      })
    } else {
      return responseP
    }
  }

  get apiKey(): string {
    return this._apiKey
Repository: trpc/trpc
File: examples/.test/internal-types-export/src/server.ts (TypeScript)

Code before:
import { initTRPC } from '@trpc/server';

// needs to be exported for the test to be valid
export const t = initTRPC.create();


const appRouter = t.router({
  foo: t.procedure.query(() => 'bar'),
})

export type AppRouter = typeof appRouter;


Review comment (bug):
Soooo, we've just noticed that this is incorrect code which showed up while doing work on next major

You cannot know that `'bar'` is correct when "before" the `TSchema` is set

so just FYI @milohansen, this will break, unless you typecast `'bar'`, when you upgrade to v11

Code after:
import { initTRPC } from '@trpc/server';

// needs to be exported for the test to be valid
export const t = initTRPC.create();

const someMiddleware = t.middleware(({ next }) => {
  return next();
});

export function genericRouter<S extends (value: any) => unknown>(schema: S) {
  return t.router({
    foo: t.procedure.output(schema).query(() => 'bar'),
  });
}

const appRouter = t.router({
  foo: t.procedure.query(() => 'bar'),
  hello: t.procedure.use(someMiddleware).query(() => 'hello'),
  generic: genericRouter((value: string) => value.toUpperCase()),
})

export type AppRouter = typeof appRouter;
Repository: trpc/trpc
File: packages/react-query/src/ssg/index.tsx (TypeScript)

Code before:
export {
  /**
   * @deprecated use `@trpc/react-query/server` instead
   */
  type CreateSSGHelpersOptions,
  /**
   * @deprecated use `@trpc/react-query/server` instead
   */
  type DecoratedProcedureSSGRecord,
  /**
   * @deprecated use `import { createServerSideHelpers } from "@trpc/react-query/server"`;
   */
  createServerSideHelpers as createProxySSGHelpers,
} from '../server';

export { createSSGHelpers } from './ssg';


Review comment (refactor):
```suggestion
   * @deprecated use `import { createServerSideHelpers } from "@trpc/react-query/server"`
````

Code after:
export {
  /**
   * @deprecated use `@trpc/react-query/server` instead
   */
  type CreateSSGHelpersOptions,
  /**
   * @deprecated use `@trpc/react-query/server` instead
   */
  type DecoratedProcedureSSGRecord,
  /**
   * @deprecated use `import { createServerSideHelpers } from "@trpc/react-query/server"`
   */
  createServerSideHelpers as createProxySSGHelpers,
} from '../server';

export { createSSGHelpers } from './ssg';
Repository: trpc/trpc
File: packages/client/src/links/internals/httpUtils.ts (TypeScript)

Code before:
import { ProcedureType } from '@trpc/server';
import { TRPCResponse } from '@trpc/server/rpc';
import { getFetch } from '../../getFetch';
import { getAbortController } from '../../internals/getAbortController';
import {
  AbortControllerEsque,
  FetchEsque,
  ResponseEsque,
} from '../../internals/types';
import { HTTPHeaders, Operation, PromiseAndCancel, TRPCClientRuntime } from '../types';

export interface HTTPLinkOptions {
  url: string;
  /**
   * Add ponyfill for fetch
   */
  fetch?: FetchEsque;
  /**
   * Add ponyfill for AbortController
   */
  AbortController?: AbortControllerEsque | null;
  /**
   * Headers to be set on outgoing requests or a callback that of said headers
   * @link http://trpc.io/docs/v10/header
   */
  headers?: HTTPHeaders | ((opts: {ops: Operation[]}) => HTTPHeaders | Promise<HTTPHeaders>);
}

export interface ResolvedHTTPLinkOptions {
  url: string;
  fetch: FetchEsque;
  AbortController: AbortControllerEsque | null;
  /**
   * Headers to be set on outgoing request
   * @link http://trpc.io/docs/v10/header
   */
  headers: (opts: {ops: Operation[]}) => HTTPHeaders | Promise<HTTPHeaders>;
}

export function resolveHTTPLinkOptions(
  opts: HTTPLinkOptions,
): ResolvedHTTPLinkOptions {
  const headers = opts.headers || {};
  return {
    url: opts.url,
    fetch: getFetch(opts.fetch),
    AbortController: getAbortController(opts.AbortController),
    headers: typeof headers === 'function' ? headers : () => headers,
  };
}


Review comment (performance):
Here we use `ops: Operation[]` for both batched and non regular http links. 

Code after:
import { ProcedureType } from '@trpc/server';
import { TRPCResponse } from '@trpc/server/rpc';
import { getFetch } from '../../getFetch';
import { getAbortController } from '../../internals/getAbortController';
import {
  AbortControllerEsque,
  FetchEsque,
  ResponseEsque,
} from '../../internals/types';
import { HTTPHeaders, PromiseAndCancel, TRPCClientRuntime } from '../types';

/**
 * @internal
 */
export interface HTTPLinkBaseOptions {
  url: string;
  /**
   * Add ponyfill for fetch
   */
  fetch?: FetchEsque;
  /**
   * Add ponyfill for AbortController
   */
  AbortController?: AbortControllerEsque | null;
}

export interface ResolvedHTTPLinkOptions {
  url: string;
  fetch: FetchEsque;
  AbortController: AbortControllerEsque | null;
}

export function resolveHTTPLinkOptions(
  opts: HTTPLinkBaseOptions,
): ResolvedHTTPLinkOptions {
  return {
    url: opts.url,
    fetch: getFetch(opts.fetch),
    AbortController: getAbortController(opts.AbortController),
  };
}

// https://github.com/trpc/trpc/pull/669
function arrayToDict(array: unknown[]) {
  const dict: Record<number, unknown> = {};
  for (let index = 0; index < array.length; index++) {
    const element = array[index];
    dict[index] = element;
  }
  return dict;
}
Repository: trpc/trpc
File: packages/client/src/links/internals/httpUtils.ts (TypeScript)

Code before:
} as const;

export interface HTTPResult {
  json: TRPCResponse;
  meta: {
    response: ResponseEsque;
  };
}

type GetInputOptions = {
  runtime: TRPCClientRuntime;
} & ({ inputs: unknown[] } | { input: unknown });

function getInput(opts: GetInputOptions) {
  return 'input' in opts
    ? opts.runtime.transformer.serialize(opts.input)
    : arrayToDict(
        opts.inputs.map((_input) => opts.runtime.transformer.serialize(_input)),
      );
}

export type HTTPRequestOptions = ResolvedHTTPLinkOptions &
  GetInputOptions & {
    type: ProcedureType;
    path: string;
    ops: Operation[]; // TODO: if we do this, then we should get rid of type and path
  };

export function getUrl(opts: HTTPRequestOptions) {
  let url = opts.url + '/' + opts.path;
  const queryParts: string[] = [];
  if ('inputs' in opts) {
    queryParts.push('batch=1');
  }
  if (opts.type === 'query') {
    const input = getInput(opts);
    if (input !== undefined) {
      queryParts.push(`input=${encodeURIComponent(JSON.stringify(input))}`);
    }
  }
  if (queryParts.length) {
    url += '?' + queryParts.join('&');
  }
  return url;
}

type GetBodyOptions = { type: ProcedureType } & GetInputOptions;

export function getBody(opts: GetBodyOptions) {
  if (opts.type === 'query') {
    return undefined;

Review comment (refactor):
@KATT do you agree on this approach? If so, then I'm thinking of getting rid of passing in `path` which can be extracted from `ops`.

Code after:
    : arrayToDict(
        opts.inputs.map((_input) => opts.runtime.transformer.serialize(_input)),
      );
}

type GetUrlOptions = ResolvedHTTPLinkOptions &
  GetInputOptions & {
    type: ProcedureType;
    path: string;
  };

export function getUrl(opts: GetUrlOptions) {
  let url = opts.url + '/' + opts.path;
  const queryParts: string[] = [];
  if ('inputs' in opts) {
    queryParts.push('batch=1');
  }
  if (opts.type === 'query') {
    const input = getInput(opts);
    if (input !== undefined) {
      queryParts.push(`input=${encodeURIComponent(JSON.stringify(input))}`);
    }
  }
  if (queryParts.length) {
    url += '?' + queryParts.join('&');
  }
  return url;
}

type GetBodyOptions = { type: ProcedureType } & GetInputOptions;

export function getBody(opts: GetBodyOptions) {
  if (opts.type === 'query') {
    return undefined;
  }
  const input = getInput(opts);
  return input !== undefined ? JSON.stringify(input) : undefined;
}

export type HTTPRequestOptions = ResolvedHTTPLinkOptions &
  GetInputOptions & {
    type: ProcedureType;
    path: string;
    headers: () => HTTPHeaders | Promise<HTTPHeaders>;
  };

export function httpRequest(
  opts: HTTPRequestOptions,
): PromiseAndCancel<HTTPResult> {
  const { type } = opts;
  const ac = opts.AbortController ? new opts.AbortController() : null;
Repository: trpc/trpc
File: www/src/theme/CodeBlock/index.js (JavaScript)

Code before:
// Based on https://github.com/facebook/docusaurus/blob/ed9d2a26f5a7b8096804ae1b3a4fffc504f8f90d/packages/docusaurus-theme-classic/src/theme/CodeBlock/index.tsx
// which is under MIT License as per the banner

import './styles.css';
import Translate, { translate } from '@docusaurus/Translate';
import React, { useRef, useState } from 'react';

const CodeBlock = ({ children, ...props }) => {
  const pre = useRef(null);
  const [showCopied, setShowCopied] = useState(false);

  const handleCopyCode = () => {
    if (pre.current) {
      navigator.clipboard.writeText(
        Array.from(pre.current.querySelectorAll('code div.line'))
          .map((el) => el.textContent)
          .join('\n'),
      );
    }
    setShowCopied(true);
    setTimeout(() => setShowCopied(false), 2000);
  };

  return (
    <pre {...props} ref={pre}>
      {children}
      <button
        type="button"
        aria-label={translate({
          id: 'theme.CodeBlock.copyButtonAriaLabel',
          message: 'Copy code to clipboard',
          description: 'The ARIA label for copy code blocks button',
        })}
        className="copy-button"
        onClick={handleCopyCode}
      >
        {showCopied ? (
          <Translate
            id="theme.CodeBlock.copied"

Review comment (suggestion):
```suggestion
      void navigator.clipboard.writeText(
```

Code after:
// Based on https://github.com/facebook/docusaurus/blob/ed9d2a26f5a7b8096804ae1b3a4fffc504f8f90d/packages/docusaurus-theme-classic/src/theme/CodeBlock/index.tsx
// which is under MIT License as per the banner

import './styles.css';
import Translate, { translate } from '@docusaurus/Translate';
import React, { useRef, useState } from 'react';

const CodeBlock = ({ children, ...props }) => {
  const pre = useRef(null);
  const [showCopied, setShowCopied] = useState(false);

  const handleCopyCode = () => {
    if (pre.current) {
      void navigator.clipboard.writeText(
        Array.from(pre.current.querySelectorAll('code div.line'))
          .map((el) => el.textContent)
          .join('\n'),
      );
    }
    setShowCopied(true);
    setTimeout(() => setShowCopied(false), 2000);
  };

  return (
    <pre {...props} ref={pre}>
      {children}
      <button
        type="button"
        aria-label={translate({
          id: 'theme.CodeBlock.copyButtonAriaLabel',
          message: 'Copy code to clipboard',
          description: 'The ARIA label for copy code blocks button',
        })}
        className="copy-button"
        onClick={handleCopyCode}
      >
        {showCopied ? (
          <Translate
            id="theme.CodeBlock.copied"
Repository: trpc/trpc
File: examples/next-prisma-starter/tailwind.config.ts (TypeScript)

Code before:
import type { Config } from 'tailwindcss';

export default {
  content: ['./src/pages/**/*.{js,ts,jsx,tsx}'],
  theme: {
    extend: {},
  },
  plugins: [],
} as Config;


Review comment (suggestion):
```suggestion
const config: Config = {
  content: ['./src/pages/**/*.{js,ts,jsx,tsx}'],
  theme: {
    extend: {},
  },
  plugins: [],
};

export default config;
```

Code after:
import type { Config } from 'tailwindcss';

const config: Config = {
  content: ['./src/pages/**/*.{js,ts,jsx,tsx}'],
  theme: {
    extend: {},
  },
  plugins: [],
};

export default config;
Repository: trpc/trpc
File: packages/tests/server/react/infiniteQuery.test.tsx (TypeScript)

Code before:
      const data = JSON.stringify(ssg.dehydrate());
      expect(data).toContain('first post');
      expect(data).toContain('second post');
    }
  });

  test('useInfiniteQuery() is exposed on procedure with optional inputs', () => {
    const { trpc, appRouter } = factory;

    type AppRouter = typeof appRouter;
    type Input = inferProcedureInput<AppRouter['paginatedPosts']>;

    type Extends<T, U> = T extends U ? true : false;

    // Optional procedure inputs are unioned with void | undefined.

    assertType<Extends<Input, { cursor?: string }>>(false);
    assertType<Extends<Input, { cursor?: string } | void>>(true);
    assertType<Extends<Input, { cursor?: string } | undefined>>(true);
    assertType<Extends<Input, { cursor?: string } | void | undefined>>(true);

    // Assert 'useInfiniteQuery' is exposed in 'trpc.paginatedPosts'.

    expectTypeOf(trpc.paginatedPosts.useInfiniteQuery).toBeFunction();
  });
});


Review comment (refactor):
```suggestion
  });

  test('useInfiniteQuery() is **not** exposed if there is not cursor', () => {
    ignoreErrors(async () => {
      // @ts-expect-error 'cursor' is required
      factory.trpc.postById.useInfiniteQuery;
      const ssg = createServerSideHelpers({
        router: factory.appRouter,
        ctx: {},
      });

      // good
      await ssg.paginatedPosts.fetchInfinite({ limit: 1 });

      // @ts-expect-error 'cursor' is required
      await ssg.postById.fetchInfinite({ limit: 1 });
    });
  });

Code after:
      await ssg.paginatedPosts.fetchInfinite({ limit: 2 });
      const data = JSON.stringify(ssg.dehydrate());
      expect(data).toContain('first post');
      expect(data).toContain('second post');
    }
  });

  test('useInfiniteQuery() is exposed on procedure with optional inputs', () => {
    const { trpc, appRouter } = factory;

    type AppRouter = typeof appRouter;
    type Input = inferProcedureInput<AppRouter['paginatedPosts']>;

    type Extends<T, U> = T extends U ? true : false;

    // Optional procedure inputs are unioned with void | undefined.

    assertType<Extends<Input, { cursor?: string }>>(false);
    assertType<Extends<Input, { cursor?: string } | void>>(true);
    assertType<Extends<Input, { cursor?: string } | undefined>>(true);
    assertType<Extends<Input, { cursor?: string } | void | undefined>>(true);

    // Assert 'useInfiniteQuery' is exposed in 'trpc.paginatedPosts'.

    expectTypeOf(trpc.paginatedPosts.useInfiniteQuery).toBeFunction();
  });

  test('useInfiniteQuery() is **not** exposed if there is not cursor', () => {
    ignoreErrors(async () => {
      // @ts-expect-error 'cursor' is required
      factory.trpc.postById.useInfiniteQuery;
      const ssg = createServerSideHelpers({
        router: factory.appRouter,
        ctx: {},
      });

      // good
      await ssg.paginatedPosts.fetchInfinite({ limit: 1 });

      // @ts-expect-error 'cursor' is required
      await ssg.postById.fetchInfinite({ limit: 1 });
    });
  });
});