Repository navigation
Expand file tree
/
Copy pathjsonToTypeScript.ts
More file actions
272 lines (220 loc) · 7.77 KB
/
Copy pathjsonToTypeScript.ts
File metadata and controls
272 lines (220 loc) · 7.77 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
/**
* JSON to TypeScript type converter
* Supports multiple JSON samples to detect optional fields
*/
interface TypeInfo {
type: string;
isOptional: boolean;
}
interface InterfaceDefinition {
name: string;
properties: Map<string, TypeInfo>;
}
const generatedInterfaces = new Map<string, InterfaceDefinition>();
let interfaceCounter = 0;
function sanitizePropertyName(name: string): string {
// Handle property names with special characters
if (/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name)) {
return name;
}
return `"${name}"`;
}
function capitalizeFirst(str: string): string {
return str.charAt(0).toUpperCase() + str.slice(1);
}
function getTypeName(value: any, propertyName: string = '', parentName: string = ''): string {
if (value === null) {
return 'null';
}
const type = typeof value;
if (type === 'string') return 'string';
if (type === 'number') return 'number';
if (type === 'boolean') return 'boolean';
if (Array.isArray(value)) {
if (value.length === 0) {
return 'any[]';
}
// Check if all items have the same type
const types = new Set(value.map(item => getTypeName(item, propertyName, parentName)));
if (types.size === 1) {
const itemType = Array.from(types)[0];
return `${itemType}[]`;
}
// Mixed types - create union
return `(${Array.from(types).join(' | ')})[]`;
}
if (type === 'object') {
// Generate interface name based on property name
const interfaceName = propertyName
? capitalizeFirst(propertyName.replace(/[^a-zA-Z0-9]/g, ''))
: `Interface${interfaceCounter++}`;
const fullInterfaceName = parentName && propertyName
? `${parentName}${interfaceName}`
: interfaceName;
// Create interface for nested object
if (!generatedInterfaces.has(fullInterfaceName)) {
const interfaceDef: InterfaceDefinition = {
name: fullInterfaceName,
properties: new Map(),
};
for (const [key, val] of Object.entries(value)) {
interfaceDef.properties.set(key, {
type: getTypeName(val, key, fullInterfaceName),
isOptional: false,
});
}
generatedInterfaces.set(fullInterfaceName, interfaceDef);
}
return fullInterfaceName;
}
return 'any';
}
function mergeObjectSchemas(obj1: any, obj2: any, propertyName: string = '', parentName: string = ''): void {
const interfaceName = propertyName
? capitalizeFirst(propertyName.replace(/[^a-zA-Z0-9]/g, ''))
: 'Root';
const fullInterfaceName = parentName && propertyName
? `${parentName}${interfaceName}`
: interfaceName;
const existingInterface = generatedInterfaces.get(fullInterfaceName);
if (!existingInterface) return;
const keys1 = new Set(Object.keys(obj1));
const keys2 = new Set(Object.keys(obj2));
// Mark fields as optional if they don't appear in both objects
for (const key of keys1) {
if (!keys2.has(key)) {
const propInfo = existingInterface.properties.get(key);
if (propInfo) {
propInfo.isOptional = true;
}
}
}
for (const key of keys2) {
if (!keys1.has(key)) {
// Field exists in obj2 but not obj1 - add as optional
existingInterface.properties.set(key, {
type: getTypeName(obj2[key], key, fullInterfaceName),
isOptional: true,
});
} else {
// Field exists in both - check if nested object needs merging
if (typeof obj1[key] === 'object' && typeof obj2[key] === 'object' &&
!Array.isArray(obj1[key]) && !Array.isArray(obj2[key]) &&
obj1[key] !== null && obj2[key] !== null) {
mergeObjectSchemas(obj1[key], obj2[key], key, fullInterfaceName);
}
}
}
}
function generateInterface(def: InterfaceDefinition): string {
const lines: string[] = [`export interface ${def.name} {`];
for (const [propName, typeInfo] of def.properties) {
const sanitizedName = sanitizePropertyName(propName);
const optional = typeInfo.isOptional ? '?' : '';
lines.push(` ${sanitizedName}${optional}: ${typeInfo.type};`);
}
lines.push('}');
return lines.join('\n');
}
export interface ConversionOptions {
rootInterfaceName?: string;
}
function generateInstantiationExample(jsonString: string, rootName: string): string {
try {
const obj = JSON.parse(jsonString);
function formatValue(value: any, indent: number = 2): string {
const spaces = ' '.repeat(indent);
if (value === null) return 'null';
if (typeof value === 'string') return `"${value}"`;
if (typeof value === 'number' || typeof value === 'boolean') return String(value);
if (Array.isArray(value)) {
if (value.length === 0) return '[]';
const items = value.map(v => `${spaces} ${formatValue(v, indent + 2)}`).join(',\n');
return `[\n${items}\n${spaces}]`;
}
if (typeof value === 'object') {
const entries = Object.entries(value);
if (entries.length === 0) return '{}';
const props = entries.map(([k, v]) => `${spaces} ${k}: ${formatValue(v, indent + 2)}`).join(',\n');
return `{\n${props}\n${spaces}}`;
}
return 'undefined';
}
const entries = Object.entries(obj);
const props = entries.map(([key, value]) => ` ${key}: ${formatValue(value, 2)}`).join(',\n');
return `const example: ${rootName} = {\n${props}\n};`;
} catch (error) {
return `// Unable to generate example: Invalid JSON`;
}
}
/**
* Convert JSON objects to TypeScript interfaces
* @param jsonStrings - Array of JSON strings (multiple samples to detect optional fields)
* @param options - Conversion options
* @returns TypeScript interface definitions
*/
export function convertJsonToTypeScript(
jsonStrings: string[],
options: ConversionOptions = {}
): { success: boolean; output?: string; example?: string; error?: string } {
try {
// Reset state
generatedInterfaces.clear();
interfaceCounter = 0;
if (jsonStrings.length === 0) {
return { success: false, error: 'No JSON provided' };
}
const parsedObjects: any[] = [];
// Parse all JSON strings
for (const jsonStr of jsonStrings) {
if (!jsonStr.trim()) continue;
const parsed = JSON.parse(jsonStr);
parsedObjects.push(parsed);
}
if (parsedObjects.length === 0) {
return { success: false, error: 'No valid JSON objects' };
}
// Generate types from first object
const rootName = options.rootInterfaceName || 'Root';
const firstObj = parsedObjects[0];
// Create root interface
const rootInterface: InterfaceDefinition = {
name: rootName,
properties: new Map(),
};
for (const [key, value] of Object.entries(firstObj)) {
rootInterface.properties.set(key, {
type: getTypeName(value, key, rootName),
isOptional: false,
});
}
generatedInterfaces.set(rootName, rootInterface);
// Merge with additional objects to detect optional fields
for (let i = 1; i < parsedObjects.length; i++) {
mergeObjectSchemas(parsedObjects[0], parsedObjects[i], '', '');
}
// Generate TypeScript code
const interfaceCode: string[] = [];
// Generate nested interfaces first
const sortedInterfaces = Array.from(generatedInterfaces.values()).sort((a, b) => {
// Root interface last
if (a.name === rootName) return 1;
if (b.name === rootName) return -1;
return a.name.localeCompare(b.name);
});
for (const interfaceDef of sortedInterfaces) {
interfaceCode.push(generateInterface(interfaceDef));
}
const example = jsonStrings[0] ? generateInstantiationExample(jsonStrings[0], rootName) : '';
return {
success: true,
output: interfaceCode.join('\n\n'),
example,
};
} catch (error) {
return {
success: false,
error: error instanceof Error ? error.message : 'Failed to convert JSON',
};
}
}