Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Min/Max for type array to generate better faker.helpers.arrayElements functionality #1339

Merged
merged 3 commits into from
Oct 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/tiny-needles-guess.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@kubb/plugin-faker": patch
---

Min/Max for type array to generate better `faker.helpers.arrayElements` functionality
3 changes: 3 additions & 0 deletions docs/changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ title: Changelog

# Changelog

## 3.0.0-beta.6
- [`plugin-faker`](/plugins/plugin-faker): Min/Max for type array to generate better `faker.helpers.arrayElements` functionality

## 3.0.0-beta.5
- [`plugin-zod`](/plugins/plugin-zod): Discard `optional()` if there is a `default()` to ensure the output type is not `T | undefined`

Expand Down
4 changes: 2 additions & 2 deletions examples/advanced/src/gen/mocks/createAddPetRequestFaker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ export function createAddPetRequestFaker(data: NonNullable<Partial<AddPetRequest
id: faker.number.int(),
name: faker.string.alpha(),
category: createCategoryFaker(),
photoUrls: faker.helpers.arrayElements([faker.string.alpha()]) as any,
tags: faker.helpers.arrayElements([createTagTagFaker()]) as any,
photoUrls: faker.helpers.multiple(() => faker.string.alpha()) as any,
tags: faker.helpers.multiple(() => createTagTagFaker()) as any,
status: faker.helpers.arrayElement(['working', 'idle']) as any,
},
...data,
Expand Down
2 changes: 1 addition & 1 deletion examples/advanced/src/gen/mocks/createCustomerFaker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { faker } from '@faker-js/faker'

export function createCustomerFaker(data: NonNullable<Partial<Customer>> = {}) {
return {
...{ id: faker.number.int(), username: faker.string.alpha(), address: faker.helpers.arrayElements([createAddressFaker()]) as any },
...{ id: faker.number.int(), username: faker.string.alpha(), address: faker.helpers.multiple(() => createAddressFaker()) as any },
...data,
}
}
4 changes: 2 additions & 2 deletions examples/advanced/src/gen/mocks/createPetFaker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ export function createPetFaker(data: NonNullable<Partial<Pet>> = {}) {
id: faker.number.int(),
name: faker.string.alpha(),
category: createCategoryFaker(),
photoUrls: faker.helpers.arrayElements([faker.string.alpha()]) as any,
tags: faker.helpers.arrayElements([createTagTagFaker()]) as any,
photoUrls: faker.helpers.multiple(() => faker.string.alpha()) as any,
tags: faker.helpers.multiple(() => createTagTagFaker()) as any,
status: faker.helpers.arrayElement(['working', 'idle']) as any,
},
...data,
Expand Down
4 changes: 2 additions & 2 deletions examples/advanced/src/gen/mocks/createUserArrayFaker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,6 @@ import type { UserArray } from '../models/ts/UserArray.ts'
import { createUserFaker } from './createUserFaker.ts'
import { faker } from '@faker-js/faker'

