ronantakizawa/codereview-bench huggingface dataset:
Repository: puppeteer/puppeteer
File: packages/puppeteer-core/src/bidi/Page.ts (TypeScript)

Code before:
    );
  }

  override isDragInterceptionEnabled(): boolean {
    return false;
  }

  override async setCacheEnabled(enabled?: boolean): Promise<void> {
    await this._client().send('Network.setCacheDisabled', {
      cacheDisabled: !enabled,
    });
  }
}

function isConsoleLogEntry(
  event: Bidi.Log.Entry
): event is Bidi.Log.ConsoleLogEntry {
  return event.type === 'console';
}

function isJavaScriptLogEntry(
  event: Bidi.Log.Entry
): event is Bidi.Log.JavascriptLogEntry {
  return event.type === 'javascript';
}

function getStackTraceLocations(
  stackTrace?: Bidi.Script.StackTrace
): ConsoleMessageLocation[] {
  const stackTraceLocations: ConsoleMessageLocation[] = [];
  if (stackTrace) {
    for (const callFrame of stackTrace.callFrames) {
      stackTraceLocations.push({
        url: callFrame.url,
        lineNumber: callFrame.lineNumber,
        columnNumber: callFrame.columnNumber,
      });
    }
  }
  return stackTraceLocations;
}

function evaluationExpression(fun: Function | string, ...args: unknown[]) {
  return `() => {${evaluationString(fun, ...args)}}`;
}


Review comment (performance):
```suggestion
    // TODO: handle CDP-specific cases such as mprach.
    await this._client().send('Network.setCacheDisabled', {
```

Code after:
    id: string
  ): Promise<void> {
    await this.#connection.send('script.removePreloadScript', {
      script: id,
    });
  }

  override async exposeFunction<Args extends unknown[], Ret>(
    name: string,
    pptrFunction:
      | ((...args: Args) => Awaitable<Ret>)
      | {default: (...args: Args) => Awaitable<Ret>}
  ): Promise<void> {
    return await this.mainFrame().exposeFunction(
      name,
      'default' in pptrFunction ? pptrFunction.default : pptrFunction
    );
  }

  override isDragInterceptionEnabled(): boolean {
    return false;
  }

  override async setCacheEnabled(enabled?: boolean): Promise<void> {
    // TODO: handle CDP-specific cases such as mprach.
    await this._client().send('Network.setCacheDisabled', {
      cacheDisabled: !enabled,
    });
  }
}

function isConsoleLogEntry(
  event: Bidi.Log.Entry
): event is Bidi.Log.ConsoleLogEntry {
  return event.type === 'console';
}

function isJavaScriptLogEntry(
  event: Bidi.Log.Entry
): event is Bidi.Log.JavascriptLogEntry {
  return event.type === 'javascript';
}

