apiplant-server 0.1.0

apiplant HTTP server: CRUD routing, function endpoints and TLS on ntex
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
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
//! The admin dashboard: its manifest, and baking a static copy of it.
//!
//! The dashboard is embedded in the binary and [served live](crate::run) for
//! every app, so the common case generates nothing. [`build`] writes the same
//! files out as a plain directory (`index.html`, `app.js`, `app.css` and a
//! manifest) for **hosting it somewhere other than the API** — a CDN, a bucket,
//! a different origin entirely. That copy is never read back by the server:
//! the running dashboard always describes the running app. Everything it needs
//! to know about the app — which resources exist, what to call them, which
//! fields to show, who may see what — is resolved *here*, at build time, and
//! written into `apiplant-admin.json`. The shipped JavaScript is the same for
//! every app.
//!
//! Two things are kept firmly apart, and it matters:
//!
//! * `[permissions]` / a function's `permission` decide what the **API**
//!   allows. They are enforced by the server on every request.
//! * `[admin]` decides what an **operator is shown**. It is presentation, and
//!   this generator treats it as such — hiding a resource here does not protect
//!   it, and the manifest never carries anything a signed-in caller could not
//!   already read from the API.

use std::collections::{BTreeMap, BTreeSet};
use std::fs;
use std::path::{Path, PathBuf};

use anyhow::{anyhow, bail, Context, Result};
use apiplant_abi::{FunctionAccess, HttpMethod};
use apiplant_core::schema::{
    is_auth_resource, relation_name, titleize, Access, ContentFormat, Field, FieldType, OnDelete,
    Resource, Widget,
};
use apiplant_core::App;
use serde::Serialize;
use serde_json::Value;

use crate::functions::FunctionRegistry;

/// Name of the manifest file the dashboard fetches on load.
pub const MANIFEST_FILE: &str = "apiplant-admin.json";

#[derive(Debug, Clone)]
pub struct Options {
    pub api: String,
    pub out: Option<PathBuf>,
}

#[derive(Debug, Serialize)]
struct AdminManifest {
    title: String,
    app_name: String,
    /// URL of the app's own mark, when it configured one.
    logo: Option<String>,
    api_base_url: String,
    docs_url: Option<String>,
    auth: AuthManifest,
    resources: Vec<ResourceManifest>,
    functions: Vec<FunctionManifest>,
}

#[derive(Debug, Serialize)]
struct AuthManifest {
    /// The field a person logs in with, and a label to put above the box.
    identity_field: String,
    identity_label: String,
    allow_registration: bool,
    /// Extra fields the register form should collect, so nobody has to type
    /// JSON to create an account.
    signup_fields: Vec<FieldManifest>,
    /// Fields the account screen lets someone edit about themselves.
    profile_fields: Vec<FieldManifest>,
    /// Roles seen anywhere in the app's permissions, so role pickers can offer
    /// real choices instead of a free-text box.
    known_roles: Vec<String>,
}

#[derive(Debug, Serialize)]
struct ResourceManifest {
    name: String,
    /// Singular human label ("Purchase order").
    label: String,
    /// Collection human label ("Purchase orders").
    plural: String,
    /// Sidebar grouping, or `None` for the ungrouped tail.
    group: Option<String>,
    order: i64,
    builtin: bool,
    /// One of the auth/tenancy resources the dashboard manages with a dedicated
    /// screen rather than a generic table.
    auth_resource: bool,
    /// Whether it belongs in the resource navigation at all.
    visible: bool,
    /// Organisation roles that may see it; empty means "anyone who can list it".
    roles: Vec<String>,
    scope: &'static str,
    owner_field: String,
    /// Field whose value names a record in tables, pickers and headings.
    display_field: Option<String>,
    /// Field the list search box filters on.
    search_field: Option<String>,
    /// Columns for the list table, in order.
    columns: Vec<String>,
    fields: Vec<FieldManifest>,
    /// `belongs_to` edges out of this resource.
    relations: Vec<RelationManifest>,
    /// `has_many` edges into it — the record screen lists these inline.
    children: Vec<ChildManifest>,
    permissions: ActionPermissionsManifest,
}

#[derive(Debug, Serialize)]
struct ActionPermissionsManifest {
    list: ActionPermissionManifest,
    read: ActionPermissionManifest,
    create: ActionPermissionManifest,
    update: ActionPermissionManifest,
    delete: ActionPermissionManifest,
}

#[derive(Debug, Serialize)]
struct ActionPermissionManifest {
    value: String,
    /// The role name when `value` is `role:<name>`, so the UI needn't re-parse.
    role: Option<String>,
    note: String,
    requires_org: bool,
}

