-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqueryHelpers.js
More file actions
358 lines (314 loc) · 10 KB
/
queryHelpers.js
File metadata and controls
358 lines (314 loc) · 10 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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
const helpers = {
prettifyMap: new Map(),
prettifyJS(sourceStr) {
if (helpers.prettifyMap.has(sourceStr)) {
return helpers.prettifyMap.get(sourceStr);
}
const prettier = require("prettier/standalone");
const prettierPluginBabel = require("prettier/plugins/babel");
const prettierPluginEstree = require("prettier/plugins/estree");
return prettier
.format(sourceStr, {
parser: "babel",
plugins: [prettierPluginBabel, prettierPluginEstree],
})
.then((formatted) => {
helpers.prettifyMap.set(sourceStr, formatted);
return formatted;
});
},
askChatGPTAboutPackages() {
const prompt = `I have a list of JavaScript packages from my React Native bundle (see below). I want to optimize bundle size by identifying similar or redundant packages — such as multiple versions of similar libraries (e.g., lodash, lodash-es, underscore, etc.), duplicate utilities, or overlapping functionality (e.g., date libraries like moment, dayjs, date-fns).
Please do the following:
1. Group similar or overlapping packages together.
2. For each group, suggest which one to keep and which ones to consider removing.
3. For each group, provide a regex string that can be used to filter those packages from the list (e.g., in grep, find, or search tools).
4. Keep the output concise and copy-paste friendly.`;
return `https://chat.openai.com/?prompt=${encodeURIComponent(prompt)}`;
},
plural(count, [singular, plural]) {
return count === 1 ? singular : plural;
},
pluralWithCount(count, [singular, plural]) {
return `${count} ${helpers.plural(count, [singular, plural])}`;
},
pluralBadge(count, [singular, plural], prefix = "") {
return {
text: prefix + count,
postfix: helpers.plural(count, [singular, plural]),
};
},
getHighchartsColors() {
const Highcharts = require("highcharts");
return Highcharts.getOptions().colors;
},
getModulesName(path) {
const modules = path.split("node_modules/");
const lastModule = modules[modules.length - 1];
const [folder, subFolder] = lastModule.split("/");
if (folder.startsWith("@")) {
return `${folder}/${subFolder}`;
}
return folder;
},
getBestNetworkGraphSize(module, params) {
let maxParentDepth = 0;
let itemsCount = 0;
do {
maxParentDepth++;
itemsCount = helpers.getNetworkGraph(module, {
...params,
maxParentDepth,
}).data.length;
if (itemsCount < 10) {
const limit = itemsCount - 1;
return limit > 2 ? limit : 2;
}
} while (maxParentDepth < 6);
return maxParentDepth;
},
getNetworkGraph(
module,
{ maxParentDepth = 2, omitVisitedModules = true } = {},
) {
const queue = [{ module, parentId: "", level: 0 }];
const visited = new Set();
const result = [];
let entryPointPath = null;
const data = [];
while (queue.length > 0) {
const { module: currentModule, parentId, level } = queue.shift();
if (level >= Number(maxParentDepth)) {
break;
}
const id = currentModule.path;
if (omitVisitedModules) {
if (visited.has(id)) {
continue;
}
visited.add(id);
}
if (parentId) {
const isEntryPoint = currentModule.dependents.length === 0;
result.push({ isEntryPoint, id, parentId });
data.push([parentId, id]);
if (isEntryPoint) {
entryPointPath = id;
}
}
if (Array.isArray(currentModule.dependents)) {
for (const dependentModule of currentModule.dependents) {
queue.push({
module: dependentModule,
parentId: id,
level: level + 1,
});
}
}
}
if (!entryPointPath) {
for (const item of result) {
if (item.isEntryPoint) {
entryPointPath = item.id;
break;
}
}
}
return { entryPointPath, data };
},
getExtColor(extName) {
const colors = {
js: "#f1e05a50",
ts: "#2b748950",
tsx: "#2b748950",
json: "#e34c2650",
svg: "#e69f0d50",
css: "#563d7c50",
png: "#e44b2350",
};
return colors[extName] ?? colors["js"];
},
getFileExtension(filename) {
const idx = filename.lastIndexOf(".");
return idx === -1 ? "js" : filename.slice(idx + 1);
},
toFixed(value, fractionDigits = 2) {
return Number(value).toFixed(fractionDigits);
},
percent(value, fractionDigits = 2) {
return (100 * value).toFixed(fractionDigits) + "%";
},
formatBytes(bytes, decimals) {
if (bytes == 0) return "0 Bytes";
const k = 1024,
dm = decimals || 2,
sizes = ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"],
i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + " " + sizes[i];
},
isPackageImport(moduleName) {
return moduleName?.[0] !== ".";
},
// isRuntimeCode(moduleName) {
// return (
// moduleName === "__prelude__" ||
// moduleName.includes("@babel/runtime") ||
// moduleName.includes("metro-runtime") ||
// moduleName.includes("@react-native/js-polyfills")
// );
// },
transformFilesList(files, rootFolder, type) {
const nodeModulesMap = { children: {}, size: 0 };
const sourceCodeMap = { children: {}, size: 0 };
files.forEach(({ path, size }) => {
if (path === "__prelude__") {
path = "node_modules/__prelude__";
}
const shortPath = path.replace(rootFolder + "/", "");
const isNodeModule = shortPath.includes("node_modules/");
const parts = shortenPath(shortPath, nodeModulesMap).split("/");
let current = (isNodeModule ? nodeModulesMap : sourceCodeMap).children;
parts.forEach((part, index) => {
// console.log((" --- xdebug " + index + " ".repeat(50)).substr(0, 40), {
// part,
// parts,
// });
if (!current[part]) {
current[part] = { size: 0, children: {} };
}
if (index === parts.length - 1) {
current[part].size = size;
current[part].path = shortPath;
}
current = current[part].children;
});
});
if (type === "foamtree") {
sumSizes(nodeModulesMap);
sumSizes(sourceCodeMap);
const sourceCodeGroup = toGroups(sourceCodeMap, "Source Code");
const nodeModulesGroup = nodeModulesMap?.children?.node_modules
? toGroups(nodeModulesMap.children.node_modules, "node_modules")
: {};
if (!sourceCodeGroup.groups) {
return nodeModulesGroup;
}
if (!nodeModulesGroup.groups) {
return nodeModulesGroup;
}
const topLevelNode = { groups: [sourceCodeGroup, nodeModulesGroup] };
topLevelNode.weight = topLevelNode.groups.reduce(
(acc, group) => acc + group.weight,
0,
);
return topLevelNode;
}
if (type === "highcharts-treemap") {
const ROOT_ID_1 = "~";
const ROOT_ID_2 = ".";
return [
{ id: ROOT_ID_1, name: "node_modules" },
{ id: ROOT_ID_2, name: "Source Code" },
]
.concat(flattenTree(nodeModulesMap.children.node_modules, ROOT_ID_1))
.concat(flattenTree(sourceCodeMap, ROOT_ID_2));
}
throw new Error("Unsupported type: " + type);
},
};
function flattenTree(
node,
parentId,
prevWasSkipped = false,
lvl = 0,
result = [],
overrideParentId,
) {
const nodeChildrenCount = Object.keys(node.children);
for (const key of nodeChildrenCount) {
const childNode = node.children[key];
const childId = parentId + "/" + key;
const childrenCount = Object.keys(childNode.children).length;
const hasChildren = childrenCount > 0;
const item = {
id: childId,
name: prevWasSkipped ? parentId : key,
parent: overrideParentId ?? parentId,
};
if (!hasChildren) {
item.value = childNode.size;
}
if (lvl === 0) {
item.color = Highcharts.getOptions().colors[randomInt(0, 9)];
}
const skipThisNode = nodeChildrenCount.length === 1 && childrenCount === 1;
if (!skipThisNode) {
result.push(item);
}
flattenTree(
childNode,
childId,
skipThisNode,
lvl + 1,
result,
skipThisNode ? (overrideParentId ?? parentId) : undefined,
);
}
return result;
}
function sumSizes(node) {
const isFile = Object.keys(node.children).length === 0;
let totalFiles = isFile ? 1 : 0;
let totalSize = node.size || 0;
for (const key in node.children) {
const result = sumSizes(node.children[key]);
totalSize += result.totalSize;
totalFiles += result.totalFiles;
}
node.type = isFile ? "file" : "folder";
node.size = totalSize;
node.files = totalFiles;
return { totalSize, totalFiles };
}
function toGroups(node, label) {
const keys = Object.keys(node.children);
const common = {
label,
weight: node.size,
files: node.files,
type: node.type,
size: helpers.formatBytes(node.size),
};
if (keys.length === 0) {
// File
return common;
}
// Folder
return Object.assign(common, {
groups: keys.map((key) => toGroups(node.children[key], key)),
});
}
function randomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
const nm = "node_modules/";
function shortenPath(path, nodeModulesMap) {
let index = path.lastIndexOf(nm);
if (index > 0) {
const pathWithoutNestedNM = path.slice(index);
// Find the package name after "node_modules/"
const firstSlash = pathWithoutNestedNM.indexOf("/");
const secondSlash = pathWithoutNestedNM.indexOf("/", firstSlash + 1);
const pkgName =
secondSlash === -1
? pathWithoutNestedNM.slice(firstSlash + 1)
: pathWithoutNestedNM.slice(firstSlash + 1, secondSlash);
if (nodeModulesMap?.children?.node_modules?.children?.[pkgName]) {
const parentPackage = helpers.getModulesName(path.slice(0, index));
return nm + parentPackage + " ~ " + pathWithoutNestedNM.slice(nm.length);
}
return pathWithoutNestedNM;
}
return path;
}
module.exports = helpers;