Skip to content

A modern and easy to use dashboard. 80+ integrations. 20K+ icons built in. Authentication out of the box. No YAML, drag and drop configuration.

7.5 KB
Raw Blame
import { getCustomWidgetSourceAuthType } from "./request-schema";
import type { HomarrCustomWidgetV2 } from "./custom-jsx-schema";
import { customWidgetImportSchema } from "./custom-jsx-schema";

export interface ImportReview {
  name: string;
  origins: string[];
  authTypes: string[];
  methods: string[];
  permissions: string[];
  hasActions: boolean;
}

export interface CustomWidgetImportIssue {
  code: string;
  path?: Array<string | number>;
  message: string;
}

export type CustomWidgetParseResult =
  | { success: true; widget: HomarrCustomWidgetV2; warnings: CustomWidgetImportIssue[] }
  | { success: false; issues: CustomWidgetImportIssue[] };

interface FencedBlock {
  language: string;
  content: string;
}

const MAX_IMPORT_ISSUES = 8;

function extractFencedBlocks(text: string): FencedBlock[] {
  const blocks: FencedBlock[] = [];
  for (const match of text.matchAll(/```([^\n`]*)\n([\s\S]*?)```/gu)) {
    blocks.push({ language: (match[1] ?? "").trim().toLowerCase(), content: match[2] ?? "" });
  }
  return blocks;
}

function jsonSyntaxIssue(error: unknown, source: string): CustomWidgetImportIssue {
  const message = error instanceof Error ? error.message : "The response is not valid JSON";
  const position = /position\s+(\d+)/iu.exec(message)?.[1];
  if (!position) return { code: "INVALID_JSON", message };
  const offset = Number(position);
  const prefix = source.slice(0, offset);
  const line = prefix.split("\n").length;
  const column = offset - prefix.lastIndexOf("\n");
  return { code: "INVALID_JSON", message: `${message} (line ${line}, column ${column})` };
}

function zodIssues(error: { issues: Array<{ path: PropertyKey[]; message: string; code: string }> }) {
  return error.issues.slice(0, MAX_IMPORT_ISSUES).map((issue) => ({
    code: issue.code === "unrecognized_keys" ? "UNSUPPORTED_FIELD" : "INVALID_WIDGET",
    path: issue.path.map((part) => (typeof part === "symbol" ? String(part) : part)),
    message: issue.message,
  }));
}

function removedStateIssues(value: Record<string, unknown>): CustomWidgetImportIssue[] {
  return ["stateSchema", "defaultState"].flatMap((field) =>
    Object.hasOwn(value, field)
      ? [
          {
            code: "REMOVED_LOCAL_STATE",
            path: [field],
            message: `${field} is not supported. Use bind with inputs for temporary values or widget options for saved configuration.`,
          },
        ]
      : [],
  );
}

type ParsedWidgetValue =
  | { success: true; value: Record<string, unknown> }
  | { success: false; issue: CustomWidgetImportIssue };

function parseWidgetValue(source: string): ParsedWidgetValue {
  try {
    const parsed: unknown = JSON.parse(source);
    if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
      return {
        success: false,
        issue: { code: "INVALID_WIDGET", message: "The response must contain one widget JSON object." },
      };
    }
    return { success: true, value: parsed as Record<string, unknown> };
  } catch (error) {
    return { success: false, issue: jsonSyntaxIssue(error, source) };
  }
}

export function parseCustomWidgetClipboard(text: string): HomarrCustomWidgetV2 | null {
  const result = parseCustomWidgetClipboardDetailed(text);
  return result.success ? result.widget : null;
}

export function parseCustomWidgetClipboardDetailed(text: string): CustomWidgetParseResult {
  const blocks = extractFencedBlocks(text);
  const jsonBlock = blocks.find((block) => block.language === "json" || block.language === "");
  const source = jsonBlock?.content ?? text;
  const parsedValue = parseWidgetValue(source);
  if (!parsedValue.success) return { success: false, issues: [parsedValue.issue] };
  const widget = { ...parsedValue.value };
  const removedIssues = removedStateIssues(widget);
  if (removedIssues.length > 0) return { success: false, issues: removedIssues };
  const parsed = customWidgetImportSchema.safeParse(widget);
  if (!parsed.success) return { success: false, issues: zodIssues(parsed.error) };
  return { success: true, widget: exportCustomWidgetDefinition(parsed.data), warnings: [] };
}

export function parseCustomWidgetAiResponse(text: string): CustomWidgetParseResult {
  const blocks = extractFencedBlocks(text);
  const jsonBlocks = blocks.filter((block) => block.language === "json" || block.language === "");
  const formatIssues: CustomWidgetImportIssue[] = [];
  if (blocks.length > 0 && jsonBlocks.length !== 1)
    formatIssues.push({ code: "AI_JSON_BLOCK_REQUIRED", message: "Expected exactly one JSON block." });
  if (blocks.length !== jsonBlocks.length)
    formatIssues.push({
      code: "AI_SINGLE_JSON_BLOCK_REQUIRED",
      message: "Expected one JSON block only. Put the complete JSX directly in its template field.",
    });
  const source = jsonBlocks[0]?.content ?? text;
  const parsedValue = parseWidgetValue(source);
  if (!parsedValue.success) {
    if (/"(?:stateSchema|defaultState)"\s*:/u.test(source))
      formatIssues.push({
        code: "REMOVED_LOCAL_STATE",
        message: "stateSchema and defaultState are not supported; use bind with inputs or widget options.",
      });
    return { success: false, issues: [parsedValue.issue, ...formatIssues].slice(0, MAX_IMPORT_ISSUES) };
  }
  const widget = { ...parsedValue.value };
  const removedIssues = removedStateIssues(widget);
  if (removedIssues.length > 0) formatIssues.push(...removedIssues);
  const warnings: CustomWidgetImportIssue[] = [];
  if (formatIssues.length > 0) return { success: false, issues: formatIssues.slice(0, MAX_IMPORT_ISSUES) };
  const parsed = customWidgetImportSchema.safeParse(widget);
  if (!parsed.success) return { success: false, issues: zodIssues(parsed.error) };
  return { success: true, widget: parsed.data, warnings };
}

export function looksLikeCustomWidgetClipboard(text: string) {
  return /homarr-custom-widget|```(?:json|jsx|tsx)?\s*\n|"\$schema"\s*:/iu.test(text);
}

