docs: refresh the technical and feature docs for v1.0.0

Every claim checked against the code.

- TECH-SPEC: current configs (React 19 / Vite 8 / Tailwind 4, the web vs
  Tauri build), Cloudflare hosting and the Worker, store versions and
  migrations, the backup format, engine rules added in 1.0, CI as it is.
- ARCHITECTURE: layers, web vs Tauri, routing and start-up, the engine,
  state, backup & restore, web delivery, the hardened Tauri shell.
- PACKAGING: tauri.conf and capabilities as shipped, the eleven
  name-only commands and what they guard, where desktop data lives, the
  first-start recovery of pre-1.0 files, the release workflows; the
  auto-update flow that never existed is gone.
- FEATURES, CONTENT-INVENTORY (+ vi): recounted from config (42 genres,
  16 store entries, 22 social/donate fields, 7 cross-post platforms,
  37 Vietnamese banks); shortcuts that never existed removed.
- DEVELOPMENT (+ vi): main-only branching, every npm script, Rust 1.90,
  Cloudflare local dev with test keys, the Rust checks.
- I18N: both namespaces and all seven registration places, including
  the check page's own language list; ROADMAP: v1.0.0 shipped + backlog.
- DISCLAIMER (vi): eight languages. The locale template script now
  prints the full registration checklist; a stale comment in main.tsx
  about the removed settings file is corrected.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
poli0981andClaude Opus 5.5 committed 2026-09-30 23:29:10 +07:00
1 parent bca589e169
commit 5b61533465
13 files changed
+2469 -1437

No files matched your search

