@netlify/cache-utils 4.1.6-rc → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/dir.js CHANGED
@@ -1,8 +1,6 @@
1
- import { resolve } from 'path'
2
-
1
+ import { resolve } from 'path';
3
2
  // Retrieve the cache directory location
4
3
  export const getCacheDir = function ({ cacheDir = DEFAULT_CACHE_DIR, cwd = '.' } = {}) {
5
- return resolve(cwd, cacheDir)
6
- }
7
-
8
- const DEFAULT_CACHE_DIR = '.netlify/cache/'
4
+ return resolve(cwd, cacheDir);
5
+ };
6
+ const DEFAULT_CACHE_DIR = '.netlify/cache/';
package/lib/expire.js CHANGED
@@ -1,15 +1,16 @@
1
- // Retrieve the expiration date when caching a file
2
- export const getExpires = function (ttl) {
3
- if (!Number.isInteger(ttl) || ttl < 1) {
4
- return
5
- }
6
-
7
- return Date.now() + ttl * SECS_TO_MSECS
8
- }
9
-
10
- const SECS_TO_MSECS = 1e3
11
-
12
- // Check if a file about to be restored is expired
13
- export const checkExpires = function (expires) {
14
- return expires !== undefined && Date.now() > expires
15
- }
1
+ const SECS_TO_MSECS = 1e3;
2
+ /**
3
+ * Calculate the expiration date based on a time to leave in seconds
4
+ * This might be used to retrieve the expiration date when caching a file
5
+ */
6
+ export const getExpires = (timeToLeave) => {
7
+ if (!Number.isInteger(timeToLeave) || timeToLeave < 1) {
8
+ return;
9
+ }
10
+ return Date.now() + timeToLeave * SECS_TO_MSECS;
11
+ };
12
+ /**
13
+ * Check if a expiredDate in milliseconds (retrieved by `Date.now`) has already expired
14
+ * This might be used to check if a file is expired
15
+ */
16
+ export const checkExpires = (expiredDate) => expiredDate !== undefined && Date.now() > expiredDate;
package/lib/fs.js CHANGED
@@ -1,60 +1,51 @@
1
- import { promises as fs } from 'fs'
2
- import { basename, dirname } from 'path'
3
-
4
- import cpy from 'cpy'
5
- import { globby } from 'globby'
6
- import { isNotJunk } from 'junk'
7
- import { moveFile } from 'move-file'
8
-
1
+ import { promises as fs } from 'fs';
2
+ import { basename, dirname } from 'path';
3
+ import cpy from 'cpy';
4
+ import { globby } from 'globby';
5
+ import { isNotJunk } from 'junk';
6
+ import { moveFile } from 'move-file';
9
7
  // Move or copy a cached file/directory from/to a local one
10
8
  export const moveCacheFile = async function (src, dest, move) {
11
- // Moving is faster but removes the source files locally
12
- if (move) {
13
- return moveFile(src, dest, { overwrite: false })
14
- }
15
-
16
- const { srcGlob, cwd } = await getSrcGlob(src)
17
- return cpy(srcGlob, dirname(dest), { cwd, parents: true, overwrite: false })
18
- }
19
-
9
+ // Moving is faster but removes the source files locally
10
+ if (move) {
11
+ return moveFile(src, dest, { overwrite: false });
12
+ }
13
+ const { srcGlob, cwd } = await getSrcGlob(src);
14
+ return cpy(srcGlob, dirname(dest), { cwd, parents: true, overwrite: false });
15
+ };
20
16
  // Non-existing files and empty directories are always skipped
21
17
  export const hasFiles = async function (src) {
22
- const { srcGlob, cwd, isDir } = await getSrcGlob(src)
23
- return srcGlob !== undefined && !(await isEmptyDir({ srcGlob, cwd, isDir }))
24
- }
25
-
18
+ const { srcGlob, cwd, isDir } = await getSrcGlob(src);
19
+ return srcGlob !== undefined && !(await isEmptyDir({ srcGlob, cwd, isDir }));
20
+ };
26
21
  // Replicates what `cpy` is doing under the hood.
