@veluai/velu 0.1.9 → 0.1.12
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/README.md +1 -1
- package/dist/cli.js +91 -9
- package/package.json +55 -51
- package/runtime/velu-ui/components/ErrorCard.jsx +138 -0
- package/runtime/velu-ui/components/theme-toggle.css +101 -70
- package/runtime/velu-ui/index.js +1 -0
- package/runtime/velu-ui/lib/component-schemas.js +100 -0
- package/runtime/velu-ui/lib/copyText.js +1 -1
- package/runtime/velu-ui/mdx-components.jsx +24 -4
- package/src/lib/extract-mdx-error.js +170 -0
- package/src/lib/issues.js +159 -0
- package/src/lib/known-components.js +34 -0
- package/src/runtime/App.jsx +4 -1
- package/src/runtime/ErrorBoundary.jsx +54 -0
package/README.md
CHANGED
|
@@ -10,7 +10,7 @@ velu init my-docs
|
|
|
10
10
|
velu dev my-docs
|
|
11
11
|
```
|
|
12
12
|
|
|
13
|
-
Then open <http://localhost:
|
|
13
|
+
Then open <http://localhost:8358>. Editing any `.mdx` page or `velu.json`
|
|
14
14
|
reloads the browser automatically.
|
|
15
15
|
|
|
16
16
|
> Requires **Node.js 18+**. Prefer not to install globally? Use
|
package/dist/cli.js
CHANGED
|
@@ -1,11 +1,93 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
3
|
-
`,"utf-8");let
|
|
4
|
-
`)}var
|
|
2
|
+
var ut=Object.defineProperty;var b=(e,t)=>()=>(e&&(t=e(e=0)),t);var le=(e,t)=>{for(var o in t)ut(e,o,{get:t[o],enumerable:!0})};var Se={};le(Se,{initProject:()=>dt});import U from"node:fs/promises";import z from"node:path";import{fileURLToPath as ft}from"node:url";async function dt(e,t){try{if((await U.readdir(e)).length>0)throw new Error(`Directory "${t}" already exists and is not empty. Choose a different name or remove the folder first.`)}catch(s){if(s.code!=="ENOENT")throw s}await U.mkdir(e,{recursive:!0}),await U.cp(mt,e,{recursive:!0});let o=z.join(e,"velu.json"),n=JSON.parse(await U.readFile(o,"utf-8"));n.name=t,await U.writeFile(o,JSON.stringify(n,null,2)+`
|
|
3
|
+
`,"utf-8");let r=await $e(e);console.log(`[velu] created ${t}/`);for(let s of r)console.log(` ${s}`);console.log(""),console.log("Next steps:"),console.log(` cd ${t}`),console.log(" velu dev")}async function $e(e,t=e,o=[]){let n=await U.readdir(e,{withFileTypes:!0});for(let r of n){let s=z.join(e,r.name);r.isDirectory()?await $e(s,t,o):o.push(z.relative(t,s).split(z.sep).join("/"))}return o.sort()}var pt,mt,je=b(()=>{pt=z.dirname(ft(import.meta.url)),mt=z.resolve(pt,"..","templates","starter")});import{visit as gt}from"unist-util-visit";import{toString as ht}from"mdast-util-to-string";import vt from"github-slugger";import{valueToEstree as yt}from"estree-util-value-to-estree";function q(){return e=>{let t=new vt,o=[];gt(e,"heading",i=>{let a=ht(i);o.push({depth:i.depth,id:t.slug(a),label:a})});let n={children:[]},r=[{node:n,depth:0}];for(let i of o){for(;r.length>1&&r[r.length-1].depth>=i.depth;)r.pop();let a={id:i.id,label:i.label},l=r[r.length-1].node;l.children||(l.children=[]),l.children.push(a),r.push({node:a,depth:i.depth})}let s=n.children;e.children.unshift({type:"mdxjsEsm",value:"",data:{estree:{type:"Program",sourceType:"module",body:[{type:"ExportNamedDeclaration",specifiers:[],declaration:{type:"VariableDeclaration",kind:"const",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"toc"},init:yt(s)}]}}]}}})}}var ce=b(()=>{});import xt from"node:fs/promises";import Ae from"node:path";function ue(e={},t){let o=e.colors?.primary??wt;return{name:e.name??t??"docs",colors:{primary:o,light:e.colors?.light??o,dark:e.colors?.dark??o},favicon:e.favicon??null,font:{family:e.font?.family??bt},navigation:e.navigation??null}}async function Pe(e){let t=Ae.join(e,"velu.json"),o;try{o=await xt.readFile(t,"utf-8")}catch(r){throw r.code==="ENOENT"?new Error(`No velu.json found in ${e}. Run \`velu init <name>\` to scaffold one.`):r}let n;try{n=JSON.parse(o)}catch(r){throw new Error(`velu.json is not valid JSON: ${r.message}`)}return ue(n,Ae.basename(e))}function Ce(e){let{colors:t,font:o}=e;return[":root:root {",` --accent-color: ${t.light};`,` --font-sans: "${o.family}", sans-serif;`,"}",':root:root[data-theme="dark"] {',` --accent-color: ${t.dark};`,"}"].join(`
|
|
4
|
+
`)}var wt,bt,Ee=b(()=>{wt="#dc143c",bt="Google Sans Flex"});import kt from"github-slugger";import $t from"iso-639-1";function jt(e){let t=String(e).toLowerCase();return $t.getNativeName(t)||e}function X(e){return new kt().slug(String(e??""))}function At(e){let t=String(e).replace(/^\/+|\/+$/g,"").split("/").filter(Boolean);return t[t.length-1]==="index"&&t.pop(),"/"+t.join("/")}function B(e){let t={kind:"root",children:D(e??{})};return Oe(t.children),t}function D(e){let t=Array.isArray(e.anchors)?e.anchors.map(_t):[];if(Array.isArray(e.products))return[...t,...e.products.map(Pt)];if(Array.isArray(e.versions))return[...t,...e.versions.map(Ct)];if(Array.isArray(e.languages))return[...t,...e.languages.map(Et)];if(Array.isArray(e.tabs))return[...t,...e.tabs.map(Tt)];let o=[...t];return Array.isArray(e.groups)&&o.push(...e.groups.map(Te)),Array.isArray(e.pages)&&o.push(...e.pages.map(_e)),o}function Pt(e){return{kind:"product",label:e.name??e.product,slug:X(e.product),icon:e.icon,color:e.color,default:!!e.default,children:D(e)}}function Ct(e){return{kind:"version",label:e.version,slug:X(e.version),default:!!e.default,children:D(e)}}function Et(e){let t=String(e.language);return{kind:"language",code:t,label:jt(t),slug:X(t),default:!!e.default,children:D(e)}}function Tt(e){return{kind:"tab",label:e.tab,slug:X(e.tab),icon:e.icon,href:e.href,children:D(e)}}function _t(e){return{kind:"anchor",label:e.anchor,icon:e.icon,href:e.href,color:e.color}}function Te(e){let t=(e.pages??[]).map(_e);return e.root&&t.unshift({kind:"page",pagePath:e.root}),{kind:"group",label:e.group,icon:e.icon,expanded:!!e.expanded,root:e.root,children:t}}function _e(e){return typeof e=="string"?{kind:"page",pagePath:e}:Te(e)}function Oe(e){for(let t of St){let o=e.filter(n=>n.kind===t);o.length&&!o.some(n=>n.default)&&(o[0].default=!0)}for(let t of e)t.children&&Oe(t.children)}function Le(e){let t=[],o=(n,r,s)=>{if(n.kind==="page"){t.push({pagePath:n.pagePath,url:Ot(n.pagePath,r),ctx:{...r},ancestors:s,node:n});return}let i=r;n.kind==="product"?i={...r,product:n.default?null:n.slug}:n.kind==="version"?i={...r,version:n.default?null:n.slug}:n.kind==="language"&&(i={...r,language:n.default?null:n.slug});let a=n.kind==="root"?s:[...s,n];for(let l of n.children??[])o(l,i,a)};return o(e,{product:null,version:null,language:null},[]),t}function Ot(e,t){let o=[t.product,t.version,t.language].filter(Boolean),n=At(e).split("/").filter(Boolean);return"/"+[...o,...n].join("/")}var St,Y=b(()=>{St=["product","version","language"]});import Lt from"node:fs";import Ne from"node:path";function V(e,t){let o=[],n=[],r=new Set;for(let s of Le(e)){if(r.has(s.url)){o.push(`duplicate URL "${s.url}" (page "${s.pagePath}") \u2014 keeping the first occurrence`);continue}r.add(s.url);let i=s.pagePath.replace(/^\/+|\/+$/g,""),a=Ne.join(t,...i.split("/"))+".mdx",l=Lt.existsSync(a);l||o.push(`page "${s.pagePath}" \u2192 ${Ne.relative(t,a)} not found`),n.push({pagePath:s.pagePath,url:s.url,fileAbsPath:a,exists:l})}return{pageEntries:n,warnings:o}}var Q=b(()=>{Y()});import Nt from"node:fs";import ee from"node:path";function Re(e){return{name:"velu-site",resolveId(t){return t===Ie?Fe:null},load(t){return t!==Fe?null:Ft(e)}}}function Ft(e){let t={};try{t=JSON.parse(Nt.readFileSync(ee.join(e,"velu.json"),"utf-8"))}catch{}let o=B(t.navigation??{}),{pageEntries:n,warnings:r}=V(o,e);for(let l of r)console.warn(`[velu] nav: ${l}`);let s=[],i=[],a=0;for(let l of n)if(l.exists){let u=JSON.stringify(l.fileAbsPath.split(ee.sep).join("/")),c=JSON.stringify(ee.relative(e,l.fileAbsPath).split(ee.sep).join("/")),f=`__p${a++}`;s.push(`import * as ${f} from ${u};`),i.push(` ${JSON.stringify(l.url)}: { Component: ${f}.default, frontmatter: ${f}.frontmatter, toc: ${f}.toc, relPath: ${c} },`)}else i.push(` ${JSON.stringify(l.url)}: { missing: true },`);return["// AUTO-GENERATED by vite-plugin-velu-site. Do not edit.",s.join(`
|
|
5
5
|
`),"","export const pages = {",i.join(`
|
|
6
|
-
`),"};",`export const navigation = ${JSON.stringify(
|
|
7
|
-
`)}var
|
|
8
|
-
`)
|
|
9
|
-
${
|
|
10
|
-
|
|
11
|
-
`)
|
|
6
|
+
`),"};",`export const navigation = ${JSON.stringify(o)};`,""].join(`
|
|
7
|
+
`)}var Ie,Fe,Me=b(()=>{Y();Q();Ie="virtual:velu-site",Fe="\0"+Ie});function h(e){return{category:"render-crash",severity:"error",file:null,line:null,column:null,frame:null,title:"Something went wrong",detail:"",hint:"",suggestion:null,...e}}function It(e,t){if(e=String(e),t=String(t),e===t)return 0;if(!e.length)return t.length;if(!t.length)return e.length;let o=Array.from({length:t.length+1},(r,s)=>s),n=new Array(t.length+1);for(let r=1;r<=e.length;r++){n[0]=r;for(let s=1;s<=t.length;s++){let i=e[r-1]===t[s-1]?0:1;n[s]=Math.min(n[s-1]+1,o[s]+1,o[s-1]+i)}[o,n]=[n,o]}return o[t.length]}function te(e,t=[]){if(!e)return null;let o=String(e).toLowerCase(),n=null,r=1/0;for(let i of t){let a=It(o,String(i).toLowerCase());a<r&&(r=a,n=i)}let s=Math.min(3,Math.max(2,Math.floor(o.length/4)));return r<=s?n:null}function Rt(e,t){return e==="warning"?C(t,$.yellow,"\u26A0"):e==="info"?C(t,$.cyan,"\u2139"):C(t,$.red,"\u2716")}function pe(e,{color:t=!1}={}){let o=fe[e.category]||e.category,n=e.line?`${e.line}${e.column?`:${e.column}`:""}`:"",r=e.file?`${e.file}${n?`:${n}`:""}`:n,s=[];if(s.push(`${Rt(e.severity,t)} ${C(t,$.bold,o)}`+(r?` ${C(t,$.dim,r)}`:"")),e.title&&s.push(` ${e.title}`),e.detail&&e.detail!==e.title&&s.push(` ${C(t,$.dim,e.detail)}`),e.frame)for(let i of String(e.frame).split(`
|
|
8
|
+
`))s.push(` ${i}`);return e.suggestion&&s.push(` ${C(t,$.cyan,`Did you mean <${e.suggestion}>?`)}`),e.hint&&s.push(` ${C(t,$.dim,`\u2192 ${e.hint}`)}`),s.join(`
|
|
9
|
+
`)}function ne(e,{color:t=!1}={}){if(!e.length)return C(t,$.cyan,"\u2713 No issues found.");let o=new Map;for(let a of e){let l=a.file||"velu.json";o.has(l)||o.set(l,[]),o.get(l).push(a)}let n=[];for(let[a,l]of o){n.push(C(t,$.bold,a));for(let u of l)n.push(pe({...u,file:null},{color:t}).replace(/^/gm," "));n.push("")}let r=e.filter(a=>a.severity!=="warning"&&a.severity!=="info").length,s=e.length-r,i=`${r} error${r===1?"":"s"}`+(s?`, ${s} warning${s===1?"":"s"}`:"");return n.push(C(t,r?$.red:$.yellow,i)),n.join(`
|
|
10
|
+
`)}var fe,$,C,F=b(()=>{fe={"mdx-syntax":"MDX syntax",frontmatter:"Frontmatter","unknown-component":"Unknown component","invalid-props":"Invalid options","render-crash":"Render error","config-json":"velu.json","config-schema":"velu.json","config-nav":"Navigation","config-asset":"Asset"};$={reset:"\x1B[0m",red:"\x1B[31m",yellow:"\x1B[33m",cyan:"\x1B[36m",dim:"\x1B[2m",bold:"\x1B[1m"},C=(e,t,o)=>e?`${t}${o}${$.reset}`:o});function Mt(e){let t=e,o=0;for(;t&&t.cause&&o<3&&!(t.loc||t.line||/`[^`]+` to be defined/.test(t.message||""));)t=t.cause,o+=1;return t||e}function me(e,t){if(!e)return null;let o=Ue(e).replace(/[?#].*$/,""),n=t?Ue(t).replace(/\/+$/,""):"";return n&&o.toLowerCase().startsWith(n.toLowerCase())?o.slice(n.length).replace(/^\/+/,""):!/^([a-zA-Z]:\/|\/)/.test(o)&&!/node_modules/.test(o)?o:null}function Ut(e){return e?String(e).replace(/([a-zA-Z]:\\|\/)[^\s'"()]+/g,t=>/node_modules|[\\/]vite[\\/]|@veluai|velu-cli|velu-ui/.test(t)?"\u2026":t).trim():""}function zt(e){let t=/\((\d+):(\d+)(?:-\d+:\d+)?\)\s*$/.exec(String(e||""));return t?{line:Number(t[1]),column:Number(t[2])}:null}function Bt(e){return String(e||"").replace(/\s*\(\d+:\d+(?:-\d+:\d+)?\)\s*$/,"").trim()}function Gt(e,t){if(!e||!t)return null;let o=String(e);return/node_modules|[\\/]vite[\\/]|@veluai[\\/]/.test(o)?null:o}function H(e,t={}){let{projectDir:o="",knownComponents:n=[],file:r=null}=t,s=null;for(let E=e,A=0;E&&A<6;E=E.cause,A+=1)if(E.veluIssue){s=E.veluIssue;break}if(s)return h({...s,file:s.file||r});let i=Mt(e)||{},a=i.message||String(e||""),l=/Expected component `([^`]+)` to be defined/.exec(a);if(l){let E=l[1],A=/referenced in your code at `(\d+):(\d+)/.exec(a),G=/\bin `([^`]+)`/.exec(a),v=G?me(G[1],o):null;return h({category:"unknown-component",file:v||r,line:A?Number(A[1]):null,column:A?Number(A[2]):null,title:`<${E}> is not a built-in component`,detail:"",hint:"Components are built in \u2014 check the spelling and capitalization (you don\u2019t import them).",suggestion:te(E,n)})}let u=i.loc||(i.line!=null?{line:i.line,column:i.column,file:i.file}:null)||zt(i.reason||a),c=i.id||u&&u.file||i.file||null,f=me(c,o)||r,_=!!f&&me(c,o)!=null,d=Gt(i.frame,_||!!r),j=Ut(Bt(i.reason||a)),m=Vt.test(a),N=i.source==="remark-frontmatter"||/\byaml\b|frontmatter/i.test(a)||u&&u.line===1&&/unexpected|expected/i.test(a)&&/---/.test(a);return u||m||d&&_?h({category:N?"frontmatter":"mdx-syntax",file:f,line:u?u.line:null,column:u?u.column:null,frame:d,title:j||(N?"Invalid frontmatter":"MDX syntax error"),detail:"",hint:N?"Check the YAML between the --- markers \u2014 indentation, quotes, and colons.":"Make sure every <Component> has a matching closing tag and that { } braces are balanced."}):/\.map is not a function|is not iterable|reading '|undefined \(reading/i.test(a)?h({category:"invalid-props",file:f,title:"A component received an invalid value",detail:j,hint:"Check the props/options you passed to a component on this page."}):h({category:"render-crash",file:f,title:"This page failed to render",detail:j,hint:"Set VELU_DEBUG=1 for the full stack trace."})}var Ue,Vt,de=b(()=>{F();Ue=e=>String(e).replace(/\\/g,"/");Vt=/closing tag|unexpected closing|could not parse (?:expression|import|export)|unexpected character|unexpected end of|expected a closing|expected the closing|unexpected `|in expression|misnested|before name/i});function Jt(e){let t=fe[e.category]||e.category,o=e.file?`${e.file}${e.line?`:${e.line}${e.column?`:${e.column}`:""}`:""}`:"",n=[];return n.push('<div class="velu-err-card">'),n.push('<div class="velu-err-head">'),n.push(`<span class="velu-err-pill">${O(t)}</span>`),n.push("</div>"),e.title&&n.push(`<div class="velu-err-title">${O(e.title)}</div>`),o&&n.push(`<a class="velu-err-loc" title="${O(o)}">${O(o)}</a>`),e.detail&&n.push(`<div class="velu-err-detail">${O(e.detail)}</div>`),e.frame&&n.push(`<pre class="velu-err-frame">${O(e.frame)}</pre>`),e.suggestion&&n.push(`<div class="velu-err-suggest">Did you mean <code><${O(e.suggestion)}></code>?</div>`),e.hint&&n.push(`<div class="velu-err-hint">${O(e.hint)}</div>`),n.push("</div>"),n.join("")}function ge(e,t={}){let o=Array.isArray(e)?e:[e],n=t.title||(o.length>1?`${o.length} problems to fix`:"There\u2019s a problem to fix"),r=o.map(Jt).join(`
|
|
11
|
+
`);return`<!doctype html>
|
|
12
|
+
<html lang="en">
|
|
13
|
+
<head>
|
|
14
|
+
<meta charset="utf-8" />
|
|
15
|
+
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
16
|
+
<title>Velu \u2014 error</title>
|
|
17
|
+
<style>
|
|
18
|
+
:root { color-scheme: light dark; }
|
|
19
|
+
* { box-sizing: border-box; }
|
|
20
|
+
body {
|
|
21
|
+
margin: 0;
|
|
22
|
+
min-height: 100vh;
|
|
23
|
+
background: #f7f7f8;
|
|
24
|
+
color: #111827;
|
|
25
|
+
font: 15px/1.55 system-ui, -apple-system, Segoe UI, sans-serif;
|
|
26
|
+
padding: 6vh 5vw;
|
|
27
|
+
}
|
|
28
|
+
@media (prefers-color-scheme: dark) {
|
|
29
|
+
body { background: #0c0d10; color: #e7e7ea; }
|
|
30
|
+
.velu-err-card { background: rgba(239,68,68,0.08); }
|
|
31
|
+
.velu-err-frame { background: rgba(255,255,255,0.05); color: #e7e7ea; }
|
|
32
|
+
}
|
|
33
|
+
.velu-err-wrap { max-width: 820px; margin: 0 auto; }
|
|
34
|
+
.velu-err-brand { font-weight: 700; letter-spacing: -0.02em; opacity: 0.7; margin-bottom: 0.4rem; }
|
|
35
|
+
.velu-err-h { font-size: 1.6rem; font-weight: 700; margin: 0 0 1.4rem; letter-spacing: -0.02em; }
|
|
36
|
+
.velu-err-card {
|
|
37
|
+
border: 1px solid #ef4444;
|
|
38
|
+
border-radius: 10px;
|
|
39
|
+
background: rgba(239,68,68,0.06);
|
|
40
|
+
padding: 1rem 1.1rem;
|
|
41
|
+
margin: 0 0 1rem;
|
|
42
|
+
}
|
|
43
|
+
.velu-err-head { display: flex; gap: 0.6rem; align-items: center; flex-wrap: wrap; }
|
|
44
|
+
.velu-err-pill {
|
|
45
|
+
font: 600 11px/1 ui-monospace, monospace;
|
|
46
|
+
text-transform: uppercase; letter-spacing: 0.06em;
|
|
47
|
+
color: #ef4444; border: 1px solid #ef4444; border-radius: 999px;
|
|
48
|
+
padding: 4px 9px; white-space: nowrap;
|
|
49
|
+
}
|
|
50
|
+
.velu-err-loc {
|
|
51
|
+
display: inline-block;
|
|
52
|
+
margin-top: 0.7rem;
|
|
53
|
+
font: 600 15px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
|
|
54
|
+
color: #ef4444;
|
|
55
|
+
background: rgba(239,68,68,0.12);
|
|
56
|
+
border: 1px solid rgba(239,68,68,0.4);
|
|
57
|
+
border-radius: 7px;
|
|
58
|
+
padding: 7px 11px;
|
|
59
|
+
letter-spacing: 0.01em;
|
|
60
|
+
}
|
|
61
|
+
.velu-err-title { margin-top: 0.6rem; font-weight: 600; font-size: 1.05rem; }
|
|
62
|
+
.velu-err-detail { margin-top: 0.25rem; opacity: 0.7; }
|
|
63
|
+
.velu-err-frame {
|
|
64
|
+
margin: 0.75rem 0 0; padding: 0.75rem 0.9rem; overflow: auto;
|
|
65
|
+
background: rgba(0,0,0,0.05); border-radius: 6px;
|
|
66
|
+
font: 12.5px/1.5 ui-monospace, monospace;
|
|
67
|
+
}
|
|
68
|
+
.velu-err-suggest { margin-top: 0.75rem; }
|
|
69
|
+
.velu-err-suggest code, .velu-err-frame code { color: #ef4444; font-weight: 600; }
|
|
70
|
+
.velu-err-hint { margin-top: 0.6rem; opacity: 0.6; font-size: 0.92rem; }
|
|
71
|
+
.velu-err-foot { margin-top: 1.6rem; opacity: 0.5; font-size: 0.85rem; }
|
|
72
|
+
</style>
|
|
73
|
+
</head>
|
|
74
|
+
<body>
|
|
75
|
+
<div class="velu-err-wrap">
|
|
76
|
+
<div class="velu-err-brand">velu</div>
|
|
77
|
+
<h1 class="velu-err-h">${O(n)}</h1>
|
|
78
|
+
${r}
|
|
79
|
+
<div class="velu-err-foot">Fix the file and save \u2014 this page reloads automatically.</div>
|
|
80
|
+
</div>
|
|
81
|
+
</body>
|
|
82
|
+
</html>`}var O,ze=b(()=>{F();O=e=>String(e??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")});var I,he=b(()=>{I=["Callout","Card","CardGroup","Accordion","AccordionGroup","Columns","Field","Prompt","Steps","Step","Tree","Folder","File","Image","CodeBlock","CodeGroup","MethodBadge","ApiPath","TryItBar","ApiField","ApiClient","ApiSidebar"]});import ve from"node:fs";import oe from"node:path";import{fileURLToPath as qt}from"node:url";import Dt from"iso-639-1";function W(e,t){if(!t)return null;let o=e.indexOf(`"${t}"`);return o===-1?null:e.slice(0,o).split(`
|
|
83
|
+
`).length}function Wt(e,t){return t==null||t<0?null:e.slice(0,t).split(`
|
|
84
|
+
`).length}function Be(e,t){if(!t)return null;let o=e.indexOf(`"${t}"`);return o===-1?null:e.slice(0,o).split(`
|
|
85
|
+
`).length}function Kt(e,t,o){let n=[];return a(e,t,"",null),n;function r(l){if(l&&l.$ref){let u=l.$ref.replace(/^#\//,"").split("/"),c=o;for(let f of u)c=c?.[f];return c||{}}return l}function s(l){return Array.isArray(l)?"array":l===null?"null":typeof l}function i(l,u){let c=n.length;a(l,u,"",null,!0);let f=n.length===c;return f||(n.length=c),f}function a(l,u,c,f,_){let d=r(u);if(d){if(d.oneOf){d.oneOf.some(m=>i(l,m))||n.push({path:c,key:f,message:"value does not match any allowed shape"});return}if(d.type&&s(l)!==d.type){n.push({path:c,key:f,message:`expected ${d.type}, got ${s(l)}`});return}if(d.type==="string"&&d.minLength!=null&&l.length<d.minLength&&n.push({path:c,key:f,message:"must not be empty"}),d.type==="object"&&s(l)==="object"){for(let m of d.required||[])m in l||n.push({path:c?`${c}.${m}`:m,key:m,message:`missing required "${m}"`});let j=d.properties||{};if(d.additionalProperties===!1)for(let m of Object.keys(l))m in j||n.push({path:c?`${c}.${m}`:m,key:m,message:`unknown field "${m}"`});for(let[m,N]of Object.entries(j))m in l&&a(l[m],N,c?`${c}.${m}`:m,m,_)}d.type==="array"&&Array.isArray(l)&&d.items&&l.forEach((j,m)=>a(j,d.items,`${c}[${m}]`,f,_))}}}function Zt(e){if(typeof e!="string")return!1;let t=e.trim();return/^#([0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(t)||/^(rgb|rgba|hsl|hsla|color|oklch|lab|lch)\(/i.test(t)||/^[a-z][a-z0-9-]*$/i.test(t)}function re(e){let t=[],o=oe.join(e,"velu.json"),n;try{n=ve.readFileSync(o,"utf-8")}catch(i){return i.code==="ENOENT"?t.push(h({category:"config-json",file:"velu.json",title:"No velu.json found",hint:"Run `velu init <name>` to scaffold a project."})):t.push(h({category:"config-json",file:"velu.json",title:"Could not read velu.json"})),t}let r;try{r=JSON.parse(n)}catch(i){let a=/position (\d+)/.exec(i.message||""),l=a?Wt(n,Number(a[1])):null;return t.push(h({category:"config-json",file:"velu.json",line:l,title:"velu.json is not valid JSON",detail:String(i.message||"").replace(/\s+in JSON.*$/,""),hint:"Check for a trailing comma, a missing quote, or an unclosed brace."})),t}let s=null;try{s=JSON.parse(ve.readFileSync(Ht,"utf-8"))}catch{}if(s)for(let i of Kt(r,s,s)){let a=/^unknown field/.test(i.message);t.push(h({category:"config-schema",severity:a?"warning":"error",file:"velu.json",line:W(n,i.key),title:i.path?`${i.path}: ${i.message}`:i.message,hint:a?"Remove it, or check the spelling against the velu.json schema.":""}))}for(let i of["primary","light","dark"]){let a=r.colors?.[i];a!=null&&!Zt(a)&&t.push(h({category:"config-schema",severity:"warning",file:"velu.json",line:W(n,i),title:`colors.${i}: "${a}" doesn\u2019t look like a CSS color`,hint:"Use a hex value like #dc143c, an rgb()/hsl() function, or a CSS color name."}))}if(typeof r.favicon=="string"&&r.favicon.trim()){let i=oe.resolve(e,r.favicon.replace(/^\/+/,""));ve.existsSync(i)||t.push(h({category:"config-asset",file:"velu.json",line:W(n,"favicon"),title:`favicon not found: ${r.favicon}`,hint:"The path is relative to the project root."}))}if(r.navigation&&typeof r.navigation=="object"){let i;try{i=B(r.navigation)}catch(a){t.push(h({category:"config-nav",file:"velu.json",line:W(n,"navigation"),title:"navigation could not be processed",detail:String(a.message||"")})),i=null}if(i){let{pageEntries:a,warnings:l}=V(i,e);for(let u of l){let c=/not found$/.test(u),f=/page "([^"]+)"/.exec(u),_=f?Be(n,f[1]):null;t.push(h({category:"config-nav",severity:c?"error":"warning",file:"velu.json",line:_,title:u,hint:c?"Create the .mdx file, or remove the page from navigation.":""}))}Xt(i,n,t)}}return t}function Xt(e,t,o){let n=new Set,r=s=>{if(!(!s||typeof s!="object")){if(s.language&&!n.has(s.language)){n.add(s.language);let i=String(s.language).toLowerCase();Dt.validate(i)||o.push(h({category:"config-nav",severity:"warning",file:"velu.json",line:Be(t,s.language)||W(t,"language"),title:`"${s.language}" is not a valid ISO 639-1 language code`,hint:'Use a two-letter code like "en", "fr", or "ja".'}))}for(let i of Object.values(s))Array.isArray(i)?i.forEach(r):i&&typeof i=="object"&&r(i)}};r(e)}var Yt,Ht,ye=b(()=>{F();Y();Q();Yt=oe.dirname(qt(import.meta.url)),Ht=oe.resolve(Yt,"..","..","schema","velu.schema.json")});import Qt from"node:fs/promises";import en from"node:fs";import R from"node:path";import{fileURLToPath as tn,pathToFileURL as nn}from"node:url";import{compile as on}from"@mdx-js/mdx";import rn from"remark-frontmatter";import sn from"remark-mdx-frontmatter";import an from"remark-gfm";import ln from"rehype-slug";import{visit as cn}from"unist-util-visit";function xe(){if(ie)return ie;let e=R.dirname(tn(import.meta.url)),t=[R.resolve(e,"..","runtime","velu-ui"),R.resolve(e,"..","..","runtime","velu-ui"),R.resolve(e,"..","..","..","velu-ui","src")],o=null;for(let n of t){let r=R.join(n,"lib","component-schemas.js");if(en.existsSync(r)){o=r;break}}return ie=o?import(nn(o).href).then(n=>n.validateProps).catch(()=>null):Promise.resolve(null),ie}function un(e){let t={};for(let o of e.attributes||[])o.type==="mdxJsxAttribute"&&(o.value==null?t[o.name]=!0:typeof o.value=="string"&&(t[o.name]=o.value));return t}function fn(e,t){return()=>o=>{cn(o,n=>{if((n.type==="mdxJsxFlowElement"||n.type==="mdxJsxTextElement")&&typeof n.name=="string"&&/^[A-Z]/.test(n.name)&&!n.name.includes(".")&&e.push({name:n.name,props:un(n),line:n.position?.start?.line??null,column:n.position?.start?.column??null}),n.type==="mdxjsEsm"&&typeof n.value=="string")for(let r of n.value.matchAll(/\b([A-Z][A-Za-z0-9_]*)\b/g))t.add(r[1])})}}async function pn(e,t){let o=[],n;try{n=await Qt.readFile(t.fileAbsPath,"utf-8")}catch{return o}let r=R.relative(e,t.fileAbsPath).split(R.sep).join("/"),s=[],i=new Set;try{await on({value:n,path:t.fileAbsPath},{remarkPlugins:[rn,sn,an,q,fn(s,i)],rehypePlugins:[ln],providerImportSource:"@mdx-js/react"})}catch(c){return o.push(H(c,{projectDir:e,knownComponents:I,file:r})),o}let a=new Set(I),l=await xe(),u=new Set;for(let c of s)if(!i.has(c.name)){if(!a.has(c.name)){if(u.has(c.name))continue;u.add(c.name),o.push(h({category:"unknown-component",file:r,line:c.line,column:c.column,title:`<${c.name}> is not a built-in component`,hint:"Components are built in \u2014 check the spelling and capitalization (you don\u2019t import them).",suggestion:te(c.name,I)}));continue}if(l){let f=l(c.name,c.props,{checkRequired:!1});f&&o.push(h({...f,file:r,line:c.line,column:c.column}))}}return o}async function Ve(e,t){let o=t.filter(a=>a.exists),n=[],r=8,s=0;async function i(){for(;s<o.length;){let a=o[s++],l=await pn(e,a);for(let u of l)n.push(u)}}return await Promise.all(Array.from({length:Math.min(r,o.length)},i)),n}var ie,we=b(()=>{ce();F();de();he()});import{visit as mn}from"unist-util-visit";function dn(e,t){let o=Ge(e).replace(/[?#].*$/,""),n=Ge(t).replace(/\/+$/,"");return n&&o.toLowerCase().startsWith(n.toLowerCase())?o.slice(n.length).replace(/^\/+/,""):null}function Je(e,t){return()=>(o,n)=>{typeof e=="function"&&mn(o,r=>{if(r.type!=="mdxJsxFlowElement"&&r.type!=="mdxJsxTextElement"||typeof r.name!="string"||!/^[A-Z]/.test(r.name)||r.name.includes("."))return;let s={};for(let a of r.attributes||[])a.type==="mdxJsxAttribute"&&(a.value==null?s[a.name]=!0:typeof a.value=="string"&&(s[a.name]=a.value));let i=e(r.name,s,{checkRequired:!1});if(i){let a=new Error(i.title);throw a.veluIssue={...i,file:dn(n?.path,t),line:r.position?.start?.line??null,column:r.position?.start?.column??null},a.loc={line:a.veluIssue.line,column:a.veluIssue.column},a}})}}var Ge,qe=b(()=>{Ge=e=>String(e||"").replace(/\\/g,"/")});var Qe={};le(Qe,{startDevServer:()=>Mn});import De from"node:fs/promises";import Ye from"node:fs";import gn from"node:http";import{spawn as hn}from"node:child_process";import S from"node:path";import{fileURLToPath as vn}from"node:url";import{createRequire as yn}from"node:module";import xn from"chokidar";import wn from"express";import bn from"@tailwindcss/vite";import kn from"@vitejs/plugin-react";import $n from"@mdx-js/rollup";import Sn from"remark-frontmatter";import jn from"remark-mdx-frontmatter";import An from"remark-gfm";import Pn from"rehype-slug";import{createServer as Cn,searchForWorkspaceRoot as En}from"vite";function Nn(e){return`<link rel="stylesheet" href="${`https://fonts.googleapis.com/css2?family=${encodeURIComponent(e).replace(/%20/g,"+")}:wght@300;400;500;600;700&display=swap`}" />`}function We(e,t){let o=pe(e,{color:!!process.stderr.isTTY});console.error(`
|
|
86
|
+
`+o+`
|
|
87
|
+
`),process.env.VELU_DEBUG&&t&&console.error(t)}async function Ke(e){try{return await Pe(e)}catch{return ue({},S.basename(e))}}async function Ze(e,t){let o=await e.moduleGraph.getModuleByUrl(t,!0),n=new Map,r=new Set;async function s(i){if(!(!i||r.has(i.url))){if(r.add(i.url),i.id&&_n.test(i.id)){let a=i.url.includes("?")?"&":"?",l=await e.transformRequest(`${i.url}${a}direct`);l?.code&&n.set(i.url,l.code)}for(let a of i.importedModules)await s(a)}}return await s(o),[...n.values()].join(`
|
|
88
|
+
`)}function Rn(e,t){let o=()=>{process.stdout.isTTY&&!process.env.VELU_NO_BELL&&process.stdout.write("\x07")},n=process.stdout.isTTY,r=f=>n&&process.stdout.write(`\x1B]${f}\x1B\\`),s=()=>{r(`0;\u23F3 ${t}`),r("9;4;3;0")},i=()=>{r(`0;${t}`),r("9;4;0;0")};if(n&&process.once("exit",()=>r("9;4;0;0")),s(),!e)return console.log("Starting Velu\u2026"),{ready:f=>{console.log(`Velu ready \u2192 ${f}`),i(),o()}};let a="\x1B[38;2;220;20;60m",l="\x1B[0m";console.log("");for(let f of Fn)console.log(`${a}${f}${l}`);console.log("");let u=null;try{u=hn(process.execPath,["-e",In],{stdio:["ignore","inherit","ignore"]}),u.on("error",()=>{})}catch{}let c=()=>{if(u){try{u.kill()}catch{}u=null}};return process.once("exit",c),{ready:f=>{c(),process.stdout.write("\x1B[2K\r"),console.log(` \x1B[32m\u2713${l} Velu ready \u2192 \x1B[36m${f}${l}`),i(),o()}}}async function Mn(e){let t=!!process.env.VELU_PROFILE,o=performance.now(),n=(x,p)=>t&&console.log(`[velu-profile] ${x}: ${(performance.now()-p).toFixed(0)}ms`),r=Rn(!!process.stdout.isTTY&&!t,S.basename(e)),s=await Ke(e),i=a();function a(){let p=re(e).filter(w=>w.severity==="error"&&(w.category==="config-json"||w.category==="config-schema"));return p.length&&console.error(`
|
|
89
|
+
`+ne(p,{color:!!process.stderr.isTTY})+`
|
|
90
|
+
`),p}let l=e;try{l=Ye.realpathSync(e)}catch{}let u=0,c=x=>{let p=performance.now();if(p-u<500)return;u=p;let w=H(x,{projectDir:l,knownComponents:I});We(w,x)};process.on("unhandledRejection",c),process.on("uncaughtException",c);let _=yn(import.meta.url).resolve("@mdx-js/react"),d=S.resolve(K,"runtime","velu-ui"),j=Ye.existsSync(d)?d:S.resolve(K,"..","velu-ui","src"),m=[{find:"@mdx-js/react",replacement:_},{find:/^velu-ui$/,replacement:S.join(j,"index.js")},{find:/^velu-ui\//,replacement:j+"/"}],N=Number(process.env.PORT)||8358,E=await xe(),A=wn(),G=gn.createServer(A),v=await Cn({root:K,appType:"custom",logLevel:t?"info":"warn",plugins:[Re(e),$n({remarkPlugins:[Sn,jn,An,q,Je(E,e)],rehypePlugins:[Pn],providerImportSource:"@mdx-js/react"}),kn(),bn()],cacheDir:S.resolve(e,".velu","vite-cache"),optimizeDeps:{include:["react","react-dom","react-dom/client","react-router-dom","@mdx-js/react","lucide-react","prism-react-renderer","iso-639-1","github-slugger"],esbuildOptions:{loader:{".mdx":"jsx"}}},resolve:{alias:m,dedupe:["react","react-dom","@mdx-js/react"]},server:{middlewareMode:!0,fs:{allow:[En(K),e,l]},hmr:{server:G}}});n("vite server created",o),A.use(v.middlewares),A.get(He,async(x,p,w)=>{if(!s.favicon)return p.status(404).end();let g=S.resolve(e,s.favicon.replace(/^\//,""));p.sendFile(g,T=>{T&&p.status(404).end()})}),A.use("*",async(x,p,w)=>{let g=x.originalUrl,T=performance.now();if(i.length)return p.status(200).set({"Content-Type":"text/html"}).end(ge(i,{title:"Fix velu.json to continue"}));try{let y=performance.now(),P=await De.readFile(Xe,"utf-8");P=await v.transformIndexHtml(g,P),n(`transformIndexHtml ${g}`,y);let M="/src/runtime/server-entry.jsx";y=performance.now();let{render:Z}=await v.ssrLoadModule(M);n(`ssrLoadModule ${g} (1st req includes dep pre-bundle)`,y),y=performance.now();let k=await Z(g);n(`render ${g}`,y),y=performance.now();let J=await Ze(v,M);n(`collectSsrCss ${g}`,y);let ae=J?`<style data-velu-ssr>${J}</style>`:"",it=`<style data-velu-config>
|
|
91
|
+
${Ce(s)}
|
|
92
|
+
</style>`,st=On.has(s.font.family)?"":Nn(s.font.family),at=s.favicon?`<link rel="icon" href="${He}" />`:"",lt=[ae,it,st,at].filter(Boolean).join(`
|
|
93
|
+
`),ct=P.replace("<!--app-title-->",Ln(s.name)).replace("<!--app-head-->",lt).replace("<!--app-html-->",k);p.status(200).set({"Content-Type":"text/html"}).end(ct),n(`TOTAL ${g}`,T)}catch(y){v.ssrFixStacktrace(y);let P=H(y,{projectDir:l,knownComponents:I});We(P,y),p.status(200).set({"Content-Type":"text/html"}).end(ge([P]))}}),xn.watch(e,{ignoreInitial:!0,ignored:/(^|[\\/])(node_modules|\.git|\.velu)([\\/]|$)/,awaitWriteFinish:{stabilityThreshold:100,pollInterval:20}}).on("all",async(x,p)=>{console.log(`[velu-cli] content ${x}: ${S.relative(e,p)}`);let w=S.basename(p)==="velu.json",g=p.endsWith(".mdx"),T=w||g&&(x==="add"||x==="unlink");if(w&&(s=await Ke(e),i=a()),T)v.moduleGraph.invalidateAll();else if(g){let y=p.split(S.sep).join("/"),P=v.moduleGraph.getModulesByFile(y);if(P)for(let M of P)v.moduleGraph.invalidateModule(M)}v.ws.send({type:"full-reload"})});async function ke(x){let p=new Set,w=12,g=0,T=[],y=()=>g<w?(g+=1,Promise.resolve()):new Promise(k=>T.push(k)).then(()=>{g+=1}),P=()=>{g-=1,T.shift()?.()},M=k=>/[\\/]\.velu[\\/]vite-cache[\\/]|[\\/]deps[\\/]/.test(k)||/[\\/]node_modules[\\/]/.test(k)&&!/velu-ui/.test(k);async function Z(k){if(!(!k||p.has(k)||M(k))){p.add(k);try{await y();try{await v.transformRequest(k,{ssr:!1})}finally{P()}let J=await v.moduleGraph.getModuleByUrl(k,!1);J?.importedModules?.size&&await Promise.all([...J.importedModules].map(ae=>Z(ae.url)))}catch{}}}return await Z(x),p.size}G.listen(N,async()=>{let x=performance.now(),p=0;try{let{render:w}=await v.ssrLoadModule("/src/runtime/server-entry.jsx");await ke("/src/runtime/client-entry.jsx"),typeof v.waitForRequestsIdle=="function"&&await v.waitForRequestsIdle();let[g]=await Promise.allSettled([ke("/src/runtime/client-entry.jsx"),w("/"),v.transformIndexHtml("/",await De.readFile(Xe,"utf-8")),Ze(v,"/src/runtime/server-entry.jsx")]).then(T=>T.map(y=>y.status==="fulfilled"?y.value:0));p=g}catch(w){t&&console.log("[velu-profile] warmup error:",w?.message)}n(`cold-start warm-up (${p} client modules)`,x),r.ready(`http://localhost:${N}`)})}var Tn,_n,On,He,Ln,K,Xe,Fn,In,et=b(()=>{ce();Ee();Me();de();ze();F();he();ye();we();qe();Tn=S.dirname(vn(import.meta.url)),_n=/\.(css|less|sass|scss|styl|stylus|pcss|postcss)(\?|$)/,On=new Set(["Google Sans Flex","Google Sans Code","Outfit"]),He="/@velu-favicon",Ln=e=>String(e).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""");K=S.resolve(Tn,".."),Xe=S.resolve(K,"src","template.html"),Fn=[" _ __ __","| | / /__ / /_ __","| | / / _ \\/ / / / /","| |/ / __/ / /_/ /","|___/\\___/_/\\__,_/"],In="const F=['\u280B','\u2819','\u2839','\u2838','\u283C','\u2834','\u2826','\u2827','\u2807','\u280F'],M=['Starting Velu','Setting up your preview','Preparing your docs','Warming things up','Almost ready'];let f=0,m=0;const t=Date.now();const C='\\x1b[38;2;220;20;60m',R='\\x1b[0m',D='\\x1b[2m';const d=()=>{const s=(Date.now()-t)/1000|0;process.stdout.write('\\x1b[2K\\r '+C+F[f]+R+' '+M[m]+'\\u2026 '+D+s+'s'+R);f=(f+1)%F.length;};d();setInterval(d,90);setInterval(()=>{if(m<M.length-1)m++;},4000);"});var nt={};le(nt,{default:()=>Vn,runValidate:()=>tt});import Un from"node:fs";import zn from"node:path";function Bn(e){try{let t=JSON.parse(Un.readFileSync(zn.join(e,"velu.json"),"utf-8"));if(!t.navigation||typeof t.navigation!="object")return[];let o=B(t.navigation);return V(o,e).pageEntries}catch{return[]}}async function tt(e){let t=re(e),o=Bn(e),n=await Ve(e,o),r=[...t,...n],s=!!process.stdout.isTTY;return console.log(ne(r,{color:s})),r.some(a=>a.severity!=="warning"&&a.severity!=="info")?1:0}var Vn,ot=b(()=>{Y();Q();ye();we();F();Vn=tt});import be from"node:path";import L from"node:process";import{readFileSync as Gn}from"node:fs";var[,,rt,se]=L.argv;function Jn(){try{return JSON.parse(Gn(new URL("../package.json",import.meta.url),"utf8")).version}catch{return"unknown"}}async function qn(){switch(rt){case"--version":case"-v":case"version":{console.log(Jn());break}case"init":{se||(console.error("Usage: velu init <project-name>"),L.exit(1));let e=se,t=be.resolve(L.cwd(),e),{initProject:o}=await Promise.resolve().then(()=>(je(),Se));await o(t,e);break}case"dev":{let e=be.resolve(L.cwd(),se??"."),{startDevServer:t}=await Promise.resolve().then(()=>(et(),Qe));await t(e);break}case"validate":{let e=be.resolve(L.cwd(),se??"."),{runValidate:t}=await Promise.resolve().then(()=>(ot(),nt)),o=await t(e);L.exit(o);break}default:console.log("Usage:"),console.log(" velu init <project-name> scaffold a new docs project"),console.log(" velu dev [dir] start the dev preview server"),console.log(" velu validate [dir] check velu.json + content for problems"),L.exit(rt?1:0)}}qn().catch(e=>{console.error(L.env.VELU_DEBUG?e:`Error: ${e.message}`),L.exit(1)});
|
package/package.json
CHANGED
|
@@ -1,51 +1,55 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "@veluai/velu",
|
|
3
|
-
"version": "0.1.
|
|
4
|
-
"type": "module",
|
|
5
|
-
"bin": "./dist/cli.js",
|
|
6
|
-
"publishConfig": {
|
|
7
|
-
"access": "public"
|
|
8
|
-
},
|
|
9
|
-
"files": [
|
|
10
|
-
"dist/**",
|
|
11
|
-
"src/runtime/**",
|
|
12
|
-
"src/navigation.js",
|
|
13
|
-
"src/template.html",
|
|
14
|
-
"
|
|
15
|
-
"
|
|
16
|
-
"
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
"
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
"
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
"@
|
|
27
|
-
"@
|
|
28
|
-
"
|
|
29
|
-
"
|
|
30
|
-
"
|
|
31
|
-
"
|
|
32
|
-
"
|
|
33
|
-
"
|
|
34
|
-
"
|
|
35
|
-
"
|
|
36
|
-
"
|
|
37
|
-
"react": "^
|
|
38
|
-
"
|
|
39
|
-
"react-
|
|
40
|
-
"
|
|
41
|
-
"
|
|
42
|
-
"
|
|
43
|
-
"
|
|
44
|
-
"
|
|
45
|
-
"
|
|
46
|
-
"
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
"
|
|
50
|
-
|
|
51
|
-
}
|
|
1
|
+
{
|
|
2
|
+
"name": "@veluai/velu",
|
|
3
|
+
"version": "0.1.12",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"bin": "./dist/cli.js",
|
|
6
|
+
"publishConfig": {
|
|
7
|
+
"access": "public"
|
|
8
|
+
},
|
|
9
|
+
"files": [
|
|
10
|
+
"dist/**",
|
|
11
|
+
"src/runtime/**",
|
|
12
|
+
"src/navigation.js",
|
|
13
|
+
"src/template.html",
|
|
14
|
+
"src/lib/issues.js",
|
|
15
|
+
"src/lib/extract-mdx-error.js",
|
|
16
|
+
"src/lib/known-components.js",
|
|
17
|
+
"runtime/velu-ui/**",
|
|
18
|
+
"schema/**",
|
|
19
|
+
"templates/**"
|
|
20
|
+
],
|
|
21
|
+
"scripts": {
|
|
22
|
+
"build": "node scripts/build.mjs",
|
|
23
|
+
"prepack": "node scripts/build.mjs"
|
|
24
|
+
},
|
|
25
|
+
"dependencies": {
|
|
26
|
+
"@icons-pack/react-simple-icons": ">=13.0.0 <13.13.0",
|
|
27
|
+
"@mdx-js/mdx": "^3.1.1",
|
|
28
|
+
"@mdx-js/react": "^3.1.1",
|
|
29
|
+
"@mdx-js/rollup": "^3.1.1",
|
|
30
|
+
"@tailwindcss/vite": "^4.1.0",
|
|
31
|
+
"@vitejs/plugin-react": "^4.3.4",
|
|
32
|
+
"chokidar": "^3.6.0",
|
|
33
|
+
"estree-util-value-to-estree": "^3.5.0",
|
|
34
|
+
"express": "^4.21.1",
|
|
35
|
+
"github-slugger": "^2.0.0",
|
|
36
|
+
"iso-639-1": "^3.1.5",
|
|
37
|
+
"lucide-react": "^0.460.0",
|
|
38
|
+
"mdast-util-to-string": "^4.0.0",
|
|
39
|
+
"prism-react-renderer": "^2.4.0",
|
|
40
|
+
"prismjs": "^1.29.0",
|
|
41
|
+
"react": "^18.3.1",
|
|
42
|
+
"react-dom": "^18.3.1",
|
|
43
|
+
"react-router-dom": "^6.28.0",
|
|
44
|
+
"rehype-slug": "^6.0.0",
|
|
45
|
+
"remark-frontmatter": "^5.0.0",
|
|
46
|
+
"remark-gfm": "^4.0.1",
|
|
47
|
+
"remark-mdx-frontmatter": "^5.2.0",
|
|
48
|
+
"tailwindcss": "^4.1.0",
|
|
49
|
+
"unist-util-visit": "^5.1.0",
|
|
50
|
+
"vite": "^5.4.11"
|
|
51
|
+
},
|
|
52
|
+
"devDependencies": {
|
|
53
|
+
"esbuild": "^0.28.0"
|
|
54
|
+
}
|
|
55
|
+
}
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
import React from 'react';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* ErrorCard — a branded, self-contained card that renders ONE Velu "issue"
|
|
5
|
+
* (an MDX or velu.json problem). Used by the dev server's per-page error
|
|
6
|
+
* boundary. Deliberately presentational and dependency-free (no other Velu
|
|
7
|
+
* components, no effects) so it can never fail while reporting a failure.
|
|
8
|
+
*
|
|
9
|
+
* Styled with inline styles + design tokens (with hard fallbacks), so it looks
|
|
10
|
+
* right even when the page's own CSS hasn't loaded.
|
|
11
|
+
*/
|
|
12
|
+
const DANGER = 'var(--danger-stroke-color, #ef4444)';
|
|
13
|
+
const DANGER_BG =
|
|
14
|
+
'var(--danger-bg-color, color-mix(in srgb, #ef4444 7%, transparent))';
|
|
15
|
+
const MUTED = 'var(--muted-color, #6b7280)';
|
|
16
|
+
const TEXT = 'var(--text-color, #111827)';
|
|
17
|
+
|
|
18
|
+
export default function ErrorCard({
|
|
19
|
+
label,
|
|
20
|
+
title,
|
|
21
|
+
file,
|
|
22
|
+
line,
|
|
23
|
+
column,
|
|
24
|
+
frame,
|
|
25
|
+
detail,
|
|
26
|
+
hint,
|
|
27
|
+
suggestion,
|
|
28
|
+
}) {
|
|
29
|
+
const loc = file
|
|
30
|
+
? `${file}${line ? `:${line}${column ? `:${column}` : ''}` : ''}`
|
|
31
|
+
: null;
|
|
32
|
+
|
|
33
|
+
return (
|
|
34
|
+
<div
|
|
35
|
+
role="alert"
|
|
36
|
+
style={{
|
|
37
|
+
border: `1px solid ${DANGER}`,
|
|
38
|
+
borderRadius: 'var(--radius-md, 10px)',
|
|
39
|
+
background: DANGER_BG,
|
|
40
|
+
padding: 'var(--s2, 1rem)',
|
|
41
|
+
margin: 'var(--s2, 1rem) 0',
|
|
42
|
+
fontFamily: 'var(--font-sans, system-ui, sans-serif)',
|
|
43
|
+
color: TEXT,
|
|
44
|
+
lineHeight: 1.5,
|
|
45
|
+
}}
|
|
46
|
+
>
|
|
47
|
+
<div
|
|
48
|
+
style={{
|
|
49
|
+
display: 'flex',
|
|
50
|
+
gap: '0.6rem',
|
|
51
|
+
alignItems: 'center',
|
|
52
|
+
flexWrap: 'wrap',
|
|
53
|
+
}}
|
|
54
|
+
>
|
|
55
|
+
<span
|
|
56
|
+
style={{
|
|
57
|
+
fontFamily: 'var(--font-mono, ui-monospace, monospace)',
|
|
58
|
+
fontSize: 11,
|
|
59
|
+
textTransform: 'uppercase',
|
|
60
|
+
letterSpacing: '0.06em',
|
|
61
|
+
fontWeight: 600,
|
|
62
|
+
color: DANGER,
|
|
63
|
+
border: `1px solid ${DANGER}`,
|
|
64
|
+
borderRadius: 999,
|
|
65
|
+
padding: '2px 9px',
|
|
66
|
+
whiteSpace: 'nowrap',
|
|
67
|
+
}}
|
|
68
|
+
>
|
|
69
|
+
{label}
|
|
70
|
+
</span>
|
|
71
|
+
</div>
|
|
72
|
+
|
|
73
|
+
{title && (
|
|
74
|
+
<div style={{ marginTop: '0.6rem', fontWeight: 600, fontSize: '1.05rem' }}>
|
|
75
|
+
{title}
|
|
76
|
+
</div>
|
|
77
|
+
)}
|
|
78
|
+
|
|
79
|
+
{loc && (
|
|
80
|
+
<div
|
|
81
|
+
style={{
|
|
82
|
+
display: 'inline-block',
|
|
83
|
+
marginTop: '0.7rem',
|
|
84
|
+
fontFamily: 'var(--font-mono, ui-monospace, monospace)',
|
|
85
|
+
fontSize: 15,
|
|
86
|
+
fontWeight: 600,
|
|
87
|
+
letterSpacing: '0.01em',
|
|
88
|
+
color: DANGER,
|
|
89
|
+
background: 'var(--danger-bg-color, rgba(239,68,68,0.12))',
|
|
90
|
+
border: `1px solid ${DANGER}`,
|
|
91
|
+
borderRadius: 7,
|
|
92
|
+
padding: '7px 11px',
|
|
93
|
+
}}
|
|
94
|
+
>
|
|
95
|
+
{loc}
|
|
96
|
+
</div>
|
|
97
|
+
)}
|
|
98
|
+
{detail && (
|
|
99
|
+
<div style={{ marginTop: '0.25rem', color: MUTED }}>{detail}</div>
|
|
100
|
+
)}
|
|
101
|
+
|
|
102
|
+
{frame && (
|
|
103
|
+
<pre
|
|
104
|
+
style={{
|
|
105
|
+
marginTop: '0.75rem',
|
|
106
|
+
marginBottom: 0,
|
|
107
|
+
padding: '0.75rem 0.9rem',
|
|
108
|
+
overflow: 'auto',
|
|
109
|
+
background: 'var(--code-bg-color, rgba(0,0,0,0.05))',
|
|
110
|
+
borderRadius: 'var(--radius-sm, 6px)',
|
|
111
|
+
fontFamily: 'var(--font-mono, ui-monospace, monospace)',
|
|
112
|
+
fontSize: 12.5,
|
|
113
|
+
lineHeight: 1.5,
|
|
114
|
+
color: TEXT,
|
|
115
|
+
}}
|
|
116
|
+
>
|
|
117
|
+
{frame}
|
|
118
|
+
</pre>
|
|
119
|
+
)}
|
|
120
|
+
|
|
121
|
+
{suggestion && (
|
|
122
|
+
<div style={{ marginTop: '0.75rem' }}>
|
|
123
|
+
Did you mean{' '}
|
|
124
|
+
<code style={{ fontWeight: 600, color: DANGER }}>
|
|
125
|
+
{`<${suggestion}>`}
|
|
126
|
+
</code>
|
|
127
|
+
?
|
|
128
|
+
</div>
|
|
129
|
+
)}
|
|
130
|
+
|
|
131
|
+
{hint && (
|
|
132
|
+
<div style={{ marginTop: '0.6rem', color: MUTED, fontSize: '0.92rem' }}>
|
|
133
|
+
{hint}
|
|
134
|
+
</div>
|
|
135
|
+
)}
|
|
136
|
+
</div>
|
|
137
|
+
);
|
|
138
|
+
}
|
|
@@ -1,70 +1,101 @@
|
|
|
1
|
-
/* ThemeToggle — circular button with a sun/moon glyph; click flips
|
|
2
|
-
the theme. Geometry is a 32 × 32 circle with an 18 × 18 glyph
|
|
3
|
-
centred inside. The pill-with-slider design was replaced earlier;
|
|
4
|
-
only the circle survives now.
|
|
5
|
-
|
|
6
|
-
In light mode: --page-bg circle, sun glyph.
|
|
7
|
-
In dark mode: --page-bg circle, moon glyph.
|
|
8
|
-
|
|
9
|
-
Visibility model: BOTH icons are always rendered, stacked at the
|
|
10
|
-
same `position: absolute` slot inside the button. Opacity controls
|
|
11
|
-
which one is visible. We use opacity (not display: none) because:
|
|
12
|
-
|
|
13
|
-
1. Stacked icons render at the exact same point — no layout
|
|
14
|
-
shift when the theme flips.
|
|
15
|
-
2. Opacity is not touched anywhere else for these elements, so
|
|
16
|
-
the cascade is trivial — no risk of a stray rule (preflight,
|
|
17
|
-
utility class, dev-time fallback) overriding `display: none`
|
|
18
|
-
and revealing the wrong icon.
|
|
19
|
-
3. Identical markup on server + client → SSR-safe, no hydration
|
|
20
|
-
mismatch and no icon flash.
|
|
21
|
-
|
|
22
|
-
All values are tokens. */
|
|
23
|
-
|
|
24
|
-
.velu-theme-toggle {
|
|
25
|
-
/* `relative` so the absolutely-positioned icons inside are
|
|
26
|
-
anchored to this button, not the page. */
|
|
27
|
-
position: relative;
|
|
28
|
-
display: inline-flex;
|
|
29
|
-
align-items: center;
|
|
30
|
-
justify-content: center;
|
|
31
|
-
inline-size: 2rem;
|
|
32
|
-
block-size: 2rem;
|
|
33
|
-
border: var(--border-width) solid var(--border-color);
|
|
34
|
-
border-radius: 999px;
|
|
35
|
-
padding: 0;
|
|
36
|
-
background: var(--page-bg);
|
|
37
|
-
cursor: pointer;
|
|
38
|
-
transition: border-color 0.12s ease, background 0.12s ease
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
/*
|
|
45
|
-
|
|
46
|
-
.
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
/*
|
|
61
|
-
|
|
62
|
-
opacity:
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
1
|
+
/* ThemeToggle — circular button with a sun/moon glyph; click flips
|
|
2
|
+
the theme. Geometry is a 32 × 32 circle with an 18 × 18 glyph
|
|
3
|
+
centred inside. The pill-with-slider design was replaced earlier;
|
|
4
|
+
only the circle survives now.
|
|
5
|
+
|
|
6
|
+
In light mode: --page-bg circle, sun glyph.
|
|
7
|
+
In dark mode: --page-bg circle, moon glyph.
|
|
8
|
+
|
|
9
|
+
Visibility model: BOTH icons are always rendered, stacked at the
|
|
10
|
+
same `position: absolute` slot inside the button. Opacity controls
|
|
11
|
+
which one is visible. We use opacity (not display: none) because:
|
|
12
|
+
|
|
13
|
+
1. Stacked icons render at the exact same point — no layout
|
|
14
|
+
shift when the theme flips.
|
|
15
|
+
2. Opacity is not touched anywhere else for these elements, so
|
|
16
|
+
the cascade is trivial — no risk of a stray rule (preflight,
|
|
17
|
+
utility class, dev-time fallback) overriding `display: none`
|
|
18
|
+
and revealing the wrong icon.
|
|
19
|
+
3. Identical markup on server + client → SSR-safe, no hydration
|
|
20
|
+
mismatch and no icon flash.
|
|
21
|
+
|
|
22
|
+
All values are tokens. */
|
|
23
|
+
|
|
24
|
+
.velu-theme-toggle {
|
|
25
|
+
/* `relative` so the absolutely-positioned icons inside are
|
|
26
|
+
anchored to this button, not the page. */
|
|
27
|
+
position: relative;
|
|
28
|
+
display: inline-flex;
|
|
29
|
+
align-items: center;
|
|
30
|
+
justify-content: center;
|
|
31
|
+
inline-size: 2rem;
|
|
32
|
+
block-size: 2rem;
|
|
33
|
+
border: var(--border-width) solid var(--border-color);
|
|
34
|
+
border-radius: 999px;
|
|
35
|
+
padding: 0;
|
|
36
|
+
background: var(--page-bg);
|
|
37
|
+
cursor: pointer;
|
|
38
|
+
transition: border-color 0.12s ease, background 0.12s ease,
|
|
39
|
+
transform 0.18s cubic-bezier(0.34, 1.56, 0.64, 1);
|
|
40
|
+
}
|
|
41
|
+
.velu-theme-toggle:hover {
|
|
42
|
+
border-color: var(--accent-color);
|
|
43
|
+
}
|
|
44
|
+
/* Tactile press feedback on click. */
|
|
45
|
+
.velu-theme-toggle:active {
|
|
46
|
+
transform: scale(0.9);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/* Both icons stack here, centred. Each animates in/out on a theme flip:
|
|
50
|
+
the hidden glyph is faded, shrunk, and rotated off its axis; the active
|
|
51
|
+
one springs to full size at 0deg. Centring is done with margins (above),
|
|
52
|
+
so `transform` is free to drive the rotate/scale animation. */
|
|
53
|
+
.velu-theme-toggle__icon {
|
|
54
|
+
position: absolute;
|
|
55
|
+
inset-block-start: 50%;
|
|
56
|
+
inset-inline-start: 50%;
|
|
57
|
+
inline-size: 1.125rem;
|
|
58
|
+
block-size: 1.125rem;
|
|
59
|
+
margin-block-start: -0.5625rem; /* half of block-size */
|
|
60
|
+
margin-inline-start: -0.5625rem; /* half of inline-size */
|
|
61
|
+
color: var(--text-color);
|
|
62
|
+
opacity: 0;
|
|
63
|
+
transition: opacity 0.28s ease,
|
|
64
|
+
transform 0.4s cubic-bezier(0.34, 1.56, 0.64, 1);
|
|
65
|
+
pointer-events: none;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/* Hidden state per glyph — sun spins out clockwise, moon anti-clockwise,
|
|
69
|
+
so the swap reads as one rotating through the other. */
|
|
70
|
+
.velu-theme-toggle__icon--sun {
|
|
71
|
+
transform: rotate(90deg) scale(0.4);
|
|
72
|
+
}
|
|
73
|
+
.velu-theme-toggle__icon--moon {
|
|
74
|
+
transform: rotate(-90deg) scale(0.4);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/* Exactly one glyph is shown — the sun in light, the moon in dark — at full
|
|
78
|
+
size, upright. Higher specificity than the hidden defaults above, so it
|
|
79
|
+
wins for whichever glyph the active theme selects. */
|
|
80
|
+
:root:not([data-theme='dark']) .velu-theme-toggle__icon--sun,
|
|
81
|
+
[data-theme='dark'] .velu-theme-toggle__icon--moon {
|
|
82
|
+
opacity: 1;
|
|
83
|
+
transform: rotate(0deg) scale(1);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/* Honour reduced-motion: keep a plain crossfade — no spin, scale, or press. */
|
|
87
|
+
@media (prefers-reduced-motion: reduce) {
|
|
88
|
+
.velu-theme-toggle {
|
|
89
|
+
transition: border-color 0.12s ease, background 0.12s ease;
|
|
90
|
+
}
|
|
91
|
+
.velu-theme-toggle:active {
|
|
92
|
+
transform: none;
|
|
93
|
+
}
|
|
94
|
+
.velu-theme-toggle__icon {
|
|
95
|
+
transition: opacity 0.2s ease;
|
|
96
|
+
}
|
|
97
|
+
.velu-theme-toggle__icon--sun,
|
|
98
|
+
.velu-theme-toggle__icon--moon {
|
|
99
|
+
transform: none;
|
|
100
|
+
}
|
|
101
|
+
}
|
package/runtime/velu-ui/index.js
CHANGED
|
@@ -7,6 +7,7 @@ export { default as NavSelect } from './components/NavSelect.jsx';
|
|
|
7
7
|
export { default as Toc } from './components/Toc.jsx';
|
|
8
8
|
export { default as TocBar } from './components/TocBar.jsx';
|
|
9
9
|
export { default as Callout } from './components/Callout.jsx';
|
|
10
|
+
export { default as ErrorCard } from './components/ErrorCard.jsx';
|
|
10
11
|
export {
|
|
11
12
|
default as Accordion,
|
|
12
13
|
AccordionGroup,
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
// Per-component option schemas — the props whose wrong value would otherwise
|
|
2
|
+
// render incorrectly *silently*. Deliberately small and high-signal; extend a
|
|
3
|
+
// component's entry here when it gains a new constrained option.
|
|
4
|
+
//
|
|
5
|
+
// Pure data + a pure validator (no React, no other imports) so BOTH sides can
|
|
6
|
+
// use it: the live MDX registry (velu-ui/mdx-components.jsx) validates at
|
|
7
|
+
// render time, and `velu validate` (velu-cli) imports this same module to
|
|
8
|
+
// statically check literal attributes — one source of truth, no drift.
|
|
9
|
+
|
|
10
|
+
// Canonical accepted values (must match the components):
|
|
11
|
+
// Callout — VARIANTS keys; the component is CASE-SENSITIVE (VARIANTS[type]).
|
|
12
|
+
// MethodBadge — METHODS; the component lower-cases the input first.
|
|
13
|
+
export const CALLOUT_TYPES = ['note', 'warning', 'info', 'tip', 'check', 'danger', 'callout'];
|
|
14
|
+
export const METHOD_NAMES = ['get', 'post', 'put', 'patch', 'delete'];
|
|
15
|
+
|
|
16
|
+
// schema: { enums: { prop: { values, caseSensitive } }, required: [prop, …] }
|
|
17
|
+
const SCHEMAS = {
|
|
18
|
+
Callout: { enums: { type: { values: CALLOUT_TYPES, caseSensitive: true } } },
|
|
19
|
+
MethodBadge: { enums: { method: { values: METHOD_NAMES, caseSensitive: false } } },
|
|
20
|
+
ApiPath: { enums: { method: { values: METHOD_NAMES, caseSensitive: false } } },
|
|
21
|
+
Image: { required: ['src'] },
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
// Smallest edit distance match within a set (for "did you mean"). Tiny inputs.
|
|
25
|
+
function closest(value, values) {
|
|
26
|
+
const v = String(value).toLowerCase();
|
|
27
|
+
let best = null;
|
|
28
|
+
let bestD = Infinity;
|
|
29
|
+
for (const cand of values) {
|
|
30
|
+
const a = v;
|
|
31
|
+
const b = cand.toLowerCase();
|
|
32
|
+
// inline Levenshtein
|
|
33
|
+
const m = a.length;
|
|
34
|
+
const n = b.length;
|
|
35
|
+
const d = Array.from({ length: n + 1 }, (_, i) => i);
|
|
36
|
+
for (let i = 1; i <= m; i++) {
|
|
37
|
+
let prev = d[0];
|
|
38
|
+
d[0] = i;
|
|
39
|
+
for (let j = 1; j <= n; j++) {
|
|
40
|
+
const tmp = d[j];
|
|
41
|
+
d[j] = Math.min(d[j] + 1, d[j - 1] + 1, prev + (a[i - 1] === b[j - 1] ? 0 : 1));
|
|
42
|
+
prev = tmp;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
if (d[n] < bestD) {
|
|
46
|
+
bestD = d[n];
|
|
47
|
+
best = cand;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
return bestD <= 3 ? best : null;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Validate a component's props against its schema.
|
|
55
|
+
* @param {string} name component tag name
|
|
56
|
+
* @param {object} props props passed to it
|
|
57
|
+
* @param {{ checkRequired?: boolean }} [opts] static callers pass
|
|
58
|
+
* checkRequired:false because a prop supplied via a {expression}
|
|
59
|
+
* isn't a literal they can see, so "missing required" would be a
|
|
60
|
+
* false positive.
|
|
61
|
+
* @returns an issue-shaped object (category 'invalid-props') or null if valid.
|
|
62
|
+
* { category, title, detail, hint, suggestion }
|
|
63
|
+
*/
|
|
64
|
+
export function validateProps(name, props = {}, opts = {}) {
|
|
65
|
+
const { checkRequired = true } = opts;
|
|
66
|
+
const schema = SCHEMAS[name];
|
|
67
|
+
if (!schema) return null;
|
|
68
|
+
|
|
69
|
+
for (const req of checkRequired ? schema.required || [] : []) {
|
|
70
|
+
const v = props[req];
|
|
71
|
+
if (v == null || v === '') {
|
|
72
|
+
return {
|
|
73
|
+
category: 'invalid-props',
|
|
74
|
+
title: `<${name}> is missing the required "${req}" prop`,
|
|
75
|
+
hint: `Add ${req}="…" to the component.`,
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
for (const [prop, rule] of Object.entries(schema.enums || {})) {
|
|
81
|
+
if (!(prop in props) || props[prop] == null) continue;
|
|
82
|
+
const raw = props[prop];
|
|
83
|
+
const ok = rule.caseSensitive
|
|
84
|
+
? rule.values.includes(raw)
|
|
85
|
+
: rule.values.map((s) => s.toLowerCase()).includes(String(raw).toLowerCase());
|
|
86
|
+
if (!ok) {
|
|
87
|
+
const guess = closest(raw, rule.values);
|
|
88
|
+
return {
|
|
89
|
+
category: 'invalid-props',
|
|
90
|
+
title: `Invalid "${prop}" on <${name}>: "${raw}"`,
|
|
91
|
+
detail: `Expected one of: ${rule.values.join(', ')}.`,
|
|
92
|
+
hint: guess ? `Did you mean "${guess}"?` : '',
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
return null;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export default validateProps;
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
*
|
|
5
5
|
* `navigator.clipboard` only exists in a secure context (HTTPS or
|
|
6
6
|
* localhost). On a plain-HTTP origin — e.g. previewing the dev server
|
|
7
|
-
* over the LAN at http://<ip>:
|
|
7
|
+
* over the LAN at http://<ip>:8358 on a phone — it's `undefined`, so a
|
|
8
8
|
* `if (!navigator.clipboard) return` guard makes copy buttons silently
|
|
9
9
|
* no-op. This util falls back to the legacy `execCommand('copy')` via a
|
|
10
10
|
* hidden textarea so copy still works on those origins.
|
|
@@ -15,6 +15,7 @@ import TryItBar from './components/TryItBar.jsx';
|
|
|
15
15
|
import ApiField from './components/ApiField.jsx';
|
|
16
16
|
import ApiClient from './components/ApiClient.jsx';
|
|
17
17
|
import ApiSidebar from './components/ApiSidebar.jsx';
|
|
18
|
+
import { validateProps } from './lib/component-schemas.js';
|
|
18
19
|
|
|
19
20
|
/**
|
|
20
21
|
* defaultMdxComponents — the registry the MDXProvider consumes.
|
|
@@ -53,12 +54,31 @@ function PreOverride({ children }) {
|
|
|
53
54
|
);
|
|
54
55
|
}
|
|
55
56
|
|
|
57
|
+
/* Wrap a component so its constrained options (see component-schemas.js)
|
|
58
|
+
are validated at render time. An invalid option throws a marked error
|
|
59
|
+
(`err.veluIssue`) that the dev server turns into a friendly card on the
|
|
60
|
+
page AND a clean block in the terminal — the same surface as an unknown
|
|
61
|
+
component. Components without a schema pass straight through. */
|
|
62
|
+
function checked(name, Comp) {
|
|
63
|
+
function Checked(props) {
|
|
64
|
+
const issue = validateProps(name, props);
|
|
65
|
+
if (issue) {
|
|
66
|
+
const err = new Error(issue.title);
|
|
67
|
+
err.veluIssue = issue;
|
|
68
|
+
throw err;
|
|
69
|
+
}
|
|
70
|
+
return <Comp {...props} />;
|
|
71
|
+
}
|
|
72
|
+
Checked.displayName = `Checked(${name})`;
|
|
73
|
+
return Checked;
|
|
74
|
+
}
|
|
75
|
+
|
|
56
76
|
export const defaultMdxComponents = {
|
|
57
77
|
/* HTML-tag overrides (lowercase keys). */
|
|
58
78
|
pre: PreOverride,
|
|
59
79
|
|
|
60
80
|
/* Authored component tags (capitalised keys). */
|
|
61
|
-
Callout,
|
|
81
|
+
Callout: checked('Callout', Callout),
|
|
62
82
|
Card,
|
|
63
83
|
CardGroup,
|
|
64
84
|
Accordion,
|
|
@@ -71,11 +91,11 @@ export const defaultMdxComponents = {
|
|
|
71
91
|
Tree,
|
|
72
92
|
Folder,
|
|
73
93
|
File,
|
|
74
|
-
Image,
|
|
94
|
+
Image: checked('Image', Image),
|
|
75
95
|
CodeBlock,
|
|
76
96
|
CodeGroup,
|
|
77
|
-
MethodBadge,
|
|
78
|
-
ApiPath,
|
|
97
|
+
MethodBadge: checked('MethodBadge', MethodBadge),
|
|
98
|
+
ApiPath: checked('ApiPath', ApiPath),
|
|
79
99
|
TryItBar,
|
|
80
100
|
ApiField,
|
|
81
101
|
ApiClient,
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
// Normalize a thrown error — from a Vite/MDX transform, an SSR render, or a
|
|
2
|
+
// React error boundary — into the shared `issue` shape (see ./issues.js).
|
|
3
|
+
//
|
|
4
|
+
// Isomorphic: no Node `path` import (path handling is string-based) so the
|
|
5
|
+
// browser ErrorBoundary can reuse it. The single hard rule is PATH SAFETY:
|
|
6
|
+
// never surface an absolute path that isn't under the user's project — those
|
|
7
|
+
// are Velu/Vite internals and must be stripped.
|
|
8
|
+
import { makeIssue, suggestComponent } from './issues.js';
|
|
9
|
+
|
|
10
|
+
// Unwrap a few layers of `err.cause` when the outer message is generic.
|
|
11
|
+
function unwrap(err) {
|
|
12
|
+
let e = err;
|
|
13
|
+
let depth = 0;
|
|
14
|
+
while (e && e.cause && depth < 3) {
|
|
15
|
+
// Stop if the current layer already carries useful location info.
|
|
16
|
+
if (e.loc || e.line || /`[^`]+` to be defined/.test(e.message || '')) break;
|
|
17
|
+
e = e.cause;
|
|
18
|
+
depth += 1;
|
|
19
|
+
}
|
|
20
|
+
return e || err;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const toPosix = (p) => String(p).replace(/\\/g, '/');
|
|
24
|
+
|
|
25
|
+
// Make an absolute path project-relative; return null for anything that isn't
|
|
26
|
+
// inside the project (i.e. our internals — never shown).
|
|
27
|
+
function rel(rawPath, projectDir) {
|
|
28
|
+
if (!rawPath) return null;
|
|
29
|
+
let p = toPosix(rawPath).replace(/[?#].*$/, ''); // drop ?query / #hash
|
|
30
|
+
const root = projectDir ? toPosix(projectDir).replace(/\/+$/, '') : '';
|
|
31
|
+
if (root && p.toLowerCase().startsWith(root.toLowerCase())) {
|
|
32
|
+
return p.slice(root.length).replace(/^\/+/, '');
|
|
33
|
+
}
|
|
34
|
+
// Already-relative, project-owned path (no drive letter, no node_modules).
|
|
35
|
+
if (!/^([a-zA-Z]:\/|\/)/.test(p) && !/node_modules/.test(p)) return p;
|
|
36
|
+
return null; // absolute and outside the project → hide it
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// Strip any absolute path (and node_modules refs) from a message so internals
|
|
40
|
+
// never leak; collapse them to "…".
|
|
41
|
+
function cleanMessage(msg) {
|
|
42
|
+
if (!msg) return '';
|
|
43
|
+
return String(msg)
|
|
44
|
+
.replace(/([a-zA-Z]:\\|\/)[^\s'"()]+/g, (m) => (/node_modules|[\\/]vite[\\/]|@veluai|velu-cli|velu-ui/.test(m) ? '…' : m))
|
|
45
|
+
.trim();
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// Pull a "(line:col)" / "(line:col-line:col)" position out of a message tail.
|
|
49
|
+
// MDX/vfile errors often carry the location only in the message string, with
|
|
50
|
+
// err.line/err.loc left undefined.
|
|
51
|
+
function parseLocFromMessage(msg) {
|
|
52
|
+
const m = /\((\d+):(\d+)(?:-\d+:\d+)?\)\s*$/.exec(String(msg || ''));
|
|
53
|
+
return m ? { line: Number(m[1]), column: Number(m[2]) } : null;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// Drop a trailing "(line:col-…)" from a message once we've surfaced it as a
|
|
57
|
+
// separate location, so it isn't shown twice.
|
|
58
|
+
function stripLocSuffix(msg) {
|
|
59
|
+
return String(msg || '').replace(/\s*\(\d+:\d+(?:-\d+:\d+)?\)\s*$/, '').trim();
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// Phrases that mark a genuine MDX *parse* error (vs a runtime throw).
|
|
63
|
+
const MDX_SYNTAX_RE =
|
|
64
|
+
/closing tag|unexpected closing|could not parse (?:expression|import|export)|unexpected character|unexpected end of|expected a closing|expected the closing|unexpected `|in expression|misnested|before name/i;
|
|
65
|
+
|
|
66
|
+
// Keep a code frame only when it clearly belongs to a project file; otherwise
|
|
67
|
+
// drop it (an internal frame would leak paths and confuse the author).
|
|
68
|
+
function safeFrame(frame, fileIsProjectOwned) {
|
|
69
|
+
if (!frame || !fileIsProjectOwned) return null;
|
|
70
|
+
const text = String(frame);
|
|
71
|
+
if (/node_modules|[\\/]vite[\\/]|@veluai[\\/]/.test(text)) return null;
|
|
72
|
+
return text;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export function extractMdxError(rawErr, opts = {}) {
|
|
76
|
+
const { projectDir = '', knownComponents = [], file: fileHint = null } = opts;
|
|
77
|
+
|
|
78
|
+
// A component (runtime) or the compile-time prop check attaches a ready-made
|
|
79
|
+
// issue. Trust it directly — it already carries plain-language wording, a
|
|
80
|
+
// suggestion, and (from the compile-time check) a file:line. Walk the cause
|
|
81
|
+
// chain since Vite/rollup may re-wrap the thrown error.
|
|
82
|
+
let tagged = null;
|
|
83
|
+
for (let e = rawErr, depth = 0; e && depth < 6; e = e.cause, depth += 1) {
|
|
84
|
+
if (e.veluIssue) {
|
|
85
|
+
tagged = e.veluIssue;
|
|
86
|
+
break;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
if (tagged) return makeIssue({ ...tagged, file: tagged.file || fileHint });
|
|
90
|
+
|
|
91
|
+
const err = unwrap(rawErr) || {};
|
|
92
|
+
const message = err.message || String(rawErr || '');
|
|
93
|
+
|
|
94
|
+
// 1) Unknown component (MDX render: `_missingMdxReference`). The message
|
|
95
|
+
// tail carries the spot: "...referenced in your code at `7:1-7:54` in
|
|
96
|
+
// `<abs path>`" — pull the line/column + file out so the author knows
|
|
97
|
+
// exactly where to look (path relative-ized for safety).
|
|
98
|
+
const missing = /Expected component `([^`]+)` to be defined/.exec(message);
|
|
99
|
+
if (missing) {
|
|
100
|
+
const name = missing[1];
|
|
101
|
+
const at = /referenced in your code at `(\d+):(\d+)/.exec(message);
|
|
102
|
+
const inFile = /\bin `([^`]+)`/.exec(message);
|
|
103
|
+
const relFile = inFile ? rel(inFile[1], projectDir) : null;
|
|
104
|
+
return makeIssue({
|
|
105
|
+
category: 'unknown-component',
|
|
106
|
+
file: relFile || fileHint,
|
|
107
|
+
line: at ? Number(at[1]) : null,
|
|
108
|
+
column: at ? Number(at[2]) : null,
|
|
109
|
+
title: `<${name}> is not a built-in component`,
|
|
110
|
+
detail: '',
|
|
111
|
+
hint: 'Components are built in — check the spelling and capitalization (you don’t import them).',
|
|
112
|
+
suggestion: suggestComponent(name, knownComponents),
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// 2) Compile error carrying a source location (Vite plugin / MDX / vfile).
|
|
117
|
+
// The location may be on err.loc, on err.line/column, or only inside the
|
|
118
|
+
// message text — try all three.
|
|
119
|
+
const loc =
|
|
120
|
+
err.loc ||
|
|
121
|
+
(err.line != null ? { line: err.line, column: err.column, file: err.file } : null) ||
|
|
122
|
+
parseLocFromMessage(err.reason || message);
|
|
123
|
+
const rawFile = err.id || (loc && loc.file) || err.file || null;
|
|
124
|
+
const file = rel(rawFile, projectDir) || fileHint;
|
|
125
|
+
const fileIsProjectOwned = Boolean(file) && rel(rawFile, projectDir) != null;
|
|
126
|
+
const frame = safeFrame(err.frame, fileIsProjectOwned || Boolean(fileHint));
|
|
127
|
+
const detail = cleanMessage(stripLocSuffix(err.reason || message));
|
|
128
|
+
const isSyntax = MDX_SYNTAX_RE.test(message);
|
|
129
|
+
const isFrontmatter =
|
|
130
|
+
err.source === 'remark-frontmatter' ||
|
|
131
|
+
/\byaml\b|frontmatter/i.test(message) ||
|
|
132
|
+
(loc && loc.line === 1 && /unexpected|expected/i.test(message) && /---/.test(message));
|
|
133
|
+
|
|
134
|
+
if (loc || isSyntax || (frame && fileIsProjectOwned)) {
|
|
135
|
+
return makeIssue({
|
|
136
|
+
category: isFrontmatter ? 'frontmatter' : 'mdx-syntax',
|
|
137
|
+
file,
|
|
138
|
+
line: loc ? loc.line : null,
|
|
139
|
+
column: loc ? loc.column : null,
|
|
140
|
+
frame,
|
|
141
|
+
title: detail || (isFrontmatter ? 'Invalid frontmatter' : 'MDX syntax error'),
|
|
142
|
+
detail: '',
|
|
143
|
+
hint: isFrontmatter
|
|
144
|
+
? 'Check the YAML between the --- markers — indentation, quotes, and colons.'
|
|
145
|
+
: 'Make sure every <Component> has a matching closing tag and that { } braces are balanced.',
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
// 3) Bad prop / option that threw at render time.
|
|
150
|
+
if (/\.map is not a function|is not iterable|reading '|undefined \(reading/i.test(message)) {
|
|
151
|
+
return makeIssue({
|
|
152
|
+
category: 'invalid-props',
|
|
153
|
+
file,
|
|
154
|
+
title: 'A component received an invalid value',
|
|
155
|
+
detail,
|
|
156
|
+
hint: 'Check the props/options you passed to a component on this page.',
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
// 4) Anything else that threw while rendering.
|
|
161
|
+
return makeIssue({
|
|
162
|
+
category: 'render-crash',
|
|
163
|
+
file,
|
|
164
|
+
title: 'This page failed to render',
|
|
165
|
+
detail,
|
|
166
|
+
hint: 'Set VELU_DEBUG=1 for the full stack trace.',
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
export default extractMdxError;
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
// The shared "issue" model used by BOTH the live `velu dev` error surface and
|
|
2
|
+
// the `velu validate` command — so an author sees the same wording whether a
|
|
3
|
+
// problem shows up live in the browser/terminal or in a batch validation run.
|
|
4
|
+
//
|
|
5
|
+
// An issue is a plain object:
|
|
6
|
+
// {
|
|
7
|
+
// category, // see CATEGORY_LABEL keys below
|
|
8
|
+
// severity, // 'error' (default) | 'warning' | 'info'
|
|
9
|
+
// file, // project-relative path (posix), or null
|
|
10
|
+
// line, column,// 1-based numbers, or null
|
|
11
|
+
// frame, // a caret-annotated code-frame string, or null
|
|
12
|
+
// title, // short, plain-language headline
|
|
13
|
+
// detail, // the underlying message (already path-stripped)
|
|
14
|
+
// hint, // how to fix it
|
|
15
|
+
// suggestion, // a "did you mean <X>" component name, or null
|
|
16
|
+
// }
|
|
17
|
+
//
|
|
18
|
+
// This module is dependency-free and isomorphic (no Node-only imports), so the
|
|
19
|
+
// browser ErrorBoundary can reuse `levenshtein`/`suggestComponent`.
|
|
20
|
+
|
|
21
|
+
export const CATEGORY_LABEL = {
|
|
22
|
+
'mdx-syntax': 'MDX syntax',
|
|
23
|
+
frontmatter: 'Frontmatter',
|
|
24
|
+
'unknown-component': 'Unknown component',
|
|
25
|
+
'invalid-props': 'Invalid options',
|
|
26
|
+
'render-crash': 'Render error',
|
|
27
|
+
'config-json': 'velu.json',
|
|
28
|
+
'config-schema': 'velu.json',
|
|
29
|
+
'config-nav': 'Navigation',
|
|
30
|
+
'config-asset': 'Asset',
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
// Fill in defaults so callers only set what they know.
|
|
34
|
+
export function makeIssue(partial) {
|
|
35
|
+
return {
|
|
36
|
+
category: 'render-crash',
|
|
37
|
+
severity: 'error',
|
|
38
|
+
file: null,
|
|
39
|
+
line: null,
|
|
40
|
+
column: null,
|
|
41
|
+
frame: null,
|
|
42
|
+
title: 'Something went wrong',
|
|
43
|
+
detail: '',
|
|
44
|
+
hint: '',
|
|
45
|
+
suggestion: null,
|
|
46
|
+
...partial,
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// Classic Levenshtein edit distance (small inputs — component names).
|
|
51
|
+
export function levenshtein(a, b) {
|
|
52
|
+
a = String(a);
|
|
53
|
+
b = String(b);
|
|
54
|
+
if (a === b) return 0;
|
|
55
|
+
if (!a.length) return b.length;
|
|
56
|
+
if (!b.length) return a.length;
|
|
57
|
+
let prev = Array.from({ length: b.length + 1 }, (_, i) => i);
|
|
58
|
+
let cur = new Array(b.length + 1);
|
|
59
|
+
for (let i = 1; i <= a.length; i++) {
|
|
60
|
+
cur[0] = i;
|
|
61
|
+
for (let j = 1; j <= b.length; j++) {
|
|
62
|
+
const cost = a[i - 1] === b[j - 1] ? 0 : 1;
|
|
63
|
+
cur[j] = Math.min(cur[j - 1] + 1, prev[j] + 1, prev[j - 1] + cost);
|
|
64
|
+
}
|
|
65
|
+
[prev, cur] = [cur, prev];
|
|
66
|
+
}
|
|
67
|
+
return prev[b.length];
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// Closest known component to `name` within a small edit distance, else null.
|
|
71
|
+
// Compared case-insensitively (so a capitalization typo still matches) but the
|
|
72
|
+
// correctly-cased known name is returned.
|
|
73
|
+
export function suggestComponent(name, known = []) {
|
|
74
|
+
if (!name) return null;
|
|
75
|
+
const lower = String(name).toLowerCase();
|
|
76
|
+
let best = null;
|
|
77
|
+
let bestD = Infinity;
|
|
78
|
+
for (const k of known) {
|
|
79
|
+
const d = levenshtein(lower, String(k).toLowerCase());
|
|
80
|
+
if (d < bestD) {
|
|
81
|
+
bestD = d;
|
|
82
|
+
best = k;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
// Allow a little more slack for longer names, capped at 3 edits.
|
|
86
|
+
const threshold = Math.min(3, Math.max(2, Math.floor(lower.length / 4)));
|
|
87
|
+
return bestD <= threshold ? best : null;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// ── Terminal formatting ─────────────────────────────────────────────────────
|
|
91
|
+
|
|
92
|
+
const COLORS = {
|
|
93
|
+
reset: '\x1b[0m',
|
|
94
|
+
red: '\x1b[31m',
|
|
95
|
+
yellow: '\x1b[33m',
|
|
96
|
+
cyan: '\x1b[36m',
|
|
97
|
+
dim: '\x1b[2m',
|
|
98
|
+
bold: '\x1b[1m',
|
|
99
|
+
};
|
|
100
|
+
const paint = (on, code, s) => (on ? `${code}${s}${COLORS.reset}` : s);
|
|
101
|
+
|
|
102
|
+
function severityMark(sev, color) {
|
|
103
|
+
if (sev === 'warning') return paint(color, COLORS.yellow, '⚠');
|
|
104
|
+
if (sev === 'info') return paint(color, COLORS.cyan, 'ℹ');
|
|
105
|
+
return paint(color, COLORS.red, '✖');
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// Format a single issue as a multi-line terminal block.
|
|
109
|
+
export function formatIssue(issue, { color = false } = {}) {
|
|
110
|
+
const label = CATEGORY_LABEL[issue.category] || issue.category;
|
|
111
|
+
const lineCol = issue.line
|
|
112
|
+
? `${issue.line}${issue.column ? `:${issue.column}` : ''}`
|
|
113
|
+
: '';
|
|
114
|
+
// Keep the line:col even when grouped output has nulled the file (so the
|
|
115
|
+
// position still shows under a per-file heading in formatReport).
|
|
116
|
+
const where = issue.file ? `${issue.file}${lineCol ? `:${lineCol}` : ''}` : lineCol;
|
|
117
|
+
const lines = [];
|
|
118
|
+
lines.push(
|
|
119
|
+
`${severityMark(issue.severity, color)} ${paint(color, COLORS.bold, label)}` +
|
|
120
|
+
(where ? ` ${paint(color, COLORS.dim, where)}` : ''),
|
|
121
|
+
);
|
|
122
|
+
if (issue.title) lines.push(` ${issue.title}`);
|
|
123
|
+
if (issue.detail && issue.detail !== issue.title) lines.push(` ${paint(color, COLORS.dim, issue.detail)}`);
|
|
124
|
+
if (issue.frame) {
|
|
125
|
+
for (const f of String(issue.frame).split('\n')) lines.push(` ${f}`);
|
|
126
|
+
}
|
|
127
|
+
if (issue.suggestion) lines.push(` ${paint(color, COLORS.cyan, `Did you mean <${issue.suggestion}>?`)}`);
|
|
128
|
+
if (issue.hint) lines.push(` ${paint(color, COLORS.dim, `→ ${issue.hint}`)}`);
|
|
129
|
+
return lines.join('\n');
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// Format a list of issues as a grouped report (used by `velu validate`).
|
|
133
|
+
export function formatReport(issues, { color = false } = {}) {
|
|
134
|
+
if (!issues.length) {
|
|
135
|
+
return paint(color, COLORS.cyan, '✓ No issues found.');
|
|
136
|
+
}
|
|
137
|
+
// Group by file (config issues with no file group under "velu.json").
|
|
138
|
+
const groups = new Map();
|
|
139
|
+
for (const issue of issues) {
|
|
140
|
+
const key = issue.file || 'velu.json';
|
|
141
|
+
if (!groups.has(key)) groups.set(key, []);
|
|
142
|
+
groups.get(key).push(issue);
|
|
143
|
+
}
|
|
144
|
+
const out = [];
|
|
145
|
+
for (const [file, group] of groups) {
|
|
146
|
+
out.push(paint(color, COLORS.bold, file));
|
|
147
|
+
for (const issue of group) {
|
|
148
|
+
out.push(formatIssue({ ...issue, file: null }, { color }).replace(/^/gm, ' '));
|
|
149
|
+
}
|
|
150
|
+
out.push('');
|
|
151
|
+
}
|
|
152
|
+
const errors = issues.filter((i) => i.severity !== 'warning' && i.severity !== 'info').length;
|
|
153
|
+
const warnings = issues.length - errors;
|
|
154
|
+
const summary =
|
|
155
|
+
`${errors} error${errors === 1 ? '' : 's'}` +
|
|
156
|
+
(warnings ? `, ${warnings} warning${warnings === 1 ? '' : 's'}` : '');
|
|
157
|
+
out.push(paint(color, errors ? COLORS.red : COLORS.yellow, summary));
|
|
158
|
+
return out.join('\n');
|
|
159
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
// The capitalized component tags an author may use in `.mdx` content.
|
|
2
|
+
//
|
|
3
|
+
// Kept in sync with velu-ui's `defaultMdxComponents`
|
|
4
|
+
// (packages/velu-ui/src/mdx-components.jsx). Used for "did you mean"
|
|
5
|
+
// suggestions and unknown-component detection on the Node side (dev server +
|
|
6
|
+
// `velu validate`). The browser ErrorBoundary derives the same set directly
|
|
7
|
+
// from `defaultMdxComponents`, so this list only needs to stay roughly in
|
|
8
|
+
// step (a missing entry just costs a suggestion, never correctness).
|
|
9
|
+
export const KNOWN_COMPONENTS = [
|
|
10
|
+
'Callout',
|
|
11
|
+
'Card',
|
|
12
|
+
'CardGroup',
|
|
13
|
+
'Accordion',
|
|
14
|
+
'AccordionGroup',
|
|
15
|
+
'Columns',
|
|
16
|
+
'Field',
|
|
17
|
+
'Prompt',
|
|
18
|
+
'Steps',
|
|
19
|
+
'Step',
|
|
20
|
+
'Tree',
|
|
21
|
+
'Folder',
|
|
22
|
+
'File',
|
|
23
|
+
'Image',
|
|
24
|
+
'CodeBlock',
|
|
25
|
+
'CodeGroup',
|
|
26
|
+
'MethodBadge',
|
|
27
|
+
'ApiPath',
|
|
28
|
+
'TryItBar',
|
|
29
|
+
'ApiField',
|
|
30
|
+
'ApiClient',
|
|
31
|
+
'ApiSidebar',
|
|
32
|
+
];
|
|
33
|
+
|
|
34
|
+
export default KNOWN_COMPONENTS;
|
package/src/runtime/App.jsx
CHANGED
|
@@ -48,6 +48,7 @@ import {
|
|
|
48
48
|
VeluMark,
|
|
49
49
|
} from 'velu-ui';
|
|
50
50
|
import { X, ChevronDown, ChevronUp } from 'lucide-react';
|
|
51
|
+
import ErrorBoundary from './ErrorBoundary.jsx';
|
|
51
52
|
|
|
52
53
|
const CALLOUT_TYPES = [
|
|
53
54
|
'note',
|
|
@@ -1351,7 +1352,9 @@ function DocsPage() {
|
|
|
1351
1352
|
<MDXProvider components={defaultMdxComponents}>
|
|
1352
1353
|
<div className="velu-prose">
|
|
1353
1354
|
{PageComponent ? (
|
|
1354
|
-
<
|
|
1355
|
+
<ErrorBoundary key={pathname} file={entry?.relPath}>
|
|
1356
|
+
<PageComponent />
|
|
1357
|
+
</ErrorBoundary>
|
|
1355
1358
|
) : (
|
|
1356
1359
|
<p style={{ color: 'var(--muted-color)' }}>
|
|
1357
1360
|
{entry?.missing
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import React from 'react';
|
|
2
|
+
import { ErrorCard } from 'velu-ui';
|
|
3
|
+
import { extractMdxError } from '../lib/extract-mdx-error.js';
|
|
4
|
+
import { CATEGORY_LABEL } from '../lib/issues.js';
|
|
5
|
+
import { KNOWN_COMPONENTS } from '../lib/known-components.js';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Catches render-time errors from the current page (unknown component, a
|
|
9
|
+
* component that threw on a bad prop, etc.) and renders a branded ErrorCard in
|
|
10
|
+
* its place — leaving the surrounding chrome (header, sidebar, TOC) mounted.
|
|
11
|
+
*
|
|
12
|
+
* This is the CLIENT-side safety net: when the reader navigates (react-router,
|
|
13
|
+
* no full reload) to a page that throws, the chrome stays put and only the
|
|
14
|
+
* body shows the card. On a direct load / reload of a broken page the error
|
|
15
|
+
* happens during SSR instead — React's renderToString doesn't recover through
|
|
16
|
+
* error boundaries, so the dev server catches it there and serves the
|
|
17
|
+
* full-page branded error (and logs it to the terminal).
|
|
18
|
+
*
|
|
19
|
+
* In `App.jsx` it's keyed by `pathname`, so navigating to another page (or
|
|
20
|
+
* fixing the file and reloading) remounts it and clears the error.
|
|
21
|
+
*/
|
|
22
|
+
export default class ErrorBoundary extends React.Component {
|
|
23
|
+
constructor(props) {
|
|
24
|
+
super(props);
|
|
25
|
+
this.state = { error: null };
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
static getDerivedStateFromError(error) {
|
|
29
|
+
return { error };
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
render() {
|
|
33
|
+
const { error } = this.state;
|
|
34
|
+
if (!error) return this.props.children;
|
|
35
|
+
|
|
36
|
+
const issue = extractMdxError(error, {
|
|
37
|
+
knownComponents: KNOWN_COMPONENTS,
|
|
38
|
+
file: this.props.file || null,
|
|
39
|
+
});
|
|
40
|
+
return (
|
|
41
|
+
<ErrorCard
|
|
42
|
+
label={CATEGORY_LABEL[issue.category] || issue.category}
|
|
43
|
+
title={issue.title}
|
|
44
|
+
file={issue.file}
|
|
45
|
+
line={issue.line}
|
|
46
|
+
column={issue.column}
|
|
47
|
+
frame={issue.frame}
|
|
48
|
+
detail={issue.detail}
|
|
49
|
+
hint={issue.hint}
|
|
50
|
+
suggestion={issue.suggestion}
|
|
51
|
+
/>
|
|
52
|
+
);
|
|
53
|
+
}
|
|
54
|
+
}
|