stx-router 0.2.48 → 0.2.51
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/client.js +768 -0
- package/dist/client.js.map +10 -0
- package/dist/codegen.js +53 -0
- package/dist/codegen.js.map +10 -0
- package/dist/file-router.js +262 -0
- package/dist/file-router.js.map +13 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +1001 -947
- package/dist/index.js.map +6 -5
- package/dist/layout-metadata.d.ts +6 -0
- package/dist/layout-metadata.js +27 -0
- package/dist/layout-metadata.js.map +10 -0
- package/dist/matcher.js +57 -0
- package/dist/matcher.js.map +10 -0
- package/dist/middleware.js +290 -0
- package/dist/middleware.js.map +10 -0
- package/dist/named-routes.js +58 -0
- package/dist/named-routes.js.map +10 -0
- package/dist/nested-layouts.js +23 -0
- package/dist/nested-layouts.js.map +10 -0
- package/dist/types.js +3 -0
- package/dist/types.js.map +9 -0
- package/package.json +3 -2
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/client.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"/* eslint-disable prefer-const, no-console, style/max-statements-per-line, general/prefer-template */\n/**\n * STX Router - Canonical SPA Router\n *\n * Single source of truth for client-side navigation.\n * Injected via @stxRouter directive or auto-loaded with the signals runtime.\n *\n * Features:\n * - Click interception for internal links\n * - History API pushState navigation\n * - View Transitions API with CSS fade fallback\n * - <head> style swapping (prevents unstyled flash)\n * - Smart script filtering (skip signals runtime, layout guards)\n * - Page prefetching on hover\n * - Response caching (5-minute TTL)\n * - Active link class management (data-stx-link)\n * - Loading indicator bar\n * - Configurable via window.STX_ROUTER_OPTIONS or window.__stxRouterConfig\n */\nexport function getRouterScript(): string {\n return `\n;(function(){\n 'use strict';\n if(window.__stxRouter)return;\n\n // ── Configuration ──\n var defaults={container:'main',loadingClass:'stx-navigating',viewTransitions:true,cache:true,scrollToTop:true,prefetch:true,progress:true,progressColor:'#78dce8',progressHeight:'2px',interceptAllLinks:false};\n var o=Object.assign({},defaults,window.__stxRouterConfig||{},window.STX_ROUTER_OPTIONS||{});\n var containerSel=o.container;\n var debug=!!o.debug;\n function log(){if(debug&&typeof console!=='undefined'&&console.log)console.log.apply(console,arguments)}\n\n // ── Progress bar (0→100% at top of viewport) ──\n // Native loading indicator baked into the router. Starts when navigation\n // begins, trickles up to ~90% during fetch, snaps to 100% + fades on\n // completion. Opt-out via window.__stxRouterConfig={progress:false}.\n var progEl=null;\n var progVal=0;\n var progTimer=null;\n function setProgress(v){\n progVal=v<0?0:(v>100?100:v);\n if(!progEl)return;\n progEl.style.opacity=progVal>0?'1':'0';\n progEl.style.transform='scaleX('+(progVal/100)+')';\n }\n function startProgress(){\n if(!o.progress||!progEl)return;\n if(progTimer){clearInterval(progTimer);progTimer=null}\n setProgress(8);\n progTimer=setInterval(function(){\n if(progVal>=90)return;\n // Asymptotic trickle — fast at first, slower near 90%\n var inc=Math.max(0.4,(90-progVal)*0.08);\n setProgress(progVal+inc);\n },160);\n }\n function finishProgress(){\n if(!o.progress||!progEl)return;\n if(progTimer){clearInterval(progTimer);progTimer=null}\n setProgress(100);\n // Fade out, then reset. Delays chosen so the \"full\" state is briefly\n // visible before the bar disappears.\n setTimeout(function(){\n if(!progEl)return;\n progEl.style.opacity='0';\n setTimeout(function(){progVal=0;if(progEl)progEl.style.transform='scaleX(0)'},260);\n },180);\n }\n\n var cache={};\n var prefetching={};\n var isNavigating=false;\n\n // Extract top-level CSS blocks (rules AND @media blocks with nested braces).\n // The old regex ([^{}]+\\{[^{}]*\\}) silently dropped @media blocks because\n // it couldn't handle nested braces — causing responsive classes (lg:, md:)\n // to vanish after SPA navigation.\n function extractCssBlocks(css){\n var blocks=[];\n var i=0;\n var len=css.length;\n while(i<len){\n // Skip whitespace\n while(i<len&&(css[i]===' '||css[i]==='\\\\n'||css[i]==='\\\\r'||css[i]==='\\\\t'))i++;\n if(i>=len)break;\n // Find the start of a block (first {)\n var blockStart=i;\n var bracePos=css.indexOf('{',i);\n if(bracePos===-1)break;\n // Walk forward tracking brace depth to find the matching close\n var depth=0;\n var j=bracePos;\n while(j<len){\n if(css[j]==='{')depth++;\n else if(css[j]==='}'){depth--;if(depth===0){j++;break}}\n j++;\n }\n if(depth!==0)break;\n blocks.push(css.slice(blockStart,j).trim());\n i=j;\n }\n return blocks;\n }\n\n function mergeCrosswindCSS(existing,incoming){\n var blocks=extractCssBlocks(incoming);\n var newBlocks=[];\n for(var bi=0;bi<blocks.length;bi++){\n if(existing.indexOf(blocks[bi])===-1)newBlocks.push(blocks[bi]);\n }\n if(newBlocks.length>0)return existing+'\\\\n'+newBlocks.join('\\\\n');\n return null;\n }\n\n function getContainer(){\n return document.querySelector(containerSel)||document.querySelector('[data-stx-content]')||document.querySelector('main');\n }\n\n // ── Navigation ──\n // Layout group detection — layouts in the same group share a <main> container.\n // Only truly different layout groups trigger a full page reload.\n var layoutCache={};\n var layoutGroupCache={};\n // Track executed script hashes to prevent redeclaration errors on navigation.\n // Layout-level scripts (theme, nav setup) execute on initial page load and\n // should NOT re-execute when navigating to another page with the same layout.\n var executedScriptHashes={};\n function hashScript(code){\n var h=0;for(var i=0;i<code.length;i++){h=((h<<5)-h)+code.charCodeAt(i);h|=0}\n return h;\n }\n // Record scripts from the initial page load\n document.querySelectorAll('script').forEach(function(s){\n var text=s.textContent||'';\n if(text.trim()&&!s.hasAttribute('src'))executedScriptHashes[hashScript(text)]=1;\n });\n function cacheKey(url){\n var u=new URL(url,location.origin);\n return u.pathname+u.search;\n }\n function defaultLayoutGroup(layout){\n if(!layout)return 'app';\n var clean=String(layout).replace(/\\\\\\\\/g,'/');\n var parts=clean.split('/').filter(Boolean);\n var idx=parts.lastIndexOf('layouts');\n var part=idx>=0?parts[idx+1]:parts[parts.length-1];\n return part?part.replace(/\\\\.stx$/i,''):'app';\n }\n function getCurrentLayoutGroup(){\n var meta=document.querySelector('meta[name=\"stx-layout-group\"]');\n if(meta&&meta.getAttribute('content'))return meta.getAttribute('content');\n var layout=document.querySelector('meta[name=\"stx-layout\"]');\n return defaultLayoutGroup(layout?layout.getAttribute('content'):'');\n }\n function getDocLayoutGroup(doc,layout){\n var meta=doc&&doc.querySelector?doc.querySelector('meta[name=\"stx-layout-group\"]'):null;\n return meta&&meta.getAttribute('content')?meta.getAttribute('content'):defaultLayoutGroup(layout||'');\n }\n function checkLayoutChange(newLayout,targetUrl,newGroup){\n var currentLayout=document.querySelector('meta[name=\"stx-layout\"]');\n var curLayoutName=currentLayout?currentLayout.getAttribute('content'):'';\n var curGroup=getCurrentLayoutGroup();\n var nextGroup=newGroup||defaultLayoutGroup(newLayout);\n log('[router] layout check: current='+curLayoutName+'('+curGroup+') new='+(newLayout||'')+'('+nextGroup+')');\n // Different layout GROUP (e.g. app → auth): full reload\n if(curGroup!==nextGroup){\n log('[router] layout group change:',curGroup,'→',nextGroup,'— full reload to:',targetUrl);\n return true;\n }\n // Same group but different SPECIFIC layout (e.g. layouts/app → layouts/coach):\n // full body swap so nav, sidebar, and other layout-level elements update\n if(curLayoutName && newLayout && curLayoutName!==newLayout){\n log('[router] layout name change:',curLayoutName,'→',newLayout,'— full body swap');\n return true;\n }\n return false;\n }\n\n function navigate(url,pushState,force){\n log('[router] navigate() called:',url,'isNavigating:',isNavigating);\n if(isNavigating)return;\n var t=new URL(url,location.origin);\n\n if(t.origin!==location.origin){location.href=url;return}\n\n if(t.pathname===location.pathname&&t.hash){\n if(pushState!==false)history.pushState({},'',t.href);\n var el=document.querySelector(t.hash);\n if(el)el.scrollIntoView({behavior:'smooth'});\n return;\n }\n\n // Skip if user clicks a link to the page they're already on. We\n // deliberately allow popstate (pushState===false) through because\n // the browser has already updated location.href to the popped\n // entry — without this allowance, hitting back would early-return\n // and the visible page content would be left frozen on the\n // forward-navigation page.\n if(pushState!==false&&t.href===location.href&&!t.hash&&!force)return;\n\n isNavigating=true;\n document.body.classList.add(o.loadingClass);\n startProgress();\n\n var targetHref=t.href;\n var targetPath=cacheKey(url);\n var targetHash=t.hash;\n\n function done(){isNavigating=false;document.body.classList.remove(o.loadingClass);finishProgress()}\n\n if(o.cache&&cache[targetPath]&&!force){\n if(checkLayoutChange(layoutCache[targetPath],url,layoutGroupCache[targetPath])){\n // Layout changed — fetch full page and do full document swap\n log('[router] cache hit but layout changed — fetching full page');\n fetch(url,{headers:{'Accept':'text/html'}}).then(function(r){\n if(!r.ok)throw new Error(r.status);\n return r.text();\n }).then(function(html){\n log('[router] full page fetched from cache path, len:',html.length);\n swap(html,targetPath,pushState,targetHash);\n }).catch(function(err){\n console.error('[router] full page fetch error:',err);\n location.href=url;\n }).finally(done);\n return;\n }\n swap(cache[targetPath],targetPath,pushState,targetHash);\n done();\n }\nelse {\n if(force&&cache[targetPath])delete cache[targetPath];\n // First fetch as fragment (SPA mode)\n fetch(url,{headers:{'X-STX-Router':'true','Accept':'text/html'}}).then(function(r){\n if(!r.ok)throw new Error(r.status);\n var isFragment=r.headers.get('X-STX-Fragment')==='true';\n var newLayout=r.headers.get('X-STX-Layout')||'';\n var newGroup=r.headers.get('X-STX-Layout-Group')||'';\n // Layout change? Fetch the FULL page (no X-STX-Router header) and do full document swap\n if(isFragment&&checkLayoutChange(newLayout,url,newGroup)){\n log('[router] layout change — fetching full page for document swap');\n return fetch(url,{headers:{'Accept':'text/html'}}).then(function(fullRes){\n log('[router] full page fetched:',fullRes.status,'ok:',fullRes.ok);\n if(!fullRes.ok)throw new Error(fullRes.status);\n return fullRes.text().then(function(html){\n log('[router] full page html length:',html.length);\n return{html:html,isFragment:false,layout:newLayout,layoutGroup:newGroup};\n });\n });\n }\n return r.text().then(function(html){return{html:html,isFragment:isFragment,layout:newLayout,layoutGroup:newGroup}});\n }).then(function(result){\n if(!result)return;\n if(result.isFragment)result.html='<!--stx-fragment-->'+result.html;\n if(o.cache){cache[targetPath]=result.html;layoutCache[targetPath]=result.layout;layoutGroupCache[targetPath]=result.layoutGroup}\n swap(result.html,targetPath,pushState,targetHash);\n }).catch(function(err){\n console.error('[router] fetch error:',err);\n location.href=url;\n }).finally(done);\n }\n }\n\n function swap(html,url,pushState,hash){\n var isFragment=html.indexOf('<!--stx-fragment-->')===0;\n if(isFragment)html=html.slice('<!--stx-fragment-->'.length);\n var currentContent=getContainer();\n log('[router] swap: isFragment='+isFragment+' container='+!!currentContent+' tag='+(currentContent&¤tContent.tagName)+' selector='+containerSel+' htmlLen='+html.length);\n if(!currentContent){log('[router] no container — falling back');location.href=url;return}\n\n // Fragment mode: server returned just the page content (no document wrapper)\n if(isFragment){\n if(window.stx&&window.stx._cleanupContainer)window.stx._cleanupContainer(currentContent);\n function doFragSwap(){\n // Extract scripts from fragment before injecting HTML\n var fragScripts=[];\n var fragStyles=[];\n var fragCrosswindCSS=null;\n var cleanFrag=html.replace(new RegExp('<scr'+'ipt\\\\\\\\b[^>]*>([\\\\\\\\s\\\\\\\\S]*?)<\\\\\\\\/scr'+'ipt>','gi'),function(m,code){\n if(code&&code.trim())fragScripts.push(code);\n return '';\n });\n cleanFrag=cleanFrag.replace(new RegExp('<sty'+'le\\\\\\\\b([^>]*)>([\\\\\\\\s\\\\\\\\S]*?)<\\\\\\\\/sty'+'le>','gi'),function(m,attrs,css){\n if(attrs.indexOf('data-crosswind')!==-1){\n fragCrosswindCSS=css;\n }else{\n fragStyles.push({attrs:attrs,css:css});\n }\n return '';\n });\n // Remove old page styles (not crosswind — that gets merged)\n document.querySelectorAll('style[data-stx-page]').forEach(function(s){s.remove()});\n // Merge crosswind CSS from fragment into existing crosswind style\n if(fragCrosswindCSS){\n var curCrosswind=document.querySelector('head style[data-crosswind]');\n if(curCrosswind){\n var merged=mergeCrosswindCSS(curCrosswind.textContent||'',fragCrosswindCSS);\n if(merged)curCrosswind.textContent=merged;\n }else{\n var cw=document.createElement('style');\n cw.setAttribute('data-crosswind','generated');\n cw.textContent=fragCrosswindCSS;\n document.head.appendChild(cw);\n }\n }\n // Add new page styles\n fragStyles.forEach(function(s){\n var el=document.createElement('style');\n el.textContent=s.css;\n el.setAttribute('data-stx-page','');\n document.head.appendChild(el);\n });\n // Swap content\n currentContent.innerHTML=cleanFrag;\n // Remove old page scripts\n document.querySelectorAll('script[data-stx-page]').forEach(function(s){s.remove()});\n if(pushState!==false)history.pushState({},'',url+(hash||''));\n updateNav(url);\n updateActiveLinks();\n if(o.scrollToTop&&!hash)window.scrollTo({top:0,behavior:'instant'});\n else if(hash){var el=document.querySelector(hash);if(el)el.scrollIntoView({behavior:'smooth'})}\n window.dispatchEvent(new CustomEvent('stx:navigate',{detail:{url:url}}));\n // Execute page scripts FIRST — they define setup functions and set _latestSetup\n log('[router] frag scripts:', fragScripts.length);\n document.querySelectorAll('script[data-stx-page]').forEach(function(s){s.remove()});\n fragScripts.forEach(function(code){\n log('[router] exec script len:', code.length, 'has __stx_setup:', code.indexOf('__stx_setup')>-1);\n // Skip scripts that were already executed (layout-level partials\n // like theme.stx, stores.stx, nav.stx). Their top-level const/let\n // declarations would throw \"Identifier has already been declared\"\n // on re-execution. Setup functions (__stx_setup_) must always\n // re-execute because each page has its own setup.\n var h=hashScript(code);\n var isSetup=code.indexOf('__stx_setup_')!==-1;\n if(!isSetup&&executedScriptHashes[h]){\n log('[router] skipping already-executed script (hash dedup)');\n return;\n }\n executedScriptHashes[h]=1;\n var ns=document.createElement('script');\n // Wrap in block scope to prevent const/let collisions on re-navigation.\n // Without this, navigating away and back throws \"Identifier has already\n // been declared\" because the previous page's top-level const/let are\n // still in the global scope.\n var isAlreadyScoped=code.trimStart().charAt(0)==='('||code.trimStart().charAt(0)===';'||code.indexOf('window.stx.mount')>-1;\n ns.textContent=isAlreadyScoped?code:'{'+code+'}';\n ns.setAttribute('data-stx-page','');\n document.body.appendChild(ns);\n });\n log('[router] scripts done. _latestSetup:', !!window.stx._latestSetup);\n // THEN fire stx:load — now _latestSetup is set and processElement has the right scope\n window.dispatchEvent(new Event('stx:load'));\n }\n if(o.viewTransitions&&document.startViewTransition){document.startViewTransition(doFragSwap)}\n else{currentContent.style.transition='opacity 0.12s ease-out';currentContent.style.opacity='0';setTimeout(function(){doFragSwap();currentContent.style.opacity='1';setTimeout(function(){currentContent.style.transition=''},150)},120)}\n return;\n }\n\n // Full document mode: parse with DOMParser and extract container content\n var parser=new DOMParser();\n var doc=parser.parseFromString(html,'text/html');\n var newContent=doc.querySelector(containerSel)||doc.querySelector('[data-stx-content]')||doc.querySelector('main');\n if(!newContent){location.href=url;return}\n\n // Clean up existing signals/effects\n if(window.stx&&window.stx._cleanupContainer){\n window.stx._cleanupContainer(currentContent);\n }\n\n function doSwap(){\n // ── Swap <head> styles ──\n // Inject new styles FIRST, then remove old to prevent unstyled flash\n var keepIds={'stx-view-transitions':1,'stx-r-css':1};\n var curStyles=document.querySelectorAll('head style');\n var newStyles=doc.querySelectorAll('head style');\n\n // Merge crosswind styles instead of replacing — persistent elements\n // (nav, footer) outside <main> still need their utility classes\n var curCrosswind=document.querySelector('head style[data-crosswind]');\n var newCrosswind=null;\n newStyles.forEach(function(s){if(s.getAttribute('data-crosswind'))newCrosswind=s});\n\n if(curCrosswind&&newCrosswind){\n var merged=mergeCrosswindCSS(curCrosswind.textContent||'',newCrosswind.textContent||'');\n if(merged)curCrosswind.textContent=merged;\n }\n\n var incoming=[];\n newStyles.forEach(function(s){\n if(!keepIds[s.id]&&!s.getAttribute('data-crosswind')){\n var ns=document.createElement('style');\n ns.textContent=s.textContent;\n ns.setAttribute('data-stx-incoming','');\n document.head.appendChild(ns);\n incoming.push(ns);\n }\n });\n\n // If no existing crosswind but new page has one, add it\n if(!curCrosswind&&newCrosswind){\n var ns=document.createElement('style');\n ns.textContent=newCrosswind.textContent;\n ns.setAttribute('data-crosswind',newCrosswind.getAttribute('data-crosswind'));\n document.head.appendChild(ns);\n }\n\n // Remove old styles (except persistent ones, crosswind, and incoming)\n curStyles.forEach(function(s){\n if(!keepIds[s.id]&&!s.hasAttribute('data-stx-incoming')&&!s.hasAttribute('data-crosswind'))s.remove();\n });\n\n incoming.forEach(function(s){s.removeAttribute('data-stx-incoming')});\n\n // ── Swap content ──\n // For layout changes: swap the entire <body> to replace layout chrome (nav, footer, etc.)\n // For same-layout: swap only the container (<main>)\n var newBody=doc.querySelector('body');\n var isLayoutChange=false;\n if(newBody){\n var newMeta=doc.querySelector('meta[name=\"stx-layout\"]');\n var curMeta=document.querySelector('meta[name=\"stx-layout\"]');\n var curLayout=curMeta?curMeta.getAttribute('content'):'';\n var newLayout=newMeta?newMeta.getAttribute('content'):'';\n var curGroup=getCurrentLayoutGroup();\n var newGroup=getDocLayoutGroup(doc,newLayout);\n isLayoutChange=curGroup!==newGroup||(curLayout&&newLayout&&curLayout!==newLayout);\n }\n if(isLayoutChange&&newBody){\n log('[router] full body swap for layout change');\n // Replace entire body content — layout chrome and all\n var bodyHTML=newBody.innerHTML.replace(new RegExp('<scr'+'ipt\\\\\\\\b[^>]*>[\\\\\\\\s\\\\\\\\S]*?<\\\\\\\\/scr'+'ipt\\\\\\\\s*>','gi'),'');\n document.body.innerHTML=bodyHTML;\n // Copy body attributes (class, data-stx, etc.)\n Array.from(newBody.attributes).forEach(function(attr){document.body.setAttribute(attr.name,attr.value)});\n // Update layout meta tag\n var oldMeta=document.querySelector('meta[name=\"stx-layout\"]');\n var freshMeta=doc.querySelector('meta[name=\"stx-layout\"]');\n if(oldMeta&&freshMeta)oldMeta.setAttribute('content',freshMeta.getAttribute('content')||'');\n else if(freshMeta){var m=document.createElement('meta');m.name='stx-layout';m.content=freshMeta.getAttribute('content')||'';document.head.appendChild(m)}\n var oldGroupMeta=document.querySelector('meta[name=\"stx-layout-group\"]');\n var freshGroupMeta=doc.querySelector('meta[name=\"stx-layout-group\"]');\n if(oldGroupMeta&&freshGroupMeta)oldGroupMeta.setAttribute('content',freshGroupMeta.getAttribute('content')||'');\n else if(freshGroupMeta){var gm=document.createElement('meta');gm.name='stx-layout-group';gm.content=freshGroupMeta.getAttribute('content')||'';document.head.appendChild(gm)}\n // Update container reference for script execution below\n currentContent=document.querySelector(containerSel)||document.querySelector('main')||document.body;\n } else {\n // Same layout — swap only container content\n var cleanHTML=newContent.innerHTML.replace(new RegExp('<scr'+'ipt\\\\\\\\b[^>]*>[\\\\\\\\s\\\\\\\\S]*?<\\\\\\\\/scr'+'ipt\\\\\\\\s*>','gi'),'');\n currentContent.innerHTML=cleanHTML;\n }\n\n // ── Load new external <head> scripts ──\n var loadedSrcs={};\n document.querySelectorAll('head script[src]').forEach(function(s){loadedSrcs[s.src]=1});\n var extPromises=[];\n doc.querySelectorAll('head script[src]').forEach(function(s){\n var src=new URL(s.getAttribute('src'),location.origin).href;\n if(loadedSrcs[src])return;\n loadedSrcs[src]=1;\n extPromises.push(new Promise(function(resolve,reject){\n var ns=document.createElement('script');\n ns.src=src;\n ns.onload=resolve;\n ns.onerror=reject;\n document.head.appendChild(ns);\n }));\n });\n\n // ── Script re-execution ──\n // Remove previously injected page scripts\n document.querySelectorAll('script[data-stx-page]').forEach(function(s){s.remove()});\n\n var scripts=[];\n if(isLayoutChange){\n // Layout change: collect ALL scripts from the new document body\n // (layout scripts, component mounts, setup functions — everything)\n var newBodyEl=doc.querySelector('body');\n if(newBodyEl){\n newBodyEl.querySelectorAll('script').forEach(function(s){\n var text=s.textContent||'';\n if(s.hasAttribute('src'))return;\n if(!text.trim())return;\n // Skip the signals runtime IIFE — it's already loaded\n if(text.indexOf(\"'use strict';var cloakStyle\")!==-1)return;\n if(text.indexOf('__stxRouter')!==-1)return;\n scripts.push(text);\n });\n }\n // Also collect setup functions from <head>\n doc.querySelectorAll('head script').forEach(function(s){\n var text=s.textContent||'';\n if(s.hasAttribute('src'))return;\n if(!text.trim())return;\n if(text.indexOf('__stx_setup_')!==-1)scripts.push(text);\n });\n } else {\n // Same layout: collect scripts from the container\n newContent.querySelectorAll('script').forEach(function(s){\n var text=s.textContent||'';\n if(s.hasAttribute('src'))return;\n if(!text.trim())return;\n scripts.push(text);\n });\n // Collect setup scripts from <head> AND <body> (outside container).\n // SSG builds place the setup function in <body> before <main>, not\n // in <head>. Without this, SPA navigation on static sites never\n // runs the setup and reactive data stays empty.\n var seenSetups={};\n scripts.forEach(function(t){if(t.indexOf('__stx_setup_')!==-1)seenSetups[t.substring(0,80)]=1});\n doc.querySelectorAll('script').forEach(function(s){\n var text=s.textContent||'';\n if(s.hasAttribute('src'))return;\n if(!text.trim())return;\n if(text.indexOf('__stx_setup_')===-1)return;\n // Skip signals runtime and router (they contain __stx_setup references but aren't setup functions)\n if(text.indexOf(\"'use strict';var cloakStyle\")!==-1)return;\n if(text.indexOf('__stxRouter')!==-1)return;\n var key=text.substring(0,80);\n if(seenSetups[key])return;\n seenSetups[key]=1;\n scripts.push(text);\n });\n }\n\n // Push history state (before active link updates so location.pathname is current)\n if(pushState!==false)history.pushState({},'',url+(hash||''));\n\n // Update active nav links\n updateNav(url);\n updateActiveLinks();\n\n // Scroll\n if(o.scrollToTop&&!hash)window.scrollTo({top:0,behavior:'instant'});\n else if(hash){var el=document.querySelector(hash);if(el)el.scrollIntoView({behavior:'smooth'})}\n\n // Update title\n var newTitle=doc.querySelector('title');\n if(newTitle)document.title=newTitle.textContent;\n\n // Update <html lang> from the destination doc so screen readers,\n // CSS :lang() selectors, and any i18n picker that mirrors\n // document.documentElement.lang stay accurate after SPA hops.\n if(doc.documentElement&&doc.documentElement.lang){\n document.documentElement.lang=doc.documentElement.lang;\n }\n\n window.dispatchEvent(new CustomEvent('stx:navigate',{detail:{url:url}}));\n\n // Execute page scripts FIRST — they define setup functions and set _latestSetup\n function execScripts(){\n scripts.forEach(function(text){\n // Skip scripts that were already executed (layout-level partials\n // like theme.stx). Their top-level const/function declarations\n // would throw \"Identifier has already been declared\" on re-execution.\n // Exception: setup functions (__stx_setup_) must always re-execute\n // because each page has its own setup, and import statements\n // need special handling.\n var h=hashScript(text);\n var isSetup=text.indexOf('__stx_setup_')!==-1;\n var hasImport=text.indexOf('import ')!==-1;\n if(!isSetup&&executedScriptHashes[h])return;\n executedScriptHashes[h]=1;\n // Wrap scripts with import statements as modules (Bug 3 fix)\n var ns=document.createElement('script');\n if(hasImport){\n ns.type='module';\n }\n // Wrap in block scope to prevent const/let collisions on re-navigation.\n // Top-level const/let in <script> tags are global-scoped in browsers\n // and throw \"Identifier has already been declared\" on re-execution.\n var alreadyScoped=text.trimStart().charAt(0)==='('||text.trimStart().charAt(0)===';'||text.indexOf('window.stx.mount')>-1;\n ns.textContent=alreadyScoped?text:'{'+text+'}';\n ns.setAttribute('data-stx-page','');\n document.body.appendChild(ns);\n });\n // THEN fire stx:load — now _latestSetup is set and processElement has the right scope\n window.dispatchEvent(new Event('stx:load'));\n }\n\n if(extPromises.length>0){\n Promise.all(extPromises).then(execScripts).catch(execScripts);\n }\nelse {\n execScripts();\n }\n }\n\n if(o.viewTransitions&&document.startViewTransition){\n document.startViewTransition(doSwap);\n }\nelse {\n // Fallback fade for browsers without View Transitions API\n currentContent.style.transition='opacity 0.12s ease-out';\n currentContent.style.opacity='0';\n setTimeout(function(){\n doSwap();\n currentContent.style.opacity='1';\n setTimeout(function(){currentContent.style.transition=''},150);\n },120);\n }\n }\n\n // ── Link interception ──\n function shouldIntercept(link){\n if(!link)return false;\n var href=link.getAttribute('href');\n if(!href)return false;\n if(href.startsWith('http')||href.startsWith('#')||href.startsWith('mailto:')||href.startsWith('tel:')||href.startsWith('javascript:'))return false;\n if(link.target==='_blank')return false;\n if(link.hasAttribute('data-stx-no-router')||link.hasAttribute('data-no-router')||link.hasAttribute('download'))return false;\n if(href===location.pathname)return false;\n if(!getContainer())return false;\n return true;\n }\n\n // SPA click handling. By default only [data-stx-link] elements get\n // SPA navigation; regular <a href> does native full page reload. Set\n // interceptAllLinks:true (window.__stxRouterConfig or build-time\n // config) to intercept any same-origin anchor — used by static-site\n // mode where every page is part of the same SPA shell.\n document.addEventListener('click',function(e){\n if(e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||e.button!==0)return;\n if(!e.target||!e.target.closest)return;\n var link=e.target.closest('[data-stx-link]');\n if(!link&&o.interceptAllLinks){\n var anchor=e.target.closest('a[href]');\n if(anchor&&shouldIntercept(anchor))link=anchor;\n }\n if(!link){return}\n var href=link.getAttribute('href');\n log('[router] click intercepted:',href,'container:',!!getContainer(),'defaultPrevented:',e.defaultPrevented);\n if(!href||href.startsWith('http')||href.startsWith('#')||href.startsWith('mailto:')||href.startsWith('tel:')){log('[router] skipped:',href);return}\n if(link.target==='_blank'||link.hasAttribute('download'))return;\n e.preventDefault();\n e.stopPropagation();\n log('[router] navigating to:',href);\n navigate(href);\n },true);\n\n // ── Back/forward ──\n window.addEventListener('popstate',function(){\n navigate(location.pathname+location.search+location.hash,false);\n });\n\n // ── Prefetch on hover ──\n if(o.prefetch){\n document.addEventListener('mouseover',function(e){\n if(!e.target||!e.target.closest)return;\n var link=e.target.closest('[data-stx-link]');\n if(!link)return;\n var href=link.getAttribute('href');\n var key=cacheKey(href);\n if(cache[key]||prefetching[key])return;\n prefetching[key]=true;\n fetch(href,{headers:{'X-STX-Router':'true','Accept':'text/html'}}).then(function(r){\n var isFrag=r.headers.get('X-STX-Fragment')==='true';\n var pLayout=r.headers.get('X-STX-Layout')||'';\n var pGroup=r.headers.get('X-STX-Layout-Group')||'';\n return r.text().then(function(html){return{html:isFrag?'<!--stx-fragment-->'+html:html,layout:pLayout,layoutGroup:pGroup}});\n }).then(function(result){\n if(o.cache){cache[key]=result.html;layoutCache[key]=result.layout;layoutGroupCache[key]=result.layoutGroup}\n }).catch(function(){}).finally(function(){delete prefetching[key]});\n },true);\n }\n\n // ── Active link management ──\n function updateNav(url){\n document.querySelectorAll('nav a[href], #mobileNav a[href], [data-stx-nav] a[href]').forEach(function(a){\n var href=a.getAttribute('href');\n if(!href||href.startsWith('#')||href.startsWith('http'))return;\n var isActive=(href===url)||(href==='/'&&url==='/');\n if(a.hasAttribute('data-stx-link')){\n var ac=a.getAttribute('data-stx-active-class')||'active';\n if(isActive)ac.split(' ').forEach(function(cls){if(cls)a.classList.add(cls)});else ac.split(' ').forEach(function(cls){if(cls)a.classList.remove(cls)});\n }\n });\n }\n\n function updateActiveLinks(){\n // Update active classes on <stx-link> elements (and legacy data-stx-link)\n var links=document.querySelectorAll('[data-stx-link]');\n var cur=location.pathname;\n links.forEach(function(link){\n var href=link.getAttribute('to')||link.getAttribute('href')||'';\n var ac=link.getAttribute('active-class')||link.getAttribute('data-stx-active-class')||'active';\n var eac=link.getAttribute('exact-active-class')||link.getAttribute('data-stx-exact-active-class')||'exact-active';\n ac.split(' ').forEach(function(cls){if(cls)link.classList.remove(cls)});\n eac.split(' ').forEach(function(cls){if(cls)link.classList.remove(cls)});\n var isExact=cur===href;\n var isActive=href!=='/'?cur.startsWith(href):cur==='/';\n if(isExact)eac.split(' ').forEach(function(cls){if(cls)link.classList.add(cls)});\n if(isActive)ac.split(' ').forEach(function(cls){if(cls)link.classList.add(cls)});\n });\n }\n\n // ── Progress bar DOM + style ──\n // Injects a fixed-position element at the top of the viewport plus the\n // minimal CSS for its transform/opacity transitions. Kept idempotent so\n // repeated init() calls (e.g. after full-body swaps) don't duplicate.\n // Also ships the default View Transitions fade+slide CSS when\n // viewTransitions is enabled and the browser supports it. Apps can\n // override by defining more specific ::view-transition-* rules later in\n // the cascade, or opt out entirely with viewTransitions:false.\n function injectStyles(){\n if(!document.getElementById('stx-r-css')){\n var s=document.createElement('style');s.id='stx-r-css';\n // Strip characters that could escape our CSS block and inject new\n // declarations: ; { } ( ) \" ' \\\\ < > plus whitespace control chars.\n // This keeps the value safe to concat into a stylesheet even if a\n // caller wires the config from an untrusted source.\n var sanitize=function(v){return String(v).replace(/[;{}()\"'\\\\\\\\<>\\\\n\\\\r\\\\t]/g,'')};\n var pc=sanitize(o.progressColor);\n var ph=sanitize(o.progressHeight);\n var css='.stx-navigating{cursor:wait}.stx-navigating a,.stx-navigating button{pointer-events:none}#stx-router-progress{position:fixed;top:0;left:0;right:0;height:'+ph+';background:'+pc+';box-shadow:0 0 8px '+pc+',0 0 4px '+pc+';transform:scaleX(0);transform-origin:left;transition:transform .18s ease-out,opacity .26s ease;opacity:0;pointer-events:none;z-index:999999}';\n if(o.viewTransitions&&'startViewTransition' in document){\n var dur=(o.viewTransitionDuration||220)+'ms';\n var ease=o.viewTransitionEasing||'cubic-bezier(0.16, 1, 0.3, 1)';\n css+='::view-transition-old(root),::view-transition-new(root){animation-duration:'+dur+';animation-timing-function:'+ease+'}';\n css+='::view-transition-old(root){animation-name:stx-r-fade-out}::view-transition-new(root){animation-name:stx-r-fade-in}';\n css+='@keyframes stx-r-fade-out{from{opacity:1;transform:translateY(0)}to{opacity:0;transform:translateY(-4px)}}';\n css+='@keyframes stx-r-fade-in{from{opacity:0;transform:translateY(6px)}to{opacity:1;transform:translateY(0)}}';\n css+='@media (prefers-reduced-motion: reduce){::view-transition-old(root),::view-transition-new(root){animation-duration:0s;animation-name:none}}';\n }\n s.textContent=css;\n document.head.appendChild(s);\n }\n if(o.progress&&!document.getElementById('stx-router-progress')){\n var el=document.createElement('div');\n el.id='stx-router-progress';\n el.setAttribute('role','progressbar');\n el.setAttribute('aria-hidden','true');\n // Append to <html>, not <body>: when the router swaps the body\n // (container:'body' for full-page static-site SPAs) the progress\n // element gets wiped along with it. <html> stays put across\n // swaps, so the bar survives multi-hop navigation.\n document.documentElement.appendChild(el);\n progEl=el;\n } else if(o.progress){\n progEl=document.getElementById('stx-router-progress');\n }\n }\n\n function injectViewTransitionCSS(){\n if(document.getElementById('stx-view-transitions'))return;\n var s=document.createElement('style');s.id='stx-view-transitions';\n s.textContent='::view-transition-group(root){animation:none}::view-transition-old(root){animation:none}::view-transition-new(root){animation:none}main,#app-content,[data-stx-content]{view-transition-name:stx-content}::view-transition-old(stx-content){animation:stx-fade-out .15s ease-out both}::view-transition-new(stx-content){animation:stx-fade-in .15s ease-in .1s both}@keyframes stx-fade-out{from{opacity:1}to{opacity:0}}@keyframes stx-fade-in{from{opacity:0}to{opacity:1}}::view-transition{background:transparent}::view-transition-group(stx-content){background:inherit;overflow:hidden}';\n (document.head||document.documentElement).appendChild(s);\n }\n\n // ── Public API ──\n var router={\n navigate:navigate,\n navigateTo:navigate,\n prefetch:function(url){\n var key=cacheKey(url);\n if(!cache[key]){\n fetch(url,{headers:{'X-STX-Router':'true'}}).then(function(r){var isFrag=r.headers.get('X-STX-Fragment')==='true';var pLayout=r.headers.get('X-STX-Layout')||'';var pGroup=r.headers.get('X-STX-Layout-Group')||'';return r.text().then(function(html){return{html:isFrag?'<!--stx-fragment-->'+html:html,layout:pLayout,layoutGroup:pGroup}})}).then(function(result){cache[key]=result.html;layoutCache[key]=result.layout;layoutGroupCache[key]=result.layoutGroup}).catch(function(){});\n }\n },\n clearCache:function(){for(var k in cache)delete cache[k];for(var lk in layoutCache)delete layoutCache[lk];for(var gk in layoutGroupCache)delete layoutGroupCache[gk]},\n cache:cache,\n swap:swap,\n updateNav:updateNav\n };\n\n window.__stxRouter=router;\n window.stxRouter=router;\n if(window.stx)window.stx.router=router;\n\n // ── Initialize ──\n function init(){\n injectStyles();\n injectViewTransitionCSS();\n updateActiveLinks();\n updateNav(location.pathname);\n }\n\n if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',init);else init();\n})();\n`\n}\n"
|
|
6
|
+
],
|
|
7
|
+
"mappings": ";;AAmBO,SAAS,eAAe,GAAW;AAAA,EACxC,OAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;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AA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;",
|
|
8
|
+
"debugId": "A4C84E765CFC895664756E2164756E21",
|
|
9
|
+
"names": []
|
|
10
|
+
}
|
package/dist/codegen.js
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
// src/codegen.ts
|
|
3
|
+
import fs from "fs";
|
|
4
|
+
import path from "path";
|
|
5
|
+
function generateRouteTypes(routes, outputDir) {
|
|
6
|
+
const lines = [
|
|
7
|
+
"// Auto-generated by STX - do not edit",
|
|
8
|
+
'declare module "stx/routes" {',
|
|
9
|
+
" interface RouteMap {"
|
|
10
|
+
];
|
|
11
|
+
for (const route of routes) {
|
|
12
|
+
const paramEntries = [];
|
|
13
|
+
for (const p of route.params) {
|
|
14
|
+
const type = route.pattern.includes(`:${p}*`) ? "string[]" : "string";
|
|
15
|
+
paramEntries.push(`${p}: ${type}`);
|
|
16
|
+
}
|
|
17
|
+
const paramsStr = paramEntries.join("; ");
|
|
18
|
+
lines.push(` '${route.pattern}': { ${paramsStr} }`);
|
|
19
|
+
}
|
|
20
|
+
lines.push(" }", "}", "");
|
|
21
|
+
fs.mkdirSync(outputDir, { recursive: true });
|
|
22
|
+
fs.writeFileSync(path.join(outputDir, "route-types.d.ts"), lines.join(`
|
|
23
|
+
`));
|
|
24
|
+
}
|
|
25
|
+
function generateRouteManifest(routes, outputDir, pagesDir) {
|
|
26
|
+
const cwd = process.cwd();
|
|
27
|
+
const relativePages = path.relative(cwd, pagesDir);
|
|
28
|
+
const excludeDirs = ["components", "layouts", "partials"];
|
|
29
|
+
const pageRoutes = routes.filter((r) => !excludeDirs.some((dir) => r.pattern.startsWith(`/${dir}/`) || r.pattern === `/${dir}`));
|
|
30
|
+
const lines = [
|
|
31
|
+
"// Auto-generated by stx \u2014 do not edit",
|
|
32
|
+
`// Source: ${relativePages || "pages"}/`,
|
|
33
|
+
"",
|
|
34
|
+
"export const routes = ["
|
|
35
|
+
];
|
|
36
|
+
for (const route of pageRoutes) {
|
|
37
|
+
const relFile = path.relative(cwd, route.filePath).replace(/\\/g, "/");
|
|
38
|
+
const params = JSON.stringify(route.params);
|
|
39
|
+
const layoutStr = route.layout ? `, layout: '${path.relative(cwd, route.layout).replace(/\\/g, "/")}'` : "";
|
|
40
|
+
lines.push(` { pattern: '${route.pattern}', filePath: '${relFile}', isDynamic: ${route.isDynamic}, params: ${params}${layoutStr} },`);
|
|
41
|
+
}
|
|
42
|
+
lines.push("] as const", "");
|
|
43
|
+
lines.push("export type RouteName = typeof routes[number]['pattern']", "");
|
|
44
|
+
fs.mkdirSync(outputDir, { recursive: true });
|
|
45
|
+
fs.writeFileSync(path.join(outputDir, "routes.ts"), lines.join(`
|
|
46
|
+
`));
|
|
47
|
+
}
|
|
48
|
+
export {
|
|
49
|
+
generateRouteTypes,
|
|
50
|
+
generateRouteManifest
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
//# debugId=C5615717ED79810164756E2164756E21
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/codegen.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"import fs from 'node:fs'\nimport path from 'node:path'\nimport type { Route } from './types'\n\nexport function generateRouteTypes(routes: Route[], outputDir: string): void {\n const lines = [\n '// Auto-generated by STX - do not edit',\n 'declare module \"stx/routes\" {',\n ' interface RouteMap {',\n ]\n\n for (const route of routes) {\n const paramEntries: string[] = []\n for (const p of route.params) {\n const type = route.pattern.includes(`:${p}*`) ? 'string[]' : 'string'\n paramEntries.push(`${p}: ${type}`)\n }\n const paramsStr = paramEntries.join('; ')\n lines.push(` '${route.pattern}': { ${paramsStr} }`)\n }\n\n lines.push(' }', '}', '')\n\n fs.mkdirSync(outputDir, { recursive: true })\n fs.writeFileSync(path.join(outputDir, 'route-types.d.ts'), lines.join('\\n'))\n}\n\n/**\n * Generate a route manifest file (.stx/routes.ts).\n *\n * Produces a TypeScript module exporting the full route array with patterns,\n * file paths, params, and layout references. Similar to Nuxt's .nuxt/routes.mjs.\n */\nexport function generateRouteManifest(routes: Route[], outputDir: string, pagesDir: string): void {\n const cwd = process.cwd()\n const relativePages = path.relative(cwd, pagesDir)\n\n // Filter out non-page files (components, layouts, partials)\n const excludeDirs = ['components', 'layouts', 'partials']\n const pageRoutes = routes.filter(r =>\n !excludeDirs.some(dir => r.pattern.startsWith(`/${dir}/`) || r.pattern === `/${dir}`),\n )\n\n const lines = [\n '// Auto-generated by stx — do not edit',\n `// Source: ${relativePages || 'pages'}/`,\n '',\n 'export const routes = [',\n ]\n\n for (const route of pageRoutes) {\n const relFile = path.relative(cwd, route.filePath).replace(/\\\\/g, '/')\n const params = JSON.stringify(route.params)\n const layoutStr = route.layout\n ? `, layout: '${path.relative(cwd, route.layout).replace(/\\\\/g, '/')}'`\n : ''\n lines.push(` { pattern: '${route.pattern}', filePath: '${relFile}', isDynamic: ${route.isDynamic}, params: ${params}${layoutStr} },`)\n }\n\n lines.push('] as const', '')\n lines.push('export type RouteName = typeof routes[number][\\'pattern\\']', '')\n\n fs.mkdirSync(outputDir, { recursive: true })\n fs.writeFileSync(path.join(outputDir, 'routes.ts'), lines.join('\\n'))\n}\n"
|
|
6
|
+
],
|
|
7
|
+
"mappings": ";;AAAA;AACA;AAGO,S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,SACpB,cAAc,KAAK,SAAS,KAAK,MAAM,MAAM,EAAE,QAAQ,OAAO,GAAG,OACjE;AAAA,IACJ,MAAM,KAAK,iBAAiB,MAAM,wBAAwB,wBAAwB,MAAM,sBAAsB,SAAS,cAAc;AAAA,EACvI;AAAA,EAEA,MAAM,KAAK,cAAc,EAAE;AAAA,EAC3B,MAAM,KAAK,4DAA8D,EAAE;AAAA,EAE3E,GAAG,UAAU,WAAW,EAAE,WAAW,KAAK,CAAC;AAAA,EAC3C,GAAG,cAAc,KAAK,KAAK,WAAW,WAAW,GAAG,MAAM,KAAK;AAAA,CAAI,CAAC;AAAA;",
|
|
8
|
+
"debugId": "C5615717ED79810164756E2164756E21",
|
|
9
|
+
"names": []
|
|
10
|
+
}
|
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
// src/codegen.ts
|
|
3
|
+
import fs from "fs";
|
|
4
|
+
import path from "path";
|
|
5
|
+
function generateRouteTypes(routes, outputDir) {
|
|
6
|
+
const lines = [
|
|
7
|
+
"// Auto-generated by STX - do not edit",
|
|
8
|
+
'declare module "stx/routes" {',
|
|
9
|
+
" interface RouteMap {"
|
|
10
|
+
];
|
|
11
|
+
for (const route of routes) {
|
|
12
|
+
const paramEntries = [];
|
|
13
|
+
for (const p of route.params) {
|
|
14
|
+
const type = route.pattern.includes(`:${p}*`) ? "string[]" : "string";
|
|
15
|
+
paramEntries.push(`${p}: ${type}`);
|
|
16
|
+
}
|
|
17
|
+
const paramsStr = paramEntries.join("; ");
|
|
18
|
+
lines.push(` '${route.pattern}': { ${paramsStr} }`);
|
|
19
|
+
}
|
|
20
|
+
lines.push(" }", "}", "");
|
|
21
|
+
fs.mkdirSync(outputDir, { recursive: true });
|
|
22
|
+
fs.writeFileSync(path.join(outputDir, "route-types.d.ts"), lines.join(`
|
|
23
|
+
`));
|
|
24
|
+
}
|
|
25
|
+
function generateRouteManifest(routes, outputDir, pagesDir) {
|
|
26
|
+
const cwd = process.cwd();
|
|
27
|
+
const relativePages = path.relative(cwd, pagesDir);
|
|
28
|
+
const excludeDirs = ["components", "layouts", "partials"];
|
|
29
|
+
const pageRoutes = routes.filter((r) => !excludeDirs.some((dir) => r.pattern.startsWith(`/${dir}/`) || r.pattern === `/${dir}`));
|
|
30
|
+
const lines = [
|
|
31
|
+
"// Auto-generated by stx \u2014 do not edit",
|
|
32
|
+
`// Source: ${relativePages || "pages"}/`,
|
|
33
|
+
"",
|
|
34
|
+
"export const routes = ["
|
|
35
|
+
];
|
|
36
|
+
for (const route of pageRoutes) {
|
|
37
|
+
const relFile = path.relative(cwd, route.filePath).replace(/\\/g, "/");
|
|
38
|
+
const params = JSON.stringify(route.params);
|
|
39
|
+
const layoutStr = route.layout ? `, layout: '${path.relative(cwd, route.layout).replace(/\\/g, "/")}'` : "";
|
|
40
|
+
lines.push(` { pattern: '${route.pattern}', filePath: '${relFile}', isDynamic: ${route.isDynamic}, params: ${params}${layoutStr} },`);
|
|
41
|
+
}
|
|
42
|
+
lines.push("] as const", "");
|
|
43
|
+
lines.push("export type RouteName = typeof routes[number]['pattern']", "");
|
|
44
|
+
fs.mkdirSync(outputDir, { recursive: true });
|
|
45
|
+
fs.writeFileSync(path.join(outputDir, "routes.ts"), lines.join(`
|
|
46
|
+
`));
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// src/matcher.ts
|
|
50
|
+
import path2 from "path";
|
|
51
|
+
function filePathToPattern(filePath, pagesDir) {
|
|
52
|
+
const relativePath = path2.relative(pagesDir, filePath);
|
|
53
|
+
let route = relativePath.replace(/\.(stx|md)$/, "");
|
|
54
|
+
route = route.split(path2.sep).join("/");
|
|
55
|
+
if (route === "index") {
|
|
56
|
+
return "/";
|
|
57
|
+
}
|
|
58
|
+
if (route.endsWith("/index")) {
|
|
59
|
+
route = route.slice(0, -6);
|
|
60
|
+
}
|
|
61
|
+
route = route.replace(/\[\[([^\]]+)\]\]/g, ":$1?");
|
|
62
|
+
route = route.replace(/\[([^\]]+)\]/g, ":$1");
|
|
63
|
+
route = route.replace(/:\.\.\.([^/]+)/g, ":$1*");
|
|
64
|
+
return `/${route}`;
|
|
65
|
+
}
|
|
66
|
+
function patternToRegex(pattern) {
|
|
67
|
+
const params = [];
|
|
68
|
+
let regexStr = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&");
|
|
69
|
+
regexStr = regexStr.replace(/\/:([^/]+)\?/g, (_, name) => {
|
|
70
|
+
params.push(name);
|
|
71
|
+
return "(?:/([^/]+))?";
|
|
72
|
+
});
|
|
73
|
+
regexStr = regexStr.replace(/:([^/]+)\*/g, (_, name) => {
|
|
74
|
+
params.push(name);
|
|
75
|
+
return "(.+)";
|
|
76
|
+
});
|
|
77
|
+
regexStr = regexStr.replace(/:([^/]+)/g, (_, name) => {
|
|
78
|
+
params.push(name);
|
|
79
|
+
return "([^/]+)";
|
|
80
|
+
});
|
|
81
|
+
regexStr = `^${regexStr}$`;
|
|
82
|
+
return { regex: new RegExp(regexStr), params };
|
|
83
|
+
}
|
|
84
|
+
function matchRoute(pathname, routes) {
|
|
85
|
+
const normalizedPath = pathname === "" ? "/" : pathname;
|
|
86
|
+
for (const route of routes) {
|
|
87
|
+
const match = normalizedPath.match(route.regex);
|
|
88
|
+
if (match) {
|
|
89
|
+
const params = {};
|
|
90
|
+
route.params.forEach((name, index) => {
|
|
91
|
+
params[name] = match[index + 1];
|
|
92
|
+
});
|
|
93
|
+
return { route, params };
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
return null;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// src/nested-layouts.ts
|
|
100
|
+
import fs2 from "fs";
|
|
101
|
+
import path3 from "path";
|
|
102
|
+
function resolveLayoutChain(routeFilePath, pagesDir) {
|
|
103
|
+
const layouts = [];
|
|
104
|
+
let dir = path3.dirname(routeFilePath);
|
|
105
|
+
while (dir.startsWith(pagesDir) || dir === pagesDir) {
|
|
106
|
+
const layoutFile = path3.join(dir, "_layout.stx");
|
|
107
|
+
if (fs2.existsSync(layoutFile)) {
|
|
108
|
+
layouts.unshift(layoutFile);
|
|
109
|
+
}
|
|
110
|
+
if (dir === pagesDir)
|
|
111
|
+
break;
|
|
112
|
+
dir = path3.dirname(dir);
|
|
113
|
+
}
|
|
114
|
+
return layouts;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// src/file-router.ts
|
|
118
|
+
import fs3 from "fs";
|
|
119
|
+
import path4 from "path";
|
|
120
|
+
function scanDirectory(dir, extensions) {
|
|
121
|
+
const files = [];
|
|
122
|
+
if (!fs3.existsSync(dir)) {
|
|
123
|
+
return files;
|
|
124
|
+
}
|
|
125
|
+
const entries = fs3.readdirSync(dir, { withFileTypes: true });
|
|
126
|
+
for (const entry of entries) {
|
|
127
|
+
const fullPath = path4.join(dir, entry.name);
|
|
128
|
+
if (entry.isDirectory()) {
|
|
129
|
+
if (entry.name.startsWith(".")) {
|
|
130
|
+
continue;
|
|
131
|
+
}
|
|
132
|
+
files.push(...scanDirectory(fullPath, extensions));
|
|
133
|
+
} else if (entry.isFile()) {
|
|
134
|
+
const ext = path4.extname(entry.name);
|
|
135
|
+
if (extensions.includes(ext)) {
|
|
136
|
+
if (entry.name.startsWith("_") && entry.name !== "_layout.stx") {
|
|
137
|
+
continue;
|
|
138
|
+
}
|
|
139
|
+
if (entry.name === "_layout.stx") {
|
|
140
|
+
continue;
|
|
141
|
+
}
|
|
142
|
+
files.push(fullPath);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
return files;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
class Router {
|
|
150
|
+
routes;
|
|
151
|
+
pagesDir;
|
|
152
|
+
pagesDirs;
|
|
153
|
+
config;
|
|
154
|
+
constructor(baseDir, config = {}) {
|
|
155
|
+
this.config = config;
|
|
156
|
+
const rawDirs = config.pagesDirs && config.pagesDirs.length > 0 ? config.pagesDirs : [config.pagesDir || "pages"];
|
|
157
|
+
this.pagesDirs = rawDirs.map((d) => path4.resolve(baseDir, d));
|
|
158
|
+
this.pagesDir = this.pagesDirs[0];
|
|
159
|
+
const extensions = config.extensions || [".stx"];
|
|
160
|
+
const seenPatterns = new Set;
|
|
161
|
+
this.routes = [];
|
|
162
|
+
for (const dir of this.pagesDirs) {
|
|
163
|
+
const files = scanDirectory(dir, extensions);
|
|
164
|
+
for (const filePath of files) {
|
|
165
|
+
const pattern = filePathToPattern(filePath, dir);
|
|
166
|
+
if (seenPatterns.has(pattern))
|
|
167
|
+
continue;
|
|
168
|
+
seenPatterns.add(pattern);
|
|
169
|
+
const { regex, params } = patternToRegex(pattern);
|
|
170
|
+
const layouts = config.layouts !== false ? resolveLayoutChain(filePath, dir) : [];
|
|
171
|
+
this.routes.push({
|
|
172
|
+
pattern,
|
|
173
|
+
regex,
|
|
174
|
+
params,
|
|
175
|
+
filePath,
|
|
176
|
+
isDynamic: params.length > 0,
|
|
177
|
+
layout: layouts.length > 0 ? layouts[layouts.length - 1] : undefined
|
|
178
|
+
});
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
this.routes.sort((a, b) => {
|
|
182
|
+
if (!a.isDynamic && b.isDynamic)
|
|
183
|
+
return -1;
|
|
184
|
+
if (a.isDynamic && !b.isDynamic)
|
|
185
|
+
return 1;
|
|
186
|
+
const aSegments = a.pattern.split("/").length;
|
|
187
|
+
const bSegments = b.pattern.split("/").length;
|
|
188
|
+
if (aSegments !== bSegments)
|
|
189
|
+
return bSegments - aSegments;
|
|
190
|
+
return a.pattern.localeCompare(b.pattern);
|
|
191
|
+
});
|
|
192
|
+
const stxDir = path4.join(baseDir, ".stx");
|
|
193
|
+
generateRouteTypes(this.routes, stxDir);
|
|
194
|
+
generateRouteManifest(this.routes, stxDir, this.pagesDir);
|
|
195
|
+
}
|
|
196
|
+
match(pathname) {
|
|
197
|
+
const normalizedPath = pathname === "" ? "/" : pathname;
|
|
198
|
+
for (const route of this.routes) {
|
|
199
|
+
const m = normalizedPath.match(route.regex);
|
|
200
|
+
if (m) {
|
|
201
|
+
const params = {};
|
|
202
|
+
route.params.forEach((name, index) => {
|
|
203
|
+
params[name] = m[index + 1];
|
|
204
|
+
});
|
|
205
|
+
return { route, params };
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
return null;
|
|
209
|
+
}
|
|
210
|
+
resolve(name, params) {
|
|
211
|
+
const route = this.routes.find((r) => r.pattern === name || r.filePath.includes(name));
|
|
212
|
+
if (!route)
|
|
213
|
+
return "#not-found";
|
|
214
|
+
let resolved = route.pattern;
|
|
215
|
+
if (params) {
|
|
216
|
+
for (const [key, value] of Object.entries(params)) {
|
|
217
|
+
resolved = resolved.replace(`:${key}`, encodeURIComponent(value));
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
return resolved;
|
|
221
|
+
}
|
|
222
|
+
addRoute(route) {
|
|
223
|
+
this.routes.push(route);
|
|
224
|
+
this.routes.sort((a, b) => {
|
|
225
|
+
if (!a.isDynamic && b.isDynamic)
|
|
226
|
+
return -1;
|
|
227
|
+
if (a.isDynamic && !b.isDynamic)
|
|
228
|
+
return 1;
|
|
229
|
+
return a.pattern.localeCompare(b.pattern);
|
|
230
|
+
});
|
|
231
|
+
}
|
|
232
|
+
getLayout(route) {
|
|
233
|
+
return route.layout ?? null;
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
function createRouter(baseDir, config) {
|
|
237
|
+
return new Router(baseDir, config);
|
|
238
|
+
}
|
|
239
|
+
function findErrorPage(pagesDir, statusCode) {
|
|
240
|
+
const candidates = [`${statusCode}.stx`, "error.stx"];
|
|
241
|
+
for (const candidate of candidates) {
|
|
242
|
+
const filePath = path4.join(pagesDir, candidate);
|
|
243
|
+
if (fs3.existsSync(filePath))
|
|
244
|
+
return filePath;
|
|
245
|
+
}
|
|
246
|
+
return null;
|
|
247
|
+
}
|
|
248
|
+
function formatRoutes(routes, baseDir) {
|
|
249
|
+
return routes.map((route) => {
|
|
250
|
+
const relativePath = path4.relative(baseDir, route.filePath);
|
|
251
|
+
const dynamicLabel = route.isDynamic ? " (dynamic)" : "";
|
|
252
|
+
return `${route.pattern} \u2192 ${relativePath}${dynamicLabel}`;
|
|
253
|
+
});
|
|
254
|
+
}
|
|
255
|
+
export {
|
|
256
|
+
formatRoutes,
|
|
257
|
+
findErrorPage,
|
|
258
|
+
createRouter,
|
|
259
|
+
Router
|
|
260
|
+
};
|
|
261
|
+
|
|
262
|
+
//# debugId=288E1FC95396709A64756E2164756E21
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/codegen.ts", "../src/matcher.ts", "../src/nested-layouts.ts", "../src/file-router.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"import fs from 'node:fs'\nimport path from 'node:path'\nimport type { Route } from './types'\n\nexport function generateRouteTypes(routes: Route[], outputDir: string): void {\n const lines = [\n '// Auto-generated by STX - do not edit',\n 'declare module \"stx/routes\" {',\n ' interface RouteMap {',\n ]\n\n for (const route of routes) {\n const paramEntries: string[] = []\n for (const p of route.params) {\n const type = route.pattern.includes(`:${p}*`) ? 'string[]' : 'string'\n paramEntries.push(`${p}: ${type}`)\n }\n const paramsStr = paramEntries.join('; ')\n lines.push(` '${route.pattern}': { ${paramsStr} }`)\n }\n\n lines.push(' }', '}', '')\n\n fs.mkdirSync(outputDir, { recursive: true })\n fs.writeFileSync(path.join(outputDir, 'route-types.d.ts'), lines.join('\\n'))\n}\n\n/**\n * Generate a route manifest file (.stx/routes.ts).\n *\n * Produces a TypeScript module exporting the full route array with patterns,\n * file paths, params, and layout references. Similar to Nuxt's .nuxt/routes.mjs.\n */\nexport function generateRouteManifest(routes: Route[], outputDir: string, pagesDir: string): void {\n const cwd = process.cwd()\n const relativePages = path.relative(cwd, pagesDir)\n\n // Filter out non-page files (components, layouts, partials)\n const excludeDirs = ['components', 'layouts', 'partials']\n const pageRoutes = routes.filter(r =>\n !excludeDirs.some(dir => r.pattern.startsWith(`/${dir}/`) || r.pattern === `/${dir}`),\n )\n\n const lines = [\n '// Auto-generated by stx — do not edit',\n `// Source: ${relativePages || 'pages'}/`,\n '',\n 'export const routes = [',\n ]\n\n for (const route of pageRoutes) {\n const relFile = path.relative(cwd, route.filePath).replace(/\\\\/g, '/')\n const params = JSON.stringify(route.params)\n const layoutStr = route.layout\n ? `, layout: '${path.relative(cwd, route.layout).replace(/\\\\/g, '/')}'`\n : ''\n lines.push(` { pattern: '${route.pattern}', filePath: '${relFile}', isDynamic: ${route.isDynamic}, params: ${params}${layoutStr} },`)\n }\n\n lines.push('] as const', '')\n lines.push('export type RouteName = typeof routes[number][\\'pattern\\']', '')\n\n fs.mkdirSync(outputDir, { recursive: true })\n fs.writeFileSync(path.join(outputDir, 'routes.ts'), lines.join('\\n'))\n}\n",
|
|
6
|
+
"import path from 'node:path'\n\nexport function filePathToPattern(filePath: string, pagesDir: string): string {\n const relativePath = path.relative(pagesDir, filePath)\n let route = relativePath.replace(/\\.(stx|md)$/, '')\n\n route = route.split(path.sep).join('/')\n\n if (route === 'index') {\n return '/'\n }\n if (route.endsWith('/index')) {\n route = route.slice(0, -6)\n }\n\n // Convert [[param]] to :param? (optional) — BEFORE required params\n route = route.replace(/\\[\\[([^\\]]+)\\]\\]/g, ':$1?')\n\n // Convert [param] to :param\n route = route.replace(/\\[([^\\]]+)\\]/g, ':$1')\n\n // Convert [...param] to :param* (catch-all)\n route = route.replace(/:\\.\\.\\.([^/]+)/g, ':$1*')\n\n return `/${route}`\n}\n\nexport function patternToRegex(pattern: string): { regex: RegExp, params: string[] } {\n const params: string[] = []\n\n let regexStr = pattern.replace(/[.+^${}()|[\\]\\\\]/g, '\\\\$&')\n\n // Handle optional params (/:param?)\n regexStr = regexStr.replace(/\\/:([^/]+)\\?/g, (_, name) => {\n params.push(name)\n return '(?:/([^/]+))?'\n })\n\n // Handle catch-all params (:param*)\n regexStr = regexStr.replace(/:([^/]+)\\*/g, (_, name) => {\n params.push(name)\n return '(.+)'\n })\n\n // Handle regular params (:param)\n regexStr = regexStr.replace(/:([^/]+)/g, (_, name) => {\n params.push(name)\n return '([^/]+)'\n })\n\n regexStr = `^${regexStr}$`\n\n return { regex: new RegExp(regexStr), params }\n}\n\nexport function matchRoute(pathname: string, routes: { pattern: string, regex: RegExp, params: string[] }[]): { route: typeof routes[0], params: Record<string, string> } | null {\n const normalizedPath = pathname === '' ? '/' : pathname\n\n for (const route of routes) {\n const match = normalizedPath.match(route.regex)\n if (match) {\n const params: Record<string, string> = {}\n route.params.forEach((name, index) => {\n params[name] = match[index + 1]\n })\n return { route, params }\n }\n }\n\n return null\n}\n",
|
|
7
|
+
"import fs from 'node:fs'\nimport path from 'node:path'\n\nexport function resolveLayoutChain(routeFilePath: string, pagesDir: string): string[] {\n const layouts: string[] = []\n let dir = path.dirname(routeFilePath)\n\n // Walk up from the route's directory to the pages root, collecting _layout.stx files\n while (dir.startsWith(pagesDir) || dir === pagesDir) {\n const layoutFile = path.join(dir, '_layout.stx')\n if (fs.existsSync(layoutFile)) {\n layouts.unshift(layoutFile) // Prepend so root layout is first\n }\n\n if (dir === pagesDir) break\n dir = path.dirname(dir)\n }\n\n return layouts\n}\n",
|
|
8
|
+
"import fs from 'node:fs'\nimport path from 'node:path'\nimport type { Route, RouteMatch, RouterConfig } from './types'\nimport { generateRouteTypes, generateRouteManifest } from './codegen'\nimport { filePathToPattern, patternToRegex } from './matcher'\nimport { resolveLayoutChain } from './nested-layouts'\n\nfunction scanDirectory(dir: string, extensions: string[]): string[] {\n const files: string[] = []\n\n if (!fs.existsSync(dir)) {\n return files\n }\n\n const entries = fs.readdirSync(dir, { withFileTypes: true })\n\n for (const entry of entries) {\n const fullPath = path.join(dir, entry.name)\n\n if (entry.isDirectory()) {\n if (entry.name.startsWith('.')) {\n continue\n }\n files.push(...scanDirectory(fullPath, extensions))\n }\n else if (entry.isFile()) {\n const ext = path.extname(entry.name)\n if (extensions.includes(ext)) {\n // Skip layout files from being routes themselves\n if (entry.name.startsWith('_') && entry.name !== '_layout.stx') {\n continue\n }\n // Don't register _layout.stx as a route\n if (entry.name === '_layout.stx') {\n continue\n }\n files.push(fullPath)\n }\n }\n }\n\n return files\n}\n\nexport class Router {\n routes: Route[]\n private pagesDir: string\n private pagesDirs: string[]\n private config: RouterConfig\n\n constructor(baseDir: string, config: RouterConfig = {}) {\n this.config = config\n\n // Resolve the stack of page roots. `pagesDirs` wins when both are\n // set; otherwise fall back to the single-root `pagesDir`. Each\n // entry is resolved relative to `baseDir`.\n const rawDirs = (config.pagesDirs && config.pagesDirs.length > 0)\n ? config.pagesDirs\n : [config.pagesDir || 'pages']\n this.pagesDirs = rawDirs.map(d => path.resolve(baseDir, d))\n // For backwards compatibility, `pagesDir` keeps pointing at the\n // first root — that's the user-facing root for codegen output.\n this.pagesDir = this.pagesDirs[0]\n\n const extensions = config.extensions || ['.stx']\n\n // Scan each root and bucket files by their resulting URL pattern.\n // Earlier roots win, so a user's `resources/views/cart.stx` shadows\n // the framework's `storage/framework/defaults/resources/views/cart.stx`.\n const seenPatterns = new Set<string>()\n this.routes = []\n for (const dir of this.pagesDirs) {\n const files = scanDirectory(dir, extensions)\n for (const filePath of files) {\n const pattern = filePathToPattern(filePath, dir)\n if (seenPatterns.has(pattern))\n continue\n seenPatterns.add(pattern)\n\n const { regex, params } = patternToRegex(pattern)\n const layouts = config.layouts !== false ? resolveLayoutChain(filePath, dir) : []\n\n this.routes.push({\n pattern,\n regex,\n params,\n filePath,\n isDynamic: params.length > 0,\n layout: layouts.length > 0 ? layouts[layouts.length - 1] : undefined,\n })\n }\n }\n\n // Sort: static before dynamic, more segments first\n this.routes.sort((a, b) => {\n if (!a.isDynamic && b.isDynamic) return -1\n if (a.isDynamic && !b.isDynamic) return 1\n const aSegments = a.pattern.split('/').length\n const bSegments = b.pattern.split('/').length\n if (aSegments !== bSegments) return bSegments - aSegments\n return a.pattern.localeCompare(b.pattern)\n })\n\n // Generate type declarations and route manifest into .stx/\n const stxDir = path.join(baseDir, '.stx')\n generateRouteTypes(this.routes, stxDir)\n generateRouteManifest(this.routes, stxDir, this.pagesDir)\n }\n\n match(pathname: string): RouteMatch | null {\n const normalizedPath = pathname === '' ? '/' : pathname\n\n for (const route of this.routes) {\n const m = normalizedPath.match(route.regex)\n if (m) {\n const params: Record<string, string> = {}\n route.params.forEach((name, index) => {\n params[name] = m[index + 1]\n })\n return { route, params }\n }\n }\n\n return null\n }\n\n resolve(name: string, params?: Record<string, string>): string {\n const route = this.routes.find(r => r.pattern === name || r.filePath.includes(name))\n if (!route) return '#not-found'\n\n let resolved = route.pattern\n if (params) {\n for (const [key, value] of Object.entries(params)) {\n resolved = resolved.replace(`:${key}`, encodeURIComponent(value))\n }\n }\n return resolved\n }\n\n addRoute(route: Route): void {\n this.routes.push(route)\n this.routes.sort((a, b) => {\n if (!a.isDynamic && b.isDynamic) return -1\n if (a.isDynamic && !b.isDynamic) return 1\n return a.pattern.localeCompare(b.pattern)\n })\n }\n\n getLayout(route: Route): string | null {\n return route.layout ?? null\n }\n}\n\nexport function createRouter(baseDir: string, config?: RouterConfig): Router {\n return new Router(baseDir, config)\n}\n\nexport function findErrorPage(pagesDir: string, statusCode: number): string | null {\n const candidates = [`${statusCode}.stx`, 'error.stx']\n for (const candidate of candidates) {\n const filePath = path.join(pagesDir, candidate)\n if (fs.existsSync(filePath)) return filePath\n }\n return null\n}\n\nexport function formatRoutes(routes: Route[], baseDir: string): string[] {\n return routes.map((route) => {\n const relativePath = path.relative(baseDir, route.filePath)\n const dynamicLabel = route.isDynamic ? ' (dynamic)' : ''\n return `${route.pattern} → ${relativePath}${dynamicLabel}`\n })\n}\n"
|
|
9
|
+
],
|
|
10
|
+
"mappings": ";;AAAA;AACA;AAGO,SAAS,kBAAkB,CAAC,QAAiB,WAAyB;AAAA,EAC3E,MAAM,QAAQ;AAAA,IACZ;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAAA,EAEA,WAAW,SAAS,QAAQ;AAAA,IAC1B,MAAM,eAAyB,CAAC;A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AO,OAAO,IAAI,CAAC,UAAU;AAAA,IAC3B,MAAM,eAAe,MAAK,SAAS,SAAS,MAAM,QAAQ;AAAA,IAC1D,MAAM,eAAe,MAAM,YAAY,eAAe;AAAA,IACtD,OAAO,GAAG,MAAM,kBAAY,eAAe;AAAA,GAC5C;AAAA;",
|
|
11
|
+
"debugId": "288E1FC95396709A64756E2164756E21",
|
|
12
|
+
"names": []
|
|
13
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
export type { LayoutMetadata } from './layout-metadata';
|
|
1
2
|
// Types
|
|
2
3
|
export type {
|
|
3
4
|
AbortNavigationResult,
|
|
@@ -45,6 +46,7 @@ export {
|
|
|
45
46
|
} from './middleware';
|
|
46
47
|
// Nested layouts
|
|
47
48
|
export { resolveLayoutChain } from './nested-layouts';
|
|
49
|
+
export { deriveLayoutGroup, extractLayoutMetadata } from './layout-metadata';
|
|
48
50
|
// Route type generation
|
|
49
51
|
export { generateRouteTypes, generateRouteManifest } from './codegen';
|
|
50
52
|
// Client-side SPA navigation
|