27
22
  const isEmptyDir = async function ({ srcGlob, cwd, isDir }) {
28
- if (!isDir) {
29
- return false
30
- }
31
-
32
- const files = await globby(srcGlob, { cwd })
33
- const filteredFiles = files.filter((file) => isNotJunk(basename(file)))
34
- return filteredFiles.length === 0
35
- }
36
-
23
+ if (!isDir) {
24
+ return false;
25
+ }
26
+ const files = await globby(srcGlob, { cwd });
27
+ const filteredFiles = files.filter((file) => isNotJunk(basename(file)));
28
+ return filteredFiles.length === 0;
29
+ };
37
30
  // Get globbing pattern with files to move/copy
38
31
  const getSrcGlob = async function (src) {
39
- const srcStat = await getStat(src)
40
-
41
- if (srcStat === undefined) {
42
- return {}
43
- }
44
-
45
- const isDir = srcStat.isDirectory()
46
- const srcBasename = basename(src)
47
- const cwd = dirname(src)
48
-
49
- if (isDir) {
50
- return { srcGlob: `${srcBasename}/**`, cwd, isDir }
51
- }
52
-
53
- return { srcGlob: srcBasename, cwd, isDir }
54
- }
55
-
32
+ const srcStat = await getStat(src);
33
+ if (srcStat === undefined) {
34
+ return {};
35
+ }
36
+ const isDir = srcStat.isDirectory();
37
+ const srcBasename = basename(src);
38
+ const cwd = dirname(src);
39
+ if (isDir) {
40
+ return { srcGlob: `${srcBasename}/**`, cwd, isDir };
41
+ }
42
+ return { srcGlob: srcBasename, cwd, isDir };
43
+ };
56
44
  const getStat = async function (src) {
57
- try {
58
- return await fs.stat(src)
59
- } catch {}
60
- }
45
+ try {
46
+ return await fs.stat(src);
47
+ }
48
+ catch {
49
+ // continue regardless error
50
+ }
51
+ };
package/lib/hash.js CHANGED
@@ -1,36 +1,30 @@
1
- import { createHash } from 'crypto'
2
- import { createReadStream } from 'fs'
3
-
4
- import getStream from 'get-stream'
5
- import { locatePath } from 'locate-path'
6
-
1
+ import { createHash } from 'crypto';
2
+ import { createReadStream } from 'fs';
3
+ import getStream from 'get-stream';
4
+ import { locatePath } from 'locate-path';
7
5
  // Caching a big directory like `node_modules` is slow. However those can
8
6
  // sometime be represented by a digest file such as `package-lock.json`. If this
9
7
  // has not changed, we don't need to save cache again.
10
8
  export const getHash = async function (digests, move) {
11
- // Moving files is faster than computing hashes
12
- if (move || digests.length === 0) {
13
- return
14
- }
15
-
16
- const digestPath = await locatePath(digests)
17
- if (digestPath === undefined) {
18
- return
19
- }
20
-
21
- const hash = await hashFile(digestPath)
22
- return hash
23
- }
24
-
9
+ // Moving files is faster than computing hashes
10
+ if (move || digests.length === 0) {
11
+ return;
12
+ }
13
+ const digestPath = await locatePath(digests);
14
+ if (digestPath === undefined) {
15
+ return;
16
+ }
17
+ const hash = await hashFile(digestPath);
18
+ return hash;
19
+ };
25
20
  // Hash a file's contents
26
21
  const hashFile = async function (path) {
27
- const contentStream = createReadStream(path, 'utf8')
28
- const hashStream = createHash(HASH_ALGO, { encoding: 'hex' })
29
- contentStream.pipe(hashStream)
30
- const hash = await getStream(hashStream)
31
- return hash
32
- }
33
-
22
+ const contentStream = createReadStream(path, 'utf8');
23
+ const hashStream = createHash(HASH_ALGO, { encoding: 'hex' });
24
+ contentStream.pipe(hashStream);
25
+ const hash = await getStream(hashStream);
26
+ return hash;
27
+ };
34
28
  // We need a hashing algoritm that's as fast as possible.
35
29
  // Userland CRC32 implementations are actually slower than Node.js SHA1.
