fix: 审查修复波次(P0x4 + P1x30+)
- domain/rules: 计分与排名解耦、破纪录按组别、tieBreak 生效、调整分不丢、移除 aggregate 假能力 - realtime: 新建 internal/dto,快照三项契约对齐,/ws 只认会话身份 - httpapi: 流水幂等、standings 整表载荷、广播接线、强制改密、XFF 防伪造、records 写入、审计、赛事包内容、发布前备份、result.points、实例列表 - web: FormData 上传、YAML 解析、快照归一化、大屏解析层、bootstrap 降级、访客判定、主题切换 - console: 优雅关闭握手、中文化、免验证改管理员账号、选屏与日志轮转修复 - docs: 用户文档三份 + README - 主代理: 破纪录加分接线(levels 未加载导致恒 0)
This commit is contained in:
1 parent
8dae63ee70
commit
7f9701c465
61 files changed
+3844
-333
No files matched your search
+62
-6
@@ -1,4 +1,7 @@
|
||||
import { isRecord, readString } from './internal'
|
||||
import { isRawBody, isRecord, readString } from './internal'
|
||||
import { normalizeRulePack } from './rules'
|
||||
import { isGuestRole } from './session'
|
||||
import { parseYaml } from './yaml'
|
||||
import type {
|
||||
AdjustmentInput,
|
||||
ApiErrorCode,
|
||||
@@ -204,6 +207,7 @@ interface Http {
|
||||
request<T>(path: string, options?: RequestOptions): Promise<T>
|
||||
requestVoid(path: string, options?: RequestOptions): Promise<void>
|
||||
requestJson(path: string, options?: RequestOptions): Promise<unknown>
|
||||
requestText(path: string, options?: RequestOptions): Promise<string>
|
||||
url(path: string, query?: object): string
|
||||
blob(path: string, options?: RequestOptions): Promise<Blob>
|
||||
}
|
||||
@@ -276,7 +280,21 @@ function createExportApi(http: Http): ExportApi {
|
||||
|
||||
function createRulesApi(http: Http): RulesApi {
|
||||
return {
|
||||
get: () => http.request<RulePack>('/rules/export'),
|
||||
// 导出接口返回的是裸 YAML 文本(不是 {ok,data}),必须按文本取回再解析。
|
||||
get: async () => {
|
||||
const text = await http.requestText('/rules/export')
|
||||
let parsed: unknown
|
||||
try {
|
||||
parsed = parseYaml(text)
|
||||
} catch (error) {
|
||||
throw new ApiError('PARSE_FAILED', '规则包 YAML 解析失败', 0, error)
|
||||
}
|
||||
const pack = normalizeRulePack(parsed)
|
||||
if (pack === null) {
|
||||
throw new ApiError('PARSE_FAILED', '规则包格式不符(需要 scoreboard-rules v1)', 0, parsed)
|
||||
}
|
||||
return pack
|
||||
},
|
||||
preview: (pack) =>
|
||||
http.request<RulePackImportPreview>('/rules/import', {
|
||||
method: 'POST',
|
||||
@@ -343,20 +361,27 @@ export class ApiClient {
|
||||
request: (path, requestOptions) => this.request(path, requestOptions),
|
||||
requestVoid: (path, requestOptions) => this.requestVoid(path, requestOptions),
|
||||
requestJson: (path, requestOptions) => this.requestJson(path, requestOptions),
|
||||
requestText: (path, requestOptions) => this.requestText(path, requestOptions),
|
||||
url: (path, query) => this.buildUrl(path, query),
|
||||
blob: (path, requestOptions) => this.fetchBlob(path, requestOptions),
|
||||
}
|
||||
|
||||
this.auth = {
|
||||
login: (username, password) =>
|
||||
http.request<CurrentUser>('/auth/login', { method: 'POST', body: { username, password } }),
|
||||
login: async (username, password) =>
|
||||
markGuest(
|
||||
await http.request<CurrentUser>('/auth/login', {
|
||||
method: 'POST',
|
||||
body: { username, password },
|
||||
}),
|
||||
),
|
||||
changePassword: (currentPassword, newPassword) =>
|
||||
http.request<{ relogin: boolean }>('/auth/password', {
|
||||
method: 'POST',
|
||||
body: { currentPassword, newPassword },
|
||||
}),
|
||||
logout: () => http.requestVoid('/auth/logout', { method: 'POST' }),
|
||||
me: () => http.request<CurrentUser>('/auth/me'),
|
||||
// 未登录时服务端回 200 + guest DTO,这里补出 guest 标记供 isGuestUser 判定。
|
||||
me: async () => markGuest(await http.request<CurrentUser>('/auth/me')),
|
||||
}
|
||||
|
||||
this.settings = {
|
||||
@@ -452,6 +477,21 @@ export class ApiClient {
|
||||
return body
|
||||
}
|
||||
|
||||
/** 规则包导出等接口返回裸文本(非 JSON),错误体仍按 {ok,error} 解析。 */
|
||||
private async requestText(path: string, options: RequestOptions = {}): Promise<string> {
|
||||
const response = await this.send(path, options)
|
||||
if (!response.ok) {
|
||||
const body = await readBody(response)
|
||||
if (response.status === 401) {
|
||||
const error = this.toApiError(body, response.status)
|
||||
this.onUnauthorized?.(error)
|
||||
throw error
|
||||
}
|
||||
throw this.toApiError(body, response.status)
|
||||
}
|
||||
return response.text()
|
||||
}
|
||||
|
||||
private async fetchBlob(path: string, options: RequestOptions = {}): Promise<Blob> {
|
||||
const response = await this.send(path, options)
|
||||
if (!response.ok) {
|
||||
@@ -469,10 +509,16 @@ export class ApiClient {
|
||||
private async send(path: string, options: RequestOptions): Promise<Response> {
|
||||
const method: HttpMethod = options.method ?? 'GET'
|
||||
const payload = this.prepareBody(method, options.body)
|
||||
// 断言:二进制 / 表单载荷只能原样透传,一旦被归一化展开就会静默丢内容(报名表导入踩过)。
|
||||
if (isRawBody(options.body) && payload !== options.body) {
|
||||
throw new ApiError('INTERNAL', '请求体归一化破坏了 FormData/Blob 载荷', 0, options.body)
|
||||
}
|
||||
const headers: Record<string, string> = { Accept: 'application/json' }
|
||||
|
||||
if (payload instanceof FormData) {
|
||||
// 交给浏览器带 multipart boundary,手动设置 Content-Type 会丢 boundary。
|
||||
} else if (isRawBody(payload)) {
|
||||
// Blob / URLSearchParams 自带类型语义,Content-Type 交给 fetch 决定。
|
||||
} else if (payload !== undefined) {
|
||||
headers['Content-Type'] = 'application/json; charset=utf-8'
|
||||
}
|
||||
@@ -499,7 +545,7 @@ export class ApiClient {
|
||||
body:
|
||||
payload === undefined
|
||||
? undefined
|
||||
: payload instanceof FormData
|
||||
: isRawBody(payload)
|
||||
? payload
|
||||
: JSON.stringify(payload),
|
||||
signal: controller.signal,
|
||||
@@ -517,6 +563,8 @@ export class ApiClient {
|
||||
/** 写操作注入 requestId:网络抖动重发时服务端能返回首次结果而不是重复执行。 */
|
||||
private prepareBody(method: HttpMethod, body: unknown): unknown {
|
||||
if (method === 'GET' || body === undefined) return undefined
|
||||
// FormData/Blob/URLSearchParams 不能展开,否则文件/二进制内容会被丢掉。
|
||||
if (isRawBody(body)) return body
|
||||
if (isRecord(body) && !('requestId' in body)) {
|
||||
return { ...body, requestId: this.newRequestId() }
|
||||
}
|
||||
@@ -568,6 +616,14 @@ function isScalar(value: unknown): value is string | number | boolean {
|
||||
return typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean'
|
||||
}
|
||||
|
||||
/**
|
||||
* 服务端未登录时 /auth/me 也回 200 + guest DTO,
|
||||
* 这里把 role 结论固化成 guest 字段,调用方用 isGuestUser(user) 判定即可。
|
||||
*/
|
||||
function markGuest(user: CurrentUser): CurrentUser {
|
||||
return { ...user, guest: isGuestRole(user.role) }
|
||||
}
|
||||
|
||||
async function readBody(response: Response): Promise<unknown> {
|
||||
if (response.status === 204) return null
|
||||
const text = await response.text()
|
||||
|
||||
@@ -8,6 +8,8 @@
|
||||
export * from './types'
|
||||
export { ApiClient, ApiError, createApiClient } from './api'
|
||||
export type { ApiClientOptions, QueryParams, QueryValue } from './api'
|
||||
export { normalizeSettings, normalizeStandingRows } from './normalize'
|
||||
export { GUEST_ROLE, isGuestRole, isGuestUser } from './session'
|
||||
export { RealtimeClient } from './realtime'
|
||||
export type {
|
||||
RealtimeInfo,
|
||||
|
||||
@@ -30,7 +30,9 @@ export function normalizeSettings(raw: unknown): EventSettings {
|
||||
const nestedStandings = isRecord(source.standings) ? source.standings : null
|
||||
const isFlat = nestedEvent === null && nestedDisplay === null && nestedStandings === null
|
||||
|
||||
const name = firstString(isFlat ? source['event.name'] : undefined, nestedEvent?.name) ?? '未命名赛事'
|
||||
const name =
|
||||
emptyToNull(firstString(isFlat ? source['event.name'] : undefined, nestedEvent?.name)) ??
|
||||
'未命名赛事'
|
||||
const subtitle = emptyToNull(
|
||||
firstString(isFlat ? source['event.subtitle'] : undefined, nestedEvent?.subtitle),
|
||||
)
|
||||
@@ -52,7 +54,9 @@ export function normalizeSettings(raw: unknown): EventSettings {
|
||||
firstString(isFlat ? source['display.background'] : undefined, nestedDisplay?.background),
|
||||
),
|
||||
logo: displayLogo ?? logoPath,
|
||||
title: firstString(isFlat ? source['display.title'] : undefined, nestedDisplay?.title) ?? name,
|
||||
title:
|
||||
emptyToNull(firstString(isFlat ? source['display.title'] : undefined, nestedDisplay?.title)) ??
|
||||
name,
|
||||
subtitle:
|
||||
emptyToNull(
|
||||
firstString(isFlat ? source['display.subtitle'] : undefined, nestedDisplay?.subtitle),
|
||||
@@ -71,8 +75,9 @@ export function normalizeSettings(raw: unknown): EventSettings {
|
||||
nestedStandings?.individualToTeamWeight,
|
||||
),
|
||||
rankingMode:
|
||||
firstString(isFlat ? source['standings.mode'] : undefined, nestedStandings?.rankingMode) ??
|
||||
'points',
|
||||
emptyToNull(
|
||||
firstString(isFlat ? source['standings.mode'] : undefined, nestedStandings?.rankingMode),
|
||||
) ?? 'points',
|
||||
showIndividualBoard: firstBool(
|
||||
true,
|
||||
isFlat ? source['standings.show_individual_board'] : undefined,
|
||||
|
||||
@@ -0,0 +1,228 @@
|
||||
/**
|
||||
* 规则包归一化。
|
||||
*
|
||||
* `GET /api/rules/export` 返回裸 YAML(服务端 rules.Marshal),这里把解析出的
|
||||
* unknown 收敛成 shared 的 RulePack 契约:补齐缺省值、丢弃未知字段。
|
||||
* 校验口径与服务端 rules.Canonical 对齐,避免前端拿到的规则包和实际生效规则不一致。
|
||||
*/
|
||||
|
||||
import {
|
||||
asRecord,
|
||||
emptyToNull,
|
||||
firstBool,
|
||||
firstNumber,
|
||||
firstNumberOrNull,
|
||||
firstString,
|
||||
isRecord,
|
||||
} from './internal'
|
||||
import type {
|
||||
ChannelBasis,
|
||||
ChannelScope,
|
||||
ChannelTemplate,
|
||||
EventOverride,
|
||||
EventType,
|
||||
RecordBonusLevel,
|
||||
RecordBonusMode,
|
||||
ResultType,
|
||||
RuleChannel,
|
||||
RulePack,
|
||||
RulePackManualAdjustment,
|
||||
RulePackMeta,
|
||||
RulePackRecordBonus,
|
||||
RulePackStandings,
|
||||
RuleProfile,
|
||||
ScoringProfileRule,
|
||||
TieBreakKey,
|
||||
TieMode,
|
||||
} from './types'
|
||||
|
||||
const TIE_BREAK_KEYS: readonly TieBreakKey[] = [
|
||||
'points',
|
||||
'gold',
|
||||
'silver',
|
||||
'bronze',
|
||||
'teamCode',
|
||||
'name',
|
||||
]
|
||||
const DEFAULT_TIE_BREAK: TieBreakKey[] = ['points', 'gold', 'silver', 'bronze', 'teamCode']
|
||||
const TIE_MODES: readonly TieMode[] = ['skip', 'average', 'higher']
|
||||
const RECORD_BONUS_MODES: readonly RecordBonusMode[] = ['max', 'sum']
|
||||
const SCOPES: readonly ChannelScope[] = ['athlete', 'team']
|
||||
const BASES: readonly ChannelBasis[] = ['result', 'manual', 'aggregate']
|
||||
const EVENT_TYPES: readonly EventType[] = ['individual', 'team', 'match']
|
||||
const RESULT_TYPES: readonly ResultType[] = ['time', 'distance', 'count', 'score', 'none']
|
||||
|
||||
export function normalizeRulePack(raw: unknown): RulePack | null {
|
||||
if (!isRecord(raw)) return null
|
||||
if (firstString(raw.format) !== 'scoreboard-rules') return null
|
||||
if (firstNumber(0, raw.formatVersion) !== 1) return null
|
||||
return {
|
||||
format: 'scoreboard-rules',
|
||||
formatVersion: 1,
|
||||
meta: normalizeMeta(raw.meta),
|
||||
standings: normalizeStandings(raw.standings),
|
||||
profiles: normalizeProfiles(raw.profiles),
|
||||
recordBonus: normalizeRecordBonus(raw.recordBonus),
|
||||
manualAdjustment: normalizeManualAdjustment(raw.manualAdjustment),
|
||||
channelTemplates: normalizeTemplates(raw.channelTemplates),
|
||||
eventOverrides: normalizeOverrides(raw.eventOverrides),
|
||||
}
|
||||
}
|
||||
|
||||
function oneOf<T extends string>(value: unknown, allowed: readonly T[], fallback: T): T {
|
||||
return typeof value === 'string' && (allowed as readonly string[]).includes(value)
|
||||
? (value as T)
|
||||
: fallback
|
||||
}
|
||||
|
||||
function optionalOneOf<T extends string>(value: unknown, allowed: readonly T[]): T | undefined {
|
||||
return typeof value === 'string' && (allowed as readonly string[]).includes(value)
|
||||
? (value as T)
|
||||
: undefined
|
||||
}
|
||||
|
||||
function normalizeMeta(raw: unknown): RulePackMeta {
|
||||
const rec = asRecord(raw)
|
||||
return {
|
||||
code: firstString(rec.code) ?? '',
|
||||
name: firstString(rec.name) ?? '',
|
||||
version: firstString(rec.version) ?? '',
|
||||
updatedAt: firstString(rec.updatedAt) ?? '',
|
||||
author: emptyToNull(firstString(rec.author)),
|
||||
note: emptyToNull(firstString(rec.note)),
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeStandings(raw: unknown): RulePackStandings {
|
||||
const rec = asRecord(raw)
|
||||
const tieBreakRaw = rec.tieBreak
|
||||
const tieBreak = Array.isArray(tieBreakRaw)
|
||||
? tieBreakRaw.filter(
|
||||
(item): item is TieBreakKey =>
|
||||
typeof item === 'string' && (TIE_BREAK_KEYS as readonly string[]).includes(item),
|
||||
)
|
||||
: []
|
||||
return {
|
||||
individualToTeamWeight: firstNumber(1, rec.individualToTeamWeight),
|
||||
tieBreak: tieBreak.length > 0 ? tieBreak : [...DEFAULT_TIE_BREAK],
|
||||
medalCountsTeamEvents: firstBool(true, rec.medalCountsTeamEvents),
|
||||
showIndividualBoard: firstBool(true, rec.showIndividualBoard),
|
||||
showIndividualMedals: firstBool(true, rec.showIndividualMedals),
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeProfiles(raw: unknown): RuleProfile[] {
|
||||
if (!Array.isArray(raw)) return []
|
||||
const out: RuleProfile[] = []
|
||||
for (const item of raw) {
|
||||
const rec = asRecord(item)
|
||||
const code = firstString(rec.code)
|
||||
if (code === null || code === '') continue
|
||||
out.push({
|
||||
code,
|
||||
name: firstString(rec.name) ?? code,
|
||||
awardRanks: firstNumber(0, rec.awardRanks),
|
||||
lastPlaceZero: firstBool(false, rec.lastPlaceZero),
|
||||
tieMode: oneOf(rec.tieMode, TIE_MODES, 'skip'),
|
||||
recordBonusMode: optionalOneOf(rec.recordBonusMode, RECORD_BONUS_MODES),
|
||||
rules: normalizeScoringRules(rec.rules),
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
function normalizeScoringRules(raw: unknown): ScoringProfileRule[] {
|
||||
if (!Array.isArray(raw)) return []
|
||||
const out: ScoringProfileRule[] = []
|
||||
for (const item of raw) {
|
||||
const rec = asRecord(item)
|
||||
const rank = firstNumberOrNull(rec.rank)
|
||||
const points = firstNumberOrNull(rec.points)
|
||||
if (rank === null || points === null) continue
|
||||
out.push({ rank, points })
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
function normalizeRecordBonus(raw: unknown): RulePackRecordBonus {
|
||||
const rec = asRecord(raw)
|
||||
return {
|
||||
enabled: firstBool(false, rec.enabled),
|
||||
mode: oneOf(rec.mode, RECORD_BONUS_MODES, 'max'),
|
||||
levels: normalizeLevels(rec.levels),
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeLevels(raw: unknown): RecordBonusLevel[] {
|
||||
if (!Array.isArray(raw)) return []
|
||||
const out: RecordBonusLevel[] = []
|
||||
for (const item of raw) {
|
||||
const rec = asRecord(item)
|
||||
const code = firstString(rec.code)
|
||||
if (code === null || code === '') continue
|
||||
out.push({ code, name: firstString(rec.name) ?? code, points: firstNumber(0, rec.points) })
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
function normalizeManualAdjustment(raw: unknown): RulePackManualAdjustment {
|
||||
const rec = asRecord(raw)
|
||||
return {
|
||||
enabled: firstBool(false, rec.enabled),
|
||||
reasonRequired: firstBool(true, rec.reasonRequired),
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeTemplates(raw: unknown): ChannelTemplate[] {
|
||||
if (!Array.isArray(raw)) return []
|
||||
return raw.map((item) => {
|
||||
const rec = asRecord(item)
|
||||
const match = asRecord(rec.match)
|
||||
return {
|
||||
match: {
|
||||
eventType: optionalOneOf(match.eventType, EVENT_TYPES),
|
||||
resultType: optionalOneOf(match.resultType, RESULT_TYPES),
|
||||
sportCode: firstString(match.sportCode) ?? undefined,
|
||||
},
|
||||
channels: normalizeChannels(rec.channels),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function normalizeOverrides(raw: unknown): EventOverride[] {
|
||||
if (!Array.isArray(raw)) return []
|
||||
const out: EventOverride[] = []
|
||||
for (const item of raw) {
|
||||
const rec = asRecord(item)
|
||||
const eventCode = firstString(rec.eventCode)
|
||||
if (eventCode === null || eventCode === '') continue
|
||||
const override: EventOverride = { eventCode }
|
||||
const name = firstString(rec.name)
|
||||
if (name !== null) override.name = name
|
||||
if (typeof rec.scored === 'boolean') override.scored = rec.scored
|
||||
const multiplier = firstNumberOrNull(rec.multiplier)
|
||||
if (multiplier !== null) override.multiplier = multiplier
|
||||
if (Array.isArray(rec.channels)) override.channels = normalizeChannels(rec.channels)
|
||||
out.push(override)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
function normalizeChannels(raw: unknown): RuleChannel[] {
|
||||
if (!Array.isArray(raw)) return []
|
||||
const out: RuleChannel[] = []
|
||||
for (const item of raw) {
|
||||
const rec = asRecord(item)
|
||||
const profile = firstString(rec.profile)
|
||||
if (profile === null || profile === '') continue
|
||||
const channel: RuleChannel = {
|
||||
scope: oneOf(rec.scope, SCOPES, 'athlete'),
|
||||
basis: oneOf(rec.basis, BASES, 'result'),
|
||||
profile,
|
||||
}
|
||||
const aggregate = firstString(rec.aggregate)
|
||||
if (aggregate !== null && aggregate !== '') channel.aggregate = aggregate
|
||||
out.push(channel)
|
||||
}
|
||||
return out
|
||||
}
|
||||
Reference in new issue
Block a user