1 import { ArrayExpression } from "@babel/types"
2 import {
3 isValidCustomFieldFormConfigPath,
4 isValidCustomFieldFormFieldPath,
5 isValidCustomFieldFormTab,
6 isValidCustomFieldFormZone,
7 type CustomFieldFormTab,
8 type CustomFieldFormZone,
9 type CustomFieldModel,
10 } from "@medusajs/admin-shared"
11 import fs from "fs/promises"
12 import { outdent } from "outdent"
13 import {
14 ExportDefaultDeclaration,
15 File,
16 isArrayExpression,
17 isCallExpression,
18 isIdentifier,
19 isMemberExpression,
20 isObjectExpression,
21 isObjectProperty,
22 isStringLiteral,
23 isTemplateLiteral,
24 NodePath,
25 ObjectExpression,
26 ObjectProperty,
27 parse,
28 ParseResult,
29 traverse,
30 } from "../babel"
31 import { logger } from "../logger"
32 import { crawl, getParserOptions, normalizePath } from "../utils"
33 import { getConfigArgument, getModel, validateLink } from "./helpers"
34
35 type CustomFieldConfigField = {
36 name: string
37 defaultValue: string
38 validation: string
39 }
40
41 type CustomFieldConfig = {
42 zone: CustomFieldFormZone
43 fields: CustomFieldConfigField[]
44 }
45
46 type CustomFieldFormField = {
47 name: string
48 label: string
49 description: string
50 placeholder: string
51 Component: string
52 validation: string
53 }
54
55 type CustomFieldFormSection = {
56 zone: CustomFieldFormZone
57 tab?: CustomFieldFormTab
58 fields: CustomFieldFormField[]
59 }
60
61 type ParsedCustomFieldConfig = {
62 import: string
63 model: CustomFieldModel
64 configs: CustomFieldConfig[] | null
65 forms: CustomFieldFormSection[] | null
66 }
67
68 export async function generateCustomFieldForms(sources: Set<string>) {
69 const files = await getFilesFromSources(sources)
70 const results = await getCustomFieldResults(files)
71
72 const imports = results.map((result) => result.import).flat()
73 const code = generateCode(results)
74
75 return {
76 imports,
77 code,
78 }
79 }
80
81 async function getFilesFromSources(sources: Set<string>): Promise<string[]> {
82 const files = (
83 await Promise.all(
84 Array.from(sources).map(async (source) =>
85 crawl(`${source}/custom-fields`)
86 )
87 )
88 ).flat()
89 return files
90 }
91
92 function generateCode(results: ParsedCustomFieldConfig[]): string {
93 const groupedByModel = new Map<CustomFieldModel, ParsedCustomFieldConfig[]>()
94
95 results.forEach((result) => {
96 const model = result.model
97 if (!groupedByModel.has(model)) {
98 groupedByModel.set(model, [])
99 }
100 groupedByModel.get(model)!.push(result)
101 })
102
103 const segments: string[] = []
104
105 groupedByModel.forEach((results, model) => {
106 const configs = results
107 .map((result) => formatConfig(result.configs))
108 .filter((config) => config !== "")
109 .join(",\n")
110 const forms = results
111 .map((result) => formatForms(result.forms))
112 .filter((form) => form !== "")
113 .join(",\n")
114
115 segments.push(outdent`
116 ${model}: {
117 configs: [
118 ${configs}
119 ],
120 forms: [
121 ${forms}
122 ],
123 }
124 `)
125 })
126
127 return outdent`
128 customFields: {
129 ${segments.join("\n")}
130 }
131 `
132 }
133
134 function formatConfig(configs: CustomFieldConfig[] | null): string {
135 if (!configs || configs.length === 0) {
136 return ""
137 }
138
139 return outdent`
140 ${configs
141 .map(
142 (config) => outdent`
143 {
144 zone: "${config.zone}",
145 fields: {
146 ${config.fields
147 .map(
148 (field) => `${field.name}: {
149 defaultValue: ${field.defaultValue},
150 validation: ${field.validation},
151 }`
152 )
153 .join(",\n")}
154 },
155 }
156 `
157 )
158 .join(",\n")}
159 `
160 }
161
162 function formatForms(forms: CustomFieldFormSection[] | null): string {
163 if (!forms || forms.length === 0) {
164 return ""
165 }
166
167 return forms
168 .map(
169 (form) => outdent`
170 {
171 zone: "${form.zone}",
172 tab: ${form.tab === undefined ? undefined : `"${form.tab}"`},
173 fields: {
174 ${form.fields
175 .map(
176 (field) => `${field.name}: {
177 validation: ${field.validation},
178 Component: ${field.Component},
179 label: ${field.label},
180 description: ${field.description},
181 placeholder: ${field.placeholder},
182 }`
183 )
184 .join(",\n")}
185 },
186 }
187 `
188 )
189 .join(",\n")
190 }
191
192 async function getCustomFieldResults(
193 files: string[]
194 ): Promise<ParsedCustomFieldConfig[]> {
195 return (
196 await Promise.all(files.map(async (file, index) => parseFile(file, index)))
197 ).filter(Boolean) as ParsedCustomFieldConfig[]
198 }
199
200 async function parseFile(
201 file: string,
202 index: number
203 ): Promise<ParsedCustomFieldConfig | null> {
204 const content = await fs.readFile(file, "utf8")
205 let ast: ParseResult<File>
206
207 try {
208 ast = parse(content, getParserOptions(file))
209 } catch (e) {
210 logger.error(`An error occurred while parsing the file`, { file, error: e })
211 return null
212 }
213
214 const import_ = generateImport(file, index)
215
216 let configs: CustomFieldConfig[] | null = []
217 let forms: CustomFieldFormSection[] | null = []
218 let model: CustomFieldModel | null = null
219 let hasLink = false
220 try {
221 traverse(ast, {
222 ExportDefaultDeclaration(path) {
223 const _model = getModel(path, file)
224
225 if (!_model) {
226 return
227 }
228
229 model = _model
230 hasLink = validateLink(path, file) // Add this line to validate link
231 configs = getConfigs(path, model, index, file)
232 forms = getForms(path, model, index, file)
233 },
234 })
235 } catch (err) {
236 logger.error(`An error occurred while traversing the file.`, {
237 file,
238 error: err,
239 })
240 return null
241 }
242
243 if (!model) {
244 logger.warn(`'model' property is missing.`, { file })
245 return null
246 }
247
248 if (!hasLink) {
249 logger.warn(`'link' property is missing.`, { file })
250 return null
251 }
252
253 return {
254 import: import_,
255 model,
256 configs,
257 forms,
258 }
259 }
260
261 function generateCustomFieldConfigName(index: number): string {
262 return `CustomFieldConfig${index}`
263 }
264
265 function generateImport(file: string, index: number): string {
266 const path = normalizePath(file)
267 return `import ${generateCustomFieldConfigName(index)} from "${path}"`
268 }
269
270 function getForms(
271 path: NodePath<ExportDefaultDeclaration>,
272 model: CustomFieldModel,
273 index: number,
274 file: string
275 ): CustomFieldFormSection[] | null {
276 const formArray = getFormsArgument(path, file)
277
278 if (!formArray) {
279 return null
280 }
281
282 const forms: CustomFieldFormSection[] = []
283
284 formArray.elements.forEach((element, j) => {
285 if (!isObjectExpression(element)) {
286 return
287 }
288
289 const zoneProperty = element.properties.find(
290 (p) => isObjectProperty(p) && isIdentifier(p.key, { name: "zone" })
291 ) as ObjectProperty | undefined
292
293 if (!zoneProperty) {
294 logger.warn(
295 `'zone' property is missing from the ${j} index of the 'forms' property. The 'zone' property is required to load a custom field form.`,
296 { file }
297 )
298 return
299 }
300
301 if (!isStringLiteral(zoneProperty.value)) {
302 logger.warn(
303 `'zone' property at the ${j} index of the 'forms' property is not a string literal. The 'zone' property must be a string literal, e.g. 'general' or 'attributes'.`,
304 { file }
305 )
306 return
307 }
308
309 const tabProperty = element.properties.find(
310 (p) => isObjectProperty(p) && isIdentifier(p.key, { name: "tab" })
311 ) as ObjectProperty | undefined
312
313 let tab: string | undefined
314
315 if (tabProperty) {
316 if (!isStringLiteral(tabProperty.value)) {
317 logger.warn(
318 `'tab' property at the ${j} index of the 'forms' property is not a string literal. The 'tab' property must be a string literal, e.g. 'general' or 'attributes'.`,
319 { file }
320 )
321 return
322 }
323
324 tab = tabProperty.value.value
325 }
326
327 if (tab && !isValidCustomFieldFormTab(tab)) {
328 logger.warn(
329 `'tab' property at the ${j} index of the 'forms' property is not a valid custom field form tab for the '${model}' model. Received: ${tab}.`,
330 { file }
331 )
332 return
333 }
334
335 const zone = zoneProperty.value.value
336 const fullPath = getFormEntryFieldPath(model, zone, tab)
337
338 if (
339 !isValidCustomFieldFormZone(zone) ||
340 !isValidCustomFieldFormFieldPath(fullPath)
341 ) {
342 logger.warn(
343 `'zone' and 'tab' properties at the ${j} index of the 'forms' property are not a valid for the '${model}' model. Received: { zone: ${zone}, tab: ${tab} }.`,
344 { file }
345 )
346 return
347 }
348
349 const fieldsObject = element.properties.find(
350 (p) => isObjectProperty(p) && isIdentifier(p.key, { name: "fields" })
351 ) as ObjectProperty | undefined
352
353 if (!fieldsObject) {
354 logger.warn(
355 `The 'fields' property is missing at the ${j} index of the 'forms' property. The 'fields' property is required to load a custom field form.`,
356 { file }
357 )
358 return
359 }
360
361 const fields: CustomFieldFormField[] = []
362
363 if (!isObjectExpression(fieldsObject.value)) {
364 logger.warn(
365 `The 'fields' property at the ${j} index of the 'forms' property is malformed. The 'fields' property must be an object.`,
366 { file }
367 )
368 return
369 }
370
371 fieldsObject.value.properties.forEach((field) => {
372 if (!isObjectProperty(field) || !isIdentifier(field.key)) {
373 return
374 }
375
376 const name = field.key.name
377
378 if (
379 !isObjectExpression(field.value) &&
380 !(
381 isCallExpression(field.value) &&
382 isMemberExpression(field.value.callee) &&
383 isIdentifier(field.value.callee.object) &&
384 isIdentifier(field.value.callee.property) &&
385 field.value.callee.object.name === "form" &&
386 field.value.callee.property.name === "define" &&
387 field.value.arguments.length === 1 &&
388 isObjectExpression(field.value.arguments[0])
389 )
390 ) {
391 logger.warn(
392 `'${name}' property in the 'fields' property at the ${j} index of the 'forms' property in ${file} is malformed. The property must be an object or a call to form.define().`,
393 { file }
394 )
395 return
396 }
397
398 const fieldObject = isObjectExpression(field.value)
399 ? field.value
400 : (field.value.arguments[0] as ObjectExpression)
401
402 const labelProperty = fieldObject.properties.find(
403 (p) => isObjectProperty(p) && isIdentifier(p.key, { name: "label" })
404 ) as ObjectProperty | undefined
405
406 const descriptionProperty = fieldObject.properties.find(
407 (p) =>
408 isObjectProperty(p) && isIdentifier(p.key, { name: "description" })
409 ) as ObjectProperty | undefined
410
411 const componentProperty = fieldObject.properties.find(
412 (p) => isObjectProperty(p) && isIdentifier(p.key, { name: "component" })
413 ) as ObjectProperty | undefined
414
415 const validationProperty = fieldObject.properties.find(
416 (p) =>
417 isObjectProperty(p) && isIdentifier(p.key, { name: "validation" })
418 ) as ObjectProperty | undefined
419
420 const placeholderProperty = fieldObject.properties.find(
421 (p) =>
422 isObjectProperty(p) && isIdentifier(p.key, { name: "placeholder" })
423 ) as ObjectProperty | undefined
424
425 const label = getFormFieldSectionValue(
426 !!labelProperty,
427 index,
428 j,
429 name,
430 "label"
431 )
432 const description = getFormFieldSectionValue(
433 !!descriptionProperty,
434 index,
435 j,
436 name,
437 "description"
438 )
439 const placeholder = getFormFieldSectionValue(
440 !!placeholderProperty,
441 index,
442 j,
443 name,
444 "placeholder"
445 )
446 const component = getFormFieldSectionValue(
447 !!componentProperty,
448 index,
449 j,
450 name,
451 "component"
452 )
453 const validation = getFormFieldSectionValue(
454 !!validationProperty,
455 index,
456 j,
457 name,
458 "validation"
459 )
460
461 fields.push({
462 name,
463 label,
464 description,
465 Component: component,
466 validation,
467 placeholder,
468 })
469 })
470
471 forms.push({
472 zone,
473 tab: tab as CustomFieldFormTab | undefined,
474 fields,
475 })
476 })
477
478 return forms.length > 0 ? forms : null
479 }
480
481 function getFormFieldSectionValue(
482 exists: boolean,
483 fileIndex: number,
484 formIndex: number,
485 fieldKey: string,
486 value: string
487 ): string {
488 if (!exists) {
489 return "undefined"
490 }
491
492 const import_ = generateCustomFieldConfigName(fileIndex)
493 return `${import_}.forms[${formIndex}].fields.${fieldKey}.${value}`
494 }
495
496 function getFormEntryFieldPath(
497 model: CustomFieldModel,
498 zone: string,
499 tab?: string
500 ): string {
501 return `${model}.${zone}.${tab ? `${tab}.` : ""}$field`
502 }
503
504 function getConfigs(
505 path: NodePath<ExportDefaultDeclaration>,
506 model: CustomFieldModel,
507 index: number,
508 file: string
509 ): CustomFieldConfig[] | null {
510 const formArray = getFormsArgument(path, file)
511
512 if (!formArray) {
513 logger.warn(`'forms' property is missing.`, { file })
514 return null
515 }
516
517 const configs: CustomFieldConfig[] = []
518
519 formArray.elements.forEach((element, j) => {
520 if (!isObjectExpression(element)) {
521 logger.warn(
522 `'forms' property at the ${j} index is malformed. The 'forms' property must be an object.`,
523 { file }
524 )
525 return
526 }
527
528 const zoneProperty = element.properties.find(
529 (p) => isObjectProperty(p) && isIdentifier(p.key, { name: "zone" })
530 ) as ObjectProperty | undefined
531
532 if (!zoneProperty) {
533 logger.warn(
534 `'zone' property is missing from the ${j} index of the 'forms' property.`,
535 { file }
536 )
537 return
538 }
539
540 if (isTemplateLiteral(zoneProperty.value)) {
541 logger.warn(
542 `'zone' property at the ${j} index of the 'forms' property cannot be a template literal (e.g. \`general\`).`,
543 { file }
544 )
545 return
546 }
547
548 if (!isStringLiteral(zoneProperty.value)) {
549 logger.warn(
550 `'zone' property at the ${j} index of the 'forms' property is not a string literal (e.g. 'general' or 'attributes').`,
551 { file }
552 )
553 return
554 }
555
556 const zone = zoneProperty.value.value
557 const fullPath = getFormEntryConfigPath(model, zone)
558
559 if (
560 !isValidCustomFieldFormZone(zone) ||
561 !isValidCustomFieldFormConfigPath(fullPath)
562 ) {
563 logger.warn(
564 `'zone' property at the ${j} index of the 'forms' property is not a valid custom field form zone for the '${model}' model. Received: ${zone}.`
565 )
566 return
567 }
568
569 const fieldsObject = element.properties.find(
570 (p) => isObjectProperty(p) && isIdentifier(p.key, { name: "fields" })
571 ) as ObjectProperty | undefined
572
573 if (!fieldsObject) {
574 logger.warn(
575 `'fields' property is missing from the ${j} entry in the 'forms' property in ${file}.`,
576 { file }
577 )
578 return
579 }
580
581 const fields: CustomFieldConfigField[] = []
582
583 if (!isObjectExpression(fieldsObject.value)) {
584 logger.warn(
585 `'fields' property at the ${j} index of the 'forms' property is malformed. The 'fields' property must be an object.`,
586 { file }
587 )
588 return
589 }
590
591 fieldsObject.value.properties.forEach((field) => {
592 if (!isObjectProperty(field) || !isIdentifier(field.key)) {
593 return
594 }
595
596 const name = field.key.name
597
598 if (
599 !isObjectExpression(field.value) &&
600 !(
601 isCallExpression(field.value) &&
602 isMemberExpression(field.value.callee) &&
603 isIdentifier(field.value.callee.object) &&
604 isIdentifier(field.value.callee.property) &&
605 field.value.callee.object.name === "form" &&
606 field.value.callee.property.name === "define" &&
607 field.value.arguments.length === 1 &&
608 isObjectExpression(field.value.arguments[0])
609 )
610 ) {
611 logger.warn(
612 `'${name}' property in the 'fields' property at the ${j} index of the 'forms' property in ${file} is malformed. The property must be an object or a call to form.define().`,
613 { file }
614 )
615 return
616 }
617
618 const fieldObject = isObjectExpression(field.value)
619 ? field.value
620 : (field.value.arguments[0] as ObjectExpression)
621
622 const defaultValueProperty = fieldObject.properties.find(
623 (p) =>
624 isObjectProperty(p) && isIdentifier(p.key, { name: "defaultValue" })
625 ) as ObjectProperty | undefined
626
627 if (!defaultValueProperty) {
628 logger.warn(
629 `'defaultValue' property is missing at the ${j} index of the 'forms' property in ${file}.`,
630 { file }
631 )
632 return
633 }
634
635 const validationProperty = fieldObject.properties.find(
636 (p) =>
637 isObjectProperty(p) && isIdentifier(p.key, { name: "validation" })
638 ) as ObjectProperty | undefined
639
640 if (!validationProperty) {
641 logger.warn(
642 `'validation' property is missing at the ${j} index of the 'forms' property in ${file}.`,
643 { file }
644 )
645 return
646 }
647
648 const defaultValue = getFormFieldValue(index, j, name, "defaultValue")
649 const validation = getFormFieldValue(index, j, name, "validation")
650
651 fields.push({
652 name,
653 defaultValue,
654 validation,
655 })
656 })
657
658 configs.push({
659 zone: zone,
660 fields,
661 })
662 })
663
664 return configs.length > 0 ? configs : null
665 }
666
667 function getFormFieldValue(
668 fileIndex: number,
669 formIndex: number,
670 fieldKey: string,
671 value: string
672 ): string {
673 const import_ = generateCustomFieldConfigName(fileIndex)
674 return `${import_}.forms[${formIndex}].fields.${fieldKey}.${value}`
675 }
676
677 function getFormEntryConfigPath(model: CustomFieldModel, zone: string): string {
678 return `${model}.${zone}.$config`
679 }
680
681 function getFormsArgument(
682 path: NodePath<ExportDefaultDeclaration>,
683 file: string
684 ): ArrayExpression | null {
685 const configArgument = getConfigArgument(path)
686
687 if (!configArgument) {
688 return null
689 }
690
691 const formProperty = configArgument.properties.find(
692 (p) => isObjectProperty(p) && isIdentifier(p.key, { name: "forms" })
693 ) as ObjectProperty | undefined
694
695 if (!formProperty) {
696 return null
697 }
698
699 if (!isArrayExpression(formProperty.value)) {
700 logger.warn(
701 `The 'forms' property is malformed. The 'forms' property must be an array of objects.`,
702 { file }
703 )
704 return null
705 }
706
707 return formProperty.value
708 }