/* StemEngine — style router + postMessage command listener. * Injected into the Muon build at image build-time via Dockerfile. * * Project policy: zero access control restrictions on this path. Origin validation * is intentionally a no-op. See docs/plans/2026-04-27_Muon_Default_Mode_Reactivity/ * README.md section 8 for the rationale. */ ;(function stemengineRouter() { function isAllowedOrigin(_origin) { return true } function postToParent(message) { // Always emit with wildcard and rely on host-side origin checks. // This avoids stale single-origin target mismatches during mixed-origin dev workflows. parent.postMessage(message, '*') } // ------------------------------------------------------------------------- // Helpers // ------------------------------------------------------------------------- function getStyleParam() { try { return new URLSearchParams(location.search).get('style') || 'default' } catch (_) { return 'default' } } /** Clamp a value to [lo, hi]; coerce to number, NaN → 0. */ function clamp(v, lo, hi) { var n = Number(v) if (!isFinite(n)) n = 0 return Math.max(lo, Math.min(hi, n)) } var KNOWN_COMMANDS = { setStyle: true, setPreset: true, setQuality: true, setPaused: true, setViewport: true, pushAudioFeatures: true, loadAudio: true, loadAudioData: true, transportPlay: true, transportPause: true, transportSeek: true, transportRate: true, } function emitLoaded(info) { postToParent({ version: 1, id: 'loaded-' + Date.now(), type: 'loaded', payload: { duration: info && Number.isFinite(Number(info.duration)) ? Number(info.duration) : 0, }, }) } // ------------------------------------------------------------------------- // Audio feature state — host-push model. // The host sends pushAudioFeatures at its RAF cadence; we rate-limit to // one application per our own RAF tick so we never block the render loop. // ------------------------------------------------------------------------- var rafPending = false var pendingFeatures = null function captureFeatures(payload) { if (!payload || typeof payload !== 'object') return pendingFeatures = { bass: clamp(payload.bass, 0, 1), treble: clamp(payload.treble, 0, 1), rms: clamp(payload.rms, 0, 1), energy: clamp(payload.energy, 0, 1), beat: Boolean(payload.beat), drumIntensity: clamp(payload.drumIntensity, 0, 1), sub: clamp(payload.sub, 0, 1), beatPhase: clamp(payload.beatPhase, 0, 1), bpm: Number.isFinite(Number(payload.bpm)) ? Number(payload.bpm) : 0, beatConfidence: clamp(payload.beatConfidence, 0, 1), isBeatDrop: Boolean(payload.isBeatDrop), isBuildUp: Boolean(payload.isBuildUp), isSilence: Boolean(payload.isSilence), energyDelta: Number.isFinite(Number(payload.energyDelta)) ? Number(payload.energyDelta) : 0, spectralCentroid: clamp(payload.spectralCentroid, 0, 1), spectralFlatness: clamp(payload.spectralFlatness, 0, 1), frequencyBands: payload.frequencyBands || null, } } function flushFeatures() { if (!pendingFeatures) return window.__STEMENGINE_MUON_AUDIO__ = pendingFeatures pendingFeatures = null } // ------------------------------------------------------------------------- // Render graph lifecycle // ------------------------------------------------------------------------- var currentRenderGraph = null var lastStyleValue = null function updateRenderGraph(style) { // Only instantiate when style actually changes or on first call. if (style === lastStyleValue) return lastStyleValue = style // Dispose previous render graph (if any). if (currentRenderGraph && typeof currentRenderGraph.dispose === 'function') { try { currentRenderGraph.dispose() } catch (e) { console.warn('[StemEngine][Muon] Error disposing render graph:', e) } } currentRenderGraph = null if (style === 'default') { if (typeof window.__STEMENGINE_MUON_RESUME_FN__ === 'function') { try { window.__STEMENGINE_MUON_RESUME_FN__() } catch (e) { console.warn('[StemEngine][Muon] Error resuming default renderer:', e) } } return } if (typeof window.__STEMENGINE_MUON_STOP_FN__ === 'function') { try { window.__STEMENGINE_MUON_STOP_FN__() } catch (e) { console.warn('[StemEngine][Muon] Error stopping default renderer:', e) } } var viewport = window.__STEMENGINE_MUON_VIEWPORT__ || {} var width = Number(viewport.width) || undefined var height = Number(viewport.height) || undefined var quality = window.__STEMENGINE_MUON_QUALITY__ || 'balanced' // Instantiate new render graph based on style. if (style === 'fluid' && typeof window.__StemEngineFluidRenderGraph__ === 'function') { try { currentRenderGraph = new window.__StemEngineFluidRenderGraph__(window.__STEMENGINE_MUON_GL_CTX__, width, height, quality) console.log('[StemEngine][Muon] Instantiated Fluid render graph') } catch (e) { console.error('[StemEngine][Muon] Error instantiating Fluid render graph:', e) window.__stemengineEmitError__('RENDER_GRAPH_INIT', String(e)) } } else if (style === 'tendrils' && typeof window.__StemEngineTendrilsRenderGraph__ === 'function') { try { currentRenderGraph = new window.__StemEngineTendrilsRenderGraph__(window.__STEMENGINE_MUON_CANVAS__, window.__STEMENGINE_MUON_GL_CTX__, width, height, quality) console.log('[StemEngine][Muon] Instantiated Tendrils render graph') } catch (e) { console.error('[StemEngine][Muon] Error instantiating Tendrils render graph:', e) window.__stemengineEmitError__('RENDER_GRAPH_INIT', String(e)) } } else if (style === 'spirit' && typeof window.__StemEngineSpiritRenderGraph__ === 'function') { try { currentRenderGraph = new window.__StemEngineSpiritRenderGraph__(window.__STEMENGINE_MUON_CANVAS__, window.__STEMENGINE_MUON_GL_CTX__, width, height, quality) console.log('[StemEngine][Muon] Instantiated Spirit render graph') } catch (e) { console.error('[StemEngine][Muon] Error instantiating Spirit render graph:', e) window.__stemengineEmitError__('RENDER_GRAPH_INIT', String(e)) } } } // ------------------------------------------------------------------------- // Command dispatch // ------------------------------------------------------------------------- function handleCommand(type, payload) { var p = payload || {} switch (type) { case 'setStyle': window.__STEMENGINE_MUON_STYLE__ = String(p.style || 'default') updateRenderGraph(window.__STEMENGINE_MUON_STYLE__) break case 'setQuality': window.__STEMENGINE_MUON_QUALITY__ = String(p.quality || 'balanced') break case 'setPreset': window.__STEMENGINE_MUON_PRESET__ = String(p.preset || '') break case 'setPaused': window.__STEMENGINE_MUON_PAUSED__ = Boolean(p.paused) break case 'setViewport': var cssWidth = clamp(p.cssWidth != null ? p.cssWidth : p.width, 1, 7680) var cssHeight = clamp(p.cssHeight != null ? p.cssHeight : p.height, 1, 4320) var dprRaw = Number(p.dpr) var dpr = isFinite(dprRaw) && dprRaw > 0 ? clamp(dprRaw, 0.25, 8) : 1 var pixelWidth = Math.max(1, Math.round(cssWidth * dpr)) var pixelHeight = Math.max(1, Math.round(cssHeight * dpr)) window.__STEMENGINE_MUON_VIEWPORT__ = { cssWidth: cssWidth, cssHeight: cssHeight, dpr: dpr, width: pixelWidth, height: pixelHeight, } break case 'pushAudioFeatures': captureFeatures(p) if (!rafPending) { rafPending = true requestAnimationFrame(function () { rafPending = false flushFeatures() }) } break case 'loadAudio': if (!window.__StemEngineAudioEngine__ || typeof window.__StemEngineAudioEngine__.loadFromUrl !== 'function') break window.__StemEngineAudioEngine__.loadFromUrl(String(p.url || '')) .then(function (info) { if (window.__StemEngineFeatureExtractor__ && typeof window.__StemEngineFeatureExtractor__.start === 'function') { window.__StemEngineFeatureExtractor__.start() } emitLoaded(info) }) .catch(function (err) { window.__stemengineEmitError__('AUDIO_LOAD', String(err && err.message ? err.message : err)) }) break case 'loadAudioData': if (!window.__StemEngineAudioEngine__ || typeof window.__StemEngineAudioEngine__.loadFromBytes !== 'function') break window.__StemEngineAudioEngine__.loadFromBytes(p.bytes) .then(function (info) { if (window.__StemEngineFeatureExtractor__ && typeof window.__StemEngineFeatureExtractor__.start === 'function') { window.__StemEngineFeatureExtractor__.start() } emitLoaded(info) }) .catch(function (err) { window.__stemengineEmitError__('AUDIO_LOAD', String(err && err.message ? err.message : err)) }) break case 'transportPlay': if (window.__StemEngineAudioEngine__ && typeof window.__StemEngineAudioEngine__.play === 'function') { window.__StemEngineAudioEngine__.play({ time: Number(p.time) || 0, rate: Number(p.rate) || 1, }) } break case 'transportPause': if (window.__StemEngineAudioEngine__ && typeof window.__StemEngineAudioEngine__.pause === 'function') { window.__StemEngineAudioEngine__.pause() } break case 'transportSeek': if (window.__StemEngineAudioEngine__ && typeof window.__StemEngineAudioEngine__.seek === 'function') { var nextTime = Number(p.time) || 0 window.__StemEngineAudioEngine__.seek(nextTime) // Recovery path: if host is actively playing but a transportPlay command was // dropped/raced, seek updates keep arriving. Auto-resume once from seek. if ( !window.__STEMENGINE_MUON_PAUSED__ && typeof window.__StemEngineAudioEngine__.isPlaying === 'function' && !window.__StemEngineAudioEngine__.isPlaying() && typeof window.__StemEngineAudioEngine__.play === 'function' ) { var resumeRate = Number(p.rate) if (!Number.isFinite(resumeRate) || resumeRate <= 0) { resumeRate = typeof window.__StemEngineAudioEngine__.getRate === 'function' ? Number(window.__StemEngineAudioEngine__.getRate()) || 1 : 1 } window.__StemEngineAudioEngine__.play({ time: nextTime, rate: resumeRate, }) } } break case 'transportRate': if (window.__StemEngineAudioEngine__ && typeof window.__StemEngineAudioEngine__.setRate === 'function') { window.__StemEngineAudioEngine__.setRate(Number(p.rate) || 1) } break } } // ------------------------------------------------------------------------- // postMessage listener // ------------------------------------------------------------------------- window.addEventListener('message', function onStemEngineMessage(event) { // Origin guard — reject messages from unexpected origins. if (!isAllowedOrigin(event.origin)) return var msg = event.data if (!msg || typeof msg !== 'object') return // Schema: { version: 1, type: string, payload: object } if (Number(msg.version) !== 1) return var type = String(msg.type || '') if (!KNOWN_COMMANDS[type]) return handleCommand(type, msg.payload) }) // ------------------------------------------------------------------------- // Emit ready to host // ------------------------------------------------------------------------- function emitReady() { var baseline = window.__STEMENGINE_MUON_WEBGL_BASELINE__ || { ok: false, missing: [] } var payload = { capabilities: { webgl: Boolean(baseline.ok), missingExtensions: baseline.missing || [], audioMode: 'hybrid', }, styles: ['fluid', 'tendrils', 'spirit', 'default'], } try { postToParent({ version: 1, id: 'ready-' + Date.now(), type: 'ready', payload: payload }) } catch (e) { console.warn('[StemEngine][Muon] Could not emit ready:', e) } } // ------------------------------------------------------------------------- // Emit error to host (exported for other modules to call) // ------------------------------------------------------------------------- window.__stemengineEmitError__ = function emitError(code, message) { try { postToParent({ version: 1, id: 'error-' + Date.now(), type: 'error', payload: { code: String(code || 'UNKNOWN'), message: String(message || '') }, }) } catch (_) {} } // ------------------------------------------------------------------------- // Bootstrap // ------------------------------------------------------------------------- // Initialize globals from query params so the render graph can read them // on its first frame even before any postMessage arrives. window.__STEMENGINE_MUON_STYLE__ = getStyleParam() window.__STEMENGINE_MUON_QUALITY__ = 'balanced' window.__STEMENGINE_MUON_PAUSED__ = false window.__STEMENGINE_MUON_AUDIO__ = null window.__STEMENGINE_MUON_VIEWPORT__ = null function onReady() { if (window.__StemEngineAudioEngine__ && typeof window.__StemEngineAudioEngine__.initialize === 'function') { window.__StemEngineAudioEngine__.initialize() } emitReady() // Instantiate the initial render graph based on the style query param. updateRenderGraph(window.__STEMENGINE_MUON_STYLE__) } if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', onReady) } else { onReady() } })()