4단계 방·대기실: 방 만들기(게스트 포함)·6자리 코드·열린 방 목록(🔒 비밀번호 방), 인원 무제한 대기실(방장·준비·넘기기·내보내기·60초 자리 유지), 방 설정 전체 즉시 반영, 조건에 맞는 곡 N곡 + 원곡 확인 중 곡 수(1분마다 다시 셈), 대기실 채팅, 서버 재시작 안내

- 서버 테스트 49개, 브라우저 e2e(e2e/rooms.e2e.ts, 3명) 11단계
- 사용자 결정(추천안)은 docs/12 "4단계 확인"

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-18 21:07:54 +09:00
parent c018bc5a9d
commit 735ddd0322
24 changed files with 2391 additions and 15 deletions

View File

@@ -2,3 +2,5 @@ export * from './nickname';
export * from './protocol';
export * from './types';
export * from './match-key';
export * from './room-config';
export * from './room-config-schema';

View File

@@ -1,3 +1,5 @@
/** Browser entry without zod: nickname rules and plain types. */
export * from './nickname';
export * from './types';
export * from './room-config';
export type { ChatLine, RoomView, RoomPlayerView, ServerMessage } from './protocol';

View File

@@ -3,20 +3,69 @@
* room/game messages are added in later stages.
*/
import { z } from 'zod';
import { CHAT_MAX } from './types';
export const PROTOCOL = 1;
export const MAX_CLIENT_MESSAGE_BYTES = 16 * 1024;
/** Chat line limit (docs/06). */
export const CHAT_MAX = 200;
export const ClientMessage = z.discriminatedUnion('t', [
/** Clock sync (docs/12 Q1): the client sends its own clock, the server echoes it with the server clock. */
z.object({ t: z.literal('ping'), c: z.number() }),
// ---- rooms (docs/04, stage 4)
z.object({ t: z.literal('join'), code: z.string().regex(/^\d{6}$/), password: z.string().max(40).optional() }),
z.object({ t: z.literal('leave') }),
/** Host only: partial RoomConfig; validated with RoomConfigSchema on the server. */
z.object({ t: z.literal('config'), patch: z.record(z.string(), z.unknown()) }),
/** Host only: room password for visibility 'password' (null clears it). */
z.object({ t: z.literal('password'), value: z.string().min(1).max(40).nullable() }),
z.object({ t: z.literal('ready'), on: z.boolean() }),
z.object({ t: z.literal('kick'), userId: z.string().max(40) }),
z.object({ t: z.literal('host'), userId: z.string().max(40) }),
/** Room chat (docs/06; stage 4 = waiting room only). `n` echoes back so the sender can confirm its optimistic line. */
z.object({ t: z.literal('chat'), text: z.string().min(1).max(CHAT_MAX), n: z.string().max(24).optional() }),
]);
export type ClientMessage = z.infer<typeof ClientMessage>;
export interface RoomPlayerView {
id: string;
nickname: string;
avatar: string | null;
kind: 'guest' | 'member';
ready: boolean;
online: boolean;
}
export interface RoomView {
code: string;
hostId: string;
status: 'lobby' | 'playing';
config: import('./room-config').RoomConfig;
hasPassword: boolean;
players: RoomPlayerView[];
/** 조건에 맞는 곡: playable now / including songs still waiting for a YouTube match. */
pool: { playable: number; total: number };
artists: { id: number; name: string }[];
}
/** One chat log line (docs/06 한 줄 로그). `seq` is per room; system lines have no userId. */
export interface ChatLine {
seq: number;
at: number;
userId: string | null;
nickname: string;
text: string;
/** Sender's nonce for its optimistic line. */
n?: string;
}
export type ServerMessage =
| { t: 'welcome'; protocol: number; userId: string; serverNow: number }
| { t: 'room'; room: RoomView }
| { t: 'left'; code: string; reason: 'leave' | 'kicked' | 'closed' | 'elsewhere' }
| { t: 'chat'; code: string; line: ChatLine }
/** Recent lines for someone who just joined (or came back). */
| { t: 'chatlog'; code: string; lines: ChatLine[] }
| { t: 'notice'; text: string }
| { t: 'pong'; c: number; s: number }
| { t: 'error'; message: string };

View File

