4 * Copyright 2018 Palantir Technologies, Inc.
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
10 * http://www.apache.org/licenses/LICENSE-2.0
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
18 Object.defineProperty(exports, "__esModule", { value: true });
19 var fs = require("fs");
20 var resolve = require("resolve");
21 var ts = require("typescript");
23 * Enforces the invariant that the input is an array.
25 function arrayify(arg) {
26 if (Array.isArray(arg)) {
29 else if (arg != undefined) {
36 exports.arrayify = arrayify;
38 * @deprecated (no longer used)
39 * Enforces the invariant that the input is an object.
41 function objectify(arg) {
42 if (typeof arg === "object" && arg != undefined) {
49 exports.objectify = objectify;
50 function hasOwnProperty(arg, key) {
51 return Object.prototype.hasOwnProperty.call(arg, key);
53 exports.hasOwnProperty = hasOwnProperty;
55 * Replace hyphens in a rule name by upper-casing the letter after them.
56 * E.g. "foo-bar" -> "fooBar"
58 function camelize(stringWithHyphens) {
59 return stringWithHyphens.replace(/-(.)/g, function (_, nextLetter) {
60 return nextLetter.toUpperCase();
63 exports.camelize = camelize;
64 function isUpperCase(str) {
65 return str === str.toUpperCase();
67 exports.isUpperCase = isUpperCase;
68 function isLowerCase(str) {
69 return str === str.toLowerCase();
71 exports.isLowerCase = isLowerCase;
73 * Removes leading indents from a template string without removing all leading whitespace
75 function dedent(strings) {
77 for (var _i = 1; _i < arguments.length; _i++) {
78 values[_i - 1] = arguments[_i];
80 var fullString = strings.reduce(function (accumulator, str, i) { return "" + accumulator + values[i - 1] + str; });
81 // match all leading spaces/tabs at the start of each line
82 var match = fullString.match(/^[ \t]*(?=\S)/gm);
84 // e.g. if the string is empty or all whitespace.
87 // find the smallest indent, we don't want to remove all leading whitespace
88 var indent = Math.min.apply(Math, match.map(function (el) { return el.length; }));
89 var regexp = new RegExp("^[ \\t]{" + indent + "}", "gm");
90 fullString = indent > 0 ? fullString.replace(regexp, "") : fullString;
93 exports.dedent = dedent;
95 * Strip comments from file content.
97 function stripComments(content) {
99 * First capturing group matches double quoted string
100 * Second matches single quotes string
101 * Third matches block comments
102 * Fourth matches line comments
104 var regexp = /("(?:[^\\\"]*(?:\\.)?)*")|('(?:[^\\\']*(?:\\.)?)*')|(\/\*(?:\r?\n|.)*?\*\/)|(\/{2,}.*?(?:(?:\r?\n)|$))/g;
105 var result = content.replace(regexp, function (match, _m1, _m2, m3, m4) {
106 // Only one of m1, m2, m3, m4 matches
107 if (m3 !== undefined) {
108 // A block comment. Replace with nothing
111 else if (m4 !== undefined) {
112 // A line comment. If it ends in \r?\n then keep it.
113 var length = m4.length;
114 if (length > 2 && m4[length - 1] === "\n") {
115 return m4[length - 2] === "\r" ? "\r\n" : "\n";
128 exports.stripComments = stripComments;
130 * Escapes all special characters in RegExp pattern to avoid broken regular expressions and ensure proper matches
132 function escapeRegExp(re) {
133 return re.replace(/[.+*?|^$[\]{}()\\]/g, "\\$&");
135 exports.escapeRegExp = escapeRegExp;
136 function arraysAreEqual(a, b, eq) {
140 a.length === b.length &&
141 a.every(function (x, idx) { return eq(x, b[idx]); })));
143 exports.arraysAreEqual = arraysAreEqual;
144 /** Returns the first non-`undefined` result. */
145 function find(inputs, getResult) {
146 for (var _i = 0, inputs_1 = inputs; _i < inputs_1.length; _i++) {
147 var element = inputs_1[_i];
148 var result = getResult(element);
149 if (result !== undefined) {
156 /** Returns an array that is the concatenation of all output arrays. */
157 function flatMap(inputs, getOutputs) {
159 for (var i = 0; i < inputs.length; i++) {
160 out.push.apply(out, getOutputs(inputs[i], i));
164 exports.flatMap = flatMap;
165 /** Returns an array of all outputs that are not `undefined`. */
166 function mapDefined(inputs, getOutput) {
168 for (var _i = 0, inputs_2 = inputs; _i < inputs_2.length; _i++) {
169 var input = inputs_2[_i];
170 var output = getOutput(input);
171 if (output !== undefined) {
177 exports.mapDefined = mapDefined;
178 function readBufferWithDetectedEncoding(buffer) {
179 switch (detectBufferEncoding(buffer)) {
181 return buffer.toString();
183 return buffer.toString("utf-8", 2);
185 return buffer.toString("utf16le", 2);
187 // Round down to nearest multiple of 2.
188 var len = buffer.length & ~1; // tslint:disable-line no-bitwise
189 // Flip all byte pairs, then read as little-endian.
190 for (var i = 0; i < len; i += 2) {
191 var temp = buffer[i];
192 buffer[i] = buffer[i + 1];
193 buffer[i + 1] = temp;
195 return buffer.toString("utf16le", 2);
198 exports.readBufferWithDetectedEncoding = readBufferWithDetectedEncoding;
199 function detectBufferEncoding(buffer, length) {
200 if (length === void 0) { length = buffer.length; }
206 if (buffer[1] === 0xbb && length >= 3 && buffer[2] === 0xbf) {
211 if (buffer[1] === 0xff) {
216 if (buffer[1] === 0xfe) {
222 exports.detectBufferEncoding = detectBufferEncoding;
223 function trimSingleQuotes(str) {
224 return str.replace(/^'|'$/g, "");
226 exports.trimSingleQuotes = trimSingleQuotes;
227 // converts Windows normalized paths (with backwards slash `\`) to paths used by TypeScript (with forward slash `/`)
228 function denormalizeWinPath(path) {
229 return path.replace(/\\/g, "/");
231 exports.denormalizeWinPath = denormalizeWinPath;
232 function isPascalCased(name) {
233 return isUpperCase(name[0]) && !name.includes("_") && !name.includes("-");
235 exports.isPascalCased = isPascalCased;
236 function isCamelCased(name) {
237 return isLowerCase(name[0]) && !name.includes("_") && !name.includes("-");
239 exports.isCamelCased = isCamelCased;
240 function isSeparatorCased(name, disallowedSeparator) {
241 for (var i = 0; i < name.length; i++) {
242 var c = name.charAt(i);
243 if (c === disallowedSeparator || !isLowerCase(c)) {
249 function isKebabCased(name) {
250 return isSeparatorCased(name, "_");
252 exports.isKebabCased = isKebabCased;
253 function isSnakeCased(name) {
254 return isSeparatorCased(name, "-");
256 exports.isSnakeCased = isSnakeCased;
258 * Tries to resolve a package by name, optionally relative to a file path. If the
259 * file path is under a symlink, it tries to resolve the package under both the real path and under
262 function tryResolvePackage(packageName, relativeTo) {
263 var realRelativeToPath = relativeTo !== undefined ? fs.realpathSync(relativeTo) : undefined;
264 var resolvedPath = tryResolveSync(packageName, realRelativeToPath);
265 if (resolvedPath === undefined) {
266 resolvedPath = tryResolveSync(packageName, relativeTo);
270 exports.tryResolvePackage = tryResolvePackage;
272 * Calls `resolve.sync` and if it fails, it returns `undefined`
274 function tryResolveSync(packageName, relativeTo) {
276 return resolve.sync(packageName, { basedir: relativeTo });
283 * Gets the full indentation of the provided node
285 function getIndentation(node, sourceFile) {
286 var text = sourceFile.text.substr(node.pos, node.getStart() - node.pos);
287 var matches = text.match(/([ \t]*)$/);
288 return matches !== null ? matches[1] : "";
290 exports.getIndentation = getIndentation;
292 * Creates x new lines with a proper indentation at the last one based on the provided node
294 function newLineWithIndentation(node, sourceFile, linesCount) {
295 if (linesCount === void 0) { linesCount = 1; }
296 var maybeCarriageReturn = sourceFile.text[sourceFile.getLineEndOfPosition(node.pos) - 1] === "\r" ? "\r" : "";
297 var indentation = getIndentation(node, sourceFile);
298 return "" + (maybeCarriageReturn + "\n").repeat(linesCount) + indentation;
300 exports.newLineWithIndentation = newLineWithIndentation;
302 * @deprecated Copied from tsutils 2.27.2. This will be removed once TSLint requires tsutils > 3.0.
304 function isFunctionScopeBoundary(node) {
306 case ts.SyntaxKind.FunctionExpression:
307 case ts.SyntaxKind.ArrowFunction:
308 case ts.SyntaxKind.Constructor:
309 case ts.SyntaxKind.ModuleDeclaration:
310 case ts.SyntaxKind.ClassDeclaration:
311 case ts.SyntaxKind.ClassExpression:
312 case ts.SyntaxKind.EnumDeclaration:
313 case ts.SyntaxKind.MethodDeclaration:
314 case ts.SyntaxKind.FunctionDeclaration:
315 case ts.SyntaxKind.GetAccessor:
316 case ts.SyntaxKind.SetAccessor:
317 case ts.SyntaxKind.InterfaceDeclaration:
318 case ts.SyntaxKind.TypeAliasDeclaration:
319 case ts.SyntaxKind.MethodSignature:
320 case ts.SyntaxKind.CallSignature:
321 case ts.SyntaxKind.ConstructSignature:
322 case ts.SyntaxKind.ConstructorType:
323 case ts.SyntaxKind.FunctionType:
324 case ts.SyntaxKind.MappedType:
325 case ts.SyntaxKind.ConditionalType:
327 case ts.SyntaxKind.SourceFile:
328 // if SourceFile is no module, it contributes to the global scope and is therefore no scope boundary
329 // tslint:disable:no-angle-bracket-type-assertion Code copied as from tsutils as is.
330 return ts.isExternalModule(node);
331 // tslint:enable:no-angle-bracket-type-assertopn
336 exports.isFunctionScopeBoundary = isFunctionScopeBoundary;