Skip to content

Collapse whitespace

collapseWhitespace is a built‑in normalization rule that collapses repeated internal whitespace into a single space.

This produces cleaner, more consistent text without altering semantic meaning. If the value is not a string, or the collapsed form is identical to the original, no normalization step is emitted.

Signature

export const collapseWhitespace: NormalizationRule<unknown>
(value: unknown, mode: NormalizationMode, path: FieldPath) => NormalizationStep[]

Events

Event code Description
string.now.collapsed Internal whitespace was collapsed to one space.

Design rationale

  • Normalizes only internal whitespace; leading and trailing whitespace is handled by other rules.
  • Produces a consistent text structure for downstream validators, scanners, and policy layers.
  • Eliminates accidental spacing introduced by user input, copy‑paste operations, or UI frameworks.
  • Emits a normalization step only when the collapsed string differs from the original.
  • Classified as lossy normalization — the original spacing is discarded, though meaning is preserved.
  • Ensures predictable formatting for text fields without altering user intent.

Invoke

collapseWhitespace runs automatically when:

  • The value is structurally a string.
  • The normalization stage is active.
  • The current mode allows lossy normalization.

Mode behavior:

  • strict: Rule does not run (lossy).
  • moderate: Rule does not run (lossy).
  • lax: Rule runs.

Normalization cannot be invoked manually. It is always applied automatically based on structural type and mode.

Examples

Repeated whitespace collapsed

const value = "Hello    world   from   Jane";

const result = collapseWhitespace(value, "lax", "$");
// → [
//     {
//       path: "$",
//       nextValue: "Hello world from Jane",
//       lossy: "lossy",
//       events: [
//         JaneEvent{ kind: "info", code: "string.now.collapsed", ... }
//       ]
//     }
//   ]

No repeated whitespace — no normalization

const result = collapseWhitespace("Hello world", "lax", "$");
// → []

Non‑string value

const result = collapseWhitespace(42, "lax", "$");
// → []