|
| 1 | +import { |
| 2 | + isArrayNode, |
| 3 | + isLiteralNode, |
| 4 | + isObjectNode, |
| 5 | + isPropertyNode, |
| 6 | + Severity, |
| 7 | + SourceCodeType, |
| 8 | +} from '../../types'; |
| 9 | + |
| 10 | +import type { ArrayNode, PropertyNode, JSONCheckDefinition } from '../../types'; |
| 11 | + |
| 12 | +export const UniqueSettingIds: JSONCheckDefinition = { |
| 13 | + meta: { |
| 14 | + code: 'UniqueSettingId', |
| 15 | + name: 'Prevent duplicate Ids in setting_schema', |
| 16 | + docs: { |
| 17 | + description: 'This check is aimed at eliminating duplicate Ids in settings_schema.json', |
| 18 | + recommended: true, |
| 19 | + // url: 'https://shopify.dev/docs/storefronts/themes/tools/theme-check/checks/valid-schema', |
| 20 | + }, |
| 21 | + type: SourceCodeType.JSON, |
| 22 | + severity: Severity.ERROR, |
| 23 | + schema: {}, |
| 24 | + targets: [], |
| 25 | + }, |
| 26 | + |
| 27 | + create(context) { |
| 28 | + return { |
| 29 | + async onCodePathEnd(file) { |
| 30 | + if (isArrayNode(file.ast)) { |
| 31 | + const settingIds: PropertyNode[] = []; |
| 32 | + |
| 33 | + /* Find and loop through all of our nodes that have an id value and find their key value */ |
| 34 | + for (const child of file.ast.children) { |
| 35 | + if (isObjectNode(child) && child.children) { |
| 36 | + const settingsNode = child.children.find((node) => node.key.value === 'settings'); |
| 37 | + |
| 38 | + if (settingsNode && settingsNode.value && isArrayNode(settingsNode.value)) { |
| 39 | + for (const setting of settingsNode.value.children) { |
| 40 | + if (isObjectNode(setting) && setting.children) { |
| 41 | + const idNode = setting.children.find((node) => node.key.value === 'id'); |
| 42 | + if (isPropertyNode(idNode)) { |
| 43 | + settingIds.push(idNode); |
| 44 | + } |
| 45 | + } |
| 46 | + } |
| 47 | + } |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + /* Check for dupes */ |
| 52 | + const idMap = new Map<string, PropertyNode[]>(); |
| 53 | + for (const node of settingIds) { |
| 54 | + if (isLiteralNode(node.value)) { |
| 55 | + const id = node.value.value; |
| 56 | + if (typeof id === 'string') { |
| 57 | + if (!idMap.has(id)) { |
| 58 | + idMap.set(id, []); |
| 59 | + } |
| 60 | + idMap.get(id)!.push(node); |
| 61 | + } |
| 62 | + } |
| 63 | + } |
| 64 | + |
| 65 | + const duplicates: [string, PropertyNode[]][] = Array.from(idMap.entries()).filter( |
| 66 | + ([_, nodes]) => nodes.length > 1, |
| 67 | + ); |
| 68 | + |
| 69 | + if (duplicates.length > 0) { |
| 70 | + for (const [id, nodes] of duplicates) { |
| 71 | + const lastNodeFound = nodes[nodes.length - 1]; |
| 72 | + |
| 73 | + context.report({ |
| 74 | + message: `Duplicate setting id found: "${id}"`, |
| 75 | + startIndex: lastNodeFound.loc.start.offset, |
| 76 | + endIndex: lastNodeFound.loc.end.offset, |
| 77 | + }); |
| 78 | + } |
| 79 | + } |
| 80 | + } |
| 81 | + }, |
| 82 | + }; |
| 83 | + }, |
| 84 | +}; |
0 commit comments