#[derive(Debug, Serialize)]
struct FieldManifest {
    name: String,
    label: String,
    #[serde(rename = "type")]
    ty: &'static str,
    /// The input to render; `auto` lets the interface choose from `type`.
    widget: &'static str,
    help: Option<String>,
    placeholder: Option<String>,
    /// What the text is: `plain`, `markdown` or `html`. Presentation only —
    /// the dashboard highlights and previews the markup.
    format: &'static str,
    options: Vec<FieldOption>,
    required: bool,
    unique: bool,
    /// Stripped from API responses entirely (a password hash, say).
    hidden: bool,
    /// Present in the API but deliberately not shown in the dashboard.
    admin_visible: bool,
    readonly: bool,
    max_length: Option<u32>,
    references: Option<String>,
    relation: Option<String>,
    on_delete: Option<&'static str>,
    default_value: Option<Value>,
    /// Whether the dashboard may submit this field on create/update.
    writable: bool,
}

#[derive(Debug, Serialize)]
struct FieldOption {
    value: String,
    label: String,
}

#[derive(Debug, Serialize)]
struct RelationManifest {
    field: String,
    relation: String,
    target: String,
    /// Human label for the link ("Customer").
    label: String,
    required: bool,
}

/// A resource that points *at* this one — rendered as a related list on the
/// record screen, which is what turns a table of foreign keys into something a
/// non-technical operator can actually navigate.
#[derive(Debug, Serialize)]
struct ChildManifest {
    resource: String,
    /// The child's field that points here.
    field: String,
    label: String,
}

#[derive(Debug, Serialize)]
struct FunctionManifest {
    name: String,
    label: String,
    description: String,
    group: Option<String>,
    order: i64,
    method: &'static str,
    /// Effective access policy, in the shared `[permissions]` grammar.
    permission: String,
    role: Option<String>,
    permission_note: String,
    requires_org: bool,
    /// Whether it belongs in the dashboard's action list.
    visible: bool,
    roles: Vec<String>,
    /// Text for the confirmation step, or `None` to run without one.
    confirm: Option<String>,
    run_label: String,
    /// JSON Schema for the request body; the dashboard renders a form from it.
    input_schema: Option<Value>,
    output_schema: Option<Value>,
}

/// The `admin { … }` block of a function manifest, as carried over the ABI.
#[derive(Debug, Default, serde::Deserialize)]
#[serde(default)]
struct FunctionAdmin {
    visible: Option<bool>,
    roles: Vec<String>,
    label: Option<String>,
    group: Option<String>,
    description: Option<String>,
    confirm: Option<String>,
    run_label: Option<String>,
    order: Option<i64>,
}

pub fn build(app_dir: &Path, options: Options) -> Result<PathBuf> {
    let app = App::load(app_dir)?;
    let api_base_url = normalize_api_base(
        &options.api,
        &app.config.server.base_path,
        app.tls.is_some(),
    )?;
    let output_dir = options.out.unwrap_or_else(|| app_dir.join("admin"));
    let registry = FunctionRegistry::load(&app);
    let manifest = build_manifest(&app, &registry, api_base_url.clone())?;

    fs::create_dir_all(&output_dir)
        .with_context(|| format!("failed to create {}", output_dir.display()))?;

    for (relative, _) in apiplant_assets::ADMIN {
        let path = output_dir.join(relative);
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent)
                .with_context(|| format!("failed to create {}", parent.display()))?;
        }
        let bytes = asset(relative).expect("listed asset");
        write_bytes(path, &bytes)?;
    }
    write_json(output_dir.join(MANIFEST_FILE), &manifest)?;

    Ok(output_dir)
}

/// One file of the embedded dashboard, ready to serve or write out.
///
/// The stylesheet is rewritten on the way past: Vite emits absolute
/// `url(/head.png)` references, and the dashboard is never at the site root —
/// it is under `/admin/`, or in a directory someone hosts wherever they like.
pub fn asset(path: &str) -> Option<std::borrow::Cow<'static, [u8]>> {
    use std::borrow::Cow;

    let bytes = apiplant_assets::find(apiplant_assets::ADMIN, path)?;
    if path.trim_matches('/') == "app.css" {
        let css = String::from_utf8_lossy(bytes)
            .replace("url(/head.png)", "url(./head.png)")
            .replace("url(/head-inverted.png)", "url(./head-inverted.png)");
        return Some(Cow::Owned(css.into_bytes()));
    }
    Some(Cow::Borrowed(bytes))
}

/// The manifest for an app already loaded by the server, as JSON.
///
/// `api_base_url` is the prefix the dashboard puts in front of every request;
/// served from the app's own origin that is just the API's `base_path`.
pub fn manifest_json(
    app: &App,
    functions: &FunctionRegistry,
    api_base_url: String,
) -> Result<String> {
    let manifest = build_manifest(app, functions, api_base_url)?;
    Ok(serde_json::to_string(&manifest)?)
}

