llm-tokenizer 1.4.0

LLM tokenizer library with caching and chat template support
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
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
//! Kimi-K2.5 tool-declaration encoder. See module-level docs.
//!
//! Ported from <https://huggingface.co/moonshotai/Kimi-K2.5/blob/main/tool_declaration_ts.py>.
//! Mirrors the upstream Python reference function-by-function. Output must be
//! byte-equal to the Python reference; gated by golden tests in
//! `tests/kimi_k25_renderer_detection.rs`.

use std::{collections::HashMap, fmt::Write};

use anyhow::Result;
use serde_json::Value;

use crate::chat_template::{ChatTemplateParams, ChatTemplateState};

const TS_INDENT: &str = "  ";
const TS_FIELD_DELIMITER: &str = ",\n";

// On overflow, emit `any` and continue — never panic on adversarial schemas.
const MAX_RECURSION_DEPTH: usize = 32;

pub fn encode_tools_to_typescript(tools: &[Value]) -> Option<String> {
    if tools.is_empty() {
        return None;
    }
    let mut function_strs: Vec<String> = Vec::new();
    for t in tools {
        // Skip unsupported tool types (e.g. "_plugin"), matching upstream.
        if t.get("type").and_then(Value::as_str) != Some("function") {
            continue;
        }
        // Upstream `if func_def:` skips a missing/empty function object.
        let func = match t.get("function") {
            Some(f) if f.as_object().is_some_and(|o| !o.is_empty()) => f,
            _ => continue,
        };
        match openai_function_to_typescript(func) {
            Some(s) => function_strs.push(s),
            // Upstream raises here; the caller catches and renders JSON tool
            // declarations instead. We return `None` so `tools_ts_str` stays
            // undefined and the chat template takes its JSON fallback branch.
            None => {
                tracing::warn!(
                    "Kimi-K2.5 tool schema unsupported by the TypeScript encoder; \
                     leaving tools_ts_str undefined so the template falls back to JSON \
                     tool declarations"
                );
                return None;
            }
        }
    }
    if function_strs.is_empty() {
        return None;
    }
    let mut out = String::from("# Tools\n\n## functions\nnamespace functions {\n");
    out.push_str(&function_strs.join("\n"));
    out.push('\n');
    out.push_str("}\n");
    Some(out)
}

/// Renderer for `Renderer::KimiK25Tools`. Computes `tools_ts_str` and merges
/// it into `template_kwargs`, then delegates to the standard minijinja path.
pub(crate) fn apply_kimi_k25_tools(
    chat_template: &ChatTemplateState,
    messages: &[Value],
    params: ChatTemplateParams,
) -> Result<String> {
    let ts_str = params.tools.and_then(encode_tools_to_typescript);

    let owned: Option<HashMap<String, Value>> = match (params.template_kwargs, ts_str.as_ref()) {
        (Some(existing), Some(ts)) => {
            let mut m = existing.clone();
            m.insert("tools_ts_str".to_string(), Value::String(ts.clone()));
            Some(m)
        }
        (None, Some(ts)) => {
            let mut m = HashMap::with_capacity(1);
            m.insert("tools_ts_str".to_string(), Value::String(ts.clone()));
            Some(m)
        }
        _ => None, // No tools → leave tools_ts_str undefined
    };

    let new_params = ChatTemplateParams {
        template_kwargs: owned.as_ref().or(params.template_kwargs),
        ..params
    };
    chat_template.apply(messages, new_params)
}

// ---------------------------------------------------------------------------
// Function-level encoding
// ---------------------------------------------------------------------------

