Skip to content

Commit 9677b06

Browse files
bttfmhegazy
authored andcommitted
Implement fallback hashing algorithm when crypto module is not available (#19941)
* Implement fallback hashing algorithm when crypto module is not available * Fix lint errors * Expose method internally and use in watch.ts * Simplify syntax; Remove fallback from watch.ts
1 parent b80081d commit 9677b06

File tree

1 file changed

+24
-6
lines changed

1 file changed

+24
-6
lines changed

Diff for: src/compiler/sys.ts

+24-6
Original file line numberDiff line numberDiff line change
@@ -126,10 +126,32 @@ namespace ts {
126126
const _fs = require("fs");
127127
const _path = require("path");
128128
const _os = require("os");
129-
const _crypto = require("crypto");
129+
// crypto can be absent on reduced node installations
130+
let _crypto: any;
131+
try {
132+
_crypto = require("crypto");
133+
}
134+
catch {
135+
_crypto = undefined;
136+
}
130137

131138
const useNonPollingWatchers = process.env.TSC_NONPOLLING_WATCHER;
132139

140+
/**
141+
* djb2 hashing algorithm
142+
* http://www.cse.yorku.ca/~oz/hash.html
143+
*/
144+
function generateDjb2Hash(data: string): string {
145+
const chars = data.split("").map(str => str.charCodeAt(0));
146+
return `${chars.reduce((prev, curr) => ((prev << 5) + prev) + curr, 5381)}`;
147+
}
148+
149+
function createMD5HashUsingNativeCrypto(data: string) {
150+
const hash = _crypto.createHash("md5");
151+
hash.update(data);
152+
return hash.digest("hex");
153+
}
154+
133155
function createWatchedFileSet() {
134156
const dirWatchers = createMap<DirectoryWatcher>();
135157
// One file can have multiple watchers
@@ -493,11 +515,7 @@ namespace ts {
493515
return undefined;
494516
}
495517
},
496-
createHash(data) {
497-
const hash = _crypto.createHash("md5");
498-
hash.update(data);
499-
return hash.digest("hex");
500-
},
518+
createHash: _crypto ? createMD5HashUsingNativeCrypto : generateDjb2Hash,
501519
getMemoryUsage() {
502520
if (global.gc) {
503521
global.gc();

0 commit comments

Comments
 (0)