import type { Descendant, EditorJsonValue, Element, Text, Value, } from 'platejs'; import type { EditorSchemaContract, EditorSchemaContractContentProgram, EditorSchemaContractElement, } from 'platejs/compiler'; type ContractProperty = EditorSchemaContract['properties']['byId'][number]; type ContractDescriptor = ContractProperty['descriptor']; /** Context passed to a custom property value generator in `createEditorArbitrary`. */ export type EditorArbitraryPropertyContext = Readonly<{ /** Element type owning this property, or the enclosing parent element type for text marks. */ elementType: string; /** Property key or prefix being generated. */ key: string; /** Property placement in the schema contract. */ placement: 'element' | 'text'; /** Uniform `[0, 1)` random number source for deterministic generation. */ random: () => number; /** Whether the schema contract marks this property as required. */ required: boolean; }>; /** Options controlling synthetic document generation in `createEditorArbitrary`. */ export type EditorArbitraryOptions = Readonly<{ /** Maximum children generated for unconstrained containers. Defaults to `4`. */ maxChildren?: number; /** Maximum element nesting depth before falling back to shallow valid leaves. Defaults to `3`. */ maxDepth?: number; /** * Optional generators keyed by exact property key or prefix string. * Use this to supply valid values for properties with custom runtime validators. */ propertyValues?: Readonly< Record EditorJsonValue> >; }>; /** Deterministic schema-derived Plate document generator. */ export type EditorArbitrary = Readonly<{ /** Generate one deterministic schema-valid document for an integer seed. */ generate: (seed: number) => Value; /** Generate one schema-valid document using a caller-supplied `[0, 1)` PRNG. */ next: (random: () => number) => Value; }>; const SAMPLE_WORDS = [ 'alpha', 'beta', 'gamma', 'delta', 'draft', 'editor', 'schema', 'block', ] as const; const createSeededRandom = (seed: number): (() => number) => { let state = seed >>> 0; return () => { state = (state + 0x6d_2b_79_f5) >>> 0; let mixed = Math.imul(state ^ (state >>> 15), 1 | state); mixed ^= mixed + Math.imul(mixed ^ (mixed >>> 7), 61 | mixed); return ((mixed ^ (mixed >>> 14)) >>> 0) / 4_294_967_296; }; }; const pickIndex = (random: () => number, length: number): number => Math.min(length - 1, Math.floor(random() * length)); const pickFrom = (random: () => number, items: readonly T[]): T => items[pickIndex(random, items.length)]; const pickInt = (random: () => number, min: number, max: number): number => { if (max <= min) return min; return min + Math.floor(random() * (max - min + 1)); }; const propertyKeyName = (property: ContractProperty): string => typeof property.key === 'string' ? property.key : property.key.prefix; const resolvePropertyWriteKey = ( property: ContractProperty, nextSuffix: () => number ): string => typeof property.key === 'string' ? property.key : `${property.key.prefix}k${nextSuffix()}`; const isDeepEqual = (left: unknown, right: unknown): boolean => JSON.stringify(left) === JSON.stringify(right); const generateDescriptorValue = ( descriptor: ContractDescriptor, random: () => number, uniqueCounter: (() => number) | null, keyLabel: string ): EditorJsonValue => { if (descriptor.default !== undefined && uniqueCounter === null) { if (descriptor.kind === 'enum' && descriptor.values?.length) { return pickFrom(random, descriptor.values); } return structuredClone(descriptor.default) as EditorJsonValue; } switch (descriptor.kind) { case 'boolean': { return true; } case 'enum': { return descriptor.values && descriptor.values.length > 0 ? pickFrom(random, descriptor.values) : ''; } case 'number': { return uniqueCounter ? uniqueCounter() : pickInt(random, 1, 3); } case 'string': { if (uniqueCounter) { return `${keyLabel}-${uniqueCounter()}`; } return pickFrom(random, SAMPLE_WORDS); } case 'set': { const itemDescriptor = descriptor.item; if (!itemDescriptor) return []; const first = generateDescriptorValue( itemDescriptor, random, null, keyLabel ); return [first]; } case 'json': { return uniqueCounter ? { id: uniqueCounter() } : { value: pickFrom(random, SAMPLE_WORDS) }; } default: { return ''; } } }; type GenerationState = { maxChildren: number; maxDepth: number; nextSuffix: () => number; nextUnique: (propertyId: string) => number; propertyValues: NonNullable; random: () => number; }; /** * Create a deterministic, zero-dependency document generator derived from a * compiled `EditorSchemaContract`. Compose with `fast-check` using * `fc.integer().map(arbitrary.generate)`. */ export const createEditorArbitrary = ( contract: EditorSchemaContract, options: EditorArbitraryOptions = {} ): EditorArbitrary => { const maxDepth = Math.max(1, Math.trunc(options.maxDepth ?? 3)); const maxChildren = Math.max(1, Math.trunc(options.maxChildren ?? 4)); const propertyValues = options.propertyValues ?? {}; const elementsByType = new Map( contract.elements.byType.map((element) => [element.type, element]) ); const propertiesById = new Map( contract.properties.byId.map((property) => [property.id, property]) ); const textPropsByParent = new Map( contract.properties.textAllowedByParentType.map(([parentType, ids]) => [ parentType, ids .map((id) => propertiesById.get(id)) .filter( (property): property is ContractProperty => property !== undefined ), ]) ); const leafScore = new Map(); for (const element of contract.elements.byType) { if (element.behavior.void || element.content?.allowsText) { leafScore.set(element.type, 1); } } for (const _pass of contract.elements.byType) { let changed = false; for (const element of contract.elements.byType) { if (leafScore.has(element.type) || !element.content) continue; const candidateTypes = element.content.defaultPlan?.kind === 'element' ? [ element.content.defaultPlan.type, ...element.content.allowedElementTypes, ] : element.content.allowedElementTypes; let best = Number.POSITIVE_INFINITY; for (const childType of candidateTypes) { const childScore = leafScore.get(childType); if (childScore !== undefined && childScore + 1 < best) { best = childScore + 1; } } if (Number.isFinite(best)) { leafScore.set(element.type, best); changed = true; } } if (!changed) break; } const pickElementType = ( allowedTypes: readonly string[], defaultType: string | undefined, preferShallow: boolean, random: () => number ): string | null => { const known = allowedTypes.filter((type) => elementsByType.has(type)); if (known.length === 0) { return defaultType && elementsByType.has(defaultType) ? defaultType : null; } if (preferShallow) { const sorted = [...known].sort( (left, right) => (leafScore.get(left) ?? Number.POSITIVE_INFINITY) - (leafScore.get(right) ?? Number.POSITIVE_INFINITY) ); const bestScore = (sorted[0] !== undefined ? leafScore.get(sorted[0]) : undefined) ?? Number.POSITIVE_INFINITY; const shallowest = sorted.filter( (type) => (leafScore.get(type) ?? Number.POSITIVE_INFINITY) === bestScore ); if (defaultType && shallowest.includes(defaultType)) { return defaultType; } return pickFrom(random, shallowest); } return pickFrom(random, known); }; const applyProperties = ( target: Record, properties: readonly ContractProperty[], materializedIds: ReadonlySet, elementType: string, placement: 'element' | 'text', allowContentMarks: boolean, state: GenerationState ) => { const usedExclusiveGroups = new Set(); const orderedProperties = [...properties].sort((left, right) => { const leftMandatory = left.descriptor.required || materializedIds.has(left.id) ? 0 : 1; const rightMandatory = right.descriptor.required || materializedIds.has(right.id) ? 0 : 1; return leftMandatory - rightMandatory; }); for (const property of orderedProperties) { if ( placement === 'text' && !allowContentMarks && property.role === 'content' ) { continue; } if ( property.exclusiveGroupIds.some((groupId) => usedExclusiveGroups.has(groupId) ) ) { continue; } const keyLabel = propertyKeyName(property); const hasOverride = Object.hasOwn(state.propertyValues, keyLabel); const isMandatory = property.descriptor.required || materializedIds.has(property.id); if (keyLabel in target) { for (const groupId of property.exclusiveGroupIds) { usedExclusiveGroups.add(groupId); } continue; } // Skip un-overridden custom-validated optional properties and generated // optional metadata so contract-only generation does not guess validator rules. if (!isMandatory) { if ( !hasOverride && (property.descriptor.validationVersion !== undefined || property.descriptor.generated === true || property.role === 'metadata') ) { continue; } if (state.random() > 0.35) continue; } const writeKey = resolvePropertyWriteKey(property, state.nextSuffix); const uniqueCounter = property.lifecycle.unique || property.descriptor.generated ? () => state.nextUnique(property.id) : null; let value: EditorJsonValue; const override = state.propertyValues[keyLabel]; if (override) { value = override({ elementType, key: keyLabel, placement, random: state.random, required: isMandatory, }); } else if ( elementType === 'heading' && keyLabel === 'level' && property.descriptor.default === undefined ) { value = pickInt(state.random, 1, 6); } else { value = generateDescriptorValue( property.descriptor, state.random, uniqueCounter, keyLabel ); } if ( !isMandatory && property.descriptor.omitDefault && property.descriptor.default !== undefined && isDeepEqual(value, property.descriptor.default) ) { continue; } target[writeKey] = value; for (const groupId of property.exclusiveGroupIds) { usedExclusiveGroups.add(groupId); } } }; const generateTextLeaf = ( parentElement: EditorSchemaContractElement | null, text: string, allowMarks: boolean, state: GenerationState ): Text => { const leaf: Record = { text }; if (allowMarks && text.length > 0 && parentElement) { const allowedProps = textPropsByParent.get(parentElement.type) ?? []; applyProperties( leaf, allowedProps, new Set(), parentElement.type, 'text', parentElement.behavior.contentMarks !== false, state ); } return leaf as Text; }; const generateTextChildren = ( parentElement: EditorSchemaContractElement | null, program: EditorSchemaContractContentProgram, depth: number, state: GenerationState ): Descendant[] => { const inlineTypes = program.allowedElementTypes.filter((type) => { const child = elementsByType.get(type); return child !== undefined && child.behavior.inline; }); const maxCount = program.max !== null ? Math.min(program.max, state.maxChildren) : state.maxChildren; const minCount = Math.max(1, program.min); const preferShallow = depth >= state.maxDepth; if ( !preferShallow && inlineTypes.length > 0 && maxCount >= 3 && state.random() < 0.3 ) { const inlineType = pickFrom(state.random, inlineTypes); const inlineElement = generateElement( inlineType, depth + 1, state, undefined, undefined ); if (inlineElement) { return [ generateTextLeaf( parentElement, pickFrom(state.random, SAMPLE_WORDS), true, state ), inlineElement, generateTextLeaf( parentElement, pickFrom(state.random, SAMPLE_WORDS), false, state ), ]; } } const leafCount = pickInt( state.random, minCount, Math.max(minCount, Math.min(2, maxCount)) ); const leaves: Text[] = []; for (let index = 0; index < leafCount; index += 1) { const word = pickFrom(state.random, SAMPLE_WORDS); const text = index === 0 ? word : ` ${word}`; const leaf = generateTextLeaf(parentElement, text, true, state); if (leaves.length > 0) { const prev = leaves.at(-1)!; const { text: _prevText, ...prevMarks } = prev; const { text: _nextText, ...nextMarks } = leaf; if (isDeepEqual(prevMarks, nextMarks)) { leaves[leaves.length - 1] = { ...prev, text: `${prev.text}${leaf.text}`, }; continue; } } leaves.push(leaf); } return leaves; }; const generateChildrenForProgram = ( parentElement: EditorSchemaContractElement | null, program: EditorSchemaContractContentProgram, depth: number, state: GenerationState, fixedCount: number | undefined, gridColumns: number | undefined ): Descendant[] => { const children: Descendant[] = []; if (program.prefix && program.prefix.length > 0) { for (const slot of program.prefix) { const element = generateElement( slot.type, depth + 1, state, slot.properties, gridColumns ); if (element) children.push(element); } if (program.remainder) { children.push( ...generateChildrenForProgram( parentElement, program.remainder, depth, state, undefined, gridColumns ) ); } return children; } const blockTypes = program.allowedElementTypes.filter((type) => { const child = elementsByType.get(type); return child !== undefined && !child.behavior.inline; }); if (program.allowsText && blockTypes.length === 0) { return generateTextChildren(parentElement, program, depth, state); } const preferShallow = depth >= state.maxDepth; const minCount = Math.max(0, program.min); const upperBound = program.max !== null ? Math.min(program.max, Math.max(minCount, state.maxChildren)) : Math.max(minCount, state.maxChildren); const targetCount = fixedCount !== undefined ? Math.max( minCount, program.max !== null ? Math.min(program.max, fixedCount) : fixedCount ) : preferShallow ? Math.max(1, minCount) : pickInt( state.random, Math.max(1, minCount), Math.max(1, upperBound) ); if (program.allowsText && preferShallow && minCount <= 1) { return generateTextChildren(parentElement, program, depth, state); } const defaultType = program.defaultPlan?.kind === 'element' ? program.defaultPlan.type : undefined; const defaultProps = program.defaultPlan?.kind === 'element' ? program.defaultPlan.properties : undefined; for (let index = 0; index < targetCount; index += 1) { const chosenType = pickElementType( blockTypes.length > 0 ? blockTypes : program.allowedElementTypes, defaultType, preferShallow, state.random ); if (!chosenType) break; const nextGridColumns = parentElement?.structure?.kind === 'grid' && parentElement.structure.role === 'grid' ? gridColumns : undefined; const element = generateElement( chosenType, depth + 1, state, chosenType === defaultType ? defaultProps : undefined, nextGridColumns ); if (element) children.push(element); } if (children.length === 0 && program.allowsText) { return [generateTextLeaf(parentElement, '', false, state)]; } return children; }; const generateElement = ( type: string, depth: number, state: GenerationState, seedProperties: Readonly> | undefined, inheritedGridColumns: number | undefined ): Element | null => { const spec = elementsByType.get(type); if (!spec) return null; const node: Record = { ...(seedProperties ? structuredClone(seedProperties) : {}), type, }; const elementProperties = spec.propertyIds .map((id) => propertiesById.get(id)) .filter( (property): property is ContractProperty => property !== undefined ); const materialized = new Set(spec.construction.materializedPropertyIds); applyProperties( node, elementProperties, materialized, type, 'element', true, state ); if (spec.behavior.void) { node.children = [{ text: '' }]; return node as Element; } if (!spec.content) { node.children = [{ text: '' }]; return node as Element; } let fixedCount: number | undefined; let childGridColumns = inheritedGridColumns; if (spec.structure?.kind === 'grid') { if (spec.structure.role === 'grid') { childGridColumns = pickInt( state.random, 1, Math.min(3, state.maxChildren) ); fixedCount = pickInt(state.random, 1, Math.min(3, state.maxChildren)); } else if (spec.structure.role === 'row' && inheritedGridColumns) { fixedCount = inheritedGridColumns; } } node.children = generateChildrenForProgram( spec, spec.content, depth, state, fixedCount, childGridColumns ); return node as Element; }; const next = (random: () => number): Value => { let suffixCounter = 0; const uniqueCounters = new Map(); const state: GenerationState = { maxChildren, maxDepth, nextSuffix: () => { suffixCounter += 1; return suffixCounter; }, nextUnique: (propertyId: string) => { const nextValue = (uniqueCounters.get(propertyId) ?? 0) + 1; uniqueCounters.set(propertyId, nextValue); return nextValue; }, propertyValues, random, }; const children = generateChildrenForProgram( null, contract.primaryRoot.content, 0, state, undefined, undefined ); return children.filter( (child): child is Element => typeof child === 'object' && child !== null && 'type' in child ); }; return Object.freeze({ generate: (seed: number) => next(createSeededRandom(seed)), next, }); };