@cobola/dsh-geo 0.0.0-stage → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/robots.js ADDED
@@ -0,0 +1,209 @@
1
+ /**
2
+ * Minimal, deterministic robots.txt handling (RFC 9309 semantics).
3
+ *
4
+ * Only what an audit needs: group parsing, UA selection, longest-match path
5
+ * rules, Allow-over-Disallow ties, crawl-delay, sitemap declarations, and a
6
+ * per-crawler verdict for the AI agents a GEO audit cares about.
7
+ */
8
+
9
+ export const AI_CRAWLERS = [
10
+ 'gptbot',
11
+ 'oai-searchbot',
12
+ 'chatgpt-user',
13
+ 'claudebot',
14
+ 'anthropic-ai',
15
+ 'perplexitybot',
16
+ 'google-extended',
17
+ 'ccbot',
18
+ 'bytespider',
19
+ 'applebot-extended',
20
+ ];
21
+
22
+ /**
23
+ * @param {string} text robots.txt body.
24
+ * @returns {{groups: Array<{agents: string[], rules: Array<{allow: boolean, path: string}>, crawlDelay: number|null}>, sitemaps: string[], hasRules: boolean}}
25
+ */
26
+ export function parseRobots(text) {
27
+ const groups = [];
28
+ const sitemaps = [];
29
+ let current = null;
30
+ let seenDirective = false;
31
+
32
+ for (const rawLine of String(text ?? '').split(/\r?\n/)) {
33
+ const line = rawLine.replace(/#.*$/, '').trim();
34
+ if (!line) continue;
35
+ const separator = line.indexOf(':');
36
+ if (separator === -1) continue;
37
+ const field = line.slice(0, separator).trim().toLowerCase();
38
+ const value = line.slice(separator + 1).trim();
39
+
40
+ if (field === 'user-agent') {
41
+ if (!current || seenDirective) {
42
+ current = { agents: [], rules: [], crawlDelay: null };
43
+ groups.push(current);
44
+ seenDirective = false;
45
+ }
46
+ current.agents.push(value.toLowerCase());
47
+ continue;
48
+ }
49
+
50
+ if (field === 'sitemap') {
51
+ if (value) sitemaps.push(value);
52
+ continue;
53
+ }
54
+
55
+ if (field === 'allow' || field === 'disallow') {
56
+ if (!current) {
57
+ current = { agents: ['*'], rules: [], crawlDelay: null };
58
+ groups.push(current);
59
+ }
60
+ seenDirective = true;
61
+ if (value) current.rules.push({ allow: field === 'allow', path: value });
62
+ continue;
63
+ }
64
+
65
+ if (field === 'crawl-delay') {
66
+ if (!current) continue;
67
+ seenDirective = true;
68
+ const delay = Number(value);
69
+ if (Number.isFinite(delay) && delay >= 0) current.crawlDelay = delay;
70
+ }
71
+ }
72
+
73
+ return {
74
+ groups,
75
+ sitemaps,
76
+ hasRules: groups.some((group) => group.rules.length > 0),
77
+ };
78
+ }
79
+
80
+ function uaTokens(userAgent) {
81
+ return String(userAgent ?? '')
82
+ .toLowerCase()
83
+ .split(/[\s/()]+/)
84
+ .filter(Boolean);
85
+ }
86
+
87
+ function selectGroups(robots, userAgent) {
88
+ const tokens = uaTokens(userAgent);
89
+ const matches = (agent) => tokens.some((token) => token === agent || token.startsWith(`${agent}/`));
90
+ let bestLength = -1;
91
+ const matched = [];
92
+ for (const group of robots.groups) {
93
+ for (const agent of group.agents) {
94
+ if (agent === '*') continue;
95
+ if (matches(agent) && agent.length > bestLength) {
96
+ bestLength = agent.length;
97
+ matched.length = 0;
98
+ matched.push(group);
99
+ } else if (matches(agent) && agent.length === bestLength && !matched.includes(group)) {
100
+ matched.push(group);
101
+ }
102
+ }
103
+ }
104
+ if (matched.length > 0) return matched;
105
+ return robots.groups.filter((group) => group.agents.includes('*'));
106
+ }
107
+
108
+ function ruleMatches(pattern, path) {
109
+ if (!pattern) return false;
110
+ const anchored = pattern.endsWith('$');
111
+ const body = anchored ? pattern.slice(0, -1) : pattern;
112
+ const expression = body.replace(/[.+^${}()|[\]\\?]/g, '\\$&').replace(/\*/g, '.*');
113
+ try {
114
+ return new RegExp(`^${expression}${anchored ? '$' : ''}`).test(path);
115
+ } catch {
116
+ return false;
117
+ }
118
+ }
119
+
120
+ function requestPath(url) {
121
+ try {
122
+ const parsed = new URL(url);
123
+ return `${parsed.pathname}${parsed.search}`;
124
+ } catch {
125
+ return String(url ?? '/').startsWith('/') ? String(url) : `/${String(url ?? '')}`;
126
+ }
127
+ }
128
+
129
+ /**
130
+ * Whether `userAgent` may fetch `url` under this robots file.
131
+ * @param {ReturnType<typeof parseRobots>} robots
132
+ * @param {string} url
133
+ * @param {string} userAgent
134
+ */
135
+ export function isAllowed(robots, url, userAgent) {
136
+ const groups = selectGroups(robots, userAgent);
137
+ if (groups.length === 0) return true;
138
+ const path = requestPath(url);
139
+ let best = null;
140
+ for (const group of groups) {
141
+ for (const rule of group.rules) {
142
+ if (!ruleMatches(rule.path, path)) continue;
143
+ const length = rule.path.length;
144
+ if (!best || length > best.length || (length === best.length && rule.allow && !best.allow)) {
145
+ best = { allow: rule.allow, length };
146
+ }
147
+ }
148
+ }
149
+ return best ? best.allow : true;
150
+ }
151
+
152
+ /**
153
+ * Crawl delay in milliseconds for this UA (largest declared value wins).
154
+ * @param {ReturnType<typeof parseRobots>} robots
155
+ * @param {string} userAgent
156
+ */
157
+ export function crawlDelayMs(robots, userAgent) {
158
+ const groups = selectGroups(robots, userAgent);
159
+ let seconds = 0;
160
+ for (const group of groups) {
161
+ if (typeof group.crawlDelay === 'number') seconds = Math.max(seconds, group.crawlDelay);
162
+ }
163
+ return Math.round(seconds * 1000);
164
+ }
165
+
166
+ /**
167
+ * What each major AI crawler is told. `unmentioned` means no group names it,
168
+ * so the `*` group (or no rules at all) decides.
169
+ * @param {ReturnType<typeof parseRobots>} robots
170
+ * @param {string} [path]
171
+ */
172
+ export function aiCrawlerPolicy(robots, path = '/') {
173
+ const normalized = path.startsWith('/') ? path : `/${path}`;
174
+ return AI_CRAWLERS.map((agent) => {
175
+ const named = robots.groups.some((group) => group.agents.includes(agent));
176
+ const status = !named ? 'unmentioned' : isAllowed(robots, normalized, agent) ? 'allow' : 'deny';
177
+ return { agent, status };
178
+ });
179
+ }
180
+
181
+ /**
182
+ * Googlebot access at the site root, plus the image crawler's root access.
183
+ * @param {ReturnType<typeof parseRobots>} robots
184
+ */
185
+ export function googlebotAccess(robots) {
186
+ return {
187
+ allowed: isAllowed(robots, '/', 'Googlebot'),
188
+ imageAllowed: isAllowed(robots, '/', 'Googlebot-Image'),
189
+ };
190
+ }
191
+
192
+ /**
193
+ * Bingbot access at the site root.
194
+ * @param {ReturnType<typeof parseRobots>} robots
195
+ */
196
+ export function bingbotAccess(robots) {
197
+ return {
198
+ allowed: isAllowed(robots, '/', 'Bingbot'),
199
+ previewAllowed: isAllowed(robots, '/', 'BingPreview'),
200
+ };
201
+ }
202
+
203
+ /**
204
+ * True when the file forbids the whole site to everyone.
205
+ * @param {ReturnType<typeof parseRobots>} robots
206
+ */
207
+ export function blocksEverything(robots) {
208
+ return !isAllowed(robots, '/', '*');
209
+ }