dbg_swc/es/minifier/next/
check_size.rs

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
use std::{
    cmp::Reverse,
    env::current_dir,
    fs::{self, create_dir_all, read_dir, remove_dir_all},
    path::{Path, PathBuf},
    process::{Command, Stdio},
    sync::Arc,
};

use anyhow::{bail, Context, Result};
use clap::Args;
use dialoguer::{console::Term, theme::ColorfulTheme, Select};
use rayon::{
    prelude::{IntoParallelIterator, ParallelBridge, ParallelIterator},
    str::ParallelString,
};
use serde::{de::DeserializeOwned, Deserialize};
use swc_common::{errors::HANDLER, SourceMap, GLOBALS};
use tracing::info;

use crate::util::{
    gzipped_size, make_pretty,
    minifier::{get_minified, get_terser_output},
    print_js, wrap_task,
};

#[derive(Debug, Args)]
pub struct CheckSizeCommand {
    /// The directory store inputs to the swc minifier.
    #[clap(long, short = 'w', default_value = ".next/dbg-swc/minifier-check-size")]
    workspace: PathBuf,

    /// Rerun `npm run build` even if `workspace` is not empty.
    #[clap(long)]
    ensure_fresh: bool,

    /// Show every file, even if the output of swc minifier was smaller.
    #[clap(long)]
    show_all: bool,
}

impl CheckSizeCommand {
    pub fn run(self, cm: Arc<SourceMap>) -> Result<()> {
        let app_dir = current_dir().context("failed to get current directory")?;

        let files = self.store_minifier_inputs(&app_dir)?;

        info!("Running minifier");

        let mut files = GLOBALS.with(|globals| {
            HANDLER.with(|handler| {
                files
                    .into_par_iter()
                    .map(|file| {
                        GLOBALS.set(globals, || {
                            HANDLER.set(handler, || self.minify_file(cm.clone(), &file))
                        })
                    })
                    .collect::<Result<Vec<_>>>()
            })
        })?;

        if !self.show_all {
            info!(
                "Skiping files which are smaller than terser output, as `--show-all` is not \
                 specified"
            );

            files.retain(|f| f.swc > f.terser);
        }
        files.sort_by_key(|f| Reverse(f.swc as i32 - f.terser as i32));

        for file in &files {
            println!(
                "{}: {} bytes (swc) vs {} bytes (terser)",
                file.path
                    .strip_prefix(self.workspace.join("inputs"))
                    .unwrap()
                    .display(),
                file.swc,
                file.terser
            );
        }

        if !files.is_empty() {
            println!("Select a file to open diff");
        }

        let items = files
            .iter()
            .map(|f| {
                format!(
                    "{}: Diff: {} bytes; {} bytes (swc) vs {} bytes (terser)",
                    f.path
                        .strip_prefix(self.workspace.join("inputs"))
                        .unwrap()
                        .display(),
                    f.swc as i32 - f.terser as i32,
                    f.swc,
                    f.terser,
                )
            })
            .collect::<Vec<_>>();

        let selection = Select::with_theme(&ColorfulTheme::default())
            .items(&items)
            .default(0)
            .interact_on_opt(&Term::stderr())?;

        if let Some(selection) = selection {
            let swc_path = self.workspace.join("swc.output.js");
            let terser_path = self.workspace.join("terser.output.js");

            let swc = get_minified(cm.clone(), &files[selection].path, true, false)?;

            std::fs::write(&swc_path, print_js(cm, &swc.module, true)?.as_bytes())
                .context("failed to write swc.output.js")?;

            make_pretty(&swc_path)?;

            let terser = get_terser_output(&files[selection].path, true, false)?;

            std::fs::write(&terser_path, terser.as_bytes())
                .context("failed to write terser.output.js")?;

            make_pretty(&terser_path)?;

            {
                let mut c = Command::new("code");
                c.arg("--diff");
                c.arg(swc_path);
                c.arg(terser_path);
                c.output().context("failed to run vscode")?;
            }
        }

        Ok(())
    }