fn openai_function_to_typescript(function: &Value) -> Option<String> {
    let parameters = function
        .get("parameters")
        .cloned()
        .unwrap_or_else(|| Value::Object(Default::default()));
    let mut registry = SchemaRegistry::default();
    let parsed = ParameterTypeObject::parse(&parameters, &mut registry);

    let mut interfaces: Vec<String> = Vec::new();
    let mut root_interface_name: Option<&str> = None;

    if registry.has_self_ref {
        root_interface_name = Some("parameters");
        let body = parsed
            .properties
            .iter()
            .map(|p| p.to_typescript(TS_INDENT, &registry))
            .collect::<Vec<_>>()
            .join(TS_FIELD_DELIMITER);
        let body = if body.is_empty() {
            String::new()
        } else {
            format!("\n{body}\n")
        };
        interfaces.push(format!("interface parameters {{{body}}}"));
    }

    // Emit definitions in `$defs` insertion order to match upstream, which
    // iterates an insertion-ordered Python dict (do NOT sort).
    let defs_ordered: Vec<(String, Value)> = registry
        .order
        .iter()
        .filter_map(|name| {
            registry
                .definitions
                .get(name)
                .map(|v| (name.clone(), v.clone()))
        })
        .collect();
    for (name, schema) in defs_ordered {
        let obj_type = parse_parameter_type(&schema, &mut registry);
        let body = obj_type.to_typescript("", &registry);
        let mut def_str = String::new();
        if let Some(desc) = schema.get("description").and_then(Value::as_str) {
            if !desc.is_empty() {
                def_str.push_str(&format_description(desc, ""));
                def_str.push('\n');
            }
        }
        #[expect(
            clippy::unwrap_used,
            reason = "write!/writeln! into String cannot fail"
        )]
        {
            write!(def_str, "interface {name} {body}").unwrap();
        }
        interfaces.push(def_str);
    }

    let interface_str = interfaces.join("\n");
    let function_name = function
        .get("name")
        .and_then(Value::as_str)
        .unwrap_or("function");
    let type_def = match root_interface_name {
        Some(n) => format!("type {function_name} = (_: {n}) => any;"),
        None => format!(
            "type {function_name} = (_: {}) => any;",
            parsed.to_typescript("", &registry)
        ),
    };
    let description = function
        .get("description")
        .and_then(Value::as_str)
        .unwrap_or("");
    let desc_block = if description.is_empty() {
        String::new()
    } else {
        format_description(description, "")
    };

    // Upstream raises on unsupported schema constructs, aborting the whole TS
    // encoding; mirror that by signalling the caller to drop to JSON.
    if registry.unsupported {
        return None;
    }

    Some(
        [interface_str, desc_block, type_def]
            .into_iter()
            .filter(|s| !s.is_empty())
            .collect::<Vec<_>>()
            .join("\n"),
    )
}

// ---------------------------------------------------------------------------
// Schema parsing
// ---------------------------------------------------------------------------

#[derive(Default)]
struct SchemaRegistry {
    definitions: HashMap<String, Value>,
    /// Insertion order of `$defs` keys. Upstream iterates a Python `dict`,
    /// which is insertion-ordered, so we must preserve that order (not sort)
    /// to stay byte-equal for schemas whose keys aren't alphabetical.
    order: Vec<String>,
    has_self_ref: bool,
    depth: usize,
    /// Set when a schema construct is encountered that upstream would `raise`
    /// on (unresolvable `$ref`, unsupported reference format, or an
    /// unrecognized schema shape). The caller abandons the TypeScript
    /// namespace and leaves `tools_ts_str` undefined so the chat template
    /// falls back to JSON tool declarations — matching upstream semantics.
    unsupported: bool,
}

impl SchemaRegistry {
    fn register_definitions(&mut self, defs: &Value) {
        if let Some(map) = defs.as_object() {
            for (name, schema) in map {
                // A Python dict keeps a key's original position on re-assignment;
                // only record order the first time we see a key.
                if !self.definitions.contains_key(name) {
                    self.order.push(name.clone());
                }
                self.definitions.insert(name.clone(), schema.clone());
            }
        }
    }