function getStackTraceLocations(
  stackTrace?: Bidi.Script.StackTrace
): ConsoleMessageLocation[] {
  const stackTraceLocations: ConsoleMessageLocation[] = [];
  if (stackTrace) {
    for (const callFrame of stackTrace.callFrames) {
      stackTraceLocations.push({
        url: callFrame.url,
Repository: puppeteer/puppeteer
File: .eslintrc.js (JavaScript)

Code before:

    // ensure we don't have any it.only or describe.only in prod
    'mocha/no-exclusive-tests': 'error',

    'no-restricted-imports': [
      'error',
      {
        patterns: ['*Events', '*.test.js'],
        paths: [
          {
            name: 'mitt',
            message:
              'Import `mitt` from the vendored location: third_party/mitt/index.js',
          },
        ],
      },
    ],
    'import/order': [
      'error',
      {
        'newlines-between': 'always',
        alphabetize: {order: 'asc', caseInsensitive: true},
      },
    ],

    'import/no-cycle': ['error', {maxDepth: Infinity}],

    'no-restricted-syntax': [
      'error',
      // Don't allow underscored declarations on camelCased variables/properties.
      // ...RESTRICTED_UNDERSCORED_IDENTIFIERS,
    ],
  },
  overrides: [
    {
      files: ['*.ts'],
      parserOptions: {
        allowAutomaticSingleRunInference: true,
        project: './tsconfig.base.json',
      },
      extends: [
        'plugin:@typescript-eslint/eslint-recommended',
        'plugin:@typescript-eslint/recommended',
        'plugin:@typescript-eslint/stylistic',
      ],
      plugins: ['eslint-plugin-tsdoc', 'rulesdir'],
      rules: {
        // Keeps comments formatted.
        'rulesdir/prettier-comments': 'error',
        // Enforces clean up of used resources.
        'rulesdir/use-using': 'error',

Review comment (suggestion):
```suggestion
    'import/no-cycle': ['warn', {maxDepth: Infinity}],
```

Code after:

    // ensure we don't have any it.only or describe.only in prod
    'mocha/no-exclusive-tests': 'error',

    'no-restricted-imports': [
      'error',
      {
        patterns: ['*Events', '*.test.js'],
        paths: [
          {
            name: 'mitt',
            message:
              'Import `mitt` from the vendored location: third_party/mitt/index.js',
          },
        ],
      },
    ],
    'import/order': [
      'error',
      {
        'newlines-between': 'always',
        alphabetize: {order: 'asc', caseInsensitive: true},
      },
    ],

    'import/no-cycle': ['warn', {maxDepth: Infinity}],

    'no-restricted-syntax': [
      'error',
      // Don't allow underscored declarations on camelCased variables/properties.
      // ...RESTRICTED_UNDERSCORED_IDENTIFIERS,
    ],
  },
  overrides: [
    {
      files: ['*.ts'],
      parserOptions: {
        allowAutomaticSingleRunInference: true,
        project: './tsconfig.base.json',
      },
      extends: [
        'plugin:@typescript-eslint/eslint-recommended',
        'plugin:@typescript-eslint/recommended',
        'plugin:@typescript-eslint/stylistic',
      ],
      plugins: ['eslint-plugin-tsdoc', 'rulesdir'],
      rules: {
        // Keeps comments formatted.
        'rulesdir/prettier-comments': 'error',
        // Enforces clean up of used resources.
        'rulesdir/use-using': 'error',
Repository: puppeteer/puppeteer
File: packages/puppeteer-core/src/node/ChromeLauncher.ts (TypeScript)

Code before:
      return BrowsersChromeReleaseChannel.STABLE;
    case 'chrome-dev':
      return BrowsersChromeReleaseChannel.DEV;
    case 'chrome-beta':
      return BrowsersChromeReleaseChannel.BETA;
    case 'chrome-canary':
      return BrowsersChromeReleaseChannel.CANARY;
  }
}

/**
 * Extracts all features from the given command-line flag.
 *
 * Example input:
 * ["--enable-features=NetworkService,NetworkServiceInProcess", "--enable-features=Foo"]
 *
 * Example output:
 * ["NetworkService", "NetworkServiceInProcess", "Foo"]
 */
export function getFeatures(flag: string, options: string[] = []): string[] {
  const opts = options
    ?.filter(s => {
      return s.startsWith(flag);
    })
    .map(s => {
      return s.split(new RegExp(`${flag}[= ]*`))[1]!.trim();
    });
  return opts.length === 0 ? [] : opts.join(',').split(',');
}


Review comment (suggestion):
```suggestion
      return s.split(new RegExp(`${flag}\s*=\s*`))[1]!.trim();
```

Code after:
  switch (channel) {
    case 'chrome':
      return BrowsersChromeReleaseChannel.STABLE;
    case 'chrome-dev':
      return BrowsersChromeReleaseChannel.DEV;
    case 'chrome-beta':
      return BrowsersChromeReleaseChannel.BETA;
    case 'chrome-canary':
      return BrowsersChromeReleaseChannel.CANARY;
  }
}

/**
 * Extracts all features from the given command-line flag
 * (e.g. `--enable-features`, `--enable-features=`).
 *
 * Example input:
 * ["--enable-features=NetworkService,NetworkServiceInProcess", "--enable-features=Foo"]
 *
 * Example output:
 * ["NetworkService", "NetworkServiceInProcess", "Foo"]
 *
 * @internal
 */
export function getFeatures(flag: string, options: string[] = []): string[] {
  return options
    .filter(s => {
      return s.startsWith(flag.endsWith('=') ? flag : `${flag}=`);
    })
    .map(s => {
      return s.split(new RegExp(`${flag}` + '=\\s*'))[1]?.trim();
    })
    .filter(s => {
      return s;
    }) as string[];
}
Repository: puppeteer/puppeteer
File: packages/puppeteer-core/src/node/ChromeLauncher.ts (TypeScript)

Code before:
  channel: ChromeReleaseChannel
): BrowsersChromeReleaseChannel {
  switch (channel) {
    case 'chrome':
      return BrowsersChromeReleaseChannel.STABLE;
    case 'chrome-dev':
      return BrowsersChromeReleaseChannel.DEV;
    case 'chrome-beta':
      return BrowsersChromeReleaseChannel.BETA;
    case 'chrome-canary':
      return BrowsersChromeReleaseChannel.CANARY;
  }
}

/**
 * Extracts all features from the given command-line flag.
 *
 * Example input:
 * ["--enable-features=NetworkService,NetworkServiceInProcess", "--enable-features=Foo"]
 *
 * Example output:
 * ["NetworkService", "NetworkServiceInProcess", "Foo"]
 */
export function getFeatures(flag: string, options: string[] = []): string[] {
  const opts = options
    ?.filter(s => {
      return s.startsWith(flag);
    })
    .map(s => {
      return s.split(new RegExp(`${flag}\s*=\s*`))[1]!.trim();
    });
  return opts.length === 0 ? [] : opts.join(',').split(',');
}


Review comment (suggestion):
Options is always an array. So we can remove the `?` and return the `options.filter().map()` directly

Code after:

function convertPuppeteerChannelToBrowsersChannel(
  channel: ChromeReleaseChannel
): BrowsersChromeReleaseChannel {
  switch (channel) {
    case 'chrome':
      return BrowsersChromeReleaseChannel.STABLE;
    case 'chrome-dev':
      return BrowsersChromeReleaseChannel.DEV;
    case 'chrome-beta':
      return BrowsersChromeReleaseChannel.BETA;
    case 'chrome-canary':
      return BrowsersChromeReleaseChannel.CANARY;
  }
}

/**
 * Extracts all features from the given command-line flag
 * (e.g. `--enable-features`, `--enable-features=`).
 *
 * Example input:
 * ["--enable-features=NetworkService,NetworkServiceInProcess", "--enable-features=Foo"]
 *
 * Example output:
 * ["NetworkService", "NetworkServiceInProcess", "Foo"]
 *
 * @internal
 */
export function getFeatures(flag: string, options: string[] = []): string[] {
  return options
    .filter(s => {
      return s.startsWith(flag.endsWith('=') ? flag : `${flag}=`);
    })
    .map(s => {
      return s.split(new RegExp(`${flag}` + '=\\s*'))[1]?.trim();
    })
    .filter(s => {
      return s;
    }) as string[];
}
Repository: puppeteer/puppeteer
File: packages/puppeteer-core/src/node/ChromeLauncher.ts (TypeScript)

Code before:
      return BrowsersChromeReleaseChannel.STABLE;
    case 'chrome-dev':
      return BrowsersChromeReleaseChannel.DEV;
    case 'chrome-beta':
      return BrowsersChromeReleaseChannel.BETA;
    case 'chrome-canary':
      return BrowsersChromeReleaseChannel.CANARY;
  }
}

/**
 * Extracts all features from the given command-line flag.
 *
 * Example input:
 * ["--enable-features=NetworkService,NetworkServiceInProcess", "--enable-features=Foo"]
 *
 * Example output:
 * ["NetworkService", "NetworkServiceInProcess", "Foo"]
 */
export function getFeatures(flag: string, options: string[] = []): string[] {
  const opts = options
    ?.filter(s => {
      return s.startsWith(flag);
    })
    .map(s => {
      return s.split(new RegExp(`${flag}\s*=\s*`))[1]!.trim();
    });
  return opts.length === 0 ? [] : opts.join(',').split(',');
}


Review comment (suggestion):
```suggestion
      return s.split(new RegExp(`${flag}\\s*=\\s*`))[1]!.trim();
```

Code after:
  switch (channel) {
    case 'chrome':
      return BrowsersChromeReleaseChannel.STABLE;
    case 'chrome-dev':
      return BrowsersChromeReleaseChannel.DEV;
    case 'chrome-beta':
      return BrowsersChromeReleaseChannel.BETA;
    case 'chrome-canary':
      return BrowsersChromeReleaseChannel.CANARY;
  }
}

/**
 * Extracts all features from the given command-line flag
 * (e.g. `--enable-features`, `--enable-features=`).
 *
 * Example input:
 * ["--enable-features=NetworkService,NetworkServiceInProcess", "--enable-features=Foo"]
 *
 * Example output:
 * ["NetworkService", "NetworkServiceInProcess", "Foo"]
 *
 * @internal
 */
export function getFeatures(flag: string, options: string[] = []): string[] {
  return options
    .filter(s => {
      return s.startsWith(flag.endsWith('=') ? flag : `${flag}=`);
    })
    .map(s => {
      return s.split(new RegExp(`${flag}` + '=\\s*'))[1]?.trim();
    })
    .filter(s => {
      return s;
    }) as string[];
}
Repository: puppeteer/puppeteer
File: packages/puppeteer-core/src/node/ChromeLauncher.ts (TypeScript)

Code before:
      return BrowsersChromeReleaseChannel.CANARY;
  }
}

