-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
73 lines (63 loc) · 1.78 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
/**
* Copyright (C) 2016 pantojs.xyz
* index.js
*
* changelog
* 2016-06-22[13:12:07]:revised
*
* @author yanni4night@gmail.com
* @version 0.2.4
* @since 0.1.0
*/
'use strict';
const Transformer = require('panto-transformer');
const crypto = require('crypto');
class IntegrityTransformer extends Transformer {
_transform(file) {
const {
filename,
content
} = file;
const algorithms = ['sha256', 'sha384', 'sha512'];
const {
algorithm,
ignoreError
} = this.options;
const tryOne = algorithm => {
try {
let sum = algorithm + '-' + crypto.createHash(algorithm).update(content).digest().toString(
'base64');
return sum;
} catch (e) {
panto.log.warn(`IntegrityTransform error in ${filename}: ${e.message}`);
}
};
const tryN = () => {
for (let i = 0; i < algorithms.length; ++i) {
let sum = tryOne(algorithms[i]);
if (sum) {
return sum;
}
}
};
let sum;
if (panto._.isUndefined(algorithm)) {
sum = tryN();
} else if (algorithms.indexOf(algorithm) > -1) {
sum = tryOne(algorithm);
} else {
panto.log.error(`IntegrityTransform error: algorithm must be one of ${algorithms.join()}`);
}
if (!sum) {
if (ignoreError) {
return Promise.resolve(file);
} else {
return Promise.reject(file);
}
}
return Promise.resolve(panto._.extend(file, {
integrity: sum
}));
}
}
module.exports = IntegrityTransformer;