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.
This commit is contained in:
Florian Schmidt
2026-11-16 11:42:12 +01:00
parent 28e806d641
commit 845d6c828e
24 changed files with 1407 additions and 136 deletions
+72 -2
View File
@@ -3,6 +3,10 @@ import type { Block, Notebook, ParamDef, Step, StepAttrs } from "./types";
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === "object" && !Array.isArray(v);
const paramTypes = new Set(["host", "name", "path", "string", "choice", "secret"]);
const identifier = /^[A-Za-z_][A-Za-z0-9_]*$/;
/** Workspace notebook path relative to notebooks/: forward slashes, no `..`, Markdown only. */
export const includePath = (value: string) =>
/^[^\\\0\r\n:]+\.md$/.test(value) && value.split("/").every(part => part && part !== "." && part !== "..");
/** Small attribute scanner: quoted values may contain whitespace, braces and escaped quotes. */
function attributes(text: string, error: (message: string) => void): Map<string, (string | true)[]> {
@@ -90,7 +94,9 @@ export function parseNotebook(source: string): Notebook {
}
const ids = new Set<string>();
const afterRefs: { id: string; line: number }[] = [];
const aliases = new Set<string>();
let stepNumber = 0;
let hostNumber = 0;
let heading: string | undefined;
let i = start;
const parseBlocks = (nested: boolean, depth = 0): Block[] => {
@@ -118,6 +124,70 @@ export function parseNotebook(source: string): Notebook {
blocks.push({ type: "after", stepId: id, onFailure: attrs.has("failed"), blocks: children, range: { startLine: begin + 1, endLine: i } });
markdownStart = i; continue;
}
const when = /^\s{0,3}:::when\{(.*)\}\s*$/.exec(line);
if (when && depth < 100) {
flush(); const begin = i++;
const attrs = attributes(when[1]!, m => error(m, begin + 1));
const [param, raw] = [...attrs][0] ?? [];
const value = raw?.[0];
if (attrs.size !== 1 || typeof value !== "string") error("when requires exactly one param=value[,value]", begin + 1);
const values = typeof value === "string" ? value.split(",").map(v => v.trim()).filter(Boolean) : [];
const def = notebook.params.find(p => p.name === param);
if (param && !def) error(`when references unknown parameter: ${param}`, begin + 1);
else if (def?.type === "secret") error("when cannot test a secret", begin + 1);
else if (def?.options) for (const v of values) if (!def.options.includes(v)) error(`when value is not an option of ${param}: ${v}`, begin + 1);
const children = parseBlocks(true, depth + 1);
if (i === lines.length) error("Unclosed when container", begin + 1);
else i++;
blocks.push({ type: "when", param: param ?? "", values, blocks: children, range: { startLine: begin + 1, endLine: i } });
markdownStart = i; continue;
}
const leaf = /^\s{0,3}::(use|host)\{(.*)\}\s*$/.exec(line);
if (leaf) {
flush();
const lineNo = i + 1;
const attrs = attributes(leaf[2]!, m => error(m, lineNo));
const get = (key: string): string | undefined => {
const v = attrs.get(key);
if (v && (v.length > 1 || v[0] === true)) error(`${key} requires one value`, lineNo);
return typeof v?.[0] === "string" ? v[0] : undefined;
};
const range = { startLine: lineNo, endLine: lineNo };
if (leaf[1] === "use") {
for (const key of attrs.keys()) if (!["notebook", "as", "with"].includes(key)) error(`Unknown use attribute: ${key}`, lineNo);
const path = get("notebook") ?? "";
const alias = get("as") ?? "";
if (!includePath(path)) error('use requires notebook="dir/name.md" (relative to notebooks/)', lineNo);
if (!identifier.test(alias) || alias === "shellbook") error("use requires as=alias (letters, digits, _; not shellbook)", lineNo);
else if (aliases.has(alias)) error(`Duplicate use alias: ${alias}`, lineNo);
aliases.add(alias);
const bindings = Object.create(null) as Record<string, string>;
for (const value of attrs.get("with") ?? []) {
if (value === true) { error("with requires name=value pairs", lineNo); continue; }
// Values may contain commas; a new binding starts only at ",name=".
for (const pair of value.split(/,(?=\s*[A-Za-z_][A-Za-z0-9_]*\s*=)/)) {
const eq = pair.indexOf("=");
const name = pair.slice(0, Math.max(eq, 0)).trim();
if (eq <= 0 || !identifier.test(name)) error("with requires name=value pairs", lineNo);
else if (Object.hasOwn(bindings, name)) error(`Duplicate with binding: ${name}`, lineNo);
else bindings[name] = pair.slice(eq + 1).trim();
}
}
blocks.push({ type: "use", scope: alias, path, bindings, blocks: [], range });
} else {
hostNumber++;
for (const key of attrs.keys()) if (!["id", "name", "address", "user", "port", "capture"].includes(key)) error(`Unknown host attribute: ${key}`, lineNo);
const id = get("id") || `host-${hostNumber}`;
if (ids.has(id)) error(`Duplicate step id: ${id}`, lineNo);
ids.add(id);
const name = get("name"), address = get("address");
if (!name || !address) error("host requires name and address", lineNo);
const capture = get("capture");
if (capture !== undefined && !identifier.test(capture)) error("Invalid capture name", lineNo);
blocks.push({ type: "host", id, name: name ?? "", address: address ?? "", user: get("user") ?? "root", port: get("port") ?? "22", capture, range });
}
i++; markdownStart = i; continue;
}
const fence = /^ {0,3}(`{3,}|~{3,})(.*)$/.exec(line);
if (fence) {
const begin = i;
@@ -166,7 +236,7 @@ export function parseNotebook(source: string): Notebook {
}
if (kind === "check" && (attrs.has("artifacts") || attrs.has("upload"))) error("Checks cannot declare artifacts or uploads", begin + 1);
const capture = get("capture");
if (capture && !/^[A-Za-z_][A-Za-z0-9_]*$/.test(capture)) error("Invalid capture name", begin + 1);
if (capture && !identifier.test(capture)) error("Invalid capture name", begin + 1);
const step: Step = {
kind,
lang: match[1]!,
@@ -186,7 +256,7 @@ export function parseNotebook(source: string): Notebook {
i = end < lines.length ? end + 1 : end; markdownStart = i; continue;
}
heading ??= /^ {0,3}#\s+(.+?)\s*#*\s*$/.exec(line)?.[1];
if (/^\s*:::/.test(line)) error("Malformed or unexpected directive", i + 1);
if (/^\s*:::/.test(line) || /^\s{0,3}::(use|host)\b/.test(line)) error("Malformed or unexpected directive", i + 1);
i++;
}
flush(); return blocks;