DEV Community

Rahul
Rahul

Posted on

app<lib<app.ts

export type JsonObject = Record;

export type SystemStatus = {
application: { name: string; environment: string; mode: string };
metadata_database: { backend: string; available: boolean; path?: string | null };
oracle: { enabled: boolean; dsn?: string | null; allowed_owners: string[] };
ollama: {
available: boolean;
models?: string[];
base_url?: string;
error?: string | null;
};
chroma: {
available: boolean;
mode?: string;
path?: string | null;
collections?: Record;
error?: string | null;
};
models: Record;
embedding_model: string;
processing_location: string;
access: {
default_role: "analyst";
admin_enabled: boolean;
};
};

export type ModelStatus = {
installed: string[];
available: boolean;
error?: string | null;
configured: Record;
embedding: string;
};

export type AnalysisOptions = {
use_stored_knowledge: boolean;
store_generated_context: boolean;
include_raw_evidence: boolean;
retrieval_threshold: number;
retrieval_depth: number;
model_overrides: Record;
};

export type AnalysisSubmission = {
run_id: string;
status: string;
persistence: "durable" | "transient";
result?: JsonObject | null;
};

export type ApiItem = Record;

const DEFAULT_API_URL =
import.meta.env.VITE_API_URL?.replace(/\/$/, "") ??
"http://127.0.0.1:8000";
const ADMIN_AUTH_HEADER =
import.meta.env.VITE_ADMIN_AUTH_HEADER ?? "X-Admin-Key";
let adminCredential = "";

export class APIError extends Error {
status: number;

constructor(message: string, status = 0) {
super(message);
this.name = "APIError";
this.status = status;
}
}

async function request(
path: string,
init?: RequestInit,
privileged = false,
): Promise {
let response: Response;
try {
response = await fetch(${DEFAULT_API_URL}${path}, {
...init,
headers: {
...(init?.body instanceof FormData
? {}
: { "Content-Type": "application/json" }),
...(privileged && adminCredential
? { [ADMIN_AUTH_HEADER]: adminCredential }
: {}),
...init?.headers,
},
cache: "no-store",
});
} catch {
throw new APIError(
Backend unavailable at ${DEFAULT_API_URL}. Start FastAPI and try again.,
);
}

if (!response.ok) {
let detail = ${response.status} ${response.statusText};
try {
const payload = (await response.json()) as { detail?: string };
detail = payload.detail ?? detail;
} catch {
// Keep the status text when the response is not JSON.
}
throw new APIError(detail, response.status);
}
return (await response.json()) as T;
}

export const api = {
baseUrl: DEFAULT_API_URL,

status: () => request("/api/system/status"),
models: () => request("/api/models"),
authenticateAdmin: async (credential: string) => {
const result = await request<{ role: "admin"; status: string }>(
"/api/auth/admin",
{
method: "POST",
headers: { [ADMIN_AUTH_HEADER]: credential },
},
);
adminCredential = credential;
return result;
},
clearAdminCredential: () => {
adminCredential = "";
},
role: () =>
request<{ role: "analyst" | "admin"; admin_enabled: boolean }>(
"/api/auth/role",
undefined,
true,
),

submitText: (
source: string,
options: AnalysisOptions,
owner?: string,
objectName?: string,
asAdmin = false,
) =>
request("/api/analysis/text", {
method: "POST",
body: JSON.stringify({
source,
owner: owner || null,
object_name: objectName || null,
source_origin: "PASTED",
options,
}),
}, asAdmin),

submitUpload: (
sourceFile: File,
options: AnalysisOptions,
supportingDocument?: File | null,
asAdmin = false,
) => {
const form = new FormData();
form.append("source_file", sourceFile);
form.append("options_json", JSON.stringify(options));
if (supportingDocument) {
form.append("supporting_document", supportingDocument);
}
return request(
"/api/analysis/upload",
{
method: "POST",
body: form,
},
asAdmin,
);
},

submitOracle: (
owner: string,
objectName: string,
objectType: string,
options: AnalysisOptions,
) =>
request(
"/api/analysis/oracle-object",
{
method: "POST",
body: JSON.stringify({
owner,
object_name: objectName,
object_type: objectType,
options,
}),
},
true,
),

run: (runId: string, privileged = false) =>
request(
/api/analysis/${encodeURIComponent(runId)},
undefined,
privileged,
),
events: (runId: string, afterId = 0, privileged = false) =>
request<{ events: ApiItem[] }>(
/api/analysis/${encodeURIComponent(runId)}/events?after_id=${afterId},
undefined,
privileged,
),
cancelRun: (runId: string, privileged = false) =>
request(
/api/analysis/${encodeURIComponent(runId)}/cancel,
{ method: "POST" },
privileged,
),

objects: (limit = 100, offset = 0) =>
request<{ items: ApiItem[] }>(
/api/objects?limit=${limit}&offset=${offset},
undefined,
true,
),
oracleObjects: (owner: string, nameFilter = "") =>
request<{ items: ApiItem[] }>(
/api/oracle/objects?owner=${encodeURIComponent(owner)}${
nameFilter ?
&name_filter=${encodeURIComponent(nameFilter)}: ""
}
,
undefined,
true,
),
dependencies: (objectId: string) =>
request<{ object_id: string; edges: ApiItem[] }>(
/api/objects/${encodeURIComponent(objectId)}/dependencies,
undefined,
true,
),

contexts: (limit = 100, offset = 0) =>
request<{ items: ApiItem[] }>(
/api/contexts?limit=${limit}&offset=${offset},
undefined,
true,
),
reviewContext: (contextId: string, action: "approve" | "reject") =>
request(
/api/context/${encodeURIComponent(contextId)}/${action},
{
method: "POST",
body: JSON.stringify({ reviewer: "react-reviewer" }),
},
true,
),

tableContext: (owner: string, tableName: string) =>
request(
/api/tables/${encodeURIComponent(owner)}/${encodeURIComponent(
tableName,
)}/context
,
undefined,
true,
),

feedback: (
runId: string,
rating: "UP" | "DOWN",
reason = "",
resultId?: string,
) =>
request(
"/api/feedback",
{
method: "POST",
body: JSON.stringify({
run_id: runId,
result_id: resultId || null,
rating,
reason: reason || null,
}),
},
true,
),

ingestSchema: (owner: string, objectFilter = "") =>
request<{ run_id: string }>(
"/api/oracle/ingest-schema",
{
method: "POST",
body: JSON.stringify({
owner,
object_filter: objectFilter || null,
}),
},
true,
),

rebuildChroma: () =>
request(
"/api/admin/rebuild-chroma",
{ method: "POST" },
true,
),
};

export function field(
item: ApiItem | undefined | null,
name: string,
fallback: string,
): string;
export function field(
item: ApiItem | undefined | null,
name: string,
fallback: T,
): T;
export function field(
item: ApiItem | undefined | null,
name: string,
fallback: T,
): T {
if (!item) return fallback;
const value = item[name] ?? item[name.toUpperCase()];
return (value === undefined || value === null ? fallback : value) as T;
}

Top comments (0)