36
- const HASH_ALGO = 'sha1'
30
+ const HASH_ALGO = 'sha1';
package/lib/list.js CHANGED
@@ -1,29 +1,23 @@
1
- import { join } from 'path'
2
-
3
- import readdirp from 'readdirp'
4
-
5
- import { getCacheDir } from './dir.js'
6
- import { isManifest } from './manifest.js'
7
- import { getBases } from './path.js'
8
-
1
+ import { join } from 'path';
2
+ import readdirp from 'readdirp';
3
+ import { getCacheDir } from './dir.js';
4
+ import { isManifest } from './manifest.js';
5
+ import { getBases } from './path.js';
9
6
  // List all cached files/directories, at the top-level
10
7
  export const list = async function ({ cacheDir, cwd: cwdOpt, depth = DEFAULT_DEPTH } = {}) {
11
- const bases = await getBases(cwdOpt)
12
- const cacheDirA = getCacheDir({ cacheDir, cwd: cwdOpt })
13
- const files = await Promise.all(bases.map(({ name, base }) => listBase({ name, base, cacheDir: cacheDirA, depth })))
14
- const filesA = files.flat()
15
- return filesA
16
- }
17
-
18
- const DEFAULT_DEPTH = 1
19
-
8
+ const bases = await getBases(cwdOpt);
9
+ const cacheDirA = getCacheDir({ cacheDir, cwd: cwdOpt });
10
+ const files = await Promise.all(bases.map(({ name, base }) => listBase({ name, base, cacheDir: cacheDirA, depth })));
11
+ const filesA = files.flat();
12
+ return filesA;
13
+ };
14
+ const DEFAULT_DEPTH = 1;
20
15
  // TODO: the returned paths are missing the Windows drive
21
16
  const listBase = async function ({ name, base, cacheDir, depth }) {
22
- const files = await readdirp.promise(`${cacheDir}/${name}`, { fileFilter, depth, type: 'files_directories' })
23
- const filesA = files.map(({ path }) => join(base, path))
24
- return filesA
25
- }
26
-
17
+ const files = await readdirp.promise(`${cacheDir}/${name}`, { fileFilter, depth, type: 'files_directories' });
18
+ const filesA = files.map(({ path }) => join(base, path));
19
+ return filesA;
20
+ };
27
21
  const fileFilter = function ({ basename }) {
28
- return !isManifest(basename)
29
- }
22
+ return !isManifest(basename);
23
+ };
package/lib/main.js CHANGED
@@ -1,103 +1,77 @@
1
- import del from 'del'
2
-
3
- import { getCacheDir } from './dir.js'
4
- import { moveCacheFile, hasFiles } from './fs.js'
5
- import { list } from './list.js'
6
- import { getManifestInfo, writeManifest, removeManifest, isExpired } from './manifest.js'
7
- import { parsePath } from './path.js'
8
-
9
- export { getCacheDir } from './dir.js'
10
- export { list } from './list.js'
11
-
1
+ import del from 'del';
2
+ import { getCacheDir } from './dir.js';
3
+ import { moveCacheFile, hasFiles } from './fs.js';
4
+ import { list } from './list.js';
5
+ import { getManifestInfo, writeManifest, removeManifest, isExpired } from './manifest.js';
6
+ import { parsePath } from './path.js';
7
+ export { getCacheDir } from './dir.js';
8
+ export { list } from './list.js';
12
9
  // Cache a file
13
- const saveOne = async function (
14
- path,
15
- { move = DEFAULT_MOVE, ttl = DEFAULT_TTL, digests = [], cacheDir, cwd: cwdOpt } = {},
16
- ) {
17
- const { srcPath, cachePath } = await parsePath({ path, cacheDir, cwdOpt })
18
-
19
- if (!(await hasFiles(srcPath))) {
20
- return false
21
- }
22
-
23
- const { manifestInfo, identical } = await getManifestInfo({ cachePath, move, ttl, digests })
24
- if (identical) {
25
- return true
26
- }
27
-
28
- await del(cachePath, { force: true })
29
- await moveCacheFile(srcPath, cachePath, move)
30
- await writeManifest(manifestInfo)
31
-
32
- return true
33
- }
34
-
10
+ const saveOne = async function (path, { move = DEFAULT_MOVE, ttl = DEFAULT_TTL, digests = [], cacheDir, cwd: cwdOpt } = {}) {
11
+ const { srcPath, cachePath } = await parsePath({ path, cacheDir, cwdOpt });
12
+ if (!(await hasFiles(srcPath))) {
13
+ return false;
14
+ }
15
+ const { manifestInfo, identical } = await getManifestInfo({ cachePath, move, ttl, digests });
16
+ if (identical) {
17
+ return true;
18
+ }
19
+ await del(cachePath, { force: true });
20
+ await moveCacheFile(srcPath, cachePath, move);
21
+ await writeManifest(manifestInfo);
22
+ return true;
23
+ };
35
24
  // Restore a cached file
