1 | 'use strict'
|
2 |
|
3 | const { writeFile, readFile } = require('fs')
|
4 | const { dirname } = require('path')
|
5 | const { promisify } = require('util')
|
6 |
|
7 | const del = require('del')
|
8 | const makeDir = require('make-dir')
|
9 | const pathExists = require('path-exists')
|
10 |
|
11 | const { getExpires, checkExpires } = require('./expire')
|
12 | const { getHash } = require('./hash')
|
13 |
|
14 | const pWriteFile = promisify(writeFile)
|
15 | const pReadFile = promisify(readFile)
|
16 |
|
17 |
|
18 |
|
19 | const 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 |
|
30 | const 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 |
|
40 | const writeManifest = async function ({ manifestPath, manifestString }) {
|
41 | await makeDir(dirname(manifestPath))
|
42 | await pWriteFile(manifestPath, manifestString)
|
43 | }
|
44 |
|
45 |
|
46 | const removeManifest = async function (cachePath) {
|
47 | const manifestPath = getManifestPath(cachePath)
|
48 | await del(manifestPath, { force: true })
|
49 | }
|
50 |
|
51 |
|
52 | const getManifestPath = function (cachePath) {
|
53 | return `${cachePath}${CACHE_EXTENSION}`
|
54 | }
|
55 |
|
56 | const isManifest = function (filePath) {
|
57 | return filePath.endsWith(CACHE_EXTENSION)
|
58 | }
|
59 |
|
60 | const CACHE_EXTENSION = '.netlify.cache.json'
|
61 |
|
62 |
|
63 | const 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 |
|
73 | const 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 |
|
80 | module.exports = { getManifestInfo, writeManifest, removeManifest, isManifest, isExpired }
|