From 7c19ab8f1e3261edf75fe05d9ddc76d16dfd4336 Mon Sep 17 00:00:00 2001 From: wyuc Date: Tue, 30 Jun 2026 13:04:34 -0400 Subject: [PATCH] feat(dsl): JSON Schema artifacts + pure validators (#787 Part B-1) (#817) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat(dsl): add ACTION_TYPES set + isActionType guard A frozen set of every valid ActionType plus a pure membership guard, mirroring the PPT_ELEMENT_TYPES / isPPTElementType idiom in guards.ts. Used by the new validators; useful standalone for narrowing untrusted action.type values. Co-Authored-By: Claude Opus 4.8 (1M context) * feat(dsl): build-time JSON Schema codegen for stage/scene/action TS types stay the single source of truth; ts-json-schema-generator (a devDependency, build-only) emits dist/schema/{stage,scene,action}.schema.json, shipped under the new ./schema/* export. Serves non-TS / bring-your-own-validator consumers without adding a runtime dependency. JSON Schema is not generic, so schema-roots.ts provides a concrete Scene entry point (kept internal, not re-exported). schema.test.ts compiles the generated schema with ajv (devDep) to prove the artifact is real and self-contained on a clean checkout. Co-Authored-By: Claude Opus 4.8 (1M context) * feat(dsl): add pure structural validators (stage/scene/action) validateStage / validateScene / validateAction: hand-written, zero-dependency, fail-loud structural checks layered on the existing guards. They verify discriminants, required fields, and known nested discriminants — a gate for untrusted input (LLM/agent output) and persistence boundaries. Exhaustive per-field validation is delegated to the shipped JSON Schema. Error-collecting ValidationResult reports every issue with a JSON-pointer-ish path. Co-Authored-By: Claude Opus 4.8 (1M context) * docs(dsl): document the runtime schema + validator layer Add a Runtime layer section covering the two complementary consumption modes (schema-as-data via @openmaic/dsl/schema/* and the zero-dep validate* gate), the validate.ts module row, the build:schema step, and tick the JSON Schema roadmap box. Co-Authored-By: Claude Opus 4.8 (1M context) * fix(dsl): harden validators per cross-review (exhaustiveness, discriminant agreement) Addresses cross-review findings on the validator layer: - Add compile-time exhaustiveness assertions for ACTION_TYPES and SCENE_TYPES. `satisfies` only proved each entry is valid, not that the tuple covers the whole union — a newly-added Action/Scene variant could silently be rejected by the validators. The assertion now fails the build on drift. - validateScene cross-checks that scene.type agrees with content.type; a slide-typed scene carrying quiz content (or vice versa) is now rejected. - Move SCENE_TYPES + add an isSceneType guard to stage.ts, next to SceneType, matching the PPT_ELEMENT_TYPES / isPPTElementType idiom in guards.ts; validate.ts reuses them instead of re-encoding the union locally. - Make the validators' scope honest in the doc comment + README: they check the structural envelope, known discriminants, and scene/content agreement; they do NOT exhaustively check per-variant fields, and app-side interactive/pbl content is validated only at the envelope level (exhaustive checks → the JSON Schema). - Note the contract-owned content scope in schema-roots.ts. Co-Authored-By: Claude Opus 4.8 (1M context) * perf(dsl): reuse one schema generator + harden direct-invocation guard Addresses cross-review findings on the codegen path: - gen-schema.mjs built a fresh ts-json-schema-generator (full TS program parse) per root type; build one generator over the tsconfig program and reuse it for every createSchema call — parses once, identical per-type output. - Harden the `invoked directly` check to compare realpaths, so a symlinked invocation (bin shim / pnpm link) still runs main() instead of silently emitting no schema. - schema.test.ts generates all roots once at module scope, then only compiles per case — no repeated heavy codegen. Co-Authored-By: Claude Opus 4.8 (1M context) * fix(dsl): bind scene schema discriminants + pin node-20-compatible generator Addresses round-2 cross-review (codex) findings: - scene.schema.json now ties scene `type` to the matching `content.type`. SerializedScene became a discriminated union (SlideScene | QuizScene via `Omit, 'type'> & { type }`), so the generator emits a const-narrowed discriminant per branch. Previously the schema accepted e.g. { type: 'quiz', content: { type: 'slide', … } } even though validateScene rejects it — the schema is now consistent with the validator. Locked with a test. - Pin ts-json-schema-generator to ~2.4.0. ^2.3.0 resolved to 2.9.0, which declares `node >=22`, conflicting with the repo's `engines.node >=20.9.0`; 2.4.x supports node >=18, keeping the build runnable on every supported Node. Co-Authored-By: Claude Opus 4.8 (1M context) * style(dsl): prettier formatting + drop unused ts-expect-error for green CI - Apply repo Prettier (`pnpm check`) formatting to the new/edited files. - Remove the `@ts-expect-error` on the gen-schema.mjs import: the root `tsc --noEmit` (which compiles test files; allowJs infers the .mjs exports) flagged it as an unused directive (TS2578). Plain comment retained. Co-Authored-By: Claude Opus 4.8 (1M context) * refactor(dsl): align validators + schema to the public Scene type (review) Addresses cosarah's review: the validator, the JSON Schema, and the public TS type had drifted into three different notions of a valid scene. Realign them so the TS types stay the single source of truth, and position the two runtime layers honestly. - schema-roots.ts: revert SerializedScene to the plain default Scene. The schema no longer encodes a stricter type/content binding that the public Scene type doesn't express (the constraint had effectively moved into a hidden internal type). - validate.ts: drop the scene.type<->content.type agreement check (the public Scene does not bind them, so neither does the validator); restrict content to the contract-owned kinds (slide/quiz), matching SceneContent and the schema, so validator and schema no longer disagree on interactive/pbl content. - Reposition docs (validate.ts header + README): the JSON Schema is the authoritative, exhaustive per-field validator (it checks variant fields like an action's elementId) for trust boundaries; validate* are a cheap, zero-dep structural pre-check and a strict subset of the schema — not a separate or stricter gate. - Tests updated to lock the realigned behavior. Co-Authored-By: Claude Opus 4.8 (1M context) * refactor(dsl): bind scene type<->content in the public Scene contract (review) cosarah's review showed the scene type<->content agreement is a real, load-bearing invariant: consumers branch on `scene.type` and then read `scene.content` as the matching shape (e.g. `stage-api-canvas` casts `content as SlideContent` after a `scene.type === 'slide'` check; `complete-summary` counts by `scene.type` and reads `content as QuizContent`). A validator/schema that blesses mismatched pairs is unsafe. So tighten the *exported* contract rather than loosening the runtime checks to match a hole — and make the pure validators the authoritative, relied-upon boundary. DSL contract: - `Scene` becomes a distributive discriminated type binding `type` to `content['type']` (`SceneCore & { type: TContent['type']; content: TContent }` distributed over TContent). TS itself now rejects mismatched scenes; generic widening still works. Extract `SceneCore` for the kind-independent fields. - `validateScene` re-establishes the type<->content agreement check; scene `type` is the contract's slide/quiz; `scene.schema.json` (from the spelled-out discriminated `SerializedScene`) binds `type` to content per branch. Type, validator, and schema now describe the same thing. - `validateAction` checks each variant's required fields (e.g. spotlight.elementId, discussion.topic) — closes the false-positive gap. A test pins the hand map to the generated schema (the TS-derived source of truth) so it cannot drift. - Reposition docs: `validate*` is the zero-dep in-process boundary producers rely on; the JSON Schema is the cross-language mirror + exhaustive value checker. App consumers (the sites the discriminated Scene exposes): - Add `ScenePatch` (non-distributive partial) + `makeScene(core, content)` helper to lib/types/stage.ts — one isolated cast, type derived from content. Patch-typed signatures (`updateScene`, `applyScenePatchInSync`, regenerate plan) and scene rebuilds (`stage-api-scene`, store `updateScene`, `migrateScene`, stage-storage deserialize) route through these. Closes two latent desync foot-guns. Co-Authored-By: Claude Opus 4.8 (1M context) * fix(dsl): validate action field types + migrate scene.update; bidirectional drift-guard (review) Round-2 review of the contract-tightening change (codex + Claude): - validateAction now checks each variant-required field's TYPE, not just presence (`{ type:'spotlight', elementId: 123 }` is rejected — elementId must be a string). ACTION_REQUIRED_FIELDS carries a runtime kind per field. - The schema lockstep test is now bidirectional and type-aware: it asserts a fully-typed action is accepted (catches the map OVER-listing an optional field), every required field flags when missing (under-listing), and flags when present but mis-typed — all keyed off the generated schema's field names + types. - Migrate the public `stageApi.scene.update()` to ScenePatch + makeScene (the create() path was done last commit; update() still did a raw spread that could desync type<->content — masked from tsc only because StageStore.setState is typed `any`). Now both public scene-construction paths rebind type to content. Co-Authored-By: Claude Opus 4.8 (1M context) * fix(api): keep scene.create's params.type authoritative over content.type (review) cosarah's review: `CreateSceneParams` exposes an independent `type` plus `content?: Partial`, and after switching create() to makeScene() (which derives the scene kind from content.type), a call like `create({ type: 'slide', content: { type: 'interactive', ... } })` would silently become an interactive scene — params.type ignored — and mix slide defaults into it. Reject a `content.type` that disagrees with `params.type`, and pin the merged content's `type` to `params.type` so a partial content override can't flip the scene's discriminant. params.type stays authoritative. Adds a test both ways. Co-Authored-By: Claude Opus 4.8 (1M context) --------- Co-authored-by: Claude Opus 4.8 (1M context) --- lib/agent/client/apply-regenerate.ts | 6 +- lib/agent/client/apply-slide-content.ts | 4 +- lib/api/stage-api-scene.ts | 49 +++-- lib/edit/slide-schema.ts | 10 +- lib/store/stage.ts | 21 +- lib/types/stage.ts | 37 ++++ lib/utils/stage-storage.ts | 7 +- packages/@openmaic/dsl/README.md | 61 ++++- packages/@openmaic/dsl/package.json | 10 +- packages/@openmaic/dsl/scripts/gen-schema.mjs | 61 +++++ packages/@openmaic/dsl/src/action.ts | 38 ++++ packages/@openmaic/dsl/src/index.ts | 7 +- packages/@openmaic/dsl/src/schema-roots.ts | 24 ++ packages/@openmaic/dsl/src/stage.ts | 91 +++++--- packages/@openmaic/dsl/src/validate.ts | 208 ++++++++++++++++++ packages/@openmaic/dsl/test/schema.test.ts | 133 +++++++++++ packages/@openmaic/dsl/test/validate.test.ts | 94 ++++++++ pnpm-lock.yaml | 102 ++++++++- tests/api/stage-api-scene.test.ts | 41 ++++ tests/edit/slide-defaults.test.ts | 4 +- tests/edit/slide-schema.test.ts | 8 +- 21 files changed, 930 insertions(+), 86 deletions(-) create mode 100644 packages/@openmaic/dsl/scripts/gen-schema.mjs create mode 100644 packages/@openmaic/dsl/src/schema-roots.ts create mode 100644 packages/@openmaic/dsl/src/validate.ts create mode 100644 packages/@openmaic/dsl/test/schema.test.ts create mode 100644 packages/@openmaic/dsl/test/validate.test.ts create mode 100644 tests/api/stage-api-scene.test.ts diff --git a/lib/agent/client/apply-regenerate.ts b/lib/agent/client/apply-regenerate.ts index 6cd0fbe..d089f4b 100644 --- a/lib/agent/client/apply-regenerate.ts +++ b/lib/agent/client/apply-regenerate.ts @@ -9,7 +9,7 @@ */ import { nanoid } from 'nanoid'; import type { Action } from '@/lib/types/action'; -import type { Scene, SceneContent, InteractiveContent } from '@/lib/types/stage'; +import type { Scene, ScenePatch, SceneContent, InteractiveContent } from '@/lib/types/stage'; import type { GeneratedSlideContent } from '@/lib/types/generation'; import { CURRENT_SLIDE_CONTENT_SCHEMA_VERSION } from '@/lib/edit/slide-schema'; @@ -79,7 +79,7 @@ export interface RegenerateApplyPlan { actionsOnly?: boolean; } | null; /** Partial scene update to apply, or null if nothing should change. */ - patch: Partial | null; + patch: ScenePatch | null; } /** @@ -127,7 +127,7 @@ export function planRegenerateApply( | undefined; const existingCanvas = sceneContent?.type === 'slide' ? sceneContent.canvas : undefined; const runtime = toRuntimeSlideContent(details.content, existingCanvas); - const patch: Partial = { + const patch: ScenePatch = { content: runtime, ...(actions.length > 0 ? { actions } : {}), }; diff --git a/lib/agent/client/apply-slide-content.ts b/lib/agent/client/apply-slide-content.ts index a18f2da..1e1b02e 100644 --- a/lib/agent/client/apply-slide-content.ts +++ b/lib/agent/client/apply-slide-content.ts @@ -9,11 +9,11 @@ */ import { useStageStore } from '@/lib/store/stage'; import { useSlideEditSession } from '@/components/edit/surfaces/slide/slide-edit-session'; -import type { Scene, SlideContent } from '@/lib/types/stage'; +import type { ScenePatch, SlideContent } from '@/lib/types/stage'; /** Apply a scene patch to the stage store and keep the OPEN slide edit session * in lockstep (else the canvas renders stale history and clobbers the change). */ -export function applyScenePatchInSync(sceneId: string, patch: Partial): void { +export function applyScenePatchInSync(sceneId: string, patch: ScenePatch): void { useStageStore.getState().updateScene(sceneId, patch); const es = useSlideEditSession.getState(); if (patch.content && es.sceneId === sceneId) { diff --git a/lib/api/stage-api-scene.ts b/lib/api/stage-api-scene.ts index 9da7dac..e99ce97 100644 --- a/lib/api/stage-api-scene.ts +++ b/lib/api/stage-api-scene.ts @@ -4,7 +4,7 @@ * Factory function that creates the scene namespace of the Stage API. */ -import type { Scene, SceneContent } from '@/lib/types/stage'; +import { makeScene, type Scene, type ScenePatch, type SceneContent } from '@/lib/types/stage'; import type { StageStore, APIResult, CreateSceneParams } from './stage-api-types'; import { generateId, validateSceneId, getScene, createDefaultContent } from './stage-api-defaults'; @@ -45,29 +45,40 @@ export function createSceneAPI(store: StageStore) { // Determine order const order = params.order ?? state.scenes.length; - // Create default content or use the provided content + // Create default content or use the provided content. `params.type` is + // authoritative: reject a `content.type` that disagrees, and pin the + // merged content's `type` to it so the scene's discriminant can't be + // silently overridden by a partial content override. let content: SceneContent; if (params.content) { + if (params.content.type !== undefined && params.content.type !== params.type) { + return { + success: false, + error: `content.type '${params.content.type}' does not match scene type '${params.type}'`, + }; + } content = { ...createDefaultContent(params.type), ...params.content, + type: params.type, } as SceneContent; } else { content = createDefaultContent(params.type); } - const newScene: Scene = { - id: sceneId, - stageId: state.stage.id, - type: params.type, - title: params.title, - order, + const newScene: Scene = makeScene( + { + id: sceneId, + stageId: state.stage.id, + title: params.title, + order, + actions: params.actions, + ...(params.outlineId !== undefined && { outlineId: params.outlineId }), + createdAt: Date.now(), + updatedAt: Date.now(), + }, content, - actions: params.actions, - ...(params.outlineId !== undefined && { outlineId: params.outlineId }), - createdAt: Date.now(), - updatedAt: Date.now(), - }; + ); const newScenes = [...state.scenes, newScene].sort((a, b) => a.order - b.order); @@ -119,7 +130,7 @@ export function createSceneAPI(store: StageStore) { * @param updates - Fields to update * @returns Whether successful */ - update(sceneId: string, updates: Partial): APIResult { + update(sceneId: string, updates: ScenePatch): APIResult { try { const state = store.getState(); @@ -127,9 +138,13 @@ export function createSceneAPI(store: StageStore) { return { success: false, error: `Scene not found: ${sceneId}` }; } - const newScenes = state.scenes.map((scene) => - scene.id === sceneId ? { ...scene, ...updates, updatedAt: Date.now() } : scene, - ); + const newScenes = state.scenes.map((scene) => { + if (scene.id !== sceneId) return scene; + // Rebind `type` to the (possibly updated) content's kind so a + // content-only or type-only patch can't desync the discriminant. + const content = updates.content ?? scene.content; + return makeScene({ ...scene, ...updates, updatedAt: Date.now() }, content); + }); store.setState({ scenes: newScenes }); diff --git a/lib/edit/slide-schema.ts b/lib/edit/slide-schema.ts index 613c32f..48497ef 100644 --- a/lib/edit/slide-schema.ts +++ b/lib/edit/slide-schema.ts @@ -13,7 +13,13 @@ * guarantee that the field is present. */ -import type { InteractiveContent, Scene, SceneContent, SlideContent } from '@/lib/types/stage'; +import { + makeScene, + type InteractiveContent, + type Scene, + type SceneContent, + type SlideContent, +} from '@/lib/types/stage'; export const CURRENT_SLIDE_CONTENT_SCHEMA_VERSION = 1; @@ -81,7 +87,7 @@ export function migrateScene(scene: Scene): Scene { if (migratedContent === scene.content) { return scene; } - return { ...scene, content: migratedContent }; + return makeScene(scene, migratedContent); } function migrateSceneContent(content: SceneContent): SceneContent { diff --git a/lib/store/stage.ts b/lib/store/stage.ts index c05e55f..edd47a9 100644 --- a/lib/store/stage.ts +++ b/lib/store/stage.ts @@ -1,5 +1,13 @@ import { create } from 'zustand'; -import type { PBLContent, Stage, Scene, SceneContent, StageMode } from '@/lib/types/stage'; +import { + makeScene, + type PBLContent, + type Stage, + type Scene, + type SceneContent, + type ScenePatch, + type StageMode, +} from '@/lib/types/stage'; import { createSelectors } from '@/lib/utils/create-selectors'; import type { ChatSession } from '@/lib/types/chat'; import type { SceneOutline } from '@/lib/types/generation'; @@ -91,7 +99,7 @@ interface StageState { setScenes: (scenes: Scene[]) => void; addScene: (scene: Scene) => void; insertSceneAfter: (anchorSceneId: string, scene: Scene) => void; - updateScene: (sceneId: string, updates: Partial) => void; + updateScene: (sceneId: string, updates: ScenePatch) => void; deleteScene: (sceneId: string) => void; setCurrentSceneId: (sceneId: string | null) => void; setChats: (chats: ChatSession[]) => void; @@ -209,11 +217,10 @@ const useStageStoreBase = create()((set, get) => ({ updateScene: (sceneId, updates) => { const scenes = get().scenes.map((scene) => { if (scene.id !== sceneId) return scene; - return { - ...scene, - ...updates, - content: mergeSceneContentForUpdate(scene.content, updates.content) ?? scene.content, - }; + const content = mergeSceneContentForUpdate(scene.content, updates.content) ?? scene.content; + // Rebind `type` to the merged content's kind (a type-only patch can no + // longer desync the discriminant from the content). + return makeScene({ ...scene, ...updates }, content); }); set({ scenes }); debouncedSave(); diff --git a/lib/types/stage.ts b/lib/types/stage.ts index 9dfb49e..0b4b8e8 100644 --- a/lib/types/stage.ts +++ b/lib/types/stage.ts @@ -115,3 +115,40 @@ export type AppScene = DslScene & { outlineId?: string; }; export type Scene = AppScene; + +/** + * A partial update for {@link AppScene} — the patch shape used by `updateScene` / + * `applyScenePatchInSync` / the regenerate-apply plan. + * + * `Partial` is unusable here: `AppScene` is a discriminated union, and + * `Partial<>` *distributes* over it into a union of per-kind partials + * (`Partial | Partial | …`). A generic patch such as + * `{ content }`, where `content: SceneContent` spans all four kinds, then matches + * none of those members. `ScenePatch` is a single (non-distributive) object type + * that keeps `type` and `content` as independently-optional wide unions, which is + * exactly what a shallow-merge patch needs. + */ +export type ScenePatch = Partial> & { + type?: SceneContent['type']; + content?: SceneContent; +}; + +/** + * Build an {@link AppScene} from its kind-independent {@link SceneCore} plus a + * concrete content payload, binding `type` to `content.type`. + * + * The lone `as` is unavoidable and is the *only* cast in the scene-construction + * path: `AppScene` is a distributive discriminated union, and TS cannot prove + * that the freshly-built `{ ...core, type, content }` literal lands in the member + * matching `content`'s kind when that kind is only known through a generic. The + * generic return type re-narrows the result to the single member whose `type` + * equals `content.type`, so every call site still sees a correctly discriminated + * scene. `type` is always derived from `content.type`, which makes the binding + * impossible to violate at a call site. + */ +export function makeScene( + core: Omit, + content: C, +): Extract { + return { ...core, type: content.type, content } as Extract; +} diff --git a/lib/utils/stage-storage.ts b/lib/utils/stage-storage.ts index fb105ad..6a0f3fc 100644 --- a/lib/utils/stage-storage.ts +++ b/lib/utils/stage-storage.ts @@ -5,7 +5,7 @@ * Each stage has its own storage key based on stageId */ -import { Stage, Scene } from '../types/stage'; +import { makeScene, Stage, Scene } from '../types/stage'; import { ChatSession } from '../types/chat'; import { db } from './database'; import { saveChatSessions, loadChatSessions, deleteChatSessions } from './chat-storage'; @@ -106,7 +106,10 @@ export async function loadStageData(stageId: string): Promise makeScene(s, s.content)), currentSceneId: stage.currentSceneId || scenes[0]?.id || null, chats, }; diff --git a/packages/@openmaic/dsl/README.md b/packages/@openmaic/dsl/README.md index b9a2ce2..116a1e2 100644 --- a/packages/@openmaic/dsl/README.md +++ b/packages/@openmaic/dsl/README.md @@ -1,7 +1,7 @@ # @openmaic/dsl The **contract keystone** of the MAIC SDK family. `@openmaic/dsl` is *pure spec* — the -slide object-model types, (planned) JSON Schema, pure validators / type-guards, +slide object-model types, build-time JSON Schema artifacts, pure validators / type-guards, and version/migration helpers — with **zero runtime dependencies** (no React, no pptx, no echarts). @@ -26,8 +26,9 @@ nothing. | ------------- | ------------------------------------------------------------------- | | `slides.ts` | The slide object model: `Slide`, `PPTElement` and all variants, theme, background, animation, table/chart/code types, plus `ElementTypes` / `ShapePathFormulasKeys` enums. | | `stage.ts` | The lesson skeleton: `Stage`, generic `Scene`, `SceneType`, `StageMode`, `Whiteboard`, `VideoManifest`, `SlideContent`, `QuizContent`, `MultiAgentConfig`, `GeneratedAgentConfig`, plus `isSlideContent` / `isQuizContent` guards. | -| `action.ts` | The playback verb set: `Action` and all variants (spotlight, laser, speech, the `Wb*` whiteboard family, `play_video`, `discussion`, and the `widget_*` interaction actions), `ActionType`, the `FIRE_AND_FORGET_ACTIONS` / `SLIDE_ONLY_ACTIONS` / `SYNC_ACTIONS` category lists, plus the `PercentageGeometry` overlay type. | +| `action.ts` | The playback verb set: `Action` and all variants (spotlight, laser, speech, the `Wb*` whiteboard family, `play_video`, `discussion`, and the `widget_*` interaction actions), `ActionType`, the frozen `ACTION_TYPES` set + `isActionType` guard, the `FIRE_AND_FORGET_ACTIONS` / `SLIDE_ONLY_ACTIONS` / `SYNC_ACTIONS` category lists, plus the `PercentageGeometry` overlay type. | | `guards.ts` | Pure discriminant type-guards (`isTextElement`, …) and `PPT_ELEMENT_TYPES`. | +| `validate.ts` | Pure, zero-dep structural validators — `validateStage` / `validateScene` / `validateAction` returning an error-collecting `ValidationResult`. | | `version.ts` | `DSL_VERSION` + the `DslMigration` shape and (empty) migration registry. | ```ts @@ -35,6 +36,51 @@ import type { Slide, PPTElement, Action } from '@openmaic/dsl'; import { isTextElement, DSL_VERSION, SYNC_ACTIONS } from '@openmaic/dsl'; ``` +## Runtime layer (schema + validators) + +The contract is enforceable two ways — a zero-dependency in-process validator +and a cross-language JSON Schema — both generated from / aligned to the same +public TS types, and both honoring the zero-runtime-dependency invariant: + +1. **JSON Schema artifacts (cross-language mirror)** — `Stage`, the default + `Scene`, and `Action` are emitted as standalone JSON + Schema at build time and shipped. This is the language-neutral mirror of the + contract for non-TS consumers, and the place to go for exhaustive value-level + (type / format) checking: + + ```ts + import stageSchema from '@openmaic/dsl/schema/stage.schema.json' with { type: 'json' }; + import sceneSchema from '@openmaic/dsl/schema/scene.schema.json' with { type: 'json' }; + import actionSchema from '@openmaic/dsl/schema/action.schema.json' with { type: 'json' }; + // feed to any JSON Schema validator (ajv, or a non-TS / non-JS consumer) + ``` + + The schema is generated from the TS types (the single source of truth) by + `ts-json-schema-generator`, a **devDependency** — it never enters the runtime + dependency set. + +2. **Pure validators (in-process boundary)** — `validate*` are hand-written, + zero-dependency checks layered on the guards: object shape, required fields + (including each action variant's, e.g. a `spotlight`'s `elementId`), known + discriminants, and the scene `type` <-> `content` binding the public `Scene` + type enforces. Because they add no dependency, in-process (TS / JS) producers + and consumers — generators, importers, the runtime engine — can rely on them + directly without shipping a schema validator. They are a structural subset of + the schema (presence + discriminants; the schema additionally checks each + field's value shape), and describe the same contract. Both are kept in lockstep + by a test that pins the validators' per-variant required fields to the + generated schema. + + ```ts + import { validateStage, validateScene, validateAction } from '@openmaic/dsl'; + + const result = validateScene(input); + if (!result.valid) throw new Error(result.errors.map((e) => `${e.path}: ${e.message}`).join('; ')); + ``` + + `ValidationResult` is `{ valid: true } | { valid: false; errors: { path; message }[] }` — + it collects every issue rather than failing on the first. + ## Status Both consumers are now wired to `@openmaic/dsl` and no longer vendor their own copy @@ -52,7 +98,9 @@ of the slide types: - [x] Wire `@openmaic/importer` to import types from `@openmaic/dsl` (vendored copy deleted). - [x] Wire `@openmaic/renderer` to import types from `@openmaic/dsl` (vendored copy deleted). -- [ ] Add the JSON Schema for the slide contract + a pure schema validator. +- [x] Add the JSON Schema for the slide contract + a pure schema validator + (build-time `dist/schema/*.json` via a devDep generator; zero-dep + `validate*` functions). See **Runtime layer** below. - [x] Promote the `stage` / `scene` / `scene-content` types into the DSL (the universal skeleton now lives in `stage.ts`). - [x] Bring the `Action` playback verb set into the DSL (`action.ts`); the @@ -115,11 +163,14 @@ didn't previously declare). ## Build -Pure TypeScript compiled with `tsc` to ESM + `.d.ts`: +Pure TypeScript compiled with `tsc` to ESM + `.d.ts`, then the JSON Schema +artifacts are generated into `dist/schema/`: ```bash -pnpm --filter @openmaic/dsl build # -> dist/ (index.js, index.d.ts, …) +pnpm --filter @openmaic/dsl build # -> dist/ (index.js, index.d.ts, …) + dist/schema/*.json +pnpm --filter @openmaic/dsl build:schema # regenerate only dist/schema/*.json pnpm --filter @openmaic/dsl typecheck +pnpm --filter @openmaic/dsl test ``` ## License diff --git a/packages/@openmaic/dsl/package.json b/packages/@openmaic/dsl/package.json index ab30234..a0aed1f 100644 --- a/packages/@openmaic/dsl/package.json +++ b/packages/@openmaic/dsl/package.json @@ -1,6 +1,6 @@ { "name": "@openmaic/dsl", - "version": "0.0.2", + "version": "0.1.0", "description": "The MAIC slide DSL: the pure, dependency-free contract (types + JSON Schema + validators + version/migration helpers) that @openmaic/renderer and @openmaic/importer both depend on.", "type": "module", "main": "./dist/index.js", @@ -10,7 +10,8 @@ ".": { "types": "./dist/index.d.ts", "import": "./dist/index.js" - } + }, + "./schema/*": "./dist/schema/*" }, "files": [ "dist", @@ -20,7 +21,8 @@ "sideEffects": false, "scripts": { "clean": "rm -rf dist", - "build": "rm -rf dist && tsc -p tsconfig.json", + "build": "rm -rf dist && tsc -p tsconfig.json && node scripts/gen-schema.mjs", + "build:schema": "node scripts/gen-schema.mjs", "dev": "tsc -p tsconfig.json --watch", "typecheck": "tsc -p tsconfig.json --noEmit", "test": "vitest run", @@ -45,6 +47,8 @@ "access": "public" }, "devDependencies": { + "ajv": "^8.17.1", + "ts-json-schema-generator": "~2.4.0", "typescript": "^5", "vitest": "^4.1.8" } diff --git a/packages/@openmaic/dsl/scripts/gen-schema.mjs b/packages/@openmaic/dsl/scripts/gen-schema.mjs new file mode 100644 index 0000000..a1d5156 --- /dev/null +++ b/packages/@openmaic/dsl/scripts/gen-schema.mjs @@ -0,0 +1,61 @@ +// Build-time JSON Schema codegen for @openmaic/dsl. +// +// Runs ts-json-schema-generator (a devDependency) over the TS contract and +// emits static dist/schema/*.json for non-TS / bring-your-own-validator +// consumers. The generator is BUILD-ONLY — the package keeps zero runtime deps. +import { createGenerator } from 'ts-json-schema-generator'; +import { mkdirSync, writeFileSync, realpathSync } from 'node:fs'; +import { dirname, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const here = dirname(fileURLToPath(import.meta.url)); +const pkgRoot = resolve(here, '..'); + +/** Schema root type -> emitted filename. */ +export const ROOTS = { + Stage: 'stage.schema.json', + SerializedScene: 'scene.schema.json', + Action: 'action.schema.json', +}; + +// One generator over the whole tsconfig program, built lazily and reused for +// every root — parses/type-builds the program once instead of per type. +// `createSchema(typeName)` still walks from each root, so each schema only +// carries the definitions reachable from that type. +let generator; +function getGenerator() { + generator ??= createGenerator({ + tsconfig: resolve(pkgRoot, 'tsconfig.json'), + skipTypeCheck: true, + topRef: true, + }); + return generator; +} + +/** Generate the JSON Schema object for one root type (in-memory). */ +export function generateSchema(typeName) { + if (!(typeName in ROOTS)) throw new Error(`unknown schema root: ${typeName}`); + return getGenerator().createSchema(typeName); +} + +function main() { + const outDir = resolve(pkgRoot, 'dist/schema'); + mkdirSync(outDir, { recursive: true }); + for (const [typeName, out] of Object.entries(ROOTS)) { + writeFileSync(resolve(outDir, out), JSON.stringify(generateSchema(typeName), null, 2) + '\n'); + console.log(`wrote dist/schema/${out}`); + } +} + +// Run only when invoked directly (`node scripts/gen-schema.mjs`). Compare real +// paths so a symlinked invocation (bin shim, pnpm link) still matches. +function invokedDirectly() { + if (!process.argv[1]) return false; + try { + return realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url)); + } catch { + return false; + } +} + +if (invokedDirectly()) main(); diff --git a/packages/@openmaic/dsl/src/action.ts b/packages/@openmaic/dsl/src/action.ts index cc1c526..3e77c19 100644 --- a/packages/@openmaic/dsl/src/action.ts +++ b/packages/@openmaic/dsl/src/action.ts @@ -276,6 +276,44 @@ export const SYNC_ACTIONS: ActionType[] = [ 'widget_reveal', ]; +/** Frozen set of every valid {@link ActionType}, for cheap membership checks. */ +export const ACTION_TYPES = [ + 'spotlight', + 'laser', + 'play_video', + 'speech', + 'wb_open', + 'wb_draw_text', + 'wb_draw_shape', + 'wb_draw_chart', + 'wb_draw_latex', + 'wb_draw_table', + 'wb_draw_line', + 'wb_draw_code', + 'wb_edit_code', + 'wb_clear', + 'wb_delete', + 'wb_close', + 'discussion', + 'widget_highlight', + 'widget_setState', + 'widget_annotation', + 'widget_reveal', +] as const satisfies readonly ActionType[]; + +// Compile-time exhaustiveness: every ActionType must appear in ACTION_TYPES. +// `satisfies` above proves the converse (each entry is a valid ActionType); this +// fails the build if the Action union gains a member the tuple is missing — so +// the validators never silently reject a valid, newly-added action type. +type _ActionTypesExhaustive = [ActionType] extends [(typeof ACTION_TYPES)[number]] ? true : never; +const _actionTypesExhaustive: _ActionTypesExhaustive = true; +void _actionTypesExhaustive; + +/** Narrow an unknown value to a valid {@link ActionType}. Pure, no runtime deps. */ +export function isActionType(value: unknown): value is ActionType { + return typeof value === 'string' && (ACTION_TYPES as readonly string[]).includes(value); +} + // ==================== Canvas utility types (non-action) ==================== /** diff --git a/packages/@openmaic/dsl/src/index.ts b/packages/@openmaic/dsl/src/index.ts index faca106..a1ff885 100644 --- a/packages/@openmaic/dsl/src/index.ts +++ b/packages/@openmaic/dsl/src/index.ts @@ -7,9 +7,11 @@ * @openmaic/importer -> @openmaic/dsl * @openmaic/exporter -> @openmaic/dsl (reserved, future) * - * This package contains ONLY the spec: types, (future) JSON Schema, pure + * This package contains ONLY the spec: types, JSON Schema artifacts, pure * validators / type-guards, and version/migration helpers. It must never gain - * a runtime dependency on React, pptx, echarts, etc. + * a runtime dependency on React, pptx, echarts, etc. The JSON Schema is + * generated at build time (devDependency only) and shipped under + * `@openmaic/dsl/schema/*`; the pure `validate*` functions stay zero-dep. * * The lesson skeleton (`Stage` / `Scene` / `SceneContent`) and the playback * verb set (`Action` and its variants) both live here. `Scene` is generic: the @@ -22,4 +24,5 @@ export * from './slides.js'; export * from './guards.js'; export * from './stage.js'; export * from './action.js'; +export * from './validate.js'; export * from './version.js'; diff --git a/packages/@openmaic/dsl/src/schema-roots.ts b/packages/@openmaic/dsl/src/schema-roots.ts new file mode 100644 index 0000000..f5fbf36 --- /dev/null +++ b/packages/@openmaic/dsl/src/schema-roots.ts @@ -0,0 +1,24 @@ +/** + * Concrete schema-codegen entry point. + * + * JSON Schema is not generic, so the build-time generator needs a concrete, + * non-generic root. This is the contract's default `Scene` + * — it adds no constraint the public {@link Scene} type doesn't already express + * (the `type` <-> `content` binding lives in `Scene` itself). It is intentionally + * NOT re-exported from `index.ts`, so it does not widen the public type surface. + * + * The default distributes to one member per content kind. We spell that union + * out explicitly (`Scene<…, SlideContent> | Scene<…, QuizContent>`) rather than + * writing `Scene`, because the schema generator collapses + * the bare form into a single object with an unbound `type`, whereas the + * spelled-out union emits a discriminated `anyOf` that preserves the binding. + * + * Scope: `SceneContent` is the contract-owned union (`SlideContent | QuizContent`), + * so `scene.schema.json` covers those kinds. App-side `interactive` / `pbl` + * content shapes are not part of the contract — apps that widen `Scene`'s + * `TContent` own the schema for their own content shapes. + */ +import type { Scene, SlideContent, QuizContent } from './stage.js'; +import type { Action } from './action.js'; + +export type SerializedScene = Scene | Scene; diff --git a/packages/@openmaic/dsl/src/stage.ts b/packages/@openmaic/dsl/src/stage.ts index ca118f1..f53e0f6 100644 --- a/packages/@openmaic/dsl/src/stage.ts +++ b/packages/@openmaic/dsl/src/stage.ts @@ -19,6 +19,26 @@ import type { Action } from './action.js'; /** All scene kinds the contract is aware of. Feature kinds (interactive/pbl) are still valid `type` values — their *content* shapes live in the app and are composed in via {@link Scene}'s `TContent` parameter. */ export type SceneType = 'slide' | 'quiz' | 'interactive' | 'pbl'; +/** Frozen set of every valid {@link SceneType}, for cheap membership checks. */ +export const SCENE_TYPES = [ + 'slide', + 'quiz', + 'interactive', + 'pbl', +] as const satisfies readonly SceneType[]; + +// Compile-time exhaustiveness: every SceneType must appear in SCENE_TYPES. +// `satisfies` above proves the converse (each entry is a valid SceneType); this +// fails the build if the union gains a member the tuple is missing. +type _SceneTypesExhaustive = [SceneType] extends [(typeof SCENE_TYPES)[number]] ? true : never; +const _sceneTypesExhaustive: _SceneTypesExhaustive = true; +void _sceneTypesExhaustive; + +/** Narrow an unknown value to a valid {@link SceneType}. Pure, no runtime deps. */ +export function isSceneType(value: unknown): value is SceneType { + return typeof value === 'string' && (SCENE_TYPES as readonly string[]).includes(value); +} + /** Lifecycle / interaction mode a {@link Stage} can be operated in. */ export type StageMode = 'autonomous' | 'playback' | 'edit'; @@ -153,44 +173,16 @@ export interface QuizContent { export type SceneContent = SlideContent | QuizContent; /** - * Scene - Represents a single page/scene in the course. - * - * Generic so the contract owns the universal skeleton + the standard action - * set, while the app widens the content union (and, if needed, the action - * union) for its richer feature kinds: - * - * ```ts - * // app side — widen content; widen actions only if the app adds its own - * type AppScene = Scene; - * ``` - * - * Defaults (`TAction = Action`, `TContent = SlideContent | QuizContent`) yield a - * scene whose `actions` are the contract's standard {@link Action} union and - * whose content spans the two universal kinds — what the runtime engine and - * playback consumers want out of the box. Skeleton-only consumers that reject - * actions entirely can still opt out with `Scene`. The `TContent` - * constraint is structural — any union of objects tagged with a `type: - * SceneType` discriminant satisfies it — so an app can pass its own wider - * content union (slide | quiz | interactive | pbl). - * - * @template TAction - The playback action type (defaults to the standard {@link Action} union). - * @template TContent - The scene-content union; any object union tagged with a - * `type: {@link SceneType}` discriminant (defaults to the - * two universal kinds). + * The content-kind-independent fields of a {@link Scene}. Everything except the + * `type` discriminant and the `content` payload, which {@link Scene} binds + * together per kind. */ -export interface Scene< - TAction = Action, - TContent extends { type: SceneType } = SlideContent | QuizContent, -> { +export interface SceneCore { id: string; stageId: string; // ID of the parent stage (for data integrity checks) - type: SceneType; title: string; order: number; // Display order - // Type-specific content - content: TContent; - // Actions to execute during playback (app-injected) actions?: TAction[]; @@ -205,6 +197,41 @@ export interface Scene< updatedAt?: number; } +/** + * Scene - Represents a single page/scene in the course. + * + * The scene-level `type` discriminant is **bound to its `content`**: a + * slide-typed scene must carry `SlideContent`, a quiz-typed scene `QuizContent`, + * and so on. This is a real invariant — consumers branch on `scene.type` and + * then read `scene.content` as the matching shape — so the contract enforces it + * at the type level rather than leaving the two free to disagree. + * + * Implemented as a distributive conditional over `TContent`: the binding holds + * per member of the content union, so the default `Scene` is `({ type: 'slide'; content: SlideContent } | { type: 'quiz'; + * content: QuizContent }) & SceneCore`, and an app can still widen `TContent` + * with its own content kinds — each new kind ties its own `type` to its shape. + * + * ```ts + * // app side — widen content; widen actions only if the app adds its own + * type AppScene = Scene; + * ``` + * + * Skeleton-only consumers that reject actions entirely can still opt out with + * `Scene`. + * + * @template TAction - The playback action type (defaults to the standard {@link Action} union). + * @template TContent - The scene-content union; any object union tagged with a + * `type: {@link SceneType}` discriminant (defaults to the + * two universal kinds). Each member binds its own `type`. + */ +export type Scene< + TAction = Action, + TContent extends { type: SceneType } = SlideContent | QuizContent, +> = TContent extends unknown + ? SceneCore & { type: TContent['type']; content: TContent } + : never; + // --------------------------------------------------------------------------- // Pure discriminant guards // --------------------------------------------------------------------------- diff --git a/packages/@openmaic/dsl/src/validate.ts b/packages/@openmaic/dsl/src/validate.ts new file mode 100644 index 0000000..bebab81 --- /dev/null +++ b/packages/@openmaic/dsl/src/validate.ts @@ -0,0 +1,208 @@ +/** + * Pure, dependency-free structural validators for the slide DSL contract. + * + * This is the contract's authoritative, zero-dependency validation boundary for + * in-process (TS / JS) producers and consumers — generators, importers, the + * runtime engine. It checks object shape, required fields (including each action + * variant's), known discriminants, and the scene `type` <-> `content` binding + * that the public {@link Scene} type enforces. Producers can rely on it without + * shipping a schema validator, because it adds no runtime dependency. + * + * The shipped JSON Schema (`@openmaic/dsl/schema/*`) is the cross-language + * mirror of the same contract — reach for it from non-TS consumers, or when you + * want exhaustive value-level (type / format) checking. These validators are a + * structural subset (presence + discriminants); the schema additionally checks + * each field's value shape. Both describe the same contract. No runtime + * dependencies. + */ +import { isActionType } from './action.js'; +import type { ActionType } from './action.js'; + +export interface ValidationIssue { + /** JSON-pointer-ish path to the offending value, e.g. `/actions/0/elementId`. */ + path: string; + message: string; +} + +export type ValidationResult = { valid: true } | { valid: false; errors: ValidationIssue[] }; + +/** Runtime kind of a required field, checked with `typeof` / `Array.isArray`. */ +type FieldKind = 'string' | 'number' | 'boolean' | 'object' | 'array'; + +/** + * Required fields beyond `ActionBase` (`id`) for each action variant, with the + * runtime kind each must have. Checked for presence AND shape. Kept in lockstep + * (both directions, names + kinds) with the generated `action.schema.json` by a + * test — the schema, derived from the TS types, is the source of truth. + */ +const ACTION_REQUIRED_FIELDS: Record>> = { + spotlight: { elementId: 'string' }, + laser: { elementId: 'string' }, + play_video: { elementId: 'string' }, + speech: { text: 'string' }, + wb_open: {}, + wb_draw_text: { content: 'string', x: 'number', y: 'number' }, + wb_draw_shape: { shape: 'string', x: 'number', y: 'number', width: 'number', height: 'number' }, + wb_draw_chart: { + chartType: 'string', + x: 'number', + y: 'number', + width: 'number', + height: 'number', + data: 'object', + }, + wb_draw_latex: { latex: 'string', x: 'number', y: 'number' }, + wb_draw_table: { x: 'number', y: 'number', width: 'number', height: 'number', data: 'array' }, + wb_draw_line: { startX: 'number', startY: 'number', endX: 'number', endY: 'number' }, + wb_draw_code: { language: 'string', code: 'string', x: 'number', y: 'number' }, + wb_edit_code: { elementId: 'string', operation: 'string' }, + wb_clear: {}, + wb_delete: { elementId: 'string' }, + wb_close: {}, + discussion: { topic: 'string' }, + widget_highlight: { target: 'string' }, + widget_setState: { state: 'object' }, + widget_annotation: { target: 'string' }, + widget_reveal: { target: 'string' }, +}; + +function matchesKind(value: unknown, kind: FieldKind): boolean { + if (kind === 'array') return Array.isArray(value); + if (kind === 'object') return isObject(value); + return typeof value === kind; +} + +function isObject(v: unknown): v is Record { + return typeof v === 'object' && v !== null && !Array.isArray(v); +} + +function reqString( + o: Record, + key: string, + path: string, + errors: ValidationIssue[], +): void { + if (typeof o[key] !== 'string') + errors.push({ path: `${path}/${key}`, message: `expected string \`${key}\`` }); +} + +function reqNumber( + o: Record, + key: string, + path: string, + errors: ValidationIssue[], +): void { + if (typeof o[key] !== 'number') + errors.push({ path: `${path}/${key}`, message: `expected number \`${key}\`` }); +} + +function done(errors: ValidationIssue[]): ValidationResult { + return errors.length === 0 ? { valid: true } : { valid: false, errors }; +} + +function checkAction(doc: unknown, path: string, errors: ValidationIssue[]): void { + if (!isObject(doc)) { + errors.push({ path: path || '/', message: 'action must be an object' }); + return; + } + reqString(doc, 'id', path, errors); + if (!isActionType(doc.type)) { + errors.push({ + path: `${path}/type`, + message: `unknown action type: ${JSON.stringify(doc.type)}`, + }); + return; // can't check variant fields without a known type + } + for (const [field, kind] of Object.entries(ACTION_REQUIRED_FIELDS[doc.type])) { + const value = doc[field]; + if (value === undefined) { + errors.push({ + path: `${path}/${field}`, + message: `${doc.type} action requires \`${field}\``, + }); + } else if (!matchesKind(value, kind)) { + errors.push({ + path: `${path}/${field}`, + message: `${doc.type} action field \`${field}\` must be ${kind}`, + }); + } + } +} + +function checkScene(doc: unknown, path: string, errors: ValidationIssue[]): void { + if (!isObject(doc)) { + errors.push({ path: path || '/', message: 'scene must be an object' }); + return; + } + reqString(doc, 'id', path, errors); + reqString(doc, 'stageId', path, errors); + reqString(doc, 'title', path, errors); + reqNumber(doc, 'order', path, errors); + + // The scene `type` is bound to its `content` (see `Scene`): a slide scene + // carries slide content, a quiz scene quiz content. The contract owns the + // slide/quiz kinds; app-widened kinds validate their own scenes. + const t = doc.type; + if (t !== 'slide' && t !== 'quiz') { + errors.push({ + path: `${path}/type`, + message: `unknown scene type: ${JSON.stringify(t)} (the contract owns 'slide' and 'quiz')`, + }); + } + + const content = doc.content; + if (!isObject(content)) { + errors.push({ path: `${path}/content`, message: 'scene `content` must be an object' }); + } else if (t === 'slide' || t === 'quiz') { + if (content.type !== t) { + errors.push({ + path: `${path}/content/type`, + message: `content type ${JSON.stringify(content.type)} does not match scene type ${JSON.stringify(t)}`, + }); + } else if (t === 'slide' && !isObject(content.canvas)) { + errors.push({ + path: `${path}/content/canvas`, + message: 'slide content requires an object `canvas`', + }); + } else if (t === 'quiz' && !Array.isArray(content.questions)) { + errors.push({ + path: `${path}/content/questions`, + message: 'quiz content requires a `questions` array', + }); + } + } + + if (doc.actions !== undefined) { + if (!Array.isArray(doc.actions)) { + errors.push({ path: `${path}/actions`, message: '`actions` must be an array' }); + } else { + doc.actions.forEach((a, i) => checkAction(a, `${path}/actions/${i}`, errors)); + } + } +} + +/** Validate a {@link Stage} aggregate (course metadata; scenes are separate). */ +export function validateStage(doc: unknown): ValidationResult { + const errors: ValidationIssue[] = []; + if (!isObject(doc)) + return { valid: false, errors: [{ path: '/', message: 'stage must be an object' }] }; + reqString(doc, 'id', '', errors); + reqString(doc, 'name', '', errors); + reqNumber(doc, 'createdAt', '', errors); + reqNumber(doc, 'updatedAt', '', errors); + return done(errors); +} + +/** Validate a {@link Scene} aggregate, including its nested content + actions. */ +export function validateScene(doc: unknown): ValidationResult { + const errors: ValidationIssue[] = []; + checkScene(doc, '', errors); + return done(errors); +} + +/** Validate a single {@link Action}, including its variant-required fields. */ +export function validateAction(doc: unknown): ValidationResult { + const errors: ValidationIssue[] = []; + checkAction(doc, '', errors); + return done(errors); +} diff --git a/packages/@openmaic/dsl/test/schema.test.ts b/packages/@openmaic/dsl/test/schema.test.ts new file mode 100644 index 0000000..7f6397b --- /dev/null +++ b/packages/@openmaic/dsl/test/schema.test.ts @@ -0,0 +1,133 @@ +import { describe, it, expect } from 'vitest'; +import Ajv from 'ajv'; +import { validateAction } from '@openmaic/dsl'; +// JS codegen helper (the build-only generator); vitest/esbuild resolves it at +// runtime and tsc infers its exports via allowJs. +import { generateSchema } from '../scripts/gen-schema.mjs'; + +// Generate every root schema once (the generator parses the TS program a single +// time and is reused), then compile per case — no repeated heavy codegen. +const schemas = { + Stage: generateSchema('Stage'), + Action: generateSchema('Action'), + SerializedScene: generateSchema('SerializedScene'), +} as const; + +function validator(root: keyof typeof schemas) { + return new Ajv({ allErrors: true, strict: false }).compile(schemas[root]); +} + +describe('generated JSON Schema — Stage', () => { + const v = validator('Stage'); + it('accepts a well-formed stage', () => { + expect(v({ id: 's', name: 'n', createdAt: 1, updatedAt: 2 })).toBe(true); + }); + it('rejects a stage missing required fields', () => { + expect(v({ id: 's' })).toBe(false); + }); +}); + +describe('generated JSON Schema — Action', () => { + const v = validator('Action'); + it('accepts a spotlight action', () => { + expect(v({ id: 'a', type: 'spotlight', elementId: 'e' })).toBe(true); + }); + it('rejects an action missing its required discriminated fields', () => { + expect(v({ id: 'a', type: 'spotlight' /* missing elementId */ })).toBe(false); + }); +}); + +describe('generated JSON Schema — SerializedScene', () => { + const v = validator('SerializedScene'); + const slideScene = { + id: 'sc', + stageId: 'st', + type: 'slide', + title: 't', + order: 0, + content: { + type: 'slide', + canvas: { + id: 'c', + viewportSize: 1920, + viewportRatio: 0.5625, + theme: { themeColors: [], fontColor: '#000', fontName: 'Arial', backgroundColor: '#fff' }, + elements: [], + }, + }, + }; + it('accepts a well-formed slide scene', () => { + expect(v(slideScene)).toBe(true); + }); + it('rejects a scene missing required fields', () => { + expect(v({ id: 'sc' })).toBe(false); + }); + it('rejects content that is not a contract content kind (slide/quiz)', () => { + expect(v({ ...slideScene, content: { type: 'pbl' } })).toBe(false); + }); + it('rejects a scene whose type disagrees with its content (type<->content bound)', () => { + expect(v({ ...slideScene, type: 'quiz' })).toBe(false); + }); +}); + +describe('validateAction variant fields stay in lockstep with the Action schema', () => { + // The schema is generated from the TS types, so it is the source of truth for + // each variant's required fields and their types. These checks pin the + // hand-written required-field map in validate.ts to it BOTH ways: it cannot + // under-list (a schema-required field validateAction ignores), over-list (an + // optional field validateAction wrongly demands), or mis-type a field. + const schema = schemas.Action as { + definitions: Record< + string, + { + anyOf?: { $ref: string }[]; + properties?: Record; + required?: string[]; + } + >; + }; + const GOOD: Record = { + string: 's', + number: 1, + boolean: true, + object: {}, + array: [], + }; + const BAD: Record = { + string: 1, + number: 's', + boolean: 's', + object: 's', + array: {}, + }; + const paths = (doc: unknown) => { + const r = validateAction(doc); + return r.valid ? [] : r.errors.map((e) => e.path); + }; + + const branches = schema.definitions.Action.anyOf ?? []; + for (const branch of branches) { + const def = schema.definitions[branch.$ref.split('/').pop() as string]; + const type = def.properties?.type?.const; + if (!type) continue; + const required = (def.required ?? []).filter((f) => f !== 'id' && f !== 'type'); + const kinds = Object.fromEntries(required.map((f) => [f, def.properties?.[f]?.type])); + + it(`validateAction accepts a fully-typed ${type} (no over-listing)`, () => { + const good = Object.fromEntries(required.map((f) => [f, GOOD[kinds[f] ?? 'string']])); + expect(validateAction({ id: 'a', type, ...good })).toEqual({ valid: true }); + }); + + it(`validateAction flags ${type}'s missing/mis-typed required fields [${required.join(', ')}]`, () => { + for (const f of required) { + // missing → flagged + expect(paths({ id: 'a', type })).toContain(`/${f}`); + // present but wrong-typed → flagged + const st = kinds[f]; + if (typeof st === 'string' && st in BAD) { + expect(paths({ id: 'a', type, [f]: BAD[st] })).toContain(`/${f}`); + } + } + }); + } +}); diff --git a/packages/@openmaic/dsl/test/validate.test.ts b/packages/@openmaic/dsl/test/validate.test.ts new file mode 100644 index 0000000..f9454fe --- /dev/null +++ b/packages/@openmaic/dsl/test/validate.test.ts @@ -0,0 +1,94 @@ +import { describe, it, expect } from 'vitest'; +import { validateStage, validateScene, validateAction, type ValidationResult } from '@openmaic/dsl'; + +function errors(r: ValidationResult): string[] { + return r.valid ? [] : r.errors.map((e) => e.path); +} + +describe('validateStage', () => { + it('accepts a well-formed stage', () => { + expect(validateStage({ id: 's', name: 'n', createdAt: 1, updatedAt: 2 })).toEqual({ + valid: true, + }); + }); + it('collects every missing required field', () => { + const r = validateStage({ id: 's' }); + expect(r.valid).toBe(false); + expect(errors(r)).toEqual(expect.arrayContaining(['/name', '/createdAt', '/updatedAt'])); + }); + it('rejects non-objects', () => { + expect(validateStage(null).valid).toBe(false); + expect(validateStage('x').valid).toBe(false); + }); +}); + +describe('validateScene', () => { + const ok = { + id: 'sc1', + stageId: 'st1', + type: 'slide', + title: 'Intro', + order: 0, + content: { type: 'slide', canvas: { id: 'c' } }, + }; + it('accepts a well-formed slide scene', () => { + expect(validateScene(ok)).toEqual({ valid: true }); + }); + it('flags an unknown content type', () => { + const r = validateScene({ ...ok, content: { type: 'bogus' } }); + expect(errors(r)).toContain('/content/type'); + }); + it('flags a quiz scene missing its questions array', () => { + const r = validateScene({ ...ok, type: 'quiz', content: { type: 'quiz' } }); + expect(errors(r)).toContain('/content/questions'); + }); + it('flags app-widened scene kinds (contract owns only slide/quiz)', () => { + const r = validateScene({ ...ok, type: 'pbl', content: { type: 'pbl' } }); + expect(errors(r)).toContain('/type'); + }); + it('flags a scene whose content.type disagrees with its type', () => { + const r = validateScene({ + ...ok, + type: 'quiz', + content: { type: 'slide', canvas: { id: 'c' } }, + }); + expect(r.valid).toBe(false); + expect(errors(r)).toContain('/content/type'); + }); + it('validates nested actions and points at the bad one', () => { + const r = validateScene({ + ...ok, + actions: [ + { id: 'a', type: 'speech', text: 'hi' }, + { id: 'b', type: 'nope' }, + ], + }); + expect(errors(r)).toContain('/actions/1/type'); + }); +}); + +describe('validateAction', () => { + it('accepts a well-formed action (variant fields present)', () => { + expect(validateAction({ id: 'a', type: 'spotlight', elementId: 'e' })).toEqual({ valid: true }); + }); + it('rejects an unknown action type', () => { + const r = validateAction({ id: 'a', type: 'frobnicate' }); + expect(errors(r)).toContain('/type'); + }); + it('flags a known action type missing a variant-required field', () => { + // cosarah's example: a spotlight with no elementId is unusable at runtime. + const r = validateAction({ id: 'a', type: 'spotlight' }); + expect(errors(r)).toContain('/elementId'); + const d = validateAction({ id: 'a', type: 'discussion' }); + expect(errors(d)).toContain('/topic'); + }); + it('flags a variant-required field of the wrong type', () => { + // present but mis-typed: elementId must be a string, not a number. + const r = validateAction({ id: 'a', type: 'spotlight', elementId: 123 }); + expect(errors(r)).toContain('/elementId'); + }); + it('requires a string id', () => { + const r = validateAction({ type: 'laser', elementId: 'e' }); + expect(errors(r)).toContain('/id'); + }); +}); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 38bf927..25552b2 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -390,6 +390,12 @@ importers: packages/@openmaic/dsl: devDependencies: + ajv: + specifier: ^8.17.1 + version: 8.18.0 + ts-json-schema-generator: + specifier: ~2.4.0 + version: 2.4.0 typescript: specifier: ^5 version: 5.9.3 @@ -2512,6 +2518,10 @@ packages: '@types/node': optional: true + '@isaacs/cliui@9.0.0': + resolution: {integrity: sha512-AokJm4tuBHillT+FpMtxQ60n8ObyXBatq7jD2/JA9dxbDDokKQm8KMht5ibGzLVU9IJDIKK4TPKgMHEYMn3lMg==} + engines: {node: '>=18'} + '@istanbuljs/load-nyc-config@1.1.0': resolution: {integrity: sha512-VjeHSlIzpv/NyD3N0YuHfXOPDIixcA1q2ZV98wsMqcYlPmv2n3Yb2lYP9XMElnaFVXg5A7YLTeLu6V84uQDjmQ==} engines: {node: '>=8'} @@ -7696,6 +7706,10 @@ packages: foreach@2.0.6: resolution: {integrity: sha512-k6GAGDyqLe9JaebCsFCoudPPWfihKu8pylYXRlqP1J7ms39iPoTtk2fviNglIeQEwdh0bQeKJ01ZPyuyQvKzwg==} + foreground-child@3.3.1: + resolution: {integrity: sha512-gIXjKqtFuWEgzFRJA9WCQeSJLZDjgJUOMCMzxtvFq/37KojM1BFGufqsCy0r4qSQmYLsZYMeyRqzIWOMup03sw==} + engines: {node: '>=14'} + forever-agent@0.6.1: resolution: {integrity: sha512-j0KLYPhm6zeac4lz3oJ3o65qvgQCcPubiyotZrXqEaG4hNagNYO8qdlUrX5vwqv9ohqeT/Z3j6+yW067yWWdUw==} @@ -7898,6 +7912,12 @@ packages: resolution: {integrity: sha512-wGM28Ehmcnk2NqRORXFOTOR064L4imSw3EeOqU5bIwUf62eXGwg89WivH6VMahL8zlQHeodzvHpXplrqzrz3Nw==} engines: {node: '>= 10.13.0'} + glob@11.1.0: + resolution: {integrity: sha512-vuNwKSaKiqm7g0THUBu2x7ckSs3XJLXE+2ssL7/MfTGPLLcrJQ/4Uq1CjPTtO5cCIiRxqvN6Twy1qOwhL0Xjcw==} + engines: {node: 20 || >=22} + deprecated: Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me + hasBin: true + glob@7.2.3: resolution: {integrity: sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==} deprecated: Glob versions prior to v9 are no longer supported @@ -8686,6 +8706,10 @@ packages: resolution: {integrity: sha512-H0dkQoCa3b2VEeKQBOxFph+JAbcrQdE7KC0UkqwpLmv2EC4P41QXP+rqo9wYodACiG5/WM5s9oDApTU8utwj9g==} engines: {node: '>= 0.4'} + jackspeak@4.2.3: + resolution: {integrity: sha512-ykkVRwrYvFm1nb2AJfKKYPr0emF6IiXDYUaFx4Zn9ZuIH7MrzEZ3sD5RlqGXNRpHtvUHJyOnCEFxOlNDtGo7wg==} + engines: {node: 20 || >=22} + jake@10.9.4: resolution: {integrity: sha512-wpHYzhxiVQL+IV05BLE2Xn34zW1S223hvjtqk0+gsPrwd/8JNLXJgZZM/iPFsYc1xyphF+6M6EvdE5E9MBGkDA==} engines: {node: '>=10'} @@ -9511,6 +9535,10 @@ packages: lru-cache@10.4.3: resolution: {integrity: sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==} + lru-cache@11.5.1: + resolution: {integrity: sha512-RPimw/7aMdv2oqRrxKwvZXcPfwBrn/JZ2xYcY9Hus/6LaS3VOAKVWKWgNLCFSiOm1ESXinjsDlidVU7JlnCN2A==} + engines: {node: 20 || >=22} + lru-cache@4.1.5: resolution: {integrity: sha512-sWZlbEP2OsHNkXrMl5GYk/jKk70MBng6UU4YI/qGDYbgf6YbP4EvmqISbXCoJiRKs+1bSpFHVgQxvJ17F2li5g==} @@ -9830,6 +9858,10 @@ packages: resolution: {integrity: sha512-fNzuVyifolSLFL4NzpF+wEF4qrgqaaKX0haXPQEdQ7NKAN+WecoKMHV09YcuL/DHxrUsYQOK3MiuDf7Ip2OXfQ==} engines: {node: '>=8'} + minipass@7.1.3: + resolution: {integrity: sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==} + engines: {node: '>=16 || 14 >=14.17'} + minizlib@2.1.2: resolution: {integrity: sha512-bAxsR8BVfj60DWXHE3u30oHzfl4G7khkSuPW+qvpd7jFRHm7dLxOjUk1EHACJ/hxLY8phGJ0YhYHZo7jil7Qdg==} engines: {node: '>= 8'} @@ -10268,6 +10300,9 @@ packages: resolution: {integrity: sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==} engines: {node: '>=6'} + package-json-from-dist@1.0.1: + resolution: {integrity: sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw==} + package-manager-detector@1.6.0: resolution: {integrity: sha512-61A5ThoTiDG/C8s8UMZwSorAGwMJ0ERVGj2OjoW5pAalsNOg15+iQiPzrLJ4jhZ1HJzmC2PIHT2oEiH3R5fzNA==} @@ -10358,6 +10393,10 @@ packages: resolution: {integrity: sha512-QLcPegTHF11axjfojBIoDygmS2E3Lf+8+jI6wOVmNVenrKSo3mFdSGiIgdSHenczw3wPtlVMQaFVwGmM7BJdtg==} engines: {node: '>=0.10.0'} + path-scurry@2.0.2: + resolution: {integrity: sha512-3O/iVVsJAPsOnpwWIeD+d6z/7PmqApyQePUtCndjatj/9I5LylHvt5qluFaBT3I5h3r1ejfR056c+FCv+NnNXg==} + engines: {node: 18 || 20 || >=22} + path-to-regexp@0.1.12: resolution: {integrity: sha512-RA1GjUVMnvYFxuqovrEqZoxxW5NUZqbwKtYz/Tt7nXerk0LbLblQmrsgdeOxV5SFHf0UDggjS/bSeOZwt1pmEQ==} @@ -11744,6 +11783,11 @@ packages: resolution: {integrity: sha512-JfJeIHke7y2egdGGgRAvpCwYFUsHlM2gPcrVOxFkznt/4uzQ7HFmvE63iFHVLBJNDuyDOQgijDK/tXH/f6Msjg==} engines: {node: '>=6.10'} + ts-json-schema-generator@2.4.0: + resolution: {integrity: sha512-HbmNsgs58CfdJq0gpteRTxPXG26zumezOs+SB9tgky6MpqiFgQwieCn2MW70+sxpHouZ/w9LW0V6L4ZQO4y1Ug==} + engines: {node: '>=18.0.0'} + hasBin: true + ts-morph@26.0.0: resolution: {integrity: sha512-ztMO++owQnz8c/gIENcM9XfCEzgoGphTv+nKpYNM1bgsdOVC/jRZuEBf6N+mLLDNg68Kl+GgUZfOySaRiG1/Ug==} @@ -14923,6 +14967,8 @@ snapshots: '@types/node': 22.19.15 optional: true + '@isaacs/cliui@9.0.0': {} + '@istanbuljs/load-nyc-config@1.1.0': dependencies: camelcase: 5.3.1 @@ -19862,8 +19908,8 @@ snapshots: '@next/eslint-plugin-next': 16.1.2 eslint: 9.39.4(jiti@2.6.1) eslint-import-resolver-node: 0.3.9 - eslint-import-resolver-typescript: 3.10.1(eslint-plugin-import@2.32.0)(eslint@9.39.4(jiti@2.6.1)) - eslint-plugin-import: 2.32.0(eslint-import-resolver-typescript@3.10.1)(eslint@9.39.4(jiti@2.6.1)) + eslint-import-resolver-typescript: 3.10.1(eslint-plugin-import@2.32.0(eslint@9.39.4(jiti@2.6.1)))(eslint@9.39.4(jiti@2.6.1)) + eslint-plugin-import: 2.32.0(eslint-import-resolver-typescript@3.10.1(eslint-plugin-import@2.32.0(eslint@9.39.4(jiti@2.6.1)))(eslint@9.39.4(jiti@2.6.1)))(eslint@9.39.4(jiti@2.6.1)) eslint-plugin-jsx-a11y: 6.10.2(eslint@9.39.4(jiti@2.6.1)) eslint-plugin-react: 7.37.5(eslint@9.39.4(jiti@2.6.1)) eslint-plugin-react-hooks: 7.0.1(eslint@9.39.4(jiti@2.6.1)) @@ -19885,7 +19931,7 @@ snapshots: transitivePeerDependencies: - supports-color - eslint-import-resolver-typescript@3.10.1(eslint-plugin-import@2.32.0)(eslint@9.39.4(jiti@2.6.1)): + eslint-import-resolver-typescript@3.10.1(eslint-plugin-import@2.32.0(eslint@9.39.4(jiti@2.6.1)))(eslint@9.39.4(jiti@2.6.1)): dependencies: '@nolyfill/is-core-module': 1.0.39 debug: 4.4.3(supports-color@8.1.1) @@ -19896,21 +19942,21 @@ snapshots: tinyglobby: 0.2.15 unrs-resolver: 1.11.1 optionalDependencies: - eslint-plugin-import: 2.32.0(eslint-import-resolver-typescript@3.10.1)(eslint@9.39.4(jiti@2.6.1)) + eslint-plugin-import: 2.32.0(eslint-import-resolver-typescript@3.10.1(eslint-plugin-import@2.32.0(eslint@9.39.4(jiti@2.6.1)))(eslint@9.39.4(jiti@2.6.1)))(eslint@9.39.4(jiti@2.6.1)) transitivePeerDependencies: - supports-color - eslint-module-utils@2.12.1(eslint-import-resolver-node@0.3.9)(eslint-import-resolver-typescript@3.10.1)(eslint@9.39.4(jiti@2.6.1)): + eslint-module-utils@2.12.1(eslint-import-resolver-node@0.3.9)(eslint-import-resolver-typescript@3.10.1(eslint-plugin-import@2.32.0(eslint@9.39.4(jiti@2.6.1)))(eslint@9.39.4(jiti@2.6.1)))(eslint@9.39.4(jiti@2.6.1)): dependencies: debug: 3.2.7 optionalDependencies: eslint: 9.39.4(jiti@2.6.1) eslint-import-resolver-node: 0.3.9 - eslint-import-resolver-typescript: 3.10.1(eslint-plugin-import@2.32.0)(eslint@9.39.4(jiti@2.6.1)) + eslint-import-resolver-typescript: 3.10.1(eslint-plugin-import@2.32.0(eslint@9.39.4(jiti@2.6.1)))(eslint@9.39.4(jiti@2.6.1)) transitivePeerDependencies: - supports-color - eslint-plugin-import@2.32.0(eslint-import-resolver-typescript@3.10.1)(eslint@9.39.4(jiti@2.6.1)): + eslint-plugin-import@2.32.0(eslint-import-resolver-typescript@3.10.1(eslint-plugin-import@2.32.0(eslint@9.39.4(jiti@2.6.1)))(eslint@9.39.4(jiti@2.6.1)))(eslint@9.39.4(jiti@2.6.1)): dependencies: '@rtsao/scc': 1.1.0 array-includes: 3.1.9 @@ -19921,7 +19967,7 @@ snapshots: doctrine: 2.1.0 eslint: 9.39.4(jiti@2.6.1) eslint-import-resolver-node: 0.3.9 - eslint-module-utils: 2.12.1(eslint-import-resolver-node@0.3.9)(eslint-import-resolver-typescript@3.10.1)(eslint@9.39.4(jiti@2.6.1)) + eslint-module-utils: 2.12.1(eslint-import-resolver-node@0.3.9)(eslint-import-resolver-typescript@3.10.1(eslint-plugin-import@2.32.0(eslint@9.39.4(jiti@2.6.1)))(eslint@9.39.4(jiti@2.6.1)))(eslint@9.39.4(jiti@2.6.1)) hasown: 2.0.2 is-core-module: 2.16.1 is-glob: 4.0.3 @@ -20593,6 +20639,11 @@ snapshots: foreach@2.0.6: {} + foreground-child@3.3.1: + dependencies: + cross-spawn: 7.0.6 + signal-exit: 4.1.0 + forever-agent@0.6.1: {} form-data-encoder@1.7.2: {} @@ -20806,6 +20857,15 @@ snapshots: async-done: 2.0.0 chokidar: 3.6.0 + glob@11.1.0: + dependencies: + foreground-child: 3.3.1 + jackspeak: 4.2.3 + minimatch: 10.2.4 + minipass: 7.1.3 + package-json-from-dist: 1.0.1 + path-scurry: 2.0.2 + glob@7.2.3: dependencies: fs.realpath: 1.0.0 @@ -21695,6 +21755,10 @@ snapshots: has-symbols: 1.1.0 set-function-name: 2.0.2 + jackspeak@4.2.3: + dependencies: + '@isaacs/cliui': 9.0.0 + jake@10.9.4: dependencies: async: 3.2.6 @@ -22634,6 +22698,8 @@ snapshots: lru-cache@10.4.3: {} + lru-cache@11.5.1: {} + lru-cache@4.1.5: dependencies: pseudomap: 1.0.2 @@ -23167,6 +23233,8 @@ snapshots: minipass@4.2.8: {} + minipass@7.1.3: {} + minizlib@2.1.2: dependencies: minipass: 3.3.6 @@ -23651,6 +23719,8 @@ snapshots: p-try@2.2.0: {} + package-json-from-dist@1.0.1: {} + package-manager-detector@1.6.0: {} pako@1.0.11: {} @@ -23730,6 +23800,11 @@ snapshots: dependencies: path-root-regex: 0.1.2 + path-scurry@2.0.2: + dependencies: + lru-cache: 11.5.1 + minipass: 7.1.3 + path-to-regexp@0.1.12: {} path-to-regexp@6.3.0: {} @@ -25568,6 +25643,17 @@ snapshots: ts-dedent@2.3.0: {} + ts-json-schema-generator@2.4.0: + dependencies: + '@types/json-schema': 7.0.15 + commander: 13.1.0 + glob: 11.1.0 + json5: 2.2.3 + normalize-path: 3.0.0 + safe-stable-stringify: 2.5.0 + tslib: 2.8.1 + typescript: 5.9.3 + ts-morph@26.0.0: dependencies: '@ts-morph/common': 0.27.0 diff --git a/tests/api/stage-api-scene.test.ts b/tests/api/stage-api-scene.test.ts new file mode 100644 index 0000000..d041007 --- /dev/null +++ b/tests/api/stage-api-scene.test.ts @@ -0,0 +1,41 @@ +import { describe, it, expect } from 'vitest'; +import { createSceneAPI } from '@/lib/api/stage-api-scene'; +import type { StageStore } from '@/lib/api/stage-api-types'; +import type { Scene, Stage, StageMode } from '@/lib/types/stage'; + +function mockStore() { + const state = { + stage: { id: 'stage-1', name: 'S', createdAt: 1, updatedAt: 1 } as Stage, + scenes: [] as Scene[], + currentSceneId: null as string | null, + mode: 'edit' as StageMode, + }; + const store: StageStore = { + getState: () => state, + setState: (partial) => Object.assign(state, partial), + subscribe: () => () => {}, + }; + return { api: createSceneAPI(store), scenes: () => state.scenes }; +} + +describe('stage api scene.create — type/content authority', () => { + it('keeps params.type authoritative and pins content.type to it', () => { + const { api, scenes } = mockStore(); + const r = api.create({ type: 'slide', title: 'T' }); + expect(r.success).toBe(true); + const scene = scenes()[0]; + expect(scene.type).toBe('slide'); + expect(scene.content.type).toBe('slide'); + }); + + it('rejects a content.type that disagrees with the scene type (no silent override)', () => { + const { api, scenes } = mockStore(); + const r = api.create({ + type: 'slide', + title: 'T', + content: { type: 'interactive', html: 'x' }, + }); + expect(r.success).toBe(false); + expect(scenes()).toHaveLength(0); + }); +}); diff --git a/tests/edit/slide-defaults.test.ts b/tests/edit/slide-defaults.test.ts index 64456e4..f8e21b3 100644 --- a/tests/edit/slide-defaults.test.ts +++ b/tests/edit/slide-defaults.test.ts @@ -71,7 +71,9 @@ function makeSlideScene(overrides: Partial = {}): Scene { createdAt: 1, updatedAt: 1, ...overrides, - }; + // Fixture builder spreads a loose `Partial` over a fixed-kind literal, + // which widens the discriminant; the cast is contained to this test helper. + } as Scene; } describe('createBlankSlideScene', () => { diff --git a/tests/edit/slide-schema.test.ts b/tests/edit/slide-schema.test.ts index dae1ffe..9e5da95 100644 --- a/tests/edit/slide-schema.test.ts +++ b/tests/edit/slide-schema.test.ts @@ -44,7 +44,9 @@ function makeSlideScene(overrides: Partial = {}): Scene { order: 1, content: makeSlideContent(), ...overrides, - }; + // Fixture spreads a loose `Partial` over a fixed-kind literal; cast + // contained to the test helper. + } as Scene; } function makeInteractiveContent( @@ -67,7 +69,9 @@ function makeInteractiveScene(overrides: Partial = {}): Scene { order: 1, content: makeInteractiveContent(), ...overrides, - }; + // Fixture spreads a loose `Partial` over a fixed-kind literal; cast + // contained to the test helper. + } as Scene; } describe('migrateSlideContent', () => {