-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathfield.zod.ts
More file actions
416 lines (370 loc) · 17 KB
/
Copy pathfield.zod.ts
File metadata and controls
416 lines (370 loc) · 17 KB
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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
import { z } from 'zod';
import { SystemIdentifierSchema } from '../shared/identifiers.zod';
/**
* Field Type Enum
*/
export const FieldType = z.enum([
// Core Text
'text', 'textarea', 'email', 'url', 'phone', 'password',
// Rich Content
'markdown', 'html', 'richtext',
// Numbers
'number', 'currency', 'percent',
// Date & Time
'date', 'datetime', 'time',
// Logic
'boolean', 'toggle', // Toggle is a distinct UI from checkbox
// Selection
'select', // Single select dropdown
'multiselect', // Multi select (often tags)
'radio', // Radio group
'checkboxes', // Checkbox group
// Relational
'lookup', 'master_detail', // Dynamic reference
'tree', // Hierarchical reference
// Media
'image', 'file', 'avatar', 'video', 'audio',
// Calculated / System
'formula', 'summary', 'autonumber',
// Enhanced Types
'location', // GPS coordinates
'address', // Structured address
'code', // Code editor (JSON/SQL/JS)
'json', // Structured JSON data
'color', // Color picker
'rating', // Star rating
'slider', // Numeric slider
'signature', // Digital signature
'qrcode', // QR code / Barcode
'progress', // Progress bar
'tags', // Simple tag list
// AI/ML Types
'vector', // Vector embeddings for AI/ML (semantic search, RAG)
]);
export type FieldType = z.infer<typeof FieldType>;
/**
* Select Option Schema
*
* Defines option values for select/picklist fields.
*
* **CRITICAL RULE**: The `value` field is a machine identifier that gets stored in the database.
* It MUST be lowercase to avoid case-sensitivity issues in queries and comparisons.
*
* @example Good
* { label: 'New', value: 'new' }
* { label: 'In Progress', value: 'in_progress' }
* { label: 'Closed Won', value: 'closed_won' }
*
* @example Bad (will be rejected)
* { label: 'New', value: 'New' } // uppercase
* { label: 'In Progress', value: 'In Progress' } // spaces and uppercase
* { label: 'Closed Won', value: 'Closed_Won' } // mixed case
*/
export const SelectOptionSchema = z.object({
label: z.string().describe('Display label (human-readable, any case allowed)'),
value: SystemIdentifierSchema.describe('Stored value (lowercase machine identifier)'),
color: z.string().optional().describe('Color code for badges/charts'),
default: z.boolean().optional().describe('Is default option'),
});
/**
* Location Coordinates Schema
* GPS coordinates for location field type
*/
export const LocationCoordinatesSchema = z.object({
latitude: z.number().min(-90).max(90).describe('Latitude coordinate'),
longitude: z.number().min(-180).max(180).describe('Longitude coordinate'),
altitude: z.number().optional().describe('Altitude in meters'),
accuracy: z.number().optional().describe('Accuracy in meters'),
});
/**
* Currency Configuration Schema
* Configuration for currency field type supporting multi-currency
*
* Note: Currency codes are validated by length only (3 characters) to support:
* - Standard ISO 4217 codes (USD, EUR, CNY, etc.)
* - Cryptocurrency codes (BTC, ETH, etc.)
* - Custom business-specific codes
* Stricter validation can be implemented at the application layer based on business requirements.
*/
export const CurrencyConfigSchema = z.object({
precision: z.number().int().min(0).max(10).default(2).describe('Decimal precision (default: 2)'),
currencyMode: z.enum(['dynamic', 'fixed']).default('dynamic').describe('Currency mode: dynamic (user selectable) or fixed (single currency)'),
defaultCurrency: z.string().length(3).default('CNY').describe('Default or fixed currency code (ISO 4217, e.g., USD, CNY, EUR)'),
});
/**
* Currency Value Schema
* Runtime value structure for currency fields
*
* Note: Currency codes are validated by length only (3 characters) to support flexibility.
* See CurrencyConfigSchema for details on currency code validation strategy.
*/
export const CurrencyValueSchema = z.object({
value: z.number().describe('Monetary amount'),
currency: z.string().length(3).describe('Currency code (ISO 4217)'),
});
/**
* Address Schema
* Structured address for address field type
*/
export const AddressSchema = z.object({
street: z.string().optional().describe('Street address'),
city: z.string().optional().describe('City name'),
state: z.string().optional().describe('State/Province'),
postalCode: z.string().optional().describe('Postal/ZIP code'),
country: z.string().optional().describe('Country name or code'),
countryCode: z.string().optional().describe('ISO country code (e.g., US, GB)'),
formatted: z.string().optional().describe('Formatted address string'),
});
/**
* Vector Configuration Schema
* Configuration for vector field type supporting AI/ML embeddings
*
* Vector fields store numerical embeddings for semantic search, similarity matching,
* and Retrieval-Augmented Generation (RAG) workflows.
*
* @example
* // Text embeddings for semantic search
* {
* dimensions: 1536, // OpenAI text-embedding-ada-002
* distanceMetric: 'cosine',
* indexed: true
* }
*
* @example
* // Image embeddings with normalization
* {
* dimensions: 512, // ResNet-50
* distanceMetric: 'euclidean',
* normalized: true,
* indexed: true
* }
*/
export const VectorConfigSchema = z.object({
dimensions: z.number().int().min(1).max(10000).describe('Vector dimensionality (e.g., 1536 for OpenAI embeddings)'),
distanceMetric: z.enum(['cosine', 'euclidean', 'dotProduct', 'manhattan']).default('cosine').describe('Distance/similarity metric for vector search'),
normalized: z.boolean().default(false).describe('Whether vectors are normalized (unit length)'),
indexed: z.boolean().default(true).describe('Whether to create a vector index for fast similarity search'),
indexType: z.enum(['hnsw', 'ivfflat', 'flat']).optional().describe('Vector index algorithm (HNSW for high accuracy, IVFFlat for large datasets)'),
});
/**
* Field Schema - Best Practice Enterprise Pattern
*/
export const FieldSchema = z.object({
/** Identity */
name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Machine name (snake_case)').optional(),
label: z.string().optional().describe('Human readable label'),
type: FieldType.describe('Field Data Type'),
description: z.string().optional().describe('Tooltip/Help text'),
format: z.string().optional().describe('Format string (e.g. email, phone)'),
/** Database Constraints */
required: z.boolean().default(false).describe('Is required'),
searchable: z.boolean().default(false).describe('Is searchable'),
multiple: z.boolean().default(false).describe('Allow multiple values (Stores as Array/JSON). Applicable for select, lookup, file, image.'),
unique: z.boolean().default(false).describe('Is unique constraint'),
defaultValue: z.any().optional().describe('Default value'),
/** Text/String Constraints */
maxLength: z.number().optional().describe('Max character length'),
minLength: z.number().optional().describe('Min character length'),
/** Number Constraints */
precision: z.number().optional().describe('Total digits'),
scale: z.number().optional().describe('Decimal places'),
min: z.number().optional().describe('Minimum value'),
max: z.number().optional().describe('Maximum value'),
/** Selection Options */
options: z.array(SelectOptionSchema).optional().describe('Static options for select/multiselect'),
/** Relationship Config */
reference: z.string().optional().describe('Target Object Name'),
referenceFilters: z.array(z.string()).optional().describe('Filters applied to lookup dialogs (e.g. "active = true")'),
writeRequiresMasterRead: z.boolean().optional().describe('If true, user needs read access to master record to edit this field'),
deleteBehavior: z.enum(['set_null', 'cascade', 'restrict']).optional().default('set_null').describe('What happens if referenced record is deleted'),
/** Calculation */
expression: z.string().optional().describe('Formula expression'),
formula: z.string().optional().describe('Deprecated: Use expression'),
summaryOperations: z.object({
object: z.string(),
field: z.string(),
function: z.enum(['count', 'sum', 'min', 'max', 'avg'])
}).optional().describe('Roll-up summary definition'),
/** Enhanced Field Type Configurations */
// Code field config
language: z.string().optional().describe('Programming language for syntax highlighting (e.g., javascript, python, sql)'),
theme: z.string().optional().describe('Code editor theme (e.g., dark, light, monokai)'),
lineNumbers: z.boolean().optional().describe('Show line numbers in code editor'),
// Rating field config
maxRating: z.number().optional().describe('Maximum rating value (default: 5)'),
allowHalf: z.boolean().optional().describe('Allow half-star ratings'),
// Location field config
displayMap: z.boolean().optional().describe('Display map widget for location field'),
allowGeocoding: z.boolean().optional().describe('Allow address-to-coordinate conversion'),
// Address field config
addressFormat: z.enum(['us', 'uk', 'international']).optional().describe('Address format template'),
// Color field config
colorFormat: z.enum(['hex', 'rgb', 'rgba', 'hsl']).optional().describe('Color value format'),
allowAlpha: z.boolean().optional().describe('Allow transparency/alpha channel'),
presetColors: z.array(z.string()).optional().describe('Preset color options'),
// Slider field config
step: z.number().optional().describe('Step increment for slider (default: 1)'),
showValue: z.boolean().optional().describe('Display current value on slider'),
marks: z.record(z.string()).optional().describe('Custom marks/labels at specific values (e.g., {0: "Low", 50: "Medium", 100: "High"})'),
// QR Code / Barcode field config
// Note: qrErrorCorrection is only applicable when barcodeFormat='qr'
// Runtime validation should enforce this constraint
barcodeFormat: z.enum(['qr', 'ean13', 'ean8', 'code128', 'code39', 'upca', 'upce']).optional().describe('Barcode format type'),
qrErrorCorrection: z.enum(['L', 'M', 'Q', 'H']).optional().describe('QR code error correction level (L=7%, M=15%, Q=25%, H=30%). Only applicable when barcodeFormat is "qr"'),
displayValue: z.boolean().optional().describe('Display human-readable value below barcode/QR code'),
allowScanning: z.boolean().optional().describe('Enable camera scanning for barcode/QR code input'),
// Currency field config
currencyConfig: CurrencyConfigSchema.optional().describe('Configuration for currency field type'),
// Vector field config
vectorConfig: VectorConfigSchema.optional().describe('Configuration for vector field type (AI/ML embeddings)'),
/** Security & Visibility */
hidden: z.boolean().default(false).describe('Hidden from default UI'),
readonly: z.boolean().default(false).describe('Read-only in UI'),
encryption: z.boolean().default(false).describe('Encrypt at rest'),
/** Indexing */
index: z.boolean().default(false).describe('Create standard database index'),
externalId: z.boolean().default(false).describe('Is external ID for upsert operations'),
});
export type Field = z.infer<typeof FieldSchema>;
export type SelectOption = z.infer<typeof SelectOptionSchema>;
export type LocationCoordinates = z.infer<typeof LocationCoordinatesSchema>;
export type Address = z.infer<typeof AddressSchema>;
export type CurrencyConfig = z.infer<typeof CurrencyConfigSchema>;
export type CurrencyValue = z.infer<typeof CurrencyValueSchema>;
export type VectorConfig = z.infer<typeof VectorConfigSchema>;
/**
* Field Factory Helper
*/
export type FieldInput = Omit<Partial<Field>, 'type'>;
export const Field = {
text: (config: FieldInput = {}) => ({ type: 'text', ...config } as const),
textarea: (config: FieldInput = {}) => ({ type: 'textarea', ...config } as const),
number: (config: FieldInput = {}) => ({ type: 'number', ...config } as const),
boolean: (config: FieldInput = {}) => ({ type: 'boolean', ...config } as const),
date: (config: FieldInput = {}) => ({ type: 'date', ...config } as const),
datetime: (config: FieldInput = {}) => ({ type: 'datetime', ...config } as const),
currency: (config: FieldInput = {}) => ({ type: 'currency', ...config } as const),
percent: (config: FieldInput = {}) => ({ type: 'percent', ...config } as const),
url: (config: FieldInput = {}) => ({ type: 'url', ...config } as const),
email: (config: FieldInput = {}) => ({ type: 'email', ...config } as const),
phone: (config: FieldInput = {}) => ({ type: 'phone', ...config } as const),
image: (config: FieldInput = {}) => ({ type: 'image', ...config } as const),
file: (config: FieldInput = {}) => ({ type: 'file', ...config } as const),
avatar: (config: FieldInput = {}) => ({ type: 'avatar', ...config } as const),
formula: (config: FieldInput = {}) => ({ type: 'formula', ...config } as const),
summary: (config: FieldInput = {}) => ({ type: 'summary', ...config } as const),
autonumber: (config: FieldInput = {}) => ({ type: 'autonumber', ...config } as const),
markdown: (config: FieldInput = {}) => ({ type: 'markdown', ...config } as const),
html: (config: FieldInput = {}) => ({ type: 'html', ...config } as const),
password: (config: FieldInput = {}) => ({ type: 'password', ...config } as const),
/**
* Select field helper with backward-compatible API
*
* Automatically converts option values to lowercase to enforce naming conventions.
*
* @example Old API (array first) - auto-converts to lowercase
* Field.select(['High', 'Low'], { label: 'Priority' })
* // Results in: [{ label: 'High', value: 'high' }, { label: 'Low', value: 'low' }]
*
* @example New API (config object) - enforces lowercase
* Field.select({ options: [{label: 'High', value: 'high'}], label: 'Priority' })
*
* @example Multi-word values - converts to snake_case
* Field.select(['In Progress', 'Closed Won'], { label: 'Status' })
* // Results in: [{ label: 'In Progress', value: 'in_progress' }, { label: 'Closed Won', value: 'closed_won' }]
*/
select: (optionsOrConfig: SelectOption[] | string[] | FieldInput & { options: SelectOption[] | string[] }, config?: FieldInput) => {
// Helper function to convert string to lowercase snake_case
const toSnakeCase = (str: string): string => {
return str
.toLowerCase()
.replace(/\s+/g, '_') // Replace spaces with underscores
.replace(/[^a-z0-9_]/g, ''); // Remove invalid characters (keeping underscores only)
};
// Support both old and new signatures:
// Old: Field.select(['a', 'b'], { label: 'X' })
// New: Field.select({ options: [{label: 'A', value: 'a'}], label: 'X' })
let options: SelectOption[];
let finalConfig: FieldInput;
if (Array.isArray(optionsOrConfig)) {
// Old signature: array as first param
options = optionsOrConfig.map(o =>
typeof o === 'string'
? { label: o, value: toSnakeCase(o) } // Auto-convert string to snake_case
: { ...o, value: o.value.toLowerCase() } // Ensure value is lowercase
);
finalConfig = config || {};
} else {
// New signature: config object with options
options = (optionsOrConfig.options || []).map(o =>
typeof o === 'string'
? { label: o, value: toSnakeCase(o) } // Auto-convert string to snake_case
: { ...o, value: o.value.toLowerCase() } // Ensure value is lowercase
);
// Remove options from config to avoid confusion
const { options: _, ...restConfig } = optionsOrConfig;
finalConfig = restConfig;
}
return { type: 'select', options, ...finalConfig } as const;
},
lookup: (reference: string, config: FieldInput = {}) => ({
type: 'lookup',
reference,
...config
} as const),
masterDetail: (reference: string, config: FieldInput = {}) => ({
type: 'master_detail',
reference,
...config
} as const),
// Enhanced Field Type Helpers
location: (config: FieldInput = {}) => ({
type: 'location',
...config
} as const),
address: (config: FieldInput = {}) => ({
type: 'address',
...config
} as const),
richtext: (config: FieldInput = {}) => ({
type: 'richtext',
...config
} as const),
code: (language?: string, config: FieldInput = {}) => ({
type: 'code',
language,
...config
} as const),
color: (config: FieldInput = {}) => ({
type: 'color',
...config
} as const),
rating: (maxRating: number = 5, config: FieldInput = {}) => ({
type: 'rating',
maxRating,
...config
} as const),
signature: (config: FieldInput = {}) => ({
type: 'signature',
...config
} as const),
slider: (config: FieldInput = {}) => ({
type: 'slider',
...config
} as const),
qrcode: (config: FieldInput = {}) => ({
type: 'qrcode',
...config
} as const),
vector: (dimensions: number, config: FieldInput = {}) => ({
type: 'vector',
vectorConfig: {
dimensions,
distanceMetric: 'cosine' as const,
normalized: false,
indexed: true,
...config.vectorConfig
},
...config
} as const),
};