const axios = require("axios"); function resolveConfig(bru) { return { baseUrl: bru.getEnvVar("baseUrl") || bru.getVar("baseUrl"), playerId: bru.getEnvVar("playerId") || bru.getVar("playerId"), jsonHeaders: { headers: { "Content-Type": "application/json" } }, }; } function inventoryUrl(baseUrl, playerId) { return `${baseUrl}/game/players/${playerId}/inventory`; } function sumItemQuantity(inventory, itemId) { const slots = [...inventory.bagSlots, ...inventory.equipmentSlots]; return slots .filter((slot) => slot.itemId === itemId) .reduce((total, slot) => total + slot.quantity, 0); } async function getInventory(bru) { const { baseUrl, playerId } = resolveConfig(bru); const response = await axios.get(inventoryUrl(baseUrl, playerId)); if (response.status !== 200) { throw new Error(`GET inventory failed: ${response.status}`); } return response.data; } async function postMutation(bru, body) { const { baseUrl, playerId, jsonHeaders } = resolveConfig(bru); return axios.post(inventoryUrl(baseUrl, playerId), body, jsonHeaders); } async function ensureItemQuantity(bru, itemId, minQuantity) { const inventory = await getInventory(bru); const current = sumItemQuantity(inventory, itemId); if (current >= minQuantity) { return current; } const response = await postMutation(bru, { schemaVersion: 1, mutationKind: "add", itemId, quantity: minQuantity - current, }); if (response.status !== 200 || response.data?.applied !== true) { throw new Error( `seed add ${itemId} failed: ${response.status} ${JSON.stringify(response.data)}`, ); } const after = await getInventory(bru); return sumItemQuantity(after, itemId); } async function clearInventory(bru) { for (let pass = 0; pass < 32; pass += 1) { const inventory = await getInventory(bru); const totals = new Map(); for (const slot of [...inventory.bagSlots, ...inventory.equipmentSlots]) { if (!slot.itemId || slot.quantity <= 0) { continue; } totals.set(slot.itemId, (totals.get(slot.itemId) ?? 0) + slot.quantity); } if (totals.size === 0) { return; } for (const [itemId, quantity] of totals) { const response = await postMutation(bru, { schemaVersion: 1, mutationKind: "remove", itemId, quantity, }); if (response.status !== 200 || response.data?.applied !== true) { throw new Error( `clear inventory remove ${itemId} failed: ${response.status} ${JSON.stringify(response.data)}`, ); } } } throw new Error("clearInventory: bag still not empty after removal passes"); } module.exports = { sumItemQuantity, getInventory, postMutation, ensureItemQuantity, clearInventory, };