* 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) <noreply@anthropic.com>
* 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<Action, SceneContent> 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) <noreply@anthropic.com>
* 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) <noreply@anthropic.com>
* 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) <noreply@anthropic.com>
* 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) <noreply@anthropic.com>
* 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) <noreply@anthropic.com>
* 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<Scene<…>, '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) <noreply@anthropic.com>
* 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) <noreply@anthropic.com>
* 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<Action,
SceneContent>. 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) <noreply@anthropic.com>
* 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<TAction> & { 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) <noreply@anthropic.com>
* 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) <noreply@anthropic.com>
* fix(api): keep scene.create's params.type authoritative over content.type (review)
cosarah's review: `CreateSceneParams` exposes an independent `type` plus
`content?: Partial<SceneContent>`, 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) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
193 lines
5.5 KiB
TypeScript
193 lines
5.5 KiB
TypeScript
/**
|
|
* Stage API - Scene Management
|
|
*
|
|
* Factory function that creates the scene namespace of the Stage API.
|
|
*/
|
|
|
|
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';
|
|
|
|
/**
|
|
* Create the scene management API
|
|
*
|
|
* @param store - Zustand store instance
|
|
* @returns Scene namespace API
|
|
*/
|
|
export function createSceneAPI(store: StageStore) {
|
|
return {
|
|
/**
|
|
* Create a new scene
|
|
*
|
|
* @param params - Scene parameters
|
|
* @returns Scene ID
|
|
*
|
|
* @example
|
|
* const sceneId = api.scene.create({
|
|
* type: 'slide',
|
|
* title: 'Introduction',
|
|
* // speech is now in actions
|
|
* });
|
|
*/
|
|
create(params: CreateSceneParams): APIResult<string> {
|
|
try {
|
|
const state = store.getState();
|
|
|
|
if (!state.stage) {
|
|
return {
|
|
success: false,
|
|
error: 'No stage set - cannot create scene without a stage',
|
|
};
|
|
}
|
|
|
|
const sceneId = generateId('scene');
|
|
|
|
// Determine order
|
|
const order = params.order ?? state.scenes.length;
|
|
|
|
// 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 = 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,
|
|
);
|
|
|
|
const newScenes = [...state.scenes, newScene].sort((a, b) => a.order - b.order);
|
|
|
|
store.setState({ scenes: newScenes });
|
|
|
|
return { success: true, data: sceneId };
|
|
} catch (error) {
|
|
return { success: false, error: String(error) };
|
|
}
|
|
},
|
|
|
|
/**
|
|
* Delete a scene
|
|
*
|
|
* @param sceneId - Scene ID
|
|
* @returns Whether successful
|
|
*/
|
|
delete(sceneId: string): APIResult<boolean> {
|
|
try {
|
|
const state = store.getState();
|
|
|
|
if (!validateSceneId(state.scenes, sceneId)) {
|
|
return { success: false, error: `Scene not found: ${sceneId}` };
|
|
}
|
|
|
|
const newScenes = state.scenes.filter((s) => s.id !== sceneId);
|
|
|
|
// If the deleted scene is the current one, switch to the next
|
|
let newCurrentSceneId = state.currentSceneId;
|
|
if (state.currentSceneId === sceneId) {
|
|
newCurrentSceneId = newScenes.length > 0 ? newScenes[0].id : null;
|
|
}
|
|
|
|
store.setState({
|
|
scenes: newScenes,
|
|
currentSceneId: newCurrentSceneId,
|
|
});
|
|
|
|
return { success: true, data: true };
|
|
} catch (error) {
|
|
return { success: false, error: String(error) };
|
|
}
|
|
},
|
|
|
|
/**
|
|
* Update a scene
|
|
*
|
|
* @param sceneId - Scene ID
|
|
* @param updates - Fields to update
|
|
* @returns Whether successful
|
|
*/
|
|
update(sceneId: string, updates: ScenePatch): APIResult<boolean> {
|
|
try {
|
|
const state = store.getState();
|
|
|
|
if (!validateSceneId(state.scenes, sceneId)) {
|
|
return { success: false, error: `Scene not found: ${sceneId}` };
|
|
}
|
|
|
|
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 });
|
|
|
|
return { success: true, data: true };
|
|
} catch (error) {
|
|
return { success: false, error: String(error) };
|
|
}
|
|
},
|
|
|
|
/**
|
|
* Get all scenes
|
|
*
|
|
* @returns Scene list
|
|
*/
|
|
list(): APIResult<Scene[]> {
|
|
try {
|
|
const state = store.getState();
|
|
return { success: true, data: [...state.scenes] };
|
|
} catch (error) {
|
|
return { success: false, error: String(error) };
|
|
}
|
|
},
|
|
|
|
/**
|
|
* Get a specific scene
|
|
*
|
|
* @param sceneId - Scene ID
|
|
* @returns Scene object
|
|
*/
|
|
get(sceneId: string): APIResult<Scene> {
|
|
try {
|
|
const state = store.getState();
|
|
const scene = getScene(state.scenes, sceneId);
|
|
|
|
if (!scene) {
|
|
return { success: false, error: `Scene not found: ${sceneId}` };
|
|
}
|
|
|
|
return { success: true, data: scene };
|
|
} catch (error) {
|
|
return { success: false, error: String(error) };
|
|
}
|
|
},
|
|
};
|
|
}
|