@@ -0,0 +1,38 @@
import { z } from 'zod';
import { COUNTS, DEFAULT_ROOM_CONFIG, HINT_TIMES, LISTEN_SECS, LYRICS_SECS, VOTE_RULES, type RoomConfig } from './room-config';
const lit = <T extends readonly (string | number)[]>(xs: T) => z.union(xs.map((x) => z.literal(x)) as unknown as [z.ZodLiteral<T[number]>, z.ZodLiteral<T[number]>]);
export const RoomConfigSchema = z.object({
title: z.string().trim().max(40),
mode: z.enum(['listen', 'artist', 'lyrics']),
listenSec: lit(LISTEN_SECS),
startAt: z.enum(['start', 'highlight']),
artistIds: z.array(z.number().int().positive()).max(50),
lyricsSec: lit(LYRICS_SECS),
genres: z.array(z.string().max(30)).max(30),
yearFrom: z.number().int().min(1900).max(2100).nullable(),
yearTo: z.number().int().min(1900).max(2100).nullable(),
level: z.number().int().min(1).max(10),
answer: z.enum(['title', 'artist', 'both']),
strict: z.object({ space: z.boolean(), number: z.boolean(), symbol: z.boolean() }),
hint: z.union([z.literal('none'), z.literal('manual'), lit(HINT_TIMES)]),
hintVotes: z.enum(VOTE_RULES.filter((v) => v !== 'none') as ['1', '2', '1/3', '1/2', '2/3', 'all']),
skipVotes: z.enum(VOTE_RULES),
replayVotes: z.enum(VOTE_RULES),
count: lit(COUNTS),
visibility: z.enum(['public', 'private', 'password']),
});
/** Partial update from the host; returns the merged config or an error message. */
export function applyConfigPatch(cur: RoomConfig, patch: unknown): RoomConfig | string {
if (!patch || typeof patch !== 'object') return '잘못된 설정이에요.';
const merged = { ...cur, ...(patch as object), strict: { ...cur.strict, ...((patch as { strict?: object }).strict ?? {}) } };
const r = RoomConfigSchema.safeParse(merged);
if (!r.success) return `설정 값이 올바르지 않아요: ${r.error.issues.map((i) => i.path.join('.')).join(', ')}`;
const c = r.data as RoomConfig;
if (c.yearFrom && c.yearTo && c.yearFrom > c.yearTo) return '시작 연도가 끝 연도보다 늦어요.';
return c;
}
export { DEFAULT_ROOM_CONFIG };

View File

