Skip to main content

nb_api/
types.rs

1//! Public wire types for body-aware reads, edits, and commit outcomes.
2//!
3//! 0.4.0 is text-first: every structured textual field is a JSON `String`.
4//! The crate is base64-free; callers needing JSON transport base64 do it at
5//! the wire layer. Non-UTF-8-but-text files surface as typed
6//! [`crate::error::NbError::NonUtf8`]; the single raw-bytes escape hatch is
7//! `NbClient::read_note_source_bytes`.
8
9use serde::{Deserialize, Serialize};
10
11use crate::error::NbError;
12use crate::fingerprint::Fingerprint;
13use crate::parser::{DocumentKind, TodoState};
14
15/// Address an existing note by selector or notebook-relative path.
16#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
17#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
18#[serde(tag = "type", rename_all = "lowercase")]
19pub enum NoteTarget {
20    Selector { value: String },
21    Path { value: String },
22}
23
24impl NoteTarget {
25    pub fn selector(value: impl Into<String>) -> Self {
26        Self::Selector {
27            value: value.into(),
28        }
29    }
30
31    pub fn path(value: impl Into<String>) -> Self {
32        Self::Path {
33            value: value.into(),
34        }
35    }
36
37    pub fn value(&self) -> &str {
38        match self {
39            Self::Selector { value } | Self::Path { value } => value,
40        }
41    }
42}
43
44/// Entity kind for typed list and classify surfaces.
45///
46/// Struct payload, never a bare string: internally-tagged enums
47/// cannot carry primitive newtype payloads. `Other` carries a short
48/// diagnostic (`non-textual:<ext>`) for genuinely unclassifiable
49/// leftovers; kind never encodes indexing state (unindexed notes
50/// keep their `DocumentKind`, `.gitkeep`-only dirs keep `Folder`).
51/// Deliberately `non_exhaustive` for source evolution, a separate
52/// decision from the runtime `Other` value.
53#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
54#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
55#[serde(tag = "type", rename_all = "lowercase")]
56#[non_exhaustive]
57pub enum EntityKind {
58    Note,
59    Todo,
60    Bookmark,
61    Folder,
62    Other { reason: String },
63}
64
65/// One typed list entry: shadow-aware canonical selector built at
66/// the source (numeric form only when it re-resolves to the same
67/// entity, else exact-path form).
68#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
69#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
70pub struct ListEntry {
71    pub selector: String,
72    pub path: String,
73    pub kind: EntityKind,
74    /// Numeric `.index` id when resolvable via `.index` scan.
75    #[serde(default, skip_serializing_if = "Option::is_none")]
76    pub numeric_id: Option<u32>,
77}
78
79/// Classify record: kind, path, and shadow-aware selector for one
80/// id, without reading content beyond classification.
81#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
82#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
83pub struct Classify {
84    pub kind: EntityKind,
85    pub path: String,
86    pub selector: String,
87    /// Numeric `.index` id when resolvable via `.index` scan.
88    #[serde(default, skip_serializing_if = "Option::is_none")]
89    pub numeric_id: Option<u32>,
90}
91
92/// Todo summary with explicit open/closed state and shadow-aware
93/// canonical `id`. Minimal six fields, nothing more.
94#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
95#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
96pub struct TodoSummary {
97    pub id: String,
98    pub title: String,
99    pub path: String,
100    pub task_count: u32,
101    pub completed_count: u32,
102    pub state: TodoState,
103}
104
105/// Accepted-kinds set for an operation, used by
106/// [`NbError::WrongKind`]. `File` is any non-folder entity,
107/// `Document` the text kinds (`Note | Todo | Bookmark`), `Todo`
108/// only todos, `Folder` only folders.
109#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
110#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
111#[serde(rename_all = "lowercase")]
112pub enum KindSet {
113    File,
114    Document,
115    Todo,
116    Folder,
117}
118
119/// One body fragment exposed by structured show.
120///
121/// `bytes` is the fragment text (UTF-8); `start_byte`/`end_byte` are offsets
122/// into `ShowNote.source`, so `body == concat(fragment.bytes)` and each
123/// `source[start_byte..end_byte] == fragment.bytes`.
124#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
125#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
126pub struct BodyFragment {
127    pub index: u32,
128    pub bytes: String,
129    pub start_byte: u32,
130    pub end_byte: u32,
131}
132
133/// Structured `show_note` result.
134#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
135#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
136pub struct ShowNote {
137    pub selector: String,
138    pub path: String,
139    pub kind: DocumentKind,
140    pub todo_state: Option<TodoState>,
141    /// Full raw title line including trailing newline, as UTF-8.
142    pub title: Option<String>,
143    pub title_text: Option<String>,
144    pub tags: Vec<String>,
145    pub body_fragments: Vec<BodyFragment>,
146    /// Derivable (`body_fragments.len() <= 1`); kept for wire convenience.
147    pub body_contiguous: bool,
148    /// Concatenated body-fragment bytes (excludes title H1 + tags).
149    pub body: String,
150    pub fingerprint: Fingerprint,
151    /// Full file bytes verbatim, as UTF-8.
152    pub source: String,
153    /// Numeric `.index` id when resolvable via `.index` scan.
154    #[serde(default, skip_serializing_if = "Option::is_none")]
155    pub numeric_id: Option<u32>,
156}
157
158/// Versioned body-line authenticity token: `b3l1:<32 lowercase hex>`.
159#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
160#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
161#[serde(transparent)]
162pub struct LineAnchor(String);
163
164impl LineAnchor {
165    pub const PREFIX: &'static str = "b3l1:";
166
167    pub fn as_str(&self) -> &str {
168        &self.0
169    }
170
171    pub fn from_line_bytes(line_with_terminator_or_eof_marker: &[u8]) -> Self {
172        let hash = blake3::hash(line_with_terminator_or_eof_marker);
173        let hex = hash.to_hex();
174        Self(format!("{}{}", Self::PREFIX, &hex[..32]))
175    }
176
177    pub fn parse(s: &str) -> Result<Self, NbError> {
178        if !s.starts_with(Self::PREFIX) {
179            return Err(NbError::ValidationError {
180                reason: format!("unknown line anchor prefix in {s:?}"),
181                location: None,
182            });
183        }
184        let hex = &s[Self::PREFIX.len()..];
185        if hex.len() != 32
186            || !hex
187                .chars()
188                .all(|c| c.is_ascii_hexdigit() && !c.is_ascii_uppercase())
189        {
190            return Err(NbError::ValidationError {
191                reason: format!("invalid line anchor hex in {s:?}"),
192                location: None,
193            });
194        }
195        Ok(Self(s.to_string()))
196    }
197}
198
199impl std::fmt::Display for LineAnchor {
200    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
201        f.write_str(&self.0)
202    }
203}
204
205/// Document-level end-of-line marker.
206///
207/// `Lf` for `\n`, `CrLf` for `\r\n`. Bare `\r` is not a supported EOL and is
208/// preserved verbatim in line text; documents without a supported EOL report
209/// `eol: None` on [`ShowNoteLines`].
210#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
211#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
212#[serde(rename_all = "lowercase")]
213pub enum LineEol {
214    Lf,
215    CrLf,
216}
217
218impl LineEol {
219    pub fn as_bytes(self) -> &'static [u8] {
220        match self {
221            Self::Lf => b"\n",
222            Self::CrLf => b"\r\n",
223        }
224    }
225}
226
227/// One enumerated body line (line text without terminator).
228///
229/// Unknown JSON fields (including the removed 0.3.x `terminator`) are ignored
230/// on deserialization for forward compatibility.
231#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
232#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
233pub struct NoteLine {
234    pub number: u32,
235    pub anchor: LineAnchor,
236    pub text: String,
237}
238
239/// Windowed body-line listing with a document-level EOL declaration.
240#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
241#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
242pub struct ShowNoteLines {
243    pub selector: String,
244    pub path: String,
245    pub kind: DocumentKind,
246    pub total_lines: u32,
247    pub offset: u32,
248    pub limit: u32,
249    pub next_offset: Option<u32>,
250    pub lines: Vec<NoteLine>,
251    pub title: Option<String>,
252    pub tags: Vec<String>,
253    pub body_fingerprint: Fingerprint,
254    /// First-supported-EOL declaration; `None` for empty / single-line-no-EOL
255    /// / CR-only bodies.
256    pub eol: Option<LineEol>,
257    /// Whether the body ends with `eol` bytes.
258    pub has_final_eol: bool,
259    /// Numeric `.index` id when resolvable via `.index` scan.
260    #[serde(default, skip_serializing_if = "Option::is_none")]
261    pub numeric_id: Option<u32>,
262}
263
264/// Number + anchor reference to a body line.
265#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
266#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
267pub struct LineRef {
268    pub number: u32,
269    pub anchor: LineAnchor,
270}
271
272/// Insert position relative to a line or body boundary.
273#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
274#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
275#[serde(tag = "type", rename_all = "lowercase")]
276pub enum LinePosition {
277    Before { line: LineRef },
278    After { line: LineRef },
279    Boundary { at: BoundaryAt },
280}
281
282/// Virtual body boundaries (`^` / `$`).
283#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
284#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
285#[serde(rename_all = "lowercase")]
286pub enum BoundaryAt {
287    Caret,
288    Dollar,
289}
290
291/// One line-oriented edit in an `edit_note_lines` batch.
292///
293/// `content` is bare text (no terminator included; embedded `\r` preserved).
294/// The library appends document `eol` bytes when materializing edits.
295#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
296#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
297#[serde(tag = "type", rename_all = "lowercase")]
298pub enum LineEdit {
299    Insert {
300        at: LinePosition,
301        content: String,
302    },
303    Delete {
304        start: LineRef,
305        end: LineRef,
306    },
307    Replace {
308        start: LineRef,
309        end: LineRef,
310        content: String,
311    },
312}
313
314/// Substring occurrence selector.
315#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
316#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
317#[serde(tag = "type", rename_all = "lowercase")]
318pub enum Occurrence {
319    First,
320    All,
321    Nth { n: u32 },
322}
323
324/// One search hit within a body line.
325#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
326#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
327pub struct NoteLineHit {
328    pub number: u32,
329    pub anchor: LineAnchor,
330    pub start_byte: u32,
331    pub end_byte: u32,
332    #[serde(skip_serializing_if = "Option::is_none")]
333    pub text: Option<String>,
334}
335
336/// Result of `search_note_lines`.
337#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
338#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
339pub struct SearchNoteLines {
340    pub selector: String,
341    pub path: String,
342    pub kind: DocumentKind,
343    pub hits: Vec<NoteLineHit>,
344    pub body_fingerprint: Fingerprint,
345}
346
347/// Outcome of one plan op after a successful commit.
348#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
349#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
350pub struct OpOutcome {
351    pub index: u32,
352    pub path: Option<String>,
353    pub selector: Option<String>,
354    /// Numeric `.index` id when known (pinned `Option<u32>` type).
355    #[serde(default, skip_serializing_if = "Option::is_none")]
356    pub numeric_id: Option<u32>,
357    pub noop: bool,
358    #[serde(skip_serializing_if = "Option::is_none")]
359    pub fingerprint: Option<Fingerprint>,
360}
361
362/// Structured result of [`crate::Transaction::commit`].
363#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
364#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
365pub struct CommitOutcome {
366    pub commit_created: bool,
367    pub revision_id: Option<String>,
368    pub pre_revision: String,
369    pub ops: Vec<OpOutcome>,
370}