export function createUserArrayFaker(data: NonNullable<Partial<UserArray>> = []) {
return [...(faker.helpers.arrayElements([createUserFaker()]) as any), ...data]
export function createUserArrayFaker() {
return faker.helpers.multiple(() => createUserFaker()) as any
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ export function createFindPetsByStatusQueryParamsFaker(data: NonNullable<Partial
/**
* @description successful operation
*/
export function createFindPetsByStatus200Faker(data: NonNullable<Partial<FindPetsByStatus200>> = []) {
return [...(faker.helpers.arrayElements([createPetFaker()]) as any), ...data]
export function createFindPetsByStatus200Faker() {
return faker.helpers.multiple(() => createPetFaker(), { count: { min: 1, max: 3 } }) as any
}

/**
Expand All @@ -26,6 +26,6 @@ export function createFindPetsByStatus400Faker() {
/**
* @description successful operation
*/
export function createFindPetsByStatusQueryResponseFaker(data: NonNullable<Partial<FindPetsByStatusQueryResponse>> = []) {
return [...(faker.helpers.arrayElements([createPetFaker()]) as any), ...data]
export function createFindPetsByStatusQueryResponseFaker() {
return faker.helpers.multiple(() => createPetFaker(), { count: { min: 1, max: 3 } }) as any
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { faker } from '@faker-js/faker'

export function createFindPetsByTagsQueryParamsFaker(data: NonNullable<Partial<FindPetsByTagsQueryParams>> = {}) {
return {
...{ tags: faker.helpers.arrayElements([faker.string.alpha()]) as any, page: faker.string.alpha(), pageSize: faker.string.alpha() },
...{ tags: faker.helpers.multiple(() => faker.string.alpha()) as any, page: faker.string.alpha(), pageSize: faker.string.alpha() },
...data,
}
}
Expand All @@ -24,8 +24,8 @@ export function createFindPetsByTagsHeaderParamsFaker(data: NonNullable<Partial<
/**
* @description successful operation
*/
export function createFindPetsByTags200Faker(data: NonNullable<Partial<FindPetsByTags200>> = []) {
return [...(faker.helpers.arrayElements([createPetFaker()]) as any), ...data]
export function createFindPetsByTags200Faker() {
return faker.helpers.multiple(() => createPetFaker()) as any
}

/**
Expand All @@ -38,6 +38,6 @@ export function createFindPetsByTags400Faker() {
/**
* @description successful operation
*/
export function createFindPetsByTagsQueryResponseFaker(data: NonNullable<Partial<FindPetsByTagsQueryResponse>> = []) {
return [...(faker.helpers.arrayElements([createPetFaker()]) as any), ...data]
export function createFindPetsByTagsQueryResponseFaker() {
return faker.helpers.multiple(() => createPetFaker()) as any
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ export function createCreateUsersWithListInputErrorFaker() {
return undefined
}

export function createCreateUsersWithListInputMutationRequestFaker(data: NonNullable<Partial<CreateUsersWithListInputMutationRequest>> = []) {
return [...(faker.helpers.arrayElements([createUserFaker()]) as any), ...data]
export function createCreateUsersWithListInputMutationRequestFaker() {
return faker.helpers.multiple(() => createUserFaker()) as any
}

/**
Expand Down
2 changes: 1 addition & 1 deletion examples/faker/src/gen/faker/createCustomer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { faker } from '@faker-js/faker'

export function createCustomer(data: NonNullable<Partial<Customer>> = {}) {
return {
...{ id: faker.number.int(), username: faker.string.alpha(), address: faker.helpers.arrayElements([createAddress()]) as any },
...{ id: faker.number.int(), username: faker.string.alpha(), address: faker.helpers.multiple(() => createAddress()) as any },
...data,
}
}
4 changes: 2 additions & 2 deletions examples/faker/src/gen/faker/createPet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ export function createPet(data: NonNullable<Partial<Pet>> = {}) {
id: faker.number.int(),
name: faker.commerce.productName(),
category: createCategory(),
photoUrls: faker.helpers.arrayElements([faker.string.alpha()]) as any,
tags: faker.helpers.arrayElements([createTag()]) as any,
photoUrls: faker.helpers.multiple(() => faker.string.alpha()) as any,
tags: faker.helpers.multiple(() => createTag()) as any,
status: faker.helpers.arrayElement<any>(['available', 'pending', 'sold']),
},
...data,
Expand Down
4 changes: 2 additions & 2 deletions examples/faker/src/gen/faker/createUserArray.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,6 @@ import type { UserArray } from '../models/UserArray.ts'
import { createUser } from './createUser.ts'
import { faker } from '@faker-js/faker'

export function createUserArray(data: NonNullable<Partial<UserArray>> = []) {
return [...(faker.helpers.arrayElements([createUser()]) as any), ...data]
export function createUserArray() {
return faker.helpers.multiple(() => createUser()) as any
}
2 changes: 1 addition & 1 deletion examples/faker/src/gen/tag/createCustomer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { faker } from '@faker-js/faker'

export function createCustomer(data: NonNullable<Partial<Customer>> = {}) {
return {
...{ id: faker.number.int(), username: faker.string.alpha(), address: faker.helpers.arrayElements([createAddress()]) as any },
...{ id: faker.number.int(), username: faker.string.alpha(), address: faker.helpers.multiple(() => createAddress()) as any },
...data,
}
}
4 changes: 2 additions & 2 deletions examples/faker/src/gen/tag/createPet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ export function createPet(data: NonNullable<Partial<Pet>> = {}) {
id: faker.number.int(),
name: faker.string.alpha(),
category: createCategory(),
photoUrls: faker.helpers.arrayElements([faker.string.alpha()]) as any,
tags: faker.helpers.arrayElements([createTag()]) as any,
photoUrls: faker.helpers.multiple(() => faker.string.alpha()) as any,
tags: faker.helpers.multiple(() => createTag()) as any,
status: faker.helpers.arrayElement<any>(['available', 'pending', 'sold']),
},
...data,
Expand Down
4 changes: 2 additions & 2 deletions examples/faker/src/gen/tag/createUserArray.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,6 @@ import type { UserArray } from '../models/UserArray.ts'
import { createUser } from './createUser.ts'
import { faker } from '@faker-js/faker'

export function createUserArray(data: NonNullable<Partial<UserArray>> = []) {
return [...(faker.helpers.arrayElements([createUser()]) as any), ...data]
export function createUserArray() {
return faker.helpers.multiple(() => createUser()) as any
}
4 changes: 2 additions & 2 deletions examples/msw/src/gen/mocks/createAddPetRequest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ export function createAddPetRequest(data: NonNullable<Partial<AddPetRequest>> =
id: faker.number.int(),
name: faker.string.alpha(),
category: createCategory(),
photoUrls: faker.helpers.arrayElements([faker.string.alpha()]) as any,
tags: faker.helpers.arrayElements([createTag()]) as any,
photoUrls: faker.helpers.multiple(() => faker.string.alpha()) as any,
tags: faker.helpers.multiple(() => createTag()) as any,
status: faker.helpers.arrayElement<any>(['available', 'pending', 'sold']),
},
...data,
Expand Down
2 changes: 1 addition & 1 deletion examples/msw/src/gen/mocks/createCustomer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { faker } from '@faker-js/faker'
export function createCustomer(data: NonNullable<Partial<Customer>> = {}) {
faker.seed([220])
return {
...{ id: faker.number.int(), username: faker.string.alpha(), address: faker.helpers.arrayElements([createAddress()]) as any },
...{ id: faker.number.int(), username: faker.string.alpha(), address: faker.helpers.multiple(() => createAddress()) as any },
...data,
}
}
4 changes: 2 additions & 2 deletions examples/msw/src/gen/mocks/createPet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ export function createPet(data: NonNullable<Partial<Pet>> = {}) {
id: faker.number.int(),
name: faker.string.alpha(),
category: createCategory(),
photoUrls: faker.helpers.arrayElements([faker.string.alpha()]) as any,
tags: faker.helpers.arrayElements([createTag()]) as any,
photoUrls: faker.helpers.multiple(() => faker.string.alpha()) as any,
tags: faker.helpers.multiple(() => createTag()) as any,
status: faker.helpers.arrayElement<any>(['available', 'pending', 'sold']),
},
...data,
Expand Down
4 changes: 2 additions & 2 deletions examples/msw/src/gen/mocks/createUserArray.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import type { UserArray } from '../models/UserArray.ts'
import { createUser } from './createUser.ts'
import { faker } from '@faker-js/faker'

export function createUserArray(data: NonNullable<Partial<UserArray>> = []) {
export function createUserArray() {
faker.seed([220])
return [...(faker.helpers.arrayElements([createUser()]) as any), ...data]
return faker.helpers.multiple(() => createUser()) as any
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,9 @@ export function createFindPetsByStatusQueryParams(data: NonNullable<Partial<Find
/**
* @description successful operation
*/
export function createFindPetsByStatus200(data: NonNullable<Partial<FindPetsByStatus200>> = []) {
export function createFindPetsByStatus200() {
faker.seed([220])
return [...(faker.helpers.arrayElements([createPet()]) as any), ...data]
return faker.helpers.multiple(() => createPet()) as any
}

/**
Expand All @@ -29,7 +29,7 @@ export function createFindPetsByStatus400() {
/**
* @description successful operation
*/
export function createFindPetsByStatusQueryResponse(data: NonNullable<Partial<FindPetsByStatusQueryResponse>> = []) {
export function createFindPetsByStatusQueryResponse() {
faker.seed([220])
return [...(faker.helpers.arrayElements([createPet()]) as any), ...data]
return faker.helpers.multiple(() => createPet()) as any
}
10 changes: 5 additions & 5 deletions examples/msw/src/gen/mocks/petController/createFindPetsByTags.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,17 @@ import { faker } from '@faker-js/faker'
export function createFindPetsByTagsQueryParams(data: NonNullable<Partial<FindPetsByTagsQueryParams>> = {}) {
faker.seed([220])
return {
...{ tags: faker.helpers.arrayElements([faker.string.alpha()]) as any, page: faker.string.alpha(), pageSize: faker.string.alpha() },
...{ tags: faker.helpers.multiple(() => faker.string.alpha()) as any, page: faker.string.alpha(), pageSize: faker.string.alpha() },
...data,
}
}

/**
* @description successful operation
*/
export function createFindPetsByTags200(data: NonNullable<Partial<FindPetsByTags200>> = []) {
export function createFindPetsByTags200() {
faker.seed([220])
return [...(faker.helpers.arrayElements([createPet()]) as any), ...data]
return faker.helpers.multiple(() => createPet()) as any
}

/**
Expand All @@ -29,7 +29,7 @@ export function createFindPetsByTags400() {
/**
* @description successful operation
*/
export function createFindPetsByTagsQueryResponse(data: NonNullable<Partial<FindPetsByTagsQueryResponse>> = []) {
export function createFindPetsByTagsQueryResponse() {
faker.seed([220])
return [...(faker.helpers.arrayElements([createPet()]) as any), ...data]
return faker.helpers.multiple(() => createPet()) as any
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,15 @@ import { faker } from '@faker-js/faker'
/**
* @description successful operation
*/
export function createOptionsFindPetsByStatus200(data: NonNullable<Partial<OptionsFindPetsByStatus200>> = []) {
export function createOptionsFindPetsByStatus200() {
faker.seed([220])
return [...(faker.helpers.arrayElements([createPet()]) as any), ...data]
return faker.helpers.multiple(() => createPet()) as any
}

/**
* @description successful operation
*/
export function createOptionsFindPetsByStatusMutationResponse(data: NonNullable<Partial<OptionsFindPetsByStatusMutationResponse>> = []) {
export function createOptionsFindPetsByStatusMutationResponse() {
faker.seed([220])
return [...(faker.helpers.arrayElements([createPet()]) as any), ...data]
return faker.helpers.multiple(() => createPet()) as any
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,9 @@ export function createCreateUsersWithListInputError() {
return undefined
}

export function createCreateUsersWithListInputMutationRequest(data: NonNullable<Partial<CreateUsersWithListInputMutationRequest>> = []) {
export function createCreateUsersWithListInputMutationRequest() {
faker.seed([220])
return [...(faker.helpers.arrayElements([createUser()]) as any), ...data]
return faker.helpers.multiple(() => createUser()) as any
}

/**
Expand Down
2 changes: 1 addition & 1 deletion packages/cli/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@
"consola": "^3.2.3",
"cosmiconfig": "^9.0.0",
"execa": "^9.4.0",
"jiti": "^2.3.2",
"jiti": "^2.3.3",
"latest-version": "^9.0.0",
"p-queue": "^8.0.1",
"semver": "^7.6.3",
Expand Down
7 changes: 2 additions & 5 deletions packages/plugin-faker/src/generators/__snapshots__/pets.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
import { faker } from "@faker-js/faker";

export function pets(data: NonNullable<Partial<Pets>> = []) {
return [
...faker.helpers.arrayElements([pet()]) as any,
...data
];
export function pets() {
return faker.helpers.multiple(() => (pet())) as any;
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,13 @@ exports[`faker parse > 'and' 1`] = `"Object.assign({}, faker.string.alpha(), fak

exports[`faker parse > 'any' 1`] = `"undefined"`;

exports[`faker parse > 'array' 1`] = `"faker.helpers.arrayElements([faker.helpers.arrayElement<any>([faker.number.float(), faker.string.alpha()])]) as any"`;
exports[`faker parse > 'array' 1`] = `"faker.helpers.multiple(() => (faker.helpers.arrayElement<any>([faker.number.float(), faker.string.alpha()]))) as any"`;

exports[`faker parse > 'arrayAdvanced' 1`] = `"faker.helpers.arrayElements([faker.number.float({ min: 1, max: 10 })]) as any"`;
exports[`faker parse > 'arrayAdvanced' 1`] = `"faker.helpers.multiple(() => (faker.number.float({ min: 1, max: 10 })), { count: { min: 3, max: 10 }}) as any"`;

exports[`faker parse > 'arrayEmpty' 1`] = `"faker.helpers.arrayElements([]) as any"`;
exports[`faker parse > 'arrayEmpty' 1`] = `"faker.helpers.multiple(() => (undefined)) as any"`;

exports[`faker parse > 'arrayRef' 1`] = `"faker.helpers.arrayElements([Pet()]) as any"`;
exports[`faker parse > 'arrayRef' 1`] = `"faker.helpers.multiple(() => (Pet())) as any"`;

exports[`faker parse > 'arrayRegex' 1`] = `"faker.helpers.arrayElements([faker.helpers.fromRegExp(new RegExp('^[a-zA-Z0-9]{1,13}$')), faker.string.alpha()]) as any"`;

Expand Down
25 changes: 23 additions & 2 deletions packages/plugin-faker/src/parser/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,24 @@
boolean: () => 'faker.datatype.boolean()',
undefined: () => 'undefined',
null: () => 'null',
array: (items: string[] = []) => `faker.helpers.arrayElements([${items.join(', ')}]) as any`,
array: (items: string[] = [], min?: number, max?: number) => {
if (items.length > 1) {
return `faker.helpers.arrayElements([${items.join(', ')}]) as any`
}
const item = items.at(0)

if (min !== undefined && max !== undefined) {
return `faker.helpers.multiple(() => (${item}), { count: { min: ${min}, max: ${max} }}) as any`

Check warning

Code scanning / CodeQL

Improper code sanitization Medium

Code construction depends on an
improperly sanitized value
.

Copilot Autofix AI 3 months ago

To fix the problem, we need to ensure that any potentially dangerous characters in the item variable are properly escaped before being used in the template literal. This can be achieved by implementing an escapeUnsafeChars function that replaces dangerous characters with their escaped equivalents. We will then use this function to sanitize the item variable before including it in the template literal.

Suggested changeset 1
packages/plugin-faker/src/parser/index.ts

Autofix patch

Autofix patch
Run the following command in your local git repository to apply this patch
cat << 'EOF' | git apply
diff --git a/packages/plugin-faker/src/parser/index.ts b/packages/plugin-faker/src/parser/index.ts
--- a/packages/plugin-faker/src/parser/index.ts
+++ b/packages/plugin-faker/src/parser/index.ts
@@ -6,2 +6,21 @@
 
+const charMap = {
+  '<': '\\u003C',
+  '>' : '\\u003E',
+  '/': '\\u002F',
+  '\\': '\\\\',
+  '\b': '\\b',
+  '\f': '\\f',
+  '\n': '\\n',
+  '\r': '\\r',
+  '\t': '\\t',
+  '\0': '\\0',
+  '\u2028': '\\u2028',
+  '\u2029': '\\u2029'
+};
+
+function escapeUnsafeChars(str) {
+  return str.replace(/[<>\b\f\n\r\t\0\u2028\u2029]/g, x => charMap[x])
+}
+
 const fakerKeywordMapper = {
@@ -61,3 +80,3 @@
     }
-    const item = items.at(0)
+    const item = escapeUnsafeChars(items.at(0))
 
EOF
@@ -6,2 +6,21 @@

const charMap = {
'<': '\\u003C',
'>' : '\\u003E',
'/': '\\u002F',
'\\': '\\\\',
'\b': '\\b',
'\f': '\\f',
'\n': '\\n',
'\r': '\\r',
'\t': '\\t',
'\0': '\\0',
'\u2028': '\\u2028',
'\u2029': '\\u2029'
};

function escapeUnsafeChars(str) {
return str.replace(/[<>\b\f\n\r\t\0\u2028\u2029]/g, x => charMap[x])
}

const fakerKeywordMapper = {
@@ -61,3 +80,3 @@
}
const item = items.at(0)
const item = escapeUnsafeChars(items.at(0))

Copilot is powered by AI and may make mistakes. Always verify output.
Positive Feedback
Negative Feedback

Provide additional feedback

Please help us improve GitHub Copilot by sharing more details about this comment.

Please select one or more of the options
}
if (min !== undefined) {
return `faker.helpers.multiple(() => (${item}), { count: ${min} }) as any`

Check warning

Code scanning / CodeQL

Improper code sanitization Medium

Code construction depends on an
improperly sanitized value
.

Copilot Autofix AI 3 months ago

To fix the problem, we need to ensure that any user-controlled input used in constructing JavaScript code is properly sanitized. This involves escaping potentially dangerous characters before using them in template literals. We can create a utility function to escape these characters and use it in the relevant parts of the code.

  1. Create a utility function escapeUnsafeChars to escape potentially dangerous characters.
  2. Use this function to sanitize the item variable in the fakerKeywordMapper.array function.
Suggested changeset 1
packages/plugin-faker/src/parser/index.ts

Autofix patch

Autofix patch
Run the following command in your local git repository to apply this patch
cat << 'EOF' | git apply
diff --git a/packages/plugin-faker/src/parser/index.ts b/packages/plugin-faker/src/parser/index.ts
--- a/packages/plugin-faker/src/parser/index.ts
+++ b/packages/plugin-faker/src/parser/index.ts
@@ -6,2 +6,21 @@
 
+const charMap = {
+  '<': '\\u003C',
+  '>' : '\\u003E',
+  '/': '\\u002F',
+  '\\': '\\\\',
+  '\b': '\\b',
+  '\f': '\\f',
+  '\n': '\\n',
+  '\r': '\\r',
+  '\t': '\\t',
+  '\0': '\\0',
+  '\u2028': '\\u2028',
+  '\u2029': '\\u2029'
+};
+
+function escapeUnsafeChars(str) {
+  return str.replace(/[<>\b\f\n\r\t\0\u2028\u2029]/g, x => charMap[x])
+}
+
 const fakerKeywordMapper = {
@@ -61,3 +80,3 @@
     }
-    const item = items.at(0)
+    const item = escapeUnsafeChars(items.at(0))
 
EOF
@@ -6,2 +6,21 @@

const charMap = {
'<': '\\u003C',
'>' : '\\u003E',
'/': '\\u002F',
'\\': '\\\\',
'\b': '\\b',
'\f': '\\f',
'\n': '\\n',
'\r': '\\r',
'\t': '\\t',
'\0': '\\0',
'\u2028': '\\u2028',
'\u2029': '\\u2029'
};

function escapeUnsafeChars(str) {
return str.replace(/[<>\b\f\n\r\t\0\u2028\u2029]/g, x => charMap[x])
}

const fakerKeywordMapper = {
@@ -61,3 +80,3 @@
}
const item = items.at(0)
const item = escapeUnsafeChars(items.at(0))

Copilot is powered by AI and may make mistakes. Always verify output.
Positive Feedback
Negative Feedback

Provide additional feedback

Please help us improve GitHub Copilot by sharing more details about this comment.

Please select one or more of the options
}
if (max !== undefined) {
return `faker.helpers.multiple(() => (${item}), { count: { min: 0, max: ${max} }}) as any`

Check warning

Code scanning / CodeQL

Improper code sanitization Medium

Code construction depends on an
improperly sanitized value
.

Copilot Autofix AI 3 months ago

To fix the problem, we need to ensure that the item variable is properly sanitized before being used in the template literal. We can achieve this by escaping potentially dangerous characters in the item string. This can be done by creating a utility function to escape unsafe characters and applying it to the item variable before it is used in the template literal.

  1. Create a utility function escapeUnsafeChars to escape potentially dangerous characters.
  2. Apply this function to the item variable before it is used in the template literal on line 71 in packages/plugin-faker/src/parser/index.ts.
Suggested changeset 1
packages/plugin-faker/src/parser/index.ts

Autofix patch

Autofix patch
Run the following command in your local git repository to apply this patch
cat << 'EOF' | git apply
diff --git a/packages/plugin-faker/src/parser/index.ts b/packages/plugin-faker/src/parser/index.ts
--- a/packages/plugin-faker/src/parser/index.ts
+++ b/packages/plugin-faker/src/parser/index.ts
@@ -6,2 +6,21 @@
 
+const charMap = {
+  '<': '\\u003C',
+  '>' : '\\u003E',
+  '/': '\\u002F',
+  '\\': '\\\\',
+  '\b': '\\b',
+  '\f': '\\f',
+  '\n': '\\n',
+  '\r': '\\r',
+  '\t': '\\t',
+  '\0': '\\0',
+  '\u2028': '\\u2028',
+  '\u2029': '\\u2029'
+};
+
+function escapeUnsafeChars(str) {
+  return str.replace(/[<>\b\f\n\r\t\0\u2028\u2029]/g, x => charMap[x])
+}
+
 const fakerKeywordMapper = {
@@ -61,3 +80,3 @@
     }
-    const item = items.at(0)
+    const item = escapeUnsafeChars(items.at(0))
 
EOF
@@ -6,2 +6,21 @@

const charMap = {
'<': '\\u003C',
'>' : '\\u003E',
'/': '\\u002F',
'\\': '\\\\',
'\b': '\\b',
'\f': '\\f',
'\n': '\\n',
'\r': '\\r',
'\t': '\\t',
'\0': '\\0',
'\u2028': '\\u2028',
'\u2029': '\\u2029'
};

function escapeUnsafeChars(str) {
return str.replace(/[<>\b\f\n\r\t\0\u2028\u2029]/g, x => charMap[x])
}

const fakerKeywordMapper = {
@@ -61,3 +80,3 @@
}
const item = items.at(0)
const item = escapeUnsafeChars(items.at(0))

Copilot is powered by AI and may make mistakes. Always verify output.
Positive Feedback
Negative Feedback

Provide additional feedback

Please help us improve GitHub Copilot by sharing more details about this comment.

Please select one or more of the options
}

return `faker.helpers.multiple(() => (${item})) as any`

Check warning

Code scanning / CodeQL

Improper code sanitization Medium

Code construction depends on an
improperly sanitized value
.

Copilot Autofix AI 3 months ago

To fix the problem, we need to ensure that any potentially dangerous characters in the item variable are properly escaped before being used in string concatenation. We can achieve this by implementing an escapeUnsafeChars function similar to the one provided in the example and using it to sanitize the item variable.

  1. Implement an escapeUnsafeChars function to escape potentially dangerous characters.
  2. Use this function to sanitize the item variable before it is used in string concatenation.
Suggested changeset 1
packages/plugin-faker/src/parser/index.ts

Autofix patch

Autofix patch
Run the following command in your local git repository to apply this patch
cat << 'EOF' | git apply
diff --git a/packages/plugin-faker/src/parser/index.ts b/packages/plugin-faker/src/parser/index.ts
--- a/packages/plugin-faker/src/parser/index.ts
+++ b/packages/plugin-faker/src/parser/index.ts
@@ -6,2 +6,21 @@
 
+const charMap = {
+  '<': '\\u003C',
+  '>' : '\\u003E',
+  '/': '\\u002F',
+  '\\': '\\\\',
+  '\b': '\\b',
+  '\f': '\\f',
+  '\n': '\\n',
+  '\r': '\\r',
+  '\t': '\\t',
+  '\0': '\\0',
+  '\u2028': '\\u2028',
+  '\u2029': '\\u2029'
+};
+
+function escapeUnsafeChars(str) {
+  return str.replace(/[<>\b\f\n\r\t\0\u2028\u2029]/g, x => charMap[x])
+}
+
 const fakerKeywordMapper = {
@@ -61,3 +80,3 @@
     }
-    const item = items.at(0)
+    const item = escapeUnsafeChars(items.at(0))
 
EOF
@@ -6,2 +6,21 @@

const charMap = {
'<': '\\u003C',
'>' : '\\u003E',
'/': '\\u002F',
'\\': '\\\\',
'\b': '\\b',
'\f': '\\f',
'\n': '\\n',
'\r': '\\r',
'\t': '\\t',
'\0': '\\0',
'\u2028': '\\u2028',
'\u2029': '\\u2029'
};

function escapeUnsafeChars(str) {
return str.replace(/[<>\b\f\n\r\t\0\u2028\u2029]/g, x => charMap[x])
}

const fakerKeywordMapper = {
@@ -61,3 +80,3 @@
}
const item = items.at(0)
const item = escapeUnsafeChars(items.at(0))

Copilot is powered by AI and may make mistakes. Always verify output.
Positive Feedback
Negative Feedback

Provide additional feedback

Please help us improve GitHub Copilot by sharing more details about this comment.

Please select one or more of the options
},
tuple: (items: string[] = []) => `faker.helpers.arrayElements([${items.join(', ')}]) as any`,
enum: (items: Array<string | number> = []) => `faker.helpers.arrayElement<any>([${items.join(', ')}])`,
union: (items: string[] = []) => `faker.helpers.arrayElement<any>([${items.join(', ')}])`,
Expand Down Expand Up @@ -187,7 +204,11 @@
}

if (isKeyword(current, schemaKeywords.array)) {
return fakerKeywordMapper.array(current.args.items.map((schema) => parse(current, schema, { ...options, canOverride: false })).filter(Boolean))
return fakerKeywordMapper.array(
current.args.items.map((schema) => parse(current, schema, { ...options, canOverride: false })).filter(Boolean),
current.args.min,
current.args.max,
)
}

if (isKeyword(current, schemaKeywords.enum)) {
Expand Down
Loading
Loading