Spaces:
Running

File size: 3,369 Bytes
03608f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
import {
  getAccessToken,
  getStepupToken,
  notifySessionExpired,
  refreshAccessToken,
} from "@/lib/session";

export const API_URL = (process.env.NEXT_PUBLIC_API_URL ?? "http://127.0.0.1:8000").replace(
  /\/$/,
  "",
);

export class ApiError extends Error {
  constructor(

    public status: number,

    public detail: string,

    /** The parsed error body (e.g. a structured 422 ``detail``), when there is one. */

    public body?: unknown,

  ) {
    super(detail);
    this.name = "ApiError";
  }
}

export function detailOf(body: unknown, fallback: string): string {
  if (body && typeof body === "object" && "detail" in body) {
    const d = (body as { detail: unknown }).detail;
    if (typeof d === "string") return d;
    if (Array.isArray(d)) {
      return d
        .map((e) => (e && typeof e === "object" && "msg" in e ? String(e.msg) : JSON.stringify(e)))
        .join("; ");
    }
  }
  return fallback;
}

export interface RequestOptions {
  method?: "GET" | "POST" | "PUT" | "DELETE";
  body?: unknown;
  signal?: AbortSignal;
  /** Send the in-memory step-up token as X-Stepup-Token. */
  stepup?: boolean;
  query?: Record<string, string | number | boolean | null | undefined>;
}

export function buildUrl(path: string, query?: RequestOptions["query"]): string {
  // API_URL may be same-origin relative ("/backend" behind the deploy/hf proxy).
  const base = typeof window === "undefined" ? "http://127.0.0.1" : window.location.origin;
  const url = new URL(path.startsWith("http") ? path : `${API_URL}${path}`, base);
  for (const [k, v] of Object.entries(query ?? {})) {
    if (v !== undefined && v !== null && v !== "") url.searchParams.set(k, String(v));
  }
  return url.toString();
}

export async function authHeaders(stepup = false): Promise<Record<string, string>> {
  const token = getAccessToken() ?? (await refreshAccessToken());
  const h: Record<string, string> = {};
  if (token) h.Authorization = `Bearer ${token}`;
  const s = stepup ? getStepupToken() : null;
  if (s) h["X-Stepup-Token"] = s;
  return h;
}

/** Fetch JSON from the API with the in-memory bearer token. On a 401 it refreshes once

 * (httpOnly cookie via the BFF) and retries; if that fails the session is over. */
export async function api<T>(path: string, opts: RequestOptions = {}): Promise<T> {
  const send = async () =>
    fetch(buildUrl(path, opts.query), {
      method: opts.method ?? "GET",
      headers: {
        ...(opts.body !== undefined ? { "Content-Type": "application/json" } : {}),
        ...(await authHeaders(opts.stepup)),
      },
      body: opts.body !== undefined ? JSON.stringify(opts.body) : undefined,
      signal: opts.signal,
      cache: "no-store",
    });
  let res = await send();
  if (res.status === 401) {
    const token = await refreshAccessToken();
    if (!token) {
      notifySessionExpired();
      throw new ApiError(401, "session expired");
    }
    res = await send();
  }
  const text = await res.text();
  const body: unknown = text ? safeJson(text) : null;
  if (!res.ok) throw new ApiError(res.status, detailOf(body, res.statusText || "request failed"), body);
  return body as T;
}

function safeJson(text: string): unknown {
  try {
    return JSON.parse(text);
  } catch {
    return text;
  }
}