diff --git a/docs/en/DEVELOPMENT.md b/docs/en/DEVELOPMENT.md index 9f1da42..33fe61c 100644 --- a/docs/en/DEVELOPMENT.md +++ b/docs/en/DEVELOPMENT.md @@ -61,9 +61,9 @@ Not implemented yet: registration and login (their contract is declared; the ope ## Install and work loop -The frontend uses TypeScript 7.0.2 (`tsc`) for type checking. The `@typescript/native` npm alias points to that compiler, while `typescript` points to the compatible `@typescript/typescript6` API for ESLint. This follows [Microsoft's side-by-side setup](https://devblogs.microsoft.com/typescript/announcing-typescript-7-0/#running-side-by-side-with-typescript-6.0): current typescript-eslint does not support the TS7 API yet. Type checking covers source files, Vite configuration, and `codegen/orval.config.ts`. +The frontend uses TypeScript 7.0.2 (`tsc`) for type checking. The `@typescript/native` npm alias points to that compiler, while `typescript` points to the compatible `@typescript/typescript6` API for ESLint. This follows [Microsoft's side-by-side setup](https://devblogs.microsoft.com/typescript/announcing-typescript-7-0/#running-side-by-side-with-typescript-6.0): current typescript-eslint does not support the TS7 API yet. Type checking covers source files, Vite configuration, and the TypeScript files in `codegen/`. -Orval writes directly to `frontend/src/shared/api/endpoints/` and `schemas/`, without an extra `generated/` directory. The adjacent `client.ts` and root `shared/api/index.ts` are handwritten. A Node test exercises the generated MSW handler together with the generated client. Vitest still reports a peer warning expecting MSW 2; the current Node path is tested with MSW 3, and browser mode is not used. +Orval writes directly to `frontend/src/shared/api/endpoints/` and `schemas/`, without an extra `generated/` directory. The adjacent `client.ts` and root `shared/api/index.ts` are handwritten. A Node test exercises the generated MSW handler together with the generated client. After Orval, the `frontend/codegen/mock-patterns.ts` step replaces `faker.helpers.fromRegExp` in the MSW mocks with `fakeFromPattern` and the length bounds from the contract, and `mock-validity.test.ts` checks every response mock with its Zod schema; see [frontend/README.en.md](../../frontend/README.en.md#api-client-generation). Vitest still reports a peer warning expecting MSW 2; the current Node path is tested with MSW 3, and browser mode is not used. Ignore rules belong to each component's `.gitignore`; root rules cover only root files. CI installs pnpm from frontend/package.json's `packageManager` declaration and does not require bundled Corepack. To check ML locally with a different global uv version, pass `UV='uv tool run --from uv==0.12.22 uv'` to Make. diff --git a/docs/ru/DEVELOPMENT.md b/docs/ru/DEVELOPMENT.md index 3123deb..5ecd83e 100644 --- a/docs/ru/DEVELOPMENT.md +++ b/docs/ru/DEVELOPMENT.md @@ -61,9 +61,9 @@ Frontend зависимости выбираются из актуальных s ## Установка и цикл работы -Frontend проверяется компилятором TypeScript 7.0.2 (`tsc`). Пакет `@typescript/native` ссылается на него через npm alias, а `typescript` ссылается на совместимый API `@typescript/typescript6` для ESLint. Это [рекомендованная Microsoft схема совместного использования](https://devblogs.microsoft.com/typescript/announcing-typescript-7-0/#running-side-by-side-with-typescript-6.0): текущий typescript-eslint еще не работает с API TS7. В проверку типов входят исходники, Vite config и `codegen/orval.config.ts`. +Frontend проверяется компилятором TypeScript 7.0.2 (`tsc`). Пакет `@typescript/native` ссылается на него через npm alias, а `typescript` ссылается на совместимый API `@typescript/typescript6` для ESLint. Это [рекомендованная Microsoft схема совместного использования](https://devblogs.microsoft.com/typescript/announcing-typescript-7-0/#running-side-by-side-with-typescript-6.0): текущий typescript-eslint еще не работает с API TS7. В проверку типов входят исходники, Vite config и TypeScript-файлы `codegen/`. -Orval создает `frontend/src/shared/api/endpoints/` и `schemas/` без дополнительного каталога `generated/`. `client.ts` и корневой `index.ts` в `shared/api/` поддерживаются вручную. Generated MSW handler проверяется вместе с generated client в Node-тесте. Vitest пока сообщает peer warning об ожидаемом MSW 2; текущий Node-путь проверен с MSW 3, browser mode не используется. +Orval создает `frontend/src/shared/api/endpoints/` и `schemas/` без дополнительного каталога `generated/`. `client.ts` и корневой `index.ts` в `shared/api/` поддерживаются вручную. Generated MSW handler проверяется вместе с generated client в Node-тесте. После Orval шаг `frontend/codegen/mock-patterns.ts` заменяет в MSW-моках `faker.helpers.fromRegExp` на `fakeFromPattern` с границами длины из контракта, а `mock-validity.test.ts` проверяет каждый мок ответа его Zod-схемой; подробнее в [frontend/README.md](../../frontend/README.md#генерация-api-клиента). Vitest пока сообщает peer warning об ожидаемом MSW 2; текущий Node-путь проверен с MSW 3, browser mode не используется. Игноры находятся в `.gitignore` соответствующего компонента. Корневой файл содержит только правила для файлов самого корня. В CI pnpm устанавливается по `packageManager` из frontend/package.json; встроенный Corepack не требуется. Для локальной проверки ML с другой глобальной версией uv можно передать `UV='uv tool run --from uv==0.12.22 uv'` в Make. diff --git a/frontend/README.en.md b/frontend/README.en.md index 776048e..bb1ee33 100644 --- a/frontend/README.en.md +++ b/frontend/README.en.md @@ -9,7 +9,7 @@ A React and TypeScript SPA built with Vite and organized using FSD. The interfac - `src/widgets/` holds shells: `public-shell`, `candidate-shell`, `employer-shell`, plus the technical `system-status` widget. - `src/features/` and `src/entities/` are still empty. - `src/shared/ui/` holds design tokens, fonts, logos, and primitives; `src/shared/config/` holds route paths; `src/shared/api/` holds the API client with generated endpoints, Zod schemas, and MSW mocks. -- `codegen/orval.config.ts` configures generation from the shared OpenAPI contract. +- `codegen/orval.config.ts` configures generation from the shared OpenAPI contract; `codegen/mock-patterns.ts` is the step after Orval that fixes MSW mocks of strings with a `pattern` (see [API client generation](#api-client-generation)). - `scripts/` checks FSD boundaries and Orval compatibility with the OpenAPI 3.2 fixture. - `e2e/` holds Playwright specs and `playwright.config.ts` configures them; they run only against a Compose stack. @@ -35,6 +35,14 @@ Generated Orval hooks call the shared same-origin `apiRequest` client, so the `Q - `staleTime` of 30 s; window focus does not refetch, and screens that need fresh data opt in per query; - mutations do not retry until the API supports `Idempotency-Key`. +## API client generation + +`make -C frontend generate` runs Orval with `codegen/orval.config.ts` and then `codegen/mock-patterns.ts`. For a string with a `pattern`, Orval 8.40 writes `faker.helpers.fromRegExp(pattern)` into the MSW mock: faker prints the `^` and `$` anchors and `(?:...)` groups as plain text, and Orval ignores `minLength` and `maxLength` when a `pattern` is present. The second step replaces such calls with `fakeFromPattern(pattern, {minLength, maxLength})` from `src/shared/api/mock-pattern.ts`. It takes the length bounds from the OpenAPI contract by the name of the property that holds the call and by the pattern. The step fails when a call has an unexpected form, when the contract has no such property with that pattern, or when the matching schemas disagree on the length bounds. It leaves its own output unchanged, so generation is reproducible and `make check-generated` stays stable. Enums in the mocks are written as literals (`enumGenerationType: "union"`): `Object.values` of a `zod.enum` returns Zod internals, not the values. + +`fakeFromPattern` parses a regular expression subset (characters, escapes, classes, groups, alternatives, quantifiers, and `^` and `$` at the ends), picks a length within the pattern and the bounds, and builds the string with the faker generator, so the same seed gives the same data. Every value is checked with `new RegExp(pattern, "u")` and the length bounds; a pattern outside the subset (for example, a lookahead or a back reference) or unreachable bounds throw an error. + +`src/shared/api/mock-validity.test.ts` calls every `get*ResponseMock` factory in `endpoints/*/*.msw.ts` with 25 faker seeds and checks the result with the generated Zod response schema. Orval's Zod schemas do not check `uniqueItems`, so the test does not cover that constraint; the response arrays with `uniqueItems` currently hold enum values, and the mock picks them with `faker.helpers.arrayElements` without repeats. + ## Tokens and theme Tokens live in `shared/ui/theme/tokens.css`: palette, semantic colors, type scale, spacing in 4px steps, radii, lines, focus ring, content widths, and motion. Breakpoints are fixed in media queries: 360px minimum, 768px tablet (`48rem`), 1024px desktop navigation (`64rem`), and 1280px verified wide layout. diff --git a/frontend/README.md b/frontend/README.md index 7020b67..aa79ff3 100644 --- a/frontend/README.md +++ b/frontend/README.md @@ -9,7 +9,7 @@ SPA на React и TypeScript со сборкой Vite и структурой FS - `src/widgets/` - оболочки: `public-shell`, `candidate-shell`, `employer-shell`, а также технический виджет `system-status`. - `src/features/` и `src/entities/` пока пусты. - `src/shared/ui/` - токены дизайна, шрифты, логотипы и примитивы; `src/shared/config/` - пути маршрутов; `src/shared/api/` - API-клиент со сгенерированными endpoints, схемами Zod и MSW-моками. -- `codegen/orval.config.ts` - генерация из общего OpenAPI-контракта. +- `codegen/orval.config.ts` - генерация из общего OpenAPI-контракта; `codegen/mock-patterns.ts` - шаг после Orval, который исправляет MSW-моки строк с `pattern` (см. [генерацию API-клиента](#генерация-api-клиента)). - `scripts/` - проверки границ FSD и совместимости Orval с фикстурой OpenAPI 3.2. - `e2e/` - спецификации Playwright, их настройки в `playwright.config.ts`; запускаются только на Compose-стеке. @@ -35,6 +35,14 @@ SPA на React и TypeScript со сборкой Vite и структурой FS - `staleTime` 30 с; фокус окна не перезапрашивает данные, экраны со свежими данными включают это для своего запроса; - мутации не повторяются, пока API не поддерживает `Idempotency-Key`. +## Генерация API-клиента + +`make -C frontend generate` запускает Orval с `codegen/orval.config.ts`, а затем `codegen/mock-patterns.ts`. Для строки с `pattern` Orval 8.40 пишет в MSW-мок `faker.helpers.fromRegExp(pattern)`: faker выводит якоря `^`, `$` и группы `(?:...)` как обычный текст, а `minLength` и `maxLength` при `pattern` Orval не учитывает. Второй шаг заменяет такие вызовы на `fakeFromPattern(pattern, {minLength, maxLength})` из `src/shared/api/mock-pattern.ts`. Границы длины он берет из OpenAPI-контракта по имени свойства, которое содержит вызов, и шаблону. Шаг завершается ошибкой, если вызов имеет неожиданный вид, в контракте нет такого свойства с этим шаблоном или схемы с ними расходятся в границах длины. На своем результате шаг ничего не меняет, поэтому генерация воспроизводима и `make check-generated` стабилен. Перечисления в моках записаны литералами (`enumGenerationType: "union"`): `Object.values` от `zod.enum` возвращает внутренние поля Zod, а не значения. + +`fakeFromPattern` разбирает подмножество регулярных выражений (символы, экранирование, классы, группы, альтернативы, квантификаторы, `^` и `$` по краям), выбирает длину в пределах шаблона и границ и строит строку генератором faker, поэтому одинаковый seed дает одинаковые данные. Каждое значение проверяется через `new RegExp(pattern, "u")` и границы длины; шаблон вне подмножества (например, lookahead или обратная ссылка) или недостижимые границы вызывают исключение. + +`src/shared/api/mock-validity.test.ts` вызывает каждую фабрику `get*ResponseMock` из `endpoints/*/*.msw.ts` с 25 значениями seed и проверяет результат сгенерированной Zod-схемой ответа. Zod-схемы Orval не проверяют `uniqueItems`, поэтому тест эту границу не покрывает; массивы с `uniqueItems` в ответах сейчас состоят из значений перечислений, и мок выбирает их через `faker.helpers.arrayElements` без повторов. + ## Токены и тема Токены лежат в `shared/ui/theme/tokens.css`: палитра, семантические цвета, шкала шрифтов, отступы с шагом 4px, радиусы, линии, кольцо фокуса, ширины контента и анимация. Точки перелома зафиксированы в media-запросах: минимум 360px, планшет 768px (`48rem`), навигация для компьютера 1024px (`64rem`) и проверенная широкая ширина 1280px. diff --git a/frontend/codegen/mock-patterns.test.ts b/frontend/codegen/mock-patterns.test.ts new file mode 100644 index 0000000..a6150de --- /dev/null +++ b/frontend/codegen/mock-patterns.test.ts @@ -0,0 +1,201 @@ +import { readdirSync, readFileSync } from "node:fs"; +import { dirname, join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { describe, expect, it } from "vitest"; +import { parse as parseYaml } from "yaml"; +import { + buildPatternBoundsIndex, + moduleSpecifier, + rewriteMockSource, + type PatternBoundsIndex, +} from "./mock-patterns"; + +const frontendRoot = resolve(dirname(fileURLToPath(import.meta.url)), ".."); + +const document = { + components: { + schemas: { + Token: { type: "string", minLength: 32, maxLength: 128, pattern: "^[A-Za-z0-9_-]+$" }, + Tag: { type: "string", minLength: 1, maxLength: 50, pattern: "^\\S(?:.*\\S)?$" }, + Session: { + type: "object", + properties: { + token: { $ref: "#/components/schemas/Token" }, + next_cursor: { + oneOf: [ + { type: "string", minLength: 1, maxLength: 512, pattern: "^[A-Za-z0-9_-]+$" }, + { type: "null" }, + ], + }, + tags: { type: "array", items: { $ref: "#/components/schemas/Tag" } }, + nested: { + type: "object", + properties: { code: { type: "string", pattern: "^[a-z]+$" } }, + }, + }, + examples: [{ properties: { ignored: { type: "string", pattern: "x" } } }], + }, + }, + }, +}; + +const header = `/** + * Generated by orval 🍺 + * Do not edit manually. + */ +import { + faker +} from '@faker-js/faker'; + +import { + HttpResponse +} from 'msw'; +`; + +const generated = `${header} +export const getSessionMock = (): Session => ({token: faker.helpers.fromRegExp("^[A-Za-z0-9_-]+$"), next_cursor: faker.helpers.arrayElement([faker.helpers.fromRegExp("^[A-Za-z0-9_-]+$"), null]), tags: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => (faker.helpers.fromRegExp("^\\\\S(?:.*\\\\S)?$"))), nested: {code: faker.helpers.fromRegExp("^[a-z]+$")}}) +`; + +const rewritten = `/** + * Generated by orval 🍺 + * Do not edit manually. + */ +import { + faker +} from '@faker-js/faker'; + +import { + fakeFromPattern +} from '../../mock-pattern'; + +import { + HttpResponse +} from 'msw'; + +export const getSessionMock = (): Session => ({token: fakeFromPattern("^[A-Za-z0-9_-]+$", {minLength: 32, maxLength: 128}), next_cursor: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9_-]+$", {minLength: 1, maxLength: 512}), null]), tags: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\\\S(?:.*\\\\S)?$", {minLength: 1, maxLength: 50}))), nested: {code: fakeFromPattern("^[a-z]+$")}}) +`; + +const index = buildPatternBoundsIndex(document); + +function rewrite(source: string, bounds: PatternBoundsIndex = index) { + return rewriteMockSource(source, "tag.msw.ts", bounds, "../../mock-pattern"); +} + +describe("buildPatternBoundsIndex", () => { + it("indexes patterned strings by the property that holds them", () => { + expect(index.get("token")?.get("^[A-Za-z0-9_-]+$")).toEqual([ + { minLength: 32, maxLength: 128 }, + ]); + expect(index.get("next_cursor")?.get("^[A-Za-z0-9_-]+$")).toEqual([ + { minLength: 1, maxLength: 512 }, + ]); + expect(index.get("tags")?.get("^\\S(?:.*\\S)?$")).toEqual([{ minLength: 1, maxLength: 50 }]); + expect(index.get("code")?.get("^[a-z]+$")).toEqual([{}]); + // A nested object property belongs to its own name, and examples hold + // data, not schemas. + expect(index.has("nested")).toBe(false); + expect(index.has("ignored")).toBe(false); + }); + + it("keeps every distinct bound of a property and pattern", () => { + const ambiguous = buildPatternBoundsIndex({ + components: { + schemas: { + A: { properties: { id: { type: "string", maxLength: 8, pattern: "^a+$" } } }, + B: { properties: { id: { type: "string", maxLength: 9, pattern: "^a+$" } } }, + C: { properties: { id: { type: "string", maxLength: 8, pattern: "^a+$" } } }, + }, + }, + }); + expect(ambiguous.get("id")?.get("^a+$")).toEqual([{ maxLength: 8 }, { maxLength: 9 }]); + }); + + it("rejects references outside the document", () => { + expect(() => + buildPatternBoundsIndex({ properties: { id: { $ref: "other.yml#/Id" } } }), + ).toThrow("Only local references are supported"); + }); +}); + +describe("rewriteMockSource", () => { + it("replaces each faker pattern call with the helper and the schema bounds", () => { + expect(rewrite(generated)).toEqual({ text: rewritten, rewrittenCalls: 4 }); + }); + + it("leaves its own output unchanged", () => { + expect(rewrite(rewritten)).toEqual({ text: rewritten, rewrittenCalls: 0 }); + }); + + it("leaves a file without pattern calls unchanged", () => { + const source = `${header}\nexport const getHealthMock = () => ({status: 'ok'})\n`; + expect(rewrite(source)).toEqual({ text: source, rewrittenCalls: 0 }); + }); + + it("fails when no schema property has the pattern", () => { + const source = `${header}\nexport const m = () => ({token: faker.helpers.fromRegExp("^b+$")})\n`; + expect(() => rewrite(source)).toThrow( + 'tag.msw.ts:13: no schema property "token" with pattern "^b+$"', + ); + }); + + it("fails when the schemas disagree on the bounds", () => { + const ambiguous = buildPatternBoundsIndex({ + components: { + schemas: { + A: { properties: { id: { type: "string", maxLength: 8, pattern: "^a+$" } } }, + B: { properties: { id: { type: "string", maxLength: 9, pattern: "^a+$" } } }, + }, + }, + }); + const source = `${header}\nexport const m = () => ({id: faker.helpers.fromRegExp("^a+$")})\n`; + expect(() => rewrite(source, ambiguous)).toThrow("so the mock bounds are ambiguous"); + }); + + it("fails on a call that it cannot attribute to a property", () => { + const topLevel = `${header}\nexport const m = (): string => faker.helpers.fromRegExp("^a+$")\n`; + expect(() => rewrite(topLevel)).toThrow("is not the value of a named property"); + + const dynamic = `${header}\nconst p = "^a+$";\nexport const m = () => ({id: faker.helpers.fromRegExp(p)})\n`; + expect(() => rewrite(dynamic)).toThrow("must take one string literal"); + }); +}); + +describe("moduleSpecifier", () => { + it("returns an extensionless relative specifier", () => { + expect( + moduleSpecifier( + "/repo/src/shared/api/endpoints/need/need.msw.ts", + "/repo/src/shared/api/mock-pattern.ts", + ), + ).toBe("../../mock-pattern"); + expect(moduleSpecifier("/repo/a/b.msw.ts", "/repo/a/mock-pattern.ts")).toBe("./mock-pattern"); + }); +}); + +describe("generated mocks", () => { + // The committed mocks must be a fixed point of the rewrite: generation + // followed by this step reproduces them byte for byte. + it("are already rewritten against the current contract", () => { + const contract: unknown = parseYaml( + readFileSync(join(frontendRoot, "../api/core/openapi.bundle.yml"), "utf8"), + ); + const contractIndex = buildPatternBoundsIndex(contract); + const endpoints = join(frontendRoot, "src/shared/api/endpoints"); + const files = readdirSync(endpoints, { recursive: true, encoding: "utf8" }).filter((name) => + name.endsWith(".msw.ts"), + ); + expect(files.length).toBeGreaterThan(0); + for (const name of files) { + const file = join(endpoints, name); + const source = readFileSync(file, "utf8"); + const result = rewriteMockSource( + source, + name, + contractIndex, + moduleSpecifier(file, join(frontendRoot, "src/shared/api/mock-pattern.ts")), + ); + expect(result.rewrittenCalls, name).toBe(0); + expect(result.text === source, name).toBe(true); + } + }); +}); diff --git a/frontend/codegen/mock-patterns.ts b/frontend/codegen/mock-patterns.ts new file mode 100644 index 0000000..8ee1979 --- /dev/null +++ b/frontend/codegen/mock-patterns.ts @@ -0,0 +1,374 @@ +// Post-generation step for the Orval MSW mocks. +// +// Orval 8.40 mocks a string schema that has a `pattern` with +// `faker.helpers.fromRegExp(pattern)`. faker prints anchors and non-capturing +// groups literally, and Orval drops minLength and maxLength for such a schema, +// so the mock fails the generated Zod schema. Orval has no option that keeps +// the Zod output and changes only this mock: its mock overrides match property +// names, not schema constraints, and an input transformer changes every +// output. +// +// This step rewrites each such call in the generated *.msw.ts files into +// `fakeFromPattern(pattern, { minLength, maxLength })` from +// src/shared/api/mock-pattern.ts. The bounds come from the OpenAPI document: +// the call's enclosing object property and the pattern identify the schema. +// The rewrite fails when a call has an unexpected form, when no schema +// matches, or when schemas that match disagree on the bounds, so a contract +// change cannot silently produce invalid mocks. Running it again on its own +// output changes nothing. +// +// Usage: node ./codegen/mock-patterns.ts --spec --endpoints [--helper ] + +import { readdirSync, readFileSync, writeFileSync } from "node:fs"; +import { dirname, join, relative, resolve, sep } from "node:path"; +import { argv, cwd, stdout } from "node:process"; +import { fileURLToPath } from "node:url"; +import ts from "typescript"; +import { parse as parseYaml } from "yaml"; + +export interface LengthBounds { + readonly minLength?: number; + readonly maxLength?: number; +} + +/** Property name, then pattern, then every distinct length bound found. */ +export type PatternBoundsIndex = ReadonlyMap>; + +export interface RewriteResult { + readonly text: string; + readonly rewrittenCalls: number; +} + +const helperName = "fakeFromPattern"; +const fakerModule = "@faker-js/faker"; +const fakerCallee = "faker.helpers.fromRegExp"; +// Keys whose values are sample data rather than schemas. +const exampleKeys = new Set(["example", "examples"]); + +function isRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +function boundsKey(bounds: LengthBounds): string { + return `${bounds.minLength ?? ""}..${bounds.maxLength ?? ""}`; +} + +function describeBounds(bounds: LengthBounds): string { + return `minLength ${bounds.minLength ?? "unset"}, maxLength ${bounds.maxLength ?? "unset"}`; +} + +function resolveLocalReference(document: unknown, reference: string): unknown { + if (!reference.startsWith("#/")) { + throw new Error(`Only local references are supported, got ${reference}.`); + } + let current: unknown = document; + for (const segment of reference.slice(2).split("/")) { + const key = segment.replaceAll("~1", "/").replaceAll("~0", "~"); + if (!isRecord(current) || !Object.hasOwn(current, key)) { + throw new Error(`Unresolvable reference ${reference}.`); + } + current = current[key]; + } + return current; +} + +function lengthBound(schema: Record, key: "minLength" | "maxLength") { + const value = schema[key]; + if (value === undefined) { + return undefined; + } + if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) { + throw new Error(`${key} must be a non-negative integer, got ${String(value)}.`); + } + return value; +} + +// Collects every patterned string schema that a property value can resolve +// to. It follows references, compositions, and array items, but not nested +// object properties, which have their own names. +function collectPatternedStrings( + document: unknown, + schema: unknown, + seenReferences: ReadonlySet, + found: Map, +): void { + if (!isRecord(schema)) { + return; + } + const reference = schema["$ref"]; + if (typeof reference === "string") { + if (!seenReferences.has(reference)) { + const target = resolveLocalReference(document, reference); + collectPatternedStrings(document, target, new Set([...seenReferences, reference]), found); + } + } + const pattern = schema["pattern"]; + if (typeof pattern === "string") { + const minLength = lengthBound(schema, "minLength"); + const maxLength = lengthBound(schema, "maxLength"); + const bounds: LengthBounds = { + ...(minLength === undefined ? {} : { minLength }), + ...(maxLength === undefined ? {} : { maxLength }), + }; + const known = found.get(pattern) ?? []; + if (!known.some((item) => boundsKey(item) === boundsKey(bounds))) { + known.push(bounds); + } + found.set(pattern, known); + } + for (const keyword of ["allOf", "oneOf", "anyOf", "prefixItems"]) { + const members = schema[keyword]; + if (Array.isArray(members)) { + for (const member of members) { + collectPatternedStrings(document, member, seenReferences, found); + } + } + } + collectPatternedStrings(document, schema["items"], seenReferences, found); +} + +/** Indexes the length bounds of patterned strings by property name. */ +export function buildPatternBoundsIndex(document: unknown): PatternBoundsIndex { + const index = new Map>(); + const visited = new Set(); + + function addProperty(name: string, schema: unknown): void { + const byPattern = index.get(name) ?? new Map(); + collectPatternedStrings(document, schema, new Set(), byPattern); + if (byPattern.size > 0) { + index.set(name, byPattern); + } + } + + function walk(node: unknown): void { + if (typeof node !== "object" || node === null || visited.has(node)) { + return; + } + visited.add(node); + if (Array.isArray(node)) { + node.forEach(walk); + return; + } + const properties = isRecord(node) ? node["properties"] : undefined; + if (isRecord(properties)) { + for (const [name, schema] of Object.entries(properties)) { + addProperty(name, schema); + } + } + for (const [key, value] of Object.entries(node)) { + if (!exampleKeys.has(key)) { + walk(value); + } + } + } + + walk(document); + return index; +} + +function lineOf(sourceFile: ts.SourceFile, node: ts.Node): number { + return sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line + 1; +} + +function enclosingPropertyName(node: ts.Node): string | undefined { + for (let current = node.parent; current !== undefined; current = current.parent) { + if (ts.isPropertyAssignment(current)) { + const name = current.name; + if (ts.isIdentifier(name) || ts.isStringLiteral(name) || ts.isNumericLiteral(name)) { + return name.text; + } + return undefined; + } + if (ts.isVariableStatement(current) || ts.isSourceFile(current)) { + return undefined; + } + } + return undefined; +} + +function formatBoundsArgument(bounds: LengthBounds): string { + const parts = [ + ...(bounds.minLength === undefined ? [] : [`minLength: ${bounds.minLength}`]), + ...(bounds.maxLength === undefined ? [] : [`maxLength: ${bounds.maxLength}`]), + ]; + return parts.length === 0 ? "" : `, {${parts.join(", ")}}`; +} + +function findBounds( + index: PatternBoundsIndex, + property: string, + pattern: string, + location: string, +): LengthBounds { + const candidates = index.get(property)?.get(pattern) ?? []; + const [bounds] = candidates; + if (bounds === undefined) { + throw new Error( + `${location}: no schema property "${property}" with pattern ${JSON.stringify(pattern)} in the OpenAPI document.`, + ); + } + if (candidates.length > 1) { + throw new Error( + `${location}: properties named "${property}" with pattern ${JSON.stringify(pattern)} have different length bounds (${candidates + .map(describeBounds) + .join("; ")}), so the mock bounds are ambiguous.`, + ); + } + return bounds; +} + +/** + * Rewrites the faker pattern calls of one generated mock file. The helper + * specifier is the module path that the generated file imports the helper + * from. + */ +export function rewriteMockSource( + source: string, + fileName: string, + index: PatternBoundsIndex, + helperSpecifier: string, +): RewriteResult { + const sourceFile = ts.createSourceFile( + fileName, + source, + ts.ScriptTarget.Latest, + true, + ts.ScriptKind.TS, + ); + const edits: { start: number; end: number; text: string }[] = []; + + function visit(node: ts.Node): void { + if ( + ts.isCallExpression(node) && + ts.isPropertyAccessExpression(node.expression) && + node.expression.name.text === "fromRegExp" + ) { + const location = `${fileName}:${lineOf(sourceFile, node)}`; + if (node.expression.getText(sourceFile) !== fakerCallee) { + throw new Error(`${location}: unexpected fromRegExp callee ${node.expression.getText()}.`); + } + const [argument, ...rest] = node.arguments; + if (argument === undefined || rest.length > 0 || !ts.isStringLiteral(argument)) { + throw new Error(`${location}: ${fakerCallee} must take one string literal.`); + } + const property = enclosingPropertyName(node); + if (property === undefined) { + throw new Error(`${location}: ${fakerCallee} is not the value of a named property.`); + } + const pattern = argument.text; + const bounds = findBounds(index, property, pattern, location); + edits.push({ + start: node.getStart(sourceFile), + end: node.getEnd(), + text: `${helperName}(${JSON.stringify(pattern)}${formatBoundsArgument(bounds)})`, + }); + return; + } + ts.forEachChild(node, visit); + } + visit(sourceFile); + + const imports = sourceFile.statements.filter(ts.isImportDeclaration); + const moduleOf = (declaration: ts.ImportDeclaration) => + ts.isStringLiteral(declaration.moduleSpecifier) ? declaration.moduleSpecifier.text : ""; + const hasHelperImport = imports.some((declaration) => moduleOf(declaration) === helperSpecifier); + if (edits.length > 0 && !hasHelperImport) { + const fakerImport = imports.find((declaration) => moduleOf(declaration) === fakerModule); + if (fakerImport === undefined) { + throw new Error(`${fileName}: no ${fakerModule} import to place the helper import after.`); + } + edits.push({ + start: fakerImport.getEnd(), + end: fakerImport.getEnd(), + text: `\n\nimport {\n ${helperName}\n} from '${helperSpecifier}';`, + }); + } + + let text = source; + for (const edit of edits.sort((left, right) => right.start - left.start)) { + text = text.slice(0, edit.start) + edit.text + text.slice(edit.end); + } + if (text.includes("fromRegExp")) { + throw new Error(`${fileName}: a fromRegExp reference remains after the rewrite.`); + } + const rewrittenCalls = edits.filter((edit) => edit.start !== edit.end).length; + return { text, rewrittenCalls }; +} + +function mockFiles(directory: string): string[] { + return readdirSync(directory, { recursive: true, encoding: "utf8" }) + .filter((name) => name.endsWith(".msw.ts")) + .map((name) => join(directory, name)) + .sort(); +} + +/** Returns the extensionless relative module specifier of `target`. */ +export function moduleSpecifier(fromFile: string, target: string): string { + const path = relative(dirname(fromFile), target).replace(/\.ts$/, "").split(sep).join("/"); + return path.startsWith(".") ? path : `./${path}`; +} + +export function rewriteMockFiles(options: { + readonly specPath: string; + readonly endpointsDirectory: string; + readonly helperPath: string; +}): { readonly files: number; readonly calls: number } { + const document: unknown = parseYaml(readFileSync(options.specPath, "utf8")); + const index = buildPatternBoundsIndex(document); + let files = 0; + let calls = 0; + for (const file of mockFiles(options.endpointsDirectory)) { + const source = readFileSync(file, "utf8"); + const result = rewriteMockSource( + source, + relative(cwd(), file), + index, + moduleSpecifier(file, options.helperPath), + ); + if (result.text !== source) { + writeFileSync(file, result.text); + files += 1; + } + calls += result.rewrittenCalls; + } + return { files, calls }; +} + +function readOption(args: readonly string[], name: string): string | undefined { + const position = args.indexOf(name); + if (position === -1) { + return undefined; + } + const value = args[position + 1]; + if (value === undefined || value.startsWith("--")) { + throw new Error(`${name} needs a value.`); + } + return value; +} + +function main(args: readonly string[]): void { + const frontendRoot = resolve(dirname(fileURLToPath(import.meta.url)), ".."); + const specPath = readOption(args, "--spec"); + const endpointsDirectory = readOption(args, "--endpoints"); + if (specPath === undefined || endpointsDirectory === undefined) { + throw new Error( + "Usage: mock-patterns.ts --spec --endpoints [--helper ]", + ); + } + const helperPath = resolve( + readOption(args, "--helper") ?? join(frontendRoot, "src/shared/api/mock-pattern.ts"), + ); + const result = rewriteMockFiles({ + specPath: resolve(specPath), + endpointsDirectory: resolve(endpointsDirectory), + helperPath, + }); + stdout.write( + `Mock patterns: rewrote ${result.calls} ${fakerCallee} calls in ${result.files} files.\n`, + ); +} + +const entryPoint = argv[1]; +if (entryPoint !== undefined && resolve(entryPoint) === fileURLToPath(import.meta.url)) { + main(argv.slice(2)); +} diff --git a/frontend/codegen/orval.config.ts b/frontend/codegen/orval.config.ts index 7909f2b..02e4373 100644 --- a/frontend/codegen/orval.config.ts +++ b/frontend/codegen/orval.config.ts @@ -85,6 +85,11 @@ function project(inputTarget: string, endpoints: string, schemas: string): Optio generators: [{ type: "msw" }], }, override: { + // With Zod schemas, the default enum mode makes the MSW mocks pick + // from `Object.values()`, which yields Zod internals rather + // than the enum values. The union mode inlines the literal values in + // the mocks; the Zod schemas and the types do not change. + enumGenerationType: "union", mutator: { path: "../src/shared/api/client.ts", name: "apiRequest", diff --git a/frontend/package.json b/frontend/package.json index 3f59923..b93357d 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -8,7 +8,7 @@ "dev": "vite", "build": "vite build", "preview": "vite preview", - "generate": "orval --config ./codegen/orval.config.ts", + "generate": "orval --config ./codegen/orval.config.ts && node ./codegen/mock-patterns.ts --spec ../api/core/openapi.bundle.yml --endpoints ./src/shared/api/endpoints", "fmt": "prettier --write .", "fmt:check": "prettier --check .", "lint": "pnpm run lint:eslint && pnpm run lint:css", @@ -48,6 +48,7 @@ "typescript": "npm:@typescript/typescript6@6.0.2", "typescript-eslint": "8.71.0", "vite": "8.3.2", - "vitest": "5.0.3" + "vitest": "5.0.3", + "yaml": "2.9.1" } } diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yaml index 1cb8cb9..095fb51 100644 --- a/frontend/pnpm-lock.yaml +++ b/frontend/pnpm-lock.yaml @@ -242,6 +242,9 @@ importers: vitest: specifier: 5.0.3 version: 5.0.3(@types/node@26.6.4)(msw@3.0.2(@types/node@26.6.4)(@typescript/typescript6@6.0.2)(supports-color@10.2.2)(vite@8.3.2(@types/node@26.6.4)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1)))(vite@8.3.2(@types/node@26.6.4)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1)) + yaml: + specifier: 2.9.1 + version: 2.9.1 packages: diff --git a/frontend/scripts/check-orval-compat.mjs b/frontend/scripts/check-orval-compat.mjs index 44fd642..a14eef1 100644 --- a/frontend/scripts/check-orval-compat.mjs +++ b/frontend/scripts/check-orval-compat.mjs @@ -1,16 +1,18 @@ // Generates the OpenAPI 3.2 compatibility fixture with the production Orval -// settings into a temporary directory, type-checks the output with the -// frontend compiler settings, and checks that the API conventions reached the -// generated code. The directory is removed afterwards. +// settings and the mock pattern post-step into a temporary directory, +// type-checks the output with the frontend compiler settings, and checks that +// the API conventions reached the generated code. The directory is removed +// afterwards. import assert from "node:assert/strict"; import { spawnSync } from "node:child_process"; import { mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { dirname, join, relative, resolve } from "node:path"; -import { env, stdout } from "node:process"; +import { env, execPath, stdout } from "node:process"; import { fileURLToPath } from "node:url"; const frontendRoot = resolve(dirname(fileURLToPath(import.meta.url)), ".."); const bin = (name) => resolve(frontendRoot, "node_modules/.bin", name); +const fixture = resolve(frontendRoot, "../api/testdata/openapi-3.2.0.yml"); // Text that each fixture convention leaves in the generated TypeScript. const expectedFragments = { @@ -22,6 +24,7 @@ const expectedFragments = { Timestamp: "export const Timestamp = zod.iso.datetime(", Problem: "export const Problem = zod.object(", ProblemErrorType: "TError = ErrorType", + PageCursorMock: 'fakeFromPattern("^[A-Za-z0-9_-]+$", {minLength: 1, maxLength: 512})', HeaderArgument: "headers: CreateProbeItemHeaders", OptionalHeaderArgument: "headers: UpdateProbeItemHeaders", }; @@ -50,6 +53,14 @@ try { run(bin("orval"), ["--config", "./codegen/orval.config.ts"], { ORVAL_COMPAT_OUTPUT: outputDirectory, }); + // The same post-step as `pnpm run generate`, see codegen/mock-patterns.ts. + run(execPath, [ + "./codegen/mock-patterns.ts", + "--spec", + fixture, + "--endpoints", + join(outputDirectory, "endpoints"), + ]); const files = typeScriptFiles(outputDirectory); assert.ok(files.length > 0, "Orval generated no files for the compatibility fixture."); @@ -66,6 +77,7 @@ try { for (const [component, fragment] of Object.entries(expectedFragments)) { assert.ok(generated.includes(fragment), `Generated code lacks ${component}: ${fragment}`); } + assert.ok(!generated.includes("fromRegExp"), "Generated mocks still call faker fromRegExp."); stdout.write(`Orval compatibility fixture: ${files.length} files type-checked.\n`); } finally { rmSync(outputDirectory, { recursive: true, force: true }); diff --git a/frontend/src/shared/api/endpoints/assessment/assessment.msw.ts b/frontend/src/shared/api/endpoints/assessment/assessment.msw.ts index d7de5a2..3a72e12 100644 --- a/frontend/src/shared/api/endpoints/assessment/assessment.msw.ts +++ b/frontend/src/shared/api/endpoints/assessment/assessment.msw.ts @@ -8,6 +8,10 @@ import { faker } from '@faker-js/faker'; +import { + fakeFromPattern +} from '../../mock-pattern'; + import { HttpResponse, http @@ -16,23 +20,6 @@ import type { RequestHandlerOptions } from 'msw'; -import { - AssessmentAttemptState, - AssessmentGradeAvailabilityStatus, - AssessmentLimitation, - AssessmentMode, - AssessmentNextAction, - AssessmentNotDeterminedReason, - AssessmentOutcome, - AssessmentStrength, - CalibrationStatus, - GradeCode, - PracticeFailureReason, - PracticeKind, - PracticeStatus, - SpecializationCode, - TaskLanguage -} from '../../schemas'; import type { AssessmentAttempt, AssessmentAvailability, @@ -52,101 +39,101 @@ import type { } from '../../schemas'; -export const getGetMyAssessmentAvailabilityResponseMock = (overrideResponse: Partial> = {}): AssessmentAvailability => ({specializations: Array.from({ length: faker.number.int({min: 1, max: 2}) }, (_, i) => i + 1).map(() => ({specialization: faker.helpers.arrayElement(Object.values(SpecializationCode)), confirmed_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(Object.values(GradeCode)),null,]), active_attempt_id: faker.helpers.arrayElement([faker.string.uuid(), null]), grades: Array.from({ length: faker.number.int({min: 1, max: 10}) }, (_, i) => i + 1).map(() => ({grade: faker.helpers.arrayElement(Object.values(GradeCode)), status: faker.helpers.arrayElement(Object.values(AssessmentGradeAvailabilityStatus)), mode: faker.helpers.arrayElement([faker.helpers.arrayElement(Object.values(AssessmentMode)),null,]), available_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), time_limit_seconds: faker.helpers.arrayElement([faker.number.int({min: 1}), null]), max_sessions: faker.helpers.arrayElement([faker.number.int({min: 1, max: 10}), null]), max_items: faker.helpers.arrayElement([faker.number.int({min: 1, max: 100}), null]), practice_required: faker.helpers.arrayElement([faker.datatype.boolean(), null])}))})), ...overrideResponse}) +export const getGetMyAssessmentAvailabilityResponseMock = (overrideResponse: Partial> = {}): AssessmentAvailability => ({specializations: Array.from({ length: faker.number.int({min: 1, max: 2}) }, (_, i) => i + 1).map(() => ({specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), confirmed_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), active_attempt_id: faker.helpers.arrayElement([faker.string.uuid(), null]), grades: Array.from({ length: faker.number.int({min: 1, max: 10}) }, (_, i) => i + 1).map(() => ({grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), status: faker.helpers.arrayElement(['available','active_attempt','cooldown','insufficient_bank'] as const), mode: faker.helpers.arrayElement([faker.helpers.arrayElement(['demo_basic','adaptive'] as const),null,]), available_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), time_limit_seconds: faker.helpers.arrayElement([faker.number.int({min: 1}), null]), max_sessions: faker.helpers.arrayElement([faker.number.int({min: 1, max: 10}), null]), max_items: faker.helpers.arrayElement([faker.number.int({min: 1, max: 100}), null]), practice_required: faker.helpers.arrayElement([faker.datatype.boolean(), null])}))})), ...overrideResponse}) export const getCreateMyAssessmentAttemptResponseAssessmentSessionsMock = (overrideResponse: Partial = {}): AssessmentSessions => ({...{used: faker.number.int({min: 1, max: 10}), max: faker.number.int({min: 1, max: 10}), idle_timeout_seconds: faker.number.int({min: 60, max: 86400})}, ...overrideResponse}); -export const getCreateMyAssessmentAttemptResponseChoiceItemContentMock = (overrideResponse: Partial = {}): ChoiceItemContent => ({...{format: faker.helpers.arrayElement(['choice'] as const), options: Array.from({ length: faker.number.int({min: 2, max: 10}) }, (_, i) => i + 1).map(() => ({id: faker.helpers.fromRegExp("^[A-Za-z0-9_-]+$"), text: faker.string.alpha({length: {min: 1, max: 2000}})})), multiple: faker.datatype.boolean()}, ...overrideResponse}); +export const getCreateMyAssessmentAttemptResponseChoiceItemContentMock = (overrideResponse: Partial = {}): ChoiceItemContent => ({...{format: faker.helpers.arrayElement(['choice'] as const), options: Array.from({ length: faker.number.int({min: 2, max: 10}) }, (_, i) => i + 1).map(() => ({id: fakeFromPattern("^[A-Za-z0-9_-]+$", {minLength: 1, maxLength: 32}), text: faker.string.alpha({length: {min: 1, max: 2000}})})), multiple: faker.datatype.boolean()}, ...overrideResponse}); export const getCreateMyAssessmentAttemptResponseNumberItemContentMock = (overrideResponse: Partial = {}): NumberItemContent => ({...{format: faker.helpers.arrayElement(['number'] as const), unit: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 32}}), null])}, ...overrideResponse}); export const getCreateMyAssessmentAttemptResponseStringItemContentMock = (overrideResponse: Partial = {}): StringItemContent => ({...{format: faker.helpers.arrayElement(['string'] as const), max_length: faker.number.int({min: 1, max: 500})}, ...overrideResponse}); -export const getCreateMyAssessmentAttemptResponseOrderItemContentMock = (overrideResponse: Partial = {}): OrderItemContent => ({...{format: faker.helpers.arrayElement(['order'] as const), elements: Array.from({ length: faker.number.int({min: 2, max: 20}) }, (_, i) => i + 1).map(() => ({id: faker.helpers.fromRegExp("^[A-Za-z0-9_-]+$"), text: faker.string.alpha({length: {min: 1, max: 2000}})}))}, ...overrideResponse}); +export const getCreateMyAssessmentAttemptResponseOrderItemContentMock = (overrideResponse: Partial = {}): OrderItemContent => ({...{format: faker.helpers.arrayElement(['order'] as const), elements: Array.from({ length: faker.number.int({min: 2, max: 20}) }, (_, i) => i + 1).map(() => ({id: fakeFromPattern("^[A-Za-z0-9_-]+$", {minLength: 1, maxLength: 32}), text: faker.string.alpha({length: {min: 1, max: 2000}})}))}, ...overrideResponse}); -export const getCreateMyAssessmentAttemptResponseFindErrorItemContentMock = (overrideResponse: Partial = {}): FindErrorItemContent => ({...{format: faker.helpers.arrayElement(['find_error'] as const), syntax: faker.helpers.arrayElement([faker.helpers.fromRegExp("^[a-z0-9_+-]+$"), null]), lines: Array.from({ length: faker.number.int({min: 1, max: 500}) }, (_, i) => i + 1).map(() => ({number: faker.number.int({min: 1, max: 500}), text: faker.string.alpha({length: {min: 10, max: 1000}})})), max_selections: faker.number.int({min: 1, max: 10})}, ...overrideResponse}); +export const getCreateMyAssessmentAttemptResponseFindErrorItemContentMock = (overrideResponse: Partial = {}): FindErrorItemContent => ({...{format: faker.helpers.arrayElement(['find_error'] as const), syntax: faker.helpers.arrayElement([fakeFromPattern("^[a-z0-9_+-]+$", {minLength: 1, maxLength: 32}), null]), lines: Array.from({ length: faker.number.int({min: 1, max: 500}) }, (_, i) => i + 1).map(() => ({number: faker.number.int({min: 1, max: 500}), text: faker.string.alpha({length: {min: 10, max: 1000}})})), max_selections: faker.number.int({min: 1, max: 10})}, ...overrideResponse}); -export const getCreateMyAssessmentAttemptResponseConfigurationItemContentMock = (overrideResponse: Partial = {}): ConfigurationItemContent => ({...{format: faker.helpers.arrayElement(['configuration'] as const), syntax: faker.helpers.fromRegExp("^[a-z0-9_+-]+$"), initial_config: faker.string.alpha({length: {min: 10, max: 20000}}), max_length: faker.number.int({min: 1, max: 20000})}, ...overrideResponse}); +export const getCreateMyAssessmentAttemptResponseConfigurationItemContentMock = (overrideResponse: Partial = {}): ConfigurationItemContent => ({...{format: faker.helpers.arrayElement(['configuration'] as const), syntax: fakeFromPattern("^[a-z0-9_+-]+$", {minLength: 1, maxLength: 32}), initial_config: faker.string.alpha({length: {min: 10, max: 20000}}), max_length: faker.number.int({min: 1, max: 20000})}, ...overrideResponse}); -export const getCreateMyAssessmentAttemptResponsePracticeItemContentMock = (overrideResponse: Partial = {}): PracticeItemContent => ({...{format: faker.helpers.arrayElement(['practice'] as const), languages: faker.helpers.arrayElements(Object.values(TaskLanguage)), public_examples: Array.from({ length: faker.number.int({min: 1, max: 10}) }, (_, i) => i + 1).map(() => ({input: faker.string.alpha({length: {min: 10, max: 10000}}), expected_output: faker.string.alpha({length: {min: 10, max: 10000}})})), max_source_length: faker.number.int({min: 1, max: 65536})}, ...overrideResponse}); +export const getCreateMyAssessmentAttemptResponsePracticeItemContentMock = (overrideResponse: Partial = {}): PracticeItemContent => ({...{format: faker.helpers.arrayElement(['practice'] as const), languages: faker.helpers.arrayElements(['python','go'] as const), public_examples: Array.from({ length: faker.number.int({min: 1, max: 10}) }, (_, i) => i + 1).map(() => ({input: faker.string.alpha({length: {min: 10, max: 10000}}), expected_output: faker.string.alpha({length: {min: 10, max: 10000}})})), max_source_length: faker.number.int({min: 1, max: 65536})}, ...overrideResponse}); export const getCreateMyAssessmentAttemptResponseAssessmentItemMock = (overrideResponse: Partial = {}): AssessmentItem => ({...{id: faker.string.uuid(), sequence: faker.number.int({min: 1, max: 100}), prompt: faker.string.alpha({length: {min: 1, max: 20000}}), content: faker.helpers.arrayElement([{...getCreateMyAssessmentAttemptResponseChoiceItemContentMock()},{...getCreateMyAssessmentAttemptResponseNumberItemContentMock()},{...getCreateMyAssessmentAttemptResponseStringItemContentMock()},{...getCreateMyAssessmentAttemptResponseOrderItemContentMock()},{...getCreateMyAssessmentAttemptResponseFindErrorItemContentMock()},{...getCreateMyAssessmentAttemptResponseConfigurationItemContentMock()},{...getCreateMyAssessmentAttemptResponsePracticeItemContentMock()},])}, ...overrideResponse}); export const getCreateMyAssessmentAttemptResponsePracticeVerdictMock = (overrideResponse: Partial = {}): PracticeVerdict => ({...{score: faker.number.int({min: 0, max: 3}), max_score: faker.number.int({min: 3, max: 3}), groups: Array.from({ length: faker.number.int({min: 3, max: 3}) }, (_, i) => i + 1).map(() => ({group: faker.number.int({min: 1, max: 3}), passed: faker.datatype.boolean()}))}, ...overrideResponse}); -export const getCreateMyAssessmentAttemptResponseMock = (overrideResponse: Partial> = {}): AssessmentAttempt => ({id: faker.string.uuid(), version: faker.number.int({min: 1}), specialization: faker.helpers.arrayElement(Object.values(SpecializationCode)), target_grade: faker.helpers.arrayElement(Object.values(GradeCode)), task_language: faker.helpers.arrayElement([faker.helpers.arrayElement(Object.values(TaskLanguage)),null,]), mode: faker.helpers.arrayElement(Object.values(AssessmentMode)), state: faker.helpers.arrayElement(Object.values(AssessmentAttemptState)), versions: {policy_version: faker.number.int({min: 1}), bank_version: faker.helpers.fromRegExp("^[A-Za-z0-9._-]+$"), algorithm_version: faker.helpers.fromRegExp("^[A-Za-z0-9._-]+$")}, started_at: faker.date.past().toISOString().slice(0, 19) + 'Z', expires_at: faker.date.past().toISOString().slice(0, 19) + 'Z', sessions: faker.helpers.arrayElement([{...getCreateMyAssessmentAttemptResponseAssessmentSessionsMock()},null,]), finished_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), progress: {answered_items: faker.number.int({min: 0, max: 100}), max_items: faker.number.int({min: 1, max: 100})}, current_item: faker.helpers.arrayElement([{...getCreateMyAssessmentAttemptResponseAssessmentItemMock()},null,]), practices: Array.from({ length: faker.number.int({min: 1, max: 5}) }, (_, i) => i + 1).map(() => ({kind: faker.helpers.arrayElement(Object.values(PracticeKind)), item_id: faker.string.uuid(), status: faker.helpers.arrayElement(Object.values(PracticeStatus)), submitted_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), verdict: faker.helpers.arrayElement([{...getCreateMyAssessmentAttemptResponsePracticeVerdictMock()},null,]), failure_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(Object.values(PracticeFailureReason)),null,])})), ...overrideResponse}) +export const getCreateMyAssessmentAttemptResponseMock = (overrideResponse: Partial> = {}): AssessmentAttempt => ({id: faker.string.uuid(), version: faker.number.int({min: 1}), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), target_grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), task_language: faker.helpers.arrayElement([faker.helpers.arrayElement(['python','go'] as const),null,]), mode: faker.helpers.arrayElement(['demo_basic','adaptive'] as const), state: faker.helpers.arrayElement(['in_progress','practice_pending','additional_practice_pending','ready_to_finalize','completed','expired','insufficient_bank'] as const), versions: {policy_version: faker.number.int({min: 1}), bank_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}), algorithm_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64})}, started_at: faker.date.past().toISOString().slice(0, 19) + 'Z', expires_at: faker.date.past().toISOString().slice(0, 19) + 'Z', sessions: faker.helpers.arrayElement([{...getCreateMyAssessmentAttemptResponseAssessmentSessionsMock()},null,]), finished_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), progress: {answered_items: faker.number.int({min: 0, max: 100}), max_items: faker.number.int({min: 1, max: 100})}, current_item: faker.helpers.arrayElement([{...getCreateMyAssessmentAttemptResponseAssessmentItemMock()},null,]), practices: Array.from({ length: faker.number.int({min: 1, max: 5}) }, (_, i) => i + 1).map(() => ({kind: faker.helpers.arrayElement(['main','additional'] as const), item_id: faker.string.uuid(), status: faker.helpers.arrayElement(['not_started','pending','finished','failed'] as const), submitted_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), verdict: faker.helpers.arrayElement([{...getCreateMyAssessmentAttemptResponsePracticeVerdictMock()},null,]), failure_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['sandbox_busy','sandbox_error'] as const),null,])})), ...overrideResponse}) export const getGetMyAssessmentAttemptResponseAssessmentSessionsMock = (overrideResponse: Partial = {}): AssessmentSessions => ({...{used: faker.number.int({min: 1, max: 10}), max: faker.number.int({min: 1, max: 10}), idle_timeout_seconds: faker.number.int({min: 60, max: 86400})}, ...overrideResponse}); -export const getGetMyAssessmentAttemptResponseChoiceItemContentMock = (overrideResponse: Partial = {}): ChoiceItemContent => ({...{format: faker.helpers.arrayElement(['choice'] as const), options: Array.from({ length: faker.number.int({min: 2, max: 10}) }, (_, i) => i + 1).map(() => ({id: faker.helpers.fromRegExp("^[A-Za-z0-9_-]+$"), text: faker.string.alpha({length: {min: 1, max: 2000}})})), multiple: faker.datatype.boolean()}, ...overrideResponse}); +export const getGetMyAssessmentAttemptResponseChoiceItemContentMock = (overrideResponse: Partial = {}): ChoiceItemContent => ({...{format: faker.helpers.arrayElement(['choice'] as const), options: Array.from({ length: faker.number.int({min: 2, max: 10}) }, (_, i) => i + 1).map(() => ({id: fakeFromPattern("^[A-Za-z0-9_-]+$", {minLength: 1, maxLength: 32}), text: faker.string.alpha({length: {min: 1, max: 2000}})})), multiple: faker.datatype.boolean()}, ...overrideResponse}); export const getGetMyAssessmentAttemptResponseNumberItemContentMock = (overrideResponse: Partial = {}): NumberItemContent => ({...{format: faker.helpers.arrayElement(['number'] as const), unit: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 32}}), null])}, ...overrideResponse}); export const getGetMyAssessmentAttemptResponseStringItemContentMock = (overrideResponse: Partial = {}): StringItemContent => ({...{format: faker.helpers.arrayElement(['string'] as const), max_length: faker.number.int({min: 1, max: 500})}, ...overrideResponse}); -export const getGetMyAssessmentAttemptResponseOrderItemContentMock = (overrideResponse: Partial = {}): OrderItemContent => ({...{format: faker.helpers.arrayElement(['order'] as const), elements: Array.from({ length: faker.number.int({min: 2, max: 20}) }, (_, i) => i + 1).map(() => ({id: faker.helpers.fromRegExp("^[A-Za-z0-9_-]+$"), text: faker.string.alpha({length: {min: 1, max: 2000}})}))}, ...overrideResponse}); +export const getGetMyAssessmentAttemptResponseOrderItemContentMock = (overrideResponse: Partial = {}): OrderItemContent => ({...{format: faker.helpers.arrayElement(['order'] as const), elements: Array.from({ length: faker.number.int({min: 2, max: 20}) }, (_, i) => i + 1).map(() => ({id: fakeFromPattern("^[A-Za-z0-9_-]+$", {minLength: 1, maxLength: 32}), text: faker.string.alpha({length: {min: 1, max: 2000}})}))}, ...overrideResponse}); -export const getGetMyAssessmentAttemptResponseFindErrorItemContentMock = (overrideResponse: Partial = {}): FindErrorItemContent => ({...{format: faker.helpers.arrayElement(['find_error'] as const), syntax: faker.helpers.arrayElement([faker.helpers.fromRegExp("^[a-z0-9_+-]+$"), null]), lines: Array.from({ length: faker.number.int({min: 1, max: 500}) }, (_, i) => i + 1).map(() => ({number: faker.number.int({min: 1, max: 500}), text: faker.string.alpha({length: {min: 10, max: 1000}})})), max_selections: faker.number.int({min: 1, max: 10})}, ...overrideResponse}); +export const getGetMyAssessmentAttemptResponseFindErrorItemContentMock = (overrideResponse: Partial = {}): FindErrorItemContent => ({...{format: faker.helpers.arrayElement(['find_error'] as const), syntax: faker.helpers.arrayElement([fakeFromPattern("^[a-z0-9_+-]+$", {minLength: 1, maxLength: 32}), null]), lines: Array.from({ length: faker.number.int({min: 1, max: 500}) }, (_, i) => i + 1).map(() => ({number: faker.number.int({min: 1, max: 500}), text: faker.string.alpha({length: {min: 10, max: 1000}})})), max_selections: faker.number.int({min: 1, max: 10})}, ...overrideResponse}); -export const getGetMyAssessmentAttemptResponseConfigurationItemContentMock = (overrideResponse: Partial = {}): ConfigurationItemContent => ({...{format: faker.helpers.arrayElement(['configuration'] as const), syntax: faker.helpers.fromRegExp("^[a-z0-9_+-]+$"), initial_config: faker.string.alpha({length: {min: 10, max: 20000}}), max_length: faker.number.int({min: 1, max: 20000})}, ...overrideResponse}); +export const getGetMyAssessmentAttemptResponseConfigurationItemContentMock = (overrideResponse: Partial = {}): ConfigurationItemContent => ({...{format: faker.helpers.arrayElement(['configuration'] as const), syntax: fakeFromPattern("^[a-z0-9_+-]+$", {minLength: 1, maxLength: 32}), initial_config: faker.string.alpha({length: {min: 10, max: 20000}}), max_length: faker.number.int({min: 1, max: 20000})}, ...overrideResponse}); -export const getGetMyAssessmentAttemptResponsePracticeItemContentMock = (overrideResponse: Partial = {}): PracticeItemContent => ({...{format: faker.helpers.arrayElement(['practice'] as const), languages: faker.helpers.arrayElements(Object.values(TaskLanguage)), public_examples: Array.from({ length: faker.number.int({min: 1, max: 10}) }, (_, i) => i + 1).map(() => ({input: faker.string.alpha({length: {min: 10, max: 10000}}), expected_output: faker.string.alpha({length: {min: 10, max: 10000}})})), max_source_length: faker.number.int({min: 1, max: 65536})}, ...overrideResponse}); +export const getGetMyAssessmentAttemptResponsePracticeItemContentMock = (overrideResponse: Partial = {}): PracticeItemContent => ({...{format: faker.helpers.arrayElement(['practice'] as const), languages: faker.helpers.arrayElements(['python','go'] as const), public_examples: Array.from({ length: faker.number.int({min: 1, max: 10}) }, (_, i) => i + 1).map(() => ({input: faker.string.alpha({length: {min: 10, max: 10000}}), expected_output: faker.string.alpha({length: {min: 10, max: 10000}})})), max_source_length: faker.number.int({min: 1, max: 65536})}, ...overrideResponse}); export const getGetMyAssessmentAttemptResponseAssessmentItemMock = (overrideResponse: Partial = {}): AssessmentItem => ({...{id: faker.string.uuid(), sequence: faker.number.int({min: 1, max: 100}), prompt: faker.string.alpha({length: {min: 1, max: 20000}}), content: faker.helpers.arrayElement([{...getGetMyAssessmentAttemptResponseChoiceItemContentMock()},{...getGetMyAssessmentAttemptResponseNumberItemContentMock()},{...getGetMyAssessmentAttemptResponseStringItemContentMock()},{...getGetMyAssessmentAttemptResponseOrderItemContentMock()},{...getGetMyAssessmentAttemptResponseFindErrorItemContentMock()},{...getGetMyAssessmentAttemptResponseConfigurationItemContentMock()},{...getGetMyAssessmentAttemptResponsePracticeItemContentMock()},])}, ...overrideResponse}); export const getGetMyAssessmentAttemptResponsePracticeVerdictMock = (overrideResponse: Partial = {}): PracticeVerdict => ({...{score: faker.number.int({min: 0, max: 3}), max_score: faker.number.int({min: 3, max: 3}), groups: Array.from({ length: faker.number.int({min: 3, max: 3}) }, (_, i) => i + 1).map(() => ({group: faker.number.int({min: 1, max: 3}), passed: faker.datatype.boolean()}))}, ...overrideResponse}); -export const getGetMyAssessmentAttemptResponseMock = (overrideResponse: Partial> = {}): AssessmentAttempt => ({id: faker.string.uuid(), version: faker.number.int({min: 1}), specialization: faker.helpers.arrayElement(Object.values(SpecializationCode)), target_grade: faker.helpers.arrayElement(Object.values(GradeCode)), task_language: faker.helpers.arrayElement([faker.helpers.arrayElement(Object.values(TaskLanguage)),null,]), mode: faker.helpers.arrayElement(Object.values(AssessmentMode)), state: faker.helpers.arrayElement(Object.values(AssessmentAttemptState)), versions: {policy_version: faker.number.int({min: 1}), bank_version: faker.helpers.fromRegExp("^[A-Za-z0-9._-]+$"), algorithm_version: faker.helpers.fromRegExp("^[A-Za-z0-9._-]+$")}, started_at: faker.date.past().toISOString().slice(0, 19) + 'Z', expires_at: faker.date.past().toISOString().slice(0, 19) + 'Z', sessions: faker.helpers.arrayElement([{...getGetMyAssessmentAttemptResponseAssessmentSessionsMock()},null,]), finished_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), progress: {answered_items: faker.number.int({min: 0, max: 100}), max_items: faker.number.int({min: 1, max: 100})}, current_item: faker.helpers.arrayElement([{...getGetMyAssessmentAttemptResponseAssessmentItemMock()},null,]), practices: Array.from({ length: faker.number.int({min: 1, max: 5}) }, (_, i) => i + 1).map(() => ({kind: faker.helpers.arrayElement(Object.values(PracticeKind)), item_id: faker.string.uuid(), status: faker.helpers.arrayElement(Object.values(PracticeStatus)), submitted_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), verdict: faker.helpers.arrayElement([{...getGetMyAssessmentAttemptResponsePracticeVerdictMock()},null,]), failure_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(Object.values(PracticeFailureReason)),null,])})), ...overrideResponse}) +export const getGetMyAssessmentAttemptResponseMock = (overrideResponse: Partial> = {}): AssessmentAttempt => ({id: faker.string.uuid(), version: faker.number.int({min: 1}), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), target_grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), task_language: faker.helpers.arrayElement([faker.helpers.arrayElement(['python','go'] as const),null,]), mode: faker.helpers.arrayElement(['demo_basic','adaptive'] as const), state: faker.helpers.arrayElement(['in_progress','practice_pending','additional_practice_pending','ready_to_finalize','completed','expired','insufficient_bank'] as const), versions: {policy_version: faker.number.int({min: 1}), bank_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}), algorithm_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64})}, started_at: faker.date.past().toISOString().slice(0, 19) + 'Z', expires_at: faker.date.past().toISOString().slice(0, 19) + 'Z', sessions: faker.helpers.arrayElement([{...getGetMyAssessmentAttemptResponseAssessmentSessionsMock()},null,]), finished_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), progress: {answered_items: faker.number.int({min: 0, max: 100}), max_items: faker.number.int({min: 1, max: 100})}, current_item: faker.helpers.arrayElement([{...getGetMyAssessmentAttemptResponseAssessmentItemMock()},null,]), practices: Array.from({ length: faker.number.int({min: 1, max: 5}) }, (_, i) => i + 1).map(() => ({kind: faker.helpers.arrayElement(['main','additional'] as const), item_id: faker.string.uuid(), status: faker.helpers.arrayElement(['not_started','pending','finished','failed'] as const), submitted_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), verdict: faker.helpers.arrayElement([{...getGetMyAssessmentAttemptResponsePracticeVerdictMock()},null,]), failure_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['sandbox_busy','sandbox_error'] as const),null,])})), ...overrideResponse}) export const getSubmitMyAssessmentAnswerResponseAssessmentSessionsMock = (overrideResponse: Partial = {}): AssessmentSessions => ({...{used: faker.number.int({min: 1, max: 10}), max: faker.number.int({min: 1, max: 10}), idle_timeout_seconds: faker.number.int({min: 60, max: 86400})}, ...overrideResponse}); -export const getSubmitMyAssessmentAnswerResponseChoiceItemContentMock = (overrideResponse: Partial = {}): ChoiceItemContent => ({...{format: faker.helpers.arrayElement(['choice'] as const), options: Array.from({ length: faker.number.int({min: 2, max: 10}) }, (_, i) => i + 1).map(() => ({id: faker.helpers.fromRegExp("^[A-Za-z0-9_-]+$"), text: faker.string.alpha({length: {min: 1, max: 2000}})})), multiple: faker.datatype.boolean()}, ...overrideResponse}); +export const getSubmitMyAssessmentAnswerResponseChoiceItemContentMock = (overrideResponse: Partial = {}): ChoiceItemContent => ({...{format: faker.helpers.arrayElement(['choice'] as const), options: Array.from({ length: faker.number.int({min: 2, max: 10}) }, (_, i) => i + 1).map(() => ({id: fakeFromPattern("^[A-Za-z0-9_-]+$", {minLength: 1, maxLength: 32}), text: faker.string.alpha({length: {min: 1, max: 2000}})})), multiple: faker.datatype.boolean()}, ...overrideResponse}); export const getSubmitMyAssessmentAnswerResponseNumberItemContentMock = (overrideResponse: Partial = {}): NumberItemContent => ({...{format: faker.helpers.arrayElement(['number'] as const), unit: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 32}}), null])}, ...overrideResponse}); export const getSubmitMyAssessmentAnswerResponseStringItemContentMock = (overrideResponse: Partial = {}): StringItemContent => ({...{format: faker.helpers.arrayElement(['string'] as const), max_length: faker.number.int({min: 1, max: 500})}, ...overrideResponse}); -export const getSubmitMyAssessmentAnswerResponseOrderItemContentMock = (overrideResponse: Partial = {}): OrderItemContent => ({...{format: faker.helpers.arrayElement(['order'] as const), elements: Array.from({ length: faker.number.int({min: 2, max: 20}) }, (_, i) => i + 1).map(() => ({id: faker.helpers.fromRegExp("^[A-Za-z0-9_-]+$"), text: faker.string.alpha({length: {min: 1, max: 2000}})}))}, ...overrideResponse}); +export const getSubmitMyAssessmentAnswerResponseOrderItemContentMock = (overrideResponse: Partial = {}): OrderItemContent => ({...{format: faker.helpers.arrayElement(['order'] as const), elements: Array.from({ length: faker.number.int({min: 2, max: 20}) }, (_, i) => i + 1).map(() => ({id: fakeFromPattern("^[A-Za-z0-9_-]+$", {minLength: 1, maxLength: 32}), text: faker.string.alpha({length: {min: 1, max: 2000}})}))}, ...overrideResponse}); -export const getSubmitMyAssessmentAnswerResponseFindErrorItemContentMock = (overrideResponse: Partial = {}): FindErrorItemContent => ({...{format: faker.helpers.arrayElement(['find_error'] as const), syntax: faker.helpers.arrayElement([faker.helpers.fromRegExp("^[a-z0-9_+-]+$"), null]), lines: Array.from({ length: faker.number.int({min: 1, max: 500}) }, (_, i) => i + 1).map(() => ({number: faker.number.int({min: 1, max: 500}), text: faker.string.alpha({length: {min: 10, max: 1000}})})), max_selections: faker.number.int({min: 1, max: 10})}, ...overrideResponse}); +export const getSubmitMyAssessmentAnswerResponseFindErrorItemContentMock = (overrideResponse: Partial = {}): FindErrorItemContent => ({...{format: faker.helpers.arrayElement(['find_error'] as const), syntax: faker.helpers.arrayElement([fakeFromPattern("^[a-z0-9_+-]+$", {minLength: 1, maxLength: 32}), null]), lines: Array.from({ length: faker.number.int({min: 1, max: 500}) }, (_, i) => i + 1).map(() => ({number: faker.number.int({min: 1, max: 500}), text: faker.string.alpha({length: {min: 10, max: 1000}})})), max_selections: faker.number.int({min: 1, max: 10})}, ...overrideResponse}); -export const getSubmitMyAssessmentAnswerResponseConfigurationItemContentMock = (overrideResponse: Partial = {}): ConfigurationItemContent => ({...{format: faker.helpers.arrayElement(['configuration'] as const), syntax: faker.helpers.fromRegExp("^[a-z0-9_+-]+$"), initial_config: faker.string.alpha({length: {min: 10, max: 20000}}), max_length: faker.number.int({min: 1, max: 20000})}, ...overrideResponse}); +export const getSubmitMyAssessmentAnswerResponseConfigurationItemContentMock = (overrideResponse: Partial = {}): ConfigurationItemContent => ({...{format: faker.helpers.arrayElement(['configuration'] as const), syntax: fakeFromPattern("^[a-z0-9_+-]+$", {minLength: 1, maxLength: 32}), initial_config: faker.string.alpha({length: {min: 10, max: 20000}}), max_length: faker.number.int({min: 1, max: 20000})}, ...overrideResponse}); -export const getSubmitMyAssessmentAnswerResponsePracticeItemContentMock = (overrideResponse: Partial = {}): PracticeItemContent => ({...{format: faker.helpers.arrayElement(['practice'] as const), languages: faker.helpers.arrayElements(Object.values(TaskLanguage)), public_examples: Array.from({ length: faker.number.int({min: 1, max: 10}) }, (_, i) => i + 1).map(() => ({input: faker.string.alpha({length: {min: 10, max: 10000}}), expected_output: faker.string.alpha({length: {min: 10, max: 10000}})})), max_source_length: faker.number.int({min: 1, max: 65536})}, ...overrideResponse}); +export const getSubmitMyAssessmentAnswerResponsePracticeItemContentMock = (overrideResponse: Partial = {}): PracticeItemContent => ({...{format: faker.helpers.arrayElement(['practice'] as const), languages: faker.helpers.arrayElements(['python','go'] as const), public_examples: Array.from({ length: faker.number.int({min: 1, max: 10}) }, (_, i) => i + 1).map(() => ({input: faker.string.alpha({length: {min: 10, max: 10000}}), expected_output: faker.string.alpha({length: {min: 10, max: 10000}})})), max_source_length: faker.number.int({min: 1, max: 65536})}, ...overrideResponse}); export const getSubmitMyAssessmentAnswerResponseAssessmentItemMock = (overrideResponse: Partial = {}): AssessmentItem => ({...{id: faker.string.uuid(), sequence: faker.number.int({min: 1, max: 100}), prompt: faker.string.alpha({length: {min: 1, max: 20000}}), content: faker.helpers.arrayElement([{...getSubmitMyAssessmentAnswerResponseChoiceItemContentMock()},{...getSubmitMyAssessmentAnswerResponseNumberItemContentMock()},{...getSubmitMyAssessmentAnswerResponseStringItemContentMock()},{...getSubmitMyAssessmentAnswerResponseOrderItemContentMock()},{...getSubmitMyAssessmentAnswerResponseFindErrorItemContentMock()},{...getSubmitMyAssessmentAnswerResponseConfigurationItemContentMock()},{...getSubmitMyAssessmentAnswerResponsePracticeItemContentMock()},])}, ...overrideResponse}); export const getSubmitMyAssessmentAnswerResponsePracticeVerdictMock = (overrideResponse: Partial = {}): PracticeVerdict => ({...{score: faker.number.int({min: 0, max: 3}), max_score: faker.number.int({min: 3, max: 3}), groups: Array.from({ length: faker.number.int({min: 3, max: 3}) }, (_, i) => i + 1).map(() => ({group: faker.number.int({min: 1, max: 3}), passed: faker.datatype.boolean()}))}, ...overrideResponse}); -export const getSubmitMyAssessmentAnswerResponseMock = (overrideResponse: Partial> = {}): AssessmentAttempt => ({id: faker.string.uuid(), version: faker.number.int({min: 1}), specialization: faker.helpers.arrayElement(Object.values(SpecializationCode)), target_grade: faker.helpers.arrayElement(Object.values(GradeCode)), task_language: faker.helpers.arrayElement([faker.helpers.arrayElement(Object.values(TaskLanguage)),null,]), mode: faker.helpers.arrayElement(Object.values(AssessmentMode)), state: faker.helpers.arrayElement(Object.values(AssessmentAttemptState)), versions: {policy_version: faker.number.int({min: 1}), bank_version: faker.helpers.fromRegExp("^[A-Za-z0-9._-]+$"), algorithm_version: faker.helpers.fromRegExp("^[A-Za-z0-9._-]+$")}, started_at: faker.date.past().toISOString().slice(0, 19) + 'Z', expires_at: faker.date.past().toISOString().slice(0, 19) + 'Z', sessions: faker.helpers.arrayElement([{...getSubmitMyAssessmentAnswerResponseAssessmentSessionsMock()},null,]), finished_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), progress: {answered_items: faker.number.int({min: 0, max: 100}), max_items: faker.number.int({min: 1, max: 100})}, current_item: faker.helpers.arrayElement([{...getSubmitMyAssessmentAnswerResponseAssessmentItemMock()},null,]), practices: Array.from({ length: faker.number.int({min: 1, max: 5}) }, (_, i) => i + 1).map(() => ({kind: faker.helpers.arrayElement(Object.values(PracticeKind)), item_id: faker.string.uuid(), status: faker.helpers.arrayElement(Object.values(PracticeStatus)), submitted_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), verdict: faker.helpers.arrayElement([{...getSubmitMyAssessmentAnswerResponsePracticeVerdictMock()},null,]), failure_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(Object.values(PracticeFailureReason)),null,])})), ...overrideResponse}) +export const getSubmitMyAssessmentAnswerResponseMock = (overrideResponse: Partial> = {}): AssessmentAttempt => ({id: faker.string.uuid(), version: faker.number.int({min: 1}), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), target_grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), task_language: faker.helpers.arrayElement([faker.helpers.arrayElement(['python','go'] as const),null,]), mode: faker.helpers.arrayElement(['demo_basic','adaptive'] as const), state: faker.helpers.arrayElement(['in_progress','practice_pending','additional_practice_pending','ready_to_finalize','completed','expired','insufficient_bank'] as const), versions: {policy_version: faker.number.int({min: 1}), bank_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}), algorithm_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64})}, started_at: faker.date.past().toISOString().slice(0, 19) + 'Z', expires_at: faker.date.past().toISOString().slice(0, 19) + 'Z', sessions: faker.helpers.arrayElement([{...getSubmitMyAssessmentAnswerResponseAssessmentSessionsMock()},null,]), finished_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), progress: {answered_items: faker.number.int({min: 0, max: 100}), max_items: faker.number.int({min: 1, max: 100})}, current_item: faker.helpers.arrayElement([{...getSubmitMyAssessmentAnswerResponseAssessmentItemMock()},null,]), practices: Array.from({ length: faker.number.int({min: 1, max: 5}) }, (_, i) => i + 1).map(() => ({kind: faker.helpers.arrayElement(['main','additional'] as const), item_id: faker.string.uuid(), status: faker.helpers.arrayElement(['not_started','pending','finished','failed'] as const), submitted_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), verdict: faker.helpers.arrayElement([{...getSubmitMyAssessmentAnswerResponsePracticeVerdictMock()},null,]), failure_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['sandbox_busy','sandbox_error'] as const),null,])})), ...overrideResponse}) export const getFinalizeMyAssessmentAttemptResponseAssessmentSessionsMock = (overrideResponse: Partial = {}): AssessmentSessions => ({...{used: faker.number.int({min: 1, max: 10}), max: faker.number.int({min: 1, max: 10}), idle_timeout_seconds: faker.number.int({min: 60, max: 86400})}, ...overrideResponse}); -export const getFinalizeMyAssessmentAttemptResponseChoiceItemContentMock = (overrideResponse: Partial = {}): ChoiceItemContent => ({...{format: faker.helpers.arrayElement(['choice'] as const), options: Array.from({ length: faker.number.int({min: 2, max: 10}) }, (_, i) => i + 1).map(() => ({id: faker.helpers.fromRegExp("^[A-Za-z0-9_-]+$"), text: faker.string.alpha({length: {min: 1, max: 2000}})})), multiple: faker.datatype.boolean()}, ...overrideResponse}); +export const getFinalizeMyAssessmentAttemptResponseChoiceItemContentMock = (overrideResponse: Partial = {}): ChoiceItemContent => ({...{format: faker.helpers.arrayElement(['choice'] as const), options: Array.from({ length: faker.number.int({min: 2, max: 10}) }, (_, i) => i + 1).map(() => ({id: fakeFromPattern("^[A-Za-z0-9_-]+$", {minLength: 1, maxLength: 32}), text: faker.string.alpha({length: {min: 1, max: 2000}})})), multiple: faker.datatype.boolean()}, ...overrideResponse}); export const getFinalizeMyAssessmentAttemptResponseNumberItemContentMock = (overrideResponse: Partial = {}): NumberItemContent => ({...{format: faker.helpers.arrayElement(['number'] as const), unit: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 32}}), null])}, ...overrideResponse}); export const getFinalizeMyAssessmentAttemptResponseStringItemContentMock = (overrideResponse: Partial = {}): StringItemContent => ({...{format: faker.helpers.arrayElement(['string'] as const), max_length: faker.number.int({min: 1, max: 500})}, ...overrideResponse}); -export const getFinalizeMyAssessmentAttemptResponseOrderItemContentMock = (overrideResponse: Partial = {}): OrderItemContent => ({...{format: faker.helpers.arrayElement(['order'] as const), elements: Array.from({ length: faker.number.int({min: 2, max: 20}) }, (_, i) => i + 1).map(() => ({id: faker.helpers.fromRegExp("^[A-Za-z0-9_-]+$"), text: faker.string.alpha({length: {min: 1, max: 2000}})}))}, ...overrideResponse}); +export const getFinalizeMyAssessmentAttemptResponseOrderItemContentMock = (overrideResponse: Partial = {}): OrderItemContent => ({...{format: faker.helpers.arrayElement(['order'] as const), elements: Array.from({ length: faker.number.int({min: 2, max: 20}) }, (_, i) => i + 1).map(() => ({id: fakeFromPattern("^[A-Za-z0-9_-]+$", {minLength: 1, maxLength: 32}), text: faker.string.alpha({length: {min: 1, max: 2000}})}))}, ...overrideResponse}); -export const getFinalizeMyAssessmentAttemptResponseFindErrorItemContentMock = (overrideResponse: Partial = {}): FindErrorItemContent => ({...{format: faker.helpers.arrayElement(['find_error'] as const), syntax: faker.helpers.arrayElement([faker.helpers.fromRegExp("^[a-z0-9_+-]+$"), null]), lines: Array.from({ length: faker.number.int({min: 1, max: 500}) }, (_, i) => i + 1).map(() => ({number: faker.number.int({min: 1, max: 500}), text: faker.string.alpha({length: {min: 10, max: 1000}})})), max_selections: faker.number.int({min: 1, max: 10})}, ...overrideResponse}); +export const getFinalizeMyAssessmentAttemptResponseFindErrorItemContentMock = (overrideResponse: Partial = {}): FindErrorItemContent => ({...{format: faker.helpers.arrayElement(['find_error'] as const), syntax: faker.helpers.arrayElement([fakeFromPattern("^[a-z0-9_+-]+$", {minLength: 1, maxLength: 32}), null]), lines: Array.from({ length: faker.number.int({min: 1, max: 500}) }, (_, i) => i + 1).map(() => ({number: faker.number.int({min: 1, max: 500}), text: faker.string.alpha({length: {min: 10, max: 1000}})})), max_selections: faker.number.int({min: 1, max: 10})}, ...overrideResponse}); -export const getFinalizeMyAssessmentAttemptResponseConfigurationItemContentMock = (overrideResponse: Partial = {}): ConfigurationItemContent => ({...{format: faker.helpers.arrayElement(['configuration'] as const), syntax: faker.helpers.fromRegExp("^[a-z0-9_+-]+$"), initial_config: faker.string.alpha({length: {min: 10, max: 20000}}), max_length: faker.number.int({min: 1, max: 20000})}, ...overrideResponse}); +export const getFinalizeMyAssessmentAttemptResponseConfigurationItemContentMock = (overrideResponse: Partial = {}): ConfigurationItemContent => ({...{format: faker.helpers.arrayElement(['configuration'] as const), syntax: fakeFromPattern("^[a-z0-9_+-]+$", {minLength: 1, maxLength: 32}), initial_config: faker.string.alpha({length: {min: 10, max: 20000}}), max_length: faker.number.int({min: 1, max: 20000})}, ...overrideResponse}); -export const getFinalizeMyAssessmentAttemptResponsePracticeItemContentMock = (overrideResponse: Partial = {}): PracticeItemContent => ({...{format: faker.helpers.arrayElement(['practice'] as const), languages: faker.helpers.arrayElements(Object.values(TaskLanguage)), public_examples: Array.from({ length: faker.number.int({min: 1, max: 10}) }, (_, i) => i + 1).map(() => ({input: faker.string.alpha({length: {min: 10, max: 10000}}), expected_output: faker.string.alpha({length: {min: 10, max: 10000}})})), max_source_length: faker.number.int({min: 1, max: 65536})}, ...overrideResponse}); +export const getFinalizeMyAssessmentAttemptResponsePracticeItemContentMock = (overrideResponse: Partial = {}): PracticeItemContent => ({...{format: faker.helpers.arrayElement(['practice'] as const), languages: faker.helpers.arrayElements(['python','go'] as const), public_examples: Array.from({ length: faker.number.int({min: 1, max: 10}) }, (_, i) => i + 1).map(() => ({input: faker.string.alpha({length: {min: 10, max: 10000}}), expected_output: faker.string.alpha({length: {min: 10, max: 10000}})})), max_source_length: faker.number.int({min: 1, max: 65536})}, ...overrideResponse}); export const getFinalizeMyAssessmentAttemptResponseAssessmentItemMock = (overrideResponse: Partial = {}): AssessmentItem => ({...{id: faker.string.uuid(), sequence: faker.number.int({min: 1, max: 100}), prompt: faker.string.alpha({length: {min: 1, max: 20000}}), content: faker.helpers.arrayElement([{...getFinalizeMyAssessmentAttemptResponseChoiceItemContentMock()},{...getFinalizeMyAssessmentAttemptResponseNumberItemContentMock()},{...getFinalizeMyAssessmentAttemptResponseStringItemContentMock()},{...getFinalizeMyAssessmentAttemptResponseOrderItemContentMock()},{...getFinalizeMyAssessmentAttemptResponseFindErrorItemContentMock()},{...getFinalizeMyAssessmentAttemptResponseConfigurationItemContentMock()},{...getFinalizeMyAssessmentAttemptResponsePracticeItemContentMock()},])}, ...overrideResponse}); export const getFinalizeMyAssessmentAttemptResponsePracticeVerdictMock = (overrideResponse: Partial = {}): PracticeVerdict => ({...{score: faker.number.int({min: 0, max: 3}), max_score: faker.number.int({min: 3, max: 3}), groups: Array.from({ length: faker.number.int({min: 3, max: 3}) }, (_, i) => i + 1).map(() => ({group: faker.number.int({min: 1, max: 3}), passed: faker.datatype.boolean()}))}, ...overrideResponse}); -export const getFinalizeMyAssessmentAttemptResponseMock = (overrideResponse: Partial> = {}): AssessmentAttempt => ({id: faker.string.uuid(), version: faker.number.int({min: 1}), specialization: faker.helpers.arrayElement(Object.values(SpecializationCode)), target_grade: faker.helpers.arrayElement(Object.values(GradeCode)), task_language: faker.helpers.arrayElement([faker.helpers.arrayElement(Object.values(TaskLanguage)),null,]), mode: faker.helpers.arrayElement(Object.values(AssessmentMode)), state: faker.helpers.arrayElement(Object.values(AssessmentAttemptState)), versions: {policy_version: faker.number.int({min: 1}), bank_version: faker.helpers.fromRegExp("^[A-Za-z0-9._-]+$"), algorithm_version: faker.helpers.fromRegExp("^[A-Za-z0-9._-]+$")}, started_at: faker.date.past().toISOString().slice(0, 19) + 'Z', expires_at: faker.date.past().toISOString().slice(0, 19) + 'Z', sessions: faker.helpers.arrayElement([{...getFinalizeMyAssessmentAttemptResponseAssessmentSessionsMock()},null,]), finished_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), progress: {answered_items: faker.number.int({min: 0, max: 100}), max_items: faker.number.int({min: 1, max: 100})}, current_item: faker.helpers.arrayElement([{...getFinalizeMyAssessmentAttemptResponseAssessmentItemMock()},null,]), practices: Array.from({ length: faker.number.int({min: 1, max: 5}) }, (_, i) => i + 1).map(() => ({kind: faker.helpers.arrayElement(Object.values(PracticeKind)), item_id: faker.string.uuid(), status: faker.helpers.arrayElement(Object.values(PracticeStatus)), submitted_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), verdict: faker.helpers.arrayElement([{...getFinalizeMyAssessmentAttemptResponsePracticeVerdictMock()},null,]), failure_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(Object.values(PracticeFailureReason)),null,])})), ...overrideResponse}) +export const getFinalizeMyAssessmentAttemptResponseMock = (overrideResponse: Partial> = {}): AssessmentAttempt => ({id: faker.string.uuid(), version: faker.number.int({min: 1}), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), target_grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), task_language: faker.helpers.arrayElement([faker.helpers.arrayElement(['python','go'] as const),null,]), mode: faker.helpers.arrayElement(['demo_basic','adaptive'] as const), state: faker.helpers.arrayElement(['in_progress','practice_pending','additional_practice_pending','ready_to_finalize','completed','expired','insufficient_bank'] as const), versions: {policy_version: faker.number.int({min: 1}), bank_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}), algorithm_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64})}, started_at: faker.date.past().toISOString().slice(0, 19) + 'Z', expires_at: faker.date.past().toISOString().slice(0, 19) + 'Z', sessions: faker.helpers.arrayElement([{...getFinalizeMyAssessmentAttemptResponseAssessmentSessionsMock()},null,]), finished_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), progress: {answered_items: faker.number.int({min: 0, max: 100}), max_items: faker.number.int({min: 1, max: 100})}, current_item: faker.helpers.arrayElement([{...getFinalizeMyAssessmentAttemptResponseAssessmentItemMock()},null,]), practices: Array.from({ length: faker.number.int({min: 1, max: 5}) }, (_, i) => i + 1).map(() => ({kind: faker.helpers.arrayElement(['main','additional'] as const), item_id: faker.string.uuid(), status: faker.helpers.arrayElement(['not_started','pending','finished','failed'] as const), submitted_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), verdict: faker.helpers.arrayElement([{...getFinalizeMyAssessmentAttemptResponsePracticeVerdictMock()},null,]), failure_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['sandbox_busy','sandbox_error'] as const),null,])})), ...overrideResponse}) export const getGetMyAssessmentResultResponseAssessmentUncertaintyMock = (overrideResponse: Partial = {}): AssessmentUncertainty => ({...{theta: faker.number.float({fractionDigits: 2}), standard_error: faker.number.float({min: 0, fractionDigits: 2}), interval_95: {low: faker.number.float({fractionDigits: 2}), high: faker.number.float({fractionDigits: 2})}, p_grade: faker.number.float({min: 0, max: 1, fractionDigits: 2})}, ...overrideResponse}); export const getGetMyAssessmentResultResponseBasicScoreMock = (overrideResponse: Partial = {}): BasicScore => ({...{points: faker.number.int({min: 0}), max_points: faker.number.int({min: 1}), pass_points: faker.number.int({min: 1})}, ...overrideResponse}); -export const getGetMyAssessmentResultResponseMock = (overrideResponse: Partial> = {}): AssessmentResult => ({attempt_id: faker.string.uuid(), specialization: faker.helpers.arrayElement(Object.values(SpecializationCode)), target_grade: faker.helpers.arrayElement(Object.values(GradeCode)), task_language: faker.helpers.arrayElement([faker.helpers.arrayElement(Object.values(TaskLanguage)),null,]), mode: faker.helpers.arrayElement(Object.values(AssessmentMode)), versions: {policy_version: faker.number.int({min: 1}), bank_version: faker.helpers.fromRegExp("^[A-Za-z0-9._-]+$"), algorithm_version: faker.helpers.fromRegExp("^[A-Za-z0-9._-]+$")}, outcome: faker.helpers.arrayElement(Object.values(AssessmentOutcome)), not_determined_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(Object.values(AssessmentNotDeterminedReason)),null,]), confirmed_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(Object.values(GradeCode)),null,]), previous_confirmed_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(Object.values(GradeCode)),null,]), strength: faker.helpers.arrayElement([faker.helpers.arrayElement(Object.values(AssessmentStrength)),null,]), calibration_status: faker.helpers.arrayElement(Object.values(CalibrationStatus)), limitations: faker.helpers.arrayElements(Object.values(AssessmentLimitation)), uncertainty: faker.helpers.arrayElement([{...getGetMyAssessmentResultResponseAssessmentUncertaintyMock()},null,]), basic_score: faker.helpers.arrayElement([{...getGetMyAssessmentResultResponseBasicScoreMock()},null,]), practices: Array.from({ length: faker.number.int({min: 1, max: 5}) }, (_, i) => i + 1).map(() => ({kind: faker.helpers.arrayElement(Object.values(PracticeKind)), verdict: {score: faker.number.int({min: 0, max: 3}), max_score: faker.number.int({min: 3, max: 3}), groups: Array.from({ length: faker.number.int({min: 3, max: 3}) }, (_, i) => i + 1).map(() => ({group: faker.number.int({min: 1, max: 3}), passed: faker.datatype.boolean()}))}})), gaps: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => ({domain: faker.helpers.fromRegExp("^[a-z0-9_]+$"), title: faker.string.alpha({length: {min: 1, max: 200}})})), durations: {items_seconds: faker.number.int({min: 0}), practice_seconds: faker.helpers.arrayElement([faker.number.int({min: 0}), null])}, next_steps: Array.from({ length: faker.number.int({min: 1, max: 5}) }, (_, i) => i + 1).map(() => ({action: faker.helpers.arrayElement(Object.values(AssessmentNextAction)), grade: faker.helpers.arrayElement(Object.values(GradeCode)), available_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,])})), decided_at: faker.date.past().toISOString().slice(0, 19) + 'Z', ...overrideResponse}) +export const getGetMyAssessmentResultResponseMock = (overrideResponse: Partial> = {}): AssessmentResult => ({attempt_id: faker.string.uuid(), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), target_grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), task_language: faker.helpers.arrayElement([faker.helpers.arrayElement(['python','go'] as const),null,]), mode: faker.helpers.arrayElement(['demo_basic','adaptive'] as const), versions: {policy_version: faker.number.int({min: 1}), bank_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}), algorithm_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64})}, outcome: faker.helpers.arrayElement(['confirmed','not_confirmed','not_determined'] as const), not_determined_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['expired','practice_incomplete','insufficient_bank','sandbox_unavailable'] as const),null,]), confirmed_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), previous_confirmed_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), strength: faker.helpers.arrayElement([faker.helpers.arrayElement(['high','medium'] as const),null,]), calibration_status: faker.helpers.arrayElement(['uncalibrated','calibrated'] as const), limitations: faker.helpers.arrayElements(['uncalibrated_thresholds','demo_bank','practice_not_included','unproctored'] as const), uncertainty: faker.helpers.arrayElement([{...getGetMyAssessmentResultResponseAssessmentUncertaintyMock()},null,]), basic_score: faker.helpers.arrayElement([{...getGetMyAssessmentResultResponseBasicScoreMock()},null,]), practices: Array.from({ length: faker.number.int({min: 1, max: 5}) }, (_, i) => i + 1).map(() => ({kind: faker.helpers.arrayElement(['main','additional'] as const), verdict: {score: faker.number.int({min: 0, max: 3}), max_score: faker.number.int({min: 3, max: 3}), groups: Array.from({ length: faker.number.int({min: 3, max: 3}) }, (_, i) => i + 1).map(() => ({group: faker.number.int({min: 1, max: 3}), passed: faker.datatype.boolean()}))}})), gaps: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => ({domain: fakeFromPattern("^[a-z0-9_]+$", {minLength: 1, maxLength: 64}), title: faker.string.alpha({length: {min: 1, max: 200}})})), durations: {items_seconds: faker.number.int({min: 0}), practice_seconds: faker.helpers.arrayElement([faker.number.int({min: 0}), null])}, next_steps: Array.from({ length: faker.number.int({min: 1, max: 5}) }, (_, i) => i + 1).map(() => ({action: faker.helpers.arrayElement(['retake_same_grade','take_lower_grade','accept_lower_grade','take_higher_grade'] as const), grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), available_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,])})), decided_at: faker.date.past().toISOString().slice(0, 19) + 'Z', ...overrideResponse}) export const getGetMyAssessmentAvailabilityMockHandler = (overrideResponse?: AssessmentAvailability | ((info: Parameters[1]>[0]) => Promise | AssessmentAvailability), options?: RequestHandlerOptions) => { diff --git a/frontend/src/shared/api/endpoints/candidate/candidate.msw.ts b/frontend/src/shared/api/endpoints/candidate/candidate.msw.ts index 0c9dc72..f3fde30 100644 --- a/frontend/src/shared/api/endpoints/candidate/candidate.msw.ts +++ b/frontend/src/shared/api/endpoints/candidate/candidate.msw.ts @@ -8,6 +8,10 @@ import { faker } from '@faker-js/faker'; +import { + fakeFromPattern +} from '../../mock-pattern'; + import { HttpResponse, http @@ -16,12 +20,6 @@ import type { RequestHandlerOptions } from 'msw'; -import { - GradeCode, - SpecializationCode, - TaskLanguage, - WorkFormat -} from '../../schemas'; import type { CandidateExperience, CandidateQuestionnaire, @@ -31,15 +29,15 @@ import type { export const getGetMyQuestionnaireResponseCandidateExperienceMock = (overrideResponse: Partial = {}): CandidateExperience => ({...{commercial_months: faker.number.int({min: 0, max: 600}), academic_months: faker.number.int({min: 0, max: 600})}, ...overrideResponse}); -export const getGetMyQuestionnaireResponseWorkContextMock = (overrideResponse: Partial = {}): WorkContext => ({...{work_formats: faker.helpers.arrayElements(Object.values(WorkFormat))}, ...overrideResponse}); +export const getGetMyQuestionnaireResponseWorkContextMock = (overrideResponse: Partial = {}): WorkContext => ({...{work_formats: faker.helpers.arrayElements(['remote','office','hybrid'] as const)}, ...overrideResponse}); -export const getGetMyQuestionnaireResponseMock = (overrideResponse: Partial> = {}): CandidateQuestionnaire => ({version: faker.number.int({min: 0}), specializations: Array.from({ length: faker.number.int({min: 1, max: 2}) }, (_, i) => i + 1).map(() => ({specialization: faker.helpers.arrayElement(Object.values(SpecializationCode)), self_assessed_grade: faker.helpers.arrayElement(Object.values(GradeCode)), task_languages: faker.helpers.arrayElements(Object.values(TaskLanguage)), stack: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => (faker.helpers.fromRegExp("^\\S(?:.*\\S)?$"))), experience: faker.helpers.arrayElement([{...getGetMyQuestionnaireResponseCandidateExperienceMock()},null,])})), work_context: faker.helpers.arrayElement([{...getGetMyQuestionnaireResponseWorkContextMock()},null,]), updated_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), ...overrideResponse}) +export const getGetMyQuestionnaireResponseMock = (overrideResponse: Partial> = {}): CandidateQuestionnaire => ({version: faker.number.int({min: 0}), specializations: Array.from({ length: faker.number.int({min: 1, max: 2}) }, (_, i) => i + 1).map(() => ({specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), self_assessed_grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), task_languages: faker.helpers.arrayElements(['python','go'] as const), stack: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 50}))), experience: faker.helpers.arrayElement([{...getGetMyQuestionnaireResponseCandidateExperienceMock()},null,])})), work_context: faker.helpers.arrayElement([{...getGetMyQuestionnaireResponseWorkContextMock()},null,]), updated_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), ...overrideResponse}) export const getSaveMyQuestionnaireResponseCandidateExperienceMock = (overrideResponse: Partial = {}): CandidateExperience => ({...{commercial_months: faker.number.int({min: 0, max: 600}), academic_months: faker.number.int({min: 0, max: 600})}, ...overrideResponse}); -export const getSaveMyQuestionnaireResponseWorkContextMock = (overrideResponse: Partial = {}): WorkContext => ({...{work_formats: faker.helpers.arrayElements(Object.values(WorkFormat))}, ...overrideResponse}); +export const getSaveMyQuestionnaireResponseWorkContextMock = (overrideResponse: Partial = {}): WorkContext => ({...{work_formats: faker.helpers.arrayElements(['remote','office','hybrid'] as const)}, ...overrideResponse}); -export const getSaveMyQuestionnaireResponseMock = (overrideResponse: Partial> = {}): CandidateQuestionnaire => ({version: faker.number.int({min: 0}), specializations: Array.from({ length: faker.number.int({min: 1, max: 2}) }, (_, i) => i + 1).map(() => ({specialization: faker.helpers.arrayElement(Object.values(SpecializationCode)), self_assessed_grade: faker.helpers.arrayElement(Object.values(GradeCode)), task_languages: faker.helpers.arrayElements(Object.values(TaskLanguage)), stack: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => (faker.helpers.fromRegExp("^\\S(?:.*\\S)?$"))), experience: faker.helpers.arrayElement([{...getSaveMyQuestionnaireResponseCandidateExperienceMock()},null,])})), work_context: faker.helpers.arrayElement([{...getSaveMyQuestionnaireResponseWorkContextMock()},null,]), updated_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), ...overrideResponse}) +export const getSaveMyQuestionnaireResponseMock = (overrideResponse: Partial> = {}): CandidateQuestionnaire => ({version: faker.number.int({min: 0}), specializations: Array.from({ length: faker.number.int({min: 1, max: 2}) }, (_, i) => i + 1).map(() => ({specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), self_assessed_grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), task_languages: faker.helpers.arrayElements(['python','go'] as const), stack: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 50}))), experience: faker.helpers.arrayElement([{...getSaveMyQuestionnaireResponseCandidateExperienceMock()},null,])})), work_context: faker.helpers.arrayElement([{...getSaveMyQuestionnaireResponseWorkContextMock()},null,]), updated_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), ...overrideResponse}) export const getGetMyQuestionnaireMockHandler = (overrideResponse?: CandidateQuestionnaire | ((info: Parameters[1]>[0]) => Promise | CandidateQuestionnaire), options?: RequestHandlerOptions) => { diff --git a/frontend/src/shared/api/endpoints/catalog/catalog.msw.ts b/frontend/src/shared/api/endpoints/catalog/catalog.msw.ts index 710446b..82d9b3e 100644 --- a/frontend/src/shared/api/endpoints/catalog/catalog.msw.ts +++ b/frontend/src/shared/api/endpoints/catalog/catalog.msw.ts @@ -16,19 +16,12 @@ import type { RequestHandlerOptions } from 'msw'; -import { - DirectionCode, - GradeCode, - SpecializationCode, - TaskLanguage, - TestAvailabilityStatus -} from '../../schemas'; import type { SpecializationCatalog } from '../../schemas'; -export const getGetSpecializationCatalogResponseMock = (overrideResponse: Partial> = {}): SpecializationCatalog => ({directions: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => ({code: faker.helpers.arrayElement(Object.values(DirectionCode)), title: faker.string.alpha({length: {min: 1, max: 100}}), specializations: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => ({code: faker.helpers.arrayElement(Object.values(SpecializationCode)), title: faker.string.alpha({length: {min: 1, max: 100}}), test_availability: {status: faker.helpers.arrayElement(Object.values(TestAvailabilityStatus)), grades: faker.helpers.arrayElements(Object.values(GradeCode)), task_languages: faker.helpers.arrayElements(Object.values(TaskLanguage)), note: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 300}}), null])}}))})), grades: Array.from({ length: faker.number.int({min: 1, max: 10}) }, (_, i) => i + 1).map(() => ({code: faker.helpers.arrayElement(Object.values(GradeCode)), title: faker.string.alpha({length: {min: 1, max: 100}})})), ...overrideResponse}) +export const getGetSpecializationCatalogResponseMock = (overrideResponse: Partial> = {}): SpecializationCatalog => ({directions: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => ({code: faker.helpers.arrayElement(['development','infrastructure','data','security','quality'] as const), title: faker.string.alpha({length: {min: 1, max: 100}}), specializations: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => ({code: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), title: faker.string.alpha({length: {min: 1, max: 100}}), test_availability: {status: faker.helpers.arrayElement(['available','in_development'] as const), grades: faker.helpers.arrayElements(['intern','junior','middle','senior'] as const), task_languages: faker.helpers.arrayElements(['python','go'] as const), note: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 300}}), null])}}))})), grades: Array.from({ length: faker.number.int({min: 1, max: 10}) }, (_, i) => i + 1).map(() => ({code: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), title: faker.string.alpha({length: {min: 1, max: 100}})})), ...overrideResponse}) export const getGetSpecializationCatalogMockHandler = (overrideResponse?: SpecializationCatalog | ((info: Parameters[1]>[0]) => Promise | SpecializationCatalog), options?: RequestHandlerOptions) => { diff --git a/frontend/src/shared/api/endpoints/identity/identity.msw.ts b/frontend/src/shared/api/endpoints/identity/identity.msw.ts index 64d13fd..05749b9 100644 --- a/frontend/src/shared/api/endpoints/identity/identity.msw.ts +++ b/frontend/src/shared/api/endpoints/identity/identity.msw.ts @@ -8,6 +8,10 @@ import { faker } from '@faker-js/faker'; +import { + fakeFromPattern +} from '../../mock-pattern'; + import { HttpResponse, http @@ -16,11 +20,6 @@ import type { RequestHandlerOptions } from 'msw'; -import { - AccountScenario, - ConsentPurpose, - OnboardingStep -} from '../../schemas'; import type { Account, ConsentText, @@ -30,19 +29,19 @@ import type { } from '../../schemas'; -export const getGetConsentTextResponseMock = (overrideResponse: Partial> = {}): ConsentText => ({purpose: faker.helpers.arrayElement(Object.values(ConsentPurpose)), text_version: faker.helpers.fromRegExp("^[A-Za-z0-9._-]+$"), text: faker.string.alpha({length: {min: 1, max: 100000}}), published_at: faker.date.past().toISOString().slice(0, 19) + 'Z', ...overrideResponse}) +export const getGetConsentTextResponseMock = (overrideResponse: Partial> = {}): ConsentText => ({purpose: faker.helpers.arrayElement(['c1'] as const), text_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}), text: faker.string.alpha({length: {min: 1, max: 100000}}), published_at: faker.date.past().toISOString().slice(0, 19) + 'Z', ...overrideResponse}) export const getRegisterAccountResponseMock = (overrideResponse: Partial> = {}): IdentityRequestAccepted => ({status: faker.helpers.arrayElement(['accepted'] as const), ...overrideResponse}) export const getResendEmailVerificationResponseMock = (overrideResponse: Partial> = {}): IdentityRequestAccepted => ({status: faker.helpers.arrayElement(['accepted'] as const), ...overrideResponse}) -export const getConfirmEmailResponseMock = (overrideResponse: Partial> = {}): EmailVerificationResult => ({email_verified: faker.helpers.arrayElement([true] as const), scenario: faker.helpers.arrayElement(Object.values(AccountScenario)), onboarding_step: faker.helpers.arrayElement(Object.values(OnboardingStep)), ...overrideResponse}) +export const getConfirmEmailResponseMock = (overrideResponse: Partial> = {}): EmailVerificationResult => ({email_verified: faker.helpers.arrayElement([true] as const), scenario: faker.helpers.arrayElement(['candidate','employer'] as const), onboarding_step: faker.helpers.arrayElement(['candidate_consents','candidate_profile','candidate_questionnaire','candidate_assessment','employer_company','completed'] as const), ...overrideResponse}) -export const getLoginResponseMock = (overrideResponse: Partial> = {}): Session => ({account: {id: faker.string.uuid(), email: faker.internet.email(), email_verified: faker.datatype.boolean(), scenario: faker.helpers.arrayElement(Object.values(AccountScenario)), onboarding_step: faker.helpers.arrayElement(Object.values(OnboardingStep)), created_at: faker.date.past().toISOString().slice(0, 19) + 'Z'}, csrf_token: faker.helpers.fromRegExp("^[A-Za-z0-9_-]+$"), ...overrideResponse}) +export const getLoginResponseMock = (overrideResponse: Partial> = {}): Session => ({account: {id: faker.string.uuid(), email: faker.internet.email(), email_verified: faker.datatype.boolean(), scenario: faker.helpers.arrayElement(['candidate','employer'] as const), onboarding_step: faker.helpers.arrayElement(['candidate_consents','candidate_profile','candidate_questionnaire','candidate_assessment','employer_company','completed'] as const), created_at: faker.date.past().toISOString().slice(0, 19) + 'Z'}, csrf_token: fakeFromPattern("^[A-Za-z0-9_-]+$", {minLength: 32, maxLength: 128}), ...overrideResponse}) -export const getGetCurrentSessionResponseMock = (overrideResponse: Partial> = {}): Session => ({account: {id: faker.string.uuid(), email: faker.internet.email(), email_verified: faker.datatype.boolean(), scenario: faker.helpers.arrayElement(Object.values(AccountScenario)), onboarding_step: faker.helpers.arrayElement(Object.values(OnboardingStep)), created_at: faker.date.past().toISOString().slice(0, 19) + 'Z'}, csrf_token: faker.helpers.fromRegExp("^[A-Za-z0-9_-]+$"), ...overrideResponse}) +export const getGetCurrentSessionResponseMock = (overrideResponse: Partial> = {}): Session => ({account: {id: faker.string.uuid(), email: faker.internet.email(), email_verified: faker.datatype.boolean(), scenario: faker.helpers.arrayElement(['candidate','employer'] as const), onboarding_step: faker.helpers.arrayElement(['candidate_consents','candidate_profile','candidate_questionnaire','candidate_assessment','employer_company','completed'] as const), created_at: faker.date.past().toISOString().slice(0, 19) + 'Z'}, csrf_token: fakeFromPattern("^[A-Za-z0-9_-]+$", {minLength: 32, maxLength: 128}), ...overrideResponse}) -export const getGetCurrentAccountResponseMock = (overrideResponse: Partial> = {}): Account => ({id: faker.string.uuid(), email: faker.internet.email(), email_verified: faker.datatype.boolean(), scenario: faker.helpers.arrayElement(Object.values(AccountScenario)), onboarding_step: faker.helpers.arrayElement(Object.values(OnboardingStep)), created_at: faker.date.past().toISOString().slice(0, 19) + 'Z', ...overrideResponse}) +export const getGetCurrentAccountResponseMock = (overrideResponse: Partial> = {}): Account => ({id: faker.string.uuid(), email: faker.internet.email(), email_verified: faker.datatype.boolean(), scenario: faker.helpers.arrayElement(['candidate','employer'] as const), onboarding_step: faker.helpers.arrayElement(['candidate_consents','candidate_profile','candidate_questionnaire','candidate_assessment','employer_company','completed'] as const), created_at: faker.date.past().toISOString().slice(0, 19) + 'Z', ...overrideResponse}) export const getGetConsentTextMockHandler = (overrideResponse?: ConsentText | ((info: Parameters[1]>[0]) => Promise | ConsentText), options?: RequestHandlerOptions) => { diff --git a/frontend/src/shared/api/endpoints/need/need.msw.ts b/frontend/src/shared/api/endpoints/need/need.msw.ts index 5e2e8b4..9234b81 100644 --- a/frontend/src/shared/api/endpoints/need/need.msw.ts +++ b/frontend/src/shared/api/endpoints/need/need.msw.ts @@ -8,6 +8,10 @@ import { faker } from '@faker-js/faker'; +import { + fakeFromPattern +} from '../../mock-pattern'; + import { HttpResponse, http @@ -16,23 +20,6 @@ import type { RequestHandlerOptions } from 'msw'; -import { - CurrencyCode, - GradeCode, - NeedFieldName, - NeedItemStatus, - NeedMissingReason, - NeedMoneyStatus, - NeedReadinessStatus, - NeedRecommendationStatus, - NeedSupplyBand, - NeedValueOrigin, - NeedValueStatus, - SalaryPeriod, - SalaryTaxBasis, - SpecializationCode, - WorkFormat -} from '../../schemas'; import type { Need, NeedList, @@ -41,27 +28,27 @@ import type { } from '../../schemas'; -export const getListOrganizationNeedsResponseNeedValueSourceMock = (overrideResponse: Partial = {}): NeedValueSource => ({...{origin: faker.helpers.arrayElement(Object.values(NeedValueOrigin)), quote: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 300}}),null,]), extracted_in_version: faker.helpers.arrayElement([faker.number.int({min: 1}),null,]), extraction_version: faker.helpers.arrayElement([faker.helpers.fromRegExp("^[A-Za-z0-9._-]+$"),null,])}, ...overrideResponse}); +export const getListOrganizationNeedsResponseNeedValueSourceMock = (overrideResponse: Partial = {}): NeedValueSource => ({...{origin: faker.helpers.arrayElement(['manual','extracted_from_text','imported'] as const), quote: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 300}}),null,]), extracted_in_version: faker.helpers.arrayElement([faker.number.int({min: 1}),null,]), extraction_version: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}),null,])}, ...overrideResponse}); -export const getListOrganizationNeedsResponseMock = (overrideResponse: Partial> = {}): NeedList => ({items: Array.from({ length: faker.number.int({min: 1, max: 100}) }, (_, i) => i + 1).map(() => ({id: faker.string.uuid(), vacancy_id: faker.helpers.arrayElement([faker.string.uuid(), null]), title: faker.helpers.fromRegExp("^\\S(?:.*\\S)?$"), version: faker.number.int({min: 1}), specialization: {status: faker.helpers.arrayElement(Object.values(NeedValueStatus)), value: faker.helpers.arrayElement([faker.helpers.arrayElement(Object.values(SpecializationCode)),null,]), source: faker.helpers.arrayElement([{...getListOrganizationNeedsResponseNeedValueSourceMock()},null,])}, grade: {status: faker.helpers.arrayElement(Object.values(NeedValueStatus)), value: faker.helpers.arrayElement([faker.helpers.arrayElement(Object.values(GradeCode)),null,]), source: faker.helpers.arrayElement([{...getListOrganizationNeedsResponseNeedValueSourceMock()},null,])}, readiness: {status: faker.helpers.arrayElement(Object.values(NeedReadinessStatus)), missing_fields: Array.from({ length: faker.number.int({min: 1, max: 9}) }, (_, i) => i + 1).map(() => ({field: faker.helpers.arrayElement(Object.values(NeedFieldName)), reason: faker.helpers.arrayElement(Object.values(NeedMissingReason)), question: faker.string.alpha({length: {min: 1, max: 300}})}))}, created_at: faker.date.past().toISOString().slice(0, 19) + 'Z', updated_at: faker.date.past().toISOString().slice(0, 19) + 'Z'})), page: {has_more: faker.datatype.boolean(), next_cursor: faker.helpers.arrayElement([faker.helpers.fromRegExp("^[A-Za-z0-9_-]+$"), null])}, ...overrideResponse}) +export const getListOrganizationNeedsResponseMock = (overrideResponse: Partial> = {}): NeedList => ({items: Array.from({ length: faker.number.int({min: 1, max: 100}) }, (_, i) => i + 1).map(() => ({id: faker.string.uuid(), vacancy_id: faker.helpers.arrayElement([faker.string.uuid(), null]), title: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 200}), version: faker.number.int({min: 1}), specialization: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const),null,]), source: faker.helpers.arrayElement([{...getListOrganizationNeedsResponseNeedValueSourceMock()},null,])}, grade: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), source: faker.helpers.arrayElement([{...getListOrganizationNeedsResponseNeedValueSourceMock()},null,])}, readiness: {status: faker.helpers.arrayElement(['complete','incomplete'] as const), missing_fields: Array.from({ length: faker.number.int({min: 1, max: 9}) }, (_, i) => i + 1).map(() => ({field: faker.helpers.arrayElement(['specialization','grade','required_skills','desired_skills','tasks','domain','work_formats','location','salary'] as const), reason: faker.helpers.arrayElement(['unknown','unconfirmed'] as const), question: faker.string.alpha({length: {min: 1, max: 300}})}))}, created_at: faker.date.past().toISOString().slice(0, 19) + 'Z', updated_at: faker.date.past().toISOString().slice(0, 19) + 'Z'})), page: {has_more: faker.datatype.boolean(), next_cursor: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9_-]+$", {minLength: 1, maxLength: 512}), null])}, ...overrideResponse}) -export const getCreateOrganizationNeedResponseNeedValueSourceMock = (overrideResponse: Partial = {}): NeedValueSource => ({...{origin: faker.helpers.arrayElement(Object.values(NeedValueOrigin)), quote: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 300}}),null,]), extracted_in_version: faker.helpers.arrayElement([faker.number.int({min: 1}),null,]), extraction_version: faker.helpers.arrayElement([faker.helpers.fromRegExp("^[A-Za-z0-9._-]+$"),null,])}, ...overrideResponse}); +export const getCreateOrganizationNeedResponseNeedValueSourceMock = (overrideResponse: Partial = {}): NeedValueSource => ({...{origin: faker.helpers.arrayElement(['manual','extracted_from_text','imported'] as const), quote: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 300}}),null,]), extracted_in_version: faker.helpers.arrayElement([faker.number.int({min: 1}),null,]), extraction_version: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}),null,])}, ...overrideResponse}); -export const getCreateOrganizationNeedResponseSalaryRangeMock = (overrideResponse: Partial = {}): SalaryRange => ({...{salary_from: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), salary_to: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), currency: faker.helpers.arrayElement(Object.values(CurrencyCode)), period: faker.helpers.arrayElement(Object.values(SalaryPeriod)), tax_basis: faker.helpers.arrayElement(Object.values(SalaryTaxBasis))}, ...overrideResponse}); +export const getCreateOrganizationNeedResponseSalaryRangeMock = (overrideResponse: Partial = {}): SalaryRange => ({...{salary_from: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), salary_to: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), currency: faker.helpers.arrayElement(['RUB'] as const), period: faker.helpers.arrayElement(['month'] as const), tax_basis: faker.helpers.arrayElement(['net','gross'] as const)}, ...overrideResponse}); -export const getCreateOrganizationNeedResponseMock = (overrideResponse: Partial> = {}): Need => ({id: faker.string.uuid(), organization_id: faker.string.uuid(), vacancy_id: faker.helpers.arrayElement([faker.string.uuid(), null]), title: faker.helpers.fromRegExp("^\\S(?:.*\\S)?$"), source_text: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 10000}}),null,]), version: faker.number.int({min: 1}), requirements_version: faker.number.int({min: 1}), requirements: {specialization: {status: faker.helpers.arrayElement(Object.values(NeedValueStatus)), value: faker.helpers.arrayElement([faker.helpers.arrayElement(Object.values(SpecializationCode)),null,]), source: faker.helpers.arrayElement([{...getCreateOrganizationNeedResponseNeedValueSourceMock()},null,])}, grade: {status: faker.helpers.arrayElement(Object.values(NeedValueStatus)), value: faker.helpers.arrayElement([faker.helpers.arrayElement(Object.values(GradeCode)),null,]), source: faker.helpers.arrayElement([{...getCreateOrganizationNeedResponseNeedValueSourceMock()},null,])}, required_skills: Array.from({ length: faker.number.int({min: 1, max: 30}) }, (_, i) => i + 1).map(() => ({name: faker.helpers.fromRegExp("^\\S(?:.*\\S)?$"), taxonomy_code: faker.helpers.arrayElement([faker.helpers.fromRegExp("^[a-z0-9][a-z0-9_.+#-]*$"),null,]), status: faker.helpers.arrayElement(Object.values(NeedItemStatus)), source: {origin: faker.helpers.arrayElement(Object.values(NeedValueOrigin)), quote: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 300}}),null,]), extracted_in_version: faker.helpers.arrayElement([faker.number.int({min: 1}),null,]), extraction_version: faker.helpers.arrayElement([faker.helpers.fromRegExp("^[A-Za-z0-9._-]+$"),null,])}})), desired_skills: Array.from({ length: faker.number.int({min: 1, max: 30}) }, (_, i) => i + 1).map(() => ({name: faker.helpers.fromRegExp("^\\S(?:.*\\S)?$"), taxonomy_code: faker.helpers.arrayElement([faker.helpers.fromRegExp("^[a-z0-9][a-z0-9_.+#-]*$"),null,]), status: faker.helpers.arrayElement(Object.values(NeedItemStatus)), source: {origin: faker.helpers.arrayElement(Object.values(NeedValueOrigin)), quote: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 300}}),null,]), extracted_in_version: faker.helpers.arrayElement([faker.number.int({min: 1}),null,]), extraction_version: faker.helpers.arrayElement([faker.helpers.fromRegExp("^[A-Za-z0-9._-]+$"),null,])}})), tasks: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => ({text: faker.helpers.fromRegExp("^\\S(?:.*\\S)?$"), status: faker.helpers.arrayElement(Object.values(NeedItemStatus)), source: {origin: faker.helpers.arrayElement(Object.values(NeedValueOrigin)), quote: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 300}}),null,]), extracted_in_version: faker.helpers.arrayElement([faker.number.int({min: 1}),null,]), extraction_version: faker.helpers.arrayElement([faker.helpers.fromRegExp("^[A-Za-z0-9._-]+$"),null,])}})), domain: {status: faker.helpers.arrayElement(Object.values(NeedValueStatus)), value: faker.helpers.arrayElement([faker.helpers.fromRegExp("^\\S(?:.*\\S)?$"),null,]), source: faker.helpers.arrayElement([{...getCreateOrganizationNeedResponseNeedValueSourceMock()},null,])}, work_formats: {status: faker.helpers.arrayElement(Object.values(NeedValueStatus)), value: faker.helpers.arrayElement([faker.helpers.arrayElements(Object.values(WorkFormat)), null]), source: faker.helpers.arrayElement([{...getCreateOrganizationNeedResponseNeedValueSourceMock()},null,])}, location: {status: faker.helpers.arrayElement(Object.values(NeedValueStatus)), value: faker.helpers.arrayElement([faker.helpers.fromRegExp("^\\S(?:.*\\S)?$"),null,]), source: faker.helpers.arrayElement([{...getCreateOrganizationNeedResponseNeedValueSourceMock()},null,])}, salary: {status: faker.helpers.arrayElement(Object.values(NeedValueStatus)), value: faker.helpers.arrayElement([{...getCreateOrganizationNeedResponseSalaryRangeMock()},null,]), source: faker.helpers.arrayElement([{...getCreateOrganizationNeedResponseNeedValueSourceMock()},null,])}}, readiness: {status: faker.helpers.arrayElement(Object.values(NeedReadinessStatus)), missing_fields: Array.from({ length: faker.number.int({min: 1, max: 9}) }, (_, i) => i + 1).map(() => ({field: faker.helpers.arrayElement(Object.values(NeedFieldName)), reason: faker.helpers.arrayElement(Object.values(NeedMissingReason)), question: faker.string.alpha({length: {min: 1, max: 300}})}))}, recommendations: {status: faker.helpers.arrayElement(Object.values(NeedRecommendationStatus)), requirements_version: faker.number.int({min: 1}), policy_version: faker.helpers.arrayElement([faker.number.int({min: 1}), null]), algorithm_version: faker.helpers.arrayElement([faker.helpers.fromRegExp("^[A-Za-z0-9._-]+$"),null,]), computed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), categories: Array.from({ length: faker.number.int({min: 1, max: 10}) }, (_, i) => i + 1).map(() => ({specialization: faker.helpers.arrayElement(Object.values(SpecializationCode)), grade: faker.helpers.arrayElement(Object.values(GradeCode)), score: faker.helpers.arrayElement([faker.number.float({min: 0, max: 1, fractionDigits: 2}), null]), skill_overlap: {share: faker.number.float({min: 0, max: 1, fractionDigits: 2}), covered_skills: Array.from({ length: faker.number.int({min: 1, max: 60}) }, (_, i) => i + 1).map(() => (faker.helpers.fromRegExp("^\\S(?:.*\\S)?$"))), uncovered_skills: Array.from({ length: faker.number.int({min: 1, max: 60}) }, (_, i) => i + 1).map(() => (faker.helpers.fromRegExp("^\\S(?:.*\\S)?$")))}, money: {status: faker.helpers.arrayElement(Object.values(NeedMoneyStatus)), share: faker.helpers.arrayElement([faker.number.float({min: 0, max: 1, fractionDigits: 2}), null])}, supply: faker.helpers.arrayElement(Object.values(NeedSupplyBand))}))}, created_at: faker.date.past().toISOString().slice(0, 19) + 'Z', updated_at: faker.date.past().toISOString().slice(0, 19) + 'Z', ...overrideResponse}) +export const getCreateOrganizationNeedResponseMock = (overrideResponse: Partial> = {}): Need => ({id: faker.string.uuid(), organization_id: faker.string.uuid(), vacancy_id: faker.helpers.arrayElement([faker.string.uuid(), null]), title: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 200}), source_text: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 10000}}),null,]), version: faker.number.int({min: 1}), requirements_version: faker.number.int({min: 1}), requirements: {specialization: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const),null,]), source: faker.helpers.arrayElement([{...getCreateOrganizationNeedResponseNeedValueSourceMock()},null,])}, grade: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), source: faker.helpers.arrayElement([{...getCreateOrganizationNeedResponseNeedValueSourceMock()},null,])}, required_skills: Array.from({ length: faker.number.int({min: 1, max: 30}) }, (_, i) => i + 1).map(() => ({name: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}), taxonomy_code: faker.helpers.arrayElement([fakeFromPattern("^[a-z0-9][a-z0-9_.+#-]*$", {minLength: 1, maxLength: 64}),null,]), status: faker.helpers.arrayElement(['confirmed','extracted'] as const), source: {origin: faker.helpers.arrayElement(['manual','extracted_from_text','imported'] as const), quote: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 300}}),null,]), extracted_in_version: faker.helpers.arrayElement([faker.number.int({min: 1}),null,]), extraction_version: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}),null,])}})), desired_skills: Array.from({ length: faker.number.int({min: 1, max: 30}) }, (_, i) => i + 1).map(() => ({name: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}), taxonomy_code: faker.helpers.arrayElement([fakeFromPattern("^[a-z0-9][a-z0-9_.+#-]*$", {minLength: 1, maxLength: 64}),null,]), status: faker.helpers.arrayElement(['confirmed','extracted'] as const), source: {origin: faker.helpers.arrayElement(['manual','extracted_from_text','imported'] as const), quote: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 300}}),null,]), extracted_in_version: faker.helpers.arrayElement([faker.number.int({min: 1}),null,]), extraction_version: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}),null,])}})), tasks: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => ({text: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300}), status: faker.helpers.arrayElement(['confirmed','extracted'] as const), source: {origin: faker.helpers.arrayElement(['manual','extracted_from_text','imported'] as const), quote: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 300}}),null,]), extracted_in_version: faker.helpers.arrayElement([faker.number.int({min: 1}),null,]), extraction_version: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}),null,])}})), domain: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}),null,]), source: faker.helpers.arrayElement([{...getCreateOrganizationNeedResponseNeedValueSourceMock()},null,])}, work_formats: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([faker.helpers.arrayElements(['remote','office','hybrid'] as const), null]), source: faker.helpers.arrayElement([{...getCreateOrganizationNeedResponseNeedValueSourceMock()},null,])}, location: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}),null,]), source: faker.helpers.arrayElement([{...getCreateOrganizationNeedResponseNeedValueSourceMock()},null,])}, salary: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([{...getCreateOrganizationNeedResponseSalaryRangeMock()},null,]), source: faker.helpers.arrayElement([{...getCreateOrganizationNeedResponseNeedValueSourceMock()},null,])}}, readiness: {status: faker.helpers.arrayElement(['complete','incomplete'] as const), missing_fields: Array.from({ length: faker.number.int({min: 1, max: 9}) }, (_, i) => i + 1).map(() => ({field: faker.helpers.arrayElement(['specialization','grade','required_skills','desired_skills','tasks','domain','work_formats','location','salary'] as const), reason: faker.helpers.arrayElement(['unknown','unconfirmed'] as const), question: faker.string.alpha({length: {min: 1, max: 300}})}))}, recommendations: {status: faker.helpers.arrayElement(['computed','pending','not_available'] as const), requirements_version: faker.number.int({min: 1}), policy_version: faker.helpers.arrayElement([faker.number.int({min: 1}), null]), algorithm_version: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}),null,]), computed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), categories: Array.from({ length: faker.number.int({min: 1, max: 10}) }, (_, i) => i + 1).map(() => ({specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), score: faker.helpers.arrayElement([faker.number.float({min: 0, max: 1, fractionDigits: 2}), null]), skill_overlap: {share: faker.number.float({min: 0, max: 1, fractionDigits: 2}), covered_skills: Array.from({ length: faker.number.int({min: 1, max: 60}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}))), uncovered_skills: Array.from({ length: faker.number.int({min: 1, max: 60}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100})))}, money: {status: faker.helpers.arrayElement(['computed','insufficient_data','no_salary','withheld'] as const), share: faker.helpers.arrayElement([faker.number.float({min: 0, max: 1, fractionDigits: 2}), null])}, supply: faker.helpers.arrayElement(['fewer_than_5','from_5_to_29','30_or_more'] as const)}))}, created_at: faker.date.past().toISOString().slice(0, 19) + 'Z', updated_at: faker.date.past().toISOString().slice(0, 19) + 'Z', ...overrideResponse}) -export const getGetOrganizationNeedResponseNeedValueSourceMock = (overrideResponse: Partial = {}): NeedValueSource => ({...{origin: faker.helpers.arrayElement(Object.values(NeedValueOrigin)), quote: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 300}}),null,]), extracted_in_version: faker.helpers.arrayElement([faker.number.int({min: 1}),null,]), extraction_version: faker.helpers.arrayElement([faker.helpers.fromRegExp("^[A-Za-z0-9._-]+$"),null,])}, ...overrideResponse}); +export const getGetOrganizationNeedResponseNeedValueSourceMock = (overrideResponse: Partial = {}): NeedValueSource => ({...{origin: faker.helpers.arrayElement(['manual','extracted_from_text','imported'] as const), quote: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 300}}),null,]), extracted_in_version: faker.helpers.arrayElement([faker.number.int({min: 1}),null,]), extraction_version: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}),null,])}, ...overrideResponse}); -export const getGetOrganizationNeedResponseSalaryRangeMock = (overrideResponse: Partial = {}): SalaryRange => ({...{salary_from: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), salary_to: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), currency: faker.helpers.arrayElement(Object.values(CurrencyCode)), period: faker.helpers.arrayElement(Object.values(SalaryPeriod)), tax_basis: faker.helpers.arrayElement(Object.values(SalaryTaxBasis))}, ...overrideResponse}); +export const getGetOrganizationNeedResponseSalaryRangeMock = (overrideResponse: Partial = {}): SalaryRange => ({...{salary_from: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), salary_to: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), currency: faker.helpers.arrayElement(['RUB'] as const), period: faker.helpers.arrayElement(['month'] as const), tax_basis: faker.helpers.arrayElement(['net','gross'] as const)}, ...overrideResponse}); -export const getGetOrganizationNeedResponseMock = (overrideResponse: Partial> = {}): Need => ({id: faker.string.uuid(), organization_id: faker.string.uuid(), vacancy_id: faker.helpers.arrayElement([faker.string.uuid(), null]), title: faker.helpers.fromRegExp("^\\S(?:.*\\S)?$"), source_text: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 10000}}),null,]), version: faker.number.int({min: 1}), requirements_version: faker.number.int({min: 1}), requirements: {specialization: {status: faker.helpers.arrayElement(Object.values(NeedValueStatus)), value: faker.helpers.arrayElement([faker.helpers.arrayElement(Object.values(SpecializationCode)),null,]), source: faker.helpers.arrayElement([{...getGetOrganizationNeedResponseNeedValueSourceMock()},null,])}, grade: {status: faker.helpers.arrayElement(Object.values(NeedValueStatus)), value: faker.helpers.arrayElement([faker.helpers.arrayElement(Object.values(GradeCode)),null,]), source: faker.helpers.arrayElement([{...getGetOrganizationNeedResponseNeedValueSourceMock()},null,])}, required_skills: Array.from({ length: faker.number.int({min: 1, max: 30}) }, (_, i) => i + 1).map(() => ({name: faker.helpers.fromRegExp("^\\S(?:.*\\S)?$"), taxonomy_code: faker.helpers.arrayElement([faker.helpers.fromRegExp("^[a-z0-9][a-z0-9_.+#-]*$"),null,]), status: faker.helpers.arrayElement(Object.values(NeedItemStatus)), source: {origin: faker.helpers.arrayElement(Object.values(NeedValueOrigin)), quote: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 300}}),null,]), extracted_in_version: faker.helpers.arrayElement([faker.number.int({min: 1}),null,]), extraction_version: faker.helpers.arrayElement([faker.helpers.fromRegExp("^[A-Za-z0-9._-]+$"),null,])}})), desired_skills: Array.from({ length: faker.number.int({min: 1, max: 30}) }, (_, i) => i + 1).map(() => ({name: faker.helpers.fromRegExp("^\\S(?:.*\\S)?$"), taxonomy_code: faker.helpers.arrayElement([faker.helpers.fromRegExp("^[a-z0-9][a-z0-9_.+#-]*$"),null,]), status: faker.helpers.arrayElement(Object.values(NeedItemStatus)), source: {origin: faker.helpers.arrayElement(Object.values(NeedValueOrigin)), quote: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 300}}),null,]), extracted_in_version: faker.helpers.arrayElement([faker.number.int({min: 1}),null,]), extraction_version: faker.helpers.arrayElement([faker.helpers.fromRegExp("^[A-Za-z0-9._-]+$"),null,])}})), tasks: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => ({text: faker.helpers.fromRegExp("^\\S(?:.*\\S)?$"), status: faker.helpers.arrayElement(Object.values(NeedItemStatus)), source: {origin: faker.helpers.arrayElement(Object.values(NeedValueOrigin)), quote: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 300}}),null,]), extracted_in_version: faker.helpers.arrayElement([faker.number.int({min: 1}),null,]), extraction_version: faker.helpers.arrayElement([faker.helpers.fromRegExp("^[A-Za-z0-9._-]+$"),null,])}})), domain: {status: faker.helpers.arrayElement(Object.values(NeedValueStatus)), value: faker.helpers.arrayElement([faker.helpers.fromRegExp("^\\S(?:.*\\S)?$"),null,]), source: faker.helpers.arrayElement([{...getGetOrganizationNeedResponseNeedValueSourceMock()},null,])}, work_formats: {status: faker.helpers.arrayElement(Object.values(NeedValueStatus)), value: faker.helpers.arrayElement([faker.helpers.arrayElements(Object.values(WorkFormat)), null]), source: faker.helpers.arrayElement([{...getGetOrganizationNeedResponseNeedValueSourceMock()},null,])}, location: {status: faker.helpers.arrayElement(Object.values(NeedValueStatus)), value: faker.helpers.arrayElement([faker.helpers.fromRegExp("^\\S(?:.*\\S)?$"),null,]), source: faker.helpers.arrayElement([{...getGetOrganizationNeedResponseNeedValueSourceMock()},null,])}, salary: {status: faker.helpers.arrayElement(Object.values(NeedValueStatus)), value: faker.helpers.arrayElement([{...getGetOrganizationNeedResponseSalaryRangeMock()},null,]), source: faker.helpers.arrayElement([{...getGetOrganizationNeedResponseNeedValueSourceMock()},null,])}}, readiness: {status: faker.helpers.arrayElement(Object.values(NeedReadinessStatus)), missing_fields: Array.from({ length: faker.number.int({min: 1, max: 9}) }, (_, i) => i + 1).map(() => ({field: faker.helpers.arrayElement(Object.values(NeedFieldName)), reason: faker.helpers.arrayElement(Object.values(NeedMissingReason)), question: faker.string.alpha({length: {min: 1, max: 300}})}))}, recommendations: {status: faker.helpers.arrayElement(Object.values(NeedRecommendationStatus)), requirements_version: faker.number.int({min: 1}), policy_version: faker.helpers.arrayElement([faker.number.int({min: 1}), null]), algorithm_version: faker.helpers.arrayElement([faker.helpers.fromRegExp("^[A-Za-z0-9._-]+$"),null,]), computed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), categories: Array.from({ length: faker.number.int({min: 1, max: 10}) }, (_, i) => i + 1).map(() => ({specialization: faker.helpers.arrayElement(Object.values(SpecializationCode)), grade: faker.helpers.arrayElement(Object.values(GradeCode)), score: faker.helpers.arrayElement([faker.number.float({min: 0, max: 1, fractionDigits: 2}), null]), skill_overlap: {share: faker.number.float({min: 0, max: 1, fractionDigits: 2}), covered_skills: Array.from({ length: faker.number.int({min: 1, max: 60}) }, (_, i) => i + 1).map(() => (faker.helpers.fromRegExp("^\\S(?:.*\\S)?$"))), uncovered_skills: Array.from({ length: faker.number.int({min: 1, max: 60}) }, (_, i) => i + 1).map(() => (faker.helpers.fromRegExp("^\\S(?:.*\\S)?$")))}, money: {status: faker.helpers.arrayElement(Object.values(NeedMoneyStatus)), share: faker.helpers.arrayElement([faker.number.float({min: 0, max: 1, fractionDigits: 2}), null])}, supply: faker.helpers.arrayElement(Object.values(NeedSupplyBand))}))}, created_at: faker.date.past().toISOString().slice(0, 19) + 'Z', updated_at: faker.date.past().toISOString().slice(0, 19) + 'Z', ...overrideResponse}) +export const getGetOrganizationNeedResponseMock = (overrideResponse: Partial> = {}): Need => ({id: faker.string.uuid(), organization_id: faker.string.uuid(), vacancy_id: faker.helpers.arrayElement([faker.string.uuid(), null]), title: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 200}), source_text: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 10000}}),null,]), version: faker.number.int({min: 1}), requirements_version: faker.number.int({min: 1}), requirements: {specialization: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const),null,]), source: faker.helpers.arrayElement([{...getGetOrganizationNeedResponseNeedValueSourceMock()},null,])}, grade: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), source: faker.helpers.arrayElement([{...getGetOrganizationNeedResponseNeedValueSourceMock()},null,])}, required_skills: Array.from({ length: faker.number.int({min: 1, max: 30}) }, (_, i) => i + 1).map(() => ({name: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}), taxonomy_code: faker.helpers.arrayElement([fakeFromPattern("^[a-z0-9][a-z0-9_.+#-]*$", {minLength: 1, maxLength: 64}),null,]), status: faker.helpers.arrayElement(['confirmed','extracted'] as const), source: {origin: faker.helpers.arrayElement(['manual','extracted_from_text','imported'] as const), quote: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 300}}),null,]), extracted_in_version: faker.helpers.arrayElement([faker.number.int({min: 1}),null,]), extraction_version: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}),null,])}})), desired_skills: Array.from({ length: faker.number.int({min: 1, max: 30}) }, (_, i) => i + 1).map(() => ({name: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}), taxonomy_code: faker.helpers.arrayElement([fakeFromPattern("^[a-z0-9][a-z0-9_.+#-]*$", {minLength: 1, maxLength: 64}),null,]), status: faker.helpers.arrayElement(['confirmed','extracted'] as const), source: {origin: faker.helpers.arrayElement(['manual','extracted_from_text','imported'] as const), quote: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 300}}),null,]), extracted_in_version: faker.helpers.arrayElement([faker.number.int({min: 1}),null,]), extraction_version: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}),null,])}})), tasks: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => ({text: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300}), status: faker.helpers.arrayElement(['confirmed','extracted'] as const), source: {origin: faker.helpers.arrayElement(['manual','extracted_from_text','imported'] as const), quote: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 300}}),null,]), extracted_in_version: faker.helpers.arrayElement([faker.number.int({min: 1}),null,]), extraction_version: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}),null,])}})), domain: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}),null,]), source: faker.helpers.arrayElement([{...getGetOrganizationNeedResponseNeedValueSourceMock()},null,])}, work_formats: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([faker.helpers.arrayElements(['remote','office','hybrid'] as const), null]), source: faker.helpers.arrayElement([{...getGetOrganizationNeedResponseNeedValueSourceMock()},null,])}, location: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}),null,]), source: faker.helpers.arrayElement([{...getGetOrganizationNeedResponseNeedValueSourceMock()},null,])}, salary: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([{...getGetOrganizationNeedResponseSalaryRangeMock()},null,]), source: faker.helpers.arrayElement([{...getGetOrganizationNeedResponseNeedValueSourceMock()},null,])}}, readiness: {status: faker.helpers.arrayElement(['complete','incomplete'] as const), missing_fields: Array.from({ length: faker.number.int({min: 1, max: 9}) }, (_, i) => i + 1).map(() => ({field: faker.helpers.arrayElement(['specialization','grade','required_skills','desired_skills','tasks','domain','work_formats','location','salary'] as const), reason: faker.helpers.arrayElement(['unknown','unconfirmed'] as const), question: faker.string.alpha({length: {min: 1, max: 300}})}))}, recommendations: {status: faker.helpers.arrayElement(['computed','pending','not_available'] as const), requirements_version: faker.number.int({min: 1}), policy_version: faker.helpers.arrayElement([faker.number.int({min: 1}), null]), algorithm_version: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}),null,]), computed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), categories: Array.from({ length: faker.number.int({min: 1, max: 10}) }, (_, i) => i + 1).map(() => ({specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), score: faker.helpers.arrayElement([faker.number.float({min: 0, max: 1, fractionDigits: 2}), null]), skill_overlap: {share: faker.number.float({min: 0, max: 1, fractionDigits: 2}), covered_skills: Array.from({ length: faker.number.int({min: 1, max: 60}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}))), uncovered_skills: Array.from({ length: faker.number.int({min: 1, max: 60}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100})))}, money: {status: faker.helpers.arrayElement(['computed','insufficient_data','no_salary','withheld'] as const), share: faker.helpers.arrayElement([faker.number.float({min: 0, max: 1, fractionDigits: 2}), null])}, supply: faker.helpers.arrayElement(['fewer_than_5','from_5_to_29','30_or_more'] as const)}))}, created_at: faker.date.past().toISOString().slice(0, 19) + 'Z', updated_at: faker.date.past().toISOString().slice(0, 19) + 'Z', ...overrideResponse}) -export const getUpdateOrganizationNeedResponseNeedValueSourceMock = (overrideResponse: Partial = {}): NeedValueSource => ({...{origin: faker.helpers.arrayElement(Object.values(NeedValueOrigin)), quote: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 300}}),null,]), extracted_in_version: faker.helpers.arrayElement([faker.number.int({min: 1}),null,]), extraction_version: faker.helpers.arrayElement([faker.helpers.fromRegExp("^[A-Za-z0-9._-]+$"),null,])}, ...overrideResponse}); +export const getUpdateOrganizationNeedResponseNeedValueSourceMock = (overrideResponse: Partial = {}): NeedValueSource => ({...{origin: faker.helpers.arrayElement(['manual','extracted_from_text','imported'] as const), quote: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 300}}),null,]), extracted_in_version: faker.helpers.arrayElement([faker.number.int({min: 1}),null,]), extraction_version: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}),null,])}, ...overrideResponse}); -export const getUpdateOrganizationNeedResponseSalaryRangeMock = (overrideResponse: Partial = {}): SalaryRange => ({...{salary_from: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), salary_to: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), currency: faker.helpers.arrayElement(Object.values(CurrencyCode)), period: faker.helpers.arrayElement(Object.values(SalaryPeriod)), tax_basis: faker.helpers.arrayElement(Object.values(SalaryTaxBasis))}, ...overrideResponse}); +export const getUpdateOrganizationNeedResponseSalaryRangeMock = (overrideResponse: Partial = {}): SalaryRange => ({...{salary_from: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), salary_to: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), currency: faker.helpers.arrayElement(['RUB'] as const), period: faker.helpers.arrayElement(['month'] as const), tax_basis: faker.helpers.arrayElement(['net','gross'] as const)}, ...overrideResponse}); -export const getUpdateOrganizationNeedResponseMock = (overrideResponse: Partial> = {}): Need => ({id: faker.string.uuid(), organization_id: faker.string.uuid(), vacancy_id: faker.helpers.arrayElement([faker.string.uuid(), null]), title: faker.helpers.fromRegExp("^\\S(?:.*\\S)?$"), source_text: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 10000}}),null,]), version: faker.number.int({min: 1}), requirements_version: faker.number.int({min: 1}), requirements: {specialization: {status: faker.helpers.arrayElement(Object.values(NeedValueStatus)), value: faker.helpers.arrayElement([faker.helpers.arrayElement(Object.values(SpecializationCode)),null,]), source: faker.helpers.arrayElement([{...getUpdateOrganizationNeedResponseNeedValueSourceMock()},null,])}, grade: {status: faker.helpers.arrayElement(Object.values(NeedValueStatus)), value: faker.helpers.arrayElement([faker.helpers.arrayElement(Object.values(GradeCode)),null,]), source: faker.helpers.arrayElement([{...getUpdateOrganizationNeedResponseNeedValueSourceMock()},null,])}, required_skills: Array.from({ length: faker.number.int({min: 1, max: 30}) }, (_, i) => i + 1).map(() => ({name: faker.helpers.fromRegExp("^\\S(?:.*\\S)?$"), taxonomy_code: faker.helpers.arrayElement([faker.helpers.fromRegExp("^[a-z0-9][a-z0-9_.+#-]*$"),null,]), status: faker.helpers.arrayElement(Object.values(NeedItemStatus)), source: {origin: faker.helpers.arrayElement(Object.values(NeedValueOrigin)), quote: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 300}}),null,]), extracted_in_version: faker.helpers.arrayElement([faker.number.int({min: 1}),null,]), extraction_version: faker.helpers.arrayElement([faker.helpers.fromRegExp("^[A-Za-z0-9._-]+$"),null,])}})), desired_skills: Array.from({ length: faker.number.int({min: 1, max: 30}) }, (_, i) => i + 1).map(() => ({name: faker.helpers.fromRegExp("^\\S(?:.*\\S)?$"), taxonomy_code: faker.helpers.arrayElement([faker.helpers.fromRegExp("^[a-z0-9][a-z0-9_.+#-]*$"),null,]), status: faker.helpers.arrayElement(Object.values(NeedItemStatus)), source: {origin: faker.helpers.arrayElement(Object.values(NeedValueOrigin)), quote: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 300}}),null,]), extracted_in_version: faker.helpers.arrayElement([faker.number.int({min: 1}),null,]), extraction_version: faker.helpers.arrayElement([faker.helpers.fromRegExp("^[A-Za-z0-9._-]+$"),null,])}})), tasks: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => ({text: faker.helpers.fromRegExp("^\\S(?:.*\\S)?$"), status: faker.helpers.arrayElement(Object.values(NeedItemStatus)), source: {origin: faker.helpers.arrayElement(Object.values(NeedValueOrigin)), quote: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 300}}),null,]), extracted_in_version: faker.helpers.arrayElement([faker.number.int({min: 1}),null,]), extraction_version: faker.helpers.arrayElement([faker.helpers.fromRegExp("^[A-Za-z0-9._-]+$"),null,])}})), domain: {status: faker.helpers.arrayElement(Object.values(NeedValueStatus)), value: faker.helpers.arrayElement([faker.helpers.fromRegExp("^\\S(?:.*\\S)?$"),null,]), source: faker.helpers.arrayElement([{...getUpdateOrganizationNeedResponseNeedValueSourceMock()},null,])}, work_formats: {status: faker.helpers.arrayElement(Object.values(NeedValueStatus)), value: faker.helpers.arrayElement([faker.helpers.arrayElements(Object.values(WorkFormat)), null]), source: faker.helpers.arrayElement([{...getUpdateOrganizationNeedResponseNeedValueSourceMock()},null,])}, location: {status: faker.helpers.arrayElement(Object.values(NeedValueStatus)), value: faker.helpers.arrayElement([faker.helpers.fromRegExp("^\\S(?:.*\\S)?$"),null,]), source: faker.helpers.arrayElement([{...getUpdateOrganizationNeedResponseNeedValueSourceMock()},null,])}, salary: {status: faker.helpers.arrayElement(Object.values(NeedValueStatus)), value: faker.helpers.arrayElement([{...getUpdateOrganizationNeedResponseSalaryRangeMock()},null,]), source: faker.helpers.arrayElement([{...getUpdateOrganizationNeedResponseNeedValueSourceMock()},null,])}}, readiness: {status: faker.helpers.arrayElement(Object.values(NeedReadinessStatus)), missing_fields: Array.from({ length: faker.number.int({min: 1, max: 9}) }, (_, i) => i + 1).map(() => ({field: faker.helpers.arrayElement(Object.values(NeedFieldName)), reason: faker.helpers.arrayElement(Object.values(NeedMissingReason)), question: faker.string.alpha({length: {min: 1, max: 300}})}))}, recommendations: {status: faker.helpers.arrayElement(Object.values(NeedRecommendationStatus)), requirements_version: faker.number.int({min: 1}), policy_version: faker.helpers.arrayElement([faker.number.int({min: 1}), null]), algorithm_version: faker.helpers.arrayElement([faker.helpers.fromRegExp("^[A-Za-z0-9._-]+$"),null,]), computed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), categories: Array.from({ length: faker.number.int({min: 1, max: 10}) }, (_, i) => i + 1).map(() => ({specialization: faker.helpers.arrayElement(Object.values(SpecializationCode)), grade: faker.helpers.arrayElement(Object.values(GradeCode)), score: faker.helpers.arrayElement([faker.number.float({min: 0, max: 1, fractionDigits: 2}), null]), skill_overlap: {share: faker.number.float({min: 0, max: 1, fractionDigits: 2}), covered_skills: Array.from({ length: faker.number.int({min: 1, max: 60}) }, (_, i) => i + 1).map(() => (faker.helpers.fromRegExp("^\\S(?:.*\\S)?$"))), uncovered_skills: Array.from({ length: faker.number.int({min: 1, max: 60}) }, (_, i) => i + 1).map(() => (faker.helpers.fromRegExp("^\\S(?:.*\\S)?$")))}, money: {status: faker.helpers.arrayElement(Object.values(NeedMoneyStatus)), share: faker.helpers.arrayElement([faker.number.float({min: 0, max: 1, fractionDigits: 2}), null])}, supply: faker.helpers.arrayElement(Object.values(NeedSupplyBand))}))}, created_at: faker.date.past().toISOString().slice(0, 19) + 'Z', updated_at: faker.date.past().toISOString().slice(0, 19) + 'Z', ...overrideResponse}) +export const getUpdateOrganizationNeedResponseMock = (overrideResponse: Partial> = {}): Need => ({id: faker.string.uuid(), organization_id: faker.string.uuid(), vacancy_id: faker.helpers.arrayElement([faker.string.uuid(), null]), title: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 200}), source_text: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 10000}}),null,]), version: faker.number.int({min: 1}), requirements_version: faker.number.int({min: 1}), requirements: {specialization: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const),null,]), source: faker.helpers.arrayElement([{...getUpdateOrganizationNeedResponseNeedValueSourceMock()},null,])}, grade: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), source: faker.helpers.arrayElement([{...getUpdateOrganizationNeedResponseNeedValueSourceMock()},null,])}, required_skills: Array.from({ length: faker.number.int({min: 1, max: 30}) }, (_, i) => i + 1).map(() => ({name: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}), taxonomy_code: faker.helpers.arrayElement([fakeFromPattern("^[a-z0-9][a-z0-9_.+#-]*$", {minLength: 1, maxLength: 64}),null,]), status: faker.helpers.arrayElement(['confirmed','extracted'] as const), source: {origin: faker.helpers.arrayElement(['manual','extracted_from_text','imported'] as const), quote: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 300}}),null,]), extracted_in_version: faker.helpers.arrayElement([faker.number.int({min: 1}),null,]), extraction_version: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}),null,])}})), desired_skills: Array.from({ length: faker.number.int({min: 1, max: 30}) }, (_, i) => i + 1).map(() => ({name: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}), taxonomy_code: faker.helpers.arrayElement([fakeFromPattern("^[a-z0-9][a-z0-9_.+#-]*$", {minLength: 1, maxLength: 64}),null,]), status: faker.helpers.arrayElement(['confirmed','extracted'] as const), source: {origin: faker.helpers.arrayElement(['manual','extracted_from_text','imported'] as const), quote: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 300}}),null,]), extracted_in_version: faker.helpers.arrayElement([faker.number.int({min: 1}),null,]), extraction_version: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}),null,])}})), tasks: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => ({text: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300}), status: faker.helpers.arrayElement(['confirmed','extracted'] as const), source: {origin: faker.helpers.arrayElement(['manual','extracted_from_text','imported'] as const), quote: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 300}}),null,]), extracted_in_version: faker.helpers.arrayElement([faker.number.int({min: 1}),null,]), extraction_version: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}),null,])}})), domain: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}),null,]), source: faker.helpers.arrayElement([{...getUpdateOrganizationNeedResponseNeedValueSourceMock()},null,])}, work_formats: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([faker.helpers.arrayElements(['remote','office','hybrid'] as const), null]), source: faker.helpers.arrayElement([{...getUpdateOrganizationNeedResponseNeedValueSourceMock()},null,])}, location: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}),null,]), source: faker.helpers.arrayElement([{...getUpdateOrganizationNeedResponseNeedValueSourceMock()},null,])}, salary: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([{...getUpdateOrganizationNeedResponseSalaryRangeMock()},null,]), source: faker.helpers.arrayElement([{...getUpdateOrganizationNeedResponseNeedValueSourceMock()},null,])}}, readiness: {status: faker.helpers.arrayElement(['complete','incomplete'] as const), missing_fields: Array.from({ length: faker.number.int({min: 1, max: 9}) }, (_, i) => i + 1).map(() => ({field: faker.helpers.arrayElement(['specialization','grade','required_skills','desired_skills','tasks','domain','work_formats','location','salary'] as const), reason: faker.helpers.arrayElement(['unknown','unconfirmed'] as const), question: faker.string.alpha({length: {min: 1, max: 300}})}))}, recommendations: {status: faker.helpers.arrayElement(['computed','pending','not_available'] as const), requirements_version: faker.number.int({min: 1}), policy_version: faker.helpers.arrayElement([faker.number.int({min: 1}), null]), algorithm_version: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}),null,]), computed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), categories: Array.from({ length: faker.number.int({min: 1, max: 10}) }, (_, i) => i + 1).map(() => ({specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), score: faker.helpers.arrayElement([faker.number.float({min: 0, max: 1, fractionDigits: 2}), null]), skill_overlap: {share: faker.number.float({min: 0, max: 1, fractionDigits: 2}), covered_skills: Array.from({ length: faker.number.int({min: 1, max: 60}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}))), uncovered_skills: Array.from({ length: faker.number.int({min: 1, max: 60}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100})))}, money: {status: faker.helpers.arrayElement(['computed','insufficient_data','no_salary','withheld'] as const), share: faker.helpers.arrayElement([faker.number.float({min: 0, max: 1, fractionDigits: 2}), null])}, supply: faker.helpers.arrayElement(['fewer_than_5','from_5_to_29','30_or_more'] as const)}))}, created_at: faker.date.past().toISOString().slice(0, 19) + 'Z', updated_at: faker.date.past().toISOString().slice(0, 19) + 'Z', ...overrideResponse}) export const getListOrganizationNeedsMockHandler = (overrideResponse?: NeedList | ((info: Parameters[1]>[0]) => Promise | NeedList), options?: RequestHandlerOptions) => { diff --git a/frontend/src/shared/api/endpoints/support/support.msw.ts b/frontend/src/shared/api/endpoints/support/support.msw.ts index 0d8a474..e138c6c 100644 --- a/frontend/src/shared/api/endpoints/support/support.msw.ts +++ b/frontend/src/shared/api/endpoints/support/support.msw.ts @@ -8,6 +8,10 @@ import { faker } from '@faker-js/faker'; +import { + fakeFromPattern +} from '../../mock-pattern'; + import { HttpResponse, http @@ -16,17 +20,6 @@ import type { RequestHandlerOptions } from 'msw'; -import { - GradeCode, - SpecializationCode, - SupportCaseActorKind, - SupportCaseComplaintReason, - SupportCaseDecisionOutcome, - SupportCaseEventKind, - SupportCaseObjectType, - SupportCaseStatus, - SupportCaseType -} from '../../schemas'; import type { SupportCase, SupportCaseAssessmentTarget, @@ -36,27 +29,27 @@ import type { } from '../../schemas'; -export const getListMySupportCasesResponseSupportCaseObjectReferenceMock = (overrideResponse: Partial = {}): SupportCaseObjectReference => ({...{type: faker.helpers.arrayElement(Object.values(SupportCaseObjectType)), id: faker.string.uuid()}, ...overrideResponse}); +export const getListMySupportCasesResponseSupportCaseObjectReferenceMock = (overrideResponse: Partial = {}): SupportCaseObjectReference => ({...{type: faker.helpers.arrayElement(['assessment_attempt','organization','invitation','support_case'] as const), id: faker.string.uuid()}, ...overrideResponse}); -export const getListMySupportCasesResponseSupportCaseAssessmentTargetMock = (overrideResponse: Partial = {}): SupportCaseAssessmentTarget => ({...{specialization: faker.helpers.arrayElement(Object.values(SpecializationCode)), grade: faker.helpers.arrayElement(Object.values(GradeCode))}, ...overrideResponse}); +export const getListMySupportCasesResponseSupportCaseAssessmentTargetMock = (overrideResponse: Partial = {}): SupportCaseAssessmentTarget => ({...{specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const)}, ...overrideResponse}); -export const getListMySupportCasesResponseMock = (overrideResponse: Partial> = {}): SupportCaseList => ({items: Array.from({ length: faker.number.int({min: 1, max: 100}) }, (_, i) => i + 1).map(() => ({id: faker.string.uuid(), number: faker.helpers.fromRegExp("^SC-[0-9]{4}-[0-9]{6,10}$"), type: faker.helpers.arrayElement(Object.values(SupportCaseType)), status: faker.helpers.arrayElement(Object.values(SupportCaseStatus)), object: faker.helpers.arrayElement([{...getListMySupportCasesResponseSupportCaseObjectReferenceMock()},null,]), assessment_target: faker.helpers.arrayElement([{...getListMySupportCasesResponseSupportCaseAssessmentTargetMock()},null,]), response_target: {kind: faker.helpers.arrayElement(['operational_goal'] as const), business_days: faker.number.int({min: 1, max: 60}), due_at: faker.date.past().toISOString().slice(0, 19) + 'Z', answered_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), late: faker.datatype.boolean(), policy_version: faker.number.int({min: 1})}, decision_outcome: faker.helpers.arrayElement([faker.helpers.arrayElement(Object.values(SupportCaseDecisionOutcome)),null,]), created_at: faker.date.past().toISOString().slice(0, 19) + 'Z', updated_at: faker.date.past().toISOString().slice(0, 19) + 'Z'})), page: {has_more: faker.datatype.boolean(), next_cursor: faker.helpers.arrayElement([faker.helpers.fromRegExp("^[A-Za-z0-9_-]+$"), null])}, ...overrideResponse}) +export const getListMySupportCasesResponseMock = (overrideResponse: Partial> = {}): SupportCaseList => ({items: Array.from({ length: faker.number.int({min: 1, max: 100}) }, (_, i) => i + 1).map(() => ({id: faker.string.uuid(), number: fakeFromPattern("^SC-[0-9]{4}-[0-9]{6,10}$", {minLength: 14, maxLength: 18}), type: faker.helpers.arrayElement(['support','complaint','grade_appeal','anticheat_appeal','manual_assessment'] as const), status: faker.helpers.arrayElement(['submitted','in_review','waiting_for_user','waiting_expert','resolved','closed'] as const), object: faker.helpers.arrayElement([{...getListMySupportCasesResponseSupportCaseObjectReferenceMock()},null,]), assessment_target: faker.helpers.arrayElement([{...getListMySupportCasesResponseSupportCaseAssessmentTargetMock()},null,]), response_target: {kind: faker.helpers.arrayElement(['operational_goal'] as const), business_days: faker.number.int({min: 1, max: 60}), due_at: faker.date.past().toISOString().slice(0, 19) + 'Z', answered_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), late: faker.datatype.boolean(), policy_version: faker.number.int({min: 1})}, decision_outcome: faker.helpers.arrayElement([faker.helpers.arrayElement(['upheld','partially_upheld','not_upheld','answered','assessed'] as const),null,]), created_at: faker.date.past().toISOString().slice(0, 19) + 'Z', updated_at: faker.date.past().toISOString().slice(0, 19) + 'Z'})), page: {has_more: faker.datatype.boolean(), next_cursor: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9_-]+$", {minLength: 1, maxLength: 512}), null])}, ...overrideResponse}) -export const getCreateMySupportCaseResponseSupportCaseObjectReferenceMock = (overrideResponse: Partial = {}): SupportCaseObjectReference => ({...{type: faker.helpers.arrayElement(Object.values(SupportCaseObjectType)), id: faker.string.uuid()}, ...overrideResponse}); +export const getCreateMySupportCaseResponseSupportCaseObjectReferenceMock = (overrideResponse: Partial = {}): SupportCaseObjectReference => ({...{type: faker.helpers.arrayElement(['assessment_attempt','organization','invitation','support_case'] as const), id: faker.string.uuid()}, ...overrideResponse}); -export const getCreateMySupportCaseResponseSupportCaseAssessmentTargetMock = (overrideResponse: Partial = {}): SupportCaseAssessmentTarget => ({...{specialization: faker.helpers.arrayElement(Object.values(SpecializationCode)), grade: faker.helpers.arrayElement(Object.values(GradeCode))}, ...overrideResponse}); +export const getCreateMySupportCaseResponseSupportCaseAssessmentTargetMock = (overrideResponse: Partial = {}): SupportCaseAssessmentTarget => ({...{specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const)}, ...overrideResponse}); -export const getCreateMySupportCaseResponseSupportCaseDecisionMock = (overrideResponse: Partial = {}): SupportCaseDecision => ({...{outcome: faker.helpers.arrayElement(Object.values(SupportCaseDecisionOutcome)), reason: faker.string.alpha({length: {min: 1, max: 4000}}), decided_at: faker.date.past().toISOString().slice(0, 19) + 'Z'}, ...overrideResponse}); +export const getCreateMySupportCaseResponseSupportCaseDecisionMock = (overrideResponse: Partial = {}): SupportCaseDecision => ({...{outcome: faker.helpers.arrayElement(['upheld','partially_upheld','not_upheld','answered','assessed'] as const), reason: faker.string.alpha({length: {min: 1, max: 4000}}), decided_at: faker.date.past().toISOString().slice(0, 19) + 'Z'}, ...overrideResponse}); -export const getCreateMySupportCaseResponseMock = (overrideResponse: Partial> = {}): SupportCase => ({id: faker.string.uuid(), number: faker.helpers.fromRegExp("^SC-[0-9]{4}-[0-9]{6,10}$"), type: faker.helpers.arrayElement(Object.values(SupportCaseType)), status: faker.helpers.arrayElement(Object.values(SupportCaseStatus)), description: faker.helpers.fromRegExp("\\S"), object: faker.helpers.arrayElement([{...getCreateMySupportCaseResponseSupportCaseObjectReferenceMock()},null,]), assessment_target: faker.helpers.arrayElement([{...getCreateMySupportCaseResponseSupportCaseAssessmentTargetMock()},null,]), complaint_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(Object.values(SupportCaseComplaintReason)),null,]), rubric_version: faker.helpers.arrayElement([faker.number.int({min: 1}), null]), response_target: {kind: faker.helpers.arrayElement(['operational_goal'] as const), business_days: faker.number.int({min: 1, max: 60}), due_at: faker.date.past().toISOString().slice(0, 19) + 'Z', answered_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), late: faker.datatype.boolean(), policy_version: faker.number.int({min: 1})}, decision: faker.helpers.arrayElement([{...getCreateMySupportCaseResponseSupportCaseDecisionMock()},null,]), history: Array.from({ length: faker.number.int({min: 1, max: 200}) }, (_, i) => i + 1).map(() => ({sequence: faker.number.int({min: 1}), kind: faker.helpers.arrayElement(Object.values(SupportCaseEventKind)), actor: faker.helpers.arrayElement(Object.values(SupportCaseActorKind)), occurred_at: faker.date.past().toISOString().slice(0, 19) + 'Z', status: faker.helpers.arrayElement([faker.helpers.arrayElement(Object.values(SupportCaseStatus)),null,]), message: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 4000}}),null,])})), created_at: faker.date.past().toISOString().slice(0, 19) + 'Z', updated_at: faker.date.past().toISOString().slice(0, 19) + 'Z', ...overrideResponse}) +export const getCreateMySupportCaseResponseMock = (overrideResponse: Partial> = {}): SupportCase => ({id: faker.string.uuid(), number: fakeFromPattern("^SC-[0-9]{4}-[0-9]{6,10}$", {minLength: 14, maxLength: 18}), type: faker.helpers.arrayElement(['support','complaint','grade_appeal','anticheat_appeal','manual_assessment'] as const), status: faker.helpers.arrayElement(['submitted','in_review','waiting_for_user','waiting_expert','resolved','closed'] as const), description: fakeFromPattern("\\S", {minLength: 1, maxLength: 4000}), object: faker.helpers.arrayElement([{...getCreateMySupportCaseResponseSupportCaseObjectReferenceMock()},null,]), assessment_target: faker.helpers.arrayElement([{...getCreateMySupportCaseResponseSupportCaseAssessmentTargetMock()},null,]), complaint_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['organization_conduct','offer_content','salary_terms_violation','data_disclosure','other'] as const),null,]), rubric_version: faker.helpers.arrayElement([faker.number.int({min: 1}), null]), response_target: {kind: faker.helpers.arrayElement(['operational_goal'] as const), business_days: faker.number.int({min: 1, max: 60}), due_at: faker.date.past().toISOString().slice(0, 19) + 'Z', answered_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), late: faker.datatype.boolean(), policy_version: faker.number.int({min: 1})}, decision: faker.helpers.arrayElement([{...getCreateMySupportCaseResponseSupportCaseDecisionMock()},null,]), history: Array.from({ length: faker.number.int({min: 1, max: 200}) }, (_, i) => i + 1).map(() => ({sequence: faker.number.int({min: 1}), kind: faker.helpers.arrayElement(['created','status_changed','reply','decision'] as const), actor: faker.helpers.arrayElement(['user','support','system'] as const), occurred_at: faker.date.past().toISOString().slice(0, 19) + 'Z', status: faker.helpers.arrayElement([faker.helpers.arrayElement(['submitted','in_review','waiting_for_user','waiting_expert','resolved','closed'] as const),null,]), message: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 4000}}),null,])})), created_at: faker.date.past().toISOString().slice(0, 19) + 'Z', updated_at: faker.date.past().toISOString().slice(0, 19) + 'Z', ...overrideResponse}) -export const getGetMySupportCaseResponseSupportCaseObjectReferenceMock = (overrideResponse: Partial = {}): SupportCaseObjectReference => ({...{type: faker.helpers.arrayElement(Object.values(SupportCaseObjectType)), id: faker.string.uuid()}, ...overrideResponse}); +export const getGetMySupportCaseResponseSupportCaseObjectReferenceMock = (overrideResponse: Partial = {}): SupportCaseObjectReference => ({...{type: faker.helpers.arrayElement(['assessment_attempt','organization','invitation','support_case'] as const), id: faker.string.uuid()}, ...overrideResponse}); -export const getGetMySupportCaseResponseSupportCaseAssessmentTargetMock = (overrideResponse: Partial = {}): SupportCaseAssessmentTarget => ({...{specialization: faker.helpers.arrayElement(Object.values(SpecializationCode)), grade: faker.helpers.arrayElement(Object.values(GradeCode))}, ...overrideResponse}); +export const getGetMySupportCaseResponseSupportCaseAssessmentTargetMock = (overrideResponse: Partial = {}): SupportCaseAssessmentTarget => ({...{specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const)}, ...overrideResponse}); -export const getGetMySupportCaseResponseSupportCaseDecisionMock = (overrideResponse: Partial = {}): SupportCaseDecision => ({...{outcome: faker.helpers.arrayElement(Object.values(SupportCaseDecisionOutcome)), reason: faker.string.alpha({length: {min: 1, max: 4000}}), decided_at: faker.date.past().toISOString().slice(0, 19) + 'Z'}, ...overrideResponse}); +export const getGetMySupportCaseResponseSupportCaseDecisionMock = (overrideResponse: Partial = {}): SupportCaseDecision => ({...{outcome: faker.helpers.arrayElement(['upheld','partially_upheld','not_upheld','answered','assessed'] as const), reason: faker.string.alpha({length: {min: 1, max: 4000}}), decided_at: faker.date.past().toISOString().slice(0, 19) + 'Z'}, ...overrideResponse}); -export const getGetMySupportCaseResponseMock = (overrideResponse: Partial> = {}): SupportCase => ({id: faker.string.uuid(), number: faker.helpers.fromRegExp("^SC-[0-9]{4}-[0-9]{6,10}$"), type: faker.helpers.arrayElement(Object.values(SupportCaseType)), status: faker.helpers.arrayElement(Object.values(SupportCaseStatus)), description: faker.helpers.fromRegExp("\\S"), object: faker.helpers.arrayElement([{...getGetMySupportCaseResponseSupportCaseObjectReferenceMock()},null,]), assessment_target: faker.helpers.arrayElement([{...getGetMySupportCaseResponseSupportCaseAssessmentTargetMock()},null,]), complaint_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(Object.values(SupportCaseComplaintReason)),null,]), rubric_version: faker.helpers.arrayElement([faker.number.int({min: 1}), null]), response_target: {kind: faker.helpers.arrayElement(['operational_goal'] as const), business_days: faker.number.int({min: 1, max: 60}), due_at: faker.date.past().toISOString().slice(0, 19) + 'Z', answered_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), late: faker.datatype.boolean(), policy_version: faker.number.int({min: 1})}, decision: faker.helpers.arrayElement([{...getGetMySupportCaseResponseSupportCaseDecisionMock()},null,]), history: Array.from({ length: faker.number.int({min: 1, max: 200}) }, (_, i) => i + 1).map(() => ({sequence: faker.number.int({min: 1}), kind: faker.helpers.arrayElement(Object.values(SupportCaseEventKind)), actor: faker.helpers.arrayElement(Object.values(SupportCaseActorKind)), occurred_at: faker.date.past().toISOString().slice(0, 19) + 'Z', status: faker.helpers.arrayElement([faker.helpers.arrayElement(Object.values(SupportCaseStatus)),null,]), message: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 4000}}),null,])})), created_at: faker.date.past().toISOString().slice(0, 19) + 'Z', updated_at: faker.date.past().toISOString().slice(0, 19) + 'Z', ...overrideResponse}) +export const getGetMySupportCaseResponseMock = (overrideResponse: Partial> = {}): SupportCase => ({id: faker.string.uuid(), number: fakeFromPattern("^SC-[0-9]{4}-[0-9]{6,10}$", {minLength: 14, maxLength: 18}), type: faker.helpers.arrayElement(['support','complaint','grade_appeal','anticheat_appeal','manual_assessment'] as const), status: faker.helpers.arrayElement(['submitted','in_review','waiting_for_user','waiting_expert','resolved','closed'] as const), description: fakeFromPattern("\\S", {minLength: 1, maxLength: 4000}), object: faker.helpers.arrayElement([{...getGetMySupportCaseResponseSupportCaseObjectReferenceMock()},null,]), assessment_target: faker.helpers.arrayElement([{...getGetMySupportCaseResponseSupportCaseAssessmentTargetMock()},null,]), complaint_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['organization_conduct','offer_content','salary_terms_violation','data_disclosure','other'] as const),null,]), rubric_version: faker.helpers.arrayElement([faker.number.int({min: 1}), null]), response_target: {kind: faker.helpers.arrayElement(['operational_goal'] as const), business_days: faker.number.int({min: 1, max: 60}), due_at: faker.date.past().toISOString().slice(0, 19) + 'Z', answered_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), late: faker.datatype.boolean(), policy_version: faker.number.int({min: 1})}, decision: faker.helpers.arrayElement([{...getGetMySupportCaseResponseSupportCaseDecisionMock()},null,]), history: Array.from({ length: faker.number.int({min: 1, max: 200}) }, (_, i) => i + 1).map(() => ({sequence: faker.number.int({min: 1}), kind: faker.helpers.arrayElement(['created','status_changed','reply','decision'] as const), actor: faker.helpers.arrayElement(['user','support','system'] as const), occurred_at: faker.date.past().toISOString().slice(0, 19) + 'Z', status: faker.helpers.arrayElement([faker.helpers.arrayElement(['submitted','in_review','waiting_for_user','waiting_expert','resolved','closed'] as const),null,]), message: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 4000}}),null,])})), created_at: faker.date.past().toISOString().slice(0, 19) + 'Z', updated_at: faker.date.past().toISOString().slice(0, 19) + 'Z', ...overrideResponse}) export const getListMySupportCasesMockHandler = (overrideResponse?: SupportCaseList | ((info: Parameters[1]>[0]) => Promise | SupportCaseList), options?: RequestHandlerOptions) => { diff --git a/frontend/src/shared/api/mock-pattern.ts b/frontend/src/shared/api/mock-pattern.ts new file mode 100644 index 0000000..75d280b --- /dev/null +++ b/frontend/src/shared/api/mock-pattern.ts @@ -0,0 +1,572 @@ +import { faker } from "@faker-js/faker"; + +// Generated MSW mocks call this helper for every string schema with a +// `pattern`. Orval 8.40 emits `faker.helpers.fromRegExp(pattern)` there, which +// prints anchors and non-capturing groups literally and ignores minLength and +// maxLength, so its output fails the generated Zod schema. The codegen step in +// codegen/mock-patterns.ts rewrites those calls into `fakeFromPattern` with +// the length bounds of the schema. +// +// The helper parses the regular expression subset used by contracts (literal +// characters, escapes, character classes, groups, alternation, quantifiers, +// and ^/$ at the ends of a top-level alternative), picks a target length that +// fits both the pattern and the bounds, and samples a matching string with +// the faker random generator, so a seeded faker gives the same value. Every +// value is checked against `new RegExp(pattern, "u")` and the bounds. A pattern +// outside the subset, or bounds that no value can meet, make the helper throw +// instead of returning data that the schema rejects. + +export interface PatternLengthBounds { + readonly minLength?: number; + readonly maxLength?: number; +} + +type CodePointRange = readonly [number, number]; + +type PatternNode = + | { readonly kind: "set"; readonly ranges: readonly CodePointRange[]; readonly size: number } + | { readonly kind: "sequence"; readonly items: readonly PatternNode[] } + | { readonly kind: "alternation"; readonly options: readonly PatternNode[] } + | { + readonly kind: "repeat"; + readonly node: PatternNode; + readonly min: number; + readonly max: number; + }; + +interface CompiledPattern { + readonly root: PatternNode; + readonly regex: RegExp; +} + +// Mock strings stay within printable ASCII unless a class names other +// characters explicitly. Negated classes, `.`, and \S, \D, \W draw from it. +const printableRange: CodePointRange = [0x20, 0x7e]; +const digitRanges: readonly CodePointRange[] = [[0x30, 0x39]]; +const wordRanges: readonly CodePointRange[] = [ + [0x30, 0x39], + [0x41, 0x5a], + [0x5f, 0x5f], + [0x61, 0x7a], +]; +const spaceRanges: readonly CodePointRange[] = [[0x20, 0x20]]; +const syntaxCharacters = new Set("^$\\.*+?()[]{}|/-"); +const controlEscapes: Readonly> = { + t: 0x09, + n: 0x0a, + v: 0x0b, + f: 0x0c, + r: 0x0d, + "0": 0x00, +}; + +// Above the lower bound, a target length is drawn from this many extra +// characters, so a field limited to thousands of characters still gets a +// short readable mock. +const lengthSpread = 24; +const maxAttempts = 64; + +class UnsupportedPatternError extends Error {} + +function normalizeRanges(ranges: readonly CodePointRange[]): CodePointRange[] { + const sorted = [...ranges].sort((left, right) => left[0] - right[0]); + const merged: [number, number][] = []; + for (const [low, high] of sorted) { + const last = merged.at(-1); + if (last !== undefined && low <= last[1] + 1) { + last[1] = Math.max(last[1], high); + } else { + merged.push([low, high]); + } + } + return merged; +} + +function complementInPrintable(ranges: readonly CodePointRange[]): CodePointRange[] { + const result: CodePointRange[] = []; + let next = printableRange[0]; + for (const [low, high] of normalizeRanges(ranges)) { + if (high < next || low > printableRange[1]) { + continue; + } + if (low > next) { + result.push([next, low - 1]); + } + next = Math.max(next, high + 1); + } + if (next <= printableRange[1]) { + result.push([next, printableRange[1]]); + } + return result; +} + +function charSet(ranges: readonly CodePointRange[]): PatternNode { + const normalized = normalizeRanges(ranges); + const size = normalized.reduce((total, [low, high]) => total + high - low + 1, 0); + if (size === 0) { + throw new UnsupportedPatternError("a character class matches no character"); + } + return { kind: "set", ranges: normalized, size }; +} + +class PatternParser { + private index = 0; + + constructor(private readonly source: string) {} + + parse(): PatternNode { + const node = this.parseAlternation(true); + if (this.index < this.source.length) { + throw new UnsupportedPatternError(`unexpected ${this.source[this.index]} at ${this.index}`); + } + return node; + } + + private peek(): string | undefined { + return this.source[this.index]; + } + + private parseAlternation(topLevel: boolean): PatternNode { + const options = [this.parseSequence(topLevel)]; + while (this.peek() === "|") { + this.index += 1; + options.push(this.parseSequence(topLevel)); + } + return options.length === 1 && options[0] !== undefined + ? options[0] + : { kind: "alternation", options }; + } + + // A top-level alternative without ^ or $ may have any text before or after + // the match, which the sequence models as printable filler. + private parseSequence(topLevel: boolean): PatternNode { + const items: PatternNode[] = []; + let anchoredStart = false; + let anchoredEnd = false; + if (this.peek() === "^") { + if (!topLevel) { + throw new UnsupportedPatternError("^ inside a group"); + } + anchoredStart = true; + this.index += 1; + } + while (this.index < this.source.length) { + const character = this.peek(); + if (character === "|" || character === ")") { + break; + } + if (character === "$") { + const next = this.source[this.index + 1]; + if (!topLevel || (next !== undefined && next !== "|")) { + throw new UnsupportedPatternError("$ before the end of an alternative"); + } + anchoredEnd = true; + this.index += 1; + break; + } + if (character === "^") { + throw new UnsupportedPatternError("^ after the start of an alternative"); + } + items.push(this.parseQuantified()); + } + if (topLevel) { + const filler: PatternNode = { + kind: "repeat", + node: charSet([printableRange]), + min: 0, + max: Number.POSITIVE_INFINITY, + }; + if (!anchoredStart) { + items.unshift(filler); + } + if (!anchoredEnd) { + items.push(filler); + } + } + return items.length === 1 && items[0] !== undefined ? items[0] : { kind: "sequence", items }; + } + + private parseQuantified(): PatternNode { + const atom = this.parseAtom(); + const quantifier = this.parseQuantifier(); + if (quantifier === undefined) { + return atom; + } + if (this.peek() === "?") { + // A lazy quantifier matches the same strings. + this.index += 1; + } + return { kind: "repeat", node: atom, min: quantifier[0], max: quantifier[1] }; + } + + private parseQuantifier(): readonly [number, number] | undefined { + const character = this.peek(); + if (character === "*") { + this.index += 1; + return [0, Number.POSITIVE_INFINITY]; + } + if (character === "+") { + this.index += 1; + return [1, Number.POSITIVE_INFINITY]; + } + if (character === "?") { + this.index += 1; + return [0, 1]; + } + if (character !== "{") { + return undefined; + } + const match = /^\{(\d+)(,(\d*))?\}/.exec(this.source.slice(this.index)); + if (match === null) { + throw new UnsupportedPatternError(`malformed quantifier at ${this.index}`); + } + this.index += match[0].length; + const min = Number(match[1]); + const max = + match[2] === undefined + ? min + : match[3] === undefined || match[3] === "" + ? Number.POSITIVE_INFINITY + : Number(match[3]); + if (max < min) { + throw new UnsupportedPatternError(`quantifier {${min},${max}} is out of order`); + } + return [min, max]; + } + + private parseAtom(): PatternNode { + const character = this.peek(); + if (character === undefined) { + throw new UnsupportedPatternError("unexpected end of pattern"); + } + if (character === "(") { + return this.parseGroup(); + } + if (character === "[") { + return this.parseClass(); + } + if (character === ".") { + this.index += 1; + return charSet([printableRange]); + } + if (character === "\\") { + return charSet(this.parseEscape(false)); + } + if ("*+?{}])".includes(character)) { + throw new UnsupportedPatternError(`unexpected ${character} at ${this.index}`); + } + const codePoint = this.source.codePointAt(this.index) ?? 0; + this.index += String.fromCodePoint(codePoint).length; + return charSet([[codePoint, codePoint]]); + } + + private parseGroup(): PatternNode { + this.index += 1; + if (this.source.startsWith("?:", this.index)) { + this.index += 2; + } else if (/^\?<[A-Za-z_$][\w$]*>/.test(this.source.slice(this.index))) { + this.index = this.source.indexOf(">", this.index) + 1; + } else if (this.peek() === "?") { + throw new UnsupportedPatternError("lookaround or group modifiers"); + } + const node = this.parseAlternation(false); + if (this.peek() !== ")") { + throw new UnsupportedPatternError("unterminated group"); + } + this.index += 1; + return node; + } + + private parseClass(): PatternNode { + this.index += 1; + const negated = this.peek() === "^"; + if (negated) { + this.index += 1; + } + const ranges: CodePointRange[] = []; + while (this.peek() !== "]") { + if (this.index >= this.source.length) { + throw new UnsupportedPatternError("unterminated character class"); + } + const low = this.parseClassAtom(); + if (this.peek() === "-" && this.source[this.index + 1] !== "]") { + this.index += 1; + const high = this.parseClassAtom(); + const lowPoint = singleCodePoint(low); + const highPoint = singleCodePoint(high); + if (lowPoint === undefined || highPoint === undefined || highPoint < lowPoint) { + throw new UnsupportedPatternError("invalid class range"); + } + ranges.push([lowPoint, highPoint]); + } else { + ranges.push(...low); + } + } + this.index += 1; + return charSet(negated ? complementInPrintable(ranges) : ranges); + } + + private parseClassAtom(): readonly CodePointRange[] { + if (this.peek() === "\\") { + return this.parseEscape(true); + } + const codePoint = this.source.codePointAt(this.index) ?? 0; + this.index += String.fromCodePoint(codePoint).length; + return [[codePoint, codePoint]]; + } + + private parseEscape(inClass: boolean): readonly CodePointRange[] { + this.index += 1; + const character = this.peek(); + if (character === undefined) { + throw new UnsupportedPatternError("pattern ends with a backslash"); + } + this.index += 1; + switch (character) { + case "d": + return digitRanges; + case "D": + return complementInPrintable(digitRanges); + case "w": + return wordRanges; + case "W": + return complementInPrintable(wordRanges); + case "s": + return spaceRanges; + case "S": + return complementInPrintable(spaceRanges); + case "b": + if (inClass) { + return [[0x08, 0x08]]; + } + throw new UnsupportedPatternError("word boundary assertion"); + case "x": { + const hex = /^[0-9A-Fa-f]{2}/.exec(this.source.slice(this.index)); + if (hex === null) { + throw new UnsupportedPatternError("malformed \\x escape"); + } + this.index += 2; + const codePoint = Number.parseInt(hex[0], 16); + return [[codePoint, codePoint]]; + } + case "u": { + const hex = /^(?:\{([0-9A-Fa-f]{1,6})\}|([0-9A-Fa-f]{4}))/.exec( + this.source.slice(this.index), + ); + if (hex === null) { + throw new UnsupportedPatternError("malformed \\u escape"); + } + this.index += hex[0].length; + const codePoint = Number.parseInt(hex[1] ?? hex[2] ?? "", 16); + return [[codePoint, codePoint]]; + } + default: { + const control = controlEscapes[character]; + if (control !== undefined) { + return [[control, control]]; + } + if (syntaxCharacters.has(character)) { + const codePoint = character.codePointAt(0) ?? 0; + return [[codePoint, codePoint]]; + } + throw new UnsupportedPatternError(`escape \\${character}`); + } + } + } +} + +function singleCodePoint(ranges: readonly CodePointRange[]): number | undefined { + const [range] = ranges; + return ranges.length === 1 && range !== undefined && range[0] === range[1] ? range[0] : undefined; +} + +const minLengths = new WeakMap(); +const maxLengths = new WeakMap(); + +function minLength(node: PatternNode): number { + const cached = minLengths.get(node); + if (cached !== undefined) { + return cached; + } + let length: number; + switch (node.kind) { + case "set": + length = 1; + break; + case "sequence": + length = node.items.reduce((total, item) => total + minLength(item), 0); + break; + case "alternation": + length = Math.min(...node.options.map(minLength)); + break; + case "repeat": + length = node.min * minLength(node.node); + break; + } + minLengths.set(node, length); + return length; +} + +function maxLength(node: PatternNode): number { + const cached = maxLengths.get(node); + if (cached !== undefined) { + return cached; + } + let length: number; + switch (node.kind) { + case "set": + length = 1; + break; + case "sequence": + length = node.items.reduce((total, item) => total + maxLength(item), 0); + break; + case "alternation": + length = Math.max(...node.options.map(maxLength)); + break; + case "repeat": { + const item = maxLength(node.node); + length = item === 0 || node.max === 0 ? 0 : node.max * item; + break; + } + } + maxLengths.set(node, length); + return length; +} + +function pick(low: number, high: number): number { + return low >= high ? low : faker.number.int({ min: low, max: high }); +} + +function sampleSet(node: Extract): string { + let offset = pick(0, node.size - 1); + for (const [low, high] of node.ranges) { + const width = high - low + 1; + if (offset < width) { + return String.fromCodePoint(low + offset); + } + offset -= width; + } + throw new Error("Character offset outside the set."); +} + +// Splits `target` across consecutive parts so that each part stays within its +// own length range whenever the total allows it. +function sampleParts(parts: readonly PatternNode[], target: number): string { + const minimums = parts.map(minLength); + const maximums = parts.map(maxLength); + // restMinimums[i] and restMaximums[i] cover the parts after index i. + const restMinimums = new Array(parts.length).fill(0); + const restMaximums = new Array(parts.length).fill(0); + for (let index = parts.length - 2; index >= 0; index -= 1) { + restMinimums[index] = (restMinimums[index + 1] ?? 0) + (minimums[index + 1] ?? 0); + restMaximums[index] = (restMaximums[index + 1] ?? 0) + (maximums[index + 1] ?? 0); + } + let remaining = target; + let result = ""; + parts.forEach((part, index) => { + const low = Math.max(minimums[index] ?? 0, remaining - (restMaximums[index] ?? 0)); + const high = Math.min(maximums[index] ?? 0, remaining - (restMinimums[index] ?? 0)); + const length = high < low ? Math.max(0, Math.min(low, remaining)) : pick(low, high); + result += sample(part, length); + remaining -= length; + }); + return result; +} + +function sample(node: PatternNode, target: number): string { + switch (node.kind) { + case "set": + return sampleSet(node); + case "sequence": + return sampleParts(node.items, target); + case "alternation": { + const fitting = node.options.filter( + (option) => minLength(option) <= target && target <= maxLength(option), + ); + const options = fitting.length > 0 ? fitting : node.options; + return sample(options[pick(0, options.length - 1)] ?? node, target); + } + case "repeat": { + const itemMin = minLength(node.node); + const itemMax = maxLength(node.node); + // The count must satisfy count * itemMin <= target <= count * itemMax. + const neededCount = target > 0 && itemMax > 0 ? Math.max(1, Math.ceil(target / itemMax)) : 0; + const lowCount = Math.max(node.min, neededCount); + const highCount = Math.min( + node.max, + itemMin === 0 ? Math.max(lowCount, node.min + target) : Math.floor(target / itemMin), + ); + const count = highCount < lowCount ? lowCount : pick(lowCount, highCount); + if (count === 0 || !Number.isFinite(count)) { + return ""; + } + return sampleParts( + Array.from({ length: count }, () => node.node), + target, + ); + } + } +} + +const compiled = new Map(); + +function compile(pattern: string): CompiledPattern { + const cached = compiled.get(pattern); + if (cached !== undefined) { + return cached; + } + let regex: RegExp; + try { + regex = new RegExp(pattern, "u"); + } catch (error) { + throw new Error(`fakeFromPattern: /${pattern}/ is not a valid Unicode regular expression.`, { + cause: error, + }); + } + let root: PatternNode; + try { + root = new PatternParser(pattern).parse(); + } catch (error) { + if (error instanceof UnsupportedPatternError) { + throw new Error(`fakeFromPattern: /${pattern}/ uses unsupported syntax: ${error.message}.`, { + cause: error, + }); + } + throw error; + } + const result = { root, regex }; + compiled.set(pattern, result); + return result; +} + +function fits(value: string, regex: RegExp, low: number, high: number): boolean { + return value.length >= low && value.length <= high && regex.test(value); +} + +/** + * Returns a string that matches `pattern` as a whole and has a length within + * `bounds`. It throws when the pattern is outside the supported subset or when + * no sampled value meets both constraints. + */ +export function fakeFromPattern(pattern: string, bounds: PatternLengthBounds = {}): string { + const { root, regex } = compile(pattern); + const lowerBound = Math.max(bounds.minLength ?? 0, minLength(root)); + const upperBound = Math.min(bounds.maxLength ?? Number.POSITIVE_INFINITY, maxLength(root)); + if (lowerBound > upperBound) { + throw new Error( + `fakeFromPattern: /${pattern}/ has no value with length ${bounds.minLength ?? 0}..${ + bounds.maxLength ?? "unbounded" + }.`, + ); + } + const targetHigh = Math.min(upperBound, lowerBound + lengthSpread); + for (let attempt = 0; attempt < maxAttempts; attempt += 1) { + const value = sample(root, pick(lowerBound, targetHigh)); + if (fits(value, regex, bounds.minLength ?? 0, bounds.maxLength ?? Number.POSITIVE_INFINITY)) { + return value; + } + } + throw new Error( + `fakeFromPattern: no value for /${pattern}/ with length ${lowerBound}..${upperBound} after ${maxAttempts} attempts.`, + ); +} diff --git a/frontend/src/shared/api/mock-validity.test.ts b/frontend/src/shared/api/mock-validity.test.ts new file mode 100644 index 0000000..c30ea39 --- /dev/null +++ b/frontend/src/shared/api/mock-validity.test.ts @@ -0,0 +1,165 @@ +import { faker } from "@faker-js/faker"; +import { describe, expect, it } from "vitest"; +import type { ZodType } from "zod"; +import { fakeFromPattern, type PatternLengthBounds } from "./mock-pattern"; +import * as schemas from "./schemas"; + +// Every generated `get*ResponseMock` factory must produce data that its own +// generated Zod response schema accepts. MSW handlers serve these factories, +// so an invalid mock would make component and query tests exercise data the +// API can never return. The factories and the schema each one returns are +// discovered from the generated files, so a new operation is covered without +// editing this test. + +const seeds = Array.from({ length: 25 }, (_, index) => index + 1); + +const mockModules = import.meta.glob>("./endpoints/*/*.msw.ts", { + eager: true, +}); +const mockSources = import.meta.glob("./endpoints/*/*.msw.ts", { + eager: true, + query: "?raw", + import: "default", +}); + +// Orval declares each response factory with the response type as its return +// type. The Zod schema with the same name is the generated response schema. +const factoryDeclaration = + /export const (get\w+ResponseMock) = \(overrideResponse: [^=]*= \{\}\): (\w+) =>/g; + +interface ResponseMockCase { + readonly file: string; + readonly factoryName: string; + readonly schemaName: string; + readonly factory: () => unknown; + readonly schema: ZodType; +} + +function isZodSchema(value: unknown): value is ZodType { + return ( + typeof value === "object" && + value !== null && + typeof (value as { safeParse?: unknown }).safeParse === "function" + ); +} + +function discoverCases(): ResponseMockCase[] { + const cases: ResponseMockCase[] = []; + for (const [file, source] of Object.entries(mockSources)) { + const module = mockModules[file]; + if (module === undefined) { + throw new Error(`${file} has source text but no module.`); + } + const exported = Object.keys(module).filter((name) => /^get\w+ResponseMock$/.test(name)); + const declared = new Map( + [...source.matchAll(factoryDeclaration)].map((match) => [match[1] ?? "", match[2] ?? ""]), + ); + for (const factoryName of exported) { + const schemaName = declared.get(factoryName); + if (schemaName === undefined) { + throw new Error(`${file}: cannot derive the response schema of ${factoryName}.`); + } + const schema: unknown = (schemas as Record)[schemaName]; + if (!isZodSchema(schema)) { + throw new Error(`${file}: ${factoryName} returns ${schemaName}, which is no Zod schema.`); + } + const factory = module[factoryName]; + if (typeof factory !== "function") { + throw new Error(`${file}: ${factoryName} is not a function.`); + } + cases.push({ file, factoryName, schemaName, factory: factory as () => unknown, schema }); + } + } + return cases.sort((left, right) => left.factoryName.localeCompare(right.factoryName)); +} + +function valueAt(value: unknown, path: readonly PropertyKey[]): unknown { + let current = value; + for (const key of path) { + if (current === null || typeof current !== "object") { + return undefined; + } + current = (current as Record)[key]; + } + return current; +} + +function describeValue(value: unknown): string { + const text = JSON.stringify(value); + if (text === undefined) { + return String(value); + } + return text.length > 200 ? `${text.slice(0, 200)}...` : text; +} + +const cases = discoverCases(); + +describe("generated MSW response mocks", () => { + it("discovers a response factory for every generated mock module", () => { + expect(Object.keys(mockModules).length).toBeGreaterThan(0); + const covered = new Set(cases.map((item) => item.file)); + expect(Object.keys(mockModules).filter((file) => !covered.has(file))).toEqual([]); + }); + + it.each(cases)("$factoryName returns a valid $schemaName", ({ factory, schema }) => { + const failures: string[] = []; + for (const seed of seeds) { + faker.seed(seed); + const mock = factory(); + const result = schema.safeParse(mock); + if (result.success) { + continue; + } + for (const issue of result.error.issues) { + const path = issue.path.length > 0 ? issue.path.join(".") : "(root)"; + failures.push( + `seed ${seed}: ${path}: ${issue.message}; value ${describeValue(valueAt(mock, issue.path))}`, + ); + } + } + expect(failures).toEqual([]); + }); +}); + +describe("fakeFromPattern", () => { + const contractPatterns: readonly (readonly [string, PatternLengthBounds])[] = [ + ["^[A-Za-z0-9._-]+$", { minLength: 1, maxLength: 64 }], + ["^[A-Za-z0-9_-]+$", { minLength: 32, maxLength: 128 }], + ["^[a-z0-9][a-z0-9_.+#-]*$", { minLength: 1, maxLength: 64 }], + ["^[a-z0-9_+-]+$", { minLength: 1, maxLength: 32 }], + ["^[a-z0-9_]+$", { minLength: 1, maxLength: 64 }], + ["\\S", { minLength: 1, maxLength: 4000 }], + ["^\\S(?:.*\\S)?$", { minLength: 1, maxLength: 50 }], + ["^SC-[0-9]{4}-[0-9]{6,10}$", { minLength: 14, maxLength: 18 }], + ["^(/([^~/]|~[01])*)*$", { maxLength: 1024 }], + ["^(?:ab|cde)+$", { minLength: 5, maxLength: 5 }], + ]; + + it.each(contractPatterns)("matches /%s/ within %o", (pattern, bounds) => { + const regex = new RegExp(pattern, "u"); + for (const seed of Array.from({ length: 200 }, (_, index) => index)) { + faker.seed(seed); + const value = fakeFromPattern(pattern, bounds); + expect(regex.test(value), `seed ${seed}: ${JSON.stringify(value)}`).toBe(true); + expect(value.length).toBeGreaterThanOrEqual(bounds.minLength ?? 0); + expect(value.length).toBeLessThanOrEqual(bounds.maxLength ?? Number.POSITIVE_INFINITY); + } + }); + + it("returns the same value for the same faker seed", () => { + faker.seed(42); + const first = fakeFromPattern("^[A-Za-z0-9_-]+$", { minLength: 32, maxLength: 128 }); + faker.seed(42); + expect(fakeFromPattern("^[A-Za-z0-9_-]+$", { minLength: 32, maxLength: 128 })).toBe(first); + }); + + it("fails loudly instead of returning a value that the schema rejects", () => { + expect(() => fakeFromPattern("^a\\bb$")).toThrow("unsupported syntax: word boundary"); + expect(() => fakeFromPattern("^(?=a)a$")).toThrow("unsupported syntax: lookaround"); + expect(() => fakeFromPattern("^(a)\\1$")).toThrow("unsupported syntax: escape \\1"); + expect(() => fakeFromPattern("^[a-z]{2,3}$", { minLength: 5 })).toThrow( + "has no value with length 5..unbounded", + ); + expect(() => fakeFromPattern("^[a-")).toThrow("is not a valid Unicode regular expression"); + }); +});