source: frontend/node_modules/babel-loader/lib/cache.js

Last change on this file was 9af201e, checked in by MBK <marija.karapandzova@…>, 11 days ago

Fix frontend appearance

  • Property mode set to 100644
File size: 6.2 KB
Line 
1"use strict";
2
3function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
4function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
5/**
6 * Filesystem Cache
7 *
8 * Given a file and a transform function, cache the result into files
9 * or retrieve the previously cached files if the given file is already known.
10 *
11 * @see https://github.com/babel/babel-loader/issues/34
12 * @see https://github.com/babel/babel-loader/pull/41
13 */
14const fs = require("fs");
15const os = require("os");
16const path = require("path");
17const zlib = require("zlib");
18const crypto = require("crypto");
19const findCacheDir = require("find-cache-dir");
20const {
21 promisify
22} = require("util");
23const transform = require("./transform");
24// Lazily instantiated when needed
25let defaultCacheDirectory = null;
26let hashType = "sha256";
27// use md5 hashing if sha256 is not available
28try {
29 crypto.createHash(hashType);
30} catch (err) {
31 hashType = "md5";
32}
33const readFile = promisify(fs.readFile);
34const writeFile = promisify(fs.writeFile);
35const gunzip = promisify(zlib.gunzip);
36const gzip = promisify(zlib.gzip);
37const makeDir = require("make-dir");
38
39/**
40 * Read the contents from the compressed file.
41 *
42 * @async
43 * @params {String} filename
44 * @params {Boolean} compress
45 */
46const read = /*#__PURE__*/function () {
47 var _ref = _asyncToGenerator(function* (filename, compress) {
48 const data = yield readFile(filename + (compress ? ".gz" : ""));
49 const content = compress ? yield gunzip(data) : data;
50 return JSON.parse(content.toString());
51 });
52 return function read(_x, _x2) {
53 return _ref.apply(this, arguments);
54 };
55}();
56
57/**
58 * Write contents into a compressed file.
59 *
60 * @async
61 * @params {String} filename
62 * @params {Boolean} compress
63 * @params {String} result
64 */
65const write = /*#__PURE__*/function () {
66 var _ref2 = _asyncToGenerator(function* (filename, compress, result) {
67 const content = JSON.stringify(result);
68 const data = compress ? yield gzip(content) : content;
69 return yield writeFile(filename + (compress ? ".gz" : ""), data);
70 });
71 return function write(_x3, _x4, _x5) {
72 return _ref2.apply(this, arguments);
73 };
74}();
75
76/**
77 * Build the filename for the cached file
78 *
79 * @params {String} source File source code
80 * @params {Object} options Options used
81 *
82 * @return {String}
83 */
84const filename = function (source, identifier, options) {
85 const hash = crypto.createHash(hashType);
86 const contents = JSON.stringify({
87 source,
88 options,
89 identifier
90 });
91 hash.update(contents);
92 return hash.digest("hex") + ".json";
93};
94
95/**
96 * Handle the cache
97 *
98 * @params {String} directory
99 * @params {Object} params
100 */
101const handleCache = /*#__PURE__*/function () {
102 var _ref3 = _asyncToGenerator(function* (directory, params) {
103 const {
104 source,
105 options = {},
106 cacheIdentifier,
107 cacheDirectory,
108 cacheCompression,
109 logger
110 } = params;
111 const file = path.join(directory, filename(source, cacheIdentifier, options));
112 try {
113 // No errors mean that the file was previously cached
114 // we just need to return it
115 logger.debug(`reading cache file '${file}'`);
116 return yield read(file, cacheCompression);
117 } catch (err) {
118 // conitnue if cache can't be read
119 logger.debug(`discarded cache as it can not be read`);
120 }
121 const fallback = typeof cacheDirectory !== "string" && directory !== os.tmpdir();
122
123 // Make sure the directory exists.
124 try {
125 logger.debug(`creating cache folder '${directory}'`);
126 yield makeDir(directory);
127 } catch (err) {
128 if (fallback) {
129 return handleCache(os.tmpdir(), params);
130 }
131 throw err;
132 }
133
134 // Otherwise just transform the file
135 // return it to the user asap and write it in cache
136 logger.debug(`applying Babel transform`);
137 const result = yield transform(source, options);
138
139 // Do not cache if there are external dependencies,
140 // since they might change and we cannot control it.
141 if (!result.externalDependencies.length) {
142 try {
143 logger.debug(`writing result to cache file '${file}'`);
144 yield write(file, cacheCompression, result);
145 } catch (err) {
146 if (fallback) {
147 // Fallback to tmpdir if node_modules folder not writable
148 return handleCache(os.tmpdir(), params);
149 }
150 throw err;
151 }
152 }
153 return result;
154 });
155 return function handleCache(_x6, _x7) {
156 return _ref3.apply(this, arguments);
157 };
158}();
159
160/**
161 * Retrieve file from cache, or create a new one for future reads
162 *
163 * @async
164 * @param {Object} params
165 * @param {String} params.cacheDirectory Directory to store cached files
166 * @param {String} params.cacheIdentifier Unique identifier to bust cache
167 * @param {Boolean} params.cacheCompression Whether compressing cached files
168 * @param {String} params.source Original contents of the file to be cached
169 * @param {Object} params.options Options to be given to the transform fn
170 *
171 * @example
172 *
173 * const result = await cache({
174 * cacheDirectory: '.tmp/cache',
175 * cacheIdentifier: 'babel-loader-cachefile',
176 * cacheCompression: false,
177 * source: *source code from file*,
178 * options: {
179 * experimental: true,
180 * runtime: true
181 * },
182 * });
183 */
184
185module.exports = /*#__PURE__*/function () {
186 var _ref4 = _asyncToGenerator(function* (params) {
187 let directory;
188 if (typeof params.cacheDirectory === "string") {
189 directory = params.cacheDirectory;
190 } else {
191 if (defaultCacheDirectory === null) {
192 defaultCacheDirectory = findCacheDir({
193 name: "babel-loader"
194 }) || os.tmpdir();
195 }
196 directory = defaultCacheDirectory;
197 }
198 return yield handleCache(directory, params);
199 });
200 return function (_x8) {
201 return _ref4.apply(this, arguments);
202 };
203}();
Note: See TracBrowser for help on using the repository browser.