@routevn/creator-model
v1.17.0
Published
Shared RouteVN domain model, validators, and reducer
Readme
RouteVN Creator Model
Shared RouteVN domain model package.
Repo rules and contribution expectations are in GUIDELINES.md.
Schema compatibility maintenance rules are in docs/schema-compatibility.md.
This repo is intended to be the single source of truth for:
- state validation
- command payload validation
- state-aware command preconditions
- command-to-state reduction
It is intentionally not responsible for:
- Insieme transport
- Insieme storage
- partition routing
- actors, tokens, client timestamps
Those stay in the client and server repos.
Public API
SCHEMA_VERSION;
validateState({ state });
validatePayload({ type, payload });
validateAgainstState({
state,
command: { type, payload },
});
processCommand({
state,
command: { type, payload },
});
replayCommands({
state,
commands: [{ type, payload }],
});SCHEMA_VERSION is the exported schema version constant for persisted command
compatibility.
Validation functions return:
{
valid: true;
}or:
{
valid: false,
error: {
kind: "state" | "payload" | "precondition" | "invariant",
code: "payload_validation_failed",
message: "payload.data.foo is not allowed",
path: "payload.data.foo", // only when available
details: {}, // only when available
},
}processCommand() returns:
{ valid: true, state: nextState }replayCommands() returns the same result shape while applying a trusted
command tape against a single working state clone. It is intended for batch
history reconstruction paths such as offline repository boot/import replay,
where validating the full state before and after every individual command is
needlessly expensive.
Design rules:
- no classes
- pure functions whenever possible
- command payload shape is validated separately from state-aware preconditions
SCHEMA_VERSIONis the source of truth for persisted command schema versioningSCHEMA_VERSIONmust stay aligned with the minor version frompackage.json- patch releases must not change persisted schema compatibility
bun run test:compatis the required compatibility gate for model changesprocessCommand()is the authoritative state transitionreplayCommands()is the fast batch replay path for trusted command tapes- model state should contain project-owned runtime data only
- app-owned metadata like project id, name, and description should stay out of this package
projectmay start empty; fields likeresolutionare optional until the model starts owning them- random ids across RouteVN should use
nanoidwith the RouteVN base58 variant; deterministic derived tokens such as partition hashes are a separate case
Animation Camera Tracks
Animation resources may explicitly group synchronized position and scale tracks
with cameraTracks: ["update"], or ["prev", "next"] for transitions.
Each listed side must contain x, y, scaleX, and scaleY keyframe
tracks with matching timing/easing and start-value presence, absolute values,
and positive scales. Track initial values are optional; they must be numeric
on all four tracks or omitted from all four to use the target's existing pose.
Translation tracks cannot coexist with Camera on the same side.
This authoring marker does not alter the runtime animation format. Existing
animations without the marker remain separate tracks; no grouping is inferred.
An update may use cameraTracks: [] to remove grouping. Updates to animation
data are validated with the resource's retained grouping unless it is replaced
in the same command.
Font Weight Metadata
Font resources may store extracted weight capabilities in three flat fields:
{
minWeight: 100,
defaultWeight: 400,
maxWeight: 900,
}The fields are optional for compatibility with existing font resources. When
one is present, all three are required and must satisfy
1 <= minWeight <= defaultWeight <= maxWeight <= 1000. Static fonts store the
same value in all three fields; variable fonts store their fvar wght axis
range and default.
Text Style Font References
textStyle.fontId accepts either one font ID or a non-empty array of unique
font IDs. Both forms are persisted as supplied, and every ID must reference an
existing non-folder font:
{
fontId: "font-primary";
}
{
fontId: ["font-primary", "font-fallback"];
}Computed Variables
Variables support read-only computed definitions for string, number,
boolean, and object results. The presence of computed is the source
discriminator; computed variables omit stored scope, default, and value
fields:
{
id: "hpPercent",
type: "variable",
variableType: "number",
name: "HP Percent",
computed: {
expr: {
round: [
{
mul: [
{
div: [
{ var: "variables.hp" },
{ var: "variables.maxHp" },
],
},
100,
],
},
],
},
},
}Computed definitions may use a simple expr or literal value, or ordered
branches with an explicit default. Validation enforces the Route Engine
operator grammar, result types, concrete variables.*/runtime.* paths,
declared variable references, and an acyclic computed dependency graph.
Computed definitions may also store examples. Example inputs mirror the evaluation context, while calculated results remain derived and are not persisted:
{
computed: {
expr: {
mul: [
{
div: [
{ var: "variables.hp" },
{ var: "variables.maxHp" },
],
},
100,
],
},
examples: [
{
id: "example-low-health",
name: "Low health",
input: {
variables: {
hp: 40,
maxHp: 80,
},
},
},
],
},
}File Structure
src/
index.js
errors.js
helpers.js
model.js
tests/
model-api.test.js
command-direct-coverage.test.js
project.create.spec.yaml
story-and-scenes.spec.yaml
scenes-advanced.spec.yaml
sections-and-lines.spec.yaml
images.spec.yaml
sounds-and-videos.spec.yaml
animations.spec.yaml
audio-effects.test.js
audio-effects-drift.test.js
fonts-and-colors.spec.yaml
transforms-variables-textstyles.spec.yaml
characters-and-layouts.spec.yaml
state-validation.spec.yaml
animations-drift.test.js
command-sequences.test.jsHow This Maps To The Current Client Repo
Current RouteVN files:
src/internal/project/commands.jssrc/internal/project/state.js
should map into this package like this:
src/errors.js- internal domain error factories
src/helpers.js- tiny pure shared helpers
src/model.js- state validation
- invariants
- command definitions
- payload validation
- state-aware validation
- reduction
src/index.js- public exports only
projection.js should stay in the app repos for now. It is downstream of the
domain model and is still tied to current app/repository needs.
Intended Usage
Client:
- validate payload before submit when useful
- optionally run
processCommand()for optimistic apply - send to Insieme transport
Server:
- validate payload at submit boundary
- validate against current state before commit
- commit event to storage
- use
processCommand()for authoritative projection
Testing
This repo uses Bun + Vitest + Puty.
- runner:
bunx vitest run - package script:
bun run test - benchmark script:
bun run bench - YAML specs live in
tests/**/*.spec.yaml - JS sequence tests live in
tests/**/*.test.js
There are 2 test styles:
Command contract specs
- treat commands as pure functions
- validate one call at a time
- assert exact input/output or expected invalid result
- include a direct command coverage matrix for the full public registry
- examples:
Command sequence tests
- apply a sequence of commands
- assert the full state after each step
- also assert the previous state was not mutated
- use these for reducer flows that are easier to reason about as a tape
- example:
YAML Puty specs use tests/support/putyApi.js as a
small adapter so the declarative throws: assertions can stay concise while the
real public API returns { valid: ... } result objects.
Compatibility fixtures live under tests/compat/schema-<n>/.
payloads/fixtures are frozen command payload shapes for that schema versionstates/fixtures are frozen persisted-state snapshots for that schema versionstreams/fixtures are frozen command sequences for that schema version- current tests must continue to validate/replay every archived compatibility fixture from the same or older schema versions
- current schema payload coverage must include
minimal.yamlandfull.yamlfor every public command type
See also:
Current animation update tween properties support either:
keyframesauto: { duration, easing }
Transition animation mask accepts one mask object or a non-empty ordered
array. Each mask may define a non-negative safe-integer delay in
milliseconds.
Audio effects are foldered resources stored in audioEffects.items and
audioEffects.tree. Non-folder items use this wrapper:
{
id: "crossfade",
type: "audioEffect",
name: "Crossfade",
description: "Fade between two BGM sources",
tagIds: ["smooth"],
preview: {
outgoing: { soundId: "calm-theme" },
incoming: { soundId: "battle-theme" },
},
audioEffect: {
type: "transition",
prev: {
volume: {
keyframes: [{ value: 0, duration: 600, easing: "easeInOutSine" }],
},
},
next: {
volume: {
initialValue: 0,
keyframes: [{ value: 100, duration: 900, easing: "easeInOutSine" }],
},
},
},
}The optional editor preview uses outgoing and incoming sound slots for a
transition effect, or a single target sound slot for an update effect. Each
slot is an object containing a soundId.
audioEffect.type is either transition or update. Transition effects have
at least one property under prev or next; update effects place properties
under tween. Both support only volume, pan, and playbackRate. Each
property has non-empty keyframes and must finish with an absolute numeric
keyframe. A final tween or next value becomes the persistent BGM property
value after the effect finishes. Absolute volume values are bounded to
0..100, pan to -1..1, and playback rate to >= 0; relative keyframes
represent unbounded numeric deltas and cannot be final.
textStyle.previewAlign optionally sets how editors align a text style's
preview text: left, center, or right. It only affects editor previews;
align stays the alignment layouts use.
particle.preview optionally holds a particle's editor preview settings,
{ background: { imageId } }: the image shown behind the effect in its editor
preview and thumbnail. The image must reference an existing image item, not a
folder, and that image cannot be deleted while a particle preview uses it. Send
preview: {} in particle.update to clear the background.
transform.preview optionally holds a transform's editor preview settings,
{ background, target }. background is { imageId }, the image behind the
target. target is what the transform places: an image as { imageId }, or a
character as { characterId, sprites }, where sprites holds one
{ id, resourceId } per sprite group, the shape scene lines use. Sprites draw
in array order, the first at the bottom. Each image must reference an existing
non-folder image, the character an existing character, and each resourceId
one of that character's sprites, of any kind but a folder; none of them can be
deleted while a transform preview uses it. Send preview: {} in
transform.update to clear both.
Transforms, particles, layouts, and controls can record
thumbnailSourceHash next to thumbnailFileId: a non-empty string the editor
derives from what it drew for that thumbnail, so it can tell whether the
thumbnail is still current. The model does not interpret it or check it
against the image. It is only accepted together with thumbnailFileId, in state
and in each create or update payload. An update keeps it while the thumbnail
stays the same, including when the same thumbnailFileId is sent again, and
drops it when a different thumbnailFileId comes without a hash or the
thumbnail is removed. A transform's previewFileId is captured with its
thumbnail, so a different previewFileId sent without a hash drops it too. A
thumbnailSourceHash sent as undefined counts as not sent, as it is once a
command is serialized. Folders cannot have one.
project.defaultDialogueAvatarTransformId optionally references a transform for
new dialogue avatars. Omit it when no default is selected. Set or replace the
reference with project.set_default_dialogue_avatar_transform and payload
{ transformId: "transform-id" }; clear it with { transformId: null }.
Folders and missing transforms are rejected. Deleting the referenced transform
or its ancestor folder clears the default atomically. Renaming, moving, or
copying transforms leaves the default unchanged. This authoring default does
not rewrite existing dialogue avatar actions.
Stored commands are JSON, which drops keys set to undefined, so an update
cannot clear an optional field by setting it to undefined. Send null
instead for these fields: strokeColorId in textStyle.update removes a text
style's outline color, and width or height in spritesheet.update removes
a spritesheet's default frame size. A null value is never stored.
Current Scope
Currently implemented command types:
project.createproject.set_default_dialogue_avatar_transformstory.updatescene.createscene.updatescene.deletescene.movesection.createsection.updatesection.deletesection.moveline.createline.update_actionsline.deleteline.moveimage.createimage.updateimage.deleteimage.movespritesheet.createspritesheet.updatespritesheet.deletespritesheet.movesound.createsound.updatesound.deletesound.movevideo.createvideo.updatevideo.deletevideo.moveanimation.createanimation.updateanimation.deleteanimation.moveaudioEffect.createaudioEffect.updateaudioEffect.deleteaudioEffect.movefont.createfont.updatefont.deletefont.movecolor.createcolor.updatecolor.deletecolor.movetransform.createtransform.updatetransform.deletetransform.movevariable.createvariable.updatevariable.deletevariable.movetextStyle.createtextStyle.updatetextStyle.deletetextStyle.movecharacter.createcharacter.updatecharacter.deletecharacter.movelayout.createlayout.updatelayout.deletelayout.movelayout.schema.upgradecharacter.sprite.createcharacter.sprite.updatecharacter.sprite.deletecharacter.sprite.movelayout.element.createlayout.element.updatelayout.element.deletelayout.element.movecontrol.createcontrol.updatecontrol.deletecontrol.movecontrol.element.createcontrol.element.updatecontrol.element.deletecontrol.element.move
The rest of the future command surface should be added only when full validation, preconditions, reducer behavior, and tests are added together.