36
25
  const restoreOne = async function (path, { move = DEFAULT_MOVE, cacheDir, cwd: cwdOpt } = {}) {
37
- const { srcPath, cachePath } = await parsePath({ path, cacheDir, cwdOpt })
38
-
39
- if (!(await hasFiles(cachePath))) {
40
- return false
41
- }
42
-
43
- if (await isExpired(cachePath)) {
44
- return false
45
- }
46
-
47
- await del(srcPath, { force: true })
48
- await moveCacheFile(cachePath, srcPath, move)
49
-
50
- return true
51
- }
52
-
26
+ const { srcPath, cachePath } = await parsePath({ path, cacheDir, cwdOpt });
27
+ if (!(await hasFiles(cachePath))) {
28
+ return false;
29
+ }
30
+ if (await isExpired(cachePath)) {
31
+ return false;
32
+ }
33
+ await del(srcPath, { force: true });
34
+ await moveCacheFile(cachePath, srcPath, move);
35
+ return true;
36
+ };
53
37
  // Remove the cache of a file
54
38
  const removeOne = async function (path, { cacheDir, cwd: cwdOpt } = {}) {
55
- const { cachePath } = await parsePath({ path, cacheDir, cwdOpt })
56
-
57
- if (!(await hasFiles(cachePath))) {
58
- return false
59
- }
60
-
61
- await del(cachePath, { force: true })
62
- await removeManifest(cachePath)
63
-
64
- return true
65
- }
66
-
39
+ const { cachePath } = await parsePath({ path, cacheDir, cwdOpt });
40
+ if (!(await hasFiles(cachePath))) {
41
+ return false;
42
+ }
43
+ await del(cachePath, { force: true });
44
+ await removeManifest(cachePath);
45
+ return true;
46
+ };
67
47
  // Check if a file is cached
68
48
  const hasOne = async function (path, { cacheDir, cwd: cwdOpt } = {}) {
69
- const { cachePath } = await parsePath({ path, cacheDir, cwdOpt })
70
-
71
- return (await hasFiles(cachePath)) && !(await isExpired(cachePath))
72
- }
73
-
74
- const DEFAULT_MOVE = false
75
- const DEFAULT_TTL = undefined
76
-
49
+ const { cachePath } = await parsePath({ path, cacheDir, cwdOpt });
50
+ return (await hasFiles(cachePath)) && !(await isExpired(cachePath));
51
+ };
52
+ const DEFAULT_MOVE = false;
53
+ const DEFAULT_TTL = undefined;
77
54
  // Allow each of the main functions to take either a single path or an array of
78
55
  // paths as arguments
79
56
  const allowMany = async function (func, paths, ...args) {
80
- if (!Array.isArray(paths)) {
81
- return func(paths, ...args)
82
- }
83
-
84
- const results = await Promise.all(paths.map((path) => func(path, ...args)))
85
- return results.some(Boolean)
86
- }
87
-
88
- export const save = allowMany.bind(null, saveOne)
89
- export const restore = allowMany.bind(null, restoreOne)
90
- export const remove = allowMany.bind(null, removeOne)
91
- export const has = allowMany.bind(null, hasOne)
92
-
57
+ if (!Array.isArray(paths)) {
58
+ return func(paths, ...args);
59
+ }
60
+ const results = await Promise.all(paths.map((path) => func(path, ...args)));
61
+ return results.some(Boolean);
62
+ };
63
+ export const save = allowMany.bind(null, saveOne);
64
+ export const restore = allowMany.bind(null, restoreOne);
65
+ export const remove = allowMany.bind(null, removeOne);
66
+ export const has = allowMany.bind(null, hasOne);
93
67
  // Change `opts` default values
