import type { ContentSlice as ContentSliceValue, Descendant, DescendantIn, Element, Value, } from '../interfaces'; import { ElementApi } from '../interfaces'; import { getDefined } from '../internal/get-defined'; import { PreparedTokenSlice } from './change/tokens'; import { isImmutable } from './clone'; import { getEditorJsonArrayItems, getEditorJsonRecordEntries, snapshotEditorJsonValue, } from './value-codec'; import { countCoreWork } from './work'; export type ContentSlice = ContentSliceValue; type PreparedSlice = Readonly<{ detached: boolean; variants: Map; }>; const trustedSlices = new WeakMap(); const canonicalContentAuthorities = new WeakMap(); const encodedSlices = new WeakMap(); const encodedContent = new WeakMap(); const assertOpenDepth = ( content: readonly Descendant[], depth: number, edge: 'end' | 'start' ) => { let children = content; for (let level = 0; level < depth; level++) { const node = edge === 'start' ? children[0] : children.at(-1); if (!ElementApi.isElement(node)) { throw new Error( `Content slice open ${edge} exceeds its element context.` ); } ({ children } = node); } }; const invalidJson = (): never => { throw new Error('Content slice must encode to JSON-compatible data.'); }; const assertOpenDepths = (openStart: unknown, openEnd: unknown) => { if ( !Number.isSafeInteger(openStart) || !Number.isSafeInteger(openEnd) || Object.is(openStart, -0) || Object.is(openEnd, -0) || (openStart as number) < 0 || (openEnd as number) < 0 ) { throw new Error('Content slice open depths must be non-negative integers.'); } }; const variantKey = (openStart: number, openEnd: number) => `${openStart}:${openEnd}`; const snapshotSliceContent = ( content: unknown, path?: readonly number[], seen?: WeakSet ): readonly Descendant[] => { const nodePath = path ?? []; const nodeSeen = seen ?? new WeakSet(); if (!Array.isArray(content)) { throw new Error('Content slice content must be an array.'); } const items = getEditorJsonArrayItems(content) ?? invalidJson(); const result = items.map((node, index): Descendant => { const nextPath = [...nodePath, index]; countCoreWork('pathComponents', nextPath.length); if (typeof node !== 'object' || node === null || Array.isArray(node)) { throw new Error( `Content slice node at [${nextPath}] must be a text or element object.` ); } if (nodeSeen.has(node)) { throw new Error( `Content slice node at [${nextPath}] cannot be repeated or cyclic.` ); } nodeSeen.add(node); const entries = getEditorJsonRecordEntries(node) ?? invalidJson(); const hasChildren = entries.some(([key]) => key === 'children'); const hasText = entries.some(([key]) => key === 'text'); if (hasChildren === hasText) { throw new Error( `Content slice node at [${nextPath}] must have exactly one structural field.` ); } const props = Object.fromEntries( entries .filter(([key]) => key !== 'children' && key !== 'text') .map(([key, item]) => [ key, snapshotEditorJsonValue(item, 'Content slice'), ]) ); if (hasText) { const text = getDefined(entries.find(([key]) => key === 'text'))[1]; if (typeof text !== 'string') { throw new Error( `Content slice text at [${nextPath}] must be a string.` ); } return Object.freeze({ ...props, text }); } const children = getDefined(entries.find(([key]) => key === 'children'))[1]; return Object.freeze({ ...props, children: snapshotSliceContent(children, nextPath, nodeSeen), }) as Descendant; }); return Object.freeze(result); }; const snapshotContentSlice = ( value: unknown ): ContentSliceValue => { if (typeof value !== 'object' || value === null || Array.isArray(value)) { throw new Error('Content slice must be an object.'); } const entries = getEditorJsonRecordEntries(value) ?? invalidJson(); const keys = entries.map(([key]) => key).sort(); if ( (keys.length !== 3 && keys.length !== 4) || keys[0] !== 'content' || keys[1] !== 'openEnd' || keys[2] !== 'openStart' || (keys.length === 4 && keys[3] !== 'roots') ) { throw new Error( 'Content slice must contain only content, openEnd, openStart, and optional roots.' ); } const fields = new Map(entries); const openStart = fields.get('openStart'); const openEnd = fields.get('openEnd'); const seen = new WeakSet(); assertOpenDepths(openStart, openEnd); const rootsValue = fields.get('roots'); let roots: Readonly> | undefined; if (rootsValue !== undefined) { const rootEntries = getEditorJsonRecordEntries(rootsValue) ?? invalidJson(); roots = Object.freeze( Object.fromEntries( rootEntries.map(([root, content]) => { if (root.length === 0 || root === 'main') { throw new Error( 'Content slice roots must use non-empty named root keys.' ); } return [root, snapshotSliceContent(content, undefined, seen)]; }) ) ); } const result = Object.freeze({ content: snapshotSliceContent(fields.get('content'), undefined, seen), openEnd: openEnd as number, openStart: openStart as number, ...(roots && Object.keys(roots).length > 0 ? { roots } : {}), }) as ContentSliceValue; assertOpenDepth(result.content, result.openStart, 'start'); assertOpenDepth(result.content, result.openEnd, 'end'); return result; }; const prepare = ( result: ContentSliceValue, detached: boolean ): ContentSliceValue => { const variants = new Map(); variants.set(variantKey(result.openStart, result.openEnd), result); trustedSlices.set( result, Object.freeze({ detached, variants, }) ); return result; }; const snapshot = (value: unknown): ContentSliceValue => prepare(snapshotContentSlice(value), true); const fromJSON = ( value: unknown ): ContentSliceValue => { if (typeof value === 'object' && value !== null && trustedSlices.has(value)) { return value as ContentSliceValue; } return snapshot(value); }; type SliceValueFromContent = [ Extract, ] extends [never] ? Value : ReadonlyArray>; function closed( content: TContent ): ContentSliceValue>; function closed( content: ReadonlyArray> ): ContentSliceValue; function closed(content: readonly Descendant[]): ContentSliceValue { return snapshot({ content, openEnd: 0, openStart: 0, }); } const empty = closed([]); /** * Trust freshly owned, deeply immutable, shape-validated nodes. * * @internal */ export const createDetachedContentSlice = ( content: ReadonlyArray>, openStart: number, openEnd: number, options: Readonly<{ /** Authority attesting that content is owned, deeply immutable, and canonical. */ canonicalFor?: object; /** Detached secondary roots referenced by the slice content. */ roots?: Readonly>>>; }> = {} ): ContentSliceValue => { assertOpenDepths(openStart, openEnd); const seen = new WeakSet(); const assertDeeplyFrozen = (value: unknown): void => { if (typeof value !== 'object' || value === null || seen.has(value)) return; if (!isImmutable(value)) { throw new Error('Prepared content slice nodes must be deeply frozen.'); } seen.add(value); for (const key in value) { if (Object.hasOwn(value, key)) { assertDeeplyFrozen((value as Readonly>)[key]); } } }; if (options.canonicalFor) { if ( !isImmutable(content) || (options.roots && (!Object.isFrozen(options.roots) || Object.values(options.roots).some( (children) => !isImmutable(children) ))) ) { throw new Error( 'Canonical content slice nodes and roots must be frozen.' ); } } else { assertDeeplyFrozen(content); assertDeeplyFrozen(options.roots); } const result = Object.freeze({ content, openEnd, openStart, ...(options.roots && Object.keys(options.roots).length > 0 ? { roots: options.roots } : {}), }) as ContentSliceValue; assertOpenDepth(result.content, result.openStart, 'start'); assertOpenDepth(result.content, result.openEnd, 'end'); if (options.canonicalFor) { canonicalContentAuthorities.set(content, options.canonicalFor); } return prepare(result, true); }; /** * Read the schema authority that constructed canonical slice nodes. * * @internal */ export const getContentSliceCanonicalAuthority = (slice: ContentSliceValue) => canonicalContentAuthorities.get(fromJSON(slice).content); /** * Trust frozen nodes read directly from an immutable editor snapshot. * * @internal */ export const createContentSliceFromFragment = ( content: readonly Descendant[], openStart: number, openEnd: number, roots?: Readonly> ): ContentSliceValue => { assertOpenDepths(openStart, openEnd); if ( !content.every((node) => Object.isFrozen(node)) || (roots && Object.values(roots).some((children) => children.some((node) => !Object.isFrozen(node)) )) ) { return snapshot({ content, openEnd, openStart, ...(roots ? { roots } : {}), }); } const frozenContent = Object.freeze([...content]); const frozenRoots = roots && Object.keys(roots).length > 0 ? Object.freeze( Object.fromEntries( Object.entries(roots).map(([root, children]) => [ root, Object.freeze([...children]), ]) ) ) : undefined; assertOpenDepth(frozenContent, openStart, 'start'); assertOpenDepth(frozenContent, openEnd, 'end'); return prepare( Object.freeze({ content: frozenContent, openEnd, openStart, ...(frozenRoots ? { roots: frozenRoots } : {}), }) as ContentSliceValue, false ); }; /** Immutable open document content carried across host and insertion boundaries. */ export const ContentSlice = Object.freeze({ closed, empty, fromJSON, withContent: ( slice: ContentSliceValue, content: ReadonlyArray>, options: Readonly<{ open: 'closed' | 'preserve' }> ): ContentSliceValue => { if (options.open !== 'closed' && options.open !== 'preserve') { throw new Error('Content slice openness must be closed or preserved.'); } const source = fromJSON(slice); const openEnd = options.open === 'closed' ? 0 : source.openEnd; const openStart = options.open === 'closed' ? 0 : source.openStart; if ( content === source.content && openEnd === source.openEnd && openStart === source.openStart ) { return source; } const result = Object.freeze({ content: snapshotSliceContent(content), openEnd, openStart, ...(source.roots ? { roots: source.roots } : {}), }) as ContentSliceValue; assertOpenDepth(result.content, result.openStart, 'start'); assertOpenDepth(result.content, result.openEnd, 'end'); return prepare(result, true); }, }); /** * Whether a trusted slice owns detached content identities. * * @internal */ export const isDetachedContentSlice = (slice: ContentSliceValue) => getDefined(trustedSlices.get(fromJSON(slice))).detached; /** * Encode the complete trusted content behind a slice. * * @internal */ export const encodeContentSliceContent = (slice: ContentSliceValue) => { const value = fromJSON(slice); const prepared = getDefined(trustedSlices.get(value)); let fullEncoded = encodedContent.get(value.content); if (!fullEncoded) { fullEncoded = prepared.detached ? PreparedTokenSlice.fromPreparedNodes(value.content) : PreparedTokenSlice.fromJSON( PreparedTokenSlice.fromNodes(value.content).toJSON() ); encodedContent.set(value.content, fullEncoded); } return fullEncoded; }; /** * Encode a trusted JSON slice while retaining its open edges. * * @internal */ export const encodeContentSlice = (slice: ContentSliceValue) => { const value = fromJSON(slice); let encoded = encodedSlices.get(value); if (encoded) return encoded; const fullEncoded = encodeContentSliceContent(value); encoded = fullEncoded.slice( value.openStart, fullEncoded.length - value.openEnd ); encodedSlices.set(value, encoded); return encoded; }; /** * Reuse one trusted content snapshot with different valid openness. * * @internal */ export const prepareContentSliceVariant = ( slice: ContentSliceValue, openStart: number, openEnd: number ): ContentSliceValue => { assertOpenDepths(openStart, openEnd); const source = fromJSON(slice); const prepared = getDefined(trustedSlices.get(source)); const key = variantKey(openStart, openEnd); const cached = prepared.variants.get(key); if (cached) return cached as ContentSliceValue; assertOpenDepth(source.content, openStart, 'start'); assertOpenDepth(source.content, openEnd, 'end'); const result = Object.freeze({ content: source.content, openEnd, openStart, ...(source.roots ? { roots: source.roots } : {}), }) as ContentSliceValue; trustedSlices.set( result, Object.freeze({ detached: prepared.detached, variants: prepared.variants, }) ); prepared.variants.set(key, result); return result; };