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
+191
View File
@@ -0,0 +1,191 @@
// Chained notebooks (`::use`): pure composition. The server loads the files; core only
// namespaces and merges them, so display and execution keep using one notebook model.
import type { Block, Diagnostic, Notebook, ParamDef, ParamValues, Step } from "./types";
import { includePath } from "./parser";
const template = /\{\{\s*([^{}]+?)\s*\}\}/g;
/** Maximum `::use` nesting (root -> a -> b -> c -> d). */
export const MAX_INCLUDE_DEPTH = 4;
/** Runtime names provided by the server, never namespaced: {{shellbook.public_key}}. */
export const isBuiltin = (name: string) => name.startsWith("shellbook.");
/** Workspace paths a notebook includes directly, in document order. Invalid paths never reach I/O. */
export function notebookIncludes(notebook: Notebook): string[] {
const paths: string[] = [];
const walk = (blocks: Block[]) => {
for (const block of blocks) {
if (block.type === "use" && !block.blocks.length) { if (includePath(block.path)) paths.push(block.path); }
else if (block.type === "after" || block.type === "when" || block.type === "use") walk(block.blocks);
}
};
walk(notebook.blocks);
return [...new Set(paths)];
}
const qualify = (alias: string, name: string) => `${alias}.${name}`;
const rewrite = (text: string, alias: string) =>
text.replace(template, (match, name: string) => isBuiltin(name) ? match : `{{${qualify(alias, name)}}}`);
const scoped = (alias: string, scope?: string) => scope ? qualify(alias, scope) : alias;
function prefixStep(step: Step, alias: string): Step {
const a = step.attrs;
return {
...step,
script: rewrite(step.script, alias),
attrs: {
...a,
id: qualify(alias, a.id),
host: a.host === undefined ? undefined : rewrite(a.host, alias),
capture: a.capture === undefined ? undefined : qualify(alias, a.capture),
artifacts: a.artifacts.map(x => rewrite(x, alias)),
uploads: a.uploads.map(u => ({ src: rewrite(u.src, alias), dst: rewrite(u.dst, alias) })),
scope: scoped(alias, a.scope),
},
};
}
/** Namespace a composed notebook's blocks under alias (names, ids, templates, scopes). */
function prefixBlocks(blocks: Block[], alias: string): Block[] {
return blocks.map((block): Block => {
switch (block.type) {
case "markdown": return { ...block, text: rewrite(block.text, alias) };
case "step": return { type: "step", step: prefixStep(block.step, alias) };
case "after": return { ...block, stepId: qualify(alias, block.stepId), blocks: prefixBlocks(block.blocks, alias) };
case "when": return { ...block, param: qualify(alias, block.param), blocks: prefixBlocks(block.blocks, alias) };
case "use": return { ...block, scope: qualify(alias, block.scope), bindings: {}, blocks: prefixBlocks(block.blocks, alias) };
case "host": return {
...block, id: qualify(alias, block.id), scope: scoped(alias, block.scope),
name: rewrite(block.name, alias), address: rewrite(block.address, alias),
user: rewrite(block.user, alias), port: rewrite(block.port, alias),
capture: block.capture === undefined ? undefined : qualify(alias, block.capture),
};
}
});
}
function prefixParam(def: ParamDef, alias: string): ParamDef {
return {
...def,
name: qualify(alias, def.name),
default: def.default === undefined ? undefined : rewrite(def.default, alias),
scope: scoped(alias, def.scope),
};
}
/** Every step and host id in composed blocks (for duplicate detection). */
function blockIds(blocks: Block[], into: string[] = []): string[] {
for (const block of blocks) {
if (block.type === "step") into.push(block.step.attrs.id);
else if (block.type === "host") into.push(block.id);
else if (block.type !== "markdown") blockIds(block.blocks, into);
}
return into;
}
/**
* Resolve `::use` blocks: the included notebook's params, steps, captures and ids are
* namespaced by its alias ("ct.hostname") and merged into one notebook. `with` bindings
* become the included params' defaults in the including notebook's namespace.
* Missing files, cycles, nesting deeper than MAX_INCLUDE_DEPTH and errors inside an
* included notebook become error diagnostics on the `::use` line.
*/
export function composeNotebook(path: string, notebook: Notebook, load: (path: string) => Notebook | undefined): Notebook {
return compose(path, notebook, load, [path]);
}
function compose(path: string, notebook: Notebook, load: (path: string) => Notebook | undefined, stack: string[]): Notebook {
const diagnostics: Diagnostic[] = [...notebook.diagnostics];
const params: ParamDef[] = [...notebook.params];
const fail = (message: string, line: number) => diagnostics.push({ severity: "error", message, line });
const resolve = (blocks: Block[]): Block[] => blocks.map((block): Block => {
if (block.type === "after" || block.type === "when") return { ...block, blocks: resolve(block.blocks) };
if (block.type !== "use") return block;
const line = block.range.startLine;
// The parser already reported an invalid path; never hand it to the loader.
if (!includePath(block.path)) return block;
if (stack.includes(block.path)) { fail(`Notebook include cycle: ${[...stack, block.path].join(" -> ")}`, line); return block; }
if (stack.length > MAX_INCLUDE_DEPTH) { fail(`Notebook includes are nested deeper than ${MAX_INCLUDE_DEPTH}`, line); return block; }
const loaded = load(block.path);
if (!loaded) { fail(`Included notebook not found: ${block.path}`, line); return block; }
const child = compose(block.path, loaded, load, [...stack, block.path]);
for (const d of child.diagnostics) if (d.severity === "error") fail(`${block.path}${d.line ? `:${d.line}` : ""}: ${d.message}`, line);
const alias = block.scope;
for (const [name, value] of Object.entries(block.bindings)) {
const def = child.params.find(p => p.name === name && !p.scope);
if (!def) fail(`with binds unknown parameter of ${block.path}: ${name}`, line);
else if (def.type === "secret") fail(`with cannot bind secret ${name}; enter it in the form`, line);
}
for (const def of child.params) {
const prefixed = prefixParam(def, alias);
// Bindings are templates in the including notebook's namespace: not rewritten.
if (!def.scope && def.type !== "secret" && Object.hasOwn(block.bindings, def.name)) prefixed.default = block.bindings[def.name];
params.push(prefixed);
}
return { ...block, title: child.title, bindings: { ...block.bindings }, blocks: prefixBlocks(child.blocks, alias) };
});
const blocks = resolve(notebook.blocks);
const seen = new Set<string>();
for (const id of blockIds(blocks)) {
if (seen.has(id) && id.includes(".")) fail(`Duplicate step id after including notebooks: ${id}`, 1);
seen.add(id);
}
return { ...notebook, params, blocks, diagnostics };
}
/** Find a step anywhere in the block tree (after, when and use containers). */
export function findStep(blocks: Block[], id: string): Step | undefined {
for (const block of blocks) {
if (block.type === "step" && block.step.attrs.id === id) return block.step;
if (block.type === "after" || block.type === "when" || block.type === "use") {
const found = findStep(block.blocks, id);
if (found) return found;
}
}
}
/**
* Whether a step or host block is shown and runnable: every enclosing `:::when` must match
* the resolved parameter values. `:::after` only gates display, not execution.
*/
export function blockActive(notebook: Notebook, id: string, values: ParamValues): boolean {
const walk = (blocks: Block[], active: boolean): boolean | undefined => {
for (const block of blocks) {
if (block.type === "step" && block.step.attrs.id === id) return active;
if (block.type === "host" && block.id === id) return active;
if (block.type === "when") {
const found = walk(block.blocks, active && block.values.includes(values[block.param] ?? ""));
if (found !== undefined) return found;
} else if (block.type === "after" || block.type === "use") {
const found = walk(block.blocks, active);
if (found !== undefined) return found;
}
}
return undefined;
};
return walk(notebook.blocks, true) ?? false;
}
/** Whether an included notebook's scope ("ct", "svc.ct") is active, i.e. its `::use` lies in matching `:::when` sections. The root scope ("") always is. */
export function scopeActive(notebook: Notebook, scope: string, values: ParamValues): boolean {
if (!scope) return true;
const walk = (blocks: Block[], active: boolean): boolean | undefined => {
for (const block of blocks) {
if (block.type === "use" && block.scope === scope) return active;
if (block.type === "markdown" || block.type === "step" || block.type === "host") continue;
const found = walk(block.blocks, active && (block.type !== "when" || block.values.includes(values[block.param] ?? "")));
if (found !== undefined) return found;
}
return undefined;
};
return walk(notebook.blocks, true) ?? false;
}
/** Runtime names that steps or host blocks of the notebook set (`capture=`). */
export function captureNames(blocks: Block[], into = new Set<string>()): Set<string> {
for (const block of blocks) {
if (block.type === "step" && block.step.attrs.capture) into.add(block.step.attrs.capture);
else if (block.type === "host" && block.capture) into.add(block.capture);
else if (block.type !== "markdown" && block.type !== "step" && block.type !== "host") captureNames(block.blocks, into);
}
return into;
}
+82 -27
View File
@@ -1,8 +1,10 @@
// Public API of @shellbook/core. Pure functions, no I/O.
import type { Notebook, ParamValues, RenderedStep, Step } from "./types";
import type { Block, Notebook, ParamValues, RenderedHost, RenderedStep, Step } from "./types";
import { captureNames, isBuiltin } from "./compose";
export type * from "./types";
export type * from "./protocol";
export { parseNotebook } from "./parser";
export { parseNotebook, includePath } from "./parser";
export { composeNotebook, notebookIncludes, findStep, blockActive, scopeActive, captureNames, isBuiltin, MAX_INCLUDE_DEPTH } from "./compose";
const template = /\{\{\s*([^{}]+?)\s*\}\}/g;
const own = (object: object, key: string) => Object.hasOwn(object, key);
@@ -17,15 +19,20 @@ export function shellQuote(value: string): string {
return /^[A-Za-z0-9._/@:=+\-]+$/.test(value) ? value : `'${value.replace(/'/g, "'\\''")}'`;
}
/** Resolve defaults ({{other}} references) and validate all params by type. */
/**
* Resolve defaults ({{other}} references) and validate all params by type. Defaults may
* also reference runtime values (captures such as {{ct.host}}, builtins {{shellbook.*}}).
*/
export function resolveParams(
notebook: Notebook,
values: ParamValues,
hostNames: readonly string[],
runtime: ParamValues = {},
): { values: ParamValues; errors: Record<string, string> } {
const effective = dictionary();
const errors = dictionary();
const defs = new Map(notebook.params.map(def => [def.name, def]));
const captures = captureNames(notebook.blocks);
const active = new Set<string>();
const resolve = (name: string): string => {
if (own(effective, name)) return effective[name]!;
@@ -34,9 +41,14 @@ export function resolveParams(
if (active.has(name)) { errors[name] = "Cyclic parameter default"; return ""; }
active.add(name);
let value = own(values, name) ? values[name] ?? "" : "";
let pending = false;
if (!value && def.type !== "secret" && def.default !== undefined) {
value = def.default.replace(template, (match, ref: string) => {
const other = defs.get(ref);
if (!other && (captures.has(ref) || isBuiltin(ref))) {
if (own(runtime, ref) && runtime[ref]) return runtime[ref]!;
errors[name] = `Available after the step that sets ${ref}`; pending = true; return match;
}
if (!other) { errors[name] = `Unknown default reference: ${ref}`; return match; }
if (other.type === "secret") { errors[name] = "Defaults cannot reference secrets"; return match; }
const resolved = resolve(ref);
@@ -46,6 +58,8 @@ export function resolveParams(
});
}
active.delete(name);
// A default still waiting for a captured value is empty, not its literal template.
if (pending) value = "";
effective[name] = value;
if (!value) {
if (def.required) errors[name] ??= "Required parameter is missing";
@@ -63,6 +77,42 @@ export function resolveParams(
return { values: effective, errors };
}
/**
* Shared template substitution for steps and host blocks. Required params gate only
* blocks of their own scope: an included notebook's form does not block the parent.
*/
function substitution(notebook: Notebook, scope: string | undefined, values: ParamValues, runtime: ParamValues, hostNames: readonly string[]) {
const resolved = resolveParams(notebook, values, hostNames, runtime);
const captures = captureNames(notebook.blocks);
const defs = new Map(notebook.params.map(def => [def.name, def]));
const invalid = dictionary();
const missing = new Set<string>();
for (const def of notebook.params) {
if ((def.scope ?? "") !== (scope ?? "")) continue;
if (def.required && !resolved.values[def.name]) missing.add(def.name);
if ((def.required || def.type === "secret") && resolved.values[def.name]
&& own(resolved.errors, def.name)) invalid[def.name] = resolved.errors[def.name]!;
}
const substitute = (text: string, script: boolean): string => text.replace(template, (match, name: string) => {
const def = defs.get(name);
if (def?.type === "secret") { invalid[name] = "Secrets must be referenced as environment variables"; return match; }
if (!def && !own(runtime, name)) {
// A capture that has not run yet (or a builtin) is pending, not a typo.
if (captures.has(name) || isBuiltin(name)) missing.add(name);
else invalid[name] = "Unknown parameter or runtime value";
return match;
}
const value = def ? resolved.values[name] : runtime[name];
if (def && own(resolved.errors, name)) invalid[name] = resolved.errors[name]!;
if (!value) { missing.add(name); return match; }
if (value.includes("\0")) { invalid[name] = "Value cannot contain NUL"; return match; }
// Never interpolate values with validation errors into scripts or metadata.
if (own(invalid, name)) return match;
return script ? shellQuote(value) : value;
});
return { substitute, invalid, missing };
}
/**
* The single script substitution path: display and execution consume this result.
* Attributes use raw substitution and separate validation; secrets are env-only.
@@ -74,27 +124,7 @@ export function renderStep(
runtime: ParamValues,
hostNames: readonly string[],
): RenderedStep {
const resolved = resolveParams(notebook, values, hostNames);
const defs = new Map(notebook.params.map(def => [def.name, def]));
const invalid = dictionary();
const missing = new Set<string>();
for (const def of notebook.params) {
if (def.required && !resolved.values[def.name]) missing.add(def.name);
if ((def.required || def.type === "secret") && resolved.values[def.name]
&& own(resolved.errors, def.name)) invalid[def.name] = resolved.errors[def.name]!;
}
const substitute = (text: string, script: boolean): string => text.replace(template, (match, name: string) => {
const def = defs.get(name);
if (def?.type === "secret") { invalid[name] = "Secrets must be referenced as environment variables"; return match; }
if (!def && !own(runtime, name)) { invalid[name] = "Unknown parameter or runtime value"; return match; }
const value = def ? resolved.values[name] : runtime[name];
if (def && own(resolved.errors, name)) invalid[name] = resolved.errors[name]!;
if (!value) { missing.add(name); return match; }
if (value.includes("\0")) { invalid[name] = "Value cannot contain NUL"; return match; }
// Never interpolate values with validation errors into scripts or metadata.
if (own(invalid, name)) return match;
return script ? shellQuote(value) : value;
});
const { substitute, invalid, missing } = substitution(notebook, step.attrs.scope, values, runtime, hostNames);
const script = substitute(step.script, true);
const host = step.attrs.local || step.attrs.host === undefined ? undefined : substitute(step.attrs.host, false);
if (!step.attrs.local && (!host || !hostNames.includes(host))) invalid.host ??= "Unknown or missing target host";
@@ -113,15 +143,40 @@ export function renderStep(
return { stepId: step.attrs.id, kind: step.kind, host, local: step.attrs.local, script, artifacts, uploads, missing: [...missing], invalid };
}
/** Resolve a `::host` block with the same rules as hosts.yaml entries. */
export function renderHost(
notebook: Notebook,
block: Extract<Block, { type: "host" }>,
values: ParamValues,
runtime: ParamValues,
hostNames: readonly string[],
): RenderedHost {
const { substitute, invalid, missing } = substitution(notebook, block.scope, values, runtime, hostNames);
const name = substitute(block.name, false), address = substitute(block.address, false);
const user = substitute(block.user, false), portText = substitute(block.port, false);
const port = Number(portText);
if (!/^[A-Za-z0-9._-]+$/.test(name)) invalid.name ??= "Host name may only contain letters, digits, ., _ or -";
if (!address || /[\s\0]/.test(address)) invalid.address ??= "Address cannot be empty or contain whitespace";
if (!/^[A-Za-z0-9._-]+$/.test(user)) invalid.user ??= "User may only contain letters, digits, ., _ or -";
if (!Number.isInteger(port) || port < 1 || port > 65535) invalid.port ??= "Port must be 1-65535";
return { id: block.id, name, address, user, port, missing: [...missing], invalid };
}
/** Substitute prose without quoting; secrets always appear masked. */
export function renderText(text: string, values: ParamValues, notebook: Notebook): string {
const secrets = new Set(notebook.params.filter(def => def.type === "secret").map(def => def.name));
return text.replace(template, (match, name: string) => secrets.has(name) ? "••••" : own(values, name) ? values[name]! : match);
}
/** Env vars for a run: every secret param under its exact name. Server-side only. */
export function secretEnv(notebook: Notebook, values: ParamValues): Record<string, string> {
/**
* Env vars for a run: the secrets of the step's scope under their local name
* (an included notebook's `ct.TOKEN` is `$TOKEN` in its own steps). Server-side only.
*/
export function secretEnv(notebook: Notebook, values: ParamValues, scope?: string): Record<string, string> {
const env = dictionary();
for (const def of notebook.params) if (def.type === "secret" && own(values, def.name)) env[def.name] = values[def.name]!;
for (const def of notebook.params) {
if (def.type !== "secret" || (def.scope ?? "") !== (scope ?? "") || !own(values, def.name)) continue;
env[def.scope ? def.name.slice(def.scope.length + 1) : def.name] = values[def.name]!;
}
return env;
}
+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;
+9
View File
@@ -35,8 +35,17 @@ export interface NotebookListResponse {
// GET /api/notebooks/:path (path URL-encoded)
export interface NotebookResponse {
path: string;
/** The notebook's own Markdown (what the editor saves). */
source: string;
/** Parsed and composed: `::use` blocks contain the included notebooks (namespaced). */
notebook: Notebook;
/** Workspace paths of all included notebooks (reload when one of them changes). */
includes: string[];
/**
* Server-provided runtime values, e.g. "shellbook.public_key". The server sets them on
* every run itself; clients merge them into the runtime they render with.
*/
builtins: ParamValues;
/** Opaque version for optimistic concurrency on save. */
version: string;
}
+57
View File
@@ -13,6 +13,11 @@ export interface ParamDef {
label?: string;
/** Only for type "choice". */
options?: string[];
/**
* Set for params of an included notebook (`::use`): the alias path ("ct", "ct.base").
* The name is then prefixed ("ct.hostname"); a secret's env var keeps the local name.
*/
scope?: string;
}
/** Param name -> current value. Missing key or "" means "not filled". */
@@ -44,6 +49,8 @@ export interface StepAttrs {
artifacts: string[];
uploads: Upload[];
timeoutSec: number;
/** Alias path when the step comes from an included notebook (see ParamDef.scope). */
scope?: string;
}
/** 1-based, inclusive line range in the notebook source. */
@@ -72,8 +79,58 @@ export type Block =
onFailure: boolean;
blocks: Block[];
range: SourceRange;
}
| {
/** `:::when{param=a,b}` — shown, and its steps runnable, only while param is one of values. */
type: "when";
param: string;
values: string[];
blocks: Block[];
range: SourceRange;
}
| {
/**
* `::use{notebook="dir/x.md" as=alias with="p={{v}}"}` — another workspace notebook inline.
* As parsed, `blocks` is empty; composeNotebook fills it with the namespaced content.
*/
type: "use";
/** Alias path ("ct"; "ct.base" for nested includes). */
scope: string;
/** Workspace notebook path relative to notebooks/. */
path: string;
/** Included notebook's title (set by composeNotebook). */
title?: string;
/** Local param name of the included notebook -> default template in the including notebook. */
bindings: Record<string, string>;
blocks: Block[];
range: SourceRange;
}
| {
/** `::host{name= address= user= port= capture=}` — add a machine to Hosts from the notebook. */
type: "host";
id: string;
scope?: string;
/** Templates, resolved like step attributes. */
name: string;
address: string;
user: string;
port: string;
/** Runtime value set to the host name once it is in Hosts. */
capture?: string;
range: SourceRange;
};
/** A `::host` block with all templates resolved. */
export interface RenderedHost {
id: string;
name: string;
address: string;
user: string;
port: number;
missing: string[];
invalid: Record<string, string>;
}
export interface Diagnostic {
severity: "error" | "warning";
message: string;
+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"]);
});
});