canofold 0.2.1 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +0,0 @@
1
- import{a as X,b as Y,d as Q,f as E}from"./chunk-ENPRUF6E.js";import{a as R,b as W,d as K,e as q,f as B,g as k,h as O}from"./chunk-4OALGQQB.js";import{a as H}from"./chunk-KUDMXVOM.js";import{a as V,b as z,c as j}from"./chunk-EAYVCA3Z.js";import{a as I,b as P,d as U,e as _,f as J,h as v}from"./chunk-JK7ZNBUA.js";import{a as u}from"./chunk-AYDF3IFZ.js";import{analyzeMarkdown as Dt}from"@canofold/markdown/server/analyze";import jt from"gray-matter";import{join as It,posix as Rt}from"path";import{z as m}from"zod";var tt=["ai","box","code","file","file-code","gauge","globe","layers","rocket","search","sparkles","terminal"],Pt=m.object({text:m.string().min(1),link:O,primary:m.boolean().optional(),icon:m.enum(tt).optional()}).strict(),bt=m.object({accent:m.string().optional(),tagline:m.string().optional(),image:O.optional(),imageAlt:m.string().optional(),actions:m.array(Pt).refine(t=>t.filter(e=>e.primary).length<=1,{message:"Home page hero actions can contain at most one primary action"}).optional()}).strict(),Et=m.object({icon:m.enum(tt).optional(),image:O.optional(),title:m.string().min(1),details:m.string().min(1)}).strict(),$t=m.string().trim().refine(t=>m.string().date().safeParse(t).success||m.string().datetime({offset:!0}).safeParse(t).success,"Expected an ISO 8601 date"),Z=m.preprocess(t=>t instanceof Date?t.toISOString():t,$t.transform(t=>new Date(t).toISOString())),et=m.object({title:m.string().optional(),seoTitle:m.string().trim().min(1).optional(),description:m.string().optional(),createdAt:Z.optional(),updatedAt:Z.optional(),order:m.number().finite().optional(),group:m.string().optional(),subgroup:m.string().optional(),collapsed:m.boolean().optional(),sidebar:m.boolean().optional(),layout:m.enum(["document","playground"]).optional(),status:m.enum(["draft","published"]).optional(),search:m.boolean().optional(),ai:m.boolean().optional(),tags:m.array(m.string()).optional(),owner:m.string().optional(),hero:bt.optional(),features:m.array(Et).optional()}).passthrough();function le(t){return Object.fromEntries(["title","description","createdAt","updatedAt","order","group","subgroup","tags","owner"].flatMap(o=>t[o]===void 0?[]:[[o,t[o]]]))}u(le,"publicFrontmatterFor");import{readdir as St,readFile as Ct,stat as vt}from"fs/promises";import{join as kt,relative as nt}from"path";async function ot(t,e,o){if(!Number.isFinite(e)||e<1)throw new Error("Concurrency must be a positive finite number");let r=new Array(t.length),n=0,i,l=Math.min(Math.floor(e),t.length);if(await Promise.all(Array.from({length:l},async()=>{for(;n<t.length&&i===void 0;){let c=n++;try{r[c]=await o(t[c],c)}catch(p){i??=p}}})),i)throw i;return r}u(ot,"mapConcurrent");var Ot=32;async function rt(t){async function e(n){let i=[],l=[n];for(;l.length>0;){let c=l.pop();if(!c)continue;let p=await St(c,{withFileTypes:!0});for(let a of p){let s=kt(c,a.name);if(a.isSymbolicLink())throw new Error(`Documentation content must not use symbolic links: ${nt(t,s)}`);a.isDirectory()?l.push(s):a.isFile()&&V(a.name)&&i.push(s)}}return i}u(e,"walk");let o=await e(t);return(await ot(o,Ot,async n=>{let[i,l]=await Promise.all([vt(n),Ct(n,"utf8")]);return{path:nt(t,n),raw:l,mtimeMs:i.mtimeMs}})).sort((n,i)=>n.path.localeCompare(i.path))}u(rt,"scanMarkdownFiles");function it(t){return t.split("-").filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}u(it,"humanize");function $(t){return j(R(t.relativePath,t.locale))}u($,"isLocaleHome");function Nt(t){return{type:"link",title:t.title||t.routePath,routePath:t.routePath}}u(Nt,"sidebarLink");function st(t){return R(t.relativePath,t.locale).split("/")}u(st,"pageSegments");function at(t){return st(t).slice(0,-1)}u(at,"pageDirectorySegments");function Tt(t){return j(st(t).at(-1)??"")}u(Tt,"isDirectoryIndex");function Ft(t){let e=new Map,o=new Map,r=new Map;for(let n of t)if(Tt(n)&&o.set(at(n).join("/"),n),n.group&&typeof n.frontmatter.group=="string"){let i=r.get(n.group);if(i&&i!==n.frontmatter.group)throw new Error(`Inconsistent group name for locale "${n.locale}" directory "${n.group}": "${i}" and "${n.frontmatter.group}"`);r.set(n.group,n.frontmatter.group)}for(let n of t){if($(n)||n.frontmatter.sidebar===!1)continue;let i=at(n),l=i[0]??"",c=o.get(l),p=l?typeof c?.frontmatter.group=="string"?c.frontmatter.group:c?.title||r.get(l)||it(l):"";if(typeof n.frontmatter.group=="string"&&n.frontmatter.group!==p)throw new Error(`Inconsistent group name for locale "${n.locale}" directory "${n.group}": "${p}" and "${n.frontmatter.group}"`);let a=e.get(l);if(!a)a={segment:l,title:p,items:[]},e.set(l,a);else if(a.title!==p)throw new Error(`Inconsistent group name for locale "${n.locale}" directory "${n.group}": "${a.title}" and "${p}"`);let s=a.items;for(let f=1;f<i.length;f+=1){let d=i[f];if(!d)continue;let g=i.slice(0,f+1).join("/"),h=o.get(g),w=f===1&&typeof n.frontmatter.subgroup=="string"?n.frontmatter.subgroup:void 0,y=(f===1&&typeof h?.frontmatter.subgroup=="string"?h.frontmatter.subgroup:void 0)??h?.title??w??it(d);if(w&&w!==y)throw new Error(`Inconsistent subgroup name for locale "${n.locale}" directory "${g}"`);let b=s.find(C=>C.type==="group"&&C.segment===d),x=b??{type:"group",segment:d,title:y,collapsed:h?.frontmatter.collapsed===!0,items:[]};b||s.push(x),s=x.items}s.push(Nt(n))}return[...e.values()]}u(Ft,"buildSidebar");function N(t){if(t.type==="link")return t;for(let e of t.items){let o=N(e);if(o)return o}}u(N,"firstSidebarLink");function At(t){return t.flatMap(e=>{let o=e.items[0]?N(e.items[0]):void 0;return e.title&&o?[{title:e.title,routePath:o.routePath}]:[]})}u(At,"buildAutomaticNav");function Gt(t,e){return!t.startsWith("/")||e.base==="/"?t:`${e.base}${t.replace(/^\//,"")}`}u(Gt,"versionedNavLink");function Mt(t,e){return t.map(o=>({title:o.text,routePath:Gt(o.link,e)}))}u(Mt,"buildConfiguredNav");function Lt(t,e){return t.map(o=>{if(!o.routePath.startsWith("/"))return o;let r=o.routePath.split("/").filter(Boolean),n=e.find(l=>l.segment&&r.at(-1)===l.segment&&r.length>0),i=n?.items[0]?N(n.items[0]):void 0;return i?{...o,routePath:i.routePath}:o})}u(Lt,"anchorConfiguredNavToSidebar");function Vt(t){let e=new Map;for(let o of t)for(let[r,n]of[["route",o.routePath],["output",o.outputPath],["markdown output",o.markdownOutputPath]]){let i=`${r}:${P(n)}`,l=e.get(i);if(l)throw new Error(`Duplicate ${r} target ${n} for ${l.sourceRelativePath} and ${o.sourceRelativePath}`);e.set(i,o)}}u(Vt,"assertUniquePageTargets");async function zt(t,e,o,r){let n=U(t,o.docsDir,`versions.items[${o.id}].docsDir`),i=await rt(n),l=[];for(let c of i){let p=c.path.split(/[\\/]/);if(p[0]==="public")continue;let a=p[0]&&e.i18n.locales.includes(p[0])?p[0]:void 0,s=a??e.i18n.defaultLocale,f=a?p.slice(1):p;if(f.length===0)continue;let d=f.join("/"),g=Rt.join(o.docsDir.replace(/\\/g,"/"),c.path.replace(/\\/g,"/")),h=r?await r.transformSource({source:c.raw,sourceRelativePath:g,relativePath:c.path.replace(/\\/g,"/"),kind:z(c.path)?"mdx":"markdown",version:o.id,locale:s}):c.raw,w=jt(h),y=et.parse(w.data),b=y.status??"published";if(b==="draft")continue;let x=Dt(w.content),C=typeof y.order=="number"&&Number.isFinite(y.order)?y.order:Number.MAX_SAFE_INTEGER,xt=c.path.replace(/\\/g,"/"),L={sourcePath:It(n,c.path),transformedSource:h,sourceRelativePath:g,relativePath:xt,version:o.id,versionBase:o.base,docsDir:o.docsDir,locale:s,routePath:K(s,e.i18n.defaultLocale,d,o.base),outputPath:q(s,e.i18n.defaultLocale,d,o.base),markdownOutputPath:B(s,e.i18n.defaultLocale,d,o.base),title:typeof y.title=="string"?y.title:x.headings[0]?.text??"",description:typeof y.description=="string"?y.description:"",order:C,group:f.length>1?f[0]??"":"",status:b,search:y.search!==!1,ai:y.ai!==!1,body:w.content,headings:x.headings,searchText:x.text,codeExamples:x.codeExamples,lastUpdated:y.updatedAt??new Date(c.mtimeMs).toISOString(),frontmatter:y};l.push(r?await r.extendPage(L):L)}return l}u(zt,"scanVersionPages");async function De(t,e,o){let r=[];for(let a of e.versions.items)for(let s of await zt(t,e,a,o))r.push(s);let n=new Map(e.versions.items.map((a,s)=>[a.id,s])),i=new Map(e.i18n.locales.map((a,s)=>[a,s]));r.sort((a,s)=>{let f=(n.get(a.version)??0)-(n.get(s.version)??0);if(f!==0)return f;let d=(i.get(a.locale)??0)-(i.get(s.locale)??0);if(d!==0)return d;let g=$(a),h=$(s);return g!==h?g?-1:1:a.order!==s.order?a.order-s.order:a.routePath.localeCompare(s.routePath)}),Vt(r);for(let a of e.versions.items)for(let s of e.i18n.locales)if(!r.some(f=>f.version===a.id&&f.locale===s&&$(f)))throw new Error(`Missing published home page for version "${a.id}" locale "${s}"`);for(let a of e.versions.items)for(let s of e.i18n.locales){let f=r.filter(d=>d.version===a.id&&d.locale===s&&!$(d));f.forEach((d,g)=>{let h=f[g-1],w=f[g+1];h&&(d.previous={title:h.title||h.routePath,routePath:h.routePath}),w&&(d.next={title:w.title||w.routePath,routePath:w.routePath})})}let l={},c={};for(let a of e.versions.items){let s={},f={};l[a.id]=s,c[a.id]=f;for(let d of e.i18n.locales){let g=Ft(r.filter(h=>h.version===a.id&&h.locale===d));s[d]=g,f[d]=e.navigation[d]?Lt(Mt(e.navigation[d],a),g):At(g)}}let p=new Set(r.map(a=>a.routePath));for(let a of Object.values(c))for(let s of Object.values(a))for(let f of s)if(f.routePath.startsWith("/")&&!p.has(f.routePath))throw new Error(`Navigation target is not a generated page: "${f.routePath}"`);return{pages:r,sidebar:l,nav:c,locales:e.i18n.locales,defaultLocale:e.i18n.defaultLocale,versions:e.versions.items.map(a=>({...a})),currentVersion:e.versions.current}}u(De,"buildContentGraph");import{mkdir as Ut,writeFile as ct}from"fs/promises";import{dirname as _t,join as Jt}from"path";var Ht={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"};function T(t){return t.replace(/[&<>"']/g,e=>Ht[e]??e)}u(T,"escapeHtml");function F(t){let e=t==="/"?"/":`${t.replace(/\/+$/,"")}/`;return W(e)}u(F,"normalizeRedirectRoute");function A(t,e){let o=new Set(e.pages.map(i=>F(i.routePath))),r=Object.entries(t.redirects).map(([i,l])=>[F(i),F(l)]),n=new Set(r.map(([i])=>i));for(let[i,l]of r){if(i==="/")throw new Error("Redirect source must not replace the site root");if(o.has(i))throw new Error(`Redirect source collides with a generated page: "${i}"`);if(n.has(l))throw new Error(`Redirect chains are not allowed: "${i}" points to redirect "${l}"`);if(!o.has(l))throw new Error(`Redirect target is not a published generated page: "${l}"`)}if(n.size!==r.length)throw new Error("Redirect sources must be unique after route normalization");return r}u(A,"resolveRedirects");async function Ve(t,e,o){let r=A(e,o);if(r.length===0)return;let n=_(t,e.outputDir);for(let[i,l]of r){let c=v(n,k(i),"redirect route"),p=Y(e,l),a=T(p),s=T(X(e,l)??p),f=JSON.stringify(p).replace(/</g,"\\u003c"),d=`<!doctype html><html><head><meta charset="utf-8"><meta name="robots" content="noindex"><link rel="canonical" href="${s}"><meta http-equiv="refresh" content="0;url=${a}"><script>location.replace(${f})</script></head><body><a href="${a}">Redirecting to ${a}</a></body></html>`;await Ut(_t(c),{recursive:!0}),await ct(c,d)}await ct(Jt(n,"redirects.json"),JSON.stringify(Object.fromEntries(r),null,2))}u(Ve,"writeRedirects");import{posix as ut}from"path";var Wt=new Set([".benchmark.json"]),Kt=["assets/canofold-markdown","assets/canofold-playground","assets/canofold-plugins","assets/fonts","pagefind","ai/content","extensions"];function lt(t){let e=new Map;for(let o of t){let r=P(o),n=Kt.find(l=>r===l||r.startsWith(`${l}/`));if(n)throw new Error(`Generated output uses reserved directory "${n}": "${o}"`);let i=e.get(r);if(i)throw new Error(`Generated outputs overlap: "${i}" and "${o}"`);e.set(r,o)}for(let[o,r]of e){let n=ut.dirname(o);for(;n!==".";){let i=e.get(n);if(i)throw new Error(`Generated outputs overlap: "${i}" and "${r}"`);n=ut.dirname(n)}}}u(lt,"assertGeneratedOutputPlan");function pt(t,e){let o=[".benchmark.json","404.html","assets/canofold.css","robots.txt","ai/pages.json","ai/manifest.json",...e.pages.flatMap(n=>[n.outputPath,n.markdownOutputPath])];if(t.search.enabled&&(o.push("assets/canofold-search.js"),Q(t.search.provider)==="compact"))for(let n of e.versions)for(let i of e.locales)o.push(n.id===e.currentVersion?`search/${i}.json`:`search/${n.id}/${i}.json`);t.siteUrl&&o.push("sitemap.xml"),t.ai.pageSummaries&&o.push("ai/summaries.json"),t.ai.codeExamples&&o.push("ai/code-examples.json"),t.ai.markdownIndex&&o.push("ai/index.md"),t.ai.llmsTxt&&o.push("llms.txt"),t.ai.llmsFullTxt&&o.push("llms-full.txt");let r=A(t,e);if(r.length){o.push("redirects.json");for(let[n]of r)o.push(k(n))}return{paths:o,redirects:r}}u(pt,"plannedOutputPaths");function qe(t,e){let{paths:o}=pt(t,e);return lt(o),new Set(o)}u(qe,"generatedOutputPaths");function Be(t,e){let{paths:o,redirects:r}=pt(t,e);return lt(o),new Set([...o.filter(n=>!Wt.has(n)).map(n=>`/${n.split("/").map(encodeURIComponent).join("/")}`),...r.map(([n])=>n)])}u(Be,"generatedPublicPaths");import{randomUUID as Bt}from"crypto";import{mkdir as mt,readFile as Xt,rm as Yt,writeFile as gt}from"fs/promises";import{dirname as Qt,join as ht,posix as wt,resolve as Zt}from"path";import{pathToFileURL as te}from"url";import{build as ee}from"esbuild";import{createHash as ft}from"crypto";function G(t,e){if(t===null||typeof t=="boolean"||typeof t=="string")return t;if(typeof t=="number"){if(!Number.isFinite(t))throw new TypeError("Fingerprint values must contain only finite numbers");return t}if(typeof t!="object")throw new TypeError("Fingerprint values must be JSON-serializable");if(e.has(t))throw new TypeError("Fingerprint values must not be circular");let o=Object.getPrototypeOf(t);if(!Array.isArray(t)&&o!==Object.prototype&&o!==null)throw new TypeError("Fingerprint values must be JSON-serializable plain objects");e.add(t);try{if(Array.isArray(t)){if(Object.keys(t).length!==t.length)throw new TypeError("Fingerprint values must not contain sparse arrays");return t.map(n=>G(n,e))}let r=Object.entries(t).sort(([n],[i])=>n.localeCompare(i)).map(([n,i])=>[n,G(i,e)]);return Object.fromEntries(r)}finally{e.delete(t)}}u(G,"canonicalValue");function qt(t){return JSON.stringify(G(t,new WeakSet))}u(qt,"stableJson");function S(t){return ft("sha256").update(qt(t)).digest("hex")}u(S,"fingerprint");function M(t){return ft("sha256").update(t).digest("hex")}u(M,"fingerprintBytes");var oe=new Set(["apiVersion","name","outputs","transformSource","extendPage","generate"]),ne=["pnpm-lock.yaml","package-lock.json","yarn.lock","bun.lock","bun.lockb"];function D(t){return t instanceof Error?t.message:String(t)}u(D,"errorMessage");function dt(t){return{sourceRelativePath:t.sourceRelativePath,relativePath:t.relativePath,version:t.version,locale:t.locale,routePath:t.routePath,title:t.title,description:t.description,status:t.status,search:t.search,ai:t.ai,body:t.body,searchText:t.searchText,frontmatter:structuredClone(t.frontmatter)}}u(dt,"extensionPage");function yt(t,e){if(!e||e.includes("\\")||e.startsWith("/")||e!==wt.normalize(e))throw new Error(`Extension "${t}" output must be a normalized relative POSIX path: "${e}"`);if(e.split("/").some(o=>o==="."||o===".."||!o))throw new Error(`Extension "${t}" output must not contain empty, . or .. segments: "${e}"`);return e}u(yt,"normalizeDeclaredOutput");function re(t,e){if(!t||typeof t!="object")throw new Error(`Extension ${e.resolve} must export an extension object or factory`);let o=t,r=Object.keys(o).find(n=>!oe.has(n));if(r)throw new Error(`Extension ${e.resolve} has unknown key "${r}"`);if(o.apiVersion!==1)throw new Error(`Extension ${e.resolve} uses unsupported apiVersion ${String(o.apiVersion)}; expected ${1}`);if(typeof o.name!="string"||!/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(o.name))throw new Error(`Extension ${e.resolve} name must be a lowercase portable slug`);for(let n of["transformSource","extendPage","generate"])if(o[n]!==void 0&&typeof o[n]!="function")throw new Error(`Extension "${o.name}" hook ${n} must be a function`);if(o.outputs!==void 0&&!Array.isArray(o.outputs))throw new Error(`Extension "${o.name}" outputs must be an array`);if(o.generate&&!o.outputs?.length)throw new Error(`Extension "${o.name}" with generate() must declare outputs`);if(!o.generate&&o.outputs?.length)throw new Error(`Extension "${o.name}" declares outputs without generate()`);return o}u(re,"assertDefinition");function ie(t,e){if(e===void 0)return{};if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Extension "${t}" extendPage() must return an object or undefined`);let o=new Set(["title","description","searchText","search","ai"]),r=Object.keys(e).find(i=>!o.has(i));if(r)throw new Error(`Extension "${t}" extendPage() returned unknown key "${r}"`);let n=e;for(let i of["title","description","searchText"])if(n[i]!==void 0&&typeof n[i]!="string")throw new Error(`Extension "${t}" extendPage() field ${i} must be a string`);for(let i of["search","ai"])if(n[i]!==void 0&&typeof n[i]!="boolean")throw new Error(`Extension "${t}" extendPage() field ${i} must be a boolean`);return e}u(ie,"assertPagePatch");async function ae(t){let e=[];for(let o of ne){let r=ht(t,o);await I(r)&&e.push({path:o,fingerprint:M(await Xt(r))})}return S(e)}u(ae,"lockfileFingerprint");async function se(t,e,o){let r=Zt(t,o.resolve);if(await J(t,r,`extension ${o.resolve}`),!await I(r))throw new Error(`Extension module not found: ${o.resolve}`);let i=(await ee({entryPoints:[r],bundle:!0,format:"esm",platform:"node",target:"node22",write:!1,sourcemap:"inline",plugins:[{name:"canofold-extension-api",setup(c){c.onResolve({filter:/^canofold$/},()=>({path:"canofold-extension-api",namespace:"canofold-extension-api"})),c.onLoad({filter:/.*/,namespace:"canofold-extension-api"},()=>({loader:"js",contents:`
2
- export const CANOFOLD_EXTENSION_API_VERSION = ${JSON.stringify(1)}
3
- export const canofoldVersion = ${JSON.stringify(H)}
4
- export const defineExtension = (factory) => factory
5
- `}))}}]})).outputFiles[0];if(!i)throw new Error(`Failed to bundle extension ${o.resolve}`);await mt(e,{recursive:!0});let l=ht(e,`extension-${Bt()}.mjs`);await gt(l,i.contents);try{let p=(await import(`${te(l).href}?t=${Date.now()}`)).default,a=typeof p=="function"?await p(structuredClone(o.options??{})):p,s=re(a,o),f=(s.outputs??[]).map(d=>yt(s.name,d));if(new Set(f.map(P)).size!==f.length)throw new Error(`Extension "${s.name}" declares duplicate portable output paths`);return{definition:s,declaredOutputs:new Set(f),fingerprint:S({descriptor:o,bundle:M(i.contents)})}}finally{await Yt(l,{force:!0})}}u(se,"loadOneExtension");async function lo(t,e,o){let r=[];for(let c of o)try{r.push(await se(t,e,c))}catch(p){throw new Error(`Failed to load extension ${c.resolve}: ${D(p)}`,{cause:p})}let n=new Set;for(let c of r){if(n.has(c.definition.name))throw new Error(`Duplicate extension name "${c.definition.name}"`);n.add(c.definition.name)}let i=r.length?await ae(t):S({lockfiles:[]}),l=r.flatMap(({definition:c,declaredOutputs:p})=>[...p].map(a=>`/extensions/${c.name}/${a.split("/").map(encodeURIComponent).join("/")}`));return{fingerprint:S({apiVersion:1,dependencyFingerprint:i,extensions:r.map(c=>({name:c.definition.name,fingerprint:c.fingerprint}))}),publicOutputPaths:l,async transformSource(c){let p=c.source;for(let{definition:a}of r)if(a.transformSource)try{let s=await a.transformSource({...c,source:p});if(typeof s!="string")throw new Error("transformSource() must return a string");p=s}catch(s){throw new Error(`Extension "${a.name}" transformSource failed for ${c.sourceRelativePath}: ${D(s)}`,{cause:s})}return p},async extendPage(c){let p=c;for(let{definition:a}of r)if(a.extendPage)try{let s=ie(a.name,await a.extendPage(dt(p)));p={...p,...s}}catch(s){throw new Error(`Extension "${a.name}" extendPage failed for ${p.sourceRelativePath}: ${D(s)}`,{cause:s})}return p},async generate(c,p){for(let{definition:a,declaredOutputs:s}of r){if(!a.generate)continue;let f=new Set;try{await a.generate({pages:p.map(dt),emitFile:u(async(g,h)=>{let w=yt(a.name,g);if(!s.has(w))throw new Error(`generate() emitted undeclared output "${w}"`);if(f.has(w))throw new Error(`generate() emitted "${w}" more than once`);f.add(w);let y=v(c,wt.join("extensions",a.name,w),`extension ${a.name} output`);await mt(Qt(y),{recursive:!0}),await gt(y,h)},"emitFile")});let d=[...s].filter(g=>!f.has(g));if(d.length)throw new Error(`generate() did not emit declared outputs: ${d.join(", ")}`)}catch(d){throw new Error(`Extension "${a.name}" generate failed: ${D(d)}`,{cause:d})}}}}}u(lo,"loadExtensionHost");export{S as a,M as b,le as c,ot as d,De as e,T as f,Ve as g,Kt as h,qe as i,Be as j,lo as k};
6
- //# sourceMappingURL=chunk-FCABZITC.js.map
@@ -1,45 +0,0 @@
1
- import{b as N}from"./chunk-M6T5RSNJ.js";import{c as j}from"./chunk-JK7ZNBUA.js";import{a as i}from"./chunk-AYDF3IFZ.js";import{createServer as I}from"http";import{readFile as H,realpath as k}from"fs/promises";import{extname as P,isAbsolute as $,join as v,normalize as O,relative as B,resolve as S,sep as L}from"path";var T={".html":"text/html; charset=utf-8",".css":"text/css; charset=utf-8",".js":"text/javascript; charset=utf-8",".mjs":"text/javascript; charset=utf-8",".json":"application/json; charset=utf-8",".txt":"text/plain; charset=utf-8",".md":"text/markdown; charset=utf-8",".svg":"image/svg+xml",".xml":"application/xml; charset=utf-8",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".avif":"image/avif",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".pagefind":"application/wasm"};function z(e){return T[P(e).toLowerCase()]??"application/octet-stream"}i(z,"contentTypeFor");var J=15e3;function U(e){for(let o of e)o.end();e.clear()}i(U,"closeReloadClients");function w(e,o){for(let n of e)try{n.write(o)}catch{e.delete(n);try{n.end()}catch{}}}i(w,"writeReloadClients");function M(e){w(e,`:keepalive
2
-
3
- `)}i(M,"heartbeatReloadClients");function R(e,o=""){let n=o.replace(/\r\n?/g,`
4
- `).split(`
5
- `);return`event: ${e}
6
- ${n.map(d=>`data: ${d}`).join(`
7
- `)}
8
-
9
- `}i(R,"formatServerSentEvent");function A(e,o="/__canofold/events"){let n=`<script type="module">
10
- const source=new EventSource(${JSON.stringify(o)});
11
- let connected=false,disconnected=false;
12
- let overlay=null;
13
- function showError(msg){
14
- if(!overlay){overlay=document.createElement('dialog');overlay.style.cssText='all:initial;position:fixed;inset:0;width:100%;height:100%;border:none;background:rgba(15,15,20,.92);color:#f87171;font:14px/1.6 monospace;padding:2rem;box-sizing:border-box;z-index:2147483647;overflow:auto;white-space:pre-wrap;word-break:break-all;';document.documentElement.appendChild(overlay);}
15
- overlay.textContent='\u26A0\uFE0F Build error:\\n\\n'+msg;
16
- if(!overlay.open)overlay.showModal();
17
- }
18
- function clearError(){if(overlay&&overlay.open){overlay.close();overlay.remove();overlay=null;}}
19
- function normalizeRoute(value){const path=value.split(/[?#]/,1)[0]||'/';return path.endsWith('/')?path:path+'/';}
20
- async function applyPageUpdate(update){
21
- const currentRoute=normalizeRoute(location.pathname);
22
- if(!update.routes.some((route)=>normalizeRoute(route)===currentRoute))return true;
23
- const response=await fetch(location.href,{cache:'no-store',headers:{accept:'text/html'}});
24
- if(!response.ok||!(response.headers.get('content-type')||'').includes('text/html'))return false;
25
- const nextDocument=new DOMParser().parseFromString(await response.text(),'text/html');
26
- if(typeof window.__canofoldApplyPageDocument!=='function')return false;
27
- return window.__canofoldApplyPageDocument(nextDocument,{mode:'update'});
28
- }
29
- source.onopen=()=>{if(connected&&disconnected){clearError();location.reload();}connected=true;disconnected=false;};
30
- source.onerror=()=>{if(connected)disconnected=true;};
31
- source.onmessage=()=>{clearError();location.reload();};
32
- source.addEventListener('update',async(event)=>{
33
- clearError();
34
- try{
35
- const update=JSON.parse(event.data);
36
- if(update.protocol!==1||update.type!=='update'||update.mode!=='page'){location.reload();return;}
37
- if(!await applyPageUpdate(update))location.reload();
38
- }catch{location.reload();}
39
- });
40
- source.addEventListener('build-error',(e)=>showError(e.data));
41
- source.addEventListener('build-ok',()=>clearError());
42
- </script>`;return e.replace("</body>",`${n}</body>`)}i(A,"injectLiveReloadScript");function W(e,o="/"){if(o==="/")return e;let n=o.replace(/\/$/,"");return e===n?"/":e.startsWith(`${n}/`)?e.slice(n.length)||"/":void 0}i(W,"resolveMountedRequestPath");function G(e,o){let n=S(e),d=o.split("/").map(f=>{let t=decodeURIComponent(f);if(t==="."||t===".."||t.includes("/")||t.includes("\\")||/[\u0000-\u001f]/.test(t))throw new Error("Forbidden");return t}),c=O(d.join("/"));if(c.split(/[\\/]/).includes(".."))throw new Error("Forbidden");let s=S(v(n,c)),p=c.endsWith("/")?[v(s,"index.html")]:P(c)===""?[s,v(s,"index.html")]:[s];for(let f of p){let t=B(n,f);if(t===".."||t.startsWith(`..${L}`)||$(t))throw new Error("Forbidden")}return p}i(G,"resolveRequestCandidates");async function _(e,o){let[n,d]=await Promise.all([k(e),k(o)]);if(!j(n,d))throw new Error("Forbidden");return d}i(_,"resolveExistingRequestPath");async function K(e){try{let o=await _(e,v(e,"404.html"));return await H(o)}catch(o){if(o.code==="ENOENT")return;throw o}}i(K,"readGeneratedNotFound");async function ee({root:e,port:o,liveReload:n=!1,basePath:d="/"}){let c=new Set,s=I(async(t,r)=>{if(t.method!=="GET"&&t.method!=="HEAD"){r.writeHead(405,{allow:"GET, HEAD"}),r.end("Method not allowed");return}let l=new URL(t.url??"/","http://127.0.0.1"),h=typeof d=="function"?d():d,y=`${h==="/"?"":h.replace(/\/$/,"")}/__canofold/events`;if(n&&l.pathname===y){r.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),r.write(`:connected
43
-
44
- `),c.add(r);let a=i(()=>c.delete(r),"removeClient");t.once("close",a),r.once("close",a),r.once("error",a);return}let C=W(l.pathname,h),g,E=i(async()=>{r.statusCode=404;let a=await K(g);if(a){r.setHeader("content-type",T[".html"]??"text/html; charset=utf-8"),n&&(a=Buffer.from(A(a.toString("utf8"),y))),r.end(t.method==="HEAD"?void 0:a);return}r.end(t.method==="HEAD"?void 0:"Not found")},"sendNotFound"),x=i(a=>{N("Static server error:",a),r.statusCode=500,r.end(t.method==="HEAD"?void 0:"Internal server error")},"sendInternalError");if(g=S(typeof e=="function"?e():e),C===void 0){try{await E()}catch(a){x(a)}return}let D;try{D=G(g,C)}catch{r.statusCode=403,r.end("Forbidden");return}try{let a,u;for(let b of D)try{let m=await _(g,b);u=await H(m),a=m;break}catch(m){if(m.message==="Forbidden"){r.statusCode=403,r.end("Forbidden");return}let F=m.code;if(F!=="ENOENT"&&F!=="EISDIR")throw m}if(!a||!u){await E();return}r.setHeader("content-type",z(a)),r.setHeader("cache-control","no-store"),n&&P(a)===".html"&&(u=Buffer.from(A(u.toString("utf8"),y))),r.end(t.method==="HEAD"?void 0:u)}catch(a){let u=a.code;if(u==="ENOENT"||u==="EISDIR")try{await E()}catch(b){x(b)}else x(a)}});await new Promise((t,r)=>{let l=i(h=>r(h),"onError");s.once("error",l),s.listen(o,"127.0.0.1",()=>{s.off("error",l),t()})});let p=s.address();if(!p||typeof p=="string")throw new Error("Failed to start server");let f=n?setInterval(()=>M(c),J):void 0;return f?.unref(),{port:p.port,reload:i((t={protocol:1,type:"update",mode:"full",routes:[]})=>{w(c,R("update",JSON.stringify(t)))},"reload"),sendBuildError:i(t=>{w(c,R("build-error",t))},"sendBuildError"),sendBuildOk:i(()=>{w(c,R("build-ok"))},"sendBuildOk"),close:i(()=>(f&&clearInterval(f),U(c),new Promise((t,r)=>s.close(l=>l?r(l):t()))),"close")}}i(ee,"startStaticServer");export{ee as a};
45
- //# sourceMappingURL=chunk-JZIKHPBO.js.map
@@ -1,2 +0,0 @@
1
- var _="0.2.1";export{_ as a};
2
- //# sourceMappingURL=chunk-KUDMXVOM.js.map
@@ -1,2 +0,0 @@
1
- import{a as b}from"./chunk-JZIKHPBO.js";import{b as g}from"./chunk-B2QFU4ZW.js";import"./chunk-FCABZITC.js";import{b as h}from"./chunk-ENPRUF6E.js";import"./chunk-XYJ2OBL3.js";import{a as B}from"./chunk-7SYMF26J.js";import"./chunk-4OALGQQB.js";import{a as v,b as f}from"./chunk-M6T5RSNJ.js";import"./chunk-KUDMXVOM.js";import"./chunk-EAYVCA3Z.js";import{c as p,e as m}from"./chunk-JK7ZNBUA.js";import{a as o}from"./chunk-AYDF3IFZ.js";import w from"chokidar";import{createMarkdownRenderer as S}from"@canofold/markdown/server";import{relative as P,resolve as k,sep as R}from"path";function D({build:n,reload:c,onBuildError:l=o(t=>f(t instanceof Error?t.message:String(t)),"onBuildError"),onBuildOk:i,debounceMs:s=80}){let t,u,e=!1,r=!1,a=o(()=>{if(t=void 0,!r){if(u){e=!0;return}u=(async()=>{try{let d=await n();r||(i?.(),c(d))}catch(d){l(d)}finally{u=void 0,e&&!r&&(e=!1,t=setTimeout(a,0))}})()}},"run");return{schedule(){if(!r){if(u){e=!0;return}t&&clearTimeout(t),t=setTimeout(a,s)}},async close(){r=!0,e=!1,t&&clearTimeout(t),t=void 0,await u}}}o(D,"createBuildScheduler");async function y({cwd:n,port:c}){let l=S(),i=await g({cwd:n,renderer:l}),s=await b({root:o(()=>m(n,i.config.outputDir),"root"),port:c,liveReload:!0,basePath:o(()=>i.config.basePath,"basePath")}),t=w.watch(".",{cwd:n,ignoreInitial:!0,ignored:o(e=>{let r=k(n,e),a=P(n,r).split(R);return a.includes("node_modules")||a.includes(".git")||a.includes(".canofold")||a.some(d=>/^\..+\.(?:tmp|backup)-/.test(d))?!0:p(m(n,i.config.outputDir),r)||p(B(n),r)},"ignored")}),u=D({build:o(async()=>{i=await g({cwd:n,renderer:l});let e=i.changedPages.flatMap(r=>{let a=i.graph.pages.find(d=>d.sourceRelativePath===r);return a?[h(i.config,a.routePath)]:[]});return{protocol:1,type:"update",mode:i.partialReload&&e.length===1?"page":"full",routes:e}},"build"),reload:o(e=>s.reload(e),"reload"),onBuildError:o(e=>{let r=e instanceof Error?e.message:String(e);f("Build error:",r),s.sendBuildError(r)},"onBuildError"),onBuildOk:o(()=>s.sendBuildOk(),"onBuildOk")});return t.on("all",()=>u.schedule()),t.on("error",e=>{let r=e instanceof Error?e.message:String(e);f("File watcher error:",r),s.sendBuildError(r)}),{port:s.port,close:o(async()=>{await t.close(),await u.close(),await s.close()},"close")}}o(y,"startDevServer");async function z({cwd:n,port:c=3333}){let l=await y({cwd:n,port:c});return v(`Dev server running at http://127.0.0.1:${l.port}/`),l}o(z,"runDev");export{z as runDev};
2
- //# sourceMappingURL=dev-AMVXGDVE.js.map