hwp2md 0.5.0

HWP/HWPX ↔ Markdown bidirectional converter
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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
use super::*;

// ── helpers ──────────────────────────────────────────────────────────────

/// Minimal 8-byte PNG magic header used as fake image data in tests.
const PNG_MAGIC: &[u8] = &[0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];

/// Minimal 3-byte JPEG magic header.
const JPEG_MAGIC: &[u8] = &[0xFF, 0xD8, 0xFF];

/// Write a document to a temp HWPX and return the list of ZIP entry names.
fn write_to_zip_entries(doc: &Document) -> Vec<String> {
    let tmp = tempfile::NamedTempFile::new().expect("tmp file");
    write_hwpx(doc, tmp.path(), None).expect("write_hwpx");
    let file = std::fs::File::open(tmp.path()).expect("open zip");
    let mut archive = zip::ZipArchive::new(file).expect("parse zip");
    (0..archive.len())
        .map(|i| archive.by_index(i).expect("entry").name().to_owned())
        .collect()
}

/// Write a document to a temp HWPX, open the ZIP, and read a named entry's bytes.
fn read_zip_entry_bytes(doc: &Document, entry_name: &str) -> Vec<u8> {
    let tmp = tempfile::NamedTempFile::new().expect("tmp file");
    write_hwpx(doc, tmp.path(), None).expect("write_hwpx");
    let file = std::fs::File::open(tmp.path()).expect("open zip");
    let mut archive = zip::ZipArchive::new(file).expect("parse zip");
    let mut entry = archive.by_name(entry_name).expect("entry not found");
    let mut buf = Vec::new();
    entry.read_to_end(&mut buf).expect("read entry");
    buf
}

/// Write a document to a temp HWPX, open the ZIP, and read a named text entry.
fn read_zip_entry_text(doc: &Document, entry_name: &str) -> String {
    let bytes = read_zip_entry_bytes(doc, entry_name);
    String::from_utf8(bytes).expect("UTF-8 entry")
}

// ── Unit tests: collect_image_assets ─────────────────────────────────────

#[test]
fn collect_image_assets_local_file_reads_bytes_and_maps_src() {
    // Write a fake PNG to disk and make the IR point to it.
    let dir = tempfile::tempdir().expect("tmp dir");
    let img_path = dir.path().join("test.png");
    std::fs::write(&img_path, PNG_MAGIC).expect("write png");

    let src = img_path.to_str().expect("valid utf-8 path").to_owned();
    let doc = Document {
        metadata: Metadata::default(),
        sections: vec![Section {
            blocks: vec![Block::Image {
                src: src.clone(),
                alt: "test image".into(),
            }],

            page_layout: None,
            ..Default::default()
        }],
        assets: Vec::new(),
    };

    let (map, resolved) = collect_image_assets(&doc);

    // The src must be in the map.
    assert!(map.contains_key(&src), "src must be mapped: {map:?}");

    // The entry name must be the bare filename.
    let entry_name = map.get(&src).expect("entry name");
    assert_eq!(
        entry_name, "test.png",
        "entry name must be the bare filename"
    );

    // One resolved asset must be present with correct data and MIME.
    assert_eq!(resolved.len(), 1, "exactly one asset expected");
    assert_eq!(resolved[0].data, PNG_MAGIC, "asset bytes must match file");
    assert_eq!(
        resolved[0].mime_type, "image/png",
        "MIME type must be image/png"
    );
}

#[test]
fn collect_image_assets_data_uri_decodes_base64() {
    // Construct a data URI carrying the base64-encoded PNG magic.
    // PNG_MAGIC_B64 is the base64 of PNG_MAGIC[:6] ≈ correct prefix, but
    // for the test we use the full-round-trip value produced by our encoder.
    // We encode PNG_MAGIC into base64 manually (it is 8 bytes → 12 chars).
    let b64: String = base64_encode_test(PNG_MAGIC);
    let src = format!("data:image/png;base64,{b64}");

    let doc = Document {
        metadata: Metadata::default(),
        sections: vec![Section {
            blocks: vec![Block::Image {
                src: src.clone(),
                alt: "data uri image".into(),
            }],

            page_layout: None,
            ..Default::default()
        }],
        assets: Vec::new(),
    };

    let (map, resolved) = collect_image_assets(&doc);

    assert!(
        map.contains_key(&src),
        "data URI src must be mapped: {map:?}"
    );

    let entry_name = map.get(&src).expect("entry name");
    assert!(
        std::path::Path::new(entry_name)
            .extension()
            .and_then(|ext| ext.to_str())
            .is_some_and(|ext| ext.eq_ignore_ascii_case("png")),
        "data URI entry must have .png extension: {entry_name}"
    );

    assert_eq!(resolved.len(), 1, "one asset expected");
    assert_eq!(
        resolved[0].data, PNG_MAGIC,
        "decoded data must match original bytes"
    );
    assert_eq!(resolved[0].mime_type, "image/png");
}