/**
 * Extracts all features from the given command-line flag
 * (e.g. `--enable-features`, `--enable-features=`).
 *
 * Example input:
 * ["--enable-features=NetworkService,NetworkServiceInProcess", "--enable-features=Foo"]
 *
 * Example output:
 * ["NetworkService", "NetworkServiceInProcess", "Foo"]
 *
 * @internal
 */
export function getFeatures(flag: string, options: string[] = []): string[] {
  const opts = options
    .filter(s => {
      return s.startsWith(flag.endsWith('=') ? flag : `${flag}=`);
    })
    .map(s => {
      return s.split(new RegExp(`${flag}` + '=\\s*'))[1]?.trim();
    });
  return opts.length === 0 ? [] : opts.join(',').split(',');
}


Review comment (suggestion):
```suggestion
export function getFeatures(flag: string, options: string[] = []): string[] {
  return options
    .filter(s => {
      return s.startsWith(flag.endsWith('=') ? flag : `${flag}=`);
    })
    .map(s => {
      return s.split(new RegExp(`${flag}=\\s*`))[1]?.trim();
    })
    .filter(s => {
      return s;
    }) as string[];
}
```

Code after:
      return BrowsersChromeReleaseChannel.CANARY;
  }
}

/**
 * Extracts all features from the given command-line flag
 * (e.g. `--enable-features`, `--enable-features=`).
 *
 * Example input:
 * ["--enable-features=NetworkService,NetworkServiceInProcess", "--enable-features=Foo"]
 *
 * Example output:
 * ["NetworkService", "NetworkServiceInProcess", "Foo"]
 *
 * @internal
 */
