import test from 'node:test'; import assert from 'node:assert/strict'; import fs from 'node:fs'; import ts from 'typescript'; import React from 'react'; const compile=s=>ts.transpileModule(s,{compilerOptions:{target:ts.ScriptTarget.ES2022,module:ts.ModuleKind.ESNext,jsx:ts.JsxEmit.React}}).outputText; const component=compile(fs.readFileSync(new URL('../src/QualityTargetsPanel.tsx',import.meta.url),'utf8')).replace(/^import .*;\n/gm,'').replace(/export /g,''); const coordinatorCode=compile(fs.readFileSync(new URL('../src/requestCoordinator.ts',import.meta.url),'utf8')); const tick=()=>new Promise(r=>setTimeout(r,0)); const deferred=()=>{let resolve;return {promise:new Promise(r=>resolve=r),resolve:v=>resolve(v)};}; async function fixture({cancelInitial=false,cancelAfterSave=false,denied=false}={}){ const coordinator=await import(`data:text/javascript;base64,${Buffer.from(coordinatorCode).toString('base64')}#${Math.random()}`); let revision=1;coordinator.configureRequestScope({userId:'actor',authRevision:'auth',dataRevision:String(revision),currentReleaseId:'release'}); const states=[],effects=new Map(),messages=[],formValues={};let cursor=0,dirty=true,tree,pending=[],writes=0,reads=0; const data={version:{id:'targets',status:'ACTIVE',rowVersion:1},targets:[{metric:'COMPOSITE_RATE',periodType:'YEAR',year:2026,dimensions:{},value:.955,unit:'RATE'}]}; const stale=deferred();let cancelNext=cancelInitial; const coordinated=(url,dataFn)=>coordinator.coordinateRequest({url,execute:async()=>({data:await dataFn(),status:200,bytes:100})}); const api={ targetVersions:()=>coordinated('/api/analytics/targets/versions',async()=>{reads++;if(denied)throw Object.assign(new Error('无权限'),{status:403});if(cancelNext){cancelNext=false;queueMicrotask(()=>coordinator.configureRequestScope({userId:'actor',authRevision:'auth',dataRevision:String(++revision),currentReleaseId:'release'}));await stale.promise;}return {items:[data.version]};}), targetVersion:()=>coordinated('/api/analytics/targets/versions/targets',async()=>structuredClone(data)), referenceNames:()=>coordinated('/api/options/reference-names',async()=>({})), updateCurrentTargets:async body=>{writes++;data.targets=structuredClone(body.targets);data.version={...data.version,rowVersion:data.version.rowVersion+1};cancelNext=cancelAfterSave;return structuredClone(data);}, }; const hooks={ useState(initial){const i=cursor++;if(!(i in states))states[i]=initial;return [states[i],v=>{states[i]=typeof v==='function'?v(states[i]):v;dirty=true;}];}, useRef(initial){const i=cursor++;if(!(i in states))states[i]={current:initial};return states[i];}, useCallback(fn,deps){const i=cursor++,old=states[i];if(!old||deps.some((v,j)=>!Object.is(v,old.deps[j])))states[i]={fn,deps};return states[i].fn;}, useEffect(fn,deps){const i=cursor++,old=effects.get(i);if(!old||!deps||deps.some((v,j)=>!Object.is(v,old.deps[j])))pending.push(()=>{old?.cleanup?.();effects.set(i,{deps,cleanup:fn()});});}, }; const Form=Object.assign('Form',{useForm:()=>[{setFieldsValue(v){Object.assign(formValues,v);},getFieldsValue:()=>({...formValues}),validateFields:async()=>({...formValues})}],useWatch:key=>formValues[key],Item:'FormItem'}); const names=['React','useCallback','useEffect','useRef','useState','Alert','App','Button','Checkbox','Empty','Form','Input','InputNumber','Modal','Select','Spin','PlusOutlined','ReloadOutlined','CompactManagementTables','Table','ApiError','api','METRIC_NAMES','matchingTarget','obj','ruleList','readableSelectPopup','useDeleteConfirmation','useMaintenanceRefresh']; class ApiError extends Error{} const values=[React,hooks.useCallback,hooks.useEffect,hooks.useRef,hooks.useState,'Alert',{useApp:()=>({message:{success:x=>messages.push(['success',x]),error:x=>messages.push(['error',x])}})},'Button','Checkbox','Empty',Form,'Input','InputNumber','Modal','Select','Spin','Plus','Reload',{Provider:'Provider'},'Table',ApiError,api,{COMPOSITE_RATE:'综合合格率'},()=>null,v=>v&&typeof v==='object'?v:{},v=>Array.isArray(v)?v:[],{},()=>()=>{},()=>{}]; const Component=new Function(...names,component+';return QualityTargetsPanel;')(...values); const props={onUnauthorized:e=>e?.status===401}; function render(){cursor=0;dirty=false;pending=[];tree=Component(props);pending.forEach(f=>f());} async function settle(){for(let n=0;n<20;n++){if(dirty)render();await tick();}if(dirty)render();} function nodes(e){return React.isValidElement(e)?[e,...React.Children.toArray(e.props.children).flatMap(nodes)]:[];} function find(type,predicate=()=>true){return nodes(tree).find(n=>n.type===type&&predicate(n.props));} await settle(); return {settle,find,messages,stale,formValues,get writes(){return writes;},get reads(){return reads;},get data(){return data;},dispose(){effects.forEach(e=>e.cleanup?.());coordinator.resetRequestScope();}}; } test('target reads cancelled by a workspace revision automatically reload instead of leaving 请求已取消 on screen',async()=>{ const f=await fixture({cancelInitial:true});try{assert.ok(f.find('Table'),'a fresh target snapshot must render after the coordinator cancels the first GET');assert.equal(f.find('Alert'),undefined);assert.ok(f.reads>=2);f.stale.resolve();await f.settle();assert.equal(f.find('Alert'),undefined);}finally{f.dispose();} }); test('a committed new year survives refresh cancellation, is not saved twice, and becomes the selected year',async()=>{ const f=await fixture({cancelAfterSave:true});try{ f.find('Button',p=>React.Children.toArray(p.children).includes('新增目标')).props.onClick();await f.settle();Object.assign(f.formValues,{year:2025,metric:'COMPOSITE_RATE',scope:'overall',value:95,inherit:false});f.find('Modal').props.onOk();await f.settle(); assert.equal(f.writes,1);assert.equal(f.find('Alert'),undefined,'a cancelled post-save refresh is not a save failure');assert.equal(f.find('Select',p=>p['aria-label']==='目标年度').props.value,2025);assert.equal(f.find('Table').props.dataSource[0].displayValue,.95);assert.equal(f.data.targets.length,2);assert.equal(f.data.targets.find(t=>t.year===2026).value,.955); }finally{f.dispose();} }); test('real authorization errors remain visible and are not retried as cancelled reads',async()=>{ const f=await fixture({denied:true});try{assert.equal(f.reads,1);assert.ok(f.find('Alert').props.description.includes('无权限'));}finally{f.dispose();} });