kshana 0.36.0

Open, reproducible PNT-resilience simulator with quantum-sensor performance models
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
// SPDX-License-Identifier: AGPL-3.0-only
//! WebAssembly bindings (wasm-bindgen), built with the `wasm` feature.
//!
//! ```js
//! import init, { run, version } from "./pkg/kshana.js";
//! await init();
//! const result = JSON.parse(run(tomlText));
//! console.log(version(), result.quantum.fom.integrity);
//! ```

use wasm_bindgen::prelude::*;

// The typed vocabulary (`ScenarioKind`, `ErrorKind`, `KindMeta`, `FieldUnit`,
// `ResultDocument`, ...) appended to the generated `kshana.d.ts` (CAP-34).
#[wasm_bindgen(typescript_custom_section)]
const TYPED_API: &'static str = include_str!("wasm_types.d.ts");

#[wasm_bindgen]
extern "C" {
    #[wasm_bindgen(js_namespace = JSON, js_name = parse)]
    fn json_parse(text: &str) -> JsValue;
}

/// Run a scenario once and return every output as one typed object (`RunOutput` in the
/// declarations): `json`, `svg`, `summary`, `csv` (`null` for a kind that emits no
/// table) and `data`, the result document already parsed. A plain object, not a class,
/// so there is nothing to free. Throws a JS error if the scenario is invalid.
#[wasm_bindgen(unchecked_return_type = "RunOutput")]
pub fn run_typed(toml: &str) -> Result<JsValue, JsValue> {
    let o = crate::api::run_toml(toml).map_err(|e| JsValue::from_str(&e))?;
    let quoted = |s: &str| serde_json::Value::from(s).to_string();
    // `o.json` is already a JSON document, so it is spliced in as `data` rather than
    // parsed and re-serialised here.
    Ok(json_parse(&format!(
        "{{\"json\":{},\"svg\":{},\"summary\":{},\"csv\":{},\"data\":{}}}",
        quoted(&o.json),
        quoted(&o.svg),
        quoted(&o.summary),
        o.csv.as_deref().map_or_else(|| "null".to_string(), quoted),
        o.json,
    )))
}

/// The available scenario kinds and their metadata, already parsed: the typed form of
/// [`list_kinds`], which keeps its JSON-string return for existing callers.
#[wasm_bindgen(unchecked_return_type = "KindMeta[]")]
pub fn scenario_kinds() -> JsValue {
    json_parse(&crate::api::list_scenario_kinds_json())
}

/// Run a scenario given as a TOML string; returns the result document as a JSON
/// string. Throws a JS error if the scenario is invalid.
#[wasm_bindgen]
pub fn run(toml: &str) -> Result<String, JsValue> {
    crate::api::run_toml(toml)
        .map(|o| o.json)
        .map_err(|e| JsValue::from_str(&e))
}

/// Run a scenario and return its SVG chart.
#[wasm_bindgen]
pub fn chart_svg(toml: &str) -> Result<String, JsValue> {
    crate::api::run_toml(toml)
        .map(|o| o.svg)
        .map_err(|e| JsValue::from_str(&e))
}

/// Run a scenario and return its one-line human-readable summary.
#[wasm_bindgen]
pub fn summary(toml: &str) -> Result<String, JsValue> {
    crate::api::run_toml(toml)
        .map(|o| o.summary)
        .map_err(|e| JsValue::from_str(&e))
}

/// Run a scenario and return its reproducibility table as CSV text — the same bytes the
/// CLI writes as `<scenario>.table.csv`. Returns `undefined` for kinds that publish no
/// table (only `realtime-frame-eop`, `lunar-time-budget`, `lunar-jamming`, and
/// `moonlight-service-volume` with an export site configured emit one). Throws a JS error
/// if the scenario is invalid.
#[wasm_bindgen]
pub fn table_csv(toml: &str) -> Result<Option<String>, JsValue> {
    crate::api::run_toml(toml)
        .map(|o| o.csv)
        .map_err(|e| JsValue::from_str(&e))
}