export function getFeatures(flag: string, options: string[] = []): string[] {
  return options
    .filter(s => {
      return s.startsWith(flag.endsWith('=') ? flag : `${flag}=`);
    })
    .map(s => {
      return s.split(new RegExp(`${flag}` + '=\\s*'))[1]?.trim();
    })
    .filter(s => {
      return s;
    }) as string[];
}
Repository: puppeteer/puppeteer
File: test/src/device-request-prompt.spec.ts (TypeScript)

Code before:
 */
import expect from 'expect';
import {TimeoutError} from 'puppeteer';

import {launch} from './mocha-utils.js';

describe('device request prompt', function () {
  let testState: Awaited<ReturnType<typeof launch>>;

  beforeEach(async () => {
    testState = await launch({
      args: ['--enable-features=WebBluetoothNewPermissionsBackend'],
    });
  });

  afterEach(async () => {
    await testState.close();
  });

  it('does not crash', async () => {
    const {page, server} = testState;

    await page.goto(server.EMPTY_PAGE);
    await page.waitForNetworkIdle();

    await expect(page.waitForDevicePrompt()).rejects.toThrow(TimeoutError);
  });
});


Review comment (bug):
Please leave a comment ref to Bug.
Also if possible provided a lower time for timeout as currently the timeout is `30_000` and the test will always fail with a Timeout from Mocha (Mocha timeout is set to `10_000`)