fn build_manifest(
    app: &App,
    functions: &FunctionRegistry,
    api_base_url: String,
) -> Result<AdminManifest> {
    let app_name = app.display_name();
    let user = app.resources.get("user");
    let identity_field = user
        .and_then(|resource| resource.auth.as_ref())
        .map(|auth| auth.identity_field.clone())
        .unwrap_or_else(|| "email".to_string());
    let password_field = user
        .and_then(|resource| resource.auth.as_ref())
        .map(|auth| auth.password_field.clone())
        .unwrap_or_else(|| "password_hash".to_string());
    let docs_url = if app.config.docs.enabled {
        Some(format!("{}{}", api_base_url, app.config.docs.path))
    } else {
        None
    };

    // Functions bound to a resource's lifecycle are machinery, not operator
    // actions; they never appear as something to "run" even when their
    // permission would allow it.
    let hook_functions = app
        .resources
        .values()
        .flat_map(|resource| {
            resource
                .hooks
                .iter()
                .map(|(_, function)| function.to_string())
        })
        .collect::<BTreeSet<_>>();

    // Reverse index: which resources point at each resource, so a record screen
    // can offer its related lists.
    let mut children: BTreeMap<String, Vec<ChildManifest>> = BTreeMap::new();
    for child in app.resources.values() {
        let references = child.references();
        for reference in &references {
            // A tenancy column is plumbing — every org-scoped row has one, and
            // "this organization → all its products" is not a relationship
            // anyone wants to browse from the organisation screen.
            if reference.field == "organization_id" {
                continue;
            }
            if !app.resources.contains_key(&reference.target) {
                continue;
            }
            // When a child points at the same parent twice — an order's billing
            // *and* shipping address — the resource name alone names both
            // lists, so the relation has to disambiguate them.
            let ambiguous = references
                .iter()
                .filter(|other| other.target == reference.target)
                .count()
                > 1;
            let label = if ambiguous {
                format!(
                    "{} ({})",
                    child.admin_plural(),
                    titleize(&reference.relation).to_lowercase()
                )
            } else {
                child.admin_plural()
            };
            children
                .entry(reference.target.clone())
                .or_default()
                .push(ChildManifest {
                    resource: child.meta.name.clone(),
                    field: reference.field.clone(),
                    label,
                });
        }
    }

    let resources = app
        .resources
        .values()
        .map(|resource| {
            resource_manifest(
                resource,
                &password_field,
                children
                    .remove(resource.meta.name.as_str())
                    .unwrap_or_default(),
            )
        })
        .collect::<Vec<_>>();

    let mut loaded_functions = functions
        .iter()
        .filter(|entry| !hook_functions.contains(entry.manifest.name.as_str()))
        .map(|entry| function_manifest(&entry.manifest))
        // A private function has no endpoint at all, so there is nothing for an
        // operator to run and nothing to show.
        .filter(|manifest| manifest.permission != "private")
        .collect::<Vec<_>>();
    loaded_functions.sort_by(|left, right| {
        left.group
            .cmp(&right.group)
            .then(left.order.cmp(&right.order))
            .then(left.label.cmp(&right.label))
    });

    let signup_fields = user
        .map(|resource| {
            resource
                .fields
                .iter()
                .filter(|(name, field)| {
                    // The identity and password have their own inputs on the
                    // form; everything else the model *requires* has to be
                    // collected too, or registration simply fails.
                    *name != &identity_field
                        && *name != &password_field
                        && field.required
                        && !field.hidden
                        && field.admin.visible
                        && name.as_str() != "organization_id"
                })
                .map(|(name, field)| field_manifest(name, field, resource))
                .collect::<Vec<_>>()
        })
        .unwrap_or_default();

    let profile_fields = user
        .map(|resource| {
            resource
                .fields
                .iter()
                .filter(|(name, field)| {
                    !field.hidden && field.admin.visible && *name != &password_field
                })
                .map(|(name, field)| field_manifest(name, field, resource))
                .collect::<Vec<_>>()
        })
        .unwrap_or_default();

    Ok(AdminManifest {
        title: format!("{app_name} admin"),
        app_name,
        logo: app.config.admin.logo.clone(),
        api_base_url,
        docs_url,
        auth: AuthManifest {
            identity_label: titleize(&identity_field),
            identity_field,
            allow_registration: app.config.auth.allow_registration,
            signup_fields,
            profile_fields,
            known_roles: known_roles(app, functions),
        },
        resources,
        functions: loaded_functions,
    })
}

