codex@macbookpro
·
2026-04-01
utils.ts
1interface NormalizeRequiredStringOptions {
2 errorStyle?: "field" | "plain";
3}
4
5export function normalizeOptionalString(value: unknown): string | null {
6 if (typeof value !== "string") {
7 return null;
8 }
9
10 const normalized = value.trim();
11 return normalized === "" ? null : normalized;
12}
13
14export function normalizeRequiredString(
15 value: unknown,
16 name: string,
17 options: NormalizeRequiredStringOptions = {}
18): string {
19 const normalized = normalizeOptionalString(value);
20
21 if (normalized == null) {
22 throw new Error(
23 options.errorStyle === "field"
24 ? `Field "${name}" must be a non-empty string.`
25 : `${name} must be a non-empty string.`
26 );
27 }
28
29 return normalized;
30}
31
32export function parseJsonValue(value: string | null | undefined): unknown {
33 if (value == null) {
34 return null;
35 }
36
37 try {
38 return JSON.parse(value);
39 } catch {
40 return null;
41 }
42}
43
44export function isPlainRecord(value: unknown): value is Record<string, unknown> {
45 return typeof value === "object" && value != null && !Array.isArray(value);
46}