BlueGit

timfa questward

Files

questward / shared / quests / normalize.js

normalize.js

feat: edit quests on the shared step canvas
timfa project_85689633_bot_760517ee9267c86ff1d6c3a0237abf7d · pushed by timfa · 4 weeks ago
745e7e52 History
normalize.js 10.6 KiB Download Raw
1import { normalizeConditionSet, normalizeEffects, emptyConditionSet } from "./conditions.js";
2
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)
8{
9 const questId = slugId(raw?.questId ?? raw?.id, "quest");
10 const stepsIn = Array.isArray(raw?.steps) ? raw.steps : [];
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);
42 return {
43 questId,
44 title: String(raw?.title ?? questId).trim().slice(0, 80) || questId,
45 description: String(raw?.description ?? "").trim().slice(0, 500),
46 steps: safeSteps,
47 rewards: normalizeEffects(raw?.rewards),
48 cancelable: !!raw?.cancelable
49 };
50}
51
52function normalizeQuestStep (raw, index, questLookup)
53{
54 const stepId = slugId(raw?.stepId ?? raw?.id, `step-${index + 1}`);
55 const objectivesIn = Array.isArray(raw?.objectives) ? raw.objectives : [];
56 let objectives = objectivesIn.map((obj, i) => normalizeObjective(obj, i, questLookup)).filter(Boolean);
57 if (objectives.length === 0)
58 {
59 objectives = [normalizeObjective({
60 objectiveId: "obj-1",
61 text: "Complete this step",
62 when: emptyConditionSet()
63 }, 0, questLookup)];
64 }
65 const out = {
66 stepId,
67 title: String(raw?.title ?? stepId).trim().slice(0, 80) || stepId,
68 description: String(raw?.description ?? "").trim().slice(0, 500),
69 completionJournalText: String(raw?.completionJournalText ?? "").trim().slice(0, 500),
70 objectives,
71 onEnter: normalizeEffects(raw?.onEnter),
72 onComplete: normalizeEffects(raw?.onComplete),
73 exit: normalizeExplicitQuestExit(raw?.exit, questLookup)
74 };
75 const editorX = Number(raw?.editorX);
76 const editorY = Number(raw?.editorY);
77 if (Number.isFinite(editorX))
78 { out.editorX = editorX; }
79 if (Number.isFinite(editorY))
80 { out.editorY = editorY; }
81 return out;
82}
83
84/**
85 * Missing exit, or exit.implicit, is re-linked to array order on every load
86 * so the linear editor can insert steps without rewriting stored blobs.
87 * Explicit exits (continue / branches / complete without implicit) are kept.
88 */
89function normalizeExplicitQuestExit (exit, questLookup)
90{
91 if (!exit || typeof exit !== "object" || exit.implicit === true || !exit.kind)
92 { return null; }
93 if (exit.kind === "branches")
94 {
95 return {
96 kind: "branches",
97 branches: (Array.isArray(exit.branches) ? exit.branches : [])
98 .map((branch) => normalizeQuestBranch(branch, questLookup))
99 .filter(Boolean)
100 };
101 }
102 if (exit.kind === "continue")
103 {
104 const next = exit.nextStepId == null || exit.nextStepId === ""
105 ? null
106 : slugId(exit.nextStepId, "");
107 return { kind: "continue", nextStepId: next || null };
108 }
109 if (exit.kind === "complete")
110 { return { kind: "complete" }; }
111 return null;
112}
113
114function linkImplicitQuestExits (steps)
115{
116 for (let index = 0; index < steps.length; index++)
117 {
118 if (steps[index].exit)
119 { continue; }
120 if (index === steps.length - 1)
121 { steps[index].exit = { kind: "complete", implicit: true }; }
122 else
123 {
124 steps[index].exit = {
125 kind: "continue",
126 nextStepId: steps[index + 1].stepId,
127 implicit: true
128 };
129 }
130 }
131}
132
133/**
134 * Rebuild implicit exits from the current array order.
135 * Explicit exits (no implicit flag) keep their nextStepId.
136 */
137export function relinkImplicitQuestExits (steps)
138{
139 for (const step of steps ?? [])
140 {
141 if (step?.exit?.implicit === true)
142 { step.exit = null; }
143 }
144 linkImplicitQuestExits(steps ?? []);
145 return steps;
146}
147
148function normalizeQuestBranch (raw, questLookup)
149{
150 if (!raw || typeof raw !== "object")
151 { return null; }
152 const next = raw.nextStepId == null || raw.nextStepId === ""
153 ? null
154 : slugId(raw.nextStepId, "");
155 return {
156 label: String(raw.label ?? "").trim().slice(0, 80),
157 text: String(raw.text ?? "").trim().slice(0, 200),
158 when: normalizeConditionSet(raw.when ?? raw.require, { quests: questLookup }),
159 nextStepId: next || null,
160 effects: normalizeEffects(raw.effects)
161 };
162}
163
164function normalizeObjective (raw, index, questLookup)
165{
166 const objectiveId = slugId(raw?.objectiveId ?? raw?.id, `obj-${index + 1}`);
167 const when = normalizeConditionSet(raw?.when ?? raw?.require, { quests: questLookup });
168 return {
169 objectiveId,
170 text: String(raw?.text ?? objectiveId).trim().slice(0, 200) || objectiveId,
171 when
172 };
173}
174
175export function normalizeDialogueTree (raw, questLookup = null)
176{
177 const dialogueId = slugId(raw?.dialogueId ?? raw?.id, "dialogue");
178 const stepsIn = Array.isArray(raw?.steps) ? raw.steps : [];
179 const steps = stepsIn.map((step, index) => normalizeDialogueStep(step, index, questLookup)).filter(Boolean);
180 const safeSteps = steps.length > 0
181 ? steps
182 : [normalizeDialogueStep({
183 stepId: "greeting",
184 label: "Greeting",
185 lines: [{ speaker: "npc", text: "…" }],
186 exit: { kind: "end" }
187 }, 0, questLookup)];
188 const entryStepId = slugId(raw?.entryStepId ?? safeSteps[0].stepId, safeSteps[0].stepId);
189 const ids = new Set(safeSteps.map((s) => s.stepId));
190 return {
191 dialogueId,
192 label: String(raw?.label ?? dialogueId).trim().slice(0, 80) || dialogueId,
193 unique: !!raw?.unique,
194 entryStepId: ids.has(entryStepId) ? entryStepId : safeSteps[0].stepId,
195 steps: safeSteps
196 };
197}
198
199function normalizeDialogueStep (raw, index, questLookup)
200{
201 const stepId = slugId(raw?.stepId ?? raw?.id, `step-${index + 1}`);
202 const linesIn = Array.isArray(raw?.lines) ? raw.lines : [];
203 const lines = linesIn.map(normalizeDialogueLine).filter(Boolean);
204 const exit = normalizeExit(raw?.exit, raw, questLookup);
205 const out = {
206 stepId,
207 label: String(raw?.label ?? stepId).trim().slice(0, 80) || stepId,
208 lines: lines.length > 0 ? lines : [{ speaker: "npc", text: "…", effects: [] }],
209 itemRewards: normalizeItemRewards(raw?.itemRewards),
210 itemTakes: normalizeItemRewards(raw?.itemTakes),
211 questRewards: normalizeQuestRewards(raw?.questRewards),
212 exit
213 };
214 const editorX = Number(raw?.editorX);
215 const editorY = Number(raw?.editorY);
216 if (Number.isFinite(editorX))
217 { out.editorX = editorX; }
218 if (Number.isFinite(editorY))
219 { out.editorY = editorY; }
220 return out;
221}
222
223/** Step-level gifts granted after all lines are read, before exit triggers/branches. */
224function normalizeItemRewards (raw)
225{
226 if (!Array.isArray(raw))
227 { return []; }
228 const out = [];
229 const seen = new Set();
230 for (const entry of raw)
231 {
232 if (!entry || typeof entry !== "object")
233 { continue; }
234 const itemId = Number(entry.itemId);
235 if (!Number.isFinite(itemId) || itemId <= 0 || seen.has(itemId))
236 { continue; }
237 seen.add(itemId);
238 out.push({
239 itemId: itemId | 0,
240 quantity: Math.max(1, Math.min(99_999, Number(entry.quantity) || 1)) | 0
241 });
242 }
243 return out;
244}
245
246/** Step-level quests started after lines (same moment as item rewards). */
247function normalizeQuestRewards (raw)
248{
249 if (!Array.isArray(raw))
250 { return []; }
251 const out = [];
252 const seen = new Set();
253 for (const entry of raw)
254 {
255 const questId = String(entry?.questId ?? entry ?? "").trim().slice(0, 80);
256 if (!questId || seen.has(questId))
257 { continue; }
258 seen.add(questId);
259 out.push(questId);
260 }
261 return out;
262}
263
264function normalizeDialogueLine (raw)
265{
266 if (!raw || typeof raw !== "object")
267 { return null; }
268 const text = String(raw.text ?? "").trim().slice(0, 500);
269 if (!text)
270 { return null; }
271 const speaker = raw.speaker === "player" ? "player" : "npc";
272 return { speaker, text, effects: normalizeEffects(raw.effects) };
273}
274
275function normalizeExit (exit, legacy, questLookup)
276{
277 if (exit && typeof exit === "object" && exit.kind)
278 {
279 if (exit.kind === "triggers")
280 {
281 return {
282 kind: "triggers",
283 triggers: (Array.isArray(exit.triggers) ? exit.triggers : [])
284 .map((trigger) => normalizeTrigger(trigger, questLookup))
285 .filter(Boolean)
286 };
287 }
288 if (exit.kind === "branches")
289 {
290 return {
291 kind: "branches",
292 branches: (Array.isArray(exit.branches) ? exit.branches : [])
293 .map((branch) => normalizeBranch(branch, questLookup))
294 .filter(Boolean)
295 };
296 }
297 if (exit.kind === "continue")
298 {
299 const next = exit.nextStepId == null || exit.nextStepId === ""
300 ? null
301 : slugId(exit.nextStepId, "");
302 return {
303 kind: "continue",
304 nextStepId: next || null
305 };
306 }
307 return { kind: "end" };
308 }
309 if (Array.isArray(legacy?.triggers) && legacy.triggers.length > 0)
310 {
311 return {
312 kind: "triggers",
313 triggers: legacy.triggers.map((trigger) => normalizeTrigger(trigger, questLookup)).filter(Boolean)
314 };
315 }
316 if (Array.isArray(legacy?.branches) && legacy.branches.length > 0)
317 {
318 return {
319 kind: "branches",
320 branches: legacy.branches.map((branch) => normalizeBranch(branch, questLookup)).filter(Boolean)
321 };
322 }
323 return { kind: "end" };
324}
325
326function normalizeTrigger (raw, questLookup)
327{
328 if (!raw || typeof raw !== "object")
329 { return null; }
330 const trigger = slugId(raw.trigger ?? raw.id, "choice");
331 const text = String(raw.text ?? "").trim().slice(0, 120);
332 if (!text)
333 { return null; }
334 const next = raw.nextStepId == null || raw.nextStepId === ""
335 ? null
336 : slugId(raw.nextStepId, "");
337 return {
338 trigger,
339 label: String(raw.label ?? trigger).trim().slice(0, 80) || trigger,
340 text,
341 nextStepId: next || null,
342 when: normalizeConditionSet(raw.when ?? raw.require, { quests: questLookup }),
343 effects: normalizeEffects(raw.effects)
344 };
345}
346
347function normalizeBranch (raw, questLookup)
348{
349 if (!raw || typeof raw !== "object")
350 { return null; }
351 const next = raw.nextStepId == null || raw.nextStepId === ""
352 ? null
353 : slugId(raw.nextStepId, "");
354 return {
355 label: String(raw.label ?? "").trim().slice(0, 80),
356 when: normalizeConditionSet(raw.when ?? raw.require, { quests: questLookup }),
357 nextStepId: next || null,
358 effects: normalizeEffects(raw.effects)
359 };
360}
361
362function slugId (raw, fallback)
363{
364 const s = String(raw ?? "")
365 .trim()
366 .toLowerCase()
367 .replace(/[^a-z0-9_-]+/g, "-")
368 .replace(/^-+|-+$/g, "")
369 .slice(0, 64);
370 return s || fallback;
371}