formatjs_cli 1.1.10

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
/// 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 serde_json::Value;
use sha2::{Digest, Sha512};

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

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum HashAlgorithm {
    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**: `sha512`
/// - **Digest types**: `contenthash`
/// - **Encodings**: `base64`, `base64url` (URL-safe), `base62`, `hex`
/// - **Length**: Any positive integer
///
/// # Examples:
/// - `[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> {
        // Parse pattern: [hash:digest:encoding:length]
        // Default: [sha512:contenthash:base64:6]

        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.len() < 4 {
            anyhow::bail!(
                "Invalid ID interpolation pattern format: {}. Expected [hash:digest:encoding:length]",
                pattern
            );
        }

        let hash_algorithm = match parts[0] {
            "sha512" => HashAlgorithm::Sha512,
            _ => anyhow::bail!("Unsupported hash algorithm: {}", parts[0]),
        };
        let digest_type = match parts[1] {
            "contenthash" => DigestType::ContentHash,
            _ => anyhow::bail!("Unsupported digest type: {}", parts[1]),
        };
        let encoding = match parts[2] {
            "base64" => Encoding::Base64,
            "base64url" => Encoding::Base64Url,
            "base62" => Encoding::Base62,
            "hex" => Encoding::Hex,
            _ => anyhow::bail!("Unsupported encoding: {}", parts[2]),
        };
        let length: usize = parts[3]
            .parse()
            .context("Invalid length in ID interpolation pattern")?;

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

    pub fn generate(
        &self,
        default_message: Option<&str>,
        description: &Option<Value>,
    ) -> Result<String> {
        // Generate hash
        let hash = match (self.hash_algorithm, self.digest_type) {
            (HashAlgorithm::Sha512, DigestType::ContentHash) => {
                let mut hasher = Sha512::new();
                if let Some(msg) = default_message {
                    hasher.update(msg.as_bytes());
                }
                if let Some(desc) = description {
                    hasher.update(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) => hasher.update(s.as_bytes()),
                        _ => hasher.update(desc.to_string().as_bytes()),
                    }
                }
                let result = hasher.finalize();
                match self.encoding {
                    Encoding::Base64 => {
                        // Standard base64 (matches Node's crypto.digest('base64'))
                        base64::engine::general_purpose::STANDARD.encode(&result)
                    }
                    Encoding::Base64Url => {
                        // URL-safe base64 without padding (matches Node's crypto.digest('base64url'))
                        base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(&result)
                    }
                    Encoding::Base62 => encode_base62(&result),
                    Encoding::Hex => hex::encode(result),
                }
            }
        };

        // Truncate to specified length
        Ok(hash.chars().take(self.length).collect())
    }
}

#[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_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("[md5: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");
    }
}