Files
huncode 12562baeb5
Build and deploy / deploy (push) Successful in 2m39s
Implement ProgCode identity and real shared reading UI kit
2026-10-27 15:19:49 +03:00

100 lines
8.3 KiB
Python

from pathlib import Path
from html.parser import HTMLParser
from urllib.parse import urlsplit,urljoin,unquote,quote
import json,hashlib,subprocess,re,urllib.request,urllib.error,concurrent.futures,struct
r=Path('/Users/gavrilovdev/tmp/progcode.ru');w=r/'web';frozen=Path('/tmp/progcode-ds-frozen-f5d927948163');old=Path('/tmp/progcode-metrika-frozen-527ea7bf774e');out=r/'docs/design-system/candidates/f5d927948163/reviews';expected='f5d92794816398171b68a1d374b24bd0cd9ea0f85d005c7be92369b40d314900';base='http://127.0.0.1:50480'
# Independently enumerate current working sources following the inspected publication helper boundary.
names=sorted([str(p.relative_to(w)) for dirname in ['app','lib','fsd','scripts','data','public'] for p in (w/dirname).rglob('*') if p.is_file() and str(p.relative_to(w))!='public/build-identity.json']+['package.json','package-lock.json','next.config.mjs']);h=hashlib.sha256()
for name in names:h.update(name.encode());h.update((w/name).read_bytes())
assert len(names)==230 and h.hexdigest()==expected,(len(names),h.hexdigest());source=h.hexdigest();build=hashlib.sha256();outputFiles=sorted(p for p in frozen.rglob('*') if p.is_file())
for p in outputFiles:build.update(str(p.relative_to(frozen)).encode());build.update(p.read_bytes())
assert len(outputFiles)==722 and build.hexdigest()=='ea4fb0dc8934776e4e9d4213f07c27424962789bfadd1ba9ca51ad31d5736851'
assert json.loads((frozen/'build-identity.json').read_text())['sourceHash']==source
# Inspect actual import graph, not the implementer's reported graph.
ranks={'pages':0,'widgets':1,'features':2,'entities':3,'shared':4};edges=[];violations=[]
def resolve(p):
return next((q.resolve() for q in [p,*[Path(str(p)+suffix) for suffix in ['.js','.jsx','.mjs','.json','.css']],p/'index.js',p/'index.jsx'] if q.is_file()),None)
fsd=(w/'fsd').resolve()
for p in (w/'fsd').rglob('*'):
if p.suffix not in ['.js','.jsx','.mjs']:continue
src=p.relative_to(fsd).parts
for name in re.findall(r"(?:from\s*|import\s*)['\"]([^'\"]+)['\"]",p.read_text()):
if not name.startswith('.'):continue
target=resolve(p.parent/name);assert target,(p,name)
edges.append({'source':str(p.relative_to(w)),'import':name,'target':str(target.relative_to(w))})
if target.is_relative_to(fsd):
dst=target.relative_to(fsd).parts
if ranks[dst[0]]<ranks[src[0]] or (src[0]==dst[0] and src[0]!='shared' and src[1]!=dst[1]):violations.append((str(p),str(target),'direction'))
if src[:2]!=dst[:2] and target.stem!='index' and dst[0]!='shared':violations.append((str(p),str(target),'publicAPI'))
for p in (w/'app').rglob('*'):
if p.suffix not in ['.js','.jsx','.mjs']:continue
for name in re.findall(r"(?:from\s*|import\s*)['\"]([^'\"]+)['\"]",p.read_text()):
if name.startswith('.'):
target=resolve(p.parent/name);assert target
if target.is_relative_to((w/'app').resolve()) and target.suffix in ['.jsx','.js','.mjs']:violations.append((str(p),str(target),'route-to-route'))
assert not violations,violations
assert subprocess.check_output(['git','show','0458a99:web/lib/metrika.mjs'],cwd=r)==(w/'fsd/features/analytics/model/metrika.mjs').read_bytes()
assert subprocess.check_output(['git','show','0458a99:web/lib/dates.mjs'],cwd=r)==(w/'fsd/shared/lib/dates.mjs').read_bytes()
dataNames=['articles-v2.json','articles.json','publication-report.json','archive-routes.json','shortlinks.json','figure-placements.json']
for name in dataNames:assert subprocess.check_output(['git','show','0458a99:web/data/'+name],cwd=r)==(w/'data'/name).read_bytes()
class Page(HTMLParser):
def __init__(self,text):super().__init__(convert_charrefs=True);self.current=None;self.times=[];self.links=set();self.ids=set();self.feed(text)
def handle_starttag(self,t,attrs):
a=dict(attrs)
if a.get('id'):self.ids.add(a['id'])
if a.get('name'):self.ids.add(a['name'])
if t=='time':self.current=[a.get('datetime'),'']
for attr in ['href','src','action']:
u=a.get(attr)
if u:self.links.add(u)
def handle_data(self,s):
if self.current is not None:self.current[1]+=s
def handle_endtag(self,t):
if t=='time' and self.current is not None:self.times.append(self.current);self.current=None
def inner(text):
m=re.search(r'<div\b[^>]*class="[^"]*\barticle-content\b[^"]*"[^>]*>',text);assert m
depth=1;start=m.end()
for tag in re.finditer(r'</?div\b[^>]*>',text[start:]):
depth+=-1 if tag.group().startswith('</') else 1
if not depth:return text[start:start+tag.start()]
raise AssertionError('unclosed article content')
oldpages={p.relative_to(old) for p in old.rglob('*.html')};newpages={p.relative_to(frozen) for p in frozen.rglob('*.html')};assert len(oldpages)==81 and oldpages<=newpages
bodyPaths=[];times=0
for path in oldpages:
a=(old/path).read_text();b=(frozen/path).read_text();pa=Page(a);pb=Page(b);assert pa.times==pb.times,str(path);times+=len(pa.times)
if 'class="article-shell"' in a:assert inner(a)==inner(b),str(path);bodyPaths.append(str(path))
assert len(bodyPaths)==28 and times==146
media=sorted(p.relative_to(old) for p in (old/'visuals').rglob('*') if p.is_file())
for path in media:assert (old/path).read_bytes()==(frozen/path).read_bytes()
assert len(media)==11
icons={}
for size in [16,32,48,180]:
b=(frozen/f'brand/favicon-{size}.png').read_bytes();assert b.startswith(b'\x89PNG\r\n\x1a\n');actual=struct.unpack('>II',b[16:24]);assert actual==(size,size);icons[str(size)]=actual
ico=(frozen/'brand/favicon.ico').read_bytes();reserved,kind,count=struct.unpack('<HHH',ico[:6]);assert reserved==0 and kind==1 and count==3;icoSizes=[(ico[6+16*i],ico[7+16*i]) for i in range(count)];assert sorted(icoSizes)==[(16,16),(32,32),(48,48)]
# Fetch only local HTTP documents/resources. This cannot execute browser scripts or send metric traffic.
def route(path):return '/'+str(path)[:-10] if str(path).endswith('index.html') else '/'+str(path)
def get(path):
try:
with urllib.request.urlopen(base+quote(unquote(path),safe='/%?=&:#'),timeout=10) as response:return response.status,response.read()
except urllib.error.HTTPError as e:return e.code,e.read()
localPages=[];targets=set();fragments=[]
for path in sorted(newpages):
url=route(path);status,body=get(url);assert status==200,(url,status);assert body==(frozen/path).read_bytes(),url;p=Page(body.decode());localPages.append(url)
for link in p.links:
parsed=urlsplit(link)
if parsed.scheme or parsed.netloc:continue
target=urlsplit(urljoin(url,link));targets.add(target.path)
if target.fragment:fragments.append((url,target.path,unquote(target.fragment)))
intentional404=[]
for target in targets:
status,b=get(target)
if target=='/does-not-exist-uikit/':
assert status==404 and 'Такой страницы нет.'.encode() in b;intentional404.append(target)
else:assert status==200,(target,status)
for sourcePage,target,fragment in fragments:
status,b=get(target);assert fragment in Page(b.decode()).ids,(sourcePage,target,fragment)
status,b=get('/unknown/programmer-f5-check/');assert status==404 and 'Такой страницы нет.'.encode() in b
result={'candidateSource':source,'sourceFiles':len(names),'frozenBuildHash':build.hexdigest(),'frozenFiles':len(outputFiles),'workingSourceMatchesFrozenIdentity':True,'FSDImports':len(edges),'boundaryViolations':violations,'noRouteToRouteImports':True,'legacyDataFilesByteIdentical':dataNames,'originalHTMLRoutesPreserved':len(oldpages),'newHTMLRoutes':sorted(str(x) for x in newpages-oldpages),'articleBodiesByteIdentical':len(bodyPaths),'printedDateAndISOElementsExact':times,'historicalVisualsByteIdentical':len(media),'analyticsAndDatesExact0458':True,'faviconPNGSizes':icons,'icoSizes':icoSizes,'localFetchedHTMLExactFrozen':len(localPages),'localInternalTargets200':len(targets)-len(intentional404),'intentionalUIKit404Demonstration':intentional404,'localFragmentTargetsExist':len(fragments),'branded404':True,'browserOrProductionJSExecuted':False,'statisticsSent':0,'harnessNote':'First crawl correctly found the intentional UIkit404 demonstration; reviewer then classified this named fixture separately and continued asserting all other internal targets200. No product change.','limits':'Source/integration and local HTTP checks; final F5 interactive/SDK role/CI/live gates remain separate.'}
out.mkdir(parents=True,exist_ok=True);(out/'programmer-evidence.json').write_text(json.dumps(result,ensure_ascii=False,indent=2)+'\n');print(json.dumps(result,ensure_ascii=False));(out/'programmer-import-graph.json').write_text(json.dumps(edges,indent=2)+'\n')