import isEqual from 'lodash/isEqual.js'; import { type ContentSlice, ElementApi, getCompiledEditorSchemaFromApi, readNamedRootChildren, reportEditorLifecycleError, TextApi, type Descendant, type EditorCoreStateView, type EditorDocumentValue, type Element as EditorElement, type Path, type RootKey, type Text, } from '../../../facade'; import { failInvariant } from '../../../internal/failInvariant'; import { createContentFormatDocument, createPluginFormatModelView, type createPluginFormatOperationContext, } from '../../../internal/plugin/pluginFormatOperation'; import type { Editor } from '../../editor'; import type { HtmlContentToken, HtmlMappingDiagnosticInput, } from '../../plugin'; import { HTML_ATTRIBUTE_RE, normalizeStyleName } from './htmlMatcher.internal'; import { type CompiledHtmlProperty, type CompiledHtmlRule, type CompiledHtmlSerializerIndex, HTML_CONTENT_TOKEN, HTML_FORMAT, HTML_NODE_FIELDS, HTML_PATCH_FIELDS, HTML_STYLE_NAME_RE, HTML_TAG_RE, HTML_VOID_TAGS, HTML_WRAPPER_FIELDS, type HtmlMappingLoss, type HtmlUnsafeOutput, type HtmlUnsafeReport, type MutableHtmlNode, isRecord, isSafeStyleValue, normalizeAttributeName, ruleClaimKeys, } from './htmlRules.internal'; import { decideHtmlAttribute, HTML_UNSAFE_TAGS, type HtmlUnsafeRemoval, } from './htmlSafety'; export class ReportedHtmlEncodeError extends Error { override name = 'ReportedHtmlEncodeError'; } const encodeWithRule = ( editor: Editor, rule: CompiledHtmlRule, node: EditorElement | Text, parentType: string | null, run: () => T, reportErrors = true ): T => { try { return run(); } catch (error) { if (!reportErrors) throw error; reportEditorLifecycleError( Object.freeze({ cause: new Error( `Plate HTML encode failed for owner "${rule.owner}", node "${TextApi.isText(node) ? (parentType ?? 'text') : node.type}", claims "${ruleClaimKeys(rule).join(', ')}".`, { cause: error } ), editor, pluginName: 'core:html', mimeType: HTML_FORMAT, key: `${rule.owner}:html:encode`, phase: 'encode' as const, source: 'data-transfer-format' as const, }) ); throw new ReportedHtmlEncodeError(); } }; const normalizeHtmlValue = ( value: unknown, label: string ): boolean | number | string | null => { if (value === undefined || value === null || value === false) return null; if ( value !== true && typeof value !== 'string' && typeof value !== 'number' ) { throw new Error(`${label} must be a string, number, boolean, or null.`); } if (typeof value === 'number' && !Number.isFinite(value)) { throw new Error(`${label} number must be finite.`); } return value; }; const setWrite = ( writes: Map, key: string, value: T, label: string ) => { if (writes.has(key) && !isEqual(writes.get(key), value)) { throw new Error(`Plate HTML encode has conflicting ${label} "${key}".`); } writes.set(key, value); }; // Emitted values come from documents and trusted callbacks, so a value that // fails its sink is removed and reported; an unsafe name is a mapping bug. const compileWrites = ( value: Record, label: string, tag: string, onUnsafe: HtmlUnsafeReport ): Pick => { const attributeWrites = new Map(); const styleWrites = new Map(); if (value.attributes !== undefined) { if (!isRecord(value.attributes)) { throw new Error(`${label} attributes must be an object.`); } Object.entries(value.attributes).forEach(([rawName, rawValue]) => { const name = normalizeAttributeName(rawName); if ( !HTML_ATTRIBUTE_RE.test(name) || name.startsWith('on') || name === 'srcdoc' ) { throw new Error(`${label} has unsafe attribute "${rawName}".`); } const normalized = normalizeHtmlValue( rawValue, `${label} attribute "${name}"` ); const decision = typeof normalized === 'string' ? decideHtmlAttribute(tag, name, normalized) : undefined; if (decision && 'removal' in decision) { onUnsafe(decision.removal); return; } setWrite( attributeWrites, name, decision && 'value' in decision ? decision.value : normalized, 'attribute' ); }); } if (value.style !== undefined) { if (!isRecord(value.style)) { throw new Error(`${label} style must be an object.`); } if (attributeWrites.has('style')) { throw new Error(`${label} cannot use two style channels.`); } Object.entries(value.style).forEach(([rawName, rawValue]) => { const name = normalizeStyleName(rawName); if (!HTML_STYLE_NAME_RE.test(name)) { throw new Error(`${label} has unsafe style name "${rawName}".`); } const normalized = normalizeHtmlValue( rawValue, `${label} style "${name}"` ); if (normalized === true) { throw new Error(`${label} style "${name}" cannot be boolean.`); } if (typeof normalized === 'string' && !isSafeStyleValue(normalized)) { onUnsafe( Object.freeze({ action: 'removed' as const, impact: 'lossy' as const, kind: 'style' as const, message: `Removed unsafe CSS value for "${name}" from <${tag}>.`, }) ); return; } setWrite(styleWrites, name, normalized, 'style'); }); } return { attributeWrites, styleWrites }; }; const compileNodeSpec = ( value: unknown, seen: WeakSet, onUnsafe: HtmlUnsafeReport, rootTokens: ReadonlyMap = new Map() ): MutableHtmlNode => { const isContentToken = (child: unknown): child is HtmlContentToken => child === HTML_CONTENT_TOKEN || rootTokens.has(child); if (!isRecord(value)) { throw new Error('Plate HTML node encoder must return an object.'); } if (seen.has(value)) { throw new Error('Plate HTML node spec cannot be cyclic or reused.'); } seen.add(value); Object.keys(value).forEach((field) => { if (!HTML_NODE_FIELDS.has(field)) { throw new Error(`Plate HTML node spec has unknown field "${field}".`); } }); if (typeof value.tag !== 'string') { throw new Error('Plate HTML node spec tag must be a string.'); } const tag = value.tag.toLowerCase(); if (!HTML_TAG_RE.test(tag) || HTML_UNSAFE_TAGS.has(tag)) { throw new Error(`Plate HTML node spec has unsafe tag "${value.tag}".`); } if (value.patchTarget !== undefined && value.patchTarget !== true) { throw new Error('Plate HTML node spec patchTarget must be true.'); } const writes = compileWrites(value, 'Plate HTML node spec', tag, onUnsafe); const inputChildren = value.children === undefined ? HTML_VOID_TAGS.has(tag) ? [] : [HTML_CONTENT_TOKEN] : isContentToken(value.children) ? [value.children] : value.children; if (!Array.isArray(inputChildren)) { throw new Error( 'Plate HTML node spec children must be the content token or an array.' ); } const children = inputChildren.map((child) => { if (isContentToken(child)) return child; if (isRecord(child) && Object.keys(child).length === 1 && 'text' in child) { if (typeof child.text !== 'string') { throw new Error('Plate HTML literal text must be a string.'); } return Object.freeze({ text: child.text }); } return compileNodeSpec(child, seen, onUnsafe, rootTokens); }); return { ...writes, children, patchTarget: value.patchTarget === true, tag, }; }; const findPatchTarget = (root: MutableHtmlNode) => { const targets: MutableHtmlNode[] = []; const visit = (node: MutableHtmlNode) => { if (node.patchTarget) targets.push(node); node.children.forEach((child) => { if (child !== HTML_CONTENT_TOKEN && 'tag' in child) visit(child); }); }; visit(root); if (targets.length > 1) { throw new Error('Plate HTML node spec has duplicate patchTarget markers.'); } return targets[0] ?? root; }; const applyPatch = ( target: MutableHtmlNode, value: unknown, onUnsafe: HtmlUnsafeReport ) => { if (!isRecord(value)) { throw new Error('Plate HTML property encoder must return a patch object.'); } Object.keys(value).forEach((field) => { if (!HTML_PATCH_FIELDS.has(field)) { throw new Error(`Plate HTML patch has unknown field "${field}".`); } }); if (value.tag !== undefined || value.children !== undefined) { throw new Error('Plate HTML patches cannot replace tag or children.'); } const writes = compileWrites(value, 'Plate HTML patch', target.tag, onUnsafe); if ( (target.attributeWrites.has('style') && writes.styleWrites.size > 0) || (target.styleWrites.size > 0 && writes.attributeWrites.has('style')) ) { throw new Error('Plate HTML encode cannot use two style channels.'); } writes.attributeWrites.forEach((entry, key) => { setWrite(target.attributeWrites, key, entry, 'attribute'); }); writes.styleWrites.forEach((entry, key) => { setWrite(target.styleWrites, key, entry, 'style'); }); }; const escapeHtmlText = (value: string) => value .replaceAll('&', '&') .replaceAll('<', '<') .replaceAll('>', '>'); // The parser reads a raw carriage return in an attribute as a line feed. const escapeHtmlAttribute = (value: string) => escapeHtmlText(value).replaceAll('"', '"').replaceAll('\r', ' '); const renderNodeSpec = ( root: MutableHtmlNode, content: string, allowVoidRoot = false, rootContent: ReadonlyMap = new Map() ) => { let contentTokens = 0; const placedRoots = new Set(); const render = (node: MutableHtmlNode): string => { const attributes = [...node.attributeWrites.entries()] .filter(([, value]) => value !== null) .sort(([left], [right]) => left.localeCompare(right)) .map(([name, value]) => value === true ? ` ${name}` : ` ${name}="${escapeHtmlAttribute(String(value))}"` ); const styles = [...node.styleWrites.entries()] .filter(([, value]) => value !== null) .sort(([left], [right]) => left.localeCompare(right)); if (styles.length > 0) { const style = styles .map(([name, value]) => `${name}: ${String(value)}`) .join('; '); attributes.push(` style="${escapeHtmlAttribute(style)}"`); } const open = `<${node.tag}${attributes.join('')}>`; if (HTML_VOID_TAGS.has(node.tag)) { if (node.children.length > 0) { throw new Error( `Plate HTML void element "${node.tag}" cannot have children.` ); } return open; } const children = node.children .map((child) => { if (child === HTML_CONTENT_TOKEN) { contentTokens += 1; return content; } const rooted = rootContent.get(child); if (rooted !== undefined) { if (placedRoots.has(child)) { throw new Error( 'Plate HTML node spec must place each content root token once.' ); } placedRoots.add(child); return rooted; } if ('text' in child) return escapeHtmlText(child.text); if ('tag' in child) return render(child); throw new Error('Plate HTML node spec contains an invalid child.'); }) .join(''); return `${open}${children}`; }; const html = render(root); if (HTML_VOID_TAGS.has(root.tag) && !allowVoidRoot) { throw new Error( `Plate HTML non-void schema element cannot encode as void tag "${root.tag}".` ); } if (!HTML_VOID_TAGS.has(root.tag) && contentTokens !== 1) { throw new Error( 'Plate HTML node spec must consume the content token exactly once.' ); } return html; }; const propertyValue = ( node: EditorElement | Text, property: CompiledHtmlProperty, state: EditorCoreStateView, parentType: string | null ) => { const type = ElementApi.isElement(node) ? node.type : parentType; const compiled = state.schema.property({ key: property.key, placement: property.property.placement, ...(type ? { type } : {}), }); if (!compiled || compiled.id !== property.id) return undefined; const descriptor = compiled.value; const value = node[property.key] === undefined && 'default' in descriptor ? descriptor.default : node[property.key]; if ( compiled.role === 'metadata' || value === undefined || (descriptor.omitDefault && 'default' in descriptor && isEqual(value, descriptor.default)) ) { return undefined; } return value; }; const hasContentValue = ( node: EditorElement | Text, key: string, property: Pick< NonNullable>, 'role' | 'value' > ) => { const descriptor = property.value; const value = node[key] === undefined && 'default' in descriptor ? descriptor.default : node[key]; return ( property.role === 'content' && value !== undefined && !( descriptor.omitDefault && 'default' in descriptor && isEqual(value, descriptor.default) ) ); }; type HtmlEncodeOperation = Readonly<{ document?: EditorDocumentValue; getFormatContext: ReturnType; onLoss?: (loss: HtmlMappingLoss) => void; onUnsafe: (removal: HtmlUnsafeOutput) => void; operationKey: object; readRoots?: Set; reportMappingErrors?: boolean; }>; /** * Report each content property that no encoder of `node` claimed. Claims come * from retained output only, so an owner's encoder existing claims nothing. */ const reportUnclaimedProperties = ( node: EditorElement | Text, parentType: string | null, claimed: ReadonlySet, state: EditorCoreStateView, path: Path, root: RootKey, onLoss?: (loss: HtmlMappingLoss) => void ) => { const placement = ElementApi.isElement(node) ? 'element' : 'text'; const type = ElementApi.isElement(node) ? node.type : parentType; const reported = new Set(); const unsupported = (key: string, id: string) => { if (reported.has(id)) return; reported.add(id); const message = `No HTML mapping represents content property "${key}" on ${ElementApi.isElement(node) ? `"${node.type}"` : 'text'}; it was omitted.`; if (!onLoss) throw new Error(message); onLoss( Object.freeze({ action: 'dropped' as const, kind: 'attribute' as const, message, model: Object.freeze({ path, property: key, root }), owner: 'core:html', }) ); }; for (const key of Object.keys(node)) { if (key === 'children' || key === 'text' || key === 'type') continue; const property = state.schema.property({ key, placement, ...(type ? { type } : {}), }); if ( property && !claimed.has(property.id) && hasContentValue(node, key, property) ) { unsupported(key, property.id); } } const propertyIds = ElementApi.isElement(node) ? (state.schema.element(node.type)?.propertyIds ?? []) : state.schema.getVocabulary().propertyIds; const compiledSchema = getCompiledEditorSchemaFromApi(state.schema); for (const id of propertyIds) { const compiledProperty = compiledSchema?.properties.byId.get(id); const property = compiledProperty ? { id: compiledProperty.id, key: compiledProperty.key, placement: compiledProperty.placement, role: compiledProperty.role, value: compiledProperty.descriptor, } : null; if ( !property || typeof property.key !== 'string' || property.placement !== placement ) { continue; } if (!ElementApi.isElement(node)) { const resolved = state.schema.property({ key: property.key, placement: 'text', ...(parentType ? { type: parentType } : {}), }); if (resolved?.id !== id) continue; } if (!claimed.has(id) && hasContentValue(node, property.key, property)) { unsupported(property.key, id); } } }; const encodeContext = ( rule: CompiledHtmlRule, node: EditorElement | Text, state: EditorCoreStateView, parentType: string | null, document: EditorDocumentValue, path: Path, root: RootKey, getFormatContext: ReturnType, operationKey: object, contentRoot: (slot: string) => HtmlContentToken, onLoss?: (loss: HtmlMappingLoss) => void ) => { const values = new Map(); rule.properties.forEach((property) => { const value = propertyValue(node, property, state, parentType); if (value !== undefined) values.set(property.key, value); }); const record = Object.fromEntries(values); const model = createPluginFormatModelView(document, node, path, root); const report = (diagnostic: HtmlMappingDiagnosticInput) => { if (!onLoss) { throw new Error( `Plate HTML format "${rule.owner}" reported unsupported content without a diagnostic collector.` ); } onLoss( Object.freeze({ ...diagnostic, model: Object.freeze({ path, root }), owner: rule.owner, }) ); }; const operationContext = Object.freeze({ ...getFormatContext(rule.plugin, state, operationKey), ...model, report, }); const preserved = new Set(); const preserve = (...keys: readonly string[]) => { for (const key of keys) { const id = rule.propertyIdsByKey.get(key); if (id === undefined) { throw new Error( `Plate HTML mapping "${rule.owner}" cannot preserve "${key}": it is not a property of its target.` ); } preserved.add(id); } }; const structural = rule.kind === 'element' || rule.createsElement; return { context: structural ? Object.freeze({ ...operationContext, content: HTML_CONTENT_TOKEN, contentRoot, preserve, }) : rule.properties.length === 1 ? Object.freeze({ ...operationContext, value: values.get(rule.properties[0].key), }) : Object.freeze({ ...operationContext, preserve, values: Object.freeze(record), }), hasValues: values.size > 0, // A single-value mapping represents its value whenever it writes output; // every other encoder claims what it represents with `preserve`. retain: (claimed: Set) => { const ids = !structural && rule.properties.length === 1 ? [rule.properties[0].id] : preserved; for (const id of ids) claimed.add(id); }, }; }; const writesHtml = (patch: unknown) => isRecord(patch) && [patch.attributes, patch.style].some( (writes) => isRecord(writes) && Object.values(writes).some( (value) => value !== undefined && value !== null && value !== false ) ); const compileWrapperSpec = ( value: unknown, onUnsafe: HtmlUnsafeReport ): MutableHtmlNode => { if (!isRecord(value)) { throw new Error('Plate HTML mark encoder must return a wrapper object.'); } Object.keys(value).forEach((field) => { if (!HTML_WRAPPER_FIELDS.has(field)) { throw new Error(`Plate HTML wrapper has unknown field "${field}".`); } }); return compileNodeSpec( { ...value, children: HTML_CONTENT_TOKEN }, new WeakSet(), onUnsafe ); }; export const encodeCompiledHtml = ( editor: Editor, slice: ContentSlice, serializerIndex: CompiledHtmlSerializerIndex, state: EditorCoreStateView, operation: HtmlEncodeOperation ) => { const reportMappingErrors = operation.reportMappingErrors ?? true; const document = operation.document ?? createContentFormatDocument(slice); const reportLoss = (path: Path, root: RootKey) => operation.onLoss ? (loss: HtmlMappingLoss) => operation.onLoss?.( loss.model ? loss : Object.freeze({ ...loss, model: Object.freeze({ path, root }), }) ) : undefined; const encodeRoot = (root: RootKey) => (readNamedRootChildren(document.roots, root) ?? []) .map((node, index) => encodeNode(node, null, [index], [index], root)) .join(''); const encodeNode = ( node: Descendant, parentType: string | null, modelPath: Path, sourcePath: Path, root: RootKey ): string => { const path = state.nodes.path(node) ?? sourcePath; const onLoss = reportLoss(path, root); const onUnsafe = (removal: HtmlUnsafeRemoval) => operation.onUnsafe( Object.freeze({ ...removal, model: Object.freeze({ path, root }), }) ); const rootTokens = new Map(); const contentRoot = (slot: string) => { const named = ElementApi.isElement(node) ? state.schema.getElementContentRoots(node)[slot] : undefined; if (named === undefined) { throw new Error( `Plate HTML encode read content root slot "${slot}", which its node does not own.` ); } const token: HtmlContentToken = Object.freeze({ __htmlContentToken: true, }); rootTokens.set(token, named); return token; }; const placedRoots = (spec: MutableHtmlNode): Array<[unknown, RootKey]> => spec.children.flatMap((child) => { const named = rootTokens.get(child); if (named !== undefined) return [[child, named]]; return 'tag' in child ? placedRoots(child) : []; }); const collectTextWrappers = ( textNode: Text, textParentType: string | null, textModelPath: Path, textSourcePath: Path, textContentRoot: (slot: string) => HtmlContentToken ) => { const textPath = state.nodes.path(textNode) ?? textSourcePath; const textOnLoss = reportLoss(textPath, root); const textOnUnsafe = (removal: HtmlUnsafeRemoval) => operation.onUnsafe( Object.freeze({ ...removal, model: Object.freeze({ path: textPath, root }), }) ); const collected: Array< Readonly<{ root: MutableHtmlNode; rule: CompiledHtmlRule; }> > = []; const handled = new Set(); const claimed = new Set(); for (const rule of textParentType ? (serializerIndex.marksByParentType.get(textParentType) ?? []) : []) { const pending = rule.properties.filter( (property) => !handled.has(property.id) && propertyValue(textNode, property, state, textParentType) !== undefined ); if (pending.length === 0) continue; const invocation = encodeContext( rule, textNode, state, textParentType, document, textModelPath, root, operation.getFormatContext, operation.operationKey, textContentRoot, textOnLoss ); const wrapperRoot = encodeWithRule( editor, rule, textNode, textParentType, () => { const value = ( rule.declaration.encode ?? failInvariant('Expected value to be defined') )(invocation.context); return value === null ? null : compileWrapperSpec(value, textOnUnsafe); }, reportMappingErrors ); pending.forEach(({ id }) => { handled.add(id); }); if (wrapperRoot === null) continue; collected.push(Object.freeze({ root: wrapperRoot, rule })); invocation.retain(claimed); } reportUnclaimedProperties( textNode, textParentType, claimed, state, textPath, root, textOnLoss ); return collected; }; if (TextApi.isText(node)) { const wrappers = collectTextWrappers( node, parentType, modelPath, sourcePath, contentRoot ); let html = escapeHtmlText(node.text); for (let index = wrappers.length - 1; index >= 0; index--) { const wrapper = wrappers[index]; html = encodeWithRule( editor, wrapper.rule, node, parentType, () => renderNodeSpec(wrapper.root, html), reportMappingErrors ); } return html; } if (!ElementApi.isElement(node)) return ''; const encodeChildren = () => node.children .map((child, index) => encodeNode( child, node.type, [...modelPath, index], [...path, index], root ) ) .join(''); const structuralRules = serializerIndex.elementsByType.get(node.type) ?? []; let structuralRule: CompiledHtmlRule | undefined; let structural: ReturnType | undefined; for (const rule of structuralRules) { const invocation = encodeContext( rule, node, state, parentType, document, modelPath, root, operation.getFormatContext, operation.operationKey, contentRoot, onLoss ); if (rule.createsElement && !invocation.hasValues) continue; structuralRule = rule; structural = invocation; break; } // A lost element reports once; its properties are lost with it. if (!structuralRule || !structural || !structuralRule.declaration.encode) { const content = encodeChildren(); const message = `Plate HTML encode has no encoder for element "${node.type}".`; if (!onLoss) throw new Error(message); onLoss( Object.freeze({ action: 'unwrapped' as const, kind: 'element' as const, message, owner: 'core:html', }) ); return content; } const structuralContext = structural.context; const encoded = encodeWithRule( editor, structuralRule, node, parentType, () => { const spec = ( structuralRule.declaration.encode ?? failInvariant('Expected value to be defined') )(structuralContext); if (spec === null) return null; const innerRoot = compileNodeSpec( spec, new WeakSet(), onUnsafe, rootTokens ); return Object.freeze({ patchTarget: findPatchTarget(innerRoot), root: innerRoot, }); }, reportMappingErrors ); // An encoder that returns null omits the element and its subtree. if (encoded === null) return ''; const { patchTarget, root: innerSpec } = encoded; const claimed = new Set(); const handledProperties = new Set( structuralRule.properties.map(({ id }) => id) ); structural.retain(claimed); for (const rule of serializerIndex.elementPropertiesByType.get(node.type) ?? []) { const pending = rule.properties.filter( (property) => !handledProperties.has(property.id) && propertyValue(node, property, state, parentType) !== undefined ); if (pending.length === 0) continue; const invocation = encodeContext( rule, node, state, parentType, document, modelPath, root, operation.getFormatContext, operation.operationKey, contentRoot, onLoss ); const patch = encodeWithRule( editor, rule, node, parentType, () => ( rule.declaration.encode ?? failInvariant('Expected value to be defined') )(invocation.context), reportMappingErrors ); if (patch !== null) { applyPatch(patchTarget, patch, onUnsafe); if (writesHtml(patch)) invocation.retain(claimed); } pending.forEach(({ id }) => { handledProperties.add(id); }); } const wrappers: Array< Readonly<{ root: MutableHtmlNode; rule: CompiledHtmlRule; }> > = []; for (const rule of serializerIndex.elementWrappersByType.get(node.type) ?? []) { const invocation = encodeContext( rule, node, state, parentType, document, modelPath, root, operation.getFormatContext, operation.operationKey, contentRoot, onLoss ); if (!invocation.hasValues) continue; const wrapper = encodeWithRule( editor, rule, node, parentType, () => { const spec = ( rule.declaration.encode ?? failInvariant('Expected value to be defined') )(invocation.context); return spec === null ? null : compileNodeSpec(spec, new WeakSet(), onUnsafe); }, reportMappingErrors ); if (wrapper === null) continue; wrappers.push(Object.freeze({ root: wrapper, rule })); invocation.retain(claimed); } reportUnclaimedProperties( node, parentType, claimed, state, path, root, onLoss ); const markableVoidChild = state.schema.isMarkableVoid(node) && node.children.length === 1 && TextApi.isText(node.children[0]) ? node.children[0] : undefined; const markableVoidWrappers = markableVoidChild ? collectTextWrappers( markableVoidChild, node.type, [...modelPath, 0], [...path, 0], contentRoot ) : []; const content = markableVoidChild ? '' : encodeChildren(); const rootContent = new Map( placedRoots(innerSpec).map(([token, named]) => { operation.readRoots?.add(named); return [token, encodeRoot(named)] as const; }) ); let html = encodeWithRule( editor, structuralRule, node, parentType, () => renderNodeSpec( innerSpec, content, state.schema.element(node.type)?.behavior.void === true, rootContent ), reportMappingErrors ); for (let index = wrappers.length - 1; index >= 0; index--) { const wrapper = wrappers[index]; html = encodeWithRule( editor, wrapper.rule, node, parentType, () => renderNodeSpec(wrapper.root, html), reportMappingErrors ); } if (markableVoidChild) { for (let index = markableVoidWrappers.length - 1; index >= 0; index--) { const wrapper = markableVoidWrappers[index]; html = encodeWithRule( editor, wrapper.rule, markableVoidChild, node.type, () => renderNodeSpec(wrapper.root, html), reportMappingErrors ); } } return html; }; return slice.content .map((node, index) => encodeNode(node, null, [index], [index], 'main')) .join(''); };