/// Run a scenario ONCE and return every output of that run as a JSON object string:
/// `{"json": <result document string>, "svg": <chart>, "summary": <one line>,
/// "csv": <table or null>}` (the `RunAllOutput` type). `run_typed` returns the same
/// outputs, plus the parsed document, as an object. `run`, `chart_svg`, `summary` and `table_csv` each execute
/// the scenario from scratch, so a page that wants all four paid for four full engine
/// runs — about 12 s instead of 3 s for the heaviest kind in a browser. Throws a JS
/// error if the scenario is invalid.
#[wasm_bindgen]
pub fn run_all(toml: &str) -> Result<String, JsValue> {
    let o = crate::api::run_toml(toml).map_err(|e| JsValue::from_str(&e))?;
    Ok(serde_json::json!({
        "json": o.json,
        "svg": o.svg,
        "summary": o.summary,
        "csv": o.csv,
    })
    .to_string())
}

/// List the available scenario kinds and their metadata as a JSON array (name,
/// description, required and optional fields), for programmatic introspection.
#[wasm_bindgen]
pub fn list_kinds() -> String {
    crate::api::list_scenario_kinds_json()
}

/// The modules a scenario kind's verification-matrix rows name where they differ from the kind's
/// own name: a JSON object, kind to array of module names. The Studio's capability map joins a
/// scenario to its matrix rows through it.
#[wasm_bindgen]
pub fn kind_modules() -> String {
    crate::api::kind_modules_json()
}

/// Which fields of a scenario answer its question, best first, for the kinds where that is stated:
/// a JSON object, kind to `{"headline": [dotted path, ...]}`. Display metadata for a front end; the
/// engine never reads it. A kind that is absent has no stated order.
#[wasm_bindgen]
pub fn field_importance() -> String {
    crate::api::field_importance_json()
}

/// Run a scenario; on failure return the structured error *kind* tag
/// (`invalid_input`, `unsupported`, …) so the caller can branch on the failure
/// category rather than parse the message. Returns an empty string on success.
#[wasm_bindgen(unchecked_return_type = "ErrorKind | \"\"")]
pub fn error_kind(toml: &str) -> String {
    crate::api::run_scenario(toml)
        .err()
        .map(|e| e.kind_tag().to_string())
        .unwrap_or_default()
}

/// Engine version (the crate version).
#[wasm_bindgen]
pub fn version() -> String {
    env!("CARGO_PKG_VERSION").to_string()
}

/// Encode a scenario TOML into a URL-safe permalink token for a `?s=` query parameter.
#[wasm_bindgen]
pub fn encode_permalink(toml: &str) -> String {
    crate::permalink::encode_scenario(toml)
}

/// Decode a permalink token back into the scenario TOML; returns an empty string if the
/// token is not valid Base64 or not valid UTF-8.
#[wasm_bindgen]
pub fn decode_permalink(token: &str) -> String {
    crate::permalink::decode_scenario(token).unwrap_or_default()
}

/// Export a propagated constellation scenario as an **SP3-c** precise-ephemeris string
/// (the same artifact the CLI `--export-sp3` flag writes). Pure client-side; nothing is
/// uploaded. Throws a JS error if the scenario cannot produce an SP3 (e.g. a non-orbit kind).
#[wasm_bindgen]
pub fn export_sp3(toml: &str) -> Result<String, JsValue> {
    crate::api::export_sp3(toml).map_err(|e| JsValue::from_str(&e))
}

/// Export a constellation's mean elements as a **CCSDS OMM** catalogue string (one OMM
/// message per TLE-defined satellite; the CLI `--export-omm` artifact). Pure client-side.
#[wasm_bindgen]
pub fn export_omm(toml: &str) -> Result<String, JsValue> {
    crate::api::export_omm(toml).map_err(|e| JsValue::from_str(&e))
}

/// Export the velocity-carrying state as a **CCSDS OEM 2.0** ephemeris string for
/// flight-dynamics tools (GMAT / Orekit / STK; the CLI `--export-oem` artifact). Pure
/// client-side.
#[wasm_bindgen]
pub fn export_oem(toml: &str) -> Result<String, JsValue> {
    crate::api::export_oem(toml).map_err(|e| JsValue::from_str(&e))
}

/// Assess a real receiver log described by a `receiver-trust` scenario (TOML text). The
/// browser has no file system, so the log (and any navigation file) must be inline as
/// `text` or `base64`. Returns a JSON object `{json, csv, svg, summary}`.
#[wasm_bindgen]
pub fn receiver_trust(toml: &str) -> Result<String, JsValue> {
    let o = crate::receiver_trust::scenario::run_toml(toml).map_err(|e| JsValue::from_str(&e))?;
    Ok(serde_json::json!({
        "json": o.json,
        "csv": o.csv,
        "svg": o.svg,
        "summary": o.summary,
    })
    .to_string())
}

