initial commit
This commit is contained in:
commit
88c14b627e
224 files changed
+17204
No files matched your search
@@ -0,0 +1,20 @@
|
||||
.git
|
||||
**/.git
|
||||
**/node_modules
|
||||
**/dist
|
||||
**/coverage
|
||||
**/.venv
|
||||
**/__pycache__
|
||||
**/.pytest_cache
|
||||
**/.mypy_cache
|
||||
**/.ruff_cache
|
||||
**/.env
|
||||
**/.env.*
|
||||
backend/
|
||||
ml/
|
||||
api/
|
||||
observability/
|
||||
docs/
|
||||
deploy/**
|
||||
!deploy/nginx/
|
||||
!deploy/nginx/**
|
||||
@@ -0,0 +1,15 @@
|
||||
node_modules/
|
||||
dist/
|
||||
coverage/
|
||||
reports/
|
||||
playwright-report/
|
||||
test-results/
|
||||
.cache/
|
||||
.vite/
|
||||
.vitest/
|
||||
.turbo/
|
||||
*.tsbuildinfo
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
*.log
|
||||
@@ -0,0 +1 @@
|
||||
26.10.0
|
||||
@@ -0,0 +1,7 @@
|
||||
dist/
|
||||
coverage/
|
||||
node_modules/
|
||||
src/shared/api/endpoints/
|
||||
src/shared/api/schemas/
|
||||
scripts/fixtures/
|
||||
pnpm-lock.yaml
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"printWidth": 100,
|
||||
"singleQuote": false,
|
||||
"trailingComma": "all"
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
FROM node:alpine AS build
|
||||
|
||||
WORKDIR /workspace/frontend
|
||||
RUN npm install --global pnpm@12.9.1
|
||||
|
||||
COPY frontend/package.json frontend/pnpm-lock.yaml frontend/pnpm-workspace.yaml ./
|
||||
RUN pnpm install --frozen-lockfile
|
||||
|
||||
COPY frontend/ ./
|
||||
RUN pnpm run build
|
||||
|
||||
FROM nginxinc/nginx-unprivileged:alpine
|
||||
|
||||
COPY --from=build /workspace/frontend/dist/ /usr/share/nginx/html/
|
||||
COPY deploy/nginx/nginx.conf /etc/nginx/nginx.conf
|
||||
COPY deploy/nginx/conf.d/app.conf /etc/nginx/conf.d/default.conf
|
||||
|
||||
EXPOSE 8080
|
||||
USER 101
|
||||
|
||||
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 CMD ["wget", "-q", "-O", "/dev/null", "http://127.0.0.1:8080/healthz"]
|
||||
@@ -0,0 +1,43 @@
|
||||
.DEFAULT_GOAL := help
|
||||
.PHONY: help install dev build generate fmt fmt-check lint lint-fix typecheck test check verify
|
||||
|
||||
help: ## Show available frontend commands.
|
||||
@awk 'BEGIN {FS = ":.*## "} /^[a-zA-Z0-9_-]+:.*## / {printf "%-12s %s\n", $$1, $$2}' $(MAKEFILE_LIST)
|
||||
|
||||
install: ## Install frontend dependencies from the lockfile.
|
||||
pnpm install --frozen-lockfile
|
||||
|
||||
dev: ## Start the Vite development server.
|
||||
pnpm run dev
|
||||
|
||||
build: ## Build the static frontend.
|
||||
pnpm run build
|
||||
|
||||
generate: ## Generate API client, query hooks, schemas, and MSW handlers.
|
||||
@if [ "$${API_PREPARED:-0}" != "1" ]; then $(MAKE) -C ../api bundle; fi
|
||||
pnpm run generate
|
||||
|
||||
fmt: ## Format frontend source and configuration.
|
||||
pnpm run fmt
|
||||
|
||||
fmt-check: ## Check frontend formatting.
|
||||
pnpm run fmt:check
|
||||
|
||||
lint: ## Run TypeScript and CSS lint checks.
|
||||
pnpm run lint
|
||||
|
||||
lint-fix: ## Apply safe ESLint fixes.
|
||||
pnpm exec eslint . --fix --max-warnings=0
|
||||
|
||||
typecheck: ## Check strict TypeScript types.
|
||||
pnpm run typecheck
|
||||
|
||||
test: ## Run frontend unit tests.
|
||||
pnpm run test
|
||||
|
||||
check: ## Run formatting, lint, type, test, and build checks.
|
||||
pnpm run check
|
||||
|
||||
verify: ## Regenerate the API client and run all frontend checks.
|
||||
$(MAKE) generate
|
||||
$(MAKE) check
|
||||
@@ -0,0 +1,37 @@
|
||||
import { defineConfig } from "orval";
|
||||
|
||||
export default defineConfig({
|
||||
lincodex: {
|
||||
input: {
|
||||
target: "../../api/core/openapi.bundle.yml",
|
||||
},
|
||||
output: {
|
||||
mode: "tags-split",
|
||||
target: "../src/shared/api/endpoints",
|
||||
indexFiles: true,
|
||||
schemas: {
|
||||
path: "../src/shared/api/schemas",
|
||||
type: "zod",
|
||||
splitByTags: true,
|
||||
},
|
||||
client: "react-query",
|
||||
httpClient: "fetch",
|
||||
mock: {
|
||||
indexMockFiles: true,
|
||||
generators: [{ type: "msw" }],
|
||||
},
|
||||
override: {
|
||||
mutator: {
|
||||
path: "../src/shared/api/client.ts",
|
||||
name: "apiRequest",
|
||||
},
|
||||
fetch: {
|
||||
includeHttpResponseReturnType: false,
|
||||
},
|
||||
query: {
|
||||
signal: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,110 @@
|
||||
import js from "@eslint/js";
|
||||
import boundaries from "eslint-plugin-boundaries";
|
||||
import reactHooks from "eslint-plugin-react-hooks";
|
||||
import reactRefresh from "eslint-plugin-react-refresh";
|
||||
import tseslint from "typescript-eslint";
|
||||
|
||||
const layerNames = ["app", "pages", "widgets", "features", "entities", "shared"];
|
||||
const upwardPolicies = layerNames.flatMap((layer, index) => {
|
||||
const higherLayers = layerNames.slice(0, index);
|
||||
return higherLayers.length > 0
|
||||
? [
|
||||
{
|
||||
from: { element: { type: layer } },
|
||||
disallow: { to: { element: { type: higherLayers } } },
|
||||
},
|
||||
]
|
||||
: [];
|
||||
});
|
||||
const sliceLayers = ["pages", "widgets", "features", "entities"];
|
||||
const peerSlicePolicies = sliceLayers.flatMap((layer) => [
|
||||
{
|
||||
from: { element: { type: layer } },
|
||||
disallow: { to: { element: { type: layer } } },
|
||||
},
|
||||
{
|
||||
from: { element: { type: layer } },
|
||||
allow: {
|
||||
to: {
|
||||
element: {
|
||||
type: layer,
|
||||
captured: { slice: "{{from.element.captured.slice}}" },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
]);
|
||||
const publicEntryPolicies = layerNames.flatMap((sourceLayer, sourceIndex) =>
|
||||
sliceLayers
|
||||
.filter((targetLayer) => layerNames.indexOf(targetLayer) > sourceIndex)
|
||||
.flatMap((targetLayer) => [
|
||||
{
|
||||
from: { element: { type: sourceLayer } },
|
||||
disallow: { to: { element: { type: targetLayer } } },
|
||||
},
|
||||
{
|
||||
from: { element: { type: sourceLayer } },
|
||||
allow: {
|
||||
to: { element: { type: targetLayer, fileInternalPath: "index.ts" } },
|
||||
},
|
||||
},
|
||||
]),
|
||||
);
|
||||
|
||||
export default tseslint.config(
|
||||
{
|
||||
ignores: ["dist/**", "coverage/**", "src/shared/api/endpoints/**", "src/shared/api/schemas/**"],
|
||||
},
|
||||
js.configs.recommended,
|
||||
...tseslint.configs.recommended,
|
||||
{
|
||||
files: ["**/*.{ts,tsx}"],
|
||||
languageOptions: {
|
||||
parserOptions: {
|
||||
ecmaFeatures: { jsx: true },
|
||||
},
|
||||
},
|
||||
plugins: {
|
||||
boundaries,
|
||||
"react-hooks": reactHooks,
|
||||
"react-refresh": reactRefresh,
|
||||
},
|
||||
settings: {
|
||||
"boundaries/root-path": ".",
|
||||
"import/resolver": {
|
||||
node: { extensions: [".js", ".jsx", ".mjs", ".cjs", ".ts", ".tsx"] },
|
||||
},
|
||||
"boundaries/elements": [
|
||||
{ type: "app", pattern: "src/app", partialMatch: false },
|
||||
{ type: "pages", pattern: "src/pages/*", partialMatch: false, capture: ["slice"] },
|
||||
{ type: "widgets", pattern: "src/widgets/*", partialMatch: false, capture: ["slice"] },
|
||||
{
|
||||
type: "features",
|
||||
pattern: ["src/features/*", "scripts/fixtures/src/features/*"],
|
||||
partialMatch: false,
|
||||
capture: ["slice"],
|
||||
},
|
||||
{ type: "entities", pattern: "src/entities/*", partialMatch: false, capture: ["slice"] },
|
||||
{ type: "shared", pattern: "src/shared", partialMatch: false },
|
||||
],
|
||||
},
|
||||
rules: {
|
||||
...reactHooks.configs.flat.recommended.rules,
|
||||
"no-console": ["error", { allow: ["warn", "error"] }],
|
||||
"no-debugger": "error",
|
||||
"react-refresh/only-export-components": ["error", { allowConstantExport: true }],
|
||||
"boundaries/dependencies": [
|
||||
"error",
|
||||
{
|
||||
default: "allow",
|
||||
policies: [...upwardPolicies, ...peerSlicePolicies, ...publicEntryPolicies],
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
files: ["src/**/*.{ts,tsx}"],
|
||||
plugins: { boundaries },
|
||||
rules: { "boundaries/no-unknown-files": "error" },
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,13 @@
|
||||
<!doctype html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<meta name="theme-color" content="#f4f6f8" />
|
||||
<title>Lincodex</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/app/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,51 @@
|
||||
{
|
||||
"name": "lincodex-frontend",
|
||||
"private": true,
|
||||
"version": "0.1.0",
|
||||
"type": "module",
|
||||
"packageManager": "pnpm@12.9.1",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vite build",
|
||||
"preview": "vite preview",
|
||||
"generate": "orval --config ./codegen/orval.config.ts",
|
||||
"fmt": "prettier --write .",
|
||||
"fmt:check": "prettier --check .",
|
||||
"lint": "pnpm run lint:eslint && pnpm run lint:css",
|
||||
"lint:eslint": "eslint src codegen scripts/*.mjs *.mjs --max-warnings=0",
|
||||
"lint:css": "stylelint 'src/**/*.css' --max-warnings=0",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run",
|
||||
"test:fsd": "node ./scripts/test-fsd-boundaries.mjs",
|
||||
"check": "pnpm run fmt:check && pnpm run lint && pnpm run typecheck && pnpm run test && pnpm run test:fsd && pnpm run build",
|
||||
"verify": "pnpm run generate && pnpm run check"
|
||||
},
|
||||
"dependencies": {
|
||||
"@tanstack/react-query": "5.104.1",
|
||||
"react": "19.3.0",
|
||||
"react-dom": "19.3.0",
|
||||
"react-router-dom": "7.18.4",
|
||||
"zod": "4.6.5"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "10.0.1",
|
||||
"@faker-js/faker": "10.6.0",
|
||||
"@types/react": "19.3.0",
|
||||
"@types/react-dom": "19.3.0",
|
||||
"@typescript/native": "npm:typescript@7.0.2",
|
||||
"@vitejs/plugin-react": "6.1.2",
|
||||
"eslint": "10.12.0",
|
||||
"eslint-plugin-boundaries": "7.2.0",
|
||||
"eslint-plugin-react-hooks": "7.1.1",
|
||||
"eslint-plugin-react-refresh": "0.5.7",
|
||||
"msw": "3.0.2",
|
||||
"orval": "8.40.0",
|
||||
"prettier": "3.9.9",
|
||||
"stylelint": "17.16.0",
|
||||
"stylelint-config-standard": "40.0.0",
|
||||
"typescript": "npm:@typescript/typescript6@6.0.2",
|
||||
"typescript-eslint": "8.71.0",
|
||||
"vite": "8.3.2",
|
||||
"vitest": "5.0.3"
|
||||
}
|
||||
}
|
||||
Generated
+4797
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,22 @@
|
||||
autoInstallPeers: false
|
||||
minimumReleaseAge: 1440
|
||||
minimumReleaseAgeStrict: true
|
||||
minimumReleaseAgeExclude:
|
||||
- "@vitejs/plugin-react@6.1.2"
|
||||
- "orval@8.40.0"
|
||||
- "@orval/angular@8.40.0"
|
||||
- "@orval/axios@8.40.0"
|
||||
- "@orval/core@8.40.0"
|
||||
- "@orval/effect@8.40.0"
|
||||
- "@orval/fetch@8.40.0"
|
||||
- "@orval/hono@8.40.0"
|
||||
- "@orval/mcp@8.40.0"
|
||||
- "@orval/mock@8.40.0"
|
||||
- "@orval/pinia-colada@8.40.0"
|
||||
- "@orval/query@8.40.0"
|
||||
- "@orval/solid-start@8.40.0"
|
||||
- "@orval/swr@8.40.0"
|
||||
- "@orval/zod@8.40.0"
|
||||
allowBuilds:
|
||||
esbuild: true
|
||||
unrs-resolver: false
|
||||
@@ -0,0 +1 @@
|
||||
export { status } from "./model";
|
||||
@@ -0,0 +1 @@
|
||||
export const status = "available";
|
||||
@@ -0,0 +1 @@
|
||||
export { status } from "../../session";
|
||||
@@ -0,0 +1,3 @@
|
||||
import { status } from "../../session/model";
|
||||
|
||||
export const result = status;
|
||||
@@ -0,0 +1 @@
|
||||
export { status } from "./model";
|
||||
@@ -0,0 +1 @@
|
||||
export const status = "ready";
|
||||
@@ -0,0 +1,24 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { execPath } from "node:process";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { dirname, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const frontendRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");
|
||||
const eslintCli = resolve(frontendRoot, "node_modules/eslint/bin/eslint.js");
|
||||
const fixtures = [
|
||||
"scripts/fixtures/src/features/search/ui/search.ts",
|
||||
"scripts/fixtures/src/features/search/ui/entry.ts",
|
||||
];
|
||||
const result = spawnSync(execPath, [eslintCli, "--format", "json", ...fixtures], {
|
||||
cwd: frontendRoot,
|
||||
encoding: "utf8",
|
||||
});
|
||||
|
||||
assert.notEqual(result.status, 0, "ESLint accepted an import from a peer feature slice.");
|
||||
const reports = JSON.parse(result.stdout);
|
||||
assert.equal(reports.length, fixtures.length);
|
||||
for (const report of reports) {
|
||||
assert.equal(report.errorCount, 1);
|
||||
assert.equal(report.messages[0]?.ruleId, "boundaries/dependencies");
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { StrictMode } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { App } from "./ui/app";
|
||||
import "./ui/styles.css";
|
||||
|
||||
const rootElement = document.getElementById("root");
|
||||
|
||||
if (!rootElement) {
|
||||
throw new Error("The application root element is missing.");
|
||||
}
|
||||
|
||||
createRoot(rootElement).render(
|
||||
<StrictMode>
|
||||
<App />
|
||||
</StrictMode>,
|
||||
);
|
||||
@@ -0,0 +1,24 @@
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { BrowserRouter, Route, Routes } from "react-router-dom";
|
||||
import { HomePage } from "../../pages/home";
|
||||
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: {
|
||||
retry: false,
|
||||
staleTime: 30_000,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
export function App() {
|
||||
return (
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<BrowserRouter>
|
||||
<Routes>
|
||||
<Route path="*" element={<HomePage />} />
|
||||
</Routes>
|
||||
</BrowserRouter>
|
||||
</QueryClientProvider>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
:root {
|
||||
font-family:
|
||||
Inter,
|
||||
ui-sans-serif,
|
||||
system-ui,
|
||||
-apple-system,
|
||||
BlinkMacSystemFont,
|
||||
"Segoe UI",
|
||||
sans-serif;
|
||||
color: #15202b;
|
||||
background: #f4f6f8;
|
||||
font-synthesis: none;
|
||||
text-rendering: optimizelegibility;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
}
|
||||
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
body {
|
||||
min-width: 320px;
|
||||
min-height: 100vh;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
button,
|
||||
input,
|
||||
textarea {
|
||||
font: inherit;
|
||||
}
|
||||
Whitespace-only changes.
Whitespace-only changes.
@@ -0,0 +1 @@
|
||||
export { HomePage } from "./ui/home-page";
|
||||
@@ -0,0 +1,54 @@
|
||||
.page {
|
||||
display: grid;
|
||||
min-height: 100vh;
|
||||
padding: 2rem;
|
||||
place-items: center;
|
||||
}
|
||||
|
||||
.panel {
|
||||
width: min(100%, 38rem);
|
||||
padding: clamp(1.5rem, 5vw, 3rem);
|
||||
border: 1px solid #dce3e9;
|
||||
border-radius: 1.25rem;
|
||||
background: #fff;
|
||||
box-shadow: 0 1.5rem 4rem rgb(21 32 43 / 8%);
|
||||
}
|
||||
|
||||
.status-mark {
|
||||
display: block;
|
||||
width: 0.65rem;
|
||||
height: 0.65rem;
|
||||
margin-bottom: 1.75rem;
|
||||
border-radius: 50%;
|
||||
background: #477a68;
|
||||
}
|
||||
|
||||
.eyebrow {
|
||||
margin: 0 0 0.75rem;
|
||||
color: #52616f;
|
||||
font-size: 0.8rem;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.08em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.panel h1 {
|
||||
margin: 0;
|
||||
font-size: clamp(1.8rem, 5vw, 2.5rem);
|
||||
letter-spacing: -0.04em;
|
||||
line-height: 1.15;
|
||||
}
|
||||
|
||||
.description {
|
||||
max-width: 31rem;
|
||||
margin: 1rem 0 0;
|
||||
color: #52616f;
|
||||
font-size: 1rem;
|
||||
line-height: 1.65;
|
||||
}
|
||||
|
||||
@media (width <= 36rem) {
|
||||
.page {
|
||||
padding: 1rem;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import styles from "./home-page.module.css";
|
||||
|
||||
export function HomePage() {
|
||||
return (
|
||||
<main className={styles.page}>
|
||||
<section aria-labelledby="page-title" className={styles.panel}>
|
||||
<span aria-hidden="true" className={styles["status-mark"]} />
|
||||
<p className={styles.eyebrow}>Lincodex</p>
|
||||
<h1 id="page-title">Интерфейсная основа</h1>
|
||||
<p className={styles.description}>
|
||||
Сейчас доступен экран статуса каркаса. Пользовательские сценарии еще не подключены.
|
||||
</p>
|
||||
</section>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { z } from "zod";
|
||||
import { apiRequest } from "./client";
|
||||
import { getHealthz } from "./endpoints/health/health";
|
||||
|
||||
const healthSchema = z.object({ status: z.literal("ok") });
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
describe("apiRequest", () => {
|
||||
it("uses the shared request policy from generated operations", async () => {
|
||||
const signal = new AbortController().signal;
|
||||
const request = vi.fn().mockResolvedValue(
|
||||
new Response(JSON.stringify({ status: "ok" }), {
|
||||
headers: { "content-type": "application/json" },
|
||||
}),
|
||||
);
|
||||
vi.stubGlobal("fetch", request);
|
||||
|
||||
await expect(getHealthz({ signal })).resolves.toEqual({ status: "ok" });
|
||||
|
||||
expect(request).toHaveBeenCalledWith("/api/v1/healthz", {
|
||||
signal,
|
||||
method: "GET",
|
||||
credentials: "include",
|
||||
});
|
||||
});
|
||||
|
||||
it("adds the API prefix once, sends cookies, and forwards cancellation", async () => {
|
||||
const signal = new AbortController().signal;
|
||||
const request = vi.fn().mockImplementation(() =>
|
||||
Promise.resolve(
|
||||
new Response(JSON.stringify({ status: "ok" }), {
|
||||
headers: { "content-type": "application/json" },
|
||||
}),
|
||||
),
|
||||
);
|
||||
vi.stubGlobal("fetch", request);
|
||||
|
||||
const result = await apiRequest("/healthz", { signal }, healthSchema);
|
||||
await apiRequest("/api/v1/healthz", {}, healthSchema);
|
||||
|
||||
expect(result).toEqual({ status: "ok" });
|
||||
expect(request).toHaveBeenCalledTimes(2);
|
||||
expect(request).toHaveBeenNthCalledWith(1, "/api/v1/healthz", {
|
||||
signal,
|
||||
credentials: "include",
|
||||
});
|
||||
expect(request).toHaveBeenNthCalledWith(2, "/api/v1/healthz", {
|
||||
credentials: "include",
|
||||
});
|
||||
});
|
||||
|
||||
it("maps structured HTTP errors to a stable error type", async () => {
|
||||
const request = vi.fn().mockResolvedValue(
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
code: "service_unavailable",
|
||||
message: "Service unavailable",
|
||||
request_id: "req-test",
|
||||
}),
|
||||
{
|
||||
status: 503,
|
||||
headers: { "content-type": "application/json" },
|
||||
},
|
||||
),
|
||||
);
|
||||
vi.stubGlobal("fetch", request);
|
||||
|
||||
await expect(apiRequest("/healthz")).rejects.toMatchObject({
|
||||
name: "ApiRequestError",
|
||||
message: "Service unavailable",
|
||||
status: 503,
|
||||
code: "service_unavailable",
|
||||
requestId: "req-test",
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects an already-prefixed path before making a request", async () => {
|
||||
const request = vi.fn();
|
||||
vi.stubGlobal("fetch", request);
|
||||
|
||||
await expect(apiRequest("/api/v1/api/v1/healthz")).rejects.toThrow(
|
||||
"API paths must include the version prefix only once.",
|
||||
);
|
||||
expect(request).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,80 @@
|
||||
import { z } from "zod";
|
||||
|
||||
const apiPrefix = "/api/v1";
|
||||
const localOrigin = "http://lincodex.local";
|
||||
|
||||
const errorEnvelopeSchema = z
|
||||
.object({
|
||||
code: z.string().optional(),
|
||||
message: z.string().optional(),
|
||||
request_id: z.string().optional(),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
export class ApiRequestError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
readonly status: number,
|
||||
readonly code: string,
|
||||
readonly requestId: string | undefined,
|
||||
) {
|
||||
super(message);
|
||||
this.name = "ApiRequestError";
|
||||
}
|
||||
}
|
||||
|
||||
function buildApiUrl(path: string): string {
|
||||
const parsed = new URL(path, localOrigin);
|
||||
if (parsed.origin !== localOrigin) {
|
||||
throw new TypeError("API requests must use the current origin.");
|
||||
}
|
||||
|
||||
if (parsed.pathname.startsWith(`${apiPrefix}${apiPrefix}/`)) {
|
||||
throw new TypeError("API paths must include the version prefix only once.");
|
||||
}
|
||||
|
||||
const pathname =
|
||||
parsed.pathname === apiPrefix || parsed.pathname.startsWith(`${apiPrefix}/`)
|
||||
? parsed.pathname
|
||||
: `${apiPrefix}${parsed.pathname}`;
|
||||
return `${pathname}${parsed.search}`;
|
||||
}
|
||||
|
||||
async function toApiError(response: Response): Promise<ApiRequestError> {
|
||||
const body: unknown = await response.json().catch(() => undefined);
|
||||
const parsed = errorEnvelopeSchema.safeParse(body);
|
||||
|
||||
if (parsed.success) {
|
||||
return new ApiRequestError(
|
||||
parsed.data.message ?? `Request failed with status ${response.status}.`,
|
||||
response.status,
|
||||
parsed.data.code ?? "http_error",
|
||||
parsed.data.request_id,
|
||||
);
|
||||
}
|
||||
|
||||
return new ApiRequestError(
|
||||
`Request failed with status ${response.status}.`,
|
||||
response.status,
|
||||
"http_error",
|
||||
undefined,
|
||||
);
|
||||
}
|
||||
|
||||
export async function apiRequest<T>(
|
||||
path: string,
|
||||
init: RequestInit = {},
|
||||
responseSchema?: z.ZodType<T>,
|
||||
): Promise<T> {
|
||||
const response = await fetch(buildApiUrl(path), {
|
||||
...init,
|
||||
credentials: "include",
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw await toApiError(response);
|
||||
}
|
||||
|
||||
const body: unknown = response.status === 204 ? undefined : await response.json();
|
||||
return responseSchema ? responseSchema.parse(body) : (body as T);
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
/**
|
||||
* Generated by orval 🍺
|
||||
* Do not edit manually.
|
||||
* Lincodex API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
import {
|
||||
faker
|
||||
} from '@faker-js/faker';
|
||||
|
||||
import {
|
||||
HttpResponse,
|
||||
http
|
||||
} from 'msw';
|
||||
import type {
|
||||
RequestHandlerOptions
|
||||
} from 'msw';
|
||||
|
||||
import type {
|
||||
HealthResponse
|
||||
} from '../../schemas';
|
||||
|
||||
|
||||
export const getGetHealthzResponseMock = (overrideResponse: Partial<Extract<HealthResponse, object>> = {}): HealthResponse => ({status: faker.helpers.arrayElement(['ok'] as const), ...overrideResponse})
|
||||
|
||||
|
||||
export const getGetHealthzMockHandler = (overrideResponse?: HealthResponse | ((info: Parameters<Parameters<typeof http.get>[1]>[0]) => Promise<HealthResponse> | HealthResponse), options?: RequestHandlerOptions) => {
|
||||
return http.get('*/api/v1/healthz', async (info: Parameters<Parameters<typeof http.get>[1]>[0]) => {
|
||||
|
||||
|
||||
return HttpResponse.json(overrideResponse !== undefined
|
||||
? (typeof overrideResponse === "function" ? await overrideResponse(info) : overrideResponse)
|
||||
: getGetHealthzResponseMock(),
|
||||
{ status: 200
|
||||
})
|
||||
}, options)
|
||||
}
|
||||
export const getHealthMock = () => [
|
||||
getGetHealthzMockHandler()
|
||||
]
|
||||
@@ -0,0 +1,147 @@
|
||||
/**
|
||||
* Generated by orval 🍺
|
||||
* Do not edit manually.
|
||||
* Lincodex API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
import {
|
||||
useQuery
|
||||
} from '@tanstack/react-query';
|
||||
import type {
|
||||
DataTag,
|
||||
DefinedInitialDataOptions,
|
||||
DefinedUseQueryResult,
|
||||
QueryClient,
|
||||
QueryFunction,
|
||||
QueryKey,
|
||||
UndefinedInitialDataOptions,
|
||||
UseQueryOptions,
|
||||
UseQueryResult
|
||||
} from '@tanstack/react-query';
|
||||
|
||||
import type {
|
||||
HealthResponse
|
||||
} from '../../schemas';
|
||||
|
||||
import { apiRequest } from '../../client';
|
||||
|
||||
|
||||
type SecondParameter<T extends (...args: never) => unknown> = Parameters<T>[1];
|
||||
|
||||
|
||||
|
||||
const withQueryKey = <T extends object, K>(query: T, queryKey: K): T & { queryKey: K } => {
|
||||
const result = { queryKey } as T & { queryKey: K };
|
||||
for (const key of Object.keys(query)) {
|
||||
// The explicit queryKey always wins, matching the previous
|
||||
// `{ ...query, queryKey }` spread where it was set last.
|
||||
if (key === 'queryKey') continue;
|
||||
Object.defineProperty(result, key, {
|
||||
enumerable: true,
|
||||
configurable: true,
|
||||
get: () => (query as Record<string, unknown>)[key],
|
||||
});
|
||||
}
|
||||
return result;
|
||||
};
|
||||
|
||||
export const getGetHealthzUrl = () => {
|
||||
|
||||
|
||||
|
||||
|
||||
return `/api/v1/healthz`
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary Check whether the API process is responding.
|
||||
*/
|
||||
export const getHealthz = async ( options?: Parameters<typeof apiRequest>[1]): Promise<HealthResponse> => {
|
||||
|
||||
return apiRequest<HealthResponse>(getGetHealthzUrl(),
|
||||
{
|
||||
...options,
|
||||
method: 'GET'
|
||||
|
||||
|
||||
}
|
||||
);}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
export const getGetHealthzQueryKey = () => {
|
||||
return [
|
||||
`/api/v1/healthz`
|
||||
] as const;
|
||||
}
|
||||
|
||||
|
||||
export const getGetHealthzQueryOptions = <TData = Awaited<ReturnType<typeof getHealthz>>, TError = unknown>( options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getHealthz>>, TError, TData>>, request?: SecondParameter<typeof apiRequest>}
|
||||
) => {
|
||||
|
||||
const {query: queryOptions, request: requestOptions} = options ?? {};
|
||||
|
||||
const queryKey = queryOptions?.queryKey ?? getGetHealthzQueryKey();
|
||||
|
||||
|
||||
|
||||
const queryFn: QueryFunction<Awaited<ReturnType<typeof getHealthz>>> = ({ signal }) => getHealthz({ signal, ...requestOptions });
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
return { queryKey, queryFn, ...queryOptions} as UseQueryOptions<Awaited<ReturnType<typeof getHealthz>>, TError, TData> & { queryKey: DataTag<QueryKey, TData, TError> }
|
||||
}
|
||||
|
||||
export type GetHealthzQueryResult = NonNullable<Awaited<ReturnType<typeof getHealthz>>>
|
||||
export type GetHealthzQueryError = unknown
|
||||
|
||||
|
||||
export function useGetHealthz<TData = Awaited<ReturnType<typeof getHealthz>>, TError = unknown>(
|
||||
options: { query:Partial<UseQueryOptions<Awaited<ReturnType<typeof getHealthz>>, TError, TData>> & Pick<
|
||||
DefinedInitialDataOptions<
|
||||
Awaited<ReturnType<typeof getHealthz>>,
|
||||
TError,
|
||||
Awaited<ReturnType<typeof getHealthz>>
|
||||
> , 'initialData'
|
||||
>, request?: SecondParameter<typeof apiRequest>}
|
||||
, queryClient?: QueryClient
|
||||
): DefinedUseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
|
||||
export function useGetHealthz<TData = Awaited<ReturnType<typeof getHealthz>>, TError = unknown>(
|
||||
options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getHealthz>>, TError, TData>> & Pick<
|
||||
UndefinedInitialDataOptions<
|
||||
Awaited<ReturnType<typeof getHealthz>>,
|
||||
TError,
|
||||
Awaited<ReturnType<typeof getHealthz>>
|
||||
> , 'initialData'
|
||||
>, request?: SecondParameter<typeof apiRequest>}
|
||||
, queryClient?: QueryClient
|
||||
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
|
||||
export function useGetHealthz<TData = Awaited<ReturnType<typeof getHealthz>>, TError = unknown>(
|
||||
options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getHealthz>>, TError, TData>>, request?: SecondParameter<typeof apiRequest>}
|
||||
, queryClient?: QueryClient
|
||||
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
|
||||
/**
|
||||
* @summary Check whether the API process is responding.
|
||||
*/
|
||||
|
||||
export function useGetHealthz<TData = Awaited<ReturnType<typeof getHealthz>>, TError = unknown>(
|
||||
options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getHealthz>>, TError, TData>>, request?: SecondParameter<typeof apiRequest>}
|
||||
, queryClient?: QueryClient
|
||||
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> } {
|
||||
|
||||
const queryOptions = getGetHealthzQueryOptions(options)
|
||||
|
||||
const query = useQuery(queryOptions, queryClient) as UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> };
|
||||
|
||||
return withQueryKey(query, queryOptions.queryKey);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
export { getHealthMock } from './health/health.msw'
|
||||
@@ -0,0 +1 @@
|
||||
export * from './health/health';
|
||||
@@ -0,0 +1 @@
|
||||
export { ApiRequestError, apiRequest } from "./client";
|
||||
@@ -0,0 +1,26 @@
|
||||
import { setupServer } from "msw/node";
|
||||
import { afterAll, afterEach, beforeAll, expect, it, vi } from "vitest";
|
||||
import { getHealthz } from "./endpoints/health/health";
|
||||
import { getHealthMock } from "./endpoints/health/health.msw";
|
||||
import { HealthResponse } from "./schemas";
|
||||
|
||||
const server = setupServer(...getHealthMock());
|
||||
|
||||
beforeAll(() => server.listen({ onUnhandledFrame: "error" }));
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
server.resetHandlers();
|
||||
});
|
||||
afterAll(() => server.close());
|
||||
|
||||
it("serves the generated client through the generated MSW handler", async () => {
|
||||
const interceptedFetch = globalThis.fetch;
|
||||
// Node has no document origin for the browser client's relative URLs.
|
||||
vi.stubGlobal("fetch", (input: string, init?: RequestInit) =>
|
||||
interceptedFetch(new URL(input, "http://localhost"), init),
|
||||
);
|
||||
|
||||
const response = await getHealthz();
|
||||
|
||||
expect(HealthResponse.parse(response)).toEqual({ status: "ok" });
|
||||
});
|
||||
@@ -0,0 +1,14 @@
|
||||
/**
|
||||
* Generated by orval 🍺
|
||||
* Do not edit manually.
|
||||
* Lincodex API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
import * as zod from 'zod';
|
||||
|
||||
export const HealthResponse = zod.object({
|
||||
"status": zod.enum(['ok'])
|
||||
})
|
||||
|
||||
export type HealthResponse = zod.input<typeof HealthResponse>;
|
||||
export type HealthResponseOutput = zod.output<typeof HealthResponse>;
|
||||
@@ -0,0 +1,8 @@
|
||||
/**
|
||||
* Generated by orval 🍺
|
||||
* Do not edit manually.
|
||||
* Lincodex API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
|
||||
export * from './healthResponse.zod';
|
||||
@@ -0,0 +1,8 @@
|
||||
/**
|
||||
* Generated by orval 🍺
|
||||
* Do not edit manually.
|
||||
* Lincodex API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
|
||||
export * from './health';
|
||||
Whitespace-only changes.
Whitespace-only changes.
@@ -0,0 +1,3 @@
|
||||
export default {
|
||||
extends: ["stylelint-config-standard"],
|
||||
};
|
||||
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"useDefineForClassFields": true,
|
||||
"lib": ["ES2022", "DOM", "DOM.Iterable"],
|
||||
"module": "ESNext",
|
||||
"skipLibCheck": true,
|
||||
"moduleResolution": "Bundler",
|
||||
"verbatimModuleSyntax": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
"jsx": "react-jsx",
|
||||
"strict": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"noUncheckedIndexedAccess": true,
|
||||
"exactOptionalPropertyTypes": true,
|
||||
"types": ["vite/client", "vitest/globals"]
|
||||
},
|
||||
"include": ["src", "vite.config.ts", "codegen/**/*.ts"]
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import react from "@vitejs/plugin-react";
|
||||
import { defineConfig } from "vitest/config";
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [react()],
|
||||
server: {
|
||||
proxy: {
|
||||
"/api": {
|
||||
target: "http://127.0.0.1:8080",
|
||||
changeOrigin: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
test: {
|
||||
environment: "node",
|
||||
restoreMocks: true,
|
||||
},
|
||||
});
|
||||
Reference in new issue
Block a user