    fn resolve_ref(&mut self, reference: &str) -> Option<Value> {
        if reference == "#" {
            self.has_self_ref = true;
            return Some(serde_json::json!({"$self_ref": true}));
        }
        if let Some(name) = reference.strip_prefix("#/$defs/") {
            match self.definitions.get(name).cloned() {
                Some(v) => return Some(v),
                // Upstream: `raise ValueError(f"Reference not found: {ref}")`.
                None => {
                    self.unsupported = true;
                    return None;
                }
            }
        }
        // Upstream: `raise ValueError(f"Unsupported reference format: {ref}")`.
        self.unsupported = true;
        None
    }
}

enum ParameterType {
    Scalar(ParameterTypeScalar),
    Object(ParameterTypeObject),
    Array(ParameterTypeArray),
    Enum(ParameterTypeEnum),
    AnyOf(ParameterTypeAnyOf),
    Union(ParameterTypeUnion),
    Ref(ParameterTypeRef),
}

impl ParameterType {
    fn format_docstring(&self, indent: &str) -> String {
        match self {
            ParameterType::Scalar(s) => s.base.format_docstring(indent),
            ParameterType::Object(o) => o.base.format_docstring(indent),
            ParameterType::Array(a) => a.base.format_docstring(indent),
            ParameterType::Enum(e) => e.base.format_docstring(indent),
            ParameterType::AnyOf(a) => a.base.format_docstring(indent),
            ParameterType::Union(u) => u.base.format_docstring(indent),
            ParameterType::Ref(r) => r.base.format_docstring(indent),
        }
    }

    fn to_typescript(&self, indent: &str, registry: &SchemaRegistry) -> String {
        match self {
            ParameterType::Scalar(s) => s.to_typescript(),
            ParameterType::Object(o) => o.to_typescript(indent, registry),
            ParameterType::Array(a) => a.to_typescript(indent, registry),
            ParameterType::Enum(e) => e.to_typescript(),
            ParameterType::AnyOf(a) => a.to_typescript(indent, registry),
            ParameterType::Union(u) => u.to_typescript(),
            ParameterType::Ref(r) => r.to_typescript(),
        }
    }
}

#[derive(Default)]
struct BaseType {
    description: String,
    constraints: Vec<(String, Value)>,
}

impl BaseType {
    fn from_extra_props(props: &Value, allowed_keys: &[&str]) -> Self {
        let description = props
            .get("description")
            .and_then(Value::as_str)
            .unwrap_or("")
            .to_string();
        let mut constraints: Vec<(String, Value)> = props
            .as_object()
            .map(|m| {
                m.iter()
                    .filter(|(k, _)| allowed_keys.contains(&k.as_str()))
                    .map(|(k, v)| (k.clone(), v.clone()))
                    .collect()
            })
            .unwrap_or_default();
        constraints.sort_by(|a, b| a.0.cmp(&b.0));
        Self {
            description,
            constraints,
        }
    }

    fn format_docstring(&self, indent: &str) -> String {
        let mut out = String::new();
        if !self.description.is_empty() {
            out.push_str(&format_description(&self.description, indent));
            out.push('\n');
        }
        if !self.constraints.is_empty() {
            let parts: Vec<String> = self
                .constraints
                .iter()
                .map(|(k, v)| format!("{k}: {}", json_inline(v)))
                .collect();
            #[expect(
                clippy::unwrap_used,
                reason = "write!/writeln! into String cannot fail"
            )]
            {
                writeln!(out, "{indent}// {}", parts.join(", ")).unwrap();
            }
        }
        out
    }
}

struct ParameterTypeScalar {
    base: BaseType,
    typ: String,
}

impl ParameterTypeScalar {
    fn parse(typ: &str, props: &Value) -> Self {
        let allowed: &[&str] = match typ {
            "string" => &["maxLength", "minLength", "pattern"],
            "number" | "integer" => &["maximum", "minimum"],
            _ => &[],
        };
        Self {
            base: BaseType::from_extra_props(props, allowed),
            typ: typ.to_string(),
        }
    }

    fn any() -> Self {
        Self {
            base: BaseType::default(),
            typ: "any".to_string(),
        }
    }

