che-rest 0.4.0

Typed REST framework and project tooling for che-orm applications
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
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
use std::{collections::BTreeMap, fs, path::Path};

use crate::module::{ApiEndpoint, ApiSignal};
use crate::rest::Lookup;

const HEADER: &str = "// This file is generated by che-rest. Do not edit manually.\n// Run the appropriate che-rest management generator to update it.\n\n";

pub fn generate(
    out: &Path,
    endpoints: &[ApiEndpoint],
    signals: &[ApiSignal],
    include_auth: bool,
) -> Result<Vec<String>, std::io::Error> {
    fs::create_dir_all(out)?;
    let files = [
        ("api_client.ts", api_client()),
        ("channels.ts", channels(signals)),
        ("models.ts", models(endpoints)),
        ("api.ts", api(endpoints)),
        ("useModelList.ts", use_model_list()),
        ("useModelItem.ts", use_model_item()),
    ];
    let mut written = Vec::new();
    for (name, content) in files {
        let content = content.trim_end_matches('\n').to_owned() + "\n";
        fs::write(out.join(name), content)?;
        written.push(name.to_owned());
    }
    if include_auth {
        let content = auth().trim_end_matches('\n').to_owned() + "\n";
        fs::write(out.join("auth.ts"), content)?;
        written.push("auth.ts".to_owned());
    }
    Ok(written)
}

fn models(endpoints: &[ApiEndpoint]) -> String {
    let mut out = HEADER.to_owned();
    out.push_str("import type { ListParams } from \"./api_client\";\n\n");
    out.push_str("export type JsonValue = null | boolean | number | string | JsonValue[] | { [key: string]: JsonValue };\n\n");
    let mut related = BTreeMap::new();
    for endpoint in unique_models(endpoints) {
        out.push_str(&format!("export interface {} {{\n", endpoint.model_name));
        for field in endpoint.fields.iter().filter(|field| !field.write_only) {
            out.push_str(&format!(
                "  {}: {};\n",
                field.name,
                field_ts_type(endpoint, field)
            ));
            if let Some(model) = field.related_model {
                related.insert(last_path_part(model), (field.many, field.rust_type));
            }
        }
        out.push_str("}\n\n");
        if endpoint.list_fields != endpoint.fields {
            out.push_str(&format!(
                "export interface {}ListItem {{\n",
                endpoint.model_name
            ));
            for field in endpoint
                .list_fields
                .iter()
                .filter(|field| !field.write_only)
            {
                out.push_str(&format!(
                    "  {}: {};\n",
                    field.name,
                    field_ts_type(endpoint, field)
                ));
                if let Some(model) = field.related_model {
                    related.insert(last_path_part(model), (field.many, field.rust_type));
                }
            }
            out.push_str("}\n\n");
        }
        out.push_str(&format!(
            "export interface {}Create {{\n",
            endpoint.model_name
        ));
        for field in endpoint.fields.iter().filter(|field| {
            !field.read_only && (field.related_model.is_none() || field.name == field.source)
        }) {
            out.push_str(&format!(
                "  {}{}: {};\n",
                field.name,
                if field_required(endpoint, field) {
                    ""
                } else {
                    "?"
                },
                field_ts_type(endpoint, field)
            ));
        }
        out.push_str("}\n\n");
        out.push_str(&format!(
            "export interface {}Update {{\n",
            endpoint.model_name
        ));
        for field in endpoint.fields.iter().filter(|field| {
            !field.read_only && (field.related_model.is_none() || field.name == field.source)
        }) {
            out.push_str(&format!(
                "  {}?: {};\n",
                field.name,
                field_ts_type(endpoint, field)
            ));
        }
        out.push_str("}\n\n");
        out.push_str(&format!(
            "export interface {}ListParams extends ListParams {{\n",
            endpoint.model_name
        ));
        for filter in &endpoint.filters {
            let suffix = match filter.lookup {
                Lookup::Exact => "",
                Lookup::Contains => "__contains",
                Lookup::Gt => "__gt",
                Lookup::Gte => "__gte",
                Lookup::Lt => "__lt",
                Lookup::Lte => "__lte",
            };
            out.push_str(&format!(
                "  {}{}?: {};\n",
                filter.name,
                suffix,
                filter_ts_type(endpoint, filter.source)
            ));
        }
        out.push_str("}\n\n");
    }
    for model in related.keys() {
        if endpoints
            .iter()
            .any(|endpoint| endpoint.model_name == *model)
        {
            continue;
        }
        out.push_str(&format!(
            "export interface {} {{\n  id: number;\n  [key: string]: unknown;\n}}\n\n",
            model
        ));
    }
    let mut extension_schemas = BTreeMap::new();
    for endpoint in endpoints {
        for extension in &endpoint.extensions {
            for operation in &extension.operations {
                if let Some(schema) = &operation.request {
                    extension_schemas.insert(schema.name, schema.typescript);
                }
                if let Some((_, schema)) = &operation.response {
                    extension_schemas.insert(schema.name, schema.typescript);
                }
            }
        }
    }
    for definition in extension_schemas.into_values() {
        out.push_str(definition);
        out.push_str("\n\n");
    }
    out
}

