Files
ShellBook/apps/web/src/api.ts
T
Florian Schmidt 845d6c828e feat: chained notebooks with when sections and host blocks (#11)
A notebook can include another one and continue with what it produced:

- core: parse :::when{param=a,b}, ::use{notebook= as= with=} and
  ::host{name= address= user= port= capture=}; composeNotebook namespaces
  an included notebook's params, steps, captures and templates by alias
  (cycles, missing files, depth > 4 and child errors are reported on the
  use line). Defaults may reference captures and builtins
  ({{shellbook.public_key}}); required params and secrets gate only steps
  of their own scope; secretEnv passes a scope's secrets under local names.
- protocol: NotebookResponse gains includes and builtins.
- server: compose includes on load, inject builtins (client values are
  ignored), refuse steps in inactive when sections.
- web: render when/use/host blocks, group included params in the form,
  add a created machine to Hosts and capture its name, reload when an
  included notebook changes, run all checks only for active steps,
  authoring snippets for when, use and host.
2026-11-16 11:42:12 +01:00

125 lines
4.0 KiB
TypeScript

import type {
HostInfo,
HostInventoryResponse,
SaveHostRequest,
NotebookListResponse,
HostsResponse,
NotebookResponse,
SaveNotebookResponse,
StartRunRequest,
StartRunResponse,
ServerEvent,
} from "@shellbook/core";
export class HttpError extends Error {
constructor(
public status: number,
serverMessage?: string,
) {
super(serverMessage || `Request failed (${status})`);
}
}
/** Deliberate errors (4xx, 502, 503) carry a user-facing `message`; unexpected 500s may expose internals. */
async function serverMessage(response: Response): Promise<string | undefined> {
if (response.status === 500) return undefined;
try {
const body = (await response.json()) as { message?: unknown };
return typeof body.message === "string" ? body.message.slice(0, 500) : undefined;
} catch {
return undefined;
}
}
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, await serverMessage(response));
return response.status === 204
? (undefined as T)
: (response.json() as Promise<T>);
}
export interface Api {
create(
path: string,
source: string,
): Promise<{ path: string; version: string }>;
move(
path: string,
target: string,
baseVersion: string,
duplicate?: boolean,
): Promise<{ path: string; version: string }>;
deleteNotebook(path: string, baseVersion: string): Promise<unknown>;
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>;
/** Add a host to the inventory (a notebook's `::host` block); 409 if the name is taken. */
addHost(host: HostInfo): Promise<void>;
events(
receive: (event: ServerEvent) => void,
connection: (connected: boolean) => void,
): () => void;
artifact(runId: string, name: string): string;
}
export const liveApi: Api = {
create: (path, source) => json("/notebooks", "POST", { path, source }),
move: (path, target, baseVersion, duplicate = false) =>
json(
`/notebooks/${encodeURIComponent(path)}/${duplicate ? "duplicate" : "rename"}`,
"POST",
{ path: target, baseVersion },
),
deleteNotebook: (path, baseVersion) =>
json(`/notebooks/${encodeURIComponent(path)}`, "DELETE", { baseVersion }),
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),
async addHost(host) {
const { version } = await json<HostInventoryResponse>("/host-management");
const request: SaveHostRequest = { host, baseVersion: version };
await json("/host-management", "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();
},
};