/// Which interoperability formats apply to a scenario, without running it: a JSON array of
/// `{format, applies, reason, spec_url}` for `czml`, `kml`, `geojson`, `stk` and `sigmf`.
#[wasm_bindgen]
pub fn export_formats(toml: &str) -> Result<String, JsValue> {
    crate::surface::export_formats(toml, crate::surface::MAX_INPUT_BYTES)
        .map(|v| v.to_string())
        .map_err(|e| JsValue::from_str(&e))
}

/// Export a scenario in one interoperability format (`czml`, `kml`, `geojson`, `stk` or
/// `sigmf`), in memory. Returns JSON `{format, spec_url, files}`; each file is `{suffix, bytes,
/// sha256, encoding, content}` with `encoding` `"utf-8"` (the text) or `"base64"` (a binary
/// file). Times are UTC; the same scenario gives byte-identical files. Nothing is uploaded.
#[wasm_bindgen]
pub fn export_scenario(toml: &str, format: &str) -> Result<String, JsValue> {
    crate::surface::export_scenario(toml, format, crate::surface::MAX_INPUT_BYTES)
        .map(|e| e.to_json().to_string())
        .map_err(|e| JsValue::from_str(&e))
}

/// Write a GeoJSON route into a scenario of a kind that flies a waypoint track and return the
/// new TOML (the command line's `--import-route`).
#[wasm_bindgen]
pub fn import_route(toml: &str, geojson: &str) -> Result<String, JsValue> {
    crate::surface::import_route(toml, geojson, crate::surface::MAX_INPUT_BYTES)
        .map_err(|e| JsValue::from_str(&e))
}

/// Run a scenario and return its time series as an animation. `format` is `svg`, `html` or
/// `frames` (empty for `svg`); `fps` 0, `duration_s` NaN and `width` 0 mean the defaults (12,
/// 8 s, 960 px). Returns JSON `{summary, files: {name: text}}`; a kind with no sampled time
/// axis throws. Nothing is uploaded or written.
#[wasm_bindgen]
pub fn animate_scenario(
    toml: &str,
    format: &str,
    fps: u32,
    duration_s: f64,
    width: u32,
) -> Result<String, JsValue> {
    let a = crate::surface::animate_scenario(
        toml,
        (!format.is_empty()).then_some(format),
        (fps != 0).then_some(fps),
        (!duration_s.is_nan()).then_some(duration_s),
        (width != 0).then_some(width),
        crate::surface::MAX_INPUT_BYTES,
    )
    .map_err(|e| JsValue::from_str(&e))?;
    let files: serde_json::Map<String, serde_json::Value> =
        a.files.into_iter().map(|(k, v)| (k, v.into())).collect();
    Ok(serde_json::json!({"summary": a.summary, "files": files}).to_string())
}

/// The bundled reference scenarios as JSON `{count, scenarios: [{name, kind, about}]}`; a
/// non-empty `kind` limits the list to one scenario kind.
#[wasm_bindgen]
pub fn list_examples(kind: &str) -> Result<String, JsValue> {
    crate::surface::list_examples((!kind.is_empty()).then_some(kind))
        .map(|v| v.to_string())
        .map_err(|e| JsValue::from_str(&e))
}

/// The TOML text of one bundled reference scenario, byte for byte the repository's file.
#[wasm_bindgen]
pub fn get_example(name: &str) -> Result<String, JsValue> {
    crate::surface::get_example(name)
        .map(str::to_string)
        .map_err(|e| JsValue::from_str(&e))
}

