READ-ONLY PACKAGE PREVIEW

router-query/examples/extract_native.py

Version 663282b0ebbc.bb1 · MIT. This preview displays packaged text and does not execute code. Treat the contents as untrusted instructions.

← Return to resource and package checksum

from pathlib import Path
import hashlib,json,re

f=Path(__file__).resolve().parents[1]
p='packages/react-router/skills/compositions/router-query/SKILL.md'
raw=(f/'repository-context'/p).read_bytes()
text=raw.decode('utf-8')
blocks=[{'language':m.group(1),'code':m.group(2)} for m in re.finditer(r'^```([^\n]*)\n(.*?)^```[ \t]*$',text,re.M|re.S)]
assert len(blocks)==14
out=f/'output'/'source';out.mkdir(parents=True,exist_ok=True)
plan={'source_path':p,'primary_sha256':hashlib.sha256(raw).hexdigest(),'blocks':[],'entries':[],'contrast_blocks':[10,11,12,13]}
for i,item in enumerate(blocks):
 code=item['code'];(out/f'native-{i:02}.{item["language"]}').write_text(code,encoding='utf-8',newline='\n')
 plan['blocks'].append({'index':i,'language':item['language'],'sha256':hashlib.sha256(code.encode()).hexdigest(),'bytes':len(code.encode()),'executed_as_source_command':False})

def entry(name,index,prefix='',suffix='',fragment=None):
 code=blocks[index]['code'] if fragment is None else fragment
 assert code in blocks[index]['code']
 target=out/(name+'.tsx');target.write_text(prefix+code+suffix,encoding='utf-8',newline='\n')
 plan['entries'].append({'name':name,'block':index,'whole_block_unchanged':fragment is None,'original_fragment_sha256':hashlib.sha256(code.encode()).hexdigest(),'fragment_start':blocks[index]['code'].index(code),'fragment_bytes':len(code.encode()),'independent_prefix':prefix,'independent_suffix':suffix,'entry_sha256':hashlib.sha256(target.read_bytes()).hexdigest()})

entry('basic',0,suffix='\nexport { router, queryClient, App };\n')
entry('root',1)
entry('factory',2)
entry('integration',4)
entry('manual',5)
entry('posts',6,suffix='\nexport { postsQueryOptions, PostsPage };\n')
entry('post',7,suffix='\nexport { postQueryOptions, PostPage };\n')
entry('dashboard',8,prefix='''// Independent synthetic bindings absent from the original fragment.
import { createFileRoute } from '@tanstack/react-router';
const userQueryOptions = { queryKey: ['user'], queryFn: () => globalThis.__bbUser(), retry: false };
const analyticsQueryOptions = { queryKey: ['analytics'], queryFn: () => globalThis.__bbAnalytics(), retry: false };
function Skeleton() { return <p>Loading analytics</p>; }
function AnalyticsChart({data}) { return <p>{JSON.stringify(data)}</p>; }
''',suffix='\nexport { Dashboard };\n')
entry('errors',9,prefix="// Independent imports absent from the original fragment.\nimport { createFileRoute } from '@tanstack/react-router';\nimport { postsQueryOptions, PostsPage } from './posts';\n",suffix='\nexport { PostsErrorComponent };\n')

for index,names,prefix,suffix in [
 (10,['preload-default','preload-zero'],"import { createRouter } from '@tanstack/react-router';\nimport { routeTree } from './routeTree.gen';\n",'\nexport { router };\n'),
 (11,['shared-factory','fresh-factory'],"import { QueryClient } from '@tanstack/react-query';\nimport { createRouter } from '@tanstack/react-router';\nimport { routeTree } from './routeTree.gen';\n",''),
 (13,['wrong-root','correct-root'],"import { createRootRouteWithContext } from '@tanstack/react-router';\nimport type { QueryClient } from '@tanstack/react-query';\nfunction RootComponent() { return <p>Root</p>; }\n",'\nexport { rootRoute };\n')]:
 code=blocks[index]['code'];split=code.index('// CORRECT')
 for name,fragment in zip(names,[code[:split],code[split:]]):entry(name,index,prefix,suffix,fragment)

code=blocks[12]['code'];positions=[m.start() for m in re.finditer(r'^loader:',code,re.M)]
assert len(positions)==3
for i,name in enumerate(['awaited-loader','background-loader','critical-loader']):
 end=code.find('\n//',positions[i])
 if end<0:end=len(code)
 fragment=code[positions[i]:end]
 entry(name,12,prefix="import { noop } from '@tanstack/react-query';\nconst analyticsQueryOptions = { queryKey: ['analytics'], queryFn: () => globalThis.__bbAnalytics(), retry: false };\nconst criticalQueryOptions = { queryKey: ['critical'], queryFn: () => globalThis.__bbCritical(), retry: false };\nconst fixture = {\n",suffix='\n};\nexport { fixture };\n',fragment=fragment)

(out/'routeTree.gen.ts').write_text('''// Independent generated-tree equivalent; the original examples do not supply this file.
import { Route as root } from './root';
import { Route as posts } from './posts';
import { Route as post } from './post';
posts.update({ id: '/posts', path: '/posts', getParentRoute: () => root });
post.update({ id: '/posts/$postId', path: '/posts/$postId', getParentRoute: () => root });
export const routeTree = root.addChildren([posts, post]);
''',encoding='utf-8',newline='\n')
(f/'native-extraction-plan.json').write_text(json.dumps(plan,indent=2),encoding='utf-8',newline='\n')
print(json.dumps({'blocks':14,'entries':len(plan['entries']),'native_bash_executed':False,'primary_sha256':plan['primary_sha256']}))