Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: migrate jest-haste-map to TypeScript #7854

Merged
merged 16 commits into from Feb 12, 2019
Merged

Conversation

SimenB
Copy link
Member

@SimenB SimenB commented Feb 11, 2019

Summary

@jeysal I'll open up a PR even though this isn't ready. I've left tests alone except for fixing imports so they pass

See the type build on CI for a list of failures

Build diff:

diff --git c/packages/jest-haste-map/build/HasteFS.js w/packages/jest-haste-map/build/HasteFS.js
index 21564b6a0..7489b7662 100644
--- c/packages/jest-haste-map/build/HasteFS.js
+++ w/packages/jest-haste-map/build/HasteFS.js
@@ -5,33 +5,29 @@ Object.defineProperty(exports, '__esModule', {
 });
 exports.default = void 0;
 
-function _jestUtil() {
-  const data = require('jest-util');
+function _micromatch() {
+  const data = _interopRequireDefault(require('micromatch'));
 
-  _jestUtil = function _jestUtil() {
+  _micromatch = function _micromatch() {
     return data;
   };
 
   return data;
 }
 
-var fastPath = _interopRequireWildcard(require('./lib/fast_path'));
-
-function _micromatch() {
-  const data = _interopRequireDefault(require('micromatch'));
+function _jestUtil() {
+  const data = require('jest-util');
 
-  _micromatch = function _micromatch() {
+  _jestUtil = function _jestUtil() {
     return data;
   };
 
   return data;
 }
 
-var _constants = _interopRequireDefault(require('./constants'));
+var fastPath = _interopRequireWildcard(require('./lib/fast_path'));
 
-function _interopRequireDefault(obj) {
-  return obj && obj.__esModule ? obj : {default: obj};
-}
+var _constants = _interopRequireDefault(require('./constants'));
 
 function _interopRequireWildcard(obj) {
   if (obj && obj.__esModule) {
@@ -58,13 +54,15 @@ function _interopRequireWildcard(obj) {
   }
 }
 
+function _interopRequireDefault(obj) {
+  return obj && obj.__esModule ? obj : {default: obj};
+}
+
 /**
  * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
  *
  * This source code is licensed under the MIT license found in the
  * LICENSE file in the root directory of this source tree.
- *
- *
  */
 class HasteFS {
   constructor({rootDir, files}) {
@@ -117,7 +115,7 @@ class HasteFS {
 
     try {
       for (
-        var _iterator = this._files.keys()[Symbol.iterator](), _step;
+        var _iterator = this.getFileIterator()[Symbol.iterator](), _step;
         !(_iteratorNormalCompletion = (_step = _iterator.next()).done);
         _iteratorNormalCompletion = true
       ) {
diff --git c/packages/jest-haste-map/build/ModuleMap.js w/packages/jest-haste-map/build/ModuleMap.js
index 9ed4cea27..791d833f0 100644
--- c/packages/jest-haste-map/build/ModuleMap.js
+++ w/packages/jest-haste-map/build/ModuleMap.js
@@ -88,7 +88,7 @@ class ModuleMap {
   }
 
   getModule(name, platform, supportsNativePlatform, type) {
-    if (!type) {
+    if (type == null) {
       type = _constants.default.MODULE;
     }
 
@@ -106,7 +106,7 @@ class ModuleMap {
     return null;
   }
 
-  getPackage(name, platform, supportsNativePlatform) {
+  getPackage(name, platform, _supportsNativePlatform) {
     return this.getModule(name, platform, null, _constants.default.PACKAGE);
   }
 
diff --git c/packages/jest-haste-map/build/blacklist.js w/packages/jest-haste-map/build/blacklist.js
index fe7625c91..32a1dba34 100644
--- c/packages/jest-haste-map/build/blacklist.js
+++ w/packages/jest-haste-map/build/blacklist.js
@@ -10,8 +10,6 @@ exports.default = void 0;
  *
  * This source code is licensed under the MIT license found in the
  * LICENSE file in the root directory of this source tree.
- *
- *
  */
 // This list is compiled after the MDN list of the most common MIME types (see
 // https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/
diff --git c/packages/jest-haste-map/build/constants.js w/packages/jest-haste-map/build/constants.js
index 8f63443d8..bcbcf38ab 100644
--- c/packages/jest-haste-map/build/constants.js
+++ w/packages/jest-haste-map/build/constants.js
@@ -10,8 +10,6 @@ exports.default = void 0;
  *
  * This source code is licensed under the MIT license found in the
  * LICENSE file in the root directory of this source tree.
- *
- *
  */
 
 /* eslint-disable sort-keys */
@@ -24,7 +22,7 @@ exports.default = void 0;
  * This constant key map allows to keep the map smaller without having to build
  * a custom serialization library.
  */
-var _default = {
+const constants = {
   /* file map attributes */
   ID: 0,
   MTIME: 1,
@@ -45,4 +43,5 @@ var _default = {
   GENERIC_PLATFORM: 'g',
   NATIVE_PLATFORM: 'native'
 };
+var _default = constants;
 exports.default = _default;
diff --git c/packages/jest-haste-map/build/crawlers/node.js w/packages/jest-haste-map/build/crawlers/node.js
index ba2db5bf4..29a941958 100644
--- c/packages/jest-haste-map/build/crawlers/node.js
+++ w/packages/jest-haste-map/build/crawlers/node.js
@@ -63,14 +63,47 @@ function _interopRequireDefault(obj) {
   return obj && obj.__esModule ? obj : {default: obj};
 }
 
-/**
- * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
+function _slicedToArray(arr, i) {
+  return (
+    _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest()
+  );
+}
+
+function _nonIterableRest() {
+  throw new TypeError('Invalid attempt to destructure non-iterable instance');
+}
+
+function _iterableToArrayLimit(arr, i) {
+  var _arr = [];
+  var _n = true;
+  var _d = false;
+  var _e = undefined;
+  try {
+    for (
+      var _i = arr[Symbol.iterator](), _s;
+      !(_n = (_s = _i.next()).done);
+      _n = true
+    ) {
+      _arr.push(_s.value);
+      if (i && _arr.length === i) break;
+    }
+  } catch (err) {
+    _d = true;
+    _e = err;
+  } finally {
+    try {
+      if (!_n && _i['return'] != null) _i['return']();
+    } finally {
+      if (_d) throw _e;
+    }
+  }
+  return _arr;
+}
+
+function _arrayWithHoles(arr) {
+  if (Array.isArray(arr)) return arr;
+}
+
 function find(roots, extensions, ignore, callback) {
   const result = [];
   let activeCalls = 0;
@@ -132,7 +165,7 @@ function find(roots, extensions, ignore, callback) {
 }
 
 function findNative(roots, extensions, ignore, callback) {
-  const args = [].concat(roots);
+  const args = Array.from(roots);
   args.push('-type', 'f');
 
   if (extensions.length) {
@@ -197,10 +230,12 @@ module.exports = function nodeCrawl(options) {
     const callback = list => {
       const files = new Map();
       list.forEach(fileData => {
-        const filePath = fileData[0];
+        const _fileData = _slicedToArray(fileData, 3),
+          filePath = _fileData[0],
+          mtime = _fileData[1],
+          size = _fileData[2];
+
         const relativeFilePath = fastPath.relative(rootDir, filePath);
-        const mtime = fileData[1];
-        const size = fileData[2];
         const existingFile = data.files.get(relativeFilePath);
 
         if (existingFile && existingFile[_constants.default.MTIME] === mtime) {
diff --git c/packages/jest-haste-map/build/crawlers/watchman.js w/packages/jest-haste-map/build/crawlers/watchman.js
index 6cff12404..5eea023ec 100644
--- c/packages/jest-haste-map/build/crawlers/watchman.js
+++ w/packages/jest-haste-map/build/crawlers/watchman.js
@@ -1,11 +1,5 @@
 'use strict';
 
-var fastPath = _interopRequireWildcard(require('../lib/fast_path'));
-
-var _normalizePathSep = _interopRequireDefault(
-  require('../lib/normalizePathSep')
-);
-
 function _path() {
   const data = _interopRequireDefault(require('path'));
 
@@ -26,11 +20,13 @@ function _fbWatchman() {
   return data;
 }
 
-var _constants = _interopRequireDefault(require('../constants'));
+var fastPath = _interopRequireWildcard(require('../lib/fast_path'));
 
-function _interopRequireDefault(obj) {
-  return obj && obj.__esModule ? obj : {default: obj};
-}
+var _normalizePathSep = _interopRequireDefault(
+  require('../lib/normalizePathSep')
+);
+
+var _constants = _interopRequireDefault(require('../constants'));
 
 function _interopRequireWildcard(obj) {
   if (obj && obj.__esModule) {
@@ -57,6 +53,10 @@ function _interopRequireWildcard(obj) {
   }
 }
 
+function _interopRequireDefault(obj) {
+  return obj && obj.__esModule ? obj : {default: obj};
+}
+
 function _slicedToArray(arr, i) {
   return (
     _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest()
@@ -153,12 +153,12 @@ module.exports =
       const defaultWatchExpression = [
         'allof',
         ['type', 'f'],
-        ['anyof'].concat(extensions.map(extension => ['suffix', extension]))
+        ['anyof', ...extensions.map(extension => ['suffix', extension])]
       ];
       const clocks = data.clocks;
       const client = new (_fbWatchman()).default.Client();
       let clientError;
-      client.on('error', error => (clientError = WatchmanError(error)));
+      client.on('error', error => (clientError = WatchmanError(error))); // TODO: type better than `any`
 
       const cmd = (...args) =>
         new Promise((resolve, reject) =>
@@ -398,7 +398,7 @@ module.exports =
 
       if (clientError) {
         throw clientError;
-      }
+      } // TODO: remove non-null
 
       var _iteratorNormalCompletion = true;
       var _didIteratorError = false;
@@ -461,10 +461,11 @@ module.exports =
                   sha1hex &&
                   existingFileData[_constants.default.SHA1] === sha1hex
                 ) {
+                  // @ts-ignore: TODO why is this wrong?
                   nextData = [...existingFileData];
                   nextData[1] = mtime;
                 } else {
-                  // See ../constants.js
+                  // See ../constants.ts
                   nextData = ['', mtime, size, 0, [], sha1hex];
                 }
 
diff --git c/packages/jest-haste-map/build/getMockName.js w/packages/jest-haste-map/build/getMockName.js
index 851b742e8..29e0f9980 100644
--- c/packages/jest-haste-map/build/getMockName.js
+++ w/packages/jest-haste-map/build/getMockName.js
@@ -24,8 +24,6 @@ function _interopRequireDefault(obj) {
  *
  * This source code is licensed under the MIT license found in the
  * LICENSE file in the root directory of this source tree.
- *
- *
  */
 const MOCKS_PATTERN = _path().default.sep + '__mocks__' + _path().default.sep;
 
diff --git c/packages/jest-haste-map/build/index.js w/packages/jest-haste-map/build/index.js
index 08941ca3a..541331ff0 100644
--- c/packages/jest-haste-map/build/index.js
+++ w/packages/jest-haste-map/build/index.js
@@ -10,10 +10,6 @@ function _child_process() {
   return data;
 }
 
-var _package = require('../package.json');
-
-var _worker = require('./worker');
-
 function _crypto() {
   const data = _interopRequireDefault(require('crypto'));
 
@@ -44,34 +40,6 @@ function _fs() {
   return data;
 }
 
-var _getMockName = _interopRequireDefault(require('./getMockName'));
-
-var _getPlatformExtension = _interopRequireDefault(
-  require('./lib/getPlatformExtension')
-);
-
-var _constants = _interopRequireDefault(require('./constants'));
-
-var _HasteFS = _interopRequireDefault(require('./HasteFS'));
-
-var _ModuleMap = _interopRequireDefault(require('./ModuleMap'));
-
-function _invariant() {
-  const data = _interopRequireDefault(require('invariant'));
-
-  _invariant = function _invariant() {
-    return data;
-  };
-
-  return data;
-}
-
-var _node = _interopRequireDefault(require('./crawlers/node'));
-
-var _normalizePathSep = _interopRequireDefault(
-  require('./lib/normalizePathSep')
-);
-
 function _os() {
   const data = _interopRequireDefault(require('os'));
 
@@ -102,21 +70,25 @@ function _sane() {
   return data;
 }
 
-function _jestSerializer() {
-  const data = _interopRequireDefault(require('jest-serializer'));
+function _invariant() {
+  const data = _interopRequireDefault(require('invariant'));
 
-  _jestSerializer = function _jestSerializer() {
+  _invariant = function _invariant() {
     return data;
   };
 
   return data;
 }
 
-var _watchman = _interopRequireDefault(require('./crawlers/watchman'));
+function _jestSerializer() {
+  const data = _interopRequireDefault(require('jest-serializer'));
 
-var _WatchmanWatcher = _interopRequireDefault(require('./lib/WatchmanWatcher'));
+  _jestSerializer = function _jestSerializer() {
+    return data;
+  };
 
-var fastPath = _interopRequireWildcard(require('./lib/fast_path'));
+  return data;
+}
 
 function _jestWorker() {
   const data = _interopRequireDefault(require('jest-worker'));
@@ -128,6 +100,32 @@ function _jestWorker() {
   return data;
 }
 
+var _worker = require('./worker');
+
+var _getMockName = _interopRequireDefault(require('./getMockName'));
+
+var _getPlatformExtension = _interopRequireDefault(
+  require('./lib/getPlatformExtension')
+);
+
+var _constants = _interopRequireDefault(require('./constants'));
+
+var _HasteFS = _interopRequireDefault(require('./HasteFS'));
+
+var _ModuleMap = _interopRequireDefault(require('./ModuleMap'));
+
+var _node = _interopRequireDefault(require('./crawlers/node'));
+
+var _normalizePathSep = _interopRequireDefault(
+  require('./lib/normalizePathSep')
+);
+
+var _watchman = _interopRequireDefault(require('./crawlers/watchman'));
+
+var _WatchmanWatcher = _interopRequireDefault(require('./lib/WatchmanWatcher'));
+
+var fastPath = _interopRequireWildcard(require('./lib/fast_path'));
+
 function _interopRequireWildcard(obj) {
   if (obj && obj.__esModule) {
     return obj;
@@ -201,7 +199,12 @@ function _arrayWithHoles(arr) {
 const CHANGE_INTERVAL = 30;
 const MAX_WAIT_TIME = 240000;
 
-const NODE_MODULES = _path().default.sep + 'node_modules' + _path().default.sep;
+const NODE_MODULES = _path().default.sep + 'node_modules' + _path().default.sep; // TypeScript doesn't like us importing from outside `rootDir`
+
+const _JSON$parse = JSON.parse(
+    _fs().default.readFileSync(require.resolve('../package.json'), 'utf8')
+  ),
+  VERSION = _JSON$parse.version;
 
 const canUseWatchman = (() => {
   try {
@@ -362,7 +365,6 @@ class HasteMap extends _events().default {
     let dependencyExtractorHash = '';
 
     if (options.hasteImplModulePath) {
-      // $FlowFixMe: dynamic require
       const hasteImpl = require(options.hasteImplModulePath);
 
       if (hasteImpl.getCacheKey) {
@@ -371,7 +373,6 @@ class HasteMap extends _events().default {
     }
 
     if (options.dependencyExtractor) {
-      // $FlowFixMe: dynamic require
       const dependencyExtractor = require(options.dependencyExtractor);
 
       if (dependencyExtractor.getCacheKey) {
@@ -382,7 +383,7 @@ class HasteMap extends _events().default {
     this._cachePath = HasteMap.getCacheFilePath(
       this._options.cacheDirectory,
       `haste-map-${this._options.name}-${rootDirHash}`,
-      _package.version,
+      VERSION,
       this._options.name,
       this._options.roots
         .map(root => fastPath.relative(options.rootDir, root))
@@ -438,7 +439,7 @@ class HasteMap extends _events().default {
           const __hasteMapForTest =
             (process.env.NODE_ENV === 'test' && hasteMap) || null;
 
-          return this._watch(hasteMap, hasteFS, moduleMap).then(() => ({
+          return this._watch(hasteMap).then(() => ({
             __hasteMapForTest,
             hasteFS,
             moduleMap
@@ -659,7 +660,7 @@ class HasteMap extends _events().default {
       if (typeof error !== 'object' || !error.message || !error.stack) {
         error = new Error(error);
         error.stack = ''; // Remove stack for stack-less errors.
-      } // $FlowFixMe: checking error code is OK if error comes from "fs".
+      } // @ts-ignore: checking error code is OK if error comes from "fs".
 
       if (!['ENOENT', 'EACCES'].includes(error.code)) {
         throw error;
@@ -823,9 +824,10 @@ class HasteMap extends _events().default {
   }
 
   _cleanup() {
-    const worker = this._worker; // $FlowFixMe
+    const worker = this._worker; // @ts-ignore
 
     if (worker && typeof worker.end === 'function') {
+      // @ts-ignore
       worker.end();
     }
 
@@ -850,6 +852,7 @@ class HasteMap extends _events().default {
           worker: _worker.worker
         };
       } else {
+        // @ts-ignore: assignment of a worker with custom properties.
         this._worker = new (_jestWorker()).default(
           require.resolve('./worker'),
           {
@@ -925,7 +928,7 @@ class HasteMap extends _events().default {
    * Watch mode
    */
 
-  _watch(hasteMap, hasteFS, moduleMap) {
+  _watch(hasteMap) {
     if (!this._options.watch) {
       return Promise.resolve();
     } // In watch mode, we'll only warn about module collisions and we'll retain
@@ -948,6 +951,7 @@ class HasteMap extends _events().default {
     let mustCopy = true;
 
     const createWatcher = root => {
+      // @ts-ignore: TODO how? "Cannot use 'new' with an expression whose type lacks a call or construct signature."
       const watcher = new Watcher(root, {
         dot: false,
         glob: extensions.map(extension => '**/*.' + extension),
@@ -1009,8 +1013,8 @@ class HasteMap extends _events().default {
                 event.type === type &&
                 event.filePath === filePath &&
                 ((!event.stat && !stat) ||
-                  (event.stat &&
-                    stat &&
+                  (!!event.stat &&
+                    !!stat &&
                     event.stat.mtime.getTime() === stat.mtime.getTime()))
             )
           ) {
@@ -1028,12 +1032,14 @@ class HasteMap extends _events().default {
             };
           }
 
-          const add = () =>
+          const add = () => {
             eventsQueue.push({
               filePath,
               stat,
               type
             });
+            return null;
+          };
 
           const relativeFilePath = fastPath.relative(rootDir, filePath);
           const fileMetadata = hasteMap.files.get(relativeFilePath); // If it's not an addition, delete the file and all its metadata
@@ -1082,8 +1088,8 @@ class HasteMap extends _events().default {
             );
             const fileMetadata = [
               '',
-              stat.mtime.getTime(),
-              stat.size,
+              stat ? stat.mtime.getTime() : -1,
+              stat ? stat.size : 0,
               0,
               [],
               null
@@ -1189,6 +1195,7 @@ class HasteMap extends _events().default {
   }
 
   end() {
+    // @ts-ignore: TODO TS cannot decide if `setInterval` and `clearInterval` comes from NodeJS or the DOM
     clearInterval(this._changeInterval);
 
     if (!this._watchers.length) {
@@ -1252,7 +1259,9 @@ class HasteMap extends _events().default {
   }
 }
 
-const copy = object => Object.assign(Object.create(null), object);
+function copy(object) {
+  return Object.assign(Object.create(null), object);
+}
 
 function copyMap(input) {
   return new Map(input);
diff --git c/packages/jest-haste-map/build/lib/WatchmanWatcher.js w/packages/jest-haste-map/build/lib/WatchmanWatcher.js
index 4d5a5d290..f6d5eed37 100644
--- c/packages/jest-haste-map/build/lib/WatchmanWatcher.js
+++ w/packages/jest-haste-map/build/lib/WatchmanWatcher.js
@@ -35,10 +35,10 @@ function _assert() {
   return data;
 }
 
-function _common() {
-  const data = _interopRequireDefault(require('sane/src/common'));
+function _events() {
+  const data = require('events');
 
-  _common = function _common() {
+  _events = function _events() {
     return data;
   };
 
@@ -55,10 +55,10 @@ function _fbWatchman() {
   return data;
 }
 
-function _events() {
-  const data = require('events');
+function _common() {
+  const data = _interopRequireDefault(require('sane/src/common'));
 
-  _events = function _events() {
+  _common = function _common() {
     return data;
   };
 
diff --git c/packages/jest-haste-map/build/lib/dependencyExtractor.js w/packages/jest-haste-map/build/lib/dependencyExtractor.js
index 4e23b3ded..be0c9aa07 100644
--- c/packages/jest-haste-map/build/lib/dependencyExtractor.js
+++ w/packages/jest-haste-map/build/lib/dependencyExtractor.js
@@ -16,8 +16,6 @@ function _interopRequireDefault(obj) {
  *
  * This source code is licensed under the MIT license found in the
  * LICENSE file in the root directory of this source tree.
- *
- *
  */
 // Negative look behind is only supported in Node 9+
 const NOT_A_DOT = (0, _isRegExpSupported.default)('(?<!\\.\\s*)')
@@ -87,7 +85,7 @@ const JEST_EXTENSIONS_RE = createRegExp(
 function extract(code) {
   const dependencies = new Set();
 
-  const addDependency = (match, q, dep) => {
+  const addDependency = (match, _, dep) => {
     dependencies.add(dep);
     return match;
   };
diff --git c/packages/jest-haste-map/build/lib/fast_path.js w/packages/jest-haste-map/build/lib/fast_path.js
index 3dc51bf02..31b5bbb7d 100644
--- c/packages/jest-haste-map/build/lib/fast_path.js
+++ w/packages/jest-haste-map/build/lib/fast_path.js
@@ -25,8 +25,6 @@ function _interopRequireDefault(obj) {
  *
  * This source code is licensed under the MIT license found in the
  * LICENSE file in the root directory of this source tree.
- *
- *
  */
 // rootDir and filename must be absolute paths (resolved)
 function relative(rootDir, filename) {
diff --git c/packages/jest-haste-map/build/lib/getPlatformExtension.js w/packages/jest-haste-map/build/lib/getPlatformExtension.js
index 9789a218b..6b9e564f9 100644
--- c/packages/jest-haste-map/build/lib/getPlatformExtension.js
+++ w/packages/jest-haste-map/build/lib/getPlatformExtension.js
@@ -10,15 +10,8 @@ exports.default = getPlatformExtension;
  *
  * This source code is licensed under the MIT license found in the
  * LICENSE file in the root directory of this source tree.
- *
- *
  */
-const SUPPORTED_PLATFORM_EXTS = {
-  android: true,
-  ios: true,
-  native: true,
-  web: true
-}; // Extract platform extension: index.ios.js -> ios
+const SUPPORTED_PLATFORM_EXTS = new Set(['android', 'ios', 'native', 'web']); // Extract platform extension: index.ios.js -> ios
 
 function getPlatformExtension(file, platforms) {
   const last = file.lastIndexOf('.');
@@ -34,5 +27,5 @@ function getPlatformExtension(file, platforms) {
     return platform;
   }
 
-  return SUPPORTED_PLATFORM_EXTS[platform] ? platform : null;
+  return SUPPORTED_PLATFORM_EXTS.has(platform) ? platform : null;
 }
diff --git c/packages/jest-haste-map/build/lib/isRegExpSupported.js w/packages/jest-haste-map/build/lib/isRegExpSupported.js
index 22568c94f..44de4e119 100644
--- c/packages/jest-haste-map/build/lib/isRegExpSupported.js
+++ w/packages/jest-haste-map/build/lib/isRegExpSupported.js
@@ -10,8 +10,6 @@ exports.default = isRegExpSupported;
  *
  * This source code is licensed under the MIT license found in the
  * LICENSE file in the root directory of this source tree.
- *
- *
  */
 function isRegExpSupported(value) {
   try {
diff --git c/packages/jest-haste-map/build/lib/normalizePathSep.js w/packages/jest-haste-map/build/lib/normalizePathSep.js
index c3723344b..23c7782bd 100644
--- c/packages/jest-haste-map/build/lib/normalizePathSep.js
+++ w/packages/jest-haste-map/build/lib/normalizePathSep.js
@@ -5,22 +5,32 @@ Object.defineProperty(exports, '__esModule', {
 });
 exports.default = void 0;
 
+function _path() {
+  const data = _interopRequireDefault(require('path'));
+
+  _path = function _path() {
+    return data;
+  };
+
+  return data;
+}
+
+function _interopRequireDefault(obj) {
+  return obj && obj.__esModule ? obj : {default: obj};
+}
+
 /**
  * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
  *
  * This source code is licensed under the MIT license found in the
  * LICENSE file in the root directory of this source tree.
- *
- *
  */
-const path = require('path');
-
 let normalizePathSep;
 
-if (path.sep === '/') {
+if (_path().default.sep === '/') {
   normalizePathSep = filePath => filePath;
 } else {
-  normalizePathSep = filePath => filePath.replace(/\//g, path.sep);
+  normalizePathSep = filePath => filePath.replace(/\//g, _path().default.sep);
 }
 
 var _default = normalizePathSep;
diff --git c/packages/jest-haste-map/build/worker.js w/packages/jest-haste-map/build/worker.js
index 5807a4602..1996d4a8e 100644
--- c/packages/jest-haste-map/build/worker.js
+++ w/packages/jest-haste-map/build/worker.js
@@ -130,8 +130,7 @@ function _worker() {
         throw new Error('jest-haste-map: hasteImplModulePath changed');
       }
 
-      hasteImplModulePath = data.hasteImplModulePath; // $FlowFixMe: dynamic require
-
+      hasteImplModulePath = data.hasteImplModulePath;
       hasteImpl = require(hasteImplModulePath);
     }
 
@@ -178,7 +177,7 @@ function _worker() {
       if (computeDependencies) {
         const content = getContent();
         dependencies = Array.from(
-          data.dependencyExtractor // $FlowFixMe
+          data.dependencyExtractor
             ? require(data.dependencyExtractor).extract(
                 content,
                 filePath,

Test plan

Green CI

SIZE: 2;
VISITED: 3;
DEPENDENCIES: 4;
SHA1: 5;
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is missing in the flow types. It's awesome to have them properly co-located so we discover that stuff


import {HType} from './types';

const constants: HType = {
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Explicitly typing this ensure the type remains narrow rather than expanded to number

packages/jest-haste-map/src/ModuleMap.ts Outdated Show resolved Hide resolved
packages/jest-haste-map/src/crawlers/node.ts Outdated Show resolved Hide resolved
packages/jest-haste-map/src/index.ts Outdated Show resolved Hide resolved
packages/jest-haste-map/src/worker.ts Show resolved Hide resolved
@SimenB
Copy link
Member Author

SimenB commented Feb 11, 2019

@thymikee Feel free to look into the remaining type errors if you've got some time 🙂

map: $Call<typeof Array.from, $Call<$PropertyType<ModuleMapData, 'entries'>>>,
mocks: $Call<typeof Array.from, $Call<$PropertyType<MockData, 'entries'>>>,
rootDir: string,
duplicates: [string, ValueType<DuplicatesIndex>];
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

duplicates has this signature: Map<string, Map<string, Map<string, number>>>. We'd need to call Array.from recursively if we wanted to properly toJSON and fromJSON it. Is this even working properly now? To me it looks like we loose all duplicates data on every serialization

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree it seems like this isn't working properly. Should probably investigate

@SimenB SimenB changed the title [WIP] chore: migrate jest-haste-map to TypeScript chore: migrate jest-haste-map to TypeScript Feb 11, 2019
supportsNativePlatform: boolean | null,
type: HTypeValue | null,
): string | null {
if (type == null) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if the types are right, then

Suggested change
if (type == null) {
if (type === null) {

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We only do getModule (outside of unit tests) right below: return this.getModule(name, platform, null, H.PACKAGE);

So I wonder if it's never null either? May be that FB uses it internally though, who knows

@@ -66,13 +62,13 @@ export default class ModuleMap {

getPackage(
name: string,
platform: ?string,
supportsNativePlatform: ?boolean,
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

not sure why we pass null to getModule instead of using this argument

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yea, just wanted to comment about it. maybe we should start passing it?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IDK. @rubennorte?

@@ -996,6 +1002,7 @@ class HasteMap extends EventEmitter {
}

end(): Promise<void> {
// @ts-ignore: TODO TS cannot decide if `setInterval` and `clearInterval` comes from NodeJS or the DOM
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is super weird - setInterval returns NodeJS.Timeout, but clearInterval expects number. Not sure what's up?

let dependencies: WorkerMetadata['dependencies'];
let id: WorkerMetadata['id'];
let module: WorkerMetadata['module'];
let sha1: WorkerMetadata['sha1'];
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

in theory not needed, but it was way easier to track down where the assignment was wrong that it telling med the return at the bottom was wrong

@SimenB SimenB merged commit 4b07a67 into jestjs:master Feb 12, 2019
@SimenB SimenB deleted the ts-haste-map branch February 12, 2019 00:40
@jeysal
Copy link
Contributor

jeysal commented Feb 12, 2019

Good job! And sorry I didn't have time to do it yesterday :|

@SimenB
Copy link
Member Author

SimenB commented Feb 12, 2019

No worries 🙂 Probably a bunch of things that can be improved if you feel up for it!

@github-actions
Copy link

This pull request has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.
Please note this issue tracker is not a help forum. We recommend using StackOverflow or our discord channel for questions.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators May 12, 2021
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

5 participants