import type { BehaviorInputFieldSpec } from '../../sdk/behavior-plugin/index.js'; const FIELD_TYPES = new Set([ 'string', 'number', 'boolean', 'enum', 'string_list', 'player_seat', 'player_seats', ]); const BASE_KEYS = new Set(['id', 'type', 'description', 'required', 'default']); const ID_PATTERN = /^[A-Za-z][A-Za-z0-9_.-]{0,79}$/; function own(value: object, key: string): boolean { return Object.prototype.hasOwnProperty.call(value, key); } function deepFreeze(value: T): T { if (!value || typeof value !== 'object' || Object.isFrozen(value)) return value; Object.freeze(value); for (const child of Object.values(value as Record)) deepFreeze(child); return value; } function fieldRecord(value: unknown): Record | undefined { return value && typeof value === 'object' && !Array.isArray(value) ? value as Record : undefined; } function valueDiagnostic( field: Readonly>, value: unknown, prefix: 'default' | 'value', ): string | undefined { const id = String(field.id); const type = field.type; if (type === 'string') { if (typeof value !== 'string') return `behavior_input_${prefix}_type_invalid:${id}`; return value.trim() ? undefined : `behavior_input_${prefix}_empty:${id}`; } if (type === 'player_seat') { if (typeof value !== 'number' || !Number.isInteger(value)) { return `behavior_input_${prefix}_type_invalid:${id}`; } return value >= 1 && value <= 10 ? undefined : `behavior_input_${prefix}_range_invalid:${id}`; } if (type === 'number') { if (typeof value !== 'number' || !Number.isFinite(value)) { return `behavior_input_${prefix}_type_invalid:${id}`; } if ( (typeof field.min === 'number' && value < field.min) || (typeof field.max === 'number' && value > field.max) ) return `behavior_input_${prefix}_range_invalid:${id}`; return undefined; } if (type === 'boolean') { return typeof value === 'boolean' ? undefined : `behavior_input_${prefix}_type_invalid:${id}`; } if (type === 'enum') { if (typeof value !== 'string') return `behavior_input_${prefix}_type_invalid:${id}`; return (field.values as readonly string[]).includes(value) ? undefined : `behavior_input_${prefix}_enum_invalid:${id}`; } if (type === 'player_seats') { if (!Array.isArray(value) || value.some((entry) => typeof entry !== 'number' || !Number.isInteger(entry))) { return `behavior_input_${prefix}_type_invalid:${id}`; } if (value.some((entry) => entry < 1 || entry > 10)) { return `behavior_input_${prefix}_range_invalid:${id}`; } if (field.required === true && value.length === 0) { return `behavior_input_required_empty:${id}`; } if (typeof field.maxItems === 'number' && value.length > field.maxItems) { return `behavior_input_${prefix}_max_items_exceeded:${id}`; } return undefined; } if (!Array.isArray(value) || value.some((entry) => typeof entry !== 'string')) { return `behavior_input_${prefix}_type_invalid:${id}`; } if (value.some((entry) => !entry.trim())) return `behavior_input_${prefix}_empty:${id}`; if (field.required === true && value.length === 0) { return `behavior_input_required_empty:${id}`; } if (typeof field.maxItems === 'number' && value.length > field.maxItems) { return `behavior_input_${prefix}_max_items_exceeded:${id}`; } return undefined; } function fieldDiagnostic(value: unknown, seenIds: Set): string | undefined { const field = fieldRecord(value); if (!field) return 'behavior_input_field_invalid'; const id = typeof field.id === 'string' ? field.id : ''; if (!ID_PATTERN.test(id)) return `behavior_input_id_invalid:${id || 'missing'}`; if (seenIds.has(id)) return `behavior_input_id_duplicate:${id}`; seenIds.add(id); if (typeof field.type !== 'string' || !FIELD_TYPES.has(field.type as BehaviorInputFieldSpec['type'])) { return `behavior_input_type_invalid:${id}`; } if (typeof field.description !== 'string' || !field.description.trim()) { return `behavior_input_description_invalid:${id}`; } if (field.required !== undefined && typeof field.required !== 'boolean') { return `behavior_input_required_invalid:${id}`; } const type = field.type as BehaviorInputFieldSpec['type']; const allowed = new Set(BASE_KEYS); if (type === 'number') { allowed.add('min'); allowed.add('max'); } else if (type === 'enum') { allowed.add('values'); } else if (type === 'string_list' || type === 'player_seats') { allowed.add('maxItems'); } const unknown = Object.keys(field).find((key) => !allowed.has(key)); if (unknown) return `behavior_input_constraint_unknown:${id}:${unknown}`; if (type === 'number') { if ( (field.min !== undefined && (typeof field.min !== 'number' || !Number.isFinite(field.min))) || (field.max !== undefined && (typeof field.max !== 'number' || !Number.isFinite(field.max))) || (typeof field.min === 'number' && typeof field.max === 'number' && field.min > field.max) ) return `behavior_input_number_bounds_invalid:${id}`; } if (type === 'enum') { if ( !Array.isArray(field.values) || field.values.length === 0 || field.values.some((entry) => typeof entry !== 'string') || field.values.some((entry) => !entry.trim()) || new Set(field.values).size !== field.values.length ) return `behavior_input_enum_values_invalid:${id}`; } if (type === 'string_list' || type === 'player_seats') { if ( field.maxItems !== undefined && (!Number.isSafeInteger(field.maxItems) || (field.maxItems as number) <= 0) ) return `behavior_input_max_items_invalid:${id}`; } const hasDefault = own(field, 'default'); if (field.required === true && hasDefault) { return `behavior_input_required_default_conflict:${id}`; } return hasDefault ? valueDiagnostic(field, field.default, 'default') : undefined; } /** Returns one stable diagnostic without throwing or evaluating player code. */ export function behaviorInputFieldsDiagnostic(value: unknown): string | undefined { try { if (!Array.isArray(value)) return 'behavior_inputs_invalid'; const seenIds = new Set(); for (const field of value) { const diagnostic = fieldDiagnostic(field, seenIds); if (diagnostic) return diagnostic; } return undefined; } catch { return 'behavior_inputs_invalid'; } } /** Validates, detaches, and deeply freezes a manifest inputs declaration. */ export function normalizeBehaviorInputFields( value: unknown, ): readonly Readonly[] { const diagnostic = behaviorInputFieldsDiagnostic(value); if (diagnostic) throw new Error(diagnostic); try { const normalized = (value as readonly BehaviorInputFieldSpec[]).map((field) => { // Canonical property order is part of scanner/loader parity checks. const result: Record = { id: field.id, type: field.type, description: field.description, ...(field.required === undefined ? {} : { required: field.required }), ...(own(field, 'default') ? { default: structuredClone(field.default) } : {}), }; if (field.type === 'number') { if (field.min !== undefined) result.min = field.min; if (field.max !== undefined) result.max = field.max; } if (field.type === 'string_list' || field.type === 'player_seats') { if (field.maxItems !== undefined) result.maxItems = field.maxItems; } if (field.type === 'enum') result.values = [...field.values]; return result as unknown as BehaviorInputFieldSpec; }); return deepFreeze(normalized); } catch { throw new Error('behavior_inputs_not_cloneable'); } } export interface NormalizeBehaviorInputOptions { /** Host-owned keys accepted in addition to manifest fields, e.g. kind and finite timing. */ readonly allowedKeys?: readonly string[]; /** Continuous selection may defer required fields until a later hot-control update. */ readonly allowMissingRequired?: boolean; } /** Applies defaults and validates one raw input without coercion. */ export function normalizeBehaviorInput( raw: unknown, fields: readonly Readonly[], options: Readonly = {}, ): Readonly> { const prototype = raw && typeof raw === 'object' ? Object.getPrototypeOf(raw) : undefined; if ( !raw || typeof raw !== 'object' || Array.isArray(raw) || (prototype !== Object.prototype && prototype !== null) ) throw new Error('behavior_input_invalid'); const diagnostic = behaviorInputFieldsDiagnostic(fields); if (diagnostic) throw new Error(diagnostic); const source = raw as Readonly>; const byId = new Map(fields.map((field) => [field.id, field])); const allowedKeys = new Set(options.allowedKeys ?? []); for (const key of Object.keys(source)) { if (!byId.has(key) && !allowedKeys.has(key)) { throw new Error(`behavior_input_field_unknown:${key}`); } } const output: Record = {}; const assignClone = (key: string, value: unknown): void => { try { Object.defineProperty(output, key, { configurable: true, enumerable: true, writable: true, value: structuredClone(value), }); } catch { throw new Error(`behavior_input_value_not_cloneable:${key}`); } }; for (const key of allowedKeys) { if (own(source, key)) assignClone(key, source[key]); } for (const field of fields) { if (own(source, field.id)) { const value = source[field.id]; const valueError = valueDiagnostic(field as unknown as Record, value, 'value'); if (valueError) throw new Error(valueError); assignClone(field.id, value); continue; } if (own(field, 'default')) { assignClone(field.id, field.default); continue; } if (field.required === true && options.allowMissingRequired !== true) { throw new Error(`behavior_input_required:${field.id}`); } } return deepFreeze(output); }