94
68
  export const bindOpts = function (opts) {
95
- return {
96
- save: (paths, optsA) => save(paths, { ...opts, ...optsA }),
97
- restore: (paths, optsA) => restore(paths, { ...opts, ...optsA }),
98
- remove: (paths, optsA) => remove(paths, { ...opts, ...optsA }),
99
- has: (paths, optsA) => has(paths, { ...opts, ...optsA }),
100
- list: (optsA) => list({ ...opts, ...optsA }),
101
- getCacheDir: (optsA) => getCacheDir({ ...opts, ...optsA }),
102
- }
103
- }
69
+ return {
70
+ save: (paths, optsA) => save(paths, { ...opts, ...optsA }),
71
+ restore: (paths, optsA) => restore(paths, { ...opts, ...optsA }),
72
+ remove: (paths, optsA) => remove(paths, { ...opts, ...optsA }),
73
+ has: (paths, optsA) => has(paths, { ...opts, ...optsA }),
74
+ list: (optsA) => list({ ...opts, ...optsA }),
75
+ getCacheDir: (optsA) => getCacheDir({ ...opts, ...optsA }),
76
+ };
77
+ };
package/lib/manifest.js CHANGED
@@ -1,71 +1,58 @@
1
- import { promises as fs } from 'fs'
2
- import { dirname } from 'path'
3
-
4
- import del from 'del'
5
- import { pathExists } from 'path-exists'
6
-
7
- import { getExpires, checkExpires } from './expire.js'
8
- import { getHash } from './hash.js'
9
-
1
+ import { promises as fs } from 'fs';
2
+ import { dirname } from 'path';
3
+ import del from 'del';
4
+ import { pathExists } from 'path-exists';
5
+ import { getExpires, checkExpires } from './expire.js';
6
+ import { getHash } from './hash.js';
10
7
  // Retrieve cache manifest of a file to cache, which contains the file/directory
11
8
  // contents hash and the `expires` date.
12
9
  export const getManifestInfo = async function ({ cachePath, move, ttl, digests }) {
13
- const manifestPath = getManifestPath(cachePath)
14
- const expires = getExpires(ttl)
15
- const hash = await getHash(digests, move)
16
- const manifest = { expires, hash }
17
- const manifestString = `${JSON.stringify(manifest, null, 2)}\n`
18
- const identical = await isIdentical({ hash, manifestPath, manifestString })
19
- return { manifestInfo: { manifestPath, manifestString }, identical }
20
- }
21
-
10
+ const manifestPath = getManifestPath(cachePath);
11
+ const expires = getExpires(ttl);
12
+ const hash = await getHash(digests, move);
13
+ const manifest = { expires, hash };
14
+ const manifestString = `${JSON.stringify(manifest, null, 2)}\n`;
15
+ const identical = await isIdentical({ hash, manifestPath, manifestString });
16
+ return { manifestInfo: { manifestPath, manifestString }, identical };
17
+ };
22
18
  // Whether the cache manifest has changed
23
19
  const isIdentical = async function ({ hash, manifestPath, manifestString }) {
24
- if (hash === undefined || !(await pathExists(manifestPath))) {
25
- return false
26
- }
27
-
28
- const oldManifestString = await fs.readFile(manifestPath, 'utf8')
29
- return oldManifestString === manifestString
30
- }
31
-
20
+ if (hash === undefined || !(await pathExists(manifestPath))) {
21
+ return false;
22
+ }
23
+ const oldManifestString = await fs.readFile(manifestPath, 'utf8');
24
+ return oldManifestString === manifestString;
25
+ };
32
26
  // Persist the cache manifest to filesystem
33
27
  export const writeManifest = async function ({ manifestPath, manifestString }) {
34
- await fs.mkdir(dirname(manifestPath), { recursive: true })
35
- await fs.writeFile(manifestPath, manifestString)
36
- }
37
-
28
+ await fs.mkdir(dirname(manifestPath), { recursive: true });
29
+ await fs.writeFile(manifestPath, manifestString);
30
+ };
38
31
  // Remove the cache manifest from filesystem
