import assert from 'node:assert/strict'; import test from 'node:test'; import fs from 'node:fs/promises'; import { runInNewContext } from 'node:vm'; import { parse } from '@babel/parser'; import React from 'react'; import { renderToStaticMarkup } from 'react-dom/server'; import * as Ant from 'antd'; import { transformWithEsbuild } from 'vite'; import i18next from 'i18next'; import * as pagination from '../../src/components/ui/pagination.js'; await i18next.init({ lng: 'zh', initImmediate: false, resources: { zh: { translation: { '共 {{total}} 条': '共 {{total}} 条' } } }, }); const walk = (node, visit) => { if (!node || typeof node !== 'object') return; if (node.type) visit(node); for (const [key, val] of Object.entries(node)) if (!['loc', 'start', 'end'].includes(key)) { if (Array.isArray(val)) val.forEach((n) => walk(n, visit)); else if (val && typeof val === 'object') walk(val, visit); } }; async function callback(file, name, rootName) { const source = await fs.readFile(file, 'utf8'); const ast = parse(source, { sourceType: 'module', plugins: ['jsx'] }); let root = ast; if (rootName) walk(ast, (n) => { if (n.type === 'FunctionDeclaration' && n.id?.name === rootName) root = n; }); let found; walk(root, (n) => { if (!found && n.type === 'VariableDeclarator' && n.id.name === name) found = n.init?.callee?.name === 'useCallback' ? n.init.arguments[0] : n.init; }); assert.ok(found, `${file}: ${name} exists`); return { source: source.slice(found.start, found.end), root, text: source }; } const sentinel = { id: 42, name: 'pagination-fixture' }; async function exercise( { file, fn, root, args = [], expectedPath, expectedSize = 50, expectedPage = 3, pageKey = 'p', values = {}, }, failure = false, ) { const { source, root: ast } = await callback(file, fn, root); const states = {}, calls = [], errors = []; const context = { URLSearchParams, Date, Promise, console: { error() {} }, page: 3, pageSize: 50, orgId: 77, pageSizeRef: { current: 50 }, requestSeq: { current: 0 }, seqRef: { current: 0 }, orgRef: { current: 77 }, fetchSeqRef: { current: 0 }, searchKeyword: 'pagination-fixture', appliedKeyword: 'pagination-fixture', appliedOrderId: 42, appliedUserId: 7, statusFilter: '', paymentMethodFilter: '', dateRange: [], appliedMinMoney: undefined, appliedMaxMoney: undefined, levelFilter: '', salesRepFilter: '', alertFilter: '', userIdFilter: '', sortBy: '', sortOrder: '', endDateRange: [], quickFilter: '', planTypes: [], tiers: [], statuses: [], sources: [], getOrgHeaders: (id) => ({ 'X-Org-Id': String(id) }), t: (key) => key, showError: (e) => errors.push(e), getFormValues: () => ({ username: '', token_name: '', model_name: '', start_timestamp: '2026-11-02 00:00:00', end_timestamp: '2026-11-07 23:44:54', channel: '', group: '', user_id: '', logType: 0, channel_id: '', mj_id: '', }), isAdminUser: true, listRequestIdRef: { current: 0 }, logsRequestIdRef: { current: 0 }, appliedExportParamsRef: { current: {} }, ...values, API: { get: async (url, options = {}) => { calls.push({ url, options }); if (failure) throw new Error('simulated pagination failure'); return { data: { success: true, data: { items: [sentinel], list: [sentinel], total: 156, page: expectedPage, page_size: expectedSize, requests: { items: [sentinel], total: 156 }, audits: { items: [sentinel], total: 156 }, }, }, }; }, }, }; walk(ast, (n) => { if (n.type === 'Identifier' && /^set[A-Z]/.test(n.name)) context[n.name] ||= (val) => { states[n.name] = typeof val === 'function' ? val(states[n.name]) : val; }; }); const run = runInNewContext(`(${source})`, context); await run(...args); assert.ok(calls.length > 0, 'Uses the existing API wrapper'); const request = calls.find((c) => c.url.startsWith(expectedPath)); assert.ok(request, `${expectedPath} requested`); const u = new URL(request.url, 'http://localhost'); const params = { ...Object.fromEntries(u.searchParams), ...request.options.params, }; assert.equal( Number(params.page_size), expectedSize, 'Selected page size reaches API', ); assert.equal( Number(params[pageKey]), expectedPage, 'Requested page reaches API without changing indexing', ); if (failure) { if ('setLoading' in states) assert.equal(states.setLoading, false, 'Failure releases loading'); assert.ok( errors.length > 0 || Boolean(states.setError), 'Failure is reported by a message or inline error', ); } else if ('setTotal' in states) assert.equal(states.setTotal, 156, 'Response total maps to pagination'); return { calls, states, errors }; } for (const cfg of [ { file: 'src/pages/AdminOrder/index.jsx', fn: 'fetchOrders', expectedPath: '/api/order/search', }, { file: 'src/pages/AdminInvoice/index.jsx', fn: 'fetchInvoices', expectedPath: '/api/invoice/list', }, { file: 'src/pages/UserCenter/Invoice.jsx', fn: 'fetchInvoices', expectedPath: '/api/user/invoice/self', values: { invoicesPage: 3, invoicesPageSize: 50 }, }, { file: 'src/hooks/redemptions/useRedemptionsData.jsx', fn: 'loadSearchResults', expectedPath: '/api/redemption/search', args: ['pagination-fixture', 3, 50], values: { setRedemptionFormat: () => {} }, }, { file: 'src/pages/AdminOrganizations/index.jsx', fn: 'fetchOrgs', expectedPath: '/api/admin/organizations', }, { file: 'src/pages/Subscription/index.jsx', fn: 'fetchList', expectedPath: '/api/user/membership/manage/subscriptions', pageKey: 'page', }, { file: 'src/hooks/org/useOrgMembers.js', fn: 'fetch', root: 'useOrgMembers', args: [3, 50], expectedPath: '/api/org/members', }, { file: 'src/hooks/org/useOrgData.js', fn: 'fetch', root: 'useOrgTokens', args: [3, 50], expectedPath: '/api/org/tokens', }, { file: 'src/hooks/org/useOrgData.js', fn: 'fetch', root: 'useOrgAuditLogs', args: [3, 50, ''], expectedPath: '/api/org/audit', values: { seqRef: { current: 0 }, orgRef: { current: 77 } }, }, { file: 'src/hooks/org/useOrgData.js', fn: 'fetch', root: 'useOrgPromptRecords', args: [3, 50, {}], expectedPath: '/api/org/prompt-archive/records', values: { seqRef: { current: 0 } }, }, { file: 'src/hooks/org/useOrgData.js', fn: 'fetch', root: 'useOrgMemberLogs', args: [3, 50, {}], expectedPath: '/api/org/logs', values: { buildOrgLogFilters: (x) => x }, }, { file: 'src/pages/Organization/OrgRecharge.jsx', fn: 'fetchHistory', args: [3], expectedPath: '/api/org/topup', values: { historyPageSize: 50, orgHeaders: { 'X-Org-Id': '77' } }, }, { file: 'src/pages/Organization/OrgDashboard.jsx', fn: 'fetchLogs', args: [3, {}, 50], expectedPath: '/api/org/logs', values: { member: { user_id: 9 }, appliedFilters: {} }, }, { file: 'src/pages/Organization/datasecurity/OrgDsChanges.jsx', fn: 'fetchChanges', args: [{ reqP: 3, auditP: 2, section: 'requests' }], expectedPath: '/api/org/data-security/changes', pageKey: 'page', values: { reqSizeRef: { current: 50 }, auditSizeRef: { current: 20 }, headers: {}, }, }, { file: 'src/pages/Organization/datasecurity/OrgDsChanges.jsx', fn: 'fetchChanges', args: [{ reqP: 1, auditP: 3, section: 'audits' }], expectedPath: '/api/org/data-security/changes', pageKey: 'page', values: { reqSizeRef: { current: 20 }, auditSizeRef: { current: 50 }, headers: {}, }, }, { file: 'src/pages/Setting/Payment/SettingsPaymentGatewayPayPal.jsx', fn: 'refreshFeePolicy', args: [3, true], expectedPath: '/api/option/paypal/fee-policy/audits', values: { isRoot: () => true, feeAuditSizeRef: { current: 50 } }, }, { file: 'src/pages/Setting/Payment/SettingsPaymentGatewayPayPal.jsx', fn: 'refreshOperations', args: [3], expectedPath: '/api/option/paypal/operations/preflight', values: { isRoot: () => true, operationsSizeRef: { current: 50 }, normalizePayPalOperations: (d) => d, }, }, { file: 'src/hooks/analytics/useRiskControlData.js', fn: 'fetchBanLogs', args: [{ page: 3, pageSize: 50 }], expectedPath: '/api/analytics/risk/ban-logs', pageKey: 'page', values: { banLogStatus: 0, banLogPage: 1, banLogPageSize: 20 }, }, ...[ ['loadAudits', 'audit', '/api/desensitize/config-audit'], ['loadHitLogs', 'hitLog', '/api/desensitize/logs'], ['loadChangeRequests', 'changeReq', '/api/desensitize/change-requests'], ].map(([fn, name, expectedPath]) => ({ file: 'src/components/settings/DataSecuritySetting.jsx', fn, args: [3], expectedPath, pageKey: 'page', values: { [`${name}PageSize`]: 50 }, })), { file: 'src/pages/Organization/datasecurity/OrgDsHitLogs.jsx', fn: 'fetchLogs', args: [3, false], expectedPath: '/api/org/data-security/logs', pageKey: 'page', values: { logsSeqRef: { current: 0 }, lastAttemptedPageRef: { current: 1 }, headers: {}, }, }, { file: 'src/hooks/usage-logs/useUsageLogsData.jsx', fn: 'loadLogs', args: [3, 50], expectedPath: '/api/log/', values: { setLogsFormat: () => {} }, }, { file: 'src/hooks/mj-logs/useMjLogsData.js', fn: 'loadLogs', args: [3, 50], expectedPath: '/api/mj/', values: { syncPageData: () => {} }, }, ]) { test(`${cfg.file}: selected page and size use existing request contract`, () => exercise(cfg)); test(`${cfg.file}: network failure exits loading and reports error`, () => exercise(cfg, true)); } test('Resizing emits one size callback and never a stale page request', () => { const calls = []; const events = pagination.centerPaginationEvents({ pageSize: 10, onPageSizeChange: (s) => calls.push(['size', s]), onPageChange: (p) => calls.push(['page', p]), onChange: (p, s) => calls.push(['change', p, s]), }); events.onChange(3, 50); assert.deepEqual(calls, [['size', 50]]); events.onChange(2, 10); assert.deepEqual(calls.slice(1), [['page', 2]]); }); test('Combined change handlers receive page one with the new size', () => { const calls = []; const events = pagination.centerPaginationEvents({ pageSize: 20, onChange: (page, size) => calls.push([page, size]), }); events.onChange(3, 50); assert.deepEqual(calls, [[1, 50]]); }); test('Legacy Ant resize handlers receive page one exactly once', () => { const calls = []; pagination .centerPaginationEvents({ pageSize: 10, onShowSizeChange: (p, s) => calls.push([p, s]), onChange: () => calls.push('duplicate'), }) .onChange(4, 20); assert.deepEqual(calls, [[1, 20]]); }); test('Desktop and mobile share size options and translated totals; only mobile has jump input', () => { for (const mobile of [false, true]) { const opts = pagination.centerPaginationOptions({}, mobile); assert.equal(opts.size, 'small'); assert.equal(opts.showTotal(156), '共 156 条'); assert.equal(opts.showQuickJumper, mobile); assert.deepEqual(opts.pageSizeOptions, [10, 20, 50, 100]); } }); const uiFile = 'src/components/ui/index.jsx'; const transformed = await transformWithEsbuild( await fs.readFile(uiFile, 'utf8'), uiFile, { loader: 'jsx', format: 'cjs', target: 'node22', jsx: 'transform' }, ); const modules = { './pagination.css': {}, '../../hooks/common/useIsMobile': { useIsMobile: () => false }, react: React, antd: Ant, './controls': { controlSize: (s) => s }, './pagination': pagination, './overlayPolicy': {}, './form': {}, './chat': {}, '../console/ConsoleContext': { useConsolePage: () => null }, './CenterActionTable': Ant.Table, '../console/ConsolePrimitives': {}, '../console/consoleTableAdapter': {}, }; const module = { exports: {} }; runInNewContext(transformed.code, { module, exports: module.exports, window: { matchMedia: () => ({ matches: false }) }, require(name) { assert.ok(name in modules, name); return modules[name]; }, }); const { Table } = module.exports; test('Tables with pagination false or omitted never gain a paginator', () => { for (const config of [false, undefined]) { const el = Table({ pagination: config, columns: [{ dataIndex: 'id' }], dataSource: [sentinel], }); assert.equal(el.props.pagination, false); assert.doesNotMatch(renderToStaticMarkup(el), /ant-pagination/); } }); test('Supplied page rows pass through, while complete datasets are sliced locally', () => { const dataSource = Array.from({ length: 25 }, (_, index) => ({ id: index + 1, name: `pagination-row-${index + 1}-end`, })); const render = (config) => renderToStaticMarkup( Table({ rowKey: 'id', columns: [{ dataIndex: 'name' }], dataSource, pagination: { currentPage: 2, pageSize: 10, ...config }, }), ); const local = render({}); assert.match(local, /pagination-row-11-end/); assert.doesNotMatch(local, /pagination-row-(1|21)-end/); assert.match(local, /ant-pagination-options-size-changer/); const supplied = render({ total: 75, onPageSizeChange() {} }); assert.match(supplied, /pagination-row-1-end/); assert.match(supplied, /pagination-row-25-end/); assert.match(supplied, /ant-pagination-options-size-changer/); assert.doesNotMatch( render({ total: 75 }), /ant-pagination-options-size-changer/, ); }); test('Existing unpaginated tables keep pagination disabled after other UI edits', async () => { const expected = JSON.parse( await fs.readFile( new URL('./fixtures/unpaginated-tables.json', import.meta.url), 'utf8', ), ); let compared = 0; for (const [file, count] of Object.entries(expected)) { const ast = parse(await fs.readFile(file, 'utf8'), { sourceType: 'module', plugins: ['jsx'], }); let actual = 0; walk(ast, (node) => { if ( node.type !== 'JSXOpeningElement' || !/Table$/.test(node.name.name || '') ) return; if ( node.attributes.some( (attr) => attr.name?.name === 'pagination' && attr.value?.expression?.value === false, ) ) actual++; }); assert.equal(actual, count, file + ': unpaginated table count'); compared += actual; } assert.equal(compared, 6, 'Covers the intentionally unpaginated tables'); }); test('Visual model editor keeps frontend filtering and supports size reset', async () => { const file = 'src/pages/Setting/Ratio/ModelSettingsVisualEditor.jsx'; const after = await fs.readFile(file, 'utf8'); const calls = []; walk(parse(after, { sourceType: 'module', plugins: ['jsx'] }), (node) => { if (node.type === 'CallExpression' && node.callee.object?.name === 'API') calls.push(node); }); assert.equal(calls.length, 1, 'Only the existing save request is present'); assert.equal(calls[0].callee.property.name, 'put'); assert.equal(calls[0].arguments[0].value, '/api/option/'); assert.match(after, /\[pageSize, setPageSize\] = useState\(10\)/); assert.match( after, /onPageSizeChange: \(size\) => \{\s*setPageSize\(size\);\s*setCurrentPage\(1\);/, ); }); test('Multi-key read pagination preserves existing POST action and response fields', async () => { const { source } = await callback( 'src/components/table/channels/modals/MultiKeyManageModal.jsx', 'loadKeyStatus', ); const calls = [], states = {}; const context = { channel: { id: 7 }, currentPage: 3, pageSize: 50, statusFilter: 1, API: { post: async (path, data) => { calls.push({ path, data }); return { data: { success: true, data: { keys: [sentinel], total: 156, page: 3, page_size: 50, total_pages: 4, }, }, }; }, }, setLoading: (x) => { states.loading = x; }, setKeyStatusList: (x) => { states.rows = x; }, setTotal: (x) => { states.total = x; }, setCurrentPage: () => {}, setPageSize: () => {}, setTotalPages: () => {}, setEnabledCount: () => {}, setManualDisabledCount: () => {}, setAutoDisabledCount: () => {}, showError: assert.fail, t: (x) => x, console, }; await runInNewContext('(' + source + ')', context)(3, 50, 1); assert.equal(calls.length, 1); assert.equal(calls[0].path, '/api/channel/multi_key/manage'); assert.equal(calls[0].data.action, 'get_key_status'); assert.equal(calls[0].data.page, 3); assert.equal(calls[0].data.page_size, 50); assert.equal(states.total, 156); assert.equal(states.rows[0], sentinel); assert.equal(states.loading, false); });