'use strict'; const express = require('express'); const http = require('http'); const path = require('path'); const { once } = require('events'); const { webcrypto } = require('crypto'); describe('page load smoke test', () => { let server; let baseUrl; let JSDOM; let VirtualConsole; let rootsFixture; let listFixture; let spaceFixture; let meFixture; let thumbnailStatusFixture; let rootAccessFixture; let folderIconFixture; let adminUsersFixture; let adminConfigFixture; let downloadFixture; const openDoms = []; beforeEach(() => { rootsFixture = [{ label: 'Root', path: '/data' }]; listFixture = { '/data': [ { name: 'readme.txt', path: '/data/readme.txt', isDir: false, size: 12, mtime: Date.now(), }, ], }; spaceFixture = { '/data': { usedBytes: 0, freeBytes: 1024 * 1024 }, }; meFixture = { username: 'tester', isAdmin: false, permissions: {} }; thumbnailStatusFixture = {}; rootAccessFixture = {}; folderIconFixture = {}; adminUsersFixture = { users: [] }; adminConfigFixture = { port: 3000, paths: ['/data'], effectivePaths: ['/data'] }; downloadFixture = {}; }); beforeAll(async () => { ({ JSDOM, VirtualConsole } = require('jsdom')); const app = express(); const publicDir = path.join(__dirname, '../public'); app.use(express.json()); app.use(express.static(publicDir)); app.get('/api/auth/server-key', (req, res) => res.json({ publicKey: null })); app.get('/api/auth/setup-needed', (req, res) => res.json({ needed: false })); app.get('/api/auth/me', (req, res) => res.json(meFixture)); app.get('/api/files/roots', (req, res) => res.json({ roots: rootsFixture })); app.get('/api/files/list', (req, res) => { const dir = req.query.dir; res.json({ items: listFixture[dir] || [] }); }); app.get('/api/files/space', (req, res) => { const dir = req.query.dir; const stats = spaceFixture[dir] || { usedBytes: 0, freeBytes: null }; res.json(stats); }); app.get('/api/files/thumbnail', (req, res) => { const file = String(req.query.file || ''); const status = Number(thumbnailStatusFixture[file] || 200); if (status === 404) { return res.status(404).json({ error: 'Thumbnail not ready.' }); } res.type('image/webp').send('thumb'); }); app.get('/api/files/download', (req, res) => { const file = String(req.query.file || ''); const payload = downloadFixture[file]; if (!payload) { return res.status(404).json({ error: 'File not found.' }); } res.type(payload.type || 'application/octet-stream').send(payload.body || 'x'); }); app.get('/api/files/root-access', (req, res) => { const rootPath = String(req.query.rootPath || ''); res.json({ users: rootAccessFixture[rootPath] || [] }); }); app.get('/api/files/folder-icon', (req, res) => { const dir = String(req.query.dir || ''); const icon = folderIconFixture[dir] || null; res.json({ icon }); }); app.get('/api/files/folder-images', (req, res) => { res.json({ images: [] }); }); app.get('/api/admin/config', (req, res) => res.json(adminConfigFixture)); app.get('/api/admin/users', (req, res) => res.json(adminUsersFixture)); app.post('/api/auth/logout', (req, res) => res.json({ ok: true })); app.get('*', (req, res) => res.sendFile(path.join(publicDir, 'index.html'))); server = http.createServer(app); server.listen(0); await once(server, 'listening'); baseUrl = `http://127.0.0.1:${server.address().port}`; }); afterAll(() => server.close()); afterEach(() => { while (openDoms.length) { const dom = openDoms.pop(); try { dom.window.close(); } catch { /* ignore */ } } }); async function bootClient ({ mobile = false, savedSession } = {}) { const virtualConsole = new VirtualConsole(); const runtimeErrors = []; virtualConsole.on('jsdomError', (err) => { runtimeErrors.push(err); }); const dom = await JSDOM.fromURL(baseUrl + '/', { resources: 'usable', runScripts: 'dangerously', pretendToBeVisual: true, virtualConsole, beforeParse (window) { window.crypto = webcrypto; window.fetch = (input, init) => { const url = typeof input === 'string' ? input : input.url; return fetch(new URL(url, baseUrl).toString(), init); }; window.HTMLElement.prototype.focus = function focus () { }; window.HTMLCanvasElement.prototype.getContext = () => null; window.matchMedia = () => ({ matches: mobile, addListener () { }, removeListener () { }, addEventListener () { }, removeEventListener () { } }); window.scrollTo = () => { }; let blobCounter = 0; window.URL.createObjectURL = () => `blob:mock-${blobCounter++}`; window.URL.revokeObjectURL = () => { }; const defaultSaved = { token: 'saved-token', dir: '/data', rootPath: '/data', lastOperationAt: Date.now(), }; const effectiveSaved = savedSession === undefined ? defaultSaved : savedSession; if (effectiveSaved) { window.localStorage.setItem('filemanager.session.v1', JSON.stringify(effectiveSaved)); } window.addEventListener('error', (event) => runtimeErrors.push(event.error || new Error(event.message))); window.addEventListener('unhandledrejection', (event) => runtimeErrors.push(event.reason || new Error('Unhandled rejection'))); }, }); await new Promise((resolve) => dom.window.addEventListener('load', resolve, { once: true })); await new Promise((resolve) => { const startedAt = Date.now(); const maxWaitMs = 2000; function checkReady () { const app = dom.window.document.getElementById('app'); if (app && !app.classList.contains('hidden')) { resolve(); return; } if (Date.now() - startedAt >= maxWaitMs) { resolve(); return; } dom.window.setTimeout(checkReady, 25); } checkReady(); }); openDoms.push(dom); return { dom, runtimeErrors }; } async function waitFor (dom, predicate, timeoutMs = 5000) { const startedAt = Date.now(); while (Date.now() - startedAt < timeoutMs) { if (predicate()) return true; await new Promise(resolve => dom.window.setTimeout(resolve, 25)); } return predicate(); } test('requests / and boots the client without runtime errors', async () => { const { dom, runtimeErrors } = await bootClient(); expect(runtimeErrors).toEqual([]); expect(dom.window.document.getElementById('app').classList.contains('hidden')).toBe(false); expect(dom.window.document.getElementById('sidebar').classList.contains('hidden')).toBe(false); dom.window.close(); }); test('keeps sidebar folded on initial mobile boot', async () => { const { dom, runtimeErrors } = await bootClient({ mobile: true }); expect(runtimeErrors).toEqual([]); expect(dom.window.document.getElementById('app').classList.contains('hidden')).toBe(false); expect(dom.window.document.getElementById('sidebar').classList.contains('hidden')).toBe(true); dom.window.close(); }); test('suppresses default context menu on mobile file long-press', async () => { const { dom, runtimeErrors } = await bootClient({ mobile: true }); expect(runtimeErrors).toEqual([]); await waitFor(dom, () => !!dom.window.document.querySelector('.file-item')); const tile = dom.window.document.querySelector('.file-item'); expect(tile).toBeTruthy(); const evt = new dom.window.MouseEvent('contextmenu', { bubbles: true, cancelable: true, view: dom.window, }); const dispatchResult = tile.dispatchEvent(evt); expect(dispatchResult).toBe(false); expect(evt.defaultPrevented).toBe(true); dom.window.close(); }); test('in Home, root tiles single-click focus and double-click open', async () => { rootsFixture = [ { label: 'Root A', path: '/data-a' }, { label: 'Root B', path: '/data-b' }, ]; listFixture = { '/data-a': [ { name: 'docs', path: '/data-a/docs', isDir: true, size: 0, mtime: Date.now(), }, ], }; spaceFixture = { '/data-a': { usedBytes: 2048, freeBytes: 4096 }, '/data-b': { usedBytes: 1024, freeBytes: 8192 }, }; folderIconFixture = { '/data-a': { filePath: '/data-a/docs/cover.jpg' }, }; const { dom, runtimeErrors } = await bootClient({ savedSession: { token: 'saved-token', dir: null, rootPath: null, lastOperationAt: Date.now(), }, }); expect(runtimeErrors).toEqual([]); const rootTile = dom.window.document.querySelector('.file-item[data-path="/data-a"]'); expect(rootTile).toBeTruthy(); rootTile.dispatchEvent(new dom.window.MouseEvent('click', { bubbles: true })); await new Promise(resolve => dom.window.setTimeout(resolve, 40)); expect(rootTile.classList.contains('selected')).toBe(true); expect(dom.window.document.querySelector('.file-item[data-path="/data-b"]')).toBeTruthy(); expect(dom.window.document.getElementById('sidebar-meta').textContent).toContain('Used'); expect(dom.window.document.getElementById('sidebar-meta').textContent).toContain('Remaining'); let rootIconImage = null; for (let i = 0; i < 10; i++) { const rootIconSvg = rootTile.querySelector('.icon svg'); rootIconImage = rootIconSvg ? rootIconSvg.querySelector('image') : null; if (rootIconImage) break; await new Promise(resolve => dom.window.setTimeout(resolve, 25)); } // Root tiles should load folder icon thumbnails in Home view. expect(rootIconImage).toBeTruthy(); rootTile.dispatchEvent(new dom.window.MouseEvent('dblclick', { bubbles: true })); await new Promise(resolve => dom.window.setTimeout(resolve, 80)); expect(dom.window.document.querySelector('.file-item[data-path="/data-a/docs"]')).toBeTruthy(); dom.window.close(); }); test('root sidebar shows alias and original name, and excludes Move to action', async () => { rootsFixture = [ { label: 'Shared', path: '/data-a', originalName: 'data-a', alias: 'Shared' }, { label: 'Root B', path: '/data-b', originalName: 'data-b', alias: null }, ]; meFixture = { username: 'tester', isAdmin: false, permissions: { 'data-a': { read: true, write: true }, 'data-b': { read: true, write: false }, }, }; spaceFixture = { '/data-a': { usedBytes: 1024, freeBytes: 2048 }, '/data-b': { usedBytes: 2048, freeBytes: 1024 }, }; rootAccessFixture = { '/data-a': [ { username: 'alice', mode: 'R' }, { username: 'bob', mode: 'R+W' }, ], }; const { dom, runtimeErrors } = await bootClient({ savedSession: { token: 'saved-token', dir: null, rootPath: null, lastOperationAt: Date.now(), }, }); expect(runtimeErrors).toEqual([]); await waitFor(dom, () => !!dom.window.document.querySelector('.file-item[data-path="/data-a"]')); const rootTile = dom.window.document.querySelector('.file-item[data-path="/data-a"]'); expect(rootTile).toBeTruthy(); rootTile.dispatchEvent(new dom.window.MouseEvent('click', { bubbles: true })); await new Promise(resolve => dom.window.setTimeout(resolve, 40)); const sidebarText = dom.window.document.getElementById('sidebar-meta').textContent; expect(sidebarText).toContain('Alias'); expect(sidebarText).toContain('Shared'); expect(sidebarText).toContain('Original name'); expect(sidebarText).toContain('data-a'); expect(sidebarText).toContain('Access'); expect(sidebarText).toContain('alice R'); expect(sidebarText).toContain('bob R+W'); const accessItems = Array.from(dom.window.document.querySelectorAll('#sidebar-meta .root-access-list li')).map(li => li.textContent.trim()); expect(accessItems).toEqual(['bob R+W', 'alice R']); const actionButtons = Array.from(dom.window.document.querySelectorAll('#sidebar-actions button')).map(b => b.textContent); expect(actionButtons).toContain('Rename'); expect(actionButtons).not.toContain('Move to'); expect(actionButtons).not.toContain('Delete'); dom.window.close(); }); test('base-level root sidebar shows access list with no item selected', async () => { rootAccessFixture = { '/data': [ { username: 'tim', mode: 'R+W' }, { username: 'guest', mode: 'R' }, ], }; const { dom, runtimeErrors } = await bootClient(); expect(runtimeErrors).toEqual([]); await new Promise(resolve => dom.window.setTimeout(resolve, 80)); const sidebarText = dom.window.document.getElementById('sidebar-meta').textContent; expect(sidebarText).toContain('Access'); expect(sidebarText).toContain('tim R+W'); expect(sidebarText).toContain('guest R'); const accessItems = Array.from(dom.window.document.querySelectorAll('#sidebar-meta .root-access-list li')).map(li => li.textContent.trim()); expect(accessItems).toEqual(['tim R+W', 'guest R']); dom.window.close(); }); test('shows pending icon spinner when image thumbnail cache is not ready', async () => { listFixture = { '/data': [ { name: 'photo.png', path: '/data/photo.png', isDir: false, size: 1024, mtime: Date.now(), }, ], }; thumbnailStatusFixture['/data/photo.png'] = 404; const { dom, runtimeErrors } = await bootClient(); expect(runtimeErrors).toEqual([]); await new Promise(resolve => dom.window.setTimeout(resolve, 80)); const icon = dom.window.document.querySelector('.icon[data-preview-path="/data/photo.png"]'); expect(icon).toBeTruthy(); expect(icon.classList.contains('thumb-pending')).toBe(true); dom.window.close(); }); test('admin user modal locks write checkbox while read is unchecked', async () => { meFixture = { username: 'admin', isAdmin: true, permissions: {} }; adminConfigFixture = { port: 3000, paths: ['/data'], effectivePaths: ['/data'] }; adminUsersFixture = { users: [ { id: 9, username: 'guest', isAdmin: false, permissions: { data: { read: false, write: true } }, }, ], }; const { dom, runtimeErrors } = await bootClient(); expect(runtimeErrors).toEqual([]); dom.window.document.getElementById('btn-admin').dispatchEvent(new dom.window.MouseEvent('click', { bubbles: true })); await new Promise(resolve => dom.window.setTimeout(resolve, 80)); const editBtn = dom.window.document.querySelector('#admin-users-list [data-action="edit"]'); expect(editBtn).toBeTruthy(); editBtn.dispatchEvent(new dom.window.MouseEvent('click', { bubbles: true })); await new Promise(resolve => dom.window.setTimeout(resolve, 40)); const readCb = dom.window.document.querySelector('input[data-label="data"][data-type="read"]'); const writeCb = dom.window.document.querySelector('input[data-label="data"][data-type="write"]'); expect(readCb).toBeTruthy(); expect(writeCb).toBeTruthy(); expect(readCb.checked).toBe(false); expect(writeCb.checked).toBe(false); expect(writeCb.disabled).toBe(true); readCb.checked = true; readCb.dispatchEvent(new dom.window.Event('change', { bubbles: true })); expect(writeCb.disabled).toBe(false); writeCb.checked = true; readCb.checked = false; readCb.dispatchEvent(new dom.window.Event('change', { bubbles: true })); expect(writeCb.checked).toBe(false); expect(writeCb.disabled).toBe(true); dom.window.close(); }); test('uses direct svg thumbnail when svg file is under 1MB', async () => { listFixture = { '/data': [ { name: 'icon.svg', path: '/data/icon.svg', isDir: false, size: 400 * 1024, mtime: Date.now(), }, ], }; thumbnailStatusFixture['/data/icon.svg'] = 404; downloadFixture['/data/icon.svg'] = { type: 'image/svg+xml', body: '', }; const { dom, runtimeErrors } = await bootClient(); expect(runtimeErrors).toEqual([]); await new Promise(resolve => dom.window.setTimeout(resolve, 80)); const icon = dom.window.document.querySelector('.icon[data-preview-path="/data/icon.svg"]'); expect(icon).toBeTruthy(); expect(icon.classList.contains('thumb-pending')).toBe(false); expect(icon.dataset.thumbReady).toBe('1'); dom.window.close(); }); });