39
32
  export const removeManifest = async function (cachePath) {
40
- const manifestPath = getManifestPath(cachePath)
41
- await del(manifestPath, { force: true })
42
- }
43
-
33
+ const manifestPath = getManifestPath(cachePath);
34
+ await del(manifestPath, { force: true });
35
+ };
44
36
  // Retrieve the cache manifest filepath
45
37
  const getManifestPath = function (cachePath) {
46
- return `${cachePath}${CACHE_EXTENSION}`
47
- }
48
-
38
+ return `${cachePath}${CACHE_EXTENSION}`;
39
+ };
49
40
  export const isManifest = function (filePath) {
50
- return filePath.endsWith(CACHE_EXTENSION)
51
- }
52
-
53
- const CACHE_EXTENSION = '.netlify.cache.json'
54
-
41
+ return filePath.endsWith(CACHE_EXTENSION);
42
+ };
43
+ const CACHE_EXTENSION = '.netlify.cache.json';
55
44
  // Check whether a file/directory is expired by checking its cache manifest
56
45
  export const isExpired = async function (cachePath) {
57
- const manifestPath = getManifestPath(cachePath)
58
- if (!(await pathExists(manifestPath))) {
59
- return false
60
- }
61
-
62
- const { expires } = await readManifest(cachePath)
63
- return checkExpires(expires)
64
- }
65
-
46
+ const manifestPath = getManifestPath(cachePath);
47
+ if (!(await pathExists(manifestPath))) {
48
+ return false;
49
+ }
50
+ const { expires } = await readManifest(cachePath);
51
+ return checkExpires(expires);
52
+ };
66
53
  const readManifest = async function (cachePath) {
67
- const manifestPath = getManifestPath(cachePath)
68
- const manifestString = await fs.readFile(manifestPath)
69
- const manifest = JSON.parse(manifestString)
70
- return manifest
71
- }
54
+ const manifestPath = getManifestPath(cachePath);
55
+ const manifestString = await fs.readFile(manifestPath);
56
+ const manifest = JSON.parse(manifestString);
57
+ return manifest;
58
+ };
package/lib/path.js CHANGED
@@ -1,36 +1,29 @@
1
- import { homedir } from 'os'
2
- import { resolve, isAbsolute, join, sep } from 'path'
3
-
4
- import { getCacheDir } from './dir.js'
5
- import { safeGetCwd } from './utils/cwd.js'
6
-
1
+ import { homedir } from 'os';
2
+ import { resolve, isAbsolute, join, sep } from 'path';
3
+ import { getCacheDir } from './dir.js';
4
+ import { safeGetCwd } from './utils/cwd.js';
7
5
  // Find the paths of the file before/after caching
8
6
  export const parsePath = async function ({ path, cacheDir, cwdOpt }) {
9
- const srcPath = await getSrcPath(path, cwdOpt)
10
- const cachePath = await getCachePath({ srcPath, cacheDir, cwdOpt })
11
- return { srcPath, cachePath }
12
- }
13
-
7
+ const srcPath = await getSrcPath(path, cwdOpt);
8
+ const cachePath = await getCachePath({ srcPath, cacheDir, cwdOpt });
9
+ return { srcPath, cachePath };
10
+ };
14
11
  // Retrieve absolute path to the local file to cache/restore
15
12
  const getSrcPath = async function (path, cwdOpt) {
16
- const cwd = await safeGetCwd(cwdOpt)
17
- const srcPath = resolvePath(path, cwd)
18
- checkSrcPath(srcPath, cwd)
19
- return srcPath
20
- }
21
-
13
+ const cwd = await safeGetCwd(cwdOpt);
14
+ const srcPath = resolvePath(path, cwd);
15
+ checkSrcPath(srcPath, cwd);
16
+ return srcPath;
17
+ };
22
18
  const resolvePath = function (path, cwd) {
23
- if (isAbsolute(path)) {
24
- return resolve(path)
25
- }
26
-
27
- if (cwd !== '') {
28
- return resolve(cwd, path)
29
- }
30
-
31
- throw new Error(`Current directory does not exist: ${cwd}`)
32
- }
33
-
19
+ if (isAbsolute(path)) {
20
+ return resolve(path);
21
+ }
22
+ if (cwd !== '') {
23
+ return resolve(cwd, path);
24
+ }
25
+ throw new Error(`Current directory does not exist: ${cwd}`);
26
+ };
34
27
  // Caching the whole repository creates many issues:
