import { MAX_TRIGGER_RUNTIME_MS } from '../sdk/trigger-plugin/index.js'; export type GameplayTriggerRearm = 'after_clear' | 'after_cooldown'; export interface GameplayTriggerConfig { input?: Record; behavior?: string; behavior_input?: Record; reflex_priority?: number; cooldown_ms?: number; rearm?: GameplayTriggerRearm; max_runtime_ms?: number; } export type GameplayTriggerConfigs = Record; /** * Configuration-only representation consumed by Runtime assembly before it * binds an installed Trigger source. It deliberately has no dependency on a * loader, source path, module class, or Runtime plugin contract. */ export interface TriggerRegistrationOverride { readonly id: string; readonly input?: Readonly>; readonly behavior?: string; readonly behaviorInput?: Readonly>; readonly reflexPriority?: number; readonly cooldownMs?: number; readonly rearm?: GameplayTriggerRearm; readonly maxRuntimeMs?: number; } const RESOURCE_ID = /^[a-z0-9][a-z0-9._-]*$/; const TRIGGER_FIELDS = new Set([ // Legacy persisted field: accepted but deliberately ignored. Enablement is // controlled only by gameplay.disabled_triggers. 'enabled', 'input', 'behavior', 'behavior_input', 'reflex_priority', 'cooldown_ms', 'rearm', 'max_runtime_ms', ]); const MAX_JSON_DEPTH = 32; const MAX_JSON_NODES = 10_000; const MAX_TRIGGER_CONFIGS = 512; const UNSAFE_OBJECT_KEYS = new Set(['__proto__', 'prototype', 'constructor']); interface JsonCloneState { nodes: number; readonly ancestors: WeakSet; } function plainRecord(value: unknown): Record | undefined { if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined; const prototype = Object.getPrototypeOf(value); return prototype === Object.prototype || prototype === null ? value as Record : undefined; } function cloneJsonValue( value: unknown, field: string, state: JsonCloneState, depth = 0, ): unknown { state.nodes += 1; if (state.nodes > MAX_JSON_NODES) { throw new Error(`${field} exceeds the JSON value limit.`); } if (depth > MAX_JSON_DEPTH) { throw new Error(`${field} exceeds the JSON nesting limit.`); } if ( value === null || typeof value === 'string' || typeof value === 'boolean' ) return value; if (typeof value === 'number') { if (!Number.isFinite(value)) throw new Error(`${field} must contain JSON-safe values.`); return value; } if (typeof value !== 'object') { throw new Error(`${field} must contain JSON-safe values.`); } if (state.ancestors.has(value)) throw new Error(`${field} must not contain cycles.`); state.ancestors.add(value); try { if (Array.isArray(value)) { return value.map((entry, index) => ( cloneJsonValue(entry, `${field}[${index}]`, state, depth + 1) )); } const source = plainRecord(value); if (!source) throw new Error(`${field} must contain only plain JSON objects.`); const result: Record = {}; for (const [key, entry] of Object.entries(source)) { if (UNSAFE_OBJECT_KEYS.has(key)) { throw new Error(`${field} contains an unsafe object key.`); } result[key] = cloneJsonValue(entry, `${field}.${key}`, state, depth + 1); } return result; } finally { state.ancestors.delete(value); } } function jsonObject(value: unknown, field: string): Record { if (!plainRecord(value)) throw new Error(`${field} must be a JSON object.`); return cloneJsonValue(value, field, { nodes: 0, ancestors: new WeakSet(), }) as Record; } function optionalSafeInteger( value: unknown, field: string, minimum: number, ): number | undefined { if (value === undefined) return undefined; if (!Number.isSafeInteger(value) || (value as number) < minimum) { throw new Error(`${field} must be a safe integer greater than or equal to ${minimum}.`); } return value as number; } function parseTriggerConfig(value: unknown, field: string): GameplayTriggerConfig { const source = plainRecord(value); if (!source) throw new Error(`${field} must be an object.`); const unknown = Object.keys(source).filter((key) => !TRIGGER_FIELDS.has(key)); if (unknown.length > 0) { throw new Error(`${field} contains unknown fields: ${unknown.sort().join(', ')}.`); } if ( source.behavior !== undefined && (typeof source.behavior !== 'string' || !RESOURCE_ID.test(source.behavior)) ) throw new Error(`${field}.behavior must be a Behavior id.`); if ( source.rearm !== undefined && source.rearm !== 'after_clear' && source.rearm !== 'after_cooldown' ) throw new Error(`${field}.rearm must be after_clear or after_cooldown.`); const reflexPriority = optionalSafeInteger( source.reflex_priority, `${field}.reflex_priority`, Number.MIN_SAFE_INTEGER, ); const cooldownMs = optionalSafeInteger(source.cooldown_ms, `${field}.cooldown_ms`, 0); const maxRuntimeMs = optionalSafeInteger(source.max_runtime_ms, `${field}.max_runtime_ms`, 1); if (maxRuntimeMs !== undefined && maxRuntimeMs > MAX_TRIGGER_RUNTIME_MS) { throw new Error(`${field}.max_runtime_ms cannot exceed ${MAX_TRIGGER_RUNTIME_MS}.`); } return { ...(source.input === undefined ? {} : { input: jsonObject(source.input, `${field}.input`) }), ...(source.behavior === undefined ? {} : { behavior: source.behavior }), ...(source.behavior_input === undefined ? {} : { behavior_input: jsonObject(source.behavior_input, `${field}.behavior_input`), }), ...(reflexPriority === undefined ? {} : { reflex_priority: reflexPriority }), ...(cooldownMs === undefined ? {} : { cooldown_ms: cooldownMs }), ...(source.rearm === undefined ? {} : { rearm: source.rearm as GameplayTriggerRearm }), ...(maxRuntimeMs === undefined ? {} : { max_runtime_ms: maxRuntimeMs }), }; } export function parseGameplayTriggerConfigs( value: unknown, field = 'user-data/gameplay.json triggers', ): GameplayTriggerConfigs { const source = plainRecord(value); if (!source) throw new Error(`${field} must be an object keyed by Trigger id.`); if (Object.keys(source).length > MAX_TRIGGER_CONFIGS) { throw new Error(`${field} cannot contain more than ${MAX_TRIGGER_CONFIGS} entries.`); } const result: GameplayTriggerConfigs = {}; for (const id of Object.keys(source).sort()) { if (!RESOURCE_ID.test(id)) throw new Error(`${field} contains an invalid Trigger id: ${id}.`); result[id] = parseTriggerConfig(source[id], `${field}.${id}`); } return result; } /** Converts persisted snake_case values into deterministic Runtime-neutral overrides. */ export function toTriggerRegistrationOverrides( configs: GameplayTriggerConfigs, ): readonly TriggerRegistrationOverride[] { const normalized = parseGameplayTriggerConfigs(configs); return Object.entries(normalized).map(([id, config]) => Object.freeze({ id, ...(config.input === undefined ? {} : { input: Object.freeze(config.input) }), ...(config.behavior === undefined ? {} : { behavior: config.behavior }), ...(config.behavior_input === undefined ? {} : { behaviorInput: Object.freeze(config.behavior_input), }), ...(config.reflex_priority === undefined ? {} : { reflexPriority: config.reflex_priority, }), ...(config.cooldown_ms === undefined ? {} : { cooldownMs: config.cooldown_ms }), ...(config.rearm === undefined ? {} : { rearm: config.rearm }), ...(config.max_runtime_ms === undefined ? {} : { maxRuntimeMs: config.max_runtime_ms }), })); }