/// Every role named anywhere in the app — resource permissions, function
/// permissions, `[admin] roles` — so the team screen can offer a dropdown
/// rather than asking someone to remember how "admin" is spelled.
fn known_roles(app: &App, functions: &FunctionRegistry) -> Vec<String> {
    let mut roles: BTreeSet<String> = BTreeSet::new();
    // `member` is the role the built-in membership defaults describe, and every
    // app has one whether or not a permission names it.
    roles.insert("member".to_string());
    roles.insert("admin".to_string());

    for resource in app.resources.values() {
        for access in [
            &resource.permissions.list,
            &resource.permissions.read,
            &resource.permissions.create,
            &resource.permissions.update,
            &resource.permissions.delete,
        ] {
            if let Access::Role(role) = access {
                roles.insert(role.clone());
            }
        }
        roles.extend(resource.admin.roles.iter().cloned());
    }
    for entry in functions.iter() {
        if let FunctionAccess::Role(role) = entry.manifest.access() {
            roles.insert(role);
        }
        roles.extend(parse_function_admin(&entry.manifest).roles);
    }
    roles.into_iter().collect()
}

fn resource_manifest(
    resource: &Resource,
    password_field: &str,
    children: Vec<ChildManifest>,
) -> ResourceManifest {
    let fields = resource
        .fields
        .iter()
        .map(|(name, field)| field_manifest(name, field, resource))
        .collect::<Vec<_>>();
    let relations = resource
        .references()
        .into_iter()
        .filter(|reference| reference.field != "organization_id")
        .map(|reference| RelationManifest {
            label: titleize(&reference.relation),
            field: reference.field,
            relation: reference.relation,
            target: reference.target,
            required: reference.required,
        })
        .collect::<Vec<_>>();
    let org_scoped = resource.is_org_scoped();

    ResourceManifest {
        label: resource.admin_label(),
        plural: resource.admin_plural(),
        group: resource.admin.group.clone(),
        order: resource.admin.order,
        builtin: is_builtin_resource(&resource.meta.name),
        auth_resource: is_auth_resource(&resource.meta.name),
        visible: resource.admin.is_visible(&resource.meta.name),
        roles: resource.admin.roles.clone(),
        scope: if org_scoped { "organization" } else { "global" },
        owner_field: resource.meta.owner_field.clone(),
        display_field: resource.admin_display_field(),
        search_field: resource.admin_search_field(),
        columns: resource
            .admin_columns()
            .into_iter()
            // A password column would never render usefully and, on a resource
            // that names one, is exactly the thing not to put in a table.
            .filter(|column| column != password_field || resource.meta.name != "user")
            .collect(),
        permissions: ActionPermissionsManifest {
            list: permission_manifest(&resource.permissions.list, org_scoped),
            read: permission_manifest(&resource.permissions.read, org_scoped),
            create: permission_manifest(&resource.permissions.create, org_scoped),
            update: permission_manifest(&resource.permissions.update, org_scoped),
            delete: permission_manifest(&resource.permissions.delete, org_scoped),
        },
        name: resource.meta.name.clone(),
        fields,
        relations,
        children,
    }
}

fn is_builtin_resource(name: &str) -> bool {
    is_auth_resource(name)
}

fn field_manifest(name: &str, field: &Field, resource: &Resource) -> FieldManifest {
    let references = field.references.clone();
    let relation = references.as_ref().map(|_| relation_name(name).to_string());
    // The framework stamps the owner and the tenant itself; offering either as
    // an input invites someone to fill in a value the server will overwrite.
    let stamped = name == resource.meta.owner_field || name == "organization_id";

    FieldManifest {
        label: field
            .admin
            .label
            .clone()
            .unwrap_or_else(|| titleize(name))
            .to_string(),
        ty: field_type_name(field.ty),
        widget: resolve_widget(field),
        help: field.admin.help.clone(),
        placeholder: field.admin.placeholder.clone(),
        format: field.admin.format.as_str(),
        options: field
            .admin
            .options
            .iter()
            .map(|option| match option.split_once('|') {
                Some((value, label)) => FieldOption {
                    value: value.to_string(),
                    label: label.to_string(),
                },
                None => FieldOption {
                    value: option.clone(),
                    label: titleize(option),
                },
            })
            .collect(),
        required: field.required,
        unique: field.unique,
        hidden: field.hidden,
        admin_visible: field.admin.visible && !field.hidden,
        readonly: field.admin.readonly,
        max_length: field.max_length,
        references,
        relation,
        on_delete: field.on_delete.map(on_delete_name),
        default_value: field.default.clone(),
        writable: !field.hidden && !field.admin.readonly && !stamped,
        name: name.to_string(),
    }
}

