formatjs_cli 1.1.13

Command-line interface for FormatJS - A Rust-based CLI for internationalization
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
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
/// ID generation for messages using interpolation patterns.
///
/// This module handles generating message IDs based on content hashing with
/// configurable patterns like `[sha512:contenthash:base64:6]`.
use anyhow::{Context, Result};
use base64::Engine;
use md5::{Digest, Md5};
use serde_json::Value;
use sha1::Sha1;
use sha2::{Sha224, Sha256, Sha384, Sha512};

/// Base62 character set: 0-9, A-Z, a-z
const BASE62_CHARS: &[u8] = b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum HashAlgorithm {
    Md5,
    Sha1,
    Sha224,
    Sha256,
    Sha384,
    Sha512,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum DigestType {
    ContentHash,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Encoding {
    Base64,
    Base64Url,
    Base62,
    Hex,
}

/// Encode bytes to base62 string
fn encode_base62(bytes: &[u8]) -> String {
    if bytes.is_empty() {
        return String::new();
    }

    // Convert bytes to a big integer representation, then encode
    let mut result = Vec::new();
    let mut num = bytes.to_vec();

    while !num.iter().all(|&b| b == 0) {
        let mut remainder = 0u32;
        for byte in &mut num {
            let value = (remainder << 8) | (*byte as u32);
            *byte = (value / 62) as u8;
            remainder = value % 62;
        }
        result.push(BASE62_CHARS[remainder as usize]);
    }

    // Add leading zeros for leading zero bytes in input
    for &byte in bytes {
        if byte == 0 {
            result.push(BASE62_CHARS[0]);
        } else {
            break;
        }
    }

    result.reverse();
    String::from_utf8(result).unwrap_or_default()
}

/// Generate message ID using interpolation pattern.
///
/// Supports patterns in the format: `[hash:digest:encoding:length]`
///
/// # Supported formats:
/// - **Hash algorithms**: `md5`, `sha1`, `sha224`, `sha256`, `sha384`, `sha512`
/// - **Digest types**: `contenthash`, `hash`
/// - **Encodings**: `base64`, `base64url` (URL-safe), `base62`, `hex`
/// - **Length**: Any positive integer
///
/// # Examples:
/// - `[contenthash:5]` - legacy shorthand for a 5-character md5 hex ID
/// - `[sha256:contenthash:hex:5]` - 5-character sha256 hex ID
/// - `[sha512:contenthash:base64:6]` - 6-character base64 ID (standard, may contain +/)
/// - `[sha512:contenthash:base64url:6]` - 6-character URL-safe base64 ID (uses -_ instead of +/)
/// - `[sha512:contenthash:base62:6]` - 6-character base62 ID (alphanumeric only)
/// - `[sha512:contenthash:hex:10]` - 10-character hex ID
///
/// # Arguments:
/// * `pattern` - The interpolation pattern string
/// * `default_message` - The message text to hash
/// * `description` - Optional description that affects the hash
/// * `_file_path` - File path (currently unused, reserved for future use)
pub fn generate_id(
    pattern: &str,
    default_message: Option<&str>,
    description: &Option<Value>,
    _file_path: Option<&str>,
) -> Result<String> {
    IdGenerator::new(pattern)?.generate(default_message, description)
}

/// Parsed ID interpolation pattern for repeated message ID generation.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct IdGenerator {
    hash_algorithm: HashAlgorithm,
    digest_type: DigestType,
    encoding: Encoding,
    length: usize,
}

impl IdGenerator {
    pub fn new(pattern: &str) -> Result<Self> {
        if !pattern.starts_with('[') || !pattern.ends_with(']') {
            anyhow::bail!("Invalid ID interpolation pattern: {}", pattern);
        }

        let inner = &pattern[1..pattern.len() - 1];
        let parts: Vec<&str> = inner.split(':').collect();

        if parts.is_empty() || parts.iter().any(|part| part.is_empty()) {
            anyhow::bail!("Invalid ID interpolation pattern: {}", pattern);
        }

        let normalized_parts: Vec<String> = parts.iter().map(|part| part.to_lowercase()).collect();
        let mut index = 0;
        let hash_algorithm = if is_digest_type(&normalized_parts[index]) {
            // loader-utils compatibility: `[contenthash:5]` means md5 + hex + length 5.
            HashAlgorithm::Md5
        } else {
            let algorithm = parse_hash_algorithm(&normalized_parts[index])?;
            index += 1;
            algorithm
        };

        if index >= normalized_parts.len() {
            anyhow::bail!(
                "Invalid ID interpolation pattern format: {}. Expected [hash:digest:encoding:length]",
                pattern
            );
        }

        let digest_type = match normalized_parts[index].as_str() {
            "contenthash" | "hash" => DigestType::ContentHash,
            _ => anyhow::bail!("Unsupported digest type: {}", parts[index]),
        };
        index += 1;

        let encoding = if index < normalized_parts.len()
            && !normalized_parts[index]
                .chars()
                .all(|ch| ch.is_ascii_digit())
        {
            let encoding = parse_encoding(&normalized_parts[index], parts[index])?;
            index += 1;
            encoding
        } else {
            Encoding::Hex
        };

        if index >= normalized_parts.len() {
            anyhow::bail!(
                "Invalid ID interpolation pattern format: {}. Expected [hash:digest:encoding:length]",
                pattern
            );
        }

        let length: usize = parts[index]
            .parse()
            .context("Invalid length in ID interpolation pattern")?;
        if length == 0 {
            anyhow::bail!(
                "Invalid length in ID interpolation pattern: {}",
                parts[index]
            );
        }
        index += 1;

        if index != normalized_parts.len() {
            anyhow::bail!("Invalid ID interpolation pattern: {}", pattern);
        }

        Ok(Self {
            hash_algorithm,
            digest_type,
            encoding,
            length,
        })
    }

    pub fn generate(
        &self,
        default_message: Option<&str>,
        description: &Option<Value>,
    ) -> Result<String> {
        let content = hash_content(default_message, description);
        let digest = match (self.hash_algorithm, self.digest_type) {
            (HashAlgorithm::Md5, DigestType::ContentHash) => hash_with::<Md5>(&content),
            (HashAlgorithm::Sha1, DigestType::ContentHash) => hash_with::<Sha1>(&content),
            (HashAlgorithm::Sha224, DigestType::ContentHash) => hash_with::<Sha224>(&content),
            (HashAlgorithm::Sha256, DigestType::ContentHash) => hash_with::<Sha256>(&content),
            (HashAlgorithm::Sha384, DigestType::ContentHash) => hash_with::<Sha384>(&content),
            (HashAlgorithm::Sha512, DigestType::ContentHash) => hash_with::<Sha512>(&content),
        };

        Ok(encode_digest(&digest, self.encoding)
            .chars()
            .take(self.length)
            .collect())
    }
}

fn is_digest_type(part: &str) -> bool {
    matches!(part, "contenthash" | "hash")
}

fn parse_hash_algorithm(part: &str) -> Result<HashAlgorithm> {
    match part {
        "md5" => Ok(HashAlgorithm::Md5),
        "sha1" => Ok(HashAlgorithm::Sha1),
        "sha224" => Ok(HashAlgorithm::Sha224),
        "sha256" => Ok(HashAlgorithm::Sha256),
        "sha384" => Ok(HashAlgorithm::Sha384),
        "sha512" => Ok(HashAlgorithm::Sha512),
        _ => anyhow::bail!("Unsupported hash algorithm: {}", part),
    }
}

fn parse_encoding(normalized: &str, original: &str) -> Result<Encoding> {
    match normalized {
        "base64" => Ok(Encoding::Base64),
        "base64url" => Ok(Encoding::Base64Url),
        "base62" => Ok(Encoding::Base62),
        "hex" => Ok(Encoding::Hex),
        _ => anyhow::bail!("Unsupported encoding: {}", original),
    }
}

fn hash_content(default_message: Option<&str>, description: &Option<Value>) -> Vec<u8> {
    let mut content = Vec::new();
    if let Some(msg) = default_message {
        content.extend_from_slice(msg.as_bytes());
    }
    if let Some(desc) = description {
        content.push(b'#');
        // Extract string value for string types to match TypeScript CLI behavior.
        // TypeScript uses: typeof description === 'string' ? description : stringify(description)
        match desc {
            Value::String(s) => content.extend_from_slice(s.as_bytes()),
            _ => content.extend_from_slice(desc.to_string().as_bytes()),
        }
    }
    content
}

fn hash_with<D: Digest>(content: &[u8]) -> Vec<u8> {
    let mut hasher = D::new();
    hasher.update(content);
    hasher.finalize().to_vec()
}

fn encode_digest(digest: &[u8], encoding: Encoding) -> String {
    match encoding {
        Encoding::Base64 => {
            // Standard base64 (matches Node's crypto.digest('base64'))
            base64::engine::general_purpose::STANDARD.encode(digest)
        }
        Encoding::Base64Url => {
            // URL-safe base64 without padding (matches Node's crypto.digest('base64url'))
            base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(digest)
        }
        Encoding::Base62 => encode_base62(digest),
        Encoding::Hex => hex::encode(digest),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_generate_id_sha512_base64() {
        let id = generate_id(
            "[sha512:contenthash:base64:6]",
            Some("Hello World"),
            &None,
            None,
        )
        .unwrap();
        // Standard base64 (may contain + and /)
        assert_eq!(id, "LHT9F+");
    }

    #[test]
    fn test_generate_id_sha512_base64url() {
        let id = generate_id(
            "[sha512:contenthash:base64url:6]",
            Some("Hello World"),
            &None,
            None,
        )
        .unwrap();
        assert_eq!(id, "LHT9F-");
    }

    #[test]
    fn test_generate_id_with_description() {
        let desc = serde_json::Value::String("A greeting".to_string());
        let id = generate_id(
            "[sha512:contenthash:base64:8]",
            Some("Hello"),
            &Some(desc),
            None,
        )
        .unwrap();
        // Hash of "Hello#A greeting" (without JSON quotes around description)
        // This matches TypeScript CLI behavior
        assert_eq!(id, "tYLiH0T9");
    }

    #[test]
    fn test_generate_id_hex() {
        let id = generate_id("[sha512:contenthash:hex:10]", Some("Test"), &None, None).unwrap();
        assert_eq!(id, "c6ee9e33cf");
    }

    #[test]
    fn test_generate_id_legacy_contenthash_shorthand() {
        let id = generate_id("[contenthash:5]", Some("Hello World"), &None, None).unwrap();
        assert_eq!(id, "b10a8");
    }

    #[test]
    fn test_generate_id_hash_alias_shorthand() {
        let id = generate_id("[hash:5]", Some("Hello World"), &None, None).unwrap();
        assert_eq!(id, "b10a8");
    }

    #[test]
    fn test_generate_id_sha1() {
        let id = generate_id(
            "[sha1:contenthash:base64:6]",
            Some("Hello World"),
            &None,
            None,
        )
        .unwrap();
        assert_eq!(id, "Ck1VqN");
    }

    #[test]
    fn test_generate_id_sha256() {
        let id = generate_id(
            "[sha256:contenthash:hex:5]",
            Some("Hello World"),
            &None,
            None,
        )
        .unwrap();
        assert_eq!(id, "a591a");
    }

    #[test]
    fn test_generate_id_sha224_and_sha384() {
        let sha224 = generate_id("[sha224:contenthash:hex:10]", Some("Test"), &None, None).unwrap();
        let sha384 = generate_id("[sha384:contenthash:hex:10]", Some("Test"), &None, None).unwrap();

        assert_eq!(sha224, "3606346815");
        assert_eq!(sha384, "7b8f465407");
    }

    #[test]
    fn test_generate_id_hash_digest_alias() {
        let id = generate_id("[sha256:hash:hex:5]", Some("Hello World"), &None, None).unwrap();
        assert_eq!(id, "a591a");
    }

    #[test]
    fn test_generate_id_invalid_pattern() {
        let result = generate_id("invalid", Some("Test"), &None, None);
        assert!(result.is_err());
    }

    #[test]
    fn test_generate_id_different_lengths() {
        // Test various lengths
        for length in [4, 6, 8, 10, 16, 32] {
            let pattern = format!("[sha512:contenthash:base64:{}]", length);
            let id = generate_id(&pattern, Some("Test message"), &None, None).unwrap();
            assert_eq!(id.len(), length, "ID should be {} characters", length);
        }
    }

    #[test]
    fn test_generate_id_deterministic() {
        // Same input should always produce the same ID
        let id1 = generate_id(
            "[sha512:contenthash:base64:10]",
            Some("Hello World"),
            &None,
            None,
        )
        .unwrap();
        let id2 = generate_id(
            "[sha512:contenthash:base64:10]",
            Some("Hello World"),
            &None,
            None,
        )
        .unwrap();
        assert_eq!(id1, "LHT9F+2v2A");
        assert_eq!(id2, "LHT9F+2v2A");
        assert_eq!(id1, id2, "Same input should produce same ID");
    }

    #[test]
    fn test_generate_id_different_messages() {
        // Different messages should produce different IDs
        let id1 = generate_id(
            "[sha512:contenthash:base64:10]",
            Some("Message 1"),
            &None,
            None,
        )
        .unwrap();
        let id2 = generate_id(
            "[sha512:contenthash:base64:10]",
            Some("Message 2"),
            &None,
            None,
        )
        .unwrap();
        assert_eq!(id1, "ePueQ5h1ce");
        assert_eq!(id2, "fTO7rwuRCr");
        assert_ne!(id1, id2, "Different messages should produce different IDs");
    }

    #[test]
    fn test_generate_id_with_description_affects_hash() {
        let desc = serde_json::Value::String("Description".to_string());
        let id1 =
            generate_id("[sha512:contenthash:base64:10]", Some("Hello"), &None, None).unwrap();
        let id2 = generate_id(
            "[sha512:contenthash:base64:10]",
            Some("Hello"),
            &Some(desc),
            None,
        )
        .unwrap();
        assert_eq!(id1, "NhX4DJ0pPt");
        // Hash of "Hello#Description" (without JSON quotes around description)
        // This matches TypeScript CLI behavior
        assert_eq!(id2, "WgDsrbylG9");
        assert_ne!(
            id1, id2,
            "Adding description should change the generated ID"
        );
    }

    #[test]
    fn test_generate_id_hex_vs_base64() {
        let id_hex = generate_id("[sha512:contenthash:hex:10]", Some("Test"), &None, None).unwrap();
        let id_base64 =
            generate_id("[sha512:contenthash:base64:10]", Some("Test"), &None, None).unwrap();

        assert_eq!(id_hex, "c6ee9e33cf");
        assert_eq!(id_base64, "xu6eM89cZx");
    }

    #[test]
    fn test_generate_id_base64_vs_base64url() {
        let id_base64 = generate_id(
            "[sha512:contenthash:base64:10]",
            Some("Hello World"),
            &None,
            None,
        )
        .unwrap();
        let id_base64url = generate_id(
            "[sha512:contenthash:base64url:10]",
            Some("Hello World"),
            &None,
            None,
        )
        .unwrap();

        assert_eq!(id_base64, "LHT9F+2v2A");
        assert_eq!(id_base64url, "LHT9F-2v2A");
    }

    #[test]
    fn test_generate_id_base62() {
        let id = generate_id(
            "[sha512:contenthash:base62:10]",
            Some("Test message"),
            &None,
            None,
        )
        .unwrap();
        assert_eq!(id, "Gm8I0LBX6B");
    }

    #[test]
    fn test_generate_id_base62_deterministic() {
        let id1 = generate_id(
            "[sha512:contenthash:base62:10]",
            Some("Hello World"),
            &None,
            None,
        )
        .unwrap();
        let id2 = generate_id(
            "[sha512:contenthash:base62:10]",
            Some("Hello World"),
            &None,
            None,
        )
        .unwrap();
        assert_eq!(id1, "AJxnki7plR");
        assert_eq!(id2, "AJxnki7plR");
    }

    #[test]
    fn test_generate_id_base62_different_from_base64() {
        let id_base62 =
            generate_id("[sha512:contenthash:base62:10]", Some("Test"), &None, None).unwrap();
        let id_base64 =
            generate_id("[sha512:contenthash:base64:10]", Some("Test"), &None, None).unwrap();

        assert_eq!(id_base62, "kBedeOfsNe");
        assert_eq!(id_base64, "xu6eM89cZx");
    }

    #[test]
    fn test_generate_id_base62_various_lengths() {
        // Test that truncation works correctly for various lengths
        for length in [4, 6, 8, 10, 16, 32] {
            let pattern = format!("[sha512:contenthash:base62:{}]", length);
            let id = generate_id(&pattern, Some("Test message for base62"), &None, None).unwrap();
            assert_eq!(id.len(), length);
        }
    }

    #[test]
    fn test_generate_id_invalid_encoding() {
        let result = generate_id("[sha512:contenthash:base32:10]", Some("Test"), &None, None);
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("Unsupported encoding")
        );
    }

    #[test]
    fn test_generate_id_invalid_hash_algorithm() {
        let result = generate_id("[sha3:contenthash:base64:10]", Some("Test"), &None, None);
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("Unsupported hash algorithm")
        );
    }

    #[test]
    fn test_generate_id_invalid_format() {
        // Missing parts
        let result = generate_id("[sha512:contenthash]", Some("Test"), &None, None);
        assert!(result.is_err());

        // Invalid length
        let result = generate_id("[sha512:contenthash:base64:abc]", Some("Test"), &None, None);
        assert!(result.is_err());

        // Missing brackets
        let result = generate_id("sha512:contenthash:base64:10", Some("Test"), &None, None);
        assert!(result.is_err());
    }

    // https://github.com/formatjs/formatjs/issues/6009
    #[test]
    fn test_generate_id_matches_typescript_cli() {
        // This test verifies that the Rust CLI produces the same hash as the TypeScript CLI
        // for the exact test case from issue #6009
        let desc = serde_json::Value::String("Test component message".to_string());
        let id = generate_id(
            "[sha512:contenthash:base64:6]",
            Some("This is a test message."),
            &Some(desc),
            None,
        )
        .unwrap();

        // TypeScript CLI produces "rFvuOJ" for this input
        // Previously, Rust CLI incorrectly produced "8qN7+5" because it was
        // including JSON quotes around the description string
        assert_eq!(id, "rFvuOJ", "Hash should match TypeScript CLI output");
    }
}