/// Bind an RFC 3161 timestamp token to an evidence pack, in memory. `files_json` is the pack's
/// files as JSON (name to text or `{"base64": ...}`); `token_base64` is the `.tsr` file's bytes
/// as base64; `replace` allows replacing an existing token. The pack with the token must still
/// verify or this throws. Returns JSON `{files, notes}`. This does NOT verify the timestamp
/// authority's signature or certificate chain (use `openssl ts -verify`). Nothing is uploaded.
#[wasm_bindgen]
pub fn evidence_attach_timestamp(
    files_json: &str,
    token_base64: &str,
    replace: bool,
) -> Result<String, JsValue> {
    let v: serde_json::Value = serde_json::from_str(files_json)
        .map_err(|e| JsValue::from_str(&format!("files_json is not JSON: {e}")))?;
    let files = crate::surface::files_from_json(&v).map_err(|e| JsValue::from_str(&e))?;
    let token = crate::permalink::base64_decode(token_base64.trim())
        .ok_or_else(|| JsValue::from_str("token_base64 is not base64"))?;
    let t = crate::surface::evidence_attach_timestamp(
        &files,
        &token,
        replace,
        crate::surface::MAX_INPUT_BYTES,
    )
    .map_err(|e| JsValue::from_str(&e))?;
    Ok(
        serde_json::json!({"files": crate::surface::files_to_json(&t.files), "notes": t.notes})
            .to_string(),
    )
}

/// Export a scenario's vehicle motion and events for a laboratory GNSS simulator
/// (`docs/TEST-BENCH.md`), in memory: nothing is uploaded or written. `epoch` is the UTC
/// instant of motion time zero, `YYYY-MM-DDTHH:MM:SS` with an optional `Z` (empty for the
/// default 2024-01-01T00:00:00Z). Returns JSON `{files: {suffix: text}, notes, notice}`; keep
/// `notice` with the files. No radio-frequency or baseband signal is written.
#[wasm_bindgen]
pub fn bench_export(toml: &str, epoch: &str) -> Result<String, JsValue> {
    use crate::surface::{BENCH_NOTICE, MAX_INPUT_BYTES};
    let e =
        crate::surface::bench_export(toml, (!epoch.is_empty()).then_some(epoch), MAX_INPUT_BYTES)
            .map_err(|e| JsValue::from_str(&e))?;
    let files: serde_json::Map<String, serde_json::Value> =
        e.files.into_iter().map(|(k, v)| (k, v.into())).collect();
    Ok(serde_json::json!({"files": files, "notes": e.notes, "notice": BENCH_NOTICE}).to_string())
}

/// Fill the public-framework mapping from result documents: which rows of five resilience
/// frameworks and standards (`docs/compliance/`) the runs support evidence for, which they
/// do not, and the gap each row keeps. `runs_json` is a JSON array of `{label, result,
/// scenario?}` where `result` is the result JSON text and `scenario` the scenario TOML text
/// (it names the scenario kind a result does not); at most 64 runs. Returns JSON
/// `{report, markdown}`. The report carries `statement` verbatim: a status says the runs
/// support evidence for a row's capabilities, not that a framework is met. Nothing is
/// uploaded or read from disk.
#[wasm_bindgen]
pub fn compliance_report(runs_json: &str) -> Result<String, JsValue> {
    use crate::surface::{ComplianceRunText, MAX_INPUT_BYTES};
    let v: serde_json::Value = serde_json::from_str(runs_json)
        .map_err(|e| JsValue::from_str(&format!("runs_json is not JSON: {e}")))?;
    let arr = v.as_array().ok_or_else(|| {
        JsValue::from_str("runs_json must be an array of {label, result, scenario?}")
    })?;
    let mut texts = Vec::with_capacity(arr.len());
    for (i, r) in arr.iter().enumerate() {
        let field = |k: &str| r.get(k).and_then(|x| x.as_str()).map(str::to_string);
        texts.push(ComplianceRunText {
            label: field("label")
                .ok_or_else(|| JsValue::from_str(&format!("runs[{i}] needs `label`")))?,
            result_json: field("result")
                .ok_or_else(|| JsValue::from_str(&format!("runs[{i}] needs `result`")))?,
            scenario_toml: field("scenario"),
        });
    }
    let out = crate::surface::compliance_report(&texts, MAX_INPUT_BYTES)
        .map_err(|e| JsValue::from_str(&e))?;
    Ok(serde_json::json!({"report": out.report, "markdown": out.markdown}).to_string())
}

/// The static public-framework mapping as Markdown, led by the statement every report
/// carries: the tables (`sources` false) or the source documents they cite (`sources` true).
#[wasm_bindgen]
pub fn compliance_mapping(sources: bool) -> String {
    crate::surface::compliance_mapping(sources)
}

