/**
* `marimo check`-gated static HTML snapshot exporter for research notebooks.
*
* Enforces the D9 rule (`design/PLATFORM-PLAN.md`): a notebook must pass
* `marimo check --format=json` with zero errors before `marimo export html`
* runs, and exported HTML is published atomically via a sibling temp file.
*
* All subprocess execution and filesystem access are injected via ports
* (`NotebookCommandRunner`, `NotebookSnapshotFs`). `node:crypto` is loaded
* lazily at call time so `@stock-bot/research` remains browser-bundleable.
*
* Command flags and JSON diagnostic shape are confirmed against marimo 0.26.0
* (pinned in `python/uv.lock`).
*/
export const DEFAULT_MARIMO_COMMAND = 'marimo';
export const DEFAULT_NOTEBOOK_SNAPSHOT_TIMEOUT_MS = 120_000;
const MAX_TEMP_RESERVATION_ATTEMPTS = 16;
let tempSequence = 0;
/** Stable machine-readable error codes thrown by {@link NotebookSnapshotError}. */
export type NotebookSnapshotErrorCode =
| 'INVALID_OPTION'
| 'INVALID_PATH'
| 'NOTEBOOK_NOT_FOUND'
| 'CHECK_FAILED'
| 'CHECK_OUTPUT_INVALID'
| 'EXPORT_FAILED'
| 'EXPORT_EMPTY'
| 'TIMEOUT';
export interface NotebookSnapshotErrorOptions {
readonly details?: unknown;
readonly cause?: unknown;
}
/** Typed fail-closed error thrown by {@link exportNotebookSnapshot}. */
export class NotebookSnapshotError extends Error {
readonly code: NotebookSnapshotErrorCode;
readonly details?: unknown;
override readonly cause?: unknown;
constructor(
code: NotebookSnapshotErrorCode,
message: string,
options?: NotebookSnapshotErrorOptions
) {
super(message);
this.name = 'NotebookSnapshotError';
this.code = code;
if (options && 'details' in options) {
this.details = options.details;
}
if (options && 'cause' in options) {
this.cause = options.cause;
}
Object.setPrototypeOf(this, new.target.prototype);
}
}
export interface NotebookCommandRunOptions {
readonly cwd?: string;
readonly timeoutMs: number;
}
export interface NotebookCommandResult {
readonly exitCode: number;
readonly stdout: string;
readonly stderr: string;
}
/**
* Injected command-runner port.
*
* Implementations MUST execute `command` directly with `args` as an argv array
* (never via a shell string or shell interpolation).
*
* Timeout contract: on timeout, implementations MUST terminate the subprocess
* and settle (rejecting with an error carrying `code: 'ETIMEDOUT'`) only after
* the process has exited and stopped writing to disk.
*/
export interface NotebookCommandRunner {
run(
command: string,
args: readonly string[],
options: NotebookCommandRunOptions
): Promise;
}
export interface NotebookSnapshotFileStat {
readonly isFile: boolean;
readonly size: number;
}
/**
* Minimal injected filesystem port for {@link exportNotebookSnapshot}.
*/
export interface NotebookSnapshotFs {
/** Returns file metadata for `path`, or `null` when `path` does not exist. */
stat(path: string): Promise;
/**
* Exclusively creates an empty file at `path` (`O_CREAT | O_EXCL`).
* MUST throw an error carrying `code: 'EEXIST'` if `path` already exists.
*/
createExclusive(path: string): Promise;
/** Reads the complete byte contents of `path`. */
readBytes(path: string): Promise;
/** Atomically replaces `destinationPath` with `sourcePath`. */
rename(sourcePath: string, destinationPath: string): Promise;
/** Idempotently removes `path` (succeeds as a no-op if already absent). */
remove(path: string): Promise;
}
/** Parsed marimo 0.26.0 `marimo check --format=json` summary object. */
export interface MarimoCheckSummary {
readonly errored: boolean;
readonly total_files: number;
readonly [key: string]: unknown;
}
/** Parsed marimo 0.26.0 `marimo check --format=json` report object. */
export interface MarimoCheckReport {
readonly issues: readonly Readonly>[];
readonly summary: MarimoCheckSummary;
readonly [key: string]: unknown;
}
export interface ExportNotebookSnapshotOptions {
readonly notebookPath: string;
readonly outputPath: string;
readonly runner: NotebookCommandRunner;
readonly fs: NotebookSnapshotFs;
/** Executable name or path for marimo (default `'marimo'`). */
readonly marimoCommand?: string;
/** Per-command timeout in milliseconds (default `120_000`). */
readonly timeoutMs?: number;
/** Optional working directory passed to `runner.run`. */
readonly cwd?: string;
/** Optional absolute root directory that `notebookPath` must lexically reside within. */
readonly allowedNotebookRoot?: string;
/** Optional absolute root directory that `outputPath` must lexically reside within. */
readonly allowedOutputRoot?: string;
}
/** Frozen receipt returned when a notebook snapshot is cleanly checked and published. */
export interface NotebookSnapshotReceipt {
readonly notebookPath: string;
readonly outputPath: string;
readonly bytes: number;
readonly sha256: string;
readonly checkDiagnostics: MarimoCheckReport | null;
}
function isPlainObject(value: unknown): value is Record {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
function getErrorCode(err: unknown): string | undefined {
if (typeof err === 'object' && err !== null && 'code' in err) {
const code = (err as { code?: unknown }).code;
if (typeof code === 'string') {
return code;
}
}
return undefined;
}
function normalizePosixAbsolutePath(rawPath: string): string {
const segments = rawPath.split('/');
const stack: string[] = [];
for (let i = 0; i < segments.length; i += 1) {
const seg = segments[i];
if (seg === undefined || seg === '' || seg === '.') {
continue;
}
if (seg === '..') {
if (stack.length > 0) {
stack.pop();
}
continue;
}
stack.push(seg);
}
return `/${stack.join('/')}`;
}
function validateAbsolutePath(
rawPath: unknown,
label: string,
options?: { readonly requiredExtension?: string }
): string {
if (typeof rawPath !== 'string' || rawPath.length === 0) {
throw new NotebookSnapshotError(
'INVALID_PATH',
`Invalid ${label}: expected a non-empty string.`
);
}
if (rawPath.includes('\0')) {
throw new NotebookSnapshotError('INVALID_PATH', `Invalid ${label}: NUL bytes are not allowed.`);
}
if (rawPath.startsWith('-')) {
throw new NotebookSnapshotError(
'INVALID_PATH',
`Invalid ${label}: path must not start with '-'.`
);
}
if (!rawPath.startsWith('/')) {
throw new NotebookSnapshotError(
'INVALID_PATH',
`Invalid ${label}: path must be an absolute POSIX path.`
);
}
if (options?.requiredExtension !== undefined) {
if (rawPath.endsWith('/')) {
throw new NotebookSnapshotError(
'INVALID_PATH',
`Invalid ${label}: path must reference a ${options.requiredExtension} file, not a directory.`
);
}
}
const normalized = normalizePosixAbsolutePath(rawPath);
if (options?.requiredExtension !== undefined) {
const ext = options.requiredExtension;
if (!normalized.endsWith(ext) || normalized === `/${ext}` || normalized.endsWith(`/${ext}`)) {
throw new NotebookSnapshotError(
'INVALID_PATH',
`Invalid ${label}: path must end with '${ext}'.`
);
}
}
return normalized;
}
function assertWithinRoot(
normalizedPath: string,
rawRoot: unknown,
pathLabel: string,
rootLabel: string
): void {
const normalizedRoot = validateAbsolutePath(rawRoot, rootLabel);
if (normalizedRoot === '/') {
return;
}
const requiredPrefix = `${normalizedRoot}/`;
if (!normalizedPath.startsWith(requiredPrefix)) {
throw new NotebookSnapshotError(
'INVALID_PATH',
`Invalid ${pathLabel}: resolved path '${normalizedPath}' escapes ${rootLabel} '${normalizedRoot}'.`
);
}
}
function dirnamePosix(normalizedFilePath: string): string {
const lastSlash = normalizedFilePath.lastIndexOf('/');
return lastSlash <= 0 ? '/' : normalizedFilePath.slice(0, lastSlash);
}
function validatePortsAndOptions(options: ExportNotebookSnapshotOptions): {
readonly notebookPath: string;
readonly outputPath: string;
readonly runner: NotebookCommandRunner;
readonly fs: NotebookSnapshotFs;
readonly marimoCommand: string;
readonly timeoutMs: number;
readonly cwd?: string;
} {
if (!isPlainObject(options)) {
throw new NotebookSnapshotError('INVALID_OPTION', 'Invalid options: expected an object.');
}
const { runner, fs } = options;
if (!isPlainObject(runner) || typeof runner.run !== 'function') {
throw new NotebookSnapshotError(
'INVALID_OPTION',
'Invalid runner: expected an object with a callable run(command, args, options) method.'
);
}
if (
!isPlainObject(fs) ||
typeof fs.stat !== 'function' ||
typeof fs.createExclusive !== 'function' ||
typeof fs.readBytes !== 'function' ||
typeof fs.rename !== 'function' ||
typeof fs.remove !== 'function'
) {
throw new NotebookSnapshotError(
'INVALID_OPTION',
'Invalid fs: expected an object implementing stat, createExclusive, readBytes, rename, and remove.'
);
}
const marimoCommand =
options.marimoCommand === undefined ? DEFAULT_MARIMO_COMMAND : options.marimoCommand;
if (
typeof marimoCommand !== 'string' ||
marimoCommand.trim().length === 0 ||
marimoCommand.includes('\0') ||
marimoCommand.startsWith('-')
) {
throw new NotebookSnapshotError(
'INVALID_OPTION',
'Invalid marimoCommand: expected a non-empty command name or path without NUL bytes or leading "-".'
);
}
const timeoutMs =
options.timeoutMs === undefined ? DEFAULT_NOTEBOOK_SNAPSHOT_TIMEOUT_MS : options.timeoutMs;
if (typeof timeoutMs !== 'number' || !Number.isSafeInteger(timeoutMs) || timeoutMs <= 0) {
throw new NotebookSnapshotError(
'INVALID_OPTION',
'Invalid timeoutMs: expected a positive safe integer.'
);
}
const notebookPath = validateAbsolutePath(options.notebookPath, 'notebookPath', {
requiredExtension: '.py',
});
const outputPath = validateAbsolutePath(options.outputPath, 'outputPath', {
requiredExtension: '.html',
});
if (options.allowedNotebookRoot !== undefined) {
assertWithinRoot(
notebookPath,
options.allowedNotebookRoot,
'notebookPath',
'allowedNotebookRoot'
);
}
if (options.allowedOutputRoot !== undefined) {
assertWithinRoot(outputPath, options.allowedOutputRoot, 'outputPath', 'allowedOutputRoot');
}
let cwd: string | undefined;
if (options.cwd !== undefined) {
cwd = validateAbsolutePath(options.cwd, 'cwd');
}
return {
notebookPath,
outputPath,
runner,
fs,
marimoCommand,
timeoutMs,
...(cwd !== undefined ? { cwd } : {}),
};
}
function validateCommandResult(result: unknown, phase: 'check' | 'export'): NotebookCommandResult {
if (
!isPlainObject(result) ||
typeof result.exitCode !== 'number' ||
!Number.isSafeInteger(result.exitCode) ||
typeof result.stdout !== 'string' ||
typeof result.stderr !== 'string'
) {
throw new NotebookSnapshotError(
phase === 'check' ? 'CHECK_FAILED' : 'EXPORT_FAILED',
`Invalid runner result for marimo ${phase}: expected { exitCode, stdout, stderr }.`
);
}
return {
exitCode: result.exitCode,
stdout: result.stdout,
stderr: result.stderr,
};
}
function issueHasBlockingError(issue: Record): boolean {
if (issue.type === 'error' || issue.severity === 'breaking') {
return true;
}
const nested = issue.diagnostics;
if (Array.isArray(nested)) {
for (let i = 0; i < nested.length; i += 1) {
const diag = nested[i];
if (isPlainObject(diag) && (diag.type === 'error' || diag.severity === 'breaking')) {
return true;
}
}
}
return false;
}
function parseAndValidateCheckReport(parsed: unknown): {
readonly report: MarimoCheckReport;
readonly hasBlockingError: boolean;
} {
if (!isPlainObject(parsed)) {
throw new NotebookSnapshotError(
'CHECK_OUTPUT_INVALID',
'marimo check JSON output must be an object with { issues, summary }.'
);
}
const { issues, summary } = parsed;
if (!Array.isArray(issues) || !isPlainObject(summary)) {
throw new NotebookSnapshotError(
'CHECK_OUTPUT_INVALID',
'marimo check JSON output must contain an issues array and a summary object.'
);
}
if (
typeof summary.errored !== 'boolean' ||
typeof summary.total_files !== 'number' ||
!Number.isSafeInteger(summary.total_files)
) {
throw new NotebookSnapshotError(
'CHECK_OUTPUT_INVALID',
'marimo check summary must include boolean errored and integer total_files.'
);
}
if (summary.total_files !== 1) {
throw new NotebookSnapshotError(
'CHECK_OUTPUT_INVALID',
`marimo check reported summary.total_files=${summary.total_files}; expected exactly 1 checked file.`,
{ details: { diagnostics: parsed } }
);
}
let hasBlockingError = summary.errored;
for (let i = 0; i < issues.length; i += 1) {
const issue = issues[i];
if (!isPlainObject(issue)) {
throw new NotebookSnapshotError(
'CHECK_OUTPUT_INVALID',
`marimo check issues[${i}] must be an object.`,
{ details: { diagnostics: parsed } }
);
}
if (issue.type !== undefined && typeof issue.type !== 'string') {
throw new NotebookSnapshotError(
'CHECK_OUTPUT_INVALID',
`marimo check issues[${i}].type must be a string when present.`,
{ details: { diagnostics: parsed } }
);
}
if (issue.severity !== undefined && typeof issue.severity !== 'string') {
throw new NotebookSnapshotError(
'CHECK_OUTPUT_INVALID',
`marimo check issues[${i}].severity must be a string when present.`,
{ details: { diagnostics: parsed } }
);
}
if (issue.diagnostics !== undefined) {
if (!Array.isArray(issue.diagnostics)) {
throw new NotebookSnapshotError(
'CHECK_OUTPUT_INVALID',
`marimo check issues[${i}].diagnostics must be an array when present.`,
{ details: { diagnostics: parsed } }
);
}
for (let j = 0; j < issue.diagnostics.length; j += 1) {
const diag = issue.diagnostics[j];
if (!isPlainObject(diag)) {
throw new NotebookSnapshotError(
'CHECK_OUTPUT_INVALID',
`marimo check issues[${i}].diagnostics[${j}] must be an object.`,
{ details: { diagnostics: parsed } }
);
}
if (diag.type !== undefined && typeof diag.type !== 'string') {
throw new NotebookSnapshotError(
'CHECK_OUTPUT_INVALID',
`marimo check issues[${i}].diagnostics[${j}].type must be a string when present.`,
{ details: { diagnostics: parsed } }
);
}
if (diag.severity !== undefined && typeof diag.severity !== 'string') {
throw new NotebookSnapshotError(
'CHECK_OUTPUT_INVALID',
`marimo check issues[${i}].diagnostics[${j}].severity must be a string when present.`,
{ details: { diagnostics: parsed } }
);
}
}
}
if (issueHasBlockingError(issue)) {
hasBlockingError = true;
}
}
return {
report: parsed as MarimoCheckReport,
hasBlockingError,
};
}
function deepFreeze(value: T): T {
if (typeof value !== 'object' || value === null || Object.isFrozen(value)) {
return value;
}
if (Array.isArray(value)) {
for (let i = 0; i < value.length; i += 1) {
deepFreeze(value[i]);
}
return Object.freeze(value);
}
const record = value as Record;
const keys = Object.keys(record);
for (let i = 0; i < keys.length; i += 1) {
const key = keys[i] as string;
deepFreeze(record[key]);
}
return Object.freeze(value);
}
function generateTempToken(): string {
tempSequence += 1;
const randomPart =
typeof globalThis.crypto !== 'undefined' && typeof globalThis.crypto.randomUUID === 'function'
? globalThis.crypto.randomUUID().replace(/-/g, '')
: `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
return `${tempSequence}-${randomPart}`;
}
async function reserveSiblingTempHtml(fs: NotebookSnapshotFs, outputPath: string): Promise {
const dir = dirnamePosix(outputPath);
const dirPrefix = dir === '/' ? '' : dir;
for (let attempt = 0; attempt < MAX_TEMP_RESERVATION_ATTEMPTS; attempt += 1) {
const candidate = `${dirPrefix}/.marimo-snapshot-${generateTempToken()}.tmp.html`;
try {
await fs.createExclusive(candidate);
return candidate;
} catch (err) {
if (getErrorCode(err) === 'EEXIST') {
continue;
}
throw new NotebookSnapshotError(
'EXPORT_FAILED',
`Failed to reserve temporary HTML sibling for '${outputPath}'.`,
{ cause: err }
);
}
}
throw new NotebookSnapshotError(
'EXPORT_FAILED',
`Failed to reserve a unique temporary HTML sibling for '${outputPath}' after ${MAX_TEMP_RESERVATION_ATTEMPTS} attempts.`
);
}
async function sha256HexNodeCrypto(bytes: Uint8Array): Promise {
// Keep the Node built-in specifier non-literal so browser bundlers do not try
// to statically resolve `node:crypto` when bundling `@stock-bot/research`.
const cryptoSpecifier = 'node:crypto';
const nodeCrypto = (await import(cryptoSpecifier)) as typeof import('node:crypto');
return nodeCrypto.createHash('sha256').update(bytes).digest('hex');
}
async function runPhaseCommand(
runner: NotebookCommandRunner,
command: string,
args: readonly string[],
runOptions: NotebookCommandRunOptions,
phase: 'check' | 'export'
): Promise {
let rawResult: unknown;
try {
rawResult = await runner.run(command, args, runOptions);
} catch (err) {
if (getErrorCode(err) === 'ETIMEDOUT') {
throw new NotebookSnapshotError(
'TIMEOUT',
`marimo ${phase} timed out after ${runOptions.timeoutMs}ms.`,
{ cause: err, details: { phase, timeoutMs: runOptions.timeoutMs } }
);
}
throw new NotebookSnapshotError(
phase === 'check' ? 'CHECK_FAILED' : 'EXPORT_FAILED',
`marimo ${phase} command failed to execute.`,
{ cause: err, details: { phase } }
);
}
return validateCommandResult(rawResult, phase);
}
/**
* Validates a marimo notebook with `marimo check --format=json` and, only when
* the check is clean, exports a static HTML snapshot via `marimo export html`
* and publishes it atomically via sibling temp-file rename.
*/
export async function exportNotebookSnapshot(
options: ExportNotebookSnapshotOptions
): Promise {
const { notebookPath, outputPath, runner, fs, marimoCommand, timeoutMs, cwd } =
validatePortsAndOptions(options);
let notebookStat: NotebookSnapshotFileStat | null;
try {
notebookStat = await fs.stat(notebookPath);
} catch (err) {
if (getErrorCode(err) === 'ENOENT') {
notebookStat = null;
} else {
throw new NotebookSnapshotError(
'NOTEBOOK_NOT_FOUND',
`Unable to stat notebook '${notebookPath}'.`,
{ cause: err }
);
}
}
if (notebookStat === null || !notebookStat.isFile) {
throw new NotebookSnapshotError(
'NOTEBOOK_NOT_FOUND',
`Notebook file not found or is not a regular file: '${notebookPath}'.`
);
}
const runOptions: NotebookCommandRunOptions =
cwd !== undefined ? { cwd, timeoutMs } : { timeoutMs };
// Step 1: Gate on `marimo check --format=json `.
const checkResult = await runPhaseCommand(
runner,
marimoCommand,
['check', '--format=json', notebookPath],
runOptions,
'check'
);
const hasCheckStdout = checkResult.stdout.length > 0;
let parsedCheckJson: unknown = undefined;
let checkJsonParseError: unknown = undefined;
if (hasCheckStdout) {
try {
parsedCheckJson = JSON.parse(checkResult.stdout);
} catch (err) {
checkJsonParseError = err;
}
}
if (checkResult.exitCode !== 0) {
throw new NotebookSnapshotError(
'CHECK_FAILED',
`marimo check exited with code ${checkResult.exitCode}.`,
{
details: {
exitCode: checkResult.exitCode,
stderr: checkResult.stderr,
stdout: checkResult.stdout,
...(checkJsonParseError === undefined && parsedCheckJson !== undefined
? { diagnostics: parsedCheckJson }
: {}),
},
}
);
}
let checkDiagnostics: MarimoCheckReport | null = null;
if (hasCheckStdout) {
if (checkJsonParseError !== undefined) {
throw new NotebookSnapshotError(
'CHECK_OUTPUT_INVALID',
'marimo check exited 0 but emitted non-JSON stdout.',
{
cause: checkJsonParseError,
details: { stdout: checkResult.stdout, stderr: checkResult.stderr },
}
);
}
const { report, hasBlockingError } = parseAndValidateCheckReport(parsedCheckJson);
if (hasBlockingError) {
throw new NotebookSnapshotError(
'CHECK_FAILED',
'marimo check reported blocking errors in diagnostics.',
{
details: {
exitCode: checkResult.exitCode,
stderr: checkResult.stderr,
diagnostics: report,
},
}
);
}
checkDiagnostics = deepFreeze(report);
}
// Step 2: Reserve an exclusive sibling `.html` temp file and run `marimo export html`.
const tempPath = await reserveSiblingTempHtml(fs, outputPath);
let tempOwned = true;
try {
const exportResult = await runPhaseCommand(
runner,
marimoCommand,
['export', 'html', notebookPath, '-o', tempPath, '--force'],
runOptions,
'export'
);
if (exportResult.exitCode !== 0) {
throw new NotebookSnapshotError(
'EXPORT_FAILED',
`marimo export html exited with code ${exportResult.exitCode}.`,
{
details: {
exitCode: exportResult.exitCode,
stderr: exportResult.stderr,
stdout: exportResult.stdout,
},
}
);
}
let tempStat: NotebookSnapshotFileStat | null;
try {
tempStat = await fs.stat(tempPath);
} catch (err) {
if (getErrorCode(err) === 'ENOENT') {
tempStat = null;
} else {
throw new NotebookSnapshotError(
'EXPORT_FAILED',
`Failed to stat exported snapshot temp file '${tempPath}'.`,
{ cause: err }
);
}
}
if (tempStat === null || !tempStat.isFile || tempStat.size <= 0) {
throw new NotebookSnapshotError(
'EXPORT_EMPTY',
`marimo export html produced missing or empty output at '${tempPath}'.`
);
}
let exportedBytes: Uint8Array;
try {
exportedBytes = await fs.readBytes(tempPath);
} catch (err) {
if (getErrorCode(err) === 'ENOENT') {
throw new NotebookSnapshotError(
'EXPORT_EMPTY',
`Exported snapshot temp file '${tempPath}' disappeared before read.`,
{ cause: err }
);
}
throw new NotebookSnapshotError(
'EXPORT_FAILED',
`Failed to read exported snapshot temp file '${tempPath}'.`,
{ cause: err }
);
}
if (!(exportedBytes instanceof Uint8Array) || exportedBytes.byteLength === 0) {
throw new NotebookSnapshotError(
'EXPORT_EMPTY',
`marimo export html produced zero bytes at '${tempPath}'.`
);
}
const sha256 = await sha256HexNodeCrypto(exportedBytes);
const receipt: NotebookSnapshotReceipt = Object.freeze({
notebookPath,
outputPath,
bytes: exportedBytes.byteLength,
sha256,
checkDiagnostics,
});
try {
await fs.rename(tempPath, outputPath);
tempOwned = false;
} catch (err) {
throw new NotebookSnapshotError(
'EXPORT_FAILED',
`Failed to atomically publish snapshot from '${tempPath}' to '${outputPath}'.`,
{ cause: err }
);
}
return receipt;
} catch (err) {
if (tempOwned) {
try {
await fs.remove(tempPath);
} catch {
// Preserve the primary error if temp cleanup also fails.
}
}
if (err instanceof NotebookSnapshotError) {
throw err;
}
throw new NotebookSnapshotError(
'EXPORT_FAILED',
'Unexpected failure during notebook snapshot export.',
{ cause: err }
);
}
}