ronantakizawa/codereview-bench huggingface dataset:
Repository: discordjs/discord.js
File: packages/util/src/RawFile.ts (TypeScript)

Code before:
import type { Buffer } from 'node:buffer';

/**
 * Represents a file to be added to a request with multipart/form-data encoding
 */
export interface RawFile {
	/**
	 * Content-Type of the file (e.g., 'image/png', 'application/pdf')
	 * If not provided, it will be inferred from the file data when possible
	 */
	contentType?: string;
	/**
	 * The actual data for the file
	 */
	data: Buffer | Uint8Array | boolean | number | string;
	/**
	 * An explicit key to use for the formdata field for this file.
	 * When not provided, the index of the file in the files array is used in the form `files[${index}]`.
	 * If you wish to alter the placeholder snowflake, you must provide this property in the same form (`files[${placeholder}]`)
	 */
	key?: string;
	/**
	 * The name of the file. This is the actual filename that will be used when uploading to Discord.
	 * This is also the name you'll use to reference the file with attachment:// URLs.
	 *
	 * @example 'image.png'
	 * @example 'document.pdf'
	 * @example 'SPOILER_secret.jpeg'
	 */
	name: string;
}


Review comment (suggestion):
```suggestion
	 * Content-Type of the file.
	 * If not provided, it will be inferred from the file data when possible
	 *
	 * @example 'image/png'
	 * @example 'application/pdf'
```

Code after:
import type { Buffer } from 'node:buffer';

/**
 * Represents a file to be added to a request with multipart/form-data encoding
 */
export interface RawFile {
	/**
	 * Content-Type of the file.
	 * If not provided, it will be inferred from the file data when possible
	 *
	 * @example 'image/png'
	 * @example 'application/pdf'
	 */
	contentType?: string;
	/**
	 * The actual data for the file
	 */
	data: Buffer | Uint8Array | boolean | number | string;
	/**
	 * An explicit key to use for the formdata field for this file.
	 * When not provided, the index of the file in the files array is used in the form `files[${index}]`.
	 * If you wish to alter the placeholder snowflake, you must provide this property in the same form (`files[${placeholder}]`)
	 */
	key?: string;
	/**
	 * The name of the file. This is the actual filename that will be used when uploading to Discord.
	 * This is also the name you'll use to reference the file with attachment:// URLs.
	 *
	 * @example 'image.png'
	 * @example 'document.pdf'
	 * @example 'SPOILER_secret.jpeg'
	 */
	name: string;
}
Repository: discordjs/discord.js
File: packages/rest/src/lib/utils/types.ts (TypeScript)

Code before:
	 * The number of times this request has been attempted
	 */
	retries: number;
	/**
	 * The API route identifying the ratelimit for this request
	 */
	route: string;
}

export interface ResponseLike
	extends Pick<Response, 'arrayBuffer' | 'bodyUsed' | 'headers' | 'json' | 'ok' | 'status' | 'statusText' | 'text'> {
	body: Readable | ReadableStream | null;
}

export interface InvalidRequestWarningData {
	/**
	 * Number of invalid requests that have been made in the window
	 */
	count: number;
	/**
	 * Time in milliseconds remaining before the count resets
	 */
	remainingTime: number;
}

export { type RawFile } from '@discordjs/util';

export interface AuthData {
	/**
	 * The authorization prefix to use for this request, useful if you use this with bearer tokens
	 *
	 * @defaultValue `REST.options.authPrefix`
	 */
	prefix?: 'Bearer' | 'Bot';
	/**
	 * The authorization token to use for this request
	 */
	token: string;
}

/**
 * Represents possible data to be given to an endpoint
 */
export interface RequestData {
	/**
	 * Whether to append JSON data to form data instead of `payload_json` when sending files
	 */
	appendToFormData?: boolean;
	/**
	 * Alternate authorization data to use for this request only, or `false` to disable the Authorization header.
	 * When making a request to a route that includes a token (such as interactions or webhooks), set to `false`

Review comment (suggestion):
```suggestion
export type { RawFile } from '@discordjs/util';
```

Code after:
	 * The number of times this request has been attempted
	 */
	retries: number;
	/**
	 * The API route identifying the ratelimit for this request
	 */
	route: string;
}