35
28
  // - It caches many directories that are not related to Gatsby but take lots of
36
29
  // space, such as node_modules
@@ -40,32 +33,28 @@ const resolvePath = function (path, cwd) {
40
33
  // happened before this plugin starts restoring the cache, leading to
41
34
  // conflicts with other plugins, Netlify Build or the buildbot.
42
35
  const checkSrcPath = function (srcPath, cwd) {
43
- if (cwd !== '' && isParentPath(srcPath, cwd)) {
44
- throw new Error(`Cannot cache ${srcPath} because it is the current directory (${cwd}) or a parent directory`)
45
- }
46
- }
47
-
36
+ if (cwd !== '' && isParentPath(srcPath, cwd)) {
37
+ throw new Error(`Cannot cache ${srcPath} because it is the current directory (${cwd}) or a parent directory`);
38
+ }
39
+ };
48
40
  // Note: srcPath and cwd are already normalized and absolute
49
41
  const isParentPath = function (srcPath, cwd) {
50
- return `${cwd}${sep}`.startsWith(`${srcPath}${sep}`)
51
- }
52
-
42
+ return `${cwd}${sep}`.startsWith(`${srcPath}${sep}`);
43
+ };
53
44
  const getCachePath = async function ({ srcPath, cacheDir, cwdOpt }) {
54
- const cacheDirA = getCacheDir({ cacheDir, cwd: cwdOpt })
55
- const { name, relPath } = await findBase(srcPath, cwdOpt)
56
- const cachePath = join(cacheDirA, name, relPath)
57
- return cachePath
58
- }
59
-
45
+ const cacheDirA = getCacheDir({ cacheDir, cwd: cwdOpt });
46
+ const { name, relPath } = await findBase(srcPath, cwdOpt);
47
+ const cachePath = join(cacheDirA, name, relPath);
48
+ return cachePath;
49
+ };
60
50
  // The cached path is the path relative to the base which can be either the
61
51
  // current directory, the home directory or the root directory. Each is tried
62
52
  // in order.
63
53
  const findBase = async function (srcPath, cwdOpt) {
64
- const bases = await getBases(cwdOpt)
65
- const srcPathA = normalizeWindows(srcPath)
66
- return bases.map(({ name, base }) => parseBase(name, base, srcPathA)).find(Boolean)
67
- }
68
-
54
+ const bases = await getBases(cwdOpt);
55
+ const srcPathA = normalizeWindows(srcPath);
56
+ return bases.map(({ name, base }) => parseBase(name, base, srcPathA)).find(Boolean);
57
+ };
69
58
  // Windows drives are problematic:
70
59
  // - they cannot be used in `relPath` since directories cannot be called `C:`
71
60
  // for example.
@@ -77,31 +66,25 @@ const findBase = async function (srcPath, cwdOpt) {
77
66
  // current drive.
78
67
  // TODO: fix it.
79
68
  const normalizeWindows = function (srcPath) {
80
- return srcPath.replace(WINDOWS_DRIVE_REGEX, '\\')
81
- }
82
-
83
- const WINDOWS_DRIVE_REGEX = /^[a-zA-Z]:\\/
84
-
69
+ return srcPath.replace(WINDOWS_DRIVE_REGEX, '\\');
70
+ };
71
+ const WINDOWS_DRIVE_REGEX = /^[a-zA-Z]:\\/;
85
72
  // This logic works when `base` and `path` are on different Windows drives
