markopress 0.0.3 → 0.0.4

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.
@@ -1 +1 @@
1
- import{promises as e}from"node:fs";import o from"node:path";import{spawn as t}from"node:child_process";import{fileURLToPath as n}from"node:url";import s from"gray-matter";import{loadConfig as a}from"../config/loader.js";import{getDesignSystem as r,getDarkModeOverride as i}from"../theme/default/design-systems/index.js";import{globalTagValidator as c,formatValidationError as l}from"../markdown/tag-validator.js";import{PluginManager as d}from"../plugin/manager.js";import{loadMarkdownModule as u,registerMarkdownContent as g,escapeMarkoText as m}from"./vite-markdown-plugin.js";import{renderMarkdown as f}from"../markdown/renderer.js";const p=o.dirname(n(import.meta.url)),h=o.resolve(p,"..",".."),w=o.join(h,"src","theme","default"),y=new Set(["@markopress/theme-default","theme-default","default"]);function k(e){return y.has(e)}export async function build(n={}){const{outDir:r,debug:i=!1,useCatchAllRoutes:u,root:g}=n,p=g||process.cwd(),h=[],w=new Map,y=new Map,k=e=>({start:()=>{y.set(e,performance.now())},end:()=>{const o=y.get(e)||0,t=performance.now()-o;w.set(e,t)}});try{console.log("šŸš€ Building MarkoPress site...\n");const n=k("Config loading");n.start();const g=await a(p,{mode:"production",command:"build"});let y;if(n.end(),g.plugins&&g.plugins.length>0){console.log("šŸ”Œ Loading plugins...");const e=k("Plugin loading");e.start(),y=new d(g),await y.loadPlugins(g.plugins),e.end(),console.log("")}if(y){console.log("šŸ“¦ Loading plugin content...");const e=k("Plugin loadContent hooks");e.start(),await y.execLoadContentHooks(),e.end(),console.log(" Plugin content loaded\n")}const j={},b=[];for(const[t,n]of Object.entries(g.content)){const a="string"==typeof n?{dir:n}:n;if(!a?.dir)continue;const r=new Map,i={id:t,dir:a.dir,config:a,enhance(e,o){r.set(e,o)},getEnhancement:e=>r.get(e),files:[],_enhancements:r},c=o.resolve(p,a.dir);try{const n=await e.readdir(c,{withFileTypes:!0});for(const a of n)if(a.isFile()&&a.name.endsWith(".md")){const n=o.join(c,a.name),r=await e.readFile(n,"utf-8");let l={};try{l=s(r).data}catch{}i.files.push({id:a.name.replace(".md",""),slug:a.name.replace(".md",""),filePath:n,urlPath:"index"===a.name.replace(".md","")?"/"+t:`/${t}/${a.name.replace(".md","")}`,processed:{frontmatter:l}})}}catch{}b.push(i)}if(y&&b.length>0){console.log("šŸ”Œ Enhancing modules with plugin metadata...");const t=k("Module enhancement");t.start();for(const e of b)console.log(` Module: ${e.id} (${e.files.length} files)`),e.files.length>0&&console.log(" First file has processed: "+!!e.files[0].processed);await y.execEnhanceModulesHooks(b),t.end(),console.log(` Enhanced ${b.length} module(s)\n`);const n=o.join(p,"src",".generated");await e.mkdir(n,{recursive:!0});const s={};for(const e of b){const o={},t=e._enhancements.entries();for(const[e,n]of t)o[e]=n;Object.keys(o).length>0&&(s[e.id]=o)}const a=o.join(n,"module-enhancements.js"),r=`// Auto-generated by MarkoPress - Do not edit\nexport default ${JSON.stringify(s,null,2)};\n`;await e.writeFile(a,r,"utf-8"),console.log(" Wrote module enhancements to src/.generated/module-enhancements.js\n")}if(g.markdown.markoTags?.enabled){const e=o.join(p,g.markdown.markoTags.tagsDir||"src/.markopress/tags");console.log("šŸ” Scanning tags directory...");const t=k("Tag validation setup");t.start(),await c.loadAvailableTags(e),t.end(),console.log(` Found ${c.getAvailableTagsCount()} tags\n`)}else c.reset();const T=o.join(p,"src","routes");await e.mkdir(T,{recursive:!0});let $={};if(y){const e=k("Extend routes hooks");e.start(),$=await y.execExtendRoutesHooks($),e.end(),console.log("šŸ”Œ Extended routes manifest:",Object.keys($).length)}console.log("šŸ“ Generating routes from content...");const v=k("Route generation");v.start();const C=u??g.build.useCatchAllRoutes;console.log("šŸ“„ Pre-rendering markdown to .marko files...");const F=k("Pre-render markdown");F.start();const P=o.join(p,"src",".generated","markdown");await e.mkdir(P,{recursive:!0});const E={};let x=0;for(const t of b){const n=o.join(P,t.id);await e.mkdir(n,{recursive:!0});for(const s of t.files)try{const a=await e.readFile(s.filePath,"utf-8"),r=await f(a);let i=r.html.replace(/<span class="line"><\/span>(\s*<\/code>)/g,"$1");const c=`<div class="markdown-content">\n${m(i)}\n</div>`,l=o.join(n,s.slug+".marko");await e.writeFile(l,c),E[`${t.id}/${s.slug}`]={frontmatter:r.frontmatter,headers:r.headers||[]},x++}catch(e){console.warn(` Warning: Failed to pre-render ${t.id}/${s.slug}:`,e)}}const S=o.join(p,"src",".generated","content-metadata.js"),_=`// Auto-generated by MarkoPress - Do not edit\nexport default ${JSON.stringify(E,null,2)};\n`;await e.writeFile(S,_),F.end(),console.log(` Pre-rendered ${x} markdown files\n`),C?(await generateCatchAllRoutes(j,T,g,b,i,!0),console.log(" Using catch-all dynamic routes")):(await generateRoutes(j,T,g,b,i),console.log(" Using static routes")),v.end(),console.log(" Routes generated\n");const D=[];for(const[e,o]of Object.entries($))(o.handler||o.component)&&(D.push({path:e,...o}),console.log(" Found plugin route: "+e));if(console.log(`šŸ”Œ Total manifest routes: ${Object.keys($).length}, Plugin routes: ${D.length}`),y){const t=[...y.getPluginRoutes(),...D];if(t.length>0){console.log(`šŸ”Œ Generating ${t.length} plugin routes...`);const n=k("Plugin route generation");n.start(),await async function(t,n,s,a){for(const s of t){const t=s.path.slice(1),r=o.join(n,t,"+page");if(await e.mkdir(o.dirname(r),{recursive:!0}),s.handler){const t=o.join(o.dirname(r),"+handler.js");await e.writeFile(t,s.handler)}if(s.component){const o=r+".marko";await e.writeFile(o,s.component)}a&&console.log(" Generated plugin route: "+s.path)}}(t,T,0,i),n.end(),console.log(" Plugin routes generated\n")}}console.log("āš™ļø Generating Vite config...");const A=k("Vite config generation");if(A.start(),await generateViteConfig(p,i),A.end(),console.log(" Vite config generated\n"),y){console.log("šŸ”Œ Processing plugin allContentLoaded hooks...");const e=k("AllContentLoaded hooks");e.start(),await y.execAllContentLoadedHooks($),e.end(),console.log(" All content processed\n")}if(g.markdown.markoTags?.enabled){console.log("šŸ” Validating Marko tags...");const e=k("Tag validation");e.start();const o=c.validate();if(e.end(),!o.success){const e=l(o.missingTags);return console.error(`\n${e}\n`),h.push(e),{success:!1,outDir:"",pages:0,errors:h}}console.log(" All tags validated āœ“\n")}console.log("šŸŽØ Copying theme CSS...");const O=k("Theme CSS copy");O.start(),await copyThemeCSS(p,g,i),O.end(),console.log(" Theme CSS copied\n"),console.log("šŸŽØ Extracting styles from Marko components...");const M=k("Marko component styles extraction");M.start(),await extractStylesFromMarkoTags(p,g,i),M.end(),console.log(" Component styles extracted\n");const N=[];for(const e of b)for(const o of e.files)"pages"===e.id?N.push("index"===o.id?"/":"/"+o.id):N.push(o.urlPath);for(const e of Object.keys($))N.includes(e)||N.push(e);const G=o.join(p,"src",".generated","static-urls.json");await e.mkdir(o.dirname(G),{recursive:!0}),await e.writeFile(G,JSON.stringify(N,null,2)),i&&console.log(` Generated static URL manifest: ${N.length} URLs`),console.log("šŸ”Ø Building with @marko/run...");const L=k("@marko/run build");L.start();const R=r||g.build.outDir,W=await async function(e,n,s){return new Promise(a=>{const r=["build"];e&&r.push("--output",e),n&&r.push("--debug");const i=t("npx",["marko-run",...r],{stdio:"inherit",cwd:s});i.on("close",t=>{if(0===t){const t=e||"dist";a({success:!0,outDir:o.join(s,t),errors:[]})}else a({success:!1,outDir:"",errors:["Build process exited with code "+t]})}),i.on("error",e=>{a({success:!1,outDir:"",errors:["Failed to start build process: "+e.message]})})})}(R,i,p);if(L.end(),!W.success)return h.push(...W.errors),{success:!1,outDir:"",pages:0,errors:h};const I=k("Collect build assets");I.start();const B=await async function(o){const t=[];try{const n=await e.readdir(o,{recursive:!0});for(const e of n)"string"==typeof e&&(e.endsWith(".js")||e.endsWith(".css")||e.endsWith(".json"))&&t.push(e)}catch(e){console.warn("Warning: Could not collect build assets:",e)}return t}(W.outDir);if(I.end(),y){console.log("šŸ”Œ Processing plugin postBuild hooks...");const e=k("Post-build hooks");e.start(),await y.execPostBuildHooks(W.outDir,$,B),e.end(),console.log(" Post-build hooks completed\n")}console.log("šŸ“¦ Copying Marko tags directory...");const H=k("Copy tags directory");H.start(),await copyTagsDirectory(p,W.outDir,g,i),H.end(),console.log(" Tags directory copied\n"),console.log("\nāœ… Build completed successfully!"),console.log(" Output: "+W.outDir),console.log(" Pages: Generated dynamically at request time"),console.log("\nā±ļø Build timing:");const U=Array.from(w.entries()).sort((e,o)=>o[1]-e[1]);for(const[e,o]of U){const t=(o/1e3).toFixed(2);console.log(` ${"ā–ˆ".repeat(Math.min(Math.floor(o/100),20))} ${e}: ${t}s`)}return{success:!0,outDir:W.outDir,pages:0,errors:h}}catch(e){const o=e instanceof Error?e.message:e+"";return h.push(o),console.error("\nāŒ Build failed:",o),{success:!1,outDir:"",pages:0,errors:h}}}export async function generateRoutes(e,o,t,n,s){await cleanupGeneratedRoutes(o,e,s);const a=[];let r=0,i=0,c=0;for(const[o,t]of Object.entries(e)){if(!Array.isArray(t))continue;a.push(o);const e=t;if("pages"===o)for(const o of e)await b(0,0,0,0,s),r++;else if("blog"===o)for(const o of e)await $(0,0,0,0,s),c++;else for(const o of e)await T(0,0,0,0,s),i++}await v(o,t,s),await generateViteConfig(t.root,s),await C(o,t,s),s&&(console.log(` Generated ${r} page routes`),console.log(` Generated ${i} doc routes`),console.log(` Generated ${c} blog routes`))}export async function cleanupGeneratedRoutes(t,n,s){const a=[],r=["+layout.marko","+middleware.js","components/**/*","api/**/*","lib/**/*"],i=Object.keys(n).filter(e=>"pages"!==e).map(e=>e+"/");try{const n=await e.readdir(t,{recursive:!0,withFileTypes:!0});for(const c of n){if(!c.isFile())continue;const n=o.join(c.path||c.parentPath||t,c.name),l=o.relative(t,n);if(i.some(e=>l.startsWith(e)))if(r.some(e=>e.includes("**")?RegExp(e.replace(/\*\*/g,".*").replace(/\*/g,"[^/]*")).test(l):c.name===e))s&&console.log(" Preserving: "+l);else try{await e.unlink(n),s&&console.log(" Deleted: "+l)}catch(e){if("ENOENT"!==e.code){const o=e instanceof Error?e.message:e+"";a.push(`Failed to delete ${l}: ${o}`)}}}for(const e of i){const n=o.join(t,e);try{await j(n)}catch{}}a.length>0&&(console.warn("āš ļø Cleanup warnings:"),a.forEach(e=>console.warn(" "+e)))}catch(e){if("ENOENT"!==e.code)throw e}}async function j(t){try{const n=await e.readdir(t,{withFileTypes:!0});for(const e of n)if(e.isDirectory()){const n=o.join(t,e.name);await j(n)}0===(await e.readdir(t)).length&&await e.rmdir(t)}catch{}}async function b(e,o,t,n,s){s&&console.log(" Warning: Static routes deprecated, use catch-all routes")}async function T(e,o,t,n,s){s&&console.log(" Warning: Static routes deprecated, use catch-all routes")}async function $(e,o,t,n,s){s&&console.log(" Warning: Static routes deprecated, use catch-all routes")}async function v(t,n,s){const a=o.join(t,"_config.js"),r={root:n.root,site:{title:n.site?.title||"MarkoPress",description:n.site?.description||"",lang:n.site?.lang||"en-US",head:n.site?.head||[],base:n.site?.base||"/"},content:n.content,theme:{name:n.theme?.name||"@markopress/theme-default",options:n.theme?.options||{}},markdown:n.markdown||{},build:n.build||{}},i=`// Auto-generated by MarkoPress - Do not edit\nexport const config = ${JSON.stringify(r,null,2)};\n`;await e.writeFile(a,i),s&&console.log(" Generated: "+a)}async function C(t,n,s){const a=o.join(t,"+layout.marko"),r=(n.theme,n.site?.title||"MarkoPress"),i=n.theme?.options?.style||"default",c=await F("layout.marko.template",{SITE_TITLE:r,THEME_STYLE:i,BASE_PATH:n.site?.base?.replace(/\/$/,"")||""});await e.writeFile(a,c),s&&console.log(" Generated: "+a)}async function F(t,n){const s=o.dirname(new URL(import.meta.url).pathname),a=o.join(s,"..",".."),r=o.join(a,"templates",t);let i=await e.readFile(r,"utf-8");for(const[e,o]of Object.entries(n))i=i.replace(RegExp(`\\{\\{${e}\\}\\}`,"g"),o);return i}export function validateThemeName(e){if(!/^(@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/.test(e))throw Error(`Invalid theme name: "${e}". Must be a valid npm package name (e.g., "my-theme" or "@org/my-theme")`);if(e.includes(".."))throw Error(`Theme name cannot contain traversal sequences (..): "${e}"`);if(e.includes("\\"))throw Error(`Theme name cannot contain backslashes: "${e}"`);if((e.match(/\//g)||[]).length>1)throw Error(`Theme name can only contain one forward slash (for scoped packages): "${e}"`);if(o.isAbsolute(e))throw Error(`Theme name cannot be an absolute path: "${e}"`)}export async function generateViteConfig(t,n){const s=o.join(t,"vite.config.js");try{if((await e.readFile(s,"utf-8")).includes("markdownContentPlugin"))return void(n&&console.log(" Vite config already has markdownContentPlugin"))}catch{}await e.writeFile(s,"import { defineConfig } from 'vite';\nimport marko from '@marko/run/vite';\nimport { markdownContentPlugin } from 'markopress/build';\n\nexport default defineConfig({\n plugins: [\n marko(),\n markdownContentPlugin(),\n ],\n resolve: {\n // Preserve symlinks for pnpm workspace compatibility\n // This allows Marko to properly discover tags from symlinked packages\n preserveSymlinks: true,\n },\n build: {\n outDir: 'dist',\n },\n});\n"),n&&console.log(" Created vite.config.js with markdownContentPlugin")}export async function copyThemeCSS(t,n,s){const a=o.join(t,"public","_markopress","theme");await e.mkdir(a,{recursive:!0});const r=n.theme?.name||"@markopress/theme-default";try{validateThemeName(r)}catch(e){const o=e instanceof Error?e.message:e+"";throw Error("Security: "+o)}const i=n.theme?.options?.style||"default",c=`theme-${i}.css`,l=[...k(r)?[o.join(w,"public",c)]:[],o.join(t,"..","node_modules",r,"public",c),o.join(t,"node_modules",r,"public",c)];let d=null,u=null;for(const o of l)try{await e.access(o),d=await e.readFile(o,"utf-8"),u=o;break}catch{}if(!d){console.warn(` Warning: Could not find ${c}, using minimal fallback`);const t=`/* Minimal fallback CSS for style: ${i} */\nbody { font-family: system-ui, sans-serif; margin: 0; padding: 0; }`,n=o.join(a,c);return void await e.writeFile(n,t)}const g=o.join(a,c);await e.writeFile(g,d),s&&(console.log(` Copied ${c} from: ${u}`),console.log(" Output: "+g));const m="styles.css",f=[...k(r)?[o.join(w,m)]:[],o.join(t,"..","node_modules",r,"src",m),o.join(t,"node_modules",r,"src",m)];for(const t of f)try{await e.access(t);const n=await e.readFile(t,"utf-8"),r=o.join(a,m);await e.writeFile(r,n),s&&(console.log(` Copied ${m} from: ${t}`),console.log(" Output: "+r));break}catch{}}export async function extractStylesFromMarkoTags(t,n,s){const a=n.markdown?.markoTags?.tagsDir||"src/.markopress/tags",r=o.join(t,a);try{await e.access(r)}catch{return void(s&&console.log(" No tags directory found at: "+r))}const i=[];if(await async function t(n){const s=await e.readdir(n,{withFileTypes:!0});for(const e of s){const s=o.join(n,e.name);e.isDirectory()?await t(s):e.isFile()&&e.name.endsWith(".marko")&&i.push(s)}}(r),0===i.length)return void(s&&console.log(" No .marko files found in: "+r));const c=[];c.push("/* Custom markdown tag styles"),c.push(" * Loaded globally because request-time virtual markdown modules"),c.push(" * do not emit tag-local CSS assets reliably. */"),c.push("");for(const t of i){const n=o.relative(r,t),s=""===o.dirname(n)?o.basename(n,".marko"):o.join(o.dirname(n),o.basename(n,".marko"));try{const o=await e.readFile(t,"utf-8"),n=/<style\b[^>]*>([\s\S]*?)<\/style>/gi,a=Array.from(o.matchAll(n));if(a.length>0){c.push(`/* ${s}.marko */`);for(const e of a){const o=e[1]||"";if(o){const e=o.split("\n");let t=0;for(;t<e.length&&""===e[t].trim();)t++;let n=e.length-1;for(;n>=t&&""===e[n].trim();)n--;for(let o=t;o<=n;o++){const t=e[o];if(""===t.trim()){c.push("");continue}const n=t.match(/^(\s*)/),s=n?n[1].length:0,a=" ".repeat(Math.floor(s/2)),r=t.trim().replace(/:global\(([^)]+)\)/g,"$1");c.push(a+r)}}}c.push("")}}catch(e){console.warn(` Warning: Could not read file ${t}:`,e)}}const l=o.join(t,"public");await e.mkdir(l,{recursive:!0});const d=o.join(l,"markopress-components.css"),u=c.join("\n");await e.writeFile(d,u),s&&(console.log(` Extracted styles from ${i.length} Marko component(s)`),console.log(" Output: "+d))}async function P(t){const n=await e.readdir(t,{withFileTypes:!0}),s=await Promise.all(n.map(e=>{const n=o.resolve(t,e.name);return e.isDirectory()?P(n):n}));return Array.prototype.concat(...s).filter(e=>e.endsWith(".marko"))}export async function copyThemeComponents(t,n,s){const a=n.theme?.name||"@markopress/theme-default",r=o.join(t,"src"),i=o.join(r,"tags");await e.mkdir(i,{recursive:!0});const c=[...k(a)?[o.join(w,"tags")]:[],o.join(t,"..","node_modules",a,"dist","tags"),o.join(t,"node_modules",a,"dist","tags"),o.join(t,"..","node_modules",a,"src","components"),o.join(t,"node_modules",a,"src","components")];let l=null;for(const o of c)try{await e.access(o),l=o;break}catch{}if(!l)return void(s&&console.warn(" Warning: Could not find theme components, skipping"));const d=await P(l);let u=0;for(const t of d){const n=o.relative(l,t),a=o.join(i,n);let r=!1;try{await e.access(a),r=!0}catch{}r?s&&console.log(" Skipped component (user override exists): "+n):(await e.mkdir(o.dirname(a),{recursive:!0}),await e.copyFile(t,a),u++)}s&&(console.log(` Copied ${u} theme components from: ${l}`),console.log(" Output: "+i))}export async function copyTagsDirectory(t,n,s,a){const r=s.markdown?.markoTags?.tagsDir||"src/.markopress/tags",i=o.join(t,r),c=o.join(n,"tags");try{await e.access(i)}catch{return void(a&&console.log(" No tags directory found at: "+i))}await e.mkdir(c,{recursive:!0});const l=await e.readdir(i,{withFileTypes:!0});let d=0;for(const t of l){const n=o.join(i,t.name),s=o.join(c,t.name);if(t.isDirectory()){await e.mkdir(s,{recursive:!0});const t=await e.readdir(n,{withFileTypes:!0});for(const a of t){const t=o.join(n,a.name),r=o.join(s,a.name);a.isDirectory()||(await e.copyFile(t,r),d++)}}else t.isFile()&&(await e.copyFile(n,s),d++)}a&&(console.log(` Copied ${d} tag files from: ${i}`),console.log(" Output: "+c))}export async function generateCatchAllRoutes(t,n,s,a,r,i=!0){console.log(" Using catch-all dynamic routes..."),console.log(" Mode: "+(i?"build (pre-compiled)":"dev (request-time rendering)"));const c=s.content||{};for(const[t,s]of Object.entries(c))if(s&&("object"!=typeof s||null===s||"dir"in s))if("pages"===t){const t=o.join(n,"$$slug");await e.mkdir(t,{recursive:!0});const s=await F("catch-all-handler.js.template",{CONTENT_TYPE:"pages",CONFIG_PATH:"../_config.js",VITE_PLUGIN_PATH:"markopress/build",IS_BUILD:i?"true":"false"});await e.writeFile(o.join(t,"+handler.js"),s);const a=await F("catch-all-page.marko.template",{CONTENT_TYPE_CLASS:"page"});await e.writeFile(o.join(t,"+page.marko"),a),r&&console.log(" Generated pages catch-all route")}else{const s=o.join(n,t,"$$slug");await e.mkdir(s,{recursive:!0});const a=await F("catch-all-handler.js.template",{CONTENT_TYPE:t,CONFIG_PATH:"../../_config.js",VITE_PLUGIN_PATH:"markopress/build",IS_BUILD:i?"true":"false"});await e.writeFile(o.join(s,"+handler.js"),a);const c=await F("catch-all-page.marko.template",{CONTENT_TYPE_CLASS:t});await e.writeFile(o.join(s,"+page.marko"),c),r&&console.log(` Generated ${t} catch-all route`)}await v(n,s,r),await generateViteConfig(s.root,r),await C(n,s,r)}export{u as loadMarkdownModule,g as registerMarkdownContent};export{markdownContentPlugin}from"./vite-markdown-plugin.js";
1
+ import{promises as e}from"node:fs";import o from"node:path";import{spawn as t}from"node:child_process";import{fileURLToPath as n}from"node:url";import s from"gray-matter";import{loadConfig as a}from"../config/loader.js";import{getDesignSystem as r,getDarkModeOverride as i}from"../theme/default/design-systems/index.js";import{globalTagValidator as c,formatValidationError as l}from"../markdown/tag-validator.js";import{PluginManager as d}from"../plugin/manager.js";import{loadMarkdownModule as u,registerMarkdownContent as m,escapeMarkoText as g}from"./vite-markdown-plugin.js";import{renderMarkdown as f}from"../markdown/renderer.js";const p=o.dirname(n(import.meta.url)),h=o.resolve(p,"..",".."),w=o.join(h,"src","theme","default"),k=new Set(["@markopress/theme-default","theme-default","default"]);function y(e){return k.has(e)}export async function build(n={}){const{outDir:r,debug:i=!1,useCatchAllRoutes:u,root:m}=n,p=m||process.cwd(),h=[],w=new Map,k=new Map,y=e=>({start:()=>{k.set(e,performance.now())},end:()=>{const o=k.get(e)||0,t=performance.now()-o;w.set(e,t)}});try{console.log("šŸš€ Building MarkoPress site...\n");const n=y("Config loading");n.start();const m=await a(p,{mode:"production",command:"build"});let k;if(n.end(),m.plugins&&m.plugins.length>0){console.log("šŸ”Œ Loading plugins...");const e=y("Plugin loading");e.start(),k=new d(m),await k.loadPlugins(m.plugins),e.end(),console.log("")}if(k){console.log("šŸ“¦ Loading plugin content...");const e=y("Plugin loadContent hooks");e.start(),await k.execLoadContentHooks(),e.end(),console.log(" Plugin content loaded\n")}const b={},T=[];for(const[t,n]of Object.entries(m.content)){const a="string"==typeof n?{dir:n}:n;if(!a?.dir)continue;const r=new Map,i={id:t,dir:a.dir,config:a,enhance(e,o){r.set(e,o)},getEnhancement:e=>r.get(e),files:[],_enhancements:r},c=o.resolve(p,a.dir);try{const n=await e.readdir(c,{withFileTypes:!0});for(const a of n)if(a.isFile()&&a.name.endsWith(".md")){const n=o.join(c,a.name),r=await e.readFile(n,"utf-8");let l={};try{l=s(r).data}catch{}i.files.push({id:a.name.replace(".md",""),slug:a.name.replace(".md",""),filePath:n,urlPath:"index"===a.name.replace(".md","")?"/"+t:`/${t}/${a.name.replace(".md","")}`,processed:{frontmatter:l}})}}catch{}T.push(i)}if(k&&T.length>0){console.log("šŸ”Œ Enhancing modules with plugin metadata...");const t=y("Module enhancement");t.start();for(const e of T)console.log(` Module: ${e.id} (${e.files.length} files)`),e.files.length>0&&console.log(" First file has processed: "+!!e.files[0].processed);await k.execEnhanceModulesHooks(T),t.end(),console.log(` Enhanced ${T.length} module(s)\n`);const n=o.join(p,"src",".generated");await e.mkdir(n,{recursive:!0});const s=(m.site?.base||"/").replace(/\/$/,""),a={};for(const e of T){const o={},t=e._enhancements.entries();for(const[e,n]of t)o[e]=n;Object.keys(o).length>0&&(s&&j(o,s),a[e.id]=o)}const r=o.join(n,"module-enhancements.js"),i=`// Auto-generated by MarkoPress - Do not edit\nexport default ${JSON.stringify(a,null,2)};\n`;await e.writeFile(r,i,"utf-8"),console.log(" Wrote module enhancements to src/.generated/module-enhancements.js\n")}if(m.markdown.markoTags?.enabled){const e=o.join(p,m.markdown.markoTags.tagsDir||"src/.markopress/tags");console.log("šŸ” Scanning tags directory...");const t=y("Tag validation setup");t.start(),await c.loadAvailableTags(e),t.end(),console.log(` Found ${c.getAvailableTagsCount()} tags\n`)}else c.reset();const $=o.join(p,"src","routes");await e.mkdir($,{recursive:!0});let v={};if(k){const e=y("Extend routes hooks");e.start(),v=await k.execExtendRoutesHooks(v),e.end(),console.log("šŸ”Œ Extended routes manifest:",Object.keys(v).length)}console.log("šŸ“ Generating routes from content...");const C=y("Route generation");C.start();const P=u??m.build.useCatchAllRoutes;console.log("šŸ“„ Pre-rendering markdown to .marko files...");const F=y("Pre-render markdown");F.start();const E=o.join(p,"src",".generated","markdown");await e.mkdir(E,{recursive:!0});const x={};let S=0;for(const t of T){const n=o.join(E,t.id);await e.mkdir(n,{recursive:!0});for(const s of t.files)try{const a=await e.readFile(s.filePath,"utf-8"),r=(m.site?.base||"/").replace(/\/$/,""),i=await f(a,{base:r});let c=i.html.replace(/<span class="line"><\/span>(\s*<\/code>)/g,"$1");const l=`<div class="markdown-content">\n${g(c)}\n</div>`,d=o.join(n,s.slug+".marko");await e.writeFile(d,l),x[`${t.id}/${s.slug}`]={frontmatter:i.frontmatter,headers:i.headers||[]},S++}catch(e){console.warn(` Warning: Failed to pre-render ${t.id}/${s.slug}:`,e)}}const A=o.join(p,"src",".generated","content-metadata.js"),_=`// Auto-generated by MarkoPress - Do not edit\nexport default ${JSON.stringify(x,null,2)};\n`;await e.writeFile(A,_),F.end(),console.log(` Pre-rendered ${S} markdown files\n`),P?(await generateCatchAllRoutes(b,$,m,T,i,!0),console.log(" Using catch-all dynamic routes")):(await generateRoutes(b,$,m,T,i),console.log(" Using static routes")),C.end(),console.log(" Routes generated\n");const D=[];for(const[e,o]of Object.entries(v))(o.handler||o.component)&&(D.push({path:e,...o}),console.log(" Found plugin route: "+e));if(console.log(`šŸ”Œ Total manifest routes: ${Object.keys(v).length}, Plugin routes: ${D.length}`),k){const t=[...k.getPluginRoutes(),...D];if(t.length>0){console.log(`šŸ”Œ Generating ${t.length} plugin routes...`);const n=y("Plugin route generation");n.start(),await async function(t,n,s,a){for(const s of t){const t=s.path.slice(1),r=o.join(n,t,"+page");if(await e.mkdir(o.dirname(r),{recursive:!0}),s.handler){const t=o.join(o.dirname(r),"+handler.js");await e.writeFile(t,s.handler)}if(s.component){const o=r+".marko";await e.writeFile(o,s.component)}a&&console.log(" Generated plugin route: "+s.path)}}(t,$,0,i),n.end(),console.log(" Plugin routes generated\n")}}console.log("āš™ļø Generating Vite config...");const O=y("Vite config generation");if(O.start(),await generateViteConfig(p,i),O.end(),console.log(" Vite config generated\n"),k){console.log("šŸ”Œ Processing plugin allContentLoaded hooks...");const e=y("AllContentLoaded hooks");e.start(),await k.execAllContentLoadedHooks(v),e.end(),console.log(" All content processed\n")}if(m.markdown.markoTags?.enabled){console.log("šŸ” Validating Marko tags...");const e=y("Tag validation");e.start();const o=c.validate();if(e.end(),!o.success){const e=l(o.missingTags);return console.error(`\n${e}\n`),h.push(e),{success:!1,outDir:"",pages:0,errors:h}}console.log(" All tags validated āœ“\n")}console.log("šŸŽØ Copying theme CSS...");const M=y("Theme CSS copy");M.start(),await copyThemeCSS(p,m,i),M.end(),console.log(" Theme CSS copied\n"),console.log("šŸŽØ Extracting styles from Marko components...");const N=y("Marko component styles extraction");N.start(),await extractStylesFromMarkoTags(p,m,i),N.end(),console.log(" Component styles extracted\n");const G=[];for(const e of T)for(const o of e.files)"pages"===e.id?G.push("index"===o.id?"/":"/"+o.id):G.push(o.urlPath);for(const e of Object.keys(v))G.includes(e)||G.push(e);const W=o.join(p,"src",".generated","static-urls.json");await e.mkdir(o.dirname(W),{recursive:!0}),await e.writeFile(W,JSON.stringify(G,null,2)),i&&console.log(` Generated static URL manifest: ${G.length} URLs`),console.log("šŸ”Ø Building with @marko/run...");const L=y("@marko/run build");L.start();const R=r||m.build.outDir,I=await async function(e,n,s){return new Promise(a=>{const r=["build"];e&&r.push("--output",e),n&&r.push("--debug");const i=t("npx",["marko-run",...r],{stdio:"inherit",cwd:s});i.on("close",t=>{if(0===t){const t=e||"dist";a({success:!0,outDir:o.join(s,t),errors:[]})}else a({success:!1,outDir:"",errors:["Build process exited with code "+t]})}),i.on("error",e=>{a({success:!1,outDir:"",errors:["Failed to start build process: "+e.message]})})})}(R,i,p);if(L.end(),!I.success)return h.push(...I.errors),{success:!1,outDir:"",pages:0,errors:h};const B=y("Collect build assets");B.start();const H=await async function(o){const t=[];try{const n=await e.readdir(o,{recursive:!0});for(const e of n)"string"==typeof e&&(e.endsWith(".js")||e.endsWith(".css")||e.endsWith(".json"))&&t.push(e)}catch(e){console.warn("Warning: Could not collect build assets:",e)}return t}(I.outDir);if(B.end(),k){console.log("šŸ”Œ Processing plugin postBuild hooks...");const e=y("Post-build hooks");e.start(),await k.execPostBuildHooks(I.outDir,v,H),e.end(),console.log(" Post-build hooks completed\n")}console.log("šŸ“¦ Copying Marko tags directory...");const U=y("Copy tags directory");U.start(),await copyTagsDirectory(p,I.outDir,m,i),U.end(),console.log(" Tags directory copied\n"),console.log("\nāœ… Build completed successfully!"),console.log(" Output: "+I.outDir),console.log(" Pages: Generated dynamically at request time"),console.log("\nā±ļø Build timing:");const V=Array.from(w.entries()).sort((e,o)=>o[1]-e[1]);for(const[e,o]of V){const t=(o/1e3).toFixed(2);console.log(` ${"ā–ˆ".repeat(Math.min(Math.floor(o/100),20))} ${e}: ${t}s`)}return{success:!0,outDir:I.outDir,pages:0,errors:h}}catch(e){const o=e instanceof Error?e.message:e+"";return h.push(o),console.error("\nāŒ Build failed:",o),{success:!1,outDir:"",pages:0,errors:h}}}function j(e,o){Array.isArray(e.sidebar)&&(e.sidebar=e.sidebar.map(e=>({...e,items:Array.isArray(e.items)?e.items.map(e=>({...e,link:e.link&&!e.link.startsWith(o)?o+e.link:e.link})):e.items}))),Array.isArray(e.blogPosts)&&(e.blogPosts=e.blogPosts.map(e=>({...e,link:e.link&&!e.link.startsWith(o)?o+e.link:e.link})))}export async function generateRoutes(e,o,t,n,s){await cleanupGeneratedRoutes(o,e,s);const a=[];let r=0,i=0,c=0;for(const[o,t]of Object.entries(e)){if(!Array.isArray(t))continue;a.push(o);const e=t;if("pages"===o)for(const o of e)await T(0,0,0,0,s),r++;else if("blog"===o)for(const o of e)await v(0,0,0,0,s),c++;else for(const o of e)await $(0,0,0,0,s),i++}await C(o,t,s),await generateViteConfig(t.root,s),await P(o,t,s),s&&(console.log(` Generated ${r} page routes`),console.log(` Generated ${i} doc routes`),console.log(` Generated ${c} blog routes`))}export async function cleanupGeneratedRoutes(t,n,s){const a=[],r=["+layout.marko","+middleware.js","components/**/*","api/**/*","lib/**/*"],i=Object.keys(n).filter(e=>"pages"!==e).map(e=>e+"/");try{const n=await e.readdir(t,{recursive:!0,withFileTypes:!0});for(const c of n){if(!c.isFile())continue;const n=o.join(c.path||c.parentPath||t,c.name),l=o.relative(t,n);if(i.some(e=>l.startsWith(e)))if(r.some(e=>e.includes("**")?RegExp(e.replace(/\*\*/g,".*").replace(/\*/g,"[^/]*")).test(l):c.name===e))s&&console.log(" Preserving: "+l);else try{await e.unlink(n),s&&console.log(" Deleted: "+l)}catch(e){if("ENOENT"!==e.code){const o=e instanceof Error?e.message:e+"";a.push(`Failed to delete ${l}: ${o}`)}}}for(const e of i){const n=o.join(t,e);try{await b(n)}catch{}}a.length>0&&(console.warn("āš ļø Cleanup warnings:"),a.forEach(e=>console.warn(" "+e)))}catch(e){if("ENOENT"!==e.code)throw e}}async function b(t){try{const n=await e.readdir(t,{withFileTypes:!0});for(const e of n)if(e.isDirectory()){const n=o.join(t,e.name);await b(n)}0===(await e.readdir(t)).length&&await e.rmdir(t)}catch{}}async function T(e,o,t,n,s){s&&console.log(" Warning: Static routes deprecated, use catch-all routes")}async function $(e,o,t,n,s){s&&console.log(" Warning: Static routes deprecated, use catch-all routes")}async function v(e,o,t,n,s){s&&console.log(" Warning: Static routes deprecated, use catch-all routes")}async function C(t,n,s){const a=o.join(t,"_config.js"),r={root:n.root,site:{title:n.site?.title||"MarkoPress",description:n.site?.description||"",lang:n.site?.lang||"en-US",head:n.site?.head||[],base:n.site?.base||"/"},content:n.content,theme:{name:n.theme?.name||"@markopress/theme-default",options:n.theme?.options||{}},markdown:n.markdown||{},build:n.build||{}},i=(n.site?.base||"/").replace(/\/$/,"");i&&r.theme.options?.navbar&&(r.theme.options.navbar=r.theme.options.navbar.map(e=>({...e,link:e.link&&!e.link.startsWith(i)?i+e.link:e.link})));const c=`// Auto-generated by MarkoPress - Do not edit\nexport const config = ${JSON.stringify(r,null,2)};\n`;await e.writeFile(a,c),s&&console.log(" Generated: "+a)}async function P(t,n,s){const a=o.join(t,"+layout.marko"),r=(n.theme,n.site?.title||"MarkoPress"),i=n.theme?.options?.style||"default",c=await F("layout.marko.template",{SITE_TITLE:r,THEME_STYLE:i,BASE_PATH:n.site?.base?.replace(/\/$/,"")||""});await e.writeFile(a,c),s&&console.log(" Generated: "+a)}async function F(t,n){const s=o.dirname(new URL(import.meta.url).pathname),a=o.join(s,"..",".."),r=o.join(a,"templates",t);let i=await e.readFile(r,"utf-8");for(const[e,o]of Object.entries(n))i=i.replace(RegExp(`\\{\\{${e}\\}\\}`,"g"),o);return i}export function validateThemeName(e){if(!/^(@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/.test(e))throw Error(`Invalid theme name: "${e}". Must be a valid npm package name (e.g., "my-theme" or "@org/my-theme")`);if(e.includes(".."))throw Error(`Theme name cannot contain traversal sequences (..): "${e}"`);if(e.includes("\\"))throw Error(`Theme name cannot contain backslashes: "${e}"`);if((e.match(/\//g)||[]).length>1)throw Error(`Theme name can only contain one forward slash (for scoped packages): "${e}"`);if(o.isAbsolute(e))throw Error(`Theme name cannot be an absolute path: "${e}"`)}export async function generateViteConfig(t,n){const s=o.join(t,"vite.config.js");try{if((await e.readFile(s,"utf-8")).includes("markdownContentPlugin"))return void(n&&console.log(" Vite config already has markdownContentPlugin"))}catch{}await e.writeFile(s,"import { defineConfig } from 'vite';\nimport marko from '@marko/run/vite';\nimport { markdownContentPlugin } from 'markopress/build';\n\nexport default defineConfig({\n plugins: [\n marko(),\n markdownContentPlugin(),\n ],\n resolve: {\n // Preserve symlinks for pnpm workspace compatibility\n // This allows Marko to properly discover tags from symlinked packages\n preserveSymlinks: true,\n },\n build: {\n outDir: 'dist',\n },\n});\n"),n&&console.log(" Created vite.config.js with markdownContentPlugin")}export async function copyThemeCSS(t,n,s){const a=o.join(t,"public","_markopress","theme");await e.mkdir(a,{recursive:!0});const r=n.theme?.name||"@markopress/theme-default";try{validateThemeName(r)}catch(e){const o=e instanceof Error?e.message:e+"";throw Error("Security: "+o)}const i=n.theme?.options?.style||"default",c=`theme-${i}.css`,l=[...y(r)?[o.join(w,"public",c)]:[],o.join(t,"..","node_modules",r,"public",c),o.join(t,"node_modules",r,"public",c)];let d=null,u=null;for(const o of l)try{await e.access(o),d=await e.readFile(o,"utf-8"),u=o;break}catch{}if(!d){console.warn(` Warning: Could not find ${c}, using minimal fallback`);const t=`/* Minimal fallback CSS for style: ${i} */\nbody { font-family: system-ui, sans-serif; margin: 0; padding: 0; }`,n=o.join(a,c);return void await e.writeFile(n,t)}const m=o.join(a,c);await e.writeFile(m,d),s&&(console.log(` Copied ${c} from: ${u}`),console.log(" Output: "+m));const g="styles.css",f=[...y(r)?[o.join(w,g)]:[],o.join(t,"..","node_modules",r,"src",g),o.join(t,"node_modules",r,"src",g)];for(const t of f)try{await e.access(t);const n=await e.readFile(t,"utf-8"),r=o.join(a,g);await e.writeFile(r,n),s&&(console.log(` Copied ${g} from: ${t}`),console.log(" Output: "+r));break}catch{}}export async function extractStylesFromMarkoTags(t,n,s){const a=n.markdown?.markoTags?.tagsDir||"src/.markopress/tags",r=o.join(t,a);try{await e.access(r)}catch{return void(s&&console.log(" No tags directory found at: "+r))}const i=[];if(await async function t(n){const s=await e.readdir(n,{withFileTypes:!0});for(const e of s){const s=o.join(n,e.name);e.isDirectory()?await t(s):e.isFile()&&e.name.endsWith(".marko")&&i.push(s)}}(r),0===i.length)return void(s&&console.log(" No .marko files found in: "+r));const c=[];c.push("/* Custom markdown tag styles"),c.push(" * Loaded globally because request-time virtual markdown modules"),c.push(" * do not emit tag-local CSS assets reliably. */"),c.push("");for(const t of i){const n=o.relative(r,t),s=""===o.dirname(n)?o.basename(n,".marko"):o.join(o.dirname(n),o.basename(n,".marko"));try{const o=await e.readFile(t,"utf-8"),n=/<style\b[^>]*>([\s\S]*?)<\/style>/gi,a=Array.from(o.matchAll(n));if(a.length>0){c.push(`/* ${s}.marko */`);for(const e of a){const o=e[1]||"";if(o){const e=o.split("\n");let t=0;for(;t<e.length&&""===e[t].trim();)t++;let n=e.length-1;for(;n>=t&&""===e[n].trim();)n--;for(let o=t;o<=n;o++){const t=e[o];if(""===t.trim()){c.push("");continue}const n=t.match(/^(\s*)/),s=n?n[1].length:0,a=" ".repeat(Math.floor(s/2)),r=t.trim().replace(/:global\(([^)]+)\)/g,"$1");c.push(a+r)}}}c.push("")}}catch(e){console.warn(` Warning: Could not read file ${t}:`,e)}}const l=o.join(t,"public");await e.mkdir(l,{recursive:!0});const d=o.join(l,"markopress-components.css"),u=c.join("\n");await e.writeFile(d,u),s&&(console.log(` Extracted styles from ${i.length} Marko component(s)`),console.log(" Output: "+d))}async function E(t){const n=await e.readdir(t,{withFileTypes:!0}),s=await Promise.all(n.map(e=>{const n=o.resolve(t,e.name);return e.isDirectory()?E(n):n}));return Array.prototype.concat(...s).filter(e=>e.endsWith(".marko"))}export async function copyThemeComponents(t,n,s){const a=n.theme?.name||"@markopress/theme-default",r=o.join(t,"src"),i=o.join(r,"tags");await e.mkdir(i,{recursive:!0});const c=[...y(a)?[o.join(w,"tags")]:[],o.join(t,"..","node_modules",a,"dist","tags"),o.join(t,"node_modules",a,"dist","tags"),o.join(t,"..","node_modules",a,"src","components"),o.join(t,"node_modules",a,"src","components")];let l=null;for(const o of c)try{await e.access(o),l=o;break}catch{}if(!l)return void(s&&console.warn(" Warning: Could not find theme components, skipping"));const d=await E(l);let u=0;for(const t of d){const n=o.relative(l,t),a=o.join(i,n);let r=!1;try{await e.access(a),r=!0}catch{}r?s&&console.log(" Skipped component (user override exists): "+n):(await e.mkdir(o.dirname(a),{recursive:!0}),await e.copyFile(t,a),u++)}s&&(console.log(` Copied ${u} theme components from: ${l}`),console.log(" Output: "+i))}export async function copyTagsDirectory(t,n,s,a){const r=s.markdown?.markoTags?.tagsDir||"src/.markopress/tags",i=o.join(t,r),c=o.join(n,"tags");try{await e.access(i)}catch{return void(a&&console.log(" No tags directory found at: "+i))}await e.mkdir(c,{recursive:!0});const l=await e.readdir(i,{withFileTypes:!0});let d=0;for(const t of l){const n=o.join(i,t.name),s=o.join(c,t.name);if(t.isDirectory()){await e.mkdir(s,{recursive:!0});const t=await e.readdir(n,{withFileTypes:!0});for(const a of t){const t=o.join(n,a.name),r=o.join(s,a.name);a.isDirectory()||(await e.copyFile(t,r),d++)}}else t.isFile()&&(await e.copyFile(n,s),d++)}a&&(console.log(` Copied ${d} tag files from: ${i}`),console.log(" Output: "+c))}export async function generateCatchAllRoutes(t,n,s,a,r,i=!0){console.log(" Using catch-all dynamic routes..."),console.log(" Mode: "+(i?"build (pre-compiled)":"dev (request-time rendering)"));const c=s.content||{};for(const[t,s]of Object.entries(c))if(s&&("object"!=typeof s||null===s||"dir"in s))if("pages"===t){const t=o.join(n,"$$slug");await e.mkdir(t,{recursive:!0});const s=await F("catch-all-handler.js.template",{CONTENT_TYPE:"pages",CONFIG_PATH:"../_config.js",VITE_PLUGIN_PATH:"markopress/build",IS_BUILD:i?"true":"false"});await e.writeFile(o.join(t,"+handler.js"),s);const a=await F("catch-all-page.marko.template",{CONTENT_TYPE_CLASS:"page"});await e.writeFile(o.join(t,"+page.marko"),a),r&&console.log(" Generated pages catch-all route")}else{const s=o.join(n,t,"$$slug");await e.mkdir(s,{recursive:!0});const a=await F("catch-all-handler.js.template",{CONTENT_TYPE:t,CONFIG_PATH:"../../_config.js",VITE_PLUGIN_PATH:"markopress/build",IS_BUILD:i?"true":"false"});await e.writeFile(o.join(s,"+handler.js"),a);const c=await F("catch-all-page.marko.template",{CONTENT_TYPE_CLASS:t});await e.writeFile(o.join(s,"+page.marko"),c),r&&console.log(` Generated ${t} catch-all route`)}await C(n,s,r),await generateViteConfig(s.root,r),await P(n,s,r)}export{u as loadMarkdownModule,m as registerMarkdownContent};export{markdownContentPlugin}from"./vite-markdown-plugin.js";
package/dist/dev/index.js CHANGED
@@ -1 +1 @@
1
- import{promises as o}from"node:fs";import e from"node:path";import{spawn as t}from"node:child_process";import{loadConfig as r}from"../config/index.js";import{PluginManager as s}from"../plugin/manager.js";import{generateRoutes as n,copyThemeCSS as i,generateCatchAllRoutes as l}from"../build/index.js";export async function startDevServer(c={}){console.log("šŸš€ Starting MarkoPress dev server...\n");const a=c.root||process.cwd(),d=await r(a,{mode:"development",command:"dev"});let p;console.log("āœ“ Config loaded from "+d.root),d.plugins&&d.plugins.length>0&&(p=new s(d),await p.loadPlugins(d.plugins),await p.execLoadContentHooks());const m={},g=[];console.log("šŸ“ Generating routes from content...");const u=e.join(d.root,"src","routes"),v=c.useCatchAllRoutes??d.build.useCatchAllRoutes;await o.mkdir(u,{recursive:!0});let x={};p&&(x=await p.execExtendRoutesHooks(x)),v?(await l(m,u,d,g,!1,!1),console.log(" Using catch-all dynamic routes")):(await n(m,u,d,g,!1),console.log(" Using static routes")),console.log(" Routes generated\n"),p&&await p.execAllContentLoadedHooks(x),console.log("šŸŽØ Copying theme CSS..."),await i(d.root,d,!1),console.log(" Theme CSS copied\n"),console.log("šŸ”Ø Starting @marko/run dev server...\n");const w=c.port||3e3,f=["dev"];w&&f.push("--port",w+"");const h=t("npx",["marko-run",...f],{stdio:"inherit",cwd:d.root});h.on("error",o=>{console.error("Failed to start dev server:",o),process.exit(1)}),h.on("exit",o=>{0!==o&&(console.error("Dev server exited with code "+o),process.exit(o||1))}),process.on("SIGINT",()=>{h.kill("SIGINT"),process.exit(0)}),process.on("SIGTERM",()=>{h.kill("SIGTERM"),process.exit(0)})}
1
+ import{promises as o}from"node:fs";import e from"node:path";import{spawn as r}from"node:child_process";import{loadConfig as t}from"../config/index.js";import{PluginManager as s}from"../plugin/manager.js";import{generateRoutes as n,copyThemeCSS as i,generateCatchAllRoutes as c}from"../build/index.js";export async function startDevServer(a={}){console.log("šŸš€ Starting MarkoPress dev server...\n");const l=a.root||process.cwd(),d=await t(l,{mode:"development",command:"dev"});let m;console.log("āœ“ Config loaded from "+d.root),d.plugins&&d.plugins.length>0&&(m=new s(d),await m.loadPlugins(d.plugins),await m.execLoadContentHooks());const p=e.join(d.root,"src",".generated","markdown");await o.rm(p,{recursive:!0,force:!0});const g={},u=[];console.log("šŸ“ Generating routes from content...");const v=e.join(d.root,"src","routes"),w=a.useCatchAllRoutes??d.build.useCatchAllRoutes;await o.mkdir(v,{recursive:!0});let x={};m&&(x=await m.execExtendRoutesHooks(x)),w?(await c(g,v,d,u,!1,!1),console.log(" Using catch-all dynamic routes")):(await n(g,v,d,u,!1),console.log(" Using static routes")),console.log(" Routes generated\n"),m&&await m.execAllContentLoadedHooks(x),console.log("šŸŽØ Copying theme CSS..."),await i(d.root,d,!1),console.log(" Theme CSS copied\n"),console.log("šŸ”Ø Starting @marko/run dev server...\n");const f=a.port||3e3,h=["dev"];f&&h.push("--port",f+"");const S=r("npx",["marko-run",...h],{stdio:"inherit",cwd:d.root});S.on("error",o=>{console.error("Failed to start dev server:",o),process.exit(1)}),S.on("exit",o=>{0!==o&&(console.error("Dev server exited with code "+o),process.exit(o||1))}),process.on("SIGINT",()=>{S.kill("SIGINT"),process.exit(0)}),process.on("SIGTERM",()=>{S.kill("SIGTERM"),process.exit(0)})}
@@ -0,0 +1,16 @@
1
+ import type MarkdownIt from 'markdown-it';
2
+ /**
3
+ * markdown-it plugin that prefixes absolute internal links with a base path.
4
+ *
5
+ * Rewrites:
6
+ * /features → /markopress/features
7
+ * /blog/my-post → /markopress/blog/my-post
8
+ *
9
+ * Does NOT rewrite:
10
+ * https://... (external)
11
+ * //cdn.com/... (protocol-relative)
12
+ * #section (anchor)
13
+ * mailto:... (non-http)
14
+ * paths already starting with base
15
+ */
16
+ export declare function basePathPlugin(md: MarkdownIt, base: string): void;
@@ -0,0 +1 @@
1
+ export function basePathPlugin(t,n){const s=n.replace(/\/$/,"");if(!s||"/"===s)return;const o=t.renderer.rules.link_open||((e,r,t,n,s)=>s.renderToken(e,r,t));t.renderer.rules.link_open=(r,t,n,c,l)=>{const i=r[t].attrIndex("href");if(i>=0){const n=r[t].attrs[i][1];r[t].attrs[i][1]=e(n,s)}return o(r,t,n,c,l)};const c=t.renderer.rules.image||((e,r,t,n,s)=>s.renderToken(e,r,t));t.renderer.rules.image=(r,t,n,o,l)=>{const i=r[t].attrIndex("src");if(i>=0){const n=r[t].attrs[i][1];r[t].attrs[i][1]=e(n,s)}return c(r,t,n,o,l)};const l=t.renderer.rules.html_block||((e,r)=>e[r].content);t.renderer.rules.html_block=(e,t,n,o,c)=>(e[t].content=r(e[t].content,s),l(e,t,n,o,c));const i=t.renderer.rules.html_inline||((e,r)=>e[r].content);t.renderer.rules.html_inline=(e,t,n,o,c)=>(e[t].content=r(e[t].content,s),i(e,t,n,o,c))}function e(e,r){return e.startsWith("/")?e.startsWith("//")||e.startsWith(r+"/")||e===r?e:r+e:e}function r(r,t){return r.replace(/((?:href|src)\s*=\s*)(["'])(\/(?!\/)[^"']*)\2/gi,(r,n,s,o)=>n+s+e(o,t)+s)}
@@ -1 +1 @@
1
- import e from"gray-matter";import t from"markdown-it";import r from"markdown-it-anchor";import a from"markdown-it-attrs";import*as n from"markdown-it-emoji";import{createHighlighter as o}from"shiki";import{setupContainers as s,setupDetails as i}from"./containers.js";import{createEnhancedHighlighter as c}from"./code.js";import{preprocessIncludesWithRegions as l}from"./includes.js";import{preserveTagsPlugin as p}from"./preserve-tags.js";import{globalTagValidator as g}from"./tag-validator.js";let u=null;const m=new Set,d=["javascript","typescript","js","ts","bash","markdown","md"],f={js:"javascript",ts:"typescript",py:"python",rs:"rust",sh:"bash",shell:"bash",yml:"yaml",cs:"csharp",cpp:"c++"};function h(e){return f[e]||e}async function y(){return u||(u=await o({themes:["github-light","github-dark"],langs:Array.from(d)}),d.forEach(e=>m.add(h(e)))),u}export async function preloadLanguages(e){u||await y();const t=[];for(const r of e){const e=h(r);m.has(e)||t.push((async()=>{try{const{bundledLanguages:t}=await import("shiki/langs");e in t&&(await u.loadLanguage(t[e]),m.add(e))}catch{}})())}await Promise.all(t)}export async function getMarkdownIt(e={},o={}){const l=await y(),u=c(l,{lineNumbers:e.lineNumbers??!0}),m=new t({html:!0,linkify:!0,typographer:!0,highlight:(e,t,r)=>{if(!t)return"";try{return u(e,t,r)}catch(e){return""}}});return m.use(r,{slugify:k,permalink:r.permalink.linkInsideHeader({symbol:"#",placement:"before"})}),m.use(a),m.use(n.full||n.bare),s(m),i(m),e.markoTags?.enabled&&m.use(p,{tagsDir:e.markoTags?.tagsDir||"tags/",onTagDetected:(e,t)=>{g.addDetectedTag(e,o.filePath||"unknown",t)}}),m}export async function parseMarkdown(t,r={},a={},n){const{data:o,content:s,excerpt:i}=e(t,{excerpt:!0,excerpt_separator:"\x3c!-- more --\x3e"}),c=await l(s,{root:a.rootDir??process.cwd(),currentFile:a.filePath??""}),p=n||await async function(e,t){return getMarkdownIt(e,t)}(r,a),g=p.render(c,a),u=a.extractToc?function(e){const t=[],r=e.replace(/```[\s\S]*?```/g,"").replace(/~~~[\s\S]*?~~~/g,"").replace(/^(\t| {4}).+$/gm,""),a=/^(#{1,6})\s+(.+)$/gm;let n;for(;null!==(n=a.exec(r));){const e=n[1].length,r=n[2].trim(),a=w(r),o=k(r);t.push({level:e,title:a,slug:o})}return t}(c):[];return{frontmatter:o,content:c,html:g,excerpt:i,headers:b(u)}}function w(e){return e.replace(/`([^`]+)`/g,"$1").replace(/\*\*\*\+([^*]+)\*\*\+/g,"$1").replace(/___+([^_]+)___+/g,"$1").replace(/\*\*([^*]+)\*\*/g,"$1").replace(/__([^_]+)__/g,"$1").replace(/\*([^*]+)\*/g,"$1").replace(/_([^_]+)_/g,"$1").replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/\[([^\]]+)\]\[[^\]]+\]/g,"$1").trim()}function b(e){const t=[],r=[];for(const a of e){const e={level:a.level,title:a.title,slug:a.slug,children:[]};for(;r.length>0&&r[r.length-1].level>=a.level;)r.pop();0===r.length?t.push(e):r[r.length-1].children.push(e),r.push(e)}return t}function k(e){return e.trim().replace(/([a-z])([A-Z])/g,"$1-$2").replace(/([0-9])([a-zA-Z])/g,"$1-$2").replace(/([a-zA-Z])([0-9])/g,"$1-$2").toLowerCase().replace(/\s+/g,"-").replace(/[^\w\u00A0-\uFFFF\-]+/g,"").replace(/^-+|-+$/g,"").replace(/-+/g,"-")}export function validateFrontmatter(e){const t=[];return void 0!==e.title&&"string"!=typeof e.title&&t.push("title must be a string"),void 0!==e.description&&"string"!=typeof e.description&&t.push("description must be a string"),void 0!==e.draft&&"boolean"!=typeof e.draft&&t.push("draft must be a boolean"),void 0!==e.date&&("string"==typeof e.date||e.date instanceof Date||t.push("date must be a string or Date")),void 0===e.tags||Array.isArray(e.tags)||t.push("tags must be an array"),void 0===e.categories||Array.isArray(e.categories)||t.push("categories must be an array"),{valid:0===t.length,errors:t}}
1
+ import e from"gray-matter";import t from"markdown-it";import r from"markdown-it-anchor";import a from"markdown-it-attrs";import*as s from"markdown-it-emoji";import{createHighlighter as n}from"shiki";import{setupContainers as o,setupDetails as i}from"./containers.js";import{createEnhancedHighlighter as c}from"./code.js";import{preprocessIncludesWithRegions as l}from"./includes.js";import{preserveTagsPlugin as p}from"./preserve-tags.js";import{globalTagValidator as g}from"./tag-validator.js";import{basePathPlugin as u}from"./base-path-plugin.js";import{mdLinkPlugin as m}from"./md-link-plugin.js";let d=null;const f=new Set,h=["javascript","typescript","js","ts","bash","markdown","md"],y={js:"javascript",ts:"typescript",py:"python",rs:"rust",sh:"bash",shell:"bash",yml:"yaml",cs:"csharp",cpp:"c++"};function b(e){return y[e]||e}async function w(){return d||(d=await n({themes:["github-light","github-dark"],langs:Array.from(h)}),h.forEach(e=>f.add(b(e)))),d}export async function preloadLanguages(e){d||await w();const t=[];for(const r of e){const e=b(r);f.has(e)||t.push((async()=>{try{const{bundledLanguages:t}=await import("shiki/langs");e in t&&(await d.loadLanguage(t[e]),f.add(e))}catch{}})())}await Promise.all(t)}export async function getMarkdownIt(e={},n={}){const l=await w(),d=c(l,{lineNumbers:e.lineNumbers??!0}),f=new t({html:!0,linkify:!0,typographer:!0,highlight:(e,t,r)=>{if(!t)return"";try{return d(e,t,r)}catch(e){return""}}});return f.use(r,{slugify:v,permalink:r.permalink.linkInsideHeader({symbol:"#",placement:"before"})}),f.use(a),f.use(s.full||s.bare),o(f),i(f),e.markoTags?.enabled&&f.use(p,{tagsDir:e.markoTags?.tagsDir||"tags/",onTagDetected:(e,t)=>{g.addDetectedTag(e,n.filePath||"unknown",t)}}),f.use(m),e.base&&f.use(u,e.base),f}export async function parseMarkdown(t,r={},a={},s){const{data:n,content:o,excerpt:i}=e(t,{excerpt:!0,excerpt_separator:"\x3c!-- more --\x3e"}),c=await l(o,{root:a.rootDir??process.cwd(),currentFile:a.filePath??""}),p=s||await async function(e,t){return getMarkdownIt(e,t)}(r,a),g=p.render(c,a),u=a.extractToc?function(e){const t=[],r=e.replace(/```[\s\S]*?```/g,"").replace(/~~~[\s\S]*?~~~/g,"").replace(/^(\t| {4}).+$/gm,""),a=/^(#{1,6})\s+(.+)$/gm;let s;for(;null!==(s=a.exec(r));){const e=s[1].length,r=s[2].trim(),a=k(r),n=v(r);t.push({level:e,title:a,slug:n})}return t}(c):[];return{frontmatter:n,content:c,html:g,excerpt:i,headers:$(u)}}function k(e){return e.replace(/`([^`]+)`/g,"$1").replace(/\*\*\*\+([^*]+)\*\*\+/g,"$1").replace(/___+([^_]+)___+/g,"$1").replace(/\*\*([^*]+)\*\*/g,"$1").replace(/__([^_]+)__/g,"$1").replace(/\*([^*]+)\*/g,"$1").replace(/_([^_]+)_/g,"$1").replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/\[([^\]]+)\]\[[^\]]+\]/g,"$1").trim()}function $(e){const t=[],r=[];for(const a of e){const e={level:a.level,title:a.title,slug:a.slug,children:[]};for(;r.length>0&&r[r.length-1].level>=a.level;)r.pop();0===r.length?t.push(e):r[r.length-1].children.push(e),r.push(e)}return t}function v(e){return e.trim().replace(/([a-z])([A-Z])/g,"$1-$2").replace(/([0-9])([a-zA-Z])/g,"$1-$2").replace(/([a-zA-Z])([0-9])/g,"$1-$2").toLowerCase().replace(/\s+/g,"-").replace(/[^\w\u00A0-\uFFFF\-]+/g,"").replace(/^-+|-+$/g,"").replace(/-+/g,"-")}export function validateFrontmatter(e){const t=[];return void 0!==e.title&&"string"!=typeof e.title&&t.push("title must be a string"),void 0!==e.description&&"string"!=typeof e.description&&t.push("description must be a string"),void 0!==e.draft&&"boolean"!=typeof e.draft&&t.push("draft must be a boolean"),void 0!==e.date&&("string"==typeof e.date||e.date instanceof Date||t.push("date must be a string or Date")),void 0===e.tags||Array.isArray(e.tags)||t.push("tags must be an array"),void 0===e.categories||Array.isArray(e.categories)||t.push("categories must be an array"),{valid:0===t.length,errors:t}}
@@ -0,0 +1,14 @@
1
+ import type MarkdownIt from 'markdown-it';
2
+ /**
3
+ * markdown-it plugin that strips .md extensions from link hrefs.
4
+ *
5
+ * Rewrites:
6
+ * ./theming.md → ./theming
7
+ * ../guides/api.md → ../guides/api
8
+ * /guides/plugins.md → /guides/plugins
9
+ *
10
+ * Does NOT rewrite:
11
+ * https://example.com/file.md (external)
12
+ * #section (anchor)
13
+ */
14
+ export declare function mdLinkPlugin(md: MarkdownIt): void;
@@ -0,0 +1 @@
1
+ export function mdLinkPlugin(n){const r=n.renderer.rules.link_open||((t,e,n,r,s)=>s.renderToken(t,e,n));n.renderer.rules.link_open=(e,n,s,i,o)=>{const l=e[n].attrIndex("href");if(l>=0){const r=e[n].attrs[l][1];e[n].attrs[l][1]=t(r)}return r(e,n,s,i,o)};const s=n.renderer.rules.html_block||((t,e)=>t[e].content);n.renderer.rules.html_block=(t,n,r,i,o)=>(t[n].content=e(t[n].content),s(t,n,r,i,o));const i=n.renderer.rules.html_inline||((t,e)=>t[e].content);n.renderer.rules.html_inline=(t,n,r,s,o)=>(t[n].content=e(t[n].content),i(t,n,r,s,o))}function t(t){return t.startsWith("http://")||t.startsWith("https://")||t.startsWith("//")||t.startsWith("#")||t.startsWith("mailto:")?t:t.endsWith(".md")?t.slice(0,-3):t}function e(e){return e.replace(/(href\s*=\s*)(["'])([^"']*\.md)\2/gi,(e,n,r,s)=>n+r+t(s)+r)}
@@ -16,6 +16,8 @@ export interface MarkdownOptions {
16
16
  /** Directory containing Marko component files (default: 'tags/') */
17
17
  tagsDir?: string;
18
18
  };
19
+ /** Base path for link rewriting (e.g., '/markopress'). Links are rewritten only when this is non-root. */
20
+ base?: string;
19
21
  }
20
22
  export interface MarkdownProcessor {
21
23
  process(src: string, filePath?: string): Promise<ProcessedMarkdown>;
@@ -101,6 +101,7 @@ export interface PostData extends PageData {
101
101
  export interface RouteData {
102
102
  path: string;
103
103
  component?: string;
104
+ handler?: string;
104
105
  layout?: string;
105
106
  meta?: Record<string, unknown>;
106
107
  }
@@ -1 +1 @@
1
- let n=null,e=null;export default function t(t={}){const{postsPerPage:o=10,showExcerpts:r=!0,showDates:a=!0,showAuthors:s=!0,path:l="/blog"}=t,d={postsPerPage:o,showExcerpts:r,showDates:a,showAuthors:s};return{name:"blog-index",modules:["blog"],async enhanceModules(t){const o=t.find(n=>"blog"===n.id);if(!o)return;const r=[...o.files].sort((n,e)=>{const t=new Date(n.processed.frontmatter.date||0);return new Date(e.processed.frontmatter.date||0).getTime()-t.getTime()}).map(n=>({title:n.processed.frontmatter.title,description:n.processed.frontmatter.description,date:n.processed.frontmatter.date,author:n.processed.frontmatter.author,excerpt:n.processed.excerpt,link:n.urlPath}));n=r,e=d,o.enhance("blogPosts",r),o.enhance("blogConfig",d),o.enhance("blogIndexPath",l)},extendRoutes:async t=>n&&e?(t[l]={path:l,component:'<div class="blog-index">\n <h1>Blog</h1>\n <div class="blog-posts">\n <for|post| of=$global.blogPosts>\n <article class="blog-post-card">\n <h2>\n <a href=post.link>${post.title}</a>\n </h2>\n <if=post.date>\n <div class="post-date">\n <small>${new Date(post.date).toLocaleDateString()}</small>\n </div>\n </if>\n <if=post.author>\n <div class="post-author">\n <small>by ${post.author}</small>\n </div>\n </if>\n <if=post.excerpt>\n <div class="post-excerpt">\n <p>${post.excerpt}</p>\n </div>\n </if>\n <a href=post.link class="read-more">Read more →</a>\n </article>\n </for>\n </div>\n</div>\n\n<style>\n .blog-index {\n max-width: var(--content-max-width, 960px);\n margin: 0 auto;\n padding: var(--content-padding, 2rem 1.5rem);\n }\n\n .blog-posts {\n display: flex;\n flex-direction: column;\n gap: 2rem;\n }\n\n .blog-post-card {\n border: 1px solid var(--border-default, #e5e7eb);\n border-radius: var(--radius-lg, 0.5rem);\n padding: 1.5rem;\n background: var(--bg-default, #ffffff);\n }\n\n .blog-post-card h2 {\n margin: 0 0 0.5rem 0;\n }\n\n .blog-post-card h2 a {\n color: var(--text-1, #111827);\n text-decoration: none;\n }\n\n .blog-post-card h2 a:hover {\n color: var(--color-primary-2, #3b82f6);\n }\n\n .post-date,\n .post-author {\n color: var(--text-3, #6b7280);\n margin-bottom: 0.5rem;\n }\n\n .post-excerpt {\n margin: 1rem 0;\n color: var(--text-2, #4b5563);\n }\n\n .read-more {\n display: inline-block;\n color: var(--color-primary-2, #3b82f6);\n text-decoration: none;\n font-weight: 500;\n }\n\n .read-more:hover {\n text-decoration: underline;\n }\n</style>\n',meta:{blogPosts:n,blogConfig:e}},t):t}}
1
+ let n=null,e=null;export default function t(t={}){const{postsPerPage:o=10,showExcerpts:a=!0,showDates:r=!0,showAuthors:s=!0,path:l="/blog"}=t,c={postsPerPage:o,showExcerpts:a,showDates:r,showAuthors:s};return{name:"blog-index",modules:["blog"],async enhanceModules(t){const o=t.find(n=>"blog"===n.id);if(!o)return;const a=[...o.files].sort((n,e)=>{const t=new Date(n.processed.frontmatter.date||0);return new Date(e.processed.frontmatter.date||0).getTime()-t.getTime()}).map(n=>({title:n.processed.frontmatter.title,description:n.processed.frontmatter.description,date:n.processed.frontmatter.date,author:n.processed.frontmatter.author,excerpt:n.processed.excerpt,link:n.urlPath}));n=a,e=c,o.enhance("blogPosts",a),o.enhance("blogConfig",c),o.enhance("blogIndexPath",l)},extendRoutes:async t=>n&&e?(t[l]={path:l,component:'<div class="blog-index">\n <h1>Blog</h1>\n <div class="blog-posts">\n <for|post| of=$global.blogPosts>\n <article class="blog-post-card">\n <h2>\n <a href=post.link>${post.title}</a>\n </h2>\n <if=post.date>\n <div class="post-date">\n <small>${new Date(post.date).toLocaleDateString()}</small>\n </div>\n </if>\n <if=post.author>\n <div class="post-author">\n <small>by ${post.author}</small>\n </div>\n </if>\n <if=post.excerpt>\n <div class="post-excerpt">\n <p>${post.excerpt}</p>\n </div>\n </if>\n <a href=post.link class="read-more">Read more →</a>\n </article>\n </for>\n </div>\n</div>\n\n<style>\n .blog-index {\n max-width: var(--content-max-width, 960px);\n margin: 0 auto;\n padding: var(--content-padding, 2rem 1.5rem);\n }\n\n .blog-posts {\n display: flex;\n flex-direction: column;\n gap: 2rem;\n }\n\n .blog-post-card {\n border: 1px solid var(--border-default, #e5e7eb);\n border-radius: var(--radius-lg, 0.5rem);\n padding: 1.5rem;\n background: var(--bg-default, #ffffff);\n }\n\n .blog-post-card h2 {\n margin: 0 0 0.5rem 0;\n }\n\n .blog-post-card h2 a {\n color: var(--text-1, #111827);\n text-decoration: none;\n }\n\n .blog-post-card h2 a:hover {\n color: var(--color-primary-2, #3b82f6);\n }\n\n .post-date,\n .post-author {\n color: var(--text-3, #6b7280);\n margin-bottom: 0.5rem;\n }\n\n .post-excerpt {\n margin: 1rem 0;\n color: var(--text-2, #4b5563);\n }\n\n .read-more {\n display: inline-block;\n color: var(--color-primary-2, #3b82f6);\n text-decoration: none;\n font-weight: 500;\n }\n\n .read-more:hover {\n text-decoration: underline;\n }\n</style>\n',handler:"import { config } from '../_config.js';\n\nlet moduleEnhancements = {};\ntry {\n moduleEnhancements = (await import('/src/.generated/module-enhancements.js')).default;\n} catch {}\n\nexport async function GET(context, next) {\n const base = (config.site.base || '/').replace(/\\/$/, '');\n context.base = base || '/';\n\n // Standard context fields\n context.navbar = config.theme.options.navbar || [];\n context.lang = config.site.lang || 'en-US';\n context.siteHead = config.site.head || [];\n context.footer = config.theme.options.footer || null;\n context.title = 'Blog';\n context.description = 'Blog posts';\n\n // Blog posts from module enhancements (links already prefixed at build time)\n const blogModule = moduleEnhancements['blog'] || {};\n context.blogPosts = blogModule.blogPosts || [];\n}\n",meta:{blogPosts:n,blogConfig:e}},t):t}}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "markopress",
3
- "version": "0.0.3",
3
+ "version": "0.0.4",
4
4
  "description": "A fast, modern static site generator built on Marko.js v6 - drop-in alternative to VitePress and Docusaurus with full content compatibility",
5
5
  "keywords": [
6
6
  "static-site-generator",
@@ -107,11 +107,7 @@ export async function GET(context, next) {
107
107
 
108
108
  // === SHARED: Set context for template ===
109
109
  // Prefix navbar links with base path
110
- const rawNavbar = config.theme.options.navbar || [];
111
- context.navbar = rawNavbar.map(item => ({
112
- ...item,
113
- link: item.link ? base + item.link : item.link,
114
- }));
110
+ context.navbar = config.theme.options.navbar || [];
115
111
  context.lang = config.site.lang || 'en-US';
116
112
  context.siteHead = config.site.head || [];
117
113
  context.footer = config.theme.options.footer || null;
@@ -123,18 +119,7 @@ export async function GET(context, next) {
123
119
 
124
120
  // Load module enhancements for this content type (sidebar, etc.)
125
121
  const enhancements = moduleEnhancements[contentType] || {};
126
- const rawSidebar = enhancements.sidebar || null;
127
- if (rawSidebar && base) {
128
- context.sidebar = rawSidebar.map(section => ({
129
- ...section,
130
- items: (section.items || []).map(item => ({
131
- ...item,
132
- link: item.link ? base + item.link : item.link,
133
- })),
134
- }));
135
- } else {
136
- context.sidebar = rawSidebar;
137
- }
122
+ context.sidebar = enhancements.sidebar || null;
138
123
 
139
124
  // TOC (table of contents)
140
125
  if (headers && headers.length > 0) {