SPB Git

Repository Public

schemaForm.ts 7.1 KB 167 lines typescript

1// Turns the JSON Schema of an action type / job template (`params_schema`) into form fields, and validates and2// coerces the entered values. Supported subset: object with string (enum, minLength, maxLength, pattern, format),3// integer / number (minimum, maximum), boolean, and arrays of strings (optionally enum). Anything else falls back4// to a raw JSON field so no parameter is ever unreachable. The server remains the authority: this validation only5// spares a round trip.67export type FieldKind = "string" | "text" | "enum" | "integer" | "number" | "boolean" | "string-list" | "enum-list" | "json";89export interface FormField {10  name: string;11  kind: FieldKind;12  label: string;13  description?: string;14  required: boolean;15  options?: string[];16  min?: number;17  max?: number;18  minLength?: number;19  maxLength?: number;20  pattern?: string;21  format?: string;22  defaultValue?: unknown;23}2425export type FormValues = Record<string, unknown>;26export type FieldErrorCode = "required" | "min" | "max" | "minLength" | "maxLength" | "pattern" | "integer" | "number" | "enum" | "json";27export interface FieldError {28  field: string;29  code: FieldErrorCode;30  limit?: number | string;31}3233type Schema = Record<string, unknown>;34const isObj = (v: unknown): v is Schema => typeof v === "object" && v !== null && !Array.isArray(v);35const num = (v: unknown) => (typeof v === "number" ? v : undefined);36const str = (v: unknown) => (typeof v === "string" ? v : undefined);37const strList = (v: unknown) => (Array.isArray(v) && v.every((x) => typeof x === "string") ? (v as string[]) : undefined);3839export function schemaToFields(schema: unknown): FormField[] {40  if (!isObj(schema) || !isObj(schema.properties)) return [];41  const required = new Set(strList(schema.required) ?? []);42  const fields: FormField[] = [];43  for (const [name, raw] of Object.entries(schema.properties)) {44    const p = isObj(raw) ? raw : {};45    const base: FormField = { name, kind: "json", label: str(p.title) ?? name, required: required.has(name) };46    const description = str(p.description);47    if (description) base.description = description;48    if (p.default !== undefined) base.defaultValue = p.default;49    const type = Array.isArray(p.type) ? p.type.find((t) => t !== "null") : p.type;50    const en = strList(p.enum);51    if (type === "string" || (type === undefined && en)) {52      if (en) fields.push({ ...base, kind: "enum", options: en });53      else {54        const f: FormField = { ...base, kind: (num(p.maxLength) ?? 0) > 200 ? "text" : "string" };55        const minLength = num(p.minLength), maxLength = num(p.maxLength), pattern = str(p.pattern), format = str(p.format);56        if (minLength !== undefined) f.minLength = minLength;57        if (maxLength !== undefined) f.maxLength = maxLength;58        if (pattern !== undefined) f.pattern = pattern;59        if (format !== undefined) f.format = format;60        fields.push(f);61      }62    } else if (type === "integer" || type === "number") {63      const f: FormField = { ...base, kind: type };64      const min = num(p.minimum), max = num(p.maximum);65      if (min !== undefined) f.min = min;66      if (max !== undefined) f.max = max;67      fields.push(f);68    } else if (type === "boolean") {69      fields.push({ ...base, kind: "boolean" });70    } else if (type === "array" && isObj(p.items) && (p.items.type === "string" || strList(p.items.enum))) {71      const opts = strList(p.items.enum);72      fields.push(opts ? { ...base, kind: "enum-list", options: opts } : { ...base, kind: "string-list" });73    } else {74      fields.push(base);75    }76  }77  return fields;78}7980/** Initial form state: schema defaults, booleans false, everything else empty. */81export function initialValues(fields: FormField[]): FormValues {82  const out: FormValues = {};83  for (const f of fields) {84    if (f.defaultValue !== undefined) out[f.name] = f.kind === "json" ? JSON.stringify(f.defaultValue) : f.kind === "integer" || f.kind === "number" ? String(f.defaultValue) : f.defaultValue;85    else if (f.kind === "boolean") out[f.name] = false;86    else if (f.kind === "enum-list" || f.kind === "string-list") out[f.name] = [];87    else out[f.name] = "";88  }89  return out;90}9192export interface FormResult {93  errors: FieldError[];94  /** Coerced parameters, empty optional fields omitted. Only meaningful when `errors` is empty. */95  params: Record<string, unknown>;96}9798export function validateForm(fields: FormField[], values: FormValues): FormResult {99  const errors: FieldError[] = [];100  const params: Record<string, unknown> = {};101  for (const f of fields) {102    const v = values[f.name];103    const empty = v === undefined || v === null || v === "" || (Array.isArray(v) && v.length === 0);104    if (f.kind === "boolean") {105      params[f.name] = v === true;106      continue;107    }108    if (empty) {109      if (f.required) errors.push({ field: f.name, code: "required" });110      continue;111    }112    switch (f.kind) {113      case "string":114      case "text": {115        const s = String(v);116        if (f.minLength !== undefined && s.length < f.minLength) errors.push({ field: f.name, code: "minLength", limit: f.minLength });117        else if (f.maxLength !== undefined && s.length > f.maxLength) errors.push({ field: f.name, code: "maxLength", limit: f.maxLength });118        else if (f.pattern !== undefined && !safeTest(f.pattern, s)) errors.push({ field: f.name, code: "pattern", limit: f.pattern });119        else params[f.name] = s;120        break;121      }122      case "enum":123        if (!f.options?.includes(String(v))) errors.push({ field: f.name, code: "enum" });124        else params[f.name] = String(v);125        break;126      case "integer":127      case "number": {128        const n = typeof v === "number" ? v : Number(String(v).trim().replace(",", "."));129        if (!Number.isFinite(n)) errors.push({ field: f.name, code: "number" });130        else if (f.kind === "integer" && !Number.isInteger(n)) errors.push({ field: f.name, code: "integer" });131        else if (f.min !== undefined && n < f.min) errors.push({ field: f.name, code: "min", limit: f.min });132        else if (f.max !== undefined && n > f.max) errors.push({ field: f.name, code: "max", limit: f.max });133        else params[f.name] = n;134        break;135      }136      case "string-list": {137        const list = (Array.isArray(v) ? v.map(String) : String(v).split(/[\n,]/)).map((s) => s.trim()).filter(Boolean);138        if (list.length === 0 && f.required) errors.push({ field: f.name, code: "required" });139        else if (list.length > 0) params[f.name] = list;140        break;141      }142      case "enum-list": {143        const list = Array.isArray(v) ? v.map(String) : [];144        if (list.some((x) => !f.options?.includes(x))) errors.push({ field: f.name, code: "enum" });145        else params[f.name] = list;146        break;147      }148      case "json":149        try {150          params[f.name] = typeof v === "string" ? JSON.parse(v) : v;151        } catch {152          errors.push({ field: f.name, code: "json" });153        }154        break;155    }156  }157  return { errors, params };158}159160function safeTest(pattern: string, value: string): boolean {161  try {162    return new RegExp(pattern, "u").test(value);163  } catch {164    return true; // a pattern this engine cannot compile is left to the server165  }166}167
Files main
Menu

Theme