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
+218
View File
@@ -0,0 +1,218 @@
import { describe, expect, it } from "vitest";
import {
blockActive, scopeActive, composeNotebook, findStep, notebookIncludes, parseNotebook, renderHost,
renderStep, resolveParams, secretEnv, type Block, type Notebook,
} from "../src/index";
const lxc = `---
title: LXC container
params:
proxmox: {type: host, required: true}
hostname: {type: name, required: true}
memory: {type: name, default: "2048"}
ROOTPW: {type: secret}
---
# LXC
Creates {{hostname}}.
\`\`\`sh {run host="{{proxmox}}" id=create capture=address}
pct create --hostname {{hostname}} --memory {{memory}} --key {{shellbook.public_key}} --pw "$ROOTPW"
\`\`\`
:::after{step=create}
Created {{address}}.
:::
::host{name="{{hostname}}" address="{{address}}" capture=host}
`;
const service = `---
title: Web server
params:
target: {type: choice, options: [existing, lxc], default: lxc}
service: {type: name, default: web}
host: {type: host, required: true, default: "{{ct.host}}"}
TOKEN: {type: secret}
---
:::when{target=lxc}
::use{notebook="infra/lxc.md" as=ct with="hostname={{service}}-ct, memory=512"}
:::
\`\`\`sh {run host="{{host}}" id=install}
apt-get install -y nginx
\`\`\`
`;
const files: Record<string, string> = { "infra/lxc.md": lxc, "services/web.md": service };
const load = (path: string) => files[path] === undefined ? undefined : parseNotebook(files[path]!);
const composed = () => composeNotebook("services/web.md", parseNotebook(service), load);
function all(blocks: Block[]): Block[] {
return blocks.flatMap(b => b.type === "markdown" || b.type === "step" || b.type === "host" ? [b] : [b, ...all(b.blocks)]);
}
const hosts = ["pve", "web-ct", "existing"];
describe("directives", () => {
it("parses when, use and host blocks", () => {
const n = parseNotebook(service);
expect(n.diagnostics).toEqual([]);
const when = n.blocks.find(b => b.type === "when");
expect(when).toMatchObject({ type: "when", param: "target", values: ["lxc"] });
expect(when?.type === "when" && when.blocks.find(b => b.type === "use")).toMatchObject({
type: "use", scope: "ct", path: "infra/lxc.md", bindings: { hostname: "{{service}}-ct", memory: "512" }, blocks: [],
});
expect(notebookIncludes(n)).toEqual(["infra/lxc.md"]);
const host = parseNotebook(lxc).blocks.find(b => b.type === "host");
expect(host).toMatchObject({ id: "host-1", name: "{{hostname}}", address: "{{address}}", user: "root", port: "22", capture: "host" });
});
it("reports malformed directives", () => {
const bad = parseNotebook(`---
params:
mode: {type: choice, options: [a, b]}
pw: {type: secret}
---
:::when{mode=c}
:::
:::when{nope=a}
:::
:::when{pw=x}
:::
::use{notebook="../x.md" as=1x}
::use{notebook="a.md" as=shellbook}
::use{notebook="a.md" as=a with="x"}
::use{notebook="a.md" as=a}
::host{name=x}
::host{name=x address=y capture=bad-name extra=1}
::use{broken
`);
// Invalid include paths are reported but never handed to the loader.
expect(notebookIncludes(bad)).toEqual(["a.md"]);
const loaded: string[] = [];
composeNotebook("bad.md", bad, p => { loaded.push(p); return undefined; });
expect(loaded).not.toContain("../x.md");
const messages = bad.diagnostics.map(d => d.message);
expect(messages).toEqual(expect.arrayContaining([
"when value is not an option of mode: c",
"when references unknown parameter: nope",
"when cannot test a secret",
'use requires notebook="dir/name.md" (relative to notebooks/)',
"use requires as=alias (letters, digits, _; not shellbook)",
"with requires name=value pairs",
"Duplicate use alias: a",
"host requires name and address",
"Invalid capture name",
"Unknown host attribute: extra",
"Malformed or unexpected directive",
]));
});
});
describe("composeNotebook", () => {
it("namespaces the included notebook and applies with bindings", () => {
const n = composed();
expect(n.diagnostics).toEqual([]);
expect(n.params.map(p => [p.name, p.scope, p.default])).toEqual([
["target", undefined, "lxc"], ["service", undefined, "web"], ["host", undefined, "{{ct.host}}"], ["TOKEN", undefined, undefined],
["ct.proxmox", "ct", undefined], ["ct.hostname", "ct", "{{service}}-ct"], ["ct.memory", "ct", "512"], ["ct.ROOTPW", "ct", undefined],
]);
const create = findStep(n.blocks, "ct.create")!;
expect(create.attrs).toMatchObject({ host: "{{ct.proxmox}}", capture: "ct.address", scope: "ct" });
expect(create.script).toBe('pct create --hostname {{ct.hostname}} --memory {{ct.memory}} --key {{shellbook.public_key}} --pw "$ROOTPW"\n');
const blocks = all(n.blocks);
expect(blocks.find(b => b.type === "after")).toMatchObject({ stepId: "ct.create" });
expect(blocks.find(b => b.type === "host")).toMatchObject({ id: "ct.host-1", scope: "ct", name: "{{ct.hostname}}", capture: "ct.host" });
expect(blocks.find(b => b.type === "use")).toMatchObject({ title: "LXC container", scope: "ct" });
expect(blocks.some(b => b.type === "markdown" && b.text.includes("Creates {{ct.hostname}}."))).toBe(true);
});
it("namespaces nested includes by alias path", () => {
const nested = { ...files, "outer.md": '::use{notebook="services/web.md" as=svc}\n' };
const n = composeNotebook("outer.md", parseNotebook(nested["outer.md"]), p => nested[p as keyof typeof nested] === undefined ? undefined : parseNotebook(nested[p as keyof typeof nested]!));
expect(n.diagnostics).toEqual([]);
expect(n.params.find(p => p.name === "svc.ct.hostname")).toMatchObject({ scope: "svc.ct", default: "{{svc.service}}-ct" });
expect(n.params.find(p => p.name === "svc.host")).toMatchObject({ scope: "svc", default: "{{svc.ct.host}}" });
expect(findStep(n.blocks, "svc.ct.create")?.attrs.scope).toBe("svc.ct");
});
it("reports missing files, cycles, depth, child errors and bad bindings on the use line", () => {
const cases: Record<string, string> = {
"a.md": '\n::use{notebook="b.md" as=b}\n',
"b.md": '::use{notebook="a.md" as=a}\n',
"missing.md": '::use{notebook="nowhere.md" as=x}\n',
"broken.md": '::use{notebook="bad.md" as=x}\n',
"bad.md": "```sh {run bogus}\nx\n```\n",
"bind.md": '::use{notebook="infra/lxc.md" as=x with="nope=1,ROOTPW=2"}\n',
"d0.md": '::use{notebook="d1.md" as=a}\n', "d1.md": '::use{notebook="d2.md" as=a}\n', "d2.md": '::use{notebook="d3.md" as=a}\n',
"d3.md": '::use{notebook="d4.md" as=a}\n', "d4.md": '::use{notebook="d5.md" as=a}\n', "d5.md": "# deep\n",
...files,
};
const get = (p: string) => cases[p] === undefined ? undefined : parseNotebook(cases[p]!);
const errors = (p: string) => composeNotebook(p, get(p)!, get).diagnostics;
expect(errors("a.md")).toEqual([expect.objectContaining({ line: 2, message: expect.stringContaining("Notebook include cycle: a.md -> b.md -> a.md") })]);
expect(errors("missing.md")).toEqual([{ severity: "error", line: 1, message: "Included notebook not found: nowhere.md" }]);
expect(errors("broken.md")[0]?.message).toBe("bad.md:1: Unknown attribute: bogus");
expect(errors("bind.md").map(d => d.message)).toEqual([
"with binds unknown parameter of infra/lxc.md: nope", "with cannot bind secret ROOTPW; enter it in the form",
]);
expect(errors("d0.md").map(d => d.message).join()).toContain("nested deeper than 4");
});
});
describe("rendering chained notebooks", () => {
const values = { target: "lxc", "ct.proxmox": "pve", "ct.ROOTPW": "pw-secret", TOKEN: "tok" };
const runtime = { "shellbook.public_key": "ssh-ed25519 AAAA shellbook" };
it("renders included steps with bindings, builtins and shell quoting", () => {
const n = composed();
const r = renderStep(n, findStep(n.blocks, "ct.create")!, resolveParams(n, values, hosts, runtime).values, runtime, hosts);
expect(r).toMatchObject({ host: "pve", missing: [], invalid: {} });
expect(r.script).toBe("pct create --hostname web-ct --memory 512 --key 'ssh-ed25519 AAAA shellbook' --pw \"$ROOTPW\"\n");
});
it("gates required params per scope and resolves defaults from captures", () => {
const n = composed();
const before = resolveParams(n, values, hosts, runtime);
expect(before.errors.host).toBe("Available after the step that sets ct.host");
// The parent's missing host does not block the included notebook's steps ...
expect(renderStep(n, findStep(n.blocks, "ct.create")!, before.values, runtime, hosts).missing).toEqual([]);
// ... but blocks the parent's own steps until the container is in Hosts.
expect(renderStep(n, findStep(n.blocks, "install")!, before.values, runtime, hosts).missing).toContain("host");
const after = resolveParams(n, values, hosts, { ...runtime, "ct.host": "web-ct" });
expect(after.values.host).toBe("web-ct");
expect(renderStep(n, findStep(n.blocks, "install")!, after.values, { "ct.host": "web-ct" }, hosts)).toMatchObject({ host: "web-ct", missing: [], invalid: {} });
// An included required param blocks only its own scope.
const empty = resolveParams(n, { target: "lxc" }, hosts, runtime).values;
expect(renderStep(n, findStep(n.blocks, "ct.create")!, empty, runtime, hosts).missing).toContain("ct.proxmox");
expect(renderStep(n, findStep(n.blocks, "install")!, { ...empty, host: "existing" }, runtime, hosts).missing).toEqual([]);
});
it("activates when sections by resolved choice", () => {
const n = composed();
expect(blockActive(n, "ct.create", { target: "lxc" })).toBe(true);
expect(blockActive(n, "ct.host-1", { target: "lxc" })).toBe(true);
expect(blockActive(n, "ct.create", { target: "existing" })).toBe(false);
expect(blockActive(n, "install", { target: "existing" })).toBe(true);
expect(blockActive(n, "unknown", {})).toBe(false);
expect(scopeActive(n, "", {})).toBe(true);
expect(scopeActive(n, "ct", { target: "lxc" })).toBe(true);
expect(scopeActive(n, "ct", { target: "existing" })).toBe(false);
expect(scopeActive(n, "nope", { target: "lxc" })).toBe(false);
});
it("passes secrets only to their own scope under the local name", () => {
const n = composed();
expect(secretEnv(n, values, "ct")).toEqual({ ROOTPW: "pw-secret" });
expect(secretEnv(n, values)).toEqual({ TOKEN: "tok" });
});
it("resolves and validates host blocks", () => {
const n = composed();
const block = all(n.blocks).find(b => b.type === "host") as Extract<Block, { type: "host" }>;
const rv = resolveParams(n, values, hosts, runtime).values;
expect(renderHost(n, block, rv, runtime, hosts)).toMatchObject({ name: "web-ct", missing: ["ct.address"] });
expect(renderHost(n, block, rv, { "ct.address": "10.0.30.160" }, hosts)).toEqual({
id: "ct.host-1", name: "web-ct", address: "10.0.30.160", user: "root", port: 22, missing: [], invalid: {},
});
const bad: Notebook = parseNotebook('::host{name="a b" address="x y" user=r/oot port=0}\n');
expect(Object.keys(renderHost(bad, bad.blocks[0] as Extract<Block, { type: "host" }>, {}, {}, []).invalid).sort()).toEqual(["address", "name", "port", "user"]);
});
});