/// Build a GNSS interference map from CSV text (`source` is `"adsb"` or `"ais"`; formats in
/// `docs/INTERFERENCE-MAP.md`). `dataset` is an approved preset or `"custom"`, which also
/// needs `licence`, `licence_url` and `attribution`; pass an empty string for any field
/// that does not apply, and `NaN` for the default 0.5 degree cell. `land_geojson` (AIS only,
/// empty for none) is a land-polygon file. Returns a JSON array of
/// `{file_name, date, cells_published, cells_flagged, geojson}`, one per UTC day. Aggregate
/// only; a degraded cell does not name interference as the cause. Nothing is uploaded.
#[wasm_bindgen]
#[allow(clippy::too_many_arguments)]
pub fn interference_map(
    source: &str,
    csv: &str,
    dataset: &str,
    cell_deg: f64,
    licence: &str,
    licence_url: &str,
    attribution: &str,
    land_geojson: &str,
) -> Result<String, JsValue> {
    use crate::surface::{interference_map as build, CustomDataset, MapSource, MAX_INPUT_BYTES};
    let custom =
        (!licence.is_empty() || !licence_url.is_empty() || !attribution.is_empty()).then(|| {
            CustomDataset {
                licence: licence.into(),
                licence_url: licence_url.into(),
                attribution: attribution.into(),
            }
        });
    let days = build(
        MapSource::parse(source).map_err(|e| JsValue::from_str(&e))?,
        csv,
        dataset,
        (!cell_deg.is_nan()).then_some(cell_deg),
        custom.as_ref(),
        (!land_geojson.is_empty()).then_some(land_geojson),
        MAX_INPUT_BYTES,
    )
    .map_err(|e| JsValue::from_str(&e))?;
    Ok(serde_json::Value::Array(
        days.into_iter()
            .map(|d| {
                serde_json::json!({
                    "file_name": d.file_name,
                    "date": d.date,
                    "cells_published": d.cells_published,
                    "cells_flagged": d.cells_flagged,
                    "geojson": d.geojson,
                })
            })
            .collect(),
    )
    .to_string())
}

/// Share of a route (GeoJSON LineString or `lat,lon` CSV text) through degraded cells of the
/// maps in `maps_json` (a JSON array of map GeoJSON strings, as `interference_map` returns),
/// optionally limited to `date_from`..`date_to` (`YYYY-MM-DD`, empty for no limit). Returns
/// the report as JSON text. Not a forecast; unobserved cells are not evidence of a clear
/// route.
#[wasm_bindgen]
pub fn route_exposure(
    route: &str,
    maps_json: &str,
    date_from: &str,
    date_to: &str,
) -> Result<String, JsValue> {
    let maps: Vec<String> = serde_json::from_str(maps_json).map_err(|e| {
        JsValue::from_str(&format!("maps_json must be a JSON array of strings: {e}"))
    })?;
    let refs: Vec<&str> = maps.iter().map(String::as_str).collect();
    crate::surface::route_exposure(
        route,
        &refs,
        (!date_from.is_empty()).then_some(date_from),
        (!date_to.is_empty()).then_some(date_to),
        crate::surface::MAX_INPUT_BYTES,
    )
    .map_err(|e| JsValue::from_str(&e))
}

/// Generate synthetic bridge NMEA 0183 for crew training from a `nmea-scenario` TOML.
/// `seed` replaces the scenario's seed unless it is `NaN` or negative. Returns a JSON object
/// `{nmea, log_json, log_text}`. Text only; never for a vessel's live navigation systems.
/// Advisory, not type-approved navigation equipment.
#[wasm_bindgen]
pub fn nmea_training(toml: &str, seed: f64) -> Result<String, JsValue> {
    let seed = (seed.is_finite() && seed >= 0.0).then_some(seed as u64);
    let t = crate::surface::nmea_training(toml, seed, crate::surface::MAX_INPUT_BYTES)
        .map_err(|e| JsValue::from_str(&e))?;
    Ok(
        serde_json::json!({"nmea": t.nmea, "log_json": t.log_json, "log_text": t.log_text})
            .to_string(),
    )
}