+337 -262
View File
@@ -2,132 +2,157 @@
## YTDescGen — Technical Architecture
Reflects **v1.0.0**. Implementation details (configs, interfaces, file formats, CI) are in [TECH-SPEC.md](TECH-SPEC.md); desktop and Android builds in [PACKAGING.md](PACKAGING.md); running the web deployment in [HOSTING.md](HOSTING.md).
---
## 1. High-Level Architecture
```
┌─────────────────────────────────────────────────────────────┐
│ Presentation Layer │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌───────────────┐ │
│ │ Editor │ │ Output │ │ Profiles │ │ Batch / History│ │
│ │ Page │ │ Page │ │ Page │ │ Pages │ │
│ └────┬─────┘ └────┬─────┘ └────┬─────┘ └──────┬────────┘ │
│ │ │ │ │ │
│ ┌────┴─────────────┴────────────┴───────────────┴────────┐ │
│ │ Shared Components (ui/, editor/, output/) │ │
│ └────────────────────────────┬────────────────────────────┘ │
├───────────────────────────────┼──────────────────────────────┤
│ Application Layer │
│ ┌────────────┐ ┌───────────┴──────────┐ ┌──────────────┐ │
│ │ Hooks │ │ State (Zustand) │ │ i18next │ │
│ │ useGenerate │ │ editor / profile / │ │ locales/ │ │
│ │ useClipboard│ │ preset / history / │ │ en/vi/ja/ │ │
│ │ useCharCount│ │ settings │ │ es/ko/zh │ │
│ └──────┬─────┘ └───────────┬───────────┘ └──────┬───────┘ │
├─────────┼────────────────────┼──────────────────────┼────────┤
│ Core Engine Layer │
│ ┌──────┴────────────────────┴──────────────────────┴──────┐ │
│ │ engine/ (Pure TypeScript) │ │
│ │ ┌──────────────┐ ┌──────────────────┐ ┌──────────────┐ │ │
│ │ │ title-builder│ │description-builder│ │ tag-generator│ │ │
│ │ └──────┬───────┘ └────────┬─────────┘ └──────┬───────┘ │ │
│ │ └──────────────────┼───────────────────┘ │ │
│ │ ┌────────┴────────┐ │ │
│ │ │template-renderer│ │ │
│ │ └─────────────────┘ │ │
│ └──────────────────────────────────────────────────────────┘ │
├──────────────────────────────────────────────────────────────┤
│ Infrastructure Layer │
│ ┌────────────────┐ ┌───────────────┐ ┌─────────────────┐ │
│ │ localStorage │ │ File System │ │ Clipboard API │ │
│ │ (Web) │ │ (Tauri) │ │ │ │
│ └────────────────┘ └───────────────┘ └─────────────────┘ │
└──────────────────────────────────────────────────────────────┘
┌────────────────────────────────────────────────────────────────────┐
│ Presentation Layer │
│ Pages: Editor · Output · Profiles · History · Settings · Batch │
│ Social · Playlist · Logs · About · Legal (+ error pages) │
│ Shell: Sidebar · Header · MobileNav · CommandPalette (cmdk) │
│ Components: ui/ (Radix, Motion, sonner) · editor/ · output/ │
│ backup/ · profiles/ · presets/ · templates/ · … │
├────────────────────────────────────────────────────────────────────┤
│ Application Layer │
│ Hooks: useGeneratedOutput · useRenderOptions · useOutputCopy │
│ useOutputLimits · useStrictBlock · useSaveToHistory · … │
│ Stores (Zustand): editor · profiles · presets · templates │
│ history · settings · logs · pending-invalid │
│ i18next: 8 locales — en bundled, the other seven lazy-loaded │
│ utils/: backup/ · library-apply · store-paste · file-ops │
│ native · log-storage · validation · … │
├────────────────────────────────────────────────────────────────────┤
│ Core Engine Layer — src/engine/ (pure TypeScript) │
│ renderAll() in template-renderer │
│ ├─ title-builder │
│ ├─ description-builder ── rig-block · timeline-parser │
│ │ channel-phrase · endings-format │
│ └─ tag-generator │
│ Also: title-variants · limits · social-post-builder │
│ pinned-comment-builder · playlist-builder · graphics-vendor │
├────────────────────────────────────────────────────────────────────┤
│ Infrastructure Layer │
│ localStorage (every platform) · Clipboard API │
│ Web: File System Access API or a download │
│ Tauri: name-only Rust commands (backups, logs) · Save/Open │
│ dialogs run from Rust · opener plugin (external links) │
└────────────────────────────────────────────────────────────────────┘
```
**Error pages (v0.27):** `components/errors/` holds a reusable `ErrorPage`
(404/403/419/500/offline/runtime) driven by the pure `config/error-pages.ts`
map. The dedicated error routes (`/403`, `/419`, `/500`, `/offline`, catch-all
`*`) are declared as **siblings of the `AppShell` route group** in `App.tsx`, so
they render full-screen with no Sidebar/Header. `ErrorPage` is router-agnostic
(hash anchors + `history.back()`) so the root `ErrorBoundary` — mounted outside
`HashRouter` in `main.tsx` — can reuse it as its crash fallback.
The same source ships two ways:
```
One React source (src/), two Vite builds
┌──────────────────┴───────────────────┐
▼ ▼
┌──────────────────────────────────┐ ┌──────────────────────────────────┐
│ Web — ytgenerator.stream │ │ Tauri 2 — desktop and Android │
│ BrowserRouter (real paths) │ │ HashRouter (asset protocol) │
│ Build adds: static /legal pages, │ │ Build (TAURI_ENV_PLATFORM set): │
│ security.txt, analytics beacon │ │ es2020 target, no analytics │
│ Cloudflare Worker (worker/): │ │ Rust core (src-tauri/): │
│ Turnstile gate · headers · │ │ name-only file commands, │
│ /legal/* · static assets │ │ native dialogs, tray (desktop) │
│ Data: the browser's localStorage │ │ Data: WebView localStorage + │
│ │ │ app data dir (backups, logs) │
└──────────────────────────────────┘ └──────────────────────────────────┘
```
**Routing.** `App.tsx` picks the router at runtime: `BrowserRouter` on the web — the Worker serves the app shell for every route, and Web Analytics counts page views by path — and `HashRouter` inside Tauri, whose asset protocol has no server-side fallback. Before the router reads the URL, `main.tsx` rewrites an old web bookmark (`/#/output` → `/output`); Tauri keeps hash URLs.
**Route tree.** `/legal` and `/legal/:docId` (the Legal Center) sit outside the consent guard, so the consent screen can open each document. Everything else is inside `ConsentGuard`, a layout route that renders `ConsentGate` until the user has accepted the current terms version (`CURRENT_TERMS_VERSION` = 2 since v1.0.0). Inside it, `AppShell` holds the pages: the Editor (index route) stays in the entry bundle; Output, Profiles, History, Settings, Batch, Social, Playlist, Logs and About are `React.lazy` chunks, each wrapped in its own `ErrorBoundary` + `Suspense` so a crash on one page cannot blank the app. On the web, `/legal/<id>` loaded directly is the Worker's static page; navigated to inside the app, it is the Legal Center — the same URL either way.
**App shell.** `AppShell` combines a collapsible `Sidebar`, the `Header` top bar (output and interface languages, theme), `MobileNav` (a bottom bar on phones, with a "More" drawer), and three lazily loaded pieces: the ⌘/Ctrl + K `CommandPalette` (cmdk), the shortcut help and the backup `RestoreDialog`, mounted only while a restore is pending. UI primitives in `components/ui/` wrap Radix (Dialog, AlertDialog, Popover, Tooltip, Tabs, Switch, Checkbox, ToggleGroup); animation is Motion behind `LazyMotion` (its feature bundle loads after first paint, and `MotionConfig reducedMotion="user"` honours the OS setting); toasts are sonner.
**Error pages (v0.27).** `components/errors/` holds a reusable `ErrorPage` (404/403/419/500/offline/runtime) driven by the pure `config/error-pages.ts` map. The error routes (`/403`, `/419`, `/500`, `/offline`, catch-all `*`) are **siblings of the `AppShell` route group** inside the consent guard, so they render full-screen without the shell. `ErrorPage` is router-agnostic — Home is a plain location change (`/` on the web, `#/` in Tauri) and Back is `history.back()` — so the root `ErrorBoundary`, mounted in `main.tsx` outside the router, reuses it as its crash fallback.
**Start-up.** Before first paint:
1. `public/theme-init.js` (a plain script in `index.html`) applies the saved theme and sets `<html lang>` to the saved UI language, so a light-theme user sees no dark flash.
2. `main.tsx` rewrites old hash URLs (web), carries over a terms acceptance from the gate page's `ytg_terms` cookie (web), and registers a one-time reload for chunk files that a new deploy removed (`vite:preloadError`).
3. It loads the saved UI and output languages (capped at 2 s), applies the theme class, installs the external-link handler (Tauri: links open in the system browser through the opener plugin), then renders.
After mount, `App.tsx` starts a first-run draft in the Default Output Language, runs the Tauri data chores (`startAppData()`: legacy-file recovery, then automatic backups on desktop) before loading the persisted logs, prefetches the Output page when the browser is idle, and keeps i18next in step with the `appLanguage` setting.
## 2. Core Engine Design
Engine module chứa toàn bộ logic generate — **zero framework dependency**. Mọi function đều pure: input → string.
The engine holds all generation logic with **zero framework dependency**: no React, no DOM, no storage, no clipboard. Every function is pure — typed input in, string (or list) out. Values from the environment come from the caller: the translator `t`, and the year for the copyright line and trending tags (the builders fall back to the current year when it is omitted).
| Module | Role |
| -------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `template-renderer.ts` | `renderAll(input, t, options)` → `GeneratorOutput`: title + description + tags, character counts, over-limit warnings |
| `title-builder.ts` | Titles: video-type segment, quality badge (position, case), separator, order (game first / video first) |
| `title-variants.ts` | Three alternative title shapes, each built by `buildTitle` with a different order / badge position |
| `description-builder.ts` | The description, block by block (intro, timestamps, store links, video settings, rig, warnings, notes, donate, social, community, contact, copyright, …) |
| `tag-generator.ts` | Tag pools, de-duplication, YouTube's own tag-length count (`youtubeTagsLength`) and trimming |
| `timeline-parser.ts` | Timestamps → translated chapter lines; YouTube's chapter rules (`checkChapters`); "Tidy up" (`normalizeTimeline`) |
| `channel-phrase.ts` | Drops "on {{channelName}}" (per language) when the channel name is empty |
| `rig-block.ts` | The rig as localised `Label: value` lines in a fixed order (description and social captions) |
| `endings-format.ts`, `graphics-vendor.ts` | Endings lists split across videos; valid upscaler / frame-generation options per vendor |
| `limits.ts` | Over-limit status per field, Copy All rules, `<` / `>` detection |
| `social-post-builder.ts` | Captions for TikTok, YouTube Shorts, Instagram Reels, Facebook Reels, X (weighted count), Threads, Bluesky |
| `pinned-comment-builder.ts`, `playlist-builder.ts` | Pinned comment; playlist title, description and comment |
| `types.ts` | `GeneratorInput`, `GeneratorOutput`, `YT_LIMITS`, the option unions |
### 2.1 Type Definitions (`engine/types.ts`)
```typescript
// ── Video Types ──
// ── Video types (20) ──
// prettier-ignore
type VideoType =
| "full" // Full Gameplay
| "part" // Gameplay Part X
| "boss" // Boss Fight
| "boss_nohit" // Boss No Hit
| "ending" // Ending / All Endings
| "speedrun" // Speedrun
| "100percent" // 100% Completion
| "dlc" // DLC Content
| "newgame_plus" // New Game+
| "challenge" // Challenge Run
| "side_quest" // Side Quest / Optional Content
| "secret" // Secret / Hidden Content
| "comparison" // Graphics / Version Comparison
| "guide"; // Silent Guide / Walkthrough
| "full" | "part" | "full_demo" | "demo_part"
| "boss" | "boss_nohit" | "ending" | "speedrun" | "100percent"
| "dlc" | "newgame_plus" | "challenge" | "side_quest" | "secret"
| "comparison" | "guide" | "mods" | "collectibles" | "livestream" | "gacha_quest";
// ── Genre ──
// ── Genres (42, up to 3 per video — MAX_GENRES) ──
// prettier-ignore
type Genre =
| "action" | "horror" | "rpg" | "fps" | "openworld"
| "indie" | "soulslike" | "racing" | "story" | "simulation"
| "fighting" | "stealth" | "survival_craft" | "mmo"
| "rhythm" | "puzzle" | "roguelike" | "metroidvania"
| "tower_defense" | "card_game" | "battle_royale"
| "crpg" | "tactical" | "space" | "farming";
| "action" | "hack_slash" | "beatemup" | "platformer"
| "horror" | "survival_horror" | "psychological_horror"
| "rpg" | "jrpg" | "action_rpg" | "crpg"
| "fps" | "arena_shooter" | "tactical_fps" | "boomer_shooter" | "extraction_shooter" | "shmup"
| "openworld" | "indie" | "soulslike" | "racing" | "story" | "simulation" | "city_builder"
| "fighting" | "stealth" | "survival_craft" | "roguelike" | "metroidvania" | "mmo"
| "rhythm" | "puzzle" | "tower_defense" | "card_game" | "deck_builder" | "auto_battler"
| "battle_royale" | "tactical" | "space" | "farming" | "fmv" | "visual_novel";
// ── Supported Languages ──
type SupportedLanguage = "en" | "vi" | "ja" | "es" | "ko" | "zh"
| "fr" | "de" | "pt" | "ru" | "th" | "ar";
// ── Supported languages (8) ──
type SupportedLanguage = "en" | "vi" | "ja" | "es" | "ko" | "zh" | "pt-BR" | "id";
// ── Input State ──
// ── Input (abridged — about 75 fields) ──
interface GeneratorInput {
// Core
videoType: VideoType;
language: SupportedLanguage;
genre: Genre;
genres: Genre[];
// Game info
// Game and channel
gameName: string;
gameNameLocalized?: Record<SupportedLanguage, string>; // optional localized game name
channelName: string;
gameNameLocalized?: Partial<Record<SupportedLanguage, string>>;
channelName: string; // may be empty
platform: string;
// Video type-specific
partNumber?: string;
bossName?: string;
dlcName?: string;
challengeName?: string;
// Video-type specific: partNumber, bossName, dlcName, challengeName, modName, modList,
// liveUrl, scheduledTime, gacha quest fields …
// Video settings: resolution, fps, graphicsPreset, ray tracing, frame generation,
// upscaling, artStyle, videoStyleEra, versionInfo …
// Content: timestamps, playlistLink, emails, music, sponsor, publisher, content warnings,
// tech notes, playthrough notes, endings, playtest, community links …
// Video settings
resolution?: string;
fps?: string;
graphicsPreset?: string;
// Content
timestamps?: string;
playlistLink?: string;
contactEmail?: string;
// Warnings
// Deprecated since v0.11 (folded into contentWarnings), kept for old drafts
spoilerWarning: boolean;
matureWarning: boolean;
// Links
storeLinks: Record<string, string>;
social: Record<string, string>;
rig: Record<string, string>;
// Links and hardware
storeLinks: Partial<Record<string, string>>;
storeLinkTypes?: Partial<Record<string, StoreLinkType>>; // "paid" | "free" | "demo"
social: Partial<Record<string, string>>;
rig: Partial<Record<string, string>>; // GPU as "gpu:<catalog id>" since v1.0.0
}
// ── Output ──
@@ -139,33 +164,29 @@ interface GeneratorOutput {
charCounts: {
title: number;
description: number;
tags: number;
tags: number; // YouTube's count: quotes around multi-word tags + commas
};
warnings: string[]; // e.g. "Tags exceed 500 character limit"
warnings: CharLimitWarning[]; // one per field strictly over its limit
}
```
### 2.2 Template Architecture
Templates sử dụng **data-driven approach** thay vì hardcode string concatenation:
Templates are **data-driven**: every sentence the engine writes comes from the output language's `templates.json`, not from string concatenation in code. The engine interpolates `{{placeholders}}` through `t`. An excerpt of `src/i18n/locales/en/templates.json`:
```typescript
// i18n/locales/en/templates.json
```json
{
"title": {
"separator": " — ",
"separators": { "emDash": " — ", "hyphen": " - ", "colon": ": ", "pipe": " | " },
"suffix": "Gameplay No Commentary",
"videoType": {
"full": "",
"part": "Part {{partNumber}}",
"full_demo": "Demo",
"demo_part": "Demo Part {{partNumber}}",
"boss": "{{bossName}} Boss Fight",
"boss_nohit": "{{bossName}} Boss No Hit",
"ending": "Ending",
"speedrun": "Speedrun",
"100percent": "100% Completion",
"dlc": "{{dlcName}} DLC",
"newgame_plus": "New Game+",
"challenge": "{{challengeName}} Challenge"
"boss_nohit": "{{bossName}} Boss No Hit"
}
},
"description": {
@@ -176,224 +197,278 @@ Templates sử dụng **data-driven approach** thay vì hardcode string concaten
"noCommentaryLine": "No Commentary — pure gameplay for your enjoyment.",
"sections": {
"timestamps": "⏱ TIMESTAMPS",
"storeLinks": "🎮 GET THE GAME",
"videoSettings": "🖥 VIDEO SETTINGS: {{settings}}",
"storeLinksBuy": "🎮 GET THE GAME (if you want to buy)",
"storeLinksDownload": "⬇️ DOWNLOAD THE GAME (if you want to play)",
"videoSettings": "🖥 VIDEO SETTINGS",
"rig": "💻 MY RIG",
"spoilerWarning": "⚠️ SPOILER WARNING: This video contains spoilers.",
"matureWarning": "🔞 MATURE CONTENT (18+): Contains violence / strong language.",
"playlist": "▶️ Watch the full series: {{link}}",
"contact": "📧 Business inquiries: {{email}}",
"cta": "👍 Like | 🔔 Subscribe | ↗️ Share"
}
},
"rigLabels": { "cpu": "CPU", "gpu": "GPU", "ram": "RAM" }
}
}
```
The file's top-level sections are `title`, `description`, `pinnedComment`, `hashtags`, `playlist` and `timeline` (the translated chapter keywords). When the channel name is empty, the builders render `{{channelName}}` as a placeholder slot and `channel-phrase.ts` removes the words around it, per language.
### 2.3 Tag Generator Architecture
```
TagGenerator Pipeline:
┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐
│ Core Pool│───→│Genre Pool│───→│ Platform │───→│ Quality │
│ (always) │ │(by genre)│ │ Pool │ │ Pool │
└──────────┘ └──────────┘ └──────────┘ └──────────┘
│ │ │ │
└───────────────┴──────────────┴───────────────┘
│
┌─────────┴─────────┐
│ VideoType Pool │
│ (boss, speedrun…) │
└─────────┬─────────┘
│
┌─────────┴─────────┐
│ Multilingual Pool │
│ (JA, VI, ES…) │
└─────────┬─────────┘
│
┌─────────┴─────────┐
│ Trending Pool │
│ (year-based) │
└─────────┬─────────┘
│
┌─────────┴─────────┐
│ Dedup (Set) │
│ + Priority Sort │
│ + 500 char trim │
└───────────────────┘
generateTags(input, { includeMultilingualTags, includeTrendingTags, year })
priority pool source
1 game name bare tag (≤ 30 chars) + a shorter form for composites
2 core CORE_TAGS_BY_LANG[language]
3 genre GENRE_TAG_REGISTRY[genre], for every selected genre
4 video type VIDEO_TYPE_TAGS[videoType]
5 platform PLATFORMS[].tagName ("Steam", "itch.io", …)
6 quality resolution / fps
7 multilingual MULTILINGUAL_TAGS[language] (setting)
8 trending year-based, first genre only (setting)
9 publisher/developer pubDevName, as a bare tag
│
▼
de-duplicate (case-insensitive) · drop tags over 30 characters
│
▼
trimToCharLimit(tags, 500): keep tags in priority order while they fit,
measured the way YouTube measures them (youtubeTagsLength); a tag that
doesn't fit is skipped and the shorter ones after it are still tried
```
Tag pools là registry pattern — thêm genre mới chỉ cần thêm 1 entry:
The pools are registries — a new genre is one entry in `GENRE_TAG_REGISTRY` plus its search term in `GENRE_SEARCH_TERMS` (used by the trending tags), and `tests/engine/tag-generator.test.ts` fails if either disagrees with `config/genres.ts`:
```typescript
// engine/tag-generator.ts
const TAG_REGISTRY: Record<Genre, (gameName: string) => string[]> = {
action: (g) => [`${g} action`, "action game no commentary", "action adventure gameplay"],
horror: (g) => [`${g} horror`, "horror game no commentary", "survival horror gameplay"],
// ... thêm genre ở đây
export const GENRE_TAG_REGISTRY: Record<string, (gameName: string) => string[]> = {
action: (g) => [
`${g} action`,
"action game no commentary",
"action adventure gameplay",
`${g} combat`,
],
// … one entry per genre in config/genres.ts
};
```
## 3. State Architecture
```
Zustand Stores:
┌───────────────────────────────────────────────┐
│ EditorStore │
│ - videoType, language, genre │
│ - gameName, channelName, platform │
│ - timestamps, storeLinks, rig, social │
│ - spoilerWarning, matureWarning │
│ Middleware: none (ephemeral per session) │
│ + persist: auto-save draft (debounced) │
├───────────────────────────────────────────────┤
│ ProfileStore │
│ - profiles: Profile[] │
│ - activeProfileId: string | null │
│ Middleware: persist (localStorage) │
├───────────────────────────────────────────────┤
│ PresetStore │
│ - gamePresets: GamePreset[] │
│ Middleware: persist (localStorage) │
├───────────────────────────────────────────────┤
│ HistoryStore │
│ - entries: HistoryEntry[] (max 100) │
│ Middleware: persist (localStorage, pruned) │
├───────────────────────────────────────────────┤
│ SettingsStore │
│ - theme: "dark" | "light" │
│ - appLanguage / defaultOutputLanguage │
│ - strictMode, settingsAccordionState (v12) │
│ - (flags: quality badge / copyright / ...) │
│ Middleware: persist (localStorage + file) │
├───────────────────────────────────────────────┤
│ PendingInvalidStore (0.35) │
│ - entries: Record<fieldId, PendingInvalid> │
│ Middleware: NONE — in-flight typing, not data │
└───────────────────────────────────────────────┘
┌────────────────────────────────────────────────────────────────────┐
│ EditorStore — "ytdescgen-editor-draft", v19 │
│ - the draft: every form field (EditorData) + setter actions │
│ - persists data only (editorDataOf); migrateEditorState │
├────────────────────────────────────────────────────────────────────┤
│ ProfileStore — "ytdescgen-profiles", v3 │
│ - profiles: Profile[] — channel fields (PROFILE_FIELDS) │
├────────────────────────────────────────────────────────────────────┤
│ PresetStore — "ytdescgen-presets", v2 │
│ - presets: GamePreset[] — per-game fields (PRESET_FIELDS) │
├────────────────────────────────────────────────────────────────────┤
│ TemplateStore — "ytdescgen-templates", v2 │
│ - templates: EditorTemplate[] — whole-form snapshots │
├────────────────────────────────────────────────────────────────────┤
│ HistoryStore — "ytdescgen-history", v3 │
│ - entries: HistoryEntry[] — one per video, newest first │
│ - capped by the History Limit setting (10–500, default 100) │
├────────────────────────────────────────────────────────────────────┤
│ SettingsStore — "ytdescgen-settings", v12 │
│ - theme · appLanguage · defaultOutputLanguage · titleFormat │
│ - description toggles · strictMode · copyAllIncludesTags · … │
│ - healSettings on every load; consent and UI state never exported │
├────────────────────────────────────────────────────────────────────┤
│ LogStore — not persisted by Zustand │
│ - ≤ 2000 entries in memory; log-storage.ts mirrors each entry │
│ - (web: localStorage "ytdescgen-logs"; Tauri: daily JSONL files) │
├────────────────────────────────────────────────────────────────────┤
│ PendingInvalidStore — not persisted (v0.35) │
│ - typed text that is invalid and therefore not saved │
├────────────────────────────────────────────────────────────────────┤
│ useRestoreDialog (utils/backup) — not persisted │
│ - the file waiting in the restore dialog │
└────────────────────────────────────────────────────────────────────┘
```
Every persisted store uses Zustand `persist` with `createJSONStorage(() => localStorage)` — **the only store on every platform**. The Tauri "mirror" file of earlier versions is gone (see [PACKAGING.md](PACKAGING.md) for how its leftovers are recovered). Each store exports its version and its migration function (`EDITOR_STORE_VERSION` / `migrateEditorState`, `PROFILE_STORE_VERSION` / `migrateProfilesState`, `PRESET_STORE_VERSION` / `migratePresetsState`, `TEMPLATE_STORE_VERSION` / `migrateTemplatesState`, `HISTORY_STORE_VERSION` / `migrateHistoryState`, `SETTINGS_STORE_VERSION` / `healSettings`). The migrations are idempotent and shared with backup import, which replays them from the version a file records (section 5).
### Profiles, presets and templates
`src/config/library-fields.ts` is the one list of which editor fields each kind of library item carries — the save forms, Apply, backups and imports all read it:
- **Profile** = the channel: `PROFILE_FIELDS` (channel name, emails, social, rig, resolution / fps / graphics preset, ad text, Vietnamese donate fields, community links).
- **Preset** = the game: `PRESET_FIELDS` (names, genres, platform, store links and their types, publisher, content warnings, language patch, game version, art style, the skip-graphics-settings switch, playlist link).
- **Template** = the whole form (every field since v1.0.0).
- `PER_VIDEO_FIELDS` is what belongs to one video only (boss, chapter, timestamps, pinned comment, endings, …).
`src/utils/library-apply.ts` does everything that fills or clears the editor in one go, each with Undo (the editor is snapshotted first): apply a profile / preset / template, **Next part** (part number + 1, per-video fields cleared), **New video, same game**, and **Start over** (keeps the profile fields and starts in the Default Output Language). Applying a preset for another game also clears the per-video fields. `QuickStart` (top of the editor) remembers the last profile and preset (`lastProfileId`, `lastPresetId`) and asks before overwriting filled-in fields. `src/utils/store-paste.ts` routes a store link pasted anywhere in the editor to the right store field (matching `PLATFORMS[].urlPattern`), sets the platform for the first link, and fills an empty game name from the URL (`url-extractors.ts`).
### Settings → engine options
`renderAll` is called from three places (the Output hook, the multi-language
Output hook, BatchPage). Each used to hand-copy the same twelve settings fields
into an options object, and they had drifted — BatchPage's copy silently omitted
`splitContactEmail` and `showThirdPartyAds`, so Batch rendered a different
description than Output from identical data.
`renderAll` is called from three places (the Output hook, the multi-language Output hook, BatchPage). Each used to hand-copy the same twelve settings fields into an options object, and they had drifted — BatchPage's copy silently omitted `splitContactEmail` and `showThirdPartyAds`, so Batch rendered a different description than Output from identical data.
`src/hooks/use-render-options.ts` is now the single mapping, with two guards:
- **Compile-time** — `buildRenderOptions` builds a
`Required<SettingsRenderOptions>`, so omitting a key is a type error.
- **Runtime** — `tests/hooks/render-options-parity.test.ts` diffs the produced
keys against `SETTINGS_DERIVED_RENDER_KEYS` in both directions.
- **Compile-time** — `buildRenderOptions` builds a `Required<SettingsRenderOptions>`, so omitting a key is a type error.
- **Runtime** — `tests/hooks/render-options-parity.test.ts` diffs the produced keys against `SETTINGS_DERIVED_RENDER_KEYS` in both directions.
`RenderOptions` is split accordingly: `SettingsRenderOptions` (from the user)
plus `RenderOptionOverrides` (`tEn`, `bilingualContentBlocks` — decided per call
site, since Output wants bilingual content blocks and Batch does not).
`RenderOptions` is split accordingly: `SettingsRenderOptions` (from the user) plus `RenderOptionOverrides` (`tEn`, `bilingualContentBlocks`, `year` — decided per call site, since Output wants bilingual content blocks and Batch does not).
### Validation state
Two sources, unioned by `useStrictBlock`, because neither alone is sufficient:
| Source | Catches | Why it's needed |
|---|---|---|
| `collectEditorIssues` (pure, over `EditorData`) | Saved values that fail validation | Bad data from imports — `ValidatedInput` refuses to commit invalid text, so imports are the main way it gets in |
| `PendingInvalidStore` | Typed text that is invalid and therefore **not** saved | Otherwise a field showing a red error is invisible to every gate, because the store behind it holds the last good value |
| Source | Catches | Why it's needed |
| ----------------------------------------------- | ------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------- |
| `collectEditorIssues` (pure, over `EditorData`) | Saved values that fail validation | Bad data from imports — `ValidatedInput` refuses to commit invalid text, so imports are the main way it gets in |
| `PendingInvalidStore` | Typed text that is invalid and therefore **not** saved | Otherwise a field showing a red error is invisible to every gate, because the store behind it holds the last good value |
Both are filtered through `isRelevantIssueId`, so a field that isn't currently
shown (`adEmail` with split-email off, `zaloGroupLink` outside Vietnamese
output) can never block on a value with no visible input to fix it.
Both are filtered through `isRelevantIssueId`, so a field that isn't currently shown (`adEmail` with split-email off, `zaloGroupLink` outside Vietnamese output) can never block on a value with no visible input to fix it. Strict Mode is opt-in; with it off, no gate blocks.
The first implementation registered issues from the inputs themselves and
cleared on unmount. It typechecked and had passing tests, and did nothing: the
fields live on the Editor page while the gates live on Batch / Social / Output,
so navigating away cleared every issue. Deriving from state removes the mount
coupling entirely.
The first implementation registered issues from the inputs themselves and cleared on unmount. It typechecked and had passing tests, and did nothing: the fields live on the Editor page while the gates live on Batch / Social / Output, so navigating away cleared every issue. Deriving from state removes the mount coupling entirely.
## 4. i18n Architecture
```
i18n/locales/
├── en/
│ ├── ui.json # UI strings: buttons, labels, tooltips, errors
│ └── templates.json # Generated content: title patterns, description sections
├── vi/
│ ├── ui.json
│ └── templates.json
├── ja/
│ ├── ui.json
│ └── templates.json
└── _schema.json # JSON Schema — validates all locale files have same keys
i18n/
├── index.ts # i18next setup + SUPPORTED_LANGUAGES
└── locales/
├── en/
│ ├── ui.json # UI strings: buttons, labels, tooltips, errors
│ └── templates.json # Generated content: titles, description blocks, pinned comment, playlist, chapter keywords
├── vi/ ja/ es/ ko/ zh/ pt-BR/ id/
│ ├── ui.json
│ └── templates.json
└── _schema.json # the expected key list for both namespaces
```
**Adding a new language** = 2 JSON files + 1 line registration. See docs/I18N.md.
`npm run validate:locales` checks every locale against `_schema.json`, and `tests/i18n/locale-registration.test.ts` checks the language list against the locale folders in both directions. **Adding a language** is two JSON files plus registration: the `SupportedLanguage` union, `SUPPORTED_LANGUAGES`, `detectBrowserLanguage` in `settings-heal.ts`, and the per-language records TypeScript enforces (the tag pools in `tag-generator.ts`, the channel-phrase patterns in `channel-phrase.ts`). The Turnstile gate page keeps its own strings and language list in `worker/gate-i18n.ts`. See [I18N.md](I18N.md).
**Lazy loading (v0.26+)**: only English is bundled into the main chunk — it is the `fallbackLng` and the engine's bilingual `tEn` translator, both of which must resolve synchronously. Every other language is fetched on first use as a Vite async chunk via `i18next-resources-to-backend` + dynamic `import()`. Generation paths gate on bundle readiness (`useLanguagesReady` hook / `ensureLanguagesLoaded`): an unloaded language would otherwise silently render English fallback output. A chunk that fails to fetch degrades to English and logs to the in-app Log page — it never hangs the UI.
**UI language vs Output language**: These are independent. User can browse the app in English but generate descriptions in Japanese. UI language follows `SettingsStore.defaultLanguage`, output language follows `EditorStore.language`.
**UI language vs output language**: independent. The UI follows `SettingsStore.appLanguage` (loaded before the first render in `main.tsx`, then kept in step with i18next by `App.tsx`); the generated text follows `EditorStore.language`. A new draft — first run or Start over — starts in `SettingsStore.defaultOutputLanguage`. Both settings default to the browser's language when it is supported.
## 5. Desktop Packaging (Tauri)
## 5. Backup & Restore
Code in `src/utils/backup/`, UI in `src/components/backup/` (`BackupSection` in Settings › Backup & restore, `ExportBackupDialog`, `RestoreDialog`). Format and rules: [TECH-SPEC.md § 4](TECH-SPEC.md#4-backup-file-format-v100).
| Module | Role |
| -------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `format.ts` | The `_format: 2` envelope, `_type` values, section list, per-section store versions, dated file names |
| `collect.ts` | Builds a backup of the chosen sections, a single-section export, or the History CSV |
| `detect.ts` | Recognises every file any version has written (v2, v0.15–v0.38 envelopes, bare arrays, the old desktop data file) and reports each section with its version |
| `sanitize.ts` | Store migrations first, then a strict whitelist; keeps device-local settings |
| `restore.ts` | Plans the restore (new / same / changed per row) and applies the choice in one step, with undo |
| `restore-flow.ts` | Gets a file into the dialog: Open dialog, drop, or one of the desktop app's own backups |
| `restore-request.ts` | `useRestoreDialog` — the pending file, kept apart so the shell can watch it without loading the rest |
| `auto-backup.ts` | Desktop automatic backups |
| `startup.ts` | Tauri start-up: legacy-file recovery, then automatic backups (desktop) |
```
Web App (React + Vite)
Restore from file · drop · desktop backup list · "Review" on the legacy toast
│ restore-flow.ts (openTextFile / readTextFile / appBackups.read)
▼
detect.ts — readBackupText → sections + recorded versions
│ (logs, social, unknown or newer files are refused with a message)
▼
useRestoreDialog.open → RestoreDialog (lazy)
│
▼
┌───────────────────┐
│ Tauri Shell │
│ ┌──────────────┐ │
│ │ WebView │ │ ← Renders the same React app
│ │ (system) │ │
│ └──────────────┘ │
│ ┌──────────────┐ │
│ │ Rust Core │ │ ← File system access, clipboard, tray
│ └──────────────┘ │
└───────────────────┘
│
restore.ts — planRestore
│ sanitize.ts: store migrations → whitelist
│ per row: new / same / changed; Merge (newer | both) or Replace
▼
Binary output:
- Windows: .msi / .exe (~8MB)
- macOS: .dmg / .app (~10MB)
applyRestore — one synchronous write to every store → toast with Undo
(desktop: a "before-restore" automatic backup is written first)
```
Export: `ExportBackupDialog` → `collectBackup(chosen sections)` → `saveTextFile` (`ytdescgen-backup-YYYY-MM-DD.json`); the library tabs and History export single sections (History also as CSV).
## 6. Web Delivery
The web build is served at <https://ytgenerator.stream> by a Cloudflare Worker (`worker/`, configured by `wrangler.jsonc`) that Cloudflare Workers Builds deploys from `main`. The Worker puts a Turnstile check in front of the app (verified server-side; a signed `HttpOnly` `__Host-ytg_gate` cookie remembers the pass for 24 hours), serves the prerendered legal pages at `/legal/*` to everyone, and sets the security headers (a CSP per page type). Agreeing to the terms on the gate page sets the `ytg_terms` cookie, which the app reads so a web visitor meets one blocking screen, not two. Build-time extras for the web only — static legal pages, `/.well-known/security.txt`, the cookieless Web Analytics beacon — come from `build-plugins/`. The desktop and Android builds use none of this and contain no analytics. Request flow, cookies, headers and operations: [HOSTING.md](HOSTING.md).
## 7. Desktop Packaging (Tauri)
```
React app (src/), built with TAURI_ENV_PLATFORM set
│
▼
┌────────────────────────────────────────┐
│ Tauri 2 shell │
│ ┌──────────────────────────────────┐ │
│ │ System WebView │ │ ← renders the same React app
│ │ WebView2 · WKWebView · WebKitGTK │ │
│ │ Android System WebView │ │
│ └──────────────────────────────────┘ │
│ ┌──────────────────────────────────┐ │
│ │ Rust core (src-tauri/src) │ │
│ │ lib.rs │ │ ← plugins, commands, tray, single instance
│ │ storage.rs │ │ ← backups and logs, by file name
│ │ file_dialog.rs │ │ ← Save / Open dialogs run in Rust
│ └──────────────────────────────────┘ │
└────────────────────────────────────────┘
│
▼
Release assets:
- Windows: .msi and NSIS .exe
- macOS (Apple silicon): .app.tar.gz
- Linux: .AppImage, .deb, .rpm
- Android: universal .apk
```
**The webview never names a path.** Since v1.0.0 the Rust side exposes only name-only commands for its own files (`backup_*` and `log_*` under the app data directory, `recover_legacy_data`) and two commands that open the native Save / Open dialog themselves (`export_text_file`, `import_text_file`: text formats only, imports capped at 20 MB). The capability file grants the webview only `core:default` and `opener:default`; the fs and shell plugins are gone. The JavaScript bridge is `src/utils/native.ts`, used by `file-ops.ts` (exports and imports on every platform), `log-storage.ts` and `utils/backup/`. Details: [PACKAGING.md](PACKAGING.md).
Tauri advantages over Electron:
- Binary size: ~8MB vs ~150MB
- Memory: ~30MB vs ~100MB+
- No bundled Chromium — uses system WebView
- Rust backend for native features
## 6. Extensibility Points
- No bundled Chromium — uses the system WebView, so installers stay a few megabytes (the v0.38.0 MSI was 4.6 MB)
- Lower memory use
- A Rust backend for native features, with a capability system that limits what the webview can call
| What | How to Extend | Files to Touch |
|------|--------------|----------------|
| New language | Add `locales/{code}/ui.json` + `templates.json`, register in `SUPPORTED_LANGUAGES` (lazy-loaded automatically) | 3 files |
| New genre | Add entry to `config/genres.ts`, add tag pool to `engine/tag-generator.ts` | 2 files |
| New video type | Add to `config/video-types.ts`, add patterns to all `templates.json` | 1 + N locale files |
| New platform/store | Add entry to `config/platforms.ts` | 1 file |
| New social link | Add entry to `config/social-fields.ts` | 1 file |
| New rig field | Add entry to `config/rig-fields.ts` | 1 file |
| Custom template | Edit `templates.json` for target language | 1 file |
| Desktop feature | Add Tauri command in `src-tauri/src/main.rs` | 1 file |
## 8. Extensibility Points
## 7. Data Flow
| What | How to extend | Files to touch |
| ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- |
| New language | Add `locales/{code}/ui.json` + `templates.json` and register it (see section 4 and [I18N.md](I18N.md)); lazy-loaded automatically | 2 locale files + `types.ts`, `i18n/index.ts`, `settings-heal.ts`, `tag-generator.ts`, `channel-phrase.ts` |
| New genre | Add it to the `Genre` union (`engine/types.ts`) and `config/genres.ts`, its tag pool (`GENRE_TAG_REGISTRY`) and search term (`GENRE_SEARCH_TERMS`) to `engine/tag-generator.ts` — a test keeps the three lists in sync — and its `genres.<id>` label to every `ui.json` | 3 + N locale files |
| New video type | Add it to the `VideoType` union and `config/video-types.ts`, its `videoTypes.<id>` label to every `ui.json`, and its title, intro and pinned-comment greeting to every `templates.json` | 2 + 2N locale files |
| New store / platform | Add an entry to `config/platforms.ts` (URL pattern, optional normaliser, `tagName`); optionally a game-name extractor in `utils/url-extractors.ts` | 1–2 files |
| New social link | Add an entry to `config/social-fields.ts` and its `social.<id>` label to every `ui.json` | 1 + N locale files |
| New rig field | Add an entry to `config/rig-fields.ts`, its `rig.<id>` label to every `ui.json` and `description.rigLabels.<id>` to every `templates.json` | 1 + 2N locale files |
| New cross-post platform | Add an entry to `config/social-platforms.ts` (limit, hashtags, count mode) and its `socialPost.platforms.<id>` label | 1 + N locale files |
| Custom template text | Edit `templates.json` for the target language | 1 file |
| Desktop feature | Add a command in `src-tauri/src/` (a module like `storage.rs`), register it in `lib.rs`'s `generate_handler!`, add a typed wrapper in `src/utils/native.ts`. Never take a path from the webview | 3 files |
| Persisted data shape | Bump the store's exported version and add an idempotent step to its exported migration; backups replay it | 1 file |
## 9. Data Flow
```
User Input (form)
User input (form, paste, Quick start, command palette)
│
▼
EditorStore (Zustand)
EditorStore (Zustand, persist → localStorage "ytdescgen-editor-draft")
│
├──→ useGeneratedOutput hook
├──→ useCurrentGeneratorInput → GeneratorInput
│ │
│ ├──→ titleBuilder(input, locale) → title string
│ ├──→ descriptionBuilder(input, locale) → description string
│ ├──→ tagGenerator(input) → tags string[]
│ │
│ └──→ GeneratorOutput (memoized)
│ │
│ ▼
│ OutputPage (display + copy)
│ ▼
│ useGeneratedOutput
│ ├─ useLanguagesReady ([output language])
│ ├─ i18n.getFixedT(language, "templates") + the English tEn
│ ├─ useRenderOptions (Settings → RenderOptions)
│ └─ renderAll → buildTitle · buildDescription · generateTags
│ → GeneratorOutput (memoized)
│ │
│ ▼
│ Output page · Editor live preview · Social captions ·
│ Copy (limits.ts gates) · Ctrl/⌘+Shift+C · command palette
│ │
│ └──→ HistoryStore.addEntry
│ (Output page and Ctrl/⌘+S; one entry per video)
│
├──→ ProfileStore.save() ──→ localStorage
├──→ PresetStore.save() ──→ localStorage
└──→ HistoryStore.add() ──→ localStorage
├──→ Profile / Preset / Template stores (save from the editor;
│ apply through library-apply.ts) ──→ localStorage
│
└──→ Desktop: auto-backup.ts ──→ backup_write ──→ <app data>/backups/
```
The multi-language Output tabs (`useMultilangOutput`) and BatchPage call `renderAll` themselves, once per language, with the same `useRenderOptions` mapping.
+151 -75
View File
@@ -1,15 +1,21 @@
# Content Inventory
A static manifest of every video type, game genre, and content warning surfaced in YTDescGen's editor. Maintained manually — when adding a new option to one of the source files below, **add a row here too** in the same PR.
A static manifest of every video type, game genre, content warning, store, link field and cross-post platform surfaced in YTDescGen's editor (as of v1.0.0). Maintained manually — when adding a new option to one of the source files below, **add a row here too** in the same PR.
This file exists for **transparency** — anyone curious about what the editor can describe (without installing the app or reading the source) can scan it in one minute.
**Vietnamese mirror:** [`docs/i18n/vi/CONTENT-INVENTORY.md`](./i18n/vi/CONTENT-INVENTORY.md).
**Source of truth:**
- Video types: [`src/config/video-types.ts`](../src/config/video-types.ts)
- Game genres: [`src/config/genres.ts`](../src/config/genres.ts)
- Content warnings: [`src/config/content-warning-groups.ts`](../src/config/content-warning-groups.ts)
- Stores: [`src/config/platforms.ts`](../src/config/platforms.ts)
- Social & donate links: [`src/config/social-fields.ts`](../src/config/social-fields.ts)
- Community links: [`src/components/editor/CommunityEditor.tsx`](../src/components/editor/CommunityEditor.tsx)
- Vietnamese banks: [`src/config/vietnamese-banks.ts`](../src/config/vietnamese-banks.ts)
- Cross-post platforms: [`src/config/social-platforms.ts`](../src/config/social-platforms.ts)
---
@@ -17,87 +23,87 @@ This file exists for **transparency** — anyone curious about what the editor c
Each video type drives a dedicated description template + title structure + tag bias. The "Extra fields" column lists fields the editor reveals when this type is selected.
| Icon | Type | Extra fields |
|---|---|---|
| 🎮 | Full Gameplay | — |
| 📂 | Gameplay Part | Part Number |
| 🎬 | Full Demo | — |
| 🎞 | Demo Part | Part Number |
| 👹 | Boss Fight | Boss Name |
| 💀 | Boss No Hit | Boss Name |
| 🏁 | Ending / All Endings | — |
| ⚡ | Speedrun | — |
| 💯 | 100% Completion | — |
| 📦 | DLC Content | DLC Name |
| 🔄 | New Game+ | — |
| 🏆 | Challenge Run | Challenge Name |
| 📌 | Side Quests | — |
| 🔍 | Secrets / Hidden | — |
| ⚖️ | Graphics Comparison | — |
| 📘 | Silent Guide | — |
| 🧩 | Modded Gameplay | Mod Name |
| ⭐ | All Collectibles | — |
| 🔴 | Livestream | Live URL, Scheduled Time |
| 🎴 | Gacha Quest | Quest Type, Chapter Name, Quest Name, Part Number |
| Icon | Type | Extra fields |
| ---- | -------------------- | ------------------------------------------------- |
| 🎮 | Full Gameplay | — |
| 📂 | Gameplay Part | Part Number |
| 🎬 | Full Demo | — |
| 🎞 | Demo Part | Part Number |
| 👹 | Boss Fight | Boss Name |
| 💀 | Boss No Hit | Boss Name |
| 🏁 | Ending / All Endings | — |
| ⚡ | Speedrun | — |
| 💯 | 100% Completion | — |
| 📦 | DLC Content | DLC Name |
| 🔄 | New Game+ | — |
| 🏆 | Challenge Run | Challenge Name |
| 📌 | Side Quests | — |
| 🔍 | Secrets / Hidden | — |
| ⚖️ | Graphics Comparison | — |
| 📘 | Silent Guide | — |
| 🧩 | Modded Gameplay | Mod Name |
| ⭐ | All Collectibles | — |
| 🔴 | Livestream | Live URL, Scheduled Time |
| 🎴 | Gacha Quest | Quest Type, Chapter Name, Quest Name, Part Number |
---
## 2. Game genres (41)
## 2. Game genres (42)
Selected genres feed the title format, the tag pool, and (when configured in Settings → Genre Playlists) the pinned-comment recommendation.
Selected genres (up to 3 per video) feed the title format, the tag pool, and (when configured in Settings → Genre Playlists) the pinned-comment recommendation.
Bulk-select groups available in the editor: **All RPGs** (rpg + jrpg + action_rpg + crpg), **All Shooters** (fps + arena_shooter + tactical_fps + boomer_shooter + extraction_shooter + shmup), **All Horror** (horror + survival_horror + psychological_horror).
Bulk-select groups available in the editor: **All RPGs** (rpg + jrpg + action_rpg + crpg), **All Shooters** (fps + arena_shooter + tactical_fps + boomer_shooter + extraction_shooter + shmup), **All Horror** (horror + survival_horror + psychological_horror). A group replaces the selection with its first three genres.
| Icon | Genre |
|---|---|
| ⚔️ | Action / Adventure |
| 🗡 | Hack & Slash |
| 👊 | Beat 'em Up |
| 🦘 | Platformer |
| 👻 | Horror / Survival |
| 🧟 | Survival Horror |
| 🧠 | Psychological Horror |
| 🛡 | RPG |
| 🎎 | JRPG |
| 🏹 | Action RPG |
| 📜 | CRPG / Isometric |
| 🔫 | FPS / Shooter |
| 🎯 | Arena Shooter |
| 🎖 | Tactical FPS |
| 💥 | Boomer Shooter |
| 🎒 | Extraction Shooter |
| 🛸 | SHMUP / Bullet Hell |
| 🌍 | Open World / Sandbox |
| 🕹 | Indie |
| 💀 | Souls-like |
| 🏎 | Racing / Sports |
| 📖 | Story / Narrative |
| 🏗 | Simulation / Strategy |
| 🏙 | City Builder |
| 🥊 | Fighting |
| 🥷 | Stealth / Espionage |
| ⛏ | Survival / Crafting |
| 🎲 | Roguelike / Roguelite |
| 🗺 | Metroidvania |
| 🌐 | MMO / Online |
| 🎵 | Rhythm / Music |
| 🧩 | Puzzle |
| 🏰 | Tower Defense |
| 🃏 | Card Game |
| 🎴 | Deck Builder |
| 🤖 | Auto Battler |
| 🏆 | Battle Royale |
| ♟ | Tactical / Turn-based |
| 🚀 | Space / Sci-Fi |
| 🌾 | Farming / Life Sim |
| 🎬 | FMV / Interactive Movie |
| 💬 | Visual Novel |
| Icon | Genre |
| ---- | ----------------------- |
| ⚔️ | Action / Adventure |
| 🗡 | Hack & Slash |
| 👊 | Beat 'em Up |
| 🦘 | Platformer |
| 👻 | Horror / Survival |
| 🧟 | Survival Horror |
| 🧠 | Psychological Horror |
| 🛡 | RPG |
| 🎎 | JRPG |
| 🏹 | Action RPG |
| 📜 | CRPG / Isometric |
| 🔫 | FPS / Shooter |
| 🎯 | Arena Shooter |
| 🎖 | Tactical FPS |
| 💥 | Boomer Shooter |
| 🎒 | Extraction Shooter |
| 🛸 | SHMUP / Bullet Hell |
| 🌍 | Open World / Sandbox |
| 🕹 | Indie |
| 💀 | Souls-like |
| 🏎 | Racing / Sports |
| 📖 | Story / Narrative |
| 🏗 | Simulation / Strategy |
| 🏙 | City Builder |
| 🥊 | Fighting |
| 🥷 | Stealth / Espionage |
| ⛏ | Survival / Crafting |
| 🎲 | Roguelike / Roguelite |
| 🗺 | Metroidvania |
| 🌐 | MMO / Online |
| 🎵 | Rhythm / Music |
| 🧩 | Puzzle |
| 🏰 | Tower Defense |
| 🃏 | Card Game |
| 🎴 | Deck Builder |
| 🤖 | Auto Battler |
| 🏆 | Battle Royale |
| ♟ | Tactical / Turn-based |
| 🚀 | Space / Sci-Fi |
| 🌾 | Farming / Life Sim |
| 🎬 | FMV / Interactive Movie |
| 💬 | Visual Novel |
---
## 3. Content warnings (248, grouped)
Selected warnings are appended to a `⚠ CONTENT WARNINGS` block in the description, ahead of timestamps. Each group is collapsible in the editor; warnings render in description order = user's selection order.
Selected warnings are rendered in a `▸ ⚠️ CONTENT WARNINGS` block in the description, after the rig block (and the mod list, for Modded Gameplay). Each group is collapsible in the editor; warnings render in description order = user's selection order.
### Spoilers (6)
@@ -149,13 +155,83 @@ Mods used · Cheats / debug · Glitches used · Guide-assisted · Educational /
---
## 4. Maintenance
## 4. Stores (15 + publisher site)
Each store has a link field. A store link pasted anywhere in the editor lands in the right field; the first one also sets the video's platform, whose search name is used in the tags. Each link is marked paid, free or demo.
| Store | Links accepted | Name in tags |
| -------------------------- | -------------------------------------------------------------------------- | --------------- |
| Steam | `store.steampowered.com/app/…` (also `/sub/`, `/bundle/` and `s.team/a/…`) | Steam |
| Epic Games Store | `store.epicgames.com/…` | Epic Games |
| PlayStation Store | `store.playstation.com/…` | PlayStation |
| Xbox / Microsoft Store | `xbox.com/…`, `apps.microsoft.com/…`, Microsoft Store pages | Xbox |
| Nintendo eShop | `nintendo.com/…` and the regional Nintendo sites | Nintendo Switch |
| GOG | `gog.com/…` | GOG |
| itch.io | `<dev>.itch.io/<game>` | itch.io |
| Humble Bundle | `humblebundle.com/…` | Humble Bundle |
| Amazon Luna | `luna.amazon.com/…`, Amazon storefronts | Amazon Luna |
| EA app | `ea.com/…` | EA app |
| Ubisoft Store | `store.ubisoft.com/…`, `ubisoft.com/…` | Ubisoft Connect |
| Battle.net | `shop.battle.net/…` and its regional hosts | Battle.net |
| Google Play | `play.google.com/store/apps/details?id=…` | Android |
| App Store | `apps.apple.com/…` | iOS |
| Meta Quest Store | `meta.com/…`, `oculus.com/…` | Meta Quest |
| Publisher / Developer site | any `https://` link | — |
---
## 5. Social, donate & community links
### Donate (5)
Ko-fi · Patreon · Buy Me a Coffee · PayPal · Streamlabs
### Social (17)
GitHub · YouTube · X (Twitter) · Discord · Twitch · Kick · TikTok · Instagram · Threads · Bluesky · Mastodon · Facebook · Facebook Page · Reddit · Bilibili · Telegram · Website
### Community (5)
Messenger community · Signal group · Instagram group chat · Facebook Group · Zalo group (Vietnamese output only)
### Vietnamese banks (37)
For the Donate (Vietnam) block — bank transfer, MoMo and ZaloPay — which renders only when the output language is Vietnamese. "Other" lets you type any bank; a profile saved with a bank's former name is offered the new one.
- **State-owned (4):** Vietcombank · BIDV · VietinBank · Agribank
- **Joint-stock (24):** Techcombank · MB Bank · ACB · VPBank · TPBank · Sacombank · HDBank · VIB · SHB · Eximbank · OCB · MSB · LPBank · SeABank · ABBank · BAC A Bank · PVcomBank · NCB · Nam A Bank · KienlongBank · Saigonbank · VietABank · Vietbank · BVBank
- **Renamed in 2025, and digital-first (5):** MBV (formerly OceanBank) · VCBNeo (formerly CBBank) · Vikki Bank (formerly DongA Bank) · Cake by VPBank · Timo
- **Foreign-owned (4):** HSBC Vietnam · Standard Chartered · Shinhan Bank · UOB Vietnam
---
## 6. Cross-post platforms (7)
The Social tab turns the same editor data into short-form captions. When a caption runs over the platform's limit, optional blocks are dropped (content warnings first); hashtags are capped per platform.
| Platform | Caption limit | Hashtags |
| --------------- | --------------------------------------------------------------------------------------------- | -------- |
| TikTok | 4,000 | no cap |
| YouTube Shorts | 5,000 | up to 5 |
| Instagram Reels | 2,200 | no cap |
| Facebook Reels | 2,200 | no cap |
| X | 280, counted the way X counts (CJK, Vietnamese letters with diacritics and emoji count twice) | up to 3 |
| Threads | 500 | 1 |
| Bluesky | 300 | up to 3 |
---
## 7. Maintenance
When adding a new item to any of the source files:
1. **Video types** → append to [`src/config/video-types.ts`](../src/config/video-types.ts) AND add a row in section 1 above.
2. **Genres** → append to [`src/config/genres.ts`](../src/config/genres.ts) AND add a row in section 2.
1. **Video types** → append to [`src/config/video-types.ts`](../src/config/video-types.ts) (plus its title, intro and pinned-comment greeting in every `templates.json`) AND add a row in section 1 above.
2. **Genres** → append to [`src/config/genres.ts`](../src/config/genres.ts) (plus its tag pool and search term in `src/engine/tag-generator.ts` — a test keeps them in sync) AND add a row in section 2.
3. **Content warnings** → append to the relevant group in [`src/config/content-warning-groups.ts`](../src/config/content-warning-groups.ts) AND add the label to the right group in section 3 — keep the group count in the heading accurate.
4. Update the Vietnamese mirror at [`docs/i18n/vi/CONTENT-INVENTORY.md`](./i18n/vi/CONTENT-INVENTORY.md) in the same PR.
4. **Stores** → add to [`src/config/platforms.ts`](../src/config/platforms.ts) (URL pattern and `tagName`; optionally a game-name extractor in `src/utils/url-extractors.ts`) AND add a row in section 4.
5. **Social / donate links** → add to [`src/config/social-fields.ts`](../src/config/social-fields.ts) (plus its `social.<id>` label in every `ui.json`) AND add it to section 5.
6. **Vietnamese banks** → add to [`src/config/vietnamese-banks.ts`](../src/config/vietnamese-banks.ts) — for a renamed bank, add the new name and map the old one in `VIETNAMESE_BANK_RENAMES` — AND update section 5.
7. **Cross-post platforms** → add to [`src/config/social-platforms.ts`](../src/config/social-platforms.ts) (plus its `socialPost.platforms.<id>` label in every `ui.json`) AND add a row in section 6.
8. Update the Vietnamese mirror at [`docs/i18n/vi/CONTENT-INVENTORY.md`](./i18n/vi/CONTENT-INVENTORY.md) in the same PR.
Mismatch between this file and the source files is treated as a documentation bug — open an issue or PR.
+135 -42
View File
@@ -1,19 +1,19 @@
# Development Guide
This guide covers setting up YTDescGen for local development on Windows, macOS, or Linux. The application is a Vite/React web app with an optional Tauri desktop shell.
This guide covers setting up YTDescGen for local development on Windows, macOS, or Linux. The application is a Vite/React web app with an optional Tauri shell for desktop and Android. On the web it is served at [ytgenerator.stream](https://ytgenerator.stream) by a Cloudflare Worker — see [HOSTING.md](./HOSTING.md).
## Reference Workstation
The reference workstation used to develop and ship this project:
| Component | Spec |
| --- | --- |
| OS | Windows 11 Pro (24H2 or newer) |
| CPU | Modern x86-64 — 6+ cores with AVX2 (Intel 11th-gen / AMD Zen 3 or newer) |
| GPU | Discrete or integrated — Tauri's WebView2 backend runs fine on iGPU |
| RAM | 16 GB minimum, 32 GB recommended for parallel typecheck + dev server |
| Storage | 5 GB free for `node_modules` + Cargo `target/` after a full Tauri build |
| Display | 1920×1080 minimum; mobile-responsive layout tested down to 360×640 |
| Component | Spec |
| --------- | ------------------------------------------------------------------------ |
| OS | Windows 11 Pro (24H2 or newer) |
| CPU | Modern x86-64 — 6+ cores with AVX2 (Intel 11th-gen / AMD Zen 3 or newer) |
| GPU | Discrete or integrated — Tauri's WebView2 backend runs fine on iGPU |
| RAM | 16 GB minimum, 32 GB recommended for parallel typecheck + dev server |
| Storage | 5 GB free for `node_modules` + Cargo `target/` after a full Tauri build |
| Display | 1920×1080 minimum; mobile-responsive layout tested down to 360×640 |
macOS and Linux work for development. Tauri release builds are cross-compiled or run on dedicated CI runners — see [PACKAGING.md](./PACKAGING.md).
@@ -21,13 +21,13 @@ macOS and Linux work for development. Tauri release builds are cross-compiled or
Install in this order:
| Tool | Version | Why |
| --- | --- | --- |
| **Node.js** | `>= 22.12.0` | Vite 8 requires Node `^20.19` or `>= 22.12`. Use [nvm](https://github.com/nvm-sh/nvm) or [fnm](https://github.com/Schniz/fnm). |
| **npm** | bundled with Node 22 | The project uses npm; `pnpm` and `yarn` are not tested. |
| **Rust** | stable, `>= 1.78` | Required for the Tauri desktop build. Install via [rustup](https://rustup.rs/). |
| **Python** | `3.12` | Optional — only needed for some Tauri platform tooling on Windows. |
| **Tauri prerequisites** | per OS | See <https://v2.tauri.app/start/prerequisites/>. |
| Tool | Version | Why |
| ----------------------- | --------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Node.js** | **22** — the version in `.node-version` | CI, the release workflows and Cloudflare Workers Builds all read `.node-version`. Vite 8 needs Node `^20.19` or `>= 22.12` and wrangler needs `>= 22`, so use 22.12 or newer. Use [nvm](https://github.com/nvm-sh/nvm) or [fnm](https://github.com/Schniz/fnm) (fnm reads `.node-version`). |
| **npm** | bundled with Node 22 | The project uses npm; `pnpm` and `yarn` are not tested. |
| **Rust** | stable, `>= 1.90` | Required for the Tauri desktop and Android builds (Tauri 2.12 needs Rust 1.90). Install via [rustup](https://rustup.rs/); its default profile includes `rustfmt` and `clippy`. |
| **Python** | `3.12` | Optional — only needed for some Tauri platform tooling on Windows. |
| **Tauri prerequisites** | per OS | See <https://v2.tauri.app/start/prerequisites/>. |
### Windows specifics
@@ -52,7 +52,7 @@ The reference workflow uses **JetBrains 2026.x** IDEs (WebStorm or RustRover) as
- Enable the **Tailwind CSS** plugin.
- Enable the **i18next** plugin (or rely on `src/i18n/locales/_schema.json` for autocomplete).
- Settings → Languages → TypeScript → "Use TypeScript from `node_modules/typescript`".
- Settings → Code Style → Prettier → Run on save (`src/**/*.{ts,tsx,json,css}`).
- Settings → Code Style → Prettier → Run on save (`{src,tests,scripts,worker,build-plugins}/**/*.{ts,tsx,css}` — the same files `npm run format` covers).
### VS Code
@@ -79,27 +79,90 @@ npm run dev
# → http://localhost:5173
```
The dev server is the app alone: no Turnstile gate and no analytics. To run the Worker that serves the web app, see [Cloudflare Worker (local)](#cloudflare-worker-local).
## Branches and Pull Requests
- Branch from `main` (`feat/…`, `fix/…`, `docs/…`, `chore/…`) and open the pull request against `main`. There is no other long-lived branch, and every merge to `main` deploys the web app.
- PR titles use the commit format `type(scope): message`; CI checks them.
- Every PR runs the `check` job (below), `dependency-review`, `workflow-lint`, `reuse` and `pr-title`; the Rust jobs `lint-and-test` and `cargo-deny` run when `src-tauri/` changes.
Full rules: [CONTRIBUTING.md](../CONTRIBUTING.md).
## Common Commands
| Command | What it does |
| --- | --- |
| `npm run dev` | Vite dev server, hot reload, web only. |
| `npm run build` | Production web bundle into `dist/`. |
| `npm run preview` | Serve the production bundle for sanity-testing. |
| `npm run typecheck` | `tsc --noEmit` over `src/` — what Vite actually builds. |
| `npm run typecheck:all` | Same, plus `tests/` and `scripts/`, which the base config deliberately excludes. Added in v0.35.0 after it turned out they had **never** been type-checked — and immediately found three fields silently missing from the editor→engine parity fixture. |
| `npm run lint` | ESLint. Use `npm run lint:fix` to autofix. |
| `npm run format` | Prettier write across `src/`, `tests/`, `scripts/`. |
| `npm run format:check` | Same, read-only. CI gate. Markdown and the locale JSON are deliberately out of scope — Prettier reflows prose and expands the schema's compact arrays by ~1600 lines for no benefit. |
| `npm run knip` | Dead-code / unused-dependency check. CI gate. |
| `npm run check:version` | Asserts all **six** version fields agree (`package.json`, both `package-lock.json` entries, `tauri.conf.json`, `Cargo.toml`, `Cargo.lock`). The only thing that notices a missed one. |
| `npm run test` | Vitest watch mode. |
| `npm run test:run` | Vitest single-run (for CI / pre-commit). |
| `npm run test:coverage` | Coverage report into `coverage/`. |
| `npm run validate:locales` | Enforces all 8 locales match `_schema.json` exactly. **Must pass before any locale-touching PR merges.** |
| `npm run generate:locale` | Scaffold a locale from the English source. `--lang <code>`, plus optional `--copy-english` / `--force`. (Advertised since v0.1 but only actually written in v0.35.0.) |
| `npm run tauri:dev` | Tauri desktop in dev mode (auto-restarts on Rust or frontend changes). |
| `npm run tauri:build` | Tauri release binary for the current platform. |
### Develop and build
| Command | What it does |
| --------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `npm run dev` | Vite dev server, hot reload, web only. |
| `npm run build` | `tsc` + production web bundle into `dist/`. The web build also gets the Web Analytics beacon, `/.well-known/security.txt` and the static `/legal/*` pages; builds started by the Tauri CLI leave them out. |
| `npm run preview` | Serve the production bundle for sanity-testing (without the Worker). |
| `npm run cf:dev` | `wrangler dev` — the Worker in front of `dist/` on `http://localhost:8787`. See [Cloudflare Worker (local)](#cloudflare-worker-local). |
| `npm run tauri:dev` | Tauri desktop in dev mode (also `npm run tauri dev`): starts `npm run dev` and opens the app window on it. Frontend changes hot-reload; Rust changes rebuild the app. |
| `npm run tauri:build` | Tauri release binary for the current platform. |
### Check
| Command | What it does |
| -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `npm run typecheck` | `tsc --noEmit` over `src/` — what Vite actually builds. |
| `npm run typecheck:all` | Same, plus `tests/`, `scripts/`, `worker/` and `build-plugins/` (`tsconfig.check.json`), which the base config deliberately excludes. Added in v0.35.0 after it turned out tests and scripts had **never** been type-checked — and immediately found three fields silently missing from the editor→engine parity fixture. |
| `npm run lint` | ESLint over `src/`, `tests/`, `scripts/`, `worker/` and `build-plugins/`. Use `npm run lint:fix` to autofix. |
| `npm run format` | Prettier write across `src/`, `tests/`, `scripts/`, `worker/` and `build-plugins/` (`.ts`, `.tsx`, `.css`). |
| `npm run format:check` | Same, read-only. CI gate. Markdown and the locale JSON are deliberately out of scope. |
| `npm run knip` | Dead-code / unused-dependency check. CI gate. |
| `npm run validate:locales` | Enforces all 8 locales match `_schema.json` exactly. **Must pass before any locale-touching PR merges.** |
| `npm run test` | Vitest watch mode. |
| `npm run test:run` | Vitest single-run. |
| `npm run test:coverage` | Single run with a coverage report into `coverage/`; fails below the thresholds for `src/engine/` and `worker/` set in `vitest.config.ts`. This is what CI runs. |
| `npm run check:version` | Asserts all **six** version fields agree (`package.json`, both `package-lock.json` entries, `tauri.conf.json`, `Cargo.toml`, `Cargo.lock`). The only thing that notices a missed one. |
| `npm run check:tauri` | The `@tauri-apps/*` npm packages and the Tauri crates must share major.minor. The Tauri CLI refuses to build otherwise, and CI never runs a Tauri build. |
| `npm run check:licenses` | Every bundled package has an allowed license, and `THIRD_PARTY_NOTICES.md` matches what is installed. |
| `npm run check:bundle` | Run after `npm run build`: the initial load must stay ≤ 280 KB gzip and no JS chunk over 500 KB raw. |
| `npm run cf:check` | `wrangler deploy --dry-run`: validates `wrangler.jsonc` and bundles the Worker the way Workers Builds will, without deploying. |
### Generate
| Command | What it does |
| ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `npm run generate:locale` | Scaffold a locale from the English source. `--lang <code>`, plus optional `--copy-english` / `--force`. (Advertised since v0.1 but only actually written in v0.35.0.) |
| `npm run generate:third-party` | Rewrite `THIRD_PARTY_NOTICES.md` from the installed packages — needed after a dependency change, or `check:licenses` fails. |
| `npm run generate:brand` | Rasterise the brand SVGs in `assets/brand/` into the web's PNG icons and link-preview card in `public/`. The PNGs are committed. The desktop and Android icons come from the same logo: `npx tauri icon assets/brand/logo.svg`. |
## Before You Open a PR
Run what CI's `check` job runs:
```bash
npm run typecheck && npm run typecheck:all
npm run lint && npm run format:check
npm run validate:locales
npm run test:coverage
npm run knip
npm run check:version && npm run check:tauri && npm run check:licenses
npm run build && npm run check:bundle
npm run cf:check
```
Touched `src-tauri/`? Also run the [Rust checks](#rust-checks).
## Cloudflare Worker (local)
The web app is served by a Cloudflare Worker ([`worker/`](../worker), configured in [`wrangler.jsonc`](../wrangler.jsonc)) that puts the Turnstile gate, the security headers and the public `/legal` pages in front of `dist/`. To run it locally:
```bash
cp .dev.vars.example .dev.vars # Cloudflare's public Turnstile TEST keys only
npm run build # the Worker serves dist/
npm run cf:dev # wrangler dev → http://localhost:8787
```
- `.dev.vars` (git-ignored) holds Cloudflare's published Turnstile **test** keys: the widget always passes and the secret only accepts the dummy token it produces. Never put the real secret in a file — production keeps `TURNSTILE_SECRET` as a Cloudflare Secret.
- Without `.dev.vars` the Worker has no `TURNSTILE_SECRET` and fails open: the app loads without the gate.
- The Worker serves the last build — run `npm run build` again to see frontend changes behind it.
- Worker tests run with the rest of the suite (`tests/worker/`).
Deployment, cookies, headers, secrets and rollback: [HOSTING.md](./HOSTING.md).
## Tauri Desktop Build
@@ -107,16 +170,37 @@ See [PACKAGING.md](./PACKAGING.md) for the full release pipeline. Quick local bu
```bash
npm run tauri:build
# Output: src-tauri/target/release/bundle/{msi,deb,dmg,app}
# Output: src-tauri/target/release/bundle/
# Windows: MSI + NSIS installers · Linux: deb, rpm, AppImage · macOS: .app + DMG
```
The first build takes ~5–10 minutes (cold Cargo cache). Subsequent builds are incremental.
The Vite dev server does not watch `src-tauri/**` or `.wrangler/**` (`server.watch.ignored` in `vite.config.ts`): while `tauri dev` runs, Cargo rewrites files under `src-tauri/target`, and watching them crashed Vite on Windows with `EBUSY` on a locked `.dll`.
### Rust checks
The same steps as the `lint-and-test` job in `.github/workflows/rust.yml`, which runs when `src-tauri/` changes (and weekly):
```bash
npm run build # tauri::generate_context!() embeds dist/, so clippy and the tests need a build
cd src-tauri
cargo fmt --all -- --check
cargo clippy --all-targets --locked -- -D warnings
cargo test --locked
```
The `cargo-deny` job checks RustSec advisories, licenses and crate sources against `src-tauri/deny.toml`. Locally (after `cargo install cargo-deny`): `cargo deny check advisories licenses sources` in `src-tauri/`.
## Troubleshooting
### `validate:locales` fails after adding a key
You forgot to update `src/i18n/locales/_schema.json`. The schema is the source of truth; locales must match it exactly.
You forgot to update `src/i18n/locales/_schema.json`, or one of the 8 locales. The schema is the source of truth; every locale must match it exactly.
### `validate:locales` fails but I didn't touch locales
Someone — or a merge from `main` — added a key to `_schema.json` (for example the label of a new `CONTENT_WARNINGS` id from `src/engine/types.ts`) that isn't in every locale yet. New keys need a value in all 8 locales.
### Tauri build fails with `link.exe not found` (Windows)
@@ -126,6 +210,18 @@ Install Visual Studio Build Tools 2022 + Desktop C++ workload, then restart your
Install the per-distro Tauri prerequisites listed at <https://v2.tauri.app/start/prerequisites/>.
### `check:tauri` fails after a dependency update
A `@tauri-apps/*` npm package moved to a new minor version without the crates (or the other way round). Run `cargo update -p tauri` (and the plugin crates `check:tauri` names) in `src-tauri/` on the same branch.
### `check:bundle` can't find `dist/index.html`
It measures a build — run `npm run build` first.
### `npm run cf:dev` shows no Turnstile gate
`.dev.vars` is missing, so the Worker has no secret and serves the app without the gate. Copy `.dev.vars.example` to `.dev.vars` and restart.
### `npm install` is slow or hangs
Disable corporate VPNs / proxies that block the npm registry. The lock file is committed; offline installs work after one successful online install.
@@ -138,13 +234,10 @@ Since v0.26, only English ships in the main chunk; the other languages are
lazy-loaded async chunks fetched on first use (see `src/i18n/index.ts` and
docs/I18N.md). The restart advice above still applies to all of them.
### Pre-commit hook fails on `validate:locales` but I didn't touch locales
You probably added a new key to `_schema.json` indirectly via the engine types (`src/engine/types.ts` → `CONTENT_WARNINGS`). New IDs require translations in all 8 locales.
## See Also
- [ARCHITECTURE.md](./ARCHITECTURE.md) — layer model, data flow, engine design.
- [HOSTING.md](./HOSTING.md) — how ytgenerator.stream is built, deployed and protected.
- [I18N.md](./I18N.md) — adding new languages step-by-step.
- [PACKAGING.md](./PACKAGING.md) — Tauri release builds and signing.
- [Top-level CONTRIBUTING.md](../CONTRIBUTING.md) — PR process, commit conventions, auto-ignore rules.
+396 -221
View File
@@ -1,9 +1,26 @@
# Complete Feature List
## YTDescGen — All Features (Current + Planned)
## YTDescGen — All Features (v1.0.0 + Planned)
---
## 🌍 Where It Runs
| Platform | Where | Bot check & analytics |
| ----------- | --------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- |
| **Web** | [ytgenerator.stream](https://ytgenerator.stream) | A Cloudflare **Turnstile** check (usually invisible), remembered for 24 hours; **cookieless** Web Analytics |
| **Desktop** | Windows, macOS, Linux — [Releases](https://github.com/poli0981/youtube-generator/releases) | Neither |
| **Android** | Android 11+, sideloaded `.apk` — [Releases](https://github.com/poli0981/youtube-generator/releases) | Neither |
The web app is a Cloudflare Worker in front of the static build, and
Cloudflare Workers Builds deploys every merge to `main` — see
[HOSTING.md](./HOSTING.md). On every platform your data stays on the device.
GitHub Pages is retired. Until **2026-11-29** the old
`poli0981.github.io/youtube-generator` address shows a moving notice whose
**Download my data** button saves what the browser stored there as a backup
file — restore it in **Settings › Backup & restore**.
## 🎬 Video Types (20 types)
Twenty video types, each driving a dedicated description template, title
@@ -16,117 +33,206 @@ the extra fields the editor reveals — is in
All eight locales ship today — UI strings and description templates fully
translated and parity-validated by `npm run validate:locales`.
| Code | Language | Native Name | Status |
|------|----------|-------------|--------|
| `en` | English | English | ✅ Shipped |
| `vi` | Vietnamese | Tiếng Việt | ✅ Shipped |
| `ja` | Japanese | 日本語 | ✅ Shipped |
| `es` | Spanish | Español | ✅ Shipped |
| `ko` | Korean | 한국어 | ✅ Shipped |
| `zh` | Chinese (Simplified) | 简体中文 | ✅ Shipped |
| `pt-BR` | Portuguese (Brazil) | Português (BR) | ✅ Shipped |
| `id` | Indonesian | Bahasa Indonesia | ✅ Shipped |
| Code | Language | Native Name | Status |
| ------- | -------------------- | ---------------- | ---------- |
| `en` | English | English | ✅ Shipped |
| `vi` | Vietnamese | Tiếng Việt | ✅ Shipped |
| `ja` | Japanese | 日本語 | ✅ Shipped |
| `es` | Spanish | Español | ✅ Shipped |
| `ko` | Korean | 한국어 | ✅ Shipped |
| `zh` | Chinese (Simplified) | 简体中文 | ✅ Shipped |
| `pt-BR` | Portuguese (Brazil) | Português (BR) | ✅ Shipped |
| `id` | Indonesian | Bahasa Indonesia | ✅ Shipped |
The interface language and the output language are chosen separately. The
Output page, Batch and Social can render several output languages at once.
Japanese, Spanish, Korean, Chinese, Portuguese and Indonesian are
AI-translated — see [DISCLAIMER.md](../DISCLAIMER.md).
Further locales (French, German, Russian, Thai, Arabic) are tracked in
[Roadmap § 5.3](./ROADMAP.md). Arabic additionally needs RTL layout work —
see [I18N.md](./I18N.md).
Each language requires:
- `ui.json` — UI labels, buttons, placeholders, error messages
- `templates.json` — Title patterns, description sections, CTA text
- `templates.json` — everything the engine writes: title patterns, description blocks, rig labels, timestamp keywords, pinned comments, CTA text
## 🎮 Game Genres (41 genres)
## 🎮 Game Genres (42 genres)
Forty-one genres feed the title format, the tag pool, and (when configured
Forty-two genres feed the title format, the tag pool, and (when configured
in Settings → Genre Playlists) the pinned-comment playlist recommendation.
The complete list — with icons and bulk-select groups — is in
[Content Inventory](./CONTENT-INVENTORY.md).
A video takes up to **3** genres, picked from a searchable list or with the
All RPGs / All Shooters / All Horror shortcuts. The complete list — with
icons and bulk-select groups — is in [Content Inventory](./CONTENT-INVENTORY.md).
## 🛒 Store Platforms (9 platforms)
## 🛒 Store Platforms (15 stores + publisher site)
| ID | Label | URL Prefix |
|----|-------|-----------|
| `steam` | Steam | `https://store.steampowered.com/app/` |
| `epic` | Epic Games Store | `https://store.epicgames.com/` |
| `ps` | PlayStation Store | `https://store.playstation.com/` |
| `xbox` | Xbox / Microsoft Store | `https://www.xbox.com/games/` |
| `nintendo` | Nintendo eShop | `https://www.nintendo.com/store/` |
| `gog` | GOG | `https://www.gog.com/game/` |
| `itchio` | itch.io | `https://itch.io/` |
| `humble` | Humble Bundle | `https://www.humblebundle.com/store/` |
| `amazon` | Amazon Luna | `https://www.amazon.com/luna/` |
| ID | Label | URL Prefix | Name in tags |
| ------------ | -------------------------- | ------------------------------------------------ | --------------- |
| `steam` | Steam | `https://store.steampowered.com/app/` | Steam |
| `epic` | Epic Games Store | `https://store.epicgames.com/` | Epic Games |
| `ps` | PlayStation Store | `https://store.playstation.com/` | PlayStation |
| `xbox` | Xbox / Microsoft Store | `https://www.xbox.com/games/` | Xbox |
| `nintendo` | Nintendo eShop | `https://www.nintendo.com/store/` | Nintendo Switch |
| `gog` | GOG | `https://www.gog.com/game/` | GOG |
| `itchio` | itch.io | `https://<dev>.itch.io/<game>` | itch.io |
| `humble` | Humble Bundle | `https://www.humblebundle.com/store/` | Humble Bundle |
| `amazon` | Amazon Luna | `https://luna.amazon.com/game/` | Amazon Luna |
| `ea` | EA app | `https://www.ea.com/games/` | EA app |
| `ubisoft` | Ubisoft Store | `https://store.ubisoft.com/` | Ubisoft Connect |
| `battlenet` | Battle.net | `https://shop.battle.net/` | Battle.net |
| `googleplay` | Google Play | `https://play.google.com/store/apps/details?id=` | Android |
| `appstore` | App Store | `https://apps.apple.com/app/` | iOS |
| `meta` | Meta Quest Store | `https://www.meta.com/experiences/` | Meta Quest |
| `publisher` | Publisher / Developer site | any `https://` link | — |
## ☕ Social & Donate Links (12 fields)
EA app, Ubisoft, Battle.net, Google Play, App Store and Meta Quest are new in
v1.0.0. Validation accepts the variants people actually paste (Steam `/sub/`,
`/bundle/` and `s.team` links, regional Nintendo sites, `www.`-less hosts);
Steam links lose their tracking parameters. Each link is marked **paid**,
**free** or **demo**, and the store block's heading switches to "DOWNLOAD THE
GAME" when most links are free or demos.
### Donate
| ID | Label | Prefix |
|----|-------|--------|
| `kofi` | Ko-fi | `https://ko-fi.com/` |
| `patreon` | Patreon | `https://patreon.com/` |
## ☕ Social & Donate Links (22 fields)
### Donate (5)
| ID | Label | Prefix |
| -------------- | --------------- | --------------------------- |
| `kofi` | Ko-fi | `https://ko-fi.com/` |
| `patreon` | Patreon | `https://patreon.com/` |
| `buymeacoffee` | Buy Me a Coffee | `https://buymeacoffee.com/` |
| `paypal` | PayPal | `https://paypal.me/` |
| `streamlabs` | Streamlabs | `https://streamlabs.com/` |
| `paypal` | PayPal | `https://paypal.me/` |
| `streamlabs` | Streamlabs | `https://streamlabs.com/` |
### Social
| ID | Label | Prefix |
|----|-------|--------|
| `github` | GitHub | `https://github.com/` |
| `twitter` | Twitter / X | `https://x.com/` |
| `discord` | Discord | `https://discord.gg/` |
| `twitch` | Twitch | `https://twitch.tv/` |
| `tiktok` | TikTok | `https://tiktok.com/@` |
| `instagram` | Instagram | `https://instagram.com/` |
| `website` | Website | — |
### Social (17)
## 💻 Rig Fields (8 fields)
| ID | Label | Prefix |
| ----------- | ------------- | --------------------------------- |
| `github` | GitHub | `https://github.com/` |
| `youtube` | YouTube | `https://www.youtube.com/` |
| `twitter` | X (Twitter) | `https://x.com/` |
| `discord` | Discord | `https://discord.gg/` |
| `twitch` | Twitch | `https://twitch.tv/` |
| `kick` | Kick | `https://kick.com/` |
| `tiktok` | TikTok | `https://tiktok.com/@` |
| `instagram` | Instagram | `https://instagram.com/` |
| `threads` | Threads | `https://www.threads.com/@` |
| `bluesky` | Bluesky | `https://bsky.app/profile/` |
| `mastodon` | Mastodon | — (full URL including the server) |
| `facebook` | Facebook | `https://facebook.com/` |
| `fb_page` | Facebook Page | `https://facebook.com/` |
| `reddit` | Reddit | `https://www.reddit.com/` |
| `bilibili` | Bilibili | `https://space.bilibili.com/` |
| `telegram` | Telegram | `https://t.me/` |
| `website` | Website | — |
| ID | Label | Example |
|----|-------|---------|
| `cpu` | CPU | Intel i9-14900K / AMD Ryzen 9 7950X |
| `gpu` | GPU | NVIDIA RTX 4090 / AMD RX 7900 XTX |
| `ram` | RAM | 32GB DDR5-6000 |
| `storage` | Storage | 2TB Samsung 990 PRO NVMe |
| `motherboard` | Motherboard | ASUS ROG Maximus Z790 |
| `monitor` | Monitor | LG 27GP950 27" 4K 144Hz |
| `capture` | Capture Software | OBS Studio 30.x |
| `controller` | Controller | DualSense / Xbox Elite Series 2 |
YouTube, Threads, Kick, Reddit and Bilibili are new in v1.0.0; "Twitter / X"
is now "X (Twitter)" (same `twitter` id, so saved links still load).
### Community & Vietnam
- **Community** block — Messenger community, Signal group, Instagram group chat
and Facebook Group links for every language; a Zalo group link for
Vietnamese output only.
- **Donate (Vietnam)** — bank transfer (a list of 37 Vietnamese banks, or
type your own), account number and holder, MoMo and ZaloPay. Rendered only
when the output language is Vietnamese. v1.0.0 added MBV, VCBNeo, Vikki
Bank, Cake by VPBank and Timo; a profile saved with OceanBank, CBBank or
DongA Bank is offered the new name in one click.
## 💻 Rig Fields (10 fields)
Printed in this order, with labels in the output language.
| ID | Label | Input | Example |
| -------------- | ---------------- | ----------------------------------------------------------- | ------------------------------------ |
| `cpu` | CPU | Text with suggestions; names pasted from Windows are tidied | AMD Ryzen 7 9800X3D |
| `gpu` | GPU | Searchable catalog (below) or your own text | NVIDIA GeForce RTX 5080 |
| `ram` | RAM | Size + type (DDR, LPDDR) + speed | 32 GB DDR5-6000 |
| `motherboard` | Motherboard | Text | ASUS ROG Strix X870E-E Gaming |
| `storage` | Storage | Text | 2TB Samsung 990 PRO NVMe |
| `os` | Operating System | Windows / macOS / Linux + version or distro + edition | Windows 11 Pro, Ubuntu 24.04 LTS |
| `monitor` | Monitor | Text | LG 27GP950 27" 4K 144Hz |
| `capture` | Capture Software | Text | OBS Studio 31 |
| `controller` | Controller | Text | DualSense / Xbox Wireless Controller |
| `video_editor` | Video Editor | Dropdown + version | DaVinci Resolve Studio 19.1 |
**GPU catalog (v1.0.0)** — 198 models in 29 groups: NVIDIA GeForce (desktop
and laptop), AMD Radeon (including integrated), Intel Arc and integrated,
Apple M1–M5 and handheld PCs, each printed under its official name ("NVIDIA
GeForce RTX 5080", "AMD Radeon RX 9070 XT", "Apple M4 Pro"). Cards that never
shipped are not listed. Values saved by older versions (Brand › Series ›
Model) are migrated.
## 📄 Output Sections (Description Structure)
Mỗi ngôn ngữ có description structure như sau (tất cả sections optional):
Every block is optional and skipped when empty. In order:
```
1. Intro line (auto-generated from video type + game name)
2. No Commentary tagline
3. ─── Timestamps ─── (if provided)
4. ─── Store Links ─── (if any platform link provided)
5. ─── Video Settings ─── (resolution / FPS / graphics)
6. ─── My Rig ─── (if any rig field provided)
7. ─── Content Warnings ─── (if any selected — 248 IDs across 12 groups)
8. ─── Donate Links ─── (if any provided)
9. ─── Social Links ─── (if any provided)
10. ─── Playlist Link ─── (if provided)
11. ─── Contact Email ─── (if provided)
12. CTA line (Like / Subscribe / Share)
13. Hashtags (3 max, auto-generated)
1. Intro line (video type + game; gacha quests have their own openings)
2. Livestream link / scheduled time (Livestream only)
3. Playthrough notes (run type, difficulty, endings shown, language patch, game version)
4. No Commentary tagline
5. ⏱ Timestamps (keywords translated into the output language)
6. 🎮 Store links (heading depends on paid vs. free / demo links)
7. © Game copyright line (opt-in)
8. 🧪 Playtest / early access (when a playtest link is set)
9. 🖥 Video settings (skipped for games without graphics settings)
10. 💻 My rig
11. 🧩 Mod list (Modded Gameplay only)
12. ⚠️ Content warnings (248 IDs across 12 groups)
13. Tech notes
14. Translation-quality note (opt-in; not for English or Vietnamese)
15. 🎁 Sponsor credit (opt-in)
16. 🤝 Sponsors & partners (opt-in)
17. 🎵 Music / sound
18. ☕ Donate links
19. 🏦 Bank transfer / e-wallet (Vietnamese output only)
20. 🔗 Social links
21. 💬 Community
22. ▶️ Playlist link
23. 📧 Contact email(s) — one line, or split by purpose
24. CTA line (Like / Subscribe / Share)
25. © Copyright line (on by default; needs a channel name)
26. 📋 Usage policy (opt-in)
27. Hashtags (1–3, auto-generated)
```
With one output language selected, the Output page shows content warnings,
tech notes and playthrough notes bilingually (English · output language)
unless the output is English; with several languages selected, each tab —
like each Batch row — stays in its own language. An empty channel name drops
the "on …" phrase from every sentence, in all eight languages.
The Output page also shows the thumbnail text, your pinned-comment draft and,
opt-in, a generated pinned-comment template.
## 🔁 Cross-Post Captions (Social tab)
A dedicated **Social** tab re-packages the same editor source that drives the
YouTube description into short-form captions for other platforms — no
re-typing. Each caption is derived live from the current form.
| Platform | Caption limit | Popular hashtags appended |
|----------|--------------|----------------------------|
| TikTok | 4,000 | `#fyp #foryou #foryoupage #gaming #gamingtiktok #gameplay #gamer` |
| Instagram Reels | 2,200 | `#reels #reelsinstagram #gaming #gamingreels #gamer #instagaming #videogames` |
| Facebook Reels | 2,200 | `#reels #facebookreels #fbreels #gaming #gameplay #gamingcommunity #videogames` |
| Platform | Caption limit | Hashtags | Popular hashtags appended |
| --------------- | --------------------------------- | -------- | ------------------------------------------------------------------------------- |
| TikTok | 4,000 | no cap | `#fyp #foryou #foryoupage #gaming #gamingtiktok #gameplay #gamer` |
| YouTube Shorts | 5,000 | up to 5 | `#shorts #gaming #gameplay` |
| Instagram Reels | 2,200 | no cap | `#reels #reelsinstagram #gaming #gamingreels #gamer #instagaming #videogames` |
| Facebook Reels | 2,200 | no cap | `#reels #facebookreels #fbreels #gaming #gameplay #gamingcommunity #videogames` |
| X | 280, **counted the way X counts** | up to 3 | `#gaming` |
| Threads | 500 | 1 | — |
| Bluesky | 300 | up to 3 | `#gaming` |
YouTube Shorts, X, Threads and Bluesky are new in v1.0.0. X's count weighs
CJK characters, Vietnamese letters with diacritics and emoji double.
Each caption pulls, in order: **Title** (quality badge suppressed for
short-form), **My Rig**, **Content Warnings**, **Thanks / sponsor credit**,
**Copyright**, and **hashtags** (game + primary genre + the curated
per-platform popular set, deduplicated case-insensitively).
**Copyright**, and **hashtags** (game, `#GameplayNoCommentary`, primary genre,
then the platform's popular set — deduplicated case-insensitively and capped
per platform).
- **Overflow handling** — when a caption exceeds the platform limit, optional
blocks are dropped in priority order (warnings → copyright → thanks → rig).
@@ -144,106 +250,163 @@ per-platform popular set, deduplicated case-insensitively).
### Tag Pools by Category
| Pool | Triggered By | Sample Output |
|------|-------------|---------------|
| Core | Always | `[game] gameplay`, `[game] no commentary`, `gameplay no commentary` |
| Genre | Genre selection | `horror game no commentary`, `RPG gameplay no commentary` |
| VideoType | Video type | `[game] boss fight`, `[game] speedrun`, `[game] all endings` |
| Platform | Platform field | `[game] PC`, `PC gameplay`, `[game] Steam` |
| Quality | Resolution/FPS | `[game] 4K`, `4K gameplay no commentary`, `[game] 4K 60FPS` |
| Multilingual JA | Always | `[game] ゲームプレイ`, `[game] 実況なし` |
| Multilingual VI | Always | `[game] gameplay không bình luận` |
| Multilingual ES | If ES enabled | `[game] sin comentarios`, `juego de acción` |
| Trending | Always | `[game] 2026`, `best [genre] games 2026` |
| Pool | Triggered By | Sample Output |
| ------------ | --------------------------------- | ------------------------------------------------------------------------ |
| Game name | Always | `[game]` (shortened to fit 30 characters) |
| Core | Always, in the output language | `[game] gameplay`, `[game] no commentary`, `gameplay no commentary` |
| Genre | Each selected genre | `horror game no commentary`, `RPG gameplay no commentary` |
| VideoType | Video type | `[game] boss fight`, `[game] speedrun`, `[game] all endings` |
| Platform | Platform field | `[game] Steam`, `Steam gameplay`, `[game] Steam gameplay` |
| Quality | Resolution / FPS | `[game] 4K`, `4K gameplay no commentary`, `[game] 4K 60fps` |
| Multilingual | Setting on — output language only | `[game] tiếng Việt` (vi), `[game] 日本語` (ja), `[game] en español` (es) |
| Trending | Setting on | `[game] 2026`, `best horror games 2026`, `horror gameplay 2026` |
| Publisher | Publisher / developer set | `[publisher]` |
### Tag Pipeline
1. Collect tags from all applicable pools
2. Deduplicate (Set-based)
3. Priority sort (core first, trending last)
4. Trim to 500 character limit (drop lowest priority first)
5. Output as comma-separated string
1. Collect tags from all applicable pools, in the priority order above
2. Deduplicate case-insensitively; drop any tag over 30 characters
3. Fit to **500 characters the way YouTube counts them** — every tag, plus
the quotes YouTube puts around a tag with a space, plus a comma between
tags. A tag that doesn't fit is skipped and shorter ones after it are
still tried (v1.0.0; the old count missed the quotes)
4. Output as comma-separated string
Game names are cleaned of characters YouTube splits tags on (`,` `;` `|`) and
of ™ / ® / ©.
## ⚡ Faster Data Entry (v1.0.0)
- **Quick start** — at the top of the editor, pick a **channel profile** and
a **game preset** (both remembered). If that would replace fields you
already filled, it asks first. "Update profile" / "Update preset" appears
when the editor no longer matches them.
- **Next part** — same game, next part: the part number goes up by one and
what belonged to the last video (boss, timestamps, endings, pinned comment,
sponsor, …) is cleared.
- **New video, same game** — the same clean-up, without touching the part
number. Applying a preset for another game clears those fields too.
- **Start over** — clears the game and video fields but keeps your channel
(name, contact, social links, rig, donate and community links); the draft
starts in your **Default Output Language**.
- **Paste a store link anywhere** — on the page, in the Game name field or in
the wrong store's field: the link lands in the right store field, sets the
platform when it's the game's first store link, and fills an empty Game
name from the link ("Final Fantasy VII Remake").
- **Game-name suggestions** — the Game name field suggests names from your
presets and history.
- **Title shapes** — the Output page's title alternatives (game first, video
first, quality badge first); "Use this shape" saves one to the title
format.
- **Batch** — Part or Demo part N…M (up to 100 parts) in several languages at
once, continuing from the editor's part number.
- **Save to History** — Ctrl/⌘+S from any page.
Applying a profile, preset or template, Next part, New video, Start over and
a pasted store link can each be undone from the toast they show.
## 🖥 Interface (v1.0.0)
- **App shell** — a collapsible sidebar, a top bar with the output and
interface languages, and on phones a bottom bar (Editor, Output, Batch,
Profiles, More).
- **Command palette** (Ctrl/⌘+K) — go to any page or the Legal Center; copy
the title, description, tags or everything; apply a saved profile, game
preset or template; switch theme, interface language or output language;
open the shortcuts, the wiki or a bug report.
- **Live preview** — the generated title, description and tags beside the
editor form (a sheet on phones), with the same counters and copy rules as
the Output page.
- **YouTube preview** (Output) — where search results cut the title (about
70 characters) and what shows above "…more" (about the first 150
characters of the description).
- **Chapter check** (Timestamps) — whether YouTube will show chapters (first
timestamp at 0:00, at least 3, ascending, each at least 10 seconds long);
**Tidy up** rewrites a pasted list as one `M:SS label` per line.
- **Pages** — Editor, Output, Batch, Social, Playlist; Profiles (profiles,
game presets, templates), History; Settings, Logs, About; the Legal Center.
- Dark and light themes; animated icons follow the system's _reduce motion_;
controls grow on touch screens.
## 💾 Data Persistence
### Profile (saved once, reused always)
```typescript
interface Profile {
id: string; // uuid
name: string; // "Main Channel"
channelName: string;
contactEmail: string;
social: Record<string, string>;
rig: Record<string, string>;
resolution: string;
fps: string;
graphicsPreset: string;
createdAt: string;
updatedAt: string;
}
```
Everything stays on the device: the browser's storage for
`ytgenerator.stream` on the web, the app's own storage on desktop and
Android. There is no account and no server-side copy.
### Game Preset (saved per game, reused for all parts)
```typescript
interface GamePreset {
id: string;
gameName: string;
gameNameLocalized?: Record<string, string>;
genre: Genre;
platform: string;
storeLinks: Record<string, string>;
spoilerWarning: boolean;
matureWarning: boolean;
createdAt: string;
}
```
| Item | What it holds | Where |
| ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------- |
| **Profile** — the channel | Channel name; contact emails (general, advertising, game keys); social and donate links; community links; Vietnamese bank / MoMo / ZaloPay details; rig; resolution, FPS and graphics preset; sponsors & partners text | Profiles › Profiles |
| **Game preset** — the game | Game name (+ per-language names); genres; platform; store links and their type (paid / free / demo); publisher / developer; content warnings; language patch; game version; art style; "no graphics settings"; series playlist | Profiles › Game presets |
| **Template** — the whole form | Every editor field | Profiles › Templates |
| **History** | One entry per video — game, video type, language, genres, title, description, tags. Saving the same video again updates its entry (v1.0.0) | History |
| **Draft** | The editor form, saved as you type | — |
### History Entry (auto-saved per generation)
```typescript
interface HistoryEntry {
id: string;
gameName: string;
videoType: VideoType;
language: SupportedLanguage;
title: string;
description: string;
tags: string;
createdAt: string;
}
```
The field lists live in `src/config/library-fields.ts`. Profiles, presets and
templates export and import as JSON; History exports as **CSV** or JSON.
Backups and exports carry the date in their file names
(`ytdescgen-backup-2026-09-30.json`).
### Backup & restore (v1.0.0)
In **Settings › Backup & restore**:
- **Back up** everything — or chosen parts: profiles, game presets,
templates, history, settings, the current draft — to one JSON file.
Settings never carry your legal consent or which panels are open.
- **Restore** from a file, or drop the file on the section. Files from every
earlier version are read (v0.15–v0.38 exports, pre-v0.15 arrays, the old
desktop data file) and go through the same migrations the app runs on its
own data.
- **Preview before anything changes**: each item is _new_, _already here_ or
_different_. **Merge** adds what's new and, for items that differ, keeps
the newer one or both; **Replace** makes each chosen section match the
file. One step, with **Undo**.
- **Automatic backups (desktop)** — the newest ten in the app's data folder,
written after the library changes and before every restore. Restore any of
them from the same section, or **Back up now**.
## ⌨️ Keyboard Shortcuts
| Shortcut | Action |
|----------|--------|
| `Ctrl+Enter` | Generate output (switch to Output tab) |
| `Ctrl+Shift+C` | Copy all (title + description + tags) |
| `Ctrl+Shift+T` | Copy title only |
| `Ctrl+Shift+D` | Copy description only |
| `Ctrl+Shift+G` | Copy tags only |
| `Ctrl+S` | Save current form as draft |
| `Ctrl+P` | Quick-switch profile |
| `Ctrl+/` | Show keyboard shortcuts |
| `Escape` | Close modal / clear selection |
`Ctrl` on Windows / Linux / Android, `⌘` on a Mac — both work everywhere.
| Shortcut | Action |
| ---------------------------- | --------------------------------------------------------------- |
| `Ctrl/⌘+K` | Command palette |
| `Ctrl/⌘+Enter` or `Ctrl/⌘+G` | Generate (switch to Output) |
| `Ctrl/⌘+Shift+C` | Copy All — same limits and Strict Mode rules as the Output page |
| `Ctrl/⌘+S` | Save the current output to History |
| `Ctrl/⌘+B` | Collapse / expand the sidebar |
| `Ctrl/⌘+/` or `?` | Show keyboard shortcuts (`?` only outside text fields) |
| `Escape` | Close modal |
## 🔧 Settings
| Setting | Type | Default | Description |
|---------|------|---------|-------------|
| Theme | dark / light | dark | App color theme |
| App Language | SupportedLanguage | browser-detected | Language of the interface |
| Default Output Language | SupportedLanguage | en | Pre-selected for new drafts |
| Show Character Count | boolean | true | Display char counters on output. **Does not** affect copy blocking |
| Compact Tag Display | boolean | false | Tags as comma list vs chip display |
| **Strict Mode** | boolean | **false** | v0.35.0. Blocks Generate / Copy / Export while any field has a hard error |
| History Limit | number | 100 | Max history entries to keep |
| Log Retention | 1–90 days | 7 | Log files older than this are deleted at boot |
| Include Multilingual Tags | boolean | true | Add per-language tags to tag output |
| Include Trending Tags | boolean | true | Add year-based trending tags |
| Hashtag Count | 1-3 | 3 | Number of hashtags to generate |
| Genre Playlists | map | `{}` | One playlist URL per genre (42), collapsed by default |
| Setting | Type | Default | Description |
| -------------------------- | ------------------------------- | ---------------- | ---------------------------------------------------------------------------------- |
| Theme | dark / light | dark | App color theme |
| App Language | SupportedLanguage | browser-detected | Language of the interface |
| Default Output Language | SupportedLanguage | browser-detected | Language a new draft starts in (first run, Start over) |
| Show Character Count | boolean | true | Display char counters on output. **Does not** affect copy blocking |
| Compact Tag Display | boolean | false | Tags as comma list vs chip display |
| Copy All includes the tags | boolean | false | v1.0.0. Copy All copies title, description, then tags |
| **Strict Mode** | boolean | **false** | v0.35.0. Blocks Generate / Copy / Export while any field has a hard error |
| Show quality badge | boolean | true | `[2K 60FPS]`-style badge in the title when resolution or FPS is above the defaults |
| Title order | game first / video first | game first | v1.0.0. "Hades — Part 3" or "Part 3 — Hades" |
| Quality badge position | prefix / middle / suffix | middle | Where the badge sits in the title |
| Segment separator | em dash / hyphen / colon / pipe | em dash | Characters come from each locale |
| Badge case | upper / lower | upper | "2K" or "2k" |
| Include Multilingual Tags | boolean | true | Add tags in the output language |
| Include Trending Tags | boolean | true | Add year-based trending tags |
| Hashtag Count | 1-3 | 3 | Number of hashtags to generate |
| Genre Playlists | map | `{}` | One playlist URL per genre (42), collapsed by default |
| History Limit | 10–500 | 100 | Max history entries to keep |
| Log Retention | 1–90 days | 7 | Log files older than this are deleted at boot |
`Default Genre` and `Auto-save Draft` were removed in v0.22.0 and v0.3
respectively — the draft autosaves unconditionally, so the toggle was dead.
"Browser-detected" means the browser's language when it is one of the eight,
otherwise English. `Default Genre` and `Auto-save Draft` were removed in
v0.22.0 and v0.3 respectively — the draft autosaves unconditionally, so the
toggle was dead. **Backup & restore** is the last section of the page.
### Description toggles
@@ -252,32 +415,37 @@ respectively — the draft autosaves unconditionally, so the toggle was dead.
`showPinnedCommentTemplate` · `pinnedCommentIncludeAskNextGame` ·
`pinnedCommentIncludeGenrePlaylist`
## 🛡 Guardrails (v0.35.0)
On by default: `showCopyright` and `pinnedCommentIncludeAskNextGame`.
Three independent mechanisms. The first two are always on.
## 🛡 Guardrails
| Mechanism | Scope |
|---|---|
| **Character limits** | Title 100 / description 5,000 / tags 500. If **any one** is over, **no** field can be copied — on Output and Batch. Batch scopes per part; Copy All Batch blocks if any part is over |
| **Field limits** | Hard `maxLength` per category: URL 200, email 320, short name 100, label 300, long text 2,000, timestamps 5,000, numeric 10. Imported values are clamped too |
| **Strict Mode** | Opt-in. Blocks Generate / Copy / Export on hard errors only; warnings (e.g. a working link on a non-standard prefix) never block. Log export is exempt |
| Mechanism | Scope |
| ------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Character limits** | Title 100 / description 5,000 / tags 500 (tags counted the way YouTube counts them). Since v1.0.0 only the field that is over can't be copied; the others still can. Copy All is blocked when the title or description is over — or the tags, when Copy All includes them. In Batch an over-limit part blocks only its own field; Copy All Batch is blocked when any part is over |
| **Characters YouTube rejects** | The Output page warns when the title or description contains `<` or `>` |
| **Field limits** | Hard `maxLength` per category: URL 200, email 320, short name 100, label 300, long text 2,000, timestamps 5,000, numeric 10. Imported values are clamped too |
| **Strict Mode** | Opt-in. Blocks Generate / Copy / Export on hard errors only; warnings (e.g. a working link on a non-standard prefix) never block. Log export is exempt |
Emails are capped at **three per field**, enforced on the increase so an
over-cap legacy value stays editable. Invalid input is never committed to the
store, so a malformed URL cannot reach the generated description whether Strict
Mode is on or off.
over-cap legacy value stays editable, and a domain without a TLD is rejected.
Invalid input is never committed to the store, so a malformed URL cannot
reach the generated description whether Strict Mode is on or off.
## 🖥 Desktop App Features (Tauri)
| Feature | Description |
|---------|-------------|
| System Tray | Minimize to tray, quick access |
| Native Clipboard | Direct clipboard write (no browser permission) |
| File Export | Save outputs as `.txt` / `.json` to file system |
| File Import | Import profiles/presets from JSON file |
| Auto-update | Tauri updater (check GitHub releases) |
| Offline | Full functionality without internet |
| Global Hotkey | System-wide hotkey to open app (optional) |
| Feature | Description |
| ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| System Tray | One tray icon (the app icon) with Show / Quit; left-click shows the window; closing the window hides it to the tray |
| Single instance | Launching the app again brings the running window forward |
| Files | Export and import through native Save / Open dialogs run from Rust — text formats only (`json`, `jsonl`, `txt`, `csv`, `md`), imports capped in size. The webview never handles a file path (v1.0.0) |
| Automatic backups | The newest ten in the app's data folder (see Backup & restore) |
| Logs | One log file per day in the app's data folder, pruned by Log Retention |
| Offline | Full functionality without internet; no analytics, no Turnstile check |
| Window | Resizable, 1280×820 by default |
| Installer | The Windows MSI / NSIS installers show the license page |
There is no auto-updater yet — new versions come from
[Releases](https://github.com/poli0981/youtube-generator/releases).
## 📱 Android App (v0.29)
@@ -285,61 +453,68 @@ An installable, sideloadable `.apk` built from the same Tauri 2 codebase — no
separate mobile project. Build with `cargo tauri android build --apk`; see
[PACKAGING.md](./PACKAGING.md#android-apk-packaging).
| Feature | Description |
|---------|-------------|
| Same codebase | One Tauri 2 project produces web, desktop, and Android |
| Min version | Android 11+ (minSdk 30); `targetSdk` 36 (Android 16) |
| Tested | Android 11 → 16 (emulators); real device on Android 12 |
| Signed APK | Self-signed release APK for sideloading; CI publishes it to GitHub Releases |
| Responsive UI | Drawer navigation, touch-sized controls, safe-area insets |
| File export | Routed through the WebView download (lands in Downloads) on Android |
| Persistence | App-private data dir (`appDataDir()`) + localStorage; works offline |
| No tray | Desktop-only tray / single-instance are `#[cfg(desktop)]`-gated out |
| Feature | Description |
| ------------- | ---------------------------------------------------------------------------------------------- |
| Same codebase | One Tauri 2 project produces web, desktop, and Android |
| Min version | Android 11+ (minSdk 30); `targetSdk` 36 (Android 16) |
| Tested | Android 11 → 16 (emulators); real device on Android 12 |
| Signed APK | Self-signed release APK for sideloading; CI publishes it to GitHub Releases |
| Responsive UI | Bottom tab bar (Editor, Output, Batch, Profiles, More), touch-sized controls, safe-area insets |
| File export | Routed through the WebView download (lands in Downloads) on Android |
| Persistence | App-private storage; works offline |
| No tray | Desktop-only tray / single-instance / automatic backups are left out |
## 🚦 Error Pages & Offline (v0.27)
A single reusable, fully-localized `ErrorPage` component (`src/components/errors/`)
backed by a pure kind→meta config (`src/config/error-pages.ts`). All copy ships
in every locale (en/vi/ja/es/ko/zh).
in all eight locales.
| Kind | Route | Trigger |
|------|-------|---------|
| 404 Not found | catch-all `*` | A mistyped / dead hash route (live — was a blank screen before) |
| 403 Forbidden | `/#/403` | Designed page, route-reachable for future triggers |
| 419 Expired | `/#/419` | Designed page, route-reachable for future triggers |
| 500 Server error | `/#/500` | Designed page (covers 408/5xx), route-reachable for future triggers |
| Offline | `/#/offline` + banner | `navigator.onLine` flips false |
| Runtime crash | — | A render error caught by `ErrorBoundary` (shared `contained` variant) |
Routes are real paths on the web (`/403`) and hash routes in the desktop and
Android apps (`/#/403`). Old `/#/…` links on the web still work — they are
rewritten to the path form (v1.0.0).
| Kind | Route | Trigger |
| ---------------- | ------------------- | --------------------------------------------------------------------- |
| 404 Not found | catch-all `*` | A mistyped / dead route (live — was a blank screen before) |
| 403 Forbidden | `/403` | Designed page, route-reachable for future triggers |
| 419 Expired | `/419` | Designed page, route-reachable for future triggers |
| 500 Server error | `/500` | Designed page (covers 408/5xx), route-reachable for future triggers |
| Offline | `/offline` + banner | `navigator.onLine` flips false |
| Runtime crash | — | A render error caught by `ErrorBoundary` (shared `contained` variant) |
- **Full-screen, no shell** — dedicated error routes render outside `AppShell`
(no Sidebar/Header), with Home / Back / (Reload) / Report-a-bug actions.
- **Non-blocking offline banner** — a dismissible bottom strip; the app stays
fully usable offline, and a toast confirms when the connection returns.
## ⚖️ Legal & Consent (v0.28)
## ⚖️ Legal & Consent (v0.28, reworked in v1.0.0)
A first-run **consent gate** (`src/components/ConsentGate.tsx`, backed by the
pure `src/config/legal.ts`) blocks the app until the user reviews the legal
documents and ticks one "I agree" checkbox.
| Aspect | Behaviour |
|--------|-----------|
| Documents | Terms of Use, Privacy Policy, Disclaimer, License — linked to the GitHub-hosted copies (open in the browser); also surfaced in About → Legal |
| Acceptance | One combined checkbox; Continue disabled until checked |
| Persistence | Stored in the existing settings record (`legalConsentVersion` + timestamp) — **no cookie, no new storage key** |
| Re-prompt | Version-based — only when `CURRENT_TERMS_VERSION` is raised (terms changed); also re-shows in fresh / incognito storage |
| Desktop | Same in-app gate on Windows/macOS/Linux, **plus** a license-acceptance page in the Windows MSI/NSIS installer (`bundle.licenseFile`) |
| Layout | Full-screen, non-dismissible, theme- and locale-aware (all 6 languages) |
| Aspect | Behaviour |
| ----------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Documents | Terms of Use, Privacy Policy, Disclaimer, License (the four you agree to), plus Third-party notices, Security, Notice and Code of Conduct — rendered from the repository's files at build time into the in-app **Legal Center** (offline on desktop and Android; linked from the sidebar, About and the command palette). The Disclaimer also has a Vietnamese version |
| On the web | The same documents are public pages at `/legal/<doc>` (e.g. `/legal/privacy`), readable before the Turnstile check |
| Acceptance | One combined checkbox; Continue disabled until checked; each document opens in the Legal Center; language and theme can be changed on the gate |
| Persistence | `legalConsentVersion` + timestamp in the settings record. On the web, agreeing on the Turnstile page sets a `ytg_terms` cookie the app reads, so a web visitor sees one blocking screen, not two |
| Re-prompt | Version-based — only when `CURRENT_TERMS_VERSION` is raised (terms changed); also re-shows in fresh / incognito storage. Version **2** since v1.0.0 (Cloudflare hosting, Turnstile and Web Analytics in the Privacy Policy) |
| Desktop | Same in-app gate on Windows/macOS/Linux, **plus** a license-acceptance page in the Windows MSI/NSIS installer (`bundle.licenseFile`) |
| Layout | Full-screen, non-dismissible, theme- and locale-aware (all 8 languages) |
## 🔌 Future Extension Points
| Extension | Description | Effort |
|-----------|-------------|--------|
| VS Code Extension | Command palette → generate description | Medium |
| CLI Tool | `ytdesc generate --game "Elden Ring" --type full --lang en` | Low |
| Browser Extension | Right-click on YouTube Studio → auto-fill | High |
| YouTube API | Auto-apply description to video via API | High |
| Template Marketplace | Share/import community templates | Medium |
| AI Tag Suggestions | Use game name to suggest trending tags | Medium |
| Thumbnail Text | Generate text overlay suggestions for thumbnails | Low |
| Multi-channel | Support multiple YouTube channels per profile | Low |
See [ROADMAP.md](./ROADMAP.md) for the post-1.0 backlog.
| Extension | Description | Effort |
| -------------------- | ----------------------------------------------------------- | ------ |
| VS Code Extension | Command palette → generate description | Medium |
| CLI Tool | `ytdesc generate --game "Elden Ring" --type full --lang en` | Low |
| Browser Extension | Right-click on YouTube Studio → auto-fill | High |
| YouTube API | Auto-apply description to video via API | High |
| Template Marketplace | Share/import community templates | Medium |
| AI Tag Suggestions | Use game name to suggest trending tags | Medium |
| Thumbnail Text | Generate text overlay suggestions for thumbnails | Low |
| Multi-channel | Support multiple YouTube channels per profile | Low |
+267 -195
View File
@@ -8,49 +8,104 @@
YTDescGen has **two independent language contexts**:
1. **UI Language** — The app interface (buttons, labels, tooltips). Controlled by `SettingsStore.defaultLanguage`. Affects how the app *looks*.
2. **Output Language** — The generated title/description/tags. Controlled by `EditorStore.language`. Affects what the app *produces*.
1. **UI Language** — the app interface (buttons, labels, tooltips). Stored as `appLanguage` in the settings store (`src/store/settings-store.ts`); changed from the top bar, Settings or the command palette. Affects how the app _looks_.
2. **Output Language** — the generated title/description/tags. Stored as `language` in the editor store (`src/store/editor-store.ts`), per draft; a new draft starts in **Settings › Default Output Language**. Affects what the app _produces_. The Output page, Batch and Social can also render several output languages at once.
These are independent: a Vietnamese user can browse the app in Vietnamese (UI) while generating descriptions in Japanese (output).
These are independent: a Vietnamese user can browse the app in Vietnamese (UI) while generating descriptions in Japanese (output). Both defaults follow the browser's language when it is one of the eight, otherwise English.
## Locales (8)
| Code | Language | Authoring |
| ------- | -------------------- | ----------------------------------------------------- |
| `en` | English | Source locale; the only one bundled in the main chunk |
| `vi` | Vietnamese | Reviewed by the maintainer, a native speaker |
| `ja` | Japanese | AI-translated, not native-reviewed |
| `es` | Spanish | AI-translated, not native-reviewed |
| `ko` | Korean | AI-translated, not native-reviewed |
| `zh` | Chinese (Simplified) | AI-translated, not native-reviewed |
| `pt-BR` | Portuguese (Brazil) | AI-translated, not native-reviewed |
| `id` | Indonesian | AI-translated, not native-reviewed |
The authoring status of each locale is recorded in [DISCLAIMER.md](../DISCLAIMER.md).
## Two Namespaces
| Namespace | File | Holds | Rendered in |
| ----------- | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------- |
| `ui` | `ui.json` | Everything the interface shows | the UI language |
| `templates` | `templates.json` | Everything the engine writes: title patterns, description blocks, rig labels (`description.rigLabels`), timestamp keywords (`timeline.keywords`), pinned comments, playlist copy, hashtags | the output language |
**Rule: generated text lives in `templates.json`.** A sentence or label the
engine writes into a title, description or caption is looked up in
`templates.json`, in the output language, through the `t` the engine is
given (`i18n.getFixedT(language, "templates")`, see
`src/hooks/use-generated-output.ts`) — it is never typed into
`src/engine/`. v1.0.0 moved the rig labels there (`description.rigLabels.*`);
they used to print as English field names in every language.
What stays in code is per-language data that isn't a sentence:
- the tag pools `CORE_TAGS_BY_LANG` and `MULTILINGUAL_TAGS` in `src/engine/tag-generator.ts` (search terms), and
- the patterns in `src/engine/channel-phrase.ts` that remove the words going with an empty channel name ("on", "trên kênh", "による"…).
Both are typed `Record<SupportedLanguage, …>`, so a new language is a compile
error until it has an entry — see Steps 5 and 6.
## File Structure
```
src/i18n/
├── index.ts # i18next init + SUPPORTED_LANGUAGES (en eager, others lazy-loaded)
├── locales/
│ ├── _schema.json # JSON Schema defining all required keys
│ ├── en/
│ │ ├── ui.json # UI strings (buttons, labels, errors, tooltips)
│ │ └── templates.json # Generated content (title, description patterns)
│ ├── vi/
│ │ ├── ui.json
│ │ └── templates.json
│ ├── ja/
│ │ ├── ui.json
│ │ └── templates.json
│ └── es/ # Example: adding Spanish
│ ├── ui.json
│ └── templates.json
└── locales/
├── _schema.json # Every required key, per namespace
├── en/
│ ├── ui.json # UI strings (buttons, labels, errors, tooltips)
│ └── templates.json # Generated content (titles, description blocks, …)
├── vi/
├── ja/
├── es/
├── ko/
├── zh/
├── pt-BR/
└── id/ # Each with the same ui.json + templates.json
```
`_schema.json` lists, for each object path in each namespace, the keys it
must contain — an excerpt:
```json
{
"ui": {
"sidebar": ["expand", "collapse"]
},
"templates": {
"title.separators": ["emDash", "hyphen", "colon", "pipe"]
}
}
```
Adding or removing a key means editing `_schema.json` **and** all 8 locales.
## Adding a New Language — Checklist
The examples use French (`fr`), one of the locales on the
[roadmap](./ROADMAP.md).
### Step 1: Create locale files
```bash
# Generate empty locale from schema
npm run generate:locale -- --lang es
# Generate empty locale from the English source
npm run generate:locale -- --lang fr
# This creates:
# src/i18n/locales/es/ui.json (all keys, empty values)
# src/i18n/locales/es/templates.json (all keys, empty values)
# src/i18n/locales/fr/ui.json (all keys, empty values)
# src/i18n/locales/fr/templates.json (all keys, empty values)
# Prefer editing in place over working from blanks? Pre-fill with English:
npm run generate:locale -- --lang es --copy-english
npm run generate:locale -- --lang fr --copy-english
# Overwrite an existing locale directory:
npm run generate:locale -- --lang es --force
npm run generate:locale -- --lang fr --force
```
The output is key-for-key identical to English, so `npm run validate:locales`
@@ -60,98 +115,47 @@ values were actually translated.
Or copy from English and translate:
```bash
cp -r src/i18n/locales/en src/i18n/locales/es
cp -r src/i18n/locales/en src/i18n/locales/fr
```
### Step 2: Translate ui.json
```jsonc
// src/i18n/locales/es/ui.json
What a finished file looks like — an excerpt of
`src/i18n/locales/es/ui.json` (locale files are plain JSON: no comments, no
trailing commas):
```json
{
"app": {
"title": "Generador de Descripción YT",
"subtitle": "Motor de plantillas Gameplay No Commentary"
},
"tabs": {
"editor": "✏️ Editor",
"output": "📄 Resultado",
"profiles": "💾 Perfiles",
"history": "📜 Historial",
"settings": "⚙️ Ajustes",
"batch": "📦 Lote"
},
"editor": {
"videoType": "Tipo de Video",
"language": "Idioma",
"genre": "Género del Juego",
"gameName": "Nombre del Juego",
"channelName": "Nombre del Canal",
"platform": "Plataforma",
"resolution": "Resolución",
"fps": "FPS",
"graphics": "Gráficos",
"timestamps": "Marcas de Tiempo",
"storeLinks": "Enlaces de Tienda",
"rig": "Mi PC",
"social": "Redes Sociales y Donaciones",
"warnings": "Advertencias",
"spoilerWarning": "Advertencia de Spoiler",
"matureWarning": "Contenido para Adultos (18+)",
"playlistLink": "Enlace de Lista de Reproducción",
"contactEmail": "Correo de Contacto"
"editor": "Editor",
"output": "Resultado",
"profiles": "Perfiles",
"history": "Historial",
"settings": "Ajustes",
"batch": "Lote",
"social": "Redes",
"playlist": "Playlist",
"logs": "Registros",
"about": "Acerca de",
"reportBug": "Reportar bug"
},
"output": {
"title": "📌 Título",
"description": "📝 Descripción",
"tags": "🏷 Etiquetas",
"title": "Título",
"description": "Descripción",
"tags": "Etiquetas",
"copyTitle": "Copiar Título",
"copyDescription": "Copiar Descripción",
"copyTags": "Copiar Etiquetas",
"copyAll": "📋 Copiar Todo",
"copied": "✓ ¡Copiado!",
"copyAll": "Copiar Todo",
"copied": "¡Copiado!",
"charCount": "{{count}}/{{limit}}"
},
"profiles": {
"saveProfile": "Guardar Perfil",
"loadProfile": "Cargar",
"deleteProfile": "Eliminar",
"profileName": "Nombre del Perfil",
"noProfiles": "No hay perfiles guardados.",
"gamePresets": "Preajustes de Juegos"
},
"common": {
"save": "Guardar",
"cancel": "Cancelar",
"delete": "Eliminar",
"confirm": "Confirmar",
"export": "Exportar",
"import": "Importar",
"reset": "Restablecer",
"search": "Buscar"
},
"videoTypes": {
"full": "Gameplay Completo",
"part": "Gameplay Parte",
"boss": "Pelea de Jefe",
"boss_nohit": "Jefe Sin Golpes",
"ending": "Final / Todos los Finales",
"speedrun": "Speedrun",
"100percent": "100% Completado",
"dlc": "Contenido DLC",
"newgame_plus": "New Game+",
"challenge": "Desafío",
"side_quest": "Misiones Secundarias",
"secret": "Secretos / Ocultos",
"comparison": "Comparación de Gráficos",
"guide": "Guía Silenciosa"
}
}
```
### Step 3: Translate templates.json
```jsonc
// src/i18n/locales/es/templates.json
An excerpt of `src/i18n/locales/es/templates.json`:
```json
{
"title": {
"separator": " — ",
@@ -160,91 +164,95 @@ cp -r src/i18n/locales/en src/i18n/locales/es
"full": "",
"part": "Parte {{partNumber}}",
"boss": "{{bossName}} Pelea de Jefe",
"boss_nohit": "{{bossName}} Jefe Sin Golpes",
"ending": "Final",
"speedrun": "Speedrun",
"100percent": "100%",
"dlc": "{{dlcName}} DLC",
"newgame_plus": "New Game+",
"challenge": "Desafío {{challengeName}}",
"side_quest": "Misiones Secundarias",
"secret": "Secretos",
"comparison": "Comparación",
"guide": "Guía"
"dlc": "{{dlcName}} DLC"
}
},
"description": {
"intro": {
"full": "Este video presenta el gameplay completo de {{gameName}} en {{channelName}}.",
"part": "Este video presenta la Parte {{partNumber}} de {{gameName}} en {{channelName}}.",
"boss": "Este video presenta la pelea de jefe {{bossName}} de {{gameName}} en {{channelName}}.",
"boss_nohit": "Este video presenta la pelea de jefe {{bossName}} (sin golpes) de {{gameName}} en {{channelName}}.",
"ending": "Este video presenta el final de {{gameName}} en {{channelName}}.",
"speedrun": "Este video presenta un speedrun de {{gameName}} en {{channelName}}.",
"100percent": "Este video presenta el 100% completado de {{gameName}} en {{channelName}}.",
"dlc": "Este video presenta el DLC {{dlcName}} de {{gameName}} en {{channelName}}.",
"newgame_plus": "Este video presenta el New Game+ de {{gameName}} en {{channelName}}.",
"challenge": "Este video presenta el desafío {{challengeName}} de {{gameName}} en {{channelName}}.",
"side_quest": "Este video presenta las misiones secundarias de {{gameName}} en {{channelName}}.",
"secret": "Este video presenta los secretos y contenido oculto de {{gameName}} en {{channelName}}.",
"comparison": "Este video compara los gráficos de {{gameName}} en {{channelName}}.",
"guide": "Este video es una guía silenciosa de {{gameName}} en {{channelName}}."
"part": "Este video presenta la Parte {{partNumber}} de {{gameName}} en {{channelName}}."
},
"noCommentaryLine": "Sin comentarios — gameplay puro para tu disfrute.",
"noCommentaryLine": "Sin Comentarios — gameplay puro para tu disfrute.",
"sections": {
"timestamps": "⏱ MARCAS DE TIEMPO",
"storeLinks": "🎮 OBTENER EL JUEGO",
"videoSettings": "🖥 AJUSTES DE VIDEO: {{settings}}",
"rig": "💻 MI PC",
"spoilerWarning": "⚠️ ADVERTENCIA DE SPOILER: Este video contiene spoilers. ¡Míralo bajo tu propio riesgo!",
"matureWarning": "🔞 CONTENIDO PARA ADULTOS (18+): Contiene violencia / lenguaje fuerte / contenido gráfico.",
"playlist": "▶️ Ver la serie completa: {{link}}",
"contact": "📧 Consultas comerciales: {{email}}",
"rig": "💻 MI EQUIPO",
"cta": "👍 Me gusta | 🔔 Suscríbete | ↗️ Comparte"
},
"rigLabels": {
"cpu": "CPU",
"gpu": "GPU",
"os": "Sistema Operativo"
}
},
"tags": {
"multilingual": [
"{{gameName}} sin comentarios",
"{{gameName}} gameplay completo",
"juego de acción sin comentarios"
]
"timeline": {
"keywords": {
"chapter": "Capítulo {{n}}",
"boss": "Jefe {{n}}",
"final_boss": "Jefe Final",
"credits": "Créditos"
}
}
}
```
- Keep every `{{variable}}` exactly as it is; only the text around it is translated.
- Sentences that name the channel (`{{channelName}}`) must still read naturally when the channel phrase is removed — see Step 5.
- Don't use i18next plural suffixes (`_one`, `_other`, …). Languages need different plural forms, so the key sets would differ between locales and `validate:locales` would fail. Write count-neutral text instead (`"{{n}} damaged item(s) skipped"`).
### Step 4: Register the language
**Four edits, not one.** This section previously claimed `SUPPORTED_LANGUAGES`
was the only registration step; it isn't, and the missing edits fail in
different ways — one at compile time, one silently at runtime.
Registering a locale touches several files, and two of them fail **silently**
if missed. `tests/i18n/locale-registration.test.ts` guards the picker list
against the locale folders on disk, in both directions.
```typescript
// 1. src/i18n/index.ts — the flag + native name shown in every language picker
// 1. src/engine/types.ts — the union the whole engine is typed against
export type SupportedLanguage = "en" | "vi" | "ja" | "es" | "ko" | "zh" | "pt-BR" | "id" | "fr";
// 2. src/i18n/index.ts — every language picker shows `nativeName (id)`.
// `flag` is no longer displayed, but the registration test requires it.
export const SUPPORTED_LANGUAGES = [
{ id: "en", label: "English", flag: "🇬🇧", nativeName: "English" },
{ id: "vi", label: "Vietnamese", flag: "🇻🇳", nativeName: "Tiếng Việt" },
{ id: "ja", label: "Japanese", flag: "🇯🇵", nativeName: "日本語" },
{ id: "es", label: "Spanish", flag: "🇪🇸", nativeName: "Español" }, // ← Add here
] as const;
// …
{ id: "fr", label: "French", flag: "🇫🇷", nativeName: "Français" },
] as const satisfies readonly {
id: SupportedLanguage;
label: string;
flag: string;
nativeName: string;
}[];
// 2. src/engine/types.ts — the union the whole engine is typed against
export type SupportedLanguage = "en" | "vi" | "ja" | "es" | "ko" | "zh";
// 3. src/store/settings-heal.ts — detectBrowserLanguage's own hardcoded copy.
// 3. src/store/settings-heal.ts — detectBrowserLanguage's own copy of the list.
// Bare codes go in `supported`, region-qualified ones (like "pt-BR") in `REGIONAL`.
// Miss this and the language works, but is never auto-selected for a
// first-time visitor whose browser is set to it.
const supported: SupportedLanguage[] = ["en", "vi", "ja", "es", "ko", "zh"];
const supported: SupportedLanguage[] = ["en", "vi", "ja", "es", "ko", "zh", "id", "fr"];
// 4. src/engine/tag-generator.ts — MULTILINGUAL_TAGS (see Step 5).
// Typed `Record<SupportedLanguage, …>`, so TypeScript catches this one.
// 4. src/engine/tag-generator.ts — CORE_TAGS_BY_LANG + MULTILINGUAL_TAGS (Step 6)
// 5. src/engine/channel-phrase.ts — DROP + FALLBACK (Step 5)
```
> `SUPPORTED_LANGUAGES` is **not** type-bound to `SupportedLanguage`, and every
> consumer casts (`lang.id as SupportedLanguage`). A mismatch between edits 1
> and 2 therefore compiles cleanly and fails at runtime. Do both.
The `satisfies` clause makes an id that isn't in the union a compile error.
Items 4 and 5 are `Record<SupportedLanguage, …>`, so TypeScript catches those
too once the union has the new code.
`npm run generate:locale` prints this checklist on success.
Two more places, outside `src/`:
- **`worker/gate-i18n.ts`** — the Turnstile gate page, the first screen every
web visitor sees, has its own copy of the languages: add the code to
`GateLang`, its strings to `GATE_STRINGS`, and its `Accept-Language` prefix
to `PREFIX_TO_LANG`. `GateLang` is not tied to `SupportedLanguage`, so a miss
is **silent** — those visitors get the gate page in English. Update
`tests/worker/gate-i18n.test.ts` too; it pins the list of gate languages.
- **`DISCLAIMER.md`** (and `docs/i18n/vi/DISCLAIMER.md`) — add the locale to
the translation-quality table.
Optional: if the new locale is human-reviewed, add it to `TRANSLATION_TRUSTED`
in `src/engine/description-builder.ts` so it doesn't get the AI-translation
note, and update `description.translationQuality.intro` (which names the
reviewed languages) in every locale.
`npm run generate:locale` prints a shorter checklist on success; the list
above is the complete one.
No import or `resources` edits needed (v0.26+): locales are lazy-loaded
through a dynamic `import("./locales/<code>/<ns>.json")`, so Vite picks the
@@ -254,18 +262,66 @@ exactly `ui.json` and `templates.json`**. Only English is eagerly bundled
static imports for other languages, that would drag them back into the
main chunk.
### Step 5: Add multilingual tag pool
### Step 5: Channel-phrase patterns
Without a channel name, sentences such as "…of Hades on {{channelName}}." must
not end in "on ." (fixed in v1.0.0). The engine renders `{{channelName}}` as a
placeholder, then removes the words that go with it, per language:
```typescript
// src/engine/tag-generator.ts — add to MULTILINGUAL_TAG_POOLS
multilingual_es: (gameName: string) => [
`${gameName} sin comentarios`,
`${gameName} gameplay completo`,
`juego sin comentarios`,
],
// src/engine/channel-phrase.ts
const DROP: Record<SupportedLanguage, readonly RegExp[]> = {
// …
"pt-BR": [new RegExp(`\\s+no ${S}`, "g")], // "…de Hades no {{channelName}}." → "…de Hades."
};
/** For a sentence shape none of the patterns covers: a neutral stand-in. */
const FALLBACK: Record<SupportedLanguage, string> = {
// …
"pt-BR": "este canal",
};
```
### Step 6: Validate
Write the patterns for the phrases your `templates.json` actually uses. Then
add the code to `LANGS` in `tests/engine/channel-phrase.test.ts`: it renders
every template that names the channel with an empty channel and fails on any
leftover.
### Step 6: Tag pools
```typescript
// src/engine/tag-generator.ts
export const CORE_TAGS_BY_LANG: Record<SupportedLanguage, (gameName: string) => string[]> = {
// …
"pt-BR": (g) => [
`${g} gameplay`,
`${g} sem comentários`,
"gameplay sem comentários",
`${g} detonado`,
`${g} jogo completo`,
`${g} gameplay sem comentarios`,
],
};
export const MULTILINGUAL_TAGS: Record<SupportedLanguage, (gameName: string) => string[]> = {
// …
"pt-BR": (g) => [`${g} português`, `${g} em português`, "gameplay em português"],
};
```
Core tags come right after the game name in the tag list; multilingual tags
are added when **Settings › Include Multilingual Tags** is on, for the output
language only. Tags longer than 30 characters are dropped, and the
registration test checks that each language's core tags use the game name.
### Step 7: Check the font
The bundled Inter font covers Latin (including Vietnamese), Cyrillic and
Greek. Other scripts use the system fonts in `--font-sans-stack`
(`src/styles/globals.css`), which already lists Noto Sans JP / KR / SC for
CJK — add a fallback there if the new language uses another script.
### Step 8: Validate
```bash
npm run validate:locales
@@ -273,26 +329,36 @@ npm run validate:locales
# Reports missing/extra keys per language
```
### Step 7: Test
### Step 9: Test
```bash
npm run test -- --grep "i18n"
# Runs i18n-related tests including new language
npm run test:run -- tests/i18n tests/engine/channel-phrase.test.ts tests/engine/tag-generator.test.ts tests/worker/gate-i18n.test.ts
# Then the whole suite and the type check
npm run test:run
npm run typecheck && npm run typecheck:all
```
## Locale Validation Script
The `scripts/validate-locales.ts` script ensures all locale files are complete:
The `scripts/validate-locales.ts` script checks every locale folder against
`_schema.json`. At v1.0.0 (1,247 UI + 573 template keys per locale):
```
✓ en/ui.json — 47/47 keys
✓ en/templates.json — 32/32 keys
✓ vi/ui.json — 47/47 keys
✓ vi/templates.json — 32/32 keys
✓ ja/ui.json — 47/47 keys
✓ ja/templates.json — 32/32 keys
✗ es/ui.json — 45/47 keys (missing: editor.dlcName, editor.challengeName)
✓ es/templates.json — 32/32 keys
✓ en/ui.json — 1247/1247 keys
✓ en/templates.json — 573/573 keys
✓ es/ui.json — 1247/1247 keys
✓ es/templates.json — 573/573 keys
…
✓ zh/templates.json — 573/573 keys
All locale files are complete!
```
A gap fails the run and names the keys:
```
✗ fr/ui.json — 1245/1247 keys
Missing: editor.quick.nextPart, editor.quick.newVideo
```
## Template Interpolation
@@ -303,33 +369,39 @@ Templates use `{{variable}}` syntax (i18next default):
"intro": "This video features the full gameplay of {{gameName}} on {{channelName}}."
```
Engine passes variables:
The engine gets a `t` fixed to the output language and passes the variables:
```typescript
t("templates:description.intro.full", {
gameName: state.gameName,
channelName: state.channelName,
// src/hooks/use-generated-output.ts
const t = i18n.getFixedT(input.language, "templates");
// src/engine/description-builder.ts
const intro = t(`description.intro.${input.videoType}`, {
gameName,
channelName: channelOrSlot(input.channelName), // a placeholder when there is no channel
partNumber: input.partNumber ?? "",
// …
});
sections.push(withoutEmptyChannel(intro, input.language));
```
## RTL Language Support (Arabic)
For Arabic (`ar`), add RTL handling:
```typescript
// src/i18n/index.ts
export const RTL_LANGUAGES = ["ar"] as const;
// src/App.tsx — set dir attribute
const isRTL = RTL_LANGUAGES.includes(currentLanguage);
<div dir={isRTL ? "rtl" : "ltr"}>
```
Not supported yet. Arabic (`ar`) would need `dir="rtl"` on `<html>` — set
next to `lang`, which `src/main.tsx` updates on every `languageChanged` — and
a right-to-left pass over the layout.
## Contributing Translations
Community members can contribute translations by:
1. Fork the repository
2. Copy `src/i18n/locales/en/` to `src/i18n/locales/{code}/`
3. Translate all strings
4. Run `npm run validate:locales` to check completeness
5. Submit a PR with the new locale files
2. Run `npm run generate:locale -- --lang {code}` (or copy `src/i18n/locales/en/` to `src/i18n/locales/{code}/`)
3. Translate all strings in both files
4. Register the language (Step 4 above)
5. Run `npm run validate:locales` and the tests in Step 9
6. Submit a PR with the new locale files
Native-speaker corrections to the AI-translated locales are the most welcome
contribution of all. `src/i18n/locales/<code>/*.json` can be edited straight
from GitHub's web UI; see [CONTRIBUTING.md](../CONTRIBUTING.md).
+287 -224
View File
@@ -1,113 +1,122 @@
# Desktop Packaging Guide
## YTDescGen — Tauri Desktop App
## YTDescGen — Tauri 2 Desktop and Android Apps
Reflects **v1.0.0**: Windows, macOS (Apple silicon) and Linux desktop apps plus an Android APK, all built from the same Tauri 2 project in `src-tauri/`. The web app is deployed separately — see [HOSTING.md](HOSTING.md).
---
## Why Tauri?
| Feature | Tauri 2 | Electron |
|---------|---------|----------|
| Binary size | ~8 MB | ~150 MB |
| Memory usage | ~30 MB | ~100 MB+ |
| Bundled runtime | System WebView | Chromium |
| Backend language | Rust | Node.js |
| Security | Strict CSP, no Node in renderer | Full Node access |
| Auto-update | Built-in updater | electron-updater |
| CI build time | ~5 min | ~10 min |
| Feature | Tauri 2 | Electron |
| ---------------- | --------------------------------------------------------------------------------------------------------------------- | --------------------------------------- |
| Download size | 3–6 MB installers (v0.38.0: MSI 4.6 MB, NSIS 3.2 MB, `.deb` 5.9 MB); the AppImage, which bundles its libraries, 80 MB | ~150 MB |
| Memory usage | Lower — no second browser engine | Higher — bundled Chromium + Node.js |
| Bundled runtime | System WebView | Chromium |
| Backend language | Rust | Node.js |
| Security model | Capability allow-list and CSP; no Node.js in the webview | Node.js main process, Chromium renderer |
| Auto-update | Updater plugin available — not used by this app | electron-updater |
Kokone đã quen Rust (từ hệ sinh thái Tauri/build tooling). Binary nhỏ, tốn ít RAM, deploy đơn giản.
The maintainer already knew Rust from the Tauri / build-tooling ecosystem; the small binary, low memory use and simple deployment settled it.
## Prerequisites
```bash
# Rust toolchain
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
- **Rust** (stable) via [rustup](https://rustup.rs/).
- **Node.js 22** (`.node-version`) and npm.
- **Tauri CLI** — the npm package `@tauri-apps/cli` is a pinned dev dependency, so `npm run tauri …` (or `npm run tauri:dev` / `npm run tauri:build`) needs nothing else. The cargo CLI (`cargo install tauri-cli --version "^2" --locked`, then `cargo tauri …`) works the same way; the Android release job uses it.
- **Platform tools**:
- Windows: Microsoft C++ Build Tools. WebView2 ships with Windows 10/11; the installers bootstrap it where it is missing (`webviewInstallMode: downloadBootstrapper`).
- macOS: Xcode Command Line Tools.
- Linux: `libwebkit2gtk-4.1-dev libgtk-3-dev libayatana-appindicator3-dev librsvg2-dev patchelf` (what CI installs).
- **Android**: see [Android (.apk) Packaging](#android-apk-packaging).
# Tauri CLI
cargo install tauri-cli
# Node.js 22+
# npm already installed from web development
# Platform-specific
# Windows: Microsoft Visual Studio C++ Build Tools
# macOS: Xcode Command Line Tools
```
`npm run check:tauri` fails when the `@tauri-apps/*` npm packages and the `tauri` crates differ in major.minor — `tauri build` refuses to run in that state, and no workflow runs `tauri build` before a release tag does.
## Project Setup
### 1. Initialize Tauri in existing Vite project
The project was initialised once with `tauri init` (not needed again). `src-tauri/` is committed, except build output (`target/`, the Gradle build folders) and the Android signing files:
```bash
npm run tauri init
```
src-tauri/
├── Cargo.toml, Cargo.lock, build.rs
├── deny.toml # cargo-deny: advisories, licences, sources
├── tauri.conf.json
├── capabilities/default.json # what the webview may call
├── installer-license.txt # Windows installers' licence page
├── icons/ # desktop + Android icons (from assets/brand/logo.svg)
├── src/
│ ├── main.rs # desktop entry → yt_desc_gen_lib::run()
│ ├── lib.rs # plugins, commands, tray, single instance
│ ├── storage.rs # backups and logs under the app data directory
│ └── file_dialog.rs # native Save / Open dialogs
└── gen/android/ # the Android Gradle project (committed)
```
This creates `src-tauri/` directory.
The icons come from the one brand logo: `npx tauri icon assets/brand/logo.svg` regenerates them (`npm run generate:brand` does the same for the web's favicon, PWA icons and link-preview card).
### 2. tauri.conf.json
### 1. tauri.conf.json
```jsonc
```json
{
"$schema": "https://raw.githubusercontent.com/nicedoc/tauri/dev/tooling/cli/schema.json",
"$schema": "https://raw.githubusercontent.com/tauri-apps/tauri/dev/crates/tauri-cli/schema.json",
"productName": "YTDescGen",
"version": "1.0.0",
"identifier": "com.skullmute.ytdescgen",
"build": {
"beforeBuildCommand": "npm run build",
"beforeDevCommand": "npm run dev",
"devPath": "http://localhost:5173",
"distDir": "../dist"
"frontendDist": "../dist",
"devUrl": "http://localhost:5173"
},
"package": {
"productName": "YTDescGen",
"version": "0.1.0"
},
"tauri": {
"bundle": {
"active": true,
"identifier": "com.skullmute.ytdescgen",
"icon": [
"icons/32x32.png",
"icons/128x128.png",
"icons/128x128@2x.png",
"icons/icon.icns",
"icons/icon.ico"
],
"targets": ["msi", "nsis", "dmg", "app"],
"windows": {
"webviewInstallMode": {
"type": "downloadBootstrapper"
}
}
},
"app": {
"windows": [
{
"title": "YTDescGen",
"width": 1100,
"height": 750,
"minWidth": 800,
"minHeight": 600,
"width": 1280,
"height": 820,
"minWidth": 960,
"minHeight": 640,
"resizable": true,
"maximizable": true,
"fullscreen": false,
"center": true
}
],
"security": {
"csp": "default-src 'self'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com"
"csp": "default-src 'self'; style-src 'self' 'unsafe-inline'"
}
},
"bundle": {
"active": true,
"licenseFile": "installer-license.txt",
"icon": [
"icons/32x32.png",
"icons/128x128.png",
"icons/128x128@2x.png",
"icons/icon.icns",
"icons/icon.ico"
],
"targets": "all",
"android": {
"minSdkVersion": 30
},
"systemTray": {
"iconPath": "icons/icon.png",
"iconAsTemplate": true
},
"updater": {
"active": true,
"dialog": true,
"endpoints": [
"https://github.com/poli0981/yt-desc-gen/releases/latest/download/latest.json"
]
"windows": {
"webviewInstallMode": {
"type": "downloadBootstrapper"
}
}
}
}
```
Notes:
- The window opens at 1280×820 and can be resized down to 960×640.
- The CSP allows only the app's own files (plus inline styles, which Radix, Motion and sonner set). That is why the Vite build never inlines assets as `data:` URIs (`assetsInlineLimit: 0`) and the fonts are self-hosted. The Tauri build also carries no analytics beacon — Vite adds it only to the web build.
- There is **no `trayIcon` entry**: the tray icon is built in code (`lib.rs`), with the app icon — a `trayIcon` entry would add a second one.
- There is **no `updater` configuration** — see [Updates](#updates).
- `targets: "all"` builds every bundle the platform supports (MSI + NSIS on Windows, `.app` + `.dmg` on macOS, `.deb` + `.rpm` + AppImage on Linux); the release workflow narrows macOS to `.app`.
> **Installer license page (v0.28).** The real `src-tauri/tauri.conf.json`
> sets `bundle.licenseFile: "installer-license.txt"` (path relative to
> `src-tauri/`). Tauri shows that file as an "accept the terms" page in the
@@ -117,108 +126,144 @@ This creates `src-tauri/` directory.
> the per-bundler keys (`bundle.windows.wix.licenseFile` wants `.rtf`,
> `bundle.windows.nsis.licenseFile` accepts `.txt`).
### 3. Rust Backend (src-tauri/src/main.rs)
### 2. Capabilities (src-tauri/capabilities/default.json)
```rust
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
use tauri::{Manager, SystemTray, SystemTrayMenu, SystemTrayMenuItem, SystemTrayEvent};
#[tauri::command]
fn save_to_file(path: String, content: String) -> Result<(), String> {
std::fs::write(&path, &content).map_err(|e| e.to_string())
}
#[tauri::command]
fn read_from_file(path: String) -> Result<String, String> {
std::fs::read_to_string(&path).map_err(|e| e.to_string())
}
fn main() {
let tray_menu = SystemTrayMenu::new()
.add_item(tauri::CustomMenuItem::new("show", "Show"))
.add_native_item(SystemTrayMenuItem::Separator)
.add_item(tauri::CustomMenuItem::new("quit", "Quit"));
let system_tray = SystemTray::new().with_menu(tray_menu);
tauri::Builder::default()
.system_tray(system_tray)
.on_system_tray_event(|app, event| match event {
SystemTrayEvent::LeftClick { .. } => {
let window = app.get_window("main").unwrap();
window.show().unwrap();
window.set_focus().unwrap();
}
SystemTrayEvent::MenuItemClick { id, .. } => match id.as_str() {
"show" => {
let window = app.get_window("main").unwrap();
window.show().unwrap();
window.set_focus().unwrap();
}
"quit" => {
std::process::exit(0);
}
_ => {}
},
_ => {}
})
.invoke_handler(tauri::generate_handler![save_to_file, read_from_file])
.run(tauri::generate_context!())
.expect("error while running tauri application");
```json
{
"identifier": "default",
"description": "Default capabilities for YTDescGen. File access goes through the app's own name-only commands and native dialogs run from Rust, so the webview gets no dialog, fs or shell permissions.",
"windows": ["main"],
"permissions": ["core:default", "opener:default"]
}
```
The webview can call Tauri's core APIs, the opener plugin (external links open in the system browser, mail client or dialler) and the app's own commands — nothing else. v1.0.0 removed the `fs` and `shell` plugins and their permissions. `tauri-plugin-dialog` is still a dependency, but only Rust uses it: the webview has no dialog permission and no dialog JavaScript package. (`tauri-plugin-fs` still appears in `Cargo.lock` as a dependency of the dialog plugin; the app does not register it.)
### 3. Rust Backend (src-tauri/src)
`main.rs` only calls `yt_desc_gen_lib::run()`. `lib.rs`, abridged:
```rust
mod file_dialog;
mod storage;
#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
// Shared by every platform (desktop + Android). No command takes a path.
let builder = tauri::Builder::default()
.plugin(tauri_plugin_dialog::init())
.plugin(tauri_plugin_opener::init())
.invoke_handler(tauri::generate_handler![
storage::backup_list,
storage::backup_read,
storage::backup_write,
storage::backup_delete,
storage::log_append,
storage::log_list,
storage::log_read,
storage::log_delete,
storage::recover_legacy_data,
file_dialog::export_text_file,
file_dialog::import_text_file,
]);
#[cfg(desktop)]
{
// tauri_plugin_single_instance (first desktop plugin: a second launch
// focuses the running window), a tray icon built in setup() with the
// app icon and a Show / Quit menu, close-to-tray, and exit prevention
// unless Quit was chosen from the tray.
}
#[cfg(not(desktop))]
builder
.run(tauri::generate_context!())
.expect("error while building tauri application");
}
```
The commands:
| Command | Arguments | What it does |
| --------------------- | ---------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- |
| `backup_list` | — | Lists the backups in `<app data>/backups/`, newest first (`name`, `size`, `modifiedMs`) |
| `backup_read` | `name` | Reads one backup (at most 32 MB) |
| `backup_write` | `name`, `content` | Writes atomically (temporary file + rename); after writing a `ytdescgen-backup-*` file, deletes all but the newest ten of those |
| `backup_delete` | `name` | Deletes one backup (a missing file is not an error) |
| `log_append` | `name`, `content` | Appends one entry (at most 256 KB) to `<app data>/logs/<name>` |
| `log_list` | — | The log file names, sorted |
| `log_read` | `name` | Reads one log file (at most 32 MB) |
| `log_delete` | `name` | Deletes one log file |
| `recover_legacy_data` | — | Moves files written by versions before 1.0 into place (see [Legacy files](#legacy-files-from-versions-before-10)); returns `{ backups, logsMoved }` |
| `export_text_file` | `suggestedName`, `content`, `filterName`, `extensions`, `title?` | Opens the native Save dialog **in Rust** and writes the file the user picked; returns its name, or `null` when cancelled |
| `import_text_file` | `filterName`, `extensions`, `title?` | Opens the native Open dialog in Rust and returns `{ name, text }`, or `null` when cancelled |
What makes them safe:
- **Names, not paths.** `storage.rs` builds every path itself, under Tauri's `app_data_dir()`, from a name that must match `ytdescgen-<lowercase letters, digits, hyphens>.json` (at most 100 bytes) for backups or `ytdescgen-YYYYMMDD.jsonl` for logs. Anything else — `..`, separators, other extensions — is rejected before a path exists.
- **Dialogs run in Rust.** `file_dialog.rs` accepts only the extensions `json`, `jsonl`, `txt`, `csv` and `md`; reduces a suggested name to its file name (`../../x/backup.json` → `backup.json`); makes a saved file end in an allowed extension (`backup` → `backup.json`, `backup.exe` → `backup.exe.json`); and refuses imports over 20 MB or that are not UTF-8 (a byte-order mark is stripped). The chosen path never passes through JavaScript. On desktop the dialog is attached to the app window.
- **Removed in v1.0.0**: the five commands that read, wrote, appended to, listed and deleted any path the webview sent (`save_to_file`, `read_from_file`, `append_to_file`, `list_dir`, `delete_file`), and the fs and shell plugins.
Both modules have unit tests (`cargo test` in `src-tauri/`): the name rules, path rejection, backup pruning, legacy recovery, dialog filters and the import checks.
### 4. Frontend Tauri Integration
```typescript
// src/utils/platform.ts
export const IS_TAURI = "__TAURI__" in window;
- **`src/utils/platform.ts`** — `IS_TAURI` (`"__TAURI_INTERNALS__" in window`), `IS_MOBILE` (an Android user agent) and `IS_MAC` (how shortcuts are spelled).
- **`src/utils/native.ts`** — the typed bridge to the commands above; `invoke` from `@tauri-apps/api/core` is imported lazily, so the web build never loads it. Exposes `appBackups` (`list`, `read`, `write`, `remove`), `appLogs` (`append`, `list`, `read`, `remove`), `recoverLegacyData`, `nativeSaveTextFile`, `nativeOpenTextFile`, and `HAS_NATIVE_DIALOGS = IS_TAURI && !IS_MOBILE`.
- **`src/utils/file-ops.ts`** — exports and imports on every platform:
// src/utils/file-ops.ts
import { IS_TAURI } from "./platform";
```typescript
// saveTextFile({ content, filename, mimeType?, description? }) → "saved" | "cancelled" | "failed"
// 1. Tauri desktop: nativeSaveTextFile → export_text_file (dialog + write in Rust)
// 2. Web with the File System Access API (Chromium): showSaveFilePicker
// 3. Anything else (Android, Firefox, Safari): a blob download
//
// openTextFile({ extensions, description? }) → picked | cancelled | failed
// Tauri desktop: nativeOpenTextFile → import_text_file
// Elsewhere: a hidden <input type="file">; its "cancel" event reports a
// dismissed picker (no focus-timer guessing). readTextFile() applies the
// same extension and 20 MB checks to dropped files.
```
export async function saveFile(content: string, filename: string): Promise<void> {
if (IS_TAURI) {
const { save } = await import("@tauri-apps/api/dialog");
const { invoke } = await import("@tauri-apps/api/tauri");
const path = await save({ defaultPath: filename });
if (path) await invoke("save_to_file", { path, content });
} else {
// Web fallback: download via blob
const blob = new Blob([content], { type: "text/plain" });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = filename;
a.click();
URL.revokeObjectURL(url);
}
}
- **`src/utils/log-storage.ts`** — in Tauri, one JSONL line per log entry through `appLogs.append` into the day's file; at start-up it loads the files inside the retention window and deletes older ones. On the web it uses the `ytdescgen-logs` localStorage key instead.
- **`src/utils/open-external.ts`** — in Tauri, external links go through the opener plugin. `target="_blank"` is stripped from external anchors and clicks are intercepted in the capture phase, so a link can neither navigate the app's own webview nor trigger the webview's new-window handling (which failed on Android).
- **`src/utils/backup/startup.ts`** — `startAppData()`, run once from `App.tsx` in Tauri builds: legacy-file recovery, then automatic backups on desktop.
export async function loadFile(): Promise<string | null> {
if (IS_TAURI) {
const { open } = await import("@tauri-apps/api/dialog");
const { invoke } = await import("@tauri-apps/api/tauri");
const path = await open({ filters: [{ name: "JSON", extensions: ["json"] }] });
if (typeof path === "string") return invoke("read_from_file", { path });
return null;
} else {
// Web fallback: file input
return new Promise((resolve) => {
const input = document.createElement("input");
input.type = "file";
input.accept = ".json";
input.onchange = async () => {
const file = input.files?.[0];
if (file) resolve(await file.text());
else resolve(null);
};
input.click();
});
}
}
```
## Where the Apps Keep Data
- **Everything the app holds** — profiles, presets, templates, history, settings and the current draft — is in the **WebView's localStorage**, under the same `ytdescgen-*` keys as the web app (Zustand `persist`). On Windows that is WebView2's profile in `%LOCALAPPDATA%\com.skullmute.ytdescgen\EBWebView`. There is no second copy: the settings "mirror" file of earlier versions is gone.
- **Files the app writes itself** live under Tauri's `app_data_dir()` — `<data dir>/com.skullmute.ytdescgen`, which is `%APPDATA%\com.skullmute.ytdescgen` on Windows:
- `backups/` — `ytdescgen-backup-YYYYMMDD-HHmm.json` files: the automatic backups, **Back up now**, and the backup written before each restore (with a `-before-restore` suffix); the newest ten of these are kept (desktop only). Also the recovered legacy files (`ytdescgen-legacy-data*.json`), which are never deleted automatically. On desktop, Settings › Backup & restore lists them all and restores any of them.
- `logs/` — `ytdescgen-YYYYMMDD.jsonl`, one file per day, deleted after the Log retention setting (1–90 days, default 7).
- **Exports** go wherever the user picks in the Save dialog (desktop) or are downloaded (Android).
Automatic backups: 5 s after start, then after the library changes (30 s quiet, at most every 10 minutes), only when the data differs from the last backup and the library is not empty. Format and rules: [TECH-SPEC.md § 4](TECH-SPEC.md#4-backup-file-format-v100).
### Legacy files from versions before 1.0
Before v1.0.0 the frontend glued file names onto the data directory without a separator, so the settings "mirror" was written as `…\com.skullmute.ytdescgensettings.json` next to the data folder — and never read back — and the log files landed in a `…\com.skullmute.ytdescgenlogs\` folder beside it.
On start, `startAppData()` calls `recover_legacy_data`, which:
- moves the old data file (from the glued path, or `settings.json` inside the data folder) into `backups/` as `ytdescgen-legacy-data.json` (`-2`, `-3`, … when taken). It is **never applied on its own** — the data in the app is usually newer. A toast offers **Review**, which opens the restore preview for that file; on desktop it also stays listed under Settings › Backup & restore.
- merges the stray daily log files into `logs/` (appending when that day's file already exists) and removes the stray folder once it is empty; anything else in it is left alone.
The recovery runs in every Tauri build (desktop and Android); a second run finds nothing to do.
## Versioning
A release bumps the version in **six places**, and `npm run check:version` (in CI and in the release `verify` job) fails until they agree:
| File | Field |
| --------------------------- | ----------------------- |
| `package.json` | `version` |
| `package-lock.json` | `version` |
| `package-lock.json` | `packages[""].version` |
| `src-tauri/tauri.conf.json` | `version` |
| `src-tauri/Cargo.toml` | `[package] version` |
| `src-tauri/Cargo.lock` | the `yt-desc-gen` entry |
`npm version --no-git-tag-version <version>` covers the first three; the Rust / Tauri files are edited by hand (cargo also rewrites the `Cargo.lock` entry on the next non-`--locked` build or check in `src-tauri/`). Add the `CHANGELOG.md` entry in the same change.
## Build & Release
@@ -228,8 +273,8 @@ export async function loadFile(): Promise<string | null> {
# Web only
npm run dev
# Desktop (opens native window with hot reload)
npm run tauri dev
# Desktop (native window against the Vite dev server, with hot reload)
npm run tauri:dev
```
### Production Build
@@ -239,38 +284,60 @@ npm run tauri dev
npm run build
# Desktop → src-tauri/target/release/bundle/
npm run tauri build
npm run tauri:build
```
Output locations:
- Windows: `src-tauri/target/release/bundle/msi/YTDescGen_0.1.0_x64.msi`
- macOS: `src-tauri/target/release/bundle/dmg/YTDescGen_0.1.0_aarch64.dmg`
The Tauri CLI runs `npm run build` first (`beforeBuildCommand`) with `TAURI_ENV_PLATFORM` set, which switches Vite to the Tauri build: `es2020` target, the Legal Center content only, and no static legal pages, `security.txt` or analytics beacon.
Output file names, with the v0.38.0 release sizes:
| Platform | Bundle | File | Size |
| --------------------- | -------------------------------- | ---------------------------------------- | ------ |
| Windows | MSI | `YTDescGen_<version>_x64_en-US.msi` | 4.6 MB |
| Windows | NSIS | `YTDescGen_<version>_x64-setup.exe` | 3.2 MB |
| macOS (Apple silicon) | `.app`, archived by tauri-action | `YTDescGen_<version>_aarch64.app.tar.gz` | 4.4 MB |
| Linux | Debian | `YTDescGen_<version>_amd64.deb` | 5.9 MB |
| Linux | RPM | `YTDescGen-<version>-1.x86_64.rpm` | 5.9 MB |
| Linux | AppImage | `YTDescGen_<version>_amd64.AppImage` | 80 MB |
| Android | Universal APK | `app-universal-release.apk` | 57 MB |
### GitHub Actions Release
The live workflow lives at [.github/workflows/release-desktop.yml](../.github/workflows/release-desktop.yml). Pushing a `v*` tag (e.g. `v0.10.0`) triggers a three-platform matrix build (Windows, macOS ARM, Linux) and uploads each installer to a single draft GitHub Release named `YTDescGen v__VERSION__`. Publish the draft manually after smoke-testing the binaries.
Pushing a `v*` tag (signed, e.g. `v1.0.0`) runs [.github/workflows/release-desktop.yml](../.github/workflows/release-desktop.yml) and [.github/workflows/release-android.yml](../.github/workflows/release-android.yml). Both start with a **`verify`** job, and their build jobs `needs: verify`:
Matrix entries:
```yaml
- run: npm ci # a clean install: package-manager-cache: false
- run: npm run typecheck
- run: npm run test:run
- run: npm run check:version
- run: npm run check:tauri
- name: Tag matches the manifests # "v" + package.json version must equal the tag
```
| Runner | Target | Output |
|---|---|---|
| `windows-latest` | `x86_64-pc-windows-msvc` | `.msi`, `.exe` (NSIS) |
| `macos-14` | `aarch64-apple-darwin` | `.app.tar.gz` |
| `ubuntu-latest` | `x86_64-unknown-linux-gnu` | `.AppImage`, `.deb` |
Release jobs use no dependency caches — a poisoned cache entry written by another workflow must not reach the binaries — and every action is pinned by commit SHA.
Linux runners install `libwebkit2gtk-4.1-dev`, `libgtk-3-dev`, `libayatana-appindicator3-dev`, `librsvg2-dev`, and `patchelf` before building — Tauri's webview + AppImage tooling needs these.
The desktop build is a three-platform matrix; `tauri-apps/tauri-action` builds each target and uploads its bundles to one **draft** GitHub Release named `YTDescGen vX.Y.Z`:
| Runner | Target | Output |
| ---------------- | -------------------------- | --------------------------- |
| `windows-latest` | `x86_64-pc-windows-msvc` | `.msi`, `.exe` (NSIS) |
| `macos-14` | `aarch64-apple-darwin` | `.app.tar.gz` |
| `ubuntu-latest` | `x86_64-unknown-linux-gnu` | `.AppImage`, `.deb`, `.rpm` |
Linux runners install `libwebkit2gtk-4.1-dev`, `libgtk-3-dev`, `libayatana-appindicator3-dev`, `librsvg2-dev` and `patchelf` before building — Tauri's webview and AppImage tooling need them. AppImage bundling runs with `APPIMAGE_EXTRACT_AND_RUN=1` (linuxdeploy needs FUSE, which hosted runners don't reliably provide) and `NO_STRIP=true`.
`fail-fast: false` keeps the other platforms going if one breaks. The `bundleArgs` matrix field is concatenated with `--target ${{ matrix.target }}` and passed through to `tauri build`.
**macOS notes (v0.9.1+):**
- **DMG bundling is skipped** (`--bundles app`). Tauri's DMG bundler runs an AppleScript that flakes intermittently on hosted macOS runners (the headless display can't load Finder fast enough for `osascript` to position icons), so we ship a `.app.tar.gz` instead. Users expand the archive and drag the `.app` into `/Applications`.
- **Intel macOS (`macos-13`) is NOT built.** GitHub started deprecating the `macos-13` free runner pool in 2025; jobs queue indefinitely. If Intel support becomes a priority, switch the macos-14 entry's target to `universal-apple-darwin` (Tauri builds both archs and lipos them into one universal binary) — the runner already has the toolchain capacity.
**Code signing is intentionally skipped** for both Windows and macOS — this is an open-source personal tool, and signing certificates carry recurring cost. End users will see the standard "unverified publisher" / "unidentified developer" prompts on first launch. Document the bypass steps in the release notes if needed.
**Code signing is intentionally skipped** for both Windows and macOS — this is an open-source personal tool, and signing certificates carry recurring cost. End users will see the standard "unverified publisher" / "unidentified developer" prompts on first launch. Document the bypass steps in the release notes if needed. (The Android APK is signed — see below.)
**Auto-changelog** (`git-cliff`) is out of scope; release notes come from the tag's annotated message via the default `tauri-action` behaviour. CHANGELOG.md is hand-maintained.
**Release notes.** tauri-action gives the draft a fixed body ("See the assets to download the installer for your platform."). `CHANGELOG.md` is hand-maintained and is the source for the notes; the maintainer smoke-tests the binaries and publishes the draft by hand. Publishing triggers `announce-release.yml` (the Announcements discussion and Discord).
**Manual re-run:** the workflow accepts `workflow_dispatch` with a `tag` input — `gh workflow run release-desktop.yml -f tag=v0.9.0` rebuilds an existing release without deleting + recreating the tag. Useful when a transient runner failure costs a single arch's binary.
**Manual re-run:** both workflows accept `workflow_dispatch` with a `tag` input — `gh workflow run release-desktop.yml -f tag=v1.0.0` rebuilds an existing release without deleting and recreating the tag. The manifests at that tag must already carry the version, or `verify` stops the run. Useful when a transient runner failure costs a single platform's binary.
**Backfill for pre-workflow tags:** `v0.8.0` and `v0.8.1` predate the multi-platform matrix and only have local Windows builds. To attach binaries retroactively, build manually then `gh release create v0.8.0 --notes-file CHANGELOG.md path/to/*.msi …`.
@@ -285,12 +352,12 @@ is gated behind `#[cfg(desktop)]` so the library compiles for Android.
### Requirements & tested versions
| | |
|---|---|
| **Minimum OS** | **Android 11** (API level 30, `minSdk 30`). The APK will not install below this. |
| **Target OS** | **Android 16** (API level 36, `targetSdk 36`). |
| **Architectures** | Universal APK — `arm64-v8a`, `armeabi-v7a`, `x86`, `x86_64`. |
| **Tested** | **Android 11 → 16.** The v0.29.0 build was verified on Android emulators across this range **and on a real device running Android 12** (the maintainer's phone). |
| | |
| ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Minimum OS** | **Android 11** (API level 30, `minSdk 30`). The APK will not install below this. |
| **Target OS** | **Android 16** (API level 36, `targetSdk 36`, `compileSdk 36`). |
| **Architectures** | Universal APK — `arm64-v8a`, `armeabi-v7a`, `x86`, `x86_64`. |
| **Tested** | **Android 11 → 16.** The v0.29.0 build was verified on Android emulators across this range **and on a real device running Android 12** (the maintainer's phone). |
Where the value lives: `bundle.android.minSdkVersion` in
[`src-tauri/tauri.conf.json`](../src-tauri/tauri.conf.json) is the source of
@@ -306,11 +373,11 @@ directly if you change the floor without re-running `init`.
- **A modern, patched WebView.** The app renders entirely in the system WebView,
whose minimum is Android 10. On Android 11+ the WebView auto-updates via Google
Play, so the rendering/JS engine stays current and patched. This is exactly why
the **real-device test on Android 12 worked**, while a *stale* Android-12
the **real-device test on Android 12 worked**, while a _stale_ Android-12
emulator stuck on WebView 91 showed a black screen (the `crypto.randomUUID`
boot crash) — that class of bug is fixed in v0.29.0 and is moot on an
up-to-date WebView.
- **Security upkeep.** Even though Google's *OS-level* monthly security bulletins
- **Security upkeep.** Even though Google's _OS-level_ monthly security bulletins
for Android 11–13 have ended (Android 12 in 2025, Android 13 in early 2026),
Android 11+ keeps receiving security updates for the components that matter to a
sandboxed WebView app: Google Play system updates (Project Mainline), Google
@@ -319,8 +386,8 @@ directly if you change the floor without re-running `init`.
### Prerequisites
- **Android SDK** — platform-tools, a platform (e.g. `android-34`/`android-36`), build-tools. Install via Android Studio or the command-line tools.
- **Android NDK** — r27 LTS recommended (e.g. `27.3.13750724`).
- **Android SDK** — platform-tools, a platform (e.g. `android-36`), build-tools. Install via Android Studio or the command-line tools.
- **Android NDK** — r27 LTS (`27.3.13750724`, what CI uses).
- **JDK 17** — Android Studio's bundled JBR works (`…/Android Studio/jbr`).
- **Rust android targets**:
```bash
@@ -372,7 +439,7 @@ keyPassword=<key-password>
```
`app/build.gradle.kts` carries a `release` `signingConfigs` block that reads this
file, guarded by `if (exists())` — a missing keystore yields an *unsigned*
file, guarded by `if (exists())` — a missing keystore yields an _unsigned_
release build rather than a hard failure (handy for contributors).
### Build
@@ -386,6 +453,7 @@ cargo tauri android build --apk
- `cargo tauri android build --apk --target aarch64` builds an arm64-only APK (smaller download; covers virtually all modern phones).
- The build runs `npm run build` first (the `beforeBuildCommand`), then Gradle. The first build takes several minutes (Rust × up to 4 ABIs + a cold Gradle).
- For on-device iteration with hot reload: `cargo tauri android dev`.
- With the npm CLI instead of the cargo one: `npm run tauri android build -- --apk`.
Install on a device: copy the APK over (or `adb install -r <apk>`) and enable
"Install unknown apps" for the source app.
@@ -393,48 +461,43 @@ Install on a device: copy the APK over (or `adb install -r <apk>`) and enable
### CI
[.github/workflows/release-android.yml](../.github/workflows/release-android.yml)
builds and signs the APK on a `v*` tag (or `workflow_dispatch`) and attaches it
to the same draft GitHub Release as the desktop binaries. It needs four repo
secrets:
runs on a `v*` tag (or `workflow_dispatch` with a `tag`). After `verify`, the
`build-android` job sets up JDK 17 (Temurin), the Android SDK, NDK
`27.3.13750724`, the four Rust Android targets and the cargo Tauri CLI; decodes
the keystore into `$RUNNER_TEMP`; writes `src-tauri/gen/android/keystore.properties`;
and runs `cargo tauri android build --apk` with `NDK_HOME` pinned to that NDK.
| Secret | Value |
|---|---|
The APK is kept as the workflow artifact `ytdescgen-android-apk`, then attached
to the draft release with `gh release upload <tag> --clobber`. That upload needs
the draft the desktop workflow creates; if the Android job gets there first,
re-run it. It needs four repo secrets:
| Secret | Value |
| ------------------------- | --------------------------------------------------------- |
| `ANDROID_KEYSTORE_BASE64` | base64 of the `.jks` (`base64 -w0 ytdescgen-release.jks`) |
| `ANDROID_STORE_PASSWORD` | keystore store password |
| `ANDROID_KEY_PASSWORD` | key password |
| `ANDROID_KEY_ALIAS` | `ytdescgen` |
| `ANDROID_STORE_PASSWORD` | keystore store password |
| `ANDROID_KEY_PASSWORD` | key password |
| `ANDROID_KEY_ALIAS` | `ytdescgen` |
### App-level changes for Android
- **`src-tauri/src/lib.rs`** — tray / single-instance / hide-to-tray / exit-prevention are `#[cfg(desktop)]`; the dialog/fs/opener/shell plugins and the six file commands run on every platform.
- **`src-tauri/src/lib.rs`** — tray / single-instance / hide-to-tray / exit-prevention are `#[cfg(desktop)]`; the dialog and opener plugins and the eleven commands are registered on every platform.
- **`src-tauri/Cargo.toml`** — `tauri-plugin-single-instance` lives in a desktop-only `[target.'cfg(not(any(target_os = "android", target_os = "ios")))'.dependencies]` table.
- **`src/utils/platform.ts` / `file-ops.ts`** — `IS_MOBILE` routes file export through the WebView blob download on Android (the native save dialog is unreliable under scoped storage). Settings persist via `appDataDir()` (app-private storage) **and** localStorage, both of which work on Android.
- **`src/utils/native.ts` / `file-ops.ts`** — `HAS_NATIVE_DIALOGS` is false on Android (a picked location there is a content URI, not a path), so exports are a WebView download and imports use the file input. Automatic backups are desktop-only; the legacy-file recovery runs on Android too.
- **Storage** — as on desktop, everything is in the WebView's localStorage; the app's own data directory holds `logs/` and, after an upgrade from an older version, the recovered legacy file in `backups/`.
## Auto-Update Flow
## Updates
```
App Start
│
▼
Check GitHub Releases endpoint
│
├─ No update → Continue normally
│
└─ Update available
│
▼
Show dialog: "Update v0.2.0 available. Install now?"
│
├─ Yes → Download + install + restart
└─ No → Dismiss, ask again next launch
```
The app has no in-app updater: no updater plugin, no `updater` configuration, and it never checks for new versions. New versions are published as GitHub Releases; users download the installer or APK for their platform and install it over the existing app. User data is outside the installation — in the WebView storage and the app data directory described above — so it is kept. An Android update must be signed with the same keystore to install over an existing copy.
## Offline Capability
The app is fully offline-capable because:
- All templates and configs are bundled
- State persists in localStorage (web) or app data directory (Tauri)
- No external API calls required
- Fonts can be bundled locally for desktop
The desktop and Android apps work fully offline:
Only auto-update requires internet connectivity.
- All templates, configuration and translations are bundled; the non-English locales are separate chunks inside the app.
- The legal documents are rendered into the build at build time (the Legal Center reads them locally).
- Fonts (Inter, JetBrains Mono) are self-hosted.
- State lives in the WebView's localStorage; backups and logs in the app data directory.
- The app makes no network requests of its own. Only external links (opened in the system browser) need a connection.
The web app is the same code, but reaching it needs the network: the Turnstile check runs at the edge before the app loads, at most once a day per browser (see [HOSTING.md](HOSTING.md)).
+100 -13
View File
@@ -2,13 +2,20 @@
## YTDescGen — Phased Development Plan
> **Status (2026-09-30): v1.0.0 has shipped.** Phases 1–4 are the original
> plan, kept as a record; notes added beside or under an item say what has
> changed since. Every release is listed in [CHANGELOG.md](../CHANGELOG.md).
> What's next: Phase 5 and the backlog at the end of this page.
---
## Phase 1 — MVP Core (Priority: P0) ✅ COMPLETED 2026-04-07
**Goal**: Ứng dụng web chạy được, generate title + description + tags, copy to clipboard.
**Estimated**: 3-4 days | **Actual**: 1 day
### Tasks
```
1.1 Project scaffold
- [x] Vite + React 18 + TypeScript setup
@@ -57,6 +64,7 @@
- [x] EditorPage (form + quick preview)
- [x] OutputPage (title + desc + tags + copy)
- [x] React Router setup (HashRouter)
(v1.0.0: real paths on the web; hash routes only in the desktop/Android apps)
1.8 Testing
- [x] Vitest config
@@ -66,6 +74,8 @@
1.9 CI/CD
- [x] GitHub Actions: lint + typecheck + test
- [x] GitHub Actions: deploy to GitHub Pages
(retired in v1.0.0 — Cloudflare Workers Builds deploys ytgenerator.stream
from main; see HOSTING.md)
### Definition of Done
- [x] User can select video type, language, genre
@@ -73,16 +83,18 @@
- [x] Title, description, and tags generate correctly in EN/VI/JA
- [x] Copy buttons work for title, description, tags, and all
- [x] Character counts displayed (5000 desc, 500 tags)
- [x] CI passes, deploys to GitHub Pages
- [x] CI passes, deploys to GitHub Pages (ytgenerator.stream since v1.0.0)
```
---
## Phase 2 — Profiles & Presets (Priority: P1) ✅ COMPLETED 2026-04-07
**Goal**: Lưu thông tin tái sử dụng, không phải nhập lại mỗi lần.
**Estimated**: 2-3 days | **Actual**: 1 day
### Tasks
```
2.1 Profile system
- [x] profile-store.ts (Zustand + persist)
@@ -133,10 +145,12 @@
---
## Phase 3 — Polish & Advanced Features (Priority: P1-P2) ✅ COMPLETED 2026-04-07
**Goal**: Batch mode, history, keyboard shortcuts, theme.
**Estimated**: 2-3 days | **Actual**: 1 day
### Tasks
```
3.1 History system
- [x] history-store.ts (max entries, auto-prune, configurable limit)
@@ -145,6 +159,7 @@
- [x] Delete history entries
- [x] Search/filter history by game name or title
- [x] Auto-save to history on OutputPage view
(v1.0.0: one entry per video, updated in place)
3.2 Batch mode
- [x] BatchPage UI
@@ -168,10 +183,12 @@
3.5 Keyboard shortcuts
- [x] Global keyboard listener (useKeyboardShortcuts hook)
- [x] Ctrl+Enter (go to output), Ctrl+Shift+C (copy all), Ctrl+S (save draft)
(v1.0.0: Ctrl/⌘+S saves the output to History — the draft saves itself;
Ctrl/⌘+K opens the command palette)
- [x] Ctrl+/ shortcut help modal
3.6 UX Polish
- [x] Toast notifications for copy/save/delete (react-hot-toast)
- [x] Toast notifications for copy/save/delete (react-hot-toast; sonner since v1.0.0)
- [x] Responsive layout (mobile-first, lg breakpoint for sidebar)
- [x] Scrollable tab bar for mobile
- [x] Empty states for all list pages
@@ -199,10 +216,12 @@
---
## Phase 4 — Desktop App (Priority: P2) ✅ COMPLETED 2026-04-08
**Goal**: Đóng gói thành ứng dụng desktop bằng Tauri.
**Estimated**: 2-3 days | **Actual**: 1 day
### Tasks
```
4.1 Tauri setup
- [x] Install Tauri CLI v2 + dependencies (@tauri-apps/api, plugins)
@@ -210,9 +229,12 @@
- [x] tauri.conf.json configuration (Tauri v2 format)
- [x] App icons (all sizes via cargo tauri icon)
- [x] Capabilities (default.json with dialog, fs, shell permissions)
(v1.0.0: only core + opener; the fs and shell plugins are removed)
4.2 Desktop features
- [x] Native file save/load via Tauri commands (save_to_file, read_from_file)
(v1.0.0: replaced by name-only commands under the app's data folder
and Save / Open dialogs run from Rust)
- [x] Platform detection (IS_TAURI flag)
- [x] File ops with web fallback (src/utils/file-ops.ts)
- [x] System tray with Show/Quit menu
@@ -225,14 +247,16 @@
4.4 Build pipeline
- [x] GitHub Actions: release-desktop.yml (Windows + macOS cross-compile)
(now Windows, macOS and Linux; Android via release-android.yml)
- [x] Tag-triggered release (v* tags)
- [x] Verified local build: MSI 4.1MB, NSIS 2.7MB, EXE 14MB
4.5 Platform-specific
- [x] Windows: MSI + NSIS installers built successfully
- [ ] macOS: requires macOS runner (CI handles this)
- [x] macOS: built on the macos-14 CI runner (Apple Silicon .app)
- [x] Offline functionality verified (all bundled, no API calls)
- [x] Vite base URL conditional (/ for Tauri, /yt-desc-gen/ for web)
(v1.0.0: / for both)
### Definition of Done
- [x] Windows installer < 15MB (4.1MB MSI), installs and runs
@@ -244,11 +268,50 @@
---
## v1.0.0 — Stable Release ✅ SHIPPED 2026-09-30
**Goal**: A stable 1.0 on its own domain, with data that is right. Web, desktop
and Android all ship as 1.0.0 — the full list is in
[CHANGELOG.md](../CHANGELOG.md#v100--2026-09-30).
### Contents
```
- [x] Web app at ytgenerator.stream — Cloudflare Worker, deployed by Workers
Builds from main; GitHub Pages retired (moving notice until 2026-11-29)
- [x] Turnstile check before the web app; cookieless Web Analytics (web only);
legal pages served in-site; terms version 2
- [x] New interface — design system, app shell with a bottom bar on phones,
command palette (Ctrl/⌘+K), live preview, YouTube preview
- [x] Backup & restore — preview (new / already here / different), merge or
replace, undo, drag-and-drop, automatic desktop backups, History as CSV
- [x] Quick start — profile + preset pickers, Next part, New video same game,
Start over keeps the channel
- [x] Faster entry — store links pasted anywhere, game-name suggestions,
title shapes + Title order, Copy All with tags, Batch Part / Demo part,
Ctrl/⌘+S saves to History
- [x] Data that is right — GPU catalog and hardware names, tags counted the way
YouTube counts them, chapter check + Tidy up, one History entry per
video, per-field copy gating
- [x] Catalogs — EA app, Ubisoft, Battle.net, Google Play, App Store, Meta
Quest; YouTube, Threads, Kick, Reddit, Bilibili links; YouTube Shorts,
X, Threads, Bluesky captions; five Vietnamese banks
- [x] Desktop hardening — the webview never names a path, Save / Open dialogs
run from Rust, fs and shell plugins removed, one tray icon
- [x] CI — dependency review, workflow lint, OpenSSF Scorecard, REUSE, PR
titles, Rust checks, coverage thresholds, bundle budget, licence
allow-list, Cloudflare dry-run; every action pinned by SHA
```
---
## Phase 5 — Extensions & Ecosystem (Priority: P2-P3)
**Goal**: IDE extension, CLI, community features.
**Estimated**: Ongoing
### Tasks
```
5.1 CLI tool
- [ ] Standalone Node.js CLI using engine/
@@ -263,14 +326,21 @@
- [ ] Settings sync with VS Code settings
5.3 Additional languages
- [ ] French, German, Portuguese, Russian, Thai, Arabic
- [ ] Community contribution guide for translations
- [ ] Locale validation CI check
- [x] Portuguese — shipped as Brazilian Portuguese (pt-BR) in v0.38.0,
together with Indonesian (id)
- [ ] French, German, Russian, Thai, Arabic
- [x] Community contribution guide for translations (docs/I18N.md,
CONTRIBUTING.md)
- [x] Locale validation CI check (npm run validate:locales in the
required `check` job)
5.4 Template customization
- [ ] Custom template editor in app
- [ ] Template import/export
- [ ] Template sharing (JSON format)
(Full-form templates — every editor field — already export and
import as JSON on Profiles › Templates; these items are about
editing the description templates themselves.)
5.5 Quality of life
- [ ] YouTube API integration (auto-apply description)
@@ -280,14 +350,31 @@
---
## Backlog (after v1.0.0)
Ideas carried over from the v1.0.0 planning — not scheduled.
```
- [ ] Auto-fill game info from Steam through the Worker — needs rate limiting
and a decision for the desktop app
- [ ] More genres: Sports, Point & Click, MOBA, Party — the taxonomy is still
to decide
- [ ] PWA offline for the web — conflicts with the Turnstile gate in front of
the app
- [ ] PGP signature for security.txt
```
---
## Timeline Summary
| Phase | Scope | Days | Cumulative |
|-------|-------|------|------------|
| Phase 1 | MVP Core | 3-4 | 3-4 days |
| Phase 2 | Profiles & Presets | 2-3 | 5-7 days |
| Phase 3 | Polish & Advanced | 2-3 | 7-10 days |
| Phase 4 | Desktop App | 2-3 | 9-13 days |
| Phase 5 | Extensions | Ongoing | — |
| Phase | Scope | Days | Cumulative |
| ------- | ------------------ | ------- | ---------- |
| Phase 1 | MVP Core | 3-4 | 3-4 days |
| Phase 2 | Profiles & Presets | 2-3 | 5-7 days |
| Phase 3 | Polish & Advanced | 2-3 | 7-10 days |
| Phase 4 | Desktop App | 2-3 | 9-13 days |
| Phase 5 | Extensions | Ongoing | — |
**MVP usable after Phase 1** (~3-4 days). Full-featured after Phase 3 (~7-10 days).
**v1.0.0 shipped on 2026-09-30.**
+487 -275
View File
@@ -2,17 +2,20 @@
## YTDescGen — Implementation Details
Reflects **v1.0.0**. The module map and data flow are in [ARCHITECTURE.md](ARCHITECTURE.md), the desktop and Android builds in [PACKAGING.md](PACKAGING.md), and running the web deployment (Cloudflare Worker, Turnstile, secrets, rollback) in [HOSTING.md](HOSTING.md).
---
## 1. Package Configuration
### package.json
```jsonc
```json
{
"name": "yt-desc-gen",
"version": "0.20.0",
"version": "1.0.0",
"private": true,
"license": "Apache-2.0",
"type": "module",
"scripts": {
"dev": "vite",
@@ -21,55 +24,89 @@
"test": "vitest",
"test:run": "vitest run",
"test:coverage": "vitest run --coverage",
"lint": "eslint src/ --ext .ts,.tsx",
"lint:fix": "eslint src/ --ext .ts,.tsx --fix",
"lint": "eslint src/ tests/ scripts/ worker/ build-plugins/",
"lint:fix": "eslint src/ tests/ scripts/ worker/ build-plugins/ --fix",
"knip": "knip",
"typecheck": "tsc --noEmit",
"format": "prettier --write \"src/**/*.{ts,tsx,json,css}\"",
"typecheck:all": "tsc --noEmit -p tsconfig.check.json",
"format": "prettier --write \"{src,tests,scripts,worker,build-plugins}/**/*.{ts,tsx,css}\"",
"format:check": "prettier --check \"{src,tests,scripts,worker,build-plugins}/**/*.{ts,tsx,css}\"",
"check:version": "tsx scripts/check-version-sync.ts",
"validate:locales": "tsx scripts/validate-locales.ts",
"generate:locale": "tsx scripts/generate-locale-template.ts",
"tauri": "tauri",
"tauri:dev": "tauri dev",
"tauri:build": "tauri build"
"tauri:build": "tauri build",
"generate:brand": "tsx scripts/generate-brand-assets.ts",
"cf:dev": "wrangler dev",
"cf:check": "wrangler deploy --dry-run --outdir .wrangler/dry-run",
"check:tauri": "tsx scripts/check-tauri-versions.ts",
"check:bundle": "tsx scripts/check-bundle-size.ts",
"check:licenses": "tsx scripts/third-party.ts",
"generate:third-party": "tsx scripts/third-party.ts --write"
},
"dependencies": {
"react": "^18.3.0",
"react-dom": "^18.3.0",
"react-router-dom": "^6.26.0",
"zustand": "^4.5.0",
"i18next": "^23.15.0",
"react-i18next": "^15.0.0",
"react-hot-toast": "^2.4.0",
"lucide-react": "^0.400.0",
"clsx": "^2.1.0"
"@fontsource-variable/inter": "^5.3.0",
"@fontsource-variable/jetbrains-mono": "^5.3.0",
"@tauri-apps/api": "^2.12.0",
"@tauri-apps/plugin-opener": "^2.7.0",
"clsx": "^2.1.1",
"cmdk": "^1.1.1",
"i18next": "^26.4.2",
"i18next-resources-to-backend": "^1.2.3",
"lucide-react": "^1.49.0",
"motion": "^13.4.6",
"radix-ui": "^1.6.7",
"react": "^19.3.0",
"react-dom": "^19.3.0",
"react-i18next": "^17.0.15",
"react-router-dom": "^7.18.4",
"simple-icons": "^16.33.0",
"sonner": "^2.0.8",
"zustand": "^5.0.15"
},
"devDependencies": {
"@types/react": "^18.3.0",
"@types/react-dom": "^18.3.0",
"@vitejs/plugin-react": "^4.3.0",
"typescript": "^5.5.0",
"vite": "^5.4.0",
"vitest": "^2.0.0",
"@testing-library/react": "^16.0.0",
"@testing-library/jest-dom": "^6.4.0",
"tailwindcss": "^3.4.0",
"postcss": "^8.4.0",
"autoprefixer": "^10.4.0",
"eslint": "^9.0.0",
"@eslint/js": "^9.0.0",
"typescript-eslint": "^8.0.0",
"eslint-plugin-react-hooks": "^4.6.0",
"prettier": "^3.3.0",
"prettier-plugin-tailwindcss": "^0.6.0",
"@tauri-apps/cli": "^2.0.0",
"@tauri-apps/api": "^2.0.0",
"tsx": "^4.16.0"
"@eslint/js": "^10.0.1",
"@resvg/resvg-js": "2.6.2",
"@tailwindcss/postcss": "^4.3.3",
"@tauri-apps/cli": "2.12.0",
"@testing-library/jest-dom": "^7.0.1",
"@testing-library/react": "^16.3.3",
"@types/node": "^26.6.3",
"@types/react": "^19.3.0",
"@types/react-dom": "^19.3.0",
"@vitejs/plugin-react": "^6.1.1",
"@vitest/coverage-v8": "^4.1.11",
"autoprefixer": "^10.6.1",
"eslint": "^10.11.0",
"eslint-plugin-react-hooks": "^7.1.1",
"knip": "^6.38.0",
"marked": "18.0.14",
"postcss": "^8.5.28",
"prettier": "^3.9.9",
"prettier-plugin-tailwindcss": "^0.8.1",
"tailwindcss": "^4.3.3",
"tsx": "^4.23.15",
"typescript": "^5.9.3",
"typescript-eslint": "^8.71.0",
"vite": "^8.3.1",
"vitest": "^4.1.11",
"wrangler": "4.144.0"
}
}
```
Notes:
- **UI stack**: React 19, React Router 7, Zustand 5, i18next 26 / react-i18next 17, Radix primitives through the single `radix-ui` package (Dialog, AlertDialog, Popover, Tooltip, Tabs, Switch, Checkbox, ToggleGroup, Slot), Motion (loaded through `LazyMotion`), cmdk for the command palette, sonner for toasts (react-hot-toast is gone), lucide-react 1.x for UI icons and simple-icons (CC0-1.0) for the brand marks lucide 1.x dropped.
- **Tauri on the JavaScript side** is only `@tauri-apps/api` (for `invoke`) and `@tauri-apps/plugin-opener`. There are no dialog, fs or shell plugin packages: file access goes through the app's own Rust commands (see [PACKAGING.md](PACKAGING.md)). `@tauri-apps/cli` is pinned exactly, and `npm run check:tauri` keeps the npm packages on the same major.minor as the crates.
- **Build-time only**: `marked` renders the legal documents and `@resvg/resvg-js` rasterises the brand assets; neither ships in the app. `wrangler` is pinned exactly for `cf:dev` / `cf:check`.
- **Fonts** are self-hosted: `@fontsource-variable/inter` and `@fontsource-variable/jetbrains-mono` are imported in `src/main.tsx`, and each subset (latin, latin-ext, vietnamese, …) is fetched only when a page uses it.
- **Node 22** comes from `.node-version`, which CI, the release workflows and Cloudflare Workers Builds all read.
### tsconfig.json
```jsonc
```json
{
"compilerOptions": {
"target": "ES2020",
@@ -106,36 +143,70 @@
}
```
`tsconfig.json` covers only `src/` — what `vite build` compiles. `tsconfig.check.json` extends it for `npm run typecheck:all`: it adds `tests`, `scripts`, `worker` and `build-plugins`, plus the `vitest/globals` and `node` types those need.
### vite.config.ts
```typescript
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import path from "path";
import { legalDocsPlugin } from "./build-plugins/legal-docs.ts";
import { cloudflareWebAnalytics, securityTxt } from "./build-plugins/web-only.ts";
// Set by the Tauri CLI for `tauri dev` / `tauri build`.
const isTauri = !!process.env.TAURI_ENV_PLATFORM;
export default defineConfig({
plugins: [react()],
base: "/yt-desc-gen/", // GitHub Pages
plugins: [
react(),
// In-app Legal Center content for every build; the static /legal pages,
// security.txt and the analytics beacon only for the web deployment.
legalDocsPlugin({ emitStaticPages: !isTauri }),
...(isTauri ? [] : [securityTxt(), cloudflareWebAnalytics()]),
],
// Web: https://ytgenerator.stream (Cloudflare Workers static assets).
// Tauri: its own asset protocol. The GitHub Pages sub-path is gone.
base: "/",
resolve: {
alias: {
"@": path.resolve(__dirname, "./src"),
"@config": path.resolve(__dirname, "./src/config"),
"@engine": path.resolve(__dirname, "./src/engine"),
"@store": path.resolve(__dirname, "./src/store"),
"@hooks": path.resolve(__dirname, "./src/hooks"),
"@components": path.resolve(__dirname, "./src/components"),
"@pages": path.resolve(__dirname, "./src/pages"),
"@utils": path.resolve(__dirname, "./src/utils"),
"@i18n": path.resolve(__dirname, "./src/i18n"),
"@": path.resolve(import.meta.dirname, "./src"),
"@config": path.resolve(import.meta.dirname, "./src/config"),
"@engine": path.resolve(import.meta.dirname, "./src/engine"),
"@store": path.resolve(import.meta.dirname, "./src/store"),
"@hooks": path.resolve(import.meta.dirname, "./src/hooks"),
"@components": path.resolve(import.meta.dirname, "./src/components"),
"@pages": path.resolve(import.meta.dirname, "./src/pages"),
"@utils": path.resolve(import.meta.dirname, "./src/utils"),
"@i18n": path.resolve(import.meta.dirname, "./src/i18n"),
},
},
server: {
// `tauri dev` rebuilds under src-tauri/target while Vite runs; watching
// it crashed Vite on Windows (EBUSY on the locked .dll).
watch: { ignored: ["**/src-tauri/**", "**/.wrangler/**"] },
},
build: {
// Old Android System WebViews choke on Vite's modern default target.
target: isTauri ? "es2020" : undefined,
// The Tauri CSP allows only 'self' for images and fonts: no data: URIs.
assetsInlineLimit: 0,
// Full license texts of the bundled packages, linked from the
// third-party notices.
license: { fileName: "licenses/third-party.md" },
rollupOptions: {
output: {
manualChunks: {
react: ["react", "react-dom"],
router: ["react-router-dom"],
i18n: ["i18next", "react-i18next"],
// Rolldown (Vite 8) only accepts the function form of manualChunks.
manualChunks(id) {
if (/[\\/]node_modules[\\/]react(-dom)?[\\/]/.test(id)) return "react";
if (/[\\/]node_modules[\\/]react-router(-dom)?[\\/]/.test(id)) return "router";
if (
/[\\/]node_modules[\\/](i18next|react-i18next|i18next-resources-to-backend)[\\/]/.test(
id,
)
)
return "i18n";
return undefined;
},
},
},
@@ -143,78 +214,129 @@ export default defineConfig({
});
```
### tailwind.config.ts
What differs between the two builds:
```typescript
import type { Config } from "tailwindcss";
| | Web build | Tauri build (`TAURI_ENV_PLATFORM` set) |
| ------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- | -------------------------------------- |
| Legal documents | `virtual:legal-docs` (lazy chunk for the Legal Center) **and** static `dist/legal/<id>.html` (+ `<id>.vi.html`, `index.html`) | `virtual:legal-docs` only |
| `/.well-known/security.txt` | Generated on every build (RFC 9116, `Expires` 180 days ahead) | — |
| Cloudflare Web Analytics beacon | Injected before `</body>` of `index.html` (build only, never in `npm run dev`) | — |
| JS target | Vite default | `es2020` |
export default {
content: ["./index.html", "./src/**/*.{ts,tsx}"],
darkMode: "class",
theme: {
extend: {
colors: {
surface: {
0: "var(--surface-0)", // deepest background
1: "var(--surface-1)", // card background
2: "var(--surface-2)", // elevated surface
3: "var(--surface-3)", // hover/active state
},
border: {
DEFAULT: "var(--border)",
strong: "var(--border-strong)",
},
text: {
primary: "var(--text-primary)",
secondary: "var(--text-secondary)",
muted: "var(--text-muted)",
},
accent: {
DEFAULT: "var(--accent)",
hover: "var(--accent-hover)",
muted: "var(--accent-muted)",
},
success: "var(--success)",
warning: "var(--warning)",
danger: "var(--danger)",
},
fontFamily: {
sans: ["var(--font-sans)"],
mono: ["var(--font-mono)"],
},
},
},
plugins: [],
} satisfies Config;
`build-plugins/legal-docs.ts` renders the repository's legal files (`TERMS.md`, `PRIVACY.md`, `DISCLAIMER.md` + `docs/i18n/vi/DISCLAIMER.md`, `LICENSE`, `THIRD_PARTY_NOTICES.md`, `SECURITY.md`, `NOTICE`, `CODE_OF_CONDUCT.md`; list in `src/config/legal.ts`) with `marked` at build time. `build-plugins/web-only.ts` holds the analytics snippet and the `security.txt` generator.
### Styling: Tailwind CSS 4
There is no `tailwind.config.ts` (removed in v0.37.0). PostCSS loads `@tailwindcss/postcss` and `autoprefixer` (`postcss.config.js`), and Tailwind is configured in CSS, in `src/styles/globals.css`:
```css
@import "tailwindcss";
/* The app toggles a .dark / .light class on <html> instead of following the OS. */
@custom-variant dark (&:where(.dark, .dark *));
/* Tailwind names → runtime variables. The values live in the :root / .light blocks,
which is what the theme toggle rewrites. */
@theme {
--color-surface-0: var(--surface-0);
--color-surface-1: var(--surface-1);
--color-text-primary: var(--text-primary);
--color-accent: var(--accent);
--font-sans: var(--font-sans-stack);
--radius-card: 0.875rem;
/* Controls are compact with a mouse and 44px on touch screens. */
--spacing-control: var(--control-h);
/* … the full token list is in the file … */
}
```
Components use the tokens (`bg-surface-1`, `text-text-muted`, `rounded-card`, …), never raw colours. `public/theme-init.js` applies the saved theme (and sets `<html lang>` to the saved UI language) before the first paint; it is a separate file rather than an inline script so the Content-Security-Policy needs no exception.
### wrangler.jsonc
The only Cloudflare file in the repository; Workers Builds runs `npx wrangler deploy` on every push to `main`. Its settings, without the file's comments:
```json
{
"name": "youtube-generator",
"main": "worker/index.ts",
"compatibility_date": "2026-09-25",
"workers_dev": false,
"preview_urls": true,
"routes": [{ "pattern": "ytgenerator.stream", "custom_domain": true }],
"build": { "command": "npm run build" },
"assets": {
"directory": "./dist",
"binding": "ASSETS",
"not_found_handling": "404-page",
"run_worker_first": [
"/*",
"!/assets/*",
"!/icons/*",
"!/.well-known/*",
"!/favicon.svg",
"!/favicon.ico",
"!/apple-touch-icon.png",
"!/og-image.png",
"!/manifest.webmanifest",
"!/robots.txt",
"!/sitemap.xml",
"!/theme-init.js",
"!/licenses/*",
"!/404.html"
]
},
"vars": {
"TURNSTILE_SITE_KEY": "0x4AAAAAAFKFAMUx9rQ5H6bQ",
"GATE_TTL_SECONDS": "86400"
},
"observability": { "enabled": true }
}
```
Every request goes through the Worker first except content-hashed build output and the public files browsers and crawlers fetch without cookies. `not_found_handling` is `404-page`, not the SPA fallback, so no path can reach `index.html` without passing the gate. `TURNSTILE_SECRET` is a dashboard Secret, never committed. Request flow, cookies, headers and operations: [HOSTING.md](HOSTING.md).
The Worker (`worker/`): `index.ts` (entry; injects the clock, `fetch` and random ids), `router.ts` (routing), `env.ts` (bindings, constants, the gate lifetime clamped to 5 min – 30 days), `turnstile.ts` (siteverify call and verdict: success, hostname, action `enter`, token age ≤ 300 s), `cookie.ts` (the HMAC-signed `__Host-ytg_gate` cookie, key derived from the Turnstile secret, bound to a User-Agent hash), `headers.ts` (CSP per page type and the baseline security headers), `gate-page.ts` + `gate-i18n.ts` (the gate page in the app's eight languages). It uses only standard Web APIs, so it type-checks against the DOM lib and runs under Vitest in Node.
## 2. Core Engine Interfaces
`renderAll(input, t, options?)` in `src/engine/template-renderer.ts` is the entry point: it calls `buildTitle`, `buildDescription` and `generateTags` and returns a `GeneratorOutput`. `t` is an i18next translator fixed to the output language and the `templates` namespace.
```typescript
// src/engine/types.ts
// src/engine/types.ts — abridged; the file has every field with its history.
export type SupportedLanguage = "en" | "vi" | "ja" | "es" | "ko" | "zh" | "pt-BR" | "id";
export interface GeneratorInput {
videoType: VideoType;
videoType: VideoType; // 20 video types
language: SupportedLanguage;
genre: Genre;
/** 1–3 genres (MAX_GENRES); the first drives the genre hashtag and trending tags. */
genres: Genre[];
gameName: string;
gameNameLocalized?: Partial<Record<SupportedLanguage, string>>;
/** May be empty: the channel phrase is then dropped (channel-phrase.ts). */
channelName: string;
platform: string;
partNumber?: string;
bossName?: string;
dlcName?: string;
challengeName?: string;
resolution?: string;
fps?: string;
graphicsPreset?: string;
timestamps?: string;
playlistLink?: string;
contactEmail?: string;
// Video-type specific: partNumber, bossName, dlcName, challengeName, modName, modList,
// liveUrl, scheduledTime, gachaQuestType, chapterName, questName, characterName,
// anniversaryYear, gachaVersion.
// Video settings: resolution, fps, graphicsPreset (+ graphicsPresetCustom),
// skipGraphicsSettings, rayTracingModes, frameGenVendor, frameGenMultiplier,
// upscaleQuality, artStyle, videoStyleEra, versionInfo.
// Content: timestamps, playlistLink, contactEmail, adEmail, gameKeyEmail,
// musicAttribution, sponsorName, sponsorPlatform, pubDevName, thirdPartyAdText,
// playthroughStatus, difficulty, endings, languagePatch, gameVersion,
// contentWarnings, techNotes, playtest fields, community invite links,
// Vietnamese donate fields.
/** @deprecated v0.11 — folded into contentWarnings. */
spoilerWarning: boolean;
/** @deprecated v0.11 — folded into contentWarnings. */
matureWarning: boolean;
storeLinks: Partial<Record<string, string>>;
/** "paid" | "free" | "demo" per store link. */
storeLinkTypes?: Partial<Record<string, StoreLinkType>>;
social: Partial<Record<string, string>>;
/** Since v1.0.0 the GPU is stored as `gpu:<catalog id>` (src/config/gpu-catalog.ts). */
rig: Partial<Record<string, string>>;
}
@@ -222,12 +344,15 @@ export interface GeneratorOutput {
title: string;
description: string;
tags: string[];
/** The tags joined with ", " — what Copy puts on the clipboard. */
tagString: string;
charCounts: {
title: number; // YouTube limit: 100
description: number; // YouTube limit: 5000
tags: number; // YouTube limit: 500
title: number;
description: number;
/** youtubeTagsLength(tags) — YouTube's count, not tagString.length. */
tags: number;
};
/** One entry per field that is strictly over its limit. */
warnings: CharLimitWarning[];
}
@@ -235,241 +360,331 @@ export interface CharLimitWarning {
field: "title" | "description" | "tags";
current: number;
limit: number;
message: string;
message: string; // English; the UI builds its own text from the numbers
}
// YouTube official limits
// YouTube limits
export const YT_LIMITS = {
TITLE_MAX: 100,
DESCRIPTION_MAX: 5000,
TAGS_MAX: 500,
SINGLE_TAG_MAX: 30, // single tag character limit
SINGLE_TAG_MAX: 30,
HASHTAG_MAX: 3,
} as const;
export interface TitleFormatConfig {
badgePosition: TitleBadgePosition; // "prefix" | "middle" | "suffix"
separator: TitleSeparatorId; // "emDash" | "hyphen" | "colon" | "pipe"
badgeCase: TitleBadgeCase; // "upper" | "lower"
/** v1.0.0. Missing on settings saved before — read as "gameFirst". */
order?: TitleOrder; // "gameFirst" | "typeFirst"
}
```
`RenderOptions` = `SettingsRenderOptions` (the twelve settings-derived knobs, built by `buildRenderOptions` in `src/hooks/use-render-options.ts`) + `RenderOptionOverrides` (`tEn`, `bilingualContentBlocks`, `year`, decided per call site). The year for the copyright line and trending tags comes in as an option so tests are deterministic; the builders fall back to the current year when it is omitted.
### 2.1 Engine rules added or changed in v1.0.0
**Tag length, counted the way YouTube counts it** (`tag-generator.ts`):
- `youtubeTagsLength(tags)` = the sum of each tag's length, plus 2 for the quotes YouTube puts around any tag containing whitespace, plus one comma between tags. The old measure (length of the `", "`-joined string) ignored the quotes; 15 of 51 real tag sets were over 500 by YouTube's count while showing as under.
- `generateTags` collects, in priority order: the game name (bare, and a shortened form for composites), core tags for the output language, genre tags for every selected genre, video-type tags, platform tags, quality tags, the output language's multilingual tags (setting), trending tags for the first genre (setting), and the publisher/developer name. It then de-duplicates case-insensitively, drops tags over 30 characters, and `trimToCharLimit(tags, 500)` keeps tags in priority order while they fit — a tag that doesn't fit is skipped and the shorter ones after it are still tried.
- Platform tags use `PlatformConfig.tagName` ("Steam", "Epic Games", "itch.io"), not the id; the publisher's own site has no tag name and adds no platform tags.
**Empty channel name** (`channel-phrase.ts`, used by the description, pinned comment and playlist builders): templates render with `CHANNEL_SLOT` (`@@CHANNEL@@`) in place of an empty channel name. `withoutEmptyChannel(text, language)` then removes the words that go with the channel name in that language ("trên kênh", "による", "en", "no", "di", …) and the English "on" (for English, and for locales that still carry English sentences for newer video types), replaces any slot left over with a neutral fallback ("this channel", "kênh", …) and tidies the spacing before punctuation. "…of Hades on ." no longer happens in any of the eight languages.
**Rig block** (`rig-block.ts`): `buildRigLines(rig, t)` returns `Label: value` lines, shared by the description and the social captions. Labels come from `description.rigLabels.<field>` in the output language, the order is `RIG_FIELDS` (CPU, GPU, RAM, motherboard, storage, OS, monitor, capture, controller, video editor), and values go through `formatRigValue` (`gpu:nvidia-rtx-5080` → "NVIDIA GeForce RTX 5080"). Keys that are no longer rig fields are still printed, after the known ones.
**Chapters** (`timeline-parser.ts`):
- A timestamp line may be `0:00 label`, `[0:00] label`, `(0:00) label`, `H:MM:SS`, or frame-accurate `HH:MM:SS:FF` (frames are dropped), with an optional separator (`-`, `–`, `—`, `:`, `|`, `•`, `·`).
- Latin-script keywords must end at a non-letter ("Part 2" is a part, "Party" is not). A bare "Final" counts as an ending only when nothing but a number or punctuation follows it, so "Final Fantasy VII" stays a game name.
- `checkChapters(entries)` applies YouTube's rules (`CHAPTER_RULES = { minCount: 3, minSeconds: 10 }`): first timestamp at 0:00, at least three, ascending, each chapter at least 10 s. Issues: `firstNotZero`, `tooFew`, `outOfOrder`, `tooShort`. An empty list has no issues.
- `normalizeTimeline(raw)` ("Tidy up") rewrites a pasted list as `M:SS label` lines without brackets, frames or separators; lines that are not timestamps are kept.
**Title shapes** (`title-variants.ts`): `buildTitleVariants` returns three shapes, each produced by the real `buildTitle` with a different `{ order, badgePosition }` — `default` (gameFirst, middle), `typeFirst` (typeFirst, middle), `qualityFirst` (gameFirst, prefix). The user's separator and badge case still apply, and the shape's `format` is what "Apply" writes into the `titleFormat` setting, so the Output title then matches what was shown.
**Social captions** (`social-post-builder.ts`, platforms in `src/config/social-platforms.ts`):
| Platform | Limit | Hashtags kept | Count |
| --------------- | ----- | ------------- | ---------------------------- |
| TikTok | 4,000 | all | plain length |
| YouTube Shorts | 5,000 | 5 | plain length |
| Instagram Reels | 2,200 | all | plain length |
| Facebook Reels | 2,200 | all | plain length |
| X | 280 | 3 | weighted (`xWeightedLength`) |
| Threads | 500 | 1 | plain length |
| Bluesky | 300 | 3 | plain length |
`xWeightedLength` NFC-normalises the text and walks grapheme clusters: an emoji counts 2; otherwise each code point counts 1 inside X's weight-1 ranges (U+0000–U+10FF, U+2000–U+200D, U+2010–U+201F, U+2032–U+2037) and 2 outside them (CJK, Hangul, Vietnamese letters from Latin Extended Additional). When a caption is over its limit, optional blocks are dropped in the order warnings → copyright → thanks → rig; `isOver` reports any overflow that remains.
**Limits and forbidden characters** (`limits.ts`): see [§ 7](#7-youtube-character-limits-reference).
## 3. Zustand Store Pattern
Every persisted store follows the same shape. The editor store, abridged:
```typescript
// src/store/editor-store.ts
// src/store/editor-store.ts (abridged)
import { create } from "zustand";
import { persist, createJSONStorage } from "zustand/middleware";
import type { GeneratorInput } from "@engine/types";
import { DEFAULTS } from "@config/defaults";
interface EditorState extends GeneratorInput {
// Actions
set: <K extends keyof GeneratorInput>(key: K, value: GeneratorInput[K]) => void;
export interface EditorData {
/* every form field */
}
interface EditorActions {
set: <K extends keyof EditorData>(key: K, value: EditorData[K]) => void;
setNested: <G extends "storeLinks" | "social" | "rig">(
group: G,
key: string,
value: string,
) => void;
loadProfile: (profile: Partial<GeneratorInput>) => void;
loadPreset: (preset: Partial<GeneratorInput>) => void;
setStoreLinkType: (platformId: string, type: StoreLinkType) => void;
loadProfile: (profile: Partial<EditorData>) => void;
loadPreset: (preset: Partial<EditorData>) => void;
reset: () => void;
}
export const useEditorStore = create<EditorState>()(
/** Bump together with a new step in migrateEditorState. */
export const EDITOR_STORE_VERSION = 19;
export const useEditorStore = create<EditorData & EditorActions>()(
persist(
(set) => ({
...DEFAULTS.editor,
...initialState, // built from DEFAULTS.editor (src/config/defaults.ts)
set: (key, value) => set({ [key]: value }),
setNested: (group, key, value) =>
set((state) => ({
[group]: { ...state[group], [key]: value },
})),
loadProfile: (profile) => set((state) => ({ ...state, ...profile })),
loadPreset: (preset) => set((state) => ({ ...state, ...preset })),
reset: () => set(DEFAULTS.editor),
set((state) => ({ [group]: { ...state[group], [key]: value } })),
setStoreLinkType: (platformId, type) =>
set((state) => ({ storeLinkTypes: { ...state.storeLinkTypes, [platformId]: type } })),
// normalizeEditorPatch maps legacy values and clamps string lengths.
loadProfile: (profile) => set((state) => ({ ...state, ...normalizeEditorPatch(profile) })),
loadPreset: (preset) => set((state) => ({ ...state, ...normalizeEditorPatch(preset) })),
reset: () => set(initialState),
}),
{
name: "ytdescgen-editor-draft",
storage: createJSONStorage(() => localStorage),
partialize: (state) => {
// Exclude actions from persistence
const { set: _s, setNested: _sn, loadProfile: _lp, loadPreset: _lpre, reset: _r, ...data } = state;
return data;
},
version: EDITOR_STORE_VERSION,
migrate: (persistedState, version) => migrateEditorState(persistedState, version),
partialize: (state) => editorDataOf(state), // data only, never the actions
},
),
);
/** The persist migration — exported, and run again by backup import. */
export function migrateEditorState(persistedState: unknown, version: number): EditorData {
/* one `if (version < N)` block per schema change; every step is idempotent */
}
```
## 4. GitHub Actions CI
| Store | localStorage key | Version | Migration (exported) |
| ------------------ | ------------------------ | ----------------------------- | ---------------------------------------------------------------------------------------------- |
| `useEditorStore` | `ytdescgen-editor-draft` | `EDITOR_STORE_VERSION` = 19 | `migrateEditorState` |
| `useProfileStore` | `ytdescgen-profiles` | `PROFILE_STORE_VERSION` = 3 | `migrateProfilesState` |
| `usePresetStore` | `ytdescgen-presets` | `PRESET_STORE_VERSION` = 2 | `migratePresetsState` |
| `useTemplateStore` | `ytdescgen-templates` | `TEMPLATE_STORE_VERSION` = 2 | `migrateTemplatesState` |
| `useHistoryStore` | `ytdescgen-history` | `HISTORY_STORE_VERSION` = 3 | `migrateHistoryState` |
| `useSettingsStore` | `ytdescgen-settings` | `SETTINGS_STORE_VERSION` = 12 | `healSettings` (`settings-heal.ts`), as `migrate` **and** in `merge`, so it runs on every load |
v1.0.0 migration steps: editor v19, profiles v3 and templates v2 move the GPU to the catalog format (`migrateRig`: `brand|series|model` → `gpu:<id>`, or the full name as free text when the card is not in the catalog); history v3 folds the duplicates older versions piled up into one entry per video (`dedupeHistory`; a video is game name (case-insensitive) + video type + language + title), keeping the newest.
Rules:
- **localStorage is the only store**, on the web, desktop and Android. The desktop "mirror" file of earlier versions (`storage-adapter.ts`, `saveSettings`, `checkDataFileHealth`) was removed in v1.0.0; it was written next to the data folder and never read back. [PACKAGING.md](PACKAGING.md) covers how the leftover file is recovered.
- `partialize` persists data only. A shape change bumps the store's exported version and adds an idempotent step to its exported migration; backup import replays the same steps from the version a file records.
- Settings are healed on every load, not only on a version change, so a hand-edited value never reaches the app. Seven settings are device-local and never exported or overwritten by an import (`LOCAL_SETTINGS_KEYS` in `src/utils/backup/sanitize.ts`): `legalConsentVersion`, `legalConsentAt`, `editorAccordionState`, `settingsAccordionState`, `sidebarCollapsed`, `lastProfileId`, `lastPresetId`.
- **Not persisted by Zustand**: `useLogStore` (up to 2,000 entries in memory; `src/utils/log-storage.ts` mirrors each entry to the `ytdescgen-logs` localStorage key on the web, capped at 5,000, or to daily JSONL files in Tauri), `usePendingInvalidStore` (typed-but-invalid text) and `useRestoreDialog` (the file waiting in the restore dialog).
## 4. Backup File Format (v1.0.0)
Code: `src/utils/backup/`. Every export since v1.0.0 is a `_format: 2` envelope:
```json
{
"_app": "ytdescgen",
"_format": 2,
"_type": "backup",
"_schemaVersion": 1,
"_appVersion": "1.0.0",
"_exportedAt": "2026-09-30T14:00:00.000Z",
"data": {
"profiles": { "version": 3, "items": [] },
"settings": { "version": 12, "value": {} }
}
}
```
- `_type`: `backup` | `profiles` | `presets` | `templates` | `settings` | `history` | `logs` | `social`.
- **`backup`**: `_schemaVersion` is the container version (`BACKUP_CONTAINER_VERSION` = 1). `data` holds any of the sections `profiles`, `presets`, `templates`, `history`, `settings`, `draft`, each as `{ version, items }` (lists) or `{ version, value }` (settings, draft), where `version` is the store version the data is in (`SECTION_VERSIONS`). Settings are written without the device-local keys.
- **Single-section export** (`_type: "profiles"`, … — the library tabs and History): `_schemaVersion` is that store's version and `data` is the items (or the value).
- `logs` and `social` files are exports only; they are recognised and refused by restore.
- File names: `ytdescgen-<kind>-YYYY-MM-DD.<ext>` (`datedFileName`, local date). History also exports CSV (`historyToCsv`): UTF-8 with a byte-order mark, CRLF, RFC 4180 quoting, and a `'` prefix on cells a spreadsheet would read as a formula.
### Reading a file (`detect.ts`)
| File | Written by | Read as |
| ----------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- |
| `_format: 2` backup or section export | v1.0.0+ | As recorded. `_format` > 2, or a backup `_schemaVersion` > 1, is refused as "made by a newer version" |
| `{ "_app": "ytdescgen", "_type": "profile" \| "preset" \| "template" \| "settings" \| "history" \| "social", … }` | v0.15 – v0.38 | One section. A `history` file whose rows are log entries is a logs export |
| Bare array | before v0.15 | Section guessed from the first row |
| `{ "ytdescgen-settings": …, "ytdescgen-profiles": …, … }` | The desktop app's old data file; the pre-v0.18 Settings export, which dumped it | Each store key, as `{ state, version }` or bare data |
| Bare settings object (`appLanguage` / `theme`) | Hand-made, pre-v0.18 | Settings, version 0 |
An unknown version is read as 0: every migration step is idempotent, so running all of them on data that didn't need them changes nothing. A section saved by a newer store version than this build's is marked `tooNew` — shown in the preview but not restorable.
### Cleaning (`sanitize.ts`)
1. **Store migration first** — the store's own exported function, from the recorded version. List sections migrate in one pass (so the history de-duplication works across rows); if that throws, row by row, and a row that still throws is dropped instead of failing the file.
2. **Whitelist** — only known fields with the right types; choice fields limited to known ids (video types, languages, genres, graphics options, content warnings, tech notes, …); strings cut to the editor's limits (`PATCH_FIELD_LIMITS`, `FIELD_LIMITS`); map keys `^[A-Za-z0-9][A-Za-z0-9_.:-]{0,63}$` (at most 100 entries); an id that is not `^[A-Za-z0-9_-]{1,64}$`, or repeats one already taken, is replaced by a new one; at most 5,000 items per section. Nothing is copied by key except the whitelist, so a key like `__proto__`, or `set` (which once overwrote an editor action), cannot reach a store.
3. **Settings** go through `healSettings` and keep this device's local keys. Dropped rows are counted per section and reported.
### Restoring (`restore.ts`)
- `planRestore(file, readCurrentData())` marks every incoming row `new`, `same` or `changed`. A row is matched to an existing item by id, then by content (ignoring `id`, `createdAt`, `updatedAt`), then — for history — by video (`historyKey`). `incomingNewer` compares `updatedAt ?? createdAt`. Settings and the draft are `same` or `changed`.
- The choice (`RestoreChoice`): sections and rows (by default every row that would change something; in Replace mode every row), mode `merge` or `replace`, and for Merge a conflict rule: `newer` (replace the item here only when the incoming copy is newer) or `both` (add the incoming copy with a new id; profiles and templates get a free name such as "Main (2)"; history has no "both" — one entry per video).
- **Replace** makes the section exactly the selected rows; a matched row keeps the id it has here, so nothing pointing at it breaks.
- In either mode, restored history is sorted newest first, de-duplicated per video and cut to the history limit (the incoming limit when settings are restored too).
- `applyRestore` writes every store synchronously, in one step, and returns `undo`, which puts back only the sections that restore changed — edits made afterwards in other sections survive. The desktop app also writes a `…-before-restore` automatic backup first.
### Automatic backups (desktop)
`auto-backup.ts` writes `ytdescgen-backup-YYYYMMDD-HHmm.json` through the `backup_write` command into `<app data>/backups/`: 5 s after start, then 30 s after the last change to profiles, presets, templates, history or settings, at most once every 10 minutes. It skips a write when the data is identical to the last backup (FNV-1a hash of `data`, seeded from the newest backup on start) or when the library (profiles, presets, templates, history) is empty, so a run of empty backups can never push the good ones out. The draft is included but does not trigger a backup. **Back up now** in Settings and the backup before a restore (`…-before-restore.json`) use the same folder and name pattern. The Rust side writes atomically (temporary file + rename) and keeps the newest ten `ytdescgen-backup-*` files; any other name, such as a recovered `ytdescgen-legacy-data.json`, is never deleted automatically.
## 5. GitHub Actions
| Workflow | Runs on | Jobs |
| ------------------------------------------------------ | ------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `ci.yml` (CI) | PRs to and pushes on `main` | `check` — the required status on `main` |
| `security.yml` (Security) | PRs, pushes on `main`, weekly, manual | `dependency-review` (PRs: fails on a newly added high/critical advisory), `workflow-lint` (actionlint + zizmor, `.github/zizmor.yml`), `scorecard` (OpenSSF Scorecard, informational; not on PRs) |
| `compliance.yml` (Compliance) | PRs, pushes on `main` | `reuse` (REUSE licensing via `REUSE.toml`), `pr-title` (Conventional-Commit PR titles with a lower-case subject) |
| `rust.yml` (Rust) | Changes under `src-tauri/`, weekly, manual | `lint-and-test` (`cargo fmt --all -- --check`, `cargo clippy --all-targets --locked -- -D warnings`, `cargo test --locked`, after `npm run build` because `generate_context!` embeds `dist/`), `cargo-deny` (`check advisories licenses sources`, `src-tauri/deny.toml`) |
| `release-desktop.yml`, `release-android.yml` | `v*` tags, manual with a `tag` input | `verify`, then the builds — see [PACKAGING.md](PACKAGING.md) |
| `announce-release.yml` | Release published, manual | Links the release to an Announcements discussion and posts to Discord |
| `notify-ci-failure.yml`, `notify-release-pipeline.yml` | `workflow_run` | Discord notifications through the maintainer's shared workflows |
| `pages-migration.yml` | Manual only | Publishes `migration-page/` to the old GitHub Pages address until 2026-11-29 |
The `check` job, in order:
```yaml
# .github/workflows/ci.yml
name: CI
on:
push:
branches: [main, dev]
pull_request:
branches: [main]
jobs:
check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- uses: actions/setup-node@v6
with:
node-version: 22
cache: npm
- run: npm ci
# correctness
- run: npm run typecheck # src/
- run: npm run typecheck:all # + tests/ and scripts/
- run: npm run lint
- run: npm run validate:locales
- run: npm run test:run
# consistency
- run: npm run format:check
- run: npm run knip
- run: npm run check:version
# security (advisory — a fresh transitive advisory must not redden
# every unrelated PR before Dependabot opens its fix)
- run: npm audit --audit-level=high
continue-on-error: true
- run: npm run build
- run: npm ci
# correctness
- run: npm run typecheck # src/
- run: npm run typecheck:all # + tests/, scripts/, worker/, build-plugins/
- run: npm run lint
- run: npm run validate:locales
- run: npm run test:coverage # thresholds in vitest.config.ts
# consistency
- run: npm run format:check
- run: npm run knip
- run: npm run check:version # the six version fields agree
- run: npm run check:tauri # @tauri-apps/* npm packages and tauri crates on the same major.minor
# licensing
- run: npm run check:licenses # allow-list + THIRD_PARTY_NOTICES.md matches what is installed
# security (advisory: a fresh transitive advisory must not redden unrelated PRs)
- run: npm audit --audit-level=high
continue-on-error: true
# build
- run: npm run build
- run: npm run check:bundle # initial load ≤ 280 KB gzip, no JS chunk > 500 KB raw
- run: npx wrangler deploy --dry-run --outdir .wrangler/dry-run
```
The workflow also declares `permissions: contents: read` (least privilege, and
it clears CodeQL's `actions/missing-workflow-permissions` alert) and a
`concurrency` group that cancels superseded runs everywhere except `main`, where
each commit's result is a historical record the release process reads back.
- **Bundle budget** (`scripts/check-bundle-size.ts`): the initial load is every script, modulepreload and stylesheet `dist/index.html` references, summed gzip — lazy chunks (pages, locales, legal documents) are excluded. The result is printed as a table and added to the job summary.
- **Licences** (`scripts/lib/third-party.ts`): every package bundled into the app must carry an allowed licence (MIT, ISC, Apache-2.0, BSD-2/3-Clause, 0BSD, CC0-1.0, Unlicense, BlueOak-1.0.0, OFL-1.1, Zlib, MPL-2.0), and `THIRD_PARTY_NOTICES.md` is generated (`npm run generate:third-party`) and checked, not hand-written.
- **Wrangler dry run** validates `wrangler.jsonc` and bundles the Worker exactly as Workers Builds will, without deploying.
- Every workflow declares least-privilege `permissions`, checks out with `persist-credentials: false`, and pins actions by commit SHA (Dependabot keeps the SHAs and version comments current). The exceptions are the actionlint Docker image (pinned by version tag) and the maintainer's own `poli0981/.github` reusable workflows (tracked at `main`, allowed in `.github/zizmor.yml`). CI, Security, Compliance and Rust cancel superseded runs through a `concurrency` group, except on `main`, where each commit's result is a record the release process reads back.
**Why these gates exist.** Every one of them was already installed and
configured before v0.35.0, and none of them ran. `knip` was in `package.json`
with a `knip.json` beside it. Prettier had a config and a `format` script.
Turning them on found real problems immediately — most notably that
`tsconfig.json` covers only `src/`, so `tests/` and `scripts/` had **never** been
type-checked, which was hiding three fields silently missing from the
editor→engine parity fixture whose entire job is catching that class of drift.
**Web deployment is not a GitHub workflow.** Cloudflare Workers Builds builds and deploys the Worker and `dist/` on every push to `main` (preview versions for other branches). The old `deploy-web.yml` (GitHub Pages) is gone; `pages-migration.yml` only serves the moving notice, which hands visitors the data their browser saved on the old address as a `_format: 2` backup file. See [HOSTING.md](HOSTING.md).
```yaml
# .github/workflows/deploy-web.yml
name: Deploy to GitHub Pages
**Why these gates exist (v0.35.0).** Several gates were installed and configured long before they ran: `knip` had a `knip.json`, Prettier had a config and a `format` script. Turning them on found real problems at once — most notably that `tsconfig.json` covers only `src/`, so `tests/` and `scripts/` had never been type-checked, which hid three fields missing from the editor → engine parity fixture.
on:
push:
branches: [main]
## 6. Testing Strategy
permissions:
contents: read
pages: write
id-token: write
Vitest runs `tests/**/*.test.{ts,tsx}` and `src/**/*.test.{ts,tsx}` in the **node** environment, with `globals: true`: 930 tests in 48 files at v1.0.0. Directories: `tests/engine`, `store`, `utils` (backup detect / sanitize / restore, quick entry, validation, the migration page), `worker` (router, cookie, Turnstile verdicts, headers, gate language), `build` (legal pages, web-only plugins), `config`, `hooks`, `i18n`, `scripts`. No test renders components: React Testing Library is installed but jsdom is not, so a rendering test would need both jsdom and a `// @vitest-environment jsdom` docblock.
jobs:
deploy:
runs-on: ubuntu-latest
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
steps:
- uses: actions/checkout@v6
- uses: actions/setup-node@v6
with:
node-version: 22
cache: npm
- run: npm ci
- run: npm run build
- uses: actions/configure-pages@v6
- uses: actions/upload-pages-artifact@v5
with:
path: dist
- id: deployment
uses: actions/deploy-pages@v5
```
## 5. Testing Strategy
Engine tests build a full `GeneratorInput` and pass a mock translator (`tests/helpers/mock-t.ts`) that reads the real `templates.json` files (en, vi, ja):
```typescript
// tests/engine/title-builder.test.ts
import { describe, it, expect } from "vitest";
import { buildTitle } from "@engine/title-builder";
import { createMockT } from "../helpers/mock-t";
import type { GeneratorInput } from "@engine/types";
function makeInput(overrides: Partial<GeneratorInput> = {}): GeneratorInput {
return {
videoType: "full",
language: "en",
genres: ["action"],
gameName: "Elden Ring",
channelName: "TestChannel",
platform: "steam",
spoilerWarning: false,
matureWarning: false,
storeLinks: {},
social: {},
rig: {},
...overrides,
};
}
describe("buildTitle", () => {
it("generates full gameplay title in English", () => {
const result = buildTitle({
gameName: "Elden Ring",
videoType: "full",
language: "en",
});
expect(result).toBe("Elden Ring — Gameplay No Commentary");
const t = createMockT("en");
expect(buildTitle(makeInput(), t)).toBe("Elden Ring — Gameplay No Commentary");
});
it("generates part title with number", () => {
const result = buildTitle({
gameName: "Elden Ring",
videoType: "part",
partNumber: "5",
language: "en",
});
const t = createMockT("en");
const result = buildTitle(makeInput({ videoType: "part", partNumber: "5" }), t);
expect(result).toBe("Elden Ring — Part 5 — Gameplay No Commentary");
});
it("generates boss title in Japanese", () => {
const result = buildTitle({
gameName: "エルデンリング",
videoType: "boss",
bossName: "マルギット",
language: "ja",
});
expect(result).toBe("エルデンリング — マルギット ボス戦 — Gameplay No Commentary");
});
it("warns when title exceeds 100 characters", () => {
// ... test char limit warning
});
});
```
## 6. YouTube Character Limits Reference
`npm run test:coverage` (what CI runs) measures `src/engine/**`, `worker/**` and `build-plugins/**` with V8 and fails below these thresholds — the engine is what the whole app trusts, the Worker is what guards the site:
| Field | Limit | Behavior When Exceeded |
|-------|-------|----------------------|
| Title | 100 chars | YouTube truncates with "..." |
| Description | 5,000 chars | YouTube silently truncates |
| Tags (total) | 500 chars | YouTube rejects all tags |
| Single Tag | 30 chars | YouTube rejects that tag |
| Hashtags in description | 60 max, 3 shown | First 3 shown above title |
| Playlist title | 150 chars | Truncated |
| Scope | Statements | Branches | Functions | Lines |
| ----------------------------------------- | ---------- | -------- | --------- | ----- |
| `src/engine/**` | 88 % | 85 % | 60 % | 88 % |
| `worker/**` (excluding `worker/index.ts`) | 95 % | 85 % | 95 % | 95 % |
### Enforcement (v0.35.0)
Guard tests worth knowing: `tests/hooks/render-options-parity.test.ts` (settings → engine options), `tests/hooks/generator-input-mapping.test.ts` (editor → engine input), `tests/i18n/locale-registration.test.ts` (language registration in both directions), the genre/tag-pool sync in `tests/engine/tag-generator.test.ts`, and `tests/worker/headers.test.ts` (keeps the Worker's baseline headers in step with `public/_headers`). The Rust side has its own `cargo test` suite (name validation, path rejection, pruning, legacy recovery, dialog filters).
`renderAll` has always returned `warnings: CharLimitWarning[]`; until v0.35.0
nothing in the UI read it. `src/engine/limits.ts` is now the single derivation,
consumed by `useOutputLimits` on Output and precomputed per row in Batch.
## 7. YouTube Character Limits Reference
The rule is **all-or-nothing per output**: one over-limit field disables every
copy button for that output. `checkTitleWarning` / `checkDescriptionWarning`
only fire when a field is *strictly over*, never at the 80 % counter threshold,
so a non-empty `warnings` array is an exact "YouTube will reject this" signal.
| Field | Limit | When exceeded |
| ---------------------------------- | ---------------------------------------------------------------------------------------- | ------------------------------- |
| Title | 100 chars | Studio won't save it |
| Description | 5,000 chars | Studio won't save it |
| Tags (total) | 500 chars, counted YouTube's way: quotes around multi-word tags + one comma between tags | Studio won't save the tag list |
| Single tag | 30 chars (`SINGLE_TAG_MAX`) | The generator drops longer tags |
| Hashtags in description | 60 max, 3 shown | First 3 shown above the title |
| Playlist title | 150 chars | Truncated |
| `<` or `>` in title or description | not allowed | Studio rejects the text |
Deliberately not gated by `YT_LIMITS`: thumbnail text and the pinned comment
(different surfaces), the Playlist tab (150-char title, not 100), and social
captions (per-platform caps in `SOCIAL_PLATFORMS`).
### Enforcement (v1.0.0)
## 7. Field Limits (v0.35.0)
`renderAll` returns `warnings: CharLimitWarning[]` with one entry per field that is **strictly over** its limit (never at the 80 % counter threshold), so a warning is an exact "YouTube will reject this" signal. `src/engine/limits.ts` is the single derivation, shared by the Output page, Batch, the command palette and the Ctrl/⌘+Shift+C shortcut (`useOutputCopy`):
`src/config/field-limits.ts` — caps on what can be *typed*, distinct from
YouTube's caps on what is *generated*.
- `getOutputLimitStatus(output)` / `mergeLimitStatus(statuses)` — one output, or several merged (multi-language Copy All, Copy All Batch), keeping the worst offender per field.
- **Per field** (changed in v1.0.0 from all-or-nothing per output): `isFieldOver(status, field)` blocks copying only the field that is over (`useCopyGate` puts the reason in the button's tooltip); the other fields stay copyable.
- **Copy All** copies title + description, plus the tags when the `copyAllIncludesTags` setting is on (`copyAllText`); `isCopyAllBlocked(status, withTags)` blocks it when the title or description is over, or the tags when they are included.
- With the opt-in Strict Mode setting on, `useStrictBlock` blocks every copy while the editor has an error (a saved value that fails validation, or typed text that is invalid and therefore not saved).
- `fieldsWithForbiddenChars(output)` reports a title or description containing `<` or `>`; the Output page shows a warning for each (it does not block copying).
Deliberately not gated by `YT_LIMITS`: thumbnail text and the pinned comment (different surfaces), the Playlist tab (150-character title), and social captions (per-platform limits in `SOCIAL_PLATFORMS`).
## 8. Field Limits (v0.35.0)
`src/config/field-limits.ts` — caps on what can be _typed_, distinct from YouTube's caps on what is _generated_.
```typescript
export const FIELD_LIMITS = {
URL: 200,
EMAIL_FIELD: 320, // 3 addresses; RFC 5321 caps a single one at 254
EMAIL_FIELD: 320, // 3 addresses; RFC 5321 caps a single one at 254
SHORT_NAME: 100,
LABEL: 300,
LONG_TEXT: 2000,
@@ -478,9 +693,6 @@ export const FIELD_LIMITS = {
} as const;
```
Values are UTF-16 code units, matching the DOM `maxLength` attribute — an emoji
costs 2. Grapheme counting would be more correct but cannot be enforced by the
browser, and these are ceilings against absurd input, not a character budget.
Values are UTF-16 code units, matching the DOM `maxLength` attribute — an emoji costs 2. Grapheme counting would be more correct but cannot be enforced by the browser, and these are ceilings against absurd input, not a character budget.
`maxLength` only constrains typing and pasting, so `clampField` is applied in
`normalizeEditorPatch` to cover profile / preset / template imports.
`maxLength` only constrains typing and pasting, so `clampField` is applied in `normalizeEditorPatch` (via `PATCH_FIELD_LIMITS`) whenever a profile, preset or template is applied, and backup restore cuts every string to the same limits in `sanitize.ts`.
+151 -75
View File
@@ -1,15 +1,21 @@
# Danh mục Nội dung
Bản kê khai tĩnh cho mọi loại video, thể loại game, và cảnh báo nội dung trong editor của YTDescGen. Cập nhật thủ công — khi thêm mục mới vào một trong các file nguồn dưới đây, **thêm dòng tương ứng vào đây** trong cùng PR.
Bản kê khai tĩnh cho mọi loại video, thể loại game, cảnh báo nội dung, cửa hàng, trường link và nền tảng đăng chéo trong editor của YTDescGen (tính đến v1.0.0). Cập nhật thủ công — khi thêm mục mới vào một trong các file nguồn dưới đây, **thêm dòng tương ứng vào đây** trong cùng PR.
File này tồn tại để **minh bạch** — bất kỳ ai tò mò về việc editor có thể mô tả được gì (mà không cần cài app hay đọc source) đều có thể quét trong một phút.
**Bản gốc tiếng Anh:** [`docs/CONTENT-INVENTORY.md`](../../CONTENT-INVENTORY.md).
**Nguồn tham chiếu (source of truth):**
- Loại video: [`src/config/video-types.ts`](../../../src/config/video-types.ts)
- Thể loại game: [`src/config/genres.ts`](../../../src/config/genres.ts)
- Cảnh báo nội dung: [`src/config/content-warning-groups.ts`](../../../src/config/content-warning-groups.ts)
- Cửa hàng: [`src/config/platforms.ts`](../../../src/config/platforms.ts)
- Link mạng xã hội & donate: [`src/config/social-fields.ts`](../../../src/config/social-fields.ts)
- Link cộng đồng: [`src/components/editor/CommunityEditor.tsx`](../../../src/components/editor/CommunityEditor.tsx)
- Ngân hàng Việt Nam: [`src/config/vietnamese-banks.ts`](../../../src/config/vietnamese-banks.ts)
- Nền tảng đăng chéo: [`src/config/social-platforms.ts`](../../../src/config/social-platforms.ts)
---
@@ -17,87 +23,87 @@ File này tồn tại để **minh bạch** — bất kỳ ai tò mò về việ
Mỗi loại video kéo theo một template description, cấu trúc title, và tag bias riêng. Cột "Trường bổ sung" liệt kê các trường editor sẽ hiển thị khi chọn loại video tương ứng.
| Icon | Loại | Trường bổ sung |
|---|---|---|
| 🎮 | Gameplay đầy đủ | — |
| 📂 | Gameplay theo phần | Số phần |
| 🎬 | Demo đầy đủ | — |
| 🎞 | Demo theo phần | Số phần |
| 👹 | Đấu trùm | Tên trùm |
| 💀 | Đấu trùm không trúng đòn | Tên trùm |
| 🏁 | Kết thúc / Toàn bộ Ending | — |
| ⚡ | Speedrun | — |
| 💯 | Hoàn thành 100% | — |
| 📦 | Nội dung DLC | Tên DLC |
| 🔄 | New Game+ | — |
| 🏆 | Thử thách | Tên thử thách |
| 📌 | Nhiệm vụ phụ | — |
| 🔍 | Bí mật / Ẩn | — |
| ⚖️ | So sánh đồ họa | — |
| 📘 | Hướng dẫn không lời | — |
| 🧩 | Chơi với Mod | Tên Mod |
| ⭐ | Toàn bộ vật phẩm sưu tầm | — |
| 🔴 | Livestream | URL Live, Thời gian dự kiến |
| 🎴 | Nhiệm vụ Gacha | Loại nhiệm vụ, Tên chapter, Tên quest, Số phần |
| Icon | Loại | Trường bổ sung |
| ---- | ------------------------- | ---------------------------------------------- |
| 🎮 | Gameplay đầy đủ | — |
| 📂 | Gameplay theo phần | Số phần |
| 🎬 | Demo đầy đủ | — |
| 🎞 | Demo theo phần | Số phần |
| 👹 | Đấu trùm | Tên trùm |
| 💀 | Đấu trùm không trúng đòn | Tên trùm |
| 🏁 | Kết thúc / Toàn bộ Ending | — |
| ⚡ | Speedrun | — |
| 💯 | Hoàn thành 100% | — |
| 📦 | Nội dung DLC | Tên DLC |
| 🔄 | New Game+ | — |
| 🏆 | Thử thách | Tên thử thách |
| 📌 | Nhiệm vụ phụ | — |
| 🔍 | Bí mật / Ẩn | — |
| ⚖️ | So sánh đồ họa | — |
| 📘 | Hướng dẫn không lời | — |
| 🧩 | Chơi với Mod | Tên Mod |
| ⭐ | Toàn bộ vật phẩm sưu tầm | — |
| 🔴 | Livestream | URL Live, Thời gian dự kiến |
| 🎴 | Nhiệm vụ Gacha | Loại nhiệm vụ, Tên chapter, Tên quest, Số phần |
---
## 2. Thể loại game (41)
## 2. Thể loại game (42)
Thể loại được chọn ảnh hưởng đến định dạng title, tag pool, và (khi cấu hình ở Settings → Genre Playlists) gợi ý playlist trong pinned comment.
Thể loại được chọn (tối đa 3 cho mỗi video) ảnh hưởng đến định dạng title, tag pool, và (khi cấu hình ở Settings → Genre Playlists) gợi ý playlist trong pinned comment.
Các nhóm bulk-select trong editor: **All RPGs** (rpg + jrpg + action_rpg + crpg), **All Shooters** (fps + arena_shooter + tactical_fps + boomer_shooter + extraction_shooter + shmup), **All Horror** (horror + survival_horror + psychological_horror).
Các nhóm bulk-select trong editor: **All RPGs** (rpg + jrpg + action_rpg + crpg), **All Shooters** (fps + arena_shooter + tactical_fps + boomer_shooter + extraction_shooter + shmup), **All Horror** (horror + survival_horror + psychological_horror). Bấm một nhóm sẽ thay lựa chọn hiện tại bằng ba thể loại đầu tiên của nhóm đó.
| Icon | Thể loại |
|---|---|
| ⚔️ | Hành động / Phiêu lưu |
| 🗡 | Hack & Slash |
| 👊 | Beat 'em Up |
| 🦘 | Platformer |
| 👻 | Kinh dị / Sinh tồn |
| 🧟 | Kinh dị Sinh tồn |
| 🧠 | Kinh dị Tâm lý |
| 🛡 | RPG |
| 🎎 | JRPG |
| 🏹 | Action RPG |
| 📜 | CRPG / Góc nhìn từ trên |
| 🔫 | FPS / Bắn súng |
| 🎯 | Bắn súng Arena |
| 🎖 | Bắn súng Chiến thuật |
| 💥 | Boomer Shooter |
| 🎒 | Extraction Shooter |
| 🛸 | SHMUP / Bullet Hell |
| 🌍 | Thế giới mở / Sandbox |
| 🕹 | Indie |
| 💀 | Souls-like |
| 🏎 | Đua xe / Thể thao |
| 📖 | Cốt truyện |
| 🏗 | Mô phỏng / Chiến thuật |
| 🏙 | Xây thành |
| 🥊 | Đối kháng |
| 🥷 | Lén lút / Gián điệp |
| ⛏ | Sinh tồn / Chế tạo |
| 🎲 | Roguelike / Roguelite |
| 🗺 | Metroidvania |
| 🌐 | MMO / Trực tuyến |
| 🎵 | Âm nhạc / Nhịp điệu |
| 🧩 | Giải đố |
| 🏰 | Tower Defense |
| 🃏 | Bài / Card |
| 🎴 | Deck Builder |
| 🤖 | Auto Battler |
| 🏆 | Battle Royale |
| ♟ | Chiến thuật theo lượt |
| 🚀 | Không gian / Sci-Fi |
| 🌾 | Nông trại / Life Sim |
| 🎬 | FMV / Phim tương tác |
| 💬 | Visual Novel |
| Icon | Thể loại |
| ---- | ----------------------- |
| ⚔️ | Hành động / Phiêu lưu |
| 🗡 | Hack & Slash |
| 👊 | Beat 'em Up |
| 🦘 | Platformer |
| 👻 | Kinh dị / Sinh tồn |
| 🧟 | Kinh dị Sinh tồn |
| 🧠 | Kinh dị Tâm lý |
| 🛡 | RPG |
| 🎎 | JRPG |
| 🏹 | Action RPG |
| 📜 | CRPG / Góc nhìn từ trên |
| 🔫 | FPS / Bắn súng |
| 🎯 | Bắn súng Arena |
| 🎖 | Bắn súng Chiến thuật |
| 💥 | Boomer Shooter |
| 🎒 | Extraction Shooter |
| 🛸 | SHMUP / Bullet Hell |
| 🌍 | Thế giới mở / Sandbox |
| 🕹 | Indie |
| 💀 | Souls-like |
| 🏎 | Đua xe / Thể thao |
| 📖 | Cốt truyện |
| 🏗 | Mô phỏng / Chiến thuật |
| 🏙 | Xây thành |
| 🥊 | Đối kháng |
| 🥷 | Lén lút / Gián điệp |
| ⛏ | Sinh tồn / Chế tạo |
| 🎲 | Roguelike / Roguelite |
| 🗺 | Metroidvania |
| 🌐 | MMO / Trực tuyến |
| 🎵 | Âm nhạc / Nhịp điệu |
| 🧩 | Giải đố |
| 🏰 | Tower Defense |
| 🃏 | Bài / Card |
| 🎴 | Deck Builder |
| 🤖 | Auto Battler |
| 🏆 | Battle Royale |
| ♟ | Chiến thuật theo lượt |
| 🚀 | Không gian / Sci-Fi |
| 🌾 | Nông trại / Life Sim |
| 🎬 | FMV / Phim tương tác |
| 💬 | Visual Novel |
---
## 3. Cảnh báo nội dung (248, chia nhóm)
Cảnh báo được chọn sẽ thêm vào khối `⚠ CONTENT WARNINGS` trong description, trước phần timestamp. Mỗi nhóm có thể thu gọn trong editor; cảnh báo hiển thị theo thứ tự người dùng chọn.
Cảnh báo được chọn sẽ hiển thị trong khối cảnh báo nội dung của description (`▸ ⚠️ CẢNH BÁO NỘI DUNG` khi output là tiếng Việt), ngay sau khối cấu hình máy (và danh sách mod, với loại Chơi với Mod). Mỗi nhóm có thể thu gọn trong editor; cảnh báo hiển thị theo thứ tự người dùng chọn.
### Spoiler (6)
@@ -149,13 +155,83 @@ Dùng mod · Bật cheat / debug · Dùng glitch · Có guide hỗ trợ · Game
---
## 4. Bảo trì
## 4. Cửa hàng (15 + trang nhà phát hành)
Mỗi cửa hàng có một ô link riêng. Dán link cửa hàng vào bất kỳ đâu trong editor, link sẽ tự vào đúng ô; link đầu tiên còn đặt luôn nền tảng của video, và tên tìm kiếm của nền tảng đó được dùng trong tag. Mỗi link được đánh dấu là trả phí, miễn phí hoặc demo.
| Cửa hàng | Link được chấp nhận | Tên dùng trong tag |
| ------------------------------------ | ----------------------------------------------------------------------- | ------------------ |
| Steam | `store.steampowered.com/app/…` (cả `/sub/`, `/bundle/` và `s.team/a/…`) | Steam |
| Epic Games Store | `store.epicgames.com/…` | Epic Games |
| PlayStation Store | `store.playstation.com/…` | PlayStation |
| Xbox / Microsoft Store | `xbox.com/…`, `apps.microsoft.com/…`, các trang Microsoft Store | Xbox |
| Nintendo eShop | `nintendo.com/…` và các trang Nintendo theo khu vực | Nintendo Switch |
| GOG | `gog.com/…` | GOG |
| itch.io | `<dev>.itch.io/<game>` | itch.io |
| Humble Bundle | `humblebundle.com/…` | Humble Bundle |
| Amazon Luna | `luna.amazon.com/…`, các cửa hàng Amazon | Amazon Luna |
| EA app | `ea.com/…` | EA app |
| Ubisoft Store | `store.ubisoft.com/…`, `ubisoft.com/…` | Ubisoft Connect |
| Battle.net | `shop.battle.net/…` và các host theo khu vực | Battle.net |
| Google Play | `play.google.com/store/apps/details?id=…` | Android |
| App Store | `apps.apple.com/…` | iOS |
| Meta Quest Store | `meta.com/…`, `oculus.com/…` | Meta Quest |
| Trang nhà phát hành / nhà phát triển | mọi link `https://` | — |
---
## 5. Link mạng xã hội, donate & cộng đồng
### Donate (5)
Ko-fi · Patreon · Buy Me a Coffee · PayPal · Streamlabs
### Mạng xã hội (17)
GitHub · YouTube · X (Twitter) · Discord · Twitch · Kick · TikTok · Instagram · Threads · Bluesky · Mastodon · Facebook · Facebook Page · Reddit · Bilibili · Telegram · Website
### Cộng đồng (5)
Cộng đồng Messenger · Nhóm Signal · Nhóm chat Instagram · Nhóm Facebook · Nhóm Zalo (chỉ khi output là tiếng Việt)
### Ngân hàng Việt Nam (37)
Dùng cho khối Donate (Việt Nam) — chuyển khoản ngân hàng, MoMo và ZaloPay — khối này chỉ hiển thị khi output là tiếng Việt. Mục "Khác (nhập tay)" cho phép gõ tên bất kỳ ngân hàng nào; profile còn lưu tên cũ của một ngân hàng đã đổi tên sẽ được gợi ý tên mới.
- **Ngân hàng thương mại nhà nước (4):** Vietcombank · BIDV · VietinBank · Agribank
- **Ngân hàng TMCP (24):** Techcombank · MB Bank · ACB · VPBank · TPBank · Sacombank · HDBank · VIB · SHB · Eximbank · OCB · MSB · LPBank · SeABank · ABBank · BAC A Bank · PVcomBank · NCB · Nam A Bank · KienlongBank · Saigonbank · VietABank · Vietbank · BVBank
- **Đổi tên năm 2025, và ngân hàng số (5):** MBV (trước là OceanBank) · VCBNeo (trước là CBBank) · Vikki Bank (trước là DongA Bank) · Cake by VPBank · Timo
- **Ngân hàng 100% vốn nước ngoài (4):** HSBC Vietnam · Standard Chartered · Shinhan Bank · UOB Vietnam
---
## 6. Nền tảng đăng chéo (7)
Tab Mạng xã hội dùng lại chính dữ liệu trong editor để tạo caption video ngắn. Khi caption vượt giới hạn của nền tảng, các khối tùy chọn sẽ bị bỏ bớt (cảnh báo nội dung bị bỏ trước); số hashtag được giới hạn theo từng nền tảng.
| Nền tảng | Giới hạn caption | Hashtag |
| --------------- | ------------------------------------------------------------------------------- | -------------- |
| TikTok | 4.000 | không giới hạn |
| YouTube Shorts | 5.000 | tối đa 5 |
| Instagram Reels | 2.200 | không giới hạn |
| Facebook Reels | 2.200 | không giới hạn |
| X | 280, đếm theo cách của X (chữ CJK, chữ tiếng Việt có dấu và emoji tính gấp đôi) | tối đa 3 |
| Threads | 500 | 1 |
| Bluesky | 300 | tối đa 3 |
---
## 7. Bảo trì
Khi thêm mục mới vào bất kỳ file nguồn nào:
1. **Loại video** → thêm vào [`src/config/video-types.ts`](../../../src/config/video-types.ts) VÀ thêm dòng vào mục 1 ở trên.
2. **Thể loại** → thêm vào [`src/config/genres.ts`](../../../src/config/genres.ts) VÀ thêm dòng vào mục 2.
1. **Loại video** → thêm vào [`src/config/video-types.ts`](../../../src/config/video-types.ts) (kèm title, câu mở đầu và lời chào pinned comment trong mọi file `templates.json`) VÀ thêm dòng vào mục 1 ở trên.
2. **Thể loại** → thêm vào [`src/config/genres.ts`](../../../src/config/genres.ts) (kèm tag pool và từ khóa tìm kiếm trong `src/engine/tag-generator.ts` — có test giữ hai bên khớp nhau) VÀ thêm dòng vào mục 2.
3. **Cảnh báo nội dung** → thêm vào nhóm phù hợp ở [`src/config/content-warning-groups.ts`](../../../src/config/content-warning-groups.ts) VÀ thêm label vào đúng nhóm ở mục 3 — giữ số đếm trong tiêu đề chính xác.
4. Cập nhật cả bản gốc EN tại [`docs/CONTENT-INVENTORY.md`](../../CONTENT-INVENTORY.md) trong cùng PR.
4. **Cửa hàng** → thêm vào [`src/config/platforms.ts`](../../../src/config/platforms.ts) (URL pattern và `tagName`; có thể thêm hàm đọc tên game trong `src/utils/url-extractors.ts`) VÀ thêm dòng vào mục 4.
5. **Link mạng xã hội / donate** → thêm vào [`src/config/social-fields.ts`](../../../src/config/social-fields.ts) (kèm label `social.<id>` trong mọi file `ui.json`) VÀ thêm vào mục 5.
6. **Ngân hàng Việt Nam** → thêm vào [`src/config/vietnamese-banks.ts`](../../../src/config/vietnamese-banks.ts) — ngân hàng đổi tên thì thêm tên mới và ánh xạ tên cũ trong `VIETNAMESE_BANK_RENAMES` — VÀ cập nhật mục 5.
7. **Nền tảng đăng chéo** → thêm vào [`src/config/social-platforms.ts`](../../../src/config/social-platforms.ts) (kèm label `socialPost.platforms.<id>` trong mọi file `ui.json`) VÀ thêm dòng vào mục 6.
8. Cập nhật cả bản gốc EN tại [`docs/CONTENT-INVENTORY.md`](../../CONTENT-INVENTORY.md) trong cùng PR.
Sai lệch giữa file này và file nguồn được xem là lỗi tài liệu — mở issue hoặc PR.
+135 -38
View File
@@ -2,20 +2,20 @@
> **Lưu ý dịch thuật:** Tiếng Anh là phiên bản chính ([`docs/DEVELOPMENT.md`](../../DEVELOPMENT.md)). Bản tiếng Việt này có thể chậm cập nhật một vài commit.
Hướng dẫn này bao gồm cách cài đặt YTDescGen để phát triển cục bộ trên Windows, macOS hoặc Linux. Ứng dụng là một web app Vite/React với tùy chọn vỏ desktop Tauri.
Hướng dẫn này bao gồm cách cài đặt YTDescGen để phát triển cục bộ trên Windows, macOS hoặc Linux. Ứng dụng là một web app Vite/React, kèm vỏ Tauri (tùy chọn) cho desktop và Android. Bản web chạy tại [ytgenerator.stream](https://ytgenerator.stream) thông qua một Cloudflare Worker — xem [HOSTING.md](../../HOSTING.md).
## Cấu hình máy tham chiếu
Cấu hình máy đã dùng để phát triển và phát hành dự án:
| Thành phần | Thông số |
| --- | --- |
| OS | Windows 11 Pro (24H2 trở lên) |
| CPU | x86-64 hiện đại — 6 nhân trở lên có AVX2 (Intel gen 11 / AMD Zen 3 hoặc mới hơn) |
| GPU | Rời hoặc tích hợp — backend WebView2 của Tauri chạy thoải mái trên iGPU |
| RAM | Tối thiểu 16 GB, khuyến nghị 32 GB để chạy song song typecheck + dev server |
| Lưu trữ | 5 GB trống cho `node_modules` + `target/` Cargo sau khi build Tauri đầy đủ |
| Màn hình | Tối thiểu 1920×1080; layout mobile đã test đến 360×640 |
| Thành phần | Thông số |
| ---------- | -------------------------------------------------------------------------------- |
| OS | Windows 11 Pro (24H2 trở lên) |
| CPU | x86-64 hiện đại — 6 nhân trở lên có AVX2 (Intel gen 11 / AMD Zen 3 hoặc mới hơn) |
| GPU | Rời hoặc tích hợp — backend WebView2 của Tauri chạy thoải mái trên iGPU |
| RAM | Tối thiểu 16 GB, khuyến nghị 32 GB để chạy song song typecheck + dev server |
| Lưu trữ | 5 GB trống cho `node_modules` + `target/` Cargo sau khi build Tauri đầy đủ |
| Màn hình | Tối thiểu 1920×1080; layout mobile đã test đến 360×640 |
macOS và Linux đều dùng được để phát triển. Build release Tauri được cross-compile hoặc chạy trên CI riêng — xem [PACKAGING.md](../../PACKAGING.md).
@@ -23,13 +23,13 @@ macOS và Linux đều dùng được để phát triển. Build release Tauri
Cài theo thứ tự:
| Công cụ | Phiên bản | Lý do |
| --- | --- | --- |
| **Node.js** | `>= 22.12.0` | Vite 8 yêu cầu Node `^20.19` hoặc `>= 22.12`. Dùng [nvm](https://github.com/nvm-sh/nvm) hoặc [fnm](https://github.com/Schniz/fnm). |
| **npm** | đi kèm Node 22 | Dự án dùng npm; `pnpm` và `yarn` chưa test. |
| **Rust** | stable, `>= 1.78` | Bắt buộc cho build Tauri. Cài qua [rustup](https://rustup.rs/). |
| **Python** | `3.12` | Tùy chọn — chỉ cần cho một số tooling Tauri trên Windows. |
| **Tauri prerequisites** | theo OS | Xem <https://v2.tauri.app/start/prerequisites/>. |
| Công cụ | Phiên bản | Lý do |
| ----------------------- | --------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Node.js** | **22** — đúng phiên bản trong `.node-version` | CI, các workflow release và Cloudflare Workers Builds đều đọc `.node-version`. Vite 8 cần Node `^20.19` hoặc `>= 22.12`, còn wrangler cần `>= 22`, nên hãy dùng 22.12 trở lên. Dùng [nvm](https://github.com/nvm-sh/nvm) hoặc [fnm](https://github.com/Schniz/fnm) (fnm đọc được `.node-version`). |
| **npm** | đi kèm Node 22 | Dự án dùng npm; `pnpm` và `yarn` chưa test. |
| **Rust** | stable, `>= 1.90` | Bắt buộc cho bản build Tauri desktop và Android (Tauri 2.12 cần Rust 1.90). Cài qua [rustup](https://rustup.rs/); profile mặc định đã có sẵn `rustfmt` và `clippy`. |
| **Python** | `3.12` | Tùy chọn — chỉ cần cho một số tooling Tauri trên Windows. |
| **Tauri prerequisites** | theo OS | Xem <https://v2.tauri.app/start/prerequisites/>. |
### Windows
@@ -54,7 +54,7 @@ Quy trình tham chiếu dùng **JetBrains 2026.x** (WebStorm hoặc RustRover) l
- Bật plugin **Tailwind CSS**.
- Bật plugin **i18next** (hoặc dùng `src/i18n/locales/_schema.json` để autocomplete).
- Settings → Languages → TypeScript → "Use TypeScript from `node_modules/typescript`".
- Settings → Code Style → Prettier → Run on save (`src/**/*.{ts,tsx,json,css}`).
- Settings → Code Style → Prettier → Run on save (`{src,tests,scripts,worker,build-plugins}/**/*.{ts,tsx,css}` — đúng các file mà `npm run format` xử lý).
### VS Code
@@ -81,23 +81,90 @@ npm run dev
# → http://localhost:5173
```
Dev server chỉ chạy riêng app: không có cổng Turnstile, không có analytics. Muốn chạy Worker phục vụ bản web, xem mục **Cloudflare Worker (chạy cục bộ)** bên dưới.
## Nhánh và Pull Request
- Tạo nhánh từ `main` (`feat/…`, `fix/…`, `docs/…`, `chore/…`) và mở pull request vào `main`. Không có nhánh dài hạn nào khác, và mỗi lần merge vào `main` đều deploy bản web.
- Tiêu đề PR theo định dạng commit `type(scope): message`; CI có kiểm tra.
- Mỗi PR đều chạy job `check` (xem bên dưới), `dependency-review`, `workflow-lint`, `reuse` và `pr-title`; hai job Rust `lint-and-test` và `cargo-deny` chạy khi có thay đổi trong `src-tauri/`.
Quy định đầy đủ: [CONTRIBUTING.md](../../../CONTRIBUTING.md).
## Lệnh thường dùng
| Lệnh | Tác dụng |
| --- | --- |
| `npm run dev` | Vite dev server, hot reload, chỉ web. |
| `npm run build` | Bundle web production vào `dist/`. |
| `npm run preview` | Phục vụ bundle production để kiểm tra. |
| `npm run typecheck` | `tsc --noEmit`. Chạy trước mỗi PR. |
| `npm run lint` | ESLint. Dùng `npm run lint:fix` để autofix. |
| `npm run format` | Chạy Prettier trên `src/`. |
| `npm run test` | Vitest chế độ watch. |
| `npm run test:run` | Vitest chạy một lần (cho CI / pre-commit). |
| `npm run test:coverage` | Báo cáo coverage vào `coverage/`. |
| `npm run validate:locales` | Bắt buộc cả 6 locale có cùng key với `_schema.json`. **Phải pass trước khi merge PR động đến locale.** |
| `npm run generate:locale` | Scaffold locale rỗng từ `_schema.json` cho ngôn ngữ mới. |
| `npm run tauri:dev` | Tauri desktop chế độ dev (tự restart khi đổi Rust hoặc frontend). |
| `npm run tauri:build` | Build binary Tauri release cho platform hiện tại. |
### Phát triển và build
| Lệnh | Tác dụng |
| --------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `npm run dev` | Vite dev server, hot reload, chỉ web. |
| `npm run build` | `tsc` + bundle web production vào `dist/`. Bản build web có thêm beacon Web Analytics, `/.well-known/security.txt` và các trang tĩnh `/legal/*`; bản build do Tauri CLI chạy thì không có những thứ này. |
| `npm run preview` | Phục vụ bundle production để kiểm tra (không qua Worker). |
| `npm run cf:dev` | `wrangler dev` — Worker đứng trước `dist/` tại `http://localhost:8787`. Xem mục **Cloudflare Worker (chạy cục bộ)**. |
| `npm run tauri:dev` | Tauri desktop chế độ dev (hoặc `npm run tauri dev`): chạy `npm run dev` rồi mở cửa sổ app trỏ vào đó. Sửa frontend thì hot reload; sửa Rust thì app được build lại. |
| `npm run tauri:build` | Build binary Tauri release cho platform hiện tại. |
### Kiểm tra
| Lệnh | Tác dụng |
| -------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `npm run typecheck` | `tsc --noEmit` trên `src/` — đúng phần Vite build. |
| `npm run typecheck:all` | Như trên, thêm `tests/`, `scripts/`, `worker/` và `build-plugins/` (`tsconfig.check.json`) — những thư mục config gốc cố ý bỏ qua. Có từ v0.35.0, khi phát hiện tests và scripts **chưa từng** được type-check — và lần chạy đầu đã tìm ra ba field bị thiếu âm thầm trong fixture parity editor→engine. |
| `npm run lint` | ESLint trên `src/`, `tests/`, `scripts/`, `worker/` và `build-plugins/`. Dùng `npm run lint:fix` để tự sửa. |
| `npm run format` | Chạy Prettier (ghi file) trên `src/`, `tests/`, `scripts/`, `worker/` và `build-plugins/` (`.ts`, `.tsx`, `.css`). |
| `npm run format:check` | Như trên nhưng chỉ kiểm tra. Là cổng CI. Markdown và JSON locale cố ý nằm ngoài phạm vi. |
| `npm run knip` | Tìm code chết / dependency không dùng. Là cổng CI. |
| `npm run validate:locales` | Bắt buộc cả 8 locale khớp chính xác với `_schema.json`. **Phải pass trước khi merge PR động đến locale.** |
| `npm run test` | Vitest chế độ watch. |
| `npm run test:run` | Vitest chạy một lần. |
| `npm run test:coverage` | Chạy một lần kèm báo cáo coverage vào `coverage/`; fail nếu thấp hơn ngưỡng đặt cho `src/engine/` và `worker/` trong `vitest.config.ts`. CI chạy lệnh này. |
| `npm run check:version` | Kiểm tra cả **sáu** trường version khớp nhau (`package.json`, hai chỗ trong `package-lock.json`, `tauri.conf.json`, `Cargo.toml`, `Cargo.lock`). Đây là thứ duy nhất phát hiện khi bỏ sót một chỗ. |
| `npm run check:tauri` | Các package npm `@tauri-apps/*` và các crate Tauri phải cùng major.minor. Tauri CLI sẽ từ chối build nếu lệch, mà CI thì không chạy build Tauri. |
| `npm run check:licenses` | Mọi package được bundle đều có license nằm trong danh sách cho phép, và `THIRD_PARTY_NOTICES.md` khớp với những gì đang cài. |
| `npm run check:bundle` | Chạy sau `npm run build`: lần tải đầu phải ≤ 280 KB gzip và không chunk JS nào vượt 500 KB (chưa nén). |
| `npm run cf:check` | `wrangler deploy --dry-run`: kiểm tra `wrangler.jsonc` và bundle Worker y như Workers Builds sẽ làm, nhưng không deploy. |
### Sinh file
| Lệnh | Tác dụng |
| ------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `npm run generate:locale` | Tạo khung locale mới từ bản tiếng Anh. `--lang <mã>`, thêm tùy chọn `--copy-english` / `--force`. (Được nhắc đến từ v0.1 nhưng đến v0.35.0 mới thật sự có script.) |
| `npm run generate:third-party` | Ghi lại `THIRD_PARTY_NOTICES.md` từ các package đang cài — cần chạy sau khi đổi dependency, nếu không `check:licenses` sẽ fail. |
| `npm run generate:brand` | Chuyển các SVG thương hiệu trong `assets/brand/` thành icon PNG và ảnh preview khi chia sẻ link của bản web, đặt trong `public/`. Các file PNG được commit. Icon desktop và Android dùng chung logo đó: `npx tauri icon assets/brand/logo.svg`. |
## Trước khi mở PR
Chạy đúng những gì job `check` của CI chạy:
```bash
npm run typecheck && npm run typecheck:all
npm run lint && npm run format:check
npm run validate:locales
npm run test:coverage
npm run knip
npm run check:version && npm run check:tauri && npm run check:licenses
npm run build && npm run check:bundle
npm run cf:check
```
Có động đến `src-tauri/`? Chạy thêm phần **Kiểm tra Rust** bên dưới.
## Cloudflare Worker (chạy cục bộ)
Bản web được phục vụ bởi một Cloudflare Worker ([`worker/`](../../../worker), cấu hình trong [`wrangler.jsonc`](../../../wrangler.jsonc)), đứng trước `dist/` để lo cổng Turnstile, các security header và các trang `/legal` công khai. Để chạy cục bộ:
```bash
cp .dev.vars.example .dev.vars # chỉ chứa key TEST công khai của Cloudflare Turnstile
npm run build # Worker phục vụ dist/
npm run cf:dev # wrangler dev → http://localhost:8787
```
- `.dev.vars` (đã nằm trong `.gitignore`) chứa các key Turnstile **test** mà Cloudflare công bố: widget luôn pass, và secret chỉ chấp nhận token giả do chính widget đó tạo ra. Tuyệt đối không ghi secret thật vào file — trên production, `TURNSTILE_SECRET` được lưu dưới dạng Secret của Cloudflare.
- Không có `.dev.vars` thì Worker không có `TURNSTILE_SECRET` và sẽ fail open: app vẫn tải lên nhưng không qua cổng.
- Worker phục vụ bản build gần nhất — chạy lại `npm run build` để thấy thay đổi ở frontend.
- Test của Worker chạy chung với cả bộ test (`tests/worker/`).
Deploy, cookie, header, secret và rollback: [HOSTING.md](../../HOSTING.md).
## Build Tauri desktop
@@ -105,16 +172,37 @@ Xem [PACKAGING.md](../../PACKAGING.md) cho pipeline release đầy đủ. Build
```bash
npm run tauri:build
# Output: src-tauri/target/release/bundle/{msi,deb,dmg,app}
# Output: src-tauri/target/release/bundle/
# Windows: bộ cài MSI + NSIS · Linux: deb, rpm, AppImage · macOS: .app + DMG
```
Build đầu tiên mất khoảng 5–10 phút (Cargo cache rỗng). Build sau đó là incremental.
Vite dev server không theo dõi `src-tauri/**` và `.wrangler/**` (`server.watch.ignored` trong `vite.config.ts`): khi `tauri dev` đang chạy, Cargo liên tục ghi lại các file trong `src-tauri/target`, và việc theo dõi chúng từng làm Vite crash trên Windows với lỗi `EBUSY` do file `.dll` bị khóa.
### Kiểm tra Rust
Giống các bước của job `lint-and-test` trong `.github/workflows/rust.yml` (chạy khi `src-tauri/` thay đổi, và hằng tuần):
```bash
npm run build # tauri::generate_context!() nhúng dist/, nên clippy và test cần có bản build
cd src-tauri
cargo fmt --all -- --check
cargo clippy --all-targets --locked -- -D warnings
cargo test --locked
```
Job `cargo-deny` kiểm tra advisory RustSec, license và nguồn crate theo `src-tauri/deny.toml`. Chạy cục bộ (sau khi `cargo install cargo-deny`): `cargo deny check advisories licenses sources` trong `src-tauri/`.
## Khắc phục sự cố
### `validate:locales` fail sau khi thêm key
Bạn quên cập nhật `src/i18n/locales/_schema.json`. Schema là source of truth; locale phải khớp 100%.
Bạn quên cập nhật `src/i18n/locales/_schema.json`, hoặc còn thiếu ở một trong 8 locale. Schema là nguồn chuẩn; mọi locale phải khớp 100%.
### `validate:locales` fail mà mình không động đến locale
Có người — hoặc một lần merge từ `main` — đã thêm key vào `_schema.json` (ví dụ nhãn cho một id mới trong `CONTENT_WARNINGS` ở `src/engine/types.ts`) mà chưa có ở mọi locale. Key mới cần có giá trị ở cả 8 locale.
### Build Tauri báo `link.exe not found` (Windows)
@@ -124,6 +212,18 @@ Cài Visual Studio Build Tools 2022 + workload Desktop C++, sau đó khởi đ
Cài Tauri prerequisites theo distro tại <https://v2.tauri.app/start/prerequisites/>.
### `check:tauri` fail sau khi cập nhật dependency
Một package npm `@tauri-apps/*` đã lên minor mới mà crate chưa lên (hoặc ngược lại). Chạy `cargo update -p tauri` (và các crate plugin mà `check:tauri` liệt kê) trong `src-tauri/`, trên cùng nhánh.
### `check:bundle` không tìm thấy `dist/index.html`
Lệnh này đo bản build — hãy chạy `npm run build` trước.
### `npm run cf:dev` không hiện cổng Turnstile
Thiếu `.dev.vars`, nên Worker không có secret và phục vụ app mà không qua cổng. Copy `.dev.vars.example` thành `.dev.vars` rồi chạy lại.
### `npm install` chậm / treo
Tắt VPN/proxy doanh nghiệp chặn npm registry. Lock file đã commit; install offline chạy được sau lần install thành công đầu tiên.
@@ -136,13 +236,10 @@ Từ v0.26, chỉ tiếng Anh nằm trong main chunk; các ngôn ngữ khác là
chunk lazy-load, tải khi dùng lần đầu (xem `src/i18n/index.ts` và
docs/I18N.md). Lời khuyên restart ở trên vẫn áp dụng cho tất cả.
### Pre-commit hook fail ở `validate:locales` mà mình không động đến locale
Có thể bạn vô tình thêm key mới vào `_schema.json` thông qua `src/engine/types.ts` → `CONTENT_WARNINGS`. ID mới cần dịch ở cả 6 locale.
## Xem thêm
- [ARCHITECTURE.md](../../ARCHITECTURE.md) — mô hình layer, data flow, thiết kế engine.
- [HOSTING.md](../../HOSTING.md) — cách ytgenerator.stream được build, deploy và bảo vệ.
- [I18N.md](../../I18N.md) — thêm ngôn ngữ mới từng bước.
- [PACKAGING.md](../../PACKAGING.md) — Tauri release build và signing.
- [CONTRIBUTING.md ở root](../../../CONTRIBUTING.md) — quy trình PR, quy ước commit, auto-ignore rules.
+11 -9
View File
@@ -20,16 +20,18 @@ Xem thêm: [`THIRD_PARTY_NOTICES.md`](../../../THIRD_PARTY_NOTICES.md) § "AI-As
## Chất lượng bản dịch
UI ứng dụng hỗ trợ sáu ngôn ngữ. Chất lượng tác giả khác nhau:
Ứng dụng có tám ngôn ngữ. Chất lượng tác giả khác nhau:
| Locale | Tác giả | Ghi chú |
| ------------------------ | ---------------------------- | ------------------------------------------------------------------------------------- |
| Tiếng Anh (`en`) | Người duy trì + AI | Locale làm việc chính. Chuỗi được review trước khi commit. |
| Tiếng Việt (`vi`) | Người duy trì (bản ngữ) + AI | Review bởi người duy trì là người bản ngữ tiếng Việt. |
| Tiếng Nhật (`ja`) | AI dịch | Không có review bản ngữ. Ngữ pháp và văn phong có thể chưa chuẩn. |
| Tiếng Tây Ban Nha (`es`) | AI dịch | Không có review bản ngữ. Không nhắm cụ thể vào giọng vùng miền (LatAm vs. Castilian). |
| Tiếng Hàn (`ko`) | AI dịch | Không có review bản ngữ. Honorific register chọn ở mức trung tính. |
| Tiếng Trung (`zh`) | AI dịch | Giản thể. Không có review bản ngữ. |
| Locale | Tác giả | Ghi chú |
| ---------------------------------- | ---------------------------- | ---------------------------------------------------------------------------------------------------------- |
| Tiếng Anh (`en`) | Người duy trì + AI | Locale làm việc chính. Chuỗi được review trước khi commit. |
| Tiếng Việt (`vi`) | Người duy trì (bản ngữ) + AI | Review bởi người duy trì là người bản ngữ tiếng Việt. |
| Tiếng Nhật (`ja`) | AI dịch | Không có review bản ngữ. Ngữ pháp và văn phong có thể chưa chuẩn. |
| Tiếng Tây Ban Nha (`es`) | AI dịch | Không có review bản ngữ. Không nhắm cụ thể vào giọng vùng miền (LatAm vs. Castilian). |
| Tiếng Hàn (`ko`) | AI dịch | Không có review bản ngữ. Honorific register chọn ở mức trung tính. |
| Tiếng Trung (`zh`) | AI dịch | Giản thể. Không có review bản ngữ. |
| Tiếng Bồ Đào Nha, Brazil (`pt-BR`) | AI dịch | Không có review bản ngữ. Nhắm riêng tiếng Bồ Đào Nha Brazil, không nhắm bản châu Âu. |
| Tiếng Indonesia (`id`) | AI dịch | Không có review bản ngữ. Tiếng Indonesia chuẩn; thuật ngữ game giữ tiếng Anh khi đó là cách dùng phổ biến. |
Nếu bạn là người bản ngữ và phát hiện dịch sai, vui lòng mở issue hoặc PR — xem [CONTRIBUTING.md](../../../CONTRIBUTING.md) § "i18n Contributions".
+8 -5
View File
@@ -121,11 +121,14 @@ function main(): void {
console.log(`\n${total} strings to translate. Remaining steps to register "${lang}":
1. src/i18n/index.ts — add to SUPPORTED_LANGUAGES (flag + nativeName)
2. src/engine/types.ts — add to the SupportedLanguage union
3. src/store/settings-heal.ts — add to detectBrowserLanguage's supported list
4. src/engine/tag-generator.ts— add a MULTILINGUAL_TAGS entry (TS enforces this)
5. npm run validate:locales — must pass before committing
1. src/i18n/index.ts — add to SUPPORTED_LANGUAGES (flag + nativeName)
2. src/engine/types.ts — add to the SupportedLanguage union
3. src/store/settings-heal.ts — add to detectBrowserLanguage's supported list (fails silently)
4. src/engine/tag-generator.ts — add CORE_TAGS_BY_LANG and MULTILINGUAL_TAGS entries (TS enforces)
5. src/engine/channel-phrase.ts— add DROP patterns and a FALLBACK noun (TS enforces)
6. worker/gate-i18n.ts — add GateLang, GATE_STRINGS and PREFIX_TO_LANG (fails silently:
the check page would show in English)
7. npm run validate:locales — must pass before committing
See docs/I18N.md for the full checklist.`);
}
+4 -3
View File
@@ -78,9 +78,10 @@ i18n.on("languageChanged", (lng) => {
* Lazy-loaded locales (v0.26): fetch the persisted UI + output languages
* before first paint so a non-English user never sees an English flash
* (and the Output page never renders a placeholder on cold start).
* zustand persist hydrates synchronously from localStorage, so these
* reads already hold the user's values; Tauri's async settings-file
* rehydrate is bridged later by App's store subscription.
* zustand persist hydrates synchronously from localStorage — the only
* store on every platform — so these reads already hold the user's values;
* a later change (a restored backup, the language picker) reaches i18n
* through App's store subscription.
*
* `en` resolves from the eagerly-bundled resources, so English users pay
* zero extra latency. The 2 s race cap means a dead network can delay —