export interface ResponseLike
	extends Pick<Response, 'arrayBuffer' | 'bodyUsed' | 'headers' | 'json' | 'ok' | 'status' | 'statusText' | 'text'> {
	body: Readable | ReadableStream | null;
}

export interface InvalidRequestWarningData {
	/**
	 * Number of invalid requests that have been made in the window
	 */
	count: number;
	/**
	 * Time in milliseconds remaining before the count resets
	 */
	remainingTime: number;
}

export type { RawFile } from '@discordjs/util';

export interface AuthData {
	/**
	 * The authorization prefix to use for this request, useful if you use this with bearer tokens
	 *
	 * @defaultValue `REST.options.authPrefix`
	 */
	prefix?: 'Bearer' | 'Bot';
	/**
	 * The authorization token to use for this request
	 */
	token: string;
}

/**
 * Represents possible data to be given to an endpoint
 */
export interface RequestData {
	/**
	 * Whether to append JSON data to form data instead of `payload_json` when sending files
	 */
	appendToFormData?: boolean;
	/**
	 * Alternate authorization data to use for this request only, or `false` to disable the Authorization header.
	 * When making a request to a route that includes a token (such as interactions or webhooks), set to `false`
Repository: discordjs/discord.js
File: packages/builders/src/messages/Attachment.ts (TypeScript)

Code before:
		return this;
	}

	/**
	 * Sets the filename of this attachment.
	 *
	 * @param filename - The filename of the attachment
	 */
	public setFilename(filename: string): this {
		this.data.filename = filename;
		return this;
	}

	/**
	 * Clears the filename of this attachment.
	 */
	public clearFilename(): this {
		this.data.filename = undefined;
		return this;
	}

	/**
	 * Sets the file data to upload with this attachment.
	 *
	 * @param data - The file data (Buffer, Uint8Array, or string)
	 * @remarks Note that this data is NOT included in the `toJSON()` output. To retrieve, use {@link getRawFile}.
	 */
	public setFileData(data: Buffer | Uint8Array | string): this {
		this.fileData.data = data;
		return this;
	}

	/**
	 * Clears the file data from this attachment.
	 */
	public clearFileData(): this {
		this.fileData.data = undefined;
		return this;
	}

	/**
	 * Sets the content type of the file data to upload with this attachment.
	 *
	 * @remarks Note that this data is NOT included in the `toJSON()` output. To retrieve, use {@link getRawFile}.
	 */
	public setFileContentType(contentType: string): this {
		this.fileData.contentType = contentType;
		return this;
	}

	/**

Review comment (suggestion):
```suggestion
	 * @remarks Note that this data is NOT included in the {@link toJSON} output. To retrieve it, use {@link getRawFile}.
```

Code after:
		return this;
	}

	/**
	 * Sets the filename of this attachment.
	 *
	 * @param filename - The filename of the attachment
	 */
	public setFilename(filename: string): this {
		this.data.filename = filename;
		return this;
	}

	/**
	 * Clears the filename of this attachment.
	 */
	public clearFilename(): this {
		this.data.filename = undefined;
		return this;
	}

	/**
	 * Sets the file data to upload with this attachment.
	 *
	 * @param data - The file data
	 * @remarks Note that this data is NOT included in the {@link toJSON} output. To retrieve it, use {@link getRawFile}.
	 */
	public setFileData(data: Buffer | Uint8Array | string): this {
		this.fileData.data = data;
		return this;
	}

	/**
	 * Clears the file data from this attachment.
	 */
	public clearFileData(): this {
		this.fileData.data = undefined;
		return this;
	}

	/**
	 * Sets the content type of the file data to upload with this attachment.
	 *
	 * @remarks Note that this data is NOT included in the {@link toJSON} output. To retrieve it, use {@link getRawFile}.
	 */
	public setFileContentType(contentType: string): this {
		this.fileData.contentType = contentType;
		return this;
	}

