* Parse robots.txt content into structured rules * @param content - The content of robots.txt * @returns Array of parsed rules
(content: string)
| 18 | * @returns Array of parsed rules |
| 19 | */ |
| 20 | function parseRobotsTxt(content: string): RobotsRule[] { |
| 21 | const lines = content.split("\n"); |
| 22 | const rules: RobotsRule[] = []; |
| 23 | |
| 24 | let currentRule: RobotsRule | null = null; |
| 25 | |
| 26 | for (const line of lines) { |
| 27 | const trimmedLine = line.trim(); |
| 28 | |
| 29 | // Skip comments and empty lines |
| 30 | if (!trimmedLine || trimmedLine.startsWith("#")) { |
| 31 | continue; |
| 32 | } |
| 33 | |
| 34 | // Split into directive and value |
| 35 | const [directive, ...valueParts] = trimmedLine.split(":"); |
| 36 | const value = valueParts.join(":").trim(); |
| 37 | |
| 38 | if (!directive || !value) { |
| 39 | continue; |
| 40 | } |
| 41 | |
| 42 | const directiveLower = directive.trim().toLowerCase(); |
| 43 | |
| 44 | // Start a new rule when encountering a User-agent directive |
| 45 | if (directiveLower === "user-agent") { |
| 46 | if (currentRule && currentRule.userAgent) { |
| 47 | rules.push(currentRule); |
| 48 | } |
| 49 | currentRule = { userAgent: value, disallow: [], allow: [] }; |
| 50 | } |
| 51 | // Add disallow paths |
| 52 | else if (directiveLower === "disallow" && currentRule) { |
| 53 | currentRule.disallow.push(value); |
| 54 | } |
| 55 | // Add allow paths |
| 56 | else if (directiveLower === "allow" && currentRule) { |
| 57 | currentRule.allow.push(value); |
| 58 | } |
| 59 | } |
| 60 | |
| 61 | // Add the last rule if exists |
| 62 | if (currentRule && currentRule.userAgent) { |
| 63 | rules.push(currentRule); |
| 64 | } |
| 65 | |
| 66 | return rules; |
| 67 | } |
| 68 | |
| 69 | /** |
| 70 | * Check if a path is allowed according to robots.txt rules |