fn api(endpoints: &[ApiEndpoint]) -> String {
    let mut out = HEADER.to_owned();
    out.push_str("import { apiClient, createModelApi } from \"./api_client\";\nimport type {\n");
    for endpoint in unique_models(endpoints) {
        out.push_str(&format!(
            "  {},\n  {}Create,\n  {}Update,\n  {}ListParams,\n",
            endpoint.model_name, endpoint.model_name, endpoint.model_name, endpoint.model_name
        ));
        if endpoint.list_fields != endpoint.fields {
            out.push_str(&format!("  {}ListItem,\n", endpoint.model_name));
        }
    }
    let mut extension_types = BTreeMap::new();
    for endpoint in endpoints {
        for extension in &endpoint.extensions {
            for operation in &extension.operations {
                if let Some(schema) = &operation.request {
                    extension_types.insert(schema.name, ());
                }
                if let Some((_, schema)) = &operation.response {
                    extension_types.insert(schema.name, ());
                }
            }
        }
    }
    for schema in extension_types.keys() {
        out.push_str(&format!("  {schema},\n"));
    }
    out.push_str("} from \"./models\";\n\n");
    for endpoint in endpoints {
        let name = api_name(endpoint, endpoints);
        let id_type = endpoint
            .fields
            .iter()
            .find(|field| field.source == "id")
            .map(|field| field_ts_type(endpoint, field))
            .unwrap_or_else(|| "number".into());
        let list_item = if endpoint.list_fields == endpoint.fields {
            endpoint.model_name.clone()
        } else {
            format!("{}ListItem", endpoint.model_name)
        };
        if endpoint.extensions.is_empty() {
            out.push_str(&format!(
                "export const {name}Api = createModelApi<{}, {}Create, {}Update, {}ListParams, {list_item}>(\"{}\");\n",
                endpoint.model_name, endpoint.model_name, endpoint.model_name, endpoint.model_name, endpoint.resource
            ));
            continue;
        }
        if !endpoint.crud {
            out.push_str(&format!("export const {name}Api = {{\n"));
        } else {
            out.push_str(&format!(
            "const {name}Crud = createModelApi<{}, {}Create, {}Update, {}ListParams, {list_item}>(\"{}\");\nexport const {name}Api = {{\n  ...{name}Crud,\n",
            endpoint.model_name, endpoint.model_name, endpoint.model_name, endpoint.model_name, endpoint.resource
        ));
        }
        for extension in &endpoint.extensions {
            let mut operations = extension
                .operations
                .iter()
                .filter_map(|operation| operation.client.as_ref().map(|client| (operation, client)))
                .collect::<Vec<_>>();
            operations.sort_by_key(|(_, client)| client.name);
            if operations.is_empty() {
                continue;
            }
            let namespace = operations[0].1.namespace;
            out.push_str(&format!("  {namespace}: {{\n"));
            for (operation, client) in operations {
                if extension.id == "model-sync" && client.name == "changes" {
                    out.push_str(&format!("    async changes(after: string = '0', limit: number = 100): Promise<ModelChanges> {{ return (await apiClient.get<ModelChanges>(`{}`, {{ params: {{ after, limit }} }})).data; }},\n", operation.path.trim_start_matches('/')));
                    continue;
                }
                let path = operation
                    .path
                    .trim_start_matches('/')
                    .replace("{id}", "${id}");
                let response = operation
                    .response
                    .as_ref()
                    .map(|(_, schema)| schema.name)
                    .unwrap_or("void");
                let has_id = path.contains("${id}");
                if operation.multipart {
                    let extras = "if (fields) for (const [key, value] of Object.entries(fields)) data.append(key, value);";
                    match (operation.method, has_id) {
                        (crate::HttpMethod::Put | crate::HttpMethod::Post, true) => out.push_str(&format!(
                            "    async {}(id: {id_type}, file: Blob, fields?: Record<string, string | Blob>): Promise<{}> {{ const data = new FormData(); data.append(\"file\", file, file instanceof File ? file.name : \"image.png\"); {extras} return (await apiClient.{}<{}>(`{}`, data, {{ headers: {{ \"Content-Type\": undefined }} }})).data; }},\n",
                            client.name, response, operation.method.openapi_key(), response, path
                        )),
                        (crate::HttpMethod::Post, false) => out.push_str(&format!(
                            "    async {}(file: Blob, fields?: Record<string, string | Blob>): Promise<{}> {{ const data = new FormData(); data.append(\"file\", file, file instanceof File ? file.name : \"image.png\"); {extras} return (await apiClient.post<{}>(`{}`, data, {{ headers: {{ \"Content-Type\": undefined }} }})).data; }},\n",
                            client.name, response, response, path
                        )),
                        (crate::HttpMethod::Delete, true) => out.push_str(&format!(
                            "    async {}(id: {id_type}, fields?: Record<string, string | Blob>): Promise<void> {{ const data = new FormData(); {extras} await apiClient.delete(`{}`, {{ data, headers: {{ \"Content-Type\": undefined }} }}); }},\n",
                            client.name, path
                        )),
                        _ => {}
                    }
                    continue;
                }
                match (&operation.request, operation.method) {
                    (Some(request), crate::HttpMethod::Post | crate::HttpMethod::Put | crate::HttpMethod::Patch) if has_id => out.push_str(&format!(
                        "    async {}(id: {id_type}, payload: {}): Promise<{}> {{ return (await apiClient.{}<{}>(`{}`, payload)).data; }},\n",
                        client.name, request.name, response, operation.method.openapi_key(), response, path
                    )),
                    (Some(request), crate::HttpMethod::Post | crate::HttpMethod::Put | crate::HttpMethod::Patch) => out.push_str(&format!(
                        "    async {}(payload: {}): Promise<{}> {{ return (await apiClient.{}<{}>(`{}`, payload)).data; }},\n",
                        client.name, request.name, response, operation.method.openapi_key(), response, path
                    )),
                    (None, crate::HttpMethod::Get) if has_id => out.push_str(&format!(
                        "    async {}(id: {id_type}): Promise<{}> {{ return (await apiClient.get<{}>(`{}`)).data; }},\n",
                        client.name, response, response, path
                    )),
                    (None, crate::HttpMethod::Get) => out.push_str(&format!(
                        "    async {}(): Promise<{}> {{ return (await apiClient.get<{}>(`{}`)).data; }},\n",
                        client.name, response, response, path
                    )),
                    (None, crate::HttpMethod::Post) if has_id => out.push_str(&format!(
                        "    async {}(id: {id_type}): Promise<{}> {{ return (await apiClient.post<{}>(`{}`)).data; }},\n",
                        client.name, response, response, path
                    )),
                    (None, crate::HttpMethod::Post) => out.push_str(&format!(
                        "    async {}(): Promise<{}> {{ return (await apiClient.post<{}>(`{}`)).data; }},\n",
                        client.name, response, response, path
                    )),
                    _ => {}
                }
            }
            out.push_str("  },\n");
        }
        out.push_str("};\n");
    }
    out
}

