markopress 0.0.17 → 0.0.19
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/build/index.js +1 -1
- package/dist/content/filesystem-source.d.ts +27 -0
- package/dist/content/filesystem-source.js +1 -0
- package/dist/content/index.d.ts +1 -0
- package/dist/content/index.js +1 -1
- package/dist/content/registry.d.ts +37 -20
- package/dist/content/registry.js +1 -1
- package/dist/content/source.d.ts +37 -0
- package/dist/content/source.js +1 -0
- package/dist/image/tag.d.ts +2 -1
- package/dist/image/tag.js +1 -1
- package/dist/markdown/loader.js +1 -1
- package/dist/markdown/renderer.js +1 -1
- package/dist/plugin/manager.js +1 -1
- package/dist/plugins/content-registry/index.d.ts +23 -0
- package/dist/plugins/content-registry/index.js +1 -0
- package/package.json +1 -1
- package/templates/catch-all-handler.js.template +25 -7
- package/templates/catch-all-page.marko.template +51 -0
- package/dist/build/index.d.ts.map +0 -1
- package/dist/build/index.js.map +0 -1
- package/dist/build/security.test.d.ts +0 -6
- package/dist/build/security.test.d.ts.map +0 -1
- package/dist/build/security.test.js +0 -1
- package/dist/build/security.test.js.map +0 -1
- package/dist/build/types.d.ts.map +0 -1
- package/dist/build/types.js.map +0 -1
- package/dist/build/vite-config.test.d.ts +0 -2
- package/dist/build/vite-config.test.d.ts.map +0 -1
- package/dist/build/vite-config.test.js +0 -1
- package/dist/build/vite-config.test.js.map +0 -1
- package/dist/build/vite-markdown-plugin.d.ts.map +0 -1
- package/dist/build/vite-markdown-plugin.js.map +0 -1
- package/dist/build/vite-markdown-plugin.test.d.ts +0 -2
- package/dist/build/vite-markdown-plugin.test.d.ts.map +0 -1
- package/dist/build/vite-markdown-plugin.test.js +0 -1
- package/dist/build/vite-markdown-plugin.test.js.map +0 -1
- package/dist/cli/index.d.ts.map +0 -1
- package/dist/cli/index.js.map +0 -1
- package/dist/config/app-root.d.ts.map +0 -1
- package/dist/config/app-root.js.map +0 -1
- package/dist/config/app-root.test.d.ts +0 -2
- package/dist/config/app-root.test.d.ts.map +0 -1
- package/dist/config/app-root.test.js +0 -1
- package/dist/config/app-root.test.js.map +0 -1
- package/dist/config/index.d.ts.map +0 -1
- package/dist/config/index.js.map +0 -1
- package/dist/config/loader.d.ts.map +0 -1
- package/dist/config/loader.js.map +0 -1
- package/dist/config/loader.test.d.ts +0 -2
- package/dist/config/loader.test.d.ts.map +0 -1
- package/dist/config/loader.test.js +0 -1
- package/dist/config/loader.test.js.map +0 -1
- package/dist/config/types.d.ts.map +0 -1
- package/dist/config/types.js.map +0 -1
- package/dist/config/validation.d.ts.map +0 -1
- package/dist/config/validation.js.map +0 -1
- package/dist/content/index.d.ts.map +0 -1
- package/dist/content/index.js.map +0 -1
- package/dist/content/registry.d.ts.map +0 -1
- package/dist/content/registry.js.map +0 -1
- package/dist/content/types.d.ts.map +0 -1
- package/dist/content/types.js.map +0 -1
- package/dist/dev/index.d.ts.map +0 -1
- package/dist/dev/index.js.map +0 -1
- package/dist/index.d.ts.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/markdown/code.d.ts.map +0 -1
- package/dist/markdown/code.js.map +0 -1
- package/dist/markdown/containers.d.ts.map +0 -1
- package/dist/markdown/containers.js.map +0 -1
- package/dist/markdown/includes.d.ts.map +0 -1
- package/dist/markdown/includes.js.map +0 -1
- package/dist/markdown/index.d.ts.map +0 -1
- package/dist/markdown/index.js.map +0 -1
- package/dist/markdown/loader.d.ts.map +0 -1
- package/dist/markdown/loader.js.map +0 -1
- package/dist/markdown/preserve-tags.d.ts.map +0 -1
- package/dist/markdown/preserve-tags.js.map +0 -1
- package/dist/markdown/renderer.d.ts.map +0 -1
- package/dist/markdown/renderer.js.map +0 -1
- package/dist/markdown/tag-validator.d.ts.map +0 -1
- package/dist/markdown/tag-validator.js.map +0 -1
- package/dist/markdown/types.d.ts.map +0 -1
- package/dist/markdown/types.js.map +0 -1
- package/dist/plugin/compat.d.ts.map +0 -1
- package/dist/plugin/compat.js.map +0 -1
- package/dist/plugin/context.d.ts.map +0 -1
- package/dist/plugin/context.js.map +0 -1
- package/dist/plugin/index.d.ts.map +0 -1
- package/dist/plugin/index.js.map +0 -1
- package/dist/plugin/manager.d.ts.map +0 -1
- package/dist/plugin/manager.js.map +0 -1
- package/dist/plugin/types.d.ts.map +0 -1
- package/dist/plugin/types.js.map +0 -1
- package/dist/plugins/blog-index/index.d.ts.map +0 -1
- package/dist/plugins/blog-index/index.js.map +0 -1
- package/dist/plugins/sidenav/index.d.ts.map +0 -1
- package/dist/plugins/sidenav/index.js.map +0 -1
- package/dist/plugins/toc/index.d.ts.map +0 -1
- package/dist/plugins/toc/index.js.map +0 -1
- package/dist/preview/index.d.ts.map +0 -1
- package/dist/preview/index.js.map +0 -1
- package/dist/theme/default/build/generate-all.d.ts +0 -9
- package/dist/theme/default/build/generate-all.d.ts.map +0 -1
- package/dist/theme/default/build/generate-all.js +0 -1
- package/dist/theme/default/build/generate-all.js.map +0 -1
- package/dist/theme/default/build/generate-css.d.ts +0 -19
- package/dist/theme/default/build/generate-css.d.ts.map +0 -1
- package/dist/theme/default/build/generate-css.js +0 -1
- package/dist/theme/default/build/generate-css.js.map +0 -1
- package/dist/theme/default/build/index.d.ts +0 -5
- package/dist/theme/default/build/index.d.ts.map +0 -1
- package/dist/theme/default/build/index.js +0 -1
- package/dist/theme/default/build/index.js.map +0 -1
- package/dist/theme/default/design-systems/default.d.ts.map +0 -1
- package/dist/theme/default/design-systems/default.js.map +0 -1
- package/dist/theme/default/design-systems/docusaurus.d.ts.map +0 -1
- package/dist/theme/default/design-systems/docusaurus.js.map +0 -1
- package/dist/theme/default/design-systems/index.d.ts.map +0 -1
- package/dist/theme/default/design-systems/index.js.map +0 -1
- package/dist/theme/default/design-systems/rspress.d.ts.map +0 -1
- package/dist/theme/default/design-systems/rspress.js.map +0 -1
- package/dist/theme/default/design-systems/types.d.ts.map +0 -1
- package/dist/theme/default/design-systems/types.js.map +0 -1
- package/dist/theme/default/design-systems/vitepress.d.ts.map +0 -1
- package/dist/theme/default/design-systems/vitepress.js.map +0 -1
- package/dist/theme/default/index.d.ts.map +0 -1
- package/dist/theme/default/index.js.map +0 -1
- package/dist/theme/default/theme.d.ts.map +0 -1
- package/dist/theme/default/theme.js.map +0 -1
- package/dist/theme/index.d.ts.map +0 -1
- package/dist/theme/index.js.map +0 -1
- package/dist/theme/loader.d.ts.map +0 -1
- package/dist/theme/loader.js.map +0 -1
- package/dist/theme/types.d.ts.map +0 -1
- package/dist/theme/types.js.map +0 -1
- package/dist/vite/index.d.ts +0 -6
- package/dist/vite/index.d.ts.map +0 -1
- package/dist/vite/index.js +0 -1
- package/dist/vite/index.js.map +0 -1
- package/dist/vite/markdownPlugin.d.ts +0 -15
- package/dist/vite/markdownPlugin.d.ts.map +0 -1
- package/dist/vite/markdownPlugin.js +0 -1
- package/dist/vite/markdownPlugin.js.map +0 -1
- package/dist/vite/plugin.d.ts +0 -18
- package/dist/vite/plugin.d.ts.map +0 -1
- package/dist/vite/plugin.js +0 -1
- package/dist/vite/plugin.js.map +0 -1
package/dist/build/index.js
CHANGED
|
@@ -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 a from"gray-matter";import{loadConfig as s}from"../config/loader.js";import{getDesignSystem as i,getDarkModeOverride as r}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,"..",".."),y=o.join(w,"src","theme","default"),k=new Set(["@markopress/theme-default","theme-default","default"]);function j(e){return k.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 syncPublicAssets(t,n,a){if(t===n)return;const s=o.join(t,"public"),i=o.join(n,"public"),r=o.join(n,"src",".generated","public-assets-manifest.json"),c=await async function(o){try{const t=await e.readFile(o,"utf-8"),n=JSON.parse(t);return Array.isArray(n)?n.filter(e=>"string"==typeof e):[]}catch{return[]}}(r);let l=[];try{if(!(await e.stat(s)).isDirectory())return await D(i,c,l),void await _(r,l)}catch{return await D(i,c,l),void await _(r,l)}await e.mkdir(i,{recursive:!0}),l=await E(s,i),await D(i,c,l),await _(r,l),a&&(console.log(" Synced public assets from: "+s),console.log(" Output: "+i))}export async function build(n={}){const{outDir:i,debug:r=!1,useCatchAllRoutes:u,root:m}=n,h=m||process.cwd(),w=[],y=new Map,k=new Map,j=o.join(h,".markopress");let T=h;try{(await e.stat(j)).isDirectory()&&(T=j)}catch{}const v=e=>({start:()=>{k.set(e,performance.now())},end:()=>{const o=k.get(e)||0,t=performance.now()-o;y.set(e,t)}});try{console.log("🚀 Building MarkoPress site...\n");const n=v("Config loading");n.start();let m,k=await s(h,{mode:"production",command:"build"});if(n.end(),k.plugins&&k.plugins.length>0){console.log("🔌 Loading plugins...");const e=v("Plugin loading");e.start(),m=new d(k),await m.loadPlugins(k.plugins),k=m.getConfig(),e.end(),console.log("")}if(m){console.log("📦 Loading plugin content...");const e=v("Plugin loadContent hooks");e.start(),await m.execLoadContentHooks(),e.end(),console.log(" Plugin content loaded\n")}const j={},P=[],$=o.resolve(h,k.contentDir);try{const t=await e.readdir($,{withFileTypes:!0,recursive:!0}),n=new Map;for(const s of t){if(!s.isFile()||!s.name.endsWith(".md"))continue;const t=o.join(s.path||s.parentPath||$,s.name),i=o.relative($,t),r=filePathToUrl(t,$),c=i.split(o.sep),l=1===c.length?"root":c[0],d=await e.readFile(t,"utf-8");let u={};try{u=a(d).data}catch{}n.has(l)||n.set(l,[]),n.get(l).push({id:s.name.replace(".md",""),slug:s.name.replace(".md",""),filePath:t,urlPath:r,directory:l,processed:{frontmatter:u}})}for(const[e,t]of n){const n=k.content[e]||{},a=new Map;P.push({id:e,dir:o.join($,"root"===e?"":e),config:n,features:n,files:t,enhance(e,o){a.set(e,o)},getEnhancement:e=>a.get(e),_enhancements:a})}}catch(e){console.warn("Warning: Could not scan content directory: "+e)}if(m&&P.length>0){console.log("🔌 Enhancing modules with plugin metadata...");const t=v("Module enhancement");t.start();for(const e of P)console.log(` Module: ${e.id} (${e.files.length} files)`),e.files.length>0&&console.log(" First file has processed: "+!!e.files[0].processed);await m.execEnhanceModulesHooks(P),t.end(),console.log(` Enhanced ${P.length} module(s)\n`);const n=o.join(T,"src",".generated");await e.mkdir(n,{recursive:!0});const a=(k.site?.base||"/").replace(/\/$/,""),s={};for(const e of P){const o={},t=e._enhancements.entries();for(const[e,n]of t)o[e]=n;Object.keys(o).length>0&&(a&&b(o,a),s[e.id]=o)}const i=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(i,r,"utf-8"),console.log(" Wrote module enhancements to src/.generated/module-enhancements.js\n")}console.log("📦 Syncing public assets...");const F=v("Public assets sync");if(F.start(),await syncPublicAssets(h,T,r),F.end(),console.log(" Public assets synced\n"),!1!==k.search?.enabled){console.log("🔍 Building search index...");const t=v("Search index");t.start();const n=[],a=(k.site?.base||"/").replace(/\/$/,"");for(const o of P)for(const t of o.files)try{const o=await e.readFile(t.filePath,"utf-8"),s=await f(o,{...k.markdown,base:a});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,k.search),a=o.join(T,"public","search-index.json");await e.mkdir(o.dirname(a),{recursive:!0}),await e.writeFile(a,t),console.log(` Search index built (${n.length} pages)\n`)}catch(e){console.warn(" Warning: Failed to build search index:",e)}t.end()}if(k.markdown.markoTags?.enabled){const e=o.join(T,k.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 S={};if(m){const e=v("Extend routes hooks");e.start(),S=await m.execExtendRoutesHooks(S),e.end(),console.log("🔌 Extended routes manifest:",Object.keys(S).length)}console.log("📝 Generating routes from content...");const x=v("Route generation");x.start();const E=u??k.build.useCatchAllRoutes;console.log("📄 Pre-rendering markdown to .marko files...");const _=v("Pre-render markdown");_.start();const D=o.join(T,"src",".generated","markdown");await e.mkdir(D,{recursive:!0});const A={};let N=0;for(const t of P){const n=o.join(D,t.id);await e.mkdir(n,{recursive:!0});for(const a of t.files)try{const s=await e.readFile(a.filePath,"utf-8"),i=(k.site?.base||"/").replace(/\/$/,""),r=await f(s,{base:i});let c=r.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,a.slug+".marko");await e.writeFile(d,l),A[`${t.id}/${a.slug}`]={frontmatter:r.frontmatter,headers:r.headers||[],headTop:a.headTop||[],headBottom:a.headBottom||[]},N++}catch(e){console.warn(` Warning: Failed to pre-render ${t.id}/${a.slug}:`,e)}}const O=o.join(T,"src",".generated","content-metadata.js"),M=`// Auto-generated by MarkoPress - Do not edit\nexport default ${JSON.stringify(A,null,2)};\n`;await e.writeFile(O,M),_.end(),console.log(` Pre-rendered ${N} markdown files\n`),E?(await generateCatchAllRoutes(j,C,k,P,r,!0),console.log(" Using catch-all dynamic routes")):(await generateRoutes(j,C,k,P,r),console.log(" Using static routes")),x.end(),console.log(" Routes generated\n");const I=[];for(const[e,o]of Object.entries(S))(o.handler||o.component)&&(I.push({path:e,...o}),console.log(" Found plugin route: "+e));if(console.log(`🔌 Total manifest routes: ${Object.keys(S).length}, Plugin routes: ${I.length}`),m){const t=[...m.getPluginRoutes(),...I];if(t.length>0){console.log(`🔌 Generating ${t.length} plugin routes...`);const n=v("Plugin route generation");n.start(),await async function(t,n,a,s){for(const a of t){const t=a.path.slice(1),i=o.join(n,t,"+page");if(await e.mkdir(o.dirname(i),{recursive:!0}),a.handler){const t=o.join(o.dirname(i),"+handler.js");await e.writeFile(t,a.handler)}if(a.component){const o=i+".marko";await e.writeFile(o,a.component)}s&&console.log(" Generated plugin route: "+a.path)}}(t,C,0,r),n.end(),console.log(" Plugin routes generated\n")}}console.log("⚙️ Generating Vite config...");const L=v("Vite config generation");if(L.start(),await generateViteConfig(T,r),L.end(),console.log(" Vite config generated\n"),m){console.log("🔌 Processing plugin allContentLoaded hooks...");const e=v("AllContentLoaded hooks");e.start(),await m.execAllContentLoadedHooks(S),e.end(),console.log(" All content processed\n")}if(k.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 W=v("Theme CSS copy");W.start(),await copyThemeCSS(T,k,r),W.end(),console.log(" Theme CSS copied\n"),console.log("🎨 Extracting styles from Marko components...");const R=v("Marko component styles extraction");R.start(),await extractStylesFromMarkoTags(T,k,r),R.end(),console.log(" Component styles extracted\n");const G=[];for(const e of P)for(const o of e.files)G.push(o.urlPath);for(const e of Object.keys(S))G.includes(e)||G.push(e);const B=o.join(T,"src",".generated","static-urls.json");await e.mkdir(o.dirname(B),{recursive:!0}),await e.writeFile(B,JSON.stringify(G,null,2)),r&&console.log(` Generated static URL manifest: ${G.length} URLs`),console.log("🔨 Building with @marko/run...");const U=v("@marko/run build");U.start();const V=i||k.build.outDir,H=await async function(e,n,a){return new Promise(s=>{const i=["build"];e&&i.push("--output",e),n&&i.push("--debug");const r=t("npx",["marko-run",...i],{stdio:"inherit",cwd:a});r.on("close",t=>{if(0===t){const t=e||"dist";s({success:!0,outDir:o.join(a,t),errors:[]})}else s({success:!1,outDir:"",errors:["Build process exited with code "+t]})}),r.on("error",e=>{s({success:!1,outDir:"",errors:["Failed to start build process: "+e.message]})})})}(V,r,T);if(U.end(),!H.success)return w.push(...H.errors),{success:!1,outDir:"",pages:0,errors:w};const J=v("Collect build assets");J.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}(H.outDir);if(J.end(),m){console.log("🔌 Processing plugin postBuild hooks...");const e=v("Post-build hooks");e.start(),await m.execPostBuildHooks(k,H.outDir,S,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,H.outDir,k,r),q.end(),console.log(" Tags directory copied\n"),console.log("\n✅ Build completed successfully!"),console.log(" Output: "+H.outDir),console.log(" Pages: Generated dynamically at request time"),console.log("\n⏱️ Build timing:");const z=Array.from(y.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:H.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,a,s){await cleanupGeneratedRoutes(t,e,s);const i=[];let r=0,c=0,l=0;for(const[o,t]of Object.entries(e)){if(!Array.isArray(t))continue;i.push(o);const e=t;if("pages"===o)for(const o of e)await v(0,0,0,0,s),r++;else if("blog"===o)for(const o of e)await $(0,0,0,0,s),l++;else for(const o of e)await P(0,0,0,0,s),c++}await F(t,n,s);const d=o.resolve(t,"..","..");await generateViteConfig(d,s),await C(t,n,s),s&&(console.log(` Generated ${r} page routes`),console.log(` Generated ${c} doc routes`),console.log(` Generated ${l} blog routes`))}export async function cleanupGeneratedRoutes(t,n,a){const s=[],i=["+layout.marko","+middleware.js","components/**/*","api/**/*","lib/**/*"],r=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(r.some(e=>l.startsWith(e)))if(i.some(e=>e.includes("**")?RegExp(e.replace(/\*\*/g,".*").replace(/\*/g,"[^/]*")).test(l):c.name===e))a&&console.log(" Preserving: "+l);else try{await e.unlink(n),a&&console.log(" Deleted: "+l)}catch(e){if("ENOENT"!==e.code){const o=e instanceof Error?e.message:e+"";s.push(`Failed to delete ${l}: ${o}`)}}}for(const e of r){const n=o.join(t,e);try{await T(n)}catch{}}s.length>0&&(console.warn("⚠️ Cleanup warnings:"),s.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,a){a&&console.log(" Warning: Static routes deprecated, use catch-all routes")}async function P(e,o,t,n,a){a&&console.log(" Warning: Static routes deprecated, use catch-all routes")}async function $(e,o,t,n,a){a&&console.log(" Warning: Static routes deprecated, use catch-all routes")}async function F(t,n,a){const s=o.join(t,"_config.js"),i={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||{},_headInject:n._headInject||void 0},r=(n.site?.base||"/").replace(/\/$/,"");r&&i.theme.options?.navbar&&(i.theme.options.navbar=i.theme.options.navbar.map(e=>({...e,link:e.link&&!e.link.startsWith(r)?r+e.link:e.link})));const c=`// Auto-generated by MarkoPress - Do not edit\nexport const config = ${JSON.stringify(i,null,2)};\n`;await e.writeFile(s,c),a&&console.log(" Generated: "+s)}async function C(t,n,a){const s=o.join(t,"+layout.marko"),i=(n.theme,n.site?.title||"MarkoPress"),r=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:i,THEME_STYLE:r,BASE_PATH:c,COMPONENT_STYLES_LINK:l});await e.writeFile(s,d),a&&console.log(" Generated: "+s)}async function S(t,n){const a=o.dirname(new URL(import.meta.url).pathname),s=o.join(a,"..",".."),i=o.join(s,"templates",t);let r=await e.readFile(i,"utf-8");r="true"===n.IS_BUILD?r.replace(/\/\/ \{\{IF_DEV_START\}\}[\s\S]*?\/\/ \{\{IF_DEV_END\}\}/g,""):r.replace(/\/\/ \{\{IF_BUILD_START\}\}[\s\S]*?\/\/ \{\{IF_BUILD_END\}\}/g,""),r=r.replace(/\/\/ \{\{IF_(?:BUILD|DEV)_(?:START|END)\}\}\n?/g,"");for(const[e,o]of Object.entries(n))r=r.replace(RegExp(`\\{\\{${e}\\}\\}`,"g"),o);return r}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 a=o.join(t,"vite.config.js");try{if((await e.readFile(a,"utf-8")).includes("markdownContentPlugin"))return void(n&&console.log(" Vite config already has markdownContentPlugin"))}catch{}await e.writeFile(a,"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,a){const s=o.join(t,"public","_markopress","theme");await e.mkdir(s,{recursive:!0});const i=n.theme?.name||"@markopress/theme-default";try{validateThemeName(i)}catch(e){const o=e instanceof Error?e.message:e+"";throw Error("Security: "+o)}const r=n.theme?.options?.style||"default",c=`theme-${r}.css`,l=[...j(i)?[o.join(y,"public",c)]:[],o.join(t,"..","node_modules",i,"public",c),o.join(t,"node_modules",i,"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: ${r} */\nbody { font-family: system-ui, sans-serif; margin: 0; padding: 0; }`,n=o.join(s,c);return void await e.writeFile(n,t)}const m=o.join(s,c);await e.writeFile(m,d),a&&(console.log(` Copied ${c} from: ${u}`),console.log(" Output: "+m));const g="styles.css",f=[...j(i)?[o.join(y,g)]:[],o.join(t,"..","node_modules",i,"src",g),o.join(t,"node_modules",i,"src",g)];for(const t of f)try{await e.access(t);const n=await e.readFile(t,"utf-8"),i=o.join(s,g);await e.writeFile(i,n),a&&(console.log(` Copied ${g} from: ${t}`),console.log(" Output: "+i));break}catch{}}export async function extractStylesFromMarkoTags(t,n,a){const s=n.markdown?.markoTags?.tagsDir||"src/tags",i=o.join(t,s),r=o.join(t,"public");await e.mkdir(r,{recursive:!0});const c=o.join(r,"markopress-components.css");if(!n.markdown?.markoTags?.enabled){a&&console.log(" Marko tags not enabled, skipping style extraction");try{await e.unlink(c)}catch{}return}try{await e.access(i)}catch{return void(a&&console.log(" No tags directory found at: "+i))}const l=[];if(await async function t(n){const a=await e.readdir(n,{withFileTypes:!0});for(const e of a){const a=o.join(n,e.name);e.isDirectory()?await t(a):e.isFile()&&e.name.endsWith(".marko")&&l.push(a)}}(i),0===l.length)return void(a&&console.log(" No .marko files found in: "+i));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(i,t),a=""===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,s=Array.from(o.matchAll(n));if(s.length>0){d.push(`/* ${a}.marko */`);for(const e of s){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*)/),a=n?n[1].length:0,s=" ".repeat(Math.floor(a/2)),i=t.trim().replace(/:global\(([^)]+)\)/g,"$1");d.push(s+i)}}}d.push("")}}catch(e){console.warn(` Warning: Could not read file ${t}:`,e)}}const u=d.join("\n");await e.writeFile(c,u),a&&(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}),a=await Promise.all(n.map(e=>{const n=o.resolve(t,e.name);return e.isDirectory()?x(n):n}));return Array.prototype.concat(...a).filter(e=>e.endsWith(".marko"))}export async function copyThemeComponents(t,n,a){const s=n.theme?.name||"@markopress/theme-default",i=o.join(t,"src"),r=o.join(i,"tags");await e.mkdir(r,{recursive:!0});const c=[...j(s)?[o.join(y,"tags")]:[],o.join(t,"..","node_modules",s,"dist","tags"),o.join(t,"node_modules",s,"dist","tags"),o.join(t,"..","node_modules",s,"src","components"),o.join(t,"node_modules",s,"src","components")];let l=null;for(const o of c)try{await e.access(o),l=o;break}catch{}if(!l)return void(a&&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),s=o.join(r,n);let i=!1;try{await e.access(s),i=!0}catch{}i?a&&console.log(" Skipped component (user override exists): "+n):(await e.mkdir(o.dirname(s),{recursive:!0}),await e.copyFile(t,s),u++)}a&&(console.log(` Copied ${u} theme components from: ${l}`),console.log(" Output: "+r))}export async function copyTagsDirectory(t,n,a,s){const i=a.markdown?.markoTags?.tagsDir||"src/tags",r=o.join(t,i),c=o.join(n,"tags");try{await e.access(r)}catch{return void(s&&console.log(" No tags directory found at: "+r))}await e.mkdir(c,{recursive:!0});const l=await e.readdir(r,{withFileTypes:!0});let d=0;for(const t of l){const n=o.join(r,t.name),a=o.join(c,t.name);if(t.isDirectory()){await e.mkdir(a,{recursive:!0});const t=await e.readdir(n,{withFileTypes:!0});for(const s of t){const t=o.join(n,s.name),i=o.join(a,s.name);s.isDirectory()||(await e.copyFile(t,i),d++)}}else t.isFile()&&(await e.copyFile(n,a),d++)}s&&(console.log(` Copied ${d} tag files from: ${r}`),console.log(" Output: "+c))}async function E(t,n,a=t){const s=await e.readdir(t,{withFileTypes:!0}),i=[];for(const r of s){const s=o.join(t,r.name),c=o.join(n,r.name);r.isDirectory()?(await e.mkdir(c,{recursive:!0}),i.push(...await E(s,c,a))):r.isFile()&&(await e.copyFile(s,c),i.push(o.relative(a,s)))}return i}async function _(t,n){await e.mkdir(o.dirname(t),{recursive:!0}),await e.writeFile(t,JSON.stringify(n,null,2))}async function D(t,n,a){const s=new Set(a),i=n.filter(e=>!s.has(e)).sort((e,o)=>o.length-e.length);for(const n of i){const a=o.join(t,n);await e.rm(a,{force:!0}),await A(o.dirname(a),t)}}async function A(t,n){let a=t;for(;a.startsWith(n)&&a!==n;){let t;try{t=await e.readdir(a)}catch{break}if(t.length>0)break;await e.rmdir(a),a=o.dirname(a)}}export async function generateCatchAllRoutes(t,n,a,s,i,r=!0){console.log(" Using catch-all dynamic routes..."),console.log(" Mode: "+(r?"build (pre-compiled)":"dev (request-time rendering)"));const c=Object.keys(a.content||{}),l=new Set(s.map(e=>e.id)),d=[...new Set([...c,...l])];if(s.some(e=>"root"===e.id)){const t=o.join(n,"$$slug");await e.mkdir(t,{recursive:!0});const a=await S("catch-all-handler.js.template",{CONTENT_TYPE:"root",CONFIG_PATH:"../_config.js",VITE_PLUGIN_PATH:"markopress/build",IS_BUILD:r?"true":"false"});await e.writeFile(o.join(t,"+handler.js"),a);const s=await S("catch-all-page.marko.template",{CONTENT_TYPE_CLASS:"page"});await e.writeFile(o.join(t,"+page.marko"),s),i&&console.log(" Generated root pages catch-all route")}for(const t of d){if("root"===t)continue;const a=o.join(n,t,"$$slug");await e.mkdir(a,{recursive:!0});const s=await S("catch-all-handler.js.template",{CONTENT_TYPE:t,CONFIG_PATH:"../../_config.js",VITE_PLUGIN_PATH:"markopress/build",IS_BUILD:r?"true":"false"});await e.writeFile(o.join(a,"+handler.js"),s);const c=await S("catch-all-page.marko.template",{CONTENT_TYPE_CLASS:t});await e.writeFile(o.join(a,"+page.marko"),c),i&&console.log(` Generated ${t} catch-all route`)}await F(n,a,i);const u=o.resolve(n,"..","..");await generateViteConfig(u,i),await C(n,a,i)}export{u as loadMarkdownModule,m as registerMarkdownContent};export{markdownContentPlugin}from"./vite-markdown-plugin.js";
|
|
1
|
+
import{promises as e}from"node:fs";import t from"node:path";import{spawn as o}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 i,getDarkModeOverride as r}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 g,escapeMarkoText as m}from"./vite-markdown-plugin.js";import{renderMarkdown as f}from"../markdown/renderer.js";import{buildSearchIndex as p}from"../search/index.js";const h=t.dirname(n(import.meta.url)),w=t.resolve(h,"..",".."),y=t.join(w,"src","theme","default"),k=new Set(["@markopress/theme-default","theme-default","default"]);function j(e){return k.has(e)}export function filePathToUrl(e,o){const n=t.relative(o,e).replace(/\.md$/,"").split(t.sep).join("/");return"index"===n?"/":n.endsWith("/index")?"/"+n.replace("/index",""):"/"+n}export async function syncPublicAssets(o,n,s){if(o===n)return;const a=t.join(o,"public"),i=t.join(n,"public"),r=t.join(n,"src",".generated","public-assets-manifest.json"),c=await async function(t){try{const o=await e.readFile(t,"utf-8"),n=JSON.parse(o);return Array.isArray(n)?n.filter(e=>"string"==typeof e):[]}catch{return[]}}(r);let l=[];try{if(!(await e.stat(a)).isDirectory())return await _(i,c,l),void await E(r,l)}catch{return await _(i,c,l),void await E(r,l)}await e.mkdir(i,{recursive:!0}),l=await D(a,i),await _(i,c,l),await E(r,l),s&&(console.log(" Synced public assets from: "+a),console.log(" Output: "+i))}export async function build(n={}){const{outDir:i,debug:r=!1,useCatchAllRoutes:u,root:g}=n,h=g||process.cwd(),w=[],y=new Map,k=new Map,j=t.join(h,".markopress");let T=h;try{(await e.stat(j)).isDirectory()&&(T=j)}catch{}const v=e=>({start:()=>{k.set(e,performance.now())},end:()=>{const t=k.get(e)||0,o=performance.now()-t;y.set(e,o)}});try{console.log("🚀 Building MarkoPress site...\n");const n=v("Config loading");n.start();let g,k=await a(h,{mode:"production",command:"build"});if(n.end(),k.plugins&&k.plugins.length>0){console.log("🔌 Loading plugins...");const e=v("Plugin loading");e.start(),g=new d(k),await g.loadPlugins(k.plugins),k=g.getConfig(),e.end(),console.log("")}if(g){console.log("📦 Loading plugin content...");const e=v("Plugin loadContent hooks");e.start(),await g.execLoadContentHooks(),e.end(),console.log(" Plugin content loaded\n")}const j={},P=[],$=t.resolve(h,k.contentDir);try{const o=await e.readdir($,{withFileTypes:!0,recursive:!0}),n=new Map;for(const a of o){if(!a.isFile()||!a.name.endsWith(".md"))continue;const o=t.join(a.path||a.parentPath||$,a.name),i=t.relative($,o),r=filePathToUrl(o,$),c=i.split(t.sep),l=1===c.length?"root":c[0],d=await e.readFile(o,"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:o,urlPath:r,directory:l,processed:{frontmatter:u}})}for(const[e,o]of n){const n=k.content[e]||{},s=new Map;P.push({id:e,dir:t.join($,"root"===e?"":e),config:n,features:n,files:o,enhance(e,t){s.set(e,t)},getEnhancement:e=>s.get(e),_enhancements:s})}}catch(e){console.warn("Warning: Could not scan content directory: "+e)}const F={};for(const e of P){const t=e.files.map(t=>({id:t.urlPath,moduleId:e.id,metadata:{...t.processed.frontmatter},urlPath:t.urlPath}));t.length>0&&(F[e.id]=t)}if(g&&g.getPluginData().set("contentRegistry",F),r&&Object.keys(F).length>0){const e=Object.keys(F),t=Object.values(F).reduce((e,t)=>e+t.length,0);console.log(` Registry: ${t} items across ${e.length} modules (${e.join(", ")})`)}if(g&&P.length>0){console.log("🔌 Enhancing modules with plugin metadata...");const o=v("Module enhancement");o.start();for(const e of P)console.log(` Module: ${e.id} (${e.files.length} files)`),e.files.length>0&&console.log(" First file has processed: "+!!e.files[0].processed);await g.execEnhanceModulesHooks(P),o.end(),console.log(` Enhanced ${P.length} module(s)\n`);const n=t.join(T,"src",".generated");await e.mkdir(n,{recursive:!0});const s=(k.site?.base||"/").replace(/\/$/,""),a={};for(const e of P){const t={},o=e._enhancements.entries();for(const[e,n]of o)t[e]=n;Object.keys(t).length>0&&(s&&b(t,s),a[e.id]=t)}const i=t.join(n,"module-enhancements.js"),r=`// Auto-generated by MarkoPress - Do not edit\nexport default ${JSON.stringify(a,null,2)};\n`;await e.writeFile(i,r,"utf-8");const c=t.join(n,"module-enhancements.json");await e.writeFile(c,JSON.stringify(a,null,2),"utf-8"),console.log(" Wrote module enhancements to src/.generated/module-enhancements.{js,json}\n")}console.log("📦 Syncing public assets...");const C=v("Public assets sync");if(C.start(),await syncPublicAssets(h,T,r),C.end(),console.log(" Public assets synced\n"),!1!==k.search?.enabled){console.log("🔍 Building search index...");const o=v("Search index");o.start();const n=[],s=(k.site?.base||"/").replace(/\/$/,"");for(const t of P)for(const o of t.files)try{const t=await e.readFile(o.filePath,"utf-8"),a=await f(t,{...k.markdown,base:s});n.push({url:o.urlPath,html:a.html,title:a.frontmatter?.title||o.id,frontmatter:a.frontmatter})}catch(e){console.warn(` Warning: Could not index ${o.filePath}:`,e)}try{const o=await p(n,k.search),s=t.join(T,"public","search-index.json");await e.mkdir(t.dirname(s),{recursive:!0}),await e.writeFile(s,o),console.log(` Search index built (${n.length} pages)\n`)}catch(e){console.warn(" Warning: Failed to build search index:",e)}o.end()}if(k.markdown.markoTags?.enabled){const e=t.join(T,k.markdown.markoTags.tagsDir||"src/tags");console.log("🔍 Scanning tags directory...");const o=v("Tag validation setup");o.start(),await c.loadAvailableTags(e),o.end(),console.log(` Found ${c.getAvailableTagsCount()} tags\n`)}else c.reset();const S=t.join(T,"src","routes");await e.mkdir(S,{recursive:!0});let x={};if(g){const e=v("Extend routes hooks");e.start(),x=await g.execExtendRoutesHooks(x),e.end(),console.log("🔌 Extended routes manifest:",Object.keys(x).length)}console.log("📝 Generating routes from content...");const D=v("Route generation");D.start();const E=u??k.build.useCatchAllRoutes;console.log("📄 Pre-rendering markdown to .marko files...");const _=v("Pre-render markdown");_.start();const A=t.join(T,"src",".generated","markdown");await e.mkdir(A,{recursive:!0});const O={};let N=0;for(const o of P){const n=t.join(A,o.id);await e.mkdir(n,{recursive:!0});for(const s of o.files)try{const a=await e.readFile(s.filePath,"utf-8"),i=(k.site?.base||"/").replace(/\/$/,""),r=await f(a,{base:i});let c=r.html.replace(/<span class="line"><\/span>(\s*<\/code>)/g,"$1");const l=`<div class="markdown-content">\n${m(c)}\n</div>`,d=t.join(n,s.slug+".marko");await e.writeFile(d,l),O[`${o.id}/${s.slug}`]={frontmatter:r.frontmatter,headers:r.headers||[],headTop:s.headTop||[],headBottom:s.headBottom||[]},N++}catch(e){console.warn(` Warning: Failed to pre-render ${o.id}/${s.slug}:`,e)}}const M=t.join(T,"src",".generated","content-metadata.js"),I=`// Auto-generated by MarkoPress - Do not edit\nexport default ${JSON.stringify(O,null,2)};\n`;await e.writeFile(M,I),_.end(),console.log(` Pre-rendered ${N} markdown files\n`),E?(await generateCatchAllRoutes(j,S,k,P,r,!0),console.log(" Using catch-all dynamic routes")):(await generateRoutes(j,S,k,P,r),console.log(" Using static routes")),D.end(),console.log(" Routes generated\n");const W=[];for(const[e,t]of Object.entries(x))(t.handler||t.component)&&(W.push({path:e,...t}),console.log(" Found plugin route: "+e));if(console.log(`🔌 Total manifest routes: ${Object.keys(x).length}, Plugin routes: ${W.length}`),g){const o=[...g.getPluginRoutes(),...W];if(o.length>0){console.log(`🔌 Generating ${o.length} plugin routes...`);const n=v("Plugin route generation");n.start(),await async function(o,n,s,a){for(const s of o){const o=s.path.slice(1),i=t.join(n,o,"+page");if(await e.mkdir(t.dirname(i),{recursive:!0}),s.handler){const o=t.join(t.dirname(i),"+handler.js");await e.writeFile(o,s.handler)}if(s.component){const t=i+".marko";await e.writeFile(t,s.component)}a&&console.log(" Generated plugin route: "+s.path)}}(o,S,0,r),n.end(),console.log(" Plugin routes generated\n")}}console.log("⚙️ Generating Vite config...");const L=v("Vite config generation");if(L.start(),await generateViteConfig(T,r),L.end(),console.log(" Vite config generated\n"),g){console.log("🔌 Processing plugin allContentLoaded hooks...");const o=v("AllContentLoaded hooks");o.start(),await g.execAllContentLoadedHooks(x),o.end(),console.log(" All content processed\n");const n=g.getPluginData();if(n.has("contentRegistry")){const o=t.join(T,"src",".generated");await e.mkdir(o,{recursive:!0});const s=n.get("contentRegistry"),a=t.join(o,"content-registry.js"),i=`// Auto-generated by MarkoPress content-registry plugin - Do not edit\nexport default ${JSON.stringify(s,null,2)};\n`;await e.writeFile(a,i,"utf-8");const r=t.join(o,"content-registry.json");await e.writeFile(r,JSON.stringify(s,null,2),"utf-8"),console.log(" Wrote content registry to src/.generated/content-registry.{js,json}\n")}}if(k.markdown.markoTags?.enabled){console.log("🔍 Validating Marko tags...");const e=v("Tag validation");e.start();const t=c.validate();if(e.end(),!t.success){const e=l(t.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 R=v("Theme CSS copy");R.start(),await copyThemeCSS(T,k,r),R.end(),console.log(" Theme CSS copied\n"),console.log("🎨 Extracting styles from Marko components...");const G=v("Marko component styles extraction");G.start(),await extractStylesFromMarkoTags(T,k,r),G.end(),console.log(" Component styles extracted\n");const B=[];for(const e of P)for(const t of e.files)B.push(t.urlPath);for(const e of Object.keys(x))B.includes(e)||B.push(e);const U=t.join(T,"src",".generated","static-urls.json");await e.mkdir(t.dirname(U),{recursive:!0}),await e.writeFile(U,JSON.stringify(B,null,2)),r&&console.log(` Generated static URL manifest: ${B.length} URLs`),console.log("🔨 Building with @marko/run...");const V=v("@marko/run build");V.start();const H=i||k.build.outDir,J=await async function(e,n,s){return new Promise(a=>{const i=["build"];e&&i.push("--output",e),n&&i.push("--debug");const r=o("npx",["marko-run",...i],{stdio:"inherit",cwd:s});r.on("close",o=>{if(0===o){const o=e||"dist";a({success:!0,outDir:t.join(s,o),errors:[]})}else a({success:!1,outDir:"",errors:["Build process exited with code "+o]})}),r.on("error",e=>{a({success:!1,outDir:"",errors:["Failed to start build process: "+e.message]})})})}(H,r,T);if(V.end(),!J.success)return w.push(...J.errors),{success:!1,outDir:"",pages:0,errors:w};const Y=v("Collect build assets");Y.start();const q=await async function(t){const o=[];try{const n=await e.readdir(t,{recursive:!0});for(const e of n)"string"==typeof e&&(e.endsWith(".js")||e.endsWith(".css")||e.endsWith(".json"))&&o.push(e)}catch(e){console.warn("Warning: Could not collect build assets:",e)}return o}(J.outDir);if(Y.end(),g){console.log("🔌 Processing plugin postBuild hooks...");const e=v("Post-build hooks");e.start(),await g.execPostBuildHooks(k,J.outDir,x,q),e.end(),console.log(" Post-build hooks completed\n")}console.log("📦 Copying Marko tags directory...");const z=v("Copy tags directory");z.start(),await copyTagsDirectory(h,J.outDir,k,r),z.end(),console.log(" Tags directory copied\n"),console.log("\n✅ Build completed successfully!"),console.log(" Output: "+J.outDir),console.log(" Pages: Generated dynamically at request time"),console.log("\n⏱️ Build timing:");const K=Array.from(y.entries()).sort((e,t)=>t[1]-e[1]);for(const[e,t]of K){const o=(t/1e3).toFixed(2);console.log(` ${"█".repeat(Math.min(Math.floor(t/100),20))} ${e}: ${o}s`)}return{success:!0,outDir:J.outDir,pages:0,errors:w}}catch(e){const t=e instanceof Error?e.message:e+"";return w.push(t),console.error("\n❌ Build failed:",t),{success:!1,outDir:"",pages:0,errors:w}}}function b(e,t){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(t)?t+e.link:e.link})):e.items}))),Array.isArray(e.blogPosts)&&(e.blogPosts=e.blogPosts.map(e=>({...e,link:e.link&&!e.link.startsWith(t)?t+e.link:e.link})))}export async function generateRoutes(e,o,n,s,a){await cleanupGeneratedRoutes(o,e,a);const i=[];let r=0,c=0,l=0;for(const[t,o]of Object.entries(e)){if(!Array.isArray(o))continue;i.push(t);const e=o;if("pages"===t)for(const t of e)await v(0,0,0,0,a),r++;else if("blog"===t)for(const t of e)await $(0,0,0,0,a),l++;else for(const t of e)await P(0,0,0,0,a),c++}await F(o,n,a);const d=t.resolve(o,"..","..");await generateViteConfig(d,a),await C(o,n,a),a&&(console.log(` Generated ${r} page routes`),console.log(` Generated ${c} doc routes`),console.log(` Generated ${l} blog routes`))}export async function cleanupGeneratedRoutes(o,n,s){const a=[],i=["+layout.marko","+middleware.js","components/**/*","api/**/*","lib/**/*"],r=Object.keys(n).filter(e=>"pages"!==e).map(e=>e+"/");try{const n=await e.readdir(o,{recursive:!0,withFileTypes:!0});for(const c of n){if(!c.isFile())continue;const n=t.join(c.path||c.parentPath||o,c.name),l=t.relative(o,n);if(r.some(e=>l.startsWith(e)))if(i.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 t=e instanceof Error?e.message:e+"";a.push(`Failed to delete ${l}: ${t}`)}}}for(const e of r){const n=t.join(o,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(o){try{const n=await e.readdir(o,{withFileTypes:!0});for(const e of n)if(e.isDirectory()){const n=t.join(o,e.name);await T(n)}0===(await e.readdir(o)).length&&await e.rmdir(o)}catch{}}async function v(e,t,o,n,s){s&&console.log(" Warning: Static routes deprecated, use catch-all routes")}async function P(e,t,o,n,s){s&&console.log(" Warning: Static routes deprecated, use catch-all routes")}async function $(e,t,o,n,s){s&&console.log(" Warning: Static routes deprecated, use catch-all routes")}async function F(o,n,s){const a=t.join(o,"_config.js"),i={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||{},_headInject:n._headInject||void 0},r=(n.site?.base||"/").replace(/\/$/,"");r&&i.theme.options?.navbar&&(i.theme.options.navbar=i.theme.options.navbar.map(e=>({...e,link:e.link&&!e.link.startsWith(r)?r+e.link:e.link})));const c=`// Auto-generated by MarkoPress - Do not edit\nexport const config = ${JSON.stringify(i,null,2)};\n`;await e.writeFile(a,c),s&&console.log(" Generated: "+a)}async function C(o,n,s){const a=t.join(o,"+layout.marko"),i=(n.theme,n.site?.title||"MarkoPress"),r=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:i,THEME_STYLE:r,BASE_PATH:c,COMPONENT_STYLES_LINK:l});await e.writeFile(a,d),s&&console.log(" Generated: "+a)}async function S(o,n){const s=t.dirname(new URL(import.meta.url).pathname),a=t.join(s,"..",".."),i=t.join(a,"templates",o);let r=await e.readFile(i,"utf-8");r="true"===n.IS_BUILD?r.replace(/\/\/ \{\{IF_DEV_START\}\}[\s\S]*?\/\/ \{\{IF_DEV_END\}\}/g,""):r.replace(/\/\/ \{\{IF_BUILD_START\}\}[\s\S]*?\/\/ \{\{IF_BUILD_END\}\}/g,""),r=r.replace(/\/\/ \{\{IF_(?:BUILD|DEV)_(?:START|END)\}\}\n?/g,"");for(const[e,t]of Object.entries(n))r=r.replace(RegExp(`\\{\\{${e}\\}\\}`,"g"),t);return r}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(t.isAbsolute(e))throw Error(`Theme name cannot be an absolute path: "${e}"`)}export async function generateViteConfig(o,n){const s=t.join(o,"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(o,n,s){const a=t.join(o,"public","_markopress","theme");await e.mkdir(a,{recursive:!0});const i=n.theme?.name||"@markopress/theme-default";try{validateThemeName(i)}catch(e){const t=e instanceof Error?e.message:e+"";throw Error("Security: "+t)}const r=n.theme?.options?.style||"default",c=`theme-${r}.css`,l=[...j(i)?[t.join(y,"public",c)]:[],t.join(o,"..","node_modules",i,"public",c),t.join(o,"node_modules",i,"public",c)];let d=null,u=null;for(const t of l)try{await e.access(t),d=await e.readFile(t,"utf-8"),u=t;break}catch{}if(!d){console.warn(` Warning: Could not find ${c}, using minimal fallback`);const o=`/* Minimal fallback CSS for style: ${r} */\nbody { font-family: system-ui, sans-serif; margin: 0; padding: 0; }`,n=t.join(a,c);return void await e.writeFile(n,o)}const g=t.join(a,c);await e.writeFile(g,d),s&&(console.log(` Copied ${c} from: ${u}`),console.log(" Output: "+g));const m="styles.css",f=[...j(i)?[t.join(y,m)]:[],t.join(o,"..","node_modules",i,"src",m),t.join(o,"node_modules",i,"src",m)];for(const o of f)try{await e.access(o);const n=await e.readFile(o,"utf-8"),i=t.join(a,m);await e.writeFile(i,n),s&&(console.log(` Copied ${m} from: ${o}`),console.log(" Output: "+i));break}catch{}}export async function extractStylesFromMarkoTags(o,n,s){const a=n.markdown?.markoTags?.tagsDir||"src/tags",i=t.join(o,a),r=t.join(o,"public");await e.mkdir(r,{recursive:!0});const c=t.join(r,"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(i)}catch{return void(s&&console.log(" No tags directory found at: "+i))}const l=[];if(await async function o(n){const s=await e.readdir(n,{withFileTypes:!0});for(const e of s){const s=t.join(n,e.name);e.isDirectory()?await o(s):e.isFile()&&e.name.endsWith(".marko")&&l.push(s)}}(i),0===l.length)return void(s&&console.log(" No .marko files found in: "+i));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 o of l){const n=t.relative(i,o),s=""===t.dirname(n)?t.basename(n,".marko"):t.join(t.dirname(n),t.basename(n,".marko"));try{const t=await e.readFile(o,"utf-8"),n=/<style\b[^>]*>([\s\S]*?)<\/style>/gi,a=Array.from(t.matchAll(n));if(a.length>0){d.push(`/* ${s}.marko */`);for(const e of a){const t=e[1]||"";if(t){const e=t.split("\n");let o=0;for(;o<e.length&&""===e[o].trim();)o++;let n=e.length-1;for(;n>=o&&""===e[n].trim();)n--;for(let t=o;t<=n;t++){const o=e[t];if(""===o.trim()){d.push("");continue}const n=o.match(/^(\s*)/),s=n?n[1].length:0,a=" ".repeat(Math.floor(s/2)),i=o.trim().replace(/:global\(([^)]+)\)/g,"$1");d.push(a+i)}}}d.push("")}}catch(e){console.warn(` Warning: Could not read file ${o}:`,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(o){const n=await e.readdir(o,{withFileTypes:!0}),s=await Promise.all(n.map(e=>{const n=t.resolve(o,e.name);return e.isDirectory()?x(n):n}));return Array.prototype.concat(...s).filter(e=>e.endsWith(".marko"))}export async function copyThemeComponents(o,n,s){const a=n.theme?.name||"@markopress/theme-default",i=t.join(o,"src"),r=t.join(i,"tags");await e.mkdir(r,{recursive:!0});const c=[...j(a)?[t.join(y,"tags")]:[],t.join(o,"..","node_modules",a,"dist","tags"),t.join(o,"node_modules",a,"dist","tags"),t.join(o,"..","node_modules",a,"src","components"),t.join(o,"node_modules",a,"src","components")];let l=null;for(const t of c)try{await e.access(t),l=t;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 o of d){const n=t.relative(l,o),a=t.join(r,n);let i=!1;try{await e.access(a),i=!0}catch{}i?s&&console.log(" Skipped component (user override exists): "+n):(await e.mkdir(t.dirname(a),{recursive:!0}),await e.copyFile(o,a),u++)}s&&(console.log(` Copied ${u} theme components from: ${l}`),console.log(" Output: "+r))}export async function copyTagsDirectory(o,n,s,a){const i=s.markdown?.markoTags?.tagsDir||"src/tags",r=t.join(o,i),c=t.join(n,"tags");try{await e.access(r)}catch{return void(a&&console.log(" No tags directory found at: "+r))}await e.mkdir(c,{recursive:!0});const l=await e.readdir(r,{withFileTypes:!0});let d=0;for(const o of l){const n=t.join(r,o.name),s=t.join(c,o.name);if(o.isDirectory()){await e.mkdir(s,{recursive:!0});const o=await e.readdir(n,{withFileTypes:!0});for(const a of o){const o=t.join(n,a.name),i=t.join(s,a.name);a.isDirectory()||(await e.copyFile(o,i),d++)}}else o.isFile()&&(await e.copyFile(n,s),d++)}a&&(console.log(` Copied ${d} tag files from: ${r}`),console.log(" Output: "+c))}async function D(o,n,s=o){const a=await e.readdir(o,{withFileTypes:!0}),i=[];for(const r of a){const a=t.join(o,r.name),c=t.join(n,r.name);r.isDirectory()?(await e.mkdir(c,{recursive:!0}),i.push(...await D(a,c,s))):r.isFile()&&(await e.copyFile(a,c),i.push(t.relative(s,a)))}return i}async function E(o,n){await e.mkdir(t.dirname(o),{recursive:!0}),await e.writeFile(o,JSON.stringify(n,null,2))}async function _(o,n,s){const a=new Set(s),i=n.filter(e=>!a.has(e)).sort((e,t)=>t.length-e.length);for(const n of i){const s=t.join(o,n);await e.rm(s,{force:!0}),await A(t.dirname(s),o)}}async function A(o,n){let s=o;for(;s.startsWith(n)&&s!==n;){let o;try{o=await e.readdir(s)}catch{break}if(o.length>0)break;await e.rmdir(s),s=t.dirname(s)}}export async function generateCatchAllRoutes(o,n,s,a,i,r=!0){console.log(" Using catch-all dynamic routes..."),console.log(" Mode: "+(r?"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 o=t.join(n,"$$slug");await e.mkdir(o,{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:r?"true":"false"});await e.writeFile(t.join(o,"+handler.js"),s);const a=await S("catch-all-page.marko.template",{CONTENT_TYPE_CLASS:"page"});await e.writeFile(t.join(o,"+page.marko"),a),i&&console.log(" Generated root pages catch-all route")}for(const o of d){if("root"===o)continue;const s=t.join(n,o,"$$slug");await e.mkdir(s,{recursive:!0});const a=await S("catch-all-handler.js.template",{CONTENT_TYPE:o,CONFIG_PATH:"../../_config.js",VITE_PLUGIN_PATH:"markopress/build",IS_BUILD:r?"true":"false"});await e.writeFile(t.join(s,"+handler.js"),a);const c=await S("catch-all-page.marko.template",{CONTENT_TYPE_CLASS:o});await e.writeFile(t.join(s,"+page.marko"),c),i&&console.log(` Generated ${o} catch-all route`)}await F(n,s,i);const u=t.resolve(n,"..","..");await generateViteConfig(u,i),await C(n,s,i)}export{u as loadMarkdownModule,g as registerMarkdownContent};export{markdownContentPlugin}from"./vite-markdown-plugin.js";
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Filesystem-based content source.
|
|
3
|
+
*
|
|
4
|
+
* Scans local markdown files and produces ContentItems with frontmatter metadata.
|
|
5
|
+
* This is the default content source — it replaces the inline scanning logic
|
|
6
|
+
* that was previously embedded in build/index.ts.
|
|
7
|
+
*/
|
|
8
|
+
import type { ContentItem, ContentSource } from './source.js';
|
|
9
|
+
export interface FilesystemSourceOptions {
|
|
10
|
+
/** Root directory containing content (e.g., 'content/') */
|
|
11
|
+
contentDir: string;
|
|
12
|
+
/** Base URL path for generating urlPath (default: '/') */
|
|
13
|
+
basePath?: string;
|
|
14
|
+
}
|
|
15
|
+
export declare class FilesystemSource implements ContentSource {
|
|
16
|
+
readonly id = "filesystem";
|
|
17
|
+
private contentDir;
|
|
18
|
+
private basePath;
|
|
19
|
+
private items;
|
|
20
|
+
private itemIndex;
|
|
21
|
+
constructor(options: FilesystemSourceOptions);
|
|
22
|
+
scan(): Promise<ContentItem[]>;
|
|
23
|
+
read(id: string): Promise<ContentItem | null>;
|
|
24
|
+
private filePathToUrl;
|
|
25
|
+
private getModuleId;
|
|
26
|
+
private fileToItem;
|
|
27
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{promises as t}from"node:fs";import e from"node:path";import i from"gray-matter";export class FilesystemSource{id="filesystem";contentDir;basePath;items=[];itemIndex=new Map;constructor(t){this.contentDir=e.resolve(t.contentDir),this.basePath=t.basePath||"/"}async scan(){let s;this.items=[],this.itemIndex.clear();try{s=await t.readdir(this.contentDir,{withFileTypes:!0,recursive:!0})}catch{return[]}for(const r of s){if(!r.isFile()||!r.name.endsWith(".md"))continue;const s=e.join(r.path||r.parentPath||this.contentDir,r.name),n=e.relative(this.contentDir,s),a=this.filePathToUrl(n),o=this.getModuleId(n),h=await t.readFile(s,"utf-8");let d={};try{d=i(h).data}catch{}const l=this.fileToItem(s,n,a,o,d);this.items.push(l),this.itemIndex.set(l.id,l)}return this.items}async read(t){return this.itemIndex.get(t)??null}filePathToUrl(t){const i=t.replace(/\.md$/,"").split(e.sep).join("/");return"index"===i?"/":i.endsWith("/index")?"/"+i.replace("/index",""):"/"+i}getModuleId(t){const i=t.split(e.sep);return 1===i.length?"root":i[0]}fileToItem(t,i,s,r,n){return{id:`${r}/${e.basename(i,".md")}`,moduleId:r,metadata:{...n},urlPath:s}}}
|
package/dist/content/index.d.ts
CHANGED
package/dist/content/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export*from"./types.js";export*from"./registry.js";
|
|
1
|
+
export*from"./types.js";export*from"./registry.js";export*from"./source.js";
|
|
@@ -1,28 +1,45 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
2
|
+
* Content module types used by the plugin system.
|
|
3
3
|
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
4
|
+
* The ContentRegistry class was removed — at runtime, registry data is a plain
|
|
5
|
+
* Record<string, ContentItem[]> produced by the build pipeline and written to
|
|
6
|
+
* .generated/content-registry.{js,json}.
|
|
6
7
|
*/
|
|
8
|
+
import type { ContentItem } from './source.js';
|
|
9
|
+
/** Query filter for the registry (for future server-side query API) */
|
|
10
|
+
export interface ContentQuery {
|
|
11
|
+
moduleId?: string;
|
|
12
|
+
limit?: number;
|
|
13
|
+
sort?: 'date-asc' | 'date-desc';
|
|
14
|
+
}
|
|
7
15
|
/**
|
|
8
|
-
*
|
|
9
|
-
|
|
10
|
-
export type ContentModule = any;
|
|
11
|
-
/**
|
|
12
|
-
* Module registry stub - no-op since content is rendered at request time
|
|
16
|
+
* Content module passed to plugins during enhanceModules hook.
|
|
17
|
+
* Represents a content section (blog, docs, etc.) with its files and enhancement API.
|
|
13
18
|
*/
|
|
14
|
-
export
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
get size(): number;
|
|
19
|
+
export interface ContentModule {
|
|
20
|
+
id: string;
|
|
21
|
+
dir: string;
|
|
22
|
+
config: Record<string, unknown>;
|
|
23
|
+
features: Record<string, unknown>;
|
|
24
|
+
files: ContentModuleFile[];
|
|
25
|
+
enhance(key: string, data: unknown): void;
|
|
26
|
+
getEnhancement<T = unknown>(key: string): T | undefined;
|
|
27
|
+
_enhancements: Map<string, unknown>;
|
|
24
28
|
}
|
|
25
29
|
/**
|
|
26
|
-
*
|
|
30
|
+
* File within a content module.
|
|
31
|
+
* Shape matches what the build pipeline creates at build/index.ts.
|
|
27
32
|
*/
|
|
28
|
-
export
|
|
33
|
+
export interface ContentModuleFile {
|
|
34
|
+
id: string;
|
|
35
|
+
slug: string;
|
|
36
|
+
filePath: string;
|
|
37
|
+
urlPath: string;
|
|
38
|
+
directory: string;
|
|
39
|
+
processed: {
|
|
40
|
+
frontmatter: Record<string, unknown>;
|
|
41
|
+
[key: string]: unknown;
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
/** Registry data shape: module ID → array of content items */
|
|
45
|
+
export type ContentRegistryData = Record<string, ContentItem[]>;
|
package/dist/content/registry.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export
|
|
1
|
+
export{};
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Content source abstraction for the content registry.
|
|
3
|
+
*
|
|
4
|
+
* A ContentSource represents any place content can come from —
|
|
5
|
+
* local filesystem, a remote CMS, an API, etc.
|
|
6
|
+
*/
|
|
7
|
+
/**
|
|
8
|
+
* A single content item with normalized metadata.
|
|
9
|
+
* Produced by ContentSource.scan() and available to all pages via the registry.
|
|
10
|
+
*/
|
|
11
|
+
export interface ContentItem {
|
|
12
|
+
id: string;
|
|
13
|
+
moduleId: string;
|
|
14
|
+
metadata: {
|
|
15
|
+
title?: string;
|
|
16
|
+
description?: string;
|
|
17
|
+
date?: string;
|
|
18
|
+
author?: string;
|
|
19
|
+
excerpt?: string;
|
|
20
|
+
[key: string]: unknown;
|
|
21
|
+
};
|
|
22
|
+
urlPath: string;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Adapter interface for content sources.
|
|
26
|
+
*
|
|
27
|
+
* - scan() is always called first — returns lightweight metadata for all items.
|
|
28
|
+
* - read() is called lazily when a page needs full content for a specific item.
|
|
29
|
+
*/
|
|
30
|
+
export interface ContentSource {
|
|
31
|
+
/** Unique identifier for this source (e.g., 'filesystem', 'strapi') */
|
|
32
|
+
readonly id: string;
|
|
33
|
+
/** List all content items with metadata. Called once during build/init. */
|
|
34
|
+
scan(): Promise<ContentItem[]>;
|
|
35
|
+
/** Load full content for a single item. Called on demand. */
|
|
36
|
+
read(id: string): Promise<ContentItem | null>;
|
|
37
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export{};
|
package/dist/image/tag.d.ts
CHANGED
|
@@ -9,6 +9,7 @@ export interface ResolveImageTagOptions {
|
|
|
9
9
|
placeholder?: 'blur' | 'none';
|
|
10
10
|
quality?: number;
|
|
11
11
|
appRoot?: string;
|
|
12
|
+
base?: string;
|
|
12
13
|
}
|
|
13
14
|
export interface ResolvedImageTagData {
|
|
14
15
|
src: string;
|
|
@@ -19,5 +20,5 @@ export interface ResolvedImageTagData {
|
|
|
19
20
|
blurDataURL?: string;
|
|
20
21
|
}
|
|
21
22
|
export declare function resolveImageTag(options: ResolveImageTagOptions): Promise<ResolvedImageTagData>;
|
|
22
|
-
export declare function resolveImageTagsInHtml(html: string, options?: Pick<ResolveImageTagOptions, 'appRoot'>): Promise<string>;
|
|
23
|
+
export declare function resolveImageTagsInHtml(html: string, options?: Pick<ResolveImageTagOptions, 'appRoot' | 'base'>): Promise<string>;
|
|
23
24
|
export {};
|
package/dist/image/tag.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import t from"node:fs/promises";import e from"node:path";import{createHash as i}from"node:crypto";import{resolveAppRoot as r}from"../config/app-root.js";import{generateBlurPlaceholder as n,getImageDimensions as s,getImageFormat as o}from"./index.js";import{transformImage as a}from"./transform.js";const u=new Set(["jpeg","png","webp","avif"]),c=[320,480,640,768,960,1280,1536,1920],l=new Map;export async function resolveImageTag(t){const{src:u,width:g,height:m,layout:w="responsive",sizes:b,srcset:v,placeholder:y="none",quality:j
|
|
1
|
+
import t from"node:fs/promises";import e from"node:path";import{createHash as i}from"node:crypto";import{resolveAppRoot as r}from"../config/app-root.js";import{generateBlurPlaceholder as n,getImageDimensions as s,getImageFormat as o}from"./index.js";import{transformImage as a}from"./transform.js";const u=new Set(["jpeg","png","webp","avif"]),c=[320,480,640,768,960,1280,1536,1920],l=new Map;export async function resolveImageTag(t){const{src:u,width:g,height:m,layout:w="responsive",sizes:b,srcset:v,placeholder:y="none",quality:$,appRoot:j=r(),base:x="/"}=t,P=await async function(t,i,r){if(!t||t.startsWith("data:image/"))return null;try{const e=new URL(t);if("http:"===e.protocol||"https:"===e.protocol)return null}catch{}const n=function(t,e){const i=S(e);return i?t===i?"/":t.startsWith(i+"/")?t.slice(i.length):t:t}(t.split(/[?#]/,1)[0],r),s=e.join(i,"public");if(n.startsWith("/")){const t=n.replace(/^\/+/,""),i=e.join(s,t);if(await h(i))return{sourcePath:i,publicPath:t}}if(e.isAbsolute(n)&&await h(n))return{sourcePath:n,publicPath:e.basename(n)};const o=e.resolve(n);return await h(o)?{sourcePath:o,publicPath:e.basename(o)}:null}(u,j,x);if(!P)return{src:u,width:g,height:m,sizes:b??f(w,g),srcset:v};const W=await s(P.sourcePath),{width:z,height:R}=function(t,e,i,r){return i&&r?{width:i,height:r}:i?{width:i,height:Math.round(e/t*i)}:r?{width:Math.round(t/e*r),height:r}:{width:t,height:e}}(W.width,W.height,g,m),N=o(P.sourcePath),V={src:u,width:z,height:R,sizes:b??f(w,z),srcset:v};if("blur"===y&&d(N)&&(V.blurDataURL=await function(t){let e=l.get(t);return e||(e=n(t),l.set(t,e)),e}(P.sourcePath)),v||!d(N))return V;const k=function(t,e,i){const r=new Set;if("fixed"===t){const t=i??e;r.add(Math.min(t,e)),2*t<=e?r.add(2*t):r.add(e)}else{for(const t of c)t<e&&r.add(t);i&&r.add(Math.min(i,e)),r.add(e)}return[...r].filter(t=>Number.isFinite(t)&&t>0).sort((t,e)=>t-e)}(w,W.width,z);if(0===k.length)return V;const q=e.join(j,"public","_markopress","image",function(t){const r=e.dirname(t),n=i("sha1").update(t).digest("hex").slice(0,8);return e.join("."===r?"":r,n)}(P.publicPath)),D=function(t){return"jpeg"===t?"jpg":t}(N),L=[];for(const t of k)L.push(await a({src:P.sourcePath,width:t,quality:$,format:D,fit:"inside",outDir:q}));return V.src=p(j,L[L.length-1].src,x),V.srcset=L.map(t=>`${p(j,t.src,x)} ${t.width}w`).join(", "),V}export async function resolveImageTagsInHtml(t,e={}){const i=[...t.matchAll(/<image(?=[\s/>])[\s\S]*?(?:\/>|>)/g)];if(0===i.length)return t;let r="",n=0;for(const s of i){const i=s[0],o=s.index??0;r+=t.slice(n,o),r+=await g(i,e),n=o+i.length}return r+=t.slice(n),r}async function h(e){try{return(await t.stat(e)).isFile()}catch{return!1}}function f(t,e){return"fixed"===t&&e?e+"px":"fluid"===t?"100vw":"responsive"===t&&e?`(max-width: ${e}px) 100vw, ${e}px`:void 0}function d(t){return null!==t&&u.has(t)}function p(t,i,r){const n=e.join(t,"public");return function(t,e){const i=S(e);return i?!t.startsWith("/")||t.startsWith("//")||t===i||t.startsWith(i+"/")?t:`${i}${t}`:t}("/"+e.relative(n,i).split(e.sep).join("/"),r)}async function g(t,e){const i=function(t){const e=t.trimEnd().endsWith("/>"),i=t.replace(/^<image\b/,"").replace(e?/\/>\s*$/:/>\s*$/,""),r=[];let n=0;for(;n<i.length;){for(;n<i.length&&/\s/.test(i[n]);)n++;if(n>=i.length||"/"===i[n])break;const t=n;for(;n<i.length&&!/[\s=/]/.test(i[n]);)n++;const e=i.slice(t,n);if(!e)break;for(;n<i.length&&/\s/.test(i[n]);)n++;let s;if("="===i[n]){for(n++;n<i.length&&/\s/.test(i[n]);)n++;const t=m(i,n);s=t.value,n=t.end}r.push({name:e,rawValue:s})}return{attributes:r,selfClosing:e}}(t);if(!function(t){return[["src",j],["width",x],["height",x],["layout",P],["sizes",j],["srcset",j],["placeholder",W],["quality",x]].every(([e,i])=>{const r=w(t,e);return void 0===r||i(r)})}(i.attributes))return t;const r=y(w(i.attributes,"src"));if(!r)return t;const n=await resolveImageTag({src:r,width:$(w(i.attributes,"width")),height:$(w(i.attributes,"height")),layout:b(w(i.attributes,"layout")),sizes:y(w(i.attributes,"sizes")),srcset:y(w(i.attributes,"srcset")),placeholder:v(w(i.attributes,"placeholder")),quality:$(w(i.attributes,"quality")),appRoot:e.appRoot,base:e.base}),s=i.attributes.map(t=>({...t}));R(s,"src",N(n.src)),void 0!==n.width&&R(s,"width",n.width+""),void 0!==n.height&&R(s,"height",n.height+""),n.sizes&&R(s,"sizes",N(n.sizes)),n.srcset&&R(s,"srcset",N(n.srcset)),n.blurDataURL&&R(s,"blurDataURL",N(n.blurDataURL));const o=s.map(t=>function(t){return t.name?void 0===t.rawValue?t.name:`${t.name}=${t.rawValue}`:""}(t)).filter(Boolean).join(" ");return o?`<image ${o}${i.selfClosing?" />":">"}`:"<image"+(i.selfClosing?" />":">")}function m(t,e){const i=t[e];if('"'===i||"'"===i){let r=e+1;for(;r<t.length;)if("\\"!==t[r]){if(t[r]===i){r++;break}r++}else r+=2;return{value:t.slice(e,r),end:r}}if("{"===i){let i=0,r=null,n=e;for(;n<t.length;){const e=t[n];if(r){if("\\"===e){n+=2;continue}e===r&&(r=null),n++}else if('"'!==e&&"'"!==e&&"`"!==e){if("{"===e)i++;else if("}"===e&&(i--,0===i)){n++;break}n++}else r=e,n++}return{value:t.slice(e,n),end:n}}let r=e;for(;r<t.length&&!/\s/.test(t[r]);)r++;return{value:t.slice(e,r),end:r}}function w(t,e){return t.find(t=>t.name===e)?.rawValue}function b(t){const e=y(t);if("fixed"===e||"fluid"===e||"responsive"===e)return e}function v(t){const e=y(t);if("blur"===e||"none"===e)return e}function y(t){if(!t)return;const e=t.trim(),i=z(e);if(void 0!==i)return i;const r=e.match(/^\{\s*([\s\S]+)\s*\}$/);return r?z(r[1].trim()):void 0}function $(t){if(!t)return;const e=t.trim(),i=e.match(/^\{\s*([-+]?\d+(?:\.\d+)?)\s*\}$|^([-+]?\d+(?:\.\d+)?)$/),r=i?.[1]??i?.[2];if(!r){const t=y(e);if(!t||""===t.trim())return;const i=Number(t);return Number.isFinite(i)?i:void 0}const n=Number(r);return Number.isFinite(n)?n:void 0}function j(t){return void 0!==y(t)}function x(t){return void 0!==$(t)}function P(t){return void 0!==b(t)}function W(t){return void 0!==v(t)}function z(t){if(t.startsWith('"')&&t.endsWith('"'))try{return JSON.parse(t)}catch{return t.slice(1,-1)}if(t.startsWith("'")&&t.endsWith("'"))return t.slice(1,-1).replace(/\\\\/g,"\\").replace(/\\'/g,"'").replace(/\\"/g,'"')}function R(t,e,i){const r=t.find(t=>t.name===e);r?r.rawValue=i:t.push({name:e,rawValue:i})}function N(t){return JSON.stringify(t)}function S(t){return t&&"/"!==t?t.replace(/\/$/,""):""}
|
package/dist/markdown/loader.js
CHANGED
|
@@ -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
|
|
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 o}from"shiki";import{setupContainers as n,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";import{resolveImageTagsInHtml as d}from"../image/tag.js";let f=null;const h=new Set,y=["javascript","typescript","js","ts","bash","markdown","md"],b={js:"javascript",ts:"typescript",py:"python",rs:"rust",sh:"bash",shell:"bash",yml:"yaml",cs:"csharp",cpp:"c++"};function w(e){return b[e]||e}async function k(){return f||(f=await o({themes:["github-light","github-dark"],langs:Array.from(y)}),y.forEach(e=>h.add(w(e)))),f}export async function preloadLanguages(e){f||await k();const t=[];for(const r of e){const e=w(r);h.has(e)||t.push((async()=>{try{const{bundledLanguages:t}=await import("shiki/langs");e in t&&(await f.loadLanguage(t[e]),h.add(e))}catch{}})())}await Promise.all(t)}export async function getMarkdownIt(e={},o={}){const l=await k(),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:_,permalink:r.permalink.linkInsideHeader({symbol:"#",placement:"before"})}),f.use(a),f.use(s.full||s.bare),n(f),i(f),e.markoTags?.enabled&&f.use(p,{tagsDir:e.markoTags?.tagsDir||"tags/",onTagDetected:(e,t)=>{g.addDetectedTag(e,o.filePath||"unknown",t)}}),f.use(m),e.base&&f.use(u,e.base),f}export async function parseMarkdown(t,r={},a={},s){const{data:o,content:n,excerpt:i}=e(t,{excerpt:!0,excerpt_separator:"\x3c!-- more --\x3e"}),c=await l(n,{root:a.rootDir??process.cwd(),currentFile:a.filePath??""}),p=s||await async function(e,t){return getMarkdownIt(e,t)}(r,a),g=await d(p.render(c,a),{base:r.base??void 0}),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=v(r),o=_(r);t.push({level:e,title:a,slug:o})}return t}(c):[];return{frontmatter:o,content:c,html:g,excerpt:i,headers:$(u)}}function v(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 _(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 +1 @@
|
|
|
1
|
-
import e from"gray-matter";import r from"markdown-it";import{getMarkdownIt as t}from"./loader.js";import{resolveImageTagsInHtml as l}from"../image/tag.js";let n,a=null;export async function renderMarkdown(r,g){if(!a){const e={...g,markoTags:{enabled:!0,...g?.markoTags}};a=await t(e),n=e}const{data:s,content:i,excerpt:u}=e(r,{excerpt:!0,excerpt_separator:"\x3c!-- more --\x3e"});return{frontmatter:s,content:i,html:await l(a.render(i)),excerpt:u,headers:o(function(e){const r=[],t=e.replace(/```[\s\S]*?```/g,"").replace(/~~~[\s\S]*?~~~/g,"").replace(/^(\t| {4}).+$/gm,""),l=/^(#{1,6})\s+(.+)$/gm;let n;for(;null!==(n=l.exec(t));){const e=n[1].length,t=n[2].trim(),l=c(t),a=p(t);r.push({level:e,title:l,slug:a})}return r}(i))}}export function resetRendererCache(){a=null,n=void 0}export function getRendererInstance(){return a}function c(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 o(e){const r=[],t=[];for(const l of e){const e={level:l.level,title:l.title,slug:l.slug,children:[]};for(;t.length>0&&t[t.length-1].level>=l.level;)t.pop();0===t.length?r.push(e):t[t.length-1].children.push(e),t.push(e)}return r}function p(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,"-")}
|
|
1
|
+
import e from"gray-matter";import r from"markdown-it";import{getMarkdownIt as t}from"./loader.js";import{resolveImageTagsInHtml as l}from"../image/tag.js";let n,a=null;export async function renderMarkdown(r,g){if(!a){const e={...g,markoTags:{enabled:!0,...g?.markoTags}};a=await t(e),n=e}const{data:s,content:i,excerpt:u}=e(r,{excerpt:!0,excerpt_separator:"\x3c!-- more --\x3e"});return{frontmatter:s,content:i,html:await l(a.render(i),{base:g?.base??void 0}),excerpt:u,headers:o(function(e){const r=[],t=e.replace(/```[\s\S]*?```/g,"").replace(/~~~[\s\S]*?~~~/g,"").replace(/^(\t| {4}).+$/gm,""),l=/^(#{1,6})\s+(.+)$/gm;let n;for(;null!==(n=l.exec(t));){const e=n[1].length,t=n[2].trim(),l=c(t),a=p(t);r.push({level:e,title:l,slug:a})}return r}(i))}}export function resetRendererCache(){a=null,n=void 0}export function getRendererInstance(){return a}function c(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 o(e){const r=[],t=[];for(const l of e){const e={level:l.level,title:l.title,slug:l.slug,children:[]};for(;t.length>0&&t[t.length-1].level>=l.level;)t.pop();0===t.length?r.push(e):t[t.length-1].children.push(e),t.push(e)}return r}function p(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,"-")}
|
package/dist/plugin/manager.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import t from"markdown-it";import{AllContentImpl as n,ContentActionsImpl as e}from"./context.js";import{wrapLegacyPlugin as o}from"./compat.js";export class PluginManager{plugins=[];config;pluginLoadOrder=[];loadResults=[];allContent=new n;contentActions=new e;constructor(t){this.config=t}async loadPlugins(t){const n=await this.resolvePluginDependencies(t);for(const t of n){const n=await this.loadPlugin(t);if(n){const t=o(n.plugin);this.plugins.push(t),this.loadResults.push(n),this.pluginLoadOrder.push(t.name)}}console.log(`✓ Loaded ${this.plugins.length} plugins: ${this.pluginLoadOrder.join(", ")}`)}async resolvePluginDependencies(t){const n=new Set,e=new Set,o=[],i=new Map;for(const n of t){const t=this.getPluginName(n);i.set(t,n)}const s=async t=>{if(n.has(t))return;if(e.has(t))throw Error("Circular dependency detected among plugins: "+t);e.add(t);const a=i.get(t);if(!a)throw Error("Plugin not found: "+t);const r=await this.getPluginDependencies(a);for(const t of r)i.has(t)&&await s(t);e.delete(t),n.add(t),o.push(a)};for(const t of i.keys())await s(t);return o}getPluginName(t){return"string"==typeof t?t:Array.isArray(t)?t[0]:t.name}async getPluginDependencies(t){try{const n=await this.loadPluginModule(t);if(n&&n.dependencies)return n.dependencies}catch{}return[]}resolvePluginPath(t){return["sidenav","toc","blog-index","seo","head-inject"].includes(t)?`../plugins/${t}/index.js`:t}async loadPluginModule(t){try{if("string"==typeof t)return(await import(this.resolvePluginPath(t))).default;if(Array.isArray(t)){const[n]=t;return(await import(this.resolvePluginPath(n))).default}return t}catch{return null}}async loadPlugin(t){const n=this.getPluginName(t);try{let e;if("string"==typeof t){const n=await import(this.resolvePluginPath(t));e="function"==typeof n.default?await n.default():n.default}else if(Array.isArray(t)){const[n,o]=t,i=await import(this.resolvePluginPath(n));e="function"==typeof i.default?await i.default(o):i.default}else e=t;if(!e||!e.name)throw Error(`Invalid plugin: ${n} - must have a 'name' property`);if(e.config){const t={...this.config};try{this.config=await e.config(this.config)}catch(n){console.error(`Plugin ${e.name} config hook failed, using original config:`,n),this.config=t}}return{plugin:e,config:t}}catch(e){const o=e instanceof Error?e.message:e+"";return console.error(`Failed to load plugin ${n}: ${o}`),{plugin:{name:n},config:t,error:e instanceof Error?e:Error(o)}}}getPlugins(){return this.plugins}getLoadResults(){return this.loadResults}async execMarkdownHooks(t){for(const n of this.plugins)if(n.extendMarkdown)try{await n.extendMarkdown(t)}catch(t){console.error(`Plugin ${n.name} extendMarkdown hook failed:`,t)}}async execExtendRoutesHooks(t){let n=t;for(const t of this.plugins)if(t.extendRoutes)try{n=await t.extendRoutes(n)||n}catch(n){console.error(`Plugin ${t.name} extendRoutes hook failed:`,n)}return n}async execLoadContentHooks(){for(const t of this.plugins)if(t.loadContent)try{const n=await t.loadContent();this.allContent.addPluginContent(t.name,n)}catch(n){console.error(`Plugin ${t.name} loadContent hook failed:`,n)}}async execEnhanceModulesHooks(t){for(const n of this.plugins)if(n.enhanceModules)try{let e=t;n.modules&&n.modules.length>0&&(e=t.filter(t=>n.modules.includes(t.id))),await n.enhanceModules(e)}catch(t){console.error(`Plugin ${n.name} enhanceModules hook failed:`,t)}}async execContentLoadedHooks(t){for(const t of this.plugins)if(t.contentLoaded)try{const n=this.allContent.getContent(t.name)[0]||{};await t.contentLoaded({content:n,allContent:this.allContent,actions:this.contentActions})}catch(n){console.error(`Plugin ${t.name} contentLoaded hook failed:`,n)}}async execAllContentLoadedHooks(t){for(const n of this.plugins)if(n.allContentLoaded)try{await n.allContentLoaded({allContent:this.allContent,routes:t,actions:this.contentActions})}catch(t){console.error(`Plugin ${n.name} allContentLoaded hook failed:`,t)}}async execPostBuildHooks(t,n,e,o){for(const i of this.plugins)if(i.postBuild)try{await i.postBuild({config:t,outDir:n,routes:e,assets:o,allContent:this.allContent})}catch(t){console.error(`Plugin ${i.name} postBuild hook failed:`,t)}}getPluginRoutes(){return this.contentActions.getAllRoutes()}getPluginData(){return this.contentActions.getData()}getConfig(){return this.config}clear(){this.allContent=new n,this.contentActions=new e}createPluginContext(){return{config:this.config,utils:{log:t=>console.log("[markopress] "+t),warn:t=>console.warn("[markopress] "+t),error:t=>console.error("[markopress] "+t)}}}createBuildContext(t,n){return{...this.createPluginContext(),content:t,routes:n}}}
|
|
1
|
+
import t from"markdown-it";import{AllContentImpl as n,ContentActionsImpl as e}from"./context.js";import{wrapLegacyPlugin as o}from"./compat.js";export class PluginManager{plugins=[];config;pluginLoadOrder=[];loadResults=[];allContent=new n;contentActions=new e;constructor(t){this.config=t}async loadPlugins(t){const n=await this.resolvePluginDependencies(t);for(const t of n){const n=await this.loadPlugin(t);if(n){const t=o(n.plugin);this.plugins.push(t),this.loadResults.push(n),this.pluginLoadOrder.push(t.name)}}console.log(`✓ Loaded ${this.plugins.length} plugins: ${this.pluginLoadOrder.join(", ")}`)}async resolvePluginDependencies(t){const n=new Set,e=new Set,o=[],i=new Map;for(const n of t){const t=this.getPluginName(n);i.set(t,n)}const s=async t=>{if(n.has(t))return;if(e.has(t))throw Error("Circular dependency detected among plugins: "+t);e.add(t);const a=i.get(t);if(!a)throw Error("Plugin not found: "+t);const r=await this.getPluginDependencies(a);for(const t of r)i.has(t)&&await s(t);e.delete(t),n.add(t),o.push(a)};for(const t of i.keys())await s(t);return o}getPluginName(t){return"string"==typeof t?t:Array.isArray(t)?t[0]:t.name}async getPluginDependencies(t){try{const n=await this.loadPluginModule(t);if(n&&n.dependencies)return n.dependencies}catch{}return[]}resolvePluginPath(t){return["sidenav","toc","blog-index","seo","head-inject","content-registry"].includes(t)?`../plugins/${t}/index.js`:t}async loadPluginModule(t){try{if("string"==typeof t)return(await import(this.resolvePluginPath(t))).default;if(Array.isArray(t)){const[n]=t;return(await import(this.resolvePluginPath(n))).default}return t}catch{return null}}async loadPlugin(t){const n=this.getPluginName(t);try{let e;if("string"==typeof t){const n=await import(this.resolvePluginPath(t));e="function"==typeof n.default?await n.default():n.default}else if(Array.isArray(t)){const[n,o]=t,i=await import(this.resolvePluginPath(n));e="function"==typeof i.default?await i.default(o):i.default}else e=t;if(!e||!e.name)throw Error(`Invalid plugin: ${n} - must have a 'name' property`);if(e.config){const t={...this.config};try{this.config=await e.config(this.config)}catch(n){console.error(`Plugin ${e.name} config hook failed, using original config:`,n),this.config=t}}return{plugin:e,config:t}}catch(e){const o=e instanceof Error?e.message:e+"";return console.error(`Failed to load plugin ${n}: ${o}`),{plugin:{name:n},config:t,error:e instanceof Error?e:Error(o)}}}getPlugins(){return this.plugins}getLoadResults(){return this.loadResults}async execMarkdownHooks(t){for(const n of this.plugins)if(n.extendMarkdown)try{await n.extendMarkdown(t)}catch(t){console.error(`Plugin ${n.name} extendMarkdown hook failed:`,t)}}async execExtendRoutesHooks(t){let n=t;for(const t of this.plugins)if(t.extendRoutes)try{n=await t.extendRoutes(n)||n}catch(n){console.error(`Plugin ${t.name} extendRoutes hook failed:`,n)}return n}async execLoadContentHooks(){for(const t of this.plugins)if(t.loadContent)try{const n=await t.loadContent();this.allContent.addPluginContent(t.name,n)}catch(n){console.error(`Plugin ${t.name} loadContent hook failed:`,n)}}async execEnhanceModulesHooks(t){for(const n of this.plugins)if(n.enhanceModules)try{let e=t;n.modules&&n.modules.length>0&&(e=t.filter(t=>n.modules.includes(t.id))),await n.enhanceModules(e)}catch(t){console.error(`Plugin ${n.name} enhanceModules hook failed:`,t)}}async execContentLoadedHooks(t){for(const t of this.plugins)if(t.contentLoaded)try{const n=this.allContent.getContent(t.name)[0]||{};await t.contentLoaded({content:n,allContent:this.allContent,actions:this.contentActions})}catch(n){console.error(`Plugin ${t.name} contentLoaded hook failed:`,n)}}async execAllContentLoadedHooks(t){for(const n of this.plugins)if(n.allContentLoaded)try{await n.allContentLoaded({allContent:this.allContent,routes:t,actions:this.contentActions})}catch(t){console.error(`Plugin ${n.name} allContentLoaded hook failed:`,t)}}async execPostBuildHooks(t,n,e,o){for(const i of this.plugins)if(i.postBuild)try{await i.postBuild({config:t,outDir:n,routes:e,assets:o,allContent:this.allContent})}catch(t){console.error(`Plugin ${i.name} postBuild hook failed:`,t)}}getPluginRoutes(){return this.contentActions.getAllRoutes()}getPluginData(){return this.contentActions.getData()}getConfig(){return this.config}clear(){this.allContent=new n,this.contentActions=new e}createPluginContext(){return{config:this.config,utils:{log:t=>console.log("[markopress] "+t),warn:t=>console.warn("[markopress] "+t),error:t=>console.error("[markopress] "+t)}}}createBuildContext(t,n){return{...this.createPluginContext(),content:t,routes:n}}}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Content Registry Plugin for MarkoPress
|
|
3
|
+
*
|
|
4
|
+
* Enables cross-section content access — e.g., showing blog posts on the homepage.
|
|
5
|
+
*
|
|
6
|
+
* The build pipeline constructs registry data (Record<string, ContentItem[]>) from
|
|
7
|
+
* scanned content modules and writes it to .generated/content-registry.{js,json}.
|
|
8
|
+
* Handler templates load it and expose via $global.registry.
|
|
9
|
+
*
|
|
10
|
+
* Usage in templates:
|
|
11
|
+
* <for|post| of=$global.registry.blog>
|
|
12
|
+
* <if=post.metadata.date>
|
|
13
|
+
* <a href=post.urlPath>${post.metadata.title}</a>
|
|
14
|
+
* </if>
|
|
15
|
+
* </for>
|
|
16
|
+
*
|
|
17
|
+
* To add a remote CMS source, implement the ContentSource interface and
|
|
18
|
+
* contribute items to the registry via the enhanceModules hook.
|
|
19
|
+
*/
|
|
20
|
+
import type { MarkoPressPlugin } from '../../plugin/types.js';
|
|
21
|
+
export default function contentRegistryPlugin(): MarkoPressPlugin;
|
|
22
|
+
export type { ContentItem, ContentSource } from '../../content/source.js';
|
|
23
|
+
export type { ContentRegistryData } from '../../content/registry.js';
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export default function t(){return{name:"content-registry"}}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "markopress",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.19",
|
|
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",
|
|
@@ -8,6 +8,7 @@ const IS_BUILD = {{IS_BUILD}};
|
|
|
8
8
|
let moduleEnhancements = {};
|
|
9
9
|
let allMetadata = {};
|
|
10
10
|
let contentModules = {};
|
|
11
|
+
let contentRegistry = {};
|
|
11
12
|
|
|
12
13
|
// {{IF_BUILD_START}}
|
|
13
14
|
if (IS_BUILD) {
|
|
@@ -27,20 +28,34 @@ if (IS_BUILD) {
|
|
|
27
28
|
} catch {
|
|
28
29
|
moduleEnhancements = {};
|
|
29
30
|
}
|
|
31
|
+
try {
|
|
32
|
+
contentRegistry = (await import('/src/.generated/content-registry.js')).default;
|
|
33
|
+
} catch {
|
|
34
|
+
contentRegistry = {};
|
|
35
|
+
}
|
|
30
36
|
}
|
|
31
37
|
// {{IF_BUILD_END}}
|
|
32
38
|
|
|
33
39
|
// {{IF_DEV_START}}
|
|
34
40
|
if (!IS_BUILD) {
|
|
35
41
|
// Dev mode: load module enhancements for sidebar, etc.
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
42
|
+
// Resolve .generated/ by walking up to routes/ directory from handler location
|
|
43
|
+
const { promises: _fs } = await import('node:fs');
|
|
44
|
+
const { default: _path } = await import('node:path');
|
|
45
|
+
const { fileURLToPath: _fileURLToPath } = await import('node:url');
|
|
46
|
+
const _handlerDir = _path.dirname(_fileURLToPath(import.meta.url));
|
|
47
|
+
// Walk up to find the routes/ directory (handler can be at routes/$$slug/ or routes/module/$$slug/)
|
|
48
|
+
let _dir = _handlerDir;
|
|
49
|
+
while (_path.basename(_dir) !== 'routes' && _dir !== _path.dirname(_dir)) {
|
|
50
|
+
_dir = _path.dirname(_dir);
|
|
43
51
|
}
|
|
52
|
+
const _generatedDir = _path.join(_dir, '..', '.generated');
|
|
53
|
+
try {
|
|
54
|
+
moduleEnhancements = JSON.parse(await _fs.readFile(_path.join(_generatedDir, 'module-enhancements.json'), 'utf-8'));
|
|
55
|
+
} catch {}
|
|
56
|
+
try {
|
|
57
|
+
contentRegistry = JSON.parse(await _fs.readFile(_path.join(_generatedDir, 'content-registry.json'), 'utf-8'));
|
|
58
|
+
} catch {}
|
|
44
59
|
}
|
|
45
60
|
// {{IF_DEV_END}}
|
|
46
61
|
|
|
@@ -144,6 +159,9 @@ export async function GET(context, next) {
|
|
|
144
159
|
const enhancements = moduleEnhancements[contentType] || {};
|
|
145
160
|
context.sidebar = enhancements.sidebar || null;
|
|
146
161
|
|
|
162
|
+
// Content registry: cross-section data (e.g., blog posts on homepage)
|
|
163
|
+
context.registry = contentRegistry;
|
|
164
|
+
|
|
147
165
|
// TOC (table of contents)
|
|
148
166
|
if (headers && headers.length > 0) {
|
|
149
167
|
context.toc = headers;
|
|
@@ -23,6 +23,21 @@
|
|
|
23
23
|
<${$global.contentComponent || {}}>
|
|
24
24
|
<div>No content</div>
|
|
25
25
|
</${$global.contentComponent || {}}>
|
|
26
|
+
<if=$global.registry?.blog?.length>
|
|
27
|
+
<section class="recent-posts">
|
|
28
|
+
<h2>Recent Posts</h2>
|
|
29
|
+
<ul>
|
|
30
|
+
<for|post| of=$global.registry.blog>
|
|
31
|
+
<if=post.metadata.date>
|
|
32
|
+
<li>
|
|
33
|
+
<a href=post.urlPath>${post.metadata.title || post.urlPath}</a>
|
|
34
|
+
<small>${new Date(post.metadata.date).toLocaleDateString()}</small>
|
|
35
|
+
</li>
|
|
36
|
+
</if>
|
|
37
|
+
</for>
|
|
38
|
+
</ul>
|
|
39
|
+
</section>
|
|
40
|
+
</if>
|
|
26
41
|
</div>
|
|
27
42
|
<if=$global.toc>
|
|
28
43
|
<toc headers=$global.toc/>
|
|
@@ -66,4 +81,40 @@
|
|
|
66
81
|
margin-right: 0.5rem;
|
|
67
82
|
font-size: 0.75rem;
|
|
68
83
|
}
|
|
84
|
+
|
|
85
|
+
.recent-posts {
|
|
86
|
+
margin-top: 2rem;
|
|
87
|
+
padding-top: 1.5rem;
|
|
88
|
+
border-top: 1px solid #e5e7eb;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
.recent-posts h2 {
|
|
92
|
+
margin-bottom: 0.75rem;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
.recent-posts ul {
|
|
96
|
+
list-style: none;
|
|
97
|
+
padding: 0;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
.recent-posts li {
|
|
101
|
+
padding: 0.5rem 0;
|
|
102
|
+
display: flex;
|
|
103
|
+
justify-content: space-between;
|
|
104
|
+
align-items: baseline;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
.recent-posts li a {
|
|
108
|
+
color: var(--color-primary-2, #3b82f6);
|
|
109
|
+
text-decoration: none;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
.recent-posts li a:hover {
|
|
113
|
+
text-decoration: underline;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
.recent-posts small {
|
|
117
|
+
color: #6b7280;
|
|
118
|
+
font-size: 0.8rem;
|
|
119
|
+
}
|
|
69
120
|
</style>
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/build/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAQH,OAAO,KAAK,EAAE,eAAe,EAAe,MAAM,qBAAqB,CAAC;AACxE,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AAIzD,OAAO,EAAE,kBAAkB,EAAE,uBAAuB,EAAE,MAAM,2BAA2B,CAAC;AAgBxF,MAAM,MAAM,aAAa,GAAG,GAAG,CAAC;AAEhC,MAAM,WAAW,YAAY;IAC3B,iBAAiB,CAAC,EAAE,OAAO,CAAC;IAC5B,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB,IAAI,CAAC,EAAE,MAAM,CAAC;CACf;AAED,MAAM,WAAW,WAAW;IAC1B,OAAO,EAAE,OAAO,CAAC;IACjB,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,MAAM,EAAE,CAAC;CAClB;AAED;;GAEG;AACH,wBAAsB,KAAK,CAAC,OAAO,GAAE,YAAiB,GAAG,OAAO,CAAC,WAAW,CAAC,CA+W5E;AAyDD;;;GAGG;AACH,wBAAsB,cAAc,CAClC,QAAQ,EAAE,eAAe,EACzB,SAAS,EAAE,MAAM,EACjB,MAAM,EAAE,cAAc,EACtB,OAAO,EAAE,aAAa,EAAE,EACxB,KAAK,EAAE,OAAO,GACb,OAAO,CAAC,IAAI,CAAC,CAsDf;AAED;;;;;;;;;GASG;AACH,wBAAsB,sBAAsB,CAC1C,SAAS,EAAE,MAAM,EACjB,QAAQ,EAAE,eAAe,EACzB,KAAK,EAAE,OAAO,GACb,OAAO,CAAC,IAAI,CAAC,CA4Ff;AAiLD;;;;;;;;;;GAUG;AACH,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAsCpD;AAED;;GAEG;AACH,wBAAsB,kBAAkB,CACtC,OAAO,EAAE,MAAM,EACf,KAAK,EAAE,OAAO,GACb,OAAO,CAAC,IAAI,CAAC,CAuCf;AAED;;GAEG;AACH,wBAAsB,YAAY,CAChC,OAAO,EAAE,MAAM,EACf,MAAM,EAAE,cAAc,EACtB,KAAK,EAAE,OAAO,GACb,OAAO,CAAC,IAAI,CAAC,CAuFf;AAkBD,wBAAsB,mBAAmB,CACvC,OAAO,EAAE,MAAM,EACf,MAAM,EAAE,cAAc,EACtB,KAAK,EAAE,OAAO,GACb,OAAO,CAAC,IAAI,CAAC,CA6Ef;AAED;;;GAGG;AACH,wBAAsB,iBAAiB,CACrC,OAAO,EAAE,MAAM,EACf,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,cAAc,EACtB,KAAK,EAAE,OAAO,GACb,OAAO,CAAC,IAAI,CAAC,CAkDf;AAyYD;;;GAGG;AACH,wBAAsB,sBAAsB,CAC1C,QAAQ,EAAE,eAAe,EACzB,SAAS,EAAE,MAAM,EACjB,MAAM,EAAE,cAAc,EACtB,OAAO,EAAE,aAAa,EAAE,EACxB,KAAK,EAAE,OAAO,GACb,OAAO,CAAC,IAAI,CAAC,CAkEf;AAGD,OAAO,EAAE,kBAAkB,EAAE,uBAAuB,EAAE,CAAC;AACvD,OAAO,EAAE,qBAAqB,EAAE,MAAM,2BAA2B,CAAC"}
|