BlueGit

timfa questward

Files

questward / server / src / persistence / stateDb.js

stateDb.js

stateDb.js 59.3 KiB Download Raw
1import { openDatabase } from "./database.js";
2import { emptyEquipment, emptySlots, insertStack, insertStackGrowable, normalizeVault, normalizeInventorySlots, publicSlots, migrateBagCoins, migrateInheritanceCoins } from "../../../shared/items/inventory.js";
3import { attachOrigins, godsOrigin } from "../../../shared/items/origin.js";
4import { itemDefinition, ItemId } from "../../../shared/definitions/items.js";
5import { buildStarterBagContents } from "../../../shared/items/starterLoadout.js";
6import { normalizePlayerSkills, defaultPlayerSkills, storedSkillXp } from "../../../shared/skills/state.js";
7import { normalizePlayerSpells, defaultPlayerSpells, storedPlayerSpells } from "../../../shared/spells/state.js";
8import { decayKillCounter } from "../../../shared/combat/skull.js";
9import {
10 applyBountyDailyDecay,
11 bountyDecayDayKey,
12 bountyDecayDaysBetween
13} from "../../../shared/bounty/pricing.js";
14
15const STATE_SCHEMA = `
16CREATE TABLE IF NOT EXISTS accounts (
17 account_id INTEGER PRIMARY KEY AUTOINCREMENT,
18 auth_subject TEXT NOT NULL UNIQUE,
19 email TEXT,
20 is_admin INTEGER NOT NULL DEFAULT 0
21);
22
23CREATE TABLE IF NOT EXISTS surname_claims (
24 surname_normalized TEXT PRIMARY KEY,
25 account_id INTEGER NOT NULL
26);
27
28CREATE TABLE IF NOT EXISTS characters (
29 character_id INTEGER PRIMARY KEY AUTOINCREMENT,
30 account_id INTEGER NOT NULL,
31 first_name TEXT NOT NULL,
32 last_name TEXT NOT NULL,
33 first_normalized TEXT NOT NULL,
34 last_normalized TEXT NOT NULL,
35 sex TEXT NOT NULL,
36 tile_x INTEGER NOT NULL DEFAULT 8,
37 tile_y INTEGER NOT NULL DEFAULT 8,
38 gait TEXT NOT NULL DEFAULT 'walk',
39 is_dead INTEGER NOT NULL DEFAULT 0,
40 deletion_scheduled_at INTEGER,
41 hair_style TEXT,
42 hair_hue REAL NOT NULL DEFAULT 30,
43 hair_saturation REAL NOT NULL DEFAULT 0.55,
44 hair_darkness REAL NOT NULL DEFAULT 0.45
45);
46CREATE TABLE IF NOT EXISTS friend_requests (
47 request_id INTEGER PRIMARY KEY AUTOINCREMENT,
48 from_character_id INTEGER NOT NULL,
49 to_character_id INTEGER NOT NULL,
50 created_at INTEGER NOT NULL,
51 UNIQUE (from_character_id, to_character_id)
52);
53
54CREATE TABLE IF NOT EXISTS friendships (
55 character_id_a INTEGER NOT NULL,
56 character_id_b INTEGER NOT NULL,
57 created_at INTEGER NOT NULL,
58 PRIMARY KEY (character_id_a, character_id_b)
59);
60
61CREATE TABLE IF NOT EXISTS persistent_entities (
62 entity_id INTEGER PRIMARY KEY,
63 tile_x INTEGER NOT NULL,
64 tile_y INTEGER NOT NULL,
65 dimension_id TEXT NOT NULL DEFAULT 'overworld',
66 components_blob TEXT NOT NULL
67);
68
69CREATE TABLE IF NOT EXISTS character_bags (
70 character_id INTEGER PRIMARY KEY,
71 inventory_blob TEXT NOT NULL,
72 equipment_blob TEXT NOT NULL,
73 currency INTEGER NOT NULL DEFAULT 0,
74 vault_blob TEXT NOT NULL,
75 vault_currency INTEGER NOT NULL DEFAULT 0,
76 skills_blob TEXT NOT NULL DEFAULT '{}'
77);
78
79CREATE TABLE IF NOT EXISTS account_inheritance (
80 account_id INTEGER PRIMARY KEY,
81 slots_blob TEXT NOT NULL,
82 currency INTEGER NOT NULL DEFAULT 0
83);
84
85CREATE TABLE IF NOT EXISTS ground_items (
86 ground_item_id INTEGER PRIMARY KEY,
87 tile_x INTEGER NOT NULL,
88 tile_y INTEGER NOT NULL,
89 dimension_id TEXT NOT NULL DEFAULT 'overworld',
90 stack_blob TEXT NOT NULL,
91 dropped_at INTEGER NOT NULL,
92 expires_at INTEGER NOT NULL,
93 source TEXT NOT NULL,
94 dropped_by_character_id INTEGER
95);
96
97CREATE TABLE IF NOT EXISTS courier_transits (
98 courier_id INTEGER PRIMARY KEY AUTOINCREMENT,
99 sender_character_id INTEGER NOT NULL,
100 destination_kind TEXT NOT NULL,
101 destination_character_id INTEGER,
102 cargo_blob TEXT NOT NULL,
103 origin_x REAL NOT NULL,
104 origin_y REAL NOT NULL,
105 dest_x REAL NOT NULL,
106 dest_y REAL NOT NULL,
107 traveled REAL NOT NULL DEFAULT 0,
108 status TEXT NOT NULL,
109 entity_id INTEGER,
110 updated_at INTEGER NOT NULL,
111 created_at INTEGER NOT NULL
112);
113
114CREATE TABLE IF NOT EXISTS market_orders (
115 order_id INTEGER PRIMARY KEY AUTOINCREMENT,
116 character_id INTEGER NOT NULL,
117 side TEXT NOT NULL,
118 item_id INTEGER NOT NULL,
119 quantity INTEGER NOT NULL,
120 limit_unit_price INTEGER NOT NULL,
121 escrow_coins INTEGER NOT NULL DEFAULT 0,
122 escrow_stack_blob TEXT,
123 listing_key TEXT,
124 created_at INTEGER NOT NULL,
125 status TEXT NOT NULL
126);
127
128CREATE TABLE IF NOT EXISTS market_trades (
129 trade_id INTEGER PRIMARY KEY AUTOINCREMENT,
130 buy_order_id INTEGER NOT NULL,
131 sell_order_id INTEGER NOT NULL,
132 item_id INTEGER NOT NULL,
133 quantity INTEGER NOT NULL,
134 unit_price INTEGER NOT NULL,
135 buyer_character_id INTEGER NOT NULL,
136 seller_character_id INTEGER NOT NULL,
137 created_at INTEGER NOT NULL
138);
139
140CREATE TABLE IF NOT EXISTS item_last_sales (
141 item_id INTEGER PRIMARY KEY,
142 last_trade_price INTEGER NOT NULL,
143 last_trade_at INTEGER NOT NULL,
144 price_from INTEGER NOT NULL
145);
146
147CREATE TABLE IF NOT EXISTS bank_rest_notices (
148 notice_id INTEGER PRIMARY KEY AUTOINCREMENT,
149 character_id INTEGER NOT NULL,
150 item_id INTEGER NOT NULL,
151 item_name TEXT NOT NULL,
152 quantity INTEGER NOT NULL,
153 source_name TEXT NOT NULL,
154 created_at INTEGER NOT NULL
155);
156
157CREATE TABLE IF NOT EXISTS held_courier_deliveries (
158 hold_id INTEGER PRIMARY KEY AUTOINCREMENT,
159 character_id INTEGER NOT NULL,
160 sender_character_id INTEGER NOT NULL,
161 origin_tile_x INTEGER NOT NULL,
162 origin_tile_y INTEGER NOT NULL,
163 destination_kind TEXT NOT NULL,
164 destination_character_id INTEGER,
165 vault_character_id INTEGER,
166 cargo_blob TEXT NOT NULL,
167 created_at INTEGER NOT NULL
168);
169
170CREATE TABLE IF NOT EXISTS character_bounties (
171 character_id INTEGER PRIMARY KEY,
172 amount INTEGER NOT NULL DEFAULT 0,
173 last_decay_day TEXT
174);
175
176CREATE TABLE IF NOT EXISTS character_quest_state (
177 character_id INTEGER NOT NULL,
178 quest_id TEXT NOT NULL,
179 state_value TEXT NOT NULL,
180 progress_blob TEXT NOT NULL DEFAULT '{}',
181 started_at INTEGER,
182 completed_at INTEGER,
183 PRIMARY KEY (character_id, quest_id)
184);
185
186CREATE TABLE IF NOT EXISTS character_dialogue_heard (
187 character_id INTEGER NOT NULL,
188 dialogue_id TEXT NOT NULL,
189 step_id TEXT NOT NULL,
190 heard_at INTEGER NOT NULL,
191 PRIMARY KEY (character_id, dialogue_id, step_id)
192);
193
194CREATE TABLE IF NOT EXISTS character_quest_journal (
195 entry_id INTEGER PRIMARY KEY AUTOINCREMENT,
196 character_id INTEGER NOT NULL,
197 quest_id TEXT NOT NULL,
198 step_id TEXT NOT NULL,
199 text TEXT NOT NULL,
200 written_at INTEGER NOT NULL
201);
202
203CREATE TABLE IF NOT EXISTS character_dialogue_triggers (
204 character_id INTEGER NOT NULL,
205 dialogue_id TEXT NOT NULL,
206 trigger_id TEXT NOT NULL,
207 latched_at INTEGER NOT NULL,
208 PRIMARY KEY (character_id, dialogue_id, trigger_id)
209);
210
211CREATE TABLE IF NOT EXISTS character_visited_dimensions (
212 character_id INTEGER NOT NULL,
213 dimension_id TEXT NOT NULL,
214 first_visited_at INTEGER NOT NULL,
215 PRIMARY KEY (character_id, dimension_id)
216);
217`;
218
219export class StateDatabase
220{
221 constructor(filePath)
222 {
223 this.db = openDatabase(filePath);
224 this.db.exec(STATE_SCHEMA);
225 this.#migrateSchema();
226 }
227
228 #migrateSchema ()
229 {
230 const bagColumns = this.db.prepare("PRAGMA table_info(character_bags)").all();
231 if (!bagColumns.some((column) => column.name === "skills_blob"))
232 {
233 this.db.exec("ALTER TABLE character_bags ADD COLUMN skills_blob TEXT NOT NULL DEFAULT '{}'");
234 }
235 const characterColumns = this.db.prepare("PRAGMA table_info(characters)").all();
236 if (!characterColumns.some((column) => column.name === "is_dead"))
237 { this.db.exec("ALTER TABLE characters ADD COLUMN is_dead INTEGER NOT NULL DEFAULT 0"); }
238 if (!characterColumns.some((column) => column.name === "hair_style"))
239 {
240 this.db.exec("ALTER TABLE characters ADD COLUMN hair_style TEXT");
241 this.db.exec("ALTER TABLE characters ADD COLUMN hair_hue REAL NOT NULL DEFAULT 30");
242 this.db.exec("ALTER TABLE characters ADD COLUMN hair_saturation REAL NOT NULL DEFAULT 0.55");
243 this.db.exec("ALTER TABLE characters ADD COLUMN hair_darkness REAL NOT NULL DEFAULT 0.45");
244 }
245 if (!characterColumns.some((column) => column.name === "dimension_id"))
246 { this.db.exec("ALTER TABLE characters ADD COLUMN dimension_id TEXT NOT NULL DEFAULT 'overworld'"); }
247 this.db.exec(`
248 CREATE TABLE IF NOT EXISTS character_visited_dimensions (
249 character_id INTEGER NOT NULL,
250 dimension_id TEXT NOT NULL,
251 first_visited_at INTEGER NOT NULL,
252 PRIMARY KEY (character_id, dimension_id)
253 )
254 `);
255 const courierColumns = this.db.prepare("PRAGMA table_info(courier_transits)").all();
256 if (!courierColumns.some((column) => column.name === "vault_character_id"))
257 { this.db.exec("ALTER TABLE courier_transits ADD COLUMN vault_character_id INTEGER"); }
258 if (!bagColumns.some((column) => column.name === "spells_blob"))
259 {
260 this.db.exec("ALTER TABLE character_bags ADD COLUMN spells_blob TEXT NOT NULL DEFAULT '{}'");
261 }
262 if (!characterColumns.some((column) => column.name === "health_current"))
263 { this.db.exec("ALTER TABLE characters ADD COLUMN health_current INTEGER"); }
264 const accountColumns = this.db.prepare("PRAGMA table_info(accounts)").all();
265 if (!accountColumns.some((column) => column.name === "username"))
266 { this.db.exec("ALTER TABLE accounts ADD COLUMN username TEXT"); }
267 if (!characterColumns.some((column) => column.name === "kill_counter"))
268 { this.db.exec("ALTER TABLE characters ADD COLUMN kill_counter REAL NOT NULL DEFAULT 0"); }
269 if (!characterColumns.some((column) => column.name === "kill_counter_at"))
270 { this.db.exec("ALTER TABLE characters ADD COLUMN kill_counter_at INTEGER"); }
271 if (!characterColumns.some((column) => column.name === "cowardice_forgiven_hour"))
272 { this.db.exec("ALTER TABLE characters ADD COLUMN cowardice_forgiven_hour INTEGER"); }
273 if (!characterColumns.some((column) => column.name === "respawn_altar_x"))
274 {
275 this.db.exec("ALTER TABLE characters ADD COLUMN respawn_altar_x INTEGER");
276 this.db.exec("ALTER TABLE characters ADD COLUMN respawn_altar_y INTEGER");
277 this.db.exec("ALTER TABLE characters ADD COLUMN respawn_altar_dimension_id TEXT");
278 }
279 const groundColumns = this.db.prepare("PRAGMA table_info(ground_items)").all();
280 if (!groundColumns.some((column) => column.name === "dimension_id"))
281 { this.db.exec("ALTER TABLE ground_items ADD COLUMN dimension_id TEXT NOT NULL DEFAULT 'overworld'"); }
282 const persistentColumns = this.db.prepare("PRAGMA table_info(persistent_entities)").all();
283 if (!persistentColumns.some((column) => column.name === "dimension_id"))
284 { this.db.exec("ALTER TABLE persistent_entities ADD COLUMN dimension_id TEXT NOT NULL DEFAULT 'overworld'"); }
285 const marketColumns = this.db.prepare("PRAGMA table_info(market_orders)").all();
286 if (!marketColumns.some((column) => column.name === "listing_key"))
287 { this.db.exec("ALTER TABLE market_orders ADD COLUMN listing_key TEXT"); }
288 const bountyColumns = this.db.prepare("PRAGMA table_info(character_bounties)").all();
289 if (!bountyColumns.some((column) => column.name === "last_decay_day"))
290 { this.db.exec("ALTER TABLE character_bounties ADD COLUMN last_decay_day TEXT"); }
291 this.db.exec(`
292 CREATE TABLE IF NOT EXISTS account_friend_requests (
293 request_id INTEGER PRIMARY KEY AUTOINCREMENT,
294 from_account_id INTEGER NOT NULL,
295 to_account_id INTEGER NOT NULL,
296 created_at INTEGER NOT NULL,
297 UNIQUE (from_account_id, to_account_id)
298 )
299 `);
300 this.db.exec(`
301 CREATE TABLE IF NOT EXISTS account_friendships (
302 account_id_a INTEGER NOT NULL,
303 account_id_b INTEGER NOT NULL,
304 created_at INTEGER NOT NULL,
305 PRIMARY KEY (account_id_a, account_id_b)
306 )
307 `);
308 this.#migrateCharacterFriendsToAccounts();
309 this.db.exec(`
310 CREATE TABLE IF NOT EXISTS auth_sessions (
311 session_id TEXT PRIMARY KEY,
312 auth_subject TEXT NOT NULL,
313 username TEXT,
314 email TEXT,
315 access_token TEXT,
316 expires_at INTEGER NOT NULL
317 )
318 `);
319 this.db.exec(`
320 CREATE INDEX IF NOT EXISTS auth_sessions_subject ON auth_sessions(auth_subject)
321 `);
322 this.#grantLanternsToExistingCharacters();
323 }
324
325 /** One-time: lift legacy character friendships / requests to account scope. */
326 #migrateCharacterFriendsToAccounts ()
327 {
328 const legacyFriends = this.db.prepare("SELECT character_id_a, character_id_b, created_at FROM friendships").all();
329 const insertFriend = this.db.prepare(`
330 INSERT OR IGNORE INTO account_friendships (account_id_a, account_id_b, created_at)
331 VALUES (?, ?, ?)
332 `);
333 for (const row of legacyFriends)
334 {
335 const a = this.getCharacter(row.character_id_a);
336 const b = this.getCharacter(row.character_id_b);
337 if (!a || !b || a.account_id === b.account_id)
338 { continue; }
339 const [idA, idB] = pairIds(a.account_id, b.account_id);
340 insertFriend.run(idA, idB, row.created_at | 0 || Date.now());
341 }
342 const legacyRequests = this.db.prepare(`
343 SELECT from_character_id, to_character_id, created_at FROM friend_requests
344 `).all();
345 const insertReq = this.db.prepare(`
346 INSERT OR IGNORE INTO account_friend_requests (from_account_id, to_account_id, created_at)
347 VALUES (?, ?, ?)
348 `);
349 for (const row of legacyRequests)
350 {
351 const from = this.getCharacter(row.from_character_id);
352 const to = this.getCharacter(row.to_character_id);
353 if (!from || !to || from.account_id === to.account_id)
354 { continue; }
355 insertReq.run(from.account_id, to.account_id, row.created_at | 0 || Date.now());
356 }
357 if (legacyFriends.length || legacyRequests.length)
358 {
359 this.db.exec("DELETE FROM friendships");
360 this.db.exec("DELETE FROM friend_requests");
361 }
362 }
363
364 createAuthSession ({ sessionId, authSubject, username = null, email = null, accessToken = null, expiresAtMs })
365 {
366 this.db.prepare(`
367 INSERT INTO auth_sessions (session_id, auth_subject, username, email, access_token, expires_at)
368 VALUES (?, ?, ?, ?, ?, ?)
369 `).run(sessionId, authSubject, username, email, accessToken, expiresAtMs);
370 }
371
372 getAuthSession (sessionId)
373 {
374 return this.db.prepare(`
375 SELECT session_id, auth_subject, username, email, access_token, expires_at
376 FROM auth_sessions
377 WHERE session_id = ?
378 `).get(sessionId) ?? null;
379 }
380
381 deleteAuthSession (sessionId)
382 {
383 if (!sessionId)
384 { return; }
385 this.db.prepare("DELETE FROM auth_sessions WHERE session_id = ?").run(sessionId);
386 }
387
388 #grantLanternsToExistingCharacters ()
389 {
390 const def = itemDefinition(ItemId.lantern);
391 if (!def)
392 { return; }
393 const rows = this.db.prepare("SELECT character_id, inventory_blob, equipment_blob FROM character_bags").all();
394 const update = this.db.prepare(`
395 UPDATE character_bags
396 SET inventory_blob = ?, equipment_blob = ?
397 WHERE character_id = ?
398 `);
399 for (const row of rows)
400 {
401 const inventory = JSON.parse(row.inventory_blob || "[]");
402 const equipment = JSON.parse(row.equipment_blob || "{}");
403 if (bagContainsItem(inventory, equipment, ItemId.lantern))
404 { continue; }
405 if (!equipment.slots?.offhand)
406 {
407 equipment.slots = equipment.slots ?? {};
408 equipment.slots.offhand = attachOrigins({
409 itemId: ItemId.lantern,
410 quantity: 1,
411 origins: [{ origin: godsOrigin(), quantity: 1 }]
412 });
413 }
414 else
415 {
416 const result = insertStack(inventory, attachOrigins({
417 itemId: ItemId.lantern,
418 quantity: 1,
419 origins: [{ origin: godsOrigin(), quantity: 1 }]
420 }), def);
421 if (!result.ok)
422 { continue; }
423 inventory.splice(0, inventory.length, ...result.slots);
424 }
425 update.run(JSON.stringify(inventory), JSON.stringify(equipment), row.character_id);
426 }
427 }
428
429 getAccountBySubject (authSubject)
430 {
431 return this.db.prepare("SELECT * FROM accounts WHERE auth_subject = ?").get(authSubject) ?? null;
432 }
433
434 countAccounts ()
435 {
436 return this.db.prepare("SELECT COUNT(*) AS count FROM accounts").get().count;
437 }
438
439 countGameAdmins ()
440 {
441 return this.db.prepare("SELECT COUNT(*) AS count FROM accounts WHERE is_admin = 1").get().count;
442 }
443
444 findAccountByUsername (username)
445 {
446 const normalized = String(username ?? "").trim().toLowerCase();
447 if (!normalized)
448 { return null; }
449 return this.db.prepare(`
450 SELECT * FROM accounts
451 WHERE lower(username) = ?
452 ORDER BY account_id ASC
453 LIMIT 1
454 `).get(normalized) ?? null;
455 }
456
457 listGameAdmins ()
458 {
459 return this.db.prepare(`
460 SELECT account_id, auth_subject, username, email, is_admin
461 FROM accounts
462 WHERE is_admin = 1
463 ORDER BY account_id ASC
464 `).all();
465 }
466
467 #syncAccountProfile (accountId, { email, username })
468 {
469 const fields = [];
470 const values = [];
471 if (email != null)
472 {
473 fields.push("email = ?");
474 values.push(email);
475 }
476 if (username != null)
477 {
478 fields.push("username = ?");
479 values.push(username);
480 }
481 if (!fields.length)
482 { return; }
483 values.push(accountId);
484 this.db.prepare(`UPDATE accounts SET ${fields.join(", ")} WHERE account_id = ?`).run(...values);
485 }
486
487 resolveAccountFromAuth ({ authSubject, email = null, username = null })
488 {
489 const existing = this.getAccountBySubject(authSubject);
490 if (existing)
491 {
492 this.#syncAccountProfile(existing.account_id, { email, username });
493 return this.getAccountBySubject(authSubject);
494 }
495 const isFirstAccount = this.countAccounts() === 0;
496 return this.createAccount(authSubject, isFirstAccount, email, username);
497 }
498
499 setGameAdmin (authSubject, isAdmin)
500 {
501 const account = this.getAccountBySubject(authSubject);
502 if (!account)
503 {
504 const error = new Error("Account not found.");
505 error.userFacing = true;
506 throw error;
507 }
508 if (!isAdmin && account.is_admin && this.countGameAdmins() <= 1)
509 {
510 const error = new Error("Cannot remove the last game admin.");
511 error.userFacing = true;
512 throw error;
513 }
514 this.db.prepare("UPDATE accounts SET is_admin = ? WHERE auth_subject = ?").run(isAdmin ? 1 : 0, authSubject);
515 return this.getAccountBySubject(authSubject);
516 }
517
518 grantGameAdminByUsername (username)
519 {
520 const account = this.findAccountByUsername(username);
521 if (!account)
522 {
523 const error = new Error("No account with that username has signed in yet.");
524 error.userFacing = true;
525 throw error;
526 }
527 return this.setGameAdmin(account.auth_subject, true);
528 }
529
530 createAccount (authSubject, isAdmin, email = null, username = null)
531 {
532 this.db.prepare(`
533 INSERT INTO accounts (auth_subject, email, username, is_admin)
534 VALUES (?, ?, ?, ?)
535 `).run(
536 authSubject,
537 email,
538 username,
539 isAdmin ? 1 : 0
540 );
541 return this.getAccountBySubject(authSubject);
542 }
543
544 ensureAccount (authSubject, isAdmin, email = null, username = null)
545 {
546 const existing = this.getAccountBySubject(authSubject);
547 if (existing)
548 {
549 this.#syncAccountProfile(existing.account_id, { email, username });
550 return existing;
551 }
552
553 return this.createAccount(authSubject, isAdmin, email, username);
554 }
555
556 listCharacters (accountId)
557 {
558 return this.db.prepare(`
559 SELECT * FROM characters
560 WHERE account_id = ?
561 ORDER BY character_id ASC
562 `).all(accountId);
563 }
564
565 getCharacter (characterId)
566 {
567 return this.db.prepare("SELECT * FROM characters WHERE character_id = ?").get(characterId) ?? null;
568 }
569
570 /** All character ids (for world-settings fan-out such as initial quests). */
571 listAllCharacterIds ()
572 {
573 return this.db.prepare("SELECT character_id FROM characters").all()
574 .map((row) => row.character_id | 0)
575 .filter((id) => id > 0);
576 }
577
578 findSurnameClaim (surnameNormalized)
579 {
580 return this.db.prepare("SELECT * FROM surname_claims WHERE surname_normalized = ?").get(surnameNormalized) ?? null;
581 }
582
583 createCharacter (accountId, firstName, lastName, sex, tileX, tileY, hair = null, starterSettings = null, creationClothing = null)
584 {
585 const firstNormalized = normalizeName(firstName);
586 const lastNormalized = normalizeName(lastName);
587 const hairStyle = hair?.style ?? null;
588 const hairHue = Number(hair?.hue) || 30;
589 const hairSaturation = Number(hair?.saturation);
590 const hairDarkness = Number(hair?.darkness);
591 this.db.exec("BEGIN");
592 try
593 {
594 this.db.prepare(`
595 INSERT INTO characters (
596 account_id, first_name, last_name, first_normalized, last_normalized, sex, tile_x, tile_y,
597 dimension_id, hair_style, hair_hue, hair_saturation, hair_darkness
598 ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'overworld', ?, ?, ?, ?)
599 `).run(
600 accountId,
601 firstName,
602 lastName,
603 firstNormalized,
604 lastNormalized,
605 sex,
606 tileX,
607 tileY,
608 hairStyle,
609 hairHue,
610 Number.isFinite(hairSaturation) ? hairSaturation : 0.55,
611 Number.isFinite(hairDarkness) ? hairDarkness : 0.45
612 );
613 const characterId = Number(this.db.prepare("SELECT last_insert_rowid() AS id").get().id);
614
615 const claim = this.findSurnameClaim(lastNormalized);
616 if (!claim)
617 {
618 this.db.prepare("INSERT INTO surname_claims (surname_normalized, account_id) VALUES (?, ?)").run(
619 lastNormalized,
620 accountId
621 );
622 }
623
624 this.db.exec("COMMIT");
625 this.#ensureBag(characterId, starterSettings, creationClothing);
626 return this.getCharacter(characterId);
627 }
628 catch (error)
629 {
630 this.db.exec("ROLLBACK");
631 throw error;
632 }
633 }
634
635 updateCharacterHair (characterId, { style, hue, saturation, darkness })
636 {
637 this.db.prepare(`
638 UPDATE characters
639 SET hair_style = ?, hair_hue = ?, hair_saturation = ?, hair_darkness = ?
640 WHERE character_id = ?
641 `).run(
642 style ?? null,
643 Number(hue) || 30,
644 Number.isFinite(Number(saturation)) ? Number(saturation) : 0.55,
645 Number.isFinite(Number(darkness)) ? Number(darkness) : 0.45,
646 characterId | 0
647 );
648 return this.getCharacter(characterId);
649 }
650
651 scheduleDeletion (characterId, at)
652 {
653 this.db.prepare("UPDATE characters SET deletion_scheduled_at = ? WHERE character_id = ?").run(at, characterId);
654 }
655
656 cancelDeletion (characterId)
657 {
658 this.db.prepare("UPDATE characters SET deletion_scheduled_at = NULL WHERE character_id = ?").run(characterId);
659 }
660
661 deleteCharacter (characterId)
662 {
663 const character = this.getCharacter(characterId);
664 if (!character)
665 { return; }
666
667 this.db.exec("BEGIN");
668 try
669 {
670 this.#moveGoodsToInheritance(character);
671 this.db.prepare("DELETE FROM character_bags WHERE character_id = ?").run(characterId);
672 this.db.prepare("DELETE FROM characters WHERE character_id = ?").run(characterId);
673 this.db.prepare("DELETE FROM character_bounties WHERE character_id = ?").run(characterId);
674 // Account friendships persist; only clear legacy character rows if any remain.
675 this.db.prepare("DELETE FROM friend_requests WHERE from_character_id = ? OR to_character_id = ?").run(
676 characterId,
677 characterId
678 );
679 this.db.prepare("DELETE FROM friendships WHERE character_id_a = ? OR character_id_b = ?").run(
680 characterId,
681 characterId
682 );
683 const remaining = this.db.prepare(`
684 SELECT COUNT(*) AS count FROM characters
685 WHERE account_id = ? AND last_normalized = ?
686 `).get(character.account_id, character.last_normalized);
687 if (!remaining.count)
688 {
689 this.db.prepare("DELETE FROM surname_claims WHERE surname_normalized = ? AND account_id = ?").run(
690 character.last_normalized,
691 character.account_id
692 );
693 }
694 this.db.exec("COMMIT");
695 }
696 catch (error)
697 {
698 this.db.exec("ROLLBACK");
699 throw error;
700 }
701 }
702
703 saveCharacterPosition (characterId, tileX, tileY, gait, dimensionId = "overworld")
704 {
705 this.db.prepare(`
706 UPDATE characters SET tile_x = ?, tile_y = ?, gait = ?, dimension_id = ?
707 WHERE character_id = ?
708 `).run(
709 tileX,
710 tileY,
711 gait,
712 String(dimensionId ?? "overworld"),
713 characterId
714 );
715 }
716
717 getCharacterRespawnAltar (characterId)
718 {
719 const row = this.db.prepare(`
720 SELECT respawn_altar_x, respawn_altar_y, respawn_altar_dimension_id
721 FROM characters WHERE character_id = ?
722 `).get(characterId | 0);
723 if (!row || row.respawn_altar_x == null || row.respawn_altar_y == null)
724 { return null; }
725 return {
726 tileX: row.respawn_altar_x | 0,
727 tileY: row.respawn_altar_y | 0,
728 dimensionId: String(row.respawn_altar_dimension_id ?? "overworld")
729 };
730 }
731
732 setCharacterRespawnAltar (characterId, tileX, tileY, dimensionId = "overworld")
733 {
734 this.db.prepare(`
735 UPDATE characters
736 SET respawn_altar_x = ?, respawn_altar_y = ?, respawn_altar_dimension_id = ?
737 WHERE character_id = ?
738 `).run(tileX | 0, tileY | 0, String(dimensionId ?? "overworld"), characterId | 0);
739 }
740
741 markDimensionVisited (characterId, dimensionId, now = Date.now())
742 {
743 const dim = String(dimensionId ?? "overworld");
744 this.db.prepare(`
745 INSERT INTO character_visited_dimensions (character_id, dimension_id, first_visited_at)
746 VALUES (?, ?, ?)
747 ON CONFLICT(character_id, dimension_id) DO NOTHING
748 `).run(characterId | 0, dim, now);
749 }
750
751 hasVisitedDimension (characterId, dimensionId)
752 {
753 const row = this.db.prepare(`
754 SELECT 1 AS ok FROM character_visited_dimensions
755 WHERE character_id = ? AND dimension_id = ?
756 `).get(characterId | 0, String(dimensionId ?? "overworld"));
757 return !!row;
758 }
759
760 listVisitedDimensions (characterId)
761 {
762 return this.db.prepare(`
763 SELECT dimension_id, first_visited_at
764 FROM character_visited_dimensions
765 WHERE character_id = ?
766 ORDER BY first_visited_at ASC
767 `).all(characterId | 0).map((row) => ({
768 dimensionId: row.dimension_id,
769 firstVisitedAt: row.first_visited_at
770 }));
771 }
772
773 saveCharacterHealth (characterId, current)
774 {
775 this.db.prepare("UPDATE characters SET health_current = ? WHERE character_id = ?").run(
776 Math.max(0, current | 0),
777 characterId
778 );
779 }
780
781 setCharacterDead (characterId, isDead)
782 {
783 this.db.prepare("UPDATE characters SET is_dead = ? WHERE character_id = ?").run(
784 isDead ? 1 : 0,
785 characterId
786 );
787 }
788
789 listDueDeletions (now)
790 {
791 return this.db.prepare(`
792 SELECT * FROM characters
793 WHERE deletion_scheduled_at IS NOT NULL AND deletion_scheduled_at <= ?
794 `).all(now);
795 }
796
797 getCharacterByName (firstName, lastName)
798 {
799 return this.db.prepare(`
800 SELECT * FROM characters
801 WHERE first_normalized = ? AND last_normalized = ?
802 `).get(normalizeName(firstName), normalizeName(lastName)) ?? null;
803 }
804
805 /**
806 * Admin gift search: match first name, last name, "first last", or account username.
807 * @param {string} query
808 * @param {number} [limit]
809 */
810 searchCharactersForGift (query, limit = 40)
811 {
812 const raw = String(query ?? "").trim();
813 if (!raw)
814 { return []; }
815 const cap = Math.min(100, Math.max(1, limit | 0 || 40));
816 const needle = `%${normalizeName(raw).replace(/%/g, "")}%`;
817 const parts = raw.split(/\s+/u).filter(Boolean);
818 const firstPart = parts[0] ? normalizeName(parts[0]) : "";
819 const lastPart = parts.length >= 2 ? normalizeName(parts.slice(1).join(" ")) : "";
820
821 if (parts.length >= 2 && firstPart && lastPart)
822 {
823 return this.db.prepare(`
824 SELECT
825 c.character_id,
826 c.first_name,
827 c.last_name,
828 c.account_id,
829 a.username AS account_username
830 FROM characters c
831 LEFT JOIN accounts a ON a.account_id = c.account_id
832 WHERE (c.first_normalized = ? AND c.last_normalized = ?)
833 OR c.first_normalized LIKE ?
834 OR c.last_normalized LIKE ?
835 OR lower(COALESCE(a.username, '')) LIKE ?
836 OR (c.first_normalized || ' ' || c.last_normalized) LIKE ?
837 ORDER BY c.last_normalized ASC, c.first_normalized ASC, c.character_id ASC
838 LIMIT ?
839 `).all(firstPart, lastPart, needle, needle, needle, needle, cap);
840 }
841
842 return this.db.prepare(`
843 SELECT
844 c.character_id,
845 c.first_name,
846 c.last_name,
847 c.account_id,
848 a.username AS account_username
849 FROM characters c
850 LEFT JOIN accounts a ON a.account_id = c.account_id
851 WHERE c.first_normalized LIKE ?
852 OR c.last_normalized LIKE ?
853 OR lower(COALESCE(a.username, '')) LIKE ?
854 OR (c.first_normalized || ' ' || c.last_normalized) LIKE ?
855 ORDER BY c.last_normalized ASC, c.first_normalized ASC, c.character_id ASC
856 LIMIT ?
857 `).all(needle, needle, needle, needle, cap);
858 }
859
860 getCharacterBounty (characterId, now = Date.now())
861 {
862 return this.applyCharacterBountyDecay(characterId, now);
863 }
864
865 /**
866 * Daily −1 bounty decay (lazy). First touch after migration stamps today without retroactive decay.
867 * Never moves `last_decay_day` backward (simulation clocks in tests can be epoch-relative).
868 */
869 applyCharacterBountyDecay (characterId, now = Date.now())
870 {
871 const id = characterId | 0;
872 const row = this.db.prepare(`
873 SELECT amount, last_decay_day FROM character_bounties WHERE character_id = ?
874 `).get(id);
875 if (!row)
876 { return 0; }
877 const day = bountyDecayDayKey(now);
878 let amount = Math.max(0, row.amount | 0);
879 const last = row.last_decay_day ? String(row.last_decay_day) : "";
880 if (!last)
881 {
882 this.db.prepare(`
883 UPDATE character_bounties SET last_decay_day = ? WHERE character_id = ?
884 `).run(day, id);
885 return amount;
886 }
887 if (last === day)
888 { return amount; }
889 const days = bountyDecayDaysBetween(last, day);
890 if (days <= 0)
891 {
892 // `now` is on/before the stamped day (clock skew / harness) — leave the stamp alone.
893 return amount;
894 }
895 amount = applyBountyDailyDecay(amount, days);
896 this.db.prepare(`
897 UPDATE character_bounties SET amount = ?, last_decay_day = ? WHERE character_id = ?
898 `).run(amount, day, id);
899 return amount;
900 }
901
902 /** Add coins to a bounty; returns the new total. */
903 addCharacterBounty (characterId, amount, now = Date.now())
904 {
905 const id = characterId | 0;
906 const add = Math.max(0, amount | 0);
907 if (add <= 0)
908 { return this.getCharacterBounty(id, now); }
909 const day = bountyDecayDayKey(now);
910 this.applyCharacterBountyDecay(id, now);
911 this.db.prepare(`
912 INSERT INTO character_bounties (character_id, amount, last_decay_day) VALUES (?, ?, ?)
913 ON CONFLICT(character_id) DO UPDATE SET amount = amount + excluded.amount
914 `).run(id, add, day);
915 return this.getCharacterBounty(id, now);
916 }
917
918 /** Reduce bounty by up to `amount`; returns the new total. */
919 reduceCharacterBounty (characterId, amount, now = Date.now())
920 {
921 const id = characterId | 0;
922 const cut = Math.max(0, amount | 0);
923 const current = this.getCharacterBounty(id, now);
924 if (cut <= 0)
925 { return current; }
926 const next = Math.max(0, current - cut);
927 const day = bountyDecayDayKey(now);
928 this.db.prepare(`
929 INSERT INTO character_bounties (character_id, amount, last_decay_day) VALUES (?, ?, ?)
930 ON CONFLICT(character_id) DO UPDATE SET amount = excluded.amount
931 `).run(id, next, day);
932 return next;
933 }
934
935 /** Zero out and return the previous bounty amount. */
936 takeCharacterBounty (characterId, now = Date.now())
937 {
938 const id = characterId | 0;
939 const amount = this.getCharacterBounty(id, now);
940 if (amount <= 0)
941 { return 0; }
942 const day = bountyDecayDayKey(now);
943 this.db.prepare(`
944 INSERT INTO character_bounties (character_id, amount, last_decay_day) VALUES (?, 0, ?)
945 ON CONFLICT(character_id) DO UPDATE SET amount = 0
946 `).run(id, day);
947 return amount;
948 }
949
950 getQuestState (characterId, questId)
951 {
952 const row = this.db.prepare(`
953 SELECT state_value, progress_blob, started_at, completed_at
954 FROM character_quest_state
955 WHERE character_id = ? AND quest_id = ?
956 `).get(characterId | 0, String(questId));
957 if (!row)
958 { return { state: "not-started", progress: {}, startedAt: null, completedAt: null }; }
959 const progress = JSON.parse(row.progress_blob || "{}");
960 let state = row.state_value;
961 if (state !== "not-started" && state !== "completed")
962 { state = Number(state) | 0; }
963 return {
964 state,
965 progress,
966 startedAt: row.started_at ?? null,
967 completedAt: row.completed_at ?? null
968 };
969 }
970
971 listQuestStates (characterId)
972 {
973 return this.db.prepare(`
974 SELECT quest_id, state_value, progress_blob, started_at, completed_at
975 FROM character_quest_state
976 WHERE character_id = ?
977 `).all(characterId | 0).map((row) =>
978 {
979 let state = row.state_value;
980 if (state !== "not-started" && state !== "completed")
981 { state = Number(state) | 0; }
982 return {
983 questId: row.quest_id,
984 state,
985 progress: JSON.parse(row.progress_blob || "{}"),
986 startedAt: row.started_at ?? null,
987 completedAt: row.completed_at ?? null
988 };
989 });
990 }
991
992 saveQuestState (characterId, questId, state, progress = {}, startedAt = null, completedAt = null)
993 {
994 const stateValue = state === "not-started" || state === "completed" ? state : String(state | 0);
995 this.db.prepare(`
996 INSERT INTO character_quest_state
997 (character_id, quest_id, state_value, progress_blob, started_at, completed_at)
998 VALUES (?, ?, ?, ?, ?, ?)
999 ON CONFLICT(character_id, quest_id) DO UPDATE SET
1000 state_value = excluded.state_value,
1001 progress_blob = excluded.progress_blob,
1002 started_at = excluded.started_at,
1003 completed_at = excluded.completed_at
1004 `).run(
1005 characterId | 0,
1006 String(questId),
1007 stateValue,
1008 JSON.stringify(progress ?? {}),
1009 startedAt,
1010 completedAt
1011 );
1012 }
1013
1014 isDialogueHeard (characterId, dialogueId, stepId)
1015 {
1016 const row = this.db.prepare(`
1017 SELECT 1 FROM character_dialogue_heard
1018 WHERE character_id = ? AND dialogue_id = ? AND step_id = ?
1019 `).get(characterId | 0, String(dialogueId), String(stepId));
1020 return !!row;
1021 }
1022
1023 markDialogueHeard (characterId, dialogueId, stepId)
1024 {
1025 this.db.prepare(`
1026 INSERT OR IGNORE INTO character_dialogue_heard
1027 (character_id, dialogue_id, step_id, heard_at)
1028 VALUES (?, ?, ?, ?)
1029 `).run(characterId | 0, String(dialogueId), String(stepId), Date.now());
1030 }
1031
1032 listDialogueHeard (characterId)
1033 {
1034 return this.db.prepare(`
1035 SELECT dialogue_id, step_id, heard_at
1036 FROM character_dialogue_heard
1037 WHERE character_id = ?
1038 `).all(characterId | 0);
1039 }
1040
1041 isDialogueTriggerLatched (characterId, dialogueId, triggerId)
1042 {
1043 const row = this.db.prepare(`
1044 SELECT 1 FROM character_dialogue_triggers
1045 WHERE character_id = ? AND dialogue_id = ? AND trigger_id = ?
1046 `).get(characterId | 0, String(dialogueId), String(triggerId));
1047 return !!row;
1048 }
1049
1050 latchDialogueTrigger (characterId, dialogueId, triggerId)
1051 {
1052 this.db.prepare(`
1053 INSERT OR IGNORE INTO character_dialogue_triggers
1054 (character_id, dialogue_id, trigger_id, latched_at)
1055 VALUES (?, ?, ?, ?)
1056 `).run(characterId | 0, String(dialogueId), String(triggerId), Date.now());
1057 }
1058
1059 listDialogueTriggers (characterId)
1060 {
1061 return this.db.prepare(`
1062 SELECT dialogue_id, trigger_id, latched_at
1063 FROM character_dialogue_triggers
1064 WHERE character_id = ?
1065 `).all(characterId | 0);
1066 }
1067
1068 appendQuestJournal (characterId, questId, stepId, text)
1069 {
1070 const trimmed = String(text ?? "").trim();
1071 if (!trimmed)
1072 { return null; }
1073 const writtenAt = Date.now();
1074 const result = this.db.prepare(`
1075 INSERT INTO character_quest_journal
1076 (character_id, quest_id, step_id, text, written_at)
1077 VALUES (?, ?, ?, ?, ?)
1078 `).run(characterId | 0, String(questId), String(stepId), trimmed, writtenAt);
1079 return {
1080 entryId: Number(result.lastInsertRowid),
1081 questId: String(questId),
1082 stepId: String(stepId),
1083 text: trimmed,
1084 writtenAt
1085 };
1086 }
1087
1088 listQuestJournal (characterId, questId = null)
1089 {
1090 if (questId)
1091 {
1092 return this.db.prepare(`
1093 SELECT entry_id, quest_id, step_id, text, written_at
1094 FROM character_quest_journal
1095 WHERE character_id = ? AND quest_id = ?
1096 ORDER BY written_at ASC, entry_id ASC
1097 `).all(characterId | 0, String(questId));
1098 }
1099 return this.db.prepare(`
1100 SELECT entry_id, quest_id, step_id, text, written_at
1101 FROM character_quest_journal
1102 WHERE character_id = ?
1103 ORDER BY written_at ASC, entry_id ASC
1104 `).all(characterId | 0);
1105 }
1106
1107 listFriendRecords (characterId)
1108 {
1109 return this.listAccountFriendRecords(this.accountIdOfCharacter(characterId));
1110 }
1111
1112 accountIdOfCharacter (characterId)
1113 {
1114 const row = this.getCharacter(characterId);
1115 return row?.account_id | 0;
1116 }
1117
1118 getAccount (accountId)
1119 {
1120 return this.db.prepare(`
1121 SELECT account_id, auth_subject, username, email, is_admin
1122 FROM accounts WHERE account_id = ?
1123 `).get(accountId | 0) ?? null;
1124 }
1125
1126 accountDisplayName (accountId)
1127 {
1128 const row = this.getAccount(accountId);
1129 if (!row)
1130 { return "Unknown"; }
1131 const name = String(row.username ?? "").trim();
1132 return name || `Account ${row.account_id}`;
1133 }
1134
1135 listAccountFriendRecords (accountId)
1136 {
1137 const id = accountId | 0;
1138 if (!id)
1139 { return []; }
1140 return this.db.prepare(`
1141 SELECT
1142 CASE WHEN account_id_a = ? THEN account_id_b ELSE account_id_a END AS account_id,
1143 created_at
1144 FROM account_friendships
1145 WHERE account_id_a = ? OR account_id_b = ?
1146 ORDER BY created_at ASC
1147 `).all(id, id, id);
1148 }
1149
1150 areAccountFriends (accountId, otherAccountId)
1151 {
1152 const aId = accountId | 0;
1153 const bId = otherAccountId | 0;
1154 if (!aId || !bId)
1155 { return false; }
1156 if (aId === bId)
1157 { return true; }
1158 const [a, b] = pairIds(aId, bId);
1159 return !!this.db.prepare(`
1160 SELECT 1 FROM account_friendships WHERE account_id_a = ? AND account_id_b = ?
1161 `).get(a, b);
1162 }
1163
1164 areFriends (characterId, otherId)
1165 {
1166 const left = this.getCharacter(characterId);
1167 const right = this.getCharacter(otherId);
1168 if (!left || !right)
1169 { return false; }
1170 return this.areAccountFriends(left.account_id, right.account_id);
1171 }
1172
1173 insertAccountFriendship (accountId, otherId)
1174 {
1175 const [a, b] = pairIds(accountId, otherId);
1176 this.db.prepare(`
1177 INSERT OR IGNORE INTO account_friendships (account_id_a, account_id_b, created_at)
1178 VALUES (?, ?, ?)
1179 `).run(a, b, Date.now());
1180 }
1181
1182 insertFriendship (characterId, otherId)
1183 {
1184 const left = this.getCharacter(characterId);
1185 const right = this.getCharacter(otherId);
1186 if (!left || !right)
1187 { return; }
1188 this.insertAccountFriendship(left.account_id, right.account_id);
1189 }
1190
1191 deleteAccountFriendship (accountId, otherId)
1192 {
1193 const [a, b] = pairIds(accountId, otherId);
1194 this.db.prepare(`
1195 DELETE FROM account_friendships WHERE account_id_a = ? AND account_id_b = ?
1196 `).run(a, b);
1197 }
1198
1199 deleteFriendship (characterId, otherId)
1200 {
1201 const left = this.getCharacter(characterId);
1202 const right = this.getCharacter(otherId);
1203 if (!left || !right)
1204 { return; }
1205 this.deleteAccountFriendship(left.account_id, right.account_id);
1206 }
1207
1208 listIncomingAccountRequests (accountId)
1209 {
1210 return this.db.prepare(`
1211 SELECT request_id, from_account_id, to_account_id, created_at
1212 FROM account_friend_requests
1213 WHERE to_account_id = ?
1214 ORDER BY created_at ASC
1215 `).all(accountId | 0);
1216 }
1217
1218 listOutgoingAccountRequests (accountId)
1219 {
1220 return this.db.prepare(`
1221 SELECT request_id, from_account_id, to_account_id, created_at
1222 FROM account_friend_requests
1223 WHERE from_account_id = ?
1224 ORDER BY created_at ASC
1225 `).all(accountId | 0);
1226 }
1227
1228 listIncomingRequests (characterId)
1229 {
1230 return this.listIncomingAccountRequests(this.accountIdOfCharacter(characterId));
1231 }
1232
1233 listOutgoingRequests (characterId)
1234 {
1235 return this.listOutgoingAccountRequests(this.accountIdOfCharacter(characterId));
1236 }
1237
1238 getAccountFriendRequest (fromAccountId, toAccountId)
1239 {
1240 return this.db.prepare(`
1241 SELECT * FROM account_friend_requests
1242 WHERE from_account_id = ? AND to_account_id = ?
1243 `).get(fromAccountId | 0, toAccountId | 0) ?? null;
1244 }
1245
1246 getFriendRequest (fromId, toId)
1247 {
1248 const from = this.getCharacter(fromId);
1249 const to = this.getCharacter(toId);
1250 if (!from || !to)
1251 { return null; }
1252 return this.getAccountFriendRequest(from.account_id, to.account_id);
1253 }
1254
1255 insertAccountFriendRequest (fromAccountId, toAccountId)
1256 {
1257 this.db.prepare(`
1258 INSERT INTO account_friend_requests (from_account_id, to_account_id, created_at)
1259 VALUES (?, ?, ?)
1260 `).run(fromAccountId | 0, toAccountId | 0, Date.now());
1261 }
1262
1263 insertFriendRequest (fromId, toId)
1264 {
1265 const from = this.getCharacter(fromId);
1266 const to = this.getCharacter(toId);
1267 if (!from || !to)
1268 { return; }
1269 this.insertAccountFriendRequest(from.account_id, to.account_id);
1270 }
1271
1272 deleteAccountFriendRequest (fromAccountId, toAccountId)
1273 {
1274 this.db.prepare(`
1275 DELETE FROM account_friend_requests
1276 WHERE from_account_id = ? AND to_account_id = ?
1277 `).run(fromAccountId | 0, toAccountId | 0);
1278 }
1279
1280 deleteFriendRequest (fromId, toId)
1281 {
1282 const from = this.getCharacter(fromId);
1283 const to = this.getCharacter(toId);
1284 if (!from || !to)
1285 { return; }
1286 this.deleteAccountFriendRequest(from.account_id, to.account_id);
1287 }
1288
1289 /** Decayed kill counter at `now` (does not write). */
1290 peekKillCounter (characterId, now = Date.now())
1291 {
1292 const row = this.getCharacter(characterId);
1293 if (!row)
1294 { return 0; }
1295 const current = Math.max(0, Number(row.kill_counter) || 0);
1296 const at = row.kill_counter_at | 0;
1297 if (!(current > 0) || !at || now <= at)
1298 { return current; }
1299 return decayKillCounter(current, now - at).killCounter;
1300 }
1301
1302 getKillCounterState (characterId)
1303 {
1304 const row = this.getCharacter(characterId);
1305 if (!row)
1306 { return { killCounter: 0, updatedAt: Date.now() }; }
1307 return {
1308 killCounter: Math.max(0, Number(row.kill_counter) || 0),
1309 updatedAt: row.kill_counter_at | 0 || Date.now()
1310 };
1311 }
1312
1313 setKillCounter (characterId, killCounter, updatedAt = Date.now())
1314 {
1315 const value = Math.max(0, Number(killCounter) || 0);
1316 this.db.prepare(`
1317 UPDATE characters SET kill_counter = ?, kill_counter_at = ? WHERE character_id = ?
1318 `).run(value, updatedAt | 0, characterId | 0);
1319 return value;
1320 }
1321
1322 addKillCounter (characterId, amount, now = Date.now())
1323 {
1324 const state = this.getKillCounterState(characterId);
1325 const decayed = decayKillCounter(state.killCounter, Math.max(0, now - (state.updatedAt | 0)));
1326 const next = decayed.killCounter + Math.max(0, Number(amount) || 0);
1327 return this.setKillCounter(characterId, next, now);
1328 }
1329
1330 getCowardiceForgivenHour (characterId)
1331 {
1332 const row = this.getCharacter(characterId);
1333 if (!row || row.cowardice_forgiven_hour == null)
1334 { return null; }
1335 return row.cowardice_forgiven_hour | 0;
1336 }
1337
1338 setCowardiceForgivenHour (characterId, hourKey)
1339 {
1340 this.db.prepare(`
1341 UPDATE characters SET cowardice_forgiven_hour = ? WHERE character_id = ?
1342 `).run(hourKey | 0, characterId | 0);
1343 }
1344
1345 listPersistentInRegion (minX, minY, maxX, maxY, dimensionId = "overworld")
1346 {
1347 const dim = String(dimensionId ?? "overworld");
1348 return this.db.prepare(`
1349 SELECT entity_id, tile_x, tile_y, dimension_id, components_blob
1350 FROM persistent_entities
1351 WHERE tile_x >= ? AND tile_x <= ? AND tile_y >= ? AND tile_y <= ?
1352 AND dimension_id = ?
1353 `).all(minX, maxX, minY, maxY, dim);
1354 }
1355
1356 replacePersistentInRegion (minX, minY, maxX, maxY, entities, dimensionId = "overworld")
1357 {
1358 const dim = String(dimensionId ?? "overworld");
1359 this.db.exec("BEGIN");
1360 try
1361 {
1362 this.db.prepare(`
1363 DELETE FROM persistent_entities
1364 WHERE tile_x >= ? AND tile_x <= ? AND tile_y >= ? AND tile_y <= ?
1365 AND dimension_id = ?
1366 `).run(minX, maxX, minY, maxY, dim);
1367 const insert = this.db.prepare(`
1368 INSERT INTO persistent_entities (entity_id, tile_x, tile_y, dimension_id, components_blob)
1369 VALUES (?, ?, ?, ?, ?)
1370 `);
1371 for (const entity of entities)
1372 {
1373 insert.run(
1374 entity.entityId,
1375 entity.tileX,
1376 entity.tileY,
1377 String(entity.dimensionId ?? dim),
1378 JSON.stringify(entity.payload?.components ?? entity.components)
1379 );
1380 }
1381 this.db.exec("COMMIT");
1382 }
1383 catch (error)
1384 {
1385 this.db.exec("ROLLBACK");
1386 throw error;
1387 }
1388 }
1389
1390 #ensureBag (characterId, starterSettings = null, creationClothing = null)
1391 {
1392 const existing = this.db.prepare("SELECT * FROM character_bags WHERE character_id = ?").get(characterId);
1393 if (existing)
1394 { return parseBag(existing, characterId); }
1395 const contents = buildStarterBagContents(starterSettings, creationClothing);
1396 this.db.prepare(`
1397 INSERT INTO character_bags (
1398 character_id, inventory_blob, equipment_blob, currency, vault_blob, vault_currency, skills_blob
1399 ) VALUES (?, ?, ?, 0, ?, 0, ?)
1400 `).run(
1401 characterId,
1402 JSON.stringify(contents.slots),
1403 JSON.stringify(contents.equipment),
1404 JSON.stringify({ slots: [], reserved: [] }),
1405 JSON.stringify(storedSkillXp(defaultPlayerSkills()))
1406 );
1407 return this.getBag(characterId);
1408 }
1409
1410 getBag (characterId)
1411 {
1412 const row = this.db.prepare("SELECT * FROM character_bags WHERE character_id = ?").get(characterId);
1413 if (row)
1414 { return parseBag(row, characterId); }
1415 if (this.getCharacter(characterId))
1416 { return this.#ensureBag(characterId); }
1417 return null;
1418 }
1419
1420 saveBag (characterId, bag)
1421 {
1422 this.#ensureBag(characterId);
1423 const migrated = migrateBagCoins(bag);
1424 const vault = normalizeVault(
1425 migrated.vaultReserved != null
1426 ? { slots: migrated.vault, reserved: migrated.vaultReserved }
1427 : migrated.vault
1428 );
1429 this.db.prepare(`
1430 UPDATE character_bags
1431 SET inventory_blob = ?, equipment_blob = ?, currency = 0, vault_blob = ?, vault_currency = 0
1432 WHERE character_id = ?
1433 `).run(
1434 JSON.stringify(normalizeInventorySlots(migrated.inventory ?? emptySlots())),
1435 JSON.stringify(migrated.equipment ?? emptyEquipment()),
1436 JSON.stringify({ slots: vault.slots, reserved: vault.reserved }),
1437 characterId
1438 );
1439 }
1440
1441 getSkills (characterId)
1442 {
1443 const row = this.db.prepare("SELECT skills_blob FROM character_bags WHERE character_id = ?").get(characterId);
1444 if (row)
1445 {
1446 const parsed = JSON.parse(row.skills_blob || "{}");
1447 const skills = normalizePlayerSkills(parsed);
1448 // Persist floors (Health ≥ 5, others ≥ 1) for legacy under-leveled rows.
1449 if (this.#skillsBlobNeedsRewrite(parsed, skills))
1450 { this.saveSkills(characterId, skills); }
1451 return skills;
1452 }
1453 if (this.getCharacter(characterId))
1454 {
1455 this.#ensureBag(characterId);
1456 return this.getSkills(characterId);
1457 }
1458 return null;
1459 }
1460
1461 /** True when stored blob is below the default minimum levels and must be rewritten. */
1462 #skillsBlobNeedsRewrite (parsed, normalized)
1463 {
1464 const raw = parsed?.xp && typeof parsed.xp === "object" ? parsed.xp : parsed;
1465 if (!raw || typeof raw !== "object")
1466 { return true; }
1467 for (const skillId of Object.keys(normalized.xp))
1468 {
1469 const stored = Math.max(0, Math.floor(Number(raw[skillId]) || 0));
1470 if (stored < normalized.xp[skillId])
1471 { return true; }
1472 }
1473 return false;
1474 }
1475
1476 saveSkills (characterId, skills)
1477 {
1478 this.#ensureBag(characterId);
1479 const xp = storedSkillXp(skills?.xp ? skills : { xp: skills });
1480 this.db.prepare("UPDATE character_bags SET skills_blob = ? WHERE character_id = ?").run(
1481 JSON.stringify({ xp }),
1482 characterId
1483 );
1484 }
1485
1486 getSpells (characterId)
1487 {
1488 const row = this.db.prepare("SELECT spells_blob FROM character_bags WHERE character_id = ?").get(characterId);
1489 if (row)
1490 {
1491 return normalizePlayerSpells(JSON.parse(row.spells_blob || "{}"));
1492 }
1493 if (this.getCharacter(characterId))
1494 {
1495 this.#ensureBag(characterId);
1496 return this.getSpells(characterId);
1497 }
1498 return null;
1499 }
1500
1501 saveSpells (characterId, spells)
1502 {
1503 this.#ensureBag(characterId);
1504 this.db.prepare("UPDATE character_bags SET spells_blob = ? WHERE character_id = ?").run(
1505 JSON.stringify(storedPlayerSpells(spells)),
1506 characterId
1507 );
1508 }
1509 getInheritance (accountId)
1510 {
1511 const row = this.db.prepare("SELECT * FROM account_inheritance WHERE account_id = ?").get(accountId);
1512 if (!row)
1513 { return { accountId, slots: emptySlots() }; }
1514 return migrateInheritanceCoins({
1515 accountId,
1516 slots: JSON.parse(row.slots_blob),
1517 currency: row.currency
1518 });
1519 }
1520
1521 saveInheritance (accountId, inheritance)
1522 {
1523 const migrated = migrateInheritanceCoins(inheritance);
1524 this.db.prepare(`
1525 INSERT INTO account_inheritance (account_id, slots_blob, currency)
1526 VALUES (?, ?, 0)
1527 ON CONFLICT(account_id) DO UPDATE SET slots_blob = excluded.slots_blob, currency = 0
1528 `).run(accountId, JSON.stringify(migrated.slots ?? emptySlots()));
1529 }
1530
1531 #moveGoodsToInheritance (character)
1532 {
1533 const bag = this.getBag(character.character_id) ?? {
1534 inventory: emptySlots(),
1535 equipment: emptyEquipment(),
1536 vault: [],
1537 vaultReserved: []
1538 };
1539 const inheritance = this.getInheritance(character.account_id);
1540 const vault = normalizeVault(
1541 bag.vaultReserved != null
1542 ? { slots: bag.vault, reserved: bag.vaultReserved }
1543 : bag.vault
1544 );
1545 // Void outstanding cheques issued by this character: reservations return to available vault.
1546 for (const reserved of vault.reserved ?? [])
1547 {
1548 const stack = {
1549 itemId: reserved.itemId,
1550 quantity: reserved.quantity,
1551 origin: reserved.origin ?? null,
1552 instance: reserved.instance ?? null
1553 };
1554 const def = itemDefinition(stack.itemId);
1555 if (!def)
1556 { continue; }
1557 const restored = insertStackGrowable(vault.slots, stack, def);
1558 vault.slots = restored.slots;
1559 }
1560 vault.reserved = [];
1561 const incoming = [
1562 ...(bag.inventory ?? []),
1563 ...Object.values(bag.equipment?.slots ?? {}),
1564 ...(vault.slots ?? [])
1565 ].filter(Boolean);
1566 let slots = inheritance.slots ?? emptySlots();
1567 for (const stack of incoming)
1568 {
1569 const def = itemDefinition(stack.itemId);
1570 if (!def)
1571 { continue; }
1572 const result = insertStack(slots, stack, def);
1573 if (result.ok)
1574 { slots = result.slots; }
1575 else
1576 {
1577 const extra = result.slots;
1578 for (const leftover of extra)
1579 {
1580 if (leftover)
1581 { slots.push(leftover); }
1582 }
1583 slots.push({ ...stack, quantity: result.remainder });
1584 }
1585 }
1586 this.saveInheritance(character.account_id, {
1587 slots: publicSlots(slots)
1588 });
1589 }
1590
1591 nextGroundItemId ()
1592 {
1593 const row = this.db.prepare("SELECT MAX(ground_item_id) AS id FROM ground_items").get();
1594 return (row?.id ?? 0) + 1;
1595 }
1596
1597 listGroundItemsInRegion (minX, minY, maxX, maxY, dimensionId = "overworld")
1598 {
1599 const dim = String(dimensionId ?? "overworld");
1600 return this.db.prepare(`
1601 SELECT * FROM ground_items
1602 WHERE tile_x >= ? AND tile_x <= ? AND tile_y >= ? AND tile_y <= ?
1603 AND dimension_id = ?
1604 `).all(minX, maxX, minY, maxY, dim).map(parseGroundItem);
1605 }
1606
1607 upsertGroundItem (item)
1608 {
1609 this.db.prepare(`
1610 INSERT INTO ground_items (
1611 ground_item_id, tile_x, tile_y, dimension_id, stack_blob, dropped_at, expires_at, source, dropped_by_character_id
1612 ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
1613 ON CONFLICT(ground_item_id) DO UPDATE SET
1614 tile_x = excluded.tile_x,
1615 tile_y = excluded.tile_y,
1616 dimension_id = excluded.dimension_id,
1617 stack_blob = excluded.stack_blob,
1618 dropped_at = excluded.dropped_at,
1619 expires_at = excluded.expires_at,
1620 source = excluded.source,
1621 dropped_by_character_id = excluded.dropped_by_character_id
1622 `).run(
1623 item.groundItemId,
1624 item.tileX,
1625 item.tileY,
1626 String(item.dimensionId ?? "overworld"),
1627 JSON.stringify(item.stack),
1628 item.droppedAt,
1629 item.expiresAt,
1630 item.source,
1631 item.droppedByCharacterId ?? null
1632 );
1633 }
1634
1635 deleteGroundItem (groundItemId)
1636 {
1637 this.db.prepare("DELETE FROM ground_items WHERE ground_item_id = ?").run(groundItemId);
1638 }
1639
1640 insertCourierTransit (transit)
1641 {
1642 const now = transit.updatedAt ?? Date.now();
1643 const result = this.db.prepare(`
1644 INSERT INTO courier_transits (
1645 sender_character_id, destination_kind, destination_character_id, cargo_blob,
1646 origin_x, origin_y, dest_x, dest_y, traveled, status, entity_id, updated_at, created_at,
1647 vault_character_id
1648 ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
1649 `).run(
1650 transit.senderCharacterId,
1651 transit.destinationKind,
1652 transit.destinationCharacterId ?? null,
1653 JSON.stringify(transit.cargo),
1654 transit.originX,
1655 transit.originY,
1656 transit.destX,
1657 transit.destY,
1658 transit.traveled ?? 0,
1659 transit.status ?? "in_transit",
1660 transit.entityId ?? null,
1661 now,
1662 transit.createdAt ?? now,
1663 transit.vaultCharacterId ?? null
1664 );
1665 return this.getCourierTransit(Number(result.lastInsertRowid));
1666 }
1667
1668 getCourierTransit (courierId)
1669 {
1670 const row = this.db.prepare("SELECT * FROM courier_transits WHERE courier_id = ?").get(courierId);
1671 return row ? parseCourierTransit(row) : null;
1672 }
1673
1674 listActiveCourierTransits ()
1675 {
1676 return this.db.prepare(`
1677 SELECT * FROM courier_transits WHERE status = 'in_transit' ORDER BY courier_id ASC
1678 `).all().map(parseCourierTransit);
1679 }
1680
1681 updateCourierTransit (transit)
1682 {
1683 this.db.prepare(`
1684 UPDATE courier_transits
1685 SET traveled = ?, status = ?, entity_id = ?, updated_at = ?,
1686 origin_x = ?, origin_y = ?, dest_x = ?, dest_y = ?,
1687 destination_kind = ?, destination_character_id = ?, vault_character_id = ?
1688 WHERE courier_id = ?
1689 `).run(
1690 transit.traveled ?? 0,
1691 transit.status,
1692 transit.entityId ?? null,
1693 transit.updatedAt ?? Date.now(),
1694 transit.originX,
1695 transit.originY,
1696 transit.destX,
1697 transit.destY,
1698 transit.destinationKind,
1699 transit.destinationCharacterId ?? null,
1700 transit.vaultCharacterId ?? null,
1701 transit.courierId
1702 );
1703 }
1704
1705 appendBankRestNotice (characterId, entry)
1706 {
1707 const qty = Math.max(1, entry.quantity | 0);
1708 this.db.prepare(`
1709 INSERT INTO bank_rest_notices (character_id, item_id, item_name, quantity, source_name, created_at)
1710 VALUES (?, ?, ?, ?, ?, ?)
1711 `).run(
1712 characterId,
1713 entry.itemId | 0,
1714 String(entry.itemName ?? "Item"),
1715 qty,
1716 String(entry.sourceName ?? "unknown source"),
1717 entry.createdAt ?? Date.now()
1718 );
1719 }
1720
1721 listBankRestNotices (characterId)
1722 {
1723 return this.db.prepare(`
1724 SELECT * FROM bank_rest_notices WHERE character_id = ? ORDER BY notice_id ASC
1725 `).all(characterId).map((row) => ({
1726 noticeId: row.notice_id,
1727 characterId: row.character_id,
1728 itemId: row.item_id,
1729 itemName: row.item_name,
1730 quantity: row.quantity,
1731 sourceName: row.source_name,
1732 createdAt: row.created_at
1733 }));
1734 }
1735
1736 clearBankRestNotices (characterId)
1737 {
1738 this.db.prepare("DELETE FROM bank_rest_notices WHERE character_id = ?").run(characterId);
1739 }
1740
1741 insertHeldCourierDelivery (delivery)
1742 {
1743 const now = delivery.createdAt ?? Date.now();
1744 const result = this.db.prepare(`
1745 INSERT INTO held_courier_deliveries (
1746 character_id, sender_character_id, origin_tile_x, origin_tile_y,
1747 destination_kind, destination_character_id, vault_character_id, cargo_blob, created_at
1748 ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
1749 `).run(
1750 delivery.characterId,
1751 delivery.senderCharacterId,
1752 delivery.originTileX | 0,
1753 delivery.originTileY | 0,
1754 delivery.destinationKind,
1755 delivery.destinationCharacterId ?? null,
1756 delivery.vaultCharacterId ?? null,
1757 JSON.stringify(delivery.cargo),
1758 now
1759 );
1760 return Number(result.lastInsertRowid);
1761 }
1762
1763 listHeldCourierDeliveries (characterId)
1764 {
1765 return this.db.prepare(`
1766 SELECT * FROM held_courier_deliveries WHERE character_id = ? ORDER BY hold_id ASC
1767 `).all(characterId).map(parseHeldCourierDelivery);
1768 }
1769
1770 deleteHeldCourierDelivery (holdId)
1771 {
1772 this.db.prepare("DELETE FROM held_courier_deliveries WHERE hold_id = ?").run(holdId);
1773 }
1774
1775 insertMarketOrder (order)
1776 {
1777 const result = this.db.prepare(`
1778 INSERT INTO market_orders (
1779 character_id, side, item_id, quantity, limit_unit_price,
1780 escrow_coins, escrow_stack_blob, listing_key, created_at, status
1781 ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
1782 `).run(
1783 order.characterId,
1784 order.side,
1785 order.itemId | 0,
1786 order.quantity | 0,
1787 order.limitUnitPrice | 0,
1788 order.escrowCoins | 0 || 0,
1789 order.escrowStack ? JSON.stringify(order.escrowStack) : null,
1790 order.listingKey ?? null,
1791 order.createdAt ?? Date.now(),
1792 order.status ?? "open"
1793 );
1794 return this.getMarketOrder(Number(result.lastInsertRowid));
1795 }
1796
1797 getMarketOrder (orderId)
1798 {
1799 const row = this.db.prepare("SELECT * FROM market_orders WHERE order_id = ?").get(orderId);
1800 return row ? parseMarketOrder(row) : null;
1801 }
1802
1803 updateMarketOrder (order)
1804 {
1805 this.db.prepare(`
1806 UPDATE market_orders
1807 SET quantity = ?, escrow_coins = ?, escrow_stack_blob = ?, status = ?
1808 WHERE order_id = ?
1809 `).run(
1810 order.quantity | 0,
1811 order.escrowCoins | 0 || 0,
1812 order.escrowStack ? JSON.stringify(order.escrowStack) : null,
1813 order.status,
1814 order.orderId
1815 );
1816 return this.getMarketOrder(order.orderId);
1817 }
1818
1819 listOpenMarketOrdersForCharacter (characterId)
1820 {
1821 return this.db.prepare(`
1822 SELECT * FROM market_orders
1823 WHERE character_id = ? AND status = 'open'
1824 ORDER BY created_at ASC, order_id ASC
1825 `).all(characterId).map(parseMarketOrder);
1826 }
1827
1828 listOpenBuyOrdersForItem (itemId, listingKey = null)
1829 {
1830 if (listingKey)
1831 {
1832 return this.db.prepare(`
1833 SELECT * FROM market_orders
1834 WHERE status = 'open' AND side = 'buy' AND item_id = ? AND listing_key = ?
1835 ORDER BY limit_unit_price DESC, created_at ASC, order_id ASC
1836 `).all(itemId | 0, listingKey).map(parseMarketOrder);
1837 }
1838 return this.db.prepare(`
1839 SELECT * FROM market_orders
1840 WHERE status = 'open' AND side = 'buy' AND item_id = ?
1841 AND (listing_key IS NULL OR listing_key = '')
1842 ORDER BY limit_unit_price DESC, created_at ASC, order_id ASC
1843 `).all(itemId | 0).map(parseMarketOrder);
1844 }
1845
1846 listOpenSellOrdersForItem (itemId, listingKey = null)
1847 {
1848 if (listingKey)
1849 {
1850 return this.db.prepare(`
1851 SELECT * FROM market_orders
1852 WHERE status = 'open' AND side = 'sell' AND item_id = ? AND listing_key = ?
1853 ORDER BY limit_unit_price ASC, created_at ASC, order_id ASC
1854 `).all(itemId | 0, listingKey).map(parseMarketOrder);
1855 }
1856 return this.db.prepare(`
1857 SELECT * FROM market_orders
1858 WHERE status = 'open' AND side = 'sell' AND item_id = ?
1859 AND (listing_key IS NULL OR listing_key = '')
1860 ORDER BY limit_unit_price ASC, created_at ASC, order_id ASC
1861 `).all(itemId | 0).map(parseMarketOrder);
1862 }
1863
1864 listExpiredMarketOrders (createdBefore)
1865 {
1866 return this.db.prepare(`
1867 SELECT * FROM market_orders
1868 WHERE status = 'open' AND created_at < ?
1869 ORDER BY created_at ASC, order_id ASC
1870 `).all(createdBefore).map(parseMarketOrder);
1871 }
1872
1873 insertMarketTrade (trade)
1874 {
1875 const result = this.db.prepare(`
1876 INSERT INTO market_trades (
1877 buy_order_id, sell_order_id, item_id, quantity, unit_price,
1878 buyer_character_id, seller_character_id, created_at
1879 ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
1880 `).run(
1881 trade.buyOrderId,
1882 trade.sellOrderId,
1883 trade.itemId | 0,
1884 trade.quantity | 0,
1885 trade.unitPrice | 0,
1886 trade.buyerCharacterId,
1887 trade.sellerCharacterId,
1888 trade.createdAt ?? Date.now()
1889 );
1890 return Number(result.lastInsertRowid);
1891 }
1892
1893 upsertItemLastSale (sale)
1894 {
1895 this.db.prepare(`
1896 INSERT INTO item_last_sales (item_id, last_trade_price, last_trade_at, price_from)
1897 VALUES (?, ?, ?, ?)
1898 ON CONFLICT(item_id) DO UPDATE SET
1899 last_trade_price = excluded.last_trade_price,
1900 last_trade_at = excluded.last_trade_at,
1901 price_from = excluded.price_from
1902 `).run(
1903 sale.itemId | 0,
1904 sale.lastTradePrice | 0,
1905 sale.lastTradeAt,
1906 Math.round(Number(sale.priceFrom) || 0)
1907 );
1908 }
1909
1910 listItemLastSales ()
1911 {
1912 return this.db.prepare("SELECT * FROM item_last_sales").all().map((row) => ({
1913 itemId: row.item_id,
1914 lastTradePrice: row.last_trade_price,
1915 lastTradeAt: row.last_trade_at,
1916 priceFrom: row.price_from
1917 }));
1918 }
1919
1920 close ()
1921 {
1922 this.db.close();
1923 }
1924}
1925
1926export function normalizeName (value)
1927{
1928 return String(value ?? "").trim().toLocaleLowerCase();
1929}
1930
1931function pairIds (left, right)
1932{
1933 return left < right ? [left, right] : [right, left];
1934}
1935
1936function parseGroundItem (row)
1937{
1938 return {
1939 groundItemId: row.ground_item_id,
1940 tileX: row.tile_x,
1941 tileY: row.tile_y,
1942 dimensionId: String(row.dimension_id ?? "overworld"),
1943 stack: JSON.parse(row.stack_blob),
1944 droppedAt: row.dropped_at,
1945 expiresAt: row.expires_at,
1946 source: row.source,
1947 droppedByCharacterId: row.dropped_by_character_id
1948 };
1949}
1950
1951function parseMarketOrder (row)
1952{
1953 return {
1954 orderId: row.order_id,
1955 characterId: row.character_id,
1956 side: row.side,
1957 itemId: row.item_id,
1958 quantity: row.quantity,
1959 limitUnitPrice: row.limit_unit_price,
1960 escrowCoins: row.escrow_coins | 0,
1961 escrowStack: row.escrow_stack_blob ? JSON.parse(row.escrow_stack_blob) : null,
1962 listingKey: row.listing_key ?? null,
1963 createdAt: row.created_at,
1964 status: row.status
1965 };
1966}
1967
1968function bagContainsItem (inventory, equipment, itemId)
1969{
1970 for (const stack of inventory ?? [])
1971 {
1972 if (stack?.itemId === itemId)
1973 { return true; }
1974 }
1975 for (const stack of Object.values(equipment?.slots ?? {}))
1976 {
1977 if (stack?.itemId === itemId)
1978 { return true; }
1979 }
1980 return false;
1981}
1982
1983function parseBag (row, characterId)
1984{
1985 const vault = normalizeVault(JSON.parse(row.vault_blob));
1986 return migrateBagCoins({
1987 characterId,
1988 inventory: normalizeInventorySlots(JSON.parse(row.inventory_blob)),
1989 equipment: JSON.parse(row.equipment_blob),
1990 currency: row.currency,
1991 vault: vault.slots,
1992 vaultReserved: vault.reserved,
1993 vaultCurrency: row.vault_currency
1994 });
1995}
1996
1997function parseCourierTransit (row)
1998{
1999 return {
2000 courierId: row.courier_id,
2001 senderCharacterId: row.sender_character_id,
2002 destinationKind: row.destination_kind,
2003 destinationCharacterId: row.destination_character_id,
2004 vaultCharacterId: row.vault_character_id ?? null,
2005 cargo: JSON.parse(row.cargo_blob),
2006 originX: row.origin_x,
2007 originY: row.origin_y,
2008 destX: row.dest_x,
2009 destY: row.dest_y,
2010 traveled: row.traveled,
2011 status: row.status,
2012 entityId: row.entity_id,
2013 updatedAt: row.updated_at,
2014 createdAt: row.created_at
2015 };
2016}
2017
2018function parseHeldCourierDelivery (row)
2019{
2020 return {
2021 holdId: row.hold_id,
2022 characterId: row.character_id,
2023 senderCharacterId: row.sender_character_id,
2024 originTileX: row.origin_tile_x,
2025 originTileY: row.origin_tile_y,
2026 destinationKind: row.destination_kind,
2027 destinationCharacterId: row.destination_character_id,
2028 vaultCharacterId: row.vault_character_id,
2029 cargo: JSON.parse(row.cargo_blob),
2030 createdAt: row.created_at
2031 };
2032}