markopress 0.0.9 → 0.0.10

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/index.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";import{buildSearchIndex as p}from"../search/index.js";const h=o.dirname(n(import.meta.url)),w=o.resolve(h,"..",".."),k=o.join(w,"src","theme","default"),y=new Set(["@markopress/theme-default","theme-default","default"]);function j(e){return y.has(e)}export function filePathToUrl(e,t){const n=o.relative(t,e).replace(/\.md$/,"").split(o.sep).join("/");return"index"===n?"/":n.endsWith("/index")?"/"+n.replace("/index",""):"/"+n}export async function build(n={}){const{outDir:r,debug:i=!1,useCatchAllRoutes:u,root:m}=n,h=m||process.cwd(),w=[],k=new Map,y=new Map,j=o.join(h,".markopress");let T=h;try{(await e.stat(j)).isDirectory()&&(T=j)}catch{}const v=e=>({start:()=>{y.set(e,performance.now())},end:()=>{const o=y.get(e)||0,t=performance.now()-o;k.set(e,t)}});try{console.log("šŸš€ Building MarkoPress site...\n");const n=v("Config loading");n.start();const m=await a(h,{mode:"production",command:"build"});let y;if(n.end(),m.plugins&&m.plugins.length>0){console.log("šŸ”Œ Loading plugins...");const e=v("Plugin loading");e.start(),y=new d(m),await y.loadPlugins(m.plugins),e.end(),console.log("")}if(y){console.log("šŸ“¦ Loading plugin content...");const e=v("Plugin loadContent hooks");e.start(),await y.execLoadContentHooks(),e.end(),console.log(" Plugin content loaded\n")}const j={},$=[],P=o.resolve(h,m.contentDir);try{const t=await e.readdir(P,{withFileTypes:!0,recursive:!0}),n=new Map;for(const a of t){if(!a.isFile()||!a.name.endsWith(".md"))continue;const t=o.join(a.path||a.parentPath||P,a.name),r=o.relative(P,t),i=filePathToUrl(t,P),c=r.split(o.sep),l=1===c.length?"root":c[0],d=await e.readFile(t,"utf-8");let u={};try{u=s(d).data}catch{}n.has(l)||n.set(l,[]),n.get(l).push({id:a.name.replace(".md",""),slug:a.name.replace(".md",""),filePath:t,urlPath:i,directory:l,processed:{frontmatter:u}})}for(const[e,t]of n){const n=m.content[e]||{},s=new Map;$.push({id:e,dir:o.join(P,"root"===e?"":e),config:n,features:n,files:t,enhance(e,o){s.set(e,o)},getEnhancement:e=>s.get(e),_enhancements:s})}}catch(e){console.warn("Warning: Could not scan content directory: "+e)}if(y&&$.length>0){console.log("šŸ”Œ Enhancing modules with plugin metadata...");const t=v("Module enhancement");t.start();for(const e of $)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($),t.end(),console.log(` Enhanced ${$.length} module(s)\n`);const n=o.join(T,"src",".generated");await e.mkdir(n,{recursive:!0});const s=(m.site?.base||"/").replace(/\/$/,""),a={};for(const e of $){const o={},t=e._enhancements.entries();for(const[e,n]of t)o[e]=n;Object.keys(o).length>0&&(s&&b(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(!1!==m.search?.enabled){console.log("šŸ” Building search index...");const t=v("Search index");t.start();const n=[];for(const o of $)for(const t of o.files)try{const o=await e.readFile(t.filePath,"utf-8"),s=await f(o,m.markdown);n.push({url:t.urlPath,html:s.html,title:s.frontmatter?.title||t.id,frontmatter:s.frontmatter})}catch(e){console.warn(` Warning: Could not index ${t.filePath}:`,e)}try{const t=await p(n,m.search),s=o.join(T,"public","search-index.json");await e.mkdir(o.dirname(s),{recursive:!0}),await e.writeFile(s,t),console.log(` Search index built (${n.length} pages)\n`)}catch(e){console.warn(" Warning: Failed to build search index:",e)}t.end()}if(m.markdown.markoTags?.enabled){const e=o.join(T,m.markdown.markoTags.tagsDir||"src/tags");console.log("šŸ” Scanning tags directory...");const t=v("Tag validation setup");t.start(),await c.loadAvailableTags(e),t.end(),console.log(` Found ${c.getAvailableTagsCount()} tags\n`)}else c.reset();const C=o.join(T,"src","routes");await e.mkdir(C,{recursive:!0});let F={};if(y){const e=v("Extend routes hooks");e.start(),F=await y.execExtendRoutesHooks(F),e.end(),console.log("šŸ”Œ Extended routes manifest:",Object.keys(F).length)}console.log("šŸ“ Generating routes from content...");const S=v("Route generation");S.start();const x=u??m.build.useCatchAllRoutes;console.log("šŸ“„ Pre-rendering markdown to .marko files...");const E=v("Pre-render markdown");E.start();const _=o.join(T,"src",".generated","markdown");await e.mkdir(_,{recursive:!0});const D={};let A=0;for(const t of $){const n=o.join(_,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),D[`${t.id}/${s.slug}`]={frontmatter:i.frontmatter,headers:i.headers||[]},A++}catch(e){console.warn(` Warning: Failed to pre-render ${t.id}/${s.slug}:`,e)}}const N=o.join(T,"src",".generated","content-metadata.js"),M=`// Auto-generated by MarkoPress - Do not edit\nexport default ${JSON.stringify(D,null,2)};\n`;await e.writeFile(N,M),E.end(),console.log(` Pre-rendered ${A} markdown files\n`),x?(await generateCatchAllRoutes(j,C,m,$,i,!0),console.log(" Using catch-all dynamic routes")):(await generateRoutes(j,C,m,$,i),console.log(" Using static routes")),S.end(),console.log(" Routes generated\n");const O=[];for(const[e,o]of Object.entries(F))(o.handler||o.component)&&(O.push({path:e,...o}),console.log(" Found plugin route: "+e));if(console.log(`šŸ”Œ Total manifest routes: ${Object.keys(F).length}, Plugin routes: ${O.length}`),y){const t=[...y.getPluginRoutes(),...O];if(t.length>0){console.log(`šŸ”Œ Generating ${t.length} plugin routes...`);const n=v("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,C,0,i),n.end(),console.log(" Plugin routes generated\n")}}console.log("āš™ļø Generating Vite config...");const I=v("Vite config generation");if(I.start(),await generateViteConfig(T,i),I.end(),console.log(" Vite config generated\n"),y){console.log("šŸ”Œ Processing plugin allContentLoaded hooks...");const e=v("AllContentLoaded hooks");e.start(),await y.execAllContentLoadedHooks(F),e.end(),console.log(" All content processed\n")}if(m.markdown.markoTags?.enabled){console.log("šŸ” Validating Marko tags...");const e=v("Tag validation");e.start();const o=c.validate();if(e.end(),!o.success){const e=l(o.missingTags);return console.error(`\n${e}\n`),w.push(e),{success:!1,outDir:"",pages:0,errors:w}}console.log(" All tags validated āœ“\n")}console.log("šŸŽØ Copying theme CSS...");const L=v("Theme CSS copy");L.start(),await copyThemeCSS(T,m,i),L.end(),console.log(" Theme CSS copied\n"),console.log("šŸŽØ Extracting styles from Marko components...");const W=v("Marko component styles extraction");W.start(),await extractStylesFromMarkoTags(T,m,i),W.end(),console.log(" Component styles extracted\n");const R=[];for(const e of $)for(const o of e.files)R.push(o.urlPath);for(const e of Object.keys(F))R.includes(e)||R.push(e);const G=o.join(T,"src",".generated","static-urls.json");await e.mkdir(o.dirname(G),{recursive:!0}),await e.writeFile(G,JSON.stringify(R,null,2)),i&&console.log(` Generated static URL manifest: ${R.length} URLs`),console.log("šŸ”Ø Building with @marko/run...");const U=v("@marko/run build");U.start();const B=r||m.build.outDir,V=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]})})})}(B,i,T);if(U.end(),!V.success)return w.push(...V.errors),{success:!1,outDir:"",pages:0,errors:w};const H=v("Collect build assets");H.start();const Y=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}(V.outDir);if(H.end(),y){console.log("šŸ”Œ Processing plugin postBuild hooks...");const e=v("Post-build hooks");e.start(),await y.execPostBuildHooks(V.outDir,F,Y),e.end(),console.log(" Post-build hooks completed\n")}console.log("šŸ“¦ Copying Marko tags directory...");const q=v("Copy tags directory");q.start(),await copyTagsDirectory(h,V.outDir,m,i),q.end(),console.log(" Tags directory copied\n"),console.log("\nāœ… Build completed successfully!"),console.log(" Output: "+V.outDir),console.log(" Pages: Generated dynamically at request time"),console.log("\nā±ļø Build timing:");const z=Array.from(k.entries()).sort((e,o)=>o[1]-e[1]);for(const[e,o]of z){const t=(o/1e3).toFixed(2);console.log(` ${"ā–ˆ".repeat(Math.min(Math.floor(o/100),20))} ${e}: ${t}s`)}return{success:!0,outDir:V.outDir,pages:0,errors:w}}catch(e){const o=e instanceof Error?e.message:e+"";return w.push(o),console.error("\nāŒ Build failed:",o),{success:!1,outDir:"",pages:0,errors:w}}}function b(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,t,n,s,a){await cleanupGeneratedRoutes(t,e,a);const r=[];let i=0,c=0,l=0;for(const[o,t]of Object.entries(e)){if(!Array.isArray(t))continue;r.push(o);const e=t;if("pages"===o)for(const o of e)await v(0,0,0,0,a),i++;else if("blog"===o)for(const o of e)await P(0,0,0,0,a),l++;else for(const o of e)await $(0,0,0,0,a),c++}await C(t,n,a);const d=o.resolve(t,"..","..");await generateViteConfig(d,a),await F(t,n,a),a&&(console.log(` Generated ${i} page routes`),console.log(` Generated ${c} doc routes`),console.log(` Generated ${l} 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 T(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 T(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 T(n)}0===(await e.readdir(t)).length&&await e.rmdir(t)}catch{}}async function v(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 P(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,contentDir:n.contentDir,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 F(t,n,s){const a=o.join(t,"+layout.marko"),r=(n.theme,n.site?.title||"MarkoPress"),i=n.theme?.options?.style||"default",c=n.site?.base?.replace(/\/$/,"")||"",l=n.markdown?.markoTags?.enabled?`<link rel="stylesheet" href="${c}/markopress-components.css">`:"",d=await S("layout.marko.template",{SITE_TITLE:r,THEME_STYLE:i,BASE_PATH:c,COMPONENT_STYLES_LINK:l});await e.writeFile(a,d),s&&console.log(" Generated: "+a)}async function S(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");i="true"===n.IS_BUILD?i.replace(/\/\/ \{\{IF_DEV_START\}\}[\s\S]*?\/\/ \{\{IF_DEV_END\}\}/g,""):i.replace(/\/\/ \{\{IF_BUILD_START\}\}[\s\S]*?\/\/ \{\{IF_BUILD_END\}\}/g,""),i=i.replace(/\/\/ \{\{IF_(?:BUILD|DEV)_(?:START|END)\}\}\n?/g,"");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=[...j(r)?[o.join(k,"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=[...j(r)?[o.join(k,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/tags",r=o.join(t,a),i=o.join(t,"public");await e.mkdir(i,{recursive:!0});const c=o.join(i,"markopress-components.css");if(!n.markdown?.markoTags?.enabled){s&&console.log(" Marko tags not enabled, skipping style extraction");try{await e.unlink(c)}catch{}return}try{await e.access(r)}catch{return void(s&&console.log(" No tags directory found at: "+r))}const l=[];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")&&l.push(s)}}(r),0===l.length)return void(s&&console.log(" No .marko files found in: "+r));const d=[];d.push("/* Custom markdown tag styles"),d.push(" * Loaded globally because request-time virtual markdown modules"),d.push(" * do not emit tag-local CSS assets reliably. */"),d.push("");for(const t of l){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){d.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()){d.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");d.push(a+r)}}}d.push("")}}catch(e){console.warn(` Warning: Could not read file ${t}:`,e)}}const u=d.join("\n");await e.writeFile(c,u),s&&(console.log(` Extracted styles from ${l.length} Marko component(s)`),console.log(" Output: "+c))}async function x(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()?x(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=[...j(a)?[o.join(k,"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 x(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/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=Object.keys(s.content||{}),l=new Set(a.map(e=>e.id)),d=[...new Set([...c,...l])];if(a.some(e=>"root"===e.id)){const t=o.join(n,"$$slug");await e.mkdir(t,{recursive:!0});const s=await S("catch-all-handler.js.template",{CONTENT_TYPE:"root",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 S("catch-all-page.marko.template",{CONTENT_TYPE_CLASS:"page"});await e.writeFile(o.join(t,"+page.marko"),a),r&&console.log(" Generated root pages catch-all route")}for(const t of d){if("root"===t)continue;const s=o.join(n,t,"$$slug");await e.mkdir(s,{recursive:!0});const a=await S("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 S("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);const u=o.resolve(n,"..","..");await generateViteConfig(u,r),await F(n,s,r)}export{u as loadMarkdownModule,m 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/index.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";import{buildSearchIndex as p}from"../search/index.js";const h=o.dirname(n(import.meta.url)),w=o.resolve(h,"..",".."),k=o.join(w,"src","theme","default"),y=new Set(["@markopress/theme-default","theme-default","default"]);function j(e){return y.has(e)}export function filePathToUrl(e,t){const n=o.relative(t,e).replace(/\.md$/,"").split(o.sep).join("/");return"index"===n?"/":n.endsWith("/index")?"/"+n.replace("/index",""):"/"+n}export async function build(n={}){const{outDir:r,debug:i=!1,useCatchAllRoutes:u,root:m}=n,h=m||process.cwd(),w=[],k=new Map,y=new Map,j=o.join(h,".markopress");let T=h;try{(await e.stat(j)).isDirectory()&&(T=j)}catch{}const v=e=>({start:()=>{y.set(e,performance.now())},end:()=>{const o=y.get(e)||0,t=performance.now()-o;k.set(e,t)}});try{console.log("šŸš€ Building MarkoPress site...\n");const n=v("Config loading");n.start();const m=await a(h,{mode:"production",command:"build"});let y;if(n.end(),m.plugins&&m.plugins.length>0){console.log("šŸ”Œ Loading plugins...");const e=v("Plugin loading");e.start(),y=new d(m),await y.loadPlugins(m.plugins),e.end(),console.log("")}if(y){console.log("šŸ“¦ Loading plugin content...");const e=v("Plugin loadContent hooks");e.start(),await y.execLoadContentHooks(),e.end(),console.log(" Plugin content loaded\n")}const j={},$=[],P=o.resolve(h,m.contentDir);try{const t=await e.readdir(P,{withFileTypes:!0,recursive:!0}),n=new Map;for(const a of t){if(!a.isFile()||!a.name.endsWith(".md"))continue;const t=o.join(a.path||a.parentPath||P,a.name),r=o.relative(P,t),i=filePathToUrl(t,P),c=r.split(o.sep),l=1===c.length?"root":c[0],d=await e.readFile(t,"utf-8");let u={};try{u=s(d).data}catch{}n.has(l)||n.set(l,[]),n.get(l).push({id:a.name.replace(".md",""),slug:a.name.replace(".md",""),filePath:t,urlPath:i,directory:l,processed:{frontmatter:u}})}for(const[e,t]of n){const n=m.content[e]||{},s=new Map;$.push({id:e,dir:o.join(P,"root"===e?"":e),config:n,features:n,files:t,enhance(e,o){s.set(e,o)},getEnhancement:e=>s.get(e),_enhancements:s})}}catch(e){console.warn("Warning: Could not scan content directory: "+e)}if(y&&$.length>0){console.log("šŸ”Œ Enhancing modules with plugin metadata...");const t=v("Module enhancement");t.start();for(const e of $)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($),t.end(),console.log(` Enhanced ${$.length} module(s)\n`);const n=o.join(T,"src",".generated");await e.mkdir(n,{recursive:!0});const s=(m.site?.base||"/").replace(/\/$/,""),a={};for(const e of $){const o={},t=e._enhancements.entries();for(const[e,n]of t)o[e]=n;Object.keys(o).length>0&&(s&&b(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(!1!==m.search?.enabled){console.log("šŸ” Building search index...");const t=v("Search index");t.start();const n=[],s=(m.site?.base||"/").replace(/\/$/,"");for(const o of $)for(const t of o.files)try{const o=await e.readFile(t.filePath,"utf-8"),a=await f(o,{...m.markdown,base:s});n.push({url:t.urlPath,html:a.html,title:a.frontmatter?.title||t.id,frontmatter:a.frontmatter})}catch(e){console.warn(` Warning: Could not index ${t.filePath}:`,e)}try{const t=await p(n,m.search),s=o.join(T,"public","search-index.json");await e.mkdir(o.dirname(s),{recursive:!0}),await e.writeFile(s,t),console.log(` Search index built (${n.length} pages)\n`)}catch(e){console.warn(" Warning: Failed to build search index:",e)}t.end()}if(m.markdown.markoTags?.enabled){const e=o.join(T,m.markdown.markoTags.tagsDir||"src/tags");console.log("šŸ” Scanning tags directory...");const t=v("Tag validation setup");t.start(),await c.loadAvailableTags(e),t.end(),console.log(` Found ${c.getAvailableTagsCount()} tags\n`)}else c.reset();const C=o.join(T,"src","routes");await e.mkdir(C,{recursive:!0});let F={};if(y){const e=v("Extend routes hooks");e.start(),F=await y.execExtendRoutesHooks(F),e.end(),console.log("šŸ”Œ Extended routes manifest:",Object.keys(F).length)}console.log("šŸ“ Generating routes from content...");const S=v("Route generation");S.start();const x=u??m.build.useCatchAllRoutes;console.log("šŸ“„ Pre-rendering markdown to .marko files...");const E=v("Pre-render markdown");E.start();const _=o.join(T,"src",".generated","markdown");await e.mkdir(_,{recursive:!0});const D={};let A=0;for(const t of $){const n=o.join(_,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),D[`${t.id}/${s.slug}`]={frontmatter:i.frontmatter,headers:i.headers||[]},A++}catch(e){console.warn(` Warning: Failed to pre-render ${t.id}/${s.slug}:`,e)}}const N=o.join(T,"src",".generated","content-metadata.js"),M=`// Auto-generated by MarkoPress - Do not edit\nexport default ${JSON.stringify(D,null,2)};\n`;await e.writeFile(N,M),E.end(),console.log(` Pre-rendered ${A} markdown files\n`),x?(await generateCatchAllRoutes(j,C,m,$,i,!0),console.log(" Using catch-all dynamic routes")):(await generateRoutes(j,C,m,$,i),console.log(" Using static routes")),S.end(),console.log(" Routes generated\n");const O=[];for(const[e,o]of Object.entries(F))(o.handler||o.component)&&(O.push({path:e,...o}),console.log(" Found plugin route: "+e));if(console.log(`šŸ”Œ Total manifest routes: ${Object.keys(F).length}, Plugin routes: ${O.length}`),y){const t=[...y.getPluginRoutes(),...O];if(t.length>0){console.log(`šŸ”Œ Generating ${t.length} plugin routes...`);const n=v("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,C,0,i),n.end(),console.log(" Plugin routes generated\n")}}console.log("āš™ļø Generating Vite config...");const I=v("Vite config generation");if(I.start(),await generateViteConfig(T,i),I.end(),console.log(" Vite config generated\n"),y){console.log("šŸ”Œ Processing plugin allContentLoaded hooks...");const e=v("AllContentLoaded hooks");e.start(),await y.execAllContentLoadedHooks(F),e.end(),console.log(" All content processed\n")}if(m.markdown.markoTags?.enabled){console.log("šŸ” Validating Marko tags...");const e=v("Tag validation");e.start();const o=c.validate();if(e.end(),!o.success){const e=l(o.missingTags);return console.error(`\n${e}\n`),w.push(e),{success:!1,outDir:"",pages:0,errors:w}}console.log(" All tags validated āœ“\n")}console.log("šŸŽØ Copying theme CSS...");const L=v("Theme CSS copy");L.start(),await copyThemeCSS(T,m,i),L.end(),console.log(" Theme CSS copied\n"),console.log("šŸŽØ Extracting styles from Marko components...");const W=v("Marko component styles extraction");W.start(),await extractStylesFromMarkoTags(T,m,i),W.end(),console.log(" Component styles extracted\n");const R=[];for(const e of $)for(const o of e.files)R.push(o.urlPath);for(const e of Object.keys(F))R.includes(e)||R.push(e);const G=o.join(T,"src",".generated","static-urls.json");await e.mkdir(o.dirname(G),{recursive:!0}),await e.writeFile(G,JSON.stringify(R,null,2)),i&&console.log(` Generated static URL manifest: ${R.length} URLs`),console.log("šŸ”Ø Building with @marko/run...");const U=v("@marko/run build");U.start();const B=r||m.build.outDir,V=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]})})})}(B,i,T);if(U.end(),!V.success)return w.push(...V.errors),{success:!1,outDir:"",pages:0,errors:w};const H=v("Collect build assets");H.start();const Y=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}(V.outDir);if(H.end(),y){console.log("šŸ”Œ Processing plugin postBuild hooks...");const e=v("Post-build hooks");e.start(),await y.execPostBuildHooks(V.outDir,F,Y),e.end(),console.log(" Post-build hooks completed\n")}console.log("šŸ“¦ Copying Marko tags directory...");const q=v("Copy tags directory");q.start(),await copyTagsDirectory(h,V.outDir,m,i),q.end(),console.log(" Tags directory copied\n"),console.log("\nāœ… Build completed successfully!"),console.log(" Output: "+V.outDir),console.log(" Pages: Generated dynamically at request time"),console.log("\nā±ļø Build timing:");const z=Array.from(k.entries()).sort((e,o)=>o[1]-e[1]);for(const[e,o]of z){const t=(o/1e3).toFixed(2);console.log(` ${"ā–ˆ".repeat(Math.min(Math.floor(o/100),20))} ${e}: ${t}s`)}return{success:!0,outDir:V.outDir,pages:0,errors:w}}catch(e){const o=e instanceof Error?e.message:e+"";return w.push(o),console.error("\nāŒ Build failed:",o),{success:!1,outDir:"",pages:0,errors:w}}}function b(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,t,n,s,a){await cleanupGeneratedRoutes(t,e,a);const r=[];let i=0,c=0,l=0;for(const[o,t]of Object.entries(e)){if(!Array.isArray(t))continue;r.push(o);const e=t;if("pages"===o)for(const o of e)await v(0,0,0,0,a),i++;else if("blog"===o)for(const o of e)await P(0,0,0,0,a),l++;else for(const o of e)await $(0,0,0,0,a),c++}await C(t,n,a);const d=o.resolve(t,"..","..");await generateViteConfig(d,a),await F(t,n,a),a&&(console.log(` Generated ${i} page routes`),console.log(` Generated ${c} doc routes`),console.log(` Generated ${l} 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 T(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 T(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 T(n)}0===(await e.readdir(t)).length&&await e.rmdir(t)}catch{}}async function v(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 P(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,contentDir:n.contentDir,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 F(t,n,s){const a=o.join(t,"+layout.marko"),r=(n.theme,n.site?.title||"MarkoPress"),i=n.theme?.options?.style||"default",c=n.site?.base?.replace(/\/$/,"")||"",l=n.markdown?.markoTags?.enabled?`<link rel="stylesheet" href="${c}/markopress-components.css">`:"",d=await S("layout.marko.template",{SITE_TITLE:r,THEME_STYLE:i,BASE_PATH:c,COMPONENT_STYLES_LINK:l});await e.writeFile(a,d),s&&console.log(" Generated: "+a)}async function S(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");i="true"===n.IS_BUILD?i.replace(/\/\/ \{\{IF_DEV_START\}\}[\s\S]*?\/\/ \{\{IF_DEV_END\}\}/g,""):i.replace(/\/\/ \{\{IF_BUILD_START\}\}[\s\S]*?\/\/ \{\{IF_BUILD_END\}\}/g,""),i=i.replace(/\/\/ \{\{IF_(?:BUILD|DEV)_(?:START|END)\}\}\n?/g,"");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=[...j(r)?[o.join(k,"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=[...j(r)?[o.join(k,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/tags",r=o.join(t,a),i=o.join(t,"public");await e.mkdir(i,{recursive:!0});const c=o.join(i,"markopress-components.css");if(!n.markdown?.markoTags?.enabled){s&&console.log(" Marko tags not enabled, skipping style extraction");try{await e.unlink(c)}catch{}return}try{await e.access(r)}catch{return void(s&&console.log(" No tags directory found at: "+r))}const l=[];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")&&l.push(s)}}(r),0===l.length)return void(s&&console.log(" No .marko files found in: "+r));const d=[];d.push("/* Custom markdown tag styles"),d.push(" * Loaded globally because request-time virtual markdown modules"),d.push(" * do not emit tag-local CSS assets reliably. */"),d.push("");for(const t of l){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){d.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()){d.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");d.push(a+r)}}}d.push("")}}catch(e){console.warn(` Warning: Could not read file ${t}:`,e)}}const u=d.join("\n");await e.writeFile(c,u),s&&(console.log(` Extracted styles from ${l.length} Marko component(s)`),console.log(" Output: "+c))}async function x(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()?x(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=[...j(a)?[o.join(k,"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 x(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/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=Object.keys(s.content||{}),l=new Set(a.map(e=>e.id)),d=[...new Set([...c,...l])];if(a.some(e=>"root"===e.id)){const t=o.join(n,"$$slug");await e.mkdir(t,{recursive:!0});const s=await S("catch-all-handler.js.template",{CONTENT_TYPE:"root",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 S("catch-all-page.marko.template",{CONTENT_TYPE_CLASS:"page"});await e.writeFile(o.join(t,"+page.marko"),a),r&&console.log(" Generated root pages catch-all route")}for(const t of d){if("root"===t)continue;const s=o.join(n,t,"$$slug");await e.mkdir(s,{recursive:!0});const a=await S("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 S("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);const u=o.resolve(n,"..","..");await generateViteConfig(u,r),await F(n,s,r)}export{u as loadMarkdownModule,m as registerMarkdownContent};export{markdownContentPlugin}from"./vite-markdown-plugin.js";
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * MarkoPress Preview Server
3
- * Serves the production build
3
+ * Serves the production build with base path support
4
4
  */
5
5
  import type { PreviewOptions } from '../build/types.js';
6
6
  export declare function preview(options?: PreviewOptions): Promise<never>;
@@ -1 +1 @@
1
- import o from"node:path";import{existsSync as r,statSync as e}from"node:fs";import{spawn as s}from"node:child_process";export async function preview(t={}){const{port:n=4173,host:i="localhost",root:p}=t;console.log("šŸš€ Starting MarkoPress preview server...\n"),console.log(` Server: http://${i}:${n}`),console.log(" Press Ctrl+C to stop\n");const c=p||process.cwd(),l=o.join(c,".markopress"),a=r(l)&&e(l).isDirectory()?l:c;return s("npx",["marko-run","preview","--port",n+""],{stdio:"inherit",cwd:a}).on("error",o=>{console.error("Failed to start preview server:",o.message),process.exit(1)}),new Promise(()=>{})}
1
+ import e from"node:path";import{existsSync as o,statSync as r}from"node:fs";import{createServer as t,request as s}from"node:http";import{spawn as n}from"node:child_process";import{loadConfig as i}from"../config/index.js";export async function preview(a={}){const{port:p=4173,host:l="localhost",root:c}=a,d=c||process.cwd(),m=await i(d,{mode:"production",command:"preview"}),h=(m.site?.base||"/").replace(/\/?$/,"/"),w=e.join(d,".markopress"),v=o(w)&&r(w).isDirectory()?w:d;if("/"!==h){const e=3e4+Math.floor(1e4*Math.random()),o=n("npx",["marko-run","preview","--port",e+""],{stdio:"pipe",cwd:v});await new Promise(e=>{const r=o=>{const r=o.toString();(r.includes("Preview server started")||r.includes("localhost"))&&e()};o.stdout?.on("data",r),o.stderr?.on("data",r),setTimeout(e,2e3)});const r=h.replace(/\/$/,""),i=t((o,t)=>{let n=o.url||"/";n.startsWith(r+"/")?n=n.slice(r.length)||"/":n===r&&(n="/");const i=s({hostname:"localhost",port:e,path:n,method:o.method,headers:o.headers},e=>{t.writeHead(e.statusCode||200,e.headers),e.pipe(t)});i.on("error",()=>{t.writeHead(502),t.end("Bad Gateway")}),o.pipe(i)});i.listen(p,()=>{console.log("šŸš€ Starting MarkoPress preview server...\n"),console.log(` Server: http://${l}:${p}${r}/`),console.log(" Base path: "+h),console.log(" Press Ctrl+C to stop\n")}),o.on("error",e=>{console.error("Failed to start preview server:",e.message),process.exit(1)}),process.on("SIGINT",()=>{o.kill(),i.close(),process.exit(0)})}else console.log("šŸš€ Starting MarkoPress preview server...\n"),console.log(` Server: http://${l}:${p}`),console.log(" Press Ctrl+C to stop\n"),n("npx",["marko-run","preview","--port",p+""],{stdio:"inherit",cwd:v}).on("error",e=>{console.error("Failed to start preview server:",e.message),process.exit(1)});return new Promise(()=>{})}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "markopress",
3
- "version": "0.0.9",
3
+ "version": "0.0.10",
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",
@@ -64,7 +64,7 @@ export async function GET(context, next) {
64
64
  const loader = contentModules[modulePath];
65
65
 
66
66
  if (!loader) {
67
- return new Response('Not Found', { status: 404, statusText: 'Not Found' });
67
+ return next();
68
68
  }
69
69
 
70
70
  const mod = await loader();
@@ -104,10 +104,10 @@ export async function GET(context, next) {
104
104
  const source = await fs.readFile(filePath, 'utf-8').catch(() => null);
105
105
 
106
106
  if (!source) {
107
- return new Response('Not Found', { status: 404, statusText: 'Not Found' });
107
+ return next();
108
108
  }
109
109
 
110
- const rendered = await renderMarkdown(source);
110
+ const rendered = await renderMarkdown(source, { base: base !== '/' ? base : undefined });
111
111
  frontmatter = rendered.frontmatter;
112
112
  headers = rendered.headers || [];
113
113
 
@@ -116,7 +116,7 @@ export async function GET(context, next) {
116
116
  contentComponent = (await loadMarkdownModule(`virtual:markdown-content/${contentId}`)).default;
117
117
  } catch (error) {
118
118
  console.error(`Error rendering ${contentType}/${slug}:`, error);
119
- return new Response('Not Found', { status: 404, statusText: 'Not Found' });
119
+ return next();
120
120
  }
121
121
  }
122
122
  // {{IF_DEV_END}}