123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. "use strict";
  2. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  3. return new (P || (P = Promise))(function (resolve, reject) {
  4. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  5. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  6. function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
  7. step((generator = generator.apply(thisArg, _arguments || [])).next());
  8. });
  9. };
  10. var __generator = (this && this.__generator) || function (thisArg, body) {
  11. var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
  12. return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
  13. function verb(n) { return function (v) { return step([n, v]); }; }
  14. function step(op) {
  15. if (f) throw new TypeError("Generator is already executing.");
  16. while (_) try {
  17. if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t;
  18. if (y = 0, t) op = [0, t.value];
  19. switch (op[0]) {
  20. case 0: case 1: t = op; break;
  21. case 4: _.label++; return { value: op[1], done: false };
  22. case 5: _.label++; y = op[1]; op = [0]; continue;
  23. case 7: op = _.ops.pop(); _.trys.pop(); continue;
  24. default:
  25. if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
  26. if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
  27. if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
  28. if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
  29. if (t[2]) _.ops.pop();
  30. _.trys.pop(); continue;
  31. }
  32. op = body.call(thisArg, _);
  33. } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
  34. if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
  35. }
  36. };
  37. Object.defineProperty(exports, "__esModule", { value: true });
  38. var child_process_1 = require("child_process");
  39. var events_1 = require("events");
  40. var fs_1 = require("fs");
  41. var path = require("path");
  42. var ts = require("typescript");
  43. var compiler_host_factory_1 = require("./aot/compiler-host-factory");
  44. var bundle_1 = require("./bundle");
  45. var util_1 = require("./deep-linking/util");
  46. var logger_1 = require("./logger/logger");
  47. var logger_diagnostics_1 = require("./logger/logger-diagnostics");
  48. var logger_typescript_1 = require("./logger/logger-typescript");
  49. var template_1 = require("./template");
  50. var Constants = require("./util/constants");
  51. var errors_1 = require("./util/errors");
  52. var helpers_1 = require("./util/helpers");
  53. var interfaces_1 = require("./util/interfaces");
  54. function transpile(context) {
  55. var workerConfig = {
  56. configFile: getTsConfigPath(context),
  57. writeInMemory: true,
  58. sourceMaps: true,
  59. cache: true,
  60. inlineTemplate: context.inlineTemplates,
  61. useTransforms: true
  62. };
  63. var logger = new logger_1.Logger('transpile');
  64. return transpileWorker(context, workerConfig)
  65. .then(function () {
  66. context.transpileState = interfaces_1.BuildState.SuccessfulBuild;
  67. logger.finish();
  68. })
  69. .catch(function (err) {
  70. context.transpileState = interfaces_1.BuildState.RequiresBuild;
  71. throw logger.fail(err);
  72. });
  73. }
  74. exports.transpile = transpile;
  75. function transpileUpdate(changedFiles, context) {
  76. var workerConfig = {
  77. configFile: getTsConfigPath(context),
  78. writeInMemory: true,
  79. sourceMaps: true,
  80. cache: false,
  81. inlineTemplate: context.inlineTemplates,
  82. useTransforms: true
  83. };
  84. var logger = new logger_1.Logger('transpile update');
  85. var changedTypescriptFiles = changedFiles.filter(function (changedFile) { return changedFile.ext === '.ts'; });
  86. var promises = [];
  87. for (var _i = 0, changedTypescriptFiles_1 = changedTypescriptFiles; _i < changedTypescriptFiles_1.length; _i++) {
  88. var changedTypescriptFile = changedTypescriptFiles_1[_i];
  89. promises.push(transpileUpdateWorker(changedTypescriptFile.event, changedTypescriptFile.filePath, context, workerConfig));
  90. }
  91. return Promise.all(promises)
  92. .then(function () {
  93. context.transpileState = interfaces_1.BuildState.SuccessfulBuild;
  94. logger.finish();
  95. })
  96. .catch(function (err) {
  97. context.transpileState = interfaces_1.BuildState.RequiresBuild;
  98. throw logger.fail(err);
  99. });
  100. }
  101. exports.transpileUpdate = transpileUpdate;
  102. /**
  103. * The full TS build for all app files.
  104. */
  105. function transpileWorker(context, workerConfig) {
  106. // let's do this
  107. return new Promise(function (resolve, reject) {
  108. logger_diagnostics_1.clearDiagnostics(context, logger_diagnostics_1.DiagnosticsType.TypeScript);
  109. // get the tsconfig data
  110. var tsConfig = getTsConfig(context, workerConfig.configFile);
  111. if (workerConfig.sourceMaps === false) {
  112. // the worker config say, "hey, don't ever bother making a source map, because."
  113. tsConfig.options.sourceMap = false;
  114. }
  115. else {
  116. // build the ts source maps if the bundler is going to use source maps
  117. tsConfig.options.sourceMap = bundle_1.buildJsSourceMaps(context);
  118. }
  119. // collect up all the files we need to transpile, tsConfig itself does all this for us
  120. var tsFileNames = cleanFileNames(context, tsConfig.fileNames);
  121. // for dev builds let's not create d.ts files
  122. tsConfig.options.declaration = undefined;
  123. // let's start a new tsFiles object to cache all the transpiled files in
  124. var host = compiler_host_factory_1.getInMemoryCompilerHostInstance(tsConfig.options);
  125. if (workerConfig.useTransforms && helpers_1.getBooleanPropertyValue(Constants.ENV_PARSE_DEEPLINKS)) {
  126. // beforeArray.push(purgeDeepLinkDecoratorTSTransform());
  127. // beforeArray.push(getInjectDeepLinkConfigTypescriptTransform());
  128. // temporarily copy the files to a new location
  129. copyOriginalSourceFiles(context.fileCache);
  130. // okay, purge the deep link files NOT using a transform
  131. var deepLinkFiles = util_1.filterTypescriptFilesForDeepLinks(context.fileCache);
  132. deepLinkFiles.forEach(function (file) {
  133. file.content = util_1.purgeDeepLinkDecorator(file.content);
  134. });
  135. var file = context.fileCache.get(helpers_1.getStringPropertyValue(Constants.ENV_APP_NG_MODULE_PATH));
  136. var hasExisting = util_1.hasExistingDeepLinkConfig(file.path, file.content);
  137. if (!hasExisting) {
  138. var deepLinkString = util_1.convertDeepLinkConfigEntriesToString(helpers_1.getParsedDeepLinkConfig());
  139. file.content = util_1.getUpdatedAppNgModuleContentWithDeepLinkConfig(file.path, file.content, deepLinkString);
  140. }
  141. }
  142. var program = ts.createProgram(tsFileNames, tsConfig.options, host, cachedProgram);
  143. resetSourceFiles(context.fileCache);
  144. var beforeArray = [];
  145. program.emit(undefined, function (path, data, writeByteOrderMark, onError, sourceFiles) {
  146. if (workerConfig.writeInMemory) {
  147. writeTranspiledFilesCallback(context.fileCache, path, data, workerConfig.inlineTemplate);
  148. }
  149. });
  150. // cache the typescript program for later use
  151. cachedProgram = program;
  152. var tsDiagnostics = program.getSyntacticDiagnostics()
  153. .concat(program.getSemanticDiagnostics())
  154. .concat(program.getOptionsDiagnostics());
  155. var diagnostics = logger_typescript_1.runTypeScriptDiagnostics(context, tsDiagnostics);
  156. if (diagnostics.length) {
  157. // darn, we've got some things wrong, transpile failed :(
  158. logger_diagnostics_1.printDiagnostics(context, logger_diagnostics_1.DiagnosticsType.TypeScript, diagnostics, true, true);
  159. reject(new errors_1.BuildError('Failed to transpile program'));
  160. }
  161. else {
  162. // transpile success :)
  163. resolve();
  164. }
  165. });
  166. }
  167. exports.transpileWorker = transpileWorker;
  168. function canRunTranspileUpdate(event, filePath, context) {
  169. if (event === 'change' && context.fileCache) {
  170. return context.fileCache.has(path.resolve(filePath));
  171. }
  172. return false;
  173. }
  174. exports.canRunTranspileUpdate = canRunTranspileUpdate;
  175. /**
  176. * Iterative build for one TS file. If it's not an existing file change, or
  177. * something errors out then it falls back to do the full build.
  178. */
  179. function transpileUpdateWorker(event, filePath, context, workerConfig) {
  180. try {
  181. logger_diagnostics_1.clearDiagnostics(context, logger_diagnostics_1.DiagnosticsType.TypeScript);
  182. filePath = path.normalize(path.resolve(filePath));
  183. // an existing ts file we already know about has changed
  184. // let's "TRY" to do a single module build for this one file
  185. if (!cachedTsConfig) {
  186. cachedTsConfig = getTsConfig(context, workerConfig.configFile);
  187. }
  188. // build the ts source maps if the bundler is going to use source maps
  189. cachedTsConfig.options.sourceMap = bundle_1.buildJsSourceMaps(context);
  190. var beforeArray = [];
  191. var transpileOptions = {
  192. compilerOptions: cachedTsConfig.options,
  193. fileName: filePath,
  194. reportDiagnostics: true,
  195. };
  196. // let's manually transpile just this one ts file
  197. // since it is an update, it's in memory already
  198. var sourceText = context.fileCache.get(filePath).content;
  199. var textToTranspile = workerConfig.useTransforms && helpers_1.getBooleanPropertyValue(Constants.ENV_PARSE_DEEPLINKS) ? transformSource(filePath, sourceText) : sourceText;
  200. // transpile this one module
  201. var transpileOutput = ts.transpileModule(textToTranspile, transpileOptions);
  202. var diagnostics = logger_typescript_1.runTypeScriptDiagnostics(context, transpileOutput.diagnostics);
  203. if (diagnostics.length) {
  204. logger_diagnostics_1.printDiagnostics(context, logger_diagnostics_1.DiagnosticsType.TypeScript, diagnostics, false, true);
  205. // darn, we've got some errors with this transpiling :(
  206. // but at least we reported the errors like really really fast, so there's that
  207. logger_1.Logger.debug("transpileUpdateWorker: transpileModule, diagnostics: " + diagnostics.length);
  208. throw new errors_1.BuildError("Failed to transpile file - " + filePath);
  209. }
  210. else {
  211. // convert the path to have a .js file extension for consistency
  212. var newPath = helpers_1.changeExtension(filePath, '.js');
  213. var sourceMapFile = { path: newPath + '.map', content: transpileOutput.sourceMapText };
  214. var jsContent = transpileOutput.outputText;
  215. if (workerConfig.inlineTemplate) {
  216. // use original path for template inlining
  217. jsContent = template_1.inlineTemplate(transpileOutput.outputText, filePath);
  218. }
  219. var jsFile = { path: newPath, content: jsContent };
  220. var tsFile = { path: filePath, content: sourceText };
  221. context.fileCache.set(sourceMapFile.path, sourceMapFile);
  222. context.fileCache.set(jsFile.path, jsFile);
  223. context.fileCache.set(tsFile.path, tsFile);
  224. }
  225. return Promise.resolve();
  226. }
  227. catch (ex) {
  228. return Promise.reject(ex);
  229. }
  230. }
  231. function transpileDiagnosticsOnly(context) {
  232. return new Promise(function (resolve) {
  233. workerEvent.once('DiagnosticsWorkerDone', function () {
  234. resolve();
  235. });
  236. runDiagnosticsWorker(context);
  237. });
  238. }
  239. exports.transpileDiagnosticsOnly = transpileDiagnosticsOnly;
  240. var workerEvent = new events_1.EventEmitter();
  241. var diagnosticsWorker = null;
  242. function runDiagnosticsWorker(context) {
  243. if (!diagnosticsWorker) {
  244. var workerModule = path.join(__dirname, 'transpile-worker.js');
  245. diagnosticsWorker = child_process_1.fork(workerModule, [], { env: { FORCE_COLOR: true } });
  246. logger_1.Logger.debug("diagnosticsWorker created, pid: " + diagnosticsWorker.pid);
  247. diagnosticsWorker.on('error', function (err) {
  248. logger_1.Logger.error("diagnosticsWorker error, pid: " + diagnosticsWorker.pid + ", error: " + err);
  249. workerEvent.emit('DiagnosticsWorkerDone');
  250. });
  251. diagnosticsWorker.on('exit', function (code) {
  252. logger_1.Logger.debug("diagnosticsWorker exited, pid: " + diagnosticsWorker.pid);
  253. diagnosticsWorker = null;
  254. });
  255. diagnosticsWorker.on('message', function (msg) {
  256. workerEvent.emit('DiagnosticsWorkerDone');
  257. });
  258. }
  259. var msg = {
  260. rootDir: context.rootDir,
  261. buildDir: context.buildDir,
  262. configFile: getTsConfigPath(context)
  263. };
  264. diagnosticsWorker.send(msg);
  265. }
  266. function cleanFileNames(context, fileNames) {
  267. // make sure we're not transpiling the prod when dev and stuff
  268. return fileNames;
  269. }
  270. function writeTranspiledFilesCallback(fileCache, sourcePath, data, shouldInlineTemplate) {
  271. sourcePath = path.normalize(path.resolve(sourcePath));
  272. if (sourcePath.endsWith('.js')) {
  273. var file = fileCache.get(sourcePath);
  274. if (!file) {
  275. file = { content: '', path: sourcePath };
  276. }
  277. if (shouldInlineTemplate) {
  278. file.content = template_1.inlineTemplate(data, sourcePath);
  279. }
  280. else {
  281. file.content = data;
  282. }
  283. fileCache.set(sourcePath, file);
  284. }
  285. else if (sourcePath.endsWith('.js.map')) {
  286. var file = fileCache.get(sourcePath);
  287. if (!file) {
  288. file = { content: '', path: sourcePath };
  289. }
  290. file.content = data;
  291. fileCache.set(sourcePath, file);
  292. }
  293. }
  294. function getTsConfigAsync(context, tsConfigPath) {
  295. return __awaiter(this, void 0, void 0, function () {
  296. return __generator(this, function (_a) {
  297. switch (_a.label) {
  298. case 0: return [4 /*yield*/, getTsConfig(context, tsConfigPath)];
  299. case 1: return [2 /*return*/, _a.sent()];
  300. }
  301. });
  302. });
  303. }
  304. exports.getTsConfigAsync = getTsConfigAsync;
  305. function getTsConfig(context, tsConfigPath) {
  306. var config = null;
  307. tsConfigPath = tsConfigPath || getTsConfigPath(context);
  308. var tsConfigFile = ts.readConfigFile(tsConfigPath, function (path) { return fs_1.readFileSync(path, 'utf8'); });
  309. if (!tsConfigFile) {
  310. throw new errors_1.BuildError("tsconfig: invalid tsconfig file, \"" + tsConfigPath + "\"");
  311. }
  312. else if (tsConfigFile.error && tsConfigFile.error.messageText) {
  313. throw new errors_1.BuildError("tsconfig: " + tsConfigFile.error.messageText);
  314. }
  315. else if (!tsConfigFile.config) {
  316. throw new errors_1.BuildError("tsconfig: invalid config, \"" + tsConfigPath + "\"\"");
  317. }
  318. else {
  319. var parsedConfig = ts.parseJsonConfigFileContent(tsConfigFile.config, ts.sys, context.rootDir, {}, tsConfigPath);
  320. var diagnostics = logger_typescript_1.runTypeScriptDiagnostics(context, parsedConfig.errors);
  321. if (diagnostics.length) {
  322. logger_diagnostics_1.printDiagnostics(context, logger_diagnostics_1.DiagnosticsType.TypeScript, diagnostics, true, true);
  323. throw new errors_1.BuildError("tsconfig: invalid config, \"" + tsConfigPath + "\"\"");
  324. }
  325. config = {
  326. options: parsedConfig.options,
  327. fileNames: parsedConfig.fileNames,
  328. raw: parsedConfig.raw
  329. };
  330. }
  331. return config;
  332. }
  333. exports.getTsConfig = getTsConfig;
  334. function transpileTsString(context, filePath, stringToTranspile) {
  335. if (!cachedTsConfig) {
  336. cachedTsConfig = getTsConfig(context);
  337. }
  338. var transpileOptions = {
  339. compilerOptions: cachedTsConfig.options,
  340. fileName: filePath,
  341. reportDiagnostics: true,
  342. };
  343. transpileOptions.compilerOptions.allowJs = true;
  344. transpileOptions.compilerOptions.sourceMap = true;
  345. // transpile this one module
  346. return ts.transpileModule(stringToTranspile, transpileOptions);
  347. }
  348. exports.transpileTsString = transpileTsString;
  349. function transformSource(filePath, input) {
  350. if (util_1.isDeepLinkingFile(filePath)) {
  351. input = util_1.purgeDeepLinkDecorator(input);
  352. }
  353. else if (filePath === helpers_1.getStringPropertyValue(Constants.ENV_APP_NG_MODULE_PATH) && !util_1.hasExistingDeepLinkConfig(filePath, input)) {
  354. var deepLinkString = util_1.convertDeepLinkConfigEntriesToString(helpers_1.getParsedDeepLinkConfig());
  355. input = util_1.getUpdatedAppNgModuleContentWithDeepLinkConfig(filePath, input, deepLinkString);
  356. }
  357. return input;
  358. }
  359. exports.transformSource = transformSource;
  360. function copyOriginalSourceFiles(fileCache) {
  361. var deepLinkFiles = util_1.filterTypescriptFilesForDeepLinks(fileCache);
  362. var appNgModule = fileCache.get(helpers_1.getStringPropertyValue(Constants.ENV_APP_NG_MODULE_PATH));
  363. deepLinkFiles.push(appNgModule);
  364. deepLinkFiles.forEach(function (deepLinkFile) {
  365. fileCache.set(deepLinkFile.path + exports.inMemoryFileCopySuffix, {
  366. path: deepLinkFile.path + exports.inMemoryFileCopySuffix,
  367. content: deepLinkFile.content
  368. });
  369. });
  370. }
  371. exports.copyOriginalSourceFiles = copyOriginalSourceFiles;
  372. function resetSourceFiles(fileCache) {
  373. fileCache.getAll().forEach(function (file) {
  374. if (path.extname(file.path) === ".ts" + exports.inMemoryFileCopySuffix) {
  375. var originalExtension = helpers_1.changeExtension(file.path, '.ts');
  376. fileCache.set(originalExtension, {
  377. path: originalExtension,
  378. content: file.content
  379. });
  380. fileCache.getRawStore().delete(file.path);
  381. }
  382. });
  383. }
  384. exports.resetSourceFiles = resetSourceFiles;
  385. exports.inMemoryFileCopySuffix = 'original';
  386. var cachedProgram = null;
  387. var cachedTsConfig = null;
  388. function getTsConfigPath(context) {
  389. return process.env[Constants.ENV_TS_CONFIG];
  390. }
  391. exports.getTsConfigPath = getTsConfigPath;