// @smithers-type-exports-begin
/** @typedef {import("./ApprovalDecision.ts").ApprovalDecision} ApprovalDecision */
/** @typedef {import("./ApprovalRanking.ts").ApprovalRanking} ApprovalRanking */
/** @typedef {import("./ApprovalRequest.ts").ApprovalRequest} ApprovalRequest */
/** @typedef {import("./ApprovalSelection.ts").ApprovalSelection} ApprovalSelection */
// @smithers-type-exports-end
import React from "react";
import { z } from "zod";
import { SmithersContext } from "@smthrs/react-reconciler/context";
import { getTaskRuntime } from "@smthrs/driver/task-runtime";
import { SmithersDb } from "@smthrs/db/adapter";
import { SmithersError } from "@smthrs/errors/SmithersError";
/** @typedef {import("./ApprovalAutoApprove.ts").ApprovalAutoApprove} ApprovalAutoApprove */
/** @typedef {import("./ApprovalMode.ts").ApprovalMode} ApprovalMode */
/** @typedef {import("./ApprovalOption.ts").ApprovalOption} ApprovalOption */
/**
* @template Row, Output
* @typedef {import("./ApprovalProps.ts").ApprovalProps<Row, Output>} ApprovalProps
*/
export const approvalDecisionSchema = z.object({
approved: z.boolean(),
// `note` is omitted entirely when no note was provided, so the default
// decision schema must accept an absent key (optional) as well as the
// legacy null/string shapes.
note: z.string().nullable().optional(),
decidedBy: z.string().nullable(),
decidedAt: z.string().datetime().nullable(),
});
export const approvalSelectionSchema = z.object({
selected: z.string(),
notes: z.string().nullable(),
});
export const approvalRankingSchema = z.object({
ranked: z.array(z.string()),
notes: z.string().nullable(),
});
/**
* @param {unknown} value
* @returns {value is import("zod").ZodObject<import("zod").ZodRawShape>}
*/
function isZodObject(value) {
return Boolean(value && typeof value === "object" && "shape" in value);
}
/**
* @template T
* @param {unknown} value
* @returns {T | null}
*/
function parseJson(value) {
if (typeof value !== "string" || value.length === 0) {
return null;
}
try {
return JSON.parse(value);
} catch {
return null;
}
}
/**
* @param {ApprovalMode} mode
* @returns {import("zod").ZodObject<import("zod").ZodRawShape>}
*/
function defaultSchemaForMode(mode) {
switch (mode) {
case "select":
return approvalSelectionSchema;
case "rank":
return approvalRankingSchema;
default:
return approvalDecisionSchema;
}
}
/**
* @param {{ status?: string | null; note?: string | null; decidedBy?: string | null; decidedAtMs?: number | null } | undefined | null} approval
* @param {import("zod").ZodObject<import("zod").ZodRawShape>} outputSchema
* @returns {Record<string, unknown>}
*/
function buildDecisionPayload(approval, outputSchema) {
const base = {
approved: approval?.status === "approved",
decidedBy: approval?.decidedBy ?? null,
decidedAt: approval?.decidedAtMs != null ? new Date(approval.decidedAtMs).toISOString() : null,
};
if (typeof approval?.note === "string") {
return { ...base, note: approval.note };
}
if (outputSchema.safeParse(base).success) {
return base;
}
return { ...base, note: null };
}
/**
* @param {ApprovalMode | undefined} mode
* @returns {"select" | "rank" | "decision"}
*/
function normalizeMode(mode) {
switch (mode) {
case "select":
return "select";
case "rank":
return "rank";
default:
return "decision";
}
}
/**
* @param {ApprovalOption[] | undefined} options
* @returns {ApprovalOption[] | undefined}
*/
function normalizeOptions(options) {
return options?.map((option) => ({
key: option.key,
label: option.label,
...(option.summary ? { summary: option.summary } : {}),
...(option.metadata ? { metadata: option.metadata } : {}),
}));
}
/**
* @param {unknown} value
* @param {"allowedScopes" | "allowedUsers"} field
* @param {string} id
* @returns {string[] | undefined}
*/
function validateApprovalRestriction(value, field, id) {
if (value === undefined) {
return undefined;
}
if (
!Array.isArray(value) ||
Array.from(value).some((entry) => typeof entry !== "string" || entry.trim().length === 0)
) {
throw new SmithersError("INVALID_INPUT", `Approval ${id} ${field} must be an array of non-empty strings.`);
}
return value;
}
/**
* @param {ApprovalAutoApprove[keyof ApprovalAutoApprove]} callback
* @param {import("@smthrs/driver").SmithersCtx<unknown> | null} ctx
* @returns {boolean | undefined}
*/
function evaluateBooleanCallback(callback, ctx) {
if (typeof callback !== "function") {
return undefined;
}
return Boolean(/** @type {(ctx: import("@smthrs/driver").SmithersCtx<unknown> | null) => boolean} */ (callback)(ctx));
}
/**
* @template Row
* @param {ApprovalProps<Row>} props
* @returns {React.ReactElement | null}
*/
export function Approval(props) {
if (props.skipIf) return null;
const smithersContext = props.smithersContext ?? SmithersContext;
const ctx = React.useContext(smithersContext);
const mode = props.mode ?? "approve";
const approvalMode = normalizeMode(mode);
const options = normalizeOptions(props.options);
const allowedScopes = validateApprovalRestriction(props.allowedScopes, "allowedScopes", props.id);
const allowedUsers = validateApprovalRestriction(props.allowedUsers, "allowedUsers", props.id);
const outputSchema = props.outputSchema ?? (isZodObject(props.output) ? props.output : defaultSchemaForMode(mode));
if ((mode === "select" || mode === "rank") && (!options || options.length === 0)) {
throw new SmithersError("APPROVAL_OPTIONS_REQUIRED", `Approval ${props.id} requires options when mode="${mode}".`);
}
const conditionMet = props.autoApprove ? evaluateBooleanCallback(props.autoApprove.condition, ctx) : undefined;
const revertOnMet = props.autoApprove ? evaluateBooleanCallback(props.autoApprove.revertOn, ctx) : undefined;
const autoApprove = props.autoApprove
? {
...(typeof props.autoApprove.after === "number" ? { after: props.autoApprove.after } : {}),
audit: props.autoApprove.audit !== false,
...(conditionMet !== undefined ? { conditionMet } : {}),
...(revertOnMet !== undefined ? { revertOnMet } : {}),
}
: undefined;
const requestMeta = {
requestTitle: props.request.title,
...(props.request.summary ? { requestSummary: props.request.summary } : {}),
...(options ? { approvalOptions: options } : {}),
...(allowedScopes?.length ? { approvalAllowedScopes: allowedScopes } : {}),
...(allowedUsers?.length ? { approvalAllowedUsers: allowedUsers } : {}),
...(autoApprove ? { approvalAutoApprove: autoApprove } : {}),
...props.request.metadata,
...props.meta,
};
/**
* @returns {Promise<Row>}
*/
const computeDecision = async () => {
const runtime = getTaskRuntime();
if (!runtime) {
throw new SmithersError(
"APPROVAL_OUTSIDE_TASK",
"Approval decisions can only be resolved while a Smithers task is executing.",
);
}
const adapter = new SmithersDb(runtime.db);
const approval = await adapter.getApproval(runtime.runId, props.id, runtime.iteration);
const decision = parseJson(approval?.decisionJson);
if (approvalMode === "select") {
return {
selected: typeof decision?.selected === "string" ? decision.selected : "",
notes: typeof decision?.notes === "string" ? decision.notes : (approval?.note ?? null),
};
}
if (approvalMode === "rank") {
return {
ranked: Array.isArray(decision?.ranked) ? decision.ranked.filter((value) => typeof value === "string") : [],
notes: typeof decision?.notes === "string" ? decision.notes : (approval?.note ?? null),
};
}
return buildDecisionPayload(approval, outputSchema);
};
return React.createElement("smithers:task", {
id: props.id,
output: props.output,
outputSchema,
dependsOn: props.dependsOn,
needs: props.needs,
...(Object.hasOwn(props, "bind") ? { bind: props.bind } : {}),
needsApproval: true,
waitAsync: props.async === true,
approvalMode,
approvalOnDeny: props.onDeny ?? "fail",
approvalOptions: options,
approvalAllowedScopes: allowedScopes,
approvalAllowedUsers: allowedUsers,
approvalAutoApprove: autoApprove,
timeoutMs: props.timeoutMs,
heartbeatTimeoutMs: props.heartbeatTimeoutMs,
heartbeatTimeout: props.heartbeatTimeout,
retries: props.retries,
retryPolicy: props.retryPolicy,
continueOnFail: props.continueOnFail,
cache: props.cache,
label: props.label ?? props.request.title,
meta: Object.keys(requestMeta).length > 0 ? requestMeta : undefined,
__smithersKind: "compute",
__smithersComputeFn: computeDecision,
});
}