Code after:
 */
import expect from 'expect';
import {TimeoutError} from 'puppeteer';

import {launch} from './mocha-utils.js';

describe('device request prompt', function () {
  let state: Awaited<ReturnType<typeof launch>>;

  before(async () => {
    state = await launch(
      {
        args: ['--enable-features=WebBluetoothNewPermissionsBackend'],
        ignoreHTTPSErrors: true,
      },
      {
        after: 'all',
      }
    );
  });

  after(async () => {
    await state.close();
  });

  beforeEach(async () => {
    state.context = await state.browser.createIncognitoBrowserContext();
    state.page = await state.context.newPage();
  });

  afterEach(async () => {
    await state.context.close();
  });

  // Bug: #11072
  it('does not crash', async function () {
    this.timeout(1_000);

    const {page, httpsServer} = state;

    await page.goto(httpsServer.EMPTY_PAGE);

    await expect(
      page.waitForDevicePrompt({
        timeout: 10,
      })
    ).rejects.toThrow(TimeoutError);
  });
});
Repository: puppeteer/puppeteer
File: test/src/device-request-prompt.spec.ts (TypeScript)

Code before:

  after(async () => {
    await state.close();
  });

  beforeEach(async () => {
    state.context = await state.browser.createIncognitoBrowserContext();
    state.page = await state.context.newPage();
  });

  afterEach(async () => {
    await state.context.close();
  });

  // Bug: #11072
  it('does not crash', async () => {
    const {page, httpsServer} = state;

    await page.goto(httpsServer.EMPTY_PAGE);

    await expect(
      page.waitForDevicePrompt({
        timeout: 1,
      })
    ).rejects.toThrow(TimeoutError);
  }).timeout(1_000);
});


Review comment (suggestion):
Prefer to set it in the test itself as first line. That way its easier to understand 
```
this.timeout(1_000)
```

Code after:

  after(async () => {
    await state.close();
  });

  beforeEach(async () => {
    state.context = await state.browser.createIncognitoBrowserContext();
    state.page = await state.context.newPage();
  });

  afterEach(async () => {
    await state.context.close();
  });

  // Bug: #11072
  it('does not crash', async function () {
    this.timeout(1_000);

    const {page, httpsServer} = state;

    await page.goto(httpsServer.EMPTY_PAGE);

    await expect(
      page.waitForDevicePrompt({
        timeout: 10,
      })
    ).rejects.toThrow(TimeoutError);
  });
});
Repository: puppeteer/puppeteer
File: packages/puppeteer-core/src/common/CallbackRegistry.ts (TypeScript)

Code before:
/**
 * Copyright 2017 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import {ProtocolError, TargetCloseError} from './Errors.js';
import {debugError} from './util.js';
import {Deferred} from '../util/Deferred.js';
import {rewriteError} from '../util/ErrorLike.js';

/**
 * Manages callbacks and their IDs for the protocol request/response communication.
 *
 * @internal
 */
