import assert from 'node:assert/strict'; import { readFile } from 'node:fs/promises'; import vm from 'node:vm'; import { renderAccountingFreshness } from '../public/cloud/traffic-accounting.js'; const moduleSource = await readFile( new URL('../public/cloud/traffic.js', import.meta.url), 'utf8', ); const source = `const state = ${moduleSource.split('const state = ')[1]}` .replace('export async function initialize()', 'async function initialize()'); class Node { constructor(tag) { Object.assign(this, { tagName: tag.toUpperCase(), children: [], attributes: new Map(), className: '', text: '', hidden: false, disabled: false, open: false, }); } set textContent(value) { this.text = String(value); this.replaceChildren(); } get textContent() { return this.text + this.children.map(child => child.textContent).join(''); } append(...children) { for (const child of children) { child.parent = this; this.children.push(child); } } replaceChildren(...children) { this.children = []; this.append(...children); } setAttribute(name, value) { this.attributes.set(name, String(value)); } getAttribute(name) { return this.attributes.get(name) ?? null; } querySelectorAll(selector) { const matches = node => selector === 'details.cloud-traffic-line[data-line-key]' && node.tagName === 'DETAILS' && node.className.split(/\s+/).includes('cloud-traffic-line') && node.attributes.has('data-line-key'); return this.children.flatMap(child => [ ...(matches(child) ? [child] : []), ...child.querySelectorAll(selector), ]); } } const nodes = new Map([ ['cloud-traffic-list', new Node('div')], ['cloud-traffic-count', new Node('span')], ['cloud-traffic-refresh', new Node('button')], ]); const document = { createElement: tag => new Node(tag) }; const translate = (key, parameters = {}) => { if (key === 'traffic.count') return `${parameters.count} 个线路流量池`; if (key === 'traffic.coverage.label') return `覆盖:${parameters.regions}`; if (key === 'traffic.coverage.regions') return `${parameters.count} 个地区`; if (key === 'traffic.coverage.instances') return `${parameters.count} 台实例`; if (key === 'traffic.instances.count') return `${parameters.count} 台`; if (key.endsWith('_at')) return `sample ${parameters.sample_time}`; return key; }; const i18n = { text: translate, date: value => `date-${value}`, bind() {}, }; const context = vm.createContext({ document, window: { addEventListener() {} }, URL, AbortController, console, byId: id => nodes.get(id), api: async () => { throw new Error('Unexpected request'); }, initializeSession: async () => true, readBootstrap: () => ({}), showError() {}, i18n, renderAccountingFreshness: pool => renderAccountingFreshness(pool, document, i18n), t: translate, }); vm.runInContext(`${source}\nglobalThis.traffic = { applyPayload };`, context, { filename: 'traffic.js', }); const pool = (id, name = `线路 ${id}`) => ({ group_id: id, name, projection_ready: true, state: 'available', network_restriction_state: 'clear', active_entitlement_bytes: 1024, active_consumed_bytes: 0, available_bytes: 1024, overage_bytes: 0, next_expiry_at: null, next_expiry_bytes: 0, last_observed_at: null, accounting_freshness: { status: 'current', last_sample_at: 100 }, instances: [], key: `line-group:${id}`, coverage_regions: [{ code: 'hkg', name: '香港' }], coverage_region_count: 1, instance_count: 0, summary_state: 'available', requires_attention: false, default_open: false, }); const linePool = (id, overrides = {}) => ({ ...pool(id), ...overrides, }); const payload = linePools => ({ line_pools: linePools, line_pool_count: linePools.length, }); const details = () => nodes.get('cloud-traffic-list') .querySelectorAll('details.cloud-traffic-line[data-line-key]'); context.traffic.applyPayload(payload([ linePool(1, { default_open: true }), linePool(2), ])); assert.deepEqual(details().map(item => item.open), [true, false], 'Server default-open projection was not applied.'); assert.equal(nodes.get('cloud-traffic-count').textContent, '2 个线路流量池'); details()[0].open = false; details()[1].open = true; context.traffic.applyPayload(payload([ linePool(1, { default_open: true }), linePool(2), ])); assert.deepEqual(details().map(item => item.open), [false, true], 'Refresh did not retain both expanded and collapsed user choices.'); context.traffic.applyPayload(payload([ linePool(1, { summary_state: 'attention', requires_attention: true, default_open: true, }), linePool(2), ])); assert.deepEqual(details().map(item => item.open), [true, true], 'A line pool that changed from healthy to attention remained hidden.'); details()[0].open = false; context.traffic.applyPayload(payload([ linePool(1, { summary_state: 'attention', requires_attention: true, default_open: true, }), linePool(2), ])); assert.deepEqual(details().map(item => item.open), [false, true], 'A user-collapsed attention line pool reopened on every refresh.'); context.traffic.applyPayload(payload([ linePool(1, { summary_state: 'attention', requires_attention: true, default_open: true, }), linePool(2), linePool(3, { coverage_regions: [], coverage_region_count: 0, summary_state: 'attention', requires_attention: true, default_open: true, }), ])); assert.deepEqual(details().map(item => item.open), [false, true, true], 'A newly appearing attention line pool did not use its server default.'); context.traffic.applyPayload(payload([ linePool(4, { accounting_freshness: { status: 'delayed', last_sample_at: 80 }, summary_state: 'delayed', requires_attention: true, default_open: true, instance_count: 1, instances: [{ id: 40, name: 'vm-40', region: { name: '香港' }, service_expires_at: 200, network_status: 'active', period_traffic_quota_bytes: 2048, traffic_used_bytes: 512, traffic_download_bytes: 384, traffic_upload_bytes: 128, }], }), ])); const delayedContent = details()[0].textContent; assert.match(delayedContent, /traffic\.freshness\.delayed/, 'A delayed accounting projection was not made visible.'); assert.match(delayedContent, /sample date-80/, 'The delayed projection hid its last confirmed timestamp.'); assert.match(delayedContent, /traffic\.instance\.period_quota/, 'Freshness messaging replaced the per-instance raw sample list.'); console.log('Cloud traffic-pool line behavior checks passed.');