/// Score a bounded excerpt of a vessel's NMEA 0183 stream the way `kshana receiver-trust
/// live` scores it (at most 2 MiB and 20,000 epochs; it must hold the calibration window).
/// `session_toml` declares a vessel (`[platform] kind = "vessel"`). Returns a JSON object
/// `{schema, epochs, last_pksht, summary}` (`schema` is `"1.3"`): one report per epoch (`state`, `score`, `advisory`,
/// `deductions` with a `class` each, `alarms`, `geometry`, ...) and counts by state, geometry and
/// class. The geometry is `good`, `degraded` with reasons, or `unknown` without GSV or GSA, with a
/// `label` (`good`, `fair`, `poor`) always reported; the score deducts for geometry only when it
/// is `poor`. The bounded form of the live command: no
/// socket is opened and the gate is not applied (both are command-line only). Advisory software, not type-approved navigation equipment (IEC 61108, IEC 61162): the operator remains responsible for the navigation of the vessel.
#[wasm_bindgen]
pub fn receiver_trust_replay(session_toml: &str, nmea: &str) -> Result<String, JsValue> {
    let r = crate::surface::assess_vessel_excerpt(
        session_toml,
        nmea.as_bytes(),
        crate::surface::MAX_INPUT_BYTES,
    )
    .map_err(|e| JsValue::from_str(&e))?;
    serde_json::to_string(&r).map_err(|e| JsValue::from_str(&e.to_string()))
}

/// Assess a vessel's NMEA 0183 log as a batch run: `session_toml` (`[platform] kind =
/// "vessel"`, no `[log]` needed) and the log text. Returns the result document as JSON, the
/// same as `kshana receiver-trust` writes to `result.json`. Advisory software, not type-approved navigation equipment (IEC 61108, IEC 61162): the operator remains responsible for the navigation of the vessel.
#[wasm_bindgen]
pub fn assess_vessel_log(session_toml: &str, log: &str) -> Result<String, JsValue> {
    crate::surface::assess_vessel_log_json(
        session_toml,
        log.as_bytes(),
        crate::surface::MAX_INPUT_BYTES,
    )
    .map_err(|e| JsValue::from_str(&e))
}

/// Verify an evidence pack. `files_json` is a JSON object of file name to content: a string,
/// `{"utf8": text}` or `{"base64": bytes}`. `public_key` is the signer's key as 64 hex digits,
/// obtained from the signer by another route (empty for none: the signature then proves only
/// that the pack is intact against the key it names itself). `full_log` is the full log text
/// (empty for none). `require_timestamp` fails a pack without a timestamp token. Returns the
/// report as JSON: `ok`, `failures`, `checks`, `signer_fingerprint`, `signer_pinned`, `notes`,
/// plus `verdict` (`"verified"`, `"intact-signer-not-pinned"` or `"failed"`) and `message`. Nothing is uploaded; packs are made with the
/// command line, Python or the MCP server.
#[wasm_bindgen]
pub fn evidence_verify(
    files_json: &str,
    public_key: &str,
    full_log: &str,
    require_timestamp: bool,
) -> Result<String, JsValue> {
    let v: serde_json::Value = serde_json::from_str(files_json)
        .map_err(|e| JsValue::from_str(&format!("files_json is not JSON: {e}")))?;
    let files = crate::surface::files_from_json(&v).map_err(|e| JsValue::from_str(&e))?;
    let report = crate::surface::evidence_verify(
        &files,
        (!public_key.is_empty()).then_some(public_key),
        (!full_log.is_empty()).then_some(full_log.as_bytes()),
        require_timestamp,
    )
    .map_err(|e| JsValue::from_str(&e))?;
    Ok(report.to_string())
}

/// Render a trust stream or a batch result in one telemetry format, with the encoders
/// `kshana trust-telemetry` uses (no process, socket or clock). `format` is `"prometheus"`,
/// `"cef"`, `"leef"` or `"otlp"`; `input_kind` is `"result"` (a `receiver-trust` result
/// document) or `"jsonl"` (the live per-epoch stream); `host` names the sender in syslog
/// events (empty for `kshana`). `options_json` is `""` or an object with `expose_position`
/// (bool), `syslog_all` (bool: one event per epoch, not per band change) and `unix_nano`
/// (number, the time of export for `"otlp"`). Syslog lines carry no timestamp. Returns the
/// formatted text.
#[wasm_bindgen]
pub fn trust_telemetry(
    input: &str,
    format: &str,
    host: &str,
    input_kind: &str,
    options_json: &str,
) -> Result<String, JsValue> {
    use crate::surface::{self, TelemetryFormat, TelemetryInput, TelemetryOptions};
    let err = |e: String| JsValue::from_str(&e);
    let mut opts = TelemetryOptions::default();
    if !options_json.trim().is_empty() {
        let v: serde_json::Value = serde_json::from_str(options_json)
            .map_err(|e| err(format!("options_json is not JSON: {e}")))?;
        opts.expose_position = v["expose_position"].as_bool().unwrap_or(false);
        opts.syslog_all = v["syslog_all"].as_bool().unwrap_or(false);
        opts.unix_nano = v["unix_nano"].as_f64().unwrap_or(0.0) as u64;
    }
    surface::trust_telemetry(
        input,
        TelemetryFormat::parse(format).map_err(err)?,
        host,
        TelemetryInput::parse(input_kind).map_err(err)?,
        opts,
        surface::MAX_INPUT_BYTES,
    )
    .map_err(err)
}

