pagefind 1.5.1

Implement search on any static website.
Documentation
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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
use std::io::Write;
use std::path::PathBuf;
use std::time::Duration;

use crate::index::PagefindIndexes;
use crate::{SearchOptions, PAGEFIND_VERSION};
use flate2::write::GzEncoder; // TODO: Replace flate2 with async-compression since we
use flate2::Compression; //   // require that crate for the input compression anyway.
use futures::future::join_all;
use hashbrown::HashMap;
use include_dir::{include_dir, Dir};
use minifier::js::minify;
use tokio::fs::{create_dir_all, File};
use tokio::io::AsyncWriteExt;
use tokio::time::sleep;

mod entry;

const GENERIC_WEB_WASM: &[u8] = include_bytes!(concat!(
    env!("CARGO_MANIFEST_DIR"),
    "/vendor/wasm/pagefind_web_bg.unknown.",
    env!("CARGO_PKG_VERSION"),
    ".wasm.gz"
));
const WEB_WASM_FILES: Dir<'_> = include_dir!("$CARGO_MANIFEST_DIR/vendor/wasm");

const WEB_JS: &str = include_str!(concat!(
    env!("CARGO_MANIFEST_DIR"),
    "/vendor/pagefind_web.",
    env!("CARGO_PKG_VERSION"),
    ".js"
));
const WEB_UI_JS: &[u8] = include_bytes!(concat!(
    env!("CARGO_MANIFEST_DIR"),
    "/vendor/pagefind_ui.",
    env!("CARGO_PKG_VERSION"),
    ".js"
));
const WEB_UI_CSS: &[u8] = include_bytes!(concat!(
    env!("CARGO_MANIFEST_DIR"),
    "/vendor/pagefind_ui.",
    env!("CARGO_PKG_VERSION"),
    ".css"
));
const WEB_MODULAR_UI_JS: &[u8] = include_bytes!(concat!(
    env!("CARGO_MANIFEST_DIR"),
    "/vendor/pagefind_modular_ui.",
    env!("CARGO_PKG_VERSION"),
    ".js"
));
const WEB_MODULAR_UI_CSS: &[u8] = include_bytes!(concat!(
    env!("CARGO_MANIFEST_DIR"),
    "/vendor/pagefind_modular_ui.",
    env!("CARGO_PKG_VERSION"),
    ".css"
));
const COMPONENT_UI_JS: &[u8] = include_bytes!(concat!(
    env!("CARGO_MANIFEST_DIR"),
    "/vendor/pagefind_component_ui.",
    env!("CARGO_PKG_VERSION"),
    ".js"
));
const COMPONENT_UI_CSS: &[u8] = include_bytes!(concat!(
    env!("CARGO_MANIFEST_DIR"),
    "/vendor/pagefind_component_ui.",
    env!("CARGO_PKG_VERSION"),
    ".css"
));
const SEARCH_JS: &str = include_str!(concat!(
    env!("CARGO_MANIFEST_DIR"),
    "/vendor/pagefind_public_search_api.",
    env!("CARGO_PKG_VERSION"),
    ".js"
));
const HIGHLIGHT_JS: &[u8] = include_bytes!(concat!(
    env!("CARGO_MANIFEST_DIR"),
    "/vendor/pagefind_highlight.",
    env!("CARGO_PKG_VERSION"),
    ".js"
));
const WORKER_JS: &[u8] = include_bytes!(concat!(
    env!("CARGO_MANIFEST_DIR"),
    "/vendor/pagefind_worker.",
    env!("CARGO_PKG_VERSION"),
    ".js"
));

pub struct LanguageMeta {
    pub page_count: usize,
    pub language: String,
    pub hash: String,
    pub wasm: Option<String>,
}

pub async fn write_common_to_disk(
    language_indexes: Vec<LanguageMeta>,
    output_playground: bool,
    outdir: &PathBuf,
    options: &SearchOptions,
) {
    write_common(language_indexes, output_playground, outdir, options, false).await;
}

pub async fn write_common_to_memory(
    language_indexes: Vec<LanguageMeta>,
    output_playground: bool,
    outdir: &PathBuf,
    options: &SearchOptions,
) -> Vec<SyntheticFile> {
    write_common(language_indexes, output_playground, outdir, options, true)
        .await
        .unwrap()
}

