@@ -8,6 +8,50 @@ import { MachinePreset } from "../schemas/common.js";
88 * @param {number } [overhead=0.2] - The memory overhead factor (0.2 = 20% reserved for system operations)
99 * @returns {number } The calculated max old space size in MiB
1010 */
11- export function maxOldSpaceSizeForMachine ( machine : MachinePreset , overhead = 0.2 ) {
12- return machine . memory * 1_024 * ( 1 - overhead ) ;
11+ export function maxOldSpaceSizeForMachine ( machine : MachinePreset , overhead : number = 0.2 ) : number {
12+ return Math . round ( machine . memory * 1_024 * ( 1 - overhead ) ) ;
13+ }
14+
15+ /**
16+ * Returns a flag to be used for `--max-old-space-size`. It is in MiB.
17+ * Setting this correctly means V8 spends more times running Garbage Collection (GC).
18+ * It won't eliminate crashes but it will help avoid them.
19+ * @param {MachinePreset } machine - The machine preset configuration containing memory specifications
20+ * @param {number } [overhead=0.2] - The memory overhead factor (0.2 = 20% reserved for system operations)
21+ * @returns {string } The calculated max old space size flag
22+ */
23+ export function maxOldSpaceSizeFlag ( machine : MachinePreset , overhead : number = 0.2 ) : string {
24+ return `--max-old-space-size=${ maxOldSpaceSizeForMachine ( machine , overhead ) } ` ;
25+ }
26+
27+ /**
28+ * Takes the existing NODE_OPTIONS value, removes any existing max-old-space-size flag, and adds a new one.
29+ * @param {string | undefined } existingOptions - The existing NODE_OPTIONS value
30+ * @param {MachinePreset } machine - The machine preset configuration containing memory specifications
31+ * @param {number } [overhead=0.2] - The memory overhead factor (0.2 = 20% reserved for system operations)
32+ * @returns {string } The updated NODE_OPTIONS value with the new max-old-space-size flag
33+ */
34+ export function nodeOptionsWithMaxOldSpaceSize (
35+ existingOptions : string | undefined ,
36+ machine : MachinePreset ,
37+ overhead : number = 0.2
38+ ) : string {
39+ let options = existingOptions ?? "" ;
40+
41+ //remove existing max-old-space-size flag
42+ options = options . replace ( / - - m a x - o l d - s p a c e - s i z e = \d + / g, "" ) . trim ( ) ;
43+
44+ //get max-old-space-size flag
45+ const flag = maxOldSpaceSizeFlag ( machine , overhead ) ;
46+
47+ return normalizeCommandLineFlags ( options ? `${ options } ${ flag } ` : flag ) ;
48+ }
49+
50+ /**
51+ * Normalizes spaces in a string of command line flags, ensuring single spaces between flags
52+ * @param {string } input - The string to normalize
53+ * @returns {string } The normalized string with single spaces between flags
54+ */
55+ function normalizeCommandLineFlags ( input : string ) : string {
56+ return input . split ( / \s + / ) . filter ( Boolean ) . join ( " " ) ;
1357}
0 commit comments