import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import vm from 'node:vm';
// Exercise the shipped module through DOM events, without a browser dependency.
// Fetches deliberately remain resolvable after abort to check stale-response guards.
const source = await readFile(new URL('../public/cloud/announcements.js', import.meta.url), 'utf8');
class Node {
constructor(tag = 'div') {
this.tagName = tag.toUpperCase(); this.children = []; this.dataset = {};
this.attributes = new Map(); this.listeners = new Map(); this.styles = new Map();
this.style = { setProperty: (key, value) => this.styles.set(key, value), removeProperty: key => this.styles.delete(key) };
const classes = new Set();
this.classList = { add: value => classes.add(value), remove: value => classes.delete(value), contains: value => classes.has(value) };
this.hidden = false; this.disabled = false; this.isConnected = true;
this.open = false; this.replacements = 0; this.scrollWrites = 0; this._scrollTop = 0; this._text = '';
}
set textContent(value) { this._text = String(value); this.children = []; }
get textContent() { return this._text + this.children.map(child => child.textContent).join(''); }
set innerHTML(_) { throw new Error('Announcement HTML must never be interpreted.'); }
set scrollTop(value) { this._scrollTop = value; this.scrollWrites += 1; }
get scrollTop() { return this._scrollTop; }
append(...children) { this.children.push(...children); }
replaceChildren(...children) { this.replacements += 1; this._text = ''; this.children = children; }
setAttribute(key, value) { this.attributes.set(key, String(value)); }
getAttribute(key) { return this.attributes.get(key) ?? null; }
addEventListener(name, handler) {
if (!this.listeners.has(name)) this.listeners.set(name, []);
this.listeners.get(name).push(handler);
}
dispatch(name, fields = {}) {
const event = { target: this, button: 0, defaultPrevented: false, preventDefault() { this.defaultPrevented = true; }, ...fields };
for (const handler of this.listeners.get(name) ?? []) handler(event);
}
closest(selector) { return selector === '[data-announcements-open]' && this.isTrigger ? this : null; }
focus() {}
showModal() { this.open = true; }
close() { this.open = false; }
getBoundingClientRect() { return { left: 0, top: 0, right: 540, bottom: 800 }; }
}
const flush = async () => { for (let turn = 0; turn < 16; turn += 1) await Promise.resolve(); };
function fixture() {
const names = ['drawer', 'state', 'read-time', 'refresh', 'more', 'count', 'list', 'scroll', 'close'];
const nodes = Object.fromEntries(names.map(name => [name, new Node(name === 'drawer' ? 'dialog' : 'div')]));
nodes['read-time'].hidden = true;
const document = new Node(); document.visibilityState = 'visible'; document.hidden = false;
document.documentElement = new Node(); document.body = new Node();
const trigger = new Node('button'); trigger.isTrigger = true;
document.getElementById = id => nodes[id.replace('panel-announcements-', '')] ?? null;
document.createElement = tag => new Node(tag);
document.querySelectorAll = selector => selector === '[data-announcements-open]' ? [trigger] : [];
document.querySelector = selector => document.querySelectorAll(selector)[0] ?? null;
const window = new Node(); window.scrollX = 0; window.scrollY = 125; window.scrollTo = () => {};
window.VenixDrawerMotion = {
openDrawerWithMotion(dialog) { dialog.showModal(); dialog.classList.add('is-drawer-visible'); return true; },
closeDrawerWithMotion(dialog) { dialog.classList.remove('is-drawer-visible'); dialog.close(); return Promise.resolve(true); },
};
const history = { state: null, replaceState(value) { this.state = value; } };
let now = 0; let timerId = 0;
const epoch = Date.UTC(2026, 8, 30, 6, 27, 20);
class FakeDate extends Date {
constructor(...values) { super(...(values.length ? values : [epoch + now])); }
static now() { return epoch + now; }
toLocaleTimeString(locale, options) {
assert.equal(locale, 'zh-CN'); assert.equal(options.hour12, false);
return this.toISOString().slice(11, 19);
}
}
const timers = new Map(); const requests = [];
const setTimeout = (callback, delay = 0) => {
const id = ++timerId; timers.set(id, { callback, due: now + delay }); return id;
};
const fetch = (url, options) => new Promise((resolve, reject) => {
requests.push({ url, options, resolve, reject, settled: false });
});
vm.runInNewContext(source, {
document, window, history, location: { href: 'https://example.test/user/cloud' },
URL, Date: FakeDate, AbortController, fetch, setTimeout, clearTimeout: id => timers.delete(id),
requestAnimationFrame: callback => setTimeout(callback, 0), console,
}, { filename: 'announcements.js' });
return {
nodes, document, window, requests,
async advance(milliseconds) {
const end = now + milliseconds;
while (true) {
const next = [...timers.entries()].filter(([, timer]) => timer.due <= end).sort((a, b) => a[1].due - b[1].due)[0];
if (!next) break;
now = next[1].due; timers.delete(next[0]); next[1].callback(); await flush();
}
now = end; await flush();
},
async click(name) {
if (name === 'open') document.dispatch('click', { target: trigger });
else if (!nodes[name].disabled) nodes[name].dispatch('click');
await flush();
},
async respond(payload, status = 200, request = requests.find(item => !item.settled)) {
assert.ok(request, 'A response requires an outstanding request.');
request.settled = true;
request.resolve({ status, ok: status >= 200 && status < 300, json: async () => payload });
await flush();
},
async visibility(value) {
document.visibilityState = value; document.hidden = value === 'hidden';
document.dispatch('visibilitychange'); await flush();
},
async lifecycle(name, fields) { window.dispatch(name, fields); await flush(); },
};
}
function announcement(id, changes = {}) {
return {
id: String(id), title: `公告 ${id}`, type: 'notice', type_label: '通知', body: `正文 ${id}`,
status: 'published', published_at: '2026-09-30 12:00:00', updated_at: '2026-09-30 12:00:00', ...changes,
};
}
function page(items, number = 1, total = items.length) {
return { items, pagination: { page: number, per_page: 10, total, total_pages: Math.max(1, Math.ceil(total / 10)) }, generated_at: 1 };
}
function articles(test) { return test.nodes.list.children.filter(node => node.tagName === 'ARTICLE'); }
function assertQuiet(test) {
assert.equal(test.nodes.state.textContent, '', 'Normal loading and refresh must not display a status message.');
assert.doesNotMatch(test.nodes.count.textContent, /旧内容|读取于|正在|成功/);
}
// Initial lazy read, inert closed state, unchanged polling, and literal text.
{
const test = fixture();
await test.advance(90000); assert.equal(test.requests.length, 0, 'Closed drawers do not prefetch or poll.');
await test.click('open'); assert.equal(test.requests.length, 1); assertQuiet(test);
const unsafe = announcement(1, { title: '
', body: '\n第二行' });
await test.respond(page([unsafe]));
assert.equal(articles(test).length, 1); assert.match(test.nodes.list.textContent, /