fn field_ts_type(endpoint: &ApiEndpoint, field: &che_orm::SerializerField) -> String {
    if let Some(model) = field.related_model {
        if field.name == field.source {
            let nullable = endpoint
                .columns
                .iter()
                .find(|column| column.name == field.source || column.field_name == field.source)
                .is_some_and(|column| column.nullable);
            let scalar = if field.rust_type.contains("Uuid") {
                "string"
            } else {
                "number"
            };
            return if nullable {
                format!("{scalar} | null")
            } else {
                scalar.into()
            };
        }
        let ty = last_path_part(model);
        return if field.many {
            format!("{}[]", ty)
        } else {
            ty.to_owned()
        };
    }
    if let Some(choices) = endpoint
        .columns
        .iter()
        .find(|column| column.name == field.source || column.field_name == field.source)
        .and_then(|column| column.choices.as_ref())
    {
        let ty = choices
            .iter()
            .map(|choice| serde_json::to_string(choice).unwrap())
            .collect::<Vec<_>>()
            .join(" | ");
        let nullable = endpoint
            .columns
            .iter()
            .find(|column| column.name == field.source || column.field_name == field.source)
            .is_some_and(|column| column.nullable);
        return if nullable { format!("{ty} | null") } else { ty };
    }
    let ty = match field.rust_type {
        value
            if value.contains("i64")
                || value.contains("i32")
                || value.contains("u64")
                || value.contains("f64")
                || value.contains("usize") =>
        {
            "number".into()
        }
        "bool" => "boolean".into(),
        "String" | "&str" | "Option<String>" => "string".into(),
        value if value.contains("ImageField") => "string".into(),
        value if value.contains("JsonField") => "JsonValue".into(),
        value if value.contains("Uuid") => "string".into(),
        value if value.contains("OffsetDateTime") => "string".into(),
        _ => "unknown".into(),
    };
    let nullable = endpoint
        .columns
        .iter()
        .find(|column| column.name == field.source || column.field_name == field.source)
        .is_some_and(|column| column.nullable);
    if nullable { format!("{ty} | null") } else { ty }
}

