/
index.js
73 lines (62 loc) · 2.4 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
var through = require('through2');
var bookmarklet = require('bookmarklet');
var netscape = require('netscape-bookmarks');
var path = require('path');
var replaceExt = require('replace-ext');
var PluginError = require('plugin-error');
const PLUGIN_NAME = 'gulp-bookmarklet';
module.exports = function(opt) {
var opt = opt || {},
format = opt.format || 'js',
htmlSingleFileName = opt.file || 'bookmarklets.html',
validFormats = ['js', 'html', 'htmlsingle'],
bookmarklets = {},
latestFile;
if (validFormats.indexOf(format) === -1) {
throw new PluginError(PLUGIN_NAME, "Invalid format '" + format + "' - Must be one of ['js', 'html', 'htmlsingle']");
}
function generateBookmarklet(file, enc, cb) {
if (file.isStream()) {
this.emit('error', new PluginError(PLUGIN_NAME, 'Streams are not supported!'));
return cb();
}
if (file.isBuffer()) {
var filename = path.basename(file.path).replace(path.extname(file.path), ''),
data = bookmarklet.parseFile(file.contents.toString(enc));
if (data.errors) {
this.emit('error', new PluginError(PLUGIN_NAME, data.errors.join('\n')));
return cb();
}
var code = bookmarklet.convert(data.code, data.options);
latestFile = file;
if (format === 'htmlsingle') {
bookmarklets[filename] = code;
} else {
if (format === 'html') {
var bookmark = {};
bookmark[filename] = code;
code = netscape(bookmark);
file.path = replaceExt(file.path, '.html');
} else { // format === 'js'
file.path = replaceExt(file.path, '.min.js');
}
file.contents = new Buffer(code);
this.push(file);
}
cb();
}
}
function endStream(cb) {
if (format !== 'htmlsingle' || bookmarklets.length === 0) {
cb();
return;
}
var code = netscape(bookmarklets),
file = latestFile.clone({contents: false});
file.path = path.join(latestFile.base, htmlSingleFileName);
file.contents = new Buffer(code);
this.push(file);
cb();
}
return through.obj(generateBookmarklet, endStream);
};