Skip to main content

str_format/
meta.rs

1//! `.str.toml` 的解析、类型化提取与**归一化**(TOML → 规范 JSON)。
2//!
3//! 保注释写回与新建模板见 [`crate::meta_edit`]。
4
5use std::path::Path;
6
7use serde_json::{Map as JMap, Value as JValue};
8use toml_edit::{DocumentMut, Item, Table};
9
10use crate::error::{Error, Issue, Result, code};
11use crate::util;
12
13// ─────────────────────────── 规范 4.9:键序与表序 ───────────────────────────
14
15/// 顶层裸键的规范顺序(必须写在任何表头之前)。
16pub const TOP_BARE_KEYS: &[&str] = &[
17    "str",
18    "spec",
19    "kind",
20    "id",
21    "name",
22    "type",
23    "title",
24    "summary",
25    "tags",
26    "revision",
27    "created_at",
28    "updated_at",
29    "schema",
30];
31
32/// 表 / 数组表的规范顺序。
33pub const TABLE_ORDER: &[&str] = &["policies", "authors", "refs", "entries", "ext"];
34
35/// `[policies]` 内键序。
36pub const POLICIES_KEYS: &[&str] = &[
37    "id_version",
38    "max_depth",
39    "manifest",
40    "sha256",
41    "ignore",
42    "gitignore",
43    "large_asset_bytes",
44    "deep_tree_warn",
45];
46
47/// `[[authors]]` 内键序。
48pub const AUTHOR_KEYS: &[&str] = &["id", "name", "role", "at"];
49
50/// `[[refs]]` 内键序。
51pub const REF_KEYS: &[&str] = &["id", "target", "rel", "title", "order", "note"];
52
53/// `[[entries]]` 内键序。
54pub const ENTRY_KEYS: &[&str] = &[
55    "path",
56    "role",
57    "id",
58    // `target`:链接(`role = "link"`)的目标分支 id(规范 §4.6.1)。
59    "target",
60    // `mode`:链接形态(soft / hard,规范 §4.6.1)。
61    "mode",
62    "type",
63    "title",
64    "summary",
65    "order",
66    "media_type",
67    "size",
68    "sha256",
69    "count",
70    "schema",
71    "optional",
72    "note",
73];
74
75/// root 允许的顶层键。
76pub const ROOT_ALLOWED: &[&str] = &[
77    "str", "spec", "kind", "id", "name", "type", "title", "summary", "tags", "revision",
78    "created_at", "updated_at", "schema", "policies", "authors", "refs", "entries", "ext",
79];
80
81/// node / branch 允许的顶层键(无 `policies`)。
82pub const BRANCH_ALLOWED: &[&str] = &[
83    "str", "spec", "kind", "id", "name", "type", "title", "summary", "tags", "revision",
84    "created_at", "updated_at", "schema", "authors", "refs", "entries", "ext",
85];
86
87// ─────────────────────────── 模型 ───────────────────────────
88
89/// `kind` 档位。
90#[derive(Debug, Clone, Copy, PartialEq, Eq)]
91pub enum Kind {
92    /// ROOT(深度 0)。
93    Root,
94    /// 独立节点(深度 1)。
95    Node,
96    /// 关联分支(深度 ≥2)。
97    Branch,
98}
99
100impl Kind {
101    /// 字面量。
102    pub fn as_str(self) -> &'static str {
103        match self {
104            Kind::Root => "root",
105            Kind::Node => "node",
106            Kind::Branch => "branch",
107        }
108    }
109
110    /// 解析字面量。
111    pub fn parse(s: &str) -> Option<Kind> {
112        match s {
113            "root" => Some(Kind::Root),
114            "node" => Some(Kind::Node),
115            "branch" => Some(Kind::Branch),
116            _ => None,
117        }
118    }
119
120    /// root 与 node/branch 的允许键集。
121    pub fn allowed_top_keys(self) -> &'static [&'static str] {
122        match self {
123            Kind::Root => ROOT_ALLOWED,
124            _ => BRANCH_ALLOWED,
125        }
126    }
127}
128
129/// 清单策略(`policies.manifest`)。
130#[derive(Debug, Clone, Copy, PartialEq, Eq)]
131pub enum ManifestPolicy {
132    /// 清单不一致为 error。
133    Strict,
134    /// 清单不一致仅告警。
135    Advisory,
136}
137
138/// 指纹策略(`policies.sha256`)。
139#[derive(Debug, Clone, Copy, PartialEq, Eq)]
140pub enum ShaPolicy {
141    /// 文件类条目必须有 `size` + `sha256`。
142    Required,
143    /// 可选。
144    Optional,
145    /// 完全不校验。
146    Off,
147}
148
149/// 校验策略(仅 root)。
150#[derive(Debug, Clone, PartialEq, Eq)]
151pub struct Policies {
152    /// UUID 版本要求。
153    pub id_version: usize,
154    /// 分支树最大深度。
155    pub max_depth: usize,
156    /// 清单策略。
157    pub manifest: ManifestPolicy,
158    /// 指纹策略。
159    pub sha256: ShaPolicy,
160    /// 忽略名单(gitignore 语义模式,bundle 内相对路径)。
161    pub ignore: Vec<String>,
162    /// 是否自动检测并应用 `.gitignore`(规范 4.7,默认开)。
163    pub gitignore: bool,
164    /// 大文件告警阈值。
165    pub large_asset_bytes: u64,
166    /// 深树告警阈值。
167    pub deep_tree_warn: usize,
168}
169
170impl Default for Policies {
171    fn default() -> Self {
172        Self {
173            id_version: 7,
174            max_depth: 32,
175            manifest: ManifestPolicy::Strict,
176            sha256: ShaPolicy::Required,
177            ignore: Vec::new(),
178            gitignore: true,
179            large_asset_bytes: 10 * 1024 * 1024,
180            deep_tree_warn: 16,
181        }
182    }
183}
184
185/// `[[authors]]` 元素。
186#[derive(Debug, Clone, Default, PartialEq, Eq)]
187pub struct Author {
188    /// 稳定标识符。
189    pub id: String,
190    /// 展示名。
191    pub name: Option<String>,
192    /// 角色。
193    pub role: String,
194    /// 参与时间。
195    pub at: Option<String>,
196}
197
198/// `[[refs]]` 元素(跨枝关联线)。
199#[derive(Debug, Clone, Default, PartialEq, Eq)]
200pub struct RefItem {
201    /// 关联线自身 id。
202    pub id: String,
203    /// 目标分支 id。
204    pub target: String,
205    /// 关联语义。
206    pub rel: String,
207    /// 标签。
208    pub title: Option<String>,
209    /// 排序键。
210    pub order: Option<i64>,
211    /// 备注。
212    pub note: Option<String>,
213}
214
215/// `[[entries]]` 元素(本目录内容清单)。
216#[derive(Debug, Clone, Default, PartialEq, Eq)]
217pub struct Entry {
218    /// 单段路径。
219    pub path: String,
220    /// 角色。
221    pub role: String,
222    /// 子分支 id(`node` / `branch`)。
223    pub id: Option<String>,
224    /// 软连接目标分支 id(`role = "link"`,规范 §4.6.1)。
225    pub target: Option<String>,
226    /// 链接形态(仅 `role = "link"`):`"soft"`(缺省,目标完整视图)|
227    /// `"hard"`(仅内容关联,只读,不渲染目标的子分支)。
228    pub mode: Option<String>,
229    /// 子分支类型。
230    pub r#type: Option<String>,
231    /// 展示名。
232    pub title: Option<String>,
233    /// 摘要。
234    pub summary: Option<String>,
235    /// 排序键。
236    pub order: Option<i64>,
237    /// IANA 媒体类型。
238    pub media_type: Option<String>,
239    /// 字节数。
240    pub size: Option<i64>,
241    /// 内容指纹。
242    pub sha256: Option<String>,
243    /// 直接子项数(`dir`)。
244    pub count: Option<i64>,
245    /// 该文件遵循的 Schema。
246    pub schema: Option<String>,
247    /// 是否允许缺失。
248    pub optional: bool,
249    /// 备注。
250    pub note: Option<String>,
251}
252
253impl Entry {
254    /// 是否为分支条目(`node` / `branch`)。
255    pub fn is_branch(&self) -> bool {
256        self.role == "node" || self.role == "branch"
257    }
258
259    /// 是否为软连接子分支(`role = "link"`):声明式挂载,**磁盘上无对应目录**。
260    pub fn is_link(&self) -> bool {
261        self.role == "link"
262    }
263
264    /// 是否为文件类条目(需要指纹)。
265    pub fn is_file_like(&self) -> bool {
266        self.role == "payload" || self.role == "asset"
267    }
268}
269
270/// 一份 `.str.toml` 的完整内容:保序文档 + 类型化视图。
271#[derive(Debug)]
272pub struct Meta {
273    /// 保注释、保顺序的 TOML 文档(写回用)。
274    pub doc: DocumentMut,
275    /// `str` 主版本。
276    pub str_version: Option<i64>,
277    /// 规范版本。
278    pub spec: Option<String>,
279    /// 档位。
280    pub kind_raw: Option<String>,
281    /// 解析出的档位。
282    pub kind: Option<Kind>,
283    /// 自身 id。
284    pub id: Option<String>,
285    /// bundle 短名(root)。
286    pub name: Option<String>,
287    /// 类型。
288    pub r#type: Option<String>,
289    /// 标题。
290    pub title: Option<String>,
291    /// 摘要。
292    pub summary: Option<String>,
293    /// 标签。
294    pub tags: Vec<String>,
295    /// 修订号。
296    pub revision: Option<i64>,
297    /// 创建时间。
298    pub created_at: Option<String>,
299    /// 更新时间。
300    pub updated_at: Option<String>,
301    /// payload schema 引用。
302    pub schema: Option<String>,
303    /// 策略。
304    pub policies: Policies,
305    /// 贡献者。
306    pub authors: Vec<Author>,
307    /// 跨枝关联。
308    pub refs: Vec<RefItem>,
309    /// 内容清单。
310    pub entries: Vec<Entry>,
311}
312
313/// 加载结果。
314pub enum MetaLoad {
315    /// 解析成功(可能带有字段级问题)。
316    Ok(Box<Meta>, Vec<Issue>),
317    /// 解析失败(`E_PARSE`),无法构建模型。
318    Failed(Vec<Issue>),
319}
320
321/// 从磁盘读取并解析一份 `.str.toml`。
322pub fn load(path: &Path, rel: &str) -> Result<MetaLoad> {
323    let bytes = std::fs::read(path).map_err(|e| Error::io(path, e))?;
324    let mut issues = Vec::new();
325
326    // 编码:UTF-8 无 BOM
327    if bytes.starts_with(&[0xEF, 0xBB, 0xBF]) {
328        issues.push(Issue::error(
329            code::PARSE,
330            rel,
331            "文件含 UTF-8 BOM,规范要求 UTF-8 无 BOM",
332        ));
333        return Ok(MetaLoad::Failed(issues));
334    }
335    let text = match std::str::from_utf8(&bytes) {
336        Ok(t) => t,
337        Err(e) => {
338            issues.push(Issue::error(
339                code::PARSE,
340                rel,
341                format!("编码非 UTF-8:{e}"),
342            ));
343            return Ok(MetaLoad::Failed(issues));
344        }
345    };
346
347    let doc: DocumentMut = match text.parse() {
348        Ok(d) => d,
349        Err(e) => {
350            issues.push(Issue::error(code::PARSE, rel, format!("TOML 解析失败:{e}")));
351            return Ok(MetaLoad::Failed(issues));
352        }
353    };
354
355    let (meta, mut field_issues) = extract(doc, rel);
356    issues.append(&mut field_issues);
357    Ok(MetaLoad::Ok(Box::new(meta), issues))
358}
359
360/// 从已解析的文档构建类型化视图。
361pub fn extract(doc: DocumentMut, rel: &str) -> (Meta, Vec<Issue>) {
362    let mut cx = Ctx {
363        rel: rel.to_string(),
364        issues: Vec::new(),
365    };
366    let table = doc.as_table().clone();
367
368    let str_version = cx.opt_int(&table, "str");
369    let spec = cx.opt_str(&table, "spec");
370    let kind_raw = cx.opt_str(&table, "kind");
371    let kind = match kind_raw.as_deref() {
372        Some(s) => match Kind::parse(s) {
373            Some(k) => Some(k),
374            None => {
375                cx.err(
376                    code::KIND_INVALID,
377                    format!("`kind` = {s:?} 非法(应为 root / node / branch)"),
378                );
379                None
380            }
381        },
382        None => {
383            cx.err(code::SCHEMA_FIELD, "缺少必填字段 `kind`");
384            None
385        }
386    };
387
388    let allowed = kind.map(|k| k.allowed_top_keys()).unwrap_or(BRANCH_ALLOWED);
389    cx.check_unknown(&table, allowed);
390
391    // 注意:TOML 无法表达空的数组表,故 `entries` / `refs` 为空时整表省略,
392    // 归一化时补 `[]`(规范 4.1 / 4.9)。
393    for key in ["id", "revision", "created_at", "updated_at"] {
394        if table.get(key).is_none() {
395            cx.err(code::SCHEMA_FIELD, format!("缺少必填字段 `{key}`"));
396        }
397    }
398
399    let id = cx.opt_str(&table, "id");
400    let name = cx.opt_str(&table, "name");
401    let r#type = cx.opt_str(&table, "type");
402    let title = cx.opt_str(&table, "title");
403    let summary = cx.opt_str(&table, "summary");
404    let tags = cx.opt_str_array(&table, "tags").unwrap_or_default();
405    let revision = cx.opt_int(&table, "revision");
406    let created_at = cx.opt_dt(&table, "created_at");
407    let updated_at = cx.opt_dt(&table, "updated_at");
408    let schema = cx.opt_str(&table, "schema");
409
410    // `[policies]`(仅 root)
411    let mut policies = Policies::default();
412    if let Some(item) = table.get("policies") {
413        match item.as_table() {
414            Some(pt) => {
415                if kind != Some(Kind::Root) {
416                    cx.err(
417                        code::SCHEMA_FIELD,
418                        "`[policies]` 只能出现在 root 的 `.str.toml` 中",
419                    );
420                }
421                cx.check_unknown(pt, POLICIES_KEYS);
422                if let Some(v) = cx.opt_int(pt, "id_version") {
423                    policies.id_version = v.max(0) as usize;
424                }
425                if let Some(v) = cx.opt_int(pt, "max_depth") {
426                    policies.max_depth = v.max(1) as usize;
427                }
428                if let Some(v) = cx.opt_str(pt, "manifest") {
429                    policies.manifest = match v.as_str() {
430                        "strict" => ManifestPolicy::Strict,
431                        "advisory" => ManifestPolicy::Advisory,
432                        _ => {
433                            cx.err(
434                                code::SCHEMA_FIELD,
435                                format!("`policies.manifest` = {v:?} 非法(strict / advisory)"),
436                            );
437                            policies.manifest
438                        }
439                    };
440                }
441                if let Some(v) = cx.opt_str(pt, "sha256") {
442                    policies.sha256 = match v.as_str() {
443                        "required" => ShaPolicy::Required,
444                        "optional" => ShaPolicy::Optional,
445                        "off" => ShaPolicy::Off,
446                        _ => {
447                            cx.err(
448                                code::SCHEMA_FIELD,
449                                format!("`policies.sha256` = {v:?} 非法(required / optional / off)"),
450                            );
451                            policies.sha256
452                        }
453                    };
454                }
455                if let Some(v) = cx.opt_str_array(pt, "ignore") {
456                    policies.ignore = v.into_iter().filter(|s| !s.trim().is_empty()).collect();
457                }
458                if let Some(item) = pt.get("gitignore") {
459                    match item.as_bool() {
460                        Some(b) => policies.gitignore = b,
461                        None => cx.err(
462                            code::SCHEMA_FIELD,
463                            "`policies.gitignore` 必须是布尔值",
464                        ),
465                    }
466                }
467                if let Some(v) = cx.opt_int(pt, "large_asset_bytes") {
468                    policies.large_asset_bytes = v.max(0) as u64;
469                }
470                if let Some(v) = cx.opt_int(pt, "deep_tree_warn") {
471                    policies.deep_tree_warn = v.max(1) as usize;
472                }
473            }
474            None => cx.err(code::SCHEMA_FIELD, "`policies` 必须是表 `[policies]`"),
475        }
476    }
477
478    // `[[authors]]`
479    let mut authors = Vec::new();
480    if let Some(aot) = table.get("authors").and_then(|i| i.as_array_of_tables()) {
481        for (i, t) in aot.iter().enumerate() {
482            cx.set_rel(&format!("{rel} #authors[{i}]"));
483            cx.check_unknown(t, AUTHOR_KEYS);
484            let aid = cx.req_str(t, "id").unwrap_or_default();
485            let role = cx.req_str(t, "role").unwrap_or_default();
486            let aname = cx.opt_str(t, "name");
487            let at = cx.opt_dt(t, "at");
488            authors.push(Author {
489                id: aid,
490                name: aname,
491                role,
492                at,
493            });
494        }
495        cx.set_rel(rel);
496    } else if table.get("authors").is_some() {
497        cx.err(code::SCHEMA_FIELD, "`authors` 必须是数组表 `[[authors]]`");
498    }
499
500    // `[[refs]]`
501    let mut refs = Vec::new();
502    if let Some(aot) = table.get("refs").and_then(|i| i.as_array_of_tables()) {
503        for (i, t) in aot.iter().enumerate() {
504            cx.set_rel(&format!("{rel} #refs[{i}]"));
505            cx.check_unknown(t, REF_KEYS);
506            refs.push(RefItem {
507                id: cx.req_str(t, "id").unwrap_or_default(),
508                target: cx.req_str(t, "target").unwrap_or_default(),
509                rel: cx.req_str(t, "rel").unwrap_or_default(),
510                title: cx.opt_str(t, "title"),
511                order: cx.opt_int(t, "order"),
512                note: cx.opt_str(t, "note"),
513            });
514        }
515        cx.set_rel(rel);
516    } else if table.get("refs").is_some() {
517        cx.err(code::SCHEMA_FIELD, "`refs` 必须是数组表 `[[refs]]`");
518    }
519
520    // `[[entries]]`
521    let mut entries = Vec::new();
522    if let Some(aot) = table.get("entries").and_then(|i| i.as_array_of_tables()) {
523        for (i, t) in aot.iter().enumerate() {
524            cx.set_rel(&format!("{rel} #entries[{i}]"));
525            cx.check_unknown(t, ENTRY_KEYS);
526            let path = cx.req_str(t, "path").unwrap_or_default();
527            let role = cx.req_str(t, "role").unwrap_or_default();
528            if path.contains('/') {
529                cx.err(
530                    code::SCHEMA_FIELD,
531                    format!("`entries[].path` = {path:?} 必须是单段路径(不含 `/`)"),
532                );
533            }
534            let e = Entry {
535                path,
536                role,
537                id: cx.opt_str(t, "id"),
538                target: cx.opt_str(t, "target"),
539                mode: cx.opt_str(t, "mode"),
540                r#type: cx.opt_str(t, "type"),
541                title: cx.opt_str(t, "title"),
542                summary: cx.opt_str(t, "summary"),
543                order: cx.opt_int(t, "order"),
544                media_type: cx.opt_str(t, "media_type"),
545                size: cx.opt_int(t, "size"),
546                sha256: cx.opt_str(t, "sha256"),
547                count: cx.opt_int(t, "count"),
548                schema: cx.opt_str(t, "schema"),
549                optional: cx.opt_bool(t, "optional").unwrap_or(false),
550                note: cx.opt_str(t, "note"),
551            };
552            entries.push(e);
553        }
554        cx.set_rel(rel);
555    } else if table.get("entries").is_some() {
556        cx.err(code::SCHEMA_FIELD, "`entries` 必须是数组表 `[[entries]]`");
557    }
558
559    let meta = Meta {
560        doc,
561        str_version,
562        spec,
563        kind_raw,
564        kind,
565        id,
566        name,
567        r#type,
568        title,
569        summary,
570        tags,
571        revision,
572        created_at,
573        updated_at,
574        schema,
575        policies,
576        authors,
577        refs,
578        entries,
579    };
580    (meta, cx.issues)
581}
582
583// ─────────────────────────── 规范 4.9:确定性序列化 ───────────────────────────
584
585/// 规范 §4.9 的**全量规范化**:顶层裸键序 → 表序 → 各表内键序 → `entries` / `refs` 集合排序,
586/// 最后重设文档位置使顺序真正落到磁盘字节上。
587///
588/// 只调整**书写顺序**,不改动任何字段值:`toml_edit` 的键/项装饰(注释、空行)随项一起搬运,
589/// 因此注释保真(规范 4.1 / DoD 16)。
590pub fn canonicalize_doc(doc: &mut DocumentMut) {
591    // 1) 顶层:值项(裸键)按 `TOP_BARE_KEYS`,表项按 `TABLE_ORDER`。
592    //    未知的值项排在已知裸键之后、表项之前 —— 否则未知裸键会被排到表头之后,直接产出非法 TOML。
593    let top_rank = |k: &str, it: &Item| -> usize {
594        match it {
595            Item::Table(_) | Item::ArrayOfTables(_) => {
596                TOP_BARE_KEYS.len()
597                    + 1
598                    + TABLE_ORDER
599                        .iter()
600                        .position(|x| *x == k)
601                        .unwrap_or(TABLE_ORDER.len())
602            }
603            _ => TOP_BARE_KEYS
604                .iter()
605                .position(|x| *x == k)
606                .unwrap_or(TOP_BARE_KEYS.len()),
607        }
608    };
609    doc.as_table_mut()
610        .sort_values_by(|k1, i1, k2, i2| top_rank(k1.get(), i1).cmp(&top_rank(k2.get(), i2)));
611
612    // 2) 各表内的键序。
613    for (key, order) in [
614        ("policies", POLICIES_KEYS),
615        ("authors", AUTHOR_KEYS),
616        ("refs", REF_KEYS),
617        ("entries", ENTRY_KEYS),
618    ] {
619        let rank = |k: &str| order.iter().position(|x| *x == k).unwrap_or(usize::MAX);
620        match doc.as_table_mut().get_mut(key) {
621            Some(Item::Table(t)) => {
622                t.sort_values_by(|k1, _, k2, _| rank(k1.get()).cmp(&rank(k2.get())));
623            }
624            Some(Item::ArrayOfTables(a)) => {
625                for t in a.iter_mut() {
626                    t.sort_values_by(|k1, _, k2, _| rank(k1.get()).cmp(&rank(k2.get())));
627                }
628            }
629            _ => {}
630        }
631    }
632
633    // 3) 集合排序(§4.9「各自按 `order` 稳定排序」)。
634    sort_collections_in(doc);
635
636    // 4) 位置重设,见 `renumber_positions_in`。
637    renumber_positions_in(doc);
638}
639
640/// `entries` / `refs` 的排序键:`(order, path|id)`,缺 `order` 视为最大。
641fn collection_sort_key(t: &Table) -> (i64, String) {
642    let order = t
643        .get("order")
644        .and_then(Item::as_integer)
645        .unwrap_or(i64::MAX);
646    let id = t
647        .get("path")
648        .or_else(|| t.get("id"))
649        .and_then(Item::as_str)
650        .unwrap_or("")
651        .to_string();
652    (order, id)
653}
654
655/// 就地重排 `entries` / `refs` 的元素(不改变元素自身的 `doc_position`)。
656fn sort_collections_in(doc: &mut DocumentMut) {
657    for key in ["entries", "refs"] {
658        let Some(aot) = doc
659            .as_table_mut()
660            .get_mut(key)
661            .and_then(Item::as_array_of_tables_mut)
662        else {
663            continue;
664        };
665        let mut items: Vec<Table> = aot.iter().cloned().collect();
666        items.sort_by_key(collection_sort_key);
667        for (slot, table) in aot.iter_mut().zip(items) {
668            *slot = table;
669        }
670    }
671}
672
673/// 依**前序遍历顺序**重设整篇文档每个表的 `doc_position`。
674///
675/// `toml_edit` 的 `DocumentMut::fmt` 会用 `Table::position()` 把表「搬回原始位置」:
676/// 只重排内容而不重设位置,序列化结果仍保持解析时的旧顺序 —— 这正是 `sort_collections()`
677/// 此前「改了等于没改」的根因。前序赋值保证位置序 == 遍历序 ==(规范化后的)书写顺序。
678fn renumber_positions_in(doc: &mut DocumentMut) {
679    fn walk(t: &mut Table, pos: &mut isize) {
680        *pos += 1;
681        t.set_position(Some(*pos));
682        for (_, item) in t.iter_mut() {
683            match item {
684                Item::Table(child) => walk(child, pos),
685                Item::ArrayOfTables(a) => {
686                    for child in a.iter_mut() {
687                        walk(child, pos);
688                    }
689                }
690                _ => {}
691            }
692        }
693    }
694    let mut pos = 0isize;
695    walk(doc.as_table_mut(), &mut pos);
696}
697
698// ─────────────────────────── 归一化(TOML → 规范 JSON)───────────────────────────
699
700impl Meta {
701    /// 归一化为**规范 JSON**:顶层裸键与各表按 4.9 的键序/表序输出,
702    /// 未知键原样保留,使其可被 JSON Schema 校验器与 AI 稳定消费。
703    pub fn to_json(&self) -> JValue {
704        let table = self.doc.as_table();
705        let mut map = JMap::new();
706
707        for key in TOP_BARE_KEYS {
708            if let Some(item) = table.get(key) {
709                map.insert((*key).to_string(), item_to_json(item));
710            }
711        }
712        if let Some(item) = table.get("policies") {
713            match item.as_table() {
714                Some(t) => {
715                    map.insert("policies".into(), table_to_json(t, POLICIES_KEYS));
716                }
717                None => {
718                    map.insert("policies".into(), item_to_json(item));
719                }
720            }
721        }
722        if let Some(aot) = table.get("authors").and_then(|i| i.as_array_of_tables()) {
723            map.insert(
724                "authors".into(),
725                JValue::Array(
726                    aot.iter()
727                        .map(|t| table_to_json(t, AUTHOR_KEYS))
728                        .collect(),
729                ),
730            );
731        }
732        // `refs` 为空(TOML 无法表达空数组表)时补 `[]`
733        map.insert(
734            "refs".into(),
735            match table.get("refs").and_then(|i| i.as_array_of_tables()) {
736                Some(aot) => JValue::Array(
737                    aot.iter()
738                        .map(|t| table_to_json(t, REF_KEYS))
739                        .collect(),
740                ),
741                None => JValue::Array(Vec::new()),
742            },
743        );
744        map.insert(
745            "entries".into(),
746            match table.get("entries").and_then(|i| i.as_array_of_tables()) {
747                Some(aot) => JValue::Array(
748                    aot.iter()
749                        .map(|t| table_to_json(t, ENTRY_KEYS))
750                        .collect(),
751                ),
752                None => JValue::Array(Vec::new()),
753            },
754        );
755        if let Some(item) = table.get("ext") {
756            map.insert("ext".into(), item_to_json(item));
757        }
758        // 未知键原样保留(前向兼容)
759        for (k, v) in table.iter() {
760            if !map.contains_key(k) {
761                map.insert(k.to_string(), item_to_json(v));
762            }
763        }
764        JValue::Object(map)
765    }
766
767    /// 按 `(order, path|id)` 重排 `entries` / `refs`,并重设文档位置使新顺序真正落盘。
768    pub fn sort_collections(&mut self) {
769        sort_collections_in(&mut self.doc);
770        renumber_positions_in(&mut self.doc);
771    }
772
773    /// 规范 §4.9 全量规范化(顶层键序 + 表序 + 表内键序 + 集合排序)。
774    pub fn canonicalize(&mut self) {
775        canonicalize_doc(&mut self.doc);
776    }
777
778    /// 校验序号等基础合法性(`E_REVISION_STALE` 的可判定部分)。
779    pub fn revision_issues(&self, rel: &str) -> Vec<Issue> {
780        let mut out = Vec::new();
781        match self.revision {
782            None => {}
783            Some(r) if r < 1 => out.push(Issue::error(
784                code::REVISION_STALE,
785                rel,
786                format!("`revision` = {r},必须为 ≥ 1 的整数"),
787            )),
788            Some(_) => {}
789        }
790        if let (Some(c), Some(u)) = (self.created_at.as_deref(), self.updated_at.as_deref()) {
791            match (util::parse_rfc3339(c), util::parse_rfc3339(u)) {
792                (Some(cd), Some(ud)) if ud < cd => out.push(Issue::error(
793                    code::REVISION_STALE,
794                    rel,
795                    format!("`updated_at`({u})早于 `created_at`({c})"),
796                )),
797                _ => {}
798            }
799        }
800        out
801    }
802}
803
804/// TOML `Item` → JSON。
805fn item_to_json(item: &Item) -> JValue {
806    match item {
807        Item::None => JValue::Null,
808        Item::Value(v) => value_to_json(v),
809        Item::Table(t) => {
810            let mut m = JMap::new();
811            for (k, v) in t.iter() {
812                m.insert(k.to_string(), item_to_json(v));
813            }
814            JValue::Object(m)
815        }
816        Item::ArrayOfTables(aot) => JValue::Array(
817            aot.iter()
818                .map(|t| {
819                    let mut m = JMap::new();
820                    for (k, v) in t.iter() {
821                        m.insert(k.to_string(), item_to_json(v));
822                    }
823                    JValue::Object(m)
824                })
825                .collect(),
826        ),
827    }
828}
829
830/// TOML `Value` → JSON。
831fn value_to_json(v: &toml_edit::Value) -> JValue {
832    if let Some(s) = v.as_str() {
833        return JValue::String(s.to_string());
834    }
835    if let Some(i) = v.as_integer() {
836        return JValue::from(i);
837    }
838    if let Some(f) = v.as_float() {
839        return serde_json::Number::from_f64(f)
840            .map(JValue::Number)
841            .unwrap_or(JValue::Null);
842    }
843    if let Some(b) = v.as_bool() {
844        return JValue::Bool(b);
845    }
846    if let Some(d) = v.as_datetime() {
847        return JValue::String(d.to_string());
848    }
849    if let Some(a) = v.as_array() {
850        return JValue::Array(a.iter().map(value_to_json).collect());
851    }
852    if let Some(t) = v.as_inline_table() {
853        let mut m = JMap::new();
854        for (k, val) in t.iter() {
855            m.insert(k.to_string(), value_to_json(val));
856        }
857        return JValue::Object(m);
858    }
859    JValue::Null
860}
861
862/// 表 → JSON(先按 `order` 输出已知键,再补未知键)。
863fn table_to_json(table: &Table, order: &[&str]) -> JValue {
864    let mut m = JMap::new();
865    for k in order {
866        if let Some(v) = table.get(k) {
867            m.insert((*k).to_string(), item_to_json(v));
868        }
869    }
870    for (k, v) in table.iter() {
871        if !m.contains_key(k) {
872            m.insert(k.to_string(), item_to_json(v));
873        }
874    }
875    JValue::Object(m)
876}
877
878// ─────────────────────────── 提取辅助 ───────────────────────────
879
880/// 提取上下文:累积字段级问题。
881struct Ctx {
882    rel: String,
883    issues: Vec<Issue>,
884}
885
886impl Ctx {
887    fn set_rel(&mut self, rel: &str) {
888        self.rel = rel.to_string();
889    }
890
891    fn err(&mut self, code: &'static str, message: impl Into<String>) {
892        self.issues
893            .push(Issue::error(code, self.rel.clone(), message));
894    }
895
896    fn check_unknown(&mut self, t: &Table, allowed: &[&str]) {
897        for (k, _) in t.iter() {
898            if !allowed.contains(&k) {
899                self.err(
900                    code::SCHEMA_FIELD,
901                    format!("未知字段 `{k}`(扩展请放入 `[ext]`)"),
902                );
903            }
904        }
905    }
906
907    fn req_str(&mut self, t: &Table, key: &str) -> Option<String> {
908        match t.get(key) {
909            None => {
910                self.err(code::SCHEMA_FIELD, format!("缺少必填字段 `{key}`"));
911                None
912            }
913            Some(item) => match item.as_str() {
914                Some(s) => Some(s.to_string()),
915                None => {
916                    self.err(code::SCHEMA_FIELD, format!("`{key}` 必须是字符串"));
917                    None
918                }
919            },
920        }
921    }
922
923    fn opt_str(&mut self, t: &Table, key: &str) -> Option<String> {
924        match t.get(key) {
925            None => None,
926            Some(item) => match item.as_str() {
927                Some(s) => Some(s.to_string()),
928                None => {
929                    self.err(code::SCHEMA_FIELD, format!("`{key}` 必须是字符串"));
930                    None
931                }
932            },
933        }
934    }
935
936    fn opt_int(&mut self, t: &Table, key: &str) -> Option<i64> {
937        match t.get(key) {
938            None => None,
939            Some(item) => match item.as_integer() {
940                Some(i) => Some(i),
941                None => {
942                    self.err(code::SCHEMA_FIELD, format!("`{key}` 必须是整数"));
943                    None
944                }
945            },
946        }
947    }
948
949    fn opt_bool(&mut self, t: &Table, key: &str) -> Option<bool> {
950        match t.get(key) {
951            None => None,
952            Some(item) => match item.as_bool() {
953                Some(b) => Some(b),
954                None => {
955                    self.err(code::SCHEMA_FIELD, format!("`{key}` 必须是布尔值"));
956                    None
957                }
958            },
959        }
960    }
961
962    /// 读取 TOML 原生 offset date-time;写成字符串或缺少时区偏移均报 `E_PARSE`。
963    fn opt_dt(&mut self, t: &Table, key: &str) -> Option<String> {
964        let Some(item) = t.get(key) else {
965            return None;
966        };
967        if item.as_str().is_some() {
968            self.err(
969                code::PARSE,
970                format!("`{key}` 必须使用 TOML 原生 offset date-time,不得写成字符串"),
971            );
972            return None;
973        }
974        match item.as_datetime() {
975            Some(d) => {
976                if d.date.is_none() || d.time.is_none() || d.offset.is_none() {
977                    self.err(
978                        code::PARSE,
979                        format!("`{key}` 必须是带时区偏移的 offset date-time(如 2026-09-14T10:03:11+08:00)"),
980                    );
981                    return None;
982                }
983                Some(d.to_string())
984            }
985            None => {
986                self.err(
987                    code::PARSE,
988                    format!("`{key}` 必须是 offset date-time"),
989                );
990                None
991            }
992        }
993    }
994
995    fn opt_str_array(&mut self, t: &Table, key: &str) -> Option<Vec<String>> {
996        let Some(item) = t.get(key) else {
997            return None;
998        };
999        let Some(arr) = item.as_array() else {
1000            self.err(code::SCHEMA_FIELD, format!("`{key}` 必须是字符串数组"));
1001            return None;
1002        };
1003        let mut out = Vec::new();
1004        for v in arr.iter() {
1005            match v.as_str() {
1006                Some(s) => out.push(s.to_string()),
1007                None => {
1008                    self.err(code::SCHEMA_FIELD, format!("`{key}` 的元素必须是字符串"));
1009                }
1010            }
1011        }
1012        Some(out)
1013    }
1014}