/// Resolve `widget = "auto"` against the field's type, so the interface always
/// receives a concrete instruction and never has to duplicate this mapping.
fn resolve_widget(field: &Field) -> &'static str {
    if field.admin.widget != Widget::Auto {
        return field.admin.widget.as_str();
    }
    if !field.admin.options.is_empty() {
        return "select";
    }
    // Markup needs room and a preview beside it, whatever the column type.
    if field.admin.format != ContentFormat::Plain {
        return "textarea";
    }
    match field.ty {
        FieldType::Text => "textarea",
        FieldType::Boolean => "switch",
        FieldType::Json => "json",
        FieldType::Timestamp => "date_time",
        FieldType::Reference => "reference",
        FieldType::Integer | FieldType::BigInt | FieldType::Float => "number",
        FieldType::Uuid => "text",
        FieldType::String => "text",
    }
}

fn permission_manifest(access: &Access, org_scoped: bool) -> ActionPermissionManifest {
    ActionPermissionManifest {
        value: access_value(access),
        role: match access {
            Access::Role(role) => Some(role.clone()),
            _ => None,
        },
        note: access_note(access, org_scoped),
        requires_org: org_scoped || matches!(access, Access::Role(_) | Access::Member),
    }
}

fn parse_function_admin(manifest: &apiplant_abi::FunctionManifest) -> FunctionAdmin {
    if manifest.admin.is_empty() {
        return FunctionAdmin::default();
    }
    serde_json::from_str(manifest.admin.as_str()).unwrap_or_default()
}

fn function_manifest(manifest: &apiplant_abi::FunctionManifest) -> FunctionManifest {
    let access = manifest.access();
    let admin = parse_function_admin(manifest);
    let name = manifest.name.to_string();
    let label = admin.label.unwrap_or_else(|| titleize(&name));

    FunctionManifest {
        label: label.clone(),
        description: admin
            .description
            .unwrap_or_else(|| manifest.description.to_string()),
        group: admin.group,
        order: admin.order.unwrap_or(0),
        method: method_name(manifest.method),
        permission: access.as_string(),
        role: match &access {
            FunctionAccess::Role(role) => Some(role.clone()),
            _ => None,
        },
        permission_note: function_access_note(&access),
        requires_org: matches!(access, FunctionAccess::Role(_) | FunctionAccess::Member),
        visible: admin.visible.unwrap_or(true),
        roles: admin.roles,
        confirm: admin.confirm,
        run_label: admin.run_label.unwrap_or(label),
        input_schema: parse_schema(manifest.input_schema.as_str()),
        output_schema: parse_schema(manifest.output_schema.as_str()),
        name,
    }
}

/// A manifest's schemas are optional and may be malformed (they come from
/// another language's library). An unreadable one simply means "no form", not a
/// failed build.
fn parse_schema(raw: &str) -> Option<Value> {
    if raw.trim().is_empty() {
        return None;
    }
    serde_json::from_str(raw).ok()
}

fn access_value(access: &Access) -> String {
    match access {
        Access::Public => "public".to_string(),
        Access::Authenticated => "authenticated".to_string(),
        Access::Member => "member".to_string(),
        Access::Owner => "owner".to_string(),
        Access::Role(role) => format!("role:{role}"),
        Access::Private => "private".to_string(),
    }
}

fn access_note(access: &Access, org_scoped: bool) -> String {
    if org_scoped {
        return match access {
            Access::Private => "Not available.".to_string(),
            Access::Owner => "Limited to records you created.".to_string(),
            Access::Role(role) => format!("Needs the {role} role."),
            _ => "Available to everyone in this organization.".to_string(),
        };
    }

    match access {
        Access::Public => "Available to anyone.".to_string(),
        Access::Authenticated | Access::Member => "Available once you sign in.".to_string(),
        Access::Owner => "Limited to records you created.".to_string(),
        Access::Role(role) => format!("Needs the {role} role."),
        Access::Private => "Not available.".to_string(),
    }
}

fn function_access_note(access: &FunctionAccess) -> String {
    match access {
        FunctionAccess::Public => "Anyone can run this.".to_string(),
        FunctionAccess::Authenticated => "Available once you sign in.".to_string(),
        FunctionAccess::Member => "Available to everyone in this organization.".to_string(),
        FunctionAccess::Role(role) => format!("Needs the {role} role."),
        FunctionAccess::Private => "Not available.".to_string(),
    }
}

fn field_type_name(ty: FieldType) -> &'static str {
    match ty {
        FieldType::String => "string",
        FieldType::Text => "text",
        FieldType::Integer => "integer",
        FieldType::BigInt => "big_int",
        FieldType::Float => "float",
        FieldType::Boolean => "boolean",
        FieldType::Uuid => "uuid",
        FieldType::Timestamp => "timestamp",
        FieldType::Json => "json",
        FieldType::Reference => "reference",
    }
}

fn on_delete_name(on_delete: OnDelete) -> &'static str {
    match on_delete {
        OnDelete::Restrict => "restrict",
        OnDelete::SetNull => "set_null",
        OnDelete::Cascade => "cascade",
        OnDelete::NoAction => "no_action",
    }
}

