The countdown rendered each time unit with a raw monospace space, which reads wide and odd when inline with proportional text. Split the value into per-unit inline-flex cells separated by a CSS gap so spacing stays consistent, and cover the new markup in the interpolate integration test.
509 lines
19 KiB
TypeScript
509 lines
19 KiB
TypeScript
import { getPayload, Payload } from "payload";
|
|
import config from "@/payload.config";
|
|
import { createElement } from "react";
|
|
import { renderToStaticMarkup } from "react-dom/server";
|
|
|
|
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
|
|
|
import type { DialogueNode } from "@/lib/npc-dialogue/dialogue";
|
|
import { DialogueText, formatRemaining } from "@/lib/npc-dialogue/DialogueText";
|
|
import { gateCondition, selectDialogueForUser } from "@/lib/npc-dialogue/selection";
|
|
import { evaluateCondition, readFlag } from "@/lib/npc-dialogue/flags";
|
|
import { flowHash, mergeSeenNodes, unseenNodeIds } from "@/lib/npc-dialogue/seen";
|
|
import {
|
|
collectNodeTokens,
|
|
extractCountdownKeys,
|
|
extractFlagTokens,
|
|
formatFlagValue,
|
|
hasFlagTokens,
|
|
interpolateFlags,
|
|
replaceCountdowns,
|
|
resolveNodeTexts,
|
|
} from "@/lib/npc-dialogue/interpolate";
|
|
|
|
let payload: Payload;
|
|
|
|
const RUN = `dlg_${Date.now().toString(36)}`;
|
|
const TIMEOUT = 30_000;
|
|
|
|
describe("flag token extraction + interpolation (pure)", () => {
|
|
it("extracts distinct lowercased keys and ignores single-brace markup", () => {
|
|
expect(extractFlagTokens("Status: {{network_status}}. {{NETWORK_STATUS}} again")).toEqual([
|
|
"network_status",
|
|
]);
|
|
expect(extractFlagTokens("{green}no tokens here{/} **bold**")).toEqual([]);
|
|
expect(extractFlagTokens(undefined)).toEqual([]);
|
|
expect(hasFlagTokens("a {{x}} b")).toBe(true);
|
|
expect(hasFlagTokens("{red}x{/}")).toBe(false);
|
|
});
|
|
|
|
it("substitutes values, resolves missing keys to empty, keeps markup intact", () => {
|
|
const out = interpolateFlags("Link {{network_status}}, rep {{rep_merchants}}", {
|
|
network_status: "{green}NOMINAL{/}",
|
|
});
|
|
expect(out).toBe("Link {green}NOMINAL{/}, rep ");
|
|
});
|
|
|
|
it("is case-insensitive on keys and never re-scans substituted values", () => {
|
|
const out = interpolateFlags("{{Key}} says {{key}}", {
|
|
key: "{{key}}",
|
|
});
|
|
// Single pass: the injected token must survive literally, not expand.
|
|
expect(out).toBe("{{key}} says {{key}}");
|
|
});
|
|
|
|
it("formats flag values per type for interpolation", () => {
|
|
expect(formatFlagValue({ flagType: "text", textValue: "{green}OK{/}" })).toBe("{green}OK{/}");
|
|
expect(formatFlagValue({ flagType: "text" })).toBe("");
|
|
expect(formatFlagValue({ flagType: "number", numberValue: 7 })).toBe("7");
|
|
expect(formatFlagValue({ flagType: "number" })).toBe("0");
|
|
expect(formatFlagValue({ flagType: "boolean", boolValue: true })).toBe("true");
|
|
expect(formatFlagValue({ flagType: "boolean", boolValue: false })).toBe("false");
|
|
});
|
|
|
|
it("collects node tokens across body, lead-in, closing, effect message, labels", () => {
|
|
const node: DialogueNode = {
|
|
id: "n1",
|
|
type: "choice",
|
|
position: { x: 0, y: 0 },
|
|
data: {
|
|
leadIn: "Ops report: {{ops_status}}",
|
|
choices: [
|
|
{ label: "Ack ({{clearance_level}})", target: "a" },
|
|
{ label: "No tokens", target: "b" },
|
|
],
|
|
},
|
|
};
|
|
expect(new Set(collectNodeTokens(node))).toEqual(new Set(["ops_status", "clearance_level"]));
|
|
});
|
|
|
|
it("resolves only the fields a node defines, index-aligning labels", () => {
|
|
const node: DialogueNode = {
|
|
id: "n1",
|
|
type: "dialogue",
|
|
position: { x: 0, y: 0 },
|
|
data: { body: "Status {{network_status}}", next: { target: "x" } },
|
|
};
|
|
const resolved = resolveNodeTexts(node, { network_status: "{red}DOWN{/}" });
|
|
expect(resolved).toEqual({ body: "Status {red}DOWN{/}" });
|
|
|
|
const choice: DialogueNode = {
|
|
id: "n2",
|
|
type: "choice",
|
|
position: { x: 0, y: 0 },
|
|
data: {
|
|
leadIn: "{{greeting}}",
|
|
choices: [
|
|
{ label: "{{a}}", target: "t" },
|
|
{ label: "plain", target: "u" },
|
|
],
|
|
},
|
|
};
|
|
const r2 = resolveNodeTexts(choice, { greeting: "Hi", a: "1" });
|
|
expect(r2.leadIn).toBe("Hi");
|
|
expect(r2.labels).toEqual(["1", "plain"]);
|
|
expect(r2.body).toBeUndefined();
|
|
});
|
|
});
|
|
|
|
describe("text flags (player-flags collection)", () => {
|
|
beforeAll(async () => {
|
|
payload = await getPayload({ config });
|
|
}, TIMEOUT);
|
|
|
|
afterAll(async () => {
|
|
const res = await payload.find({
|
|
collection: "player-flags",
|
|
where: { key: { like: `${RUN}%` } },
|
|
limit: 50,
|
|
overrideAccess: true,
|
|
});
|
|
for (const doc of res.docs) {
|
|
await payload.delete({ collection: "player-flags", id: doc.id, overrideAccess: true });
|
|
}
|
|
});
|
|
|
|
it("stores and reads a global text flag with markup", async () => {
|
|
const created = await payload.create({
|
|
collection: "player-flags",
|
|
data: {
|
|
user: null,
|
|
key: `${RUN}_network_status`,
|
|
flagType: "text",
|
|
textValue: "{green}NOMINAL{/}",
|
|
},
|
|
overrideAccess: true,
|
|
});
|
|
expect(created.flagType).toBe("text");
|
|
expect(created.textValue).toBe("{green}NOMINAL{/}");
|
|
|
|
const fetched = await payload.findByID({
|
|
collection: "player-flags",
|
|
id: created.id,
|
|
overrideAccess: true,
|
|
});
|
|
expect(fetched.textValue).toBe("{green}NOMINAL{/}");
|
|
|
|
// Interpolates into dialogue text exactly as authored.
|
|
const values = { [`${RUN}_network_status`]: formatFlagValue(fetched) };
|
|
const line = interpolateFlags(`Grid says {{${RUN}_network_status}}`, values);
|
|
expect(line).toBe(`Grid says {green}NOMINAL{/}`);
|
|
});
|
|
|
|
it("converts an existing boolean flag to text via update (set_text semantics)", async () => {
|
|
const created = await payload.create({
|
|
collection: "player-flags",
|
|
data: { user: null, key: `${RUN}_converted`, flagType: "boolean", boolValue: true },
|
|
overrideAccess: true,
|
|
});
|
|
const updated = await payload.update({
|
|
collection: "player-flags",
|
|
id: created.id,
|
|
data: { flagType: "text", textValue: "{amber}REDACTED{/}" },
|
|
overrideAccess: true,
|
|
});
|
|
expect(updated.flagType).toBe("text");
|
|
expect(updated.textValue).toBe("{amber}REDACTED{/}");
|
|
expect(formatFlagValue(updated)).toBe("{amber}REDACTED{/}");
|
|
});
|
|
|
|
it("stores conversation priority + entry gate and drives selection", async () => {
|
|
const npc = await payload.create({
|
|
collection: "game-npcs",
|
|
data: { name: `${RUN}_gate_npc`, canMessage: true },
|
|
overrideAccess: true,
|
|
});
|
|
const flow = { nodes: [], edges: [] };
|
|
const gated = await payload.create({
|
|
collection: "npc-dialogues",
|
|
data: {
|
|
name: `${RUN}_gated`,
|
|
npc: npc.id,
|
|
flowData: flow,
|
|
priority: 10,
|
|
entryGate: { key: `${RUN}_met`, op: "is_true" },
|
|
},
|
|
overrideAccess: true,
|
|
});
|
|
const fallback = await payload.create({
|
|
collection: "npc-dialogues",
|
|
data: { name: `${RUN}_fallback`, npc: npc.id, flowData: flow },
|
|
overrideAccess: true,
|
|
});
|
|
try {
|
|
const res = await payload.find({
|
|
collection: "npc-dialogues",
|
|
where: { npc: { equals: npc.id } },
|
|
limit: 10,
|
|
depth: 0,
|
|
overrideAccess: true,
|
|
});
|
|
expect(res.docs).toHaveLength(2);
|
|
|
|
const unlocked = new Set([`${RUN}_met`]);
|
|
const chosen = await selectDialogueForUser(res.docs, async (c) => unlocked.has(c.key));
|
|
expect(chosen?.id).toBe(gated.id);
|
|
|
|
const fallen = await selectDialogueForUser(res.docs, async () => false);
|
|
expect(fallen?.id).toBe(fallback.id);
|
|
} finally {
|
|
for (const doc of [gated, fallback]) {
|
|
await payload.delete({ collection: "npc-dialogues", id: doc.id, overrideAccess: true });
|
|
}
|
|
await payload.delete({ collection: "game-npcs", id: npc.id, overrideAccess: true });
|
|
}
|
|
});
|
|
|
|
it("reads time-gated flags: pending fails with a countdown target, expired reads missing", async () => {
|
|
const future = new Date(Date.now() + 3_600_000).toISOString();
|
|
const past = new Date(Date.now() - 3_600_000).toISOString();
|
|
const pending = await payload.create({
|
|
collection: "player-flags",
|
|
data: { key: `${RUN}_pending`, flagType: "boolean", boolValue: true, activatesAt: future },
|
|
overrideAccess: true,
|
|
});
|
|
const expired = await payload.create({
|
|
collection: "player-flags",
|
|
data: { key: `${RUN}_expired`, flagType: "number", numberValue: 9, expiresAt: past },
|
|
overrideAccess: true,
|
|
});
|
|
try {
|
|
const userId = 999_999; // no player docs for this id; exercises the global path
|
|
const pendingRead = await readFlag(payload, userId, `${RUN}_pending`);
|
|
expect(pendingRead.bool).toBe(false);
|
|
expect(pendingRead.exists).toBe(true);
|
|
expect(pendingRead.activatesAt).toBe(future);
|
|
await expect(
|
|
evaluateCondition(payload, userId, { kind: "flag", key: `${RUN}_pending`, op: "is_true" }),
|
|
).resolves.toBe(false);
|
|
|
|
const expiredRead = await readFlag(payload, userId, `${RUN}_expired`);
|
|
expect(expiredRead.exists).toBe(false);
|
|
expect(expiredRead.num).toBe(0);
|
|
await expect(
|
|
evaluateCondition(payload, userId, { kind: "flag", key: `${RUN}_expired`, op: "gte", amount: 1 }),
|
|
).resolves.toBe(false);
|
|
} finally {
|
|
for (const doc of [pending, expired]) {
|
|
await payload.delete({ collection: "player-flags", id: doc.id, overrideAccess: true });
|
|
}
|
|
}
|
|
});
|
|
});
|
|
|
|
describe("inline images in dialogue markup", () => {
|
|
const render = (text: string) =>
|
|
renderToStaticMarkup(createElement(DialogueText, { text }));
|
|
|
|
it("renders site-relative and absolute-http images as inline icons", () => {
|
|
const html = render("Pay 5  now");
|
|
expect(html).toContain('<img src="/api/media/file/coin.png" alt="coin"');
|
|
expect(render("")).toContain("<img");
|
|
});
|
|
|
|
it("leaves unsafe or malformed image URLs literal", () => {
|
|
// Protocol-relative and scheme-less/bad URLs never become <img>.
|
|
expect(render("")).not.toContain("<img");
|
|
expect(render("")).not.toContain("<img");
|
|
expect(render("")).not.toContain("<img");
|
|
});
|
|
|
|
it("keeps existing markup working alongside images", () => {
|
|
const html = render("**b** {green}g{/}  `code`");
|
|
expect(html).toContain("<strong");
|
|
expect(html).toContain("text-green-400");
|
|
expect(html).toContain("<img");
|
|
expect(html).toContain("<code");
|
|
});
|
|
});
|
|
|
|
describe("conversation selection (entry gates + priority)", () => {
|
|
const pass = async () => true;
|
|
const fail = async () => false;
|
|
|
|
it("prefers higher priority regardless of input order", async () => {
|
|
const docs = [
|
|
{ id: 1, priority: 0 },
|
|
{ id: 2, priority: 10 },
|
|
{ id: 3, priority: 5 },
|
|
];
|
|
expect((await selectDialogueForUser(docs, pass))?.id).toBe(2);
|
|
});
|
|
|
|
it("breaks ties by oldest id", async () => {
|
|
const docs = [{ id: 7 }, { id: 3, priority: 0 }];
|
|
expect((await selectDialogueForUser(docs, pass))?.id).toBe(3);
|
|
});
|
|
|
|
it("skips gated conversations whose condition fails, falling back to ungated", async () => {
|
|
const docs = [
|
|
{ id: 1, priority: 10, entryGate: { key: "met_fixer", op: "is_true" as const } },
|
|
{ id: 2, priority: 0 },
|
|
];
|
|
expect((await selectDialogueForUser(docs, fail))?.id).toBe(2);
|
|
expect((await selectDialogueForUser(docs, pass))?.id).toBe(1);
|
|
});
|
|
|
|
it("returns null when every candidate is gated shut", async () => {
|
|
const docs = [{ id: 1, entryGate: { key: "secret", op: "is_true" as const } }];
|
|
expect(await selectDialogueForUser(docs, fail)).toBeNull();
|
|
});
|
|
|
|
it("treats blank gate keys as ungated and defaults the op", () => {
|
|
expect(gateCondition({ key: " " })).toBeNull();
|
|
expect(gateCondition(null)).toBeNull();
|
|
expect(gateCondition({ key: "x" })).toEqual({
|
|
kind: "flag",
|
|
key: "x",
|
|
op: "is_true",
|
|
amount: 0,
|
|
});
|
|
});
|
|
});
|
|
|
|
describe("choice tooltip interpolation", () => {
|
|
it("collects tokens from tooltips and resolves them index-aligned", () => {
|
|
const node: DialogueNode = {
|
|
id: "n",
|
|
type: "choice",
|
|
position: { x: 0, y: 0 },
|
|
data: {
|
|
choices: [
|
|
{ label: "A", target: "t", tooltip: "Cost {{cost}} " },
|
|
{ label: "B", target: "u" },
|
|
],
|
|
},
|
|
};
|
|
expect(collectNodeTokens(node)).toContain("cost");
|
|
const resolved = resolveNodeTexts(node, { cost: "5" });
|
|
expect(resolved.tooltips?.[0]).toBe("Cost 5 ");
|
|
expect(resolved.tooltips?.[1]).toBe("");
|
|
});
|
|
|
|
it("omits the tooltips array when no choice has a tooltip", () => {
|
|
const node: DialogueNode = {
|
|
id: "n",
|
|
type: "choice",
|
|
position: { x: 0, y: 0 },
|
|
data: { choices: [{ label: "A", target: "t" }] },
|
|
};
|
|
expect(resolveNodeTexts(node, {}).tooltips).toBeUndefined();
|
|
});
|
|
});
|
|
|
|
describe("markup accumulation + links + countdowns", () => {
|
|
const render = (text: string) =>
|
|
renderToStaticMarkup(createElement(DialogueText, { text }));
|
|
|
|
it("accumulates bold inside color and color inside bold", () => {
|
|
const stacked = render("{green}**cargo** secured{/}");
|
|
expect(stacked).toContain("text-green-400");
|
|
expect(stacked).toContain("<strong");
|
|
const wrapped = render("**{red}danger{/} zone**");
|
|
expect(wrapped).toContain("<strong");
|
|
expect(wrapped).toContain("text-red-400");
|
|
});
|
|
|
|
it("closes nested colors inner-first", () => {
|
|
const html = render("{cyan}outer {red}inner{/} tail{/}");
|
|
expect(html).toContain("text-cyan-400");
|
|
expect(html).toContain("text-red-400");
|
|
expect(html).toContain("tail");
|
|
expect(html).not.toContain("{/}");
|
|
});
|
|
|
|
it("renders hex colors wrapping nested markup", () => {
|
|
const html = render("{#ff00ff}*wow*{/}");
|
|
expect(html).toContain("color:#ff00ff");
|
|
expect(html).toContain("<em");
|
|
});
|
|
|
|
it("renders safe links as anchors and refuses javascript: urls", () => {
|
|
const ok = render("[After Action Report](/intelligence/missions/12)");
|
|
expect(ok).toContain('href="/intelligence/missions/12"');
|
|
expect(ok).toContain("After Action Report");
|
|
const bad = render("[trap](javascript:alert(1))");
|
|
expect(bad).not.toContain("href=");
|
|
expect(bad).toContain("[trap]");
|
|
});
|
|
|
|
it("renders countdown leaves: ticking, ready, and empty", () => {
|
|
const future = new Date(Date.now() + 3_600_000).toISOString();
|
|
expect(render(`{cd|${future}}`)).toContain("text-cyan-300");
|
|
expect(render("{cd|done}")).toContain("ready");
|
|
const empty = render("x{cd|}y");
|
|
expect(empty).toContain("xy");
|
|
expect(empty).not.toContain("cd|");
|
|
// Each unit is its own inline-flex cell (CSS gap) so the gap between units
|
|
// is controlled instead of the raw monospace space reading wide/odd inline.
|
|
const html = render(`{cd|${future}}`);
|
|
expect(html).toContain("inline-flex");
|
|
expect(html.match(/whitespace-nowrap/g)?.length).toBe(2);
|
|
});
|
|
|
|
it("formats remaining time compactly", () => {
|
|
expect(formatRemaining(9_000)).toBe("9s");
|
|
expect(formatRemaining(63_000)).toBe("1m 03s");
|
|
expect(formatRemaining(3_661_000)).toBe("1h 01m");
|
|
expect(formatRemaining(93_600_000)).toBe("1d 2h");
|
|
expect(formatRemaining(-5)).toBe("0s");
|
|
});
|
|
});
|
|
|
|
describe("countdown token resolution (pure)", () => {
|
|
it("collects countdown keys so nodes get resolved", () => {
|
|
const node: DialogueNode = {
|
|
id: "n",
|
|
type: "dialogue",
|
|
position: { x: 0, y: 0 },
|
|
data: { body: "Analysis done in {{countdown:device_scan}}." },
|
|
};
|
|
expect(collectNodeTokens(node)).toContain("device_scan");
|
|
expect(extractCountdownKeys("{{countdown:A}} {{countdown:a}} {{flag}}")).toEqual(["a"]);
|
|
});
|
|
|
|
it("rewrites tokens to leaves with resolved values", () => {
|
|
const node: DialogueNode = {
|
|
id: "n",
|
|
type: "dialogue",
|
|
position: { x: 0, y: 0 },
|
|
data: { body: "{{countdown:device_scan}} / {{countdown:missing}}" },
|
|
};
|
|
const out = resolveNodeTexts(node, {}, { device_scan: "2030-01-01T00:00:00.000Z" });
|
|
expect(out.body).toBe("{cd|2030-01-01T00:00:00.000Z} / {cd|}");
|
|
});
|
|
|
|
it("replaceCountdowns lowercases keys and defaults missing to empty", () => {
|
|
expect(replaceCountdowns("{{countdown:KEY}}", { key: "done" })).toBe("{cd|done}");
|
|
expect(replaceCountdowns("{{countdown:key}}", {})).toBe("{cd|}");
|
|
});
|
|
|
|
it("resolves locked hints index-aligned with the choices", () => {
|
|
const node: DialogueNode = {
|
|
id: "n",
|
|
type: "choice",
|
|
position: { x: 0, y: 0 },
|
|
data: {
|
|
choices: [
|
|
{ label: "A", target: "t", lockedHint: "Needs {{rep}} rep" },
|
|
{ label: "B", target: "u" },
|
|
],
|
|
},
|
|
};
|
|
const out = resolveNodeTexts(node, { rep: "3" });
|
|
expect(out.hints?.[0]).toBe("Needs 3 rep");
|
|
expect(out.hints?.[1]).toBe("");
|
|
});
|
|
});
|
|
|
|
describe("seen tracking (NEW badges)", () => {
|
|
it("hashes flowcharts deterministically and differently on change", () => {
|
|
expect(flowHash({ nodes: [{ id: "a" }] })).toBe(flowHash({ nodes: [{ id: "a" }] }));
|
|
expect(flowHash({ nodes: [{ id: "a" }] })).not.toBe(flowHash({ nodes: [{ id: "b" }] }));
|
|
});
|
|
|
|
it("ignores layout (positions, edge ids/styling) and key order", () => {
|
|
const base = {
|
|
nodes: [{ id: "a", type: "dialogue", position: { x: 0, y: 0 }, data: { body: "hi" } }],
|
|
edges: [{ id: "e1", source: "a", target: "b", style: {} }],
|
|
};
|
|
const rearranged = {
|
|
nodes: [{ id: "a", type: "dialogue", position: { x: 900, y: 400 }, data: { body: "hi" } }],
|
|
edges: [{ id: "zzz", source: "a", target: "b", style: { stroke: "red" } }],
|
|
};
|
|
expect(flowHash(rearranged)).toBe(flowHash(base));
|
|
const reordered = {
|
|
nodes: [{ data: { body: "hi" }, type: "dialogue", id: "a" }],
|
|
edges: [{ target: "b", source: "a" }],
|
|
};
|
|
expect(flowHash(reordered)).toBe(flowHash(base));
|
|
});
|
|
|
|
it("re-flags when node content changes", () => {
|
|
const base = { nodes: [{ id: "a", type: "dialogue", data: { body: "hi" } }] };
|
|
const edited = { nodes: [{ id: "a", type: "dialogue", data: { body: "changed" } }] };
|
|
expect(flowHash(edited)).not.toBe(flowHash(base));
|
|
const addedChoice = {
|
|
nodes: [
|
|
{ id: "a", type: "dialogue", data: { body: "hi" } },
|
|
{ id: "b", type: "choice", data: { choices: [{ label: "New path", target: "a" }] } },
|
|
],
|
|
};
|
|
expect(flowHash(addedChoice)).not.toBe(flowHash(base));
|
|
});
|
|
|
|
it("treats a hash mismatch as everything unseen", () => {
|
|
expect(unseenNodeIds({ hash: "old", nodes: ["a", "b"] }, "new", ["a", "b"])).toEqual([
|
|
"a",
|
|
"b",
|
|
]);
|
|
expect(unseenNodeIds({ hash: "x", nodes: ["a"] }, "x", ["a", "b"])).toEqual(["b"]);
|
|
expect(unseenNodeIds(undefined, "x", ["a"])).toEqual(["a"]);
|
|
});
|
|
|
|
it("merges seen nodes without duplicates and resets on new hash", () => {
|
|
expect(mergeSeenNodes({ hash: "x", nodes: ["a"] }, "x", "a")).toEqual(["a"]);
|
|
expect(mergeSeenNodes({ hash: "x", nodes: ["a"] }, "x", "b")).toEqual(["a", "b"]);
|
|
expect(mergeSeenNodes({ hash: "old", nodes: ["a"] }, "new", "b")).toEqual(["b"]);
|
|
});
|
|
});
|