@@ -0,0 +1,110 @@
/**
* Room settings (docs/04, docs/12). One schema for server validation, defaults and the web form.
* Plain data so lite.ts can share the constants with the browser; the zod schema lives in room-config-schema.ts.
*/
export const MODES = [
{ id: 'listen', label: '듣고맞추기', icon: '🎧' },
{ id: 'artist', label: '가수노래 맞추기', icon: '🎤' },
{ id: 'lyrics', label: '가사보고 맞추기', icon: '📜' },
] as const;
export type Mode = (typeof MODES)[number]['id'];
/** 듣고맞출시간: seconds, 0 = 끝까지. */
export const LISTEN_SECS = [1, 3, 5, 10, 30, 60, 0] as const;
/** 보고맞출시간: seconds, 0 = 무제한. */
export const LYRICS_SECS = [30, 60, 90, 120, 150, 0] as const;
export const HINT_TIMES = [15, 30, 45, 60] as const;
/** 스킵·힌트·다시듣기 인원(이상). 'none' = 불가. */
export const VOTE_RULES = ['none', '1', '2', '1/3', '1/2', '2/3', 'all'] as const;
export type VoteRule = (typeof VOTE_RULES)[number];
/** 문제 수, 0 = 무제한(조건에 맞는 곡 전부). */
export const COUNTS = [10, 20, 30, 50, 100, 0] as const;
export interface RoomConfig {
title: string;
mode: Mode;
listenSec: (typeof LISTEN_SECS)[number];
startAt: 'start' | 'highlight';
artistIds: number[];
lyricsSec: (typeof LYRICS_SECS)[number];
/** Empty = 전체. Same group "또는", different groups "그리고" (docs/04, Q9). */
genres: string[];
yearFrom: number | null;
yearTo: number | null;
/** Exactly this level (docs/12 Q7). */
level: number;
answer: 'title' | 'artist' | 'both';
/** 정답인식: true = must match that element too (docs/12 Q2). */
strict: { space: boolean; number: boolean; symbol: boolean };
/** 'none' | seconds | 'manual' (직접선택). */
hint: 'none' | (typeof HINT_TIMES)[number] | 'manual';
hintVotes: Exclude<VoteRule, 'none'>;
skipVotes: VoteRule;
replayVotes: VoteRule;
count: (typeof COUNTS)[number];
visibility: 'public' | 'private' | 'password';
}
export const DEFAULT_ROOM_CONFIG: RoomConfig = {
title: '',
mode: 'listen',
listenSec: 0,
startAt: 'start',
artistIds: [],
lyricsSec: 0,
genres: [],
yearFrom: null,
yearTo: null,
level: 3,
answer: 'title',
strict: { space: true, number: true, symbol: true },
hint: 'none',
hintVotes: '1/3',
skipVotes: '1/3',
replayVotes: '1/3',
count: 30,
visibility: 'public',
};
/** Level names (docs/04 난이도). */
export const LEVELS = [
['누구나 아는 대표곡', '장르를 전혀 안 듣는 사람도 후렴을 따라 부를 수 있는 곡'],
['길거리 단골 노래', '방송, 매장, 길거리에서 워낙 자주 나와서 귀에 익은 곡'],
['한 번쯤 들어본 히트곡', '차트 상위권에 올라서 제목은 몰라도 대부분 들어본 곡'],
['가끔 들어도 아는 곡', '장르를 자주 안 들어도 차트에서 한 번쯤 접해본 곡'],
['장르 팬 필수곡', '크게 뜨진 않았지만 장르 팬이라면 다 아는 곡'],
['뒤늦게 알려진 곡', '입소문이나 역주행으로 뒤늦게 조금 알려진 곡'],
['고인물이 아끼는 숨은 명곡', '차트 성적은 없지만 고인물들 사이에서 명곡으로 꼽히는 곡'],
['찾아 들어야 아는 곡', '어디서도 들을 일이 없어서 직접 찾아 들은 사람만 아는 곡'],
['골수 리스너 인증곡', '고인물 중에서도 극소수만 들어본 곡'],
['인간 샤잠만 가능', '들어본 사람 자체가 거의 없는 곡'],
] as const;
/** How many votes pass a rule with `n` connected players (rounded up, docs/05 스킵). null = voting off. */
export function voteThreshold(rule: VoteRule, n: number): number | null {
if (rule === 'none') return null;
if (n <= 0) return 1;
const need = rule === '1' ? 1 : rule === '2' ? 2 : rule === 'all' ? n : Math.ceil((n * Number(rule[0])) / Number(rule[2]));
return Math.max(1, Math.min(n, need));
}
export function voteLabel(rule: VoteRule): string {
return { none: '없음', '1': '1명', '2': '2명', '1/3': '1/3명', '1/2': '1/2명', '2/3': '2/3명', all: '전체' }[rule];
}
export function listenLabel(s: number): string {
return s === 0 ? '끝까지' : s >= 60 ? `${s / 60}분` : `${s}초`;
}
/** One-line summary for room cards (docs/03 열린 방 목록). */
export function configSummary(c: RoomConfig, genreName: (id: string) => string = (x) => x): string[] {
const out: string[] = [];
if (c.mode === 'lyrics') out.push(`📜 가사 ${c.lyricsSec ? `${c.lyricsSec}초` : '무제한'}`);
else out.push(`${c.mode === 'artist' ? '🎤' : '🎧'} ${listenLabel(c.listenSec)}${c.startAt === 'highlight' ? ' · 하이라이트' : ''}`);
out.push(c.yearFrom || c.yearTo ? `${c.yearFrom ?? '처음'}~${c.yearTo ?? '지금'}` : '전체 연도');
out.push(c.genres.length ? c.genres.map(genreName).join(' · ') : '전체 장르');
out.push(`★${c.level}`);
if (c.answer !== 'title') out.push(c.answer === 'both' ? '제목+가수' : '가수만');
return out;
}

View File

@@ -6,3 +6,6 @@ export interface PublicUser {
}
export type Role = 'user' | 'admin' | 'superadmin';
/** Chat line limit (docs/06). */
export const CHAT_MAX = 200;