fn method_name(method: HttpMethod) -> &'static str {
    match method {
        HttpMethod::Get => "GET",
        HttpMethod::Post => "POST",
        HttpMethod::Put => "PUT",
        HttpMethod::Delete => "DELETE",
    }
}

fn normalize_api_base(raw: &str, base_path: &str, prefer_https: bool) -> Result<String> {
    let trimmed = raw.trim();
    if trimmed.is_empty() {
        bail!("--api requires a domain or full API URL");
    }

    let mut url = if trimmed.contains("://") {
        trimmed.to_string()
    } else {
        format!(
            "{}://{}",
            if prefer_https { "https" } else { "http" },
            trimmed
        )
    };

    if !url.starts_with("http://") && !url.starts_with("https://") {
        bail!("--api must resolve to an http:// or https:// URL");
    }

    let scheme_end = url
        .find("://")
        .map(|index| index + 3)
        .ok_or_else(|| anyhow!("invalid API URL"))?;

    match url[scheme_end..].find('/') {
        None => {
            if !base_path.is_empty() {
                url.push_str(base_path);
            }
        }
        Some(relative_start) => {
            let path_start = scheme_end + relative_start;
            let path = &url[path_start..];
            if path == "/" {
                url.truncate(path_start);
                if !base_path.is_empty() {
                    url.push_str(base_path);
                }
            } else {
                while url.ends_with('/') {
                    url.pop();
                }
            }
        }
    }

    while url.ends_with('/') {
        url.pop();
    }

    Ok(url)
}

fn write_bytes(path: PathBuf, bytes: &[u8]) -> Result<()> {
    fs::write(&path, bytes).with_context(|| format!("failed to write {}", path.display()))
}

