import test from 'node:test'; import assert from 'node:assert/strict'; import fs from 'node:fs'; import ts from 'typescript'; import React from 'react'; import { readQueryLocation } from '../src/queryLoadingScope.ts'; import { pageUsesResources } from '../src/resourceInvalidation.ts'; const tick = () => new Promise(resolve => setImmediate(resolve)); const deferred = () => { let resolve, reject; const promise = new Promise((a, b) => { resolve = a; reject = b; }); return { promise, resolve, reject }; }; function fixture() { const source = fs.readFileSync(new URL('../src/CachedWorkspacePages.tsx', import.meta.url), 'utf8') .replace(/^import[\s\S]*?;\n/gm, '').replace(/export /g, ''); const values = new Map(), refs = new Map(), effects = new Map(), events = new Map(), navigations = [], scopes = []; let cursor = 0, dirty = false, queued = [], tree; let state = { authRevision: 'a1', dataRevision: 'd1', currentReleaseId: 'r1' }, failState = false, failStatus, me, optionReads=0, optionDenied=false; const props = { page: 'overall', user: { id: 'A' }, onUnauthorized: () => false, onPageChange(page) { props.page = page; dirty = true; }, onUserChange(user) { props.user = user; dirty = true; } }; const ref = { current: null }; const hooks = { useState(initial) { const i = cursor++; if (!values.has(i)) values.set(i, typeof initial === 'function' ? initial() : initial); return [values.get(i), next => { values.set(i, typeof next === 'function' ? next(values.get(i)) : next); dirty = true; }]; }, useRef(initial) { const i = cursor++; if (!refs.has(i)) refs.set(i, { current: initial }); return refs.get(i); }, useEffect(fn, deps) { const i = cursor++, old = effects.get(i); if (!old || deps.some((value, j) => !Object.is(value, old.deps[j]))) queued.push(() => { old?.cleanup?.(); effects.set(i, { deps, fn, cleanup: fn() }); }); }, useImperativeHandle(target, factory) { cursor++; target.current = factory(); }, }; const api = { async options() { optionReads++; if(optionDenied) { events.get('quality-permission-recheck')?.(); throw Object.assign(Error('denied'),{status:403}); } return {}; }, async sourceColumnCatalog() { return {}; }, async workspaceState() { if (failState) { failState = false; throw Object.assign(Error('temporary-offline'), { status: failStatus }); } return { ...state }; }, async me() { return me ? me.promise : props.user; } }; const env = { location: { search: '?page=overall', pathname: '/' }, window: { scrollY: 0, scrollTo() {}, matchMedia: () => ({ matches: false }), addEventListener: (name, fn) => events.set(name, fn), removeEventListener: name => events.delete(name) }, document: { visibilityState: 'visible', addEventListener: (name, fn) => events.set(name, fn), removeEventListener: name => events.delete(name), querySelector() {} }, history: { pushState(_state, _title, url) { env.location.search = url.slice(url.indexOf('?')); } }, requestAnimationFrame(fn) { fn(); return 1; }, cancelAnimationFrame() {}, forwardRef: component => component, lazy: () => 'Page', Suspense: 'Suspense', Alert: 'Alert', Button: 'Button', Spin: 'Spin', PageCacheContext: { Provider: 'Provider' }, WORKSPACE_INVALIDATED: 'invalidate', configureRequestScope: scope => scopes.push({ ...scope }), resetRequestScope: () => {}, createWorkspaceTransition: () => ({ run(callback) { const promise = callback(new AbortController().signal); navigations.push(promise); }, cancel() {} }), waitForWorkspaceContent: async () => {}, flushSync: fn => fn(), }; const prelude = 'const {useState,useRef,useEffect,useImperativeHandle}=hooks;const useLayoutEffect=useEffect;'; const compiled = ts.transpileModule(prelude + source + '\nreturn CachedWorkspacePages;', { fileName: 'fixture.tsx', compilerOptions: { target: ts.ScriptTarget.ES2022, jsx: ts.JsxEmit.React } }).outputText; const component = new Function('React', 'hooks', 'api', 'pageUsesResources','readQueryLocation', ...Object.keys(env), compiled)(React, hooks, api, pageUsesResources,readQueryLocation, ...Object.values(env)); const render = () => { let attempts = 0; do { cursor = 0; dirty = false; queued = []; tree = component(props, ref); queued.forEach(fn => fn()); assert.ok(++attempts < 15); } while (dirty); return tree; }; const pages = () => { const result = []; function walk(node) { if (!node || typeof node !== 'object') return; if (node.props?.['data-page']) result.push(node.props['data-page']); React.Children.forEach(node.props?.children, walk); } walk(tree); return result; }; return { render, pages, props, scopes, ref, async start() { render(); await tick(); render(); }, async settle() { await Promise.all(navigations); await tick(); render(); }, getOptionReads:()=>optionReads,denyOptions(){optionDenied=true;},failNextState(status) { failState = true; failStatus = status; }, changeIdentity() { state = { ...state, authRevision: 'b2' }; me = deferred(); return me; }, async focus() { events.get('focus')?.(); await tick(); render(); }, cleanup() { effects.forEach(effect => effect.cleanup?.()); } }; } test('a navigation rejected by workspace validation can be retried to the same destination', async () => { const ui = fixture(); await ui.start(); ui.failNextState(); ui.ref.current.navigate('department'); await ui.settle(); assert.equal(ui.props.page, 'overall'); ui.ref.current.navigate('department'); await ui.settle(); assert.equal(ui.props.page, 'department'); ui.cleanup(); }); test('revoked authorization immediately hides retained pages while the latest identity is pending or failed', async () => { const ui = fixture(); await ui.start(); assert.deepEqual(ui.pages(), ['overall']); const me = ui.changeIdentity(); await ui.focus(); assert.deepEqual(ui.pages(), []); me.reject(Error('identity-unavailable')); await tick(); ui.render(); assert.deepEqual(ui.pages(), []); ui.cleanup(); }); test('foreground validation uses the refreshed identity instead of the first mounted user', async () => { const ui = fixture(); await ui.start(); const me = ui.changeIdentity(); await ui.focus(); me.resolve({ id: 'B' }); await tick(); ui.render(); assert.equal(ui.props.user.id, 'B'); await ui.focus(); assert.equal(ui.scopes.at(-1).userId, 'B'); ui.cleanup(); }); test('workspace 403 hides private retained results and rebuilds after authorization recovery', async () => { const ui = fixture(); await ui.start(); assert.deepEqual(ui.pages(), ['overall']); ui.failNextState(403); await ui.focus(); assert.deepEqual(ui.pages(), []); await ui.focus(); await tick(); ui.render(); assert.deepEqual(ui.pages(), ['overall']); ui.cleanup(); }); test('a first-load workspace 403 can recover into a populated workspace', async () => { const ui = fixture(); ui.failNextState(403); await ui.start(); assert.deepEqual(ui.pages(), []); await ui.focus(); await tick(); ui.render(); assert.deepEqual(ui.pages(), ['overall']); ui.cleanup(); }); test('a forbidden options resource does not trigger repeated warm reads during permission rechecks', async () => { const ui=fixture();ui.denyOptions();await ui.start();await tick();ui.render();const count=ui.getOptionReads(); await ui.focus();await tick();ui.render();assert.equal(ui.getOptionReads(),count);assert.ok(count<=1);ui.cleanup(); });