Cotton code
738 lines · 29.7 KB · RustRaw
//! The chunker — a row's text, cut into the pieces that each earn one vector.//! The port of `packages/core/src/engine/chunk.ts`.//!//! Pure and deterministic, and the determinism is not tidiness. The indexer's//! staleness test is "does every chunk this row currently produces already have//! a vector at this model with a matching `content_sha`" — so if the same text//! ever produced different chunks, the indexer would re-embed the whole//! database on every pass, spending the owner's provider key to arrive back//! where it started.//!//! # Everything here counts UTF-16 CODE UNITS//!//! `String.prototype.length` and `.slice` count UTF-16 code units, and this//! module is nothing but lengths and slices: the maximum, the floor, the//! overlap, `safeBoundary`'s step-back, `lastWhitespaceBefore`'s scan. Ported//! in bytes or in `char`s, every boundary would land somewhere else on any text//! outside ASCII — a different cut, a different `content_sha`, and the whole//! database re-embedded. So the cutting functions work over//! `str::encode_utf16` and rebuild with `String::from_utf16_lossy`.//!//! **Where a lone surrogate could differ.** JavaScript strings admit unpaired//! surrogates; Rust's `String` cannot hold one, so the two implementations can//! only diverge where JavaScript would PRODUCE one://!//! - **Input.** A JavaScript caller can pass text containing a lone surrogate//!   (a truncated import, a bad decode); a Rust caller cannot, because the//!   value never got to be a `&str`. Its replacement happened at the row//!   boundary, upstream of here.//! - **Output.** [`safe_boundary`] exists precisely so no cut lands inside a//!   surrogate pair, and it has ONE escape: its loop stops at index 1, so text//!   whose very first code unit is a high surrogate could be cut at 1. That is//!   unreachable through this module (a cut of 1 needs a maximum of 1), and if//!   it were reached JavaScript would emit the lone high surrogate where//!   `from_utf16_lossy` writes U+FFFD. Both sides would be one unit long.//!//! The Node vectors in `chunk_tests.rs` check every chunk of an astral-plane//! wall, a ZWJ-sequence wall and a combining-mark wall for lone surrogates on//! the TypeScript side: there are none.//!//! `EmbedSource`, `EMBED_SOURCES` and `embed_chunk_sha` are declared HERE//! rather than in the store, for the reason `quantize.rs` declares//! `EMBED_DIMS`: this crate is where the embedding rules are decided, the store//! carries no port of the embeddings schema, and `chunk_tests.rs` pins the list//! and the hash against this declaration.use std::sync::LazyLock;use regex::Regex;use sha2::{Digest, Sha256};use cotton_store::protocol::js::is_js_whitespace;/// The target size of a chunk, in UTF-16 code units (the spec's "~1200/// chars").////// Approximate on purpose, and in both directions: a chunk is cut at a/// paragraph boundary rather than at exactly this count, and the overlap below/// pushes each chunk after the first past it. What the number is really for is/// keeping one chunk to one topic — a vector over three unrelated paragraphs is/// a vector about nothing in particular.pub const EMBED_CHUNK_MAX_CHARS: usize = 1200;/// How much of the previous chunk's tail each chunk after the first repeats.////// Without it a sentence that straddles a boundary is in neither chunk's/// meaning: the half that names the subject sits in one vector, the half that/// says what happened to it in the next, and a query about the whole thought/// matches neither well. Ten percent is enough to carry a sentence across and/// small enough that the duplicated text does not dominate the vector it rides/// in.pub const EMBED_CHUNK_OVERLAP_CHARS: usize = 120;/// The short-text floor: text this short earns no vector at all.////// The same argument D1 makes for leaving todos and events out, applied within/// a source: a vector over "ok" or "👍" sits close to everything vaguely/// adjacent, so a chat archive full of acknowledgements would return/// acknowledgements for every query. FTS already answers a two-word message/// exactly. A trailing fragment under the floor is merged back into the chunk/// before it rather than dropped — it is the tail of real prose, not an/// acknowledgement.pub const EMBED_CHUNK_MIN_CHARS: usize = 12;// ─────────────────────────────────────────────────────────────────────────────// The store's declaration, mirrored (see the module header).// ─────────────────────────────────────────────────────────────────────────────/// How one row's text becomes chunks.////// - `Whole` — the row IS one chunk. A message, a memory entry and a person's///   summary are each a single thought; cutting one in half would put half a///   sentence next to a query. (The chunker still cuts a `Whole` row that runs///   past the maximum — a provider call has a token limit and an imported///   archive really does hold a message somebody pasted a document into.)/// - `Split` — prose that runs long, cut at paragraph boundaries.#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]pub enum EmbedChunking {    Whole,    Split,}impl EmbedChunking {    pub const fn as_str(self) -> &'static str {        match self {            EmbedChunking::Whole => "whole",            EmbedChunking::Split => "split",        }    }}/// One `_embeddings.source` and where its text comes from.////// The table and the text columns are READ OFF THE DEFINITION/// ([`definition_text`]) wherever a built-in definition describes the source,/// and hand-listed ([`EmbedText::Hand`]) only where none can yet, each with/// its reason (lane T11, 22 Oct 2026: the chunker stops keeping a registry of/// table names).#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub struct EmbedSource {    /// The `_embeddings.source` value, and the lane's partition key.    pub source: &'static str,    /// The domain table its text is read from.    pub table: &'static str,    /// The PRIMITIVE KIND that owns this source.    pub kind: &'static str,    /// The columns joined, in order, into the text that gets chunked.    pub columns: &'static [&'static str],    pub chunking: EmbedChunking,}/// Where one declared source's table and columns come from.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum EmbedText {    /// The built-in table definition whose id is the source's kind    /// ([`definition_text`]).    Definition,    /// A table no shipped definition describes yet.    Hand {        table: &'static str,        columns: &'static [&'static str],    },}/// One source as declared: which kinds earn a vector and how they are cut is/// the D1 decision (the primitives registry's `embedded`); where the words/// are is the definition's.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub struct EmbedDeclaration {    pub source: &'static str,    pub kind: &'static str,    pub text: EmbedText,    pub chunking: EmbedChunking,}/// The eight sources, and the single declaration of what gets a vector (D1).////// Every kind NOT here carries a written refusal in the primitives registry —/// the registry's house rule that a "no" is never a missing entry.pub const EMBED_DECLARATIONS: [EmbedDeclaration; 8] = [    EmbedDeclaration {        source: "note",        kind: "note",        text: EmbedText::Definition,        chunking: EmbedChunking::Split,    },    EmbedDeclaration {        source: "message",        kind: "message",        text: EmbedText::Definition,        chunking: EmbedChunking::Whole,    },    EmbedDeclaration {        source: "email",        kind: "email",        text: EmbedText::Definition,        chunking: EmbedChunking::Split,    },    // The vectors sit on the PAGES; the `document` kind owns them, the way    // `fts_document_pages` sits under `fts: true` on `document`. Hand: the    // pages are a supporting table the document definition draws as one    // engine-answered `pages_text`, so no definition column names `text`.    EmbedDeclaration {        source: "document_page",        kind: "document",        text: EmbedText::Hand {            table: "cotton_document_pages",            columns: &["text"],        },        chunking: EmbedChunking::Split,    },    // Hand: no built-in definition ships for meetings yet.    EmbedDeclaration {        source: "meeting",        kind: "meeting",        text: EmbedText::Hand {            table: "cotton_meetings",            columns: &["summary_md"],        },        chunking: EmbedChunking::Split,    },    // One entry, one chunk, by construction: a memory is one sentence of at    // most 280 characters. Hand: no built-in definition ships for memory yet.    EmbedDeclaration {        source: "memory",        kind: "memory",        text: EmbedText::Hand {            table: "cotton_memories",            columns: &["title", "body"],        },        chunking: EmbedChunking::Whole,    },    EmbedDeclaration {        source: "person",        kind: "person",        text: EmbedText::Definition,        chunking: EmbedChunking::Whole,    },    // A thought (v29). `Whole`: a capture is one thought by construction.    // Hand: no built-in definition ships for thoughts yet.    EmbedDeclaration {        source: "thought",        kind: "thought",        text: EmbedText::Hand {            table: "cotton_inbox_items",            columns: &["raw_text"],        },        chunking: EmbedChunking::Whole,    },];/// The resolved sources, in [`EMBED_DECLARATIONS`] order: a slice once the/// definitions are read (`EMBED_SOURCES.iter()`, `&EMBED_SOURCES`).pub struct EmbedSources(LazyLock<Vec<EmbedSource>>);impl std::ops::Deref for EmbedSources {    type Target = [EmbedSource];    fn deref(&self) -> &[EmbedSource] {        &self.0    }}impl<'a> IntoIterator for &'a EmbedSources {    type Item = &'a EmbedSource;    type IntoIter = std::slice::Iter<'a, EmbedSource>;    fn into_iter(self) -> Self::IntoIter {        self.0.iter()    }}/// Every source with its table and columns resolved. A built-in definition/// that cannot describe its declared source is a build defect, and/// `chunk_tests.rs` names it; here it is a panic, never a source that quietly/// indexes nothing.pub static EMBED_SOURCES: EmbedSources = EmbedSources(LazyLock::new(|| {    EMBED_DECLARATIONS        .iter()        .map(|declared| {            let (table, columns) = match declared.text {                EmbedText::Hand { table, columns } => (table, columns),                EmbedText::Definition => {                    let definition = crate::definitions::builtin_table_definition(declared.kind)                        .unwrap_or_else(|| panic!("embed source {}: no built-in definition {}", declared.source, declared.kind));                    let (table, columns) = definition_text(definition, declared.chunking)                        .unwrap_or_else(|fault| panic!("embed source {}: {fault:?}", declared.source));                    // Once per process: the resolved names live as long as                    // the definitions they were read from.                    let columns: Vec<&'static str> = columns                        .into_iter()                        .map(|column| &*Box::leak(column.into_boxed_str()))                        .collect();                    (&*Box::leak(table.into_boxed_str()), &*Box::leak(columns.into_boxed_slice()))                }            };            EmbedSource {                source: declared.source,                table,                kind: declared.kind,                columns,                chunking: declared.chunking,            }        })        .collect()}));/// The table and text columns a definition's records are embedded from.////// The table is the definition's own: the one of its physical tables that/// holds its prose (supporting tables hold none). The text is the PROSE a person already finds by typing:/// the long-text columns the table's full-text index carries, in the/// definition's order — never a column the engine answers on read, never a/// stored JSON list a long-text face happens to draw (a message's reactions)./// A `Split` source is a document with a heading, so its title column leads;/// a `Whole` source is one thought, and its title is a label, not the thought.////// Works for an imported data-only table as for a built-in one: an import's/// full-text index is its definition's `search` list./// Why a definition gives no prose to cut — a fault in the shipped/// definitions, read only by the developer the panic stops, so a typed fact/// and never words.#[derive(Debug, Clone, PartialEq, Eq)]pub enum TextFault {    Storage { id: String, error: String },    NoLongText { id: String },}pub fn definition_text(    definition: &crate::definitions::TableDefinition,    chunking: EmbedChunking,) -> Result<(String, Vec<String>), TextFault> {    use crate::definitions::ColumnType;    let tables = definition        .physical_tables()        .map_err(|error| TextFault::Storage { id: definition.id.clone(), error: error.to_string() })?;    // The record's own table is the one holding its prose; a package's    // supporting tables (a note's attachments, a chat's settings) hold none.    for table in &tables {        let stored = |key: &str| table.columns.iter().any(|column| column.name == key);        let searched = full_text_columns(table);        let mut columns: Vec<String> = Vec::new();        for column in &definition.columns {            if column.column_type == ColumnType::Longtext                && stored(&column.key)                && searched.iter().any(|name| *name == column.key)                && !columns.contains(&column.key)            {                columns.push(column.key.clone());            }        }        if columns.is_empty() {            continue;        }        if chunking == EmbedChunking::Split {            let titled = definition                .columns                .iter()                .any(|column| column.key == definition.title && column.column_type == ColumnType::Text);            if titled && stored(&definition.title) {                columns.insert(0, definition.title.clone());            }        }        return Ok((table.name.clone(), columns));    }    Err(TextFault::NoLongText { id: definition.id.clone() })}/// The columns a table's full-text indexes carry: a declared index's list,/// or the column arguments of a built-in's `fts5(...)` statement (its/// `key = value` options left out).fn full_text_columns(table: &cotton_store::schema::package_tables::PackageTable) -> Vec<String> {    use cotton_store::schema::package_tables::PackageFullText;    let mut out = Vec::new();    for index in &table.full_text {        match index {            PackageFullText::Declared { columns, .. } => out.extend(columns.iter().cloned()),            PackageFullText::Legacy(sql) => {                let Some(open) = sql.find("fts5(") else { continue };                let Some(close) = sql.rfind(')') else { continue };                out.extend(                    sql[open + 5..close]                        .split(',')                        .map(str::trim)                        .filter(|argument| !argument.is_empty() && !argument.contains('='))                        .map(|argument| argument.trim_matches(|c| c == '"' || c == '`').to_string()),                );            }        }    }    out}/// One source by name, or `None` — the lane and the indexer both look up.pub fn embed_source(source: &str) -> Option<&'static EmbedSource> {    EMBED_SOURCES        .iter()        .find(|candidate| candidate.source == source)}/// `_embeddings.content_sha` — sha256 of the chunk text, first 32 hex.////// The indexer's staleness test is "does this row already have a vector, at/// this model, whose `content_sha` matches every chunk the row currently/// produces" (D16). That makes the hash a contract between the chunker and the/// index: if the same text ever produced a different hash, the indexer would/// re-embed the whole database on every pass.////// The TypeScript hashes `new TextEncoder().encode(text)`, which is UTF-8 —/// the same bytes a Rust `&str` already is, so no re-encoding step can drift.pub fn embed_chunk_sha(text: &str) -> String {    let digest = Sha256::digest(text.as_bytes());    hex::encode(digest)[..32].to_string()}// ─────────────────────────────────────────────────────────────────────────────// The chunker.// ─────────────────────────────────────────────────────────────────────────────/// One chunk of one row: what gets embedded, and the hash that identifies it.#[derive(Debug, Clone, PartialEq, Eq)]pub struct EmbedChunk {    /// 0-based within the row — `_embeddings.chunk_ix`.    pub ix: usize,    /// The text as it is sent to the provider, overlap included.    pub text: String,    /// `_embeddings.content_sha` for [`EmbedChunk::text`].    pub sha: String,}/// Why a row's text could not be read.#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]pub enum ChunkError {    /// The TypeScript's sentence verbatim, `typeof` included — every column in    /// `EMBED_SOURCES` is a `text` column, so a number arriving here means the    /// declaration names the wrong column, and a silent skip would show up only    /// as a source that mysteriously indexes nothing.    ///    /// The field is `source_name` rather than `source` because `thiserror`    /// reserves a field of that name for the error's CAUSE — this one is the    /// `_embeddings.source` value, which has no cause.    #[error("embed source {source_name}: column {column} is {found}, not text")]    NotText {        source_name: &'static str,        column: &'static str,        /// JavaScript's `typeof`: `number`, `boolean`, `object`.        found: &'static str,    },}/// The text one source reads off one row: its declared columns, in declared/// order, joined as paragraphs. An empty or absent column is skipped, so a note/// with no title reads as its body rather than as a leading blank line.////// A column holding something that is not text is REFUSED rather than coerced/// or skipped (see [`ChunkError::NotText`]). The row arrives as a JSON object/// because that is the shape both writers already hold a row in; `Value::Null`/// and an absent key read the same, which is the TypeScript's `null ||/// undefined`.pub fn embed_row_text(    source: &EmbedSource,    row: &serde_json::Map<String, serde_json::Value>,) -> Result<String, ChunkError> {    let mut parts: Vec<&str> = Vec::new();    for column in source.columns {        let value = match row.get(*column) {            None | Some(serde_json::Value::Null) => continue,            Some(value) => value,        };        let serde_json::Value::String(text) = value else {            return Err(ChunkError::NotText {                source_name: source.source,                column,                found: js_typeof(value),            });        };        let trimmed = js_trim(text);        if !trimmed.is_empty() {            parts.push(trimmed);        }    }    Ok(parts.join("\n\n"))}/// `typeof value` for the shapes JSON admits. An array is `"object"` in/// JavaScript, which is why the two map to the same string here.fn js_typeof(value: &serde_json::Value) -> &'static str {    match value {        serde_json::Value::Null => "object",        serde_json::Value::Bool(_) => "boolean",        serde_json::Value::Number(_) => "number",        serde_json::Value::String(_) => "string",        serde_json::Value::Array(_) | serde_json::Value::Object(_) => "object",    }}/// [`embed_row_text`] then [`embed_chunks`], for one row of one source.pub fn embed_row_chunks(    source: &EmbedSource,    row: &serde_json::Map<String, serde_json::Value>,) -> Result<Vec<EmbedChunk>, ChunkError> {    Ok(embed_chunks(&embed_row_text(source, row)?, source.chunking))}/// Cut text into the chunks that each earn one vector.////// `Whole` keeps the row as one chunk — a message, a memory entry and a/// person's summary are each a single thought. It is still bounded: a provider/// call has a token limit, and an imported archive really does hold a message/// somebody pasted a document into, so a `Whole` row that runs past the maximum/// is cut by the same splitter. "One message, one chunk" is a rule about not/// chopping up prose for the sake of it, not a promise to send unbounded text.pub fn embed_chunks(text: &str, chunking: EmbedChunking) -> Vec<EmbedChunk> {    let normalized = normalize_for_chunking(text);    if utf16_len(&normalized) < EMBED_CHUNK_MIN_CHARS {        return Vec::new();    }    if chunking == EmbedChunking::Whole && utf16_len(&normalized) <= EMBED_CHUNK_MAX_CHARS {        return vec![chunk(0, normalized)];    }    let bodies = merge_runt(pack(&pieces(&normalized)));    bodies        .iter()        .enumerate()        .map(|(ix, body)| {            let carried = if ix == 0 {                String::new()            } else {                overlap_tail(&bodies[ix - 1])            };            chunk(                ix,                if carried.is_empty() {                    body.clone()                } else {                    format!("{carried}\n\n{body}")                },            )        })        .collect()}fn chunk(ix: usize, text: String) -> EmbedChunk {    let sha = embed_chunk_sha(&text);    EmbedChunk { ix, text, sha }}/// The normalisation every chunk boundary is computed against.////// Line endings differ between an imported archive, a paste and the app's own/// editor, and trailing spaces survive most editors — none of which is a/// difference in meaning, but every one of which would change a `content_sha`/// and re-embed the row.fn normalize_for_chunking(text: &str) -> String {    static CR: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\r\n?").expect("a valid pattern"));    static TRAILING: LazyLock<Regex> =        LazyLock::new(|| Regex::new(r"(?m)[ \t]+$").expect("a valid pattern"));    static BLANKS: LazyLock<Regex> =        LazyLock::new(|| Regex::new(r"\n{3,}").expect("a valid pattern"));    let text = CR.replace_all(text, "\n");    let text = TRAILING.replace_all(&text, "");    let text = BLANKS.replace_all(&text, "\n\n");    js_trim(&text).to_string()}/// Paragraphs, with any paragraph longer than the maximum cut down to size.fn pieces(text: &str) -> Vec<String> {    static PARAGRAPH: LazyLock<Regex> =        LazyLock::new(|| Regex::new(r"\n{2,}").expect("a valid pattern"));    let mut out = Vec::new();    for paragraph in PARAGRAPH.split(text) {        let paragraph = js_trim(paragraph);        if paragraph.is_empty() {            continue;        }        if utf16_len(paragraph) <= EMBED_CHUNK_MAX_CHARS {            out.push(paragraph.to_string());        } else {            out.extend(hard_split(paragraph, EMBED_CHUNK_MAX_CHARS));        }    }    out.retain(|piece| !piece.is_empty());    out}/// Greedy packing: paragraphs go together until the next one would not fit.fn pack(parts: &[String]) -> Vec<String> {    let mut chunks: Vec<String> = Vec::new();    let mut current = String::new();    for part in parts {        if current.is_empty() {            current = part.clone();        } else if utf16_len(&current) + 2 + utf16_len(part) <= EMBED_CHUNK_MAX_CHARS {            current = format!("{current}\n\n{part}");        } else {            chunks.push(std::mem::take(&mut current));            current = part.clone();        }    }    if !current.is_empty() {        chunks.push(current);    }    chunks}/// A final fragment under the floor joins the chunk before it (see the floor).fn merge_runt(chunks: Vec<String>) -> Vec<String> {    if chunks.len() < 2 {        return chunks;    }    let mut out = chunks;    if utf16_len(out.last().expect("at least two")) < EMBED_CHUNK_MIN_CHARS {        let last = out.pop().expect("at least two");        let previous = out.pop().expect("at least two");        out.push(format!("{previous}\n\n{last}"));    }    out}/// One paragraph that is longer than a whole chunk, cut at whitespace.////// The fallback when there is no whitespace to cut at — a base64 blob, a wall/// of CJK text — cuts at the count, stepping back off a surrogate pair or a/// combining mark so the cut never lands inside a single character.fn hard_split(text: &str, max: usize) -> Vec<String> {    let mut out: Vec<String> = Vec::new();    let mut rest: Vec<u16> = text.encode_utf16().collect();    while rest.len() > max {        let whitespace = last_whitespace_before(&rest, max);        let cut = if whitespace > 0 {            whitespace        } else {            safe_boundary(&rest, max)        };        let piece = js_trim_end(&from_utf16(&rest[..cut])).to_string();        if !piece.is_empty() {            out.push(piece);        }        rest = js_trim_start(&from_utf16(&rest[cut..]))            .encode_utf16()            .collect();    }    let tail = from_utf16(&rest);    if !tail.is_empty() {        out.push(tail);    }    out}fn last_whitespace_before(units: &[u16], limit: usize) -> usize {    let mut i = limit.min(units.len());    while i > 0 {        if is_whitespace_unit(units[i - 1]) {            return i;        }        i -= 1;    }    0}/// Step back until the index is not inside a surrogate pair or a grapheme.////// The TypeScript's loop stops at 1 rather than 0; that is ported unchanged, so/// the two agree even on the degenerate input where it matters (see the module/// header on lone surrogates).fn safe_boundary(units: &[u16], at: usize) -> usize {    static GRAPHEME: LazyLock<Regex> =        LazyLock::new(|| Regex::new(r"^[\p{M}\u{200d}\u{fe0f}]$").expect("a valid pattern"));    let mut i = at.min(units.len());    while i > 1 {        let before = units[i - 1];        let splits_pair = (0xd800..=0xdbff).contains(&before);        // A combining mark, a zero-width joiner or a variation selector:        // cutting here would strand half of one visible character in each        // chunk.        let splits_grapheme = code_point_at(units, i)            .and_then(char::from_u32)            .is_some_and(|here| GRAPHEME.is_match(here.encode_utf8(&mut [0u8; 4])));        if !splits_pair && !splits_grapheme {            return i;        }        i -= 1;    }    i}/// `String.prototype.codePointAt(i)` over code units — `None` past the end.////// A lone surrogate answers ITSELF in JavaScript; here it answers a value/// `char::from_u32` refuses, which the one caller reads as "not a combining/// mark". The two agree: `\p{M}` never matches a lone surrogate either.fn code_point_at(units: &[u16], i: usize) -> Option<u32> {    let first = *units.get(i)? as u32;    if (0xd800..=0xdbff).contains(&first) {        if let Some(&low) = units.get(i + 1) {            if (0xdc00..=0xdfff).contains(&low) {                return Some(0x10000 + ((first - 0xd800) << 10) + (u32::from(low) - 0xdc00));            }        }    }    Some(first)}/// The tail one chunk lends the next: the last [`EMBED_CHUNK_OVERLAP_CHARS`]/// code units, snapped forward to a whitespace boundary so the overlap never/// opens mid-word.fn overlap_tail(body: &str) -> String {    if utf16_len(body) <= EMBED_CHUNK_OVERLAP_CHARS {        return js_trim(body).to_string();    }    let units: Vec<u16> = body.encode_utf16().collect();    let tail = from_utf16(&units[safe_boundary(&units, units.len() - EMBED_CHUNK_OVERLAP_CHARS)..]);    let tail_units: Vec<u16> = tail.encode_utf16().collect();    // Snapping forward past the first whitespace can leave nothing when the    // tail is one long token: carry the whole tail rather than no overlap at    // all.    if let Some(space) = tail_units.iter().position(|unit| is_whitespace_unit(*unit)) {        let snapped = js_trim(&from_utf16(&tail_units[space + 1..])).to_string();        if !snapped.is_empty() {            return snapped;        }    }    js_trim(&tail).to_string()}// ─────────────────────────────────────────────────────────────────────────────// UTF-16 and JavaScript whitespace.// ─────────────────────────────────────────────────────────────────────────────fn utf16_len(text: &str) -> usize {    text.encode_utf16().count()}fn from_utf16(units: &[u16]) -> String {    String::from_utf16_lossy(units)}/// `/\s/.test(unit)` — the ECMAScript whitespace class, every member of which/// is in the BMP, so one code unit is one candidate character.fn is_whitespace_unit(unit: u16) -> bool {    char::from_u32(u32::from(unit)).is_some_and(is_js_whitespace)}/// `String.prototype.trim` — the ECMAScript class, not Rust's, which differ on/// U+FEFF (JavaScript trims it, Rust does not) and U+0085 (the other way).fn js_trim(text: &str) -> &str {    js_trim_start(js_trim_end(text))}fn js_trim_start(text: &str) -> &str {    text.trim_start_matches(is_js_whitespace)}fn js_trim_end(text: &str) -> &str {    text.trim_end_matches(is_js_whitespace)}#[cfg(test)]#[path = "chunk_tests.rs"]mod tests;