86
73
  const parseBase = function (name, base, srcPath) {
87
- if (srcPath === base || !srcPath.startsWith(base)) {
88
- return
89
- }
90
-
91
- const relPath = srcPath.replace(base, '')
92
- return { name, relPath }
93
- }
94
-
74
+ if (srcPath === base || !srcPath.startsWith(base)) {
75
+ return;
76
+ }
77
+ const relPath = srcPath.replace(base, '');
78
+ return { name, relPath };
79
+ };
95
80
  export const getBases = async function (cwdOpt) {
96
- const cwdBase = await getCwdBase(cwdOpt)
97
- return [...cwdBase, { name: 'home', base: homedir() }, { name: 'root', base: sep }]
98
- }
99
-
81
+ const cwdBase = await getCwdBase(cwdOpt);
82
+ return [...cwdBase, { name: 'home', base: homedir() }, { name: 'root', base: sep }];
83
+ };
100
84
  const getCwdBase = async function (cwdOpt) {
101
- const cwd = await safeGetCwd(cwdOpt)
102
- if (cwd === '') {
103
- return []
104
- }
105
-
106
- return [{ name: 'cwd', base: cwd }]
107
- }
85
+ const cwd = await safeGetCwd(cwdOpt);
86
+ if (cwd === '') {
87
+ return [];
88
+ }
89
+ return [{ name: 'cwd', base: cwd }];
90
+ };
package/lib/utils/cwd.js CHANGED
@@ -1,23 +1,19 @@
1
- import { normalize } from 'path'
2
- import process from 'process'
3
-
4
- import { pathExists } from 'path-exists'
5
-
1
+ import { normalize } from 'path';
2
+ import process from 'process';
3
+ import { pathExists } from 'path-exists';
6
4
  // Like `process.cwd()` but safer when current directory is wrong
7
5
  export const safeGetCwd = async function (cwdOpt) {
8
- try {
9
- const cwd = getCwdValue(cwdOpt)
10
-
11
- if (!(await pathExists(cwd))) {
12
- return ''
6
+ try {
7
+ const cwd = getCwdValue(cwdOpt);
8
+ if (!(await pathExists(cwd))) {
9
+ return '';
10
+ }
11
+ return cwd;
13
12
  }
14
-
15
- return cwd
16
- } catch {
17
- return ''
18
- }
19
- }
20
-
13
+ catch {
14
+ return '';
15
+ }
16
+ };
21
17
  const getCwdValue = function (cwdOpt = process.cwd()) {
22
- return normalize(cwdOpt)
23
- }
18
+ return normalize(cwdOpt);
19
+ };
package/package.json CHANGED
@@ -1,17 +1,20 @@
1
1
  {
2
2
  "name": "@netlify/cache-utils",
3
- "version": "4.1.6-rc",
3
+ "version": "5.0.0",
4
4
  "description": "Utility for caching files in Netlify Build",
5
5
  "type": "module",
6
6
  "exports": "./lib/main.js",
7
7
  "main": "./lib/main.js",
8
+ "types": "./lib.main.d.ts",
8
9
  "files": [
9
10
  "lib/**/*.js"
10
11
  ],
11
12
  "author": "Netlify Inc.",
12
13
  "scripts": {
13
- "prepublishOnly": "cd ../../ && npm run prepublishOnly",
14
- "build": "cp -a src lib/"
14
+ "prebuild": "rm -rf lib",
15
+ "build": "tsc",
16
+ "test": "ava",
17
+ "test:ci": "c8 -r lcovonly -r text -r json ava"
15
18
  },
16
19
  "keywords": [
17
20
  "nodejs",
@@ -57,10 +60,14 @@
57
60
  "readdirp": "^3.4.0"
58
61
  },
59
62
  "devDependencies": {
63
+ "@types/node": "^14.18.31",
60
64
  "ava": "^4.0.0",
61
- "tmp-promise": "^3.0.0"
65
+ "c8": "^7.12.0",
66
+ "tmp-promise": "^3.0.0",
67
+ "typescript": "^4.8.4"
62
68
  },
63
69
  "engines": {
64
- "node": "^12.20.0 || ^14.14.0 || >=16.0.0"
65
- }
70
+ "node": "^14.16.0 || >=16.0.0"
71
+ },
72
+ "gitHead": "c4502f1c112e7f33d5e6fa053bfbe7dabdfe0160"
66
73
  }