#[test]
fn collect_image_assets_http_url_not_embedded() {
    let src = "https://example.com/photo.png".to_owned();
    let doc = Document {
        metadata: Metadata::default(),
        sections: vec![Section {
            blocks: vec![Block::Image {
                src: src.clone(),
                alt: "remote".into(),
            }],

            page_layout: None,
            ..Default::default()
        }],
        assets: Vec::new(),
    };

    let (map, resolved) = collect_image_assets(&doc);

    assert!(
        !map.contains_key(&src),
        "remote URL must NOT be in asset map: {map:?}"
    );
    assert!(
        resolved.is_empty(),
        "no assets must be resolved for remote URL"
    );
}

#[test]
fn collect_image_assets_missing_file_graceful() {
    let src = "/nonexistent/path/image.png".to_owned();
    let doc = Document {
        metadata: Metadata::default(),
        sections: vec![Section {
            blocks: vec![Block::Image {
                src: src.clone(),
                alt: "broken".into(),
            }],

            page_layout: None,
            ..Default::default()
        }],
        assets: Vec::new(),
    };

    // Must not panic; missing file is silently skipped.
    let (map, resolved) = collect_image_assets(&doc);

    assert!(
        !map.contains_key(&src),
        "missing file must not be in asset map"
    );
    assert!(
        resolved.is_empty(),
        "no assets expected for unreadable file"
    );
}

#[test]
fn collect_image_assets_pre_existing_assets_included() {
    // When doc.assets already contains entries (e.g. from an HWPX reader
    // roundtrip), collect_image_assets must include them in the output.
    let doc = Document {
        metadata: Metadata::default(),
        sections: vec![Section {
            blocks: vec![Block::Image {
                src: "photo.png".into(),
                alt: "pre-existing".into(),
            }],

            page_layout: None,
            ..Default::default()
        }],
        assets: vec![Asset {
            name: "photo.png".into(),
            data: PNG_MAGIC.to_vec(),
            mime_type: "image/png".into(),
        }],
    };

    let (map, resolved) = collect_image_assets(&doc);

    // The pre-existing asset name must be in the map.
    assert!(
        map.contains_key("photo.png"),
        "pre-existing asset src must be in map: {map:?}"
    );
    assert_eq!(
        resolved.len(),
        1,
        "exactly one resolved asset expected (no duplication)"
    );
    assert_eq!(resolved[0].data, PNG_MAGIC);
}

// ── Unit tests: write_hwpx BinData ZIP entries ───────────────────────────

#[test]
fn write_hwpx_local_image_creates_bindata_entry() {
    let dir = tempfile::tempdir().expect("tmp dir");
    let img_path = dir.path().join("photo.png");
    std::fs::write(&img_path, PNG_MAGIC).expect("write png");

    let doc = Document {
        metadata: Metadata::default(),
        sections: vec![Section {
            blocks: vec![Block::Image {
                src: img_path.to_str().expect("path utf-8").to_owned(),
                alt: "a photo".into(),
            }],

            page_layout: None,
            ..Default::default()
        }],
        assets: Vec::new(),
    };

    let entries = write_to_zip_entries(&doc);

    let has_bindata = entries
        .iter()
        .any(|e| e.starts_with("BinData/") && e.ends_with("photo.png"));
    assert!(
        has_bindata,
        "BinData/photo.png must be present in HWPX ZIP; entries: {entries:?}"
    );
}

#[test]
fn write_hwpx_local_image_bytes_preserved_in_bindata() {
    let dir = tempfile::tempdir().expect("tmp dir");
    let img_path = dir.path().join("pic.png");
    std::fs::write(&img_path, PNG_MAGIC).expect("write png");

    let doc = Document {
        metadata: Metadata::default(),
        sections: vec![Section {
            blocks: vec![Block::Image {
                src: img_path.to_str().expect("path utf-8").to_owned(),
                alt: "pic".into(),
            }],

            page_layout: None,
            ..Default::default()
        }],
        assets: Vec::new(),
    };

    let bytes = read_zip_entry_bytes(&doc, "BinData/pic.png");
    assert_eq!(bytes, PNG_MAGIC, "BinData bytes must match original file");
}

