-
Notifications
You must be signed in to change notification settings - Fork 53
Expand file tree
/
Copy pathcache.js
More file actions
164 lines (132 loc) · 4.35 KB
/
cache.js
File metadata and controls
164 lines (132 loc) · 4.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
// Import Node.js Dependencies
import os from "node:os";
import path from "node:path";
import fs from "node:fs";
// Import Third-party Dependencies
import cacache from "cacache";
// Import Internal Dependencies
import { logger } from "./logger.js";
// CONSTANTS
const kConfigCache = "___config";
const kPayloadsCache = "___payloads";
const kPayloadsPath = path.join(os.homedir(), ".nsecure", "payloads");
const kMaxPayloads = 3;
export const CACHE_PATH = path.join(os.tmpdir(), "nsecure-cli");
export const DEFAULT_PAYLOAD_PATH = path.join(process.cwd(), "nsecure-result.json");
class _AppCache {
constructor() {
fs.mkdirSync(kPayloadsPath, { recursive: true });
}
async updateConfig(newValue) {
await cacache.put(CACHE_PATH, kConfigCache, JSON.stringify(newValue));
}
async getConfig() {
const { data } = await cacache.get(CACHE_PATH, kConfigCache);
return JSON.parse(data.toString());
}
updatePayload(pkg, payload) {
fs.writeFileSync(path.join(kPayloadsPath, pkg.replaceAll("/", "-")), JSON.stringify(payload));
}
async getPayload(pkg) {
try {
return JSON.parse(fs.readFileSync(path.join(kPayloadsPath, pkg.replaceAll("/", "-")), "utf-8"));
}
catch (err) {
logger.error(`[cache|get](pkg: ${pkg}|cache: not found)`);
throw err;
}
}
async getPayloadOrNull(pkg) {
try {
return await this.getPayload(pkg);
}
catch {
return null;
}
}
async updatePayloadsList(payloadsList) {
await cacache.put(CACHE_PATH, kPayloadsCache, JSON.stringify(payloadsList));
}
async payloadsList() {
try {
const { data } = await cacache.get(CACHE_PATH, kPayloadsCache);
return JSON.parse(data.toString());
}
catch (err) {
logger.error(`[cache|get](cache: not found)`);
throw err;
}
}
async #initDefaultPayloadsList() {
const payload = JSON.parse(fs.readFileSync(DEFAULT_PAYLOAD_PATH, "utf-8"));
const version = Object.keys(payload.dependencies[payload.rootDependencyName].versions)[0];
const formatted = `${payload.rootDependencyName}@${version}`;
const payloadsList = {
lru: [formatted],
current: formatted,
older: [],
lastUsed: {
[formatted]: Date.now()
},
root: formatted
};
logger.info(`[cache|init](dep: ${formatted}|version: ${version}|rootDependencyName: ${payload.rootDependencyName})`);
await cacache.put(CACHE_PATH, kPayloadsCache, JSON.stringify(payloadsList));
this.updatePayload(formatted, payload);
}
async initPayloadsList(options = {}) {
const { logging = true } = options;
try {
// prevent re-initialization of the cache
await cacache.get(CACHE_PATH, kPayloadsCache);
return;
}
catch {
// Do nothing.
}
const packagesInFolder = fs.readdirSync(kPayloadsPath);
if (packagesInFolder.length === 0) {
await this.#initDefaultPayloadsList();
return;
}
if (logging) {
logger.info(`[cache|init](packagesInFolder: ${packagesInFolder})`);
}
await cacache.put(CACHE_PATH, kPayloadsCache, JSON.stringify({ older: packagesInFolder, current: null, lru: [] }));
}
removePayload(pkg) {
fs.rmSync(path.join(kPayloadsPath, pkg.replaceAll("/", "-")));
}
async removeLastLRU() {
const { lru, lastUsed, older, root } = await this.payloadsList();
if (lru.length < kMaxPayloads) {
return { lru, older, lastUsed, root };
}
const packageToBeRemoved = Object.keys(lastUsed)
.filter((key) => lru.includes(key))
.sort((a, b) => lastUsed[a] - lastUsed[b])[0];
return {
lru: lru.filter((pkg) => pkg !== packageToBeRemoved),
older: [...older, packageToBeRemoved],
lastUsed,
root
};
}
async setRootPayload(payload, options) {
const { logging = true } = options;
const version = Object.keys(payload.dependencies[payload.rootDependencyName].versions)[0];
const pkg = `${payload.rootDependencyName}@${version}`;
this.updatePayload(pkg, payload);
await this.initPayloadsList({ logging });
const { lru, older, lastUsed } = await this.removeLastLRU();
const updatedPayloadsCache = {
lru: [...new Set([...lru, pkg])],
older,
lastUsed: { ...lastUsed, [pkg]: Date.now() },
current: pkg,
root: pkg
};
await this.updatePayloadsList(updatedPayloadsCache);
}
}
export const appCache = new _AppCache();