feat(livestreamassist): add Chinese live dashboard with game icons

- Add a URL-driven Chinese overlay page rendering item rate tables,
  tech levels, current research, and Dyson sphere power for streams.
- Add the offline GameIcons layer and generate_icons.py, which extracts
  every item and tech icon from a local DSP install into
  js/generated/dsp-icons.js.
- Reuse the proto extraction in generate_text.py and cover the new
  page with test_dashboard.js.
This commit is contained in:
soarqin committed 2026-09-20 03:44:27 +08:00
1 parent 63a6a6ec6c
commit 3e3e995d55
12 files changed
+787 -15

No files matched your search

+29 -5
View File
@@ -2,22 +2,25 @@
Browser helper for the [WebSocket API](../docs/WebSocketApi.md). It is intended for OBS Browser Sources and local overlay pages with BigInt and `Promise.allSettled` support. There is no npm build; load the packed script as a classic `<script>`.
The library has three layers:
The library has four layers:
| Layer | Script surface | WebSocket? | Role |
| --- | --- | --- | --- |
| Low-level client | `LiveStreamAssist.Client` | Yes | JSON-RPC 2.0 transport, method wrappers, pending-request limit |
| High-level query | `LiveStreamAssist.GameQuery` | Yes | Common overlay reads: item rates, research, Dyson power |
| Game text | `LiveStreamAssist.GameText` | No | ID to localized name, DSP KMG formatting |
| Game icons | `LiveStreamAssist.GameIcons` | No | ID to icon data URL extracted from game textures |
`GameText` never sends API requests. Names come from generated dictionaries converted from the game's `Locale/` files and prototype tables.
`GameText` and `GameIcons` never send API requests. Names come from generated dictionaries converted from the game's `Locale/` files and prototype tables; icons come from textures extracted from a local install.
## Files
- `livestream-assist.js` — packed browser bundle
- `generated/dsp-text.js` — generated locale/proto dictionary
- `generated/dsp-icons.js` — generated item/tech icon data URLs
- `src/` — layer sources concatenated by `scripts/pack_js.py`
- `scripts/generate_text.py` — regenerate text data from a local DSP install
- `scripts/generate_icons.py` — regenerate icon data from a local DSP install
## Overlay usage
@@ -54,8 +57,21 @@ Examples:
- [research-overlay.html](../examples/research-overlay.html)
- [stats-overlay.html](../examples/stats-overlay.html)
- [live-dashboard.html](../examples/live-dashboard.html)
Keep `examples/` and `js/` side by side when copying these pages. Both examples retry failed connections, wait for each polling cycle to finish before scheduling another, and discard old results when the URL changes. Use `?lang=en`, `?lang=zh-CN`, or an LCID such as `?lang=2052`; the stats example also accepts `?item=1101`.
Keep `examples/` and `js/` side by side when copying these pages. The examples retry failed connections, wait for each polling cycle to finish before scheduling another, and discard stale results after connection changes. Use `?lang=en`, `?lang=zh-CN`, or an LCID such as `?lang=2052`; the stats example also accepts `?item=1101`.
The Chinese live-dashboard page shows only the sections selected by URL parameters and defaults to research plus Dyson power when none are given:
```text
?items=1101,1203&techs=1001,1104&research=1&dyson=1&window=1min
```
- `items` renders the game-style rate table: each material has two rows (production with its theoretical value, then consumption with its theoretical value) sharing one icon and name cell.
- `techs` renders tech levels: `cur/max` for repeatable techs, 已解锁/未解锁 for one-time techs.
- `research` renders the current tech with a progress bar and hash counters.
- `dyson` renders total Dyson sphere power generation.
- `window` selects the rate window (`1min` default, `10min`, `1hour`, `10hour`, `100hour`, `total`).
## Low-level client
@@ -102,12 +118,20 @@ Load `generated/dsp-text.js` before the library, then `GameText.fromGenerated({
- `techDisplayName(id, curLevel)` matches `TechState.currentTechString`: name, or name + `杠等级` + level
- `formatKmg`, `formatPower`, `formatEnergy` match `StringBuilderUtility.WriteKMG` / `WriteKMGPower` / `WriteKMGEnergy`: values below 10000 stay raw, then k/M/G/T/P/E with three leading digits. Decimal separators follow the selected language (`小数点`).
## Regenerating text data
## Game icons
Load `generated/dsp-icons.js` before the library, then `GameIcons.fromGenerated()`.
- `itemIcon(id)`, `techIcon(id)`, and `icon(kind, id)` return PNG data URLs extracted from the game's `Icons/ItemRecipe` and `Icons/Tech` textures, or `null` for unknown IDs.
- The data file is around 3.5 MB because it embeds every item and tech icon; pages should keep referencing it from disk like the other generated data.
## Regenerating text and icon data
Requires a local DSP install plus `pip install -r LiveStreamAssist/js/scripts/requirements.txt`.
```text
python LiveStreamAssist/js/scripts/generate_text.py --game-root "<DSP install>"
python LiveStreamAssist/js/scripts/generate_icons.py --game-root "<DSP install>"
python LiveStreamAssist/js/scripts/pack_js.py
```
@@ -119,7 +143,7 @@ Run from the repository root. JavaScript checks use Node.js 20 or later and requ
```text
python LiveStreamAssist/js/scripts/pack_js.py
node --test LiveStreamAssist/js/scripts/test_client.js LiveStreamAssist/js/scripts/test_query.js LiveStreamAssist/js/scripts/test_text.js LiveStreamAssist/js/scripts/test_overlays.js
node --test LiveStreamAssist/js/scripts/test_client.js LiveStreamAssist/js/scripts/test_query.js LiveStreamAssist/js/scripts/test_text.js LiveStreamAssist/js/scripts/test_overlays.js LiveStreamAssist/js/scripts/test_dashboard.js
python LiveStreamAssist/js/scripts/test_text.py
```
@@ -0,0 +1,2 @@
/* Generated from a local Dyson Sphere Program install by generate_icons.py. Do not edit. */
globalThis.LiveStreamAssistIconData = {"version":"1.0.0","icons":{"item":{"1000":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFAAAABQCAYAAACOEfKtAAACfElEQVR42u2cMU4DMRBFvydbBtFAQQRIaXIBjsIV4FScAYmrUEIBoiGKqEAUNJFpDMouibCzXu/MeL7kZuUknuc/49lA1nnvkUOXN88AgLWbgLPurs6zvh/lhCdBuddKNcEbYs1UG7zca3f71kApNW/omki1OS93LFQzvBwxUe3w+sYWXQO11LzcNZFqd17fWMng9YuZGMPzYbCGuLMGjlzzuotyXGsiMXVezDUWTiQB8FhDJMgSO4hNd9KIfZ6HQJGA1GXtQhIGjx1EEgiPFURauwk2hx0qbe3i8wORNAdf9BARDG/UVCbo0GgQG0XB+hL3zN1zgmpxirYaqGaDSGFwXiNAdamrNYWLbxgpdp/XAFBt6mpP4WIbSOY+c+CoG0mVuM+bAytKYV9TKpsDmQHkfvJ6c6C1MQZQeuPszYGWwgbQZADzqBG01hcAKwBvAD4BTAGcADgGcGYAd+sLwD2Ap871jzAeACzCOLAU/qtt8Lp6DMNq4Ja0fYqc+wjg1QC2tUqcvzSAbb0NDFw9wM/E+e+SAQ7xn1HTxPmHpdfJ3YEnifOPLIXbOk6cfyodYO40PgsNcowWAGaly4yERnoRAXGRAJr9rZ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HYt1AOqiz/VNypX5N0WtiWBNdHOC6hbRO1OzhSce9dd7P9gYeIMkNhdBnFgQHGgGoQ4NsWDx6YZLxUYtPwAPVuRJIkrBnsY/XIEI9OzTAcuuQaBgoF9lrQaUXs2b4brVNGRkbISEjjHMt2kLaNSlPxnGnhp+2J6TRO9PdrMVxjjMZ2bBwvICj34VnQmGuSxR0c12Hfzt0kSYo7up6xTes5c8smFLC8WGC2G+O5LisHQubbXTppyoaREVYP9XGo0WSwGOIKyUDoEAhBuxMzPTVHt1mnf7Afx5LEqcYYhe16uF5AJ+oOPGcY+LSHcgUXrdSx+SpjFEqDtF36B0r4Imd26iDNThfheBhpI6RHODBOmuasXt7P2etWkAPagC0lA4UA37ZJlKYVJWwYG6avXGK60SRKEoq+SznwmJmdx7Isup0WQRDQ399HluYI2ZsxtWwHNwgxWr/caM2znZ+OBIol3wDglwKSTnJk/RW5MgS+x9BAiTTLmKs2SBRYfhkpDWG5jPTLRHGGaXRwgoBumhD5NkjwLIuiY1PrdLEFrB3qx7YsumlOkuZMJw3OXjnOt+/6MQ8+vBMHRRZrxleMY0sLlSlyleM4Ln4hoFDppzF98JeB//Zz1YWP0CaLB2dqIyph0GNeN1XMznfRwsEvlXBsm7BSJuzrB9fDTzXab/Lw4zPcfOuPeeULt1F2HCwEnuVgi5TRSonAstg7N89Uo0Wc5ly8aQ2Hpqt857YfkkUxRmrGV07guQ5ZkpFnOXGUMDRSpjk3xdzBfRRHxu/4ecFAcyQRteMjybe7jk1Y8Km2EhrdFNtxqRRDgjDACQqUCj65tMgcjyDwGPJCJvcf4p/+6S5GxwbYsnEFw47LcOijjabWjYlMSidNGSoXGSoEFFyH7YdmSKOYPIsZHB+hUi6SRgnSCJI0x7Ftup2UyX17STsthlau+8zPnRKJuylCyqMxVVrMt1OS3FAsFiiVQiz Line truncated
+21
View File
@@ -846,5 +846,26 @@
};
ns.GameText = GameText;
function GameIcons(data) {
this.data = data || { icons: { item: {}, tech: {} } };
}
GameIcons.fromGenerated = function () {
var data = (typeof globalThis !== "undefined" && globalThis.LiveStreamAssistIconData) ||
(typeof window !== "undefined" && window.LiveStreamAssistIconData) ||
null;
if (!data) throw new Error("LiveStreamAssistIconData is not loaded. Include generated/dsp-icons.js first.");
return new GameIcons(data);
};
GameIcons.prototype.icon = function (kind, id) {
var table = this.data.icons && this.data.icons[kind];
return table ? table[String(id)] || null : null;
};
GameIcons.prototype.itemIcon = function (id) { return this.icon("item", id); };
GameIcons.prototype.techIcon = function (id) { return this.icon("tech", id); };
ns.GameIcons = GameIcons;
return ns;
});
@@ -0,0 +1,133 @@
#!/usr/bin/env python3
"""Extract DSP item and tech icons into LiveStreamAssist JS icon data."""
from __future__ import annotations
import argparse
import base64
import io
import json
import sys
from pathlib import Path
from generate_text import DEFAULT_UNITY_VERSION, extract_proto_map, find_game_root
ICON_CLASSES = ("ItemProtoSet", "TechProtoSet")
ICON_SIZE = 80
TEXTURE_FILES = ("resources.assets", "sharedassets0.assets")
def collect_icon_names(game_root: Path, unity_version: str) -> dict[str, dict[int, str]]:
"""Map item and tech IDs to the texture name from their IconPath field."""
names: dict[str, dict[int, str]] = {}
for kind, protos in extract_proto_map(game_root, unity_version, ICON_CLASSES).items():
mapping: dict[int, str] = {}
for proto_id, proto in protos.items():
icon_path = proto.get("IconPath")
if not icon_path:
continue
mapping[proto_id] = icon_path.split("/")[-1]
names[kind] = mapping
return {kind: mapping for kind, mapping in names.items() if mapping}
def load_icon_textures(data_dir: Path, names: set[str]) -> dict[str, object]:
"""Load the named textures, preferring the standard square icon size."""
import UnityPy
textures: dict[str, tuple[object, bool]] = {}
for filename in TEXTURE_FILES:
path = data_dir / filename
if not path.is_file():
continue
env = UnityPy.load(str(path))
for obj in env.objects:
if getattr(obj.type, "name", str(obj.type)) != "Texture2D":
continue
try:
data = obj.read()
except Exception:
continue
if data.m_Name not in names:
continue
square = data.m_Width == ICON_SIZE and data.m_Height == ICON_SIZE
existing = textures.get(data.m_Name)
if existing is None or (square and not existing[1]):
textures[data.m_Name] = (data, square)
return {name: value[0] for name, value in textures.items()}
def encode_icon(texture: object) -> str:
try:
image = texture.image
except ImportError as exc:
raise SystemExit(
"Pillow is required to encode icons. Install LiveStreamAssist/js/scripts/requirements.txt."
) from exc
if image.mode != "RGBA":
image = image.convert("RGBA")
buffer = io.BytesIO()
image.save(buffer, "PNG", optimize=True)
return "data:image/png;base64," + base64.b64encode(buffer.getvalue()).decode("ascii")
def build_payload(game_root: Path, unity_version: str) -> tuple[dict, list[str]]:
names = collect_icon_names(game_root, unity_version)
if not names.get("item") or not names.get("tech"):
raise SystemExit("Prototype extraction did not produce item and tech icons; generated data was not written.")
textures = load_icon_textures(game_root / "DSPGAME_Data", {name for mapping in names.values() for name in mapping.values()})
icons: dict[str, dict[str, str]] = {}
missing: list[str] = []
for kind, mapping in names.items():
icons[kind] = {}
for proto_id, texture_name in sorted(mapping.items()):
texture = textures.get(texture_name)
if texture is None:
missing.append(f"{kind} {proto_id} ({texture_name})")
continue
icons[kind][str(proto_id)] = encode_icon(texture)
return {"version": "1.0.0", "icons": icons}, missing
def emit_js(payload: dict) -> str:
body = json.dumps(payload, ensure_ascii=False, separators=(",", ":"))
return (
"/* Generated from a local Dyson Sphere Program install by generate_icons.py. Do not edit. */\n"
"globalThis.LiveStreamAssistIconData = "
+ body
+ ";\n"
)
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--game-root", help="DSP install directory containing DSPGAME_Data")
parser.add_argument("--unity-version", default=DEFAULT_UNITY_VERSION)
parser.add_argument(
"--out",
default=str(Path(__file__).resolve().parents[1] / "generated" / "dsp-icons.js"),
help="Output JS path",
)
parser.add_argument("--json-out", help="Optional JSON output path")
args = parser.parse_args(argv)
game_root = find_game_root(args.game_root)
if game_root is None:
raise SystemExit("Dyson Sphere Program install not found. Pass --game-root.")
payload, missing = build_payload(game_root, args.unity_version)
for entry in missing:
print(f"Warning: icon texture not found for {entry}", file=sys.stderr)
out_path = Path(args.out)
out_path.parent.mkdir(parents=True, exist_ok=True)
out_path.write_text(emit_js(payload), encoding="utf-8", newline="\n")
if args.json_out:
json_path = Path(args.json_out)
json_path.parent.mkdir(parents=True, exist_ok=True)
json_path.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8", newline="\n")
item_count = len(payload["icons"].get("item", {}))
tech_count = len(payload["icons"].get("tech", {}))
print(f"Wrote {out_path} (items={item_count}, techs={tech_count}, bytes={out_path.stat().st_size})")
return 0
if __name__ == "__main__":
sys.exit(main())
+23 -7
View File
@@ -249,7 +249,10 @@ def find_game_root(explicit: str | None) -> Path | None:
return None
def extract_proto_ids(game_root: Path, unity_version: str) -> dict[str, dict[str, str]]:
def extract_proto_map(
game_root: Path, unity_version: str, class_names: set[str] | None = None
) -> dict[str, dict[int, dict]]:
"""Extract prototype entries keyed by kind and ID, keeping the raw fields."""
try:
import UnityPy
from UnityPy.helpers.TypeTreeGenerator import TypeTreeGenerator
@@ -259,6 +262,7 @@ def extract_proto_ids(game_root: Path, unity_version: str) -> dict[str, dict[str
"Install LiveStreamAssist/js/scripts/requirements.txt."
) from exc
wanted = class_names or KIND_FROM_SET
data_dir = game_root / "DSPGAME_Data"
generator = TypeTreeGenerator(unity_version)
generator.load_local_game(str(game_root))
@@ -269,15 +273,15 @@ def extract_proto_ids(game_root: Path, unity_version: str) -> dict[str, dict[str
continue
script = obj.read()
class_name = getattr(script, "m_ClassName", "")
if class_name in KIND_FROM_SET:
if class_name in wanted:
script_ids[obj.path_id] = class_name
resources = UnityPy.load(str(data_dir / "resources.assets"))
nodes = {
class_name: generator.get_nodes_up("Assembly-CSharp.dll", class_name)
for class_name in KIND_FROM_SET
for class_name in wanted
}
ids: dict[str, dict[str, str]] = {kind: {} for kind in KIND_FROM_SET.values()}
protos: dict[str, dict[int, dict]] = {KIND_FROM_SET[cn]: {} for cn in wanted}
for obj in resources.objects:
if getattr(obj.type, "name", str(obj.type)) != "MonoBehaviour":
continue
@@ -293,10 +297,22 @@ def extract_proto_ids(game_root: Path, unity_version: str) -> dict[str, dict[str
tree = obj.read_typetree(nodes[class_name], check_read=False)
for proto in tree.get("dataArray") or []:
proto_id = proto.get("ID")
name = proto.get("Name")
if not proto_id or not name:
if not proto_id:
continue
ids[kind][str(int(proto_id))] = name
protos[kind][int(proto_id)] = proto
return {kind: mapping for kind, mapping in protos.items() if mapping}
def extract_proto_ids(game_root: Path, unity_version: str) -> dict[str, dict[str, str]]:
ids: dict[str, dict[str, str]] = {}
for kind, protos in extract_proto_map(game_root, unity_version).items():
mapping: dict[str, str] = {}
for proto_id, proto in protos.items():
name = proto.get("Name")
if not name:
continue
mapping[str(proto_id)] = name
ids[kind] = mapping
return {kind: mapping for kind, mapping in ids.items() if mapping}
+1
View File
@@ -10,6 +10,7 @@ parts = [
SRC / "client.js",
SRC / "query.js",
SRC / "text.js",
SRC / "icons.js",
SRC / "footer.js",
]
text = "".join(path.read_text(encoding="utf-8") for path in parts)
@@ -0,0 +1,226 @@
const assert = require("node:assert/strict");
const fs = require("node:fs");
const path = require("node:path");
const test = require("node:test");
const vm = require("node:vm");
const { ROOT, createHarness, flush } = require("./test_helpers");
const TEXT_DATA = {
languages: { "2052": { lcid: 2052, name: "简体中文", abbr: "zh-CN", abbr2: "zh" } },
ids: {
item: { 1101: "铁矿名", 1203: "电动机名" },
tech: { 1001: "电磁学名", 1002: "高效学名" }
},
strings: {
铁矿名: { "2052": "铁矿石" },
电动机名: { "2052": "电动机" },
电磁学名: { "2052": "电磁学" },
高效学名: { "2052": "高效采集" }
}
};
function createDocument() {
const byId = new Map();
const created = [];
function makeElement(tag) {
const element = {
tagName: String(tag).toUpperCase(), children: [], parentNode: null,
textContent: "", className: "", src: "", alt: "", hidden: false,
rowSpan: 0, style: {},
classList: {
set: new Set(),
add(token) { this.set.add(token); },
remove(token) { this.set.delete(token); },
toggle(token, force) {
const next = force == null ? !this.set.has(token) : !!force;
if (next) this.set.add(token); else this.set.delete(token);
return next;
},
contains(token) { return this.set.has(token); }
},
appendChild(child) { child.parentNode = element; element.children.push(child); return child; },
removeAttribute() {},
setAttribute(name, value) { element[name] = value; }
};
Object.defineProperty(element, "id", {
get() { return element._id || ""; },
set(value) { element._id = value; if (value) byId.set(value, element); }
});
created.push(element);
return element;
}
const body = makeElement("body");
return { created, byId, document: { createElement: makeElement, getElementById: id => byId.get(id) || null, body } };
}
function openDashboard(options = {}) {
const { context, clock } = createHarness();
const { created, byId, document } = createDocument();
const calls = [];
const clients = [];
const events = new Map();
const base = context.LiveStreamAssist;
class FakeClient {
constructor(settings) { this.url = settings.url; this.connections = []; clients.push(this); }
connect(url) {
if (url != null) this.url = url;
this.connections.push(url);
if (options.failFirst && this.connections.length === 1) return Promise.reject({ kind: "CONNECT_FAILED" });
return Promise.resolve(this);
}
close() { this.infoSnapshot = null; }
systemInfo() { this.infoSnapshot = {}; return Promise.resolve(this.infoSnapshot); }
validate() { return Promise.resolve({}); }
}
class FakeQuery {
getItemRates(ids, opts) {
calls.push(["rates", ids.slice(), opts]);
if (options.pendingRates) return options.pendingRates;
return Promise.resolve(ids.map(id => ({
itemId: id, perMinute: true, production: 3, consumption: 1,
theoreticalProduction: 4, theoreticalConsumption: 2
})));
}
getTechState(id) {
calls.push(["tech", id]);
const custom = options.techStates && options.techStates[id];
return Promise.resolve(custom || { techId: id, unlocked: false, curLevel: 2, maxLevel: 10 });
}
getCurrentResearch() {
calls.push(["research"]);
return Promise.resolve(options.research || {
active: true, techId: 1001, curLevel: 0, progressPercent: 42.5,
hashUploaded: "12345", hashNeeded: "67890"
});
}
getDysonPower() {
calls.push(["dyson"]);
return Promise.resolve({ watts: "60900000" });
}
}
context.LiveStreamAssist = Object.assign({}, base, {
Client: FakeClient,
GameQuery: FakeQuery,
GameText: { fromGenerated(settings) { return new base.GameText(TEXT_DATA, settings); } },
GameIcons: {
fromGenerated() {
return { itemIcon: id => "icon-item-" + id, techIcon: id => "icon-tech-" + id };
}
}
});
for (const id of ["panel", "status"]) {
const element = document.createElement("div");
element.id = id;
document.body.appendChild(element);
}
Object.assign(context, {
location: { search: options.search || "" },
URLSearchParams,
document,
console,
addEventListener(name, callback) { events.set(name, callback); }
});
const html = fs.readFileSync(path.join(ROOT, "..", "examples", "live-dashboard.html"), "utf8");
const scripts = [...html.matchAll(/<script(?:[^>]*)>([\s\S]*?)<\/script>/g)];
vm.runInContext(scripts.map(match => match[1]).join("\n"), context, { filename: "live-dashboard.html" });
return { clock, calls, clients, events, byId, created };
}
test("live-dashboard renders the requested sections", async () => {
const dashboard = openDashboard({ search: "?items=1101,1203&techs=1001,1002&research=1&dyson=1&lang=zh-CN" });
await flush();
assert.equal(dashboard.byId.get("item-1101-prod").textContent, "3.00");
assert.equal(dashboard.byId.get("item-1101-prodRef").textContent, "4.00");
assert.equal(dashboard.byId.get("item-1101-cons").textContent, "1.00");
assert.equal(dashboard.byId.get("item-1101-consRef").textContent, "2.00");
assert.equal(dashboard.byId.get("item-1203-prod").textContent, "3.00");
assert.equal(dashboard.byId.get("tech-1001").textContent, "2/10");
assert.equal(dashboard.byId.get("tech-1002").textContent, "2/10");
assert.equal(dashboard.byId.get("researchName").textContent, "电磁学");
assert.equal(dashboard.byId.get("researchPct").textContent, "42.5%");
assert.equal(dashboard.byId.get("researchHash").textContent, "12.3k / 67.8k 哈希");
assert.equal(dashboard.byId.get("dysonWatts").textContent, "60.9MW");
assert.equal(dashboard.byId.get("status").textContent, "已连接");
assert.ok(dashboard.created.some(element => element.tagName === "IMG" && element.src === "icon-item-1101"));
assert.ok(dashboard.calls.some(([name, ids]) => name === "rates" && ids.join() === "1101,1203"));
});
test("live-dashboard defaults to research and Dyson sections", async () => {
const dashboard = openDashboard({});
await flush();
assert.equal(dashboard.byId.get("researchName").textContent, "电磁学");
assert.equal(dashboard.byId.get("dysonWatts").textContent, "60.9MW");
assert.ok(!dashboard.byId.has("item-1101-prod"));
assert.ok(!dashboard.byId.has("tech-1001"));
assert.ok(!dashboard.calls.some(([name]) => name === "rates" || name === "tech"));
});
test("live-dashboard shows a repeatable and a one-time tech level", async () => {
const dashboard = openDashboard({
search: "?techs=1001,1002",
techStates: {
1001: { techId: 1001, unlocked: false, curLevel: 5, maxLevel: 20 },
1002: { techId: 1002, unlocked: true, curLevel: 0, maxLevel: 0 }
}
});
await flush();
assert.equal(dashboard.byId.get("tech-1001").textContent, "5/20");
assert.equal(dashboard.byId.get("tech-1002").textContent, "已解锁");
});
test("live-dashboard resumes polling after the first connection fails", async () => {
const dashboard = openDashboard({ search: "?items=1101", failFirst: true });
await flush();
assert.equal(dashboard.calls.length, 0);
dashboard.clock.advance(2000);
await flush();
assert.equal(dashboard.byId.get("item-1101-prod").textContent, "3.00");
assert.equal(dashboard.byId.get("status").textContent, "已连接");
});
test("live-dashboard does not overlap slow polls", async () => {
let finish;
const pending = new Promise(resolve => { finish = resolve; });
const dashboard = openDashboard({ search: "?items=1101", pendingRates: pending });
await flush();
dashboard.clock.advance(10000);
await flush();
assert.equal(dashboard.calls.length, 1);
finish([{ itemId: 1101, perMinute: true, production: 6, consumption: 2, theoreticalProduction: 8, theoreticalConsumption: 4 }]);
await flush();
assert.equal(dashboard.byId.get("item-1101-prod").textContent, "6.00");
dashboard.clock.advance(2000);
await flush();
assert.equal(dashboard.calls.length, 2);
});
test("live-dashboard stops polling on pagehide", async () => {
const dashboard = openDashboard({ search: "?research=1" });
await flush();
assert.equal(typeof dashboard.events.get("pagehide"), "function");
dashboard.events.get("pagehide")();
dashboard.clock.advance(20000);
await flush();
assert.equal(dashboard.calls.length, 1);
assert.equal(dashboard.clock.size, 0);
});
test("live-dashboard reports initialization errors without polling", async () => {
for (const search of ["?window=5min&research=1", "?techs=abc", "?items=1101&techs=0"]) {
const dashboard = openDashboard({ search });
await flush();
assert.match(dashboard.byId.get("status").textContent, /初始化失败/);
assert.equal(dashboard.calls.length, 0);
dashboard.clock.advance(10000);
await flush();
assert.equal(dashboard.calls.length, 0);
}
});
test("live-dashboard can disable the default sections explicitly", async () => {
const dashboard = openDashboard({ search: "?research=0" });
await flush();
assert.ok(!dashboard.byId.has("researchName"));
assert.ok(!dashboard.byId.has("dysonWatts"));
assert.equal(dashboard.byId.get("status").textContent, "已连接");
});
+1 -1
View File
@@ -6,7 +6,7 @@ const vm = require("node:vm");
const { ROOT, createHarness } = require("./test_helpers");
test("the packed script matches its sources", () => {
const names = ["header", "format", "client", "query", "text", "footer"];
const names = ["header", "format", "client", "query", "text", "icons", "footer"];
const sources = names.map(name => fs.readFileSync(path.join(ROOT, "src", name + ".js"), "utf8").replace(/\r\n/g, "\n")).join("");
const packed = fs.readFileSync(path.join(ROOT, "livestream-assist.js"), "utf8").replace(/\r\n/g, "\n");
assert.ok(packed === sources, "The bundle is stale; run python LiveStreamAssist/js/scripts/pack_js.py.");
+21
View File
@@ -0,0 +1,21 @@
function GameIcons(data) {
this.data = data || { icons: { item: {}, tech: {} } };
}
GameIcons.fromGenerated = function () {
var data = (typeof globalThis !== "undefined" && globalThis.LiveStreamAssistIconData) ||
(typeof window !== "undefined" && window.LiveStreamAssistIconData) ||
null;
if (!data) throw new Error("LiveStreamAssistIconData is not loaded. Include generated/dsp-icons.js first.");
return new GameIcons(data);
};
GameIcons.prototype.icon = function (kind, id) {
var table = this.data.icons && this.data.icons[kind];
return table ? table[String(id)] || null : null;
};
GameIcons.prototype.itemIcon = function (id) { return this.icon("item", id); };
GameIcons.prototype.techIcon = function (id) { return this.icon("tech", id); };
ns.GameIcons = GameIcons;