#[test]
fn write_hwpx_data_uri_image_creates_bindata_entry() {
    let b64 = base64_encode_test(PNG_MAGIC);
    let src = format!("data:image/png;base64,{b64}");

    let doc = Document {
        metadata: Metadata::default(),
        sections: vec![Section {
            blocks: vec![Block::Image {
                src,
                alt: "data uri".into(),
            }],

            page_layout: None,
            ..Default::default()
        }],
        assets: Vec::new(),
    };

    let entries = write_to_zip_entries(&doc);

    let has_bindata = entries.iter().any(|e| {
        e.starts_with("BinData/image_")
            && std::path::Path::new(e)
                .extension()
                .and_then(|ext| ext.to_str())
                .is_some_and(|ext| ext.eq_ignore_ascii_case("png"))
    });
    assert!(
        has_bindata,
        "BinData/image_N.png must be present for data URI image; entries: {entries:?}"
    );
}

#[test]
fn write_hwpx_http_url_no_bindata_entry() {
    let doc = Document {
        metadata: Metadata::default(),
        sections: vec![Section {
            blocks: vec![Block::Image {
                src: "https://example.com/photo.png".into(),
                alt: "remote".into(),
            }],

            page_layout: None,
            ..Default::default()
        }],
        assets: Vec::new(),
    };

    let entries = write_to_zip_entries(&doc);

    let has_bindata = entries.iter().any(|e| e.starts_with("BinData/"));
    assert!(
        !has_bindata,
        "HTTP URL images must NOT produce BinData entries; entries: {entries:?}"
    );
}