    fn to_typescript(&self) -> String {
        match self.typ.as_str() {
            "integer" => "number".to_string(),
            other => other.to_string(),
        }
    }
}

struct Parameter {
    name: String,
    typ: ParameterType,
    optional: bool,
    default: Option<Value>,
}

impl Parameter {
    fn to_typescript(&self, indent: &str, registry: &SchemaRegistry) -> String {
        let mut out = self.typ.format_docstring(indent);
        if let Some(d) = &self.default {
            let repr = match d {
                Value::Bool(true) => "True".to_string(),
                Value::Bool(false) => "False".to_string(),
                Value::Number(_) => d.to_string(),
                _ => serde_json::to_string(d).unwrap_or_else(|_| "null".to_string()),
            };
            #[expect(
                clippy::unwrap_used,
                reason = "write!/writeln! into String cannot fail"
            )]
            {
                writeln!(out, "{indent}// Default: {repr}").unwrap();
            }
        }
        let opt_marker = if self.optional { "?" } else { "" };
        #[expect(
            clippy::unwrap_used,
            reason = "write!/writeln! into String cannot fail"
        )]
        {
            write!(
                out,
                "{indent}{}{opt_marker}: {}",
                self.name,
                self.typ.to_typescript(indent, registry)
            )
            .unwrap();
        }
        out
    }
}

struct ParameterTypeObject {
    base: BaseType,
    properties: Vec<Parameter>,
    additional_properties: AdditionalProperties,
}

enum AdditionalProperties {
    None,
    True,
    False,
    Schema(Box<ParameterType>),
}

impl ParameterTypeObject {
    fn parse(schema: &Value, registry: &mut SchemaRegistry) -> Self {
        let base = BaseType::from_extra_props(schema, &[]);
        if let Some(defs) = schema.get("$defs") {
            registry.register_definitions(defs);
        }

        let additional_properties = match schema.get("additionalProperties") {
            None => AdditionalProperties::None,
            Some(Value::Bool(true)) => AdditionalProperties::True,
            Some(Value::Bool(false)) => AdditionalProperties::False,
            Some(other) => {
                AdditionalProperties::Schema(Box::new(parse_parameter_type(other, registry)))
            }
        };

        let props_map = schema.get("properties").and_then(Value::as_object);
        let required: Vec<&str> = schema
            .get("required")
            .and_then(Value::as_array)
            .map(|arr| arr.iter().filter_map(Value::as_str).collect())
            .unwrap_or_default();

        let properties: Vec<Parameter> = props_map
            .map(|props| {
                props
                    .iter()
                    .map(|(name, prop_schema)| {
                        let optional = !required.contains(&name.as_str());
                        let default = prop_schema.get("default").cloned();
                        let typ = parse_parameter_type(prop_schema, registry);
                        Parameter {
                            name: name.clone(),
                            typ,
                            optional,
                            default,
                        }
                    })
                    .collect()
            })
            .unwrap_or_default();

        Self {
            base,
            properties,
            additional_properties,
        }
    }

    fn to_typescript(&self, indent: &str, registry: &SchemaRegistry) -> String {
        let mut required: Vec<&Parameter> =
            self.properties.iter().filter(|p| !p.optional).collect();
        let mut optional: Vec<&Parameter> = self.properties.iter().filter(|p| p.optional).collect();
        required.sort_by(|a, b| a.name.cmp(&b.name));
        optional.sort_by(|a, b| a.name.cmp(&b.name));
        let inner_indent = format!("{indent}{TS_INDENT}");
        let mut parts: Vec<String> = required
            .into_iter()
            .chain(optional)
            .map(|p| p.to_typescript(&inner_indent, registry))
            .collect();

        match &self.additional_properties {
            AdditionalProperties::None => {}
            AdditionalProperties::True => parts.push(format!("{inner_indent}[k: string]: any")),
            AdditionalProperties::False => parts.push(format!("{inner_indent}[k: string]: never")),
            AdditionalProperties::Schema(inner) => {
                let ty = inner.to_typescript(&inner_indent, registry);
                parts.push(format!("{inner_indent}[k: string]: {ty}"));
            }
        }

        if parts.is_empty() {
            return "{}".to_string();
        }
        let body = parts.join(TS_FIELD_DELIMITER);
        let body = format!("\n{body}\n");
        format!("{{{body}{indent}}}")
    }
}

