All files / src/util runForm.ts

98.43% Statements 63/64
90% Branches 63/70
100% Functions 13/13
100% Lines 55/55

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156                                    18x   18x 179x           72x 68x 4x 1x   64x 11x 3x   8x                     26x 72x                         64x   5x   6x     2x 2x 2x 1x 1x       5x 5x   1x   4x 1x 3x     7x 2x 5x   41x                             176x 176x 176x 184x 184x 120x 120x   64x 64x   5x     176x         1x 1x                         4x 4x   1x   3x 1x 12x 7x 2x 1x   1x     1x    
import { RunField } from "@/objects/Skill";
 
/**
 * The run form's state and its translation to a request body.
 *
 * Each field type keeps the value the control it is drawn with holds: text
 * for strings, numbers, enums and JSON objects; a boolean for a toggle; a
 * list of strings for an array. `toInputs` turns that into typed values and
 * says what is wrong with any it cannot — the same checks svc-core makes, so
 * the form catches a mistake before the round trip. svc-core stays the
 * authority: whatever it refuses comes back by field name and lands beside
 * the same controls.
 */
 
export type FormValue = string | boolean | string[];
export type FormValues = Record<string, FormValue>;
 
/** `toInputs`'s error for a required field left blank. */
export const REQUIRED = "Required";
 
const isBlank = (v: FormValue | undefined) =>
  v === undefined ||
  (typeof v === "string" && v.trim() === "") ||
  (Array.isArray(v) && v.every((item) => item.trim() === ""));
 
/** The control value for a typed value — a default, or a previous run's. */
export function toFormValue(field: RunField, value: unknown): FormValue {
  if (field.type === "boolean") return value === true || value === "true";
  if (field.type === "array") {
    if (Array.isArray(value)) return value.map((v) => String(v));
    return value === undefined || value === null ? [] : [String(value)];
  }
  if (value === undefined || value === null) return "";
  if (field.type === "object") {
    return typeof value === "string" ? value : JSON.stringify(value, null, 2);
  }
  return String(value);
}
 
/**
 * Starting values: `seed` (a previous run's inputs, for "Run again") where it
 * has one, else the field's default, else empty.
 */
export function initialValues(
  fields: RunField[],
  seed?: Record<string, unknown> | null,
): FormValues {
  return Object.fromEntries(
    fields.map((f) => [
      f.name,
      toFormValue(
        f,
        seed && f.name in seed
          ? seed[f.name]
          : (f.default ?? undefined),
      ),
    ]),
  );
}
 
function coerce(field: RunField, value: FormValue): unknown {
  switch (field.type) {
    case "boolean":
      return value === true;
    case "array":
      return (value as string[]).map((v) => v.trim()).filter(Boolean);
    case "number":
    case "integer": {
      const n = Number(String(value).trim());
      Iif (!Number.isFinite(n)) throw new Error("Enter a number");
      if (field.type === "integer" && !Number.isInteger(n))
        throw new Error("Enter a whole number");
      return n;
    }
    case "object": {
      let parsed: unknown;
      try {
        parsed = JSON.parse(String(value));
      } catch {
        throw new Error("Not valid JSON");
      }
      if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
        throw new Error("Expected a JSON object — { … }");
      return parsed;
    }
    case "enum":
      if (field.values?.length && !field.values.includes(String(value)))
        throw new Error(`Choose one of ${field.values.join(", ")}`);
      return String(value);
    default:
      return String(value);
  }
}
 
/**
 * The typed `inputs` for a run, and an error per field that cannot be sent.
 *
 * A blank optional field is left out rather than sent empty, so it cannot
 * shadow the default the skill would otherwise use. A boolean is never
 * blank: an unticked box is an answer.
 */
export function toInputs(
  fields: RunField[],
  values: FormValues,
): { inputs: Record<string, unknown>; errors: Record<string, string> } {
  const inputs: Record<string, unknown> = {};
  const errors: Record<string, string> = {};
  for (const field of fields) {
    const value = values[field.name];
    if (field.type !== "boolean" && isBlank(value)) {
      if (field.required) errors[field.name] = REQUIRED;
      continue;
    }
    try {
      inputs[field.name] = coerce(field, value ?? "");
    } catch (e) {
      errors[field.name] = (e as Error).message;
    }
  }
  return { inputs, errors };
}
 
/** The form as one JSON object — the "JSON" tab's starting text. */
export function valuesToJson(fields: RunField[], values: FormValues): string {
  const { inputs } = toInputs(fields, values);
  return JSON.stringify(inputs, null, 2);
}
 
/**
 * The JSON tab's text back into form values, or an error saying why not.
 * Keys the form has no field for are reported rather than dropped, since
 * svc-core would refuse them anyway.
 */
export function jsonToValues(
  fields: RunField[],
  text: string,
): { values: FormValues } | { error: string } {
  let parsed: unknown;
  try {
    parsed = text.trim() ? JSON.parse(text) : {};
  } catch {
    return { error: "Not valid JSON" };
  }
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
    return { error: "Inputs must be a JSON object — { … }" };
  const known = new Set(fields.map((f) => f.name));
  const unknown = Object.keys(parsed).filter((k) => !known.has(k));
  if (unknown.length)
    return {
      error: `This skill takes no input named ${unknown
        .map((k) => `“${k}”`)
        .join(", ")}`,
    };
  return { values: initialValues(fields, parsed as Record<string, unknown>) };
}