BlueGit

timfa questward

feat: branch quest steps and remember which steps were finished

Quest steps gain an exit (continue, branches, or complete). Existing quests
keep a linear chain via an implicit exit that is rebuilt on load. Player
state stores the current step id, with numeric indexes still resolving, and
completed step ids stay in the progress blob across merges and loops.
questStepAtLeast becomes hasCompletedStep (or quest started) on load.

Co-authored-by: tim <tim@timfalken.com>

timfa project_85689633_bot_760517ee9267c86ff1d6c3a0237abf7d · pushed by timfa

Authored 2026-10-14 · 4 weeks ago

Hash
25915c58a1df5544005b7b97ea34b6773c7ddad6
Parent
00e2f16e
15 files changed +1368 −213
client/src/editor/conditionSetEditor.js +121 −27
@@ -15,8 +15,10 @@ import {
15 15 import { createDimensionCombobox } from "./dimensionCombobox.js";
16 16 import { OVERWORLD_ID } from "/shared/world/dimensions.js";
17 17
18 /** All condition kinds available in the shared editor UI. */
19 export const CONDITION_EDITOR_KINDS = Object.freeze(Object.values(ConditionKind));
18 /** All condition kinds available in the shared editor UI. questStepAtLeast is load-only. */
19 export const CONDITION_EDITOR_KINDS = Object.freeze(
20 Object.values(ConditionKind).filter((kind) => kind !== ConditionKind.questStepAtLeast)
21 );
20 22
21 23 export {
22 24 emptyConditionSet,
@@ -29,10 +31,10 @@ export {
29 31 export function renderConditionSet (when, onChange, ctx = {})
30 32 {
31 33 const wrap = document.createElement("div");
32 const set = normalizeConditionSet(when);
33 const bump = (remount = true) => onChange(set, { remount });
34 34 const questList = Array.isArray(ctx.quests) ? ctx.quests : [];
35 35 const dialogueList = Array.isArray(ctx.dialogues) ? ctx.dialogues : [];
36 const set = normalizeConditionSet(when, { quests: questList });
37 const bump = (remount = true) => onChange(set, { remount });
36 38 const header = document.createElement("div");
37 39 header.className = "content-editor-condition-set-header";
38 40 const title = document.createElement("strong");
@@ -215,17 +217,10 @@ export function renderConditionSet (when, onChange, ctx = {})
215 217 bump(false);
216 218 }));
217 219 }
218 else if (cond.kind === ConditionKind.questStepAtLeast)
220 else if (cond.kind === ConditionKind.hasCompletedStep)
219 221 {
220 row.append(miniField("questId", cond.questId ?? "", (v) =>
221 {
222 cond.questId = v;
223 set.all[index].condition = cond;
224 bump(false);
225 }));
226 row.append(miniField("step", cond.step ?? 1, (v) =>
222 row.append(hasCompletedStepConditionFields(cond, questList, () =>
227 223 {
228 cond.step = Math.max(1, Number(v) || 1);
229 224 set.all[index].condition = cond;
230 225 bump(false);
231 226 }));
@@ -706,22 +701,26 @@ function questStateConditionFields (cond, questList, onChanged)
706 701 stateSelect.replaceChildren();
707 702 const options = [
708 703 { value: "not-started", label: "not-started" },
709 ...((quest?.steps ?? []).map((step, index) => ({
710 value: String(index + 1),
711 label: `Step ${index + 1}: ${step.title || step.stepId}`
704 { value: "started", label: "started" },
705 ...((quest?.steps ?? []).map((step) => ({
706 value: step.stepId,
707 label: questStepMenuLabel(step)
712 708 }))),
713 709 { value: "completed", label: "completed" }
714 710 ];
715 711 let matched = false;
712 const current = cond.state ?? "not-started";
713 let currentKey = current === "not-started" || current === "completed" || current === "started"
714 ? current
715 : String(current);
716 const asIndex = Number(currentKey);
717 if (/^\d+$/.test(currentKey) && quest?.steps?.[asIndex - 1])
718 { currentKey = quest.steps[asIndex - 1].stepId; }
716 719 for (const entry of options)
717 720 {
718 721 const opt = document.createElement("option");
719 722 opt.value = entry.value;
720 723 opt.textContent = entry.label;
721 const current = cond.state ?? "not-started";
722 const currentKey = current === "not-started" || current === "completed"
723 ? current
724 : String(Number(current) || current);
725 724 if (entry.value === currentKey)
726 725 {
727 726 opt.selected = true;
@@ -749,17 +748,112 @@ function questStateConditionFields (cond, questList, onChanged)
749 748 });
750 749 stateSelect.addEventListener("change", () =>
751 750 {
752 const raw = stateSelect.value;
753 if (raw === "not-started" || raw === "completed")
754 { cond.state = raw; }
755 else
756 { cond.state = Math.max(1, Number(raw) | 0); }
751 cond.state = stateSelect.value;
757 752 onChanged();
758 753 });
759 754 wrap.append(questSelect, stateSelect);
760 755 return wrap;
761 756 }
762 757
758 function questStepMenuLabel (step)
759 {
760 const id = String(step?.stepId ?? "");
761 const title = String(step?.title || step?.label || "").trim();
762 if (title && title !== id)
763 { return `${title} (${id})`; }
764 return id || "step";
765 }
766
767 /** Quest picker + step id for hasCompletedStep. */
768 function hasCompletedStepConditionFields (cond, questList, onChanged)
769 {
770 const wrap = document.createElement("div");
771 wrap.className = "quest-condition-pair";
772 const questSelect = document.createElement("select");
773 const blank = document.createElement("option");
774 blank.value = "";
775 blank.textContent = "Select quest…";
776 questSelect.append(blank);
777 for (const quest of questList)
778 {
779 const opt = document.createElement("option");
780 opt.value = quest.questId;
781 opt.textContent = quest.title ? `${quest.title} (${quest.questId})` : quest.questId;
782 if (quest.questId === cond.questId)
783 { opt.selected = true; }
784 questSelect.append(opt);
785 }
786 if (cond.questId && !questList.some((q) => q.questId === cond.questId))
787 {
788 const missing = document.createElement("option");
789 missing.value = cond.questId;
790 missing.textContent = `${cond.questId} (missing)`;
791 missing.selected = true;
792 questSelect.append(missing);
793 }
794 const stepSelect = document.createElement("select");
795 const fillSteps = () =>
796 {
797 const quest = questList.find((q) => q.questId === cond.questId) ?? null;
798 stepSelect.replaceChildren();
799 const steps = quest?.steps ?? [];
800 if (!steps.length)
801 {
802 const empty = document.createElement("option");
803 empty.value = cond.stepId ?? "";
804 empty.textContent = cond.stepId || "No steps";
805 empty.selected = true;
806 stepSelect.append(empty);
807 return;
808 }
809 let matched = false;
810 for (const step of steps)
811 {
812 const opt = document.createElement("option");
813 opt.value = step.stepId;
814 opt.textContent = questStepMenuLabel(step);
815 if (step.stepId === cond.stepId)
816 {
817 opt.selected = true;
818 matched = true;
819 }
820 stepSelect.append(opt);
821 }
822 if (!matched)
823 {
824 if (cond.stepId)
825 {
826 const fallback = document.createElement("option");
827 fallback.value = cond.stepId;
828 fallback.textContent = cond.stepId;
829 fallback.selected = true;
830 stepSelect.append(fallback);
831 }
832 else
833 {
834 cond.stepId = steps[0].stepId;
835 stepSelect.options[0].selected = true;
836 }
837 }
838 };
839 fillSteps();
840 questSelect.addEventListener("change", () =>
841 {
842 cond.questId = questSelect.value;
843 const quest = questList.find((q) => q.questId === cond.questId);
844 cond.stepId = quest?.steps?.[0]?.stepId ?? "";
845 fillSteps();
846 onChanged();
847 });
848 stepSelect.addEventListener("change", () =>
849 {
850 cond.stepId = stepSelect.value;
851 onChanged();
852 });
853 wrap.append(questSelect, stepSelect);
854 return wrap;
855 }
856
763 857 /** Compact searchable item picker for hasItem conditions. */
764 858 function itemConditionPicker (cond, onPicked)
765 859 {
@@ -882,8 +976,8 @@ function defaultCondition (kind)
882 976 case ConditionKind.inDimension:
883 977 case ConditionKind.hasVisitedDimension:
884 978 return { kind, dimensionId: OVERWORLD_ID };
885 case ConditionKind.questStepAtLeast:
886 return { kind, questId: "", step: 1 };
979 case ConditionKind.hasCompletedStep:
980 return { kind, questId: "", stepId: "" };
887 981 case ConditionKind.hpAtLeast:
888 982 case ConditionKind.staminaAtLeast:
889 983 return { kind, amount: 1 };
@@ -15,8 +15,10 @@ import {
15import { createDimensionCombobox } from "./dimensionCombobox.js";
15import { createDimensionCombobox } from "./dimensionCombobox.js";
16import { OVERWORLD_ID } from "/shared/world/dimensions.js";
16import { OVERWORLD_ID } from "/shared/world/dimensions.js";
17
17
18/** All condition kinds available in the shared editor UI. */
18/** All condition kinds available in the shared editor UI. questStepAtLeast is load-only. */
19export const CONDITION_EDITOR_KINDS = Object.freeze(Object.values(ConditionKind));
19export const CONDITION_EDITOR_KINDS = Object.freeze(
20 Object.values(ConditionKind).filter((kind) => kind !== ConditionKind.questStepAtLeast)
21);
20
22
21export {
23export {
22 emptyConditionSet,
24 emptyConditionSet,
@@ -29,10 +31,10 @@ export {
29export function renderConditionSet (when, onChange, ctx = {})
31export function renderConditionSet (when, onChange, ctx = {})
30{
32{
31 const wrap = document.createElement("div");
33 const wrap = document.createElement("div");
32 const set = normalizeConditionSet(when);
33 const bump = (remount = true) => onChange(set, { remount });
34 const questList = Array.isArray(ctx.quests) ? ctx.quests : [];
34 const questList = Array.isArray(ctx.quests) ? ctx.quests : [];
35 const dialogueList = Array.isArray(ctx.dialogues) ? ctx.dialogues : [];
35 const dialogueList = Array.isArray(ctx.dialogues) ? ctx.dialogues : [];
36 const set = normalizeConditionSet(when, { quests: questList });
37 const bump = (remount = true) => onChange(set, { remount });
36 const header = document.createElement("div");
38 const header = document.createElement("div");
37 header.className = "content-editor-condition-set-header";
39 header.className = "content-editor-condition-set-header";
38 const title = document.createElement("strong");
40 const title = document.createElement("strong");
@@ -215,17 +217,10 @@ export function renderConditionSet (when, onChange, ctx = {})
215 bump(false);
217 bump(false);
216 }));
218 }));
217 }
219 }
218 else if (cond.kind === ConditionKind.questStepAtLeast)
220 else if (cond.kind === ConditionKind.hasCompletedStep)
219 {
221 {
220 row.append(miniField("questId", cond.questId ?? "", (v) =>
222 row.append(hasCompletedStepConditionFields(cond, questList, () =>
221 {
222 cond.questId = v;
223 set.all[index].condition = cond;
224 bump(false);
225 }));
226 row.append(miniField("step", cond.step ?? 1, (v) =>
227 {
223 {
228 cond.step = Math.max(1, Number(v) || 1);
229 set.all[index].condition = cond;
224 set.all[index].condition = cond;
230 bump(false);
225 bump(false);
231 }));
226 }));
@@ -706,22 +701,26 @@ function questStateConditionFields (cond, questList, onChanged)
706 stateSelect.replaceChildren();
701 stateSelect.replaceChildren();
707 const options = [
702 const options = [
708 { value: "not-started", label: "not-started" },
703 { value: "not-started", label: "not-started" },
709 ...((quest?.steps ?? []).map((step, index) => ({
704 { value: "started", label: "started" },
710 value: String(index + 1),
705 ...((quest?.steps ?? []).map((step) => ({
711 label: `Step ${index + 1}: ${step.title || step.stepId}`
706 value: step.stepId,
707 label: questStepMenuLabel(step)
712 }))),
708 }))),
713 { value: "completed", label: "completed" }
709 { value: "completed", label: "completed" }
714 ];
710 ];
715 let matched = false;
711 let matched = false;
712 const current = cond.state ?? "not-started";
713 let currentKey = current === "not-started" || current === "completed" || current === "started"
714 ? current
715 : String(current);
716 const asIndex = Number(currentKey);
717 if (/^\d+$/.test(currentKey) && quest?.steps?.[asIndex - 1])
718 { currentKey = quest.steps[asIndex - 1].stepId; }
716 for (const entry of options)
719 for (const entry of options)
717 {
720 {
718 const opt = document.createElement("option");
721 const opt = document.createElement("option");
719 opt.value = entry.value;
722 opt.value = entry.value;
720 opt.textContent = entry.label;
723 opt.textContent = entry.label;
721 const current = cond.state ?? "not-started";
722 const currentKey = current === "not-started" || current === "completed"
723 ? current
724 : String(Number(current) || current);
725 if (entry.value === currentKey)
724 if (entry.value === currentKey)
726 {
725 {
727 opt.selected = true;
726 opt.selected = true;
@@ -749,17 +748,112 @@ function questStateConditionFields (cond, questList, onChanged)
749 });
748 });
750 stateSelect.addEventListener("change", () =>
749 stateSelect.addEventListener("change", () =>
751 {
750 {
752 const raw = stateSelect.value;
751 cond.state = stateSelect.value;
753 if (raw === "not-started" || raw === "completed")
754 { cond.state = raw; }
755 else
756 { cond.state = Math.max(1, Number(raw) | 0); }
757 onChanged();
752 onChanged();
758 });
753 });
759 wrap.append(questSelect, stateSelect);
754 wrap.append(questSelect, stateSelect);
760 return wrap;
755 return wrap;
761}
756}
762
757
758function questStepMenuLabel (step)
759{
760 const id = String(step?.stepId ?? "");
761 const title = String(step?.title || step?.label || "").trim();
762 if (title && title !== id)
763 { return `${title} (${id})`; }
764 return id || "step";
765}
766
767/** Quest picker + step id for hasCompletedStep. */
768function hasCompletedStepConditionFields (cond, questList, onChanged)
769{
770 const wrap = document.createElement("div");
771 wrap.className = "quest-condition-pair";
772 const questSelect = document.createElement("select");
773 const blank = document.createElement("option");
774 blank.value = "";
775 blank.textContent = "Select quest…";
776 questSelect.append(blank);
777 for (const quest of questList)
778 {
779 const opt = document.createElement("option");
780 opt.value = quest.questId;
781 opt.textContent = quest.title ? `${quest.title} (${quest.questId})` : quest.questId;
782 if (quest.questId === cond.questId)
783 { opt.selected = true; }
784 questSelect.append(opt);
785 }
786 if (cond.questId && !questList.some((q) => q.questId === cond.questId))
787 {
788 const missing = document.createElement("option");
789 missing.value = cond.questId;
790 missing.textContent = `${cond.questId} (missing)`;
791 missing.selected = true;
792 questSelect.append(missing);
793 }
794 const stepSelect = document.createElement("select");
795 const fillSteps = () =>
796 {
797 const quest = questList.find((q) => q.questId === cond.questId) ?? null;
798 stepSelect.replaceChildren();
799 const steps = quest?.steps ?? [];
800 if (!steps.length)
801 {
802 const empty = document.createElement("option");
803 empty.value = cond.stepId ?? "";
804 empty.textContent = cond.stepId || "No steps";
805 empty.selected = true;
806 stepSelect.append(empty);
807 return;
808 }
809 let matched = false;
810 for (const step of steps)
811 {
812 const opt = document.createElement("option");
813 opt.value = step.stepId;
814 opt.textContent = questStepMenuLabel(step);
815 if (step.stepId === cond.stepId)
816 {
817 opt.selected = true;
818 matched = true;
819 }
820 stepSelect.append(opt);
821 }
822 if (!matched)
823 {
824 if (cond.stepId)
825 {
826 const fallback = document.createElement("option");
827 fallback.value = cond.stepId;
828 fallback.textContent = cond.stepId;
829 fallback.selected = true;
830 stepSelect.append(fallback);
831 }
832 else
833 {
834 cond.stepId = steps[0].stepId;
835 stepSelect.options[0].selected = true;
836 }
837 }
838 };
839 fillSteps();
840 questSelect.addEventListener("change", () =>
841 {
842 cond.questId = questSelect.value;
843 const quest = questList.find((q) => q.questId === cond.questId);
844 cond.stepId = quest?.steps?.[0]?.stepId ?? "";
845 fillSteps();
846 onChanged();
847 });
848 stepSelect.addEventListener("change", () =>
849 {
850 cond.stepId = stepSelect.value;
851 onChanged();
852 });
853 wrap.append(questSelect, stepSelect);
854 return wrap;
855}
856
763/** Compact searchable item picker for hasItem conditions. */
857/** Compact searchable item picker for hasItem conditions. */
764function itemConditionPicker (cond, onPicked)
858function itemConditionPicker (cond, onPicked)
765{
859{
@@ -882,8 +976,8 @@ function defaultCondition (kind)
882 case ConditionKind.inDimension:
976 case ConditionKind.inDimension:
883 case ConditionKind.hasVisitedDimension:
977 case ConditionKind.hasVisitedDimension:
884 return { kind, dimensionId: OVERWORLD_ID };
978 return { kind, dimensionId: OVERWORLD_ID };
885 case ConditionKind.questStepAtLeast:
979 case ConditionKind.hasCompletedStep:
886 return { kind, questId: "", step: 1 };
980 return { kind, questId: "", stepId: "" };
887 case ConditionKind.hpAtLeast:
981 case ConditionKind.hpAtLeast:
888 case ConditionKind.staminaAtLeast:
982 case ConditionKind.staminaAtLeast:
889 return { kind, amount: 1 };
983 return { kind, amount: 1 };
client/src/editor/tileConfigModal.js +6 −2
@@ -1242,7 +1242,9 @@ export function initTileConfigModal ({
1242 1242 itemId: line.itemId,
1243 1243 quantity: Math.max(1, line.quantity | 0)
1244 1244 }));
1245 itemSpawnerWhenDraft = normalizeConditionSet(config.when ?? emptyConditionSet());
1245 itemSpawnerWhenDraft = normalizeConditionSet(config.when ?? emptyConditionSet(), {
1246 quests: typeof getQuests === "function" ? (getQuests() ?? []) : []
1247 });
1246 1248 title.textContent = `Item Spawner · ${ctx.tileX}, ${ctx.tileY}`;
1247 1249 if (socket && MessageType)
1248 1250 {
@@ -1438,7 +1440,9 @@ export function initTileConfigModal ({
1438 1440 {
1439 1441 context = { kind: "door", ...ctx };
1440 1442 const config = ctx.config && typeof ctx.config === "object" ? ctx.config : {};
1441 doorWhenDraft = normalizeConditionSet(config.when ?? config.requirements ?? emptyConditionSet());
1443 doorWhenDraft = normalizeConditionSet(config.when ?? config.requirements ?? emptyConditionSet(), {
1444 quests: typeof getQuests === "function" ? (getQuests() ?? []) : []
1445 });
1442 1446 doorBlockedMessageDraft = String(config.blockedMessage ?? config.denyMessage ?? "").trim();
1443 1447 title.textContent = `Door · ${ctx.tileX}, ${ctx.tileY}`;
1444 1448 if (socket && MessageType)
@@ -1242,7 +1242,9 @@ export function initTileConfigModal ({
1242 itemId: line.itemId,
1242 itemId: line.itemId,
1243 quantity: Math.max(1, line.quantity | 0)
1243 quantity: Math.max(1, line.quantity | 0)
1244 }));
1244 }));
1245 itemSpawnerWhenDraft = normalizeConditionSet(config.when ?? emptyConditionSet());
1245 itemSpawnerWhenDraft = normalizeConditionSet(config.when ?? emptyConditionSet(), {
1246 quests: typeof getQuests === "function" ? (getQuests() ?? []) : []
1247 });
1246 title.textContent = `Item Spawner · ${ctx.tileX}, ${ctx.tileY}`;
1248 title.textContent = `Item Spawner · ${ctx.tileX}, ${ctx.tileY}`;
1247 if (socket && MessageType)
1249 if (socket && MessageType)
1248 {
1250 {
@@ -1438,7 +1440,9 @@ export function initTileConfigModal ({
1438 {
1440 {
1439 context = { kind: "door", ...ctx };
1441 context = { kind: "door", ...ctx };
1440 const config = ctx.config && typeof ctx.config === "object" ? ctx.config : {};
1442 const config = ctx.config && typeof ctx.config === "object" ? ctx.config : {};
1441 doorWhenDraft = normalizeConditionSet(config.when ?? config.requirements ?? emptyConditionSet());
1443 doorWhenDraft = normalizeConditionSet(config.when ?? config.requirements ?? emptyConditionSet(), {
1444 quests: typeof getQuests === "function" ? (getQuests() ?? []) : []
1445 });
1442 doorBlockedMessageDraft = String(config.blockedMessage ?? config.denyMessage ?? "").trim();
1446 doorBlockedMessageDraft = String(config.blockedMessage ?? config.denyMessage ?? "").trim();
1443 title.textContent = `Door · ${ctx.tileX}, ${ctx.tileY}`;
1447 title.textContent = `Door · ${ctx.tileX}, ${ctx.tileY}`;
1444 if (socket && MessageType)
1448 if (socket && MessageType)
server/src/doors/conditionContext.js +26 −3
@@ -8,6 +8,10 @@ import { resolveSkillRequirementLevel } from "../../../shared/combat/combatLevel
8 8 import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
9 9 import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";
10 10 import { doorHasRequirements, doorRequirementsMet } from "../../../shared/world/doorRequirements.js";
11 import {
12 deriveCompletedStepIds,
13 resolveQuestStepId
14 } from "../../../shared/quests/questProgress.js";
11 15 import { BlockType } from "../../../shared/definitions/tiles.js";
12 16 import { tileToChunk, tileToLocal, tileKey } from "../world/coordinates.js";
13 17
@@ -34,15 +38,25 @@ function floorDiv (value, size)
34 38 * Serializable snapshot stored on Component.conditionAccess.
35 39 * @param {import("../persistence/stateDb.js").StateDb} stateDb
36 40 * @param {number} characterId
41 * @param {{ quest?: Function, allQuests?: Function } | null} [questContent]
37 42 */
38 export function buildConditionAccessSnapshot (stateDb, characterId)
43 export function buildConditionAccessSnapshot (stateDb, characterId, questContent = null)
39 44 {
40 45 const questStates = Object.create(null);
41 46 const questProgress = Object.create(null);
47 const questSteps = Object.create(null);
48 for (const def of questContent?.allQuests?.() ?? [])
49 {
50 questSteps[def.questId] = (def.steps ?? []).map((step) => step.stepId);
51 }
42 52 for (const row of stateDb.listQuestStates(characterId))
43 53 {
44 questStates[row.questId] = row.state;
45 questProgress[row.questId] = row.progress ?? {};
54 const def = questContent?.quest?.(row.questId) ?? null;
55 questStates[row.questId] = resolveQuestStepId(def, row.state);
56 questProgress[row.questId] = {
57 ...(row.progress ?? {}),
58 completedStepIds: deriveCompletedStepIds(def, row.state, row.progress)
59 };
46 60 }
47 61 const dialogueHeard = (stateDb.listDialogueHeard(characterId) ?? []).map(
48 62 (row) => `${row.dialogue_id}\0${row.step_id}`
@@ -56,6 +70,7 @@ export function buildConditionAccessSnapshot (stateDb, characterId)
56 70 return {
57 71 questStates,
58 72 questProgress,
73 questSteps,
59 74 dialogueHeard,
60 75 dialogueTriggers,
61 76 visitedDimensions
@@ -84,6 +99,7 @@ export function buildEntityConditionContext (world, entityId)
84 99 const access = world.ecs.get(handle, Component.conditionAccess) ?? {
85 100 questStates: {},
86 101 questProgress: {},
102 questSteps: {},
87 103 dialogueHeard: [],
88 104 dialogueTriggers: [],
89 105 visitedDimensions: []
@@ -93,6 +109,7 @@ export function buildEntityConditionContext (world, entityId)
93 109 const visited = new Set(access.visitedDimensions ?? []);
94 110 const questStates = access.questStates ?? {};
95 111 const questProgress = access.questProgress ?? {};
112 const questSteps = access.questSteps ?? {};
96 113 return {
97 114 tileX,
98 115 tileY,
@@ -105,6 +122,12 @@ export function buildEntityConditionContext (world, entityId)
105 122 maxStamina: stamina?.max ?? 1,
106 123 countItem: (itemId) => countItemInSlots(inventory, itemId | 0),
107 124 questState: (questId) => questStates[String(questId)] ?? "not-started",
125 questSteps: (questId) => questSteps[String(questId)] ?? null,
126 hasCompletedStep: (questId, stepId) =>
127 {
128 const ids = questProgress[String(questId)]?.completedStepIds ?? [];
129 return ids.includes(String(stepId ?? ""));
130 },
108 131 dialogueHeard: (dialogueId, stepId) => heard.has(`${dialogueId}\0${stepId}`),
109 132 dialogueTriggerLatched: (dialogueId, trigger) => triggers.has(`${dialogueId}\0${trigger}`),
110 133 skillLevel: (skillId) => resolveSkillRequirementLevel(skills ?? {}, skillId),
@@ -8,6 +8,10 @@ import { resolveSkillRequirementLevel } from "../../../shared/combat/combatLevel
8import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
8import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
9import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";
9import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";
10import { doorHasRequirements, doorRequirementsMet } from "../../../shared/world/doorRequirements.js";
10import { doorHasRequirements, doorRequirementsMet } from "../../../shared/world/doorRequirements.js";
11import {
12 deriveCompletedStepIds,
13 resolveQuestStepId
14} from "../../../shared/quests/questProgress.js";
11import { BlockType } from "../../../shared/definitions/tiles.js";
15import { BlockType } from "../../../shared/definitions/tiles.js";
12import { tileToChunk, tileToLocal, tileKey } from "../world/coordinates.js";
16import { tileToChunk, tileToLocal, tileKey } from "../world/coordinates.js";
13
17
@@ -34,15 +38,25 @@ function floorDiv (value, size)
34 * Serializable snapshot stored on Component.conditionAccess.
38 * Serializable snapshot stored on Component.conditionAccess.
35 * @param {import("../persistence/stateDb.js").StateDb} stateDb
39 * @param {import("../persistence/stateDb.js").StateDb} stateDb
36 * @param {number} characterId
40 * @param {number} characterId
41 * @param {{ quest?: Function, allQuests?: Function } | null} [questContent]
37 */
42 */
38export function buildConditionAccessSnapshot (stateDb, characterId)
43export function buildConditionAccessSnapshot (stateDb, characterId, questContent = null)
39{
44{
40 const questStates = Object.create(null);
45 const questStates = Object.create(null);
41 const questProgress = Object.create(null);
46 const questProgress = Object.create(null);
47 const questSteps = Object.create(null);
48 for (const def of questContent?.allQuests?.() ?? [])
49 {
50 questSteps[def.questId] = (def.steps ?? []).map((step) => step.stepId);
51 }
42 for (const row of stateDb.listQuestStates(characterId))
52 for (const row of stateDb.listQuestStates(characterId))
43 {
53 {
44 questStates[row.questId] = row.state;
54 const def = questContent?.quest?.(row.questId) ?? null;
45 questProgress[row.questId] = row.progress ?? {};
55 questStates[row.questId] = resolveQuestStepId(def, row.state);
56 questProgress[row.questId] = {
57 ...(row.progress ?? {}),
58 completedStepIds: deriveCompletedStepIds(def, row.state, row.progress)
59 };
46 }
60 }
47 const dialogueHeard = (stateDb.listDialogueHeard(characterId) ?? []).map(
61 const dialogueHeard = (stateDb.listDialogueHeard(characterId) ?? []).map(
48 (row) => `${row.dialogue_id}\0${row.step_id}`
62 (row) => `${row.dialogue_id}\0${row.step_id}`
@@ -56,6 +70,7 @@ export function buildConditionAccessSnapshot (stateDb, characterId)
56 return {
70 return {
57 questStates,
71 questStates,
58 questProgress,
72 questProgress,
73 questSteps,
59 dialogueHeard,
74 dialogueHeard,
60 dialogueTriggers,
75 dialogueTriggers,
61 visitedDimensions
76 visitedDimensions
@@ -84,6 +99,7 @@ export function buildEntityConditionContext (world, entityId)
84 const access = world.ecs.get(handle, Component.conditionAccess) ?? {
99 const access = world.ecs.get(handle, Component.conditionAccess) ?? {
85 questStates: {},
100 questStates: {},
86 questProgress: {},
101 questProgress: {},
102 questSteps: {},
87 dialogueHeard: [],
103 dialogueHeard: [],
88 dialogueTriggers: [],
104 dialogueTriggers: [],
89 visitedDimensions: []
105 visitedDimensions: []
@@ -93,6 +109,7 @@ export function buildEntityConditionContext (world, entityId)
93 const visited = new Set(access.visitedDimensions ?? []);
109 const visited = new Set(access.visitedDimensions ?? []);
94 const questStates = access.questStates ?? {};
110 const questStates = access.questStates ?? {};
95 const questProgress = access.questProgress ?? {};
111 const questProgress = access.questProgress ?? {};
112 const questSteps = access.questSteps ?? {};
96 return {
113 return {
97 tileX,
114 tileX,
98 tileY,
115 tileY,
@@ -105,6 +122,12 @@ export function buildEntityConditionContext (world, entityId)
105 maxStamina: stamina?.max ?? 1,
122 maxStamina: stamina?.max ?? 1,
106 countItem: (itemId) => countItemInSlots(inventory, itemId | 0),
123 countItem: (itemId) => countItemInSlots(inventory, itemId | 0),
107 questState: (questId) => questStates[String(questId)] ?? "not-started",
124 questState: (questId) => questStates[String(questId)] ?? "not-started",
125 questSteps: (questId) => questSteps[String(questId)] ?? null,
126 hasCompletedStep: (questId, stepId) =>
127 {
128 const ids = questProgress[String(questId)]?.completedStepIds ?? [];
129 return ids.includes(String(stepId ?? ""));
130 },
108 dialogueHeard: (dialogueId, stepId) => heard.has(`${dialogueId}\0${stepId}`),
131 dialogueHeard: (dialogueId, stepId) => heard.has(`${dialogueId}\0${stepId}`),
109 dialogueTriggerLatched: (dialogueId, trigger) => triggers.has(`${dialogueId}\0${trigger}`),
132 dialogueTriggerLatched: (dialogueId, trigger) => triggers.has(`${dialogueId}\0${trigger}`),
110 skillLevel: (skillId) => resolveSkillRequirementLevel(skills ?? {}, skillId),
133 skillLevel: (skillId) => resolveSkillRequirementLevel(skills ?? {}, skillId),
server/src/editor/service.js +27 −10
@@ -24,7 +24,11 @@ import {
24 24 diffEquipmentStatBonuses,
25 25 equipmentStatBonusMapsEqual
26 26 } from "../../../shared/definitions/equipmentStatCategories.js";
27 import { normalizeQuestDef, normalizeDialogueTree } from "../../../shared/quests/normalize.js";
27 import {
28 normalizeQuestDef,
29 normalizeDialogueTree,
30 questLookupFromRawDefs
31 } from "../../../shared/quests/normalize.js";
28 32 import {
29 33 OVERWORLD_ID,
30 34 normalizeDimensionId,
@@ -533,10 +537,20 @@ export class EditorService
533 537 return out;
534 538 }
535 539
540 #questConditionLookup (extraRaw = null)
541 {
542 const revisionId = this.worldDb.getEditorRevisionId();
543 const raws = this.worldDb.listQuestDefs(revisionId);
544 if (extraRaw)
545 { raws.push(extraRaw); }
546 return questLookupFromRawDefs(raws);
547 }
548
536 549 loadQuests ()
537 550 {
538 551 const revisionId = this.worldDb.getEditorRevisionId();
539 const quests = this.worldDb.listQuestDefs(revisionId).map((raw) => normalizeQuestDef(raw));
552 const lookup = this.#questConditionLookup();
553 const quests = this.worldDb.listQuestDefs(revisionId).map((raw) => normalizeQuestDef(raw, lookup));
540 554 return {
541 555 revisionId,
542 556 pendingRevisionId: this.worldDb.getPendingRevisionId(),
@@ -549,10 +563,11 @@ export class EditorService
549 563
550 564 saveQuest (raw, editorAdminId)
551 565 {
552 const def = normalizeQuestDef(raw);
566 const lookup = this.#questConditionLookup(raw);
567 const def = normalizeQuestDef(raw, lookup);
553 568 const revisionId = this.worldDb.getEditorRevisionId();
554 569 const previousRaw = this.worldDb.getQuestDef(revisionId, def.questId);
555 const previous = previousRaw ? normalizeQuestDef(previousRaw) : null;
570 const previous = previousRaw ? normalizeQuestDef(previousRaw, lookup) : null;
556 571 const bullets = diffQuests(previous, def);
557 572 const pendingId = this.worldDb.ensurePendingRevision(editorAdminId);
558 573 this.worldDb.saveQuestDef(pendingId, def);
@@ -570,7 +585,7 @@ export class EditorService
570 585 this.worldDb.deleteQuestDef(pendingId, id);
571 586 if (previousRaw)
572 587 {
573 const previous = normalizeQuestDef(previousRaw);
588 const previous = normalizeQuestDef(previousRaw, this.#questConditionLookup());
574 589 this.worldDb.appendQuestChangelog(id, pendingId, editorAdminId, [
575 590 `Quest "${previous.title}" (${id}) deleted.`
576 591 ]);
@@ -581,7 +596,8 @@ export class EditorService
581 596 loadDialogues ()
582 597 {
583 598 const revisionId = this.worldDb.getEditorRevisionId();
584 const trees = this.worldDb.listDialogueTrees(revisionId).map((raw) => normalizeDialogueTree(raw));
599 const lookup = this.#questConditionLookup();
600 const trees = this.worldDb.listDialogueTrees(revisionId).map((raw) => normalizeDialogueTree(raw, lookup));
585 601 const assignmentCounts = this.#countDialogueAssignments(revisionId);
586 602 return {
587 603 revisionId,
@@ -597,10 +613,11 @@ export class EditorService
597 613
598 614 saveDialogue (raw, editorAdminId)
599 615 {
600 const tree = normalizeDialogueTree(raw);
616 const lookup = this.#questConditionLookup();
617 const tree = normalizeDialogueTree(raw, lookup);
601 618 const revisionId = this.worldDb.getEditorRevisionId();
602 619 const previousRaw = this.worldDb.getDialogueTree(revisionId, tree.dialogueId);
603 const previous = previousRaw ? normalizeDialogueTree(previousRaw) : null;
620 const previous = previousRaw ? normalizeDialogueTree(previousRaw, lookup) : null;
604 621 const assignmentCounts = this.#countDialogueAssignments(revisionId);
605 622 const assigned = assignmentCounts.get(tree.dialogueId) ?? 0;
606 623 if (tree.unique && assigned > 1)
@@ -643,7 +660,7 @@ export class EditorService
643 660 this.worldDb.deleteDialogueTree(pendingId, id);
644 661 if (previousRaw)
645 662 {
646 const previous = normalizeDialogueTree(previousRaw);
663 const previous = normalizeDialogueTree(previousRaw, this.#questConditionLookup());
647 664 this.worldDb.appendDialogueChangelog(id, pendingId, editorAdminId, [
648 665 `Dialogue "${previous.label}" (${id}) deleted.`
649 666 ]);
@@ -659,7 +676,7 @@ export class EditorService
659 676 const trees = new Map(
660 677 this.worldDb.listDialogueTrees(revisionId).map((raw) =>
661 678 {
662 const tree = normalizeDialogueTree(raw);
679 const tree = normalizeDialogueTree(raw, this.#questConditionLookup());
663 680 return [tree.dialogueId, tree];
664 681 })
665 682 );
@@ -24,7 +24,11 @@ import {
24 diffEquipmentStatBonuses,
24 diffEquipmentStatBonuses,
25 equipmentStatBonusMapsEqual
25 equipmentStatBonusMapsEqual
26} from "../../../shared/definitions/equipmentStatCategories.js";
26} from "../../../shared/definitions/equipmentStatCategories.js";
27import { normalizeQuestDef, normalizeDialogueTree } from "../../../shared/quests/normalize.js";
27import {
28 normalizeQuestDef,
29 normalizeDialogueTree,
30 questLookupFromRawDefs
31} from "../../../shared/quests/normalize.js";
28import {
32import {
29 OVERWORLD_ID,
33 OVERWORLD_ID,
30 normalizeDimensionId,
34 normalizeDimensionId,
@@ -533,10 +537,20 @@ export class EditorService
533 return out;
537 return out;
534 }
538 }
535
539
540 #questConditionLookup (extraRaw = null)
541 {
542 const revisionId = this.worldDb.getEditorRevisionId();
543 const raws = this.worldDb.listQuestDefs(revisionId);
544 if (extraRaw)
545 { raws.push(extraRaw); }
546 return questLookupFromRawDefs(raws);
547 }
548
536 loadQuests ()
549 loadQuests ()
537 {
550 {
538 const revisionId = this.worldDb.getEditorRevisionId();
551 const revisionId = this.worldDb.getEditorRevisionId();
539 const quests = this.worldDb.listQuestDefs(revisionId).map((raw) => normalizeQuestDef(raw));
552 const lookup = this.#questConditionLookup();
553 const quests = this.worldDb.listQuestDefs(revisionId).map((raw) => normalizeQuestDef(raw, lookup));
540 return {
554 return {
541 revisionId,
555 revisionId,
542 pendingRevisionId: this.worldDb.getPendingRevisionId(),
556 pendingRevisionId: this.worldDb.getPendingRevisionId(),
@@ -549,10 +563,11 @@ export class EditorService
549
563
550 saveQuest (raw, editorAdminId)
564 saveQuest (raw, editorAdminId)
551 {
565 {
552 const def = normalizeQuestDef(raw);
566 const lookup = this.#questConditionLookup(raw);
567 const def = normalizeQuestDef(raw, lookup);
553 const revisionId = this.worldDb.getEditorRevisionId();
568 const revisionId = this.worldDb.getEditorRevisionId();
554 const previousRaw = this.worldDb.getQuestDef(revisionId, def.questId);
569 const previousRaw = this.worldDb.getQuestDef(revisionId, def.questId);
555 const previous = previousRaw ? normalizeQuestDef(previousRaw) : null;
570 const previous = previousRaw ? normalizeQuestDef(previousRaw, lookup) : null;
556 const bullets = diffQuests(previous, def);
571 const bullets = diffQuests(previous, def);
557 const pendingId = this.worldDb.ensurePendingRevision(editorAdminId);
572 const pendingId = this.worldDb.ensurePendingRevision(editorAdminId);
558 this.worldDb.saveQuestDef(pendingId, def);
573 this.worldDb.saveQuestDef(pendingId, def);
@@ -570,7 +585,7 @@ export class EditorService
570 this.worldDb.deleteQuestDef(pendingId, id);
585 this.worldDb.deleteQuestDef(pendingId, id);
571 if (previousRaw)
586 if (previousRaw)
572 {
587 {
573 const previous = normalizeQuestDef(previousRaw);
588 const previous = normalizeQuestDef(previousRaw, this.#questConditionLookup());
574 this.worldDb.appendQuestChangelog(id, pendingId, editorAdminId, [
589 this.worldDb.appendQuestChangelog(id, pendingId, editorAdminId, [
575 `Quest "${previous.title}" (${id}) deleted.`
590 `Quest "${previous.title}" (${id}) deleted.`
576 ]);
591 ]);
@@ -581,7 +596,8 @@ export class EditorService
581 loadDialogues ()
596 loadDialogues ()
582 {
597 {
583 const revisionId = this.worldDb.getEditorRevisionId();
598 const revisionId = this.worldDb.getEditorRevisionId();
584 const trees = this.worldDb.listDialogueTrees(revisionId).map((raw) => normalizeDialogueTree(raw));
599 const lookup = this.#questConditionLookup();
600 const trees = this.worldDb.listDialogueTrees(revisionId).map((raw) => normalizeDialogueTree(raw, lookup));
585 const assignmentCounts = this.#countDialogueAssignments(revisionId);
601 const assignmentCounts = this.#countDialogueAssignments(revisionId);
586 return {
602 return {
587 revisionId,
603 revisionId,
@@ -597,10 +613,11 @@ export class EditorService
597
613
598 saveDialogue (raw, editorAdminId)
614 saveDialogue (raw, editorAdminId)
599 {
615 {
600 const tree = normalizeDialogueTree(raw);
616 const lookup = this.#questConditionLookup();
617 const tree = normalizeDialogueTree(raw, lookup);
601 const revisionId = this.worldDb.getEditorRevisionId();
618 const revisionId = this.worldDb.getEditorRevisionId();
602 const previousRaw = this.worldDb.getDialogueTree(revisionId, tree.dialogueId);
619 const previousRaw = this.worldDb.getDialogueTree(revisionId, tree.dialogueId);
603 const previous = previousRaw ? normalizeDialogueTree(previousRaw) : null;
620 const previous = previousRaw ? normalizeDialogueTree(previousRaw, lookup) : null;
604 const assignmentCounts = this.#countDialogueAssignments(revisionId);
621 const assignmentCounts = this.#countDialogueAssignments(revisionId);
605 const assigned = assignmentCounts.get(tree.dialogueId) ?? 0;
622 const assigned = assignmentCounts.get(tree.dialogueId) ?? 0;
606 if (tree.unique && assigned > 1)
623 if (tree.unique && assigned > 1)
@@ -643,7 +660,7 @@ export class EditorService
643 this.worldDb.deleteDialogueTree(pendingId, id);
660 this.worldDb.deleteDialogueTree(pendingId, id);
644 if (previousRaw)
661 if (previousRaw)
645 {
662 {
646 const previous = normalizeDialogueTree(previousRaw);
663 const previous = normalizeDialogueTree(previousRaw, this.#questConditionLookup());
647 this.worldDb.appendDialogueChangelog(id, pendingId, editorAdminId, [
664 this.worldDb.appendDialogueChangelog(id, pendingId, editorAdminId, [
648 `Dialogue "${previous.label}" (${id}) deleted.`
665 `Dialogue "${previous.label}" (${id}) deleted.`
649 ]);
666 ]);
@@ -659,7 +676,7 @@ export class EditorService
659 const trees = new Map(
676 const trees = new Map(
660 this.worldDb.listDialogueTrees(revisionId).map((raw) =>
677 this.worldDb.listDialogueTrees(revisionId).map((raw) =>
661 {
678 {
662 const tree = normalizeDialogueTree(raw);
679 const tree = normalizeDialogueTree(raw, this.#questConditionLookup());
663 return [tree.dialogueId, tree];
680 return [tree.dialogueId, tree];
664 })
681 })
665 );
682 );
server/src/persistence/stateDb.js +4 −9
@@ -11,6 +11,7 @@ import {
11 11 bountyDecayDayKey,
12 12 bountyDecayDaysBetween
13 13 } from "../../../shared/bounty/pricing.js";
14 import { parseStoredQuestState, serializeQuestState } from "../../../shared/quests/questProgress.js";
14 15
15 16 const STATE_SCHEMA = `
16 17 CREATE TABLE IF NOT EXISTS accounts (
@@ -974,11 +975,8 @@ export class StateDatabase
974 975 if (!row)
975 976 { return { state: "not-started", progress: {}, startedAt: null, completedAt: null }; }
976 977 const progress = JSON.parse(row.progress_blob || "{}");
977 let state = row.state_value;
978 if (state !== "not-started" && state !== "completed")
979 { state = Number(state) | 0; }
980 978 return {
981 state,
979 state: parseStoredQuestState(row.state_value),
982 980 progress,
983 981 startedAt: row.started_at ?? null,
984 982 completedAt: row.completed_at ?? null
@@ -993,12 +991,9 @@ export class StateDatabase
993 991 WHERE character_id = ?
994 992 `).all(characterId | 0).map((row) =>
995 993 {
996 let state = row.state_value;
997 if (state !== "not-started" && state !== "completed")
998 { state = Number(state) | 0; }
999 994 return {
1000 995 questId: row.quest_id,
1001 state,
996 state: parseStoredQuestState(row.state_value),
1002 997 progress: JSON.parse(row.progress_blob || "{}"),
1003 998 startedAt: row.started_at ?? null,
1004 999 completedAt: row.completed_at ?? null
@@ -1008,7 +1003,7 @@ export class StateDatabase
1008 1003
1009 1004 saveQuestState (characterId, questId, state, progress = {}, startedAt = null, completedAt = null)
1010 1005 {
1011 const stateValue = state === "not-started" || state === "completed" ? state : String(state | 0);
1006 const stateValue = serializeQuestState(state);
1012 1007 this.db.prepare(`
1013 1008 INSERT INTO character_quest_state
1014 1009 (character_id, quest_id, state_value, progress_blob, started_at, completed_at)
@@ -11,6 +11,7 @@ import {
11 bountyDecayDayKey,
11 bountyDecayDayKey,
12 bountyDecayDaysBetween
12 bountyDecayDaysBetween
13} from "../../../shared/bounty/pricing.js";
13} from "../../../shared/bounty/pricing.js";
14import { parseStoredQuestState, serializeQuestState } from "../../../shared/quests/questProgress.js";
14
15
15const STATE_SCHEMA = `
16const STATE_SCHEMA = `
16CREATE TABLE IF NOT EXISTS accounts (
17CREATE TABLE IF NOT EXISTS accounts (
@@ -974,11 +975,8 @@ export class StateDatabase
974 if (!row)
975 if (!row)
975 { return { state: "not-started", progress: {}, startedAt: null, completedAt: null }; }
976 { return { state: "not-started", progress: {}, startedAt: null, completedAt: null }; }
976 const progress = JSON.parse(row.progress_blob || "{}");
977 const progress = JSON.parse(row.progress_blob || "{}");
977 let state = row.state_value;
978 if (state !== "not-started" && state !== "completed")
979 { state = Number(state) | 0; }
980 return {
978 return {
981 state,
979 state: parseStoredQuestState(row.state_value),
982 progress,
980 progress,
983 startedAt: row.started_at ?? null,
981 startedAt: row.started_at ?? null,
984 completedAt: row.completed_at ?? null
982 completedAt: row.completed_at ?? null
@@ -993,12 +991,9 @@ export class StateDatabase
993 WHERE character_id = ?
991 WHERE character_id = ?
994 `).all(characterId | 0).map((row) =>
992 `).all(characterId | 0).map((row) =>
995 {
993 {
996 let state = row.state_value;
997 if (state !== "not-started" && state !== "completed")
998 { state = Number(state) | 0; }
999 return {
994 return {
1000 questId: row.quest_id,
995 questId: row.quest_id,
1001 state,
996 state: parseStoredQuestState(row.state_value),
1002 progress: JSON.parse(row.progress_blob || "{}"),
997 progress: JSON.parse(row.progress_blob || "{}"),
1003 startedAt: row.started_at ?? null,
998 startedAt: row.started_at ?? null,
1004 completedAt: row.completed_at ?? null
999 completedAt: row.completed_at ?? null
@@ -1008,7 +1003,7 @@ export class StateDatabase
1008
1003
1009 saveQuestState (characterId, questId, state, progress = {}, startedAt = null, completedAt = null)
1004 saveQuestState (characterId, questId, state, progress = {}, startedAt = null, completedAt = null)
1010 {
1005 {
1011 const stateValue = state === "not-started" || state === "completed" ? state : String(state | 0);
1006 const stateValue = serializeQuestState(state);
1012 this.db.prepare(`
1007 this.db.prepare(`
1013 INSERT INTO character_quest_state
1008 INSERT INTO character_quest_state
1014 (character_id, quest_id, state_value, progress_blob, started_at, completed_at)
1009 (character_id, quest_id, state_value, progress_blob, started_at, completed_at)
server/src/quests/contentCache.js +10 −4
@@ -1,4 +1,8 @@
1 import { normalizeQuestDef, normalizeDialogueTree } from "../../../shared/quests/normalize.js";
1 import {
2 normalizeQuestDef,
3 normalizeDialogueTree,
4 questLookupFromRawDefs
5 } from "../../../shared/quests/normalize.js";
2 6
3 7 /** Active-revision quest + dialogue defs for the live sim. */
4 8 export class QuestContentCache
@@ -18,14 +22,16 @@ export class QuestContentCache
18 22 this.dialogues = new Map();
19 23 if (revisionId == null)
20 24 { return; }
21 for (const raw of this.worldDb.listQuestDefs(revisionId))
25 const questRaws = this.worldDb.listQuestDefs(revisionId);
26 const questLookup = questLookupFromRawDefs(questRaws);
27 for (const raw of questRaws)
22 28 {
23 const def = normalizeQuestDef(raw);
29 const def = normalizeQuestDef(raw, questLookup);
24 30 this.quests.set(def.questId, def);
25 31 }
26 32 for (const raw of this.worldDb.listDialogueTrees(revisionId))
27 33 {
28 const tree = normalizeDialogueTree(raw);
34 const tree = normalizeDialogueTree(raw, questLookup);
29 35 this.dialogues.set(tree.dialogueId, tree);
30 36 }
31 37 }
@@ -1,4 +1,8 @@
1import { normalizeQuestDef, normalizeDialogueTree } from "../../../shared/quests/normalize.js";
1import {
2 normalizeQuestDef,
3 normalizeDialogueTree,
4 questLookupFromRawDefs
5} from "../../../shared/quests/normalize.js";
2
6
3/** Active-revision quest + dialogue defs for the live sim. */
7/** Active-revision quest + dialogue defs for the live sim. */
4export class QuestContentCache
8export class QuestContentCache
@@ -18,14 +22,16 @@ export class QuestContentCache
18 this.dialogues = new Map();
22 this.dialogues = new Map();
19 if (revisionId == null)
23 if (revisionId == null)
20 { return; }
24 { return; }
21 for (const raw of this.worldDb.listQuestDefs(revisionId))
25 const questRaws = this.worldDb.listQuestDefs(revisionId);
26 const questLookup = questLookupFromRawDefs(questRaws);
27 for (const raw of questRaws)
22 {
28 {
23 const def = normalizeQuestDef(raw);
29 const def = normalizeQuestDef(raw, questLookup);
24 this.quests.set(def.questId, def);
30 this.quests.set(def.questId, def);
25 }
31 }
26 for (const raw of this.worldDb.listDialogueTrees(revisionId))
32 for (const raw of this.worldDb.listDialogueTrees(revisionId))
27 {
33 {
28 const tree = normalizeDialogueTree(raw);
34 const tree = normalizeDialogueTree(raw, questLookup);
29 this.dialogues.set(tree.dialogueId, tree);
35 this.dialogues.set(tree.dialogueId, tree);
30 }
36 }
31 }
37 }
server/src/quests/runtime.js +275 −110
@@ -1,4 +1,10 @@
1 1 import { evaluateConditionSet, EffectKind } from "../../../shared/quests/conditions.js";
2 import {
3 deriveCompletedStepIds,
4 isActiveQuestState,
5 rememberCompletedStep,
6 resolveQuestStepId
7 } from "../../../shared/quests/questProgress.js";
2 8 import { normalizeInitialQuests } from "../../../shared/quests/initialQuests.js";
3 9 import {
4 10 countableObjectiveProgress,
@@ -72,8 +78,12 @@ export class QuestRuntime
72 78 });
73 79 continue;
74 80 }
75 const stepIndex = typeof row.state === "number" ? row.state : null;
76 const stepDef = stepIndex != null ? def.steps[stepIndex - 1] : null;
81 const stepDef = isActiveQuestState(row.state)
82 ? activeQuestStep(def, row.state)
83 : null;
84 const resolvedState = isActiveQuestState(row.state)
85 ? (resolveQuestStepId(def, row.state) ?? row.state)
86 : row.state;
77 87 const completedObjectiveIds = row.progress?.completedObjectiveIds ?? [];
78 88 const ctx = stepDef
79 89 ? this.buildConditionContext(characterId, playerView, row.questId)
@@ -82,25 +92,14 @@ export class QuestRuntime
82 92 questId: def.questId,
83 93 title: def.title,
84 94 orphaned: false,
85 state: row.state,
95 state: resolvedState,
86 96 description: def.description,
87 97 step: stepDef
88 98 ? {
89 99 stepId: stepDef.stepId,
90 100 title: stepDef.title,
91 101 description: stepDef.description,
92 objectives: stepDef.objectives.map((obj) =>
93 {
94 const done = completedObjectiveIds.includes(obj.objectiveId);
95 const progress = countableObjectiveProgress(obj.when, ctx);
96 return {
97 objectiveId: obj.objectiveId,
98 text: obj.text,
99 done,
100 current: progress?.current ?? null,
101 required: progress?.required ?? null
102 };
103 })
102 objectives: publicStepLines(stepDef, completedObjectiveIds, ctx)
104 103 }
105 104 : null,
106 105 journal: this.stateDb.listQuestJournal(characterId, def.questId).map(journalPublic)
@@ -178,7 +177,26 @@ export class QuestRuntime
178 177 stamina: playerView?.stamina ?? 0,
179 178 maxStamina: playerView?.maxStamina ?? 1,
180 179 countItem: (itemId) => countItemInSlots(inventory, itemId | 0),
181 questState: (questId) => this.stateDb.getQuestState(characterId, questId).state,
180 questState: (questId) =>
181 {
182 const row = this.stateDb.getQuestState(characterId, questId);
183 return resolveQuestStepId(this.content.quest(questId), row.state);
184 },
185 questSteps: (questId) =>
186 {
187 const def = this.content.quest(questId);
188 return def ? def.steps.map((step) => step.stepId) : null;
189 },
190 hasCompletedStep: (questId, stepId) =>
191 {
192 const row = this.stateDb.getQuestState(characterId, questId);
193 const ids = deriveCompletedStepIds(
194 this.content.quest(questId),
195 row.state,
196 row.progress
197 );
198 return ids.includes(String(stepId ?? ""));
199 },
182 200 dialogueHeard: (dialogueId, stepId) => this.stateDb.isDialogueHeard(characterId, dialogueId, stepId),
183 201 dialogueTriggerLatched: (dialogueId, trigger) =>
184 202 this.stateDb.isDialogueTriggerLatched(characterId, dialogueId, trigger),
@@ -670,12 +688,15 @@ export class QuestRuntime
670 688 const current = this.stateDb.getQuestState(characterId, questId);
671 689 if (current.state !== "not-started")
672 690 { return; }
673 this.stateDb.saveQuestState(characterId, questId, 1, {
691 const first = def.steps[0];
692 this.stateDb.saveQuestState(characterId, questId, first.stepId, {
674 693 completedObjectiveIds: [],
675 694 counters: {},
676 interacts: {}
695 interacts: {},
696 completedStepIds: [],
697 progressFingerprint: ""
677 698 }, Date.now(), null);
678 this.#applyEffects(characterId, def.steps[0]?.onEnter, playerView, events);
699 this.#applyEffects(characterId, first.onEnter, playerView, events);
679 700 events.push({ type: "questsDirty", characterId });
680 701 this.#reevaluateQuests(characterId, playerView, events);
681 702 }
@@ -842,102 +863,192 @@ export class QuestRuntime
842 863
843 864 #reevaluateQuests (characterId, playerView, events)
844 865 {
845 const states = this.stateDb.listQuestStates(characterId)
846 .filter((row) => typeof row.state === "number");
847 for (const row of states)
866 const outer = this._transitionedQuestIds == null;
867 if (outer)
868 { this._transitionedQuestIds = new Set(); }
869 try
848 870 {
849 const def = this.content.quest(row.questId);
850 if (!def)
851 { continue; }
852 const stepDef = def.steps[row.state - 1];
853 if (!stepDef)
854 { continue; }
855 const ctx = this.buildConditionContext(characterId, playerView, row.questId);
856 const completed = new Set(row.progress?.completedObjectiveIds ?? []);
857 const newlyDone = [];
858 let changed = false;
859 for (const obj of stepDef.objectives)
871 const states = this.stateDb.listQuestStates(characterId)
872 .filter((row) => isActiveQuestState(row.state));
873 for (const row of states)
860 874 {
861 if (completed.has(obj.objectiveId))
875 if (this._transitionedQuestIds.has(row.questId))
862 876 { continue; }
863 if (evaluateConditionSet(obj.when, ctx))
864 {
865 completed.add(obj.objectiveId);
866 newlyDone.push(obj);
867 changed = true;
868 }
877 const def = this.content.quest(row.questId);
878 if (!def)
879 { continue; }
880 const stepDef = activeQuestStep(def, row.state);
881 if (!stepDef)
882 { continue; }
883 const ctx = this.buildConditionContext(characterId, playerView, row.questId);
884 if (stepDef.exit?.kind === "branches")
885 { this.#advanceBranchStep(characterId, def, row, stepDef, ctx, playerView, events); }
886 else
887 { this.#advanceLinearStep(characterId, def, row, stepDef, ctx, playerView, events); }
869 888 }
870 const fingerprint = objectiveProgressFingerprint(stepDef.objectives, ctx);
871 const progressChanged = fingerprint !== (row.progress?.progressFingerprint ?? "");
872 if (!changed && !progressChanged)
889 }
890 finally
891 {
892 if (outer)
893 { this._transitionedQuestIds = null; }
894 }
895 }
896
897 #advanceLinearStep (characterId, def, row, stepDef, ctx, playerView, events)
898 {
899 const completed = new Set(row.progress?.completedObjectiveIds ?? []);
900 const newlyDone = [];
901 let changed = false;
902 for (const obj of stepDef.objectives)
903 {
904 if (completed.has(obj.objectiveId))
873 905 { continue; }
874 for (const obj of newlyDone)
875 {
876 events.push({
877 type: "questObjectiveComplete",
878 questId: row.questId,
879 objectiveId: obj.objectiveId,
880 text: obj.text || "Objective"
881 });
882 }
883 const progress = {
884 ...row.progress,
885 completedObjectiveIds: [...completed],
886 progressFingerprint: fingerprint
887 };
888 const allDone = stepDef.objectives.every((obj) => completed.has(obj.objectiveId));
889 if (!allDone)
906 if (evaluateConditionSet(obj.when, ctx))
890 907 {
891 this.stateDb.saveQuestState(characterId, row.questId, row.state, progress, row.startedAt, row.completedAt);
892 events.push({ type: "questsDirty", characterId });
893 continue;
908 completed.add(obj.objectiveId);
909 newlyDone.push(obj);
910 changed = true;
894 911 }
895 if (!changed)
896 {
897 // Progress-only update while already fully complete (should not happen).
898 this.stateDb.saveQuestState(characterId, row.questId, row.state, progress, row.startedAt, row.completedAt);
899 events.push({ type: "questsDirty", characterId });
900 continue;
901 }
902 this.#applyEffects(characterId, stepDef.onComplete, playerView, events);
903 const journal = this.stateDb.appendQuestJournal(
904 characterId,
905 row.questId,
906 stepDef.stepId,
907 stepDef.completionJournalText
908 );
909 const nextIndex = row.state + 1;
910 if (nextIndex > def.steps.length)
912 }
913 const fingerprint = objectiveProgressFingerprint(stepDef.objectives, ctx);
914 const progressChanged = fingerprint !== (row.progress?.progressFingerprint ?? "");
915 const progress = {
916 ...row.progress,
917 completedObjectiveIds: [...completed],
918 progressFingerprint: fingerprint,
919 completedStepIds: deriveCompletedStepIds(def, row.state, row.progress)
920 };
921 const allDone = stepDef.objectives.every((obj) => completed.has(obj.objectiveId));
922 for (const obj of newlyDone)
923 {
924 events.push({
925 type: "questObjectiveComplete",
926 questId: row.questId,
927 objectiveId: obj.objectiveId,
928 text: obj.text || "Objective"
929 });
930 }
931 if (allDone && this.#leaveStep(characterId, def, row, stepDef, null, playerView, events))
932 { return; }
933 if (!changed && !progressChanged)
934 { return; }
935 this.#saveActiveProgress(characterId, def, row, progress);
936 events.push({ type: "questsDirty", characterId });
937 }
938
939 #advanceBranchStep (characterId, def, row, stepDef, ctx, playerView, events)
940 {
941 const branches = stepDef.exit?.branches ?? [];
942 let matched = null;
943 for (const branch of branches)
944 {
945 if (evaluateConditionSet(branch.when, ctx))
911 946 {
912 const summary = this.#grantQuestCompletionRewards(characterId, def, playerView, events);
913 this.stateDb.saveQuestState(characterId, row.questId, "completed", progress, row.startedAt, Date.now());
914 events.push({
915 type: "questComplete",
916 questId: row.questId,
917 title: def.title,
918 xp: summary.xp,
919 items: summary.bagItems
920 });
947 matched = branch;
948 break;
921 949 }
922 else
950 }
951 const fingerprint = objectiveProgressFingerprint(branchProgressRows(branches), ctx);
952 const progressChanged = fingerprint !== (row.progress?.progressFingerprint ?? "");
953 if (!matched)
954 {
955 if (!progressChanged)
956 { return; }
957 this.#saveActiveProgress(characterId, def, row, {
958 ...row.progress,
959 progressFingerprint: fingerprint,
960 completedStepIds: deriveCompletedStepIds(def, row.state, row.progress)
961 });
962 events.push({ type: "questsDirty", characterId });
963 return;
964 }
965 this.#leaveStep(characterId, def, row, stepDef, matched, playerView, events);
966 }
967
968 /**
969 * One hop away from the current step. Returns false when a continue/branch
970 * names a step that does not exist (stay put; retry next evaluation).
971 * Empty nextStepId completes the quest. Quest-wide rewards fire only here.
972 */
973 #leaveStep (characterId, def, row, stepDef, branch, playerView, events)
974 {
975 const exit = stepDef.exit ?? { kind: "complete" };
976 let destination = null;
977 if (branch)
978 {
979 if (branch.nextStepId)
923 980 {
924 const nextStep = def.steps[nextIndex - 1];
925 this.stateDb.saveQuestState(characterId, row.questId, nextIndex, {
926 completedObjectiveIds: [],
927 counters: {},
928 interacts: {},
929 progressFingerprint: ""
930 }, row.startedAt, null);
931 this.#applyEffects(characterId, nextStep?.onEnter, playerView, events);
932 events.push({
933 type: "questStepComplete",
934 questId: row.questId,
935 title: def.title,
936 journalText: journal?.text ?? null
937 });
981 destination = def.steps.find((step) => step.stepId === branch.nextStepId) ?? null;
982 if (!destination)
983 { return false; }
938 984 }
939 events.push({ type: "questsDirty", characterId });
940 985 }
986 else if (exit.kind === "continue" && exit.nextStepId)
987 {
988 destination = def.steps.find((step) => step.stepId === exit.nextStepId) ?? null;
989 if (!destination)
990 { return false; }
991 }
992 this._transitionedQuestIds?.add(row.questId);
993 const completedStepIds = rememberCompletedStep(
994 deriveCompletedStepIds(def, row.state, row.progress),
995 stepDef.stepId
996 );
997 this.#applyEffects(characterId, stepDef.onComplete, playerView, events);
998 if (branch)
999 { this.#applyEffects(characterId, branch.effects, playerView, events); }
1000 const journal = this.stateDb.appendQuestJournal(
1001 characterId,
1002 row.questId,
1003 stepDef.stepId,
1004 stepDef.completionJournalText
1005 );
1006 if (!destination)
1007 {
1008 const summary = this.#grantQuestCompletionRewards(characterId, def, playerView, events);
1009 this.stateDb.saveQuestState(characterId, row.questId, "completed", {
1010 ...row.progress,
1011 completedStepIds
1012 }, row.startedAt, Date.now());
1013 events.push({
1014 type: "questComplete",
1015 questId: row.questId,
1016 title: def.title,
1017 xp: summary.xp,
1018 items: summary.bagItems
1019 });
1020 }
1021 else
1022 {
1023 this.stateDb.saveQuestState(characterId, row.questId, destination.stepId, {
1024 completedObjectiveIds: [],
1025 counters: {},
1026 interacts: {},
1027 progressFingerprint: "",
1028 completedStepIds
1029 }, row.startedAt, null);
1030 this.#applyEffects(characterId, destination.onEnter, playerView, events);
1031 events.push({
1032 type: "questStepComplete",
1033 questId: row.questId,
1034 title: def.title,
1035 journalText: journal?.text ?? null
1036 });
1037 }
1038 events.push({ type: "questsDirty", characterId });
1039 return true;
1040 }
1041
1042 #saveActiveProgress (characterId, def, row, progress)
1043 {
1044 const stepId = resolveQuestStepId(def, row.state) ?? row.state;
1045 const completedStepIds = Array.isArray(progress?.completedStepIds)
1046 ? progress.completedStepIds
1047 : deriveCompletedStepIds(def, row.state, row.progress);
1048 this.stateDb.saveQuestState(characterId, row.questId, stepId, {
1049 ...progress,
1050 completedStepIds
1051 }, row.startedAt, row.completedAt);
941 1052 }
942 1053
943 1054 noteKill (characterId, { mobTypeId, spawnerId })
@@ -945,18 +1056,18 @@ export class QuestRuntime
945 1056 const events = [];
946 1057 const playerView = this.playerViewFor(characterId);
947 1058 const states = this.stateDb.listQuestStates(characterId)
948 .filter((row) => typeof row.state === "number");
1059 .filter((row) => isActiveQuestState(row.state));
949 1060 for (const row of states)
950 1061 {
951 1062 const def = this.content.quest(row.questId);
952 const stepDef = def?.steps[row.state - 1];
1063 const stepDef = def ? activeQuestStep(def, row.state) : null;
953 1064 if (!stepDef)
954 1065 { continue; }
955 1066 let changed = false;
956 1067 const counters = { ...(row.progress?.counters ?? {}) };
957 for (const obj of stepDef.objectives)
1068 for (const set of stepConditionSets(stepDef))
958 1069 {
959 for (const clause of obj.when?.all ?? [])
1070 for (const clause of set?.all ?? [])
960 1071 {
961 1072 const c = clause.condition;
962 1073 if (!matchesKillCondition(c, mobTypeId, spawnerId))
@@ -968,16 +1079,70 @@ export class QuestRuntime
968 1079 }
969 1080 if (!changed)
970 1081 { continue; }
971 this.stateDb.saveQuestState(characterId, row.questId, row.state, {
1082 this.#saveActiveProgress(characterId, def, row, {
972 1083 ...row.progress,
973 counters
974 }, row.startedAt, row.completedAt);
1084 counters,
1085 completedStepIds: deriveCompletedStepIds(def, row.state, row.progress)
1086 });
975 1087 }
976 1088 this.#reevaluateQuests(characterId, playerView, events);
977 1089 return events;
978 1090 }
979 1091 }
980 1092
1093 function activeQuestStep (def, state)
1094 {
1095 const stepId = resolveQuestStepId(def, state);
1096 if (!stepId || stepId === "not-started" || stepId === "completed")
1097 { return null; }
1098 return def.steps.find((step) => step.stepId === stepId) ?? null;
1099 }
1100
1101 function stepConditionSets (stepDef)
1102 {
1103 if (stepDef?.exit?.kind === "branches")
1104 { return (stepDef.exit.branches ?? []).map((branch) => branch.when); }
1105 return (stepDef?.objectives ?? []).map((obj) => obj.when);
1106 }
1107
1108 function branchProgressRows (branches)
1109 {
1110 return (branches ?? []).map((branch, index) => ({
1111 objectiveId: `branch-${index}`,
1112 when: branch.when
1113 }));
1114 }
1115
1116 function publicStepLines (stepDef, completedObjectiveIds, ctx)
1117 {
1118 if (stepDef.exit?.kind === "branches")
1119 {
1120 return (stepDef.exit.branches ?? []).map((branch, index) =>
1121 {
1122 const progress = countableObjectiveProgress(branch.when, ctx);
1123 return {
1124 objectiveId: `branch-${index}`,
1125 text: branch.text || branch.label || `Path ${index + 1}`,
1126 done: false,
1127 current: progress?.current ?? null,
1128 required: progress?.required ?? null
1129 };
1130 });
1131 }
1132 return (stepDef.objectives ?? []).map((obj) =>
1133 {
1134 const done = completedObjectiveIds.includes(obj.objectiveId);
1135 const progress = countableObjectiveProgress(obj.when, ctx);
1136 return {
1137 objectiveId: obj.objectiveId,
1138 text: obj.text,
1139 done,
1140 current: progress?.current ?? null,
1141 required: progress?.required ?? null
1142 };
1143 });
1144 }
1145
981 1146 function journalPublic (row)
982 1147 {
983 1148 return {
@@ -1,4 +1,10 @@
1import { evaluateConditionSet, EffectKind } from "../../../shared/quests/conditions.js";
1import { evaluateConditionSet, EffectKind } from "../../../shared/quests/conditions.js";
2import {
3 deriveCompletedStepIds,
4 isActiveQuestState,
5 rememberCompletedStep,
6 resolveQuestStepId
7} from "../../../shared/quests/questProgress.js";
2import { normalizeInitialQuests } from "../../../shared/quests/initialQuests.js";
8import { normalizeInitialQuests } from "../../../shared/quests/initialQuests.js";
3import {
9import {
4 countableObjectiveProgress,
10 countableObjectiveProgress,
@@ -72,8 +78,12 @@ export class QuestRuntime
72 });
78 });
73 continue;
79 continue;
74 }
80 }
75 const stepIndex = typeof row.state === "number" ? row.state : null;
81 const stepDef = isActiveQuestState(row.state)
76 const stepDef = stepIndex != null ? def.steps[stepIndex - 1] : null;
82 ? activeQuestStep(def, row.state)
83 : null;
84 const resolvedState = isActiveQuestState(row.state)
85 ? (resolveQuestStepId(def, row.state) ?? row.state)
86 : row.state;
77 const completedObjectiveIds = row.progress?.completedObjectiveIds ?? [];
87 const completedObjectiveIds = row.progress?.completedObjectiveIds ?? [];
78 const ctx = stepDef
88 const ctx = stepDef
79 ? this.buildConditionContext(characterId, playerView, row.questId)
89 ? this.buildConditionContext(characterId, playerView, row.questId)
@@ -82,25 +92,14 @@ export class QuestRuntime
82 questId: def.questId,
92 questId: def.questId,
83 title: def.title,
93 title: def.title,
84 orphaned: false,
94 orphaned: false,
85 state: row.state,
95 state: resolvedState,
86 description: def.description,
96 description: def.description,
87 step: stepDef
97 step: stepDef
88 ? {
98 ? {
89 stepId: stepDef.stepId,
99 stepId: stepDef.stepId,
90 title: stepDef.title,
100 title: stepDef.title,
91 description: stepDef.description,
101 description: stepDef.description,
92 objectives: stepDef.objectives.map((obj) =>
102 objectives: publicStepLines(stepDef, completedObjectiveIds, ctx)
93 {
94 const done = completedObjectiveIds.includes(obj.objectiveId);
95 const progress = countableObjectiveProgress(obj.when, ctx);
96 return {
97 objectiveId: obj.objectiveId,
98 text: obj.text,
99 done,
100 current: progress?.current ?? null,
101 required: progress?.required ?? null
102 };
103 })
104 }
103 }
105 : null,
104 : null,
106 journal: this.stateDb.listQuestJournal(characterId, def.questId).map(journalPublic)
105 journal: this.stateDb.listQuestJournal(characterId, def.questId).map(journalPublic)
@@ -178,7 +177,26 @@ export class QuestRuntime
178 stamina: playerView?.stamina ?? 0,
177 stamina: playerView?.stamina ?? 0,
179 maxStamina: playerView?.maxStamina ?? 1,
178 maxStamina: playerView?.maxStamina ?? 1,
180 countItem: (itemId) => countItemInSlots(inventory, itemId | 0),
179 countItem: (itemId) => countItemInSlots(inventory, itemId | 0),
181 questState: (questId) => this.stateDb.getQuestState(characterId, questId).state,
180 questState: (questId) =>
181 {
182 const row = this.stateDb.getQuestState(characterId, questId);
183 return resolveQuestStepId(this.content.quest(questId), row.state);
184 },
185 questSteps: (questId) =>
186 {
187 const def = this.content.quest(questId);
188 return def ? def.steps.map((step) => step.stepId) : null;
189 },
190 hasCompletedStep: (questId, stepId) =>
191 {
192 const row = this.stateDb.getQuestState(characterId, questId);
193 const ids = deriveCompletedStepIds(
194 this.content.quest(questId),
195 row.state,
196 row.progress
197 );
198 return ids.includes(String(stepId ?? ""));
199 },
182 dialogueHeard: (dialogueId, stepId) => this.stateDb.isDialogueHeard(characterId, dialogueId, stepId),
200 dialogueHeard: (dialogueId, stepId) => this.stateDb.isDialogueHeard(characterId, dialogueId, stepId),
183 dialogueTriggerLatched: (dialogueId, trigger) =>
201 dialogueTriggerLatched: (dialogueId, trigger) =>
184 this.stateDb.isDialogueTriggerLatched(characterId, dialogueId, trigger),
202 this.stateDb.isDialogueTriggerLatched(characterId, dialogueId, trigger),
@@ -670,12 +688,15 @@ export class QuestRuntime
670 const current = this.stateDb.getQuestState(characterId, questId);
688 const current = this.stateDb.getQuestState(characterId, questId);
671 if (current.state !== "not-started")
689 if (current.state !== "not-started")
672 { return; }
690 { return; }
673 this.stateDb.saveQuestState(characterId, questId, 1, {
691 const first = def.steps[0];
692 this.stateDb.saveQuestState(characterId, questId, first.stepId, {
674 completedObjectiveIds: [],
693 completedObjectiveIds: [],
675 counters: {},
694 counters: {},
676 interacts: {}
695 interacts: {},
696 completedStepIds: [],
697 progressFingerprint: ""
677 }, Date.now(), null);
698 }, Date.now(), null);
678 this.#applyEffects(characterId, def.steps[0]?.onEnter, playerView, events);
699 this.#applyEffects(characterId, first.onEnter, playerView, events);
679 events.push({ type: "questsDirty", characterId });
700 events.push({ type: "questsDirty", characterId });
680 this.#reevaluateQuests(characterId, playerView, events);
701 this.#reevaluateQuests(characterId, playerView, events);
681 }
702 }
@@ -842,102 +863,192 @@ export class QuestRuntime
842
863
843 #reevaluateQuests (characterId, playerView, events)
864 #reevaluateQuests (characterId, playerView, events)
844 {
865 {
845 const states = this.stateDb.listQuestStates(characterId)
866 const outer = this._transitionedQuestIds == null;
846 .filter((row) => typeof row.state === "number");
867 if (outer)
847 for (const row of states)
868 { this._transitionedQuestIds = new Set(); }
869 try
848 {
870 {
849 const def = this.content.quest(row.questId);
871 const states = this.stateDb.listQuestStates(characterId)
850 if (!def)
872 .filter((row) => isActiveQuestState(row.state));
851 { continue; }
873 for (const row of states)
852 const stepDef = def.steps[row.state - 1];
853 if (!stepDef)
854 { continue; }
855 const ctx = this.buildConditionContext(characterId, playerView, row.questId);
856 const completed = new Set(row.progress?.completedObjectiveIds ?? []);
857 const newlyDone = [];
858 let changed = false;
859 for (const obj of stepDef.objectives)
860 {
874 {
861 if (completed.has(obj.objectiveId))
875 if (this._transitionedQuestIds.has(row.questId))
862 { continue; }
876 { continue; }
863 if (evaluateConditionSet(obj.when, ctx))
877 const def = this.content.quest(row.questId);
864 {
878 if (!def)
865 completed.add(obj.objectiveId);
879 { continue; }
866 newlyDone.push(obj);
880 const stepDef = activeQuestStep(def, row.state);
867 changed = true;
881 if (!stepDef)
868 }
882 { continue; }
883 const ctx = this.buildConditionContext(characterId, playerView, row.questId);
884 if (stepDef.exit?.kind === "branches")
885 { this.#advanceBranchStep(characterId, def, row, stepDef, ctx, playerView, events); }
886 else
887 { this.#advanceLinearStep(characterId, def, row, stepDef, ctx, playerView, events); }
869 }
888 }
870 const fingerprint = objectiveProgressFingerprint(stepDef.objectives, ctx);
889 }
871 const progressChanged = fingerprint !== (row.progress?.progressFingerprint ?? "");
890 finally
872 if (!changed && !progressChanged)
891 {
892 if (outer)
893 { this._transitionedQuestIds = null; }
894 }
895 }
896
897 #advanceLinearStep (characterId, def, row, stepDef, ctx, playerView, events)
898 {
899 const completed = new Set(row.progress?.completedObjectiveIds ?? []);
900 const newlyDone = [];
901 let changed = false;
902 for (const obj of stepDef.objectives)
903 {
904 if (completed.has(obj.objectiveId))
873 { continue; }
905 { continue; }
874 for (const obj of newlyDone)
906 if (evaluateConditionSet(obj.when, ctx))
875 {
876 events.push({
877 type: "questObjectiveComplete",
878 questId: row.questId,
879 objectiveId: obj.objectiveId,
880 text: obj.text || "Objective"
881 });
882 }
883 const progress = {
884 ...row.progress,
885 completedObjectiveIds: [...completed],
886 progressFingerprint: fingerprint
887 };
888 const allDone = stepDef.objectives.every((obj) => completed.has(obj.objectiveId));
889 if (!allDone)
890 {
907 {
891 this.stateDb.saveQuestState(characterId, row.questId, row.state, progress, row.startedAt, row.completedAt);
908 completed.add(obj.objectiveId);
892 events.push({ type: "questsDirty", characterId });
909 newlyDone.push(obj);
893 continue;
910 changed = true;
894 }
911 }
895 if (!changed)
912 }
896 {
913 const fingerprint = objectiveProgressFingerprint(stepDef.objectives, ctx);
897 // Progress-only update while already fully complete (should not happen).
914 const progressChanged = fingerprint !== (row.progress?.progressFingerprint ?? "");
898 this.stateDb.saveQuestState(characterId, row.questId, row.state, progress, row.startedAt, row.completedAt);
915 const progress = {
899 events.push({ type: "questsDirty", characterId });
916 ...row.progress,
900 continue;
917 completedObjectiveIds: [...completed],
901 }
918 progressFingerprint: fingerprint,
902 this.#applyEffects(characterId, stepDef.onComplete, playerView, events);
919 completedStepIds: deriveCompletedStepIds(def, row.state, row.progress)
903 const journal = this.stateDb.appendQuestJournal(
920 };
904 characterId,
921 const allDone = stepDef.objectives.every((obj) => completed.has(obj.objectiveId));
905 row.questId,
922 for (const obj of newlyDone)
906 stepDef.stepId,
923 {
907 stepDef.completionJournalText
924 events.push({
908 );
925 type: "questObjectiveComplete",
909 const nextIndex = row.state + 1;
926 questId: row.questId,
910 if (nextIndex > def.steps.length)
927 objectiveId: obj.objectiveId,
928 text: obj.text || "Objective"
929 });
930 }
931 if (allDone && this.#leaveStep(characterId, def, row, stepDef, null, playerView, events))
932 { return; }
933 if (!changed && !progressChanged)
934 { return; }
935 this.#saveActiveProgress(characterId, def, row, progress);
936 events.push({ type: "questsDirty", characterId });
937 }
938
939 #advanceBranchStep (characterId, def, row, stepDef, ctx, playerView, events)
940 {
941 const branches = stepDef.exit?.branches ?? [];
942 let matched = null;
943 for (const branch of branches)
944 {
945 if (evaluateConditionSet(branch.when, ctx))
911 {
946 {
912 const summary = this.#grantQuestCompletionRewards(characterId, def, playerView, events);
947 matched = branch;
913 this.stateDb.saveQuestState(characterId, row.questId, "completed", progress, row.startedAt, Date.now());
948 break;
914 events.push({
915 type: "questComplete",
916 questId: row.questId,
917 title: def.title,
918 xp: summary.xp,
919 items: summary.bagItems
920 });
921 }
949 }
922 else
950 }
951 const fingerprint = objectiveProgressFingerprint(branchProgressRows(branches), ctx);
952 const progressChanged = fingerprint !== (row.progress?.progressFingerprint ?? "");
953 if (!matched)
954 {
955 if (!progressChanged)
956 { return; }
957 this.#saveActiveProgress(characterId, def, row, {
958 ...row.progress,
959 progressFingerprint: fingerprint,
960 completedStepIds: deriveCompletedStepIds(def, row.state, row.progress)
961 });
962 events.push({ type: "questsDirty", characterId });
963 return;
964 }
965 this.#leaveStep(characterId, def, row, stepDef, matched, playerView, events);
966 }
967
968 /**
969 * One hop away from the current step. Returns false when a continue/branch
970 * names a step that does not exist (stay put; retry next evaluation).
971 * Empty nextStepId completes the quest. Quest-wide rewards fire only here.
972 */
973 #leaveStep (characterId, def, row, stepDef, branch, playerView, events)
974 {
975 const exit = stepDef.exit ?? { kind: "complete" };
976 let destination = null;
977 if (branch)
978 {
979 if (branch.nextStepId)
923 {
980 {
924 const nextStep = def.steps[nextIndex - 1];
981 destination = def.steps.find((step) => step.stepId === branch.nextStepId) ?? null;
925 this.stateDb.saveQuestState(characterId, row.questId, nextIndex, {
982 if (!destination)
926 completedObjectiveIds: [],
983 { return false; }
927 counters: {},
928 interacts: {},
929 progressFingerprint: ""
930 }, row.startedAt, null);
931 this.#applyEffects(characterId, nextStep?.onEnter, playerView, events);
932 events.push({
933 type: "questStepComplete",
934 questId: row.questId,
935 title: def.title,
936 journalText: journal?.text ?? null
937 });
938 }
984 }
939 events.push({ type: "questsDirty", characterId });
940 }
985 }
986 else if (exit.kind === "continue" && exit.nextStepId)
987 {
988 destination = def.steps.find((step) => step.stepId === exit.nextStepId) ?? null;
989 if (!destination)
990 { return false; }
991 }
992 this._transitionedQuestIds?.add(row.questId);
993 const completedStepIds = rememberCompletedStep(
994 deriveCompletedStepIds(def, row.state, row.progress),
995 stepDef.stepId
996 );
997 this.#applyEffects(characterId, stepDef.onComplete, playerView, events);
998 if (branch)
999 { this.#applyEffects(characterId, branch.effects, playerView, events); }
1000 const journal = this.stateDb.appendQuestJournal(
1001 characterId,
1002 row.questId,
1003 stepDef.stepId,
1004 stepDef.completionJournalText
1005 );
1006 if (!destination)
1007 {
1008 const summary = this.#grantQuestCompletionRewards(characterId, def, playerView, events);
1009 this.stateDb.saveQuestState(characterId, row.questId, "completed", {
1010 ...row.progress,
1011 completedStepIds
1012 }, row.startedAt, Date.now());
1013 events.push({
1014 type: "questComplete",
1015 questId: row.questId,
1016 title: def.title,
1017 xp: summary.xp,
1018 items: summary.bagItems
1019 });
1020 }
1021 else
1022 {
1023 this.stateDb.saveQuestState(characterId, row.questId, destination.stepId, {
1024 completedObjectiveIds: [],
1025 counters: {},
1026 interacts: {},
1027 progressFingerprint: "",
1028 completedStepIds
1029 }, row.startedAt, null);
1030 this.#applyEffects(characterId, destination.onEnter, playerView, events);
1031 events.push({
1032 type: "questStepComplete",
1033 questId: row.questId,
1034 title: def.title,
1035 journalText: journal?.text ?? null
1036 });
1037 }
1038 events.push({ type: "questsDirty", characterId });
1039 return true;
1040 }
1041
1042 #saveActiveProgress (characterId, def, row, progress)
1043 {
1044 const stepId = resolveQuestStepId(def, row.state) ?? row.state;
1045 const completedStepIds = Array.isArray(progress?.completedStepIds)
1046 ? progress.completedStepIds
1047 : deriveCompletedStepIds(def, row.state, row.progress);
1048 this.stateDb.saveQuestState(characterId, row.questId, stepId, {
1049 ...progress,
1050 completedStepIds
1051 }, row.startedAt, row.completedAt);
941 }
1052 }
942
1053
943 noteKill (characterId, { mobTypeId, spawnerId })
1054 noteKill (characterId, { mobTypeId, spawnerId })
@@ -945,18 +1056,18 @@ export class QuestRuntime
945 const events = [];
1056 const events = [];
946 const playerView = this.playerViewFor(characterId);
1057 const playerView = this.playerViewFor(characterId);
947 const states = this.stateDb.listQuestStates(characterId)
1058 const states = this.stateDb.listQuestStates(characterId)
948 .filter((row) => typeof row.state === "number");
1059 .filter((row) => isActiveQuestState(row.state));
949 for (const row of states)
1060 for (const row of states)
950 {
1061 {
951 const def = this.content.quest(row.questId);
1062 const def = this.content.quest(row.questId);
952 const stepDef = def?.steps[row.state - 1];
1063 const stepDef = def ? activeQuestStep(def, row.state) : null;
953 if (!stepDef)
1064 if (!stepDef)
954 { continue; }
1065 { continue; }
955 let changed = false;
1066 let changed = false;
956 const counters = { ...(row.progress?.counters ?? {}) };
1067 const counters = { ...(row.progress?.counters ?? {}) };
957 for (const obj of stepDef.objectives)
1068 for (const set of stepConditionSets(stepDef))
958 {
1069 {
959 for (const clause of obj.when?.all ?? [])
1070 for (const clause of set?.all ?? [])
960 {
1071 {
961 const c = clause.condition;
1072 const c = clause.condition;
962 if (!matchesKillCondition(c, mobTypeId, spawnerId))
1073 if (!matchesKillCondition(c, mobTypeId, spawnerId))
@@ -968,16 +1079,70 @@ export class QuestRuntime
968 }
1079 }
969 if (!changed)
1080 if (!changed)
970 { continue; }
1081 { continue; }
971 this.stateDb.saveQuestState(characterId, row.questId, row.state, {
1082 this.#saveActiveProgress(characterId, def, row, {
972 ...row.progress,
1083 ...row.progress,
973 counters
1084 counters,
974 }, row.startedAt, row.completedAt);
1085 completedStepIds: deriveCompletedStepIds(def, row.state, row.progress)
1086 });
975 }
1087 }
976 this.#reevaluateQuests(characterId, playerView, events);
1088 this.#reevaluateQuests(characterId, playerView, events);
977 return events;
1089 return events;
978 }
1090 }
979}
1091}
980
1092
1093function activeQuestStep (def, state)
1094{
1095 const stepId = resolveQuestStepId(def, state);
1096 if (!stepId || stepId === "not-started" || stepId === "completed")
1097 { return null; }
1098 return def.steps.find((step) => step.stepId === stepId) ?? null;
1099}
1100
1101function stepConditionSets (stepDef)
1102{
1103 if (stepDef?.exit?.kind === "branches")
1104 { return (stepDef.exit.branches ?? []).map((branch) => branch.when); }
1105 return (stepDef?.objectives ?? []).map((obj) => obj.when);
1106}
1107
1108function branchProgressRows (branches)
1109{
1110 return (branches ?? []).map((branch, index) => ({
1111 objectiveId: `branch-${index}`,
1112 when: branch.when
1113 }));
1114}
1115
1116function publicStepLines (stepDef, completedObjectiveIds, ctx)
1117{
1118 if (stepDef.exit?.kind === "branches")
1119 {
1120 return (stepDef.exit.branches ?? []).map((branch, index) =>
1121 {
1122 const progress = countableObjectiveProgress(branch.when, ctx);
1123 return {
1124 objectiveId: `branch-${index}`,
1125 text: branch.text || branch.label || `Path ${index + 1}`,
1126 done: false,
1127 current: progress?.current ?? null,
1128 required: progress?.required ?? null
1129 };
1130 });
1131 }
1132 return (stepDef.objectives ?? []).map((obj) =>
1133 {
1134 const done = completedObjectiveIds.includes(obj.objectiveId);
1135 const progress = countableObjectiveProgress(obj.when, ctx);
1136 return {
1137 objectiveId: obj.objectiveId,
1138 text: obj.text,
1139 done,
1140 current: progress?.current ?? null,
1141 required: progress?.required ?? null
1142 };
1143 });
1144}
1145
981function journalPublic (row)
1146function journalPublic (row)
982{
1147{
983 return {
1148 return {
server/src/simulation/simulation.js +8 −2
@@ -231,6 +231,8 @@ export class Simulation
231 231 this.market?.refreshIndex();
232 232 this.questContent.reload();
233 233 this.quests?.closeAllSessions();
234 for (const characterId of this.characterEntities.keys())
235 { this.syncCharacterConditionAccess(characterId); }
234 236 this.#refreshAltarIndex();
235 237 // Quest defs become live on Apply — grant any newly available initial quests.
236 238 this.#grantInitialQuestsAndNotify();
@@ -561,7 +563,11 @@ export class Simulation
561 563 dimensionId,
562 564 sinceMs: this.now
563 565 },
564 conditionAccess: buildConditionAccessSnapshot(this.stateDb, character.character_id ?? row.character_id)
566 conditionAccess: buildConditionAccessSnapshot(
567 this.stateDb,
568 character.character_id ?? row.character_id,
569 this.questContent
570 )
565 571 };
566 572 if (isDead)
567 573 { components.dead = {}; }
@@ -651,7 +657,7 @@ export class Simulation
651 657 this.workers[record.workerId]?.call({
652 658 type: WorkerMessage.applyConditionAccess,
653 659 entityId,
654 conditionAccess: buildConditionAccessSnapshot(this.stateDb, id)
660 conditionAccess: buildConditionAccessSnapshot(this.stateDb, id, this.questContent)
655 661 });
656 662 }
657 663
@@ -231,6 +231,8 @@ export class Simulation
231 this.market?.refreshIndex();
231 this.market?.refreshIndex();
232 this.questContent.reload();
232 this.questContent.reload();
233 this.quests?.closeAllSessions();
233 this.quests?.closeAllSessions();
234 for (const characterId of this.characterEntities.keys())
235 { this.syncCharacterConditionAccess(characterId); }
234 this.#refreshAltarIndex();
236 this.#refreshAltarIndex();
235 // Quest defs become live on Apply — grant any newly available initial quests.
237 // Quest defs become live on Apply — grant any newly available initial quests.
236 this.#grantInitialQuestsAndNotify();
238 this.#grantInitialQuestsAndNotify();
@@ -561,7 +563,11 @@ export class Simulation
561 dimensionId,
563 dimensionId,
562 sinceMs: this.now
564 sinceMs: this.now
563 },
565 },
564 conditionAccess: buildConditionAccessSnapshot(this.stateDb, character.character_id ?? row.character_id)
566 conditionAccess: buildConditionAccessSnapshot(
567 this.stateDb,
568 character.character_id ?? row.character_id,
569 this.questContent
570 )
565 };
571 };
566 if (isDead)
572 if (isDead)
567 { components.dead = {}; }
573 { components.dead = {}; }
@@ -651,7 +657,7 @@ export class Simulation
651 this.workers[record.workerId]?.call({
657 this.workers[record.workerId]?.call({
652 type: WorkerMessage.applyConditionAccess,
658 type: WorkerMessage.applyConditionAccess,
653 entityId,
659 entityId,
654 conditionAccess: buildConditionAccessSnapshot(this.stateDb, id)
660 conditionAccess: buildConditionAccessSnapshot(this.stateDb, id, this.questContent)
655 });
661 });
656 }
662 }
657
663
server/src/simulation/workerWorld.js +1 −0
@@ -982,6 +982,7 @@ export class WorkerWorld
982 982 : {
983 983 questStates: {},
984 984 questProgress: {},
985 questSteps: {},
985 986 dialogueHeard: [],
986 987 dialogueTriggers: [],
987 988 visitedDimensions: []
@@ -982,6 +982,7 @@ export class WorkerWorld
982 : {
982 : {
983 questStates: {},
983 questStates: {},
984 questProgress: {},
984 questProgress: {},
985 questSteps: {},
985 dialogueHeard: [],
986 dialogueHeard: [],
986 dialogueTriggers: [],
987 dialogueTriggers: [],
987 visitedDimensions: []
988 visitedDimensions: []
server/tests/initial-quests.test.js +3 −3
@@ -56,7 +56,7 @@ test("initial quests grant on apply after quest def becomes live", () =>
56 56
57 57 assert.equal(
58 58 harness.stateDb.getQuestState(character.character_id, "starter-hello").state,
59 1
59 "step-1"
60 60 );
61 61 const snap = harness.simulation.quests.questSnapshot(character.character_id);
62 62 assert.equal(snap.quests.length, 1);
@@ -103,7 +103,7 @@ test("request-quests ensures missing initial quests before snapshot", () =>
103 103 assert.equal(snap.quests[0].questId, "late-grant");
104 104 assert.equal(
105 105 harness.stateDb.getQuestState(character.character_id, "late-grant").state,
106 1
106 "step-1"
107 107 );
108 108 }
109 109 finally
@@ -169,7 +169,7 @@ test("request-quests re-checks hasItem objectives against the live bag", () =>
169 169 assert.ok(snap);
170 170 const questSnap = snap.quests.find((q) => q.questId === "fetch-rock");
171 171 assert.ok(questSnap);
172 assert.equal(questSnap.state, 1);
172 assert.equal(questSnap.state, "step-1");
173 173 assert.equal(questSnap.step.objectives.find((o) => o.objectiveId === "obj-rock")?.done, true);
174 174 assert.equal(questSnap.step.objectives.find((o) => o.objectiveId === "obj-gem")?.done, false);
175 175 }
@@ -56,7 +56,7 @@ test("initial quests grant on apply after quest def becomes live", () =>
56
56
57 assert.equal(
57 assert.equal(
58 harness.stateDb.getQuestState(character.character_id, "starter-hello").state,
58 harness.stateDb.getQuestState(character.character_id, "starter-hello").state,
59 1
59 "step-1"
60 );
60 );
61 const snap = harness.simulation.quests.questSnapshot(character.character_id);
61 const snap = harness.simulation.quests.questSnapshot(character.character_id);
62 assert.equal(snap.quests.length, 1);
62 assert.equal(snap.quests.length, 1);
@@ -103,7 +103,7 @@ test("request-quests ensures missing initial quests before snapshot", () =>
103 assert.equal(snap.quests[0].questId, "late-grant");
103 assert.equal(snap.quests[0].questId, "late-grant");
104 assert.equal(
104 assert.equal(
105 harness.stateDb.getQuestState(character.character_id, "late-grant").state,
105 harness.stateDb.getQuestState(character.character_id, "late-grant").state,
106 1
106 "step-1"
107 );
107 );
108 }
108 }
109 finally
109 finally
@@ -169,7 +169,7 @@ test("request-quests re-checks hasItem objectives against the live bag", () =>
169 assert.ok(snap);
169 assert.ok(snap);
170 const questSnap = snap.quests.find((q) => q.questId === "fetch-rock");
170 const questSnap = snap.quests.find((q) => q.questId === "fetch-rock");
171 assert.ok(questSnap);
171 assert.ok(questSnap);
172 assert.equal(questSnap.state, 1);
172 assert.equal(questSnap.state, "step-1");
173 assert.equal(questSnap.step.objectives.find((o) => o.objectiveId === "obj-rock")?.done, true);
173 assert.equal(questSnap.step.objectives.find((o) => o.objectiveId === "obj-rock")?.done, true);
174 assert.equal(questSnap.step.objectives.find((o) => o.objectiveId === "obj-gem")?.done, false);
174 assert.equal(questSnap.step.objectives.find((o) => o.objectiveId === "obj-gem")?.done, false);
175 }
175 }
server/tests/quest-branches.test.js added +376 −0
@@ -0,0 +1,376 @@
1 import test from "node:test";
2 import assert from "node:assert/strict";
3 import { normalizeQuestDef } from "../../shared/quests/normalize.js";
4 import { ConditionKind } from "../../shared/quests/conditions.js";
5 import { normalizeDoorConfig } from "../../shared/world/doorRequirements.js";
6 import { BlockType } from "../../shared/definitions/tiles.js";
7 import { ItemId } from "../../shared/definitions/items.js";
8 import { SkillId } from "../../shared/definitions/skills.js";
9 import { emptyEquipment, emptySlots, INVENTORY_SLOTS } from "../../shared/items/inventory.js";
10 import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
11
12 function saveLiveQuest (harness, raw)
13 {
14 const revisionId = harness.worldDb.getActiveRevisionId();
15 const quest = normalizeQuestDef(raw);
16 harness.worldDb.saveQuestDef(revisionId, quest);
17 harness.simulation.questContent.reload();
18 return quest;
19 }
20
21 function stuckObjective (itemId = 99999)
22 {
23 return [{
24 objectiveId: "stay",
25 text: "Stay",
26 when: { all: [{ condition: { kind: "hasItem", itemId, quantity: 1 } }] }
27 }];
28 }
29
30 function openObjective ()
31 {
32 return [{ objectiveId: "go", text: "Go", when: { all: [] } }];
33 }
34
35 function workerOf (simulation, entityId)
36 {
37 const record = simulation.entityRecord(entityId);
38 assert.ok(record);
39 return simulation.workers[record.workerId];
40 }
41
42 function placeDoor (worker, tileX, tileY, when)
43 {
44 const data = worker.world.chunkData(Math.floor(tileX / 16), Math.floor(tileY / 16));
45 const localX = ((tileX % 16) + 16) % 16;
46 const localY = ((tileY % 16) + 16) % 16;
47 data.blocks[localY * 16 + localX] = {
48 typeId: BlockType.door,
49 state: "oak-n-closed",
50 config: normalizeDoorConfig({ when, blockedMessage: "Not yet." })
51 };
52 }
53
54 test("linear quests still advance one step per evaluation and reward once", () =>
55 {
56 const harness = makeSimulation({ workerCount: 1 });
57 try
58 {
59 const quest = saveLiveQuest(harness, {
60 questId: "linear-chain",
61 title: "Linear",
62 steps: [
63 { stepId: "s1", title: "One", objectives: openObjective(), completionJournalText: "One done." },
64 { stepId: "s2", title: "Two", objectives: openObjective(), completionJournalText: "Two done." },
65 { stepId: "s3", title: "Three", objectives: openObjective(), completionJournalText: "Three done." }
66 ],
67 rewards: [{ kind: "giveXp", skillId: SkillId.woodworking, amount: 11 }]
68 });
69 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
70 harness.simulation.spawnCharacter(1, character);
71 harness.simulation.step();
72 const view = harness.simulation.quests.playerViewFor(character.character_id);
73 const events = [];
74 harness.simulation.quests.startQuest(character.character_id, quest.questId, view, events);
75 assert.equal(events.some((event) => event.type === "questComplete"), false);
76 let state = harness.stateDb.getQuestState(character.character_id, quest.questId);
77 assert.equal(state.state, "s2");
78 assert.deepEqual(state.progress.completedStepIds, ["s1"]);
79
80 harness.simulation.quests.reevaluateQuests(character.character_id, view, []);
81 state = harness.stateDb.getQuestState(character.character_id, quest.questId);
82 assert.equal(state.state, "s3");
83 assert.deepEqual(state.progress.completedStepIds, ["s1", "s2"]);
84 assert.equal(harness.stateDb.getSkills(character.character_id).xp.woodworking, 0);
85
86 harness.simulation.quests.reevaluateQuests(character.character_id, view, []);
87 state = harness.stateDb.getQuestState(character.character_id, quest.questId);
88 assert.equal(state.state, "completed");
89 assert.deepEqual(state.progress.completedStepIds, ["s1", "s2", "s3"]);
90 assert.equal(harness.stateDb.getSkills(character.character_id).xp.woodworking, 11);
91
92 harness.simulation.quests.reevaluateQuests(character.character_id, view, []);
93 assert.equal(harness.stateDb.getSkills(character.character_id).xp.woodworking, 11);
94 assert.equal(
95 harness.stateDb.getQuestState(character.character_id, quest.questId).state,
96 "completed"
97 );
98 }
99 finally
100 { harness.close(); }
101 });
102
103 test("branch exit takes the first matching condition set only", () =>
104 {
105 const harness = makeSimulation({ workerCount: 1 });
106 try
107 {
108 const quest = saveLiveQuest(harness, {
109 questId: "branch-first",
110 title: "Branch",
111 steps: [{
112 stepId: "hub",
113 title: "Hub",
114 exit: {
115 kind: "branches",
116 branches: [
117 {
118 label: "Bones",
119 text: "Bring bones",
120 when: { all: [{ condition: { kind: "hasItem", itemId: ItemId.bones, quantity: 1 } }] },
121 nextStepId: "bones-path"
122 },
123 {
124 label: "Other",
125 text: "Otherwise",
126 when: { all: [] },
127 nextStepId: "other-path"
128 }
129 ]
130 }
131 }, {
132 stepId: "bones-path",
133 title: "Bones",
134 objectives: stuckObjective()
135 }, {
136 stepId: "other-path",
137 title: "Other",
138 objectives: stuckObjective()
139 }]
140 });
141 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
142 const playerId = harness.simulation.spawnCharacter(1, character);
143 harness.simulation.step();
144 const inventory = emptySlots(INVENTORY_SLOTS);
145 inventory[0] = { itemId: ItemId.bones, quantity: 1 };
146 harness.simulation.applyBag(playerId, {
147 inventory,
148 equipment: emptyEquipment(),
149 vault: [],
150 vaultReserved: []
151 });
152 const view = harness.simulation.quests.playerViewFor(character.character_id);
153 harness.simulation.quests.startQuest(character.character_id, quest.questId, view, []);
154 const state = harness.stateDb.getQuestState(character.character_id, quest.questId);
155 assert.equal(state.state, "bones-path");
156 assert.deepEqual(state.progress.completedStepIds, ["hub"]);
157 const snap = harness.simulation.quests.questSnapshot(character.character_id);
158 assert.equal(snap.quests[0].step.stepId, "bones-path");
159 }
160 finally
161 { harness.close(); }
162 });
163
164 test("unmatched branch step shows branch texts with kill progress", () =>
165 {
166 const harness = makeSimulation({ workerCount: 1 });
167 try
168 {
169 const quest = saveLiveQuest(harness, {
170 questId: "branch-log",
171 title: "Log",
172 steps: [{
173 stepId: "choice",
174 title: "Choose",
175 exit: {
176 kind: "branches",
177 branches: [
178 {
179 text: "Kill rats",
180 when: { all: [{ condition: { kind: "killCount", mobTypeId: "rat", count: 3 } }] },
181 nextStepId: "done"
182 },
183 {
184 text: "Bring bones",
185 when: { all: [{ condition: { kind: "hasItem", itemId: ItemId.bones, quantity: 2 } }] },
186 nextStepId: "done"
187 }
188 ]
189 }
190 }, {
191 stepId: "done",
192 title: "Done",
193 objectives: stuckObjective()
194 }]
195 });
196 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
197 harness.simulation.spawnCharacter(1, character);
198 harness.simulation.step();
199 const view = harness.simulation.quests.playerViewFor(character.character_id);
200 harness.simulation.quests.startQuest(character.character_id, quest.questId, view, []);
201 let snap = harness.simulation.quests.questSnapshot(character.character_id);
202 assert.deepEqual(
203 snap.quests[0].step.objectives.map((line) => line.text),
204 ["Kill rats", "Bring bones"]
205 );
206 assert.equal(snap.quests[0].step.objectives[0].current, 0);
207 assert.equal(snap.quests[0].step.objectives[0].required, 3);
208
209 harness.simulation.quests.noteKill(character.character_id, { mobTypeId: "rat", spawnerId: null });
210 snap = harness.simulation.quests.questSnapshot(character.character_id);
211 assert.equal(snap.quests[0].step.stepId, "choice");
212 assert.equal(snap.quests[0].step.objectives[0].current, 1);
213 assert.equal(
214 harness.stateDb.getQuestState(character.character_id, quest.questId).state,
215 "choice"
216 );
217 }
218 finally
219 { harness.close(); }
220 });
221
222 test("noteKill counts only the active step resolved by step id", () =>
223 {
224 const harness = makeSimulation({ workerCount: 1 });
225 try
226 {
227 const quest = saveLiveQuest(harness, {
228 questId: "kill-which",
229 title: "Which",
230 steps: [{
231 stepId: "first",
232 title: "Deer",
233 objectives: [{
234 objectiveId: "deer",
235 text: "Deer",
236 when: { all: [{ condition: { kind: "killCount", mobTypeId: "deer", count: 1 } }] }
237 }]
238 }, {
239 stepId: "second",
240 title: "Rats",
241 objectives: [{
242 objectiveId: "rats",
243 text: "Rats",
244 when: { all: [{ condition: { kind: "killCount", mobTypeId: "rat", count: 2 } }] }
245 }]
246 }]
247 });
248 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
249 harness.simulation.spawnCharacter(1, character);
250 harness.simulation.step();
251 harness.stateDb.saveQuestState(character.character_id, quest.questId, "second", {
252 completedObjectiveIds: [],
253 counters: {},
254 completedStepIds: ["first"]
255 }, Date.now(), null);
256 harness.simulation.quests.noteKill(character.character_id, { mobTypeId: "deer", spawnerId: null });
257 harness.simulation.quests.noteKill(character.character_id, { mobTypeId: "rat", spawnerId: null });
258 const state = harness.stateDb.getQuestState(character.character_id, quest.questId);
259 assert.equal(state.state, "second");
260 assert.equal(state.progress.counters?.["mob:deer"], undefined);
261 assert.equal(state.progress.counters?.["mob:rat"], 1);
262 assert.deepEqual(state.progress.completedStepIds, ["first"]);
263 }
264 finally
265 { harness.close(); }
266 });
267
268 test("completed step ids survive a loop back onto the same step", () =>
269 {
270 const harness = makeSimulation({ workerCount: 1 });
271 try
272 {
273 const quest = saveLiveQuest(harness, {
274 questId: "loop-q",
275 title: "Loop",
276 steps: [{
277 stepId: "alpha",
278 title: "Alpha",
279 exit: {
280 kind: "branches",
281 branches: [{ text: "To beta", when: { all: [] }, nextStepId: "beta" }]
282 }
283 }, {
284 stepId: "beta",
285 title: "Beta",
286 exit: {
287 kind: "branches",
288 branches: [{ text: "To alpha", when: { all: [] }, nextStepId: "alpha" }]
289 }
290 }]
291 });
292 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
293 harness.simulation.spawnCharacter(1, character);
294 harness.simulation.step();
295 const view = harness.simulation.quests.playerViewFor(character.character_id);
296 harness.simulation.quests.startQuest(character.character_id, quest.questId, view, []);
297 let state = harness.stateDb.getQuestState(character.character_id, quest.questId);
298 assert.equal(state.state, "beta");
299 assert.deepEqual(state.progress.completedStepIds, ["alpha"]);
300
301 harness.simulation.quests.reevaluateQuests(character.character_id, view, []);
302 state = harness.stateDb.getQuestState(character.character_id, quest.questId);
303 assert.equal(state.state, "alpha");
304 assert.deepEqual(state.progress.completedStepIds, ["alpha", "beta"]);
305
306 harness.simulation.quests.reevaluateQuests(character.character_id, view, []);
307 state = harness.stateDb.getQuestState(character.character_id, quest.questId);
308 assert.equal(state.state, "beta");
309 assert.deepEqual(state.progress.completedStepIds, ["alpha", "beta"]);
310 assert.equal(state.state === "completed", false);
311 }
312 finally
313 { harness.close(); }
314 });
315
316 test("legacy numeric quest index resolves the step and unlocks doors", () =>
317 {
318 const harness = makeSimulation({ workerCount: 1 });
319 try
320 {
321 const quest = saveLiveQuest(harness, {
322 questId: "door-steps",
323 title: "Door Steps",
324 steps: [{
325 stepId: "gate-a",
326 title: "First",
327 objectives: stuckObjective(99991)
328 }, {
329 stepId: "gate-b",
330 title: "Second",
331 objectives: stuckObjective(99992)
332 }]
333 });
334 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
335 const entityId = harness.simulation.spawnCharacter(1, character);
336 harness.simulation.step();
337 const worker = workerOf(harness.simulation, entityId);
338 placeDoor(worker, 9, 8, {
339 all: [{ condition: { kind: ConditionKind.questStepAtLeast, questId: quest.questId, step: 2 } }]
340 });
341 assert.equal(worker.world.walkableFor(entityId, 9, 8), false);
342
343 harness.stateDb.saveQuestState(character.character_id, quest.questId, 2, {}, Date.now(), null);
344 harness.simulation.syncCharacterConditionAccess(character.character_id);
345 const snap = harness.simulation.quests.questSnapshot(character.character_id);
346 assert.equal(snap.quests[0].step.stepId, "gate-b");
347 assert.equal(worker.world.walkableFor(entityId, 9, 8), true, "at least step 2 means gate-a was completed");
348
349 placeDoor(worker, 9, 8, {
350 all: [{
351 condition: {
352 kind: ConditionKind.hasCompletedStep,
353 questId: quest.questId,
354 stepId: "gate-b"
355 }
356 }]
357 });
358 assert.equal(worker.world.walkableFor(entityId, 9, 8), false);
359
360 placeDoor(worker, 9, 8, {
361 all: [{
362 condition: { kind: ConditionKind.questState, questId: quest.questId, state: "gate-b" }
363 }]
364 });
365 assert.equal(worker.world.walkableFor(entityId, 9, 8), true);
366
367 placeDoor(worker, 9, 8, {
368 all: [{
369 condition: { kind: ConditionKind.questState, questId: quest.questId, state: "gate-a" }
370 }]
371 });
372 assert.equal(worker.world.walkableFor(entityId, 9, 8), false);
373 }
374 finally
375 { harness.close(); }
376 });
@@ -0,0 +1,376 @@
1import test from "node:test";
2import assert from "node:assert/strict";
3import { normalizeQuestDef } from "../../shared/quests/normalize.js";
4import { ConditionKind } from "../../shared/quests/conditions.js";
5import { normalizeDoorConfig } from "../../shared/world/doorRequirements.js";
6import { BlockType } from "../../shared/definitions/tiles.js";
7import { ItemId } from "../../shared/definitions/items.js";
8import { SkillId } from "../../shared/definitions/skills.js";
9import { emptyEquipment, emptySlots, INVENTORY_SLOTS } from "../../shared/items/inventory.js";
10import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
11
12function saveLiveQuest (harness, raw)
13{
14 const revisionId = harness.worldDb.getActiveRevisionId();
15 const quest = normalizeQuestDef(raw);
16 harness.worldDb.saveQuestDef(revisionId, quest);
17 harness.simulation.questContent.reload();
18 return quest;
19}
20
21function stuckObjective (itemId = 99999)
22{
23 return [{
24 objectiveId: "stay",
25 text: "Stay",
26 when: { all: [{ condition: { kind: "hasItem", itemId, quantity: 1 } }] }
27 }];
28}
29
30function openObjective ()
31{
32 return [{ objectiveId: "go", text: "Go", when: { all: [] } }];
33}
34
35function workerOf (simulation, entityId)
36{
37 const record = simulation.entityRecord(entityId);
38 assert.ok(record);
39 return simulation.workers[record.workerId];
40}
41
42function placeDoor (worker, tileX, tileY, when)
43{
44 const data = worker.world.chunkData(Math.floor(tileX / 16), Math.floor(tileY / 16));
45 const localX = ((tileX % 16) + 16) % 16;
46 const localY = ((tileY % 16) + 16) % 16;
47 data.blocks[localY * 16 + localX] = {
48 typeId: BlockType.door,
49 state: "oak-n-closed",
50 config: normalizeDoorConfig({ when, blockedMessage: "Not yet." })
51 };
52}
53
54test("linear quests still advance one step per evaluation and reward once", () =>
55{
56 const harness = makeSimulation({ workerCount: 1 });
57 try
58 {
59 const quest = saveLiveQuest(harness, {
60 questId: "linear-chain",
61 title: "Linear",
62 steps: [
63 { stepId: "s1", title: "One", objectives: openObjective(), completionJournalText: "One done." },
64 { stepId: "s2", title: "Two", objectives: openObjective(), completionJournalText: "Two done." },
65 { stepId: "s3", title: "Three", objectives: openObjective(), completionJournalText: "Three done." }
66 ],
67 rewards: [{ kind: "giveXp", skillId: SkillId.woodworking, amount: 11 }]
68 });
69 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
70 harness.simulation.spawnCharacter(1, character);
71 harness.simulation.step();
72 const view = harness.simulation.quests.playerViewFor(character.character_id);
73 const events = [];
74 harness.simulation.quests.startQuest(character.character_id, quest.questId, view, events);
75 assert.equal(events.some((event) => event.type === "questComplete"), false);
76 let state = harness.stateDb.getQuestState(character.character_id, quest.questId);
77 assert.equal(state.state, "s2");
78 assert.deepEqual(state.progress.completedStepIds, ["s1"]);
79
80 harness.simulation.quests.reevaluateQuests(character.character_id, view, []);
81 state = harness.stateDb.getQuestState(character.character_id, quest.questId);
82 assert.equal(state.state, "s3");
83 assert.deepEqual(state.progress.completedStepIds, ["s1", "s2"]);
84 assert.equal(harness.stateDb.getSkills(character.character_id).xp.woodworking, 0);
85
86 harness.simulation.quests.reevaluateQuests(character.character_id, view, []);
87 state = harness.stateDb.getQuestState(character.character_id, quest.questId);
88 assert.equal(state.state, "completed");
89 assert.deepEqual(state.progress.completedStepIds, ["s1", "s2", "s3"]);
90 assert.equal(harness.stateDb.getSkills(character.character_id).xp.woodworking, 11);
91
92 harness.simulation.quests.reevaluateQuests(character.character_id, view, []);
93 assert.equal(harness.stateDb.getSkills(character.character_id).xp.woodworking, 11);
94 assert.equal(
95 harness.stateDb.getQuestState(character.character_id, quest.questId).state,
96 "completed"
97 );
98 }
99 finally
100 { harness.close(); }
101});
102
103test("branch exit takes the first matching condition set only", () =>
104{
105 const harness = makeSimulation({ workerCount: 1 });
106 try
107 {
108 const quest = saveLiveQuest(harness, {
109 questId: "branch-first",
110 title: "Branch",
111 steps: [{
112 stepId: "hub",
113 title: "Hub",
114 exit: {
115 kind: "branches",
116 branches: [
117 {
118 label: "Bones",
119 text: "Bring bones",
120 when: { all: [{ condition: { kind: "hasItem", itemId: ItemId.bones, quantity: 1 } }] },
121 nextStepId: "bones-path"
122 },
123 {
124 label: "Other",
125 text: "Otherwise",
126 when: { all: [] },
127 nextStepId: "other-path"
128 }
129 ]
130 }
131 }, {
132 stepId: "bones-path",
133 title: "Bones",
134 objectives: stuckObjective()
135 }, {
136 stepId: "other-path",
137 title: "Other",
138 objectives: stuckObjective()
139 }]
140 });
141 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
142 const playerId = harness.simulation.spawnCharacter(1, character);
143 harness.simulation.step();
144 const inventory = emptySlots(INVENTORY_SLOTS);
145 inventory[0] = { itemId: ItemId.bones, quantity: 1 };
146 harness.simulation.applyBag(playerId, {
147 inventory,
148 equipment: emptyEquipment(),
149 vault: [],
150 vaultReserved: []
151 });
152 const view = harness.simulation.quests.playerViewFor(character.character_id);
153 harness.simulation.quests.startQuest(character.character_id, quest.questId, view, []);
154 const state = harness.stateDb.getQuestState(character.character_id, quest.questId);
155 assert.equal(state.state, "bones-path");
156 assert.deepEqual(state.progress.completedStepIds, ["hub"]);
157 const snap = harness.simulation.quests.questSnapshot(character.character_id);
158 assert.equal(snap.quests[0].step.stepId, "bones-path");
159 }
160 finally
161 { harness.close(); }
162});
163
164test("unmatched branch step shows branch texts with kill progress", () =>
165{
166 const harness = makeSimulation({ workerCount: 1 });
167 try
168 {
169 const quest = saveLiveQuest(harness, {
170 questId: "branch-log",
171 title: "Log",
172 steps: [{
173 stepId: "choice",
174 title: "Choose",
175 exit: {
176 kind: "branches",
177 branches: [
178 {
179 text: "Kill rats",
180 when: { all: [{ condition: { kind: "killCount", mobTypeId: "rat", count: 3 } }] },
181 nextStepId: "done"
182 },
183 {
184 text: "Bring bones",
185 when: { all: [{ condition: { kind: "hasItem", itemId: ItemId.bones, quantity: 2 } }] },
186 nextStepId: "done"
187 }
188 ]
189 }
190 }, {
191 stepId: "done",
192 title: "Done",
193 objectives: stuckObjective()
194 }]
195 });
196 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
197 harness.simulation.spawnCharacter(1, character);
198 harness.simulation.step();
199 const view = harness.simulation.quests.playerViewFor(character.character_id);
200 harness.simulation.quests.startQuest(character.character_id, quest.questId, view, []);
201 let snap = harness.simulation.quests.questSnapshot(character.character_id);
202 assert.deepEqual(
203 snap.quests[0].step.objectives.map((line) => line.text),
204 ["Kill rats", "Bring bones"]
205 );
206 assert.equal(snap.quests[0].step.objectives[0].current, 0);
207 assert.equal(snap.quests[0].step.objectives[0].required, 3);
208
209 harness.simulation.quests.noteKill(character.character_id, { mobTypeId: "rat", spawnerId: null });
210 snap = harness.simulation.quests.questSnapshot(character.character_id);
211 assert.equal(snap.quests[0].step.stepId, "choice");
212 assert.equal(snap.quests[0].step.objectives[0].current, 1);
213 assert.equal(
214 harness.stateDb.getQuestState(character.character_id, quest.questId).state,
215 "choice"
216 );
217 }
218 finally
219 { harness.close(); }
220});
221
222test("noteKill counts only the active step resolved by step id", () =>
223{
224 const harness = makeSimulation({ workerCount: 1 });
225 try
226 {
227 const quest = saveLiveQuest(harness, {
228 questId: "kill-which",
229 title: "Which",
230 steps: [{
231 stepId: "first",
232 title: "Deer",
233 objectives: [{
234 objectiveId: "deer",
235 text: "Deer",
236 when: { all: [{ condition: { kind: "killCount", mobTypeId: "deer", count: 1 } }] }
237 }]
238 }, {
239 stepId: "second",
240 title: "Rats",
241 objectives: [{
242 objectiveId: "rats",
243 text: "Rats",
244 when: { all: [{ condition: { kind: "killCount", mobTypeId: "rat", count: 2 } }] }
245 }]
246 }]
247 });
248 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
249 harness.simulation.spawnCharacter(1, character);
250 harness.simulation.step();
251 harness.stateDb.saveQuestState(character.character_id, quest.questId, "second", {
252 completedObjectiveIds: [],
253 counters: {},
254 completedStepIds: ["first"]
255 }, Date.now(), null);
256 harness.simulation.quests.noteKill(character.character_id, { mobTypeId: "deer", spawnerId: null });
257 harness.simulation.quests.noteKill(character.character_id, { mobTypeId: "rat", spawnerId: null });
258 const state = harness.stateDb.getQuestState(character.character_id, quest.questId);
259 assert.equal(state.state, "second");
260 assert.equal(state.progress.counters?.["mob:deer"], undefined);
261 assert.equal(state.progress.counters?.["mob:rat"], 1);
262 assert.deepEqual(state.progress.completedStepIds, ["first"]);
263 }
264 finally
265 { harness.close(); }
266});
267
268test("completed step ids survive a loop back onto the same step", () =>
269{
270 const harness = makeSimulation({ workerCount: 1 });
271 try
272 {
273 const quest = saveLiveQuest(harness, {
274 questId: "loop-q",
275 title: "Loop",
276 steps: [{
277 stepId: "alpha",
278 title: "Alpha",
279 exit: {
280 kind: "branches",
281 branches: [{ text: "To beta", when: { all: [] }, nextStepId: "beta" }]
282 }
283 }, {
284 stepId: "beta",
285 title: "Beta",
286 exit: {
287 kind: "branches",
288 branches: [{ text: "To alpha", when: { all: [] }, nextStepId: "alpha" }]
289 }
290 }]
291 });
292 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
293 harness.simulation.spawnCharacter(1, character);
294 harness.simulation.step();
295 const view = harness.simulation.quests.playerViewFor(character.character_id);
296 harness.simulation.quests.startQuest(character.character_id, quest.questId, view, []);
297 let state = harness.stateDb.getQuestState(character.character_id, quest.questId);
298 assert.equal(state.state, "beta");
299 assert.deepEqual(state.progress.completedStepIds, ["alpha"]);
300
301 harness.simulation.quests.reevaluateQuests(character.character_id, view, []);
302 state = harness.stateDb.getQuestState(character.character_id, quest.questId);
303 assert.equal(state.state, "alpha");
304 assert.deepEqual(state.progress.completedStepIds, ["alpha", "beta"]);
305
306 harness.simulation.quests.reevaluateQuests(character.character_id, view, []);
307 state = harness.stateDb.getQuestState(character.character_id, quest.questId);
308 assert.equal(state.state, "beta");
309 assert.deepEqual(state.progress.completedStepIds, ["alpha", "beta"]);
310 assert.equal(state.state === "completed", false);
311 }
312 finally
313 { harness.close(); }
314});
315
316test("legacy numeric quest index resolves the step and unlocks doors", () =>
317{
318 const harness = makeSimulation({ workerCount: 1 });
319 try
320 {
321 const quest = saveLiveQuest(harness, {
322 questId: "door-steps",
323 title: "Door Steps",
324 steps: [{
325 stepId: "gate-a",
326 title: "First",
327 objectives: stuckObjective(99991)
328 }, {
329 stepId: "gate-b",
330 title: "Second",
331 objectives: stuckObjective(99992)
332 }]
333 });
334 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
335 const entityId = harness.simulation.spawnCharacter(1, character);
336 harness.simulation.step();
337 const worker = workerOf(harness.simulation, entityId);
338 placeDoor(worker, 9, 8, {
339 all: [{ condition: { kind: ConditionKind.questStepAtLeast, questId: quest.questId, step: 2 } }]
340 });
341 assert.equal(worker.world.walkableFor(entityId, 9, 8), false);
342
343 harness.stateDb.saveQuestState(character.character_id, quest.questId, 2, {}, Date.now(), null);
344 harness.simulation.syncCharacterConditionAccess(character.character_id);
345 const snap = harness.simulation.quests.questSnapshot(character.character_id);
346 assert.equal(snap.quests[0].step.stepId, "gate-b");
347 assert.equal(worker.world.walkableFor(entityId, 9, 8), true, "at least step 2 means gate-a was completed");
348
349 placeDoor(worker, 9, 8, {
350 all: [{
351 condition: {
352 kind: ConditionKind.hasCompletedStep,
353 questId: quest.questId,
354 stepId: "gate-b"
355 }
356 }]
357 });
358 assert.equal(worker.world.walkableFor(entityId, 9, 8), false);
359
360 placeDoor(worker, 9, 8, {
361 all: [{
362 condition: { kind: ConditionKind.questState, questId: quest.questId, state: "gate-b" }
363 }]
364 });
365 assert.equal(worker.world.walkableFor(entityId, 9, 8), true);
366
367 placeDoor(worker, 9, 8, {
368 all: [{
369 condition: { kind: ConditionKind.questState, questId: quest.questId, state: "gate-a" }
370 }]
371 });
372 assert.equal(worker.world.walkableFor(entityId, 9, 8), false);
373 }
374 finally
375 { harness.close(); }
376});
server/tests/quests-conditions.test.js +126 −1
@@ -10,7 +10,9 @@ import {
10 10 countableObjectiveProgress,
11 11 formatObjectiveDisplayText
12 12 } from "../../shared/quests/objectiveProgress.js";
13 import { normalizeQuestDef, normalizeDialogueTree } from "../../shared/quests/normalize.js";
13 import { normalizeQuestDef, normalizeDialogueTree, questLookupFromRawDefs } from "../../shared/quests/normalize.js";
14 import { deriveCompletedStepIds, resolveQuestStepId } from "../../shared/quests/questProgress.js";
15 import { evaluateCondition } from "../../shared/quests/conditions.js";
14 16 import { formatDialogueRewardMessage, formatDialogueQuestRewardMessage, formatDialogueTakeMessage } from "../../shared/quests/dialogueRewards.js";
15 17
16 18 test("ConditionSet AND + NOT", () =>
@@ -74,6 +76,8 @@ test("normalize quest and dialogue", () =>
74 76 });
75 77 assert.equal(quest.questId, "fetch-ore");
76 78 assert.equal(quest.steps[0].objectives[0].when.all[0].condition.kind, "hasItem");
79 assert.equal(quest.steps[0].exit.kind, "complete");
80 assert.equal(quest.steps[0].exit.implicit, true);
77 81
78 82 const tree = normalizeDialogueTree({
79 83 dialogueId: "Smith",
@@ -149,6 +153,127 @@ test("countable objective progress for hasItem killCount and skillLevelAtLeast",
149 153 "Collect Pine Logs (5 / 30)"
150 154 );
151 155
156 const quests = [{
157 questId: "q",
158 steps: [{ stepId: "alpha" }, { stepId: "beta" }]
159 }];
160 const converted = normalizeConditionSet({
161 all: [
162 { condition: { kind: "questStepAtLeast", questId: "q", step: 1 } },
163 { condition: { kind: "questStepAtLeast", questId: "q", step: 2 } },
164 { condition: { kind: "questStepAtLeast", questId: "q", step: 3 } },
165 { condition: { kind: "questStepAtLeast", questId: "q", step: 9 } },
166 { condition: { kind: "questState", questId: "q", state: 2 } }
167 ]
168 }, { quests });
169 assert.deepEqual(converted.all[0].condition, { kind: "questState", questId: "q", state: "started" });
170 assert.deepEqual(converted.all[1].condition, { kind: "hasCompletedStep", questId: "q", stepId: "alpha" });
171 assert.deepEqual(converted.all[2].condition, { kind: "hasCompletedStep", questId: "q", stepId: "beta" });
172 assert.deepEqual(converted.all[3].condition, { kind: "questState", questId: "q", state: "completed" });
173 assert.equal(converted.all[4].condition.state, "beta");
174
175 const pending = normalizeConditionSet({
176 all: [{ condition: { kind: "questStepAtLeast", questId: "missing", step: 2 } }]
177 });
178 assert.equal(pending.all[0].condition.kind, "questStepAtLeast");
179 assert.equal(
180 evaluateCondition(pending.all[0].condition, {
181 questState: () => "beta",
182 questSteps: () => ["alpha", "beta"],
183 hasCompletedStep: (_questId, stepId) => stepId === "alpha"
184 }),
185 true
186 );
187 assert.equal(
188 evaluateCondition(
189 { kind: ConditionKind.hasCompletedStep, questId: "q", stepId: "alpha" },
190 { hasCompletedStep: (_questId, stepId) => stepId === "alpha" }
191 ),
192 true
193 );
194 assert.equal(
195 evaluateCondition(
196 { kind: ConditionKind.questState, questId: "q", state: "beta" },
197 { questState: () => "beta" }
198 ),
199 true
200 );
201 assert.equal(
202 evaluateCondition(
203 { kind: ConditionKind.questState, questId: "q", state: "started" },
204 { questState: () => "not-started" }
205 ),
206 false
207 );
208
209 const lookup = questLookupFromRawDefs(quests);
210 const tree = normalizeDialogueTree({
211 dialogueId: "gate",
212 steps: [{
213 stepId: "hi",
214 lines: [{ speaker: "npc", text: "Hi" }],
215 exit: {
216 kind: "branches",
217 branches: [{
218 when: { all: [{ condition: { kind: "questStepAtLeast", questId: "q", step: 2 } }] },
219 nextStepId: null
220 }]
221 }
222 }]
223 }, lookup);
224 assert.equal(tree.steps[0].exit.branches[0].when.all[0].condition.kind, "hasCompletedStep");
225 assert.equal(tree.steps[0].exit.branches[0].when.all[0].condition.stepId, "alpha");
226
227 const linked = normalizeQuestDef({
228 questId: "chain",
229 steps: [{ stepId: "a" }, { stepId: "b" }]
230 });
231 assert.equal(linked.steps[0].exit.kind, "continue");
232 assert.equal(linked.steps[0].exit.nextStepId, "b");
233 assert.equal(linked.steps[0].exit.implicit, true);
234 const inserted = normalizeQuestDef({
235 ...linked,
236 steps: [linked.steps[0], { stepId: "mid", title: "Mid" }, linked.steps[1]]
237 });
238 assert.equal(inserted.steps[0].exit.nextStepId, "mid");
239 assert.equal(inserted.steps[1].exit.nextStepId, "b");
240 assert.equal(inserted.steps[2].exit.kind, "complete");
241
242 const branched = normalizeQuestDef({
243 questId: "hub-quest",
244 steps: [{
245 stepId: "hub",
246 exit: {
247 kind: "branches",
248 branches: [{
249 label: "Cave",
250 text: "Stand in the cave",
251 when: { all: [{ condition: { kind: "atTile", tileX: 3, tileY: 4, dimensionId: "cave" } }] },
252 nextStepId: "end"
253 }]
254 }
255 }, { stepId: "end" }]
256 });
257 assert.equal(branched.steps[0].exit.kind, "branches");
258 assert.equal(branched.steps[0].exit.implicit, undefined);
259 assert.equal(branched.steps[0].exit.branches[0].when.all[0].condition.dimensionId, "cave");
260 assert.equal(branched.steps[1].exit.kind, "complete");
261
262 const linearDef = {
263 steps: [{ stepId: "alpha" }, { stepId: "beta" }, { stepId: "gamma" }]
264 };
265 assert.deepEqual(deriveCompletedStepIds(linearDef, 2, {}), ["alpha"]);
266 assert.deepEqual(
267 deriveCompletedStepIds(linearDef, "completed", {}),
268 ["alpha", "beta", "gamma"]
269 );
270 assert.deepEqual(
271 deriveCompletedStepIds(linearDef, "beta", { completedStepIds: ["alpha"] }),
272 ["alpha"]
273 );
274 assert.equal(resolveQuestStepId(linearDef, 2), "beta");
275 assert.equal(resolveQuestStepId(linearDef, "gamma"), "gamma");
276
152 277 const kills = normalizeConditionSet({
153 278 all: [{ condition: { kind: ConditionKind.killCount, mobTypeId: "rat", count: 3 } }]
154 279 });
@@ -10,7 +10,9 @@ import {
10 countableObjectiveProgress,
10 countableObjectiveProgress,
11 formatObjectiveDisplayText
11 formatObjectiveDisplayText
12} from "../../shared/quests/objectiveProgress.js";
12} from "../../shared/quests/objectiveProgress.js";
13import { normalizeQuestDef, normalizeDialogueTree } from "../../shared/quests/normalize.js";
13import { normalizeQuestDef, normalizeDialogueTree, questLookupFromRawDefs } from "../../shared/quests/normalize.js";
14import { deriveCompletedStepIds, resolveQuestStepId } from "../../shared/quests/questProgress.js";
15import { evaluateCondition } from "../../shared/quests/conditions.js";
14import { formatDialogueRewardMessage, formatDialogueQuestRewardMessage, formatDialogueTakeMessage } from "../../shared/quests/dialogueRewards.js";
16import { formatDialogueRewardMessage, formatDialogueQuestRewardMessage, formatDialogueTakeMessage } from "../../shared/quests/dialogueRewards.js";
15
17
16test("ConditionSet AND + NOT", () =>
18test("ConditionSet AND + NOT", () =>
@@ -74,6 +76,8 @@ test("normalize quest and dialogue", () =>
74 });
76 });
75 assert.equal(quest.questId, "fetch-ore");
77 assert.equal(quest.questId, "fetch-ore");
76 assert.equal(quest.steps[0].objectives[0].when.all[0].condition.kind, "hasItem");
78 assert.equal(quest.steps[0].objectives[0].when.all[0].condition.kind, "hasItem");
79 assert.equal(quest.steps[0].exit.kind, "complete");
80 assert.equal(quest.steps[0].exit.implicit, true);
77
81
78 const tree = normalizeDialogueTree({
82 const tree = normalizeDialogueTree({
79 dialogueId: "Smith",
83 dialogueId: "Smith",
@@ -149,6 +153,127 @@ test("countable objective progress for hasItem killCount and skillLevelAtLeast",
149 "Collect Pine Logs (5 / 30)"
153 "Collect Pine Logs (5 / 30)"
150 );
154 );
151
155
156 const quests = [{
157 questId: "q",
158 steps: [{ stepId: "alpha" }, { stepId: "beta" }]
159 }];
160 const converted = normalizeConditionSet({
161 all: [
162 { condition: { kind: "questStepAtLeast", questId: "q", step: 1 } },
163 { condition: { kind: "questStepAtLeast", questId: "q", step: 2 } },
164 { condition: { kind: "questStepAtLeast", questId: "q", step: 3 } },
165 { condition: { kind: "questStepAtLeast", questId: "q", step: 9 } },
166 { condition: { kind: "questState", questId: "q", state: 2 } }
167 ]
168 }, { quests });
169 assert.deepEqual(converted.all[0].condition, { kind: "questState", questId: "q", state: "started" });
170 assert.deepEqual(converted.all[1].condition, { kind: "hasCompletedStep", questId: "q", stepId: "alpha" });
171 assert.deepEqual(converted.all[2].condition, { kind: "hasCompletedStep", questId: "q", stepId: "beta" });
172 assert.deepEqual(converted.all[3].condition, { kind: "questState", questId: "q", state: "completed" });
173 assert.equal(converted.all[4].condition.state, "beta");
174
175 const pending = normalizeConditionSet({
176 all: [{ condition: { kind: "questStepAtLeast", questId: "missing", step: 2 } }]
177 });
178 assert.equal(pending.all[0].condition.kind, "questStepAtLeast");
179 assert.equal(
180 evaluateCondition(pending.all[0].condition, {
181 questState: () => "beta",
182 questSteps: () => ["alpha", "beta"],
183 hasCompletedStep: (_questId, stepId) => stepId === "alpha"
184 }),
185 true
186 );
187 assert.equal(
188 evaluateCondition(
189 { kind: ConditionKind.hasCompletedStep, questId: "q", stepId: "alpha" },
190 { hasCompletedStep: (_questId, stepId) => stepId === "alpha" }
191 ),
192 true
193 );
194 assert.equal(
195 evaluateCondition(
196 { kind: ConditionKind.questState, questId: "q", state: "beta" },
197 { questState: () => "beta" }
198 ),
199 true
200 );
201 assert.equal(
202 evaluateCondition(
203 { kind: ConditionKind.questState, questId: "q", state: "started" },
204 { questState: () => "not-started" }
205 ),
206 false
207 );
208
209 const lookup = questLookupFromRawDefs(quests);
210 const tree = normalizeDialogueTree({
211 dialogueId: "gate",
212 steps: [{
213 stepId: "hi",
214 lines: [{ speaker: "npc", text: "Hi" }],
215 exit: {
216 kind: "branches",
217 branches: [{
218 when: { all: [{ condition: { kind: "questStepAtLeast", questId: "q", step: 2 } }] },
219 nextStepId: null
220 }]
221 }
222 }]
223 }, lookup);
224 assert.equal(tree.steps[0].exit.branches[0].when.all[0].condition.kind, "hasCompletedStep");
225 assert.equal(tree.steps[0].exit.branches[0].when.all[0].condition.stepId, "alpha");
226
227 const linked = normalizeQuestDef({
228 questId: "chain",
229 steps: [{ stepId: "a" }, { stepId: "b" }]
230 });
231 assert.equal(linked.steps[0].exit.kind, "continue");
232 assert.equal(linked.steps[0].exit.nextStepId, "b");
233 assert.equal(linked.steps[0].exit.implicit, true);
234 const inserted = normalizeQuestDef({
235 ...linked,
236 steps: [linked.steps[0], { stepId: "mid", title: "Mid" }, linked.steps[1]]
237 });
238 assert.equal(inserted.steps[0].exit.nextStepId, "mid");
239 assert.equal(inserted.steps[1].exit.nextStepId, "b");
240 assert.equal(inserted.steps[2].exit.kind, "complete");
241
242 const branched = normalizeQuestDef({
243 questId: "hub-quest",
244 steps: [{
245 stepId: "hub",
246 exit: {
247 kind: "branches",
248 branches: [{
249 label: "Cave",
250 text: "Stand in the cave",
251 when: { all: [{ condition: { kind: "atTile", tileX: 3, tileY: 4, dimensionId: "cave" } }] },
252 nextStepId: "end"
253 }]
254 }
255 }, { stepId: "end" }]
256 });
257 assert.equal(branched.steps[0].exit.kind, "branches");
258 assert.equal(branched.steps[0].exit.implicit, undefined);
259 assert.equal(branched.steps[0].exit.branches[0].when.all[0].condition.dimensionId, "cave");
260 assert.equal(branched.steps[1].exit.kind, "complete");
261
262 const linearDef = {
263 steps: [{ stepId: "alpha" }, { stepId: "beta" }, { stepId: "gamma" }]
264 };
265 assert.deepEqual(deriveCompletedStepIds(linearDef, 2, {}), ["alpha"]);
266 assert.deepEqual(
267 deriveCompletedStepIds(linearDef, "completed", {}),
268 ["alpha", "beta", "gamma"]
269 );
270 assert.deepEqual(
271 deriveCompletedStepIds(linearDef, "beta", { completedStepIds: ["alpha"] }),
272 ["alpha"]
273 );
274 assert.equal(resolveQuestStepId(linearDef, 2), "beta");
275 assert.equal(resolveQuestStepId(linearDef, "gamma"), "gamma");
276
152 const kills = normalizeConditionSet({
277 const kills = normalizeConditionSet({
153 all: [{ condition: { kind: ConditionKind.killCount, mobTypeId: "rat", count: 3 } }]
278 all: [{ condition: { kind: ConditionKind.killCount, mobTypeId: "rat", count: 3 } }]
154 });
279 });
shared/quests/conditions.js +148 −19
@@ -2,6 +2,7 @@
2 2
3 3 import { OVERWORLD_ID, normalizeDimensionId } from "../world/dimensions.js";
4 4 import { isMetaSkillId } from "../definitions/skills.js";
5 import { legacyQuestStepNumber } from "./questProgress.js";
5 6
6 7 export const ConditionKind = Object.freeze({
7 8 hasItem: "hasItem",
@@ -12,7 +13,9 @@ export const ConditionKind = Object.freeze({
12 13 inDimension: "inDimension",
13 14 hasVisitedDimension: "hasVisitedDimension",
14 15 questState: "questState",
16 /** @deprecated Read on load and converted. Prefer hasCompletedStep. */
15 17 questStepAtLeast: "questStepAtLeast",
18 hasCompletedStep: "hasCompletedStep",
16 19 dialogueHeard: "dialogueHeard",
17 20 dialogueTrigger: "dialogueTrigger",
18 21 hpAtLeast: "hpAtLeast",
@@ -68,13 +71,19 @@ export function emptyConditionSet ()
68 71 return { mode: ConditionSetMode.allOf, all: [] };
69 72 }
70 73
71 export function normalizeConditionSet (raw)
74 /**
75 * @param {object | Array | null | undefined} raw
76 * @param {{ quests?: Function | Array | Map } | Function | null} [options]
77 * Quest catalog so legacy questStepAtLeast / numeric questState can convert on load.
78 */
79 export function normalizeConditionSet (raw, options = null)
72 80 {
81 const lookup = questLookupFromOptions(options);
73 82 const all = [];
74 83 const list = Array.isArray(raw?.all) ? raw.all : (Array.isArray(raw) ? raw : []);
75 84 for (const entry of list)
76 85 {
77 const clause = normalizeConditionClause(entry);
86 const clause = normalizeConditionClause(entry, lookup);
78 87 if (clause)
79 88 { all.push(clause); }
80 89 }
@@ -84,7 +93,25 @@ export function normalizeConditionSet (raw)
84 93 };
85 94 }
86 95
87 function normalizeConditionClause (entry)
96 function questLookupFromOptions (options)
97 {
98 const quests = typeof options === "function" ? options : options?.quests;
99 if (typeof quests === "function")
100 { return quests; }
101 if (!quests)
102 { return null; }
103 const map = new Map();
104 const list = quests instanceof Map ? [...quests.values()] : quests;
105 for (const quest of list ?? [])
106 {
107 const questId = String(quest?.questId ?? "").trim();
108 if (questId)
109 { map.set(questId, quest); }
110 }
111 return (questId) => map.get(String(questId ?? "")) ?? null;
112 }
113
114 function normalizeConditionClause (entry, lookup)
88 115 {
89 116 if (!entry || typeof entry !== "object")
90 117 { return null; }
@@ -96,10 +123,58 @@ function normalizeConditionClause (entry)
96 123 { return null; }
97 124 return {
98 125 not: !!entry.not,
99 condition: normalizeConditionFields({ ...condition, kind })
126 condition: convertLegacyQuestCondition(
127 normalizeConditionFields({ ...condition, kind }),
128 lookup
129 )
100 130 };
101 131 }
102 132
133 /**
134 * questStepAtLeast step 1 → quest started.
135 * questStepAtLeast step N (N > 1) → hasCompletedStep of step N-1.
136 * Past the end of a known quest → quest completed (the only way the old check passed).
137 * Numeric questState → that step's id, when the quest def is available.
138 * Unknown quests keep questStepAtLeast so a later load can still convert.
139 */
140 export function convertLegacyQuestCondition (condition, lookup)
141 {
142 if (!condition || typeof condition !== "object")
143 { return condition; }
144 if (condition.kind === ConditionKind.questState)
145 {
146 const index = legacyQuestStepNumber(condition.state);
147 if (index == null || !lookup)
148 { return condition; }
149 const step = lookup(condition.questId)?.steps?.[index - 1];
150 if (!step?.stepId)
151 { return condition; }
152 return { ...condition, state: step.stepId };
153 }
154 if (condition.kind !== ConditionKind.questStepAtLeast)
155 { return condition; }
156 const stepNum = Math.max(1, Number(condition.step) || 1);
157 const questId = String(condition.questId ?? "").trim().slice(0, 80);
158 if (stepNum <= 1)
159 { return { kind: ConditionKind.questState, questId, state: "started" }; }
160 const def = lookup?.(questId) ?? null;
161 const steps = def?.steps ?? null;
162 if (!steps)
163 {
164 return { kind: ConditionKind.questStepAtLeast, questId, step: stepNum };
165 }
166 const prev = steps[stepNum - 2];
167 if (prev?.stepId)
168 {
169 return {
170 kind: ConditionKind.hasCompletedStep,
171 questId,
172 stepId: String(prev.stepId)
173 };
174 }
175 return { kind: ConditionKind.questState, questId, state: "completed" };
176 }
177
103 178 /** Ensure place conditions carry dimensionId (default overworld). */
104 179 function normalizeConditionFields (condition)
105 180 {
@@ -119,6 +194,22 @@ function normalizeConditionFields (condition)
119 194 dimensionId: normalizeDimensionId(condition.dimensionId ?? OVERWORLD_ID)
120 195 };
121 196 }
197 if (kind === ConditionKind.hasCompletedStep)
198 {
199 return {
200 kind,
201 questId: String(condition.questId ?? "").trim().slice(0, 80),
202 stepId: String(condition.stepId ?? "").trim().slice(0, 64)
203 };
204 }
205 if (kind === ConditionKind.questState)
206 {
207 return {
208 ...condition,
209 kind,
210 questId: String(condition.questId ?? "").trim().slice(0, 80)
211 };
212 }
122 213 return condition;
123 214 }
124 215
@@ -205,17 +296,16 @@ export function evaluateCondition (condition, ctx)
205 296 normalizeDimensionId(condition.dimensionId ?? OVERWORLD_ID)
206 297 );
207 298 case ConditionKind.questState:
208 return questStatesEqual(ctx.questState?.(condition.questId), condition.state);
299 return questStatesEqual(
300 ctx.questState?.(condition.questId),
301 condition.state,
302 condition.questId,
303 ctx
304 );
305 case ConditionKind.hasCompletedStep:
306 return !!ctx.hasCompletedStep?.(condition.questId, condition.stepId);
209 307 case ConditionKind.questStepAtLeast:
210 {
211 const state = ctx.questState?.(condition.questId);
212 const step = Math.max(1, Number(condition.step) || 1);
213 if (state === "completed")
214 { return true; }
215 if (typeof state === "number")
216 { return state >= step; }
217 return false;
218 }
308 return evaluateLegacyQuestStepAtLeast(condition, ctx);
219 309 case ConditionKind.dialogueHeard:
220 310 return !!ctx.dialogueHeard?.(condition.dialogueId, condition.stepId);
221 311 case ConditionKind.dialogueTrigger:
@@ -248,12 +338,51 @@ export function evaluateCondition (condition, ctx)
248 338 }
249 339 }
250 340
251 function questStatesEqual (actual, expected)
341 function questStatesEqual (actual, expected, questId, ctx)
252 342 {
253 if (expected === "not-started" || expected === "completed")
254 { return actual === expected || (expected === "not-started" && (actual == null || actual === "not-started")); }
255 const n = Number(expected);
256 return Number.isFinite(n) && actual === (n | 0);
343 const want = resolveExpectedQuestState(expected, questId, ctx);
344 if (want === "started")
345 { return actual != null && actual !== "not-started"; }
346 if (want === "not-started")
347 { return actual == null || actual === "not-started"; }
348 if (want === "completed")
349 { return actual === "completed"; }
350 return String(actual ?? "") === String(want ?? "");
351 }
352
353 /** Numeric questState ("on step N") maps through the quest's step list when known. */
354 function resolveExpectedQuestState (expected, questId, ctx)
355 {
356 if (expected === "not-started" || expected === "completed" || expected === "started")
357 { return expected; }
358 const index = legacyQuestStepNumber(expected);
359 if (index != null)
360 {
361 const steps = ctx?.questSteps?.(questId);
362 if (Array.isArray(steps) && steps[index - 1])
363 { return steps[index - 1]; }
364 }
365 return expected;
366 }
367
368 /**
369 * Unconverted questStepAtLeast, same rule as convertLegacyQuestCondition:
370 * step 1 = started, step N = has completed step N-1, past the end = quest completed.
371 */
372 function evaluateLegacyQuestStepAtLeast (condition, ctx)
373 {
374 const stepNum = Math.max(1, Number(condition?.step) || 1);
375 const questId = condition?.questId;
376 const actual = ctx.questState?.(questId);
377 if (stepNum <= 1)
378 { return actual != null && actual !== "not-started"; }
379 const steps = ctx.questSteps?.(questId);
380 if (!Array.isArray(steps))
381 { return false; }
382 const prev = steps[stepNum - 2];
383 if (!prev)
384 { return actual === "completed"; }
385 return !!ctx.hasCompletedStep?.(questId, prev);
257 386 }
258 387
259 388 export const EffectKind = Object.freeze({
@@ -2,6 +2,7 @@
2
2
3import { OVERWORLD_ID, normalizeDimensionId } from "../world/dimensions.js";
3import { OVERWORLD_ID, normalizeDimensionId } from "../world/dimensions.js";
4import { isMetaSkillId } from "../definitions/skills.js";
4import { isMetaSkillId } from "../definitions/skills.js";
5import { legacyQuestStepNumber } from "./questProgress.js";
5
6
6export const ConditionKind = Object.freeze({
7export const ConditionKind = Object.freeze({
7 hasItem: "hasItem",
8 hasItem: "hasItem",
@@ -12,7 +13,9 @@ export const ConditionKind = Object.freeze({
12 inDimension: "inDimension",
13 inDimension: "inDimension",
13 hasVisitedDimension: "hasVisitedDimension",
14 hasVisitedDimension: "hasVisitedDimension",
14 questState: "questState",
15 questState: "questState",
16 /** @deprecated Read on load and converted. Prefer hasCompletedStep. */
15 questStepAtLeast: "questStepAtLeast",
17 questStepAtLeast: "questStepAtLeast",
18 hasCompletedStep: "hasCompletedStep",
16 dialogueHeard: "dialogueHeard",
19 dialogueHeard: "dialogueHeard",
17 dialogueTrigger: "dialogueTrigger",
20 dialogueTrigger: "dialogueTrigger",
18 hpAtLeast: "hpAtLeast",
21 hpAtLeast: "hpAtLeast",
@@ -68,13 +71,19 @@ export function emptyConditionSet ()
68 return { mode: ConditionSetMode.allOf, all: [] };
71 return { mode: ConditionSetMode.allOf, all: [] };
69}
72}
70
73
71export function normalizeConditionSet (raw)
74/**
75 * @param {object | Array | null | undefined} raw
76 * @param {{ quests?: Function | Array | Map } | Function | null} [options]
77 * Quest catalog so legacy questStepAtLeast / numeric questState can convert on load.
78 */
79export function normalizeConditionSet (raw, options = null)
72{
80{
81 const lookup = questLookupFromOptions(options);
73 const all = [];
82 const all = [];
74 const list = Array.isArray(raw?.all) ? raw.all : (Array.isArray(raw) ? raw : []);
83 const list = Array.isArray(raw?.all) ? raw.all : (Array.isArray(raw) ? raw : []);
75 for (const entry of list)
84 for (const entry of list)
76 {
85 {
77 const clause = normalizeConditionClause(entry);
86 const clause = normalizeConditionClause(entry, lookup);
78 if (clause)
87 if (clause)
79 { all.push(clause); }
88 { all.push(clause); }
80 }
89 }
@@ -84,7 +93,25 @@ export function normalizeConditionSet (raw)
84 };
93 };
85}
94}
86
95
87function normalizeConditionClause (entry)
96function questLookupFromOptions (options)
97{
98 const quests = typeof options === "function" ? options : options?.quests;
99 if (typeof quests === "function")
100 { return quests; }
101 if (!quests)
102 { return null; }
103 const map = new Map();
104 const list = quests instanceof Map ? [...quests.values()] : quests;
105 for (const quest of list ?? [])
106 {
107 const questId = String(quest?.questId ?? "").trim();
108 if (questId)
109 { map.set(questId, quest); }
110 }
111 return (questId) => map.get(String(questId ?? "")) ?? null;
112}
113
114function normalizeConditionClause (entry, lookup)
88{
115{
89 if (!entry || typeof entry !== "object")
116 if (!entry || typeof entry !== "object")
90 { return null; }
117 { return null; }
@@ -96,10 +123,58 @@ function normalizeConditionClause (entry)
96 { return null; }
123 { return null; }
97 return {
124 return {
98 not: !!entry.not,
125 not: !!entry.not,
99 condition: normalizeConditionFields({ ...condition, kind })
126 condition: convertLegacyQuestCondition(
127 normalizeConditionFields({ ...condition, kind }),
128 lookup
129 )
100 };
130 };
101}
131}
102
132
133/**
134 * questStepAtLeast step 1 → quest started.
135 * questStepAtLeast step N (N > 1) → hasCompletedStep of step N-1.
136 * Past the end of a known quest → quest completed (the only way the old check passed).
137 * Numeric questState → that step's id, when the quest def is available.
138 * Unknown quests keep questStepAtLeast so a later load can still convert.
139 */
140export function convertLegacyQuestCondition (condition, lookup)
141{
142 if (!condition || typeof condition !== "object")
143 { return condition; }
144 if (condition.kind === ConditionKind.questState)
145 {
146 const index = legacyQuestStepNumber(condition.state);
147 if (index == null || !lookup)
148 { return condition; }
149 const step = lookup(condition.questId)?.steps?.[index - 1];
150 if (!step?.stepId)
151 { return condition; }
152 return { ...condition, state: step.stepId };
153 }
154 if (condition.kind !== ConditionKind.questStepAtLeast)
155 { return condition; }
156 const stepNum = Math.max(1, Number(condition.step) || 1);
157 const questId = String(condition.questId ?? "").trim().slice(0, 80);
158 if (stepNum <= 1)
159 { return { kind: ConditionKind.questState, questId, state: "started" }; }
160 const def = lookup?.(questId) ?? null;
161 const steps = def?.steps ?? null;
162 if (!steps)
163 {
164 return { kind: ConditionKind.questStepAtLeast, questId, step: stepNum };
165 }
166 const prev = steps[stepNum - 2];
167 if (prev?.stepId)
168 {
169 return {
170 kind: ConditionKind.hasCompletedStep,
171 questId,
172 stepId: String(prev.stepId)
173 };
174 }
175 return { kind: ConditionKind.questState, questId, state: "completed" };
176}
177
103/** Ensure place conditions carry dimensionId (default overworld). */
178/** Ensure place conditions carry dimensionId (default overworld). */
104function normalizeConditionFields (condition)
179function normalizeConditionFields (condition)
105{
180{
@@ -119,6 +194,22 @@ function normalizeConditionFields (condition)
119 dimensionId: normalizeDimensionId(condition.dimensionId ?? OVERWORLD_ID)
194 dimensionId: normalizeDimensionId(condition.dimensionId ?? OVERWORLD_ID)
120 };
195 };
121 }
196 }
197 if (kind === ConditionKind.hasCompletedStep)
198 {
199 return {
200 kind,
201 questId: String(condition.questId ?? "").trim().slice(0, 80),
202 stepId: String(condition.stepId ?? "").trim().slice(0, 64)
203 };
204 }
205 if (kind === ConditionKind.questState)
206 {
207 return {
208 ...condition,
209 kind,
210 questId: String(condition.questId ?? "").trim().slice(0, 80)
211 };
212 }
122 return condition;
213 return condition;
123}
214}
124
215
@@ -205,17 +296,16 @@ export function evaluateCondition (condition, ctx)
205 normalizeDimensionId(condition.dimensionId ?? OVERWORLD_ID)
296 normalizeDimensionId(condition.dimensionId ?? OVERWORLD_ID)
206 );
297 );
207 case ConditionKind.questState:
298 case ConditionKind.questState:
208 return questStatesEqual(ctx.questState?.(condition.questId), condition.state);
299 return questStatesEqual(
300 ctx.questState?.(condition.questId),
301 condition.state,
302 condition.questId,
303 ctx
304 );
305 case ConditionKind.hasCompletedStep:
306 return !!ctx.hasCompletedStep?.(condition.questId, condition.stepId);
209 case ConditionKind.questStepAtLeast:
307 case ConditionKind.questStepAtLeast:
210 {
308 return evaluateLegacyQuestStepAtLeast(condition, ctx);
211 const state = ctx.questState?.(condition.questId);
212 const step = Math.max(1, Number(condition.step) || 1);
213 if (state === "completed")
214 { return true; }
215 if (typeof state === "number")
216 { return state >= step; }
217 return false;
218 }
219 case ConditionKind.dialogueHeard:
309 case ConditionKind.dialogueHeard:
220 return !!ctx.dialogueHeard?.(condition.dialogueId, condition.stepId);
310 return !!ctx.dialogueHeard?.(condition.dialogueId, condition.stepId);
221 case ConditionKind.dialogueTrigger:
311 case ConditionKind.dialogueTrigger:
@@ -248,12 +338,51 @@ export function evaluateCondition (condition, ctx)
248 }
338 }
249}
339}
250
340
251function questStatesEqual (actual, expected)
341function questStatesEqual (actual, expected, questId, ctx)
252{
342{
253 if (expected === "not-started" || expected === "completed")
343 const want = resolveExpectedQuestState(expected, questId, ctx);
254 { return actual === expected || (expected === "not-started" && (actual == null || actual === "not-started")); }
344 if (want === "started")
255 const n = Number(expected);
345 { return actual != null && actual !== "not-started"; }
256 return Number.isFinite(n) && actual === (n | 0);
346 if (want === "not-started")
347 { return actual == null || actual === "not-started"; }
348 if (want === "completed")
349 { return actual === "completed"; }
350 return String(actual ?? "") === String(want ?? "");
351}
352
353/** Numeric questState ("on step N") maps through the quest's step list when known. */
354function resolveExpectedQuestState (expected, questId, ctx)
355{
356 if (expected === "not-started" || expected === "completed" || expected === "started")
357 { return expected; }
358 const index = legacyQuestStepNumber(expected);
359 if (index != null)
360 {
361 const steps = ctx?.questSteps?.(questId);
362 if (Array.isArray(steps) && steps[index - 1])
363 { return steps[index - 1]; }
364 }
365 return expected;
366}
367
368/**
369 * Unconverted questStepAtLeast, same rule as convertLegacyQuestCondition:
370 * step 1 = started, step N = has completed step N-1, past the end = quest completed.
371 */
372function evaluateLegacyQuestStepAtLeast (condition, ctx)
373{
374 const stepNum = Math.max(1, Number(condition?.step) || 1);
375 const questId = condition?.questId;
376 const actual = ctx.questState?.(questId);
377 if (stepNum <= 1)
378 { return actual != null && actual !== "not-started"; }
379 const steps = ctx.questSteps?.(questId);
380 if (!Array.isArray(steps))
381 { return false; }
382 const prev = steps[stepNum - 2];
383 if (!prev)
384 { return actual === "completed"; }
385 return !!ctx.hasCompletedStep?.(questId, prev);
257}
386}
258
387
259export const EffectKind = Object.freeze({
388export const EffectKind = Object.freeze({
shared/quests/normalize.js +123 −23
@@ -1,32 +1,66 @@
1 1 import { normalizeConditionSet, normalizeEffects, emptyConditionSet } from "./conditions.js";
2 2
3 export function normalizeQuestDef (raw)
3 /**
4 * Step ids only, matching normalizeQuestDef, so condition conversion can run
5 * before (or without) a fully normalized catalog.
6 */
7 export function previewQuestDef (raw)
4 8 {
5 9 const questId = slugId(raw?.questId ?? raw?.id, "quest");
6 10 const stepsIn = Array.isArray(raw?.steps) ? raw.steps : [];
7 const steps = stepsIn.map((step, index) => normalizeQuestStep(step, index)).filter(Boolean);
11 let steps = stepsIn.map((step, index) => ({
12 stepId: slugId(step?.stepId ?? step?.id, `step-${index + 1}`)
13 }));
14 if (steps.length === 0)
15 { steps = [{ stepId: "step-1" }]; }
16 return { questId, steps };
17 }
18
19 /** Later raws overwrite the same questId (the def being saved wins). */
20 export function questLookupFromRawDefs (raws)
21 {
22 const map = new Map();
23 for (const raw of raws ?? [])
24 {
25 const preview = previewQuestDef(raw);
26 map.set(preview.questId, preview);
27 }
28 return (questId) => map.get(String(questId ?? "")) ?? null;
29 }
30
31 /**
32 * @param {object} raw
33 * @param {Function | null} [questLookup] Catalog for legacy quest-progress conditions.
34 */
35 export function normalizeQuestDef (raw, questLookup = null)
36 {
37 const questId = slugId(raw?.questId ?? raw?.id, "quest");
38 const stepsIn = Array.isArray(raw?.steps) ? raw.steps : [];
39 const steps = stepsIn.map((step, index) => normalizeQuestStep(step, index, questLookup)).filter(Boolean);
40 const safeSteps = steps.length > 0 ? steps : [normalizeQuestStep({ stepId: "step-1" }, 0, questLookup)];
41 linkImplicitQuestExits(safeSteps);
8 42 return {
9 43 questId,
10 44 title: String(raw?.title ?? questId).trim().slice(0, 80) || questId,
11 45 description: String(raw?.description ?? "").trim().slice(0, 500),
12 steps: steps.length > 0 ? steps : [normalizeQuestStep({ stepId: "step-1" }, 0)],
46 steps: safeSteps,
13 47 rewards: normalizeEffects(raw?.rewards),
14 48 cancelable: !!raw?.cancelable
15 49 };
16 50 }
17 51
18 function normalizeQuestStep (raw, index)
52 function normalizeQuestStep (raw, index, questLookup)
19 53 {
20 54 const stepId = slugId(raw?.stepId ?? raw?.id, `step-${index + 1}`);
21 55 const objectivesIn = Array.isArray(raw?.objectives) ? raw.objectives : [];
22 let objectives = objectivesIn.map((obj, i) => normalizeObjective(obj, i)).filter(Boolean);
56 let objectives = objectivesIn.map((obj, i) => normalizeObjective(obj, i, questLookup)).filter(Boolean);
23 57 if (objectives.length === 0)
24 58 {
25 59 objectives = [normalizeObjective({
26 60 objectiveId: "obj-1",
27 61 text: "Complete this step",
28 62 when: emptyConditionSet()
29 }, 0)];
63 }, 0, questLookup)];
30 64 }
31 65 return {
32 66 stepId,
@@ -35,14 +69,80 @@ function normalizeQuestStep (raw, index)
35 69 completionJournalText: String(raw?.completionJournalText ?? "").trim().slice(0, 500),
36 70 objectives,
37 71 onEnter: normalizeEffects(raw?.onEnter),
38 onComplete: normalizeEffects(raw?.onComplete)
72 onComplete: normalizeEffects(raw?.onComplete),
73 exit: normalizeExplicitQuestExit(raw?.exit, questLookup)
74 };
75 }
76
77 /**
78 * Missing exit, or exit.implicit, is re-linked to array order on every load
79 * so the linear editor can insert steps without rewriting stored blobs.
80 * Explicit exits (continue / branches / complete without implicit) are kept.
81 */
82 function normalizeExplicitQuestExit (exit, questLookup)
83 {
84 if (!exit || typeof exit !== "object" || exit.implicit === true || !exit.kind)
85 { return null; }
86 if (exit.kind === "branches")
87 {
88 return {
89 kind: "branches",
90 branches: (Array.isArray(exit.branches) ? exit.branches : [])
91 .map((branch) => normalizeQuestBranch(branch, questLookup))
92 .filter(Boolean)
93 };
94 }
95 if (exit.kind === "continue")
96 {
97 const next = exit.nextStepId == null || exit.nextStepId === ""
98 ? null
99 : slugId(exit.nextStepId, "");
100 return { kind: "continue", nextStepId: next || null };
101 }
102 if (exit.kind === "complete")
103 { return { kind: "complete" }; }
104 return null;
105 }
106
107 function linkImplicitQuestExits (steps)
108 {
109 for (let index = 0; index < steps.length; index++)
110 {
111 if (steps[index].exit)
112 { continue; }
113 if (index === steps.length - 1)
114 { steps[index].exit = { kind: "complete", implicit: true }; }
115 else
116 {
117 steps[index].exit = {
118 kind: "continue",
119 nextStepId: steps[index + 1].stepId,
120 implicit: true
121 };
122 }
123 }
124 }
125
126 function normalizeQuestBranch (raw, questLookup)
127 {
128 if (!raw || typeof raw !== "object")
129 { return null; }
130 const next = raw.nextStepId == null || raw.nextStepId === ""
131 ? null
132 : slugId(raw.nextStepId, "");
133 return {
134 label: String(raw.label ?? "").trim().slice(0, 80),
135 text: String(raw.text ?? "").trim().slice(0, 200),
136 when: normalizeConditionSet(raw.when ?? raw.require, { quests: questLookup }),
137 nextStepId: next || null,
138 effects: normalizeEffects(raw.effects)
39 139 };
40 140 }
41 141
42 function normalizeObjective (raw, index)
142 function normalizeObjective (raw, index, questLookup)
43 143 {
44 144 const objectiveId = slugId(raw?.objectiveId ?? raw?.id, `obj-${index + 1}`);
45 const when = normalizeConditionSet(raw?.when ?? raw?.require);
145 const when = normalizeConditionSet(raw?.when ?? raw?.require, { quests: questLookup });
46 146 return {
47 147 objectiveId,
48 148 text: String(raw?.text ?? objectiveId).trim().slice(0, 200) || objectiveId,
@@ -50,11 +150,11 @@ function normalizeObjective (raw, index)
50 150 };
51 151 }
52 152
53 export function normalizeDialogueTree (raw)
153 export function normalizeDialogueTree (raw, questLookup = null)
54 154 {
55 155 const dialogueId = slugId(raw?.dialogueId ?? raw?.id, "dialogue");
56 156 const stepsIn = Array.isArray(raw?.steps) ? raw.steps : [];
57 const steps = stepsIn.map((step, index) => normalizeDialogueStep(step, index)).filter(Boolean);
157 const steps = stepsIn.map((step, index) => normalizeDialogueStep(step, index, questLookup)).filter(Boolean);
58 158 const safeSteps = steps.length > 0
59 159 ? steps
60 160 : [normalizeDialogueStep({
@@ -62,7 +162,7 @@ export function normalizeDialogueTree (raw)
62 162 label: "Greeting",
63 163 lines: [{ speaker: "npc", text: "…" }],
64 164 exit: { kind: "end" }
65 }, 0)];
165 }, 0, questLookup)];
66 166 const entryStepId = slugId(raw?.entryStepId ?? safeSteps[0].stepId, safeSteps[0].stepId);
67 167 const ids = new Set(safeSteps.map((s) => s.stepId));
68 168 return {
@@ -74,12 +174,12 @@ export function normalizeDialogueTree (raw)
74 174 };
75 175 }
76 176
77 function normalizeDialogueStep (raw, index)
177 function normalizeDialogueStep (raw, index, questLookup)
78 178 {
79 179 const stepId = slugId(raw?.stepId ?? raw?.id, `step-${index + 1}`);
80 180 const linesIn = Array.isArray(raw?.lines) ? raw.lines : [];
81 181 const lines = linesIn.map(normalizeDialogueLine).filter(Boolean);
82 const exit = normalizeExit(raw?.exit, raw);
182 const exit = normalizeExit(raw?.exit, raw, questLookup);
83 183 const out = {
84 184 stepId,
85 185 label: String(raw?.label ?? stepId).trim().slice(0, 80) || stepId,
@@ -150,7 +250,7 @@ function normalizeDialogueLine (raw)
150 250 return { speaker, text, effects: normalizeEffects(raw.effects) };
151 251 }
152 252
153 function normalizeExit (exit, legacy)
253 function normalizeExit (exit, legacy, questLookup)
154 254 {
155 255 if (exit && typeof exit === "object" && exit.kind)
156 256 {
@@ -159,7 +259,7 @@ function normalizeExit (exit, legacy)
159 259 return {
160 260 kind: "triggers",
161 261 triggers: (Array.isArray(exit.triggers) ? exit.triggers : [])
162 .map(normalizeTrigger)
262 .map((trigger) => normalizeTrigger(trigger, questLookup))
163 263 .filter(Boolean)
164 264 };
165 265 }
@@ -168,7 +268,7 @@ function normalizeExit (exit, legacy)
168 268 return {
169 269 kind: "branches",
170 270 branches: (Array.isArray(exit.branches) ? exit.branches : [])
171 .map(normalizeBranch)
271 .map((branch) => normalizeBranch(branch, questLookup))
172 272 .filter(Boolean)
173 273 };
174 274 }
@@ -188,20 +288,20 @@ function normalizeExit (exit, legacy)
188 288 {
189 289 return {
190 290 kind: "triggers",
191 triggers: legacy.triggers.map(normalizeTrigger).filter(Boolean)
291 triggers: legacy.triggers.map((trigger) => normalizeTrigger(trigger, questLookup)).filter(Boolean)
192 292 };
193 293 }
194 294 if (Array.isArray(legacy?.branches) && legacy.branches.length > 0)
195 295 {
196 296 return {
197 297 kind: "branches",
198 branches: legacy.branches.map(normalizeBranch).filter(Boolean)
298 branches: legacy.branches.map((branch) => normalizeBranch(branch, questLookup)).filter(Boolean)
199 299 };
200 300 }
201 301 return { kind: "end" };
202 302 }
203 303
204 function normalizeTrigger (raw)
304 function normalizeTrigger (raw, questLookup)
205 305 {
206 306 if (!raw || typeof raw !== "object")
207 307 { return null; }
@@ -217,12 +317,12 @@ function normalizeTrigger (raw)
217 317 label: String(raw.label ?? trigger).trim().slice(0, 80) || trigger,
218 318 text,
219 319 nextStepId: next || null,
220 when: normalizeConditionSet(raw.when ?? raw.require),
320 when: normalizeConditionSet(raw.when ?? raw.require, { quests: questLookup }),
221 321 effects: normalizeEffects(raw.effects)
222 322 };
223 323 }
224 324
225 function normalizeBranch (raw)
325 function normalizeBranch (raw, questLookup)
226 326 {
227 327 if (!raw || typeof raw !== "object")
228 328 { return null; }
@@ -231,7 +331,7 @@ function normalizeBranch (raw)
231 331 : slugId(raw.nextStepId, "");
232 332 return {
233 333 label: String(raw.label ?? "").trim().slice(0, 80),
234 when: normalizeConditionSet(raw.when ?? raw.require),
334 when: normalizeConditionSet(raw.when ?? raw.require, { quests: questLookup }),
235 335 nextStepId: next || null,
236 336 effects: normalizeEffects(raw.effects)
237 337 };
@@ -1,32 +1,66 @@
1import { normalizeConditionSet, normalizeEffects, emptyConditionSet } from "./conditions.js";
1import { normalizeConditionSet, normalizeEffects, emptyConditionSet } from "./conditions.js";
2
2
3export function normalizeQuestDef (raw)
3/**
4 * Step ids only, matching normalizeQuestDef, so condition conversion can run
5 * before (or without) a fully normalized catalog.
6 */
7export function previewQuestDef (raw)
4{
8{
5 const questId = slugId(raw?.questId ?? raw?.id, "quest");
9 const questId = slugId(raw?.questId ?? raw?.id, "quest");
6 const stepsIn = Array.isArray(raw?.steps) ? raw.steps : [];
10 const stepsIn = Array.isArray(raw?.steps) ? raw.steps : [];
7 const steps = stepsIn.map((step, index) => normalizeQuestStep(step, index)).filter(Boolean);
11 let steps = stepsIn.map((step, index) => ({
12 stepId: slugId(step?.stepId ?? step?.id, `step-${index + 1}`)
13 }));
14 if (steps.length === 0)
15 { steps = [{ stepId: "step-1" }]; }
16 return { questId, steps };
17}
18
19/** Later raws overwrite the same questId (the def being saved wins). */
20export function questLookupFromRawDefs (raws)
21{
22 const map = new Map();
23 for (const raw of raws ?? [])
24 {
25 const preview = previewQuestDef(raw);
26 map.set(preview.questId, preview);
27 }
28 return (questId) => map.get(String(questId ?? "")) ?? null;
29}
30
31/**
32 * @param {object} raw
33 * @param {Function | null} [questLookup] Catalog for legacy quest-progress conditions.
34 */
35export function normalizeQuestDef (raw, questLookup = null)
36{
37 const questId = slugId(raw?.questId ?? raw?.id, "quest");
38 const stepsIn = Array.isArray(raw?.steps) ? raw.steps : [];
39 const steps = stepsIn.map((step, index) => normalizeQuestStep(step, index, questLookup)).filter(Boolean);
40 const safeSteps = steps.length > 0 ? steps : [normalizeQuestStep({ stepId: "step-1" }, 0, questLookup)];
41 linkImplicitQuestExits(safeSteps);
8 return {
42 return {
9 questId,
43 questId,
10 title: String(raw?.title ?? questId).trim().slice(0, 80) || questId,
44 title: String(raw?.title ?? questId).trim().slice(0, 80) || questId,
11 description: String(raw?.description ?? "").trim().slice(0, 500),
45 description: String(raw?.description ?? "").trim().slice(0, 500),
12 steps: steps.length > 0 ? steps : [normalizeQuestStep({ stepId: "step-1" }, 0)],
46 steps: safeSteps,
13 rewards: normalizeEffects(raw?.rewards),
47 rewards: normalizeEffects(raw?.rewards),
14 cancelable: !!raw?.cancelable
48 cancelable: !!raw?.cancelable
15 };
49 };
16}
50}
17
51
18function normalizeQuestStep (raw, index)
52function normalizeQuestStep (raw, index, questLookup)
19{
53{
20 const stepId = slugId(raw?.stepId ?? raw?.id, `step-${index + 1}`);
54 const stepId = slugId(raw?.stepId ?? raw?.id, `step-${index + 1}`);
21 const objectivesIn = Array.isArray(raw?.objectives) ? raw.objectives : [];
55 const objectivesIn = Array.isArray(raw?.objectives) ? raw.objectives : [];
22 let objectives = objectivesIn.map((obj, i) => normalizeObjective(obj, i)).filter(Boolean);
56 let objectives = objectivesIn.map((obj, i) => normalizeObjective(obj, i, questLookup)).filter(Boolean);
23 if (objectives.length === 0)
57 if (objectives.length === 0)
24 {
58 {
25 objectives = [normalizeObjective({
59 objectives = [normalizeObjective({
26 objectiveId: "obj-1",
60 objectiveId: "obj-1",
27 text: "Complete this step",
61 text: "Complete this step",
28 when: emptyConditionSet()
62 when: emptyConditionSet()
29 }, 0)];
63 }, 0, questLookup)];
30 }
64 }
31 return {
65 return {
32 stepId,
66 stepId,
@@ -35,14 +69,80 @@ function normalizeQuestStep (raw, index)
35 completionJournalText: String(raw?.completionJournalText ?? "").trim().slice(0, 500),
69 completionJournalText: String(raw?.completionJournalText ?? "").trim().slice(0, 500),
36 objectives,
70 objectives,
37 onEnter: normalizeEffects(raw?.onEnter),
71 onEnter: normalizeEffects(raw?.onEnter),
38 onComplete: normalizeEffects(raw?.onComplete)
72 onComplete: normalizeEffects(raw?.onComplete),
73 exit: normalizeExplicitQuestExit(raw?.exit, questLookup)
74 };
75}
76
77/**
78 * Missing exit, or exit.implicit, is re-linked to array order on every load
79 * so the linear editor can insert steps without rewriting stored blobs.
80 * Explicit exits (continue / branches / complete without implicit) are kept.
81 */
82function normalizeExplicitQuestExit (exit, questLookup)
83{
84 if (!exit || typeof exit !== "object" || exit.implicit === true || !exit.kind)
85 { return null; }
86 if (exit.kind === "branches")
87 {
88 return {
89 kind: "branches",
90 branches: (Array.isArray(exit.branches) ? exit.branches : [])
91 .map((branch) => normalizeQuestBranch(branch, questLookup))
92 .filter(Boolean)
93 };
94 }
95 if (exit.kind === "continue")
96 {
97 const next = exit.nextStepId == null || exit.nextStepId === ""
98 ? null
99 : slugId(exit.nextStepId, "");
100 return { kind: "continue", nextStepId: next || null };
101 }
102 if (exit.kind === "complete")
103 { return { kind: "complete" }; }
104 return null;
105}
106
107function linkImplicitQuestExits (steps)
108{
109 for (let index = 0; index < steps.length; index++)
110 {
111 if (steps[index].exit)
112 { continue; }
113 if (index === steps.length - 1)
114 { steps[index].exit = { kind: "complete", implicit: true }; }
115 else
116 {
117 steps[index].exit = {
118 kind: "continue",
119 nextStepId: steps[index + 1].stepId,
120 implicit: true
121 };
122 }
123 }
124}
125
126function normalizeQuestBranch (raw, questLookup)
127{
128 if (!raw || typeof raw !== "object")
129 { return null; }
130 const next = raw.nextStepId == null || raw.nextStepId === ""
131 ? null
132 : slugId(raw.nextStepId, "");
133 return {
134 label: String(raw.label ?? "").trim().slice(0, 80),
135 text: String(raw.text ?? "").trim().slice(0, 200),
136 when: normalizeConditionSet(raw.when ?? raw.require, { quests: questLookup }),
137 nextStepId: next || null,
138 effects: normalizeEffects(raw.effects)
39 };
139 };
40}
140}
41
141
42function normalizeObjective (raw, index)
142function normalizeObjective (raw, index, questLookup)
43{
143{
44 const objectiveId = slugId(raw?.objectiveId ?? raw?.id, `obj-${index + 1}`);
144 const objectiveId = slugId(raw?.objectiveId ?? raw?.id, `obj-${index + 1}`);
45 const when = normalizeConditionSet(raw?.when ?? raw?.require);
145 const when = normalizeConditionSet(raw?.when ?? raw?.require, { quests: questLookup });
46 return {
146 return {
47 objectiveId,
147 objectiveId,
48 text: String(raw?.text ?? objectiveId).trim().slice(0, 200) || objectiveId,
148 text: String(raw?.text ?? objectiveId).trim().slice(0, 200) || objectiveId,
@@ -50,11 +150,11 @@ function normalizeObjective (raw, index)
50 };
150 };
51}
151}
52
152
53export function normalizeDialogueTree (raw)
153export function normalizeDialogueTree (raw, questLookup = null)
54{
154{
55 const dialogueId = slugId(raw?.dialogueId ?? raw?.id, "dialogue");
155 const dialogueId = slugId(raw?.dialogueId ?? raw?.id, "dialogue");
56 const stepsIn = Array.isArray(raw?.steps) ? raw.steps : [];
156 const stepsIn = Array.isArray(raw?.steps) ? raw.steps : [];
57 const steps = stepsIn.map((step, index) => normalizeDialogueStep(step, index)).filter(Boolean);
157 const steps = stepsIn.map((step, index) => normalizeDialogueStep(step, index, questLookup)).filter(Boolean);
58 const safeSteps = steps.length > 0
158 const safeSteps = steps.length > 0
59 ? steps
159 ? steps
60 : [normalizeDialogueStep({
160 : [normalizeDialogueStep({
@@ -62,7 +162,7 @@ export function normalizeDialogueTree (raw)
62 label: "Greeting",
162 label: "Greeting",
63 lines: [{ speaker: "npc", text: "…" }],
163 lines: [{ speaker: "npc", text: "…" }],
64 exit: { kind: "end" }
164 exit: { kind: "end" }
65 }, 0)];
165 }, 0, questLookup)];
66 const entryStepId = slugId(raw?.entryStepId ?? safeSteps[0].stepId, safeSteps[0].stepId);
166 const entryStepId = slugId(raw?.entryStepId ?? safeSteps[0].stepId, safeSteps[0].stepId);
67 const ids = new Set(safeSteps.map((s) => s.stepId));
167 const ids = new Set(safeSteps.map((s) => s.stepId));
68 return {
168 return {
@@ -74,12 +174,12 @@ export function normalizeDialogueTree (raw)
74 };
174 };
75}
175}
76
176
77function normalizeDialogueStep (raw, index)
177function normalizeDialogueStep (raw, index, questLookup)
78{
178{
79 const stepId = slugId(raw?.stepId ?? raw?.id, `step-${index + 1}`);
179 const stepId = slugId(raw?.stepId ?? raw?.id, `step-${index + 1}`);
80 const linesIn = Array.isArray(raw?.lines) ? raw.lines : [];
180 const linesIn = Array.isArray(raw?.lines) ? raw.lines : [];
81 const lines = linesIn.map(normalizeDialogueLine).filter(Boolean);
181 const lines = linesIn.map(normalizeDialogueLine).filter(Boolean);
82 const exit = normalizeExit(raw?.exit, raw);
182 const exit = normalizeExit(raw?.exit, raw, questLookup);
83 const out = {
183 const out = {
84 stepId,
184 stepId,
85 label: String(raw?.label ?? stepId).trim().slice(0, 80) || stepId,
185 label: String(raw?.label ?? stepId).trim().slice(0, 80) || stepId,
@@ -150,7 +250,7 @@ function normalizeDialogueLine (raw)
150 return { speaker, text, effects: normalizeEffects(raw.effects) };
250 return { speaker, text, effects: normalizeEffects(raw.effects) };
151}
251}
152
252
153function normalizeExit (exit, legacy)
253function normalizeExit (exit, legacy, questLookup)
154{
254{
155 if (exit && typeof exit === "object" && exit.kind)
255 if (exit && typeof exit === "object" && exit.kind)
156 {
256 {
@@ -159,7 +259,7 @@ function normalizeExit (exit, legacy)
159 return {
259 return {
160 kind: "triggers",
260 kind: "triggers",
161 triggers: (Array.isArray(exit.triggers) ? exit.triggers : [])
261 triggers: (Array.isArray(exit.triggers) ? exit.triggers : [])
162 .map(normalizeTrigger)
262 .map((trigger) => normalizeTrigger(trigger, questLookup))
163 .filter(Boolean)
263 .filter(Boolean)
164 };
264 };
165 }
265 }
@@ -168,7 +268,7 @@ function normalizeExit (exit, legacy)
168 return {
268 return {
169 kind: "branches",
269 kind: "branches",
170 branches: (Array.isArray(exit.branches) ? exit.branches : [])
270 branches: (Array.isArray(exit.branches) ? exit.branches : [])
171 .map(normalizeBranch)
271 .map((branch) => normalizeBranch(branch, questLookup))
172 .filter(Boolean)
272 .filter(Boolean)
173 };
273 };
174 }
274 }
@@ -188,20 +288,20 @@ function normalizeExit (exit, legacy)
188 {
288 {
189 return {
289 return {
190 kind: "triggers",
290 kind: "triggers",
191 triggers: legacy.triggers.map(normalizeTrigger).filter(Boolean)
291 triggers: legacy.triggers.map((trigger) => normalizeTrigger(trigger, questLookup)).filter(Boolean)
192 };
292 };
193 }
293 }
194 if (Array.isArray(legacy?.branches) && legacy.branches.length > 0)
294 if (Array.isArray(legacy?.branches) && legacy.branches.length > 0)
195 {
295 {
196 return {
296 return {
197 kind: "branches",
297 kind: "branches",
198 branches: legacy.branches.map(normalizeBranch).filter(Boolean)
298 branches: legacy.branches.map((branch) => normalizeBranch(branch, questLookup)).filter(Boolean)
199 };
299 };
200 }
300 }
201 return { kind: "end" };
301 return { kind: "end" };
202}
302}
203
303
204function normalizeTrigger (raw)
304function normalizeTrigger (raw, questLookup)
205{
305{
206 if (!raw || typeof raw !== "object")
306 if (!raw || typeof raw !== "object")
207 { return null; }
307 { return null; }
@@ -217,12 +317,12 @@ function normalizeTrigger (raw)
217 label: String(raw.label ?? trigger).trim().slice(0, 80) || trigger,
317 label: String(raw.label ?? trigger).trim().slice(0, 80) || trigger,
218 text,
318 text,
219 nextStepId: next || null,
319 nextStepId: next || null,
220 when: normalizeConditionSet(raw.when ?? raw.require),
320 when: normalizeConditionSet(raw.when ?? raw.require, { quests: questLookup }),
221 effects: normalizeEffects(raw.effects)
321 effects: normalizeEffects(raw.effects)
222 };
322 };
223}
323}
224
324
225function normalizeBranch (raw)
325function normalizeBranch (raw, questLookup)
226{
326{
227 if (!raw || typeof raw !== "object")
327 if (!raw || typeof raw !== "object")
228 { return null; }
328 { return null; }
@@ -231,7 +331,7 @@ function normalizeBranch (raw)
231 : slugId(raw.nextStepId, "");
331 : slugId(raw.nextStepId, "");
232 return {
332 return {
233 label: String(raw.label ?? "").trim().slice(0, 80),
333 label: String(raw.label ?? "").trim().slice(0, 80),
234 when: normalizeConditionSet(raw.when ?? raw.require),
334 when: normalizeConditionSet(raw.when ?? raw.require, { quests: questLookup }),
235 nextStepId: next || null,
335 nextStepId: next || null,
236 effects: normalizeEffects(raw.effects)
336 effects: normalizeEffects(raw.effects)
237 };
337 };
shared/quests/questProgress.js added +114 −0
@@ -0,0 +1,114 @@
1 /**
2 * Player quest position: step id, with a numeric index fallback for saves
3 * written before branching quests. `completedStepIds` in the progress blob
4 * records every step the player has ever finished (merge/loop safe).
5 */
6
7 /** 1-based step index stored by older builds, or null when `state` is a step id. */
8 export function legacyQuestStepNumber (state)
9 {
10 if (typeof state === "number" && Number.isFinite(state))
11 {
12 const n = state | 0;
13 return n >= 1 ? n : null;
14 }
15 if (typeof state === "string" && /^\d+$/.test(state))
16 {
17 const n = Number(state) | 0;
18 return n >= 1 ? n : null;
19 }
20 return null;
21 }
22
23 /**
24 * DB `state_value` → runtime value.
25 * Pure integer strings stay numeric (legacy index). Anything else is a step id.
26 * A step id that is itself all digits is ambiguous with a legacy index; callers
27 * that know the quest def must prefer an exact stepId match (see resolveQuestStepId).
28 */
29 export function parseStoredQuestState (stateValue)
30 {
31 if (stateValue === "not-started" || stateValue === "completed")
32 { return stateValue; }
33 const index = legacyQuestStepNumber(stateValue);
34 if (index != null)
35 { return index; }
36 const text = String(stateValue ?? "").trim();
37 return text || "not-started";
38 }
39
40 export function serializeQuestState (state)
41 {
42 if (state === "not-started" || state === "completed")
43 { return state; }
44 if (typeof state === "number" && Number.isFinite(state))
45 { return String(state | 0); }
46 return String(state ?? "");
47 }
48
49 export function isActiveQuestState (state)
50 {
51 return state != null && state !== "not-started" && state !== "completed";
52 }
53
54 /**
55 * Current step id for an active quest, or the terminal token.
56 * Exact stepId match wins over a legacy index so a step literally named "2"
57 * is not read as "the second step".
58 */
59 export function resolveQuestStepId (def, state)
60 {
61 if (state === "completed")
62 { return "completed"; }
63 if (!isActiveQuestState(state))
64 { return "not-started"; }
65 const steps = def?.steps ?? [];
66 const text = typeof state === "number" ? String(state | 0) : String(state);
67 const byId = steps.find((step) => step?.stepId === text);
68 if (byId)
69 { return byId.stepId; }
70 const index = legacyQuestStepNumber(state);
71 if (index != null)
72 { return steps[index - 1]?.stepId ?? null; }
73 return text;
74 }
75
76 /**
77 * Steps the player has finished.
78 * A stored `completedStepIds` array is authoritative (including an empty one).
79 * Older rows derive it: every step before the numeric index, or every step
80 * when the quest is already completed.
81 */
82 export function deriveCompletedStepIds (def, state, progress)
83 {
84 if (Array.isArray(progress?.completedStepIds))
85 {
86 const out = [];
87 const seen = new Set();
88 for (const id of progress.completedStepIds)
89 {
90 const stepId = String(id ?? "").trim();
91 if (!stepId || seen.has(stepId))
92 { continue; }
93 seen.add(stepId);
94 out.push(stepId);
95 }
96 return out;
97 }
98 const steps = def?.steps ?? [];
99 if (state === "completed")
100 { return steps.map((step) => step.stepId).filter(Boolean); }
101 const index = legacyQuestStepNumber(state);
102 if (index == null)
103 { return []; }
104 return steps.slice(0, Math.max(0, index - 1)).map((step) => step.stepId).filter(Boolean);
105 }
106
107 export function rememberCompletedStep (ids, stepId)
108 {
109 const next = Array.isArray(ids) ? [...ids] : [];
110 const id = String(stepId ?? "").trim();
111 if (id && !next.includes(id))
112 { next.push(id); }
113 return next;
114 }
@@ -0,0 +1,114 @@
1/**
2 * Player quest position: step id, with a numeric index fallback for saves
3 * written before branching quests. `completedStepIds` in the progress blob
4 * records every step the player has ever finished (merge/loop safe).
5 */
6
7/** 1-based step index stored by older builds, or null when `state` is a step id. */
8export function legacyQuestStepNumber (state)
9{
10 if (typeof state === "number" && Number.isFinite(state))
11 {
12 const n = state | 0;
13 return n >= 1 ? n : null;
14 }
15 if (typeof state === "string" && /^\d+$/.test(state))
16 {
17 const n = Number(state) | 0;
18 return n >= 1 ? n : null;
19 }
20 return null;
21}
22
23/**
24 * DB `state_value` → runtime value.
25 * Pure integer strings stay numeric (legacy index). Anything else is a step id.
26 * A step id that is itself all digits is ambiguous with a legacy index; callers
27 * that know the quest def must prefer an exact stepId match (see resolveQuestStepId).
28 */
29export function parseStoredQuestState (stateValue)
30{
31 if (stateValue === "not-started" || stateValue === "completed")
32 { return stateValue; }
33 const index = legacyQuestStepNumber(stateValue);
34 if (index != null)
35 { return index; }
36 const text = String(stateValue ?? "").trim();
37 return text || "not-started";
38}
39
40export function serializeQuestState (state)
41{
42 if (state === "not-started" || state === "completed")
43 { return state; }
44 if (typeof state === "number" && Number.isFinite(state))
45 { return String(state | 0); }
46 return String(state ?? "");
47}
48
49export function isActiveQuestState (state)
50{
51 return state != null && state !== "not-started" && state !== "completed";
52}
53
54/**
55 * Current step id for an active quest, or the terminal token.
56 * Exact stepId match wins over a legacy index so a step literally named "2"
57 * is not read as "the second step".
58 */
59export function resolveQuestStepId (def, state)
60{
61 if (state === "completed")
62 { return "completed"; }
63 if (!isActiveQuestState(state))
64 { return "not-started"; }
65 const steps = def?.steps ?? [];
66 const text = typeof state === "number" ? String(state | 0) : String(state);
67 const byId = steps.find((step) => step?.stepId === text);
68 if (byId)
69 { return byId.stepId; }
70 const index = legacyQuestStepNumber(state);
71 if (index != null)
72 { return steps[index - 1]?.stepId ?? null; }
73 return text;
74}
75
76/**
77 * Steps the player has finished.
78 * A stored `completedStepIds` array is authoritative (including an empty one).
79 * Older rows derive it: every step before the numeric index, or every step
80 * when the quest is already completed.
81 */
82export function deriveCompletedStepIds (def, state, progress)
83{
84 if (Array.isArray(progress?.completedStepIds))
85 {
86 const out = [];
87 const seen = new Set();
88 for (const id of progress.completedStepIds)
89 {
90 const stepId = String(id ?? "").trim();
91 if (!stepId || seen.has(stepId))
92 { continue; }
93 seen.add(stepId);
94 out.push(stepId);
95 }
96 return out;
97 }
98 const steps = def?.steps ?? [];
99 if (state === "completed")
100 { return steps.map((step) => step.stepId).filter(Boolean); }
101 const index = legacyQuestStepNumber(state);
102 if (index == null)
103 { return []; }
104 return steps.slice(0, Math.max(0, index - 1)).map((step) => step.stepId).filter(Boolean);
105}
106
107export function rememberCompletedStep (ids, stepId)
108{
109 const next = Array.isArray(ids) ? [...ids] : [];
110 const id = String(stepId ?? "").trim();
111 if (id && !next.includes(id))
112 { next.push(id); }
113 return next;
114}