SPB Git

Repository Public

api.ts 5.7 KB 108 lines typescript

1// SP Mail Next — client typé de /api/next : capacités du serveur, erreurs classées, requêtes (cookie de session, en-tête anti-CSRF).2import { HttpError, NetworkError } from "../jmap/errors"3import { api, request, type RequestOptions } from "../jmap/http"4import { createStore, useStore } from "../state/store"56// ---------------------------------------------------------------- erreurs7/** Ce qu'une interface a besoin de distinguer d'un échec de /api/next. */8export type NextErrorKind = "offline" | "ai_disabled" | "consent_required" | "provider_unavailable" | "not_found" | "rate_limited" | "conflict" | "invalid" | "too_large" | "unavailable" | "unauthorized" | "unknown"910export class NextError extends Error {11  constructor(12    public kind: NextErrorKind,13    public status: number,14    /** code du serveur (`name_taken`, `ai_timeout`…) */15    public code: string,16    message?: string,17  ) {18    super(message ?? code)19    this.name = "NextError"20  }21}2223/** Classe une réponse d'erreur (statut HTTP + code de l'enveloppe `{error, message}`). Fonction pure. */24export function classifyError(status: number, code: string): NextErrorKind {25  if (code === "ai_disabled") return "ai_disabled"26  if (code === "consent_required" || status === 412) return "consent_required"27  if (code === "provider_unavailable" || code === "semantic_unavailable" || code === "ai_not_configured") return "provider_unavailable"28  if (status === 401) return "unauthorized"29  if (status === 404) return "not_found"30  if (status === 429) return "rate_limited"31  if (status === 409) return "conflict"32  if (status === 413) return "too_large"33  if (status === 400 || status === 422) return "invalid"34  if (status === 502 || status === 503 || status === 504) return "unavailable"35  return "unknown"36}37export function toNextError(e: unknown): NextError {38  if (e instanceof NextError) return e39  if (e instanceof NetworkError) return new NextError("offline", 0, "offline")40  if (e instanceof HttpError) return new NextError(classifyError(e.status, e.code), e.status, e.code, e.message)41  return new NextError("unknown", 0, "unknown", e instanceof Error ? e.message : undefined)42}43export const errorKindOf = (e: unknown): NextErrorKind => toNextError(e).kind44/** Requête annulée (changement d'écran, nouvelle frappe) : à ignorer en silence. */45export const isAbort = (e: unknown): boolean => e instanceof DOMException && e.name === "AbortError"4647// ---------------------------------------------------------------- requêtes48export type Params = Record<string, string | number | boolean | null | undefined>49/** `/api/next/<chemin>?<paramètres>` — les valeurs vides, nulles ou `false` sont omises ; `true` devient `1`. Fonction pure. */50export function nextUrl(path: string, params?: Params): string {51  const base = path.startsWith("/") ? path : `/api/next/${path}`52  if (!params) return base53  const q = new URLSearchParams()54  for (const [k, v] of Object.entries(params)) {55    if (v === undefined || v === null || v === "" || v === false) continue56    q.set(k, v === true ? "1" : String(v))57  }58  const s = q.toString()59  return s ? `${base}?${s}` : base60}61async function call<T>(url: string, opts: RequestOptions = {}): Promise<T> {62  try {63    return await api<T>(url, opts)64  } catch (e) {65    if (isAbort(e)) throw e66    throw toNextError(e)67  }68}69export const nx = {70  get: <T>(path: string, params?: Params, signal?: AbortSignal) => call<T>(nextUrl(path, params), { signal }),71  /** `{ data: T[] }` → `T[]` */72  list: async <T>(path: string, params?: Params, signal?: AbortSignal) => (await call<{ data: T[] }>(nextUrl(path, params), { signal })).data,73  post: <T>(path: string, json: unknown = {}, signal?: AbortSignal) => call<T>(nextUrl(path), { method: "POST", json, signal }),74  put: <T>(path: string, json: unknown) => call<T>(nextUrl(path), { method: "PUT", json }),75  patch: <T>(path: string, json: unknown) => call<T>(nextUrl(path), { method: "PATCH", json }),76  del: <T = { ok: boolean }>(path: string) => call<T>(nextUrl(path), { method: "DELETE" }),77  /** Réponse brute (ZIP, vCard) ; mêmes erreurs classées. */78  raw: async (path: string, opts: RequestOptions = {}, params?: Params): Promise<Response> => {79    try {80      return await request(nextUrl(path, params), opts)81    } catch (e) {82      if (isAbort(e)) throw e83      throw toNextError(e)84    }85  },86}8788// ---------------------------------------------------------------- capacités89/** Fonctions annoncées par `GET /api/next/capabilities` (server/src/next/index.ts). */90export type Feature = "push" | "snooze" | "reminders" | "labels" | "saved_searches" | "snippets" | "signatures" | "contacts" | "search_all" | "attachments" | "dashboard" | "undo_send" | "ai" | "rules" | "alerts"91export interface Capabilities {92  version: string93  features: string[]94}95/** `caps` null + `checked` vrai : serveur plus ancien (ou injoignable) → aucune entrée « Next » n'apparaît. */96export const NX = createStore<{ caps: Capabilities | null; checked: boolean }>({ caps: null, checked: false })97export const CAPS_CACHE_KEY = "next:capabilities"9899/** Ne garde d'une réponse que ce qui a la forme attendue (un serveur plus ancien répond 404, un mandataire peut répondre autre chose). */100export function normalizeCapabilities(raw: unknown): Capabilities | null {101  if (!raw || typeof raw !== "object") return null102  const r = raw as Record<string, unknown>103  if (!Array.isArray(r.features)) return null104  return { version: typeof r.version === "string" ? r.version : "", features: r.features.filter((f): f is string => typeof f === "string") }105}106export const hasFeature = (f: Feature, caps: Capabilities | null = NX.get().caps): boolean => !!caps && caps.features.includes(f)107export const useFeature = (f: Feature): boolean => useStore(NX, (s) => !!s.caps && s.caps.features.includes(f))108
Files main
Menu

Theme