async fn write_common(
    language_indexes: Vec<LanguageMeta>,
    output_playground: bool,
    outdir: &PathBuf,
    options: &SearchOptions,
    synthetic: bool,
) -> Option<Vec<SyntheticFile>> {
    let js_version = format!("const pagefind_version = \"{PAGEFIND_VERSION}\";");
    let mut js = vec![];
    minify(&format!("{js_version}\n{WEB_JS}\n{SEARCH_JS}"))
        .write(&mut js)
        .expect("Minifying Pagefind JS failed");

    let mut worker_js = vec![];
    minify(&format!(
        "{js_version}\n{WEB_JS}\n{}",
        String::from_utf8_lossy(WORKER_JS)
    ))
    .write(&mut worker_js)
    .expect("Minifying Pagefind Worker JS failed");

    let entry_meta = entry::PagefindEntryMeta {
        version: PAGEFIND_VERSION,
        languages: HashMap::from_iter(language_indexes.into_iter().map(|i| {
            (
                i.language,
                entry::PagefindEntryLanguage {
                    hash: i.hash,
                    wasm: i.wasm,
                    page_count: i.page_count,
                },
            )
        })),
        include_characters: options.include_characters.clone(),
    };
    let encoded_entry_meta = serde_json::to_string(&entry_meta).unwrap();

    let write_behavior = if synthetic {
        WriteBehavior::Synthetic
    } else {
        WriteBehavior::Disk
    };

    let mut files = vec![
        write(
            outdir.join("pagefind.js"),
            vec![&js],
            Compress::None,
            write_behavior,
        ),
        write(
            outdir.join("pagefind-highlight.js"),
            vec![HIGHLIGHT_JS],
            Compress::None,
            write_behavior,
        ),
        write(
            outdir.join("pagefind-worker.js"),
            vec![&worker_js],
            Compress::None,
            write_behavior,
        ),
        write(
            outdir.join("pagefind-ui.js"),
            vec![WEB_UI_JS],
            Compress::None,
            write_behavior,
        ),
        write(
            outdir.join("pagefind-ui.css"),
            vec![WEB_UI_CSS],
            Compress::None,
            write_behavior,
        ),
        write(
            outdir.join("pagefind-modular-ui.js"),
            vec![WEB_MODULAR_UI_JS],
            Compress::None,
            write_behavior,
        ),
        write(
            outdir.join("pagefind-modular-ui.css"),
            vec![WEB_MODULAR_UI_CSS],
            Compress::None,
            write_behavior,
        ),
        write(
            outdir.join("pagefind-component-ui.js"),
            vec![COMPONENT_UI_JS],
            Compress::None,
            write_behavior,
        ),
        write(
            outdir.join("pagefind-component-ui.css"),
            vec![COMPONENT_UI_CSS],
            Compress::None,
            write_behavior,
        ),
        write(
            outdir.join("wasm.unknown.pagefind"),
            vec![GENERIC_WEB_WASM],
            Compress::None,
            write_behavior,
        ),
        write(
            outdir.join("pagefind-entry.json"),
            vec![encoded_entry_meta.as_bytes()],
            Compress::None,
            write_behavior,
        ),
    ];

    if output_playground {
        files.extend([
            write(
                outdir.join("playground/index.html"),
                vec![crate::playground::PLAYGROUND_HTML.as_bytes()],
                Compress::None,
                write_behavior,
            ),
            write(
                outdir.join("playground/pagefind-playground.js"),
                vec![crate::playground::PLAYGROUND_JS.as_bytes()],
                Compress::None,
                write_behavior,
            ),
            write(
                outdir.join("playground/pagefind-playground.css"),
                vec![crate::playground::PLAYGROUND_CSS.as_bytes()],
                Compress::None,
                write_behavior,
            ),
        ]);
    }

    let output_files = join_all(files).await;

    if synthetic {
        Some(output_files.into_iter().flatten().collect())
    } else {
        None
    }
}

impl PagefindIndexes {
    fn lang_wasm_path(&self) -> Option<String> {
        let base_language = self.language.split('-').next().unwrap();
        let wasm_path = format!(
            "pagefind_web_bg.{}.{}.wasm.gz",
            base_language,
            env!("CARGO_PKG_VERSION")
        );

        if WEB_WASM_FILES.contains(&wasm_path) {
            Some(wasm_path)
        } else {
            None
        }
    }

    pub fn get_lang_meta(&self, options: &SearchOptions) -> LanguageMeta {
        let mut wasm_file = None;

        if self.language != "unknown" {
            if self.lang_wasm_path().is_some() {
                wasm_file = Some(self.language.to_string());
            } else {
                options.logger.v_warn(format!(
                    "Note: Pagefind doesn't support stemming for the language {}. \n\
                    Search will still work, but will not match across root words.",
                    self.language
                ));
            }
        }

        LanguageMeta {
            page_count: self.fragments.len(),
            language: self.language.clone(),
            hash: self.meta_index.0.clone(),
            wasm: wasm_file,
        }
    }