fn field_required(endpoint: &ApiEndpoint, field: &che_orm::SerializerField) -> bool {
    endpoint
        .columns
        .iter()
        .find(|column| column.name == field.source || column.field_name == field.source)
        .is_some_and(|column| !column.nullable && !column.has_default)
}

fn filter_ts_type(endpoint: &ApiEndpoint, source: &str) -> String {
    if let Some(choices) = endpoint
        .columns
        .iter()
        .find(|column| column.name == source)
        .and_then(|column| column.choices.as_ref())
    {
        return choices
            .iter()
            .map(|choice| serde_json::to_string(choice).unwrap())
            .collect::<Vec<_>>()
            .join(" | ");
    }
    match endpoint
        .columns
        .iter()
        .find(|column| column.name == source || column.field_name == source)
        .map(|column| column.column_type)
    {
        Some(che_orm::ColumnType::Integer | che_orm::ColumnType::Real) => "number",
        Some(che_orm::ColumnType::Boolean) => "boolean",
        _ => "string",
    }
    .into()
}

fn last_path_part(value: &str) -> &str {
    value.rsplit("::").next().unwrap_or(value).trim()
}

fn lower_first(value: &str) -> String {
    let mut chars = value.chars();
    chars
        .next()
        .map(|c| c.to_ascii_lowercase())
        .into_iter()
        .chain(chars)
        .collect()
}

fn unique_models(endpoints: &[ApiEndpoint]) -> Vec<&ApiEndpoint> {
    let mut models = BTreeMap::new();
    for endpoint in endpoints.iter().filter(|endpoint| endpoint.crud) {
        models
            .entry(endpoint.model_name.as_str())
            .or_insert(endpoint);
    }
    models.into_values().collect()
}

fn api_name(endpoint: &ApiEndpoint, endpoints: &[ApiEndpoint]) -> String {
    if endpoints
        .iter()
        .filter(|item| item.model_name == endpoint.model_name)
        .count()
        == 1
    {
        return lower_first(&endpoint.model_name);
    }
    endpoint
        .resource
        .split('/')
        .next_back()
        .unwrap_or(&endpoint.resource)
        .trim_end_matches('s')
        .split('-')
        .enumerate()
        .map(|(index, part)| {
            if index == 0 {
                part.to_owned()
            } else {
                let mut chars = part.chars();
                chars
                    .next()
                    .map(|first| first.to_ascii_uppercase())
                    .into_iter()
                    .chain(chars)
                    .collect()
            }
        })
        .collect()
}

fn api_client() -> String {
    let mut out = HEADER.to_owned();
    out.push_str(&
        r##"import axios from "axios";

export interface BaseEntity { id?: number | string; }
export interface ListParams {{ ordering?: string; limit?: number; offset?: number; [key: string]: string | number | boolean | null | undefined; }}
export interface PaginatedResponse<T> {{ count: number; results: T[]; }}
export interface ModelApi<T extends BaseEntity, CreateDTO = Partial<T>, UpdateDTO = Partial<T>, Params extends ListParams = ListParams, ListItem extends BaseEntity = T> {{
  list: (params?: Params) => Promise<PaginatedResponse<ListItem>>;
  retrieve: (id: number | string) => Promise<T>;
  create: (payload: CreateDTO) => Promise<T | null>;
  update: (id: number | string, payload: UpdateDTO) => Promise<T | null>;
  remove: (id: number | string) => Promise<void>;
}}
 export const apiClient = axios.create({{ baseURL: import.meta.env.VITE_API_BASE_URL ?? "/api", withCredentials: true, xsrfCookieName: "csrf_token", xsrfHeaderName: "X-CSRF-Token", headers: {{ "Content-Type": "application/json" }} }});
let authToken: string | null = null;
export function setAuthToken(token: string | null) {{ authToken = token; }}
apiClient.interceptors.request.use((config) => {{ if (authToken) config.headers.Authorization = `Token ${{authToken}}`; else delete config.headers.Authorization; return config; }});
export function createModelApi<T extends BaseEntity, CreateDTO = Partial<T>, UpdateDTO = Partial<T>, Params extends ListParams = ListParams, ListItem extends BaseEntity = T>(resource: string): ModelApi<T, CreateDTO, UpdateDTO, Params, ListItem> {{
  const normalized = resource.endsWith("/") ? resource : `${{resource}}/`;
  return {{
    async list(params) {{ return (await apiClient.get<PaginatedResponse<ListItem>>(normalized, {{ params }})).data; }},
    async retrieve(id) {{ return (await apiClient.get<T>(`${{normalized}}${{id}}/`)).data; }},
    async create(payload) {{ return (await apiClient.post<T | null>(normalized, payload)).data || null; }},
    async update(id, payload) {{ return (await apiClient.patch<T | null>(`${{normalized}}${{id}}/`, payload)).data || null; }},
    async remove(id) {{ await apiClient.delete(`${{normalized}}${{id}}/`); }},
  }};
}}
"##
            .replace("{{", "{")
            .replace("}}", "}"),
    );
    out
}

