1 | "use strict";
|
2 | var fs = require("fs");
|
3 | var os = require("os");
|
4 | var path = require("path");
|
5 | var zlib = require("zlib");
|
6 | var crypto_1 = require("crypto");
|
7 | function findCompiledModule(fileName) {
|
8 | var baseFileName = fileName.replace(/(\.ts|\.tsx)$/, '');
|
9 | var compiledFileName = baseFileName + ".js";
|
10 | if (fs.existsSync(compiledFileName)) {
|
11 | var mapFileName = baseFileName + ".js.map";
|
12 | var isMapExists = fs.existsSync(mapFileName);
|
13 | var result = {
|
14 | fileName: compiledFileName,
|
15 | text: fs.readFileSync(compiledFileName).toString(),
|
16 | mapName: isMapExists
|
17 | ? mapFileName
|
18 | : null,
|
19 | map: isMapExists
|
20 | ? fs.readFileSync(mapFileName).toString()
|
21 | : null
|
22 | };
|
23 | return result;
|
24 | }
|
25 | else {
|
26 | return null;
|
27 | }
|
28 | }
|
29 | exports.findCompiledModule = findCompiledModule;
|
30 | function read(filename) {
|
31 | var content = fs.readFileSync(filename);
|
32 | var jsonString = zlib.gunzipSync(content);
|
33 | return JSON.parse(jsonString.toString());
|
34 | }
|
35 | function write(filename, result) {
|
36 | var jsonString = JSON.stringify(result);
|
37 | var content = zlib.gzipSync(jsonString);
|
38 | return fs.writeFileSync(filename, content);
|
39 | }
|
40 | function filename(source, identifier, options) {
|
41 | var hash = crypto_1.createHash('sha512');
|
42 | var contents = JSON.stringify({
|
43 | identifier: identifier,
|
44 | options: options,
|
45 | source: source,
|
46 | });
|
47 | hash.end(contents);
|
48 | return hash.read().toString('hex') + '.json.gzip';
|
49 | }
|
50 | ;
|
51 | function cache(params) {
|
52 | var source = params.source;
|
53 | var options = params.options || {};
|
54 | var transform = params.transform;
|
55 | var identifier = params.identifier;
|
56 | var directory = (typeof params.directory === 'string') ?
|
57 | params.directory :
|
58 | os.tmpdir();
|
59 | var file = path.join(directory, filename(source, identifier, options));
|
60 | try {
|
61 | return Promise.resolve({ cached: true, result: read(file) });
|
62 | }
|
63 | catch (e) {
|
64 | return transform().then(function (result) {
|
65 | write(file, result);
|
66 | return { cached: false, result: result };
|
67 | });
|
68 | }
|
69 | }
|
70 | exports.cache = cache;
|
71 |
|
\ | No newline at end of file |