#[test]
fn write_hwpx_content_hpf_has_bindata_manifest_entry() {
    let dir = tempfile::tempdir().expect("tmp dir");
    let img_path = dir.path().join("logo.png");
    std::fs::write(&img_path, PNG_MAGIC).expect("write png");

    let doc = Document {
        metadata: Metadata::default(),
        sections: vec![Section {
            blocks: vec![Block::Image {
                src: img_path.to_str().expect("path utf-8").to_owned(),
                alt: "logo".into(),
            }],

            page_layout: None,
            ..Default::default()
        }],
        assets: Vec::new(),
    };

    let hpf = read_zip_entry_text(&doc, "Contents/content.hpf");

    assert!(
        hpf.contains("hp:binData"),
        "content.hpf must contain <hp:binData> element; hpf:\n{hpf}"
    );
    assert!(
        hpf.contains("logo.png"),
        "content.hpf binData must reference logo.png; hpf:\n{hpf}"
    );
    assert!(
        hpf.contains(r#"type="EMBED""#),
        "content.hpf binData must have type=\"EMBED\"; hpf:\n{hpf}"
    );
}

#[test]
fn write_hwpx_section_xml_uses_entry_name_as_binary_item_id_ref() {
    let dir = tempfile::tempdir().expect("tmp dir");
    let img_path = dir.path().join("myimage.png");
    std::fs::write(&img_path, PNG_MAGIC).expect("write png");

    let doc = Document {
        metadata: Metadata::default(),
        sections: vec![Section {
            blocks: vec![Block::Image {
                src: img_path.to_str().expect("path utf-8").to_owned(),
                alt: "my image".into(),
            }],

            page_layout: None,
            ..Default::default()
        }],
        assets: Vec::new(),
    };

    let section_xml = read_zip_entry_text(&doc, "Contents/section0.xml");

    // The binaryItemIDRef must be the bare entry name, not the full filesystem path.
    assert!(
        section_xml.contains(r#"hp:binaryItemIDRef="myimage.png""#),
        "section XML must use bare filename as binaryItemIDRef; section XML:\n{section_xml}"
    );
}

#[test]
fn write_hwpx_http_url_src_used_verbatim_as_binary_item_id_ref() {
    let url = "https://example.com/photo.png";
    let doc = Document {
        metadata: Metadata::default(),
        sections: vec![Section {
            blocks: vec![Block::Image {
                src: url.into(),
                alt: "remote".into(),
            }],

            page_layout: None,
            ..Default::default()
        }],
        assets: Vec::new(),
    };

    let section_xml = read_zip_entry_text(&doc, "Contents/section0.xml");

    // Remote URLs that are not embedded must still appear as binaryItemIDRef.
    assert!(
        section_xml.contains(url),
        "section XML must contain the original HTTP URL; section XML:\n{section_xml}"
    );
}

#[test]
fn write_hwpx_missing_file_does_not_panic() {
    let doc = Document {
        metadata: Metadata::default(),
        sections: vec![Section {
            blocks: vec![Block::Image {
                src: "/no/such/file.png".into(),
                alt: "broken".into(),
            }],

            page_layout: None,
            ..Default::default()
        }],
        assets: Vec::new(),
    };

    // Must complete without panic even when the image file does not exist.
    let tmp = tempfile::NamedTempFile::new().expect("tmp file");
    let result = write_hwpx(&doc, tmp.path(), None);
    assert!(
        result.is_ok(),
        "write_hwpx must succeed gracefully for missing image file: {result:?}"
    );

    let entries = write_to_zip_entries(&doc);
    let has_bindata = entries.iter().any(|e| e.starts_with("BinData/"));
    assert!(
        !has_bindata,
        "no BinData entry expected for unreadable file; entries: {entries:?}"
    );
}

// ── Roundtrip test ────────────────────────────────────────────────────────

#[test]
fn image_file_path_roundtrip_md_to_hwpx_embeds_bytes() {
    // Write a PNG to disk, build an IR document with a Block::Image pointing
    // to it, write to HWPX, read back, and verify the asset bytes are intact.
    let dir = tempfile::tempdir().expect("tmp dir");
    let img_path = dir.path().join("roundtrip.png");
    std::fs::write(&img_path, PNG_MAGIC).expect("write png");

    let src = img_path.to_str().expect("path utf-8").to_owned();
    let original = Document {
        metadata: Metadata::default(),
        sections: vec![Section {
            blocks: vec![Block::Image {
                src: src.clone(),
                alt: "roundtrip image".into(),
            }],

            page_layout: None,
            ..Default::default()
        }],
        assets: Vec::new(),
    };

    let tmp = tempfile::NamedTempFile::new().expect("tmp file");
    write_hwpx(&original, tmp.path(), None).expect("write_hwpx");

    let read_back = crate::hwpx::read_hwpx(tmp.path()).expect("read_hwpx");

    // The read-back document must have the asset with correct bytes.
    assert_eq!(
        read_back.assets.len(),
        1,
        "exactly one asset expected after roundtrip; assets: {:?}",
        read_back.assets
    );
    assert_eq!(
        read_back.assets[0].data, PNG_MAGIC,
        "asset bytes must match original after roundtrip"
    );
    assert_eq!(
        read_back.assets[0].mime_type, "image/png",
        "MIME type must survive roundtrip"
    );
}

#[test]
fn image_jpeg_extension_gets_correct_mime_type() {
    let dir = tempfile::tempdir().expect("tmp dir");
    let img_path = dir.path().join("photo.jpg");
    std::fs::write(&img_path, JPEG_MAGIC).expect("write jpeg");

    let src = img_path.to_str().expect("path utf-8").to_owned();
    let doc = Document {
        metadata: Metadata::default(),
        sections: vec![Section {
            blocks: vec![Block::Image {
                src,
                alt: "jpeg".into(),
            }],

            page_layout: None,
            ..Default::default()
        }],
        assets: Vec::new(),
    };

    let (_, resolved) = collect_image_assets(&doc);

    assert_eq!(resolved.len(), 1);
    assert_eq!(
        resolved[0].mime_type, "image/jpeg",
        "JPEG extension must map to image/jpeg"
    );
}

// ── test-only base64 encoder ─────────────────────────────────────────────

/// Simple base64 encoder used only inside tests so that `base64_decode`
/// can be tested with round-trip data without pulling in an external crate.
fn base64_encode_test(data: &[u8]) -> String {
    const CHARS: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    let mut out = String::new();
    let mut i = 0;
    while i + 2 < data.len() {
        let n = (u32::from(data[i]) << 16) | (u32::from(data[i + 1]) << 8) | u32::from(data[i + 2]);
        out.push(CHARS[((n >> 18) & 0x3f) as usize] as char);
        out.push(CHARS[((n >> 12) & 0x3f) as usize] as char);
        out.push(CHARS[((n >> 6) & 0x3f) as usize] as char);
        out.push(CHARS[(n & 0x3f) as usize] as char);
        i += 3;
    }
    let rem = data.len() - i;
    if rem == 1 {
        let n = u32::from(data[i]) << 16;
        out.push(CHARS[((n >> 18) & 0x3f) as usize] as char);
        out.push(CHARS[((n >> 12) & 0x3f) as usize] as char);
        out.push('=');
        out.push('=');
    } else if rem == 2 {
        let n = (u32::from(data[i]) << 16) | (u32::from(data[i + 1]) << 8);
        out.push(CHARS[((n >> 18) & 0x3f) as usize] as char);
        out.push(CHARS[((n >> 12) & 0x3f) as usize] as char);
        out.push(CHARS[((n >> 6) & 0x3f) as usize] as char);
        out.push('=');
    }
    out
}