fn channels(signals: &[ApiSignal]) -> String {
    let signal_names = if signals.is_empty() {
        "string".to_owned()
    } else {
        signals
            .iter()
            .map(|signal| format!("\"{}\"", signal.name))
            .collect::<Vec<_>>()
            .join(" | ")
    };
    format!(
        r#"{HEADER}export type SignalName = {signal_names};
export interface SignalMessage<T = unknown> {{
  type: "signal";
  signal: SignalName;
  payload: T;
}}
export interface ChannelError {{ type: "error"; code: string; detail: string; }}
export interface ChannelSubscriptionEvent {{ type: "subscribed" | "unsubscribed"; signal: SignalName; }}
export type ChannelEvent<T = unknown> = SignalMessage<T> | ChannelError | ChannelSubscriptionEvent;
export interface ChannelClientOptions {{ url?: string; onEvent?: (event: ChannelEvent) => void; onMessage?: (event: SignalMessage) => void; onError?: (event: ChannelError) => void; onClose?: (event: CloseEvent) => void; }}
export class ChannelClient {{
  private socket: WebSocket | null = null;
  private readonly eventListeners = new Set<(event: ChannelEvent) => void>();
  private readonly messageListeners = new Set<(event: SignalMessage) => void>();
  private readonly errorListeners = new Set<(event: ChannelError) => void>();
  constructor(private readonly options: ChannelClientOptions = {{}}) {{
    if (options.onEvent) this.eventListeners.add(options.onEvent);
    if (options.onMessage) this.messageListeners.add(options.onMessage);
    if (options.onError) this.errorListeners.add(options.onError);
  }}
  connect(): Promise<void> {{
    if (this.socket?.readyState === WebSocket.OPEN) return Promise.resolve();
    const socket = new WebSocket(this.options.url ?? defaultChannelUrl());
    this.socket = socket;
    socket.addEventListener("message", (message) => this.handleMessage(message));
    return new Promise((resolve, reject) => {{
      socket.addEventListener("open", () => resolve(), {{ once: true }});
      socket.addEventListener("error", () => reject(new Error("Unable to connect to WebSocket channels")), {{ once: true }});
      socket.addEventListener("close", (event) => this.options.onClose?.(event));
    }});
  }}
  subscribe(signal: SignalName) {{ this.send({{ action: "subscribe", signal }}); }}
  unsubscribe(signal: SignalName) {{ this.send({{ action: "unsubscribe", signal }}); }}
  onEvent(listener: (event: ChannelEvent) => void) {{ this.eventListeners.add(listener); return () => this.eventListeners.delete(listener); }}
  onMessage(listener: (event: SignalMessage) => void) {{ this.messageListeners.add(listener); return () => this.messageListeners.delete(listener); }}
  onError(listener: (event: ChannelError) => void) {{ this.errorListeners.add(listener); return () => this.errorListeners.delete(listener); }}
  close(code?: number, reason?: string) {{ this.socket?.close(code, reason); this.socket = null; }}
  private send(payload: unknown) {{
    if (!this.socket || this.socket.readyState !== WebSocket.OPEN) throw new Error("WebSocket channel client is not connected");
    this.socket.send(JSON.stringify(payload));
  }}
  private handleMessage(message: MessageEvent<string>) {{
    try {{
      const event = JSON.parse(message.data) as ChannelEvent;
      for (const listener of this.eventListeners) listener(event);
      if (event.type === "signal") for (const listener of this.messageListeners) listener(event);
      if (event.type === "error") for (const listener of this.errorListeners) listener(event);
    }} catch {{}}
  }}
}}
function defaultChannelUrl() {{
  const base = new URL(import.meta.env.VITE_API_BASE_URL ?? "/api", window.location.origin);
  base.protocol = base.protocol === "https:" ? "wss:" : "ws:";
  base.pathname = `${{base.pathname.replace(/\/$/, "")}}/ws/`;
  return base.toString();
}}
"#
    )
}
fn use_model_list() -> String {
    format!(
        r#"{HEADER}import {{ onMounted, reactive, ref, shallowRef, watch }} from "vue";
import type {{ BaseEntity, ListParams, ModelApi }} from "./api_client";

export interface UseModelListOptions<Params extends ListParams> {{
  defaultFilters?: Partial<Params>;
  autoLoad?: boolean;
  reloadOnFilterChange?: boolean;
  debounceMs?: number;
  onError?: (message: string, error: unknown) => void;
}}

export function useModelList<T extends BaseEntity, CreateDTO = Partial<T>, UpdateDTO = Partial<T>, Params extends ListParams = ListParams, ListItem extends BaseEntity = T>(api: ModelApi<T, CreateDTO, UpdateDTO, Params, ListItem>, options: UseModelListOptions<Params> = {{}}) {{
  const items = shallowRef<ListItem[]>([]);
  const filters = reactive({{ ...(options.defaultFilters ?? {{}}) }} as Params) as Params;
  const count = ref(0); const loading = ref(false); const error = ref("");
   let loadTimer: ReturnType<typeof setTimeout> | undefined; let skipNextFilterReload = false; let requestSequence = 0;
   async function load(params?: Partial<Params>) {{
     const request = ++requestSequence;
     if (params) {{ skipNextFilterReload = true; Object.assign(filters, params); }}
     loading.value = true; error.value = "";
     try {{ const response = await api.list(cleanParams(filters) as Params); if (request !== requestSequence) return null; items.value = response.results; count.value = response.count; return response; }}
     catch (err) {{ if (request === requestSequence) handleError(err, "Unable to load objects"); return null; }} finally {{ if (request === requestSequence) loading.value = false; }}
   }}
  async function remove(id: number | string) {{ loading.value = true; try {{ await api.remove(id); await load(); return true; }} catch (err) {{ handleError(err, "Unable to delete object"); return false; }} finally {{ loading.value = false; }} }}
  if (options.reloadOnFilterChange) watch(filters, () => {{ if (skipNextFilterReload) {{ skipNextFilterReload = false; return; }} clearTimeout(loadTimer); loadTimer = setTimeout(() => load(), options.debounceMs ?? 250); }});
  if (options.autoLoad) onMounted(() => load());
  function handleError(err: unknown, fallback: string) {{ const message = errorMessage(err, fallback); error.value = message; options.onError?.(message, err); }}
  return {{ items, filters, count, loading, error, load, remove }};
}}
function cleanParams(params: ListParams) {{ const clean: ListParams = {{}}; for (const [key, value] of Object.entries(params)) if (value !== "" && value !== null && value !== undefined) clean[key] = value; return clean; }}
function errorMessage(err: unknown, fallback: string) {{ if (typeof err === "object" && err && "detail" in err) return String((err as {{ detail: unknown }}).detail); return err instanceof Error ? err.message : fallback; }}
"#
    )
}
fn use_model_item() -> String {
    format!(
        r#"{HEADER}import {{ shallowRef, ref }} from "vue";
import type {{ BaseEntity, ListParams, ModelApi }} from "./api_client";
export interface UseModelItemOptions {{ onError?: (message: string, error: unknown) => void; }}
export function useModelItem<T extends BaseEntity, CreateDTO = Partial<T>, UpdateDTO = Partial<T>, Params extends ListParams = ListParams, ListItem extends BaseEntity = T>(api: ModelApi<T, CreateDTO, UpdateDTO, Params, ListItem>, options: UseModelItemOptions = {{}}) {{
  const item = shallowRef<T | null>(null); const loading = ref(false); const error = ref("");
  async function retrieve(id: number | string) {{ return run(() => api.retrieve(id), "Unable to load object"); }}
  async function create(payload: CreateDTO) {{ return run(() => api.create(payload), "Unable to create object"); }}
  async function update(id: number | string, payload: UpdateDTO) {{ return run(() => api.update(id, payload), "Unable to update object"); }}
  async function remove(id: number | string) {{ return run(async () => {{ await api.remove(id); item.value = null; return true; }}, "Unable to delete object"); }}
  async function run<R>(operation: () => Promise<R>, fallback: string): Promise<R | null> {{ loading.value = true; error.value = ""; try {{ const value = await operation(); if (value === null) item.value = null; else if (typeof value === "object") item.value = value as T; return value; }} catch (err) {{ error.value = err instanceof Error ? err.message : fallback; options.onError?.(error.value, err); return null; }} finally {{ loading.value = false; }} }}
  return {{ item, loading, error, retrieve, create, update, remove }};
}}
"#
    )
}

