Bin
2025-12-16 9e0b2ba2c317b1a86212f24cbae3195ad1f3dbfa
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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
import { z } from "zod";
import type { FieldDefinition, MessageDefinition, ProviderConfig } from "./common";
 
// Re-export ProviderConfig for convenience
export type { ProviderConfig };
 
// Shared function to determine if a field is actually required
export function isFieldRequired(field: FieldDefinition, isEditMode = false): boolean {
  // Access key fields are never required in edit mode (they can be provided via env vars)
  if (field.accessKey && isEditMode) {
    return false;
  }
 
  // Check if the field is explicitly marked as required
  if (field.required === true) {
    return true;
  }
 
  // Check if the schema indicates the field is required
  // A schema is considered required if it doesn't have .optional() or .default()
  const schemaAny = field.schema as any;
 
  // Check if the schema has .optional() modifier
  if (schemaAny._def?.typeName === "ZodOptional") {
    return false;
  }
 
  // Check if the schema has .default() modifier
  if (schemaAny._def?.typeName === "ZodDefault") {
    return false;
  }
 
  // Check if the inner type of a default schema is optional
  if (schemaAny._def?.innerType?._def?.typeName === "ZodOptional") {
    return false;
  }
 
  // For string fields, check if they have min(1) validation (indicating required)
  if (field.schema instanceof z.ZodString) {
    const stringSchema = field.schema as z.ZodString;
    // Check if the schema has min(1) validation
    if (stringSchema._def?.checks?.some((check: any) => check.kind === "min" && check.value === 1)) {
      return true;
    }
  }
 
  // Default to not required
  return false;
}
 
// Helper function to assemble the complete schema from field definitions
export function assembleSchema(fields: FieldDefinition[], isEditMode = false): z.ZodObject<any> {
  const schemaObject: Record<string, z.ZodTypeAny> = {};
 
  fields.forEach((field) => {
    let fieldSchema = field.schema;
    const isRequired = isFieldRequired(field, isEditMode);
 
    // For access keys in edit mode, make them optional and skip validation
    if (field.accessKey && isEditMode) {
      fieldSchema = fieldSchema.optional();
    } else if (isRequired) {
      // For required fields, ensure they have proper validation
      if (fieldSchema instanceof z.ZodString) {
        fieldSchema = fieldSchema.min(1, `${field.label} is required`);
      } else if (fieldSchema instanceof z.ZodNumber) {
        // For numbers, we might want to add additional validation if needed
        // For now, just ensure it's not optional
        fieldSchema = fieldSchema.refine((val) => val !== undefined && val !== null, {
          message: `${field.label} is required`,
        });
      } else if (fieldSchema instanceof z.ZodBoolean) {
        // For booleans, ensure they're not optional
        fieldSchema = fieldSchema.refine((val) => val !== undefined && val !== null, {
          message: `${field.label} is required`,
        });
      } else {
        // For other types, ensure they're not optional
        fieldSchema = fieldSchema.refine((val) => val !== undefined && val !== null, {
          message: `${field.label} is required`,
        });
      }
    } else {
      // For optional fields, make them nullable to handle null values from server
      if (fieldSchema instanceof z.ZodString) {
        fieldSchema = fieldSchema.nullable().optional();
      } else if (fieldSchema instanceof z.ZodNumber) {
        fieldSchema = fieldSchema.nullable().optional();
      } else if (fieldSchema instanceof z.ZodBoolean) {
        fieldSchema = fieldSchema.nullable().optional();
      } else {
        fieldSchema = fieldSchema.nullable().optional();
      }
    }
 
    schemaObject[field.name] = fieldSchema;
  });
 
  return z.object(schemaObject);
}
 
// Helper function to extract default values from Zod schemas
export function extractDefaultValues(fields: (FieldDefinition | MessageDefinition)[]): Record<string, any> {
  const defaultValues: Record<string, any> = {};
 
  fields.forEach((field) => {
    if (field.type === "message") return;
 
    // Check if the field has a default value
    if (Object.prototype.hasOwnProperty.call(field, "defaultValue") && field.defaultValue !== undefined) {
      const customDefault = typeof field.defaultValue === "function" ? field.defaultValue() : field.defaultValue;
      defaultValues[field.name] = customDefault;
      return;
    }
 
    // If the field does not have a default value, try to get it from the schema
    try {
      // Try to get the default value from the schema by accessing the internal structure
      const schemaAny = field.schema as any;
      let defaultValue = undefined;
 
      // Check different possible locations for default values in Zod schemas
      if (schemaAny._def?.defaultValue !== undefined) {
        defaultValue =
          typeof schemaAny._def.defaultValue === "function"
            ? schemaAny._def.defaultValue()
            : schemaAny._def.defaultValue;
      } else if (schemaAny._def?.innerType?._def?.defaultValue !== undefined) {
        defaultValue =
          typeof schemaAny._def.innerType._def.defaultValue === "function"
            ? schemaAny._def.innerType._def.defaultValue()
            : schemaAny._def.innerType._def.defaultValue;
      } else if (schemaAny._def?.typeName === "ZodDefault") {
        defaultValue =
          typeof schemaAny._def.innerType._def.defaultValue === "function"
            ? schemaAny._def.innerType._def.defaultValue()
            : schemaAny._def.innerType._def.defaultValue;
      }
 
      if (defaultValue !== undefined) {
        defaultValues[field.name] = defaultValue;
      } else {
        // Set appropriate defaults based on field type
        switch (field.type) {
          case "text":
          case "password":
          case "textarea":
            defaultValues[field.name] = "";
            break;
          case "number":
          case "counter":
            defaultValues[field.name] = field.min || 0;
            break;
          case "select":
            defaultValues[field.name] = field.options?.[0]?.value || "";
            break;
          case "toggle":
            defaultValues[field.name] = false;
            break;
        }
      }
    } catch (error) {
      // If we can't extract the default, use type-based defaults
      switch (field.type) {
        case "text":
        case "password":
        case "textarea":
          defaultValues[field.name] = "";
          break;
        case "number":
        case "counter":
          defaultValues[field.name] = field.min || 0;
          break;
        case "select":
          defaultValues[field.name] = field.options?.[0]?.value || "";
          break;
        case "toggle":
          defaultValues[field.name] = false;
          break;
      }
    }
  });
 
  return defaultValues;
}
 
// Helper function to get field by name
export function getFieldByName(
  fields: (FieldDefinition | MessageDefinition)[],
  name: string,
): FieldDefinition | MessageDefinition | undefined {
  return fields.find((field) => field.name === name);
}
 
// Helper function to get fields for a specific row
export function getFieldsForRow(
  fields: (FieldDefinition | MessageDefinition)[],
  rowFields: string[],
  target?: "import" | "export",
): (FieldDefinition | MessageDefinition)[] {
  const filteredFields = rowFields.map((fieldName) => getFieldByName(fields, fieldName)).filter(Boolean) as (
    | FieldDefinition
    | MessageDefinition
  )[];
 
  // Filter fields based on target if specified
  if (target) {
    return filteredFields.filter((field) => {
      if (field.type === "message") return true; // Always show messages
      return !field.target || field.target === target;
    });
  }
 
  return filteredFields;
}