	/**
Repository: discordjs/discord.js
File: packages/builders/src/messages/Attachment.ts (TypeScript)

Code before:
		return this;
	}

	/**
	 * Sets the file data to upload with this attachment.
	 *
	 * @param data - The file data (Buffer, Uint8Array, or string)
	 * @remarks Note that this data is NOT included in the `toJSON()` output. To retrieve, use {@link getRawFile}.
	 */
	public setFileData(data: Buffer | Uint8Array | string): this {
		this.fileData.data = data;
		return this;
	}

	/**
	 * Clears the file data from this attachment.
	 */
	public clearFileData(): this {
		this.fileData.data = undefined;
		return this;
	}

	/**
	 * Sets the content type of the file data to upload with this attachment.
	 *
	 * @remarks Note that this data is NOT included in the `toJSON()` output. To retrieve, use {@link getRawFile}.
	 */
	public setFileContentType(contentType: string): this {
		this.fileData.contentType = contentType;
		return this;
	}

	/**
	 * Clears the content type of the file data from this attachment.
	 */
	public clearFileContentType(): this {
		this.fileData.contentType = undefined;
		return this;
	}

	/**
	 * Converts this attachment to a RawFile for uploading.
	 *
	 * @returns A RawFile object, or undefined if no file data is set
	 */
	public getRawFile(): Partial<RawFile> | undefined {
		if (!this.fileData?.data) {
			return;
		}

		return {

Review comment (suggestion):
```suggestion
	 * @remarks Note that this data is NOT included in the {@link toJSON} output. To retrieve it, use {@link getRawFile}.
```

Code after:
		return this;
	}

	/**
	 * Sets the file data to upload with this attachment.
	 *
	 * @param data - The file data
	 * @remarks Note that this data is NOT included in the {@link toJSON} output. To retrieve it, use {@link getRawFile}.
	 */
	public setFileData(data: Buffer | Uint8Array | string): this {
		this.fileData.data = data;
		return this;
	}

	/**
	 * Clears the file data from this attachment.
	 */
	public clearFileData(): this {
		this.fileData.data = undefined;
		return this;
	}

	/**
	 * Sets the content type of the file data to upload with this attachment.
	 *
	 * @remarks Note that this data is NOT included in the {@link toJSON} output. To retrieve it, use {@link getRawFile}.
	 */
	public setFileContentType(contentType: string): this {
		this.fileData.contentType = contentType;
		return this;
	}

	/**
	 * Clears the content type of the file data from this attachment.
	 */
	public clearFileContentType(): this {
		this.fileData.contentType = undefined;
		return this;
	}

	/**
	 * Converts this attachment to a {@link RawFile} for uploading.
	 *
	 * @returns A {@link RawFile} object, or `undefined` if no file data is set
	 */
	public getRawFile(): Partial<RawFile> | undefined {
		if (!this.fileData?.data) {
			return;
		}

		return {
Repository: discordjs/discord.js
File: packages/builders/src/messages/Attachment.ts (TypeScript)

Code before:
		this.fileData.data = undefined;
		return this;
	}

	/**
	 * Sets the content type of the file data to upload with this attachment.
	 *
	 * @remarks Note that this data is NOT included in the `toJSON()` output. To retrieve, use {@link getRawFile}.
	 */
	public setFileContentType(contentType: string): this {
		this.fileData.contentType = contentType;
		return this;
	}

	/**
	 * Clears the content type of the file data from this attachment.
	 */
	public clearFileContentType(): this {
		this.fileData.contentType = undefined;
		return this;
	}

	/**
	 * Converts this attachment to a RawFile for uploading.
	 *
	 * @returns A RawFile object, or undefined if no file data is set
	 */
	public getRawFile(): Partial<RawFile> | undefined {
		if (!this.fileData?.data) {
			return;
		}

		return {
			...this.fileData,
			name: this.data.filename,
			key: this.data.id ? `files[${this.data.id}]` : undefined,
		};
	}

	/**
	 * Sets the title of this attachment.
	 *
	 * @param title - The title of the attachment
	 */
	public setTitle(title: string): this {
		this.data.title = title;
		return this;
	}

	/**
	 * Clears the title of this attachment.

Review comment (suggestion):
```suggestion
	 * Converts this attachment to a {@link RawFile} for uploading.
	 *
	 * @returns A {@link RawFile} object, or `undefined` if no file data is set
```

Code after:
		this.fileData.data = undefined;
		return this;
	}

	/**
	 * Sets the content type of the file data to upload with this attachment.
	 *
	 * @remarks Note that this data is NOT included in the {@link toJSON} output. To retrieve it, use {@link getRawFile}.
	 */
	public setFileContentType(contentType: string): this {
		this.fileData.contentType = contentType;
		return this;
	}

	/**
	 * Clears the content type of the file data from this attachment.
	 */
	public clearFileContentType(): this {
		this.fileData.contentType = undefined;
		return this;
	}

	/**
	 * Converts this attachment to a {@link RawFile} for uploading.
	 *
	 * @returns A {@link RawFile} object, or `undefined` if no file data is set
	 */
	public getRawFile(): Partial<RawFile> | undefined {
		if (!this.fileData?.data) {
			return;
		}

		return {
			...this.fileData,
			name: this.data.filename,
			key: this.data.id ? `files[${this.data.id}]` : undefined,
		};
	}

	/**
	 * Sets the title of this attachment.
	 *
	 * @param title - The title of the attachment
	 */
	public setTitle(title: string): this {
		this.data.title = title;
		return this;
	}

	/**
	 * Clears the title of this attachment.
Repository: discordjs/discord.js
File: packages/builders/src/messages/Assertions.ts (TypeScript)

Code before:
		}),
	])
	.array()
	.min(1)
	.max(10);

const messageComponentsV2Predicate = baseMessagePredicate.extend({
	components: allTopLevelComponentsPredicate,
	flags: z.int().refine((flags) => (flags & MessageFlags.IsComponentsV2) === MessageFlags.IsComponentsV2, {
		error: 'Must set IsComponentsV2 flag to use Components V2',
	}),
	// These fields cannot be set
	content: z.string().length(0).nullish(),
	embeds: z.array(z.never()).nullish(),
	sticker_ids: z.array(z.never()).nullish(),
	poll: z.null().optional(),
});

export const messagePredicate = z.union([messageNoComponentsV2Predicate, messageComponentsV2Predicate]);

// This validator does not assert file.key <-> attachment.id coherence. This is fine, because the builders
// should effectively guarantee that.
export const fileBodyMessagePredicate = z.object({
	body: messagePredicate,
	// No min length to support message edits
	files: rawFilePredicate.array(),
});


Review comment (suggestion):
```suggestion
	files: rawFilePredicate.array().max(10),
```

Code after:
		}),
	])
	.array()
	.min(1)
	.max(10);

const messageComponentsV2Predicate = baseMessagePredicate.extend({
	components: allTopLevelComponentsPredicate,
	flags: z.int().refine((flags) => (flags & MessageFlags.IsComponentsV2) === MessageFlags.IsComponentsV2, {
		error: 'Must set IsComponentsV2 flag to use Components V2',
	}),
	// These fields cannot be set
	content: z.string().length(0).nullish(),
	embeds: z.array(z.never()).nullish(),
	sticker_ids: z.array(z.never()).nullish(),
	poll: z.null().optional(),
});

export const messagePredicate = z.union([messageNoComponentsV2Predicate, messageComponentsV2Predicate]);

// This validator does not assert file.key <-> attachment.id coherence. This is fine, because the builders
// should effectively guarantee that.
export const fileBodyMessagePredicate = z.object({
	body: messagePredicate,
	// No min length to support message edits
	files: rawFilePredicate.array().max(10),
});
Repository: discordjs/discord.js
File: packages/util/src/gatewayRateLimitError.ts (TypeScript)

Code before:
import type { GatewayOpcodeRateLimitMetadataMap, GatewayRateLimitedDispatchData } from 'discord-api-types/v10';

/**
 * Represents the error thrown when the gateway emits a `RATE_LIMITED` event after a certain request.
 */
export class GatewayRateLimitError extends Error {
	public override readonly name = GatewayRateLimitError.name;

	public constructor(
		/**
		 * The data associated with the rate limit event
		 */
		public readonly data: GatewayRateLimitedDispatchData<keyof GatewayOpcodeRateLimitMetadataMap>,
		/**
		 * The payload data that lead to this rate limit
		 */
		// Too complicated to type properly here (i.e. extract the ['data']
		// of event payloads that have t = keyof GatewayOpcodeRateLimitMetadataMap)
		public readonly payload: unknown,
	) {
		super(`Request with opcode ${data.opcode} was rate limited. Retry after ${data.retry_after} seconds.`);
	}
}


Review comment (refactor):
```suggestion
		/**
		 * The payload data that lead to this rate limit
		 *
		 * @privateRemarks
		 * Too complicated to type properly here (i.e. extract the ['data']
		 * of event payloads that have t = keyof GatewayOpcodeRateLimitMetadataMap)
		 */
```

Code after:
import type { GatewayOpcodeRateLimitMetadataMap, GatewayRateLimitedDispatchData } from 'discord-api-types/v10';

/**
 * Represents the error thrown when the gateway emits a `RATE_LIMITED` event after a certain request.
 */
export class GatewayRateLimitError extends Error {
	public override readonly name = GatewayRateLimitError.name;

	public constructor(
		/**
		 * The data associated with the rate limit event
		 */
		public readonly data: GatewayRateLimitedDispatchData<keyof GatewayOpcodeRateLimitMetadataMap>,
		/**
		 * The payload data that lead to this rate limit
		 *
		 * @privateRemarks
		 * Too complicated to type properly here (i.e. extract the ['data']
		 * of event payloads that have t = keyof GatewayOpcodeRateLimitMetadataMap)
		 */
		public readonly payload: unknown,
	) {
		super(`Request with opcode ${data.opcode} was rate limited. Retry after ${data.retry_after} seconds.`);
	}
}
Repository: discordjs/discord.js
File: packages/discord.js/src/client/websocket/handlers/RATE_LIMITED.js (JavaScript)

Code before:
'use strict';

const process = require('node:process');
const { GatewayRateLimitError } = require('@discordjs/util');
const { GatewayOpcodes } = require('discord-api-types/v10');

const emittedFor = new Set();

module.exports = (client, { d: data }) => {
  switch (data.opcode) {
    case GatewayOpcodes.RequestGuildMembers: {
      break;
    }

    default: {
      if (!emittedFor.has(data.opcode)) {
        const warning = new GatewayRateLimitError(data, '<unknown>');
        process.emitWarning(
          'Received a rate limit for an unknown opcode. The error below contains information about the rate limit. Please open an issue on GitHub',
        );
        process.emitWarning(warning);

        emittedFor.add(data.opcode);
      }
    }
  }
};


Review comment (suggestion):
This is only going to log the string (i.e. `GatewayRateLimitError: Request with opcode X was rate limited. Retry after Y seconds.`), is that intended? It sounds like we'd want to log the object (we lose logging `meta`).

Code after:
'use strict';

const process = require('node:process');
const { GatewayOpcodes } = require('discord-api-types/v10');

const emittedFor = new Set();

module.exports = (client, { d: data }) => {
  switch (data.opcode) {
    case GatewayOpcodes.RequestGuildMembers: {
      break;
    }

    default: {
      if (!emittedFor.has(data.opcode)) {
        process.emitWarning(
          `Hit a gateway rate limit on opcode ${data.opcode} (${GatewayOpcodes[data.opcode]}). If the discord.js version you're using is up-to-date, please open an issue on GitHub.`,
        );

        emittedFor.add(data.opcode);
      }
    }
  }
};
Repository: discordjs/discord.js
File: packages/discord.js/src/client/websocket/handlers/RATE_LIMITED.js (JavaScript)

Code before:
'use strict';

const process = require('node:process');
const { GatewayOpcodes } = require('discord-api-types/v10');

const emittedFor = new Set();

module.exports = (client, { d: data }) => {
  switch (data.opcode) {
    case GatewayOpcodes.RequestGuildMembers: {
      break;
    }

    default: {
      if (!emittedFor.has(data.opcode)) {
        process.emitWarning(
          `Hit a gateway rate limit on opcode ${data.opcode}. If your library is up-to-date, please open an issue on GitHub.`,
        );

        emittedFor.add(data.opcode);
      }
    }
  }
};


Review comment (suggestion):
```suggestion
          `Hit a gateway rate limit on opcode ${data.opcode} (${GatewayOpcodes[data.opcode]}). If the discord.js version you're using is up-to-date, please open an issue on GitHub.`,
```

Code after:
'use strict';

const process = require('node:process');
const { GatewayOpcodes } = require('discord-api-types/v10');

const emittedFor = new Set();

module.exports = (client, { d: data }) => {
  switch (data.opcode) {
    case GatewayOpcodes.RequestGuildMembers: {
      break;
    }

    default: {
      if (!emittedFor.has(data.opcode)) {
        process.emitWarning(
          `Hit a gateway rate limit on opcode ${data.opcode} (${GatewayOpcodes[data.opcode]}). If the discord.js version you're using is up-to-date, please open an issue on GitHub.`,
        );

        emittedFor.add(data.opcode);
      }
    }
  }
};
Repository: discordjs/discord.js
File: packages/discord.js/src/managers/ChannelManager.js (JavaScript)

