"use client"; import { useEffect, useMemo, useState, type ChangeEvent } from "react"; import { FilePlus2, Save, Trash2, Upload } from "lucide-react"; import { toast } from "sonner"; import { Button } from "@/components/ui/button"; import { Textarea } from "@/components/ui/textarea"; import { WikiSourceViewer } from "./wiki-source-viewer"; import { useAddWikiSources, useRemoveWikiSource, useUpdateWikiSource, useWikiSource, useWikiSources, } from "@/hooks/use-wikis"; import { useI18n } from "@/i18n/i18n-context"; import { showApiError } from "@/lib/api-error-toast"; import { ApiClientError } from "@/services/api-client"; import { isSupportedWikiSourcePath, isTextWikiSourcePath, MAX_WIKI_SOURCE_BATCH_BYTES, MAX_WIKI_SOURCE_CONTENT_BYTES, MAX_WIKI_SOURCE_COUNT, WIKI_SOURCE_ACCEPT, wikiSourceMediaType, } from "@/lib/wiki-source-contract"; import { bytesToBase64 } from "@/lib/binary-content"; import type { WikiRawSource, WikiScope, WikiSourceContent, WikiSourceBatchResult, } from "@/types/wiki"; interface WikiSourceUploadFile { name: string; size: number; text: () => Promise; arrayBuffer?: () => Promise; } async function readWikiSourceFile( file: WikiSourceUploadFile, path = file.name, ): Promise { if (file.size > MAX_WIKI_SOURCE_CONTENT_BYTES) { throw new Error("SOURCE_TOO_LARGE"); } if (isTextWikiSourcePath(path)) { const content = await file.text(); if ( new TextEncoder().encode(content).byteLength > MAX_WIKI_SOURCE_CONTENT_BYTES ) { throw new Error("SOURCE_TOO_LARGE"); } return { path, content }; } const mediaType = wikiSourceMediaType(path); if (!mediaType || !file.arrayBuffer) throw new Error("UNSUPPORTED_SOURCE"); const bytes = new Uint8Array(await file.arrayBuffer()); if (bytes.byteLength === 0) throw new Error("UNSUPPORTED_SOURCE"); if (bytes.byteLength > MAX_WIKI_SOURCE_CONTENT_BYTES) { throw new Error("SOURCE_TOO_LARGE"); } return { path, contentBase64: bytesToBase64(bytes), mediaType }; } function wikiSourceReadErrorCode(error: unknown): string { if ( error instanceof Error && (error.message === "SOURCE_TOO_LARGE" || error.message === "UNSUPPORTED_SOURCE") ) { return error.message; } return "FILE_READ_FAILED"; } export type WikiSourceReplacementErrorMessage = | { key: "wiki.sources.replaceTooLarge"; variables: { limit: number }; } | { key: "wiki.sources.replaceFormatMismatch" }; export function getWikiSourceReplacementErrorMessage( error: unknown, ): WikiSourceReplacementErrorMessage | undefined { if (!(error instanceof Error)) return undefined; if (error.message === "SOURCE_TOO_LARGE") { return { key: "wiki.sources.replaceTooLarge", variables: { limit: MAX_WIKI_SOURCE_CONTENT_BYTES }, }; } if (error.message === "UNSUPPORTED_SOURCE") { return { key: "wiki.sources.replaceFormatMismatch" }; } return undefined; } export type WikiSourceUploadOutcome = | { path: string; ok: true } | { path: string; ok: false; error: WikiSourceDiagnostic }; export interface WikiSourceDiagnostic { code: string; message?: string; requestId?: string; httpStatus?: number; upstreamCode?: string; upstreamRequestId?: string; } export interface WikiSourceDiagnosticLabels { code: string; upstreamCode: string; requestId: string; upstreamRequestId: string; } function safeWikiSourceMessage( message: string | undefined, ): string | undefined { if (!message || message.includes("/.wiki/")) return undefined; return message; } function wikiSourceDiagnosticFromError( error: unknown, fallbackCode: string, ): WikiSourceDiagnostic { if (error instanceof ApiClientError) { return { code: error.code, message: safeWikiSourceMessage(error.message), requestId: error.requestId, httpStatus: error.status, upstreamCode: error.details?.upstreamCode, upstreamRequestId: error.details?.upstreamRequestId, }; } return { code: fallbackCode, message: safeWikiSourceMessage( error instanceof Error ? error.message : undefined, ), }; } export async function uploadWikiSourceFiles( files: readonly WikiSourceUploadFile[], uploadBatch: (sources: WikiSourceContent[]) => Promise, ): Promise { const eligible = files .filter((file) => isSupportedWikiSourcePath(file.name)) .map((file, index) => ({ file, index, path: file.name })); const outcomes = new Array( eligible.length, ); for (let offset = 0; offset < eligible.length;) { let end = offset; let batchBytes = 0; while (end < eligible.length && end - offset < MAX_WIKI_SOURCE_COUNT) { const nextSize = Math.max(eligible[end]!.file.size, 0); if (end > offset && batchBytes + nextSize > MAX_WIKI_SOURCE_BATCH_BYTES) { break; } batchBytes += nextSize; end += 1; } const candidates = eligible.slice(offset, end); offset = end; const readable = ( await Promise.all( candidates.map(async ({ file, index, path }) => { try { return { index, source: await readWikiSourceFile(file, path) }; } catch (error) { outcomes[index] = { path, ok: false, error: { code: wikiSourceReadErrorCode(error) }, }; return null; } }), ) ).filter( (source): source is { index: number; source: WikiSourceContent } => source !== null, ); if (readable.length === 0) continue; try { const response = await uploadBatch(readable.map(({ source }) => source)); readable.forEach(({ source }, index) => { const result = response.results[index]; outcomes[readable[index]!.index] = result?.ok && result.path === source.path ? { path: source.path, ok: true } : { path: source.path, ok: false, error: result?.error ? { ...result.error, message: safeWikiSourceMessage(result.error.message), } : { code: "INVALID_BATCH_RESPONSE" }, }; }); } catch (error) { const diagnostic = wikiSourceDiagnosticFromError(error, "UPLOAD_FAILED"); for (const { index, source } of readable) { outcomes[index] = { path: source.path, ok: false, error: diagnostic, }; } } } return outcomes.filter( (outcome): outcome is WikiSourceUploadOutcome => outcome !== undefined, ); } export function showWikiSourceUploadOutcomes( outcomes: readonly WikiSourceUploadOutcome[], translate: ( key: | "wiki.sources.fileAdded" | "wiki.sources.fileFailed" | "wiki.sources.fileTooLarge" | "wiki.sources.fileFormatMismatch", variables: Record, ) => string, labels?: WikiSourceDiagnosticLabels, ): void { for (const outcome of outcomes) { if (outcome.ok) { toast.success( translate("wiki.sources.fileAdded", { path: outcome.path }), ); } else { if (outcome.error.code === "SOURCE_TOO_LARGE") { toast.error( translate("wiki.sources.fileTooLarge", { path: outcome.path, limit: MAX_WIKI_SOURCE_CONTENT_BYTES, }), ); continue; } if (outcome.error.code === "UNSUPPORTED_SOURCE") { toast.error( translate("wiki.sources.fileFormatMismatch", { path: outcome.path, }), ); continue; } const title = translate("wiki.sources.fileFailed", { path: outcome.path, code: outcome.error.upstreamCode ?? outcome.error.code, }); const description = formatWikiSourceDiagnostic(outcome.error, labels); if (description) { toast.error(title, { description }); } else { toast.error(title); } } } } function formatWikiSourceDiagnostic( diagnostic: WikiSourceDiagnostic, labels?: WikiSourceDiagnosticLabels, ): string | undefined { const parts: string[] = []; const message = safeWikiSourceMessage(diagnostic.message); const displayCode = diagnostic.upstreamCode ?? diagnostic.code; if (message) parts.push(`[${displayCode}] ${message}`); if (diagnostic.httpStatus !== undefined) { parts.push(`HTTP ${diagnostic.httpStatus}`); } if (labels && diagnostic.upstreamCode) { if (diagnostic.code !== diagnostic.upstreamCode) { parts.push(`${labels.code}: ${diagnostic.code}`); } parts.push(`${labels.upstreamCode}: ${diagnostic.upstreamCode}`); } if (labels && diagnostic.requestId) { parts.push(`${labels.requestId}: ${diagnostic.requestId}`); } if ( labels && diagnostic.upstreamRequestId && diagnostic.upstreamRequestId !== diagnostic.requestId ) { parts.push(`${labels.upstreamRequestId}: ${diagnostic.upstreamRequestId}`); } return parts.length ? parts.join(" ยท ") : undefined; } export function buildWikiSourceUpdateVariables( memoryStoreName: string, scope: WikiScope, source: Pick, content: string, ) { return { memoryStoreName, scope, path: source.path, content, expectedVersionId: source.latestVersionId, }; } export function buildWikiSourceDeleteVariables( memoryStoreName: string, scope: WikiScope, source: Pick, ) { return { memoryStoreName, scope, path: source.path, expectedVersionId: source.latestVersionId, }; } export function WikiSourcesPanel({ memoryStoreName, scope, }: { memoryStoreName: string; scope: WikiScope; }) { const { t } = useI18n(); const list = useWikiSources(memoryStoreName, scope, { limit: 100 }); const sources = useMemo( () => list.data?.pages.flatMap((page) => page.sources) ?? [], [list.data], ); const [selectedPath, setSelectedPath] = useState(); const source = useWikiSource(memoryStoreName, scope, selectedPath); const [content, setContent] = useState(""); const add = useAddWikiSources(); const update = useUpdateWikiSource(); const remove = useRemoveWikiSource(); const diagnosticLabels: WikiSourceDiagnosticLabels = { code: t("wiki.sources.errorCode"), upstreamCode: t("wiki.sources.upstreamCode"), requestId: t("wiki.detail.requestId"), upstreamRequestId: t("wiki.detail.upstreamRequestId"), }; useEffect(() => { setContent(source.data?.content ?? ""); }, [source.data]); async function handleFiles(event: ChangeEvent) { const files = Array.from(event.target.files ?? []).filter((file) => isSupportedWikiSourcePath(file.name), ); event.target.value = ""; const outcomes = await uploadWikiSourceFiles(files, (sources) => add.mutateAsync({ memoryStoreName, scope, sources, }), ); showWikiSourceUploadOutcomes(outcomes, t, diagnosticLabels); } async function handleBinaryReplacement(event: ChangeEvent) { const file = event.target.files?.[0]; event.target.value = ""; if (!file || !source.data || !selectedPath) return; try { if ( wikiSourceMediaType(file.name) !== wikiSourceMediaType(selectedPath) ) { throw new Error("UNSUPPORTED_SOURCE"); } const replacement = await readWikiSourceFile(file, selectedPath); if (!("contentBase64" in replacement)) { throw new Error("UNSUPPORTED_SOURCE"); } await update.mutateAsync({ memoryStoreName, scope, ...replacement, expectedVersionId: source.data.latestVersionId, }); toast.success(t("wiki.sources.saved")); } catch (error) { const localError = getWikiSourceReplacementErrorMessage(error); if (localError) { toast.error( localError.key === "wiki.sources.replaceTooLarge" ? t(localError.key, localError.variables) : t(localError.key), ); return; } showWikiSourceError(error, { fallbackTitle: t("wiki.sources.saveFailed"), conflictMessage: t("wiki.sources.conflict"), refreshLabel: t("wiki.sources.refresh"), onRefresh: () => void source.refetch(), labels: diagnosticLabels, }); } } async function handleSave() { if (!source.data || !selectedPath) return; try { await update.mutateAsync( buildWikiSourceUpdateVariables( memoryStoreName, scope, source.data, content, ), ); toast.success(t("wiki.sources.saved")); } catch (error) { showWikiSourceError(error, { fallbackTitle: t("wiki.sources.saveFailed"), conflictMessage: t("wiki.sources.conflict"), refreshLabel: t("wiki.sources.refresh"), onRefresh: () => void source.refetch(), labels: diagnosticLabels, }); } } async function handleDelete() { if (!source.data || !selectedPath) return; try { await remove.mutateAsync( buildWikiSourceDeleteVariables(memoryStoreName, scope, source.data), ); toast.success(t("wiki.sources.deleted")); setSelectedPath(undefined); } catch (error) { showWikiSourceError(error, { fallbackTitle: t("wiki.sources.deleteFailed"), conflictMessage: t("wiki.sources.conflict"), refreshLabel: t("wiki.sources.refresh"), onRefresh: () => void source.refetch(), labels: diagnosticLabels, }); } } return (
{selectedPath ? ( <>

{selectedPath}

{t("wiki.sources.version", { version: source.data?.latestVersionId ?? "-", })}

{source.data?.contentBase64 ? ( <> ) : null}
{source.isLoading ? (

{t("common.loading")}

) : source.data?.contentBase64 ? (
) : (