export function formatCustomWidgetImportIssues(issues: readonly CustomWidgetImportIssue[]) {
  const visible = issues.slice(0, 3).map((issue) => {
    const path = issue.path?.length ? `${issue.path.join(".")}: ` : "";
    return `${path}${issue.message}`;
  });
  const remaining = issues.length - visible.length;
  return `${visible.join(" ")}${remaining > 0 ? ` (+${remaining} more)` : ""}`;
}

export function getImportReview(value: unknown): ImportReview | null {
  const parsed = customWidgetImportSchema.safeParse(value);
  if (!parsed.success) return null;
  const widget = parsed.data;
  return {
    name: widget.name,
    origins: Object.values(widget.sources).map((source) =>
      source.type === "integration" ? source.integrationKind : new URL(source.baseUrl).origin,
    ),
    authTypes: [
      ...new Set(
        Object.values(widget.sources).map((source) =>
          source.type === "integration" ? "integration" : getCustomWidgetSourceAuthType(source),
        ),
      ),
    ],
    methods: [...new Set(Object.values(widget.requests).map((request) => request.method))],
    permissions: [...new Set(Object.values(widget.requests).map((request) => request.permission))],
    hasActions: Object.values(widget.requests).some((request) => request.kind === "action"),
  };
}

/** Deployment bindings never travel with an exported or published widget. */
export function exportCustomWidgetDefinition(widget: HomarrCustomWidgetV2): HomarrCustomWidgetV2 {
  return {
    ...widget,
    sources: Object.fromEntries(
      Object.entries(widget.sources).map(([id, source]) => {
        if (source.type !== "integration") return [id, source];
        const { integrationId: _localBinding, ...portable } = source;
        return [id, portable];
      }),
    ),
  };
}