export class CallbackRegistry {

Review comment (suggestion):
```suggestion
 * Copyright 2023 Google Inc. All rights reserved.
```

Code after:
/**
 * Copyright 2023 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import {Deferred} from '../util/Deferred.js';
import {rewriteError} from '../util/ErrorLike.js';

import {ProtocolError, TargetCloseError} from './Errors.js';
import {debugError} from './util.js';

/**
 * Manages callbacks and their IDs for the protocol request/response communication.
 *
 * @internal
 */
Repository: puppeteer/puppeteer
File: packages/puppeteer-core/src/node/ChromeLauncher.ts (TypeScript)

Code before:
  /**
   * @internal
   */
  override async cleanUserDataDir(
    path: string,
    opts: {isTemp: boolean}
  ): Promise<void> {
    if (opts.isTemp) {
      try {
        await rm(path);
      } catch (error) {
        debugError(error);
        throw error;
      }
    }
  }

  override defaultArgs(options: BrowserLaunchArgumentOptions = {}): string[] {
    // See https://github.com/GoogleChrome/chrome-launcher/blob/main/docs/chrome-flags-for-tools.md

    const userDisabledFeatures = getFeatures(
      '--disable-features',
      options.args
    );
    if (userDisabledFeatures.length > 0) {
      removeMatching(options.args ?? [], /^--disable-features=.*/);
    }

    // Merge default disabled features with user-provided ones, if any.
    const disabledFeatures = [
      'Translate',
      // AcceptCHFrame disabled because of crbug.com/1348106.
      'AcceptCHFrame',
      'MediaRouter',
      'OptimizationHints',
      // https://crbug.com/1492053
      'ProcessPerSiteUpToMainFrameThreshold',
      ...userDisabledFeatures,
    ];

    const userEnabledFeatures = getFeatures('--enable-features', options.args);
    if (userEnabledFeatures.length > 0) {
      removeMatching(options.args ?? [], /^--enable-features=.*/);
    }

    // Merge default enabled features with user-provided ones, if any.
    const enabledFeatures = [
      'NetworkServiceInProcess2',
      ...userEnabledFeatures,
    ];


Review comment (suggestion):
Nit: 
```suggestion
    if (options.args && userDisabledFeatures.length > 0) {
      removeMatching(options.args, /^--disable-features=.*/);
```

Code after:
  /**
   * @internal
   */
  override async cleanUserDataDir(
    path: string,
    opts: {isTemp: boolean}
  ): Promise<void> {
    if (opts.isTemp) {
      try {
        await rm(path);
      } catch (error) {
        debugError(error);
        throw error;
      }
    }
  }

  override defaultArgs(options: BrowserLaunchArgumentOptions = {}): string[] {
    // See https://github.com/GoogleChrome/chrome-launcher/blob/main/docs/chrome-flags-for-tools.md

    const userDisabledFeatures = getFeatures(
      '--disable-features',
      options.args
    );
    if (options.args && userDisabledFeatures.length > 0) {
      removeMatchingFlags(options.args, '--disable-features');
    }

    // Merge default disabled features with user-provided ones, if any.
    const disabledFeatures = [
      'Translate',
      // AcceptCHFrame disabled because of crbug.com/1348106.
      'AcceptCHFrame',
      'MediaRouter',
      'OptimizationHints',
      // https://crbug.com/1492053
      'ProcessPerSiteUpToMainFrameThreshold',
      ...userDisabledFeatures,
    ];

    const userEnabledFeatures = getFeatures('--enable-features', options.args);
    if (options.args && userEnabledFeatures.length > 0) {
      removeMatchingFlags(options.args, '--enable-features');
    }

    // Merge default enabled features with user-provided ones, if any.
    const enabledFeatures = [
      'NetworkServiceInProcess2',
      ...userEnabledFeatures,
    ];