UNPKG

2.32 kBJavaScriptView Raw
1/**
2 * Copyright (c) Facebook, Inc. and its affiliates.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 */
7
8var flowRemoveTypes = require('./index');
9var pirates = require('pirates');
10
11// Supported options:
12//
13// - all: Transform all files, not just those with a @flow comment.
14// - includes: A Regexp/String to determine which files should be transformed.
15// (alias: include)
16// - excludes: A Regexp/String to determine which files should not be
17// transformed, defaults to ignoring /node_modules/, provide null
18// to exclude nothing. (alias: exclude)
19var options;
20module.exports = function setOptions(newOptions) {
21 options = newOptions;
22};
23
24var jsLoader = require.extensions['.js'];
25var exts = ['.js', '.mjs', '.cjs', '.jsx', '.flow', '.es6'];
26
27var revert = pirates.addHook(
28 function hook(code, filename) {
29 try {
30 return flowRemoveTypes(code, options).toString();
31 } catch (e) {
32 e.message = filename + ': ' + e.message;
33 throw e;
34 }
35 },
36 {exts: exts, matcher: shouldTransform}
37);
38
39function shouldTransform(filename) {
40 var includes = options && regexpPattern(options.includes || options.include);
41 var excludes =
42 options && 'excludes' in options
43 ? regexpPattern(options.excludes)
44 : options && 'exclude' in options
45 ? regexpPattern(options.exclude)
46 : /\/node_modules\//;
47 return (
48 (!includes || includes.test(filename)) &&
49 !(excludes && excludes.test(filename))
50 );
51}
52
53// Given a null | string | RegExp | any, returns null | Regexp or throws a
54// more helpful error.
55function regexpPattern(pattern) {
56 if (!pattern) {
57 return pattern;
58 }
59 // A very simplified glob transform which allows passing legible strings like
60 // "myPath/*.js" instead of a harder to read RegExp like /\/myPath\/.*\.js/.
61 if (typeof pattern === 'string') {
62 pattern = pattern.replace(/\./g, '\\.').replace(/\*/g, '.*');
63 if (pattern[0] !== '/') {
64 pattern = '/' + pattern;
65 }
66 return new RegExp(pattern);
67 }
68 if (typeof pattern.test === 'function') {
69 return pattern;
70 }
71 throw new Error(
72 'flow-remove-types: ' +
73 'includes and excludes must be RegExp or path strings. Got: ' +
74 pattern
75 );
76}