import assert from 'node:assert/strict'; import { readFile } from 'node:fs/promises'; import vm from 'node:vm'; const source = await readFile(new URL('../public/cloud/invoices.js', import.meta.url), 'utf8'); const template = await readFile( new URL('../resources/views/venix/cloud/pages/invoices.tpl', import.meta.url), 'utf8', ); const tick = () => new Promise(resolve => setImmediate(resolve)); class Node { constructor(tag) { Object.assign(this, { tagName: tag.toUpperCase(), children: [], listeners: new Map(), attributes: new Map(), className: '', value: '', hidden: false, disabled: false, text: '', href: '', }); } set textContent(value) { this.text = String(value); this.replaceChildren(); } get textContent() { return this.text + this.children.map(child => child.textContent).join(''); } append(...children) { this.children.push(...children); } replaceChildren(...children) { this.children = [...children]; } setAttribute(name, value) { this.attributes.set(name, String(value)); } addEventListener(name, handler) { if (!this.listeners.has(name)) this.listeners.set(name, []); this.listeners.get(name).push(handler); } async fire(name) { const event = { target: this, currentTarget: this, defaultPrevented: false, preventDefault() { this.defaultPrevented = true; }, }; for (const handler of this.listeners.get(name) || []) await handler(event); await tick(); return event; } } const invoice = id => ({ id: String(id), purpose: 'renewal', title: '实例续费', amount: '10.00', status: 'paid', created_at: 2_000_000_000 + Number(id), renews_expires_at: 2_000_100_000, }); const payload = (id, overrides = {}) => ({ invoices: [invoice(id)], purpose: 'all', filters: { purpose: 'all', status: 'all', keyword: '', date_from: '', date_to: '' }, pagination: { page: 1, per_page: 25, total: 1, total_pages: 1, has_previous: false, has_next: false, from: 1, to: 1 }, balance: '20.00', ...overrides, }); const deferred = () => { let resolve; let reject; const promise = new Promise((yes, no) => { resolve = yes; reject = no; }); return { promise, resolve, reject }; }; async function setup() { const nodes = new Map(); for (const match of template.matchAll(/<([a-z][a-z0-9]*)\b[^>]*\bid="([^"]+)"[^>]*>/g)) { nodes.set(match[2], new Node(match[1])); } nodes.set('cloud-page-error', new Node('p')); nodes.get('invoices-bootstrap').textContent = JSON.stringify(payload(1)); const documentEvents = new Map(); const windowEvents = new Map(); const document = { hidden: false, getElementById: id => nodes.get(id) || null, createElement: tag => new Node(tag), addEventListener: (name, handler) => documentEvents.set(name, handler), }; const location = new URL('https://panel.example.test/user/cloud/invoices'); location.assign = value => { location.href = new URL(value, location.href).href; }; const calls = []; let responder = () => Promise.reject(new Error('Unexpected invoice request')); const fetch = (url, options = {}) => { calls.push({ url, options }); return responder(url, options); }; const window = { setTimeout: () => 1, clearTimeout() {}, addEventListener: (name, handler) => windowEvents.set(name, handler), }; const history = { state: null, replaceState(_state, _title, next) { location.href = new URL(next, location.href).href; }, }; const context = vm.createContext({ AbortController, URL, URLSearchParams, console, document, fetch, history, location, window, Date, Error, }); vm.runInContext( source.replace('export async function initialize()', 'async function initialize()') + '\nglobalThis.page = { initialize, state };', context, { filename: 'invoices.js' }, ); await context.page.initialize(); return { nodes, calls, location, state: context.page.state, respondWith(fn) { responder = fn; }, event(name, event = {}) { return windowEvents.get(name)?.(event); }, documentEvent(name) { return documentEvents.get(name)?.(); }, setHidden(value) { document.hidden = value === true; }, }; } const response = value => ({ ok: true, status: 200, json: async () => structuredClone(value) }); { const page = await setup(); assert.equal(page.calls.length, 0, 'SSR hydration repeated the initial invoice GET.'); const first = deferred(); const second = deferred(); page.respondWith((_url, options) => page.calls.length === 1 ? first.promise : second.promise); page.nodes.get('invoices-keyword-filter').value = 'first-vm'; await page.nodes.get('invoices-filter-form').fire('submit'); page.nodes.get('invoices-keyword-filter').value = 'second-vm'; await page.nodes.get('invoices-filter-form').fire('submit'); assert.equal(page.calls.length, 2, 'A newer filter was discarded while the first read was pending.'); assert.equal(page.calls[0].options.signal.aborted, true, 'A superseded invoice read was not aborted.'); second.resolve(response(payload(2, { filters: { purpose: 'all', status: 'all', keyword: 'second-vm', date_from: '', date_to: '' }, pagination: { page: 1, per_page: 25, total: 30, total_pages: 2, has_previous: false, has_next: true, from: 1, to: 25 }, }))); await tick(); await tick(); assert.equal(page.state.invoices[0].id, '2'); assert.match(page.location.search, /keyword=second-vm/); first.resolve(response(payload(1, { filters: { purpose: 'all', status: 'all', keyword: 'first-vm', date_from: '', date_to: '' }, }))); await tick(); await tick(); assert.equal(page.state.invoices[0].id, '2', 'A stale invoice response overwrote the newest filter result.'); const next = deferred(); page.respondWith(() => next.promise); await page.nodes.get('invoices-next').fire('click'); assert.match(page.calls.at(-1).url, /page=2/); assert.match(page.calls.at(-1).url, /keyword=second-vm/); next.resolve(response(payload(3, { filters: { purpose: 'all', status: 'all', keyword: 'second-vm', date_from: '', date_to: '' }, pagination: { page: 2, per_page: 25, total: 30, total_pages: 2, has_previous: true, has_next: false, from: 26, to: 30 }, }))); await tick(); await tick(); assert.match(page.location.search, /page=2/); const backgroundRead = deferred(); page.respondWith(() => backgroundRead.promise); page.nodes.get('invoices-keyword-filter').value = 'background-safe'; await page.nodes.get('invoices-filter-form').fire('submit'); const backgroundCall = page.calls.at(-1); page.setHidden(true); page.documentEvent('visibilitychange'); assert.equal(backgroundCall.options.signal.aborted, false, 'Changing tab visibility cancelled a user-requested invoice filter.'); backgroundRead.resolve(response(payload(4, { filters: { purpose: 'all', status: 'all', keyword: 'background-safe', date_from: '', date_to: '' }, }))); await tick(); await tick(); assert.equal(page.state.invoices[0].id, '4', 'A valid filtered response was discarded only because the tab was hidden.'); page.setHidden(false); page.documentEvent('visibilitychange'); const failed = deferred(); page.respondWith(() => failed.promise); await page.nodes.get('invoices-refresh').fire('click'); failed.reject(new Error('temporary failure')); await tick(); await tick(); assert.equal(page.state.invoices[0].id, '4', 'A failed refresh erased the last confirmed invoice list.'); } console.log('Cloud invoice list hydration, filters and read-race checks passed.');