histoire
Version:
A fast story book powered by Vite
267 lines (259 loc) • 13.3 kB
JavaScript
/**
* Emits the inbound `message` listener installed by the preview app: the
* origin/source guard followed by the dispatch over PREVIEW_SYNC, STATE_SYNC,
* PREVIEW_SETTINGS_SYNC, COLLECT_TESTS and RUN_TESTS.
*
* Emitted at the indentation of the app `setup()` body — it is spliced inside
* it by {@link previewApp}.
*/
export function previewMessageHandler() {
return ` window.addEventListener('message', async (event) => {
// Defense-in-depth, applied uniformly to every message type: the host
// posts same-origin messages from the window embedding this sandbox, all
// carrying the __histoire marker. Anything from a foreign frame or
// origin, or without the marker, is dropped before it reaches the
// dispatch below. Resolved through \`getHostWindow()\` rather than
// \`window.parent\` for the reasons documented there.
const hostWindow = getHostWindow()
if (!hostWindow || event.source !== hostWindow) return
if (event.origin && event.origin !== window.location.origin) return
if (!event.data?.__histoire) return
try {
await handlePreviewMessage(event)
}
catch (error) {
// Every branch is guarded, not just the selection one: an error while
// applying a state or a settings message would otherwise escape this
// async listener as an unhandled rejection and paint the error overlay
// over an otherwise healthy preview.
console.error(error)
}
})
async function handlePreviewMessage(event) {
// New opt-in traffic never inherits legacy optional document identity.
if ((event.data.type === HOST_CHANNEL_MESSAGE || (event.data.type === RUNTIME_REQUEST && ['channel.post', 'plugin.post'].includes(event.data.command))) && event.data.documentId !== previewDocumentId) return
if (event.data.documentId !== undefined && event.data.documentId !== previewDocumentId) return
if ([MEASURE_REQUEST, ELEMENT_PICK_REQUEST, PROPS_OVERRIDE].includes(event.data.type)) {
if (initialSelection.controls) return
if (event.data.storyId !== undefined && event.data.storyId !== story.value?.id) return
if (event.data.variantId !== undefined && event.data.variantId !== variant.value?.id) return
if (event.data.requestId !== undefined && (typeof event.data.requestId !== 'string' || event.data.requestId.length > 200)) return
}
// Automation requests retain exact tuple and document identity. Existing
// UI callers omit these additive fields and keep their current protocol.
if (event.data.type === COLLECT_TESTS || event.data.type === RUN_TESTS || event.data.type === RUN_TEST_CASE) {
if (event.data.documentId !== undefined && event.data.documentId !== previewDocumentId) return
if (event.data.storyId !== undefined && event.data.storyId !== story.value?.id) return
if (event.data.variantId !== undefined && event.data.variantId !== variant.value?.id) return
if (event.data.mcpNonce !== undefined && event.data.mcpNonce !== new URLSearchParams(window.location.search).get('mcpNonce')) return
if (event.data.mcpEpoch !== undefined && event.data.mcpEpoch !== new URLSearchParams(window.location.search).get('mcpEpoch')) return
}
if (event.data?.type === PREVIEW_SYNC) {
const currentVariant = variant.value
if (event.data.selectionVersion !== undefined) {
if (!Number.isSafeInteger(event.data.selectionVersion) || event.data.selectionVersion < previewSelectionVersion) return
previewSelectionVersion = event.data.selectionVersion
}
let syncedToken
try {
syncedToken = await syncSelection(event.data)
if (syncedToken === null || syncedToken !== selectionToken) return
}
catch (error) {
// A failed selection (story that stayed unknown after the reload
// guard) must not escape the message listener as an unhandled
// rejection; the host times out and shows its own error state.
console.error(error)
return
}
// Reload can restore the URL's same actor after its initial ready event.
if (!initialSelection.controls && currentVariant && variant.value === currentVariant && frameworkReadyVariants.has(currentVariant)) {
await markVariantReady(currentVariant.id)
if (selectionToken !== syncedToken) return
}
if (selectionToken !== syncedToken) return
postVariantStateSnapshot(story.value?.id, variant.value)
postToParent({ type: SANDBOX_READY, storyId: story.value?.id, variantId: variant.value?.id })
}
else if (event.data?.type === STATE_SYNC) {
if (initialSelection.controls && !controlsRevision.accept(event.data.controlsRevision)) return
if (mounted) {
const updatedVariant = applyVariantStateUpdate({
storyId: story.value?.id ?? selection.storyId,
variantId: event.data.variantId,
state: event.data.state,
getVariantById,
guards: variantStateGuards,
})
if (updatedVariant) reapplyPropsOverride(updatedVariant.id)
}
}
else if (event.data?.type === MEASURE_REQUEST || event.data?.type === ELEMENT_PICK_REQUEST) {
handleElementInspection(event.data, { storyId: story.value?.id, variantId: variant.value?.id })
}
else if (event.data?.type === PROPS_OVERRIDE) {
applyPropsOverride(event.data)
}
else if (event.data?.type === PREVIEW_SETTINGS_SYNC) {
applyPreviewSettings(event.data.settings)
}
else if (event.data?.type === RUNTIME_REQUEST) {
await handleRuntimeRequest(event.data)
}
else if (event.data?.type === HOST_CHANNEL_MESSAGE && event.data.plugin !== undefined) {
// Plugin traffic addresses one actor by id, never the selected variant.
try { receiveFramePluginMessage(event.data.plugin) }
catch { /* Rejections are counted against the plugin; the story runtime is unaffected. */ }
}
else if (event.data?.type === HOST_CHANNEL_MESSAGE) {
if (event.data.storyId !== story.value?.id || event.data.variantId !== variant.value?.id) return
// Malformed application data must not replace or fail the story runtime.
try { runtimeHostChannels.receive(event.data.channel, { storyId: event.data.storyId, variantId: event.data.variantId }) }
catch { /* Application admission errors never fail the story runtime. */ }
}
else if (event.data?.type === COLLECT_TESTS) {
const requestId = event.data?.requestId
if (!story.value || !variant.value) {
setCollectedTestDefinitions([])
// Answer with the key of what is actually selected (nothing), never
// with the requested one: echoing it would report "this variant has
// no tests" for a variant that was never collected. A host request
// scoped to a variant sees the mismatch and re-issues it once the
// preview caught up with the selection.
postToParent({
type: TEST_DEFINITIONS,
requestId,
variantKey: null,
storyId: null,
variantId: null,
mcpNonce: event.data.mcpNonce,
mcpEpoch: event.data.mcpEpoch,
definitions: [],
})
return
}
// Capture the selection synchronously. The await below can span a
// PREVIEW_SYNC message that flips story/variant, so
// re-reading story.value/variant.value afterwards would tag the reply
// with the variant we did NOT collect. The host matches replies by this
// key against its pending request and drops mismatches — a stale key
// there stalls the request until the 15s timeout instead of resolving it.
const collectedStoryId = story.value.id
const collectedVariantId = variant.value.id
try {
const definitions = await variantTestSession.collectVariantTests(collectedStoryId, collectedVariantId)
// Only publish as the current definitions global when the selection did
// not change while collecting, so we never surface another variant's
// tests as the active ones.
if (story.value?.id === collectedStoryId && variant.value?.id === collectedVariantId) {
setCollectedTestDefinitions(definitions)
}
// Tag the reply with the key of the variant that was actually
// collected (captured before the await), so the host files it against
// the matching request instead of ignoring a stale-keyed reply.
postToParent({
type: TEST_DEFINITIONS,
requestId,
variantKey: \`\${collectedStoryId}:\${collectedVariantId}\`,
storyId: collectedStoryId,
variantId: collectedVariantId,
mcpNonce: event.data.mcpNonce,
mcpEpoch: event.data.mcpEpoch,
definitions,
})
}
catch (error) {
console.error(error)
setCollectedTestDefinitions([])
postToParent({
type: TEST_DEFINITIONS,
requestId,
variantKey: \`\${collectedStoryId}:\${collectedVariantId}\`,
storyId: collectedStoryId,
variantId: collectedVariantId,
mcpNonce: event.data.mcpNonce,
mcpEpoch: event.data.mcpEpoch,
definitions: [],
// Lets the host UI distinguish "no tests registered" from a
// crashed collection (e.g. a story module that fails to load).
error: serializeTestError(error),
})
}
}
else if (event.data?.type === RUN_TESTS) {
if (!story.value || !variant.value) {
// Same as the collection branch: tagged with what is selected (
// nothing), so a variant-scoped request retries instead of taking
// this failure as its own variant's result.
postToParent({
type: TEST_RESULT,
runId: event.data.runId,
variantKey: null,
storyId: null,
variantId: null,
mcpNonce: event.data.mcpNonce,
mcpEpoch: event.data.mcpEpoch,
summary: createFailedRunSummary('unknown', 'unknown', new Error('Could not run tests. No active story/variant is selected.')),
})
return
}
// Capture the selection synchronously so a variant swap during the run
// cannot re-tag the reply with the wrong key. A mismatched key is dropped
// by the host, stalling the request until timeout and escalating to the
// heavy node-side vitest browser fallback despite a valid iframe result.
const runStory = story.value
const runVariant = variant.value
try {
const summary = await runVariantTests(runStory, runVariant)
// Tag the reply with the key of the variant that was actually run
// (captured before the await), so the host files it against the
// matching request instead of ignoring a stale-keyed reply.
postToParent({ type: TEST_RESULT, runId: event.data.runId, variantKey: \`\${runStory.id}:\${runVariant.id}\`, storyId: runStory.id, variantId: runVariant.id, mcpNonce: event.data.mcpNonce, mcpEpoch: event.data.mcpEpoch, summary })
}
catch (error) {
if (event.data.command === 'tests.run') {
postToParent({ type: TEST_RESULT, runId: event.data.runId, storyId: runStory.id, variantId: runVariant.id, error: { code: 'COLLECTION_FAILED', message: error instanceof Error ? error.message : String(error) } })
return
}
postToParent({
type: TEST_RESULT,
runId: event.data.runId,
variantKey: \`\${runStory.id}:\${runVariant.id}\`,
storyId: runStory.id,
variantId: runVariant.id,
mcpNonce: event.data.mcpNonce,
mcpEpoch: event.data.mcpEpoch,
summary: createFailedRunSummary(runStory.id, runVariant.id, error),
})
}
}
else if (event.data?.type === RUN_TEST_CASE) {
if (!story.value || !variant.value || !event.data.definition || typeof event.data.runId !== 'string') {
return
}
const runStory = story.value
const runVariant = variant.value
try {
const summary = await variantTestSession.runPreviewTestCase(runStory.id, runVariant.id, event.data.definition)
postToParent({
type: TEST_CASE_RESULT,
runId: event.data.runId,
storyId: runStory.id,
variantId: runVariant.id,
definition: event.data.definition,
summary,
})
}
catch (error) {
postToParent({
type: TEST_CASE_RESULT,
runId: event.data.runId,
storyId: runStory.id,
variantId: runVariant.id,
definition: event.data.definition,
summary: createFailedRunSummary(runStory.id, runVariant.id, error),
})
}
}
}`;
}