refactor: full codebase audit — extract modules, fix type safety, clean dead code

- Extract API helpers from UploadZone into lib/upload-api.ts (FormData builder, checkFolderDiffs, uploadDrive, uploadGit)
- Extract upload orchestration into hooks/useUploadOrchestrator.ts (UploadZone: 489 → 162 lines)
- Extract file diff classification into lib/diff-files.ts (from git route)
- Extract shared SVG icons into components/ui/icons.tsx (7 icons, 0 duplication)
- Extract shared modal wrapper into components/ui/Modal.tsx + ModalActions
- Extract DriveStatusLine sub-component from FolderCard
- Fix checkFolderDiffs silently swallowing auth/network errors (now throws)
- Fix type safety: remove as never casts, add isHttpError type guard, use discriminated union for validateFolder
- Fix nextcloud: cache getConfig, add max bound to findNextVersion, optimize mkdirRecursive (skip PROPFIND)
- Fix drive route: remove req.clone(), extend parseMultiUpload to return extra fields
- Fix commit message: model shown as unchanged with ↔️ on updates (not falsely marked as modified)
- Clean dead code: unused folderExists import, FileStatus/DriveStatus exports, ParsedFile.textureName, getConfig basePath
- Add security headers in next.config.ts (HSTS, X-Content-Type-Options, X-Frame-Options, etc.)
- Update README with new project structure
This commit is contained in:
Tom Boullay
2026-04-14 17:19:10 +02:00
parent 110d64ec33
commit 78f4aa83e0
26 changed files with 957 additions and 721 deletions
+1 -1
View File
@@ -23,7 +23,7 @@ export async function GET(req: NextRequest) {
return NextResponse.json({ success: false, error: 'Parametres manquants' }, { status: 400 })
}
if (!VALID_DESTINATIONS.has(destination as never)) {
if (!VALID_DESTINATIONS.has(destination)) {
return NextResponse.json({ success: false, error: 'Destination invalide' }, { status: 400 })
}
+7 -15
View File
@@ -2,7 +2,6 @@ import { NextRequest, NextResponse } from 'next/server'
import { validateUploadSecret } from '@/lib/auth'
import { parseMultiUpload } from '@/lib/parse-upload'
import {
folderExists,
mkdirRecursive,
moveFolder,
uploadFile,
@@ -22,11 +21,11 @@ export const dynamic = 'force-dynamic'
// - action: "new" | "replace"
//
// Versioning logic:
// VF/{folderName} latest version
// V1/{folderName} first archive, V2/ second, etc.
// VF/{folderName} <- latest version
// V1/{folderName} <- first archive, V2/ second, etc.
//
// action="new" just mkdir + upload into VF/
// action="replace" archive VF Vx, then re-upload all files into VF/
// action="new" -> just mkdir + upload into VF/
// action="replace" -> archive VF -> Vx, then re-upload all files into VF/
// ---------------------------------------------------------------------------
export async function POST(req: NextRequest) {
@@ -42,11 +41,7 @@ export async function POST(req: NextRequest) {
)
}
// --- Parse files ---
// Clone the request before parseMultiUpload consumes the body stream,
// so we can read the `action` field separately.
const cloned = req.clone()
// --- Parse files (includes extra fields like "action") ---
let folderName: string
let parsedFiles: Awaited<ReturnType<typeof parseMultiUpload>>['files']
let action: string
@@ -55,10 +50,7 @@ export async function POST(req: NextRequest) {
const parsed = await parseMultiUpload(req)
folderName = parsed.folderName
parsedFiles = parsed.files
// Read action from the cloned request (parseMultiUpload doesn't expose it)
const formData = await cloned.formData()
action = (formData.get('action') as string | null)?.trim() || 'new'
action = parsed.extra.action?.trim() || 'new'
} catch (err) {
const message = err instanceof Error ? err.message : 'Erreur inconnue'
return NextResponse.json({ success: false, error: message }, { status: 400 })
@@ -75,7 +67,7 @@ export async function POST(req: NextRequest) {
// 2. Ensure Vx/ exists
await mkdirRecursive(`${basePath}/${nextVersion}`)
// 3. Move VF/{folderName} Vx/{folderName}
// 3. Move VF/{folderName} -> Vx/{folderName}
await moveFolder(vfFolderPath, `${basePath}/${nextVersion}/${folderName}`)
// 4. Re-create VF/{folderName}
+4 -46
View File
@@ -7,8 +7,8 @@ import { parseMultiUpload } from '@/lib/parse-upload'
import { compressWithBlender } from '@/lib/blender'
import { getRemoteFolder, pushAllToGitHub } from '@/lib/github'
import { buildCommitMessage } from '@/lib/commit-message'
import { TMP_DIR, MODEL_EXTENSIONS } from '@/lib/constants'
import type { FileChange } from '@/lib/types'
import { classifyFileChanges } from '@/lib/diff-files'
import { TMP_DIR } from '@/lib/constants'
export const runtime = 'nodejs'
export const dynamic = 'force-dynamic'
@@ -85,8 +85,6 @@ export async function POST(req: NextRequest) {
}
// --- Detect existing files and classify changes ---
// Models: always re-push (compression changes size, can't compare with LFS remote)
// Textures: compare by size (not compressed, reliable)
const folderPath = `public/models/${destination}/${folderName}`
let remoteFileMap: Map<string, number>
@@ -99,48 +97,8 @@ export async function POST(req: NextRequest) {
const isReplace = remoteFileMap.size > 0
const fileChanges = new Map<string, FileChange>()
const changedFilesToPush: { path: string; contentBase64: string }[] = []
for (const f of filesToPush) {
const filename = f.path.split('/').pop() ?? ''
const ext = filename.slice(filename.lastIndexOf('.')).toLowerCase()
const isModel = MODEL_EXTENSIONS.has(ext)
if (isModel) {
// Model: always re-push since compression makes size comparison unreliable.
// Mark as 'unchanged' for the commit message when the folder already exists,
// because we can't know if the model really changed after Blender compression.
const remoteSize = remoteFileMap.get(filename.toLowerCase())
fileChanges.set(filename.toLowerCase(), remoteSize === undefined ? 'new' : 'unchanged')
changedFilesToPush.push(f)
} else {
// Texture: compare by size
const localSize = Buffer.from(f.contentBase64, 'base64').length
const remoteSize = remoteFileMap.get(filename.toLowerCase())
if (remoteSize === undefined) {
fileChanges.set(filename.toLowerCase(), 'new')
changedFilesToPush.push(f)
} else if (remoteSize !== localSize) {
fileChanges.set(filename.toLowerCase(), 'changed')
changedFilesToPush.push(f)
} else {
fileChanges.set(filename.toLowerCase(), 'unchanged')
}
}
}
// Files on remote not in the new upload → deleted (orphans)
const newFileNames = new Set(filesToPush.map((f) => (f.path.split('/').pop() ?? '').toLowerCase()))
const deletedFileNames: string[] = []
const deletePaths: string[] = []
for (const [name] of remoteFileMap) {
if (!newFileNames.has(name)) {
deletedFileNames.push(name)
deletePaths.push(`${folderPath}/${name}`)
}
}
const { fileChanges, changedFilesToPush, deletedFileNames, deletePaths } =
classifyFileChanges(filesToPush, remoteFileMap, folderPath)
// If nothing changed, don't create an empty commit
if (changedFilesToPush.length === 0 && deletePaths.length === 0) {