UNPKG

15.3 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3var crypto_1 = require("crypto");
4var path_1 = require("path");
5var fs_extra_1 = require("fs-extra");
6var osName = require("os-name");
7var Constants = require("./constants");
8var errors_1 = require("./errors");
9var logger_1 = require("../logger/logger");
10var camel_case_regexp_1 = require("./helpers/camel-case-regexp");
11var camel_case_upper_regexp_1 = require("./helpers/camel-case-upper-regexp");
12var non_word_regexp_1 = require("./helpers/non-word-regexp");
13var _context;
14var _deepLinkConfigEntriesMap;
15var cachedAppScriptsPackageJson;
16function getAppScriptsPackageJson() {
17 if (!cachedAppScriptsPackageJson) {
18 try {
19 cachedAppScriptsPackageJson = fs_extra_1.readJsonSync(path_1.join(__dirname, '..', '..', 'package.json'));
20 }
21 catch (e) { }
22 }
23 return cachedAppScriptsPackageJson;
24}
25exports.getAppScriptsPackageJson = getAppScriptsPackageJson;
26function getAppScriptsVersion() {
27 var appScriptsPackageJson = getAppScriptsPackageJson();
28 return (appScriptsPackageJson && appScriptsPackageJson.version) ? appScriptsPackageJson.version : '';
29}
30exports.getAppScriptsVersion = getAppScriptsVersion;
31function getUserPackageJson(userRootDir) {
32 try {
33 return fs_extra_1.readJsonSync(path_1.join(userRootDir, 'package.json'));
34 }
35 catch (e) { }
36 return null;
37}
38function getSystemText(userRootDir) {
39 var systemData = getSystemData(userRootDir);
40 var d = [];
41 d.push("Ionic Framework: " + systemData.ionicFramework);
42 if (systemData.ionicNative) {
43 d.push("Ionic Native: " + systemData.ionicNative);
44 }
45 d.push("Ionic App Scripts: " + systemData.ionicAppScripts);
46 d.push("Angular Core: " + systemData.angularCore);
47 d.push("Angular Compiler CLI: " + systemData.angularCompilerCli);
48 d.push("Node: " + systemData.node);
49 d.push("OS Platform: " + systemData.osName);
50 return d;
51}
52exports.getSystemText = getSystemText;
53function getSystemData(userRootDir) {
54 var d = {
55 ionicAppScripts: getAppScriptsVersion(),
56 ionicFramework: '',
57 ionicNative: '',
58 angularCore: '',
59 angularCompilerCli: '',
60 node: process.version.replace('v', ''),
61 osName: osName()
62 };
63 try {
64 var userPackageJson = getUserPackageJson(userRootDir);
65 if (userPackageJson) {
66 var userDependencies = userPackageJson.dependencies;
67 if (userDependencies) {
68 d.ionicFramework = userDependencies['ionic-angular'];
69 d.ionicNative = userDependencies['ionic-native'];
70 d.angularCore = userDependencies['@angular/core'];
71 d.angularCompilerCli = userDependencies['@angular/compiler-cli'];
72 }
73 }
74 }
75 catch (e) { }
76 return d;
77}
78exports.getSystemData = getSystemData;
79function splitLineBreaks(sourceText) {
80 if (!sourceText)
81 return [];
82 sourceText = sourceText.replace(/\\r/g, '\n');
83 return sourceText.split('\n');
84}
85exports.splitLineBreaks = splitLineBreaks;
86exports.objectAssign = (Object.assign) ? Object.assign : function (target, source) {
87 var output = Object(target);
88 for (var index = 1; index < arguments.length; index++) {
89 source = arguments[index];
90 if (source !== undefined && source !== null) {
91 for (var key in source) {
92 if (source.hasOwnProperty(key)) {
93 output[key] = source[key];
94 }
95 }
96 }
97 }
98 return output;
99};
100function titleCase(str) {
101 return str.charAt(0).toUpperCase() + str.substr(1);
102}
103exports.titleCase = titleCase;
104function writeFileAsync(filePath, content) {
105 return new Promise(function (resolve, reject) {
106 fs_extra_1.writeFile(filePath, content, function (err) {
107 if (err) {
108 return reject(err);
109 }
110 return resolve();
111 });
112 });
113}
114exports.writeFileAsync = writeFileAsync;
115function readFileAsync(filePath) {
116 return new Promise(function (resolve, reject) {
117 fs_extra_1.readFile(filePath, 'utf-8', function (err, buffer) {
118 if (err) {
119 return reject(err);
120 }
121 return resolve(buffer);
122 });
123 });
124}
125exports.readFileAsync = readFileAsync;
126function readJsonAsync(filePath) {
127 return new Promise(function (resolve, reject) {
128 fs_extra_1.readJson(filePath, {}, function (err, object) {
129 if (err) {
130 return reject(err);
131 }
132 return resolve(object);
133 });
134 });
135}
136exports.readJsonAsync = readJsonAsync;
137function readAndCacheFile(filePath, purge) {
138 if (purge === void 0) { purge = false; }
139 var file = _context.fileCache.get(filePath);
140 if (file && !purge) {
141 return Promise.resolve(file.content);
142 }
143 return readFileAsync(filePath).then(function (fileContent) {
144 _context.fileCache.set(filePath, { path: filePath, content: fileContent });
145 return fileContent;
146 });
147}
148exports.readAndCacheFile = readAndCacheFile;
149function unlinkAsync(filePath) {
150 var filePaths;
151 if (typeof filePath === 'string') {
152 filePaths = [filePath];
153 }
154 else if (Array.isArray(filePath)) {
155 filePaths = filePath;
156 }
157 else {
158 return Promise.reject('unlinkAsync, invalid filePath type');
159 }
160 var promises = filePaths.map(function (filePath) {
161 return new Promise(function (resolve, reject) {
162 fs_extra_1.unlink(filePath, function (err) {
163 if (err) {
164 return reject(err);
165 }
166 return resolve();
167 });
168 });
169 });
170 return Promise.all(promises);
171}
172exports.unlinkAsync = unlinkAsync;
173function rimRafAsync(directoryPath) {
174 return new Promise(function (resolve, reject) {
175 fs_extra_1.remove(directoryPath, function (err) {
176 if (err) {
177 return reject(err);
178 }
179 return resolve();
180 });
181 });
182}
183exports.rimRafAsync = rimRafAsync;
184function copyFileAsync(srcPath, destPath) {
185 return new Promise(function (resolve, reject) {
186 var writeStream = fs_extra_1.createWriteStream(destPath);
187 writeStream.on('error', function (err) {
188 reject(err);
189 });
190 writeStream.on('close', function () {
191 resolve();
192 });
193 fs_extra_1.createReadStream(srcPath).pipe(writeStream);
194 });
195}
196exports.copyFileAsync = copyFileAsync;
197function mkDirpAsync(directoryPath) {
198 return new Promise(function (resolve, reject) {
199 fs_extra_1.ensureDir(directoryPath, function (err) {
200 if (err) {
201 return reject(err);
202 }
203 return resolve();
204 });
205 });
206}
207exports.mkDirpAsync = mkDirpAsync;
208function readDirAsync(pathToDir) {
209 return new Promise(function (resolve, reject) {
210 fs_extra_1.readdir(pathToDir, function (err, fileNames) {
211 if (err) {
212 return reject(err);
213 }
214 resolve(fileNames);
215 });
216 });
217}
218exports.readDirAsync = readDirAsync;
219function setContext(context) {
220 _context = context;
221}
222exports.setContext = setContext;
223function getContext() {
224 return _context;
225}
226exports.getContext = getContext;
227function setParsedDeepLinkConfig(map) {
228 _deepLinkConfigEntriesMap = map;
229}
230exports.setParsedDeepLinkConfig = setParsedDeepLinkConfig;
231function getParsedDeepLinkConfig() {
232 return _deepLinkConfigEntriesMap;
233}
234exports.getParsedDeepLinkConfig = getParsedDeepLinkConfig;
235function transformSrcPathToTmpPath(originalPath, context) {
236 return originalPath.replace(context.srcDir, context.tmpDir);
237}
238exports.transformSrcPathToTmpPath = transformSrcPathToTmpPath;
239function transformTmpPathToSrcPath(originalPath, context) {
240 return originalPath.replace(context.tmpDir, context.srcDir);
241}
242exports.transformTmpPathToSrcPath = transformTmpPathToSrcPath;
243function changeExtension(filePath, newExtension) {
244 var dir = path_1.dirname(filePath);
245 var extension = path_1.extname(filePath);
246 var extensionlessfileName = path_1.basename(filePath, extension);
247 var newFileName = extensionlessfileName + newExtension;
248 return path_1.join(dir, newFileName);
249}
250exports.changeExtension = changeExtension;
251function escapeHtml(unsafe) {
252 return unsafe
253 .replace(/&/g, '&amp;')
254 .replace(/</g, '&lt;')
255 .replace(/>/g, '&gt;')
256 .replace(/"/g, '&quot;')
257 .replace(/'/g, '&#039;');
258}
259exports.escapeHtml = escapeHtml;
260function escapeStringForRegex(input) {
261 return input.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
262}
263exports.escapeStringForRegex = escapeStringForRegex;
264function rangeReplace(source, startIndex, endIndex, newContent) {
265 return source.substring(0, startIndex) + newContent + source.substring(endIndex);
266}
267exports.rangeReplace = rangeReplace;
268function stringSplice(source, startIndex, numToDelete, newContent) {
269 return source.slice(0, startIndex) + newContent + source.slice(startIndex + Math.abs(numToDelete));
270}
271exports.stringSplice = stringSplice;
272function toUnixPath(filePath) {
273 return filePath.replace(/\\/g, '/');
274}
275exports.toUnixPath = toUnixPath;
276function generateRandomHexString(numCharacters) {
277 return crypto_1.randomBytes(Math.ceil(numCharacters / 2)).toString('hex').slice(0, numCharacters);
278}
279exports.generateRandomHexString = generateRandomHexString;
280function getStringPropertyValue(propertyName) {
281 var result = process.env[propertyName];
282 return result;
283}
284exports.getStringPropertyValue = getStringPropertyValue;
285function getIntPropertyValue(propertyName) {
286 var result = process.env[propertyName];
287 return parseInt(result, 0);
288}
289exports.getIntPropertyValue = getIntPropertyValue;
290function getBooleanPropertyValue(propertyName) {
291 var result = process.env[propertyName];
292 return result === 'true';
293}
294exports.getBooleanPropertyValue = getBooleanPropertyValue;
295function convertFilePathToNgFactoryPath(filePath) {
296 var directory = path_1.dirname(filePath);
297 var extension = path_1.extname(filePath);
298 var extensionlessFileName = path_1.basename(filePath, extension);
299 var ngFactoryFileName = extensionlessFileName + '.ngfactory' + extension;
300 return path_1.join(directory, ngFactoryFileName);
301}
302exports.convertFilePathToNgFactoryPath = convertFilePathToNgFactoryPath;
303function printDependencyMap(map) {
304 map.forEach(function (dependencySet, filePath) {
305 logger_1.Logger.unformattedDebug('\n\n');
306 logger_1.Logger.unformattedDebug(filePath + " is imported by the following files:");
307 dependencySet.forEach(function (importeePath) {
308 logger_1.Logger.unformattedDebug(" " + importeePath);
309 });
310 });
311}
312exports.printDependencyMap = printDependencyMap;
313function webpackStatsToDependencyMap(context, stats) {
314 var statsObj = stats.toJson({
315 source: false,
316 timings: false,
317 version: false,
318 errorDetails: false,
319 chunks: false,
320 chunkModules: false
321 });
322 return processStatsImpl(statsObj);
323}
324exports.webpackStatsToDependencyMap = webpackStatsToDependencyMap;
325function processStatsImpl(webpackStats) {
326 var dependencyMap = new Map();
327 if (webpackStats && webpackStats.modules) {
328 webpackStats.modules.forEach(function (webpackModule) {
329 var moduleId = purgeWebpackPrefixFromPath(webpackModule.identifier);
330 var dependencySet = new Set();
331 webpackModule.reasons.forEach(function (webpackDependency) {
332 var depId = purgeWebpackPrefixFromPath(webpackDependency.moduleIdentifier);
333 dependencySet.add(depId);
334 });
335 dependencyMap.set(moduleId, dependencySet);
336 });
337 }
338 return dependencyMap;
339}
340exports.processStatsImpl = processStatsImpl;
341function purgeWebpackPrefixFromPath(filePath) {
342 return filePath.replace(process.env[Constants.ENV_WEBPACK_LOADER], '').replace('!', '');
343}
344exports.purgeWebpackPrefixFromPath = purgeWebpackPrefixFromPath;
345function replaceAll(input, toReplace, replacement) {
346 if (!replacement) {
347 replacement = '';
348 }
349 return input.split(toReplace).join(replacement);
350}
351exports.replaceAll = replaceAll;
352function ensureSuffix(input, suffix) {
353 if (!input.endsWith(suffix)) {
354 input += suffix;
355 }
356 return input;
357}
358exports.ensureSuffix = ensureSuffix;
359function removeSuffix(input, suffix) {
360 if (input.endsWith(suffix)) {
361 input = input.substring(0, input.length - suffix.length);
362 }
363 return input;
364}
365exports.removeSuffix = removeSuffix;
366function buildErrorToJson(buildError) {
367 return {
368 message: buildError.message,
369 name: buildError.name,
370 stack: buildError.stack,
371 hasBeenLogged: buildError.hasBeenLogged,
372 isFatal: buildError.isFatal
373 };
374}
375exports.buildErrorToJson = buildErrorToJson;
376function jsonToBuildError(nonTypedBuildError) {
377 var error = new errors_1.BuildError(new Error(nonTypedBuildError.message));
378 error.name = nonTypedBuildError.name;
379 error.stack = nonTypedBuildError.stack;
380 error.hasBeenLogged = nonTypedBuildError.hasBeenLogged;
381 error.isFatal = nonTypedBuildError.isFatal;
382 return error;
383}
384exports.jsonToBuildError = jsonToBuildError;
385function upperCaseFirst(input) {
386 if (input.length > 1) {
387 return input.charAt(0).toUpperCase() + input.substr(1);
388 }
389 return input.toUpperCase();
390}
391exports.upperCaseFirst = upperCaseFirst;
392function sentenceCase(input) {
393 var noCase = removeCaseFromString(input);
394 return upperCaseFirst(noCase);
395}
396exports.sentenceCase = sentenceCase;
397function snakeCase(input) {
398 return removeCaseFromString(input, '_');
399}
400exports.snakeCase = snakeCase;
401function constantCase(input) {
402 return snakeCase(input).toUpperCase();
403}
404exports.constantCase = constantCase;
405function camelCase(input) {
406 input = removeCaseFromString(input);
407 input = input.replace(/ (?=\d)/g, '_');
408 return input.replace(/ (.)/g, function (m, arg) {
409 return arg.toUpperCase();
410 });
411}
412exports.camelCase = camelCase;
413function paramCase(input) {
414 return removeCaseFromString(input, '-');
415}
416exports.paramCase = paramCase;
417function pascalCase(input) {
418 return upperCaseFirst(camelCase(input));
419}
420exports.pascalCase = pascalCase;
421function removeCaseFromString(input, inReplacement) {
422 var replacement = inReplacement && inReplacement.length > 0 ? inReplacement : ' ';
423 function replace(match, index, value) {
424 if (index === 0 || index === (value.length - match.length)) {
425 return '';
426 }
427 return replacement;
428 }
429 var modified = input
430 .replace(camel_case_regexp_1.CAMEL_CASE_REGEXP, '$1 $2')
431 .replace(camel_case_upper_regexp_1.CAMEL_CASE_UPPER_REGEXP, '$1 $2')
432 .replace(non_word_regexp_1.NON_WORD_REGEXP, replace);
433 return modified.toLowerCase();
434}
435exports.removeCaseFromString = removeCaseFromString;
436function semverStringToObject(semverString) {
437 var versionArray = semverString.split('.');
438 return {
439 major: parseInt(versionArray[0], 10),
440 minor: parseInt(versionArray[1], 10),
441 patch: parseInt(versionArray[2], 10)
442 };
443}
444exports.semverStringToObject = semverStringToObject;