BlueGit

timfa questward

Files

questward / server / src / alchemy / service.js

service.js

service.js 24.1 KiB Download Raw
1import { Component } from "../ecs/components.js";
2import { BlockType } from "../../../shared/definitions/tiles.js";
3import {
4 AlchemyStepKind,
5 CAULDRON_SLOT_COUNT,
6 DYE_CAULDRON_SLOT_COUNT
7} from "../../../shared/definitions/alchemy.js";
8import { ItemId, itemDefinition } from "../../../shared/definitions/items.js";
9import { SkillId } from "../../../shared/definitions/skills.js";
10import {
11 evaluateAlchemyBottle,
12 potionItemInstance,
13 recipePaperBody,
14 resolvedAlchemyPotions,
15 cauldronFlavorText
16} from "../../../shared/alchemy/recipes.js";
17import {
18 DEFAULT_DYE_FILL,
19 FLOWER_MAX_STACK,
20 mixFlowersForDye
21} from "../../../shared/definitions/dyes.js";
22import { bagView, placeOrMergeGroundStack } from "../items/bags.js";
23import {
24 countItemInSlots,
25 emptySlots,
26 insertStack,
27 normalizeInventorySlots,
28 takeMatchingFromSlots,
29 stackQuantity
30} from "../../../shared/items/inventory.js";
31import { isFullPotionBottle } from "../../../shared/items/charges.js";
32import { attachOrigins, craftOrigin, CraftOriginVerb, writtenOrigin, normalizeOrigins } from "../../../shared/items/origin.js";
33import { applySkillXp, publicSkillsPayload, storedSkillXp } from "../../../shared/skills/state.js";
34import {
35 craftXpForConsumedInputs,
36 craftXpMultiplierForSkill
37} from "../../../shared/definitions/gathering.js";
38import { tileToChunk, tileToLocal } from "../world/coordinates.js";
39import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
40import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";
41import { randomUUID } from "node:crypto";
42import { tileShoveTowardBlock } from "../simulation/tileInteract.js";
43
44/**
45 * Cauldron UI slot contents live on the client only.
46 * Server sessions track brew *steps* and soft ingredient claims (itemId/qty/instance)
47 * without removing items from the bag until bottle / create-dye succeeds.
48 */
49
50function userError (message)
51{
52 const error = new Error(message);
53 error.userFacing = true;
54 return error;
55}
56
57function characterDisplayName (world, handle)
58{
59 const appearance = world.ecs.get(handle, Component.appearance);
60 const name = [appearance?.firstName, appearance?.lastName].filter(Boolean).join(" ").trim();
61 return name || "someone";
62}
63
64function ensureSessions (world)
65{
66 if (!world.cauldronSessions)
67 { world.cauldronSessions = new Map(); }
68 return world.cauldronSessions;
69}
70
71function emptySession ()
72{
73 return {
74 /** Soft claims for alchemy inserts — still in the bag until bottle. */
75 pendingBrew: [],
76 steps: [],
77 lastSuccessRecipe: null
78 };
79}
80
81function sessionView (session)
82{
83 const steps = session.steps ?? [];
84 return {
85 // Slots / dye slots are client-only; never authoritative on the server.
86 slots: Array.from({ length: CAULDRON_SLOT_COUNT }, () => null),
87 dyeSlots: Array.from({ length: DYE_CAULDRON_SLOT_COUNT }, () => null),
88 brew: (session.pendingBrew ?? []).map((row) => ({
89 itemId: row.itemId,
90 quantity: row.quantity | 0,
91 instance: row.instance ? structuredClone(row.instance) : null
92 })),
93 steps: steps.map((step) => ({ ...step })),
94 flavorText: cauldronFlavorText(steps),
95 canProcessActions: steps.some((step) => step.kind === AlchemyStepKind.insert),
96 /** Top ingredient slots lock after the first brew step until Bottle/Clear. */
97 canAddIngredients: steps.length === 0,
98 canSaveRecipe: !!session.lastSuccessRecipe,
99 lastSuccess: session.lastSuccessRecipe
100 ? {
101 potionKey: session.lastSuccessRecipe.potionKey,
102 displayName: session.lastSuccessRecipe.displayName,
103 minAlchemyLevel: session.lastSuccessRecipe.minAlchemyLevel ?? 1
104 }
105 : null
106 };
107}
108
109function nearCauldron (world, tileX, tileY, dimensionId = OVERWORLD_ID)
110{
111 const dim = normalizeDimensionId(dimensionId);
112 for (let dy = -1; dy <= 1; dy++)
113 {
114 for (let dx = -1; dx <= 1; dx++)
115 {
116 if (dx === 0 && dy === 0)
117 { continue; }
118 const data = world.chunkData(tileToChunk(tileX + dx), tileToChunk(tileY + dy), dim);
119 const index = tileToLocal(tileY + dy) * CHUNK_SIZE + tileToLocal(tileX + dx);
120 if (data.blocks[index]?.typeId === BlockType.cauldron)
121 { return true; }
122 }
123 }
124 return false;
125}
126
127function requireNearCauldron (world, handle)
128{
129 const position = world.ecs.get(handle, Component.position);
130 const dim = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID);
131 if (!nearCauldron(world, position.tileX, position.tileY, dim))
132 { throw userError("Stand next to a cauldron."); }
133}
134
135function requireSession (world, characterId)
136{
137 const session = ensureSessions(world).get(characterId);
138 if (!session)
139 { throw userError("Open a cauldron first."); }
140 return session;
141}
142
143function clearAlchemy (session)
144{
145 session.pendingBrew = [];
146 session.steps = [];
147}
148
149function ensureInventory (world, handle)
150{
151 let inventory = world.ecs.get(handle, Component.inventory);
152 if (!inventory)
153 { inventory = world.ecs.add(handle, Component.inventory, { slots: emptySlots() }); }
154 inventory.slots = normalizeInventorySlots(inventory.slots ?? emptySlots());
155 return inventory;
156}
157
158function countMatchingInstance (slots, itemId, instance)
159{
160 let total = 0;
161 const key = JSON.stringify(instance ?? null);
162 for (const slot of slots ?? [])
163 {
164 if (!slot || slot.itemId !== itemId)
165 { continue; }
166 if (JSON.stringify(slot.instance ?? null) !== key)
167 { continue; }
168 total += stackQuantity(slot.quantity);
169 }
170 return total;
171}
172
173function pendingClaimedQuantity (pendingBrew, itemId, instance)
174{
175 const key = JSON.stringify(instance ?? null);
176 let total = 0;
177 for (const row of pendingBrew ?? [])
178 {
179 if (row.itemId !== itemId)
180 { continue; }
181 if (JSON.stringify(row.instance ?? null) !== key)
182 { continue; }
183 total += row.quantity | 0;
184 }
185 return total;
186}
187
188function addPendingBrew (session, brewRow)
189{
190 const existing = session.pendingBrew.find((row) =>
191 row.itemId === brewRow.itemId
192 && JSON.stringify(row.instance ?? null) === JSON.stringify(brewRow.instance ?? null));
193 if (existing)
194 { existing.quantity += brewRow.quantity; }
195 else
196 { session.pendingBrew.push(brewRow); }
197}
198
199function refundStacks (inventory, rows)
200{
201 for (const row of rows ?? [])
202 {
203 const def = itemDefinition(row.itemId);
204 const refund = insertStack(inventory.slots, attachOrigins({
205 itemId: row.itemId,
206 quantity: row.quantity,
207 instance: row.instance ? structuredClone(row.instance) : null,
208 origins: row.origins ?? normalizeOrigins(row)
209 }), def);
210 if (refund.ok)
211 { inventory.slots = refund.slots; }
212 }
213}
214
215export function handleAlchemyCommand (world, sessionId, command)
216{
217 switch (command.type)
218 {
219 case "open-cauldron":
220 return openCauldron(world, sessionId, command);
221 case "cauldron-set-slot":
222 case "cauldron-set-dye-slot":
223 // Slot UI is client-only; ignore mutations, echo session for sync.
224 return echoSession(world, sessionId, command);
225 case "cauldron-insert":
226 return insertIngredient(world, sessionId, command);
227 case "cauldron-action":
228 return action(world, sessionId, command);
229 case "cauldron-bottle":
230 return bottle(world, sessionId, command);
231 case "cauldron-create-dye":
232 return createDye(world, sessionId, command);
233 case "cauldron-clear":
234 return clear(world, sessionId, command);
235 case "cauldron-clear-dye":
236 return clearDye(world, sessionId, command);
237 case "cauldron-save-recipe":
238 return saveRecipe(world, sessionId, command);
239 case "cauldron-close":
240 return closeCauldron(world, sessionId, command);
241 default:
242 return null;
243 }
244}
245
246function echoSession (world, sessionId, command)
247{
248 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
249 requireNearCauldron(world, handle);
250 const session = requireSession(world, command.characterId);
251 return {
252 events: [],
253 private: bagView(world.ecs, handle),
254 cauldron: true,
255 cauldronState: sessionView(session)
256 };
257}
258
259function openCauldron (world, sessionId, command)
260{
261 const { handle, entityId } = world.requireOwnedEntity(sessionId, command.characterId);
262 requireNearCauldron(world, handle);
263 const inventory = ensureInventory(world, handle);
264 if (countItemInSlots(inventory.slots, ItemId.glassBottle) < 1)
265 { throw userError("I don't have any empty bottles."); }
266
267 const sessions = ensureSessions(world);
268 const existing = sessions.get(command.characterId) ?? emptySession();
269 if (!Array.isArray(existing.pendingBrew))
270 { existing.pendingBrew = []; }
271 if (!Array.isArray(existing.steps))
272 { existing.steps = []; }
273 sessions.set(command.characterId, existing);
274 const shove = tileShoveTowardBlock(world, handle, entityId, BlockType.cauldron);
275 return {
276 events: shove ? [shove] : [],
277 private: bagView(world.ecs, handle),
278 cauldron: true,
279 cauldronState: sessionView(existing)
280 };
281}
282
283function closeCauldron (world, sessionId, command)
284{
285 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
286 // Soft claims only — bag never held station items.
287 ensureSessions(world).delete(command.characterId);
288 return { events: [], private: bagView(world.ecs, handle), cauldron: false };
289}
290
291function insertIngredient (world, sessionId, command)
292{
293 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
294 requireNearCauldron(world, handle);
295 const session = requireSession(world, command.characterId);
296
297 const itemId = command.itemId | 0;
298 const quantity = Math.max(0, command.quantity | 0);
299 if (!itemId || quantity <= 0)
300 { throw userError("Nothing to insert."); }
301
302 const def = itemDefinition(itemId);
303 const instance = command.instance ? structuredClone(command.instance) : null;
304 const isPotion = itemId === ItemId.potion && instance?.kind === "potion";
305
306 if (!def || def.uniqueInstance || def.equipment
307 || itemId === ItemId.glassBottle
308 || itemId === ItemId.flower || itemId === ItemId.dye || def.flower || def.dye)
309 { throw userError("Use the Dyes tab for flowers."); }
310
311 if (itemId === ItemId.potion && !isPotion)
312 { throw userError("That is not a bottled brew."); }
313 if (isPotion)
314 {
315 if (!isFullPotionBottle({ itemId, instance }))
316 { throw userError("Only full bottles can be used as ingredients."); }
317 }
318
319 const inventory = ensureInventory(world, handle);
320 const have = instance
321 ? countMatchingInstance(inventory.slots, itemId, instance)
322 : countItemInSlots(inventory.slots, itemId);
323 const alreadyClaimed = pendingClaimedQuantity(session.pendingBrew, itemId, instance);
324 if (have < alreadyClaimed + quantity)
325 { throw userError("Not enough of that item in your inventory."); }
326
327 const uniqueKeys = new Set((session.pendingBrew ?? []).map((row) =>
328 {
329 if ((row.itemId | 0) === ItemId.potion && row.instance?.potionKey)
330 { return `potion:${row.instance.potionKey}`; }
331 return `item:${row.itemId | 0}`;
332 }));
333 const claimKey = isPotion
334 ? `potion:${instance.potionKey}`
335 : `item:${itemId}`;
336 if (!uniqueKeys.has(claimKey) && uniqueKeys.size >= CAULDRON_SLOT_COUNT)
337 {
338 throw userError(
339 `A brew can use at most ${CAULDRON_SLOT_COUNT} different ingredients.`
340 );
341 }
342
343 addPendingBrew(session, { itemId, quantity, instance });
344 session.steps.push({
345 kind: AlchemyStepKind.insert,
346 itemId,
347 ...(isPotion ? { potionKey: instance.potionKey } : {})
348 });
349 session.lastSuccessRecipe = null;
350
351 return {
352 events: [],
353 private: bagView(world.ecs, handle),
354 cauldron: true,
355 cauldronState: sessionView(session)
356 };
357}
358
359function action (world, sessionId, command)
360{
361 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
362 requireNearCauldron(world, handle);
363 const session = requireSession(world, command.characterId);
364 const kind = command.action;
365 if (kind !== AlchemyStepKind.stir && kind !== AlchemyStepKind.heat && kind !== AlchemyStepKind.cool)
366 { throw userError("Unknown cauldron action."); }
367 if (!session.steps.some((step) => step.kind === AlchemyStepKind.insert))
368 { throw userError("Insert an ingredient first."); }
369 session.steps.push({ kind });
370 session.lastSuccessRecipe = null;
371 return {
372 events: [],
373 private: bagView(world.ecs, handle),
374 cauldron: true,
375 cauldronState: sessionView(session)
376 };
377}
378
379function grantEmptyGlassBottles (world, handle, characterId, quantity, events, now = Date.now())
380{
381 const want = Math.max(0, quantity | 0);
382 if (want <= 0)
383 { return; }
384 const inventory = ensureInventory(world, handle);
385 const bottleDef = itemDefinition(ItemId.glassBottle);
386 const inserted = insertStack(inventory.slots, {
387 itemId: ItemId.glassBottle,
388 quantity: want
389 }, bottleDef);
390 inventory.slots = inserted.slots;
391 const remainder = inserted.remainder | 0;
392 if (remainder <= 0)
393 { return; }
394 const position = world.ecs.get(handle, Component.position);
395 const placed = placeOrMergeGroundStack(world, {
396 tileX: position.tileX,
397 tileY: position.tileY,
398 stack: { itemId: ItemId.glassBottle, quantity: remainder },
399 now,
400 source: "alchemy-overflow",
401 droppedByCharacterId: characterId
402 });
403 events.push(...placed.events);
404 events.push({
405 type: "toast",
406 sessionId: null,
407 characterId,
408 message: "Glass bottle dropped on the ground"
409 });
410}
411
412function bottle (world, sessionId, command)
413{
414 const { handle, entityId } = world.requireOwnedEntity(sessionId, command.characterId);
415 requireNearCauldron(world, handle);
416 const session = requireSession(world, command.characterId);
417 if (!(session.pendingBrew?.length > 0) && !(session.steps?.length > 0))
418 { throw userError("The cauldron is empty."); }
419
420 const inventory = ensureInventory(world, handle);
421 const skills = world.ecs.get(handle, Component.skills) ?? {};
422
423 const evaluation = evaluateAlchemyBottle({
424 skills,
425 brewStacks: session.pendingBrew,
426 takenSteps: session.steps,
427 potions: resolvedAlchemyPotions()
428 });
429
430 const wanted = Math.max(1, evaluation.batch | 0);
431 const requiresEmptyBottles = evaluation.result?.requiresEmptyBottles !== false;
432 const bottles = countItemInSlots(inventory.slots, ItemId.glassBottle);
433 const produced = requiresEmptyBottles ? Math.min(wanted, bottles) : wanted;
434 if (requiresEmptyBottles && produced <= 0)
435 { throw userError("You need glass bottles to bottle the brew."); }
436
437 for (const row of session.pendingBrew ?? [])
438 {
439 if (row.itemId === ItemId.potion && row.instance?.kind === "potion"
440 && !isFullPotionBottle({ itemId: row.itemId, instance: row.instance }))
441 { throw userError("Only full bottles can be used as ingredients."); }
442 const have = row.instance
443 ? countMatchingInstance(inventory.slots, row.itemId, row.instance)
444 : countItemInSlots(inventory.slots, row.itemId);
445 if (have < (row.quantity | 0))
446 { throw userError("Not enough of that item in your inventory."); }
447 }
448
449 // Consume soft-claimed ingredients only now (success path).
450 const consumed = [];
451 for (const row of session.pendingBrew ?? [])
452 {
453 const pulled = takeMatchingFromSlots(inventory.slots, {
454 itemId: row.itemId,
455 quantity: row.quantity,
456 instance: row.instance ?? null,
457 compact: false
458 });
459 if (!pulled.ok)
460 {
461 refundStacks(inventory, consumed);
462 throw userError("Not enough of that item in your inventory.");
463 }
464 inventory.slots = pulled.slots;
465 consumed.push(pulled.taken);
466 }
467
468 let takeBottles = null;
469 if (requiresEmptyBottles)
470 {
471 takeBottles = takeMatchingFromSlots(inventory.slots, {
472 itemId: ItemId.glassBottle,
473 quantity: produced,
474 compact: false
475 });
476 if (!takeBottles.ok)
477 {
478 refundStacks(inventory, consumed);
479 throw userError("You need glass bottles to bottle the brew.");
480 }
481 inventory.slots = takeBottles.slots;
482 }
483
484 const origin = craftOrigin(CraftOriginVerb.brewed, characterDisplayName(world, handle));
485 const outputItemId = evaluation.result?.outputItemId | 0;
486 let alchemyPotionView = null;
487
488 if (outputItemId && evaluation.success)
489 {
490 const outQty = Math.max(1, (evaluation.result.outputQuantity | 0) || 1) * produced;
491 const outDef = itemDefinition(outputItemId);
492 const inserted = insertStack(inventory.slots, attachOrigins({
493 itemId: outputItemId,
494 quantity: outQty,
495 origins: [{ origin, quantity: outQty }]
496 }), outDef);
497 if (!inserted.ok)
498 {
499 refundStacks(inventory, consumed);
500 if (takeBottles)
501 { refundStacks(inventory, [takeBottles.taken]); }
502 throw userError("Not enough inventory space for the brew.");
503 }
504 inventory.slots = inserted.slots;
505 alchemyPotionView = {
506 potionKey: evaluation.result.potionKey,
507 displayName: evaluation.result.displayName,
508 unstable: false,
509 color: evaluation.result.color,
510 fillLevel: null
511 };
512 }
513 else
514 {
515 const instance = potionItemInstance(evaluation.result);
516 const potionDef = itemDefinition(ItemId.potion);
517 const inserted = insertStack(inventory.slots, attachOrigins({
518 itemId: ItemId.potion,
519 quantity: produced,
520 instance,
521 origins: [{ origin, quantity: produced }]
522 }), potionDef);
523 if (!inserted.ok)
524 {
525 refundStacks(inventory, consumed);
526 if (takeBottles)
527 { refundStacks(inventory, [takeBottles.taken]); }
528 throw userError("Not enough inventory space for potions.");
529 }
530 inventory.slots = inserted.slots;
531 alchemyPotionView = {
532 potionKey: instance.potionKey,
533 displayName: instance.displayName,
534 unstable: instance.unstable,
535 color: instance.color,
536 fillLevel: instance.fillLevel
537 };
538 }
539
540 session.lastSuccessRecipe = evaluation.success ? evaluation.recipe : null;
541 clearAlchemy(session);
542
543 const events = [];
544 let returnedBottles = 0;
545 for (const row of consumed)
546 {
547 if ((row.itemId | 0) === ItemId.potion)
548 { returnedBottles += stackQuantity(row.quantity); }
549 }
550 grantEmptyGlassBottles(world, handle, command.characterId, returnedBottles, events);
551
552 if (evaluation.success && skills?.xp)
553 {
554 const xpInputs = (consumed ?? []).map((row) => ({
555 itemId: row.itemId,
556 quantity: row.quantity
557 }));
558 const amount = craftXpForConsumedInputs(xpInputs, SkillId.alchemy);
559 if (amount > 0)
560 {
561 const result = applySkillXp(
562 skills,
563 SkillId.alchemy,
564 amount,
565 world.ecs.get(handle, Component.equipment)
566 );
567 if (result.changed)
568 {
569 events.push({
570 type: "skills-updated",
571 entityId,
572 characterId: command.characterId,
573 ...publicSkillsPayload(skills),
574 stored: storedSkillXp(skills),
575 levelUps: result.levelUp ? [result.levelUp] : []
576 });
577 }
578 }
579 }
580
581 return {
582 events,
583 private: bagView(world.ecs, handle),
584 cauldron: true,
585 cauldronState: sessionView(session),
586 alchemyResult: {
587 success: !!evaluation.success,
588 reason: evaluation.reason ?? null,
589 produced,
590 wanted,
591 lost: Math.max(0, wanted - produced),
592 potion: alchemyPotionView
593 }
594 };
595}
596
597function createDye (world, sessionId, command)
598{
599 const { handle, entityId } = world.requireOwnedEntity(sessionId, command.characterId);
600 requireNearCauldron(world, handle);
601 requireSession(world, command.characterId);
602
603 const rows = normalizeFlowerRows(command.flowers);
604 if (!rows.length)
605 { throw userError("Add flowers to make dye."); }
606
607 const mixed = mixFlowersForDye(rows);
608 if (!mixed.ok)
609 { throw userError(mixed.reason); }
610
611 const wanted = mixed.quantity;
612 const inventory = ensureInventory(world, handle);
613 const bottles = countItemInSlots(inventory.slots, ItemId.glassBottle);
614 if (bottles < wanted && !command.confirmOverflow)
615 {
616 return {
617 events: [],
618 private: bagView(world.ecs, handle),
619 cauldron: true,
620 cauldronState: sessionView(requireSession(world, command.characterId)),
621 dyeConfirm: {
622 wanted,
623 bottles,
624 lost: Math.max(0, wanted - bottles)
625 }
626 };
627 }
628
629 const produced = Math.min(wanted, bottles);
630 if (produced <= 0)
631 { throw userError("You need glass bottles to bottle the dye."); }
632
633 for (const row of rows)
634 {
635 const have = countMatchingInstance(inventory.slots, ItemId.flower, row.instance);
636 if (have < row.quantity)
637 { throw userError("Not enough of those flowers in your inventory."); }
638 }
639
640 for (const row of rows)
641 {
642 const pulled = takeMatchingFromSlots(inventory.slots, {
643 itemId: ItemId.flower,
644 quantity: row.quantity,
645 instance: row.instance,
646 compact: false
647 });
648 if (!pulled.ok)
649 { throw userError("Not enough of those flowers in your inventory."); }
650 inventory.slots = pulled.slots;
651 }
652
653 const takeBottles = takeMatchingFromSlots(inventory.slots, {
654 itemId: ItemId.glassBottle,
655 quantity: produced,
656 compact: false
657 });
658 if (!takeBottles.ok)
659 { throw userError("You need glass bottles to bottle the dye."); }
660 inventory.slots = takeBottles.slots;
661
662 const dyeDef = itemDefinition(ItemId.dye);
663 const origin = craftOrigin(CraftOriginVerb.mixed, characterDisplayName(world, handle));
664 const inserted = insertStack(inventory.slots, attachOrigins({
665 itemId: ItemId.dye,
666 quantity: produced,
667 instance: mixed.instance,
668 origins: [{ origin, quantity: produced }]
669 }), dyeDef);
670 if (!inserted.ok)
671 { throw userError("Not enough inventory space for dye."); }
672 inventory.slots = inserted.slots;
673
674 const events = [];
675 const skills = world.ecs.get(handle, Component.skills);
676 const flowerCount = rows.reduce((sum, row) => sum + (row.quantity | 0), 0);
677 if (skills?.xp && flowerCount > 0)
678 {
679 const result = applySkillXp(
680 skills,
681 SkillId.alchemy,
682 flowerCount * craftXpMultiplierForSkill(SkillId.alchemy),
683 world.ecs.get(handle, Component.equipment)
684 );
685 if (result.changed)
686 {
687 events.push({
688 type: "skills-updated",
689 entityId,
690 characterId: command.characterId,
691 ...publicSkillsPayload(skills),
692 stored: storedSkillXp(skills),
693 levelUps: result.levelUp ? [result.levelUp] : []
694 });
695 }
696 }
697
698 return {
699 events,
700 private: bagView(world.ecs, handle),
701 cauldron: true,
702 cauldronState: sessionView(requireSession(world, command.characterId)),
703 alchemyResult: {
704 success: true,
705 reason: null,
706 produced,
707 wanted,
708 lost: Math.max(0, wanted - produced),
709 potion: {
710 potionKey: "dye",
711 displayName: "Dye",
712 unstable: false,
713 color: mixed.instance?.color ?? null,
714 fillLevel: mixed.instance?.fillLevel ?? DEFAULT_DYE_FILL
715 }
716 }
717 };
718}
719
720function normalizeFlowerRows (flowers)
721{
722 if (!Array.isArray(flowers))
723 { return []; }
724 const rows = [];
725 for (const entry of flowers)
726 {
727 const itemId = entry?.itemId | 0;
728 const quantity = Math.min(FLOWER_MAX_STACK, Math.max(0, entry?.quantity | 0));
729 if (itemId !== ItemId.flower || quantity <= 0)
730 { continue; }
731 const instance = entry.instance ? structuredClone(entry.instance) : null;
732 if (!instance?.color)
733 { continue; }
734 rows.push({ itemId: ItemId.flower, quantity, instance });
735 }
736 return rows;
737}
738
739function clear (world, sessionId, command)
740{
741 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
742 requireNearCauldron(world, handle);
743 const session = requireSession(world, command.characterId);
744 clearAlchemy(session);
745 session.lastSuccessRecipe = null;
746 return {
747 events: [],
748 private: bagView(world.ecs, handle),
749 cauldron: true,
750 cauldronState: sessionView(session)
751 };
752}
753
754function clearDye (world, sessionId, command)
755{
756 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
757 requireNearCauldron(world, handle);
758 const session = requireSession(world, command.characterId);
759 // Dye slots are client-only; nothing to clear server-side.
760 return {
761 events: [],
762 private: bagView(world.ecs, handle),
763 cauldron: true,
764 cauldronState: sessionView(session)
765 };
766}
767
768function saveRecipe (world, sessionId, command)
769{
770 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
771 requireNearCauldron(world, handle);
772 const session = requireSession(world, command.characterId);
773 const recipe = session.lastSuccessRecipe;
774 if (!recipe)
775 { throw userError("No successful recipe to save."); }
776
777 const inventory = ensureInventory(world, handle);
778 const paperIndex = inventory.slots.findIndex((slot) => slot?.itemId === ItemId.paper);
779 if (paperIndex < 0)
780 { throw userError("You need paper to write a recipe."); }
781 const paperSlot = inventory.slots[paperIndex];
782 const recipeStack = attachOrigins({
783 itemId: ItemId.recipePaper,
784 quantity: 1,
785 origins: [{
786 origin: writtenOrigin(characterDisplayName(world, handle)),
787 quantity: 1
788 }],
789 instance: {
790 kind: "recipe-paper",
791 recipeId: randomUUID(),
792 potionKey: recipe.potionKey,
793 displayName: `${recipe.displayName} recipe`,
794 authorCharacterId: command.characterId,
795 authorDisplayName: characterDisplayName(world, handle),
796 minAlchemyLevel: recipe.minAlchemyLevel ?? 1,
797 body: recipePaperBody(recipe),
798 writtenAt: Date.now()
799 }
800 });
801
802 if (stackQuantity(paperSlot.quantity) <= 1)
803 { inventory.slots[paperIndex] = recipeStack; }
804 else
805 {
806 const free = inventory.slots.findIndex((entry) => !entry);
807 if (free < 0)
808 { throw userError("Need a free inventory slot for the recipe paper."); }
809 paperSlot.quantity -= 1;
810 inventory.slots[free] = recipeStack;
811 }
812
813 session.lastSuccessRecipe = null;
814 return {
815 events: [],
816 private: bagView(world.ecs, handle),
817 cauldron: true,
818 cauldronState: sessionView(session)
819 };
820}