import assert from 'node:assert/strict'; import { readFile } from 'node:fs/promises'; import vm from 'node:vm'; // Exercise the shipped classic script through its public browser API. The // lightweight DOM keeps this test dependency-free while preserving dialog, // focus, event and timer behaviour that callers observe. const source = await readFile( new URL('../public/cloud/user-dialog.js', import.meta.url), 'utf8', ); class FakeEvent { constructor(type, fields = {}) { this.type = type; this.bubbles = fields.bubbles ?? false; this.cancelable = fields.cancelable ?? false; this.defaultPrevented = false; this.target = fields.target ?? null; this.currentTarget = null; Object.assign(this, fields); } preventDefault() { if (this.cancelable) this.defaultPrevented = true; } stopPropagation() { this.cancelBubble = true; } } class FakeNode { constructor(tag = 'div', documentRef = null) { this.tagName = String(tag).toUpperCase(); this.ownerDocument = documentRef; this.parentNode = null; this.children = []; this.listeners = new Map(); this.attributes = new Map(); this.dataset = {}; this.hidden = false; this.disabled = false; this.open = false; this.value = ''; this.returnValue = ''; this.type = ''; this.name = ''; this._text = ''; this._innerHTML = ''; this.innerHTMLWrites = []; this.focusCount = 0; this.style = { values: new Map(), setProperty: (name, value) => this.style.values.set(name, String(value)), removeProperty: name => this.style.values.delete(name), }; const classes = new Set(); this.classList = { add: (...names) => names.forEach(name => classes.add(name)), remove: (...names) => names.forEach(name => classes.delete(name)), contains: name => classes.has(name), toggle: (name, force) => { const next = force === undefined ? !classes.has(name) : Boolean(force); if (next) classes.add(name); else classes.delete(name); return next; }, }; } set id(value) { this.setAttribute('id', value); } get id() { return this.getAttribute('id') || ''; } set className(value) { this.setAttribute('class', value); for (const name of String(value).split(/\s+/).filter(Boolean)) this.classList.add(name); } get className() { return this.getAttribute('class') || ''; } set textContent(value) { this._text = String(value ?? ''); this.children.forEach(child => { child.parentNode = null; }); this.children = []; } get textContent() { return this._text + this.children.map(child => child.textContent).join(''); } set innerHTML(value) { const next = String(value ?? ''); this.innerHTMLWrites.push(next); this._innerHTML = next; this._text = ''; this.children.forEach(child => { child.parentNode = null; }); this.children = []; } get innerHTML() { return this._innerHTML; } get isConnected() { let current = this; while (current) { if (current === this.ownerDocument?.documentElement) return true; current = current.parentNode; } return false; } append(...children) { children.forEach(child => { if (child === null || child === undefined) return; const node = typeof child === 'object' ? child : this.ownerDocument.createTextNode(String(child)); node.parentNode = this; this.children.push(node); }); } appendChild(child) { this.append(child); return child; } replaceChildren(...children) { this._text = ''; this.children.forEach(child => { child.parentNode = null; }); this.children = []; this.append(...children); } remove() { if (!this.parentNode) return; this.parentNode.children = this.parentNode.children.filter(child => child !== this); this.parentNode = null; } contains(candidate) { if (candidate === this) return true; return this.children.some(child => child.contains?.(candidate)); } setAttribute(name, value) { this.attributes.set(String(name), String(value)); if (name === 'hidden') this.hidden = true; if (name === 'disabled') this.disabled = true; } getAttribute(name) { return this.attributes.get(String(name)) ?? null; } hasAttribute(name) { return this.attributes.has(String(name)); } removeAttribute(name) { this.attributes.delete(String(name)); if (name === 'hidden') this.hidden = false; if (name === 'disabled') this.disabled = false; } addEventListener(type, listener, options = {}) { const entries = this.listeners.get(type) || []; entries.push({ listener, once: options === true || options?.once === true }); this.listeners.set(type, entries); } removeEventListener(type, listener) { this.listeners.set(type, (this.listeners.get(type) || []).filter(entry => entry.listener !== listener)); } dispatchEvent(event) { if (!(event instanceof FakeEvent)) throw new TypeError('Expected FakeEvent.'); if (!event.target) event.target = this; let current = this; while (current) { event.currentTarget = current; const entries = [...(current.listeners.get(event.type) || [])]; for (const entry of entries) { entry.listener.call(current, event); if (entry.once) current.removeEventListener(event.type, entry.listener); } if (!event.bubbles || event.cancelBubble) break; current = current.parentNode; } return !event.defaultPrevented; } dispatch(type, fields = {}) { return this.dispatchEvent(new FakeEvent(type, { bubbles: fields.bubbles ?? true, cancelable: fields.cancelable ?? true, ...fields, })); } click() { if (this.disabled) return; const allowed = this.dispatch('click'); if (!allowed || this.tagName !== 'BUTTON' || this.type !== 'submit') return; const form = this.closest('form'); if (!form) return; const submitted = form.dispatch('submit', { target: form, submitter: this }); if (!submitted || form.getAttribute('method') !== 'dialog') return; form.closest('dialog')?.close(this.value); } closest(selector) { let current = this; while (current) { if (current.matches(selector)) return current; current = current.parentNode; } return null; } matches(selector) { if (selector.startsWith('#')) return this.id === selector.slice(1); if (selector.startsWith('.')) return this.classList.contains(selector.slice(1)); return this.tagName === String(selector).toUpperCase(); } querySelector(selector) { for (const child of this.children) { if (child.matches?.(selector)) return child; const nested = child.querySelector?.(selector); if (nested) return nested; } return null; } focus(options) { this.focusCount += 1; this.lastFocusOptions = options; if (this.ownerDocument) this.ownerDocument.activeElement = this; } showModal() { this.open = true; this.setAttribute('open', ''); } close(returnValue = '') { if (!this.open) return; this.returnValue = String(returnValue); this.open = false; this.removeAttribute('open'); const notify = () => this.dispatch('close', { bubbles: false, cancelable: false }); if (typeof this.ownerDocument?.queueTask === 'function') this.ownerDocument.queueTask(notify); else notify(); } reset() { const resetNode = node => { if (node.tagName === 'INPUT' || node.tagName === 'TEXTAREA') node.value = ''; node.children.forEach(resetNode); }; resetNode(this); } setCustomValidity(message) { this.validationMessage = String(message); } getBoundingClientRect() { return { left: 100, top: 100, right: 600, bottom: 500, width: 500, height: 400 }; } } class FakeDocument extends FakeNode { constructor() { super('#document'); this.ownerDocument = this; this.readyState = 'complete'; this.documentElement = new FakeNode('html', this); this.body = new FakeNode('body', this); this.documentElement.append(this.body); this.activeElement = this.body; } createElement(tag) { return new FakeNode(tag, this); } createTextNode(value) { const node = new FakeNode('#text', this); node._text = String(value); return node; } getElementById(id) { const visit = node => { if (node.id === id) return node; for (const child of node.children) { const match = visit(child); if (match) return match; } return null; }; return visit(this.documentElement); } querySelector(selector) { if (selector.startsWith('#')) return this.getElementById(selector.slice(1)); return null; } } const flush = async () => { for (let turn = 0; turn < 16; turn += 1) await Promise.resolve(); }; function appendDialogMarkup(document) { const element = (tag, id) => { const node = document.createElement(tag); node.id = id; return node; }; const dialog = element('dialog', 'panel-user-dialog'); const form = element('form', 'panel-user-dialog-form'); const title = element('h2', 'panel-user-dialog-title'); const message = element('p', 'panel-user-dialog-message'); const kicker = document.createElement('span'); kicker.className = 'panel-user-dialog-kicker'; const close = element('button', 'panel-user-dialog-close'); const cancel = element('button', 'panel-user-dialog-cancel'); const confirm = element('button', 'panel-user-dialog-confirm'); const verification = element('div', 'panel-user-dialog-verification'); const input = element('input', 'panel-user-dialog-verification-input'); const label = element('label', 'panel-user-dialog-verification-label'); const hint = element('p', 'panel-user-dialog-verification-hint'); form.setAttribute('method', 'dialog'); close.type = 'button'; cancel.type = 'button'; confirm.type = 'submit'; verification.hidden = true; verification.append(label, input, hint); form.append(close, kicker, title, message, verification, cancel, confirm); dialog.append(form); document.body.append(dialog); } function fixture() { const document = new FakeDocument(); appendDialogMarkup(document); let now = 0; let timerSequence = 0; const timers = new Map(); const setTimeout = (callback, delay = 0) => { const id = ++timerSequence; timers.set(id, { callback, due: now + Math.max(0, Number(delay) || 0) }); return id; }; const clearTimeout = id => timers.delete(id); document.queueTask = callback => setTimeout(callback, 0); const window = new FakeNode('#window', document); Object.assign(window, { window, self: window, document, Event: FakeEvent, CustomEvent: FakeEvent, Element: FakeNode, HTMLElement: FakeNode, HTMLDialogElement: FakeNode, setTimeout, clearTimeout, requestAnimationFrame: callback => setTimeout(callback, 16), cancelAnimationFrame: clearTimeout, console, }); vm.runInNewContext(source, window, { filename: 'user-dialog.js' }); document.dispatch('DOMContentLoaded', { bubbles: false, cancelable: false }); const byId = id => { const node = document.getElementById(id); assert.ok(node, `Missing dialog element #${id}.`); return node; }; return { window, document, byId, async advance(milliseconds) { const end = now + milliseconds; let turns = 0; while (true) { const next = [...timers.entries()] .filter(([, timer]) => timer.due <= end) .sort((left, right) => left[1].due - right[1].due)[0]; if (!next) break; assert.ok(turns++ < 1000, 'Dialog scheduled an unbounded timer loop.'); now = next[1].due; timers.delete(next[0]); next[1].callback(); await flush(); } now = end; await flush(); }, }; } function tracked(promise) { const outcome = { settled: false, rejected: false, value: undefined }; promise.then( value => { outcome.settled = true; outcome.value = value; }, error => { outcome.settled = true; outcome.rejected = true; outcome.value = error; }, ); return outcome; } async function expectResolution(test, promise, expected) { const outcome = tracked(promise); await test.advance(1000); assert.equal(outcome.settled, true, 'Dialog promise did not settle after a user decision.'); assert.equal(outcome.rejected, false, 'Dialog user decisions must not reject.'); assert.equal(outcome.value, expected); } // A normal confirmation remains pending until the user decides, starts on the // safe action, resolves true on confirmation, and restores its opener. { const test = fixture(); assert.equal(typeof test.window.VenixDialog?.confirm, 'function'); assert.equal(typeof test.window.VenixDialog?.alert, 'function'); const opener = test.document.createElement('button'); test.document.body.append(opener); opener.focus(); const promise = test.window.VenixDialog.confirm({ title: '强制断电', message: '此操作可能导致未保存的数据丢失。', confirmText: '继续操作', cancelText: '取消', }); const outcome = tracked(promise); await test.advance(600_000); assert.equal(outcome.settled, false, 'A confirmation must not auto-dismiss on a timer.'); assert.equal(test.byId('panel-user-dialog').open, true); assert.equal(test.document.activeElement, test.byId('panel-user-dialog-cancel')); test.byId('panel-user-dialog-confirm').click(); await expectResolution(test, promise, true); assert.equal(test.document.activeElement, opener, 'Closing must restore focus to the opener.'); } // Every non-confirming exit fails closed, including Cancel, the close button, // Escape, and an actual backdrop click. A click inside the panel is inert. for (const exit of ['cancel', 'close', 'escape', 'backdrop']) { const test = fixture(); const opener = test.document.createElement('button'); test.document.body.append(opener); opener.focus(); const promise = test.window.VenixDialog.confirm({ title: '删除快照', message: '删除后无法恢复。' }); await test.advance(0); const dialog = test.byId('panel-user-dialog'); if (exit === 'cancel') test.byId('panel-user-dialog-cancel').click(); if (exit === 'close') test.byId('panel-user-dialog-close').click(); if (exit === 'escape') dialog.dispatch('cancel', { bubbles: false, cancelable: true }); if (exit === 'backdrop') { dialog.dispatch('click', { target: test.byId('panel-user-dialog-form') }); await flush(); assert.equal(dialog.open, true, 'Clicks inside the dialog must not cancel it.'); dialog.dispatch('click', { target: dialog }); } await expectResolution(test, promise, false); assert.equal(test.document.activeElement, opener, `${exit} must restore focus to the opener.`); } // Typed destructive confirmation is exact and literal. User-controlled copy is // rendered as text, while the action stays unavailable until a strict match. { const test = fixture(); const unsafeTitle = ' 删除实例'; const unsafeMessage = ' 请输入完整实例名称。'; const expectedName = 'Prod-VM<&>01'; const promise = test.window.VenixDialog.confirm({ title: unsafeTitle, message: unsafeMessage, requiredText: expectedName, confirmText: '永久删除', }); await test.advance(0); const title = test.byId('panel-user-dialog-title'); const message = test.byId('panel-user-dialog-message'); const verification = test.byId('panel-user-dialog-verification'); const input = test.byId('panel-user-dialog-verification-input'); const confirm = test.byId('panel-user-dialog-confirm'); assert.equal(title.textContent, unsafeTitle); assert.equal(message.textContent, unsafeMessage); assert.equal(verification.hidden, false); assert.equal(input.getAttribute('aria-required'), 'true'); assert.equal(input.hasAttribute('required'), true); assert.equal(confirm.disabled, true); assert.ok(![...title.innerHTMLWrites, ...message.innerHTMLWrites] .some(value => value.includes(unsafeTitle) || value.includes(unsafeMessage)), 'Dynamic dialog copy must never be assigned through innerHTML.'); for (const mismatch of ['prod-vm<&>01', `${expectedName} `, ` ${expectedName}`]) { input.value = mismatch; input.dispatch('input'); assert.equal(confirm.disabled, true, `Non-exact value ${JSON.stringify(mismatch)} enabled deletion.`); assert.equal(input.getAttribute('aria-invalid'), 'true'); assert.match(test.byId('panel-user-dialog-verification-hint').textContent, /名称不匹配/); } input.value = expectedName; input.dispatch('input'); assert.equal(confirm.disabled, false); assert.equal(input.getAttribute('aria-invalid'), 'false'); assert.match(test.byId('panel-user-dialog-verification-hint').textContent, /名称已匹配/); confirm.click(); await expectResolution(test, promise, true); } // A second concurrent request must fail closed without replacing or resolving // the active confirmation. { const test = fixture(); const first = test.window.VenixDialog.confirm({ title: '第一项操作', message: '保持可见。' }); await test.advance(0); const firstOutcome = tracked(first); const second = test.window.VenixDialog.confirm({ title: '第二项操作', message: '不得覆盖第一项。' }); await expectResolution(test, second, false); assert.equal(firstOutcome.settled, false); assert.equal(test.byId('panel-user-dialog-title').textContent, '第一项操作'); assert.equal(test.byId('panel-user-dialog').open, true); test.byId('panel-user-dialog-cancel').click(); await expectResolution(test, first, false); } // Browsers queue the close event from dialog.close(). A stale close event from // the previous decision must not cancel a dialog opened immediately afterward. { const test = fixture(); const first = test.window.VenixDialog.confirm({ title: '第一项操作', message: '立即确认。' }); const firstOutcome = tracked(first); test.byId('panel-user-dialog-confirm').click(); await flush(); assert.equal(firstOutcome.settled, true); assert.equal(firstOutcome.value, true); const second = test.window.VenixDialog.confirm({ title: '第二项操作', message: '必须保持打开。' }); const secondOutcome = tracked(second); await test.advance(0); assert.equal(secondOutcome.settled, false, 'A stale close event cancelled the next dialog.'); assert.equal(test.byId('panel-user-dialog').open, true); assert.equal(test.byId('panel-user-dialog-title').textContent, '第二项操作'); test.byId('panel-user-dialog-cancel').click(); await expectResolution(test, second, false); } // Alerts share the in-product surface, resolve with no value, and never invoke // a browser-native acknowledgement dialog. { const test = fixture(); const promise = test.window.VenixDialog.alert({ title: '操作完成', message: '任务已提交。' }); await test.advance(0); assert.equal(test.byId('panel-user-dialog-title').textContent, '操作完成'); assert.equal(test.byId('panel-user-dialog-message').textContent, '任务已提交。'); test.byId('panel-user-dialog-confirm').click(); await expectResolution(test, promise, undefined); } console.log('User dialog behavior checks passed.');