    /// Invokes `npm run build` with appropriate environment variables, and
    /// store the result in `self.workspace`.
    fn store_minifier_inputs(&self, app_dir: &Path) -> Result<Vec<PathBuf>> {
        wrap_task(|| {
            if !self.ensure_fresh
                && self.workspace.is_dir()
                && read_dir(self.workspace.join("inputs"))
                    .context("failed to read workspace directory")?
                    .count()
                    != 0
            {
                info!(
                    "Skipping `npm run build` because the cache exists and `--ensure-fresh` is \
                     not set"
                );

                return get_all_files(&self.workspace.join("inputs"))
                    .context("failed to get files from cache");
            }

            let files = self.build_app(app_dir)?;

            files
                .into_par_iter()
                .map(|file| {
                    let file_path = self.workspace.join("inputs").join(file.name);
                    create_dir_all(file_path.parent().unwrap())
                        .context("failed to create a directory")?;
                    fs::write(&file_path, file.source).context("failed to write file")?;

                    Ok(file_path)
                })
                .collect::<Result<_>>()
        })
        .context("failed to extract inputs for the swc minifier")
    }

    /// Invokes `npm run build` and extacts the inputs for the swc minifier.
    fn build_app(&self, app_dir: &Path) -> Result<Vec<InputFile>> {
        wrap_task(|| {
            info!("Running `npm run build`");

            // Remove cache
            let _ = remove_dir_all(app_dir.join(".next"));

            let mut c = Command::new("npm");
            c.current_dir(app_dir);
            c.env("FORCE_COLOR", "3");
            c.env("NEXT_DEBUG_MINIFY", "1");
            c.arg("run").arg("build");

            c.stderr(Stdio::inherit());

            let output = c
                .output()
                .context("failed to get output of `npm run build`")?;

            if !output.status.success() {
                bail!("`npm run build` failed");
            }

            let output = String::from_utf8_lossy(&output.stdout);

            output
                .par_lines()
                .filter(|line| line.contains("{ name:"))
                .map(|line| {
                    parse_loose_json::<InputFile>(line).context("failed to parse input file")
                })
                .collect::<Result<_>>()
        })
        .with_context(|| format!("failed to build app in `{}`", app_dir.display()))
    }

    fn minify_file(&self, cm: Arc<SourceMap>, js_file: &Path) -> Result<CompareResult> {
        wrap_task(|| {
            let terser_full =
                get_terser_output(js_file, true, true).context("failed to get terser output")?;

            let swc_full = get_minified(cm.clone(), js_file, true, true)?;
            let swc_full = print_js(cm.clone(), &swc_full.module, true)?;

            Ok(CompareResult {
                terser: gzipped_size(&terser_full),
                swc: gzipped_size(&swc_full),
                path: js_file.to_owned(),
            })
        })
        .with_context(|| format!("failed to minify `{}`", js_file.display()))
    }
}

struct CompareResult {
    path: PathBuf,
    swc: usize,
    terser: usize,
}

#[derive(Deserialize)]
struct InputFile {
    name: String,
    source: String,
}

fn parse_loose_json<T>(s: &str) -> Result<T>
where
    T: DeserializeOwned,
{
    wrap_task(|| {
        let mut c = Command::new("node");

        c.arg("-e");
        c.arg(
            r#"
            function looseJsonParse(obj) {
                return Function('"use strict";return (' + obj + ")")();
            }
            console.log(JSON.stringify(looseJsonParse(process.argv[1])));
            "#,
        );

        c.arg(s);

        c.stderr(Stdio::inherit());

        let json_str = c
            .output()
            .context("failed to parse json loosely using node")?
            .stdout;

        serde_json::from_slice(&json_str).context("failed to parse json")
    })
    .with_context(|| format!("failed to parse loose json: {}", s))
}

fn get_all_files(path: &Path) -> Result<Vec<PathBuf>> {
    if path.is_dir() {
        let v = read_dir(path)
            .with_context(|| format!("failed to read directory at `{}`", path.display()))?
            .par_bridge()
            .map(|entry| get_all_files(&entry?.path()).context("failed get recurse"))
            .collect::<Result<Vec<_>>>()?;

        Ok(v.into_iter().flatten().collect())
    } else {
        Ok(vec![path.to_path_buf()])
    }
}