tldts-utils 6.1.81
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/LICENSE +13 -0
- package/README.md +3 -0
- package/bin/update.js +7 -0
- package/dist/cjs/index.js +698 -0
- package/dist/cjs/index.js.map +1 -0
- package/dist/cjs/src/builders/hashes.js +186 -0
- package/dist/cjs/src/builders/hashes.js.map +1 -0
- package/dist/cjs/src/builders/trie.js +155 -0
- package/dist/cjs/src/builders/trie.js.map +1 -0
- package/dist/cjs/src/find-base-dir.js +13 -0
- package/dist/cjs/src/find-base-dir.js.map +1 -0
- package/dist/cjs/src/list.js +11 -0
- package/dist/cjs/src/list.js.map +1 -0
- package/dist/cjs/src/parser.js +63 -0
- package/dist/cjs/src/parser.js.map +1 -0
- package/dist/cjs/src/update.js +23 -0
- package/dist/cjs/src/update.js.map +1 -0
- package/dist/cjs/tsconfig.tsbuildinfo +1 -0
- package/dist/es6/index.js +4 -0
- package/dist/es6/index.js.map +1 -0
- package/dist/es6/src/builders/hashes.js +184 -0
- package/dist/es6/src/builders/hashes.js.map +1 -0
- package/dist/es6/src/builders/trie.js +153 -0
- package/dist/es6/src/builders/trie.js.map +1 -0
- package/dist/es6/src/find-base-dir.js +10 -0
- package/dist/es6/src/find-base-dir.js.map +1 -0
- package/dist/es6/src/list.js +8 -0
- package/dist/es6/src/list.js.map +1 -0
- package/dist/es6/src/parser.js +61 -0
- package/dist/es6/src/parser.js.map +1 -0
- package/dist/es6/src/update.js +20 -0
- package/dist/es6/src/update.js.map +1 -0
- package/dist/es6/tsconfig.bundle.tsbuildinfo +1 -0
- package/dist/types/index.d.ts +4 -0
- package/dist/types/src/builders/hashes.d.ts +90 -0
- package/dist/types/src/builders/trie.d.ts +28 -0
- package/dist/types/src/find-base-dir.d.ts +1 -0
- package/dist/types/src/list.d.ts +1 -0
- package/dist/types/src/parser.d.ts +12 -0
- package/dist/types/src/update.d.ts +1 -0
- package/index.ts +4 -0
- package/package.json +56 -0
- package/src/builders/hashes.ts +201 -0
- package/src/builders/trie.ts +216 -0
- package/src/find-base-dir.ts +11 -0
- package/src/list.ts +8 -0
- package/src/parser.ts +75 -0
- package/src/update.ts +36 -0
|
@@ -0,0 +1,698 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var fs = require('fs');
|
|
4
|
+
var path = require('path');
|
|
5
|
+
|
|
6
|
+
/** Highest positive signed 32-bit float value */
|
|
7
|
+
const maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1
|
|
8
|
+
|
|
9
|
+
/** Bootstring parameters */
|
|
10
|
+
const base = 36;
|
|
11
|
+
const tMin = 1;
|
|
12
|
+
const tMax = 26;
|
|
13
|
+
const skew = 38;
|
|
14
|
+
const damp = 700;
|
|
15
|
+
const initialBias = 72;
|
|
16
|
+
const initialN = 128; // 0x80
|
|
17
|
+
const delimiter = '-'; // '\x2D'
|
|
18
|
+
const regexNonASCII = /[^\0-\x7F]/; // Note: U+007F DEL is excluded too.
|
|
19
|
+
const regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g; // RFC 3490 separators
|
|
20
|
+
|
|
21
|
+
/** Error messages */
|
|
22
|
+
const errors = {
|
|
23
|
+
'overflow': 'Overflow: input needs wider integers to process',
|
|
24
|
+
'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
|
|
25
|
+
'invalid-input': 'Invalid input'
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
/** Convenience shortcuts */
|
|
29
|
+
const baseMinusTMin = base - tMin;
|
|
30
|
+
const floor = Math.floor;
|
|
31
|
+
const stringFromCharCode = String.fromCharCode;
|
|
32
|
+
|
|
33
|
+
/*--------------------------------------------------------------------------*/
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* A generic error utility function.
|
|
37
|
+
* @private
|
|
38
|
+
* @param {String} type The error type.
|
|
39
|
+
* @returns {Error} Throws a `RangeError` with the applicable error message.
|
|
40
|
+
*/
|
|
41
|
+
function error(type) {
|
|
42
|
+
throw new RangeError(errors[type]);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* A generic `Array#map` utility function.
|
|
47
|
+
* @private
|
|
48
|
+
* @param {Array} array The array to iterate over.
|
|
49
|
+
* @param {Function} callback The function that gets called for every array
|
|
50
|
+
* item.
|
|
51
|
+
* @returns {Array} A new array of values returned by the callback function.
|
|
52
|
+
*/
|
|
53
|
+
function map(array, callback) {
|
|
54
|
+
const result = [];
|
|
55
|
+
let length = array.length;
|
|
56
|
+
while (length--) {
|
|
57
|
+
result[length] = callback(array[length]);
|
|
58
|
+
}
|
|
59
|
+
return result;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* A simple `Array#map`-like wrapper to work with domain name strings or email
|
|
64
|
+
* addresses.
|
|
65
|
+
* @private
|
|
66
|
+
* @param {String} domain The domain name or email address.
|
|
67
|
+
* @param {Function} callback The function that gets called for every
|
|
68
|
+
* character.
|
|
69
|
+
* @returns {String} A new string of characters returned by the callback
|
|
70
|
+
* function.
|
|
71
|
+
*/
|
|
72
|
+
function mapDomain(domain, callback) {
|
|
73
|
+
const parts = domain.split('@');
|
|
74
|
+
let result = '';
|
|
75
|
+
if (parts.length > 1) {
|
|
76
|
+
// In email addresses, only the domain name should be punycoded. Leave
|
|
77
|
+
// the local part (i.e. everything up to `@`) intact.
|
|
78
|
+
result = parts[0] + '@';
|
|
79
|
+
domain = parts[1];
|
|
80
|
+
}
|
|
81
|
+
// Avoid `split(regex)` for IE8 compatibility. See #17.
|
|
82
|
+
domain = domain.replace(regexSeparators, '\x2E');
|
|
83
|
+
const labels = domain.split('.');
|
|
84
|
+
const encoded = map(labels, callback).join('.');
|
|
85
|
+
return result + encoded;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Creates an array containing the numeric code points of each Unicode
|
|
90
|
+
* character in the string. While JavaScript uses UCS-2 internally,
|
|
91
|
+
* this function will convert a pair of surrogate halves (each of which
|
|
92
|
+
* UCS-2 exposes as separate characters) into a single code point,
|
|
93
|
+
* matching UTF-16.
|
|
94
|
+
* @see `punycode.ucs2.encode`
|
|
95
|
+
* @see <https://mathiasbynens.be/notes/javascript-encoding>
|
|
96
|
+
* @memberOf punycode.ucs2
|
|
97
|
+
* @name decode
|
|
98
|
+
* @param {String} string The Unicode input string (UCS-2).
|
|
99
|
+
* @returns {Array} The new array of code points.
|
|
100
|
+
*/
|
|
101
|
+
function ucs2decode(string) {
|
|
102
|
+
const output = [];
|
|
103
|
+
let counter = 0;
|
|
104
|
+
const length = string.length;
|
|
105
|
+
while (counter < length) {
|
|
106
|
+
const value = string.charCodeAt(counter++);
|
|
107
|
+
if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
|
|
108
|
+
// It's a high surrogate, and there is a next character.
|
|
109
|
+
const extra = string.charCodeAt(counter++);
|
|
110
|
+
if ((extra & 0xFC00) == 0xDC00) { // Low surrogate.
|
|
111
|
+
output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
|
|
112
|
+
} else {
|
|
113
|
+
// It's an unmatched surrogate; only append this code unit, in case the
|
|
114
|
+
// next code unit is the high surrogate of a surrogate pair.
|
|
115
|
+
output.push(value);
|
|
116
|
+
counter--;
|
|
117
|
+
}
|
|
118
|
+
} else {
|
|
119
|
+
output.push(value);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
return output;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Converts a digit/integer into a basic code point.
|
|
127
|
+
* @see `basicToDigit()`
|
|
128
|
+
* @private
|
|
129
|
+
* @param {Number} digit The numeric value of a basic code point.
|
|
130
|
+
* @returns {Number} The basic code point whose value (when used for
|
|
131
|
+
* representing integers) is `digit`, which needs to be in the range
|
|
132
|
+
* `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
|
|
133
|
+
* used; else, the lowercase form is used. The behavior is undefined
|
|
134
|
+
* if `flag` is non-zero and `digit` has no uppercase form.
|
|
135
|
+
*/
|
|
136
|
+
const digitToBasic = function(digit, flag) {
|
|
137
|
+
// 0..25 map to ASCII a..z or A..Z
|
|
138
|
+
// 26..35 map to ASCII 0..9
|
|
139
|
+
return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
|
|
140
|
+
};
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* Bias adaptation function as per section 3.4 of RFC 3492.
|
|
144
|
+
* https://tools.ietf.org/html/rfc3492#section-3.4
|
|
145
|
+
* @private
|
|
146
|
+
*/
|
|
147
|
+
const adapt = function(delta, numPoints, firstTime) {
|
|
148
|
+
let k = 0;
|
|
149
|
+
delta = firstTime ? floor(delta / damp) : delta >> 1;
|
|
150
|
+
delta += floor(delta / numPoints);
|
|
151
|
+
for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {
|
|
152
|
+
delta = floor(delta / baseMinusTMin);
|
|
153
|
+
}
|
|
154
|
+
return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
|
|
155
|
+
};
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* Converts a string of Unicode symbols (e.g. a domain name label) to a
|
|
159
|
+
* Punycode string of ASCII-only symbols.
|
|
160
|
+
* @memberOf punycode
|
|
161
|
+
* @param {String} input The string of Unicode symbols.
|
|
162
|
+
* @returns {String} The resulting Punycode string of ASCII-only symbols.
|
|
163
|
+
*/
|
|
164
|
+
const encode = function(input) {
|
|
165
|
+
const output = [];
|
|
166
|
+
|
|
167
|
+
// Convert the input in UCS-2 to an array of Unicode code points.
|
|
168
|
+
input = ucs2decode(input);
|
|
169
|
+
|
|
170
|
+
// Cache the length.
|
|
171
|
+
const inputLength = input.length;
|
|
172
|
+
|
|
173
|
+
// Initialize the state.
|
|
174
|
+
let n = initialN;
|
|
175
|
+
let delta = 0;
|
|
176
|
+
let bias = initialBias;
|
|
177
|
+
|
|
178
|
+
// Handle the basic code points.
|
|
179
|
+
for (const currentValue of input) {
|
|
180
|
+
if (currentValue < 0x80) {
|
|
181
|
+
output.push(stringFromCharCode(currentValue));
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
const basicLength = output.length;
|
|
186
|
+
let handledCPCount = basicLength;
|
|
187
|
+
|
|
188
|
+
// `handledCPCount` is the number of code points that have been handled;
|
|
189
|
+
// `basicLength` is the number of basic code points.
|
|
190
|
+
|
|
191
|
+
// Finish the basic string with a delimiter unless it's empty.
|
|
192
|
+
if (basicLength) {
|
|
193
|
+
output.push(delimiter);
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
// Main encoding loop:
|
|
197
|
+
while (handledCPCount < inputLength) {
|
|
198
|
+
|
|
199
|
+
// All non-basic code points < n have been handled already. Find the next
|
|
200
|
+
// larger one:
|
|
201
|
+
let m = maxInt;
|
|
202
|
+
for (const currentValue of input) {
|
|
203
|
+
if (currentValue >= n && currentValue < m) {
|
|
204
|
+
m = currentValue;
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
// Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
|
|
209
|
+
// but guard against overflow.
|
|
210
|
+
const handledCPCountPlusOne = handledCPCount + 1;
|
|
211
|
+
if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
|
|
212
|
+
error('overflow');
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
delta += (m - n) * handledCPCountPlusOne;
|
|
216
|
+
n = m;
|
|
217
|
+
|
|
218
|
+
for (const currentValue of input) {
|
|
219
|
+
if (currentValue < n && ++delta > maxInt) {
|
|
220
|
+
error('overflow');
|
|
221
|
+
}
|
|
222
|
+
if (currentValue === n) {
|
|
223
|
+
// Represent delta as a generalized variable-length integer.
|
|
224
|
+
let q = delta;
|
|
225
|
+
for (let k = base; /* no condition */; k += base) {
|
|
226
|
+
const t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
|
|
227
|
+
if (q < t) {
|
|
228
|
+
break;
|
|
229
|
+
}
|
|
230
|
+
const qMinusT = q - t;
|
|
231
|
+
const baseMinusT = base - t;
|
|
232
|
+
output.push(
|
|
233
|
+
stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
|
|
234
|
+
);
|
|
235
|
+
q = floor(qMinusT / baseMinusT);
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
output.push(stringFromCharCode(digitToBasic(q, 0)));
|
|
239
|
+
bias = adapt(delta, handledCPCountPlusOne, handledCPCount === basicLength);
|
|
240
|
+
delta = 0;
|
|
241
|
+
++handledCPCount;
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
++delta;
|
|
246
|
+
++n;
|
|
247
|
+
|
|
248
|
+
}
|
|
249
|
+
return output.join('');
|
|
250
|
+
};
|
|
251
|
+
|
|
252
|
+
/**
|
|
253
|
+
* Converts a Unicode string representing a domain name or an email address to
|
|
254
|
+
* Punycode. Only the non-ASCII parts of the domain name will be converted,
|
|
255
|
+
* i.e. it doesn't matter if you call it with a domain that's already in
|
|
256
|
+
* ASCII.
|
|
257
|
+
* @memberOf punycode
|
|
258
|
+
* @param {String} input The domain name or email address to convert, as a
|
|
259
|
+
* Unicode string.
|
|
260
|
+
* @returns {String} The Punycode representation of the given domain name or
|
|
261
|
+
* email address.
|
|
262
|
+
*/
|
|
263
|
+
const toASCII = function(input) {
|
|
264
|
+
return mapDomain(input, function(string) {
|
|
265
|
+
return regexNonASCII.test(string)
|
|
266
|
+
? 'xn--' + encode(string)
|
|
267
|
+
: string;
|
|
268
|
+
});
|
|
269
|
+
};
|
|
270
|
+
|
|
271
|
+
/**
|
|
272
|
+
* Parse public suffix list and invoke callback on each rule.
|
|
273
|
+
*/
|
|
274
|
+
var parse = (body, cb) => {
|
|
275
|
+
const beginPrivateDomains = '// ===begin private domains===';
|
|
276
|
+
let isIcann = true;
|
|
277
|
+
// Iterate on lines and extract public suffix rules
|
|
278
|
+
const lines = body.split('\n');
|
|
279
|
+
for (let line of lines) {
|
|
280
|
+
line = line.trim().toLowerCase();
|
|
281
|
+
// Ignore comments
|
|
282
|
+
if (line.length === 0 || line.startsWith('//')) {
|
|
283
|
+
if (line.startsWith(beginPrivateDomains)) {
|
|
284
|
+
isIcann = false;
|
|
285
|
+
}
|
|
286
|
+
continue;
|
|
287
|
+
}
|
|
288
|
+
let isException = false;
|
|
289
|
+
let isWildcard = false;
|
|
290
|
+
let isNormal = false;
|
|
291
|
+
// Select correct section to insert the rule
|
|
292
|
+
if (line.startsWith('!')) {
|
|
293
|
+
isException = true;
|
|
294
|
+
line = line.slice(1);
|
|
295
|
+
}
|
|
296
|
+
else if (line.startsWith('*.')) {
|
|
297
|
+
isWildcard = true;
|
|
298
|
+
}
|
|
299
|
+
else {
|
|
300
|
+
isNormal = true;
|
|
301
|
+
}
|
|
302
|
+
// Specification says that we should only consider the content of a line up
|
|
303
|
+
// to the first whitespace encountered.
|
|
304
|
+
const spaceIndex = line.indexOf(' ');
|
|
305
|
+
if (spaceIndex !== -1) {
|
|
306
|
+
line = line.substr(0, spaceIndex);
|
|
307
|
+
}
|
|
308
|
+
// If suffix is not ascii, we index the suffix twice so that we support IDNA
|
|
309
|
+
// labels as well. This allows to not have to perform the conversion at
|
|
310
|
+
// runtime.
|
|
311
|
+
const encoded = toASCII(line);
|
|
312
|
+
if (line !== encoded) {
|
|
313
|
+
cb({
|
|
314
|
+
isException,
|
|
315
|
+
isIcann,
|
|
316
|
+
isNormal,
|
|
317
|
+
isWildcard,
|
|
318
|
+
rule: encoded,
|
|
319
|
+
});
|
|
320
|
+
}
|
|
321
|
+
cb({
|
|
322
|
+
isException,
|
|
323
|
+
isIcann,
|
|
324
|
+
isNormal,
|
|
325
|
+
isWildcard,
|
|
326
|
+
rule: line,
|
|
327
|
+
});
|
|
328
|
+
}
|
|
329
|
+
};
|
|
330
|
+
|
|
331
|
+
function findBaseDir (target) {
|
|
332
|
+
let baseDir = __dirname;
|
|
333
|
+
while (!fs.existsSync(path.resolve(baseDir, target))) {
|
|
334
|
+
baseDir = path.resolve(baseDir, '../');
|
|
335
|
+
}
|
|
336
|
+
return path.resolve(baseDir, target);
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
function loadPublicSuffixList () {
|
|
340
|
+
return fs.readFileSync(findBaseDir('./publicsuffix/public_suffix_list.dat'), {
|
|
341
|
+
encoding: 'utf-8',
|
|
342
|
+
});
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
/**
|
|
346
|
+
* This builder implements a probabilistic data-structure to store the public
|
|
347
|
+
* suffixes from Mozilla's 'publicsuffix' project. The goals are:
|
|
348
|
+
*
|
|
349
|
+
* 1. Allow storing the parsed rules in a very compact form (<30KB)
|
|
350
|
+
* 2. Allow super fast load time with no parsing required (typed array)
|
|
351
|
+
* 2. Super fast lookup times (~2M+ per second)
|
|
352
|
+
*
|
|
353
|
+
* These are achieved by hashing each available suffix as a 32bits number and
|
|
354
|
+
* storing them in a typed array which is bundled in the library itself. This
|
|
355
|
+
* way the only cost of loading the rules is paid by the JavaScript engine
|
|
356
|
+
* loading the source and the size of the rules is ~29KB. Matching is also
|
|
357
|
+
* extremely fast, at around 2M+ lookups per second.
|
|
358
|
+
*
|
|
359
|
+
* **WARNING**: The drawback of this structure is that, because we use hashes of
|
|
360
|
+
* suffixes instead of their initial values, there can be collisions (think
|
|
361
|
+
* bloom filters). Some future work involves estimating the probability of
|
|
362
|
+
* collisions. Only use this structure if you are fine with this limitation and
|
|
363
|
+
* need the most compact/fast data structure available.
|
|
364
|
+
*
|
|
365
|
+
* Data Structure
|
|
366
|
+
* ==============
|
|
367
|
+
*
|
|
368
|
+
* The basic idea behind the packed hashes structure is that suffixes will be
|
|
369
|
+
* grouped by number of labels then hashed to 32bits integers using a fast
|
|
370
|
+
* hashing function. For examples:
|
|
371
|
+
*
|
|
372
|
+
* 1 label:
|
|
373
|
+
* com -> hash(com)
|
|
374
|
+
* fr -> hash(fr)
|
|
375
|
+
* gov -> hash(gov)
|
|
376
|
+
* 2 labels:
|
|
377
|
+
* co.uk -> hash(co.uk)
|
|
378
|
+
*
|
|
379
|
+
* Then the hashes are organized in a typed array from least number of labels to
|
|
380
|
+
* most number of labels, and in each section, hashes are sorted so that we can
|
|
381
|
+
* perform lookups using a binary search:
|
|
382
|
+
*
|
|
383
|
+
* |#1 length|suffix 1|suffix 2|...|#2 length|suffix 1|suffix 2|...|...
|
|
384
|
+
* ^ ^ number of suffixes with 2 labels
|
|
385
|
+
* | number of suffix with 1 label
|
|
386
|
+
*
|
|
387
|
+
* In the example above:
|
|
388
|
+
*
|
|
389
|
+
* 3|hash(com)|hash(fr)|hash(gov)|1|hash(co.uk)
|
|
390
|
+
* ^ ^ we have on suffix with 2 labels (co.uk)
|
|
391
|
+
* | we have 3 suffixes with one label
|
|
392
|
+
*
|
|
393
|
+
* In practice, the data-structure is slightly more complex as we have to handle
|
|
394
|
+
* the ICANN and PRIVATE sections of the list separately (which allows to pick
|
|
395
|
+
* one or the other at runtime; or both, which is the default) as well as
|
|
396
|
+
* wildcards and exceptions rules. The structure looks more like:
|
|
397
|
+
*
|
|
398
|
+
* |icann exceptions|private exceptions|icann wildcards|private wildcards|icann rules|private rules
|
|
399
|
+
*
|
|
400
|
+
* Still ordered from least number of labels to most number of labels. This
|
|
401
|
+
* allows the matching to be a forward progression from beginning to end,
|
|
402
|
+
* potentially skipping some sections (e.g.: private) by just incrementing the
|
|
403
|
+
* index.
|
|
404
|
+
*
|
|
405
|
+
* Finding a Match
|
|
406
|
+
* ===============
|
|
407
|
+
*
|
|
408
|
+
* Finding a match can be done efficiently, without any string copy and by a
|
|
409
|
+
* single pass over the input (from end to beginning). The algorithm is as
|
|
410
|
+
* follows:
|
|
411
|
+
*
|
|
412
|
+
* - For each character `c` in hostname, from end to start:
|
|
413
|
+
* 1. If `c` is '.' then we reached the end of a label:
|
|
414
|
+
* * Use a binary search in the section containing suffixes of the same
|
|
415
|
+
* size as our current label to check if our hash is there.
|
|
416
|
+
* * Move forward to the next section by incrementing the index by the
|
|
417
|
+
* number of suffixes in this section.
|
|
418
|
+
* 2. Update the hash with the current character
|
|
419
|
+
*
|
|
420
|
+
* This does not account for wildcards and exceptions, but explains the general
|
|
421
|
+
* idea of the matching algorithm. Have a look at the source bellow for more
|
|
422
|
+
* details.
|
|
423
|
+
*
|
|
424
|
+
* Some nice properties of this algorithm:
|
|
425
|
+
* 1. Pretty straight-forward implementation
|
|
426
|
+
* 2. Matching is always going forward in the array
|
|
427
|
+
* 3. Sections can be skipped by just incrementing the index
|
|
428
|
+
* 4. Hash can be computed on-the-fly from end to start without any string copy
|
|
429
|
+
*/
|
|
430
|
+
/**
|
|
431
|
+
* Compute 32 bits hash of `str` backward.
|
|
432
|
+
*/
|
|
433
|
+
function fastHash(str) {
|
|
434
|
+
let hash = 5381;
|
|
435
|
+
for (let j = str.length - 1; j >= 0; j -= 1) {
|
|
436
|
+
hash = (hash * 33) ^ str.charCodeAt(j);
|
|
437
|
+
}
|
|
438
|
+
return hash >>> 0;
|
|
439
|
+
}
|
|
440
|
+
/**
|
|
441
|
+
* Build packed typed array given the raw public list as a string.
|
|
442
|
+
*/
|
|
443
|
+
var buildHashes = (body) => {
|
|
444
|
+
const rules = {
|
|
445
|
+
icann: [],
|
|
446
|
+
priv: [],
|
|
447
|
+
};
|
|
448
|
+
const wildcards = {
|
|
449
|
+
icann: [],
|
|
450
|
+
priv: [],
|
|
451
|
+
};
|
|
452
|
+
const exceptions = {
|
|
453
|
+
icann: [],
|
|
454
|
+
priv: [],
|
|
455
|
+
};
|
|
456
|
+
// Keep track of maximum number of labels seen in a given rule. This allows us
|
|
457
|
+
// to make sure that all sections of the typed array (wildcards, exceptions
|
|
458
|
+
// and normal rules) have the same size and we do not need to check that while
|
|
459
|
+
// matching.
|
|
460
|
+
let maximumNumberOfLabels = 0;
|
|
461
|
+
// Iterate on public suffix rules
|
|
462
|
+
parse(body, ({ rule, isIcann, isException, isWildcard, isNormal }) => {
|
|
463
|
+
// Select correct section to insert the rule
|
|
464
|
+
let hashesPerLabels = null;
|
|
465
|
+
if (isException) {
|
|
466
|
+
hashesPerLabels = isIcann ? exceptions.icann : exceptions.priv;
|
|
467
|
+
}
|
|
468
|
+
else if (isWildcard) {
|
|
469
|
+
hashesPerLabels = isIcann ? wildcards.icann : wildcards.priv;
|
|
470
|
+
// eslint-disable-next-line no-param-reassign
|
|
471
|
+
rule = rule.slice(2);
|
|
472
|
+
}
|
|
473
|
+
else if (isNormal) {
|
|
474
|
+
hashesPerLabels = isIcann ? rules.icann : rules.priv;
|
|
475
|
+
}
|
|
476
|
+
if (hashesPerLabels === null) {
|
|
477
|
+
return;
|
|
478
|
+
}
|
|
479
|
+
// Count number of labels in this suffix
|
|
480
|
+
const numberOfLabels = rule.split('.').length;
|
|
481
|
+
// Experimentally, we start ignoring suffixes with only one label since the
|
|
482
|
+
// fallback to '*' will yield the same result. This helps reduce the size of
|
|
483
|
+
// the bundle further and speed-up matching. One potential side-effect is
|
|
484
|
+
// that we might not accurately return the information about if a suffix is
|
|
485
|
+
// from the ICANN or PRIVATE section.
|
|
486
|
+
if (numberOfLabels === 1 &&
|
|
487
|
+
(hashesPerLabels === rules.icann || hashesPerLabels === rules.priv)) {
|
|
488
|
+
return;
|
|
489
|
+
}
|
|
490
|
+
maximumNumberOfLabels = Math.max(maximumNumberOfLabels, numberOfLabels);
|
|
491
|
+
let hashesForLabel = hashesPerLabels[numberOfLabels];
|
|
492
|
+
if (hashesForLabel === undefined) {
|
|
493
|
+
hashesForLabel = [];
|
|
494
|
+
hashesPerLabels[numberOfLabels] = hashesForLabel;
|
|
495
|
+
}
|
|
496
|
+
hashesForLabel.push(fastHash(rule));
|
|
497
|
+
});
|
|
498
|
+
// Pack everything together
|
|
499
|
+
const chunks = [];
|
|
500
|
+
const pushHashes = (hashes = []) => {
|
|
501
|
+
chunks.push([
|
|
502
|
+
hashes.length,
|
|
503
|
+
...hashes.sort((a, b) => {
|
|
504
|
+
if (a < b) {
|
|
505
|
+
return -1;
|
|
506
|
+
}
|
|
507
|
+
if (a > b) {
|
|
508
|
+
return 1;
|
|
509
|
+
}
|
|
510
|
+
return 0;
|
|
511
|
+
}),
|
|
512
|
+
]);
|
|
513
|
+
};
|
|
514
|
+
for (let label = 1; label <= maximumNumberOfLabels; label += 1) {
|
|
515
|
+
pushHashes(exceptions.icann[label]);
|
|
516
|
+
pushHashes(exceptions.priv[label]);
|
|
517
|
+
pushHashes(wildcards.icann[label]);
|
|
518
|
+
pushHashes(wildcards.priv[label]);
|
|
519
|
+
pushHashes(rules.icann[label]);
|
|
520
|
+
pushHashes(rules.priv[label]);
|
|
521
|
+
}
|
|
522
|
+
return new Uint32Array([
|
|
523
|
+
maximumNumberOfLabels,
|
|
524
|
+
...[].concat(...chunks),
|
|
525
|
+
]);
|
|
526
|
+
};
|
|
527
|
+
|
|
528
|
+
/**
|
|
529
|
+
* This builder implements a fast and compact DAWG data-structure (a.k.a.:
|
|
530
|
+
* direct acyclic word graph, with suffix and prefix compression of the
|
|
531
|
+
* top-level domains) using JavaScript Objects. It is a good trade-off between
|
|
532
|
+
* correctness, speed and space. This is much faster then using a linear scan
|
|
533
|
+
* over all the rules, but slightly slower than the probabilistic
|
|
534
|
+
* data-structure implemented in `bin/builders/hashes.js`.
|
|
535
|
+
*
|
|
536
|
+
* Here is a simple example:
|
|
537
|
+
*
|
|
538
|
+
* co.uk
|
|
539
|
+
* gov.uk
|
|
540
|
+
* fr
|
|
541
|
+
*
|
|
542
|
+
* <root>
|
|
543
|
+
* |_ uk
|
|
544
|
+
* |_ co *
|
|
545
|
+
* |_ gov *
|
|
546
|
+
* |_ fr *
|
|
547
|
+
*
|
|
548
|
+
* Finding a match is then a matter of iterating on labels of a hostname
|
|
549
|
+
* backward and following the branches of the Trie. Whenever we find a terminal
|
|
550
|
+
* node (indicated with a '*' above), we consider this a match.
|
|
551
|
+
*/
|
|
552
|
+
function convertToCompactTrie(trie) {
|
|
553
|
+
return [
|
|
554
|
+
trie.$,
|
|
555
|
+
Object.fromEntries(Object.entries(trie.succ).map(([label, succ]) => [
|
|
556
|
+
label,
|
|
557
|
+
typeof succ === 'string' ? succ : convertToCompactTrie(succ),
|
|
558
|
+
])),
|
|
559
|
+
];
|
|
560
|
+
}
|
|
561
|
+
/**
|
|
562
|
+
* Insert a public suffix rule in the `trie`.
|
|
563
|
+
*/
|
|
564
|
+
function insertInTrie({ parts, isIcann, }, trie) {
|
|
565
|
+
let node = trie;
|
|
566
|
+
for (const part of parts) {
|
|
567
|
+
let nextNode = node.succ[part];
|
|
568
|
+
if (nextNode === undefined) {
|
|
569
|
+
nextNode = { $: 0, succ: {} };
|
|
570
|
+
node.succ[part] = nextNode;
|
|
571
|
+
}
|
|
572
|
+
node = nextNode;
|
|
573
|
+
}
|
|
574
|
+
node.$ = isIcann ? 1 : 2;
|
|
575
|
+
return trie;
|
|
576
|
+
}
|
|
577
|
+
let nextId = 0;
|
|
578
|
+
/**
|
|
579
|
+
* Compress the given `trie` into a DAWG (by compressing common suffixes as
|
|
580
|
+
* well as prefixes). This form is very efficient but cannot be dumped as a
|
|
581
|
+
* simple JSON into the file. The solution is to create intermediary variables
|
|
582
|
+
* for each shared sub-tree, which are then used in the main DAWG.
|
|
583
|
+
*/
|
|
584
|
+
function compressToDAWG(trie, name) {
|
|
585
|
+
const nodesByHash = new Map();
|
|
586
|
+
const replaceNodes = new Map();
|
|
587
|
+
(function groupNodesByHash(node) {
|
|
588
|
+
// Get a sorted list of next labels from this node
|
|
589
|
+
const nexts = Object.entries(node.succ)
|
|
590
|
+
.filter(([n]) => n !== '$')
|
|
591
|
+
.sort();
|
|
592
|
+
// Create a setter which can be used later to replace the value of a node.
|
|
593
|
+
// Each node is associated with a lambda function accepting one argument:
|
|
594
|
+
// the new value of the node. Because the context of the node (parent and
|
|
595
|
+
// label) is captured in the closure, it allows to just call it later, in a
|
|
596
|
+
// different context, to change the value of a given node in-place.
|
|
597
|
+
nexts.forEach(([n, succ]) => {
|
|
598
|
+
replaceNodes.set(succ, (newNode) => {
|
|
599
|
+
node.succ[n] = newNode;
|
|
600
|
+
});
|
|
601
|
+
});
|
|
602
|
+
// Compute a unique hash for this node recursively.
|
|
603
|
+
const hash = `(${node.$},${[
|
|
604
|
+
...nexts.map(([c, succ]) => `${c},${groupNodesByHash(succ)}`),
|
|
605
|
+
].join('|')})`;
|
|
606
|
+
// Keep track of all node's hashes
|
|
607
|
+
let nodes = nodesByHash.get(hash);
|
|
608
|
+
if (nodes === undefined) {
|
|
609
|
+
nodes = [];
|
|
610
|
+
nodesByHash.set(hash, nodes);
|
|
611
|
+
}
|
|
612
|
+
nodes.push(node);
|
|
613
|
+
return hash;
|
|
614
|
+
})(trie);
|
|
615
|
+
// Given `nodesByHash`, which associates a list of nodes to each hash
|
|
616
|
+
// encountered in the previous step, we will detect all the sub-trees being
|
|
617
|
+
// seen more than once and store them in a variable to allow sharing with
|
|
618
|
+
// different parts in the DAWG.
|
|
619
|
+
const variables = [];
|
|
620
|
+
nodesByHash.forEach((nodes) => {
|
|
621
|
+
if (nodes.length > 1) {
|
|
622
|
+
// Dump one of the nodes (they are all the same so it does not matter which one)
|
|
623
|
+
variables.push(`_${nextId}: ITrie = ${JSON.stringify(convertToCompactTrie(nodes[0]))}`);
|
|
624
|
+
// Replace all the other ones by the name of this new variable
|
|
625
|
+
nodes.forEach((node) => {
|
|
626
|
+
var _a;
|
|
627
|
+
// @ts-expect-error
|
|
628
|
+
(_a = replaceNodes.get(node)) === null || _a === void 0 ? void 0 : _a(`_${nextId}`);
|
|
629
|
+
});
|
|
630
|
+
nextId += 1;
|
|
631
|
+
}
|
|
632
|
+
});
|
|
633
|
+
const output = [];
|
|
634
|
+
// Create TypeScript source code to declare all of these variables. Because
|
|
635
|
+
// the value of nodes has been set to a value of the form '"_id"', we need to
|
|
636
|
+
// replace this on the fly to '_id'. We use a RegExp for this.
|
|
637
|
+
if (variables.length !== 0) {
|
|
638
|
+
let variablesSourceCode = `const ${variables.join(',')};`;
|
|
639
|
+
for (let i = 0; i < nextId; i += 1) {
|
|
640
|
+
variablesSourceCode = variablesSourceCode.replace(new RegExp(`"_${i}"`, 'g'), `_${i}`);
|
|
641
|
+
}
|
|
642
|
+
output.push(variablesSourceCode);
|
|
643
|
+
}
|
|
644
|
+
// Dump the root of the DAWG as well, and perform the same replacement of _id
|
|
645
|
+
// parts than for the variables above.
|
|
646
|
+
let serializedTrie = JSON.stringify(convertToCompactTrie(trie));
|
|
647
|
+
for (let i = 0; i < nextId; i += 1) {
|
|
648
|
+
serializedTrie = serializedTrie.replace(new RegExp(`"_${i}"`, 'g'), `_${i}`);
|
|
649
|
+
}
|
|
650
|
+
output.push(`const ${name}: ITrie = ${serializedTrie};`);
|
|
651
|
+
return output.join('\n');
|
|
652
|
+
}
|
|
653
|
+
function convertToTypeScriptSource(rules, exceptions, { includePrivate }) {
|
|
654
|
+
return `
|
|
655
|
+
export type ITrie = [${includePrivate ? '0 | 1 | 2' : '0 | 1'}, { [label: string]: ITrie}];
|
|
656
|
+
|
|
657
|
+
export const exceptions: ITrie = (function() {
|
|
658
|
+
${compressToDAWG(exceptions, 'exceptions')}
|
|
659
|
+
return exceptions;
|
|
660
|
+
})();
|
|
661
|
+
|
|
662
|
+
export const rules: ITrie = (function() {
|
|
663
|
+
${compressToDAWG(rules, 'rules')}
|
|
664
|
+
return rules;
|
|
665
|
+
})();
|
|
666
|
+
`;
|
|
667
|
+
}
|
|
668
|
+
var buildTrie = (body, { includePrivate }) => {
|
|
669
|
+
const exceptions = { $: 0, succ: {} };
|
|
670
|
+
const rules = { $: 0, succ: {} };
|
|
671
|
+
// Iterate on public suffix rules
|
|
672
|
+
parse(body, ({ rule, isIcann, isException }) => {
|
|
673
|
+
if (isIcann || includePrivate) {
|
|
674
|
+
insertInTrie({ isIcann, parts: rule.split('.').reverse() }, isException ? exceptions : rules);
|
|
675
|
+
}
|
|
676
|
+
});
|
|
677
|
+
return convertToTypeScriptSource(rules, exceptions, { includePrivate });
|
|
678
|
+
};
|
|
679
|
+
|
|
680
|
+
function update () {
|
|
681
|
+
console.log('Updating rules...');
|
|
682
|
+
const publicSuffixList = loadPublicSuffixList();
|
|
683
|
+
// Build trie and update TypeScript file
|
|
684
|
+
fs.writeFileSync(findBaseDir('./tldts/src/data/trie.ts'), buildTrie(publicSuffixList, { includePrivate: true }), 'utf-8');
|
|
685
|
+
// Build trie and update TypeScript file (ICANN only)
|
|
686
|
+
fs.writeFileSync(findBaseDir('./tldts-icann/src/data/trie.ts'), buildTrie(publicSuffixList, { includePrivate: false }), 'utf-8');
|
|
687
|
+
// Build hashes and update TypeScript file
|
|
688
|
+
const packed = buildHashes(publicSuffixList);
|
|
689
|
+
fs.writeFileSync(findBaseDir('./tldts-experimental/src/data/hashes.ts'), `
|
|
690
|
+
// Code automatically generated using ./bin/builders/hashes.ts
|
|
691
|
+
export default new Uint32Array([${Array.from(packed).toString()}]);
|
|
692
|
+
`, 'utf-8');
|
|
693
|
+
}
|
|
694
|
+
|
|
695
|
+
exports.loadPublicSuffixList = loadPublicSuffixList;
|
|
696
|
+
exports.parsePublicSuffixRules = parse;
|
|
697
|
+
exports.updateInternalDataStructures = update;
|
|
698
|
+
//# sourceMappingURL=index.js.map
|