fn auth() -> String {
    format!(
        r#"{HEADER}import axios from "axios";

export interface LoginRequest {{ username: string; password: string; }}
export interface AuthUser {{ id: number; username: string; is_staff: boolean; is_admin: boolean; is_superuser: boolean; }}
export interface SessionLoginResponse {{ user: AuthUser; expires_at: string; }}
export interface SessionInfo {{ id: number; user_id: number; revision: number; expires_at: string; }}
export interface SessionMeResponse {{ user: AuthUser; session: SessionInfo | null; }}
export interface TokenLoginResponse {{ token: string; }}

const authClient = axios.create({{
  baseURL: import.meta.env.VITE_AUTH_BASE_URL ?? "",
  withCredentials: true,
  xsrfCookieName: "csrf_token",
  xsrfHeaderName: "X-CSRF-Token",
  headers: {{ "Content-Type": "application/json" }},
}});

export const sessionAuth = {{
  async login(payload: LoginRequest): Promise<SessionLoginResponse> {{
    return (await authClient.post<SessionLoginResponse>("/api-session-auth/login/", payload)).data;
  }},
  async logout(): Promise<void> {{ await authClient.post("/api-session-auth/logout/"); }},
  async me(): Promise<SessionMeResponse> {{
    return (await authClient.get<SessionMeResponse>("/api-session-auth/me/")).data;
  }},
}};

export const tokenAuth = {{
  async login(payload: LoginRequest): Promise<TokenLoginResponse> {{
    return (await authClient.post<TokenLoginResponse>("/api-token-auth/", payload)).data;
  }},
}};
"#
    )
}

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

    #[test]
    fn multipart_image_actions_generate_formdata_put_and_delete_methods() {
        let operation = |method, name, response| crate::ApiOperation {
            extension_id: "image-field",
            operation_id: format!("image.{name}"),
            method,
            path: "/boards/{id}/images/preview/".into(),
            request: None,
            response,
            client: Some(crate::ClientMethod {
                namespace: "preview",
                name,
            }),
            multipart: true,
            openapi: serde_json::json!({}),
        };
        let mut endpoint = ApiEndpoint {
            crud: true,
            app_name: "boards",
            model_name: "Board".into(),
            resource: "boards".into(),
            fields: vec![],
            list_fields: vec![],
            columns: vec![],
            filters: vec![],
            extensions: vec![crate::ApiExtension {
                id: "image-field",
                operations: vec![
                    operation(
                        crate::HttpMethod::Put,
                        "replace",
                        Some((
                            200,
                            crate::ApiSchemaDefinition {
                                name: "ImageUploadResponse",
                                openapi: serde_json::json!({}),
                                typescript: "export interface ImageUploadResponse { url: string; }",
                            },
                        )),
                    ),
                    operation(crate::HttpMethod::Delete, "clear", None),
                ],
            }],
        };
        let output = api(&[endpoint.clone()]);
        assert!(output.contains("async replace(id: number, file: Blob"));
        assert!(output.contains("data.append(\"file\", file"));
        assert!(output.contains("async clear(id: number, fields?"));
        assert!(output.contains("apiClient.delete(`boards/${id}/images/preview/`"));
        endpoint.fields.push(che_orm::SerializerField {
            name: "id",
            source: "id",
            read_only: true,
            write_only: false,
            rust_type: "che_orm::Uuid",
            related_model: None,
            many: false,
        });
        let mut actions = endpoint.clone();
        actions.crud = false;
        let action_output = api(&[actions.clone()]);
        assert!(action_output.contains("export const boardApi = {"));
        assert!(!action_output.contains("const boardCrud"));
        assert!(!models(&[actions]).contains("export interface Board {"));
        let uuid_output = api(&[endpoint]);
        assert!(uuid_output.contains("async replace(id: string, file: Blob"));
        assert!(uuid_output.contains("async clear(id: string, fields?"));
    }

    #[test]
    fn image_field_uses_nullable_storage_column_even_with_db_column_alias() {
        let field = che_orm::SerializerField {
            name: "preview",
            source: "preview",
            read_only: true,
            write_only: false,
            rust_type: "Option<che_orm::ImageField>",
            related_model: None,
            many: false,
        };
        let endpoint = ApiEndpoint {
            crud: true,
            app_name: "diagrams",
            model_name: "Board".into(),
            resource: "boards".into(),
            fields: vec![field],
            list_fields: vec![field],
            columns: vec![crate::module::ApiColumn {
                name: "preview_storage_name",
                field_name: "preview",
                column_type: che_orm::ColumnType::Text,
                nullable: true,
                has_default: false,
                choices: None,
            }],
            filters: vec![],
            extensions: vec![],
        };
        assert_eq!(field_ts_type(&endpoint, &field), "string | null");
    }

    #[test]
    fn generates_nested_model_and_typed_write_dtos() {
        let endpoint = ApiEndpoint {
            crud: true,
            app_name: "tasks",
            model_name: "Task".into(),
            resource: "tasks".into(),
            fields: vec![
                che_orm::SerializerField {
                    name: "id",
                    source: "id",
                    read_only: true,
                    write_only: false,
                    rust_type: "i64",
                    related_model: None,
                    many: false,
                },
                che_orm::SerializerField {
                    name: "author",
                    source: "author_id",
                    read_only: true,
                    write_only: false,
                    rust_type: "AuthorSerializer",
                    related_model: Some("che_rest::auth::models::User"),
                    many: false,
                },
                che_orm::SerializerField {
                    name: "name",
                    source: "name",
                    read_only: false,
                    write_only: false,
                    rust_type: "String",
                    related_model: None,
                    many: false,
                },
                che_orm::SerializerField {
                    name: "status",
                    source: "status",
                    read_only: false,
                    write_only: false,
                    rust_type: "TaskStatus",
                    related_model: None,
                    many: false,
                },
                che_orm::SerializerField {
                    name: "config",
                    source: "config",
                    read_only: false,
                    write_only: false,
                    rust_type: "che_orm::JsonField",
                    related_model: None,
                    many: false,
                },
            ],
            list_fields: vec![],
            columns: vec![crate::module::ApiColumn {
                name: "status",
                field_name: "status",
                column_type: che_orm::ColumnType::Text,
                nullable: false,
                has_default: false,
                choices: Some(vec!["draft", "in_progress", "done"]),
            }],
            filters: vec![
                crate::module::ApiFilter {
                    name: "name",
                    source: "name",
                    lookup: Lookup::Contains,
                },
                crate::module::ApiFilter {
                    name: "status",
                    source: "status",
                    lookup: Lookup::Exact,
                },
            ],
            extensions: vec![],
        };

        let generated = models(&[endpoint]);
        assert!(generated.contains("author: User;"));
        assert!(generated.contains("config: JsonValue;"));
        assert!(generated.contains("name: string;"));
        assert!(generated.contains("status: \"draft\" | \"in_progress\" | \"done\";"));
        assert!(generated.contains("name__contains?: string;"));
        assert!(generated.contains("status?: \"draft\" | \"in_progress\" | \"done\";"));
        assert!(!generated.contains("id: number;\n}\n\nexport interface TaskCreate"));
    }

    #[test]
    fn generated_helpers_keep_typed_and_eventful_apis() {
        assert!(use_model_list().contains("UseModelListOptions"));
        assert!(use_model_list().contains("ModelApi<T"));
        assert!(use_model_item().contains("UseModelItemOptions"));
        assert!(channels(&[]).contains("onEvent"));
        assert!(channels(&[]).contains("onClose"));
    }

    #[test]
    fn list_serializer_generates_distinct_item_type() {
        let id = che_orm::SerializerField {
            name: "id",
            source: "id",
            read_only: true,
            write_only: false,
            rust_type: "i64",
            related_model: None,
            many: false,
        };
        let mut description = id;
        description.name = "description";
        description.source = "description";
        description.rust_type = "String";
        let endpoint = ApiEndpoint {
            crud: true,
            app_name: "knowledge",
            model_name: "Module".into(),
            resource: "modules".into(),
            fields: vec![id, description],
            list_fields: vec![id],
            columns: vec![],
            filters: vec![],
            extensions: vec![],
        };
        let types = models(std::slice::from_ref(&endpoint));
        assert!(types.contains("export interface ModuleListItem {\n  id: number;\n}"));
        assert!(!types.contains("export interface ModuleListItem {\n  id: number;\n  description"));
        assert!(api(&[endpoint]).contains("ModuleListParams, ModuleListItem>"));
    }

    #[test]
    fn duplicate_model_endpoints_use_resource_api_names() {
        let user = ApiEndpoint {
            crud: true,
            app_name: "auth",
            model_name: "User".into(),
            resource: "users".into(),
            fields: vec![],
            list_fields: vec![],
            columns: vec![],
            filters: vec![],
            extensions: vec![],
        };
        let assignees = ApiEndpoint {
            crud: true,
            app_name: "tasks",
            resource: "task-assignees".into(),
            ..user.clone()
        };
        let generated = api(&[user, assignees]);
        assert_eq!(generated.matches("  UserCreate,\n").count(), 1);
        assert!(generated.contains("export const userApi"));
        assert!(generated.contains("export const taskAssigneeApi"));
    }
}