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 { collectNodeTokens, extractCountdownKeys, extractFlagTokens, extractTernaryKeys, formatFlagValue, hasFlagTokens, interpolateFlags, replaceCountdowns, resolveNodeTexts, resolveTernaries, } 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 ![coin](/api/media/file/coin.png) now"); expect(html).toContain('coin { // Protocol-relative and scheme-less/bad URLs never become . expect(render("![x](//evil.com/a.png)")).not.toContain(" { const html = render("**b** {green}g{/} ![c](/c.png) `code`"); expect(html).toContain(" { 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}} ![coin](/i.png)" }, { label: "B", target: "u" }, ], }, }; expect(collectNodeTokens(node)).toContain("cost"); const resolved = resolveNodeTexts(node, { cost: "5" }); expect(resolved.tooltips?.[0]).toBe("Cost 5 ![coin](/i.png)"); 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(" { 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(" { 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("ternary tokens ({{ cond ? yes : no }})", () => { const truths = { trust: { bool: true, num: 1 }, met: { bool: false, num: 0 }, rep: { bool: true, num: 7 }, }; it("picks branches by boolean truth, negation and numeric comparison", () => { expect(resolveTernaries("He is {{ trust ? friend : hostile }}.", truths)).toBe( "He is friend.", ); expect(resolveTernaries("He is {{ met ? friend : hostile }}.", truths)).toBe( "He is hostile.", ); expect(resolveTernaries("{{ !met ? who_are_you : welcome_back }}", truths)).toBe( "who_are_you", ); expect(resolveTernaries("{{ rep >= 5 ? elite : rookie }}", truths)).toBe("elite"); expect(resolveTernaries("{{ rep > 10 ? elite : rookie }}", truths)).toBe("rookie"); expect(resolveTernaries("{{ rep = 7 ? exact : off }}", truths)).toBe("exact"); }); it("treats missing flags as falsy and keeps malformed tokens literal", () => { expect(resolveTernaries("{{ ghost ? a : b }}", truths)).toBe("b"); expect(resolveTernaries("{{ !ghost ? a : b }}", truths)).toBe("a"); // Not ternaries: plain flag, countdown, and a token without a colon. const plain = "Status {{network_status}} at {{countdown:exfil}} maybe {{ broken"; expect(resolveTernaries(plain, truths)).toBe(plain); }); it("leaves nested tokens for the later passes and resolves nested ternaries", () => { // Branch tokens survive resolveTernaries; interpolateFlags fills them next. const once = resolveTernaries("{{ trust ? {{ rep }} pts : none }}", truths); expect(once).toBe("{{ rep }} pts"); expect(interpolateFlags(once, { rep: "7" })).toBe("7 pts"); // A ternary inside a branch resolves on the second bounded pass. expect( resolveTernaries("{{ trust ? {{ met ? seen : new }} : dark }}", truths), ).toBe("new"); }); it("extracts condition keys (negated and numeric) for the flag read", () => { // The third token has no `?`, so it is not a ternary and contributes nothing. expect(extractTernaryKeys("{{ trust ? a : b }} {{ !met ? c : d }} {{ rep >= 2 : e : f }}")).toEqual([ "trust", "met", ]); expect(extractTernaryKeys("{{ rep >= 2 ? e : f }}")).toEqual(["rep"]); expect(extractTernaryKeys("no tokens {{plain}} {{countdown:x}}")).toEqual([]); }); it("resolves through resolveNodeTexts with values, countdowns and truths", () => { const node: DialogueNode = { id: "t1", type: "dialogue", position: { x: 0, y: 0 }, data: { body: "{{ trust ? Status {{ rep }} : silent }} {{countdown:exfil}}" }, }; const resolved = resolveNodeTexts(node, { rep: "7" }, { exfil: "done" }, truths); expect(resolved.body).toBe("Status 7 {cd|done}"); // collectNodeTokens must see ternary keys so the server reads those flags. expect(collectNodeTokens(node)).toEqual(expect.arrayContaining(["trust", "rep", "exfil"])); }); }); describe("block lists in dialogue markup", () => { const render = (text: string) => renderToStaticMarkup(createElement(DialogueText, { text })); it("renders consecutive dash lines as one bullet list with markers", () => { const html = render("- first\n- second"); expect(html).toContain('role="list"'); expect(html.match(/role="listitem"/g)?.length).toBe(2); expect(html).toContain("first"); expect(html).toContain("\u2022"); }); it("renders numbered lines as an ordered list and keeps inline markup inside items", () => { const html = render("1. **one**\n2. *two*"); expect(html).toContain("one"); expect(html).toContain("two"); expect(html).toContain("1."); expect(html).toContain("2."); }); it("splits paragraphs from lists and adjacent kinds into separate lists", () => { const html = render("intro line\n- a\n- b\n\n1. x\n1. y"); expect(html.match(/role="list"/g)?.length).toBe(2); expect(html).toContain("intro line"); }); it("does not treat leading emphasis or prose asterisks as bullets", () => { const html = render("*emphasis start* is fine"); expect(html).toContain("emphasis start"); expect(html).not.toContain('role="list"'); }); });