81 lines
2.4 KiB
TypeScript
81 lines
2.4 KiB
TypeScript
import type {
|
|
NotebookListResponse,
|
|
HostsResponse,
|
|
NotebookResponse,
|
|
SaveNotebookResponse,
|
|
StartRunRequest,
|
|
StartRunResponse,
|
|
ServerEvent,
|
|
} from "@shellbook/core";
|
|
|
|
export class HttpError extends Error {
|
|
constructor(public status: number) {
|
|
super(`Request failed (${status})`);
|
|
}
|
|
}
|
|
export async function json<T>(
|
|
path: string,
|
|
method = "GET",
|
|
body?: unknown,
|
|
): Promise<T> {
|
|
const response = await fetch(`/api${path}`, {
|
|
method,
|
|
credentials: "same-origin",
|
|
headers: body === undefined ? {} : { "Content-Type": "application/json" },
|
|
body: body === undefined ? undefined : JSON.stringify(body),
|
|
});
|
|
if (!response.ok) throw new HttpError(response.status);
|
|
return response.status === 204
|
|
? (undefined as T)
|
|
: (response.json() as Promise<T>);
|
|
}
|
|
export interface Api {
|
|
me(): Promise<unknown>;
|
|
login(password: string): Promise<unknown>;
|
|
list(): Promise<NotebookListResponse>;
|
|
hosts(): Promise<HostsResponse>;
|
|
notebook(path: string): Promise<NotebookResponse>;
|
|
save(
|
|
path: string,
|
|
source: string,
|
|
baseVersion: string,
|
|
): Promise<SaveNotebookResponse>;
|
|
run(request: StartRunRequest): Promise<StartRunResponse>;
|
|
events(
|
|
receive: (event: ServerEvent) => void,
|
|
connection: (connected: boolean) => void,
|
|
): () => void;
|
|
artifact(runId: string, name: string): string;
|
|
}
|
|
export const liveApi: Api = {
|
|
me: () => json("/auth/me"),
|
|
login: (password) => json("/auth/login", "POST", { password }),
|
|
list: () => json("/notebooks"),
|
|
hosts: () => json("/hosts"),
|
|
notebook: (path) => json(`/notebooks/${encodeURIComponent(path)}`),
|
|
save: (path, source, baseVersion) =>
|
|
json(`/notebooks/${encodeURIComponent(path)}`, "PUT", {
|
|
source,
|
|
baseVersion,
|
|
}),
|
|
run: (request) => json("/runs", "POST", request),
|
|
artifact: (id, name) =>
|
|
`/api/runs/${encodeURIComponent(id)}/artifacts/${encodeURIComponent(name)}`,
|
|
events(receive, connection) {
|
|
const ws = new WebSocket(
|
|
`${location.protocol === "https:" ? "wss:" : "ws:"}//${location.host}/api/events`,
|
|
);
|
|
ws.onopen = () => connection(true);
|
|
ws.onclose = () => connection(false);
|
|
ws.onerror = () => connection(false);
|
|
ws.onmessage = (message) => {
|
|
try {
|
|
receive(JSON.parse(String(message.data)) as ServerEvent);
|
|
} catch {
|
|
connection(false);
|
|
}
|
|
};
|
|
return () => ws.close();
|
|
},
|
|
};
|