    pub async fn write_files_to_disk(&self, options: &SearchOptions, outdir: &PathBuf) {
        self.write_files(options, outdir, false).await;
    }

    pub async fn write_files_to_memory(
        &self,
        options: &SearchOptions,
        outdir: &PathBuf,
    ) -> Vec<SyntheticFile> {
        self.write_files(options, outdir, true).await.unwrap()
    }

    async fn write_files(
        &self,
        options: &SearchOptions,
        outdir: &PathBuf,
        synthetic: bool,
    ) -> Option<Vec<SyntheticFile>> {
        let immutable_write_behaviour = if synthetic {
            WriteBehavior::Synthetic
        } else {
            WriteBehavior::Immutable
        };

        let mut files = vec![write(
            outdir.join(format!("pagefind.{}.pf_meta", &self.meta_index.0)),
            vec![&self.meta_index.1],
            Compress::GZ,
            immutable_write_behaviour,
        )];

        if self.language != "unknown" {
            if let Some(wasm_path) = self.lang_wasm_path() {
                files.push(write(
                    outdir.join(format!("wasm.{}.pagefind", self.language)),
                    vec![WEB_WASM_FILES
                        .get_file(wasm_path)
                        .expect("WASM should exist")
                        .contents()],
                    Compress::None,
                    if synthetic {
                        WriteBehavior::Synthetic
                    } else {
                        WriteBehavior::Disk
                    },
                ));
            } else {
                options.logger.v_warn(format!(
                    "Note: Pagefind doesn't support stemming for the language {}. \n\
                    Search will still work, but will not match across root words.",
                    self.language
                ));
            }
        }

        files.extend(self.fragments.iter().map(|(hash, fragment)| {
            write(
                outdir.join(format!("fragment/{}.pf_fragment", hash)),
                vec![fragment.as_bytes()],
                Compress::GZ,
                immutable_write_behaviour,
            )
        }));

        files.extend(self.word_indexes.iter().map(|(hash, index)| {
            write(
                outdir.join(format!("index/{}.pf_index", hash)),
                vec![index],
                Compress::GZ,
                immutable_write_behaviour,
            )
        }));

        files.extend(self.filter_indexes.iter().map(|(hash, index)| {
            write(
                outdir.join(format!("filter/{}.pf_filter", hash)),
                vec![index],
                Compress::GZ,
                immutable_write_behaviour,
            )
        }));

        let output_files = join_all(files).await;
        if synthetic {
            Some(output_files.into_iter().flatten().collect())
        } else {
            None
        }
    }
}

#[derive(Copy, Clone)]
enum Compress {
    GZ,
    None,
}

#[derive(Copy, Clone)]
enum WriteBehavior {
    Synthetic,
    Immutable,
    Disk,
}

#[derive(Clone)]
pub struct SyntheticFile {
    pub filename: PathBuf,
    pub contents: Vec<u8>,
}

async fn write(
    filename: PathBuf,
    content_chunks: Vec<&[u8]>,
    compression: Compress,
    write_behavior: WriteBehavior,
) -> Option<SyntheticFile> {
    let mut file = None;

    match write_behavior {
        WriteBehavior::Synthetic => {}
        // For "immutable" (hashed) files, don't re-write them as the contents _should_ be unchanged.
        WriteBehavior::Immutable if filename.exists() => return None,
        WriteBehavior::Immutable | WriteBehavior::Disk => {
            if let Some(parent) = filename.parent() {
                create_dir_all(parent).await.unwrap();
            }

            let mut output_file = File::create(&filename).await;
            while output_file.is_err() {
                sleep(Duration::from_millis(100)).await;
                output_file = File::create(&filename).await;
            }
            file = output_file.ok();
        }
    };

    match compression {
        Compress::GZ => {
            let mut gz = GzEncoder::new(Vec::new(), Compression::best());
            for chunk in content_chunks {
                gz.write_all(b"pagefind_dcd").unwrap();
                gz.write_all(chunk).unwrap();
            }
            if let Ok(contents) = gz.finish() {
                if let Some(mut file) = file {
                    file.write_all(&contents).await.unwrap();
                } else {
                    return Some(SyntheticFile { filename, contents });
                }
            }
            None
        }
        Compress::None => {
            if let Some(mut file) = file {
                for chunk in content_chunks {
                    file.write_all(chunk).await.unwrap();
                }
                None
            } else {
                return Some(SyntheticFile {
                    filename,
                    contents: content_chunks.into_iter().flatten().cloned().collect(),
                });
            }
        }
    }
}