From 9677b0641cc5ba7d8b701b4f892ed7e54ceaee9a Mon Sep 17 00:00:00 2001 From: Adnan Chowdhury Date: Thu, 25 Jan 2018 16:17:58 -0800 Subject: [PATCH] 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 --- src/compiler/sys.ts | 30 ++++++++++++++++++++++++------ 1 file changed, 24 insertions(+), 6 deletions(-) diff --git a/src/compiler/sys.ts b/src/compiler/sys.ts index 3256eef4dc2..ef1a3f8fd49 100644 --- a/src/compiler/sys.ts +++ b/src/compiler/sys.ts @@ -126,10 +126,32 @@ namespace ts { const _fs = require("fs"); const _path = require("path"); const _os = require("os"); - const _crypto = require("crypto"); + // crypto can be absent on reduced node installations + let _crypto: any; + try { + _crypto = require("crypto"); + } + catch { + _crypto = undefined; + } const useNonPollingWatchers = process.env.TSC_NONPOLLING_WATCHER; + /** + * djb2 hashing algorithm + * http://www.cse.yorku.ca/~oz/hash.html + */ + function generateDjb2Hash(data: string): string { + const chars = data.split("").map(str => str.charCodeAt(0)); + return `${chars.reduce((prev, curr) => ((prev << 5) + prev) + curr, 5381)}`; + } + + function createMD5HashUsingNativeCrypto(data: string) { + const hash = _crypto.createHash("md5"); + hash.update(data); + return hash.digest("hex"); + } + function createWatchedFileSet() { const dirWatchers = createMap(); // One file can have multiple watchers @@ -493,11 +515,7 @@ namespace ts { return undefined; } }, - createHash(data) { - const hash = _crypto.createHash("md5"); - hash.update(data); - return hash.digest("hex"); - }, + createHash: _crypto ? createMD5HashUsingNativeCrypto : generateDjb2Hash, getMemoryUsage() { if (global.gc) { global.gc();