| 1 | import { BLOCK_TYPES, BlockType } from "./getBlockType.js"; |
| 2 | |
| 3 | export class BlockDuplicationDetector { |
| 4 | private records: Map<string, Set<string>>; |
| 5 | |
| 6 | constructor() { |
| 7 | this.records = new Map(); |
| 8 | for (const blockType of BLOCK_TYPES) { |
| 9 | this.records.set(blockType, new Set()); |
| 10 | } |
| 11 | } |
| 12 | |
| 13 | private isRuleDuplicated(rule: any): boolean { |
| 14 | if (typeof rule === "string") { |
| 15 | return this.check(rule, "rules"); |
| 16 | } else { |
| 17 | return this.check(rule.name, "rules"); |
| 18 | } |
| 19 | } |
| 20 | |
| 21 | private isContextDuplicated(context: any): boolean { |
| 22 | return this.check(context.provider, "context"); |
| 23 | } |
| 24 | |
| 25 | private isCommonBlockDuplicated(block: any, blockType: BlockType): boolean { |
| 26 | return this.check(block.name, blockType); |
| 27 | } |
| 28 | |
| 29 | private check(identifier: string, blockType: BlockType): boolean { |
| 30 | if (this.records.get(blockType)!.has(identifier)) { |
| 31 | return true; |
| 32 | } else { |
| 33 | this.records.get(blockType)!.add(identifier); |
| 34 | return false; |
| 35 | } |
| 36 | } |
| 37 | |
| 38 | // Check if the name is duplicated within the same blockType |
| 39 | isDuplicated( |
| 40 | block: any, |
| 41 | blockType: BlockType, |
| 42 | injectError?: (errorMsg: string) => void, |
| 43 | ): boolean { |
| 44 | // Not checking any null or undefined object |
| 45 | if (block === null || block === undefined) { |
| 46 | return false; |
| 47 | } |
| 48 | |
| 49 | switch (blockType) { |
| 50 | case "rules": |
| 51 | if (this.isRuleDuplicated(block)) { |
| 52 | injectError?.( |
| 53 | `Duplicate rules${typeof block === "string" ? "" : ` named ${block.name}`} detected. The duplicate one has been deleted for preventing unexpected behavior.`, |
| 54 | ); |
| 55 | return true; |
| 56 | } |
| 57 | return false; |
| 58 | case "context": |
| 59 | if (this.isContextDuplicated(block)) { |
| 60 | injectError?.( |
| 61 | `Duplicate ${block.provider} context providers detected. The duplicate one has been deleted for preventing unexpected behavior.`, |
| 62 | ); |
| 63 | return true; |
| 64 | } |
| 65 | return false; |
| 66 | default: |
| 67 | if (this.isCommonBlockDuplicated(block, blockType)) { |
| 68 | injectError?.( |
| 69 | `Duplicate ${blockType} named ${block.name} detected. The duplicate one has been deleted for preventing unexpected behavior.`, |
| 70 | ); |
| 71 | return true; |
| 72 | } |
| 73 | return false; |
| 74 | } |
| 75 | } |
| 76 | } |