/// Check Galileo OSNMA authentication of I/NAV pages, in memory, with the verifier
/// `kshana osnma verify` runs. Advisory: this is analysis and monitoring output and not
/// type-approved navigation equipment. The authentication status reported here is not a
/// navigation integrity service and must not be the sole basis for any navigation or safety
/// decision. `input_base64` is the pages (plain text or the published vector CSV) or a u-blox
/// UBX byte stream; `format` is `"pages"`, `"vector-csv"`, `"ubx"` or `""` (by content);
/// `start_gst` is a vector CSV's start in GST seconds; `merkle_root_hex` is the trusted Merkle
/// root (64 hex digits, or `""`); `public_keys` are trusted keys as `ID:TYPE:HEX`;
/// `reference_time` is the present time in GST seconds from an independent source and
/// `max_time_error` the widest distance of a sub-frame from it (below 30; needs a reference
/// time). Without a reference time freshness is not enforced and the report says so. Returns
/// the JSON `kshana osnma verify --json` prints. Nothing is uploaded.
#[wasm_bindgen]
pub fn osnma_verify(
    input_base64: &str,
    format: &str,
    start_gst: Option<u32>,
    merkle_root_hex: &str,
    public_keys: Vec<String>,
    reference_time: Option<u32>,
    max_time_error: Option<u32>,
) -> Result<String, JsValue> {
    let b64 = input_base64.trim();
    if b64.len() / 4 * 3 > crate::surface::MAX_INPUT_BYTES {
        return Err(JsValue::from_str(&format!(
            "input is about {} bytes, over the {}-byte limit",
            b64.len() / 4 * 3,
            crate::surface::MAX_INPUT_BYTES
        )));
    }
    let bytes = crate::permalink::base64_decode(b64)
        .ok_or_else(|| JsValue::from_str("input_base64 is not base64"))?;
    crate::surface::osnma_verify(
        &bytes,
        format,
        start_gst,
        merkle_root_hex,
        &public_keys,
        reference_time,
        max_time_error,
        crate::surface::MAX_INPUT_BYTES,
    )
    .map_err(|e| JsValue::from_str(&e))
}

/// The satellites a site sees under a skyline and their geometry (design note item 2).
/// `request_json` is a JSON (or TOML) object: `site` (`{lat_deg, lon_deg, height_m}`),
/// `time_s`, `systems` (preset names such as `"gps-baseline"`, `"galileo"`, `"beidou-meo"`,
/// `"xona-pulsar"`, or `leo-pvt` `[[system]]` objects) and/or `satellites` (`{id?, system?,
/// az_deg, el_deg}` or `{id?, system?, ecef_m}`), `mask_deg`, `skyline` (`preset`,
/// `street_az_deg`, `width_m`, `height_left_m`, `height_right_m`, `antenna_m`, `length_m`,
/// `table`, `sectors`, `terrain`), `clock` (`"per-system"` default, or `"common"`),
/// `sigma_uere_m` (default 1) and `confidence` (default 0.95). Returns a JSON object: per
/// satellite `id`, `system`, `az_deg`, `el_deg`, `cut_deg`, `visible`, `masked`; `n_visible`,
/// `n_masked`, `open_fraction`; `dop` (`gdop`, `pdop`, `hdop`, `vdop`, `tdop`,
/// `tdop_by_clock`, or null); `states`, `cofactor_enu`, `covariance_enu_m2`; `ellipse_1sigma`
/// and `ellipse` (`semi_major_m`, `semi_minor_m`, `orientation_deg`, ...); `label`
/// (MODELLED), `statement` and `advisory`. Throws a JS error on an invalid request.
#[wasm_bindgen]
pub fn sky_geometry(request_json: &str) -> Result<String, JsValue> {
    crate::surface::sky_geometry(request_json, crate::surface::MAX_INPUT_BYTES)
        .map_err(|e| JsValue::from_str(&e))
}

