-
Notifications
You must be signed in to change notification settings - Fork 64
/
Copy pathindex.js
302 lines (254 loc) · 8.31 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
'use strict';
var path = require('path'),
fs = require('fs'),
natural = require('natural'),
lunr = require('lunr'),
tokenizer = new natural.WordTokenizer(),
loc = path.resolve(__dirname, 'content'),
scraper = {
title: /\[meta:title\]:\s<>\s\((.+?)\)(?!\))/,
description: /\[meta:description\]:\s<>\s\((.+?)\)(?!\))/,
firstlines: /^((.*\n){2}){1,3}/
};
//
// ### @private function scrape()
// #### @content {String} document content
// #### @key {String} scraper key
// #### @n {Number} index of match that should be returned
// Scrapes the [key] from the content by Regular Epression
//
function scrape(content, key, n) {
if (!content) return '';
var match = content.match(scraper[key]);
// Only return scraped content if there is a meta:[key].
return match && match[n] ? match[n].trim() : '';
}
//
// ### @private function normalize()
// #### @file {String} file name
// Normalize the file name to resolve to a Markdown or index file.
//
function normalize(file) {
if (!file) file = 'index.md';
// Remove trailing slashes from paths
if (file[file.length - 1] === '/') file = file.slice(0, -1);
return ~file.indexOf('.md') ? file : file + '.md';
}
//
// ### @private function fileContent()
// #### @content {String} Document content
// Sugar content with additional properties from scraped content.
//
function fileContent(content) {
return {
content: content || '',
description: scrape(content, 'description', 1) || scrape(content, 'firstlines', 0),
title: scrape(content, 'title', 1),
tags: tags(content, 10)
};
}
//
// ### @private function frequency()
// #### @content {String} Document content
// Return list of words scored by Term Frequency-Inverse Document Frequency.
//
function frequency(content) {
var tfidf = new natural.TfIdf(),
processed = [],
words = [];
// Add the current content.
content = content.toLowerCase();
tfidf.addDocument(content);
tokenizer.tokenize(content).forEach(function wordFrequency(word) {
// Return early if word is processed, to short or only a number.
if (+word || word.length < 3 || ~processed.indexOf(word)) return;
words.push({
word: word,
score: tfidf.tfidf(word, 0)
});
// Add word to processed so tfidf is not called more than required.
processed.push(word);
});
return words;
}
//
// ### @private function tags()
// #### @content {String} Document content
// #### @n {Number} number of tags
// Return n highest scoring tags as determined by term frequency.
//
function tags(content, n) {
if (!content) return [];
return frequency(content).sort(function sortByScore(a, b) {
return b.score - a.score;
}).slice(0, n).map(function extractWords(tag) {
return tag.word;
});
}
//
// ### @private function read()
// #### @file {String} Filename
// #### @callback {Function} Callback for file contents
// Returns file content by normalized path, if a callback is provided, content
// is returned asynchronously.
//
function read(file, callback) {
file = path.resolve(loc, normalize(file));
if (!callback) return fileContent(fs.readFileSync(file, 'utf8'));
fs.readFile(file, 'utf8', function read(error, content) {
callback.apply(this, [error, fileContent(content)]);
});
}
//
// ### @private function walk()
// #### @dir {String} Directory path to crawl
// #### @result {Object} Append content to current results
// #### @callback {Function} Callback for sub directory
// #### @sub {Boolean} Is directory subdirectory of dir
// Recusive walk of directory by using asynchronous functions, returns
// a collection of markdown files in each folder.
//
function walk(dir, callback, result, sub) {
var current = sub ? path.basename(dir) : 'index';
// Prepare containers.
result = result || {};
result[current] = {};
// Read the current directory
fs.readdir(dir, function readDir(error, list) {
if (error) return callback(error);
var pending = list.length;
if (!pending) return callback(null, result);
list.forEach(function loopFiles(file) {
file = dir + '/' + file;
fs.stat(file, function statFile(error, stat) {
var name, ref;
if (stat && stat.isDirectory()) {
walk(file, function dirDone() {
if (!--pending) callback(null, result);
}, result, true);
} else {
// Only get markdown files from the directory content.
if (path.extname(file) !== '.md') return;
ref = path.basename(file, '.md');
name = ['/' + path.basename(dir), ref];
// Only append the name of the file if not index
if (ref === 'index') name.pop();
// Get the tile of the file.
read(file, function getFile(err, file) {
result[current][ref] = {
href: sub ? name.join('/') + '/' : '/',
title: file.title,
description: file.description,
path: dir
};
if (!--pending) callback(null, result);
});
}
});
});
});
}
//
// ### @private function walkSync()
// #### @dir {String} Directory path to crawl
// #### @result {Object} Append content to current results
// #### @sub {Boolean} Is directory subdirectory of dir
// Recusive walk of directory by using synchronous functions, returns
// a collection of markdown files in each folder.
//
function walkSync(dir, result, sub) {
var current = sub ? path.basename(dir) : 'index';
// Prepare containers.
result = result || {};
result[current] = {};
// Read the current directory
fs.readdirSync(dir).forEach(function loopDir(file) {
var stat, name, ref;
file = dir + '/' + file;
stat = fs.statSync(file);
// If directory initiate another walk.
if (stat && stat.isDirectory()) {
walkSync(file, result, true);
} else {
// Only get markdown files from the directory content.
if (path.extname(file) !== '.md') return;
ref = path.basename(file, '.md');
name = ['/' + path.basename(dir), ref];
// Only append the name of the file if not index
if (ref === 'index') name.pop();
// Append file information to current container.
file = read(file);
result[current][ref] = {
href: sub ? name.join('/') + '/' : '/',
title: file.title,
description: file.description,
path: dir
};
}
});
return result;
}
//
// ### function Handbook()
// Constructor for easy access to Handbook content. On constructuing handbook
// synchronously prepare the search index. Listening to a search index ready
// event is not required thus easing the flow.
//
function Handbook() {
var toc = this.index = walkSync(loc),
cache = this.cache = {},
idx = this.idx = lunr(function setupLunr() {
this.field('title', { boost: 10 });
this.field('body');
});
Object.keys(toc).forEach(function loopSections(section) {
Object.keys(toc[section]).forEach(function loopPages(page) {
var document = read((section !== 'index' ? section + '/' : '') + page)
, id = section + '/' + page;
idx.add({
id: id,
title: document.title,
body: document.content
});
//
// Keep cached reference of all documents, for quick external access.
//
cache[id] = document;
});
});
}
//
// ### function get()
// #### @file {String} Filename
// #### @callback {Function} Callback for file contents
// Proxy method to private async method read. This method can be called
// synchronously by omitting the callback.
//
Handbook.prototype.get = function get(file, callback) {
return read.apply(this, arguments);
};
//
// ### function catalog()
// #### @callback {Function} Callback for catalog/TOC
// Returns a catalog by parsing the content directory, if a callback is provided
// content is returned asynchronously.
//
Handbook.prototype.catalog = function catalog(callback) {
if (!callback) return walkSync(loc);
walk(loc, callback);
};
//
// ### function search()
// #### @query {String} Query to search against
// Proxy to the search method of Lunr, returns a list of documents, this must
// be called in Lunr scope.
//
Handbook.prototype.search = function (query) {
return this.idx.search.call(this.idx, query);
};
//
// Expose the 301 routes for the handbook.
//
Handbook.redirect = require('./301.json');
// Expose public functions.
module.exports = Handbook;