fn write_json(path: PathBuf, manifest: &AdminManifest) -> Result<()> {
    let bytes = serde_json::to_vec_pretty(manifest)?;
    fs::write(&path, bytes).with_context(|| format!("failed to write {}", path.display()))
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::time::{SystemTime, UNIX_EPOCH};

    fn temp_dir(label: &str) -> PathBuf {
        let mut dir = std::env::temp_dir();
        let stamp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_nanos();
        dir.push(format!(
            "apiplant-admin-{label}-{}-{stamp}",
            std::process::id()
        ));
        fs::create_dir_all(&dir).unwrap();
        dir
    }

    fn build_manifest_for(models: &[(&str, &str)]) -> Value {
        build_manifest_with_config(
            "[server]\nbase_path = \"/api\"\n\n[auth]\nallow_registration = true\n",
            models,
        )
    }

    fn build_manifest_with_config(main_toml: &str, models: &[(&str, &str)]) -> Value {
        let app_dir = temp_dir("app");
        let out_dir = temp_dir("out");
        fs::create_dir_all(app_dir.join("models")).unwrap();
        fs::write(app_dir.join("main.toml"), main_toml).unwrap();
        for (name, src) in models {
            fs::write(app_dir.join(format!("models/{name}.toml")), src).unwrap();
        }

        build(
            &app_dir,
            Options {
                api: "https://example.com".to_string(),
                out: Some(out_dir.clone()),
            },
        )
        .unwrap();

        let manifest: Value =
            serde_json::from_slice(&fs::read(out_dir.join("apiplant-admin.json")).unwrap())
                .unwrap();
        fs::remove_dir_all(app_dir).unwrap();
        fs::remove_dir_all(out_dir).unwrap();
        manifest
    }

    fn resource<'a>(manifest: &'a Value, name: &str) -> &'a Value {
        manifest["resources"]
            .as_array()
            .unwrap()
            .iter()
            .find(|resource| resource["name"] == name)
            .unwrap_or_else(|| panic!("no `{name}` in manifest"))
    }

    /// The header an operator reads is the app's to choose; the directory it
    /// happens to live in is only the fallback.
    #[test]
    fn app_name_comes_from_config_and_falls_back_to_the_directory() {
        let named = build_manifest_with_config(
            "[app]\nname = \"Acme Logistics\"\n\n[server]\nbase_path = \"/api\"\n",
            &[],
        );
        assert_eq!(named["app_name"], "Acme Logistics");
        assert_eq!(named["title"], "Acme Logistics admin");

        // A blank name is not a name: it would render as a header with nothing
        // in it, so it falls back like an absent one.
        let blank = build_manifest_with_config(
            "[app]\nname = \"   \"\n\n[server]\nbase_path = \"/api\"\n",
            &[],
        );
        assert!(blank["app_name"]
            .as_str()
            .unwrap()
            .starts_with("apiplant-admin-app-"));

        let unnamed = build_manifest_for(&[]);
        assert!(unnamed["app_name"]
            .as_str()
            .unwrap()
            .starts_with("apiplant-admin-app-"));
    }

    #[test]
    fn api_base_uses_app_base_path_when_only_a_domain_is_given() {
        assert_eq!(
            normalize_api_base("admin.example.com", "/api", true).unwrap(),
            "https://admin.example.com/api"
        );
        assert_eq!(
            normalize_api_base("127.0.0.1:8099", "", false).unwrap(),
            "http://127.0.0.1:8099"
        );
    }

    #[test]
    fn explicit_api_paths_are_preserved() {
        assert_eq!(
            normalize_api_base("https://example.com/custom/", "/api", true).unwrap(),
            "https://example.com/custom"
        );
        assert_eq!(
            normalize_api_base("https://example.com/", "/api", true).unwrap(),
            "https://example.com/api"
        );
    }

    #[test]
    fn build_writes_static_admin_files_and_manifest() {
        let app_dir = temp_dir("files");
        let out_dir = temp_dir("files-out");
        fs::create_dir_all(app_dir.join("models")).unwrap();
        fs::write(
            app_dir.join("main.toml"),
            "[server]\nbase_path = \"/api\"\n",
        )
        .unwrap();

        let written = build(
            &app_dir,
            Options {
                api: "https://example.com".to_string(),
                out: Some(out_dir.clone()),
            },
        )
        .unwrap();

        assert_eq!(written, out_dir);
        for file in [
            "index.html",
            "app.js",
            "app.css",
            "head.png",
            "head-inverted.png",
            "apiplant-admin.json",
        ] {
            assert!(out_dir.join(file).exists(), "{file} was not written");
        }

        fs::remove_dir_all(app_dir).unwrap();
        fs::remove_dir_all(out_dir).unwrap();
    }

    #[test]
    fn auth_resources_are_hidden_from_the_resource_navigation_by_default() {
        let manifest = build_manifest_for(&[(
            "post",
            "[resource]\nname = \"post\"\n\n[fields.title]\ntype = \"string\"\n",
        )]);

        for name in ["user", "organization", "membership", "api_key"] {
            let auth = resource(&manifest, name);
            assert_eq!(auth["visible"], false, "{name} should be hidden");
            assert_eq!(auth["auth_resource"], true);
        }
        assert_eq!(resource(&manifest, "post")["visible"], true);
        assert_eq!(resource(&manifest, "post")["auth_resource"], false);
    }

    #[test]
    fn admin_section_overrides_labels_columns_and_role_visibility() {
        let manifest = build_manifest_for(&[(
            "product",
            r#"
[resource]
name = "product"

[admin]
visible = true
roles = ["manager"]
label = "Item"
plural = "Catalogue items"
group = "Catalogue"
order = 3
display_field = "title"
columns = ["title", "status"]

[fields.title]
type = "string"
required = true

[fields.status]
type = "string"
default = "draft"

[fields.status.admin]
label = "Lifecycle"
widget = "select"
options = ["draft", "active|Live"]
help = "Only live items are sold."

[fields.internal_note]
type = "text"

[fields.internal_note.admin]
visible = false
"#,
        )]);

        let product = resource(&manifest, "product");
        assert_eq!(product["label"], "Item");
        assert_eq!(product["plural"], "Catalogue items");
        assert_eq!(product["group"], "Catalogue");
        assert_eq!(product["order"], 3);
        assert_eq!(product["roles"][0], "manager");
        assert_eq!(product["display_field"], "title");
        assert_eq!(product["columns"][0], "title");
        assert_eq!(product["columns"][1], "status");

        let field = |name: &str| {
            product["fields"]
                .as_array()
                .unwrap()
                .iter()
                .find(|field| field["name"] == name)
                .unwrap()
        };
        let status = field("status");
        assert_eq!(status["label"], "Lifecycle");
        assert_eq!(status["widget"], "select");
        assert_eq!(status["help"], "Only live items are sold.");
        assert_eq!(status["options"][0]["value"], "draft");
        assert_eq!(status["options"][0]["label"], "Draft");
        // `value|Label` splits into an explicit caption.
        assert_eq!(status["options"][1]["value"], "active");
        assert_eq!(status["options"][1]["label"], "Live");

        // Hidden in the dashboard, still part of the API.
        assert_eq!(field("internal_note")["admin_visible"], false);
        assert_eq!(field("internal_note")["hidden"], false);

        // The injected tenancy column is never an input.
        assert_eq!(field("organization_id")["writable"], false);
        assert_eq!(field("organization_id")["admin_visible"], false);
    }

    #[test]
    fn content_format_reaches_the_manifest_and_forces_a_textarea() {
        let manifest = build_manifest_for(&[(
            "article",
            r#"
[resource]
name = "article"

[fields.body]
type = "text"

[fields.body.admin]
format = "markdown"

[fields.summary]
type = "string"

[fields.summary.admin]
format = "html"

[fields.slug]
type = "string"
"#,
        )]);

        let article = resource(&manifest, "article");
        let field = |name: &str| {
            article["fields"]
                .as_array()
                .unwrap()
                .iter()
                .find(|field| field["name"] == name)
                .unwrap()
                .clone()
        };

        assert_eq!(field("body")["format"], "markdown");
        assert_eq!(field("body")["widget"], "textarea");
        // Markup needs the room even when the column is a plain string.
        assert_eq!(field("summary")["format"], "html");
        assert_eq!(field("summary")["widget"], "textarea");
        assert_eq!(field("slug")["format"], "plain");
        assert_eq!(field("slug")["widget"], "text");
    }

    #[test]
    fn labels_and_columns_are_inferred_when_admin_says_nothing() {
        let manifest = build_manifest_for(&[(
            "purchase_order",
            r#"
[resource]
name = "purchase_order"

[fields.name]
type = "string"

[fields.notes]
type = "text"

[fields.settings]
type = "json"
"#,
        )]);

        let purchase_order = resource(&manifest, "purchase_order");
        assert_eq!(purchase_order["label"], "Purchase order");
        assert_eq!(purchase_order["plural"], "Purchase orders");
        assert_eq!(purchase_order["display_field"], "name");
        assert_eq!(purchase_order["search_field"], "name");

        // `text` and `json` never read well in a table cell, so they are left
        // out of the inferred column set.
        let columns: Vec<&str> = purchase_order["columns"]
            .as_array()
            .unwrap()
            .iter()
            .map(|column| column.as_str().unwrap())
            .collect();
        assert_eq!(columns, vec!["name"]);
    }

    #[test]
    fn related_lists_are_derived_from_incoming_references() {
        let manifest = build_manifest_for(&[
            (
                "order",
                "[resource]\nname = \"order\"\n\n[fields.number]\ntype = \"string\"\n",
            ),
            (
                "order_line",
                r#"
[resource]
name = "order_line"

[fields.order_id]
type = "reference"
references = "order"
required = true

[fields.quantity]
type = "integer"
"#,
            ),
        ]);

        let order = resource(&manifest, "order");
        let children = order["children"].as_array().unwrap();
        assert_eq!(children.len(), 1);
        assert_eq!(children[0]["resource"], "order_line");
        assert_eq!(children[0]["field"], "order_id");
        assert_eq!(children[0]["label"], "Order lines");

        // …and the child knows which way its own reference points.
        let line = resource(&manifest, "order_line");
        let relation = line["relations"]
            .as_array()
            .unwrap()
            .iter()
            .find(|relation| relation["field"] == "order_id")
            .unwrap();
        assert_eq!(relation["target"], "order");
        assert_eq!(relation["label"], "Order");
        assert_eq!(relation["required"], true);
    }

    #[test]
    fn known_roles_collect_every_role_the_app_names() {
        let manifest = build_manifest_for(&[(
            "product",
            r#"
[resource]
name = "product"

[permissions]
create = "role:buyer"
delete = "role:auditor"

[fields.name]
type = "string"
"#,
        )]);

        let roles: Vec<&str> = manifest["auth"]["known_roles"]
            .as_array()
            .unwrap()
            .iter()
            .map(|role| role.as_str().unwrap())
            .collect();
        assert!(roles.contains(&"buyer"));
        assert!(roles.contains(&"auditor"));
        // The two roles every app has, whether or not a permission names them.
        assert!(roles.contains(&"admin"));
        assert!(roles.contains(&"member"));
    }

    #[test]
    fn signup_collects_required_profile_fields_so_nobody_types_json() {
        let manifest = build_manifest_for(&[(
            "user",
            r#"
[resource]
name = "user"
scope = "global"

[auth]
identity_field = "email"
password_field = "password_hash"

[fields.email]
type = "string"
required = true
unique = true

[fields.password_hash]
type = "string"
hidden = true

[fields.full_name]
type = "string"
required = true

[fields.nickname]
type = "string"
"#,
        )]);

        let signup: Vec<&str> = manifest["auth"]["signup_fields"]
            .as_array()
            .unwrap()
            .iter()
            .map(|field| field["name"].as_str().unwrap())
            .collect();
        // Required extras only: the identity and password have their own inputs,
        // and an optional field would just be noise on a sign-up form.
        assert_eq!(signup, vec!["full_name"]);
        assert_eq!(manifest["auth"]["identity_label"], "Email");

        // The account screen offers everything editable, including optional
        // fields — but never the password hash.
        let profile: Vec<&str> = manifest["auth"]["profile_fields"]
            .as_array()
            .unwrap()
            .iter()
            .map(|field| field["name"].as_str().unwrap())
            .collect();
        assert!(profile.contains(&"nickname"));
        assert!(!profile.contains(&"password_hash"));
    }
}