struct ParameterTypeArray {
    base: BaseType,
    item: Box<ParameterType>,
}

impl ParameterTypeArray {
    fn parse(schema: &Value, registry: &mut SchemaRegistry) -> Self {
        let base = BaseType::from_extra_props(schema, &["minItems", "maxItems"]);
        let item = match schema.get("items") {
            Some(items) if !items.is_null() => parse_parameter_type(items, registry),
            _ => ParameterType::Scalar(ParameterTypeScalar::any()),
        };
        Self {
            base,
            item: Box::new(item),
        }
    }

    fn to_typescript(&self, indent: &str, registry: &SchemaRegistry) -> String {
        let inner_indent = format!("{indent}{TS_INDENT}");
        let item_doc = self.item.format_docstring(&inner_indent);
        let item_ts = self.item.to_typescript(&inner_indent, registry);
        if item_doc.is_empty() {
            format!("Array<{item_ts}>")
        } else {
            format!("Array<\n{item_doc}{inner_indent}{item_ts}\n{indent}>")
        }
    }
}

struct ParameterTypeEnum {
    base: BaseType,
    values: Vec<Value>,
}

impl ParameterTypeEnum {
    fn parse(schema: &Value) -> Self {
        let values = schema
            .get("enum")
            .and_then(Value::as_array)
            .cloned()
            .unwrap_or_default();
        Self {
            base: BaseType::from_extra_props(schema, &[]),
            values,
        }
    }

    fn to_typescript(&self) -> String {
        self.values
            .iter()
            .map(|v| match v {
                // Upstream emits `f'"{e}"'` with no escaping; match it byte-for-byte.
                Value::String(s) => format!("\"{s}\""),
                Value::Null => "None".to_string(),
                Value::Bool(true) => "True".to_string(),
                Value::Bool(false) => "False".to_string(),
                other => other.to_string(),
            })
            .collect::<Vec<_>>()
            .join(" | ")
    }
}

struct ParameterTypeAnyOf {
    base: BaseType,
    branches: Vec<ParameterType>,
}

impl ParameterTypeAnyOf {
    fn parse(schema: &Value, registry: &mut SchemaRegistry) -> Self {
        let branches = schema
            .get("anyOf")
            .and_then(Value::as_array)
            .map(|arr| {
                arr.iter()
                    .map(|s| parse_parameter_type(s, registry))
                    .collect()
            })
            .unwrap_or_default();
        Self {
            base: BaseType::from_extra_props(schema, &[]),
            branches,
        }
    }

    fn to_typescript(&self, indent: &str, registry: &SchemaRegistry) -> String {
        self.branches
            .iter()
            .map(|b| b.to_typescript(indent, registry))
            .collect::<Vec<_>>()
            .join(" | ")
    }
}

struct ParameterTypeUnion {
    base: BaseType,
    types: Vec<String>,
}

struct ParameterTypeRef {
    base: BaseType,
    ref_name: String,
}

impl ParameterTypeUnion {
    fn parse(schema: &Value) -> Self {
        let raw_types = schema
            .get("type")
            .and_then(Value::as_array)
            .map(|arr| arr.iter().filter_map(Value::as_str).collect::<Vec<_>>())
            .unwrap_or_default();
        let types = raw_types
            .into_iter()
            .map(|t| match t {
                "string" => "string".to_string(),
                "number" => "number".to_string(),
                "integer" => "number".to_string(),
                "boolean" => "boolean".to_string(),
                "null" => "null".to_string(),
                "object" => "{}".to_string(),
                "array" => "Array<any>".to_string(),
                other => other.to_string(),
            })
            .collect();
        Self {
            base: BaseType::from_extra_props(schema, &[]),
            types,
        }
    }

