SPB Git

Repository Public MIT

upload.ts 5.7 KB 114 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : VQuant8 * File             : client/src/lib/research/upload.ts9 * Module           : lib10 * Repository       : https://git.spboucher.ai/vquant11 * Project Website  : https://vquant.spboucher.ai12 * Created          : 2026-11-2013 * Last Modified    : 2026-11-2014 *15 * Author           : Simon-Pierre Boucher16 * Position         : Professor of Finance17 * Institution      : Université du Québec en Outaouais (UQO)18 * Organization     : SP Boucher19 * Website          : https://spboucher.ai20 * Git              : https://git.spboucher.ai21 *22 * Preferred Contact: contact@spboucher.ai23 * Development      : dev@spboucher.ai24 * Support          : support@spboucher.ai25 * Security/Admin   : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * SPDX Identifier  : MIT34 * License          : MIT License35 * License File     : LICENSE36 *37 * Do not embed credentials, private keys, access tokens,38 * certificates or confidential personal information.39 *40 * =============================================================================41 * END OF SP BOUCHER SOURCE HEADER42 * =============================================================================43 */4445/**46 * Dataset upload (CONTRACT §9.1): the checks a browser can make before sending (extension, size, emptiness), the47 * upload itself with progress, and the words for what the server refuses. The server checks the bytes again.48 */49export const DATASET_EXTENSIONS = [".csv", ".tsv", ".txt", ".json", ".jsonl", ".parquet", ".xlsx", ".xls", ".feather"] as const;50export const DATASET_ACCEPT = DATASET_EXTENSIONS.join(",");51/** Limit of the route when the server has not been asked yet (`GET /api/v2/research/sandbox` → uploadMaxBytes). */52export const DEFAULT_UPLOAD_MAX_BYTES = 200 * 1024 * 1024;5354export type UploadCheck = { ok: true; extension: string } | { ok: false; error: string };5556export function extensionOf(name: string): string {57  const i = name.lastIndexOf(".");58  return i <= 0 ? "" : name.slice(i).toLowerCase();59}6061export function formatBytes(bytes: number | null | undefined): string {62  if (bytes == null || !Number.isFinite(bytes)) return "—";63  const fr = (v: number, d: number) => v.toLocaleString("fr-CA", { minimumFractionDigits: d, maximumFractionDigits: d });64  if (bytes < 1024) return `${fr(bytes, 0)} o`;65  if (bytes < 1024 ** 2) return `${fr(bytes / 1024, bytes < 10 * 1024 ? 1 : 0)} ko`;66  if (bytes < 1024 ** 3) return `${fr(bytes / 1024 ** 2, 1)} Mo`;67  return `${fr(bytes / 1024 ** 3, 2)} Go`;68}6970export function validateDataset(file: { name: string; size: number }, maxBytes: number = DEFAULT_UPLOAD_MAX_BYTES): UploadCheck {71  const extension = extensionOf(file.name);72  if (!extension) return { ok: false, error: "Ce fichier n'a pas d'extension : impossible de savoir comment le lire. Formats acceptés : CSV, TSV, JSON, Parquet, Excel, Feather." };73  if (!(DATASET_EXTENSIONS as readonly string[]).includes(extension)) {74    return { ok: false, error: `Le format ${extension} n'est pas accepté. Formats acceptés : CSV, TSV, TXT, JSON, JSONL, Parquet, XLSX, XLS, Feather.` };75  }76  if (file.size === 0) return { ok: false, error: "Ce fichier est vide." };77  if (file.size > maxBytes) return { ok: false, error: `Ce fichier pèse ${formatBytes(file.size)} ; la limite est de ${formatBytes(maxBytes)}.` };78  return { ok: true, extension };79}8081/** What the server answered, in French. */82export function uploadErrorMessage(status: number, serverMessage?: string | null): string {83  if (status === 413) return "Le serveur refuse ce fichier : il dépasse la taille maximale.";84  if (status === 415) return "Le contenu du fichier ne correspond pas à son extension (ou c'est une archive, un PDF ou un exécutable).";85  if (status === 401) return "Session verrouillée : rouvrez VQuant puis recommencez.";86  if (status === 404) return "L'espace de recherche de cette conversation est introuvable.";87  if (status === 0) return "Connexion interrompue pendant l'envoi.";88  return serverMessage ? `Envoi refusé : ${serverMessage}` : `Envoi refusé (erreur ${status}).`;89}9091export interface UploadedFile { path: string; bytes: number; sha256: string }9293/** Sends one file to the workspace. XMLHttpRequest because fetch reports no upload progress. */94export function uploadDataset(workspaceId: string, file: File, onProgress: (fraction: number) => void, signal?: AbortSignal): Promise<UploadedFile> {95  return new Promise((resolve, reject) => {96    const xhr = new XMLHttpRequest();97    xhr.open("POST", `/api/v2/research/sessions/${encodeURIComponent(workspaceId)}/upload`);98    xhr.responseType = "text";99    xhr.upload.onprogress = (e) => { if (e.lengthComputable) onProgress(Math.min(1, e.loaded / e.total)); };100    xhr.onerror = () => reject(new Error(uploadErrorMessage(0)));101    xhr.onabort = () => reject(new DOMException("Envoi annulé", "AbortError"));102    xhr.onload = () => {103      let body: { file?: UploadedFile; error?: string } | null = null;104      try { body = JSON.parse(xhr.responseText); } catch { /* not JSON */ }105      if (xhr.status === 201 && body?.file) return resolve(body.file);106      reject(new Error(uploadErrorMessage(xhr.status, body?.error)));107    };108    signal?.addEventListener("abort", () => xhr.abort(), { once: true });109    const form = new FormData();110    form.append("file", file, file.name);111    xhr.send(form);112  });113}114
Files main
Menu

Theme