import { isDeepStrictEqual } from 'node:util'; import { normaliseBody } from '#lib/body.ts'; import { countWords } from '#lib/words.ts'; import { bodyToText } from './markdown.ts'; export type PreparedBody = ReturnType; export interface DocumentContent { body: unknown; bodyText: string; } export interface PreparedDocument extends DocumentContent { body: PreparedBody; wordCount: number; } export const EMPTY_SCENE_BODY: PreparedBody = { type: 'doc', content: [{ type: 'paragraph' }] }; export const EMPTY_PREPARED_DOCUMENT: PreparedDocument = { body: EMPTY_SCENE_BODY, bodyText: '', wordCount: 0 }; /** Checks whether a client payload provides a top-level ProseMirror doc envelope. */ export function isDocEnvelope(raw: unknown): raw is { type: 'doc'; content?: unknown[] } { if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) return false; const candidate = raw as { type?: unknown; content?: unknown }; if (candidate.type !== 'doc') return false; return candidate.content === undefined || Array.isArray(candidate.content); } /** * Normalises a document once onto the editor schema and derives `bodyText` and * `wordCount` solely from that normalised document so stored fields cannot drift. */ export function prepareDocumentBody(raw: unknown): PreparedDocument { const body = normaliseBody(raw); const bodyText = bodyToText(body); return { body, bodyText, wordCount: countWords(bodyText) }; } /** * Compares both the flattened text and the lossless ProseMirror tree so * formatting-only edits are never treated as unchanged. */ export function sameDocument(left: DocumentContent, right: DocumentContent): boolean { return left.bodyText === right.bodyText && isDeepStrictEqual(left.body, right.body); }