    fn to_typescript(&self) -> String {
        self.types.join(" | ")
    }
}

impl ParameterTypeRef {
    fn parse(schema: &Value, registry: &mut SchemaRegistry) -> Self {
        let reference = schema.get("$ref").and_then(Value::as_str).unwrap_or("");
        let resolved = registry.resolve_ref(reference);
        let ref_name = match resolved {
            Some(ref v) if v.get("$self_ref").and_then(Value::as_bool) == Some(true) => {
                "parameters".to_string()
            }
            Some(_) => reference.rsplit('/').next().unwrap_or("").to_string(),
            None => "any".to_string(),
        };
        Self {
            base: BaseType::from_extra_props(schema, &[]),
            ref_name,
        }
    }

    fn to_typescript(&self) -> String {
        self.ref_name.clone()
    }
}

fn parse_parameter_type(schema: &Value, registry: &mut SchemaRegistry) -> ParameterType {
    if registry.depth >= MAX_RECURSION_DEPTH {
        return ParameterType::Scalar(ParameterTypeScalar::any());
    }
    registry.depth += 1;
    let result = parse_parameter_type_inner(schema, registry);
    registry.depth -= 1;
    result
}

fn parse_parameter_type_inner(schema: &Value, registry: &mut SchemaRegistry) -> ParameterType {
    if schema.is_boolean() {
        return ParameterType::Scalar(ParameterTypeScalar {
            base: BaseType::default(),
            typ: if schema.as_bool() == Some(true) {
                "any"
            } else {
                "null"
            }
            .to_string(),
        });
    }
    let obj = match schema.as_object() {
        Some(o) => o,
        // A non-object, non-boolean schema is malformed; upstream raises.
        None => {
            registry.unsupported = true;
            return ParameterType::Scalar(ParameterTypeScalar::any());
        }
    };

    if obj.contains_key("$ref") {
        return ParameterType::Ref(ParameterTypeRef::parse(schema, registry));
    }

    if obj.contains_key("anyOf") {
        return ParameterType::AnyOf(ParameterTypeAnyOf::parse(schema, registry));
    }
    if obj.contains_key("enum") {
        return ParameterType::Enum(ParameterTypeEnum::parse(schema));
    }

    if let Some(typ_value) = obj.get("type") {
        if typ_value.is_array() {
            return ParameterType::Union(ParameterTypeUnion::parse(schema));
        }
        if let Some(typ) = typ_value.as_str() {
            return match typ {
                "object" => ParameterType::Object(ParameterTypeObject::parse(schema, registry)),
                "array" => ParameterType::Array(ParameterTypeArray::parse(schema, registry)),
                other => ParameterType::Scalar(ParameterTypeScalar::parse(other, schema)),
            };
        }
    }
    if obj.is_empty() {
        // Upstream maps the empty schema `{}` to `any`.
        return ParameterType::Scalar(ParameterTypeScalar::any());
    }
    // Fallthrough: a non-empty schema with no type/anyOf/enum/$ref. Upstream
    // raises `ValueError(f"Invalid JSON Schema object: ...")` here; flag it so
    // the caller drops the TS namespace and falls back to JSON.
    registry.unsupported = true;
    ParameterType::Scalar(ParameterTypeScalar::any())
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

fn format_description(description: &str, indent: &str) -> String {
    description
        .split('\n')
        .map(|line| {
            if line.is_empty() {
                String::new()
            } else {
                format!("{indent}// {line}")
            }
        })
        .collect::<Vec<_>>()
        .join("\n")
}

fn json_inline(v: &Value) -> String {
    match v {
        Value::String(s) => s.clone(),
        Value::Bool(b) => b.to_string(),
        Value::Number(n) => n.to_string(),
        Value::Null => "null".to_string(),
        other => serde_json::to_string(other).unwrap_or_default(),
    }
}