/// `n` (1 to 5000) least-squares position errors under independent Gaussian range errors of
/// `sigma_uere_m` on the visible set of `request_json` (as for `sky_geometry`), seeded by
/// `seed` (a non-negative integer; the same request, seed and `n` give the same cloud). Returns
/// a JSON object: `samples_enu_m` (`[[e, n, u], ...]`), `empirical_covariance_enu_m2`,
/// `rms_horizontal_m`, `rms_3d_m`, `predicted_rms_horizontal_m` (sigma x HDOP),
/// `predicted_rms_3d_m`, `fraction_inside_95`, `label`, `statement`, `advisory`. Throws a JS
/// error on an invalid request, a seed that is not a non-negative integer, or `n` out of range.
#[wasm_bindgen]
pub fn sky_monte_carlo(request_json: &str, seed: f64, n: u32) -> Result<String, JsValue> {
    if !(seed.is_finite() && seed >= 0.0 && seed.fract() == 0.0 && seed <= 9_007_199_254_740_991.0)
    {
        return Err(JsValue::from_str("seed must be a non-negative integer"));
    }
    crate::surface::sky_monte_carlo(
        request_json,
        seed as u64,
        n as usize,
        crate::surface::MAX_INPUT_BYTES,
    )
    .map_err(|e| JsValue::from_str(&e))
}

/// The named skyline presets (`city-street`, `harbour-approach`, `fjord`,
/// `container-terminal`) as a JSON array: `name`, `label` (REPRESENTATIVE), `description`,
/// `provenance`, `table` (the cut every degree of azimuth from north, 360 numbers) and
/// `open_fraction`.
#[wasm_bindgen]
pub fn skyline_presets() -> String {
    crate::surface::skyline_presets()
}

/// A skyline section (`skyline_json`, the `skyline` object of a `sky_geometry` request) reduced
/// to the normalised table the engine uses: a JSON object with `table` (360 numbers, the cut
/// every degree of azimuth from north), `open_fraction`, `source` and `provenance`. Throws a
/// JS error on an invalid section.
#[wasm_bindgen]
pub fn skyline_profile(skyline_json: &str) -> Result<String, JsValue> {
    crate::surface::skyline_profile(skyline_json, crate::surface::MAX_INPUT_BYTES)
        .map_err(|e| JsValue::from_str(&e))
}

/// The skyplot of `request_json` (as for `sky_geometry`) as static SVG markup (no script, no
/// external reference; every input string escaped). Throws a JS error on an invalid request.
#[wasm_bindgen]
pub fn skyplot_svg(request_json: &str) -> Result<String, JsValue> {
    crate::surface::skyplot_svg(request_json, crate::surface::MAX_INPUT_BYTES)
        .map_err(|e| JsValue::from_str(&e))
}

/// The signal names `iq_run_short` accepts: a JSON array.
#[wasm_bindgen]
pub fn iq_signals() -> String {
    crate::iq::short::signals_json().to_string()
}

/// A short synthetic scene, acquired and tracked in memory: `ids` are the PRNs (GLONASS L1OF:
/// the frequency channel), `dopplers_hz` one value for all or one each, `cn0_dbhz` NaN for the
/// elevation default. Bounded to 0.25 s, 1 000 000 samples and 8 satellites. Returns JSON
/// `{fs_hz, samples, acquisition, tracking}`; the same request gives the same answer as the
/// native build.
#[wasm_bindgen]
pub fn iq_run_short(
    fs_hz: f64,
    duration_s: f64,
    signal: &str,
    ids: Vec<f64>,
    dopplers_hz: Vec<f64>,
    cn0_dbhz: f64,
    seed: u32,
) -> Result<String, JsValue> {
    let req = crate::iq::short::ShortRequest {
        fs_hz,
        duration_s,
        signal: signal.to_string(),
        ids: ids.iter().map(|&v| v as i64).collect(),
        dopplers: dopplers_hz,
        cn0_dbhz: if cn0_dbhz.is_nan() {
            None
        } else {
            Some(cn0_dbhz)
        },
        seed: u64::from(seed),
    };
    crate::iq::short::run_short(&req)
        .map(|v| v.to_string())
        .map_err(|e| JsValue::from_str(&e))
}