robots-parser 3.0.1 → 3.1.1

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/CHANGELOG.md CHANGED
@@ -1,9 +1,41 @@
1
1
  # Changelog
2
2
 
3
+ ## Version 3.1.1
4
+
5
+ - Fixed bug from 3.1.0 with sitemap, crawl-delay, host and unknown directives not terminating groups.
6
+ – Thanks to @bardrop for reporting and fixing.
7
+
8
+ ## Version 3.1.0
9
+
10
+ - Updated README to point to RFC 9309 instead of the draft specification.
11
+ – Thanks to @joepie91 for reporting.
12
+ - Fixed CommonJS export type in typescript definitions.
13
+ – Thanks to @markedwards for fixing.
14
+ - Added `isExplicitlyDisallowed()` method.
15
+ – Thanks to @AuDigent for implementing.
16
+ - Fixed grouping to match RFC 9309 by not treating non-standard directives like crawl-delay as terminating a group.
17
+ – Thanks to @bensynapse for reporting.
18
+ - Fixed URL encoded path handling to match RFC 9309.
19
+ – Thanks to @bensynapse for reporting.
20
+ - Fixed bug with /robots.txt not being implicitly allowed as required by RFC 9309.
21
+ – Thanks to @bensynapse for reporting.
22
+ - Fixed bug with user-agent not followed by any directives not creating new group.
23
+ – Thanks to @bensynapse for reporting.
24
+ - Added Synapse rfc9309-test-vectors.json tests.
25
+
26
+ RFC 9309 test vectors by Synapse, https://synapsereality.io/open-source/answer-crawler-check/rfc9309-test-vectors/, CC BY 4.0, https://creativecommons.org/licenses/by/4.0/
27
+ - Fixed user-agent to be more restrictive in what it accepts as a name to match RFC 9309.
28
+ - Added parsing limit of 2097152 characters.
29
+ - Changed the matching algorithm to a linear `O(N)` instead of `O(M*N)` worst case.
30
+
31
+ The previous matching algorithm was one from google/robotstxt which was used to ensure compatibility with any edge cases. This new algorithm should be fully compatible.
32
+
33
+ – Thanks to @EQSTLab for reporting.
34
+
3
35
  ## Version 3.0.1
4
36
 
5
37
  - Fixed bug with `https:` URLs defaulting to port `80` instead of `443` if no port is specified.
6
- Thanks to @dskvr for reporting
38
+ – Thanks to @dskvr for reporting
7
39
 
8
40
  This affects comparing URLs with the default HTTPs port to URLs without it.
9
41
  For example, comparing `https://example.com/` to `https://example.com:443/` or vice versa.
package/README.md CHANGED
@@ -1,12 +1,12 @@
1
1
  # Robots Parser [![NPM downloads](https://img.shields.io/npm/dm/robots-parser)](https://www.npmjs.com/package/robots-parser) [![DeepScan grade](https://deepscan.io/api/teams/457/projects/16277/branches/344939/badge/grade.svg)](https://deepscan.io/dashboard#view=project&tid=457&pid=16277&bid=344939) [![GitHub license](https://img.shields.io/github/license/samclarke/robots-parser.svg)](https://github.com/samclarke/robots-parser/blob/master/license.md) [![Coverage Status](https://coveralls.io/repos/github/samclarke/robots-parser/badge.svg?branch=master)](https://coveralls.io/github/samclarke/robots-parser?branch=master)
2
2
 
