UNPKG

2.63 kBJavaScriptView Raw
1'use strict'
2
3const { writeFile, readFile } = require('fs')
4const { dirname } = require('path')
5const { promisify } = require('util')
6
7const del = require('del')
8const makeDir = require('make-dir')
9const pathExists = require('path-exists')
10
11const { getExpires, checkExpires } = require('./expire')
12const { getHash } = require('./hash')
13
14const pWriteFile = promisify(writeFile)
15const pReadFile = promisify(readFile)
16
17// Retrieve cache manifest of a file to cache, which contains the file/directory
18// contents hash and the `expires` date.
19const getManifestInfo = async function ({ cachePath, move, ttl, digests }) {
20 const manifestPath = getManifestPath(cachePath)
21 const expires = getExpires(ttl)
22 const hash = await getHash(digests, move)
23 const manifest = { expires, hash }
24 const manifestString = `${JSON.stringify(manifest, null, 2)}\n`
25 const identical = await isIdentical({ hash, manifestPath, manifestString })
26 return { manifestInfo: { manifestPath, manifestString }, identical }
27}
28
29// Whether the cache manifest has changed
30const isIdentical = async function ({ hash, manifestPath, manifestString }) {
31 if (hash === undefined || !(await pathExists(manifestPath))) {
32 return false
33 }
34
35 const oldManifestString = await pReadFile(manifestPath, 'utf8')
36 return oldManifestString === manifestString
37}
38
39// Persist the cache manifest to filesystem
40const writeManifest = async function ({ manifestPath, manifestString }) {
41 await makeDir(dirname(manifestPath))
42 await pWriteFile(manifestPath, manifestString)
43}
44
45// Remove the cache manifest from filesystem
46const removeManifest = async function (cachePath) {
47 const manifestPath = getManifestPath(cachePath)
48 await del(manifestPath, { force: true })
49}
50
51// Retrieve the cache manifest filepath
52const getManifestPath = function (cachePath) {
53 return `${cachePath}${CACHE_EXTENSION}`
54}
55
56const isManifest = function (filePath) {
57 return filePath.endsWith(CACHE_EXTENSION)
58}
59
60const CACHE_EXTENSION = '.netlify.cache.json'
61
62// Check whether a file/directory is expired by checking its cache manifest
63const isExpired = async function (cachePath) {
64 const manifestPath = getManifestPath(cachePath)
65 if (!(await pathExists(manifestPath))) {
66 return false
67 }
68
69 const { expires } = await readManifest(cachePath)
70 return checkExpires(expires)
71}
72
73const readManifest = async function (cachePath) {
74 const manifestPath = getManifestPath(cachePath)
75 const manifestString = await pReadFile(manifestPath, 'utf8')
76 const manifest = JSON.parse(manifestString)
77 return manifest
78}
79
80module.exports = { getManifestInfo, writeManifest, removeManifest, isManifest, isExpired }