@hexlet/frontend-blog-server 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,5 @@
1
+ /**
2
+ * This file was auto-generated by openapi-typescript.
3
+ * Do not make direct changes to the file.
4
+ */
5
+ export {};
@@ -0,0 +1,9 @@
1
+ export declare const seedUsers: string[];
2
+ export declare const seedPassword = "password";
3
+ export declare const seedCategories: {
4
+ slug: string;
5
+ name: string;
6
+ }[];
7
+ type SeedArticle = [author: string, category: string, title: string, body: string];
8
+ export declare const seedArticles: SeedArticle[];
9
+ export {};
@@ -0,0 +1,189 @@
1
+ // Сид загружается при каждом старте сервера: данные живут в памяти,
2
+ // и после перезапуска блог возвращается к этому состоянию.
3
+ export const seedUsers = ["alice", "bob", "carol"];
4
+ export const seedPassword = "password";
5
+ export const seedCategories = [
6
+ { slug: "frontend", name: "Frontend" },
7
+ { slug: "backend", name: "Backend" },
8
+ { slug: "devops", name: "DevOps" },
9
+ { slug: "design", name: "Design" },
10
+ { slug: "career", name: "Career" },
11
+ { slug: "news", name: "News" },
12
+ ];
13
+ export const seedArticles = [
14
+ [
15
+ "alice",
16
+ "frontend",
17
+ "Как устроен виртуальный DOM",
18
+ "Виртуальный DOM это **описание** интерфейса в памяти.\n\nБиблиотека сравнивает два описания и меняет в браузере только разницу.",
19
+ ],
20
+ [
21
+ "bob",
22
+ "backend",
23
+ "REST API без лишних слов",
24
+ "Ресурс, метод и код ответа.\n\n- `GET` читает\n- `POST` создаёт\n- `DELETE` удаляет",
25
+ ],
26
+ [
27
+ "carol",
28
+ "design",
29
+ "Why spacing matters",
30
+ "Consistent spacing makes a page **readable**.\n\nPick a scale like 4, 8, 16, 32 and stick to it.",
31
+ ],
32
+ [
33
+ "alice",
34
+ "devops",
35
+ "Первый Dockerfile",
36
+ 'Образ собирается слоями.\n\n```dockerfile\nFROM node:22-slim\nWORKDIR /app\nCOPY . .\nRUN npm ci\nCMD ["npm", "start"]\n```',
37
+ ],
38
+ [
39
+ "bob",
40
+ "career",
41
+ "Как пройти первое собеседование",
42
+ "Готовьте рассказ о **своём** проекте.\n\nВас спросят, почему вы приняли то или иное решение.",
43
+ ],
44
+ [
45
+ "carol",
46
+ "news",
47
+ "TypeScript ships a native compiler",
48
+ "The new compiler is written in Go and is *much* faster on large projects.",
49
+ ],
50
+ [
51
+ "alice",
52
+ "frontend",
53
+ "CSS Grid за десять минут",
54
+ "Сетка задаётся на контейнере.\n\n```css\n.layout {\n display: grid;\n grid-template-columns: 1fr 3fr;\n}\n```",
55
+ ],
56
+ [
57
+ "bob",
58
+ "backend",
59
+ "Pagination patterns",
60
+ "Offset pagination is simple. Cursor pagination survives inserts.\n\nThis blog uses `page` and `perPage`.",
61
+ ],
62
+ [
63
+ "carol",
64
+ "design",
65
+ "Цвет и контраст",
66
+ "Текст должен читаться на любом фоне.\n\nПроверяйте контраст по [WCAG](https://www.w3.org/WAI/WCAG22/quickref/).",
67
+ ],
68
+ [
69
+ "alice",
70
+ "devops",
71
+ "Deploying from an image",
72
+ "Build once, run anywhere.\n\nThe same image runs on your laptop, in CI and in production.",
73
+ ],
74
+ [
75
+ "bob",
76
+ "career",
77
+ "Code review etiquette",
78
+ "Review the code, not the person.\n\n> Ask questions instead of giving orders.",
79
+ ],
80
+ [
81
+ "carol",
82
+ "news",
83
+ "Вышел Node.js 26",
84
+ "В новой версии стабилизировали **запуск TypeScript** без сборки.",
85
+ ],
86
+ [
87
+ "alice",
88
+ "frontend",
89
+ "Accessible forms",
90
+ "Every input needs a `label`.\n\nScreen readers announce the label when the field gets focus.",
91
+ ],
92
+ [
93
+ "bob",
94
+ "backend",
95
+ "Коды ответов HTTP",
96
+ "- `200` всё хорошо\n- `401` нужен вход\n- `403` вход есть, прав нет\n- `404` ничего не нашли",
97
+ ],
98
+ [
99
+ "carol",
100
+ "design",
101
+ "Typography basics",
102
+ "Use at most **two** typefaces.\n\nLine length around 60–75 characters reads best.",
103
+ ],
104
+ [
105
+ "alice",
106
+ "devops",
107
+ "Переменные окружения",
108
+ "Настройки приложения приходят из окружения.\n\nТак один образ работает и локально, и на хостинге.",
109
+ ],
110
+ [
111
+ "bob",
112
+ "career",
113
+ "Pet projects that get noticed",
114
+ "Ship something people can open.\n\nA live link beats a long README.",
115
+ ],
116
+ ["carol", "news", "Обновился Vite", "Сборка стала быстрее, а конфигурация осталась прежней."],
117
+ [
118
+ "alice",
119
+ "frontend",
120
+ "Markdown в браузере",
121
+ "Markdown превращается в HTML на клиенте.\n\nНе забывайте **очищать** результат перед вставкой в страницу.",
122
+ ],
123
+ [
124
+ "bob",
125
+ "backend",
126
+ "Tokens vs sessions",
127
+ "A bearer token travels in the `Authorization` header.\n\nThe server checks it on every request.",
128
+ ],
129
+ [
130
+ "carol",
131
+ "design",
132
+ "Пустые состояния",
133
+ "Пустой список тоже экран.\n\nПодскажите пользователю, что сделать дальше.",
134
+ ],
135
+ [
136
+ "alice",
137
+ "devops",
138
+ "Health checks",
139
+ "An endpoint like `/api/health` tells the platform that the app is alive.",
140
+ ],
141
+ [
142
+ "bob",
143
+ "career",
144
+ "Как читать вакансии",
145
+ "Требования в вакансии это пожелания.\n\nОткликайтесь, если совпадает больше половины.",
146
+ ],
147
+ [
148
+ "carol",
149
+ "news",
150
+ "Browsers ship the Popover API",
151
+ "Tooltips and menus without JavaScript libraries are now possible.",
152
+ ],
153
+ [
154
+ "alice",
155
+ "frontend",
156
+ "Состояние формы",
157
+ "Форма хранит значения, ошибки и признак отправки.\n\nНе давайте отправить форму дважды.",
158
+ ],
159
+ [
160
+ "bob",
161
+ "backend",
162
+ "Idempotent requests",
163
+ "`PUT` and `DELETE` can be repeated safely.\n\nThe like button in this blog relies on that.",
164
+ ],
165
+ [
166
+ "carol",
167
+ "design",
168
+ "Иконки и подписи",
169
+ "Иконка без подписи понятна не всем.\n\nДобавьте `aria-label` хотя бы для экранного диктора.",
170
+ ],
171
+ [
172
+ "alice",
173
+ "devops",
174
+ "Логи в продакшене",
175
+ "Пишите логи в stdout.\n\nХостинг сам соберёт их и покажет в панели.",
176
+ ],
177
+ [
178
+ "bob",
179
+ "career",
180
+ "Learning in public",
181
+ "Write about what you learn.\n\nThis blog is a good place to start.",
182
+ ],
183
+ [
184
+ "carol",
185
+ "news",
186
+ "Добро пожаловать в блог",
187
+ "Здесь пишут о **фронтенде**, бэкенде и карьере.\n\nЗарегистрируйтесь и опубликуйте первую статью.",
188
+ ],
189
+ ];
@@ -0,0 +1,58 @@
1
+ import type { components } from "./generated/api.js";
2
+ type Schemas = components["schemas"];
3
+ export type User = Schemas["User"];
4
+ export type Category = Schemas["Category"];
5
+ export interface StoredUser extends User {
6
+ passwordHash: string;
7
+ }
8
+ export interface StoredArticle {
9
+ id: number;
10
+ title: string;
11
+ body: string;
12
+ categoryId: number;
13
+ authorId: number;
14
+ createdAt: Date;
15
+ updatedAt: Date;
16
+ }
17
+ export interface StoredComment {
18
+ id: number;
19
+ articleId: number;
20
+ parentId: number | null;
21
+ authorId: number;
22
+ body: string;
23
+ createdAt: Date;
24
+ }
25
+ export declare const verifyPassword: (password: string, stored: string) => boolean;
26
+ export declare const createState: () => {
27
+ users: StoredUser[];
28
+ tokens: Map<string, number>;
29
+ categories: {
30
+ id: number;
31
+ slug: string;
32
+ name: string;
33
+ }[];
34
+ articles: StoredArticle[];
35
+ comments: StoredComment[];
36
+ likes: Set<string>;
37
+ addUser: (username: string, password: string) => StoredUser;
38
+ issueToken: (user: StoredUser) => string;
39
+ addArticle: (authorId: number, categoryId: number, title: string, body: string, at?: Date) => {
40
+ id: number;
41
+ title: string;
42
+ body: string;
43
+ categoryId: number;
44
+ authorId: number;
45
+ createdAt: Date;
46
+ updatedAt: Date;
47
+ };
48
+ addComment: (articleId: number, authorId: number, body: string, parentId: number | null) => {
49
+ id: number;
50
+ articleId: number;
51
+ parentId: number | null;
52
+ authorId: number;
53
+ body: string;
54
+ createdAt: Date;
55
+ };
56
+ };
57
+ export type State = ReturnType<typeof createState>;
58
+ export {};
@@ -0,0 +1,81 @@
1
+ import { randomBytes, randomUUID, scryptSync, timingSafeEqual } from "node:crypto";
2
+ import { seedArticles, seedCategories, seedPassword, seedUsers } from "./seed.js";
3
+ const hashPassword = (password) => {
4
+ const salt = randomBytes(16).toString("hex");
5
+ return `${salt}:${scryptSync(password, salt, 32).toString("hex")}`;
6
+ };
7
+ export const verifyPassword = (password, stored) => {
8
+ const [salt, hash] = stored.split(":");
9
+ return timingSafeEqual(Buffer.from(hash, "hex"), scryptSync(password, salt, 32));
10
+ };
11
+ export const createState = () => {
12
+ const users = [];
13
+ const tokens = new Map();
14
+ const categories = seedCategories.map((c, i) => ({ id: i + 1, ...c }));
15
+ const articles = [];
16
+ const comments = [];
17
+ // Ключ лайка: `${articleId}:${userId}`.
18
+ const likes = new Set();
19
+ const nextId = { user: 1, article: 1, comment: 1 };
20
+ const addUser = (username, password) => {
21
+ const user = { id: nextId.user++, username, passwordHash: hashPassword(password) };
22
+ users.push(user);
23
+ return user;
24
+ };
25
+ const issueToken = (user) => {
26
+ const token = randomUUID();
27
+ tokens.set(token, user.id);
28
+ return token;
29
+ };
30
+ const addArticle = (authorId, categoryId, title, body, at = new Date()) => {
31
+ const article = {
32
+ id: nextId.article++,
33
+ title,
34
+ body,
35
+ categoryId,
36
+ authorId,
37
+ createdAt: at,
38
+ updatedAt: at,
39
+ };
40
+ articles.push(article);
41
+ return article;
42
+ };
43
+ const addComment = (articleId, authorId, body, parentId) => {
44
+ const comment = {
45
+ id: nextId.comment++,
46
+ articleId,
47
+ parentId,
48
+ authorId,
49
+ body,
50
+ createdAt: new Date(),
51
+ };
52
+ comments.push(comment);
53
+ return comment;
54
+ };
55
+ for (const username of seedUsers)
56
+ addUser(username, seedPassword);
57
+ // Сид старше любой новой статьи: по часу между статьями, самая новая час назад.
58
+ const now = Date.now();
59
+ seedArticles.forEach(([author, category, title, body], i) => {
60
+ const authorId = users.find((u) => u.username === author).id;
61
+ const categoryId = categories.find((c) => c.slug === category).id;
62
+ addArticle(authorId, categoryId, title, body, new Date(now - (seedArticles.length - i) * 3_600_000));
63
+ });
64
+ const welcome = articles[articles.length - 1];
65
+ const question = addComment(welcome.id, users[0].id, "Отличный старт!", null);
66
+ addComment(welcome.id, users[1].id, "Согласен, жду новых статей.", question.id);
67
+ likes.add(`${welcome.id}:${users[0].id}`);
68
+ likes.add(`${welcome.id}:${users[1].id}`);
69
+ return {
70
+ users,
71
+ tokens,
72
+ categories,
73
+ articles,
74
+ comments,
75
+ likes,
76
+ addUser,
77
+ issueToken,
78
+ addArticle,
79
+ addComment,
80
+ };
81
+ };
package/package.json CHANGED
@@ -1,6 +1,52 @@
1
1
  {
2
2
  "name": "@hexlet/frontend-blog-server",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "Hexlet-provided backend for the blog project. Implements the contract/ OpenAPI in-memory and serves a built SPA.",
5
+ "type": "module",
6
+ "main": "dist/src/app.js",
7
+ "types": "dist/src/app.d.ts",
8
+ "bin": {
9
+ "frontend-blog-server": "dist/bin/cli.js"
10
+ },
11
+ "files": [
12
+ "dist",
13
+ "contract/openapi.yaml",
14
+ "contract/main.tsp",
15
+ "README.md"
16
+ ],
17
+ "publishConfig": {
18
+ "access": "public"
19
+ },
20
+ "engines": {
21
+ "node": ">=22"
22
+ },
23
+ "scripts": {
24
+ "build": "tsc -p tsconfig.json",
25
+ "gen:types": "openapi-typescript contract/openapi.yaml -o src/generated/api.ts && oxfmt src/generated/api.ts",
26
+ "dev": "fastify start -w -l info -P -a 0.0.0.0 -p 8080 -i tsx src/app.ts",
27
+ "start": "fastify start -l info -a 0.0.0.0 -p 8080 dist/src/app.js",
28
+ "test": "vitest run",
29
+ "typecheck": "tsc -p tsconfig.json --noEmit",
30
+ "lint": "oxlint && oxfmt --ignore-path=../.oxfmtignore --check",
31
+ "release": "release-it",
32
+ "prepublishOnly": "npm run build"
33
+ },
34
+ "license": "MIT",
35
+ "dependencies": {
36
+ "@fastify/static": "^10.1.8",
37
+ "cac": "^7.1.0",
38
+ "fastify": "^5.12.7",
39
+ "fastify-cli": "^8.0.3",
40
+ "zod": "^4.6.7"
41
+ },
42
+ "devDependencies": {
43
+ "@types/node": "^26.6.5",
44
+ "openapi-typescript": "^7.13.0",
45
+ "oxfmt": "^0.75.0",
46
+ "oxlint": "^1.90.0",
47
+ "release-it": "^21.1.1",
48
+ "tsx": "^4.23.15",
49
+ "typescript": "^5.9.3",
50
+ "vitest": "^5.0.5"
51
+ }
52
+ }