sing-ui/components/kv.ts

35 lines
1.2 KiB
TypeScript

// Helpers for the "one key=value per line" textareas used by the connection
// dialog (URL params) and the pipeline form (replication env).
// Parse textarea lines into an object. Blank lines, lines starting with '#'
// and lines without a key or '=' are ignored. Values may contain '='.
export function parseKeyValueLines(text: string): Record<string, string> {
const out: Record<string, string> = {};
for (const raw of text.split("\n")) {
const line = raw.trim();
if (!line || line.startsWith("#")) continue;
const i = line.indexOf("=");
if (i <= 0) continue;
const key = line.slice(0, i).trim();
const value = line.slice(i + 1).trim();
if (key) out[key] = value;
}
return out;
}
// Serialize a JSON-object column back into key=value lines for editing.
export function keyValueLinesFromJson(json: string | undefined | null): string {
if (!json) return "";
try {
const v = JSON.parse(json) as unknown;
if (v && typeof v === "object" && !Array.isArray(v)) {
return Object.entries(v as Record<string, unknown>)
.map(([k, val]) => `${k}=${String(val)}`)
.join("\n");
}
} catch {
// fall through
}
return "";
}