Parse YAML frontmatter, shell steps and conditional sections with source ranges and diagnostics. Resolve typed defaults and runtime values through one script substitution path, keeping secrets env-only and validating artifact metadata. Add yaml for standards-compliant frontmatter parsing and bounded alias handling rather than implementing YAML locally. Cover the spec example and edge cases with 59 core tests, including 256 POSIX shell quoting round trips.
128 lines
6.6 KiB
TypeScript
128 lines
6.6 KiB
TypeScript
// Public API of @shellbook/core. Pure functions, no I/O.
|
|
import type { Notebook, ParamValues, RenderedStep, Step } from "./types";
|
|
export type * from "./types";
|
|
export type * from "./protocol";
|
|
export { parseNotebook } from "./parser";
|
|
|
|
const template = /\{\{\s*([^{}]+?)\s*\}\}/g;
|
|
const own = (object: object, key: string) => Object.hasOwn(object, key);
|
|
const dictionary = (): Record<string, string> => Object.create(null) as Record<string, string>;
|
|
|
|
/**
|
|
* Quote a value for POSIX sh. Returns the value unchanged when it only contains
|
|
* [A-Za-z0-9._/@:=+-] and is non-empty; otherwise single-quoted with ' escaped as '\''.
|
|
* The ONLY place in the codebase that quotes shell values.
|
|
*/
|
|
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. */
|
|
export function resolveParams(
|
|
notebook: Notebook,
|
|
values: ParamValues,
|
|
hostNames: readonly string[],
|
|
): { values: ParamValues; errors: Record<string, string> } {
|
|
const effective = dictionary();
|
|
const errors = dictionary();
|
|
const defs = new Map(notebook.params.map(def => [def.name, def]));
|
|
const active = new Set<string>();
|
|
const resolve = (name: string): string => {
|
|
if (own(effective, name)) return effective[name]!;
|
|
const def = defs.get(name);
|
|
if (!def) return "";
|
|
if (active.has(name)) { errors[name] = "Cyclic parameter default"; return ""; }
|
|
active.add(name);
|
|
let value = own(values, name) ? values[name] ?? "" : "";
|
|
if (!value && def.type !== "secret" && def.default !== undefined) {
|
|
value = def.default.replace(template, (match, ref: string) => {
|
|
const other = defs.get(ref);
|
|
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);
|
|
if (own(errors, ref)) errors[name] = `Invalid default dependency: ${ref}`;
|
|
if (!resolved) errors[name] = `Missing default dependency: ${ref}`;
|
|
return resolved || match;
|
|
});
|
|
}
|
|
active.delete(name);
|
|
effective[name] = value;
|
|
if (!value) {
|
|
if (def.required) errors[name] ??= "Required parameter is missing";
|
|
return value;
|
|
}
|
|
// POSIX arguments and environment values cannot contain NUL, regardless of type.
|
|
if (value.includes("\0")) errors[name] = "Value cannot contain NUL";
|
|
else if (def.type === "host" && !hostNames.includes(value)) errors[name] = "Unknown host";
|
|
else if (def.type === "name" && !/^[A-Za-z0-9._-]+$/.test(value)) errors[name] = "Expected a name containing only letters, digits, ., _ or -";
|
|
else if (def.type === "path" && /[\r\n]/.test(value)) errors[name] = "Path cannot contain newlines";
|
|
else if (def.type === "choice" && !def.options?.includes(value)) errors[name] = "Value is not an available choice";
|
|
return value;
|
|
};
|
|
for (const def of notebook.params) resolve(def.name);
|
|
return { values: effective, errors };
|
|
}
|
|
|
|
/**
|
|
* The single script substitution path: display and execution consume this result.
|
|
* Attributes use raw substitution and separate validation; secrets are env-only.
|
|
*/
|
|
export function renderStep(
|
|
notebook: Notebook,
|
|
step: Step,
|
|
values: ParamValues,
|
|
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 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";
|
|
const plainFile = (name: string) => !!name && !/[\\/\0\r\n]/.test(name) && !name.includes("..");
|
|
const artifacts = step.attrs.artifacts.map((raw, i) => {
|
|
const name = substitute(raw, false);
|
|
if (!plainFile(name)) invalid[`artifacts[${i}]`] = "Artifact must be a plain file name without ..";
|
|
return name;
|
|
});
|
|
const uploads = step.attrs.uploads.map((upload, i) => {
|
|
const src = substitute(upload.src, false), dst = substitute(upload.dst, false);
|
|
if (!plainFile(src)) invalid[`uploads[${i}].src`] = "Upload source must be a plain artifact file name without ..";
|
|
if (!dst || /[\0\r\n]/.test(dst)) invalid[`uploads[${i}].dst`] = "Upload destination must be a path without NUL or newlines";
|
|
return { src, dst };
|
|
});
|
|
return { stepId: step.attrs.id, kind: step.kind, host, local: step.attrs.local, script, artifacts, uploads, 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> {
|
|
const env = dictionary();
|
|
for (const def of notebook.params) if (def.type === "secret" && own(values, def.name)) env[def.name] = values[def.name]!;
|
|
return env;
|
|
}
|