Code before:
   * client.channels.createMessage(channel, {
   *   files: ['https://github.com/discordjs.png']
   * })
   *   .then(console.log)
   *   .catch(console.error);
   * @example
   * // Send a local file
   * client.channels.createMessage(channel, {
   *   files: [{
   *     attachment: 'entire/path/to/file.jpg',
   *     name: 'file.jpg',
   *     description: 'A description of the file'
   *   }]
   * })
   *   .then(console.log)
   *   .catch(console.error);
   */
  async createMessage(channel, options) {
    let payload;

    if (options instanceof MessagePayload) {
      payload = await options.resolveBody().resolveFiles();
    } else if (isFileBodyEncodable(options)) {
      payload = options.toFileBody();
    } else if (isJSONEncodable(options)) {
      payload = { body: options.toJSON(), files: [] };
    } else {
      payload = await MessagePayload.create(this, options).resolveBody().resolveFiles();
    }

    const resolvedChannelId = this.resolveId(channel);
    const resolvedChannel = this.resolve(channel);
    const data = await this.client.rest.post(Routes.channelMessages(resolvedChannelId), payload);

    return resolvedChannel?.messages._add(data) ?? new (getMessage())(this.client, data);
  }
}

exports.ChannelManager = ChannelManager;


Review comment (suggestion):
```suggestion
      payload = { body: options.toJSON() };
```

Code after:
   * client.channels.createMessage(channel, {
   *   files: ['https://github.com/discordjs.png']
   * })
   *   .then(console.log)
   *   .catch(console.error);
   * @example
   * // Send a local file
   * client.channels.createMessage(channel, {
   *   files: [{
   *     attachment: 'entire/path/to/file.jpg',
   *     name: 'file.jpg',
   *     description: 'A description of the file'
   *   }]
   * })
   *   .then(console.log)
   *   .catch(console.error);
   */
  async createMessage(channel, options) {
    let payload;

    if (options instanceof MessagePayload) {
      payload = await options.resolveBody().resolveFiles();
    } else if (isFileBodyEncodable(options)) {
      payload = options.toFileBody();
    } else if (isJSONEncodable(options)) {
      payload = { body: options.toJSON() };
    } else {
      payload = await MessagePayload.create(this, options).resolveBody().resolveFiles();
    }

    const resolvedChannelId = this.resolveId(channel);
    const resolvedChannel = this.resolve(channel);
    const data = await this.client.rest.post(Routes.channelMessages(resolvedChannelId), payload);

    return resolvedChannel?.messages._add(data) ?? new (getMessage())(this.client, data);
  }
}

exports.ChannelManager = ChannelManager;