3
- A robots.txt parser which aims to be complaint with the [draft specification](https://datatracker.ietf.org/doc/html/draft-koster-rep).
3
+ A robots.txt parser which aims to be complaint with the [RFC 9309 specification](https://datatracker.ietf.org/doc/html/rfc9309).
4
4
 
5
5
  The parser currently supports:
6
6
 
7
7
  - User-agent:
8
8
  - Allow:
9
- - Disallow:
9
+ - Disallow (with explicit mode support):
10
10
  - Sitemap:
11
11
  - Crawl-delay:
12
12
  - Host:
@@ -41,6 +41,7 @@ var robots = robotsParser('http://www.example.com/robots.txt', [
41
41
  robots.isAllowed('http://www.example.com/test.html', 'Sams-Bot/1.0'); // true
42
42
  robots.isAllowed('http://www.example.com/dir/test.html', 'Sams-Bot/1.0'); // true
43
43
  robots.isDisallowed('http://www.example.com/dir/test2.html', 'Sams-Bot/1.0'); // true
44
+ robots.isExplicitlyDisallowed('http://www.example.com/dir/test2.html', 'Sams-Bot/1.0'); // false
44
45
  robots.getCrawlDelay('Sams-Bot/1.0'); // 1
45
46
  robots.getSitemaps(); // ['http://example.com/sitemap.xml']
46
47
  robots.getPreferredHost(); // example.com
@@ -62,6 +63,23 @@ Returns true if crawling the specified URL is not allowed for the specified user
62
63
 
63
64
  This will return `undefined` if the URL isn't valid for this robots.txt.
64
65
 
66
+ ### isExplicitlyDisallowed(url, ua)
67
+
68
+ **boolean or undefined**
69
+
70
+ > [!CAUTION]
71
+ > This is not part of the robots.txt specification and should only be used with
72
+ > the websites owners permission.
73
+ > This method is only intended for special purposes where a user-agent shouldn't
74
+ > fallback to matching against global (*) rules.
75
+ >
76
+ > An example of this behaviour is [Google AdsBot](https://developers.google.com/search/docs/crawling-indexing/google-special-case-crawlers)
77
+ > which must be explicitly excluded. This is done with the website owners permission.
78
+
79
+ Returns trues if explicitly disallowed for the specified user agent (User Agent wildcards are discarded).
80
+
81
+ This will return undefined if the URL is not valid for this robots.txt file.
82
+
65
83
  ### getMatchingLineNumber(url, [ua])
66
84
 
67
85
  **number or undefined**
@@ -94,6 +112,38 @@ Returns the preferred host name specified by the `host:` directive or null if th
94
112
 
95
113
  # Changes
96
114
 
115
+ ## Version 3.1.1
116
+
117
+ - Fixed bug from 3.1.0 with sitemap, crawl-delay, host and unknown directives not terminating groups.
118
+ – Thanks to @bardrop for reporting and fixing.
119
+
120
+ ## Version 3.1.0
121
+
122
+ - Updated README to point to RFC 9309 instead of the draft specification.
123
+ – Thanks to @joepie91 for reporting.
124
+ - Fixed CommonJS export type in typescript definitions.
125
+ – Thanks to @markedwards for fixing.
126
+ - Added `isExplicitlyDisallowed()` method.
127
+ – Thanks to @AuDigent for implementing.
128
+ - Fixed grouping to match RFC 9309 by not treating non-standard directives like crawl-delay as terminating a group.
129
+ – Thanks to @bensynapse for reporting.
130
+ - Fixed URL encoded path handling to match RFC 9309.
131
+ – Thanks to @bensynapse for reporting.
132
+ - Fixed bug with /robots.txt not being implicitly allowed as required by RFC 9309.
133
+ – Thanks to @bensynapse for reporting.
134
+ - Fixed bug with user-agent not followed by any directives not creating new group.
135
+ – Thanks to @bensynapse for reporting.
136
+ - Added Synapse rfc9309-test-vectors.json tests.
137
+
138
+ RFC 9309 test vectors by Synapse, https://synapsereality.io/open-source/answer-crawler-check/rfc9309-test-vectors/, CC BY 4.0, https://creativecommons.org/licenses/by/4.0/
139
+ - Fixed user-agent to be more restrictive in what it accepts as a name to match RFC 9309.
140
+ - Added parsing limit of 2097152 characters.
141
+ - Changed the matching algorithm to a linear `O(N)` instead of `O(M*N)` worst case.
142
+
143
+ The previous matching algorithm was one from google/robotstxt which was used to ensure compatibility with any edge cases. This new algorithm should be fully compatible.
144
+
145
+ – Thanks to @EQSTLab for reporting.
146
+
97
147
  ### Version 3.0.1
98
148
 
99
149
  - Fixed bug with `https:` URLs defaulting to port `80` instead of `443` if no port is specified.
package/Robots.js CHANGED
@@ -63,14 +63,15 @@ function splitLine(line) {
63
63
  */
64
64
  function formatUserAgent(userAgent) {
65
65
  var formattedUserAgent = userAgent.toLowerCase();
66
-
67
- // Strip the version number from robot/1.0 user agents
68
- var idx = formattedUserAgent.indexOf('/');
69
- if (idx > -1) {
70
- formattedUserAgent = formattedUserAgent.substr(0, idx);
66
+ if (formattedUserAgent[0] === '*') {
67
+ return '*';
71
68
  }
72
69
 
73
- return formattedUserAgent.trim();
70
+ // 2.2.1. The User-Agent Line
71
+ // The product token MUST contain only uppercase and lowercase letters
72
+ // ("a-z" and "A-Z"), underscores ("_"), and hyphens ("-"). The
73
+ var match = formattedUserAgent.match(/^[a-zA-Z_-]+/);
74
+ return match && match[0] ? match[0] : '';
74
75
  }
75
76
 
76
77
  /**
@@ -83,91 +84,252 @@ function formatUserAgent(userAgent) {
83
84
  */
84
85
  function normaliseEncoding(path) {
85
86
  try {
86
- return urlEncodeToUpper(encodeURI(path).replace(/%25/g, '%'));
87
+ // Encode any non-ASCII chars
88
+ return safeDecodeURI(path).replace(/[^\x00-\x7F]/gu, (char) => {
89
+ return encodeURIComponent(char).toUpperCase();
90
+ });
87
91
  } catch (e) {
88
92
  return path;
89
93
  }
90
94
  }
91
95
 
92
96
  /**
93
- * Convert URL encodings to support case.
94
- *
95
- * e.g.: %2a%ef becomes %2A%EF
96
- *
97
+ * Only decodes alpha numeric and - . _ ~ characters and converts all others to
98
+ * uppercase.
97
99
  * @param {string} path
98
- * @return {string}
99
- * @private
100
100
  */
101
- function urlEncodeToUpper(path) {
102
- return path.replace(/%[0-9a-fA-F]{2}/g, function (match) {
103
- return match.toUpperCase();
101
+ function safeDecodeURI(path) {
102
+ return path.replace(/%[0-9a-f]{2}/gi, (match) => {
103
+ const code = parseInt(match.slice(1), 16);
104
+ const isUnreserved =
105
+ (code >= 0x41 && code <= 0x5a) || // A-Z
106
+ (code >= 0x61 && code <= 0x7a) || // a-z
107
+ (code >= 0x30 && code <= 0x39) || // 0-9
108
+ code === 0x2d || // -
109
+ code === 0x2e || // .
110
+ code === 0x5f || // _
111
+ code === 0x7e; // ~
112
+
113
+ return isUnreserved ? String.fromCharCode(code) : match.toUpperCase();
104
114
  });
105
115
  }
106
116
 
107
117
  /**
108
- * Matches a pattern with the specified path
109
118
  *
110
- * Uses same algorithm to match patterns as the Google implementation in
111
- * google/robotstxt so it should be consistent with the spec.
119
+ * @param {string} pattern
120
+ * @returns {Float64Array}
121
+ */
122
+ function makeGoodSuffixTable(pattern) {
123
+ const m = pattern.length;
124
+ // Float64 is the same as number in JS so will allow indexing up to the spec
125
+ // limit of a JS string length 2^(53 - 1). Most implementations cap strings
126
+ // significantly below that limit and and no pattern should ever be that
127
+ // long, so Uint32Array could be used but Float64Array has the same
128
+ // performance so might as well be spec compliant.
129
+ const suffixes = new Float64Array(m);
130
+ const goodSuffixTable = new Float64Array(m).fill(m);
131
+
132
+ suffixes[m - 1] = m;
133
+ let g = m - 1;
134
+ let f = 0;
135
+
136
+ for (let i = m - 2; i >= 0; --i) {
137
+ if (i > g && suffixes[i + m - 1 - f] < i - g) {
138
+ suffixes[i] = suffixes[i + m - 1 - f];
139
+ } else {
140
+ if (i < g) {
141
+ g = i;
142
+ }
143
+
144
+ f = i;
145
+ while (g >= 0 && pattern[g] === pattern[g + m - 1 - f]) {
146
+ g--;
147
+ }
148
+ suffixes[i] = f - g;
149
+ }
150
+ }
151
+
152
+ let j = 0;
153
+ for (let i = m - 1; i >= 0; i--) {
154
+ if (suffixes[i] === i + 1) {
155
+ for (; j < m - 1 - i; j++) {
156
+ goodSuffixTable[j] = m - 1 - i;
157
+ }
158
+ }
159
+ }
160
+
161
+ for (let i = 0; i <= m - 2; i++) {
162
+ goodSuffixTable[m - 1 - suffixes[i]] = m - 1 - i;
163
+ }
164
+
165
+ return goodSuffixTable;
166
+ }
167
+
168
+ /**
169
+ * Boyer-Moore which returns on the first match. This has a worst case of O(N)
170
+ * time and O(M) space.
171
+ *
172
+ * It is not O(N*M) worst case as it stops at first match. If it was finding all
173
+ * matches, then it would be O(N+R*M) which would be O(N*M) worst case for a
174
+ * repeating character string. The Galil rule changes that to linear matching
175
+ * when finding all matches but as this is only getting first match it is O(N).
176
+ *
177
+ * @param {string} needle
178
+ * @param {string} haystack
179
+ * @param {number} startIndex
180
+ * @returns {number}
181
+ */
182
+ function boyerMoore(needle, haystack, startIndex) {
183
+ const n = haystack.length;
184
+ const m = needle.length;
185
+
186
+ if (n < m || startIndex < 0 || startIndex > n - m) {
187
+ return -1;
188
+ }
189
+
190
+ const badCharacterTable = new Map();
191
+ for (let i = 0; i < m - 1; i++) {
192
+ badCharacterTable.set(needle[i], m - 1 - i);
193
+ }
194
+
195
+ const goodSuffixTable = makeGoodSuffixTable(needle);
196
+
197
+ let j = startIndex;
198
+ while (j <= n - m) {
199
+ let i = m - 1;
200
+
201
+ while (i >= 0 && needle[i] === haystack[j + i]) {
202
+ i--;
203
+ }
204
+
205
+ if (i < 0) {
206
+ return j;
207
+ }
208
+
209
+ const matchedLength = m - 1 - i;
210
+ const badCharacterShift = badCharacterTable.has(haystack[j + i])
211
+ ? badCharacterTable.get(haystack[j + i]) - matchedLength
212
+ : m - matchedLength;
213
+ const goodSuffixShift = goodSuffixTable[i];
214
+
215
+ j += Math.max(goodSuffixShift, badCharacterShift, 1);
216
+ }
217
+
218
+ return -1;
219
+ }
220
+
221
+ /**
222
+ * @param {string} needle
223
+ * @param {string} haystack
224
+ * @param {Number} index
225
+ * @returns {Number}
226
+ */
227
+ function indexOf(needle, haystack, index) {
228
+ if (needle === '') {
229
+ return index;
230
+ }
231
+
232
+ const n = haystack.length - index;
233
+
234
+ // For small M, native indexOf() even if O(N*M) is faster
235
+ // The worst case N*M when N = 1000 is also faster so anything less is fine
236
+ // As the worst case of N = 1000 is 500000 (M=500, N=1000) anything taking
237
+ // less than that should also fine. This covers most paths and patterns.
238
+ if (needle.length < 10 || n < 1000 || needle.length * n < 500000) {
239
+ return haystack.indexOf(needle, index);
240
+ }
241
+
242
+ return boyerMoore(needle, haystack, index);
243
+ }
244
+
245
+ /**
246
+ * This algorithm is O(N + ∑ indexOf(part)) making the worst case for this the
247
+ * same as indexOf().
248
+ *
249
+ * V8: For large N uses Boyer-Moore-Horspool which falls back to Boyer-Moore for
250
+ * bad inputs. The Boyer-Moore implementation has a limit on table sizes so it
251
+ * could be O(N*M) but previous strategies look like they match, at least some,
252
+ * inputs that would cause O(N*M). It's worst case appears to be O(N) although
253
+ * there maybe some inputs that can get though and cause O(N*M) behaviour.
254
+ * https://sourcegraph.com/r/github.com/v8/v8/-/blob/src/strings/string-search.h?L297
255
+ * JSC: Same as V8
256
+ * https://github.com/WebKit/WebKit/blob/main/Source/WTF/wtf/text/AdaptiveStringSearcher.h
257
+ * SpiderMonkey: For large N uses SIMD with O(N*M) worst case
258
+ * https://searchfox.org/firefox-main/source/js/src/builtin/String.cpp#2179
259
+ *
260
+ * Base on the above, this will have a worst case of either O(N) or O(N*M) in
261
+ * V8 and JSC, and O(N*M) on SpiderMonkey.
262
+ *
263
+ * Because of this, it makes sense to use an O(N) algorithm although due to the
264
+ * amount of setup, and the fact it isn't written in native code, the JS
265
+ * implementation of Boyer-Moore is slower for small N so we fall back to the
266
+ * native indexOf for them.
267
+ *
268
+ * BoyersMoore with N=2,000,000 (with 2,000,000 robots.txt limit) is ~24ms which
269
+ * seems like a safe limit as neither Chrome nor Safari can process anything
270
+ * larger and the defaults for most servers are significantly lower:
271
+ *
272
+ * - Chrome displays up to ~32,000 chars and supports up to 2MB
273
+ * - Safari ~80,000 chars
274
+ * - Firefox displays up to ~64,000 chars but supports longer
275
+ * - Cloudflare 16kb
276
+ * - Nginx 4kb (can be configured larger)
277
+ * - Apache 8kb (can be configured larger)
278
+ * - IIS 16kb (can be configured larger)
279
+ *
280
+ * How this works:
281
+ *
282
+ * This splits a pattern at wildcards, it finds the first match for each part of
283
+ * the pattern. It then skips to find the first match for the next part and so
284
+ * on, if it reaches the end then it matches, if not, it doesn't.
285
+ *
286
+ * This never needs to backtrack as always does minimum required and any string
287
+ * that doesn't match the minimum will not match.
288
+ *
289
+ * If has an end anchor, it checks the last part matches the end. This is
290
+ * correct as there will be a * between he last part and the remainder which
291
+ * means anything between will match.
112
292
  *
113
- * @see https://github.com/google/robotstxt/blob/f465f0ede81099dd8bc4aeb2966b3a892bd488b3/robots.cc#L74
114
293
  * @param {string} pattern
115
294
  * @param {string} path
116
- * @return {boolean}
295
+ * @returns {boolean}
117
296
  * @private
118
297
  */
119
298
  function matches(pattern, path) {
120
- // I've added extra comments to try make this easier to understand
121
-
122
- // Stores the lengths of all the current matching substrings.
123
- // Maximum number of possible matching lengths is every length in path plus
124
- // 1 to handle 0 length too (if pattern starts with * which is zero or more)
125
- var matchingLengths = new Array(path.length + 1);
126
- var numMatchingLengths = 1;
127
-
128
- // Initially longest match is 0
129
- matchingLengths[0] = 0;
130
-
131
- for (var p = 0; p < pattern.length; p++) {
132
- // If $ is at the end of pattern then we must match the whole path.
133
- // Which is true if the longest matching length matches path length
134
- if (pattern[p] === '$' && p + 1 === pattern.length) {
135
- return matchingLengths[numMatchingLengths - 1] === path.length;
136
- }
299
+ const hasEndAnchor = pattern.endsWith('$');
137
300
 
138
- // Handle wildcards
139
- if (pattern[p] == '*') {
140
- // Wildcard so all substrings minus the current smallest matching
141
- // length are matches
142
- numMatchingLengths = path.length - matchingLengths[0] + 1;
143
-
144
- // Update matching lengths to include the smallest all the way up
145
- // to numMatchingLengths
146
- // Don't update smallest possible match as * matches zero or more
147
- // so the smallest current match is also valid
148
- for (var i = 1; i < numMatchingLengths; i++) {
149
- matchingLengths[i] = matchingLengths[i - 1] + 1;
150
- }
151
- } else {
152
- // Check the char at the matching length matches the pattern, if it
153
- // does increment it and add it as a valid length, ignore if not.
154
- var numMatches = 0;
155
- for (var i = 0; i < numMatchingLengths; i++) {
156
- if (
157
- matchingLengths[i] < path.length &&
158
- path[matchingLengths[i]] === pattern[p]
159
- ) {
160
- matchingLengths[numMatches++] = matchingLengths[i] + 1;
161
- }
162
- }
301
+ // Remove duplicate wildcards and end anchor and split into parts
302
+ const parts = pattern.replace(/\*+/g, '*').replace(/\$$/, '').split('*');
163
303
 
164
- // No paths matched the current pattern char so not a match
165
- if (numMatches == 0) {
166
- return false;
167
- }
304
+ // End anchor with no wildcards means must be 100% equal
305
+ if (hasEndAnchor && parts.length === 1) {
306
+ return path === parts[0];
307
+ }
308
+
309
+ // Must always start with first part. If pattern is *test the parts will be
310
+ // ['', 'test'] and '' will always match which is correct for *
311
+ if (!path.startsWith(parts[0])) {
312
+ return false;
313
+ }
168
314
 
169
- numMatchingLengths = numMatches;
315
+ // Make sure end part (if there is any parts) matches.
316
+ // Can't exit early if only two parts as a*a$ would match "a" so need to
317
+ // continue to full matching loop if this matches
318
+ if (hasEndAnchor && !path.endsWith(parts[parts.length - 1])) {
319
+ return false;
320
+ }
321
+
322
+ let pathIndex = parts[0].length;
323
+ // This isn't N*N as it starts at pathIndex index and never backtracks, so
324
+ // the worst case is indexOf(part) + indexOf(part) + ...
325
+ // making it the same worst case as indexOf()
326
+ for (let i = 1; i < parts.length; i++) {
327
+ const index = indexOf(parts[i], path, pathIndex);
328
+ if (index < 0) {
329
+ return false;
170
330
  }
331
+
332
+ pathIndex = index + parts[i].length;
171
333
  }
172
334
 
173
335
  return true;
@@ -176,13 +338,23 @@ function matches(pattern, path) {
176
338
  function parseRobots(contents, robots) {
177
339
  var newlineRegex = /\r\n|\r|\n/;
178
340
  var lines = contents
341
+ // Limit to ~2 mb (could be larger due to unicode but this deals with
342
+ // chars makes no difference for this case) which is 4x larger than
343
+ // Google's limit of 500 kb and the minimum required by the spec
344
+ .substring(0, 2097152)
179
345
  .split(newlineRegex)
180
346
  .map(removeComments)
181
347
  .map(splitLine)
182
348
  .map(trimLine);
183
349
 
184
350
  var currentUserAgents = [];
185
- var isNoneUserAgentState = true;
351
+ /**
352
+ * Used to allow crawl-delay and any other non-standard directives to have
353
+ * their own grouping without affecting the RFC standard groupings.
354
+ */
355
+ var currentNoneStandardUserAgents = [];
356
+ var isGroupTermination = true;
357
+ var isNoneStandardGroupTermination = true;
186
358
  for (var i = 0; i < lines.length; i++) {
187
359
  var line = lines[i];
188
360
 
@@ -190,14 +362,23 @@ function parseRobots(contents, robots) {
190
362
  continue;
191
363
  }
192
364
 
193
- switch (line[0].toLowerCase()) {
365
+ const rule = line[0].toLowerCase();
366
+ switch (rule) {
194
367
  case 'user-agent':
195
- if (isNoneUserAgentState) {
368
+ if (isGroupTermination) {
196
369
  currentUserAgents.length = 0;
197
370
  }
198
371
 
372
+ if (isNoneStandardGroupTermination) {
373
+ currentNoneStandardUserAgents.length = 0;
374
+ }
375
+
199
376
  if (line[1]) {
200
- currentUserAgents.push(formatUserAgent(line[1]));
377
+ const userAgent = formatUserAgent(line[1]);
378
+ currentUserAgents.push(userAgent);
379
+ currentNoneStandardUserAgents.push(userAgent);
380
+
381
+ robots._rules[userAgent] = robots._rules[userAgent] || [];
201
382
  }
202
383
  break;
203
384
  case 'disallow':
@@ -207,7 +388,7 @@ function parseRobots(contents, robots) {
207
388
  robots.addRule(currentUserAgents, line[1], true, i + 1);
208
389
  break;
209
390
  case 'crawl-delay':
210
- robots.setCrawlDelay(currentUserAgents, line[1]);
391
+ robots.setCrawlDelay(currentNoneStandardUserAgents, line[1]);
211
392
  break;
212
393
  case 'sitemap':
213
394
  if (line[1]) {
@@ -221,7 +402,14 @@ function parseRobots(contents, robots) {
221
402
  break;
222
403
  }
223
404
 
224
- isNoneUserAgentState = line[0].toLowerCase() !== 'user-agent';
405
+ // Other records (sitemap, crawl-delay, host, unknown) must not change
406
+ // the grouping: only a rule ends the user-agent lines of a group
407
+ if (rule === 'user-agent') {
408
+ isGroupTermination = false;
409
+ } else if (rule === 'allow' || rule === 'disallow') {
410
+ isGroupTermination = true;
411
+ }
412
+ isNoneStandardGroupTermination = rule !== 'user-agent';
225
413
  }
226
414
  }
227
415
 
@@ -286,6 +474,10 @@ function parseUrl(url) {
286
474
  }
287
475
  }
288
476
 
477
+ /**
478
+ * @param {string} url
479
+ * @param {string} contents
480
+ */
289
481
  function Robots(url, contents) {
290
482
  this._url = parseUrl(url) || {};
291
483
  this._rules = Object.create(null);
@@ -308,8 +500,6 @@ Robots.prototype.addRule = function (userAgents, pattern, allow, lineNumber) {
308
500
  var rules = this._rules;
309
501
 
310
502
  userAgents.forEach(function (userAgent) {
311
- rules[userAgent] = rules[userAgent] || [];
312
-
313
503
  if (!pattern) {
314
504
  return;
315
505
  }
@@ -333,8 +523,6 @@ Robots.prototype.setCrawlDelay = function (userAgents, delayStr) {
333
523
  var delay = Number(delayStr);
334
524
 
335
525
  userAgents.forEach(function (userAgent) {
336
- rules[userAgent] = rules[userAgent] || [];
337
-
338
526
  if (isNaN(delay)) {
339
527
  return;
340
528
  }
@@ -361,7 +549,7 @@ Robots.prototype.setPreferredHost = function (url) {
361
549
  this._preferredHost = url;
362
550
  };
363
551
 
364
- Robots.prototype._getRule = function (url, ua) {
552
+ Robots.prototype._getRule = function (url, ua, explicit) {
365
553
  var parsedUrl = parseUrl(url) || {};
366
554
  var userAgent = formatUserAgent(ua || '*');
367
555
 
@@ -374,11 +562,19 @@ Robots.prototype._getRule = function (url, ua) {
374
562
  return;
375
563
  }
376
564
 
377
- var rules = this._rules[userAgent] || this._rules['*'] || [];
378
- var path = urlEncodeToUpper(parsedUrl.pathname + parsedUrl.search);
379
- var rule = findRule(path, rules);
565
+ var rules = this._rules[userAgent];
566
+ if (!explicit) {
567
+ rules = rules || this._rules['*'];
568
+ }
569
+ rules = rules || [];
380
570
 
381
- return rule;
571
+ var path = normaliseEncoding(parsedUrl.pathname + parsedUrl.search);
572
+ // The /robots.txt URI is implicitly allowed
573
+ if (path === '/robots.txt') {
574
+ return null;
575
+ }
576
+
577
+ return findRule(path, rules);
382
578
  };
383
579
 
384
580
  /**
@@ -392,7 +588,7 @@ Robots.prototype._getRule = function (url, ua) {
392
588
  * @return {boolean?}
393
589
  */
394
590
  Robots.prototype.isAllowed = function (url, ua) {
395
- var rule = this._getRule(url, ua);
591
+ var rule = this._getRule(url, ua, false);
396
592
 
397
593
  if (typeof rule === 'undefined') {
398
594
  return;
@@ -416,7 +612,7 @@ Robots.prototype.isAllowed = function (url, ua) {
416
612
  * @return {number?}
417
613
  */
418
614
  Robots.prototype.getMatchingLineNumber = function (url, ua) {
419
- var rule = this._getRule(url, ua);
615
+ var rule = this._getRule(url, ua, false);
420
616
 
421
617
  return rule ? rule.lineNumber : -1;
422
618
  };
@@ -425,13 +621,32 @@ Robots.prototype.getMatchingLineNumber = function (url, ua) {
425
621
  * Returns the opposite of isAllowed()
426
622
  *
427
623
  * @param {string} url
428
- * @param {string} ua
624
+ * @param {string?} ua
429
625
  * @return {boolean}
430
626
  */
431
627
  Robots.prototype.isDisallowed = function (url, ua) {
432
628
  return !this.isAllowed(url, ua);
433
629
  };
434
630
 
631
+ /**
632
+ * Returns trues if explicitly disallowed
633
+ * for the specified user agent (User Agent wildcards are discarded).
634
+ *
635
+ * This will return undefined if the URL is not valid for this robots.txt file.
636
+ *
637
+ * @param {string} url
638
+ * @param {string} ua
639
+ * @return {boolean?}
640
+ */
641
+ Robots.prototype.isExplicitlyDisallowed = function (url, ua) {
642
+ var rule = this._getRule(url, ua, true);
643
+ if (typeof rule === 'undefined') {
644
+ return;
645
+ }
646
+
647
+ return !(!rule || rule.allow);
648
+ };
649
+
435
650
  /**
436
651
  * Gets the crawl delay if there is one.
437
652
  *
package/index.d.ts CHANGED
@@ -1,12 +1,13 @@
1
- declare module 'robots-parser';
2
-
3
1
  interface Robot {
4
2
  isAllowed(url: string, ua?: string): boolean | undefined;
5
3
  isDisallowed(url: string, ua?: string): boolean | undefined;
4
+ isExplicitlyDisallowed(url: string, ua: string): boolean | undefined;
6
5
  getMatchingLineNumber(url: string, ua?: string): number;
7
6
  getCrawlDelay(ua?: string): number | undefined;
8
7
  getSitemaps(): string[];
9
8
  getPreferredHost(): string | null;
10
9
  }
11
10
 
12
- export default function robotsParser(url: string, robotstxt: string): Robot;
11
+ declare function robotsParser(url: string, robotstxt: string): Robot;
12
+
13
+ export = robotsParser;
package/index.js CHANGED
@@ -1,5 +1,10 @@
1
+ //@ts-check
1
2
  var Robots = require('./Robots');
2
3
 
4
+ /**
5
+ * @param {string} url
6
+ * @param {string} contents
7
+ */
3
8
  module.exports = function (url, contents) {
4
9
  return new Robots(url, contents);
5
- };
10
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "robots-parser",
3
- "version": "3.0.1",
3
+ "version": "3.1.1",
4
4
  "description": "A specification compliant robots.txt parser with wildcard (*) matching support.",
5
5
  "keywords": [
6
6
  "robots.txt",
@@ -9,7 +9,8 @@
9
9
  "scraper",
10
10
  "spider",
11
11
  "bot",
12
- "robots-exclusion-standard"
12
+ "robots-exclusion-standard",
13
+ "RFC 9309"
13
14
  ],
14
15
  "main": "index.js",
15
16
  "directories": {
@@ -49,9 +50,9 @@
49
50
  "trailingComma": "none"
50
51
  },
51
52
  "devDependencies": {
52
- "chai": "^4.3.6",
53
- "mocha": "^10.0.0",
54
- "nyc": "^15.1.0"
53
+ "chai": "^6.3.0",
54
+ "mocha": "^12.0.3",
55
+ "nyc": "^18.0.0"
55
56
  },
56
57
  "types": "./index.d.ts"
57
58
  }
package/test/Robots.js CHANGED
@@ -1,16 +1,18 @@
1
1
  var robotsParser = require('../index');
2
2
  var expect = require('chai').expect;
3
+ const fs = require('fs');
4
+ const path = require('path')
3
5
 
4
6
 
5
7
  function testRobots(url, contents, allowed, disallowed) {
6
8
  var robots = robotsParser(url, contents);
7
9
 
8
10
  allowed.forEach(function (url) {
9
- expect(robots.isAllowed(url)).to.equal(true);
11
+ expect(robots.isAllowed(url), `should allow url: ${url}`).to.equal(true);
10
12
  });
11
13
 
12
14
  disallowed.forEach(function (url) {
13
- expect(robots.isDisallowed(url)).to.equal(true);
15
+ expect(robots.isDisallowed(url), `should reject url: ${url}`).to.equal(true);
14
16
  });
15
17
  }
16
18
 
@@ -65,14 +67,20 @@ describe('Robots', function () {
65
67
  'User-agent: *',
66
68
  'Disallow: /fish*.php',
67
69
  'Disallow: /*.dext$',
68
- 'Disallow: /dir*'
70
+ 'Disallow: /dir*',
71
+ 'Disallow: /tester$',
72
+ 'Disallow: /a*b*c',
73
+ 'Disallow: /x*$'
69
74
  ].join('\n');
70
75
 
71
76
  var allowed = [
72
77
  'http://www.example.com/Fish.PHP',
73
78
  'http://www.example.com/Fish.dext1',
74
79
  'http://www.example.com/folder/dir.html',
75
- 'http://www.example.com/folder/dir/test.html'
80
+ 'http://www.example.com/folder/dir/test.html',
81
+ 'http://www.example.com/testers',
82
+ 'http://www.example.com/something/tester',
83
+ 'http://www.example.com/something/ab'
76
84
  ];
77
85
 
78
86
  var disallowed = [
@@ -81,7 +89,84 @@ describe('Robots', function () {
81
89
  'http://www.example.com/AnYthInG.dext',
82
90
  'http://www.example.com/Fish.dext.dext',
83
91
  'http://www.example.com/dir/test.html',
84
- 'http://www.example.com/directory.html'
92
+ 'http://www.example.com/directory.html',
93
+ 'http://www.example.com/tester',
94
+ 'http://www.example.com/abc',
95
+ 'http://www.example.com/axbxcx',
96
+ 'http://www.example.com/x',
97
+ 'http://www.example.com/xyz'
98
+ ];
99
+
100
+ testRobots('http://www.example.com/robots.txt', contents, allowed, disallowed);
101
+ });
102
+
103
+ it('should parse empty patterns', function () {
104
+ var contents = [
105
+ 'User-agent: *',
106
+ 'Disallow: ****$'
107
+ ].join('\n');
108
+
109
+ var allowed = [];
110
+
111
+ var disallowed = [
112
+ 'http://www.example.com/',
113
+ 'http://www.example.com/test.html'
114
+ ];
115
+
116
+ testRobots('http://www.example.com/robots.txt', contents, allowed, disallowed);
117
+ });
118
+
119
+ it('should handle end patterns that start and end with same pattern', function () {
120
+ var contents = [
121
+ 'User-agent: *',
122
+ 'Disallow: /a$',
123
+ 'Disallow: /abc$'
124
+ ].join('\n');
125
+
126
+ var allowed = [
127
+ 'http://www.example.com/abca',
128
+ 'http://www.example.com/abcXYZabc'
129
+ ];
130
+
131
+ var disallowed = [
132
+ 'http://www.example.com/a',
133
+ 'http://www.example.com/abc'
134
+ ];
135
+
136
+ testRobots('http://www.example.com/robots.txt', contents, allowed, disallowed);
137
+ });
138
+
139
+ it('should handle empty end patterns', function () {
140
+ var contents = [
141
+ 'User-agent: *',
142
+ 'Disallow: $',
143
+ ].join('\n');
144
+
145
+ var allowed = [
146
+ 'http://www.example.com/',
147
+ 'http://www.example.com/test.html'
148
+ ];
149
+
150
+ var disallowed = [];
151
+
152
+ testRobots('http://www.example.com/robots.txt', contents, allowed, disallowed);
153
+ });
154
+
155
+ it('should not match start and end of wildcard end patterns twice', function () {
156
+ var contents = [
157
+ 'User-agent: *',
158
+ 'Disallow: a*a$',
159
+ 'Disallow: *a*a$',
160
+ ].join('\n');
161
+
162
+ var allowed = [
163
+ 'http://www.example.com/a',
164
+ 'http://www.example.com/ba'
165
+ ];
166
+
167
+ var disallowed = [
168
+ 'http://www.example.com/axa',
169
+ 'http://www.example.com/xaxa'
85
170
  ];
86
171
 
87
172
  testRobots('http://www.example.com/robots.txt', contents, allowed, disallowed);
@@ -302,6 +387,19 @@ describe('Robots', function () {
302
387
  expect(robots.isAllowed("http://www.example.com/fish", "agenta")).to.equal(false);
303
388
  });
304
389
 
390
+ it('should not fallback to * when specified but empty', function () {
391
+ var contents = [
392
+ 'User-agent: *',
393
+ 'Disallow: /fish',
394
+ 'User-agent: agent',
395
+ ].join('\n');
396
+
397
+ var robots = robotsParser('http://www.example.com/robots.txt', contents);
398
+
399
+ expect(robots.isAllowed("http://www.example.com/fish", "agent-other")).to.equal(false);
400
+ expect(robots.isAllowed("http://www.example.com/fish", "agent")).to.equal(true);
401
+ });
402
+
305
403
  it('should return undefined for invalid urls', function () {
306
404
  var contents = [
307
405
  'User-agent: *',
@@ -359,7 +457,9 @@ describe('Robots', function () {
359
457
  'Disallow: /✼*t$',
360
458
  'Disallow: /%E2%9C%A4*t$',
361
459
  'Disallow: /✿%a',
362
- 'Disallow: /http%3A%2F%2Fexample.org'
460
+ 'Disallow: /http%3A%2F%2Fexample.org',
461
+ 'Disallow: /%E0',
462
+ 'Disallow: /%00test'
363
463
  ].join('\n');
364
464
 
365
465
  var allowed = [
@@ -367,8 +467,7 @@ describe('Robots', function () {
367
467
  'http://www.example.com/%E2%9C%BCtesting',
368
468
  'http://www.example.com/✤testing',
369
469
  'http://www.example.com/%E2%9C%A4testing',
370
- 'http://www.example.com/http://example.org',
371
- 'http://www.example.com/http:%2F%2Fexample.org'
470
+ 'http://www.example.com/%00allow',
372
471
  ];
373
472
 
374
473
  var disallowed = [
@@ -392,12 +491,51 @@ describe('Robots', function () {
392
491
  'http://www.example.com/%E2%9C%A4testt',
393
492
  'http://www.example.com/✿%a',
394
493
  'http://www.example.com/%E2%9C%BF%atest',
395
- 'http://www.example.com/http%3A%2F%2Fexample.org'
494
+ 'http://www.example.com/http%3A%2F%2Fexample.org',
495
+ 'http://www.example.com/%E0test',
496
+ 'http://www.example.com/%00test'
396
497
  ];
397
498
 
398
499
  testRobots('http://www.example.com/robots.txt', contents, allowed, disallowed);
399
500
  });
400
501
 
502
+ it('should handle urlencoded path segments', function () {
503
+ var contents = [
504
+ 'User-agent: *',
505
+ 'Allow: /test%2Ftest',
506
+ 'Disallow: /test/test'
507
+ ].join('\n');
508
+
509
+ var allowed = [
510
+ 'http://www.example.com/test%2Ftest',
511
+ ];
512
+
513
+ var disallowed = [
514
+ 'http://www.example.com/test/test'
515
+ ];
516
+
517
+ testRobots('http://www.example.com/robots.txt', contents, allowed, disallowed);
518
+ });
519
+
520
+ it('should handle encoded / in paths an URLs', function () {
521
+ var contents = [
522
+ 'User-agent: *',
523
+ 'Disallow: /a/b',
524
+ 'Allow: /a%2Fb'
525
+ ].join('\n');
526
+
527
+ var allowed = [
528
+ 'http://www.example.com/a%2Fb'
529
+ ];
530
+
531
+ var disallowed = [
532
+ 'http://www.example.com/a/b/c',
533
+ 'http://www.example.com/a/b'
534
+ ];
535
+
536
+ testRobots('http://www.example.com/robots.txt', contents, allowed, disallowed);
537
+ });
538
+
401
539
  it('should handle lone high / low surrogates', function () {
402
540
  var contents = [
403
541
  'User-agent: *',
@@ -665,6 +803,27 @@ describe('Robots', function () {
665
803
  });
666
804
 
667
805
  it('should fallback to * when a UA has no rules of its own', function () {
806
+ var contents = [
807
+ 'User-agent: *',
808
+ 'Disallow: /a',
809
+
810
+ 'user-agent: b',
811
+ 'Disallow: /b',
812
+
813
+ 'user-agent: c',
814
+ 'user-agent: d',
815
+ 'Disallow: /c',
816
+ ].join('\n');
817
+
818
+ var robots = robotsParser('http://www.example.com/robots.txt', contents);
819
+
820
+ expect(robots.isAllowed('http://www.example.com/a', 'should-fall-back')).to.equal(false);
821
+ expect(robots.isAllowed('http://www.example.com/a', 'd')).to.equal(true);
822
+ expect(robots.isAllowed('http://www.example.com/c', 'should-fall-back')).to.equal(true);
823
+ expect(robots.isAllowed('http://www.example.com/c', 'd')).to.equal(false);
824
+ });
825
+
826
+ it('should have crawl-delay fallback to * when a UA has no rules of its own', function () {
668
827
  var contents = [
669
828
  'user-agent: *',
670
829
  'crawl-delay: 1',
@@ -730,6 +889,33 @@ describe('Robots', function () {
730
889
  expect(robots.getCrawlDelay('b / 1.0')).to.equal(12);
731
890
  });
732
891
 
892
+ it('should ignore spaces UA string', function () {
893
+ var contents = [
894
+ 'user-agent: *',
895
+ 'disallow:',
896
+
897
+ 'user-agent: b foo',
898
+ 'disallow: /b',
899
+
900
+ 'user-agent: c',
901
+ 'disallow: /c'
902
+ ].join('\n');
903
+
904
+ var robots = robotsParser('http://www.example.com/robots.txt', contents);
905
+
906
+ expect(robots.isAllowed('http://www.example.com/b', 'b')).to.equal(false);
907
+ expect(robots.isAllowed('http://www.example.com/b', 'b foo')).to.equal(false);
908
+ expect(robots.isAllowed('http://www.example.com/b', 'b anything')).to.equal(false);
909
+ expect(robots.isAllowed('http://www.example.com/b', 'bC')).to.equal(true);
910
+ expect(robots.isAllowed('http://www.example.com/b', 'b-c')).to.equal(true);
911
+
912
+ expect(robots.isAllowed('http://www.example.com/c', 'c')).to.equal(false);
913
+ expect(robots.isAllowed('http://www.example.com/c', 'c foo')).to.equal(false);
914
+ expect(robots.isAllowed('http://www.example.com/c', 'c anything')).to.equal(false);
915
+ expect(robots.isAllowed('http://www.example.com/c', 'cC')).to.equal(true);
916
+ expect(robots.isAllowed('http://www.example.com/c', 'c-c')).to.equal(true);
917
+ });
918
+
733
919
 
734
920
  it('should return the line number of the matching directive', function () {
735
921
  var contents = [
@@ -792,6 +978,123 @@ describe('Robots', function () {
792
978
  expect(end - start).to.be.lessThan(500);
793
979
  });
794
980
 
981
+ it('should handle a long pattern after a leading wildcard', function () {
982
+ var contents = [
983
+ 'User-agent: *',
984
+ 'Disallow: /*' + 'test123testing'.repeat(100)
985
+ ].join('\n');
986
+
987
+
988
+ var allowed = [
989
+ 'http://www.example.com/' + 'test123testing'.repeat(99),
990
+ ];
991
+
992
+ var disallowed = [
993
+ 'http://www.example.com/' + 'test123testing'.repeat(100000) + 'b',
994
+ 'http://www.example.com/b' + 'test123testing'.repeat(100000),
995
+ ];
996
+
997
+ testRobots('http://www.example.com/robots.txt', contents, allowed, disallowed);
998
+ });
999
+
1000
+ it('should handle long repeating patterns', function () {
1001
+ var contents = [
1002
+ 'User-agent: *',
1003
+ 'Disallow: /' + 'test123testing'.repeat(100) + '*' + 'test123testing'.repeat(100),
1004
+ ].join('\n');
1005
+
1006
+
1007
+ var allowed = [
1008
+ 'http://www.example.com/' + 'test123testing'.repeat(199),
1009
+ ];
1010
+
1011
+ var disallowed = [
1012
+ 'http://www.example.com/' + 'test123testing'.repeat(100000) + 'b',
1013
+ 'http://www.example.com/' + 'test123testing'.repeat(100) + 'x' + 'test123testing'.repeat(100),
1014
+ ];
1015
+
1016
+ testRobots('http://www.example.com/robots.txt', contents, allowed, disallowed);
1017
+ });
1018
+
1019
+ it('should not have N*M performance for large N or M', function () {
1020
+ const n = 100000;
1021
+
1022
+ var contents = [
1023
+ 'User-agent: *',
1024
+ 'Disallow: /*' + 'a'.repeat(Math.floor(n / 2)) + 'b',
1025
+ 'Disallow: /*b' + 'a'.repeat(Math.floor(n / 2)),
1026
+ ].join('\n');
1027
+
1028
+
1029
+ var allowed = [
1030
+ 'http://www.example.com/' + 'a'.repeat(n),
1031
+ 'http://www.example.com/x' + 'a'.repeat(n),
1032
+ 'http://www.example.com/' + 'x'.repeat(Math.floor(n / 2)) + 'x'+ 'a'.repeat(n/2),
1033
+ ];
1034
+
1035
+ var disallowed = [
1036
+ 'http://www.example.com/' + 'a'.repeat(Math.floor(n / 2)) + 'b',
1037
+ 'http://www.example.com/b' + 'a'.repeat(n),
1038
+ ];
1039
+
1040
+ const start = performance.now();
1041
+ testRobots('http://www.example.com/robots.txt', contents, allowed, disallowed);
1042
+ const end = performance.now();
1043
+
1044
+ // Should take less than 500 ms (high to allow for variableness of
1045
+ // machines running the test, should normally be much less)
1046
+ expect(end - start).to.be.lessThan(500);
1047
+ });
1048
+
1049
+ it('should not have N*M performance for large N or M with wildcards', function () {
1050
+ const n = 100000;
1051
+
1052
+ var contents = [
1053
+ 'User-agent: *',
1054
+ 'Disallow: /' + 'a*'.repeat(Math.floor(n / 2)) + 'b',
1055
+ 'Disallow: /b' + 'a*'.repeat(Math.floor(n / 2)),
1056
+ ].join('\n');
1057
+
1058
+
1059
+ var allowed = [
1060
+ 'http://www.example.com/' + 'a'.repeat(n),
1061
+ ];
1062
+
1063
+ var disallowed = [
1064
+ 'http://www.example.com/' + 'a'.repeat(Math.floor(n / 2)) + 'b',
1065
+ 'http://www.example.com/b' + 'a'.repeat(n),
1066
+ ];
1067
+
1068
+ const start = performance.now();
1069
+ testRobots('http://www.example.com/robots.txt', contents, allowed, disallowed);
1070
+ const end = performance.now();
1071
+
1072
+ // Should take less than 500 ms (high to allow for variableness of
1073
+ // machines running the test, should normally be much less)
1074
+ expect(end - start).to.be.lessThan(500);
1075
+ });
1076
+
1077
+ it('should find matches in long paths that the bad character shift could skip', function () {
1078
+ // Forces the Boyer-Moore path in indexOf() (part length >= 10 and
1079
+ // part length * path length >= 500000). The only run of 10 a's starts
1080
+ // right after the mismatched 'b', which the old bad character shift
1081
+ // of m skipped over.
1082
+ var contents = [
1083
+ 'User-agent: *',
1084
+ 'Disallow: /*aaaaaaaaaa'
1085
+ ].join('\n');
1086
+
1087
+ var allowed = [
1088
+ 'http://www.example.com/b' + 'a'.repeat(9) + 'c'.repeat(100000)
1089
+ ];
1090
+
1091
+ var disallowed = [
1092
+ 'http://www.example.com/b' + 'a'.repeat(10) + 'c'.repeat(100000)
1093
+ ];
1094
+
1095
+ testRobots('http://www.example.com/robots.txt', contents, allowed, disallowed);
1096
+ });
1097
+
795
1098
  it('should honor given port number', function () {
796
1099
  var contents = [
797
1100
  'User-agent: *',
@@ -861,4 +1164,140 @@ describe('Robots', function () {
861
1164
 
862
1165
  testRobots('https://www.example.com/robots.txt', contents, allowed, disallowed);
863
1166
  });
1167
+
1168
+ it('should not be disallowed when wildcard is used in explicit mode', function () {
1169
+ var contents = [
1170
+ 'User-agent: *',
1171
+ 'Disallow: /',
1172
+ ].join('\n')
1173
+
1174
+ var url = 'https://www.example.com/hello'
1175
+ var userAgent = 'SomeBot';
1176
+ var robots = robotsParser(url, contents);
1177
+
1178
+ expect(robots.isExplicitlyDisallowed(url, userAgent)).to.equal(false)
1179
+ });
1180
+
1181
+ it('should be disallowed when user agent equal robots rule in explicit mode', function () {
1182
+ var contents = [
1183
+ 'User-agent: SomeBot',
1184
+ 'Disallow: /',
1185
+ ].join('\n')
1186
+
1187
+ var url = 'https://www.example.com/hello'
1188
+ var userAgent = 'SomeBot';
1189
+ var robots = robotsParser(url, contents);
1190
+
1191
+ expect(robots.isExplicitlyDisallowed(url, userAgent)).to.equal(true)
1192
+ });
1193
+
1194
+ it('should return undefined when given an invalid URL in explicit mode', function () {
1195
+ var contents = [
1196
+ 'User-agent: SomeBot',
1197
+ 'Disallow: /',
1198
+ ].join('\n')
1199
+
1200
+ var url = 'https://www.example.com/hello'
1201
+ var userAgent = 'SomeBot';
1202
+ var robots = robotsParser('http://example.com', contents);
1203
+
1204
+ expect(robots.isExplicitlyDisallowed(url, userAgent)).to.equal(undefined)
1205
+ });
1206
+
1207
+ it('should return false when no matching rule specified calling isDisallowed()', function () {
1208
+ var contents = [
1209
+ 'User-agent: OtherBot',
1210
+ 'Disallow: /',
1211
+ ].join('\n')
1212
+
1213
+ var url = 'https://example.com/hello'
1214
+ var userAgent = 'SomeBot';
1215
+ var robots = robotsParser('https://example.com', contents);
1216
+
1217
+ expect(robots.isDisallowed(url, userAgent)).to.equal(false)
1218
+ });
1219
+
1220
+ it('should ignore content beyond the 2 MiB parsing limit', function () {
1221
+ var contents = [
1222
+ 'User-agent: *',
1223
+ 'Disallow: /within-limit',
1224
+ '#' + 'a'.repeat(2097152),
1225
+ 'Disallow: /beyond-limit'
1226
+ ].join('\n');
1227
+
1228
+ var allowed = [
1229
+ 'http://www.example.com/beyond-limit'
1230
+ ];
1231
+
1232
+ var disallowed = [
1233
+ 'http://www.example.com/within-limit'
1234
+ ];
1235
+
1236
+ testRobots('http://www.example.com/robots.txt', contents, allowed, disallowed);
1237
+ });
1238
+
1239
+ it('should implicitly allow robots.txt URLs', function () {
1240
+ var contents = [
1241
+ 'User-agent: *',
1242
+ 'Disallow: /robots.txt',
1243
+ ].join('\n');
1244
+
1245
+ var allowed = [
1246
+ 'https://www.example.com/robots.txt',
1247
+ ];
1248
+
1249
+ // The spec says /robots.txt URI is implicitly allowed so assuming that
1250
+ // is strict and doesn't include query strings
1251
+ var disallowed = [
1252
+ 'https://www.example.com/robots.txt?testing=123',
1253
+ 'https://www.example.com/robots.txt/something',
1254
+ 'https://www.example.com/robots.txts'
1255
+ ];
1256
+
1257
+ testRobots('https://www.example.com/robots.txt', contents, allowed, disallowed);
1258
+ });
1259
+
1260
+ it('should start a new group after rules even if other records follow them', function () {
1261
+ ['Sitemap: http://www.example.com/sitemap.xml', 'Crawl-delay: 1', 'Host: www.example.com', 'Foo: bar'].forEach(function (record) {
1262
+ var contents = [
1263
+ 'User-agent: a',
1264
+ 'Allow: /fish',
1265
+ record,
1266
+ 'User-agent: b',
1267
+ 'Disallow: /'
1268
+ ].join('\n');
1269
+
1270
+ var robots = robotsParser('http://www.example.com/robots.txt', contents);
1271
+
1272
+ expect(robots.isAllowed('http://www.example.com/test.html', 'a'), record).to.equal(true);
1273
+ expect(robots.isAllowed('http://www.example.com/test.html', 'b'), record).to.equal(false);
1274
+ });
1275
+ });
1276
+
1277
+ it('should not end a group of user-agent lines on other records', function () {
1278
+ var contents = [
1279
+ 'User-agent: a',
1280
+ 'Sitemap: http://www.example.com/sitemap.xml',
1281
+ 'User-agent: b',
1282
+ 'Disallow: /'
1283
+ ].join('\n');
1284
+
1285
+ var robots = robotsParser('http://www.example.com/robots.txt', contents);
1286
+
1287
+ expect(robots.isAllowed('http://www.example.com/test.html', 'a')).to.equal(false);
1288
+ expect(robots.isAllowed('http://www.example.com/test.html', 'b')).to.equal(false);
1289
+ });
1290
+
1291
+ it('should pass rfc9309-test-vectors.json tests', function () {
1292
+ const file = path.resolve(__dirname,'./rfc9309-test-vectors.json')
1293
+ const testVectors = JSON.parse(fs.readFileSync(file, 'utf8'));
1294
+
1295
+ testVectors.vectors.forEach(vector => {
1296
+ const robots = robotsParser('http://www.example.com/robots.txt', vector.robots_txt);
1297
+ const result = robots.isAllowed('http://www.example.com' + vector.path, vector.user_agent);
1298
+ const expected = vector.expected === "allowed";
1299
+
1300
+ expect(result, `should pass test id "${vector.id}"`).to.equal(expected);
1301
+ });
1302
+ });
864
1303
  });