@pathmx/core 0.5.0 → 0.5.2

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/pathmx.js CHANGED
@@ -1,1224 +1,3 @@
1
1
  #!/usr/bin/env bun
2
- // @bun
3
- import{Command as Uw}from"commander";import Cy from"@parcel/watcher";import{fileURLToPath as Ay}from"url";import{dirname as Iy,isAbsolute as $y,join as Vp,relative as Ty,resolve as Hp,sep as Ey}from"path";import{existsSync as Ku}from"fs";import{readdir as Si}from"fs/promises";import{join as Wn,resolve as Zu}from"path";function Iu(e){return typeof e==="object"&&e!==null&&"id"in e&&typeof e.id==="string"}function ie(e){let t=[],n=new Set;function r(o,i){if(Array.isArray(o)){if(n.has(o))throw Error(`Cyclic PluginPreset at ${i}.`);n.add(o),o.forEach((s,a)=>r(s,`${i}[${a}]`)),n.delete(o);return}if(typeof o==="function"||Iu(o)){t.push(o);return}throw Error(`Invalid Plugin contribution at ${i}: expected a Plugin, PluginFactory, or PluginPreset.`)}return e.forEach((o,i)=>r(o,`plugins[${i}]`)),Object.freeze(t)}function ve(e){if(typeof e!=="function")return e;let t=e();if(!t.name&&e.name)t.name=e.name;return t}function U(e,t){let n=e.replaceAll("\\","/").replace(/\/+$/,""),r=n.lastIndexOf("/");return`${r===-1?"":n.slice(0,r+1)}${t}`}import{mkdir as wi,unlink as Fu}from"fs/promises";import{dirname as xi,join as Uu,posix as _u}from"path";import{fileURLToPath as Qu}from"url";import{Database as Wu}from"bun:sqlite";var{YAML:bi}=globalThis.Bun;import{copyFile as $u,mkdir as Nt,mkdtemp as Tu,rename as Bt,rm as fi}from"fs/promises";import{basename as Eu,dirname as zt,isAbsolute as hi,join as qt,parse as Ou,relative as Mu,resolve as yi,sep as Du}from"path";var gi=32;async function ju(e,t){for(let n=0;n<e.length;n+=gi)await Promise.all(e.slice(n,n+gi).map(t))}function Lu(e){return typeof e==="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}async function Bu(e,t){try{return await Bt(e,t),!0}catch(n){if(Lu(n))return!1;throw n}}function Un(e,t){let n=yi(e,t),r=Mu(e,n);if(!t||hi(t)||r===".."||r.startsWith(`..${Du}`)||hi(r))throw Error(`Invalid publication artifact path: ${t}`);if(r===qt(".pathmx","manifest.json"))throw Error("Publication artifact conflicts with .pathmx/manifest.json.");return n}function Nu(e){return Object.freeze({async put(t,n){let r=Un(e,t);return await Nt(zt(r),{recursive:!0}),await Bun.write(r,n),Object.freeze({size:n.size,read:async()=>Bun.file(r)})}})}function zu(e){return e==="/"?"index.html":qt(e.replace(/^\/+|\/+$/g,""),"index.html")}async function qu(e,t){let n=new Map(t.artifacts.map((o)=>[o.path,o])),r=t.manifest.routes.filter((o)=>o.type==="page");await ju(r,async(o)=>{let i=o.representations.find((u)=>u.default&&u.type==="html"),s=i?n.get(i.artifact):void 0;if(!s)throw Error(`Page route has no default HTML artifact: ${o.pathname}`);let a=zu(o.pathname),c=n.get(a);if(c&&c!==s)throw Error(`Directory publication cannot represent both ${o.pathname} and /${a}.`);let p=Un(e,a);await Nt(zt(p),{recursive:!0}),await $u(Un(e,s.path),p)})}async function Vu(e,t){await qu(e,t);let n=qt(e,".pathmx","manifest.json");await Nt(zt(n),{recursive:!0}),await Bun.write(n,JSON.stringify(t.manifest,null,2)+`
4
- `)}async function Hu(e,t){let n=yi(e);if(n===Ou(n).root)throw Error("Publication output cannot be a filesystem root.");let r=zt(n);await Nt(r,{recursive:!0});let o=await Tu(qt(r,`.${Eu(n)}-`)),i=`${o}.previous`,s=!1;try{let a=await t(o);s=await Bu(n,i);try{await Bt(o,n)}catch(c){if(s)await Bt(i,n),s=!1;throw c}if(s)await fi(i,{recursive:!0,force:!0}).catch(()=>{return}),s=!1;return a}catch(a){if(await fi(o,{recursive:!0,force:!0}),s)await Bt(i,n);throw a}}async function _n(e,t){return Hu(e,async(n)=>{let r=await t(Nu(n));return await Vu(n,r),r.manifest})}function Qn(e){return Array.isArray(e)}function Xu(e){return typeof e==="object"&&e!==null&&"code"in e&&e.code==="SQLITE_BUSY"}async function ct(e,t=5000){let n=Date.now()+t;while(!0)try{return e()}catch(r){if(!Xu(r)||Date.now()>=n)throw r;await new Promise((o)=>setTimeout(o,10))}}function Ju(e){let t=new Wu(e,{create:!0,strict:!0});t.exec("PRAGMA foreign_keys = ON"),t.exec("PRAGMA journal_mode = WAL"),t.exec("PRAGMA busy_timeout = 0");let n=Promise.resolve(),r=(s)=>{let a=n.then(s,s);return n=a.then(()=>{return},()=>{return}),a},o=(s)=>Object.freeze({all:async(a,c)=>ct(()=>{if(!c)return t.query(a).all();return Qn(c)?t.query(a).all(...c):t.query(a).all({...c})}),get:async(a,c)=>await ct(()=>!c?t.query(a).get():Qn(c)?t.query(a).get(...c):t.query(a).get({...c}))??void 0,run:async(a,c)=>{let p=await ct(()=>!c?t.query(a).run():Qn(c)?t.query(a).run(...c):t.query(a).run({...c}));return{changes:p.changes,...p.lastInsertRowid!=null?{lastInsertRowId:p.lastInsertRowid}:{}}},exec:async(a)=>{t.exec(a)},transaction:async(a)=>{if(!s)throw Error("Nested database transactions are not supported.");await ct(()=>t.exec("BEGIN IMMEDIATE"));try{let c=await a(o(!1));return await ct(()=>t.exec("COMMIT")),c}catch(c){throw t.exec("ROLLBACK"),c}}}),i=o(!0);return Object.freeze({all:(s,a)=>r(()=>i.all(s,a)),get:(s,a)=>r(()=>i.get(s,a)),run:(s,a)=>r(()=>i.run(s,a)),exec:(s)=>r(()=>i.exec(s)),transaction:(s)=>r(()=>i.transaction(s)),close:()=>r(()=>{t.close(!1)})})}function Gu(e){if(e.includes("javascript"))return"script";if(e.includes("css"))return"style";return"file"}function Yu(e,t){let n=new HTMLRewriter;for(let[r,o]of t)n.on(r,o);if(typeof e==="string")return n.transform(e);return n.transform(e)}var ue={renderMarkdown:(e)=>Bun.markdown.html(e,{headings:{ids:!0},noIndentedCodeBlocks:!0}),rewriteHtml:Yu,loadAsset:(e)=>Bun.file(e),bundle:async(e)=>{let t=await Bun.build({entrypoints:[e instanceof URL?Qu(e):e],target:"browser",minify:!0,define:{"process.env.NODE_ENV":JSON.stringify("production")},throw:!0});return Promise.all(t.outputs.map(async(n)=>{let r=n.path.replace(/^\.\//,""),o=Gu(n.type);return o==="file"?{path:r,type:o,blob:n}:{path:r,type:o,text:await n.text()}}))},loadModule:async(e)=>{if(!await Bun.file(e).exists())return;return import(e)},path:_u,yaml:{parse:bi.parse,stringify:(e)=>bi.stringify(e,null,2)},storage:{list:(e)=>[...new Bun.Glob("**/*").scanSync({cwd:e,onlyFiles:!0})],readText:(e)=>Bun.file(e).text(),readBlob:(e)=>Bun.file(e),writeText:async(e,t)=>{await wi(xi(e),{recursive:!0}),await Bun.write(e,t)},delete:(e)=>Fu(e),exists:(e)=>Bun.file(e).exists()},database:{path:Uu,open:async(e)=>(await wi(xi(e),{recursive:!0}),Ju(e))}};var el=/^[^/]+\.plugin\.(?:ts|tsx|js|jsx)$/,tl=/^index\.plugin\.(?:ts|tsx|js|jsx)$/;function Xn(e){return U(e,"plugins")}async function nl(e){if(!Ku(e))return[];let t=await Si(e,{withFileTypes:!0}),n=t.filter((o)=>o.isFile()&&el.test(o.name)).map((o)=>Wn(e,o.name)),r=await Promise.all(t.filter((o)=>o.isDirectory()).map(async(o)=>{let i=Wn(e,o.name);return(await Si(i,{withFileTypes:!0})).filter((a)=>a.isFile()&&tl.test(a.name)).map((a)=>Wn(i,a.name))}));return[...n,...r.flat()].sort()}function rl(e,t){try{return ie([e]),e}catch(n){throw Error(`Repository Plugin ${t} must default-export a Plugin, PluginFactory, or PluginPreset.`,{cause:n})}}async function Vt(e,t){let n=[],r=Zu(Xn(e));for(let o of await nl(r)){let i=await ue.loadModule(o),s=rl(i?.default,o);t.info("plugin.discover",{entrypoint:o}),n.push(s)}return n}import{resolve as Zo}from"path";import ot from"picocolors";import{join as hy}from"path";function vi(e){return e.split("/").filter(Boolean)}function ke(e){if(!e)return".";let t=e.startsWith("/"),n=[];for(let o of e.split("/")){if(!o||o===".")continue;if(o===".."){if(n.length&&n.at(-1)!=="..")n.pop();else if(!t)n.push(o)}else n.push(o)}return`${t?"/":""}${n.join("/")}`||(t?"/":".")}function ki(...e){return ke(e.filter(Boolean).join("/"))}function ol(e){let t=ke(e);if(t==="/"||t===".")return t;let n=t.lastIndexOf("/");if(n===-1)return".";return n===0?"/":t.slice(0,n)}function Pi(e){let t=ke(e);if(t==="/"||t===".")return t;return t.slice(t.lastIndexOf("/")+1)}function il(e,t){let n=vi(ke(e)),r=vi(ke(t)),o=0;while(o<n.length&&o<r.length&&n[o]===r[o])o++;return[...Array.from({length:n.length-o},()=>".."),...r.slice(o)].join("/")}function sl(e){let t=Pi(e),n=t.lastIndexOf(".");return n>0?t.slice(n):""}function al(e,t){return ke(t.startsWith("/")?t:ki(e,t))}var S={basename:Pi,dirname:ol,extname:sl,join:ki,normalize:ke,relative:il,resolve:al};var cl=/(`+)([\s\S]*?)\1/g;function Ri(e){return e.replace(cl,(t)=>" ".repeat(t.length))}var pl=String.raw`\{\{\s*[A-Za-z_][\w-]*(?:\.[A-Za-z_][\w-]*)*\s*\}\}`,ul=String.raw`(?:(?:${pl})|[^\s)])+`,Jn=new RegExp(String.raw`(!?)\[([^\]]*)\]\(\s*(?:<([^>\r\n]+)>|(${ul}))`,"g"),Gn=/<a\b[^>]*\bhref\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s>]+))/gi,Yn=/^[ \t]{0,3}\[([^\]]+)\]:[ \t]+(?:<([^>\r\n]+)>|(\S+))(?:[ \t]+(?:"([^"]*)"|'([^']*)'|\(([^)]*)\)))?[ \t]*$/gm,ll=/^@([A-Za-z][\w-]*)((?:\.[A-Za-z][\w-]*)*)(?:\s+([\s\S]*))?$/,dl=/^[a-z][a-z\d+.-]*:/i;function le(e){let t=e.trim();return dl.test(t)||t.startsWith("//")}function Ht(e){let t=e.trim();return Boolean(t&&t.endsWith(".md")&&!t.includes("?")&&!t.includes("#")&&!t.includes("\\")&&!t.startsWith("//")&&!t.startsWith("~/")&&!/^[a-z][a-z\d+.-]*:/i.test(t))}function Kn(e){let t=e?.trim();if(!t)return{};let n=t.match(ll);if(!n)return{label:t};let r=n[2]?n[2].slice(1).split(".").filter(Boolean):[],o=n[3]?.trim();return{directive:{name:n[1],qualifiers:r},...o?{label:o}:{}}}function ml(e,t,n,r,o){let i=n?.trim();if(!i)return;if(r!=="definition"){let c=`${r}:${i}`;if(t.has(c))return;t.add(c)}let{label:s,directive:a}=Kn(o);e.push({href:i,type:"unresolved",kind:r,...s?{label:s}:{},...a?{directive:a}:{}})}function pt(e){let t=[],n=new Set;for(let r of e){let o=Ri(r),i=[];for(let s of o.matchAll(Yn))i.push({index:s.index??0,href:s[2]??s[3],kind:"definition",label:s[1]});for(let s of o.matchAll(Jn))i.push({index:s.index??0,href:s[3]??s[4],kind:s[1]==="!"?"image":"inline",label:s[2]});for(let s of o.matchAll(Gn))i.push({index:s.index??0,href:s[1]??s[2]??s[3],kind:"html"});i.sort((s,a)=>s.index-a.index);for(let s of i)ml(t,n,s.href,s.kind,s.label)}return t}function fl(e){return pt([e])}function de(e){return fl(e)}function Be(e,t){return t.matchAll(new RegExp(e.source,e.flags))}function Ci(e,t,n){if(e.index==null)return;let r=n==="<"?`<${t}`:t,o=e[0].indexOf(r,e[0].lastIndexOf(n));if(o===-1)return;let i=e.index+o+(n==="<"?1:0);return{start:i,end:i+t.length}}function Ai(e){let t=e[3]??e[4];if(!t)return;return Ci(e,t,e[3]!=null?"<":"(")}function hl(e){let t=e[1]??e[2]??e[3];if(!t||e.index==null)return;let n=e[0].search(/href\s*=/i);if(n===-1)return;let r=e[0].indexOf("=",n)+1;while(r<e[0].length&&/\s/.test(e[0][r]))r++;if(e[0][r]==='"'||e[0][r]==="'")r++;return{start:e.index+r,end:e.index+r+t.length}}function gl(e){let t=e[2]??e[3];if(!t)return;return Ci(e,t,e[2]!=null?"<":"]:")}function Ii(e,t){t.sort((r,o)=>o.start-r.start);let n=e;for(let{start:r,end:o,text:i}of t)n=`${n.slice(0,r)}${i}${n.slice(o)}`;return n}function yl(e,t){let n=t;while(n<e.length&&(e[n]===" "||e[n]==="\t"))n++;let r=e[n];if(r==='"'||r==="'"){n++;while(n<e.length&&e[n]!==r)n++;if(e[n]===r)n++}else if(e[n]==="("){n++;while(n<e.length&&e[n]!==")")n++;if(e[n]===")")n++}while(n<e.length&&(e[n]===" "||e[n]==="\t"))n++;if(e[n]===")")n++;return n}function wl(e,t){if(t.index==null)return;let n=e.indexOf(">",t.index);if(n===-1)return;if(e[n-1]==="/")return{start:t.index,end:n+1,inner:""};let r=e.toLowerCase().indexOf("</a>",n+1);if(r===-1)return;return{start:t.index,end:r+4,inner:e.slice(n+1,r)}}function xl(e,t){if(t.index==null)return;let n=t.index+t[0].length;if(e[n]==="\r")n++;if(e[n]===`
5
- `)n++;return{start:t.index,end:n}}function ut(e,t){let n=[],r=(o,i)=>{if(!o||!i)return;let s=t(o);if(s==null||s===o)return;n.push({...i,text:s})};for(let o of Be(Jn,e))r(o[3]??o[4],Ai(o));for(let o of Be(Gn,e))r(o[1]??o[2]??o[3],hl(o));for(let o of Be(Yn,e))r(o[2]??o[3],gl(o));return Ii(e,n)}function Ft(e,t){let n=[];for(let r of Be(Jn,e)){let o=r[3]??r[4],i=Ai(r);if(!o||!i||r.index==null||!t(o))continue;n.push({start:r.index,end:yl(e,i.end),text:r[2]??""})}for(let r of Be(Gn,e)){let o=r[1]??r[2]??r[3],i=wl(e,r);if(!o||!i||!t(o))continue;n.push({...i,text:i.inner})}for(let r of Be(Yn,e)){let o=r[2]??r[3],i=xl(e,r);if(!o||!i||!t(o))continue;n.push({...i,text:""})}return Ii(e,n)}var $i=/^(\s*)([`~]{3,})(.*)$/;function x(e){let t=e.match($i);if(!t)return;return{indent:t[1],marker:t[2],info:t[3].trim()}}function v(e,t){let n=e.match($i);return Boolean(n&&n[2][0]===t[0]&&n[2].length>=t.length&&!n[3].trim())}function Ut(e){let t=[],n=e.split(/\r?\n/),r;for(let o=0;o<n.length;o++){let i=n[o]??"";if(r){if(v(i,r.marker))t.push({lang:r.lang,info:r.info,body:n.slice(r.start,o).join(`
6
- `)}),r=void 0;continue}let s=x(i);if(!s)continue;let a=s.info.split(/\s+/,1)[0]??"";r={marker:s.marker,lang:a,info:s.info,start:o+1}}return t}function me(e,t){let n=t,r="",o=0;while(o<e.length){if(n){let s=e.indexOf("-->",o);if(s===-1)return{line:r,inComment:n};n=!1,o=s+3;continue}let i=e.indexOf("<!--",o);if(i===-1){r+=e.slice(o);break}r+=e.slice(o,i),n=!0,o=i+4}return{line:r,inComment:n}}var bl=/^( *)([-+*]|(\d+)[.)])[ \t]+(.+?)[ \t]*$/,Sl=/^\[([ xX])\](?:[ \t]+(.*))?$/,vl=/(?:^|[ \t]+)\{#([A-Za-z][\w-]*)((?:[ \t]+\.[A-Za-z][\w-]*)*)\}$/,kl=/^\[([^\]\r\n]+)\]\(\s*(?:<([^>\r\n]+)>|([^\s)]+))(?:[ \t]+(?:"[^"]*"|'[^']*'|\([^)]*\)))?\s*\)$/,Zn=Object.freeze([]);function Pl(e){let t=0;while(e.charCodeAt(t)===32)t++;let n=e.charCodeAt(t);if(n===45||n===43||n===42){let i=e.charCodeAt(t+1);return i===32||i===9}if(n<48||n>57)return!1;while(e.charCodeAt(t)>=48&&e.charCodeAt(t)<=57)t++;let r=e.charCodeAt(t);if(r!==46&&r!==41)return!1;let o=e.charCodeAt(t+1);return o===32||o===9}function Ti(e){for(let t of e){for(let n of t.items){if(n.children!==Zn)Ti(n.children);Object.freeze(n)}Object.freeze(t.items),Object.freeze(t)}return Object.freeze(e)}function Rl(e){let t=e.text.match(Sl);if(!t)return;let n=t[2]??"",r=n.match(vl),o=r?.[2]?r[2].trim().split(/[ \t]+/).map((i)=>i.slice(1)):[];return Object.freeze({line:e.line,text:r?n.slice(0,r.index).trimEnd():n,checked:t[1].toLowerCase()==="x",...r?{id:r[1]}:{},tags:Object.freeze(o)})}function Cl(e){let t=[],n=(r)=>{for(let o of r)for(let i of o.items){let s=Rl(i);if(s)t.push(s);n(i.children)}};return n(e),Object.freeze(t)}class Ei{collectOther;lists=[];other=[];levels=[];finished;constructor(e=!1){this.collectOther=e}separate(){this.levels.length=0}add(e,t){if(!e.trim())return;let n=Pl(e)?e.match(bl):null;if(!n){if(this.separate(),this.collectOther)this.other.push({line:t,text:e});return}let r=n[1].length,o=n[3]?"ordered":"unordered",i=n[3]?Number(n[3]):void 0;while(this.levels.length&&r<this.levels.at(-1).indent)this.levels.pop();let s,a=this.levels.at(-1);if(a?.indent===r&&a.list.type===o)s=a.list;else{if(a?.indent===r)this.levels.pop();let c=this.levels.at(-1)?.list.items.at(-1);if(s={type:o,...i!==void 0?{start:i}:{},items:[]},c){if(c.children===Zn)c.children=[];c.children.push(s)}else this.lists.push(s);this.levels.push({indent:r,list:s})}s.items.push({line:t,text:n[4],children:Zn})}finish(){return this.finished??=Ti(this.lists)}}function Ne(e){let t=new Ei(!0),n=e.includes("<!--"),r,o=!1;for(let[a,c]of e.split(/\r?\n/).entries()){if(r){if(v(c,r))r=void 0;continue}let p=n||o?me(c,o):void 0;if(p)o=p.inComment;let u=p?.line??c,l=x(u);if(l){r=l.marker,t.add(u,a+1);continue}t.add(u,a+1)}let i=t.finish(),s;return{lists:i,get tasks(){return s??=Cl(i)},other:t.other}}function lt(e){let t=e.text.match(kl);if(!t)return;return{label:t[1],href:(t[2]??t[3]??"").trim()}}function Al(e){return e.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1").replace(/\[([^\]]+)\]\([^)]*\)/g,"$1").replace(/`([^`]*)`/g,"$1").replace(/<[^>]*>/g,"").replace(/\\([\\`*_{}\[\]()#+.!-])/g,"$1").replace(/[\*_~]/g,"").trim()}function Il(e){return e.toLowerCase().replace(/[^a-z0-9\s-]/g,"").trim().replace(/[\s-]+/g,"-")}function Oi(e,t){let n=Il(e),r=t.get(n)??0;return t.set(n,r+1),r===0?n:`${n}-${r}`}function Mi(e,t){let n=e.match(/^\s{0,3}(#{1,6})[ \t]+(.+?)(?:[ \t]+#+[ \t]*)?$/);if(!n?.[1]||!n[2])return;let r=Al(n[2]);if(!r)return;return{depth:n[1].length,id:Oi(r,t),text:r}}function _t(e){let t=new Map;return e.map((n)=>({...n,id:Oi(n.text,t)}))}function Qt(e){let t=e.split(/\r?\n/),n=[],r=[],o=[],i=[],s=new Map,a=e.includes("<!--"),c=!1,p,u=()=>{if(i.some((l)=>l.includes("[")||/<a\b/i.test(l)))o.push(i.join(`
7
- `));i=[]};for(let l=0;l<t.length;l++){let d=t[l]??"";if(p){if(!v(d,p.marker)){p.body.push(d);continue}r.push({lang:p.lang,info:p.info,body:p.body.join(`
8
- `)}),p=void 0;continue}let m=a||c?me(d,c):void 0;if(m)c=m.inComment;let f=m?.line??d,h=x(f);if(h){u(),p={marker:h.marker,lang:h.info.split(/\s+/,1)[0]??"",info:h.info,body:[]};continue}let w=Mi(f,s);if(w)n.push(w);if(f.trim())i.push(f);else u()}return u(),{linkFragments:o,headings:n,fences:r}}class R extends Error{diagnostic;constructor(e){super(e.message);this.name="SourceDiagnosticError",this.diagnostic=e}}class er{mode;log;sources=new Map;constructor(e,t){this.mode=e;this.log=t}delete(e){this.sources.delete(e)}capture(e){if(this.mode!=="collect"||!(e instanceof R))return!1;let t=e.diagnostic,n=this.sources.get(t.source);if(!n)n=new Map,this.sources.set(t.source,n);let r=`${t.plugin}\x00${t.message}`;if(!n.has(r))n.set(r,t),this.log.error("source.invalid",t);return!0}all(){return[...this.sources.values()].flatMap((e)=>[...e.values()]).sort((e,t)=>e.source.localeCompare(t.source)||e.plugin.localeCompare(t.plugin)||e.message.localeCompare(t.message))}}class Wt extends Error{constructor(e){super(e instanceof Error?e.message:String(e),{cause:e});this.name="YamlMapParseError"}}function nr(e,t){let n;try{n=t.parse(e)}catch(r){throw new Wt(r)}return n&&typeof n==="object"&&!Array.isArray(n)?n:{}}function tr(e){return{data:{},body:e}}function Z(e,t){let n=e.match(/^---[ \t]*\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/);if(!n)return tr(e);if(!t)throw Error("A YAML codec is required to parse frontmatter.");return{data:nr(n[1],t),body:e.slice(n[0].length)}}function $l(e){let t=e.split(/\r?\n/).find((n)=>n.trim()&&!n.trimStart().startsWith("#"));return/^[ \t]*[A-Za-z0-9_.-]+:[ \t]*/.test(t??"")}function fe(e,t){let n=e.match(/^\s*<!--([\s\S]*?)-->/);if(!n?.[1]||!$l(n[1]))return tr(e);if(!t)throw Error("A YAML codec is required to parse topmatter.");let r=nr(n[1],t);if(!Object.keys(r).length)return tr(e);return{data:r,body:e.slice(n[0].length)}}function Tl(e){return typeof e.type==="string"&&e.type.trim()?e.type.trim():"block"}function El(e){return typeof e.id==="string"&&e.id.trim()?e.id.trim():void 0}function dt(e,t,n,r={},o){let i;try{i=fe(n,o)}catch(d){if(!(d instanceof Wt))throw d;throw new R({source:e.path,plugin:"source",message:`Invalid Block topmatter in ${e.path} (block ${t+1}): ${d.message}`})}let s={...i.data,...r},a=i.body.trim(),c=El(s)??`block-${t}`,p=Qt(a),u,l=()=>u??=Ne(a);return{id:c,path:`${e.path}#${c}`,type:Tl(s),data:s,links:pt(p.linkFragments),headings:p.headings,fences:p.fences,get lists(){return l().lists},get tasks(){return l().tasks},content:n,body:a}}function Di(e){return!e?.trim()}function G(e){let t=e.split(/\r?\n/),n=[],r=0,o;for(let s=0;s<t.length;s++){let a=t[s]??"";if(o){if(v(a,o))o=void 0;continue}let c=x(a);if(c){o=c.marker;continue}if(a.trim()!=="---"||!Di(t[s-1])||!Di(t[s+1]))continue;let p=t.slice(r,s).join(`
9
- `).trim();if(p)n.push(p);r=s+1}let i=t.slice(r).join(`
10
- `).trim();if(i)n.push(i);return n}function g(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function ee(e){if(!e.includes("&"))return e;return e.replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;|&apos;/g,"'").replace(/&#x([0-9a-f]+);/gi,(t,n)=>String.fromCodePoint(parseInt(n,16))).replace(/&#(\d+);/g,(t,n)=>String.fromCodePoint(Number(n))).replace(/&amp;/g,"&")}function ze(e){return ee(e).replace(/!\[[^\]\n]*\]\([^)\n]*\)/g," ").replace(/\[([^\]\n]+)\]\([^)\n]*\)/g,"$1").replace(/<[^>]*>/g," ").replace(/[`*_~]/g,"").replace(/\s+/g," ").trim()}function Ol(e){return e.startsWith("#")||e.startsWith("<")||e.startsWith(">")||e.startsWith("|")||/^([-*_]\s*){3,}$/.test(e)||/^[-*+]\s+\S/.test(e)||/^\d+[.)]\s+\S/.test(e)||/^!\[[^\]\n]*\]\([^)\n]*\)\s*$/.test(e)||/^\[[^\]\n]+\]\([^)\n]*\)\s*$/.test(e)||/^\[[^\]\n]+\]:/.test(e)}function Ml(e,t){if(e.length<=t)return e;return`${e.slice(0,t).replace(/\s+\S*$/,"").trim()||e.slice(0,t).trim()}...`}function rr(e,{minLength:t=12,maxLength:n=160}={}){let r=e.replace(/<!--[\s\S]*?-->/g,"").split(/\r?\n/),o=[],i,s=()=>{if(!o.length)return;let a=ze(o.join(" "));if(o=[],a.length>=t)return Ml(a,n)};for(let a of r){if(i){if(v(a,i))i=void 0;continue}let c=x(a);if(c){i=c.marker;let u=s();if(u)return u;continue}let p=a.trim();if(!p||Ol(p)){let u=s();if(u)return u;continue}o.push(p)}return s()??""}function Xt(e){let n=(e.split("/").filter(Boolean).at(-1)??e).replace(/\.[^.]+$/,""),r=n.split(".").filter(Boolean),o=r.length>1?r.at(-1):void 0,i=r.length>2?r.slice(1,-1):[];return{name:(r[0]??n).trim(),typeHint:o,qualifiers:i}}var Jt="page";function ji(e,t=Jt){if(S.extname(e)!==".md")return e;let n=e.slice(0,-3),{typeHint:r}=Xt(e);return r?n:`${n}.${t}`}function Pe(e,t){if(typeof t.id==="string"&&t.id.trim())return t.id.trim();let n=typeof t.type==="string"&&t.type.trim()?t.type.trim():Jt;return ji(e,n)}function se(e,t,n){let{data:r,body:o}=Z(t,n),{name:i,typeHint:s,qualifiers:a}=Xt(e),c=typeof r.type==="string"&&r.type.trim()?r.type.trim():void 0,p=s??c??Jt,u=[];return{id:Pe(e,r),path:e,name:i,type:p,qualifiers:a,data:r,links:[],headings:[],fences:[],get lists(){return u.flatMap((l)=>l.lists)},get tasks(){return u.flatMap((l)=>l.tasks)},content:t,body:o,blocks:u}}function Li(e){let t=new Map,n=[],r=[];for(let o of e.blocks){for(let i of o.links)if(!t.has(i.href))t.set(i.href,i);n.push(...o.headings),r.push(...o.fences)}e.links=[...t.values()],e.headings=_t(n),e.fences=r}function or(e,t){let n=G(e.body).map((r,o)=>dt(e,o,r,{},t));e.blocks.splice(0,e.blocks.length,...n),Li(e)}function Bi(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0&&t!==""))}function he(e,t){let n=Bi(e);if(!Object.keys(n).length)return"";return`---
11
- ${t.stringify(n).trimEnd()}
12
- ---
13
- `}function mt(e,t){let n=Bi({...e.data,...e.id?{id:e.id}:{},...e.type?{type:e.type}:{}}),r=Object.keys(n).length?`<!--
14
- ${t.stringify(n).trimEnd()}
15
- -->`:"",o=(e.body??"").trim();return[r,o].filter(Boolean).join(`
16
-
17
- `)}function ir(e,t,n){let{data:r,body:o}=Z(e,n),i=G(o);return i.push(mt(t,n)),pr(r,i,n)}function Ll(e,t){if(!t)return 0;let n=e.findIndex((r)=>new RegExp(`(?:^|\\n)type:\\s*${t}\\s*$`,"m").test(r)||r.includes(`<${t}`));return n===-1?e.length:n}function sr(e,t,n){let{data:r,body:o}=Z(e,n),i=G(o);return i.splice(Ll(i,t.type),0,mt(t,n)),`${he(r,n)}${i.join(`
18
-
19
- ---
20
-
21
- `)}
22
- `}function ar(e,t,n=[]){let r=he(e,t);if(!n.length)return r;let o=n.map((i)=>mt(i,t)).join(`
23
-
24
- ---
25
-
26
- `);return`${r}${r?`
27
- `:""}${o}
28
- `}function cr(e,t,n){let{data:r,body:o}=Z(e,n);return`${he({...r,...t},n)}${o}`}function Bl(e,t,n){let{data:r}=fe(e,n);return typeof r.id==="string"&&r.id.trim()?r.id.trim():`block-${t}`}function Ni(e,t,n){let r=e.findIndex((o,i)=>Bl(o,i,n)===t);if(r===-1)throw Error(`Block not found: ${t}`);return r}function pr(e,t,n){let r=he(e,n);if(!t.length)return r;return`${r}${t.join(`
29
-
30
- ---
31
-
32
- `)}
33
- `}function ur(e,t,n,r){let{data:o,body:i}=Z(e,r),s=G(i),a=Ni(s,t,r),c=fe(s[a],r),{id:p,type:u,...l}=c.data,d={...typeof p==="string"?{id:p}:{},...typeof u==="string"?{type:u}:{},data:l,body:c.body},m=typeof n==="function"?n(d):n;return s[a]=mt({id:m.id??d.id,type:m.type??d.type,data:{...d.data,...m.data},body:m.body!==void 0?m.body:c.body},r),pr(o,s,r)}function lr(e,t,n){let{data:r,body:o}=Z(e,n),i=G(o),s=Ni(i,t,n);return i.splice(s,1),pr(r,i,n)}var zi=/\{\{\s*([A-Za-z_][\w-]*(?:\.[A-Za-z_][\w-]*)*)\s*\}\}/g;function qi(e,t){let n=e;for(let r of t.split(".")){if(!n||typeof n!=="object"||Array.isArray(n))return"";n=n[r]}if(typeof n==="string"||typeof n==="number"||typeof n==="boolean")return String(n);return""}function Nl(e,t){return e.replace(zi,(n,r)=>g(qi(t,r)))}function _(e,t){return e.replace(zi,(n,r)=>qi(t,r))}function dr(e,t){let n=e.split(/\r?\n/),r=[],o;for(let i of n){if(o){if(r.push(i),v(i,o))o=void 0;continue}let s=x(i);if(s){o=s.marker,r.push(i);continue}r.push(Nl(i,t))}return r.join(`
34
- `)}var Vi=new WeakMap,Hi=new WeakMap;function zl(e,t){let n=t.trim();if(!n||n.startsWith("/")||n.startsWith("#")||n.startsWith("?")||/^(?:\/\/|[a-z][a-z0-9+.-]*:)/i.test(n))return n;return S.resolve(S.dirname(e),n)}function ql(e){let t=_(e.body,e.data);return de(t).find((n)=>n.kind==="image")?.href??e.links.find((n)=>n.kind==="image")?.href??""}function mr(e){return typeof e==="string"&&e.trim()?e.trim():void 0}function Fi(e,t,n=""){let r=ze(e.headings[0]?.text??""),o=(s)=>_(s,e.data).trim(),i=o(mr(e.data.image)??ql(e));return{title:o(mr(e.data.title)??(r||n)),description:o(mr(e.data.description)??rr(e.body)),image:i?zl(t,i):""}}function te(e){let t=Vi.get(e);if(t)return t;let n=Fi(e,e.path,e.name);if(!n.title)n.title=e.name;return Vi.set(e,n),n}function fr(e,t){let n=Hi.get(e);if(n)return n;let r=Fi(e,t.path);return Hi.set(e,r),r}class Gt extends Error{constructor(e){super(`Invalid canonical path: ${e}`);this.name="CanonicalPathError"}}function Q(e){if(!e.startsWith("/")||e.includes("\\")||e.includes("\x00")||e.includes("?")||e.includes("#")||e.length>1&&e.endsWith("/"))throw new Gt(e);if(e==="/")return e;if(e.slice(1).split("/").some((n)=>!n||n==="."||n===".."))throw new Gt(e);return e}function Y(e){let t=Q(e);if(t==="/"||t.endsWith(".md"))throw new Gt(e);return t}function Ui(e){try{return Q(e)}catch{return}}var Vl=/^[a-z0-9][a-z0-9._-]*$/;function K(e){return e.type==="user"||e.type==="agent"&&e.data.actor===!0}class M extends R{sourceId;constructor(e,t){super({source:e.path,plugin:"actors",message:`Invalid Actor Source ${e.id}: ${t}`});this.name="ActorSourceError",this.sourceId=e.id}}function Qi(e){return e.trim().toLowerCase()}function Hl(e,t){let n=e.data[t];if(typeof n!=="string"||!n.trim())throw new M(e,`${t} is required`);return n.trim()}function _i(e,t){let n=e.data[t];if(n==null||n==="")return;if(typeof n!=="string"||!n.trim())throw new M(e,`${t} must be a non-empty string`);return n.trim()}function Fl(e,t){let n=e.data[t];if(!Array.isArray(n)||!n.length)throw new M(e,`${t} must be a non-empty list`);let r=n.map((o)=>typeof o==="string"?o.trim():"");if(r.some((o)=>!o))throw new M(e,`${t} must contain only strings`);return r}function Ul(e){let t=_i(e,"username")??e.name;if(!Vl.test(t))throw new M(e,`invalid username: ${t}`);let n=_i(e,"avatar");return Object.freeze({name:Hl(e,"name"),username:t,...n?{avatar:n}:{}})}function _l(e){let t=`.${e.type}`;if(!e.id.endsWith(t))throw new M(e,`id must end in ${t} so its Home can be derived`);return e.id.slice(0,-t.length)}function Ql(e){let t=Ul(e),n={id:e.id,profile:t,home:_l(e)};if(e.type==="agent")return{actor:Object.freeze({...n,type:"agent"}),emails:[]};if(e.type!=="user")throw new M(e,`unsupported Actor type: ${e.type}`);let r=e.data.role,o=r==null||r===""?"member":r;if(o!=="member"&&o!=="staff")throw new M(e,"role must be member or staff");let i=Fl(e,"emails").map(Qi);if(new Set(i).size!==i.length)throw new M(e,"emails must be unique");return{actor:Object.freeze({...n,type:"user",role:o}),emails:i}}class hr{actors=new Map;usernames=new Map;emails=new Map;homes=new Map;sourceActors=new Map;actorEmails=new Map;profiles=Object.freeze({findById:(e)=>this.profileRef(this.actors.get(e)),findByUsername:(e)=>this.profileRef(this.usernames.get(e))});findActorById(e){return this.actors.get(e)}findHomeOwner(e){let t=e.replace(/\/+$/,"")||"/";while(t){let n=this.homes.get(t);if(n)return n;let r=t.lastIndexOf("/");if(r<=0)return this.homes.get("/");t=t.slice(0,r)}}findById(e){return this.profileRef(this.actors.get(e))}findByUsername(e){return this.profileRef(this.usernames.get(e))}findUserByEmail(e){return this.emails.get(Qi(e))}credentialUsers(){return this.all().filter((e)=>e.type==="user").map((e)=>({actor:e,emails:this.actorEmails.get(e.id)??[]}))}all(){return[...this.actors.values()].sort((e,t)=>e.id.localeCompare(t.id))}index(e){if(!K(e))return;let{actor:t,emails:n}=Ql(e);if(this.actors.get(t.id))throw new M(e,`duplicate Actor id: ${t.id}`);if(this.usernames.get(t.profile.username))throw new M(e,`duplicate username: ${t.profile.username}`);if(this.homes.has(t.home))throw new M(e,`duplicate Home: ${t.home}`);for(let i of n)if(this.emails.has(i))throw new M(e,`duplicate normalized email: ${i}`);if(this.actors.set(t.id,t),this.usernames.set(t.profile.username,t),this.homes.set(t.home,t),this.sourceActors.set(e.path,t.id),this.actorEmails.set(t.id,n),t.type==="user")for(let i of n)this.emails.set(i,t)}unindex(e){let t=this.sourceActors.get(e);if(!t)return;let n=this.actors.get(t);if(this.sourceActors.delete(e),this.actors.delete(t),n)this.usernames.delete(n.profile.username);if(n)this.homes.delete(n.home);for(let r of this.actorEmails.get(t)??[])this.emails.delete(r);this.actorEmails.delete(t)}profileRef(e){return e?{id:e.id,profile:e.profile}:void 0}}function Wi(e){return{id:"actors",name:"ActorDirectoryPlugin",schema:{sources:{user:{label:"User",icon:"circle-user",color:"blue"},agent:{label:"Agent",icon:"bot",color:"purple"}}},index(t){e.index(t)},unindex(t){e.unindex(t)},invalidate(t){let n=new Set;if(t.before&&K(t.before))n.add(t.before.id);if(t.after&&K(t.after))n.add(t.after.id);return n.size?{targets:[{type:"actor",actors:n}]}:void 0}}}var Xi=new WeakMap;function L(e){return e.name==="index"}function Re(e){return e.type!=="layout"&&e.type!=="navigation"&&!K(e)}function Yt(e){let t=e.path.lastIndexOf("/");return t<=0?"/":e.path.slice(0,t)}function y(e){if(Re(e)&&L(e))return Yt(e);return e.id}function Wl(e,t){return e.atPath(t)??e.get(Pe(t,{}))}function Xl(e){let t;try{t=decodeURIComponent(e)}catch{return}return Ui(t||"/")}function qe(e,t){let n=Xl(t);if(!n)return;if(n.endsWith(".md")){let i=Wl(e,n);return i?{type:"source",source:i}:void 0}let r=e.get(Pe(n,{}));if(r&&Re(r)&&r.id===n)return{type:"page",source:r};let o=Jl(e,n)[0];if(o)return{type:"page",source:o}}function Jl(e,t){return Ji(e).byDirectory.get(t)??[]}function Gl(e){return e.sort((t,n)=>t.id<n.id?-1:t.id>n.id?1:0)}function Ji(e){let t=Xi.get(e);if(t?.revision===e.revision)return t;let n=new Map;for(let o of e.all()){if(!Re(o)||!L(o))continue;let i=Yt(o),s=n.get(i);if(s)s.push(o);else n.set(i,[o])}for(let o of n.values())Gl(o);let r={revision:e.revision,byDirectory:n};return Xi.set(e,r),r}function Gi(e){let t=[],{byDirectory:n}=Ji(e);for(let r of[...n.keys()].sort()){let o=n.get(r);if(o.length>1)t.push({dir:r,winner:o[0],shadowed:o.slice(1)})}return t}function Yl(e){let t=e.indexOf("#"),n=t===-1?e:e.slice(0,t),r=n.indexOf("?");return{pathname:r===-1?n:n.slice(0,r),query:r===-1?void 0:n.slice(r+1),fragment:t===-1?void 0:e.slice(t+1)}}class gr{repository;nodes=new Map;outgoing=new Map;incoming=new Map;constructor(e){this.repository=e}async rebuild(){this.nodes.clear(),this.outgoing.clear(),this.incoming.clear();for(let e of this.repository.all())await this.indexSource(e)}async indexSource(e){await this.indexNode(e);for(let t of e.blocks)this.nodes.set(t.path,t)}linksFrom(e){return this.outgoing.get(e)??[]}linksTo(e){return this.incoming.get(e)??[]}unresolvedLinks(){return[...this.outgoing.values()].flat().filter((e)=>e.type==="unresolved")}neighbors(e){return this.linksFrom(e).map((t)=>t.to?this.nodes.get(t.to):void 0).filter((t)=>t!=null)}backlinks(e){return this.linksTo(e).map((t)=>this.nodes.get(t.from)).filter((t)=>t!=null)}async indexNode(e){this.nodes.set(e.path,e);let t=[];for(let n of e.links){let r=await this.resolveLink(e,_(n.href,e.data)),o={from:e.path,href:n.href,type:r.type,label:n.label,directive:n.directive,to:r.targetPath,fragment:r.fragment};if(t.push(o),o.type==="source"&&o.to)this.addIncoming(o.to,o)}this.outgoing.set(e.path,t)}pageSourceAt(e){let t=qe(this.repository,e);return t?.type==="page"?t.source:void 0}addIncoming(e,t){let n=this.incoming.get(e);if(n)n.push(t);else this.incoming.set(e,[t])}async resolveLink(e,t){if(le(t))return{type:"external"};if(t.startsWith("~/"))return{type:"actor-relative"};let{pathname:n,query:r,fragment:o}=Yl(t);if(!n&&(r!==void 0||o!==void 0))return{type:"fragment",targetPath:e.path,fragment:o};if(!n)return{type:"unresolved"};let i=n.startsWith("/")?this.repository.environment.path.normalize(n):this.repository.environment.path.join(this.repository.environment.path.dirname(e.path),n),s=this.repository.atPath(i)??this.pageSourceAt(i);if(s)return{type:"source",targetPath:s.path,fragment:o};if(await this.repository.isFile(i))return{type:"asset",targetPath:i,fragment:o};return{type:"unresolved",targetPath:i,fragment:o}}}var Yi={debug:10,info:20,warn:30,error:40};function Ki(e){if(e==="debug"||e==="info"||e==="warn"||e==="error")return e;return"info"}function Kl(e){let t=new Date(e.time).toISOString(),n=e.context?Object.entries(e.context).filter(([,r])=>r!==void 0).map(([r,o])=>`${r}=${String(o)}`).join(" "):"";return n?`${t} ${e.level} ${e.message} ${n}`:`${t} ${e.level} ${e.message}`}function Zl(e){let t=Kl(e);if(e.level==="error")console.error(t);else if(e.level==="warn")console.warn(t);else console.log(t)}class B{level;sink;records=[];limit;constructor(e){this.level=e?.level??"info",this.sink=e?.sink??Zl,this.limit=e?.limit??1000}write(e,t,n){let r={time:Date.now(),level:e,message:t,context:n};if(this.records.push(r),this.records.length>this.limit)this.records.shift();if(Yi[e]>=Yi[this.level])this.sink(r)}debug(e,t){this.write("debug",e,t)}info(e,t){this.write("info",e,t)}warn(e,t){this.write("warn",e,t)}error(e,t){this.write("error",e,t)}}class yr{records=new Map;measure(e,t,n){let r=performance.now();try{return t()}finally{this.add(e,performance.now()-r,n)}}async measureAsync(e,t,n){let r=performance.now();try{return await t()}finally{this.add(e,performance.now()-r,n)}}record(e,t,n){this.add(e,t,n)}snapshot(){return[...this.records.values()]}format(){let e=this.snapshot();if(!e.length)return"";let t=Math.max(...e.map((r)=>r.name.length)),n=Math.max(...e.map((r)=>String(r.count).length));return e.map((r)=>{let o=r.name.padEnd(t),i=`n=${r.count}`.padEnd(n+2),s=`${r.totalMs.toFixed(1)} ms`,a=`max=${r.maxMs.toFixed(1)} ms`,c=r.maxLabel?` ${r.maxLabel}`:"";return`${o} ${i} ${s} ${a}${c}`}).join(`
35
- `)}reset(){this.records.clear()}add(e,t,n){let r=this.records.get(e);if(!r){this.records.set(e,{name:e,count:1,totalMs:t,maxMs:t,lastMs:t,maxLabel:n});return}if(r.count+=1,r.totalMs+=t,r.lastMs=t,t>=r.maxMs)r.maxMs=t,r.maxLabel=n}}function Kt(e){if(e==null||typeof e!=="object"&&typeof e!=="function")return!1;let t=e["~standard"];if(t==null||typeof t!=="object")return!1;let n=t;return n.version===1&&typeof n.validate==="function"}function ed(e){if(e==null||typeof e!=="object"&&typeof e!=="function")return!1;let t=e["~standard"]?.jsonSchema;return t!=null&&typeof t.input==="function"&&typeof t.output==="function"}function td(e){return e!=null&&typeof e==="object"&&!Array.isArray(e)}var wr=new WeakMap;function W(e,t,n){if(!Kt(e)||!ed(e))throw Error(`${n} must implement Standard Schema and Standard JSON Schema v1.`);let r=wr.get(e)?.[t];if(r)return r;let o;try{o=e["~standard"].jsonSchema[t]({target:"draft-2020-12"})}catch(a){let c=a instanceof Error?a.message:String(a);throw Error(`${n} ${t} JSON Schema failed: ${c}`)}if(!td(o))throw Error(`${n} ${t} JSON Schema must be an object.`);let i=Object.freeze(o),s=wr.get(e)??{};return s[t]=i,wr.set(e,s),i}function xr(e,t){let n=e?.["~standard"]?.jsonSchema?.[t];if(!n)return;try{return Object.freeze(n({target:"draft-2020-12"}))}catch{return}}function q(e){return e.map((t)=>{let n=t.path?.map((r)=>String(typeof r==="object"?r.key:r)).join(".");return n?`${n}: ${t.message}`:t.message}).join("; ")}class k extends R{sourceId;detail;constructor(e,t){super({source:e.path,plugin:"source-access",message:`Invalid shared access on ${e.id}: ${t}`});this.name="SourceAccessError",this.sourceId=e.id,this.detail=t}}class ne extends Error{code;constructor(e="access-denied"){super("Source access denied.");this.name="AccessDeniedError",this.code=e}}function rs(e){return e!=null&&typeof e==="object"&&!Array.isArray(e)?e:void 0}var Ce={read:1,write:2,execute:4},ye=Ce.read,vr=Ce.write,os=Ce.execute,nd=ye|vr|os,rd=Object.freeze(["read","write","execute"]);function od(e){return rd.filter((t)=>e&Ce[t])}function id(e){return e}function ae(e,t,n){return{visibility:"denied",capabilities:0,basis:n?.({type:"denied",sourceId:e,reason:t})}}function sd(e){return typeof e==="string"&&Object.hasOwn(Ce,e)}function ad(e,t,n){if(!Array.isArray(e)||!e.length)throw new k(t,`member ${n} must declare a non-empty can list`);let r=0;for(let o of e){if(!sd(o))throw new k(t,`member ${n} has an invalid capability: ${String(o)}`);let i=Ce[o];if(r&i)throw new k(t,`member ${n} capabilities must be unique`);r|=i}if(!(r&ye))throw new k(t,`member ${n} must be readable`);return r}function cd(e,t){let n=rs(t);if(!n)throw new k(e,"members must contain actor capability grants");let r=typeof n.actor==="string"?n.actor.trim():"";if(!r)throw new k(e,"member actor is required");try{Y(r)}catch{throw new k(e,"member actor must be a canonical Source id")}return Object.freeze({actor:r,capabilities:ad(n.can,e,r)})}function br(e,t){return e.capabilitiesByActor.get(t)??0}function Zi(e){if(e.data.access==null)return;let t=rs(e.data.access);if(!t||t.type!=="shared")throw new k(e,"access.type must be shared");let n=typeof t.owner==="string"?t.owner.trim():"";if(!n)throw new k(e,"owner is required");if(!Array.isArray(t.members)||!t.members.length)throw new k(e,"members must be a non-empty list");let r=t.members.map((s)=>cd(e,s)),o=r.map((s)=>s.actor);try{Y(n)}catch{throw new k(e,"owner must be a canonical Source id")}if(new Set(o).size!==o.length)throw new k(e,"members must be unique");if(!o.includes(n))throw new k(e,"owner must also be a member");if(!((r.find((s)=>s.actor===n)?.capabilities??0)&vr))throw new k(e,`owner ${n} must be writable`);return Object.freeze({type:"shared",owner:n,members:Object.freeze(r),capabilitiesByActor:new Map(r.map((s)=>[s.actor,s.capabilities]))})}function Zt(e){let t=e.data.attachments;if(t==null)return[];if(!Array.isArray(t))throw new k(e,"attachments must be a list");let n=t.map((r)=>typeof r==="string"?r.trim():"");if(n.some((r)=>!r))throw new k(e,"attachments must contain paths");try{for(let r of n)if(Q(r),r.endsWith(".md"))throw Error()}catch{throw new k(e,"attachments must be canonical non-Source paths")}if(new Set(n).size!==n.length)throw new k(e,"attachments must be unique");return n}function es(e,t){return e===t||e.startsWith(`${t}/`)}function Sr(e){let t=e.split("/").filter(Boolean);return t.length>=3&&(t[0]==="users"||t[0]==="agents")}function ts(e,t){return JSON.stringify(e.data.access)===JSON.stringify(t.data.access)}function ns(e,t){return JSON.stringify(e.data.attachments)===JSON.stringify(t.data.attachments)}function pd(e,t){let{attachments:n,...r}=e.data,{attachments:o,...i}=t.data;return e.id===t.id&&e.body===t.body&&JSON.stringify(r)===JSON.stringify(i)}var ge=Object.freeze({type:"allowed"});function E(e){return{type:"denied",code:e}}class kr{repo;actors;sharedById=new Map;sourcePaths=new Map;actorSources=new Map;invalidIds=new Set;invalidMessages=new Map;attachments=new Map;sourceAttachments=new Map;constructor(e,t){this.repo=e;this.actors=t}index(e){try{let t=Zt(e);for(let r of t){let o=this.attachments.get(r);if(o&&o!==e.id)throw new k(e,`attachment already belongs to ${o}: ${r}`)}for(let r of t)this.attachments.set(r,e.id);if(t.length)this.sourceAttachments.set(e.id,t);if(t.length||e.data.access!=null)this.sourcePaths.set(e.path,e.id);if(e.data.access==null)return;let n=Zi(e);if(!n)return;this.sharedById.set(e.id,n),this.sourcePaths.set(e.path,e.id),this.invalidIds.delete(e.id),this.invalidMessages.delete(e.id);for(let{actor:r}of n.members){let o=this.actorSources.get(r)??new Set;o.add(e.id),this.actorSources.set(r,o)}}catch(t){throw this.invalidIds.add(e.id),this.invalidMessages.set(e.id,t instanceof k?t.detail:t instanceof Error?t.message:String(t)),this.sourcePaths.set(e.path,e.id),t}}unindex(e){let t=this.sourcePaths.get(e);if(!t)return;let n=this.sharedById.get(t);if(n)for(let{actor:r}of n.members){let o=this.actorSources.get(r);if(o?.delete(t),!o?.size)this.actorSources.delete(r)}for(let r of this.sourceAttachments.get(t)??[])this.attachments.delete(r);this.sourceAttachments.delete(t),this.sharedById.delete(t),this.sourcePaths.delete(e),this.invalidIds.delete(t),this.invalidMessages.delete(t)}validate(){let e=this.diagnostics()[0];if(e){let t=this.repo.get(e.sourceId);if(t)throw new k(t,e.message)}}diagnostics(){let e=[...this.invalidMessages].map(([t,n])=>({sourceId:t,message:n}));for(let[t,n]of this.sharedById){if(!this.actors.findActorById(n.owner)){e.push({sourceId:t,message:`owner does not resolve: ${n.owner}`});continue}for(let r of n.members)if(!this.actors.findActorById(r.actor))e.push({sourceId:t,message:`member does not resolve: ${r.actor}`})}return e.sort((t,n)=>t.sourceId.localeCompare(n.sourceId)||t.message.localeCompare(n.message))}sharedSourcesFor(e){return[...this.actorSources.get(e)??[]]}sourceForId(e){return this.repo.get(e)}resolvedAccess(e,t,n=!1){let r=n?id:void 0,o=typeof t==="string"?this.sourceFor(t):t,i;try{i=o?.id??Q(typeof t==="string"?t:t.id)}catch{return ae(String(typeof t==="string"?t:t.id),"unknown-source",r)}if(!o){let u=this.attachments.get(i),l=u?this.repo.get(u):void 0;if(l)return this.resolvedAccess(e,l,n)}if(this.invalidIds.has(i))return ae(i,"invalid-access",r);if(o&&K(o))return ae(i,"actor-source",r);let s=e.type==="actor"&&this.actors.findActorById(e.actor.id)===e.actor?e.actor:void 0,a=this.sharedById.get(i);if(a){if(!this.actors.findActorById(a.owner))return ae(i,"invalid-access",r);if(!s)return ae(i,e.type==="actor"?"stale-actor":"authentication-required",r);let u=br(a,s.id);if(u)return{visibility:"private",capabilities:u,basis:r?.({type:"exact-grant",sourceId:i,actorId:s.id,owner:a.owner===s.id})};if(s.type==="user"&&s.role==="staff")return{visibility:"private",capabilities:ye,basis:r?.({type:"staff-review",sourceId:i,actorId:s.id})};return ae(i,"not-granted",r)}let c=o?.id??i,p=this.homeOwner(c);if(p){if(!s)return ae(i,e.type==="actor"?"stale-actor":"authentication-required",r);if(s.id===p.id)return{visibility:"private",capabilities:nd,basis:r?.({type:"home-owner",sourceId:i,actorId:s.id,home:p.home})};if(s.type==="user"&&s.role==="staff")return{visibility:"private",capabilities:ye,basis:r?.({type:"staff-review",sourceId:i,actorId:s.id})};return ae(i,"private-home",r)}if(Sr(c))return ae(i,"private-home",r);return{visibility:"public",capabilities:s?ye|os:ye,basis:r?.({type:"public-source",sourceId:i})}}readAccess(e,t){let n=this.resolvedAccess(e,t);if(!(n.capabilities&ye))return"denied";return n.visibility}inspect(e,t){let n=this.resolvedAccess(e,t,!0);if(!n.basis)throw Error("Permission inspection basis missing");return{visibility:n.visibility,capabilities:od(n.capabilities),basis:n.basis}}hasCapability(e,t,n){let r=this.resolvedAccess(e,t);return Boolean(r.capabilities&Ce[n])}authorizeChange(e,t){if(this.actors.findActorById(e.id)!==e)return E("actor-not-current");if(t.type==="create")return this.authorizeCreate(e,t.after);let n=this.accessFromSource(t.before);if(t.type==="delete"){if(n)return n.owner===e.id?ge:E("shared-delete-owner-only");return this.ownsHome(e,t.before.id)?ge:E("home-owner-only")}if(t.operation==="grants"){if(!ns(t.before,t.after))return E("attachment-change-requires-attachment-operation");let r=this.validShared(t.after),o=n?.owner??e.id;if(o!==e.id||r.owner!==o)return E("shared-grants-owner-only");return this.membersResolve(r)?ge:E("shared-member-not-found")}if(t.operation==="attachments"){if(!ts(t.before,t.after)||!pd(t.before,t.after))return E("attachment-operation-may-only-change-attachments");if(Zt(t.after),!this.attachmentsAvailable(t.after))return E("attachment-already-bound");if(n)return n.owner===e.id?ge:E("shared-attachment-owner-only");return this.ownsHome(e,t.before.id)?ge:E("home-owner-only")}if(!ts(t.before,t.after))return E("access-change-requires-grants-operation");if(!ns(t.before,t.after))return E("attachment-change-requires-attachment-operation");return this.hasCapability({type:"actor",actor:e},t.before,"write")?ge:E("source-write-required")}canEmbed(e,t){let n=this.sourceFor(e),r=this.sourceFor(t);if(!n||!r)return!1;if(K(r))return!1;let o=this.sharedById.get(n.id),i=this.sharedById.get(r.id);if(o){if(!i)return!this.homeProtected(r.id);return o.members.every((a)=>Boolean(br(i,a.actor)&ye))}let s=this.homeOwner(n.id);if(s){if(!this.homeProtected(r.id))return!i;return es(r.id,s.home)}if(Sr(n.id))return!1;return!i&&!this.homeProtected(r.id)}authorizeCreate(e,t){if(Zt(t),!this.attachmentsAvailable(t))return E("attachment-already-bound");let n=this.accessFromSource(t);if(n){if(n.owner!==e.id||!(br(n,e.id)&vr))return E("shared-create-owner-required");return this.membersResolve(n)?ge:E("shared-member-not-found")}return this.ownsHome(e,t.id)?ge:E("home-owner-only")}membersResolve(e){return e.members.every((t)=>this.actors.findActorById(t.actor))}attachmentsAvailable(e){return Zt(e).every((t)=>{let n=this.attachments.get(t);return n==null||n===e.id})}validShared(e){let t=Zi(e);if(!t)throw new k(e,"shared access is required");return t}accessFromSource(e){return e.data.access==null?void 0:this.validShared(e)}sourceFor(e){return this.repo.get(e)??this.repo.atPath(e)}homeOwner(e){return this.actors.findHomeOwner(e)}homeProtected(e){return this.homeOwner(e)!=null||Sr(e)}ownsHome(e,t){return es(t,e.home)}}function is(e){return{id:"source-access",name:"SourceAccessPlugin",index(t){e.index(t)},unindex(t){e.unindex(t)},lint(t){for(let n of e.diagnostics()){let r=e.sourceForId(n.sourceId);if(!r)continue;t(r,`Invalid shared access on ${r.id}: ${n.message}`)}},invalidate(t){let n=[],r=new Set;for(let o of[t.before,t.after]){if(!o)continue;if(o.data.access!=null||o.data.attachments!=null)r.add(y(o));if(K(o))for(let i of e.sharedSourcesFor(o.id)){let s=e.sourceForId(i);if(s)r.add(y(s))}}for(let o of r)n.push({type:"route",route:o});return n.length?{targets:n}:void 0}}}function ss(e,t,n){let r=!1,o=[],i=(a)=>{let c=a;for(let p of o)if(p.type==="data")c=cr(c,p.patch,n);else if(p.type==="append")c=ir(c,p.block,n);else if(p.type==="prepend")c=sr(c,p.block,n);else if(p.type==="update")c=ur(c,p.id,p.update,n);else c=lr(c,p.id,n);return c},s={path:e,create(){return r=!0,s},data(a){return o.push({type:"data",patch:a}),s},appendBlock(a){return o.push({type:"append",block:a}),s},prependBlock(a){return o.push({type:"prepend",block:a}),s},updateBlock(a,c){return o.push({type:"update",id:a,update:c}),s},removeBlock(a){return o.push({type:"remove",id:a}),s},async flush(){if(r){await t.create(e,i(ar({},n)));return}await t.update(e,i(await t.read(e)))}};return s}function ud(e,t){let n=e.repo,r=new Map,o=new Map,i=(l)=>{let d=Y(l);return n.get(d)?.path??`${d}.md`},s=async(l)=>{if(!t.readable(l))return!1;if(r.has(l))return r.get(l)!==null;return Boolean(n.atPath(l)??n.get(n.pathToId(l)))},a=async(l)=>{if(!t.readable(l))throw new ne;if(r.has(l)){let m=r.get(l);if(m==null)throw Error(`Path does not exist: ${l}`);return m}let d=n.atPath(l)??n.get(n.pathToId(l));if(d)return d.content;throw Error(`Path does not exist: ${l}`)},c=async(l,d)=>{if(await s(l))throw Error(`Path already exists: ${l}`);r.set(l,d)},p=async(l,d)=>{if(!t.readable(l))throw new ne;if(!await s(l))throw Error(`Path does not exist: ${l}`);r.set(l,d)};return{create(l,d){return c(i(l),d)},update(l,d){return p(i(l),d)},async delete(l){let d=i(l);if(!t.readable(d))throw new ne;if(!await s(d))throw Error(`Path does not exist: ${d}`);r.set(d,null)},read(l){return a(i(l))},exists(l){return s(i(l))},source(l){let d=i(l),m=o.get(d);if(!m)m=ss(d,{create:c,update:p,read:a},e.environment.yaml),o.set(d,m);return m},async changeSet(){for(let d of o.values())await d.flush();let l=[];for(let[d,m]of r){let f=n.atPath(d),h=f?.id??n.pathToId(d),w=m==null?f?{type:"delete",sourceId:h,before:f}:void 0:(()=>{let T=se(d,m,e.environment.yaml);if(!f)return{type:"create",sourceId:T.id,after:T};return{type:"update",operation:"content",sourceId:f.id,before:f,after:T}})();if(!w)throw Error(`Path does not exist: ${h}`);if(t.authorize(w),m==null)l.push({type:"delete",path:d});else l.push({type:f?"replace":"create",path:d,content:m})}return r.clear(),o.clear(),{changes:l}}}}function Ve(e,t){return ud(e,{readable(n){return e.readAccess({type:"actor",actor:t},e.repo.atPath(n)??e.repo.pathToId(n))!=="denied"},authorize(n){let r=e.authorizeChange(t,n);if(r.type==="denied")throw new ne(r.code)}})}function cs(e){return U(e,"actions")}class ft extends Error{constructor(e){super(`Action not found: ${e}`);this.name="ActionNotFoundError"}}class en extends Error{issues;constructor(e){super(q(e));this.name="ActionValidationError",this.issues=e}}class we extends Error{constructor(e,t){super(t??`Action unavailable: ${e}`);this.name="ActionUnavailableError"}}function Pr(e,t){if(t)return Object.assign(t,{input:e});let n=e;return Object.assign(n.execute,{title:n.title,...n.description?{description:n.description}:{},...n.input?{input:n.input}:{},...n.output?{output:n.output}:{},...n.affordance?{affordance:n.affordance}:{},...n.authorize?{authorize:n.authorize}:{}})}function ld(e){if(e===!1)return;if(e===!0)return{};if(typeof e==="string")return{status:"unavailable",reason:e};return e}async function ps(e,t){if(!e.affordance)return Object.freeze({declared:!1,description:void 0});return Object.freeze({declared:!0,description:ld(await e.affordance(t))})}async function us(e,t,n){if(!t.title||!t.affordance)return;let{description:r}=await ps(t,n);if(!r)return;let o=xr(t.input,"input"),i=xr(t.output,"output");return Object.freeze({type:"action",id:e,rel:r.rel??e,title:r.title??t.title,...r.description??t.description?{description:r.description??t.description}:{},method:"post",href:`/actions/${e}`,target:Object.freeze({type:"source",id:n.target.id}),...o?{input:o}:{},...i?{output:i}:{},...r.boundInput?{boundInput:Object.freeze({...r.boundInput})}:{},status:r.status??"available",...r.reason?{reason:r.reason}:{}})}async function as(e,t){let n=e["~standard"].validate(t);if(n instanceof Promise)n=await n;if(n.issues)throw new en(n.issues);return n.value}async function ls(e,t,n,r,o){let i=e.pluginAction(t)??await dd(e,t);e.log.info("action",{name:t,actor:r.id,target:o?.id});let s=void 0,a=await e.commitPrepared(async()=>{let c=o?e.repo.atPath(o.path):void 0;if(o&&!c)throw new we(t);let p;if(c){let h={type:"actor",actor:r};if(!e.hasSourceCapability(h,c,"execute"))throw new we(t);let w=await ps(i,{principal:h,target:c,yaml:e.environment.yaml,can:(T)=>e.hasSourceCapability(h,c,T)});if(w.declared&&!w.description)throw new we(t);if(w.description?.status==="unavailable")throw new we(t,w.description.reason);p=w.description?.boundInput}let u={...n,...p??{}},l=Kt(i.input)?await as(i.input,u):u,d=Ve(e,r),m={actor:r,tx:d,target:c,yaml:e.environment.yaml},f=await i.authorize?.(m);if(f===!1||typeof f==="string")throw new we(t,typeof f==="string"?f:void 0);if(s=await i(l,m),Kt(i.output))s=await as(i.output,s);return d.changeSet()});return Object.freeze({value:s,commit:a})}async function dd(e,t){if(!/^[a-z0-9-]+$/.test(t))throw new ft(t);let r=`${e.actionsRoot.replace(/\/+$/,"")}/${t}.action.ts`,o=await e.environment.loadModule(r);if(typeof o?.default!=="function")throw new ft(t);return o.default}class ht extends Error{constructor(e="Agent job admission denied."){super(e);this.name="AgentAdmissionError"}}async function ds(e,t,n,r){let{agentId:o,targetId:i,operationId:s}=n;if(!s.trim())throw new ht;let a=t.findActorById(o);if(!a||a.type!=="agent")throw new ht;return e.commitPrepared(async()=>{let c=e.repo.get(i);if(!c)throw new ht;let p={type:"actor",actor:a};if(e.readAccess(p,c)==="denied")throw new ht;if(c.blocks.some((m)=>m.data.operation_id===s))return{changes:[]};let u=Ve(e,a),l=u.source(c.id);await r({actor:a,principal:p,sourceId:c.id,appendBlock(m){l.appendBlock({...m,data:{...m.data,operation_id:s}})},updateBlock(m,f){l.updateBlock(m,(h)=>{let w=typeof f==="function"?f(h):f;return{...w,data:{...w.data,operation_id:s}}})}});let d=await u.changeSet();if(d.changes.some((m)=>e.repo.pathToId(m.path)!==c.id))throw new ne("agent-target-only");return d})}function He(e){if(e.type==="meta")return e.attrs.charset!=null?0:2;if(e.type==="title")return 1;if(e.type==="preload")return 3;if(e.type==="stylesheet")return 4;if(e.type==="style")return 5;return 6}function ms(e){if(e.type==="style")return`style:${e.text}`;if(e.type==="script"){if("name"in e&&e.name)return`script:name:${e.name}`;if("source"in e)return`script:source:${e.source}`;return"href"in e?`script:${e.href}`:`script:${e.text}`}if(e.type==="title")return"title";if(e.type==="preload")return`preload:${e.href}:${e.as}`;if(e.type==="meta"){let{charset:t,name:n,property:r}=e.attrs;return`meta:${t!=null?"charset":n??r??JSON.stringify(e.attrs)}:${e.attrs.media??""}`}if("name"in e&&e.name)return`stylesheet:name:${e.name}`;return`stylesheet:${"href"in e?e.href:""}`}function md(e,t){let n=ms(t);if(e.some((r)=>ms(r)===n))return;e.push(Object.freeze(t.type==="meta"?{...t,attrs:Object.freeze({...t.attrs})}:{...t}))}function hs(e=[]){return{assets:e,addAsset(...t){for(let n of t)md(e,n)}}}function fs(e,t){return e.replace(new RegExp(`<\\/${t}`,"gi"),`<\\/${t}`)}function gs(e){return e.map((t)=>{if(t.type==="title")return`<title>${g(t.text)}</title>`;if(t.type==="meta")return`<meta${Object.entries(t.attrs).map(([o,i])=>` ${o}="${g(i)}"`).join("")}>`;if(t.type==="preload"){let r=t.contentType?` type="${g(t.contentType)}"`:"",o=t.crossorigin?" crossorigin":"";return`<link rel="preload" href="${g(t.href)}" as="${g(t.as)}"${r}${o}>`}if(t.type==="stylesheet"){let r="href"in t?t.href:"",o=t.media?` media="${g(t.media)}"`:"";return`<link rel="stylesheet" href="${g(r)}"${o}>`}if(t.type==="style")return`<style>${fs(t.text,"style")}</style>`;let n=t.module?' type="module"':"";if("href"in t)return`<script${n} src="${g(t.href)}"></script>`;if("source"in t)throw Error(`Unresolved authored script asset: ${t.source}`);return`<script${n}>${fs(t.text,"script")}</script>`}).join("")}function tn(e,t){let n=0;for(let r of e.blocks){if(r.id===t.id)return e.headings.slice(n,n+r.headings.length);n+=r.headings.length}return t.headings}var fd=/(<li class="task-list-item"><input type="checkbox" class="task-list-item-checkbox"[^>]*><strong>[\s\S]*?<\/strong>)\r?\n/g;function ys(e){if(!e.includes('class="task-list-item"'))return e;return e.replace(fd,"$1<br>")}function ws(e,t,n){if(!t.length)return e;let r=0;return e.replace(/<h([1-6]) id="([^"]*)">[\s\S]*?<\/h\1>/g,(o,i,s)=>{let a=t[r],c=n[r];if(!a||!c||Number(i)!==c.depth||s!==g(c.id))return o;r++;let p=g(a.id),u=o.replace(`<h${i} id="${s}">`,`<h${i} id="${p}">`);if(!p)return u;return[`<div class="pmx-heading level-h${i}">`,u,`<a class="pmx-heading-anchor" href="#${p}" aria-labelledby="${p}">`,"</a></div>"].join("")})}var Rr='<template data-pathmx-block-flow="">',Cr="</template>";function xs(e){return`${Rr}${e}${Cr}`}function bs(e){let t=e.trim();if(!t.startsWith(Rr)||!t.endsWith(Cr))return;return t.slice(Rr.length,-Cr.length).trim()}function Ar(e,t,n){let r=n?.id??e.id,o=e.type!=="block"?` data-type="${g(e.type)}"`:"";return`<section id="${g(r)}" data-pmx-block data-pmx-block-path="${g(e.path)}" class="pmx-prose"${o}>
36
- ${t.trim()}
37
- </section>`}function Ss(e,t){return`<article class="pmx-document" data-type="${g(e.type)}" data-source="${g(e.id)}">${t}</article>`}var hd=/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/;var Rs=new TextEncoder;function vs(e){return e^=e>>>16,e=Math.imul(e,2246822507),e^=e>>>13,e=Math.imul(e,3266489909),(e^e>>>16)>>>0}class Ir{fnv=2166136261;djb=5381;update(e){for(let t=0;t<e.length;t++){let n=e[t];this.fnv=Math.imul(this.fnv^n,16777619),this.djb=Math.imul(this.djb,33)^n}}digest(){return[vs(this.fnv),vs(this.djb)].map((e)=>e.toString(16).padStart(8,"0")).join("")}}function Cs(e,t){e.update(Rs.encode(t)),e.update(new Uint8Array([0]))}function gd(e,t){let n=new Ir;return Cs(n,t),n.update(Rs.encode(e)),n.digest()}async function gt(e,t){let n=new Ir;Cs(n,t);let r=e.stream().getReader();try{while(!0){let o=await r.read();if(o.done)return n.digest();n.update(o.value)}}finally{r.releaseLock()}}function ks(e){if(!hd.test(e))throw Error(`Invalid generated asset name: ${e}`)}function Ps(e,t){let n=e.lastIndexOf("."),r=n===-1?e:e.slice(0,n),o=n===-1?"":e.slice(n);return`/.pmx/${r}-${t}${o}`}class nn{limit;assets=new Map;latest=new Map;constructor(e=128){this.limit=e}get(e){let t=this.assets.get(e);if(!t)return;return this.assets.delete(e),this.assets.set(e,t),t.asset}entries(){return[...this.assets].map(([e,t])=>[e,t.asset])}publishText(e,t,n){ks(e);let r=this.latest.get(e);if(r?.body===t&&r.contentType===n)return this.get(r.href),r.href;let o=Ps(e,gd(t,n));return this.retain(e,o,{body:t,contentType:n}),o}async publishBlob(e,t,n=t.type){ks(e),n||="application/octet-stream";let r=this.latest.get(e);if(r?.body===t&&r.contentType===n)return this.get(r.href),r.href;let o=Ps(e,await gt(t,n));return this.retain(e,o,{body:t,contentType:n}),o}retain(e,t,n){this.assets.delete(t),this.assets.set(t,{name:e,asset:n}),this.latest.set(e,{...n,href:t});while(this.assets.size>this.limit){let r=this.assets.keys().next().value,{name:o}=this.assets.get(r);if(this.assets.delete(r),this.latest.get(o)?.href===r)this.latest.delete(o)}}}var yd=Object.freeze({type:"anonymous",signIn:null});function $r(){return{async ready(){},async resolve(){return yd},async fetch(){return new Response("Not Found",{status:404})},async close(){}}}var rn=Symbol("PathMX.Html");function wd(e){return Object.freeze({[rn]:e,toString:()=>e})}function xd(e){return typeof e==="object"&&e!==null&&rn in e}function As(e){if(e==null||typeof e==="boolean")return"";if(Array.isArray(e))return e.map(As).join("");if(xd(e))return e[rn];return g(String(e)).replace(/'/g,"&#39;")}function b(e,...t){let n=e[0]??"";for(let r=0;r<t.length;r++)n+=As(t[r])+(e[r+1]??"");return wd(n)}function on(e){return typeof e==="string"?e:e[rn]}var bd=/([^\s=/>]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g;function Fe(e){let t={};for(let n of e?.matchAll(bd)??[]){let r=n[1].toLowerCase();if(Object.hasOwn(t,r))continue;t[r]=ee(n[2]??n[3]??n[4]??"")}return t}var Is="<!--[\\s\\S]*?(?:-->|$)",Sd="(`+)[\\s\\S]*?\\1";function $s(e,t,n){let r=new RegExp(t,"g"),o=0,i="";for(let s of e.matchAll(r))i+=n(e.slice(o,s.index)),i+=s[0],o=s.index+s[0].length;return i+n(e.slice(o))}function Ts(e,t){if(!e.includes("<!--"))return t(e);return $s(e,Is,t)}function sn(e,t){let n=e.split(/\r?\n/),r=[],o=[],i,s=!1,a=()=>{if(!o.length)return;r.push($s(o.join(`
38
- `),`${Is}|${Sd}`,t)),o.length=0};for(let c of n){if(i){if(r.push(c),v(c,i))i=void 0;continue}let p=me(c,s);s=p.inComment;let u=x(p.line);if(u){a(),i=u.marker,r.push(c);continue}o.push(c)}return a(),r.join(`
39
- `)}var yt="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",vd=new RegExp("^"+yt+":"+yt+"$"),kd=new RegExp("^x-"+yt+"$"),Pd=/^[a-z][\w.-]*$/,Ae="pmx-view",wt="data-pmx-view",Es="data-pmx-view-slot",Os="((?:\\s+(?:[^<>\\\"']|\\\"[^\\\"]*\\\"|'[^']*')*)?)",Ms=new RegExp("<(x-"+yt+")"+Os+"\\s*(?:/\\s*>|>\\s*</\\1\\s*>)","gi"),Rd=new RegExp("<(x-"+yt+")(?:\\s|/?>)","i"),Cd=/<x-[a-z]/i,Ad=/<!--pmx-component-syntax:(\d+)-->/g,Id=/\{\{\s*([A-Za-z_][\w-]*)\.([A-Za-z_][\w-]*(?:\.[A-Za-z_][\w-]*)*)\s*\}\}/g,N="data-pmx-component-origin";function an(e){return e.replace(/[-/\\^$*+?.()|[\]{}]/g,"\\$&")}function Tr(e){return vd.test(e)}function Ds(e){return kd.test(e)}function Er(e){return Pd.test(e)}function xe(e){if(!Tr(e))throw Error("Invalid View Component tag: "+e);return"x-"+e.replace(":","-")}function js(){let e=an(Ae),t="((?:\\s+(?:[^<>\\\"']|\\\"[^\\\"]*\\\"|'[^']*')*)?)";return new RegExp("<"+e+"((?:\\s+(?:[^<>\\\"']|\\\"[^\\\"]*\\\"|'[^']*')*)?)\\s*(?:/\\s*>|>\\s*</"+e+"\\s*>)","gi")}function Ls(e){return new RegExp("<"+Ae+"(?:\\s|/?>)","i").test(e)}function $d(e,t){let n=e.replace(Ms,(o,i,s)=>"<"+Ae+" "+wt+'="'+i+'"'+s+" />"),r=n.match(Rd);if(r)throw Error("<"+r[1]+"> must be empty or self-closing in "+t+".");return n}function Or(e,t){return Ts(e,(n)=>$d(n,t))}function Td(e,t,n){if(!t.length)return e;let r=t.map(an).join("|"),o=new RegExp("<\\/?(?:"+r+")"+Os+"\\s*\\/?>","gi");return e.replace(o,(i)=>"<!--pmx-component-syntax:"+(n.push(i)-1)+"-->")}function Ed(e,t,n=[],r=[]){return sn(e,(o)=>Td(Or(o,t),n,r))}function Bs(e){let t=[];return sn(e,(n)=>{for(let r of n.matchAll(new RegExp(Ms.source,"gi")))t.push(Object.freeze({tag:r[1].toLowerCase(),props:Object.freeze(Fe(r[2]))}));return n}),Object.freeze(t)}function cn(e){let t=new Set;for(let n of e.matchAll(/<([a-z][\w:.-]*)\b/gi))if(n[1])t.add(n[1].toLowerCase());return t}function Mr(e,t,n,r){return r(e,[["*",{element(o){if(o.tagName==="pmx-content")return;if(o.tagName===Ae||o.tagName.includes(":")||o.tagName.includes("-")||n.has(o.tagName))o.setAttribute(N,t)}}]])}function Ns(e,t,n){let r=!1;return n(e,[["*",{element(o){if(r)return;r=!0;for(let[i,s]of Object.entries(t))o.setAttribute(i,s)}}]])}function xt(e,t,n,r){return Ns(e,{"data-component":t,...r?{"data-pmx-attrs":JSON.stringify(r)}:{}},n)}function Dr(e){if(!e.includes(N))return e;return e.replace(new RegExp("\\s"+N+'="[^"]*"',"g"),"")}class jr{variables=new Map;variableMatcher;authoredTags=new Map;authoredMatcher;slots=new WeakMap;registerVariables(e){let t=!1;for(let[n,r]of e)this.variables.set(n,r),t=!0;if(!t)return;this.variableMatcher=new RegExp("\\{\\{\\s*(?:"+[...this.variables.keys()].map(an).join("|")+")\\.")}compileVariables(e){if(!this.variableMatcher?.test(e))return e;return sn(e,(t)=>t.replace(Id,(n,r,o)=>{let i=this.variables.get(r);return i?"<"+Ae+" "+wt+'="'+i+'" data-pmx-variable="'+o+'" />':n}))}compile(e,t){if(!e.includes("<"))return e;let n=Cd.test(e),r=this.authoredMatcher?.test(e)??!1;if(!n&&!r)return e;let o=[],i=Ed(e,t.source.path,r?[...this.authoredTags.keys()]:[],o);if(o.length)this.slots.set(t,o);return i}restore(e,t){let n=this.slots.get(t);if(!n)return e;return this.slots.delete(t),e.replace(Ad,(r,o)=>n[Number(o)]??r)}replaceAuthored(e,t){let n=new Set(t);for(let r of n){if(!Er(r))throw Error("Invalid Literate Component tag: "+r);if(r.startsWith("x-"))throw Error("Literate Component tag <"+r+"> uses the reserved x- prefix.");let o=this.authoredTags.get(r);if(o&&o!==e)throw Error("Duplicate Literate Component <"+r+"> in "+e+" and "+o+".")}for(let[r,o]of this.authoredTags)if(o===e)this.authoredTags.delete(r);for(let r of n)this.authoredTags.set(r,e);this.rebuildMatcher()}deleteAuthored(e){let t=!1;for(let[n,r]of this.authoredTags){if(r!==e)continue;this.authoredTags.delete(n),t=!0}if(t)this.rebuildMatcher()}has(e){return this.authoredTags.has(e)}stampOrigins(e,t,n){return Mr(e,t,this.authoredTags,n)}rebuildMatcher(){let e=[...this.authoredTags.keys()];this.authoredMatcher=e.length?new RegExp("<(?:"+e.map(an).join("|")+")(?:\\s|/?>)","i"):void 0}}function Od(e,t){let n=new Map(t.map((s)=>[s.marker,s])),r=[],o=0,i=0;for(let s of e.matchAll(/<template data-pmx-view-slot="[a-z0-9]+-[a-z0-9]+"><\/template>/g)){let a=n.get(s[0]);if(!a)continue;if(s.index>o)r.push(e.slice(o,s.index));r.push(a),o=s.index+s[0].length,i++}if(i!==t.length)throw Error("Compiled view slots do not match compiled HTML.");if(o<e.length)r.push(e.slice(o));return{html:e,segments:r}}function Md(e,t){let n=t.client,r=n?async(o,i,s)=>{let[a]=await Promise.all([t.compile?.(o,i,s),i.addBrowserBundle(n,t.tag)]);return a}:t.compile;return{plugin:e,tag:t.tag,authoredTag:xe(t.tag),props:t.props,data:t.data,compile:r,render:(o,i,s,a)=>t.render(o,i,s,a)}}function Dd(e,t){let n=`${t.namespace}:$variable`;return{plugin:e,tag:n,render:async(o,i,s,a)=>{let c=o.props["data-pmx-variable"]?.split(".")??[],p=await t.render({path:c,origin:o.origin},s,a);return b`${p}`}}}async function zs(e,t){if(!e.props)return;let n=e.props["~standard"].validate(t.props);if(n instanceof Promise)n=await n;if(!n.issues)return;throw Error(`Invalid <${e.authoredTag??e.tag}> props in ${t.origin.path}: ${q(n.issues)}`)}async function jd(e,t){if(!e.data)return t;let n=e.data["~standard"].validate(t);if(n instanceof Promise)n=await n;if(!n.issues)return n.value;throw Error(`Invalid <${e.authoredTag??e.tag}> data: ${q(n.issues)}`)}class Lr{views=new Map;authoredViews=new Map;variableNamespaces=new Set;dataViews=new Map;dataViewsByOwner=new Map;syntax=new jr;generation=0;has(e){return this.views.has(e)||this.authoredViews.has(e)}compileVariables(e,t){return this.syntax.compileVariables(e)}compileSyntax(e,t){return this.syntax.compile(e,t)}restoreSyntax(e,t){return this.syntax.restore(e,t)}register(e){let t=new Map,n=new Map,r=new Map;for(let o of e.components??[]){let i=o.tag;if(!Tr(i))throw Error(`Invalid View Component tag: ${i}`);if(!i.startsWith(`${e.id}:`))throw Error(`View Component <${i}> must use the ${e.id}: namespace.`);if(t.has(i)||this.views.has(i))throw Error(`Duplicate View Component tag: ${i}`);if(o.data)W(o.data,"input",`View Component <${i}> data`),W(o.data,"output",`View Component <${i}> data`);let s=Md(e.id,o),a=s.authoredTag;if(!Ds(a))throw Error(`Invalid authored View Component tag: ${a}`);if(n.has(a)||this.authoredViews.has(a))throw Error(`Duplicate authored View Component tag: ${a}`);t.set(i,s),n.set(a,s)}for(let o of e.variables??[]){let i=o.namespace;if(i!==e.id)throw Error(`View Variable {{ ${i}.* }} must use the ${e.id} namespace.`);if(r.has(i)||this.variableNamespaces.has(i))throw Error(`Duplicate View Variable namespace: ${i}`);r.set(i,Dd(e.id,o))}for(let[o,i]of t)this.views.set(o,i);for(let[o,i]of n)this.authoredViews.set(o,i);for(let[o,i]of r)this.variableNamespaces.add(o),this.views.set(i.tag,i);this.syntax.registerVariables([...r].map(([o,i])=>[o,i.tag]))}replaceAuthored(e,t){this.syntax.replaceAuthored(e,t)}deleteAuthored(e){this.syntax.deleteAuthored(e);for(let t of this.dataViewsByOwner.get(e)??[])this.dataViews.delete(t);this.dataViewsByOwner.delete(e)}replaceData(e,t,n){let r=[...n],o=new Set;for(let i of r){if(!Er(i.tag))throw Error(`Invalid authored data component: ${i.tag}`);if(o.has(i.tag))throw Error(`Duplicate authored data component: ${i.tag}`);let s=this.dataViews.get(i.tag);if(s&&s.owner!==t)throw Error(`Duplicate authored data component <${i.tag}> in ${t} and ${s.owner}.`);o.add(i.tag)}for(let i of this.dataViewsByOwner.get(t)??[])this.dataViews.delete(i);for(let i of r)this.dataViews.set(i.tag,{plugin:e,owner:t,tag:i.tag,available:i.available,compile:i.compile?(s,a,c)=>i.compile(s.origin,a,c):void 0,render:(s,a,c,p)=>i.render(s,a,c,p)});this.dataViewsByOwner.set(t,o)}hasAny(e){if(!e?.size)return!1;for(let t of e)if(this.authoredViews.has(t)||this.syntax.has(t))return!0;return!1}async prepareData(e,t,n,r,o){let i=this.views.get(e)??this.authoredViews.get(e)??this.dataViews.get(e);if(!i||i.available?.(n)===!1)throw Error(`Unknown data component <${e}> in ${n.path}.`);if(!this.dataViews.has(e)&&!i.data)throw Error(`View Component <${i.authoredTag??e}> does not declare data.`);let s={props:Object.freeze({...t}),origin:n};await zs(i,s);let a=i.compile?await i.compile(s,r,o.appContext(i.plugin)):void 0;return Object.freeze({view:i,use:s,compiled:a})}async renderData(e,t,n,r){let o=e;if(!o?.view||!o.use)throw Error("Invalid prepared component.");let i=await jd(o.view,t),s=r.appContext(o.view.plugin),a=await o.view.render({...o.use,data:i},o.compiled,Object.freeze({...n,database:s.database}),s);return xt(on(a),o.view.tag,r.environment.rewriteHtml)}stampOrigins(e,t,n){return this.syntax.stampOrigins(e,t,n)}async compile(e,t,n,r){if(e=Or(e,t.path),!e.includes(`<${Ae}`))return{html:Dr(e),plan:void 0};let o=[],i=(this.generation++).toString(36),s=js(),a=0,c="",p;while(p=s.exec(e)){c+=e.slice(a,p.index);let u=Fe(p[1]),l=u[wt]??"";delete u[wt];let d=this.views.get(l)??this.authoredViews.get(l);if(!d)throw Error(`Unknown View Component <${l}> in ${t.path}.`);let m=u[N];delete u[N];let f=m&&r.appContext(d.plugin).sources.get(m)||t,h={props:Object.freeze(u),origin:f};await zs(d,h);let w=performance.now(),T;try{T=d.compile?await d.compile(h,n,r.appContext(d.plugin)):void 0}finally{r.perf.record(`${d.plugin}.view.compile`,performance.now()-w,`${t.path} <${d.tag}>`)}let oe=`<template ${Es}="${i}-${o.length.toString(36)}"></template>`;o.push({marker:oe,view:d,use:h,compiled:T}),c+=oe,a=s.lastIndex}if(e=c+e.slice(a),Ls(e))throw Error(`Invalid compiled View Component use in ${t.path}.`);return e=Dr(e),{html:e,plan:o.length?Od(e,o):void 0}}async renderSegments(e,t,n,r){if(!t)return[e];let o=e.indexOf(t.html);if(o===-1)throw Error("Compiled view page does not match rendered HTML.");let i=[];if(o)i.push(e.slice(0,o));for(let a of t.segments){if(typeof a==="string"){i.push(a);continue}let c=performance.now(),p;try{let u=r.appContext(a.view.plugin),l=Object.freeze({...n,database:u.database});p=await a.view.render(a.use,a.compiled,l,u)}finally{r.perf.record(`${a.view.plugin}.view.render`,performance.now()-c,`${n.source.path} <${a.view.tag}>`)}i.push(xt(on(p),a.view.tag,r.environment.rewriteHtml))}let s=o+t.html.length;if(s<e.length)i.push(e.slice(s));return i}}var Ld=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function bt(e){if(!Ld.test(e))throw Error(`Invalid plugin id: ${e}`);return e}function D(e){return e}function Br(e){return e}function qs(e,t,n){return{method:e,path:t,handle:n}}function Ue(e){return(t,n)=>qs(e,t,n)}var ce=Object.freeze({get:Ue("GET"),post:Ue("POST"),put:Ue("PUT"),patch:Ue("PATCH"),delete:Ue("DELETE"),options:Ue("OPTIONS"),all:(e,t)=>qs("*",e,t)});var Bd=/^[a-z0-9]+(?:[-_.][a-z0-9]+)*$/;async function Vs(e){let t=new TextEncoder().encode(e),n=await crypto.subtle.digest("SHA-256",t);return[...new Uint8Array(n)].map((r)=>r.toString(16).padStart(2,"0")).join("")}function Hs(e){let t=new Set;for(let n of e){if(!Bd.test(n.id))throw Error(`Invalid database migration id: ${n.id}`);if(t.has(n.id))throw Error(`Duplicate database migration id: ${n.id}`);if(!n.sql.trim())throw Error(`Database migration ${n.id} is empty.`);t.add(n.id)}}async function Nd(e,t,n){Hs(n),await t.transaction(async(r)=>{await r.exec(`
40
- CREATE TABLE IF NOT EXISTS _pathmx_migrations (
41
- id TEXT PRIMARY KEY,
42
- checksum TEXT NOT NULL,
43
- applied_at TEXT NOT NULL
44
- )
45
- `);let o=await r.all("SELECT id, checksum FROM _pathmx_migrations ORDER BY rowid");for(let[i,s]of o.entries()){let a=n[i];if(!a||a.id!==s.id)throw Error(`Database migration history changed: ${e}`);let c=await Vs(a.sql);if(s.checksum!==c)throw Error(`Applied database migration changed: ${e}/${a.id}`)}for(let i of n.slice(o.length)){let s=await Vs(i.sql);await r.exec(i.sql),await r.run("INSERT INTO _pathmx_migrations (id, checksum, applied_at) VALUES (?, ?, ?)",[i.id,s,new Date().toISOString()])}})}function zd(e){return Object.freeze({all:(t,n)=>e().then((r)=>r.all(t,n)),get:(t,n)=>e().then((r)=>r.get(t,n)),run:(t,n)=>e().then((r)=>r.run(t,n)),exec:(t)=>e().then((n)=>n.exec(t)),transaction:(t)=>e().then((n)=>n.transaction(t))})}class Ie{environment;stateRoot;registered=new Map;closing;constructor(e,t){this.environment=e;this.stateRoot=t}prepare(e){let t=(e.migrations??[]).map((n)=>Object.freeze({...n}));return Hs(t),Object.freeze({migrations:Object.freeze(t)})}register(e,t){let n=this.prepare(t);if(this.registered.has(e))throw Error(`Duplicate plugin database: ${e}`);let r,o={handle:zd(()=>r??=this.create(e,n)),connection:()=>r};this.registered.set(e,o)}get(e){return this.registered.get(e)?.handle}async create(e,t){if(!this.environment)throw Error(`Plugin ${e} requires SQL database support in this environment.`);let n=await this.environment.open(this.environment.path(this.stateRoot,`${e}.sqlite`));try{return await Nd(e,n,t.migrations??[]),n}catch(r){throw await n.close().catch(()=>{return}),r}}async closeAll(){let e=[...this.registered.values()].map((r)=>r.connection()).filter((r)=>!!r),n=(await Promise.allSettled(e.map(async(r)=>(await r).close()))).find((r)=>r.status==="rejected");if(n)throw n.reason}close(){return this.closing??=this.closeAll()}}function Nr(e,t){let n=(r)=>(o,i)=>e[r](`${t}.${o}`,i);return Object.freeze({debug:n("debug"),info:n("info"),warn:n("warn"),error:n("error")})}function qd(e){return Object.freeze({linksFrom:(t)=>[...e.graph.linksFrom(t)],linksTo:(t)=>[...e.graph.linksTo(t)],neighbors:(t)=>e.graph.neighbors(t),backlinks:(t)=>e.graph.backlinks(t)})}function Vd(e,t){return e.resolve(t)??e.repo.get(t)??e.repo.atPath(t)}function Fs(e,t,n){return Object.freeze({plugin:e,log:Nr(t.log,e),runtime:t.runtime,database:n})}function Us(e,t,n){return Object.freeze({...e,schema:t.schema,query:Object.freeze({prepare:(r,o)=>t.queries.prepare(r,o)}),yaml:t.environment.yaml,sources:Object.freeze({get:(r)=>Vd(t,r),all:()=>t.repo.all(),resolve:(r)=>t.resolve(r),path:(r)=>t.repo.graphPath(r),isPage:(r)=>t.isPage(r),builtPages:()=>[...t.pageCache.values()]}),graph:qd(t),actors:Object.freeze({profile:(r)=>t.profiles.findById(r)?.profile,homeActorId:(r)=>t.homeActorId(r)}),access:Object.freeze({read:(r,o)=>t.readAccess(r,o),can:(r,o,i)=>t.hasSourceCapability(r,o,i),canEmbed:(r,o)=>t.canEmbed(r,o)}),assets:Object.freeze({load:(r)=>t.environment.loadAsset(r),publish:(r,o,i)=>t.publishAsset(r,o,i)}),html:Object.freeze({rewrite:(r,o)=>t.environment.rewriteHtml(r,o)}),compile:Object.freeze({block:(r,o,i,s)=>t.compileBlock(r,o,i,s,"embedded"),document:(r,o)=>t.compileDocument(r,o,e.plugin)}),components:n,diagnostics:Object.freeze({invalid(r,o){throw new R({source:r.path,plugin:e.plugin,message:o})}})})}var $e=Object.freeze({type:"anonymous"});function Te(e){return e.type==="authenticated"?{type:"actor",actor:e.actor}:$e}function St(e){if(e.headers.set("Cache-Control","private, no-store"),!e.headers.get("Vary")?.split(",").some((n)=>n.trim()==="Cookie"))e.headers.append("Vary","Cookie");return e}function be(e,t,n){return t==="private"||n.type==="authenticated"?St(e):e}var _s=`<!doctype html>
46
- <html lang="en" data-pmx-document="1" {{ html_attrs }}>
47
- <head>
48
- {{ head }}
49
- </head>
50
- <body>
51
- <div
52
- data-pmx-view
53
- data-pmx-route="{{ route }}"
54
- data-pmx-actor="{{ actor }}"
55
- >
56
- {{ content }}
57
- </div>
58
- </body>
59
- </html>
60
- `;var Fd=_s;function V(){return new Response(`# Not Found
61
-
62
- The requested resource does not exist or is not available. Start at [the site root](/) or browse the public index in [/llms.txt](/llms.txt).
63
- `,{status:404,headers:{"Content-Type":"text/markdown; charset=utf-8"}})}async function Qs(e,t,n,r,o,i={}){let s=await e.documentHead(o),a=i.scheme?` data-pmx-scheme="${i.scheme}" style="color-scheme: ${i.scheme}"`:"",c=n.type==="actor"?n.actor.id:"",p=_(Fd,{head:s,html_attrs:a,route:g(o.route),actor:g(c),content:o.html}),u=new Headers(i.headers);if(!u.has("Content-Type"))u.set("Content-Type","text/html; charset=utf-8");return e.rewrite(t,p,r,{status:i.status,headers:u})}async function pn(e,t,n,r,o={}){let i=e.readAccess(n,r);if(i==="denied")return V();let s=await Qs(e,t,n,r,await e.ensurePage(r),o);return be(s,i,t)}async function Ws(e,t,n,r,o={}){let i=e.readAccess(n,r);if(i==="denied")return V();try{let s=await Qs(e,t,n,r,await e.compilePage(r),o);return be(s,i,t)}finally{e.forgetCompiledPage(r.path)}}var Ud="pathmx-scheme";function _d(e,t){if(!e)return;for(let n of e.split(";")){let r=n.indexOf("=");if(r===-1||n.slice(0,r).trim()!==t)continue;try{return decodeURIComponent(n.slice(r+1).trim())}catch{return}}}function un(e){let t=_d(e.headers.get("cookie"),Ud);if(t==="light"||t==="dark")return t}function Xs(e,t,n,r,o){let i,s,a=()=>i??=e.resolveCredentials(r),c=()=>s??=a().then((l)=>e.view(l)),p=e.appContext(t),u=(l)=>typeof l==="string"?p.sources.get(l):l;return Object.freeze({request:r,url:o,path:n,plugin:t,log:p.log,runtime:p.runtime,database:p.database,graph:p.graph,source(l){return p.sources.get(l)},sources(){return p.sources.all()},resolve(l){return p.sources.resolve(l)},isPublic(l){return p.access.read({type:"anonymous"},l)==="public"},session:a,view:c,async readAccess(l){let d=await a();return p.access.read(Te(d),l)},onSync(l){return e.onSync(l)},async render(l,d={}){let m=u(l);if(!m)return V();let f=await a();return pn(e,f,Te(f),m,{...d,scheme:un(r)})},async mutate(l){let d=await a();if(d.type!=="authenticated")throw new ne("authentication-required");let m=await e.commitPrepared(async()=>{let f=Ve(e,d.actor);return await l(f),f.changeSet()});if(m.applied.length)e.log.info("server.mutation",{plugin:t,method:r.method,path:o.pathname,changes:m.applied.length});return m},mutateAsAgent(l,d){return e.runAgentJob(l,d)},handleCredentials(){return e.credentialRequest(r)}})}var _e="agent-browsing",Qd=Object.freeze({"/llms.txt":"/api/agent-browsing/llms.txt","/robots.txt":"/api/agent-browsing/robots.txt","/sitemap.xml":"/api/agent-browsing/sitemap.xml"});function ln(e){return Qd[e]}var zr="/api",Wd=["GET","HEAD","POST","PUT","PATCH","DELETE","OPTIONS"],Xd=new Set(["GET","POST","PUT","PATCH","DELETE","OPTIONS","*"]);function Jd(e){if(e.startsWith("/")||e.includes("?")||e.includes("#"))throw Error(`Invalid server route path: ${e}`);let t=e==="*"||e.endsWith("/*"),n=e==="*"?"":t?e.slice(0,-2):e;if(n.includes("*")||n.includes("\\")||/%2f|%5c/i.test(n))throw Error(`Invalid server route path: ${e}`);let r=`${zr}/${n}`,o=new URL(r,"http://pathmx.local");if(o.pathname!==r||o.search||o.hash||n.split("/").includes(".."))throw Error(`Invalid server route path: ${e}`);return t?n?`${n}/*`:"*":n}function Gd(e,t){let n=t?`/${t}`:"";return`${zr}/${e}${n}`}function Yd(e,t){let n=`${zr}/${e}`;return t===n?"":t.slice(n.length+1)}function Kd(e){return e.endsWith("/*")?e.slice(0,-1):void 0}function Zd(e,t){return e==="*"||t==="*"||e===t}function em(e,t){let n=e.prefix,r=t.prefix;if(!n&&!r)return e.path===t.path;if(n&&r)return n.startsWith(r)||r.startsWith(n);if(n)return t.path.startsWith(n);if(r)return e.path.startsWith(r);return!1}function tm(e,t){return`Overlapping server routes: ${e.method} ${e.path} (${e.plugin}) and ${t.method} ${t.path} (${t.plugin})`}function nm(e){return new Response(null,{status:e.status,statusText:e.statusText,headers:e.headers})}class qr{routes=[];exact=new Map;prefixes=[];prepare(e){let t=(e.routes??[]).map((r)=>{if(!Xd.has(r.method))throw Error(`Invalid server route method: ${r.method}`);let o=Jd(r.path),i=Gd(e.id,o);return{...r,path:i,relative:o,plugin:e.id,prefix:Kd(i)}}),n=[...this.routes];for(let r of t){for(let o of n)if(em(r,o)&&(r.path!==o.path||Zd(r.method,o.method)))throw Error(tm(o,r));n.push(r)}return t}register(e){for(let t of e){if(this.routes.push(t),t.prefix){this.prefixes.push(t);continue}let n=this.exact.get(t.path)??[];n.push(t),this.exact.set(t.path,n)}}async dispatch(e,t,n,r=t){let o=ln(t.pathname)??t.pathname,i=this.exact.get(o),s=i?[...i]:[];if(!i)for(let u of this.prefixes){let l=u.prefix;if(l&&o.startsWith(l))s.push(u)}if(!s.length)return;let a=e.method.toUpperCase(),c=s.find((u)=>u.method==="*"||u.method===a||a==="HEAD"&&u.method==="GET");if(!c){let u=new Set(s.flatMap((l)=>l.method==="GET"?["GET","HEAD"]:[l.method]));return new Response("Method Not Allowed",{status:405,headers:{Allow:Wd.filter((l)=>u.has(l)).join(", ")}})}let p=await n.perf.measureAsync(`route.${c.plugin}`,async()=>c.handle(Xs(n,c.plugin,Yd(c.plugin,o),e,r)),c.path);return a==="HEAD"?nm(p):p}}var rm=/^[a-z0-9]+(?:[/-][a-z0-9]+)*$/,Fr=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;function dn(e,t){return e<t?-1:e>t?1:0}function Js(e){return(e.split("/").at(-1)??e).replace(/[-_]+/g," ").replace(/\b\w/g,(n)=>n.toUpperCase())}function mn(e,t,n){if(typeof e!=="string"||!e.trim())throw Error(`${n} ${t} must be a non-empty string.`);return e.trim()}function Gs(e,t,n,r){if(!rm.test(n))throw Error(`Plugin ${t} has an invalid ${e} type: ${n}`);if(!r||typeof r!=="object")throw Error(`Plugin ${t} ${e} type ${n} must be an object.`);let o=`${t}:${n}`,i=`Plugin ${t} ${e} type ${n} schema`,s=r.schema?W(r.schema,"input",i):void 0,a=r.schema?W(r.schema,"output",i):void 0,c=Object.freeze({...r.label!==void 0?{label:mn(r.label,"label",o)}:{},...r.description!==void 0?{description:mn(r.description,"description",o)}:{},...r.icon!==void 0?{icon:mn(r.icon,"icon",o)}:{},...r.color!==void 0?{color:mn(r.color,"color",o)}:{},...r.schema?{schema:r.schema}:{}});if(!Object.keys(c).length)throw Error(`Plugin ${t} ${e} type ${n} must contribute presentation or a schema.`);return Object.freeze({type:n,plugin:t,definition:c,...s?{inputJsonSchema:s}:{},...a?{outputJsonSchema:a}:{}})}function om(e,t,n){if(!Fr.test(t))throw Error(`Plugin ${e} has an invalid data prop: ${t}`);let r=`Plugin ${e} data prop ${t}`,o=W(n,"input",r),i=W(n,"output",r);return Object.freeze({name:t,plugin:e,schema:n,inputJsonSchema:o,outputJsonSchema:i})}function im(e,t,n){if(!Fr.test(t))throw Error(`Plugin ${e} has an invalid query name: ${t}`);if(!n||typeof n!=="object")throw Error(`Plugin query ${e}:${t} must be an object.`);if(typeof n.resolve!=="function")throw Error(`Plugin query ${e}:${t} must define resolve().`);let r=`${e}:${t}`,o=W(n.output,"output",`Plugin query ${r} output`),i=n.input?W(n.input,"input",`Plugin query ${r} input`):void 0;return Object.freeze({id:r,name:t,plugin:e,definition:n,...i?{input:i}:{},output:o})}function sm(e,t,n){if(!Fr.test(t))throw Error(`Plugin ${e} has an invalid Action name: ${t}`);if(typeof n!=="function")throw Error(`Plugin Action ${e}:${t} must be a function.`);if(n.input)W(n.input,"input",`Plugin Action ${e}:${t} input`);if(n.output)W(n.output,"output",`Plugin Action ${e}:${t} output`);return Object.freeze([`${e}:${t}`,n])}function am(e){return e!=null&&(typeof e==="object"||typeof e==="function")&&typeof e.then==="function"}function Vr(e,t,n,r,o,i){let s=o["~standard"].validate(i),a=am(s);if(a)Promise.resolve(s).catch(()=>{return});let c=a?"application schemas must validate authored data synchronously":s.issues?.length?q(s.issues):void 0;return c?new R({source:e.path,plugin:n,message:`Invalid ${r} on ${t.path}: ${c}`}):void 0}function Hr(e,t){if(e&&!t?.(e))throw e}class Ur{sourceContributions=new Map;blockContributions=new Map;sourceDescriptors=new Map;blockDescriptors=new Map;observedSourceDescriptors=new Map;observedBlockDescriptors=new Map;propContributions=new Map;queryContributions=new Map;queryReferences=new WeakMap;queryDescriptions=new Map;prepare(e,t){let n=Object.entries(t?.sources??{}).map(([a,c])=>Gs("Source",e,a,c)),r=Object.entries(t?.blocks??{}).map(([a,c])=>Gs("Block",e,a,c)),o=Object.entries(t?.props??{}).map(([a,c])=>om(e,a,c)),i=Object.entries(t?.query??{}).map(([a,c])=>im(e,a,c)),s=Object.entries(t?.actions??{}).map(([a,c])=>sm(e,a,c));for(let a of o){let c=this.propContributions.get(a.name);if(c)throw Error(`Data prop ${a.name} is already owned by Plugin ${c.plugin}.`)}for(let a of i)if(this.queryContributions.has(a.id))throw Error(`Duplicate Plugin query: ${a.id}`);return Object.freeze({sources:Object.freeze(n),blocks:Object.freeze(r),props:Object.freeze(o),queries:Object.freeze(i),actions:Object.freeze(s)})}register(e){this.registerTypes(e.sources,this.sourceContributions,this.sourceDescriptors),this.registerTypes(e.blocks,this.blockContributions,this.blockDescriptors);for(let t of e.props)this.propContributions.set(t.name,t);for(let t of e.queries)this.queryContributions.set(t.id,t),this.queryReferences.set(t.definition,t),this.queryDescriptions.set(t.id,Object.freeze({id:t.id,plugin:t.plugin,...t.definition.input?{input:t.definition.input,inputJsonSchema:t.input}:{},output:t.definition.output,outputJsonSchema:t.output}))}registerTypes(e,t,n){for(let r of e){let o=t.get(r.type);if(o)o.push(r);else t.set(r.type,[r]);n.delete(r.type)}}sourceType(e){let t=typeof e==="string"?e:e.type;return this.typeDescriptor(t,this.sourceContributions,this.sourceDescriptors,this.observedSourceDescriptors)}sourceTypes(){return this.typeDescriptors(this.sourceContributions,this.observedSourceDescriptors,(e)=>this.sourceType(e))}blockType(e){let t=typeof e==="string"?e:e.type;return this.typeDescriptor(t,this.blockContributions,this.blockDescriptors,this.observedBlockDescriptors)}blockTypes(){return this.typeDescriptors(this.blockContributions,this.observedBlockDescriptors,(e)=>this.blockType(e))}typeDescriptor(e,t,n,r){let o=t.get(e);if(!o?.length)return this.observedType(e,r);let i=n.get(e);if(i)return i;let s,a,c,p;for(let{definition:u}of o)s=u.label??s,a=u.description??a,c=u.icon??c,p=u.color??p;return i=Object.freeze({type:e,label:s??Js(e),...a?{description:a}:{},icon:c??"file-text",color:p??"slate",origin:"defined",plugins:Object.freeze([...new Set(o.map((u)=>u.plugin))])}),n.set(e,i),i}typeDescriptors(e,t,n){let r=new Set([...e.keys(),...t.keys()]);return Object.freeze([...r].sort(dn).map(n))}sourceSchemas(e){let t=typeof e==="string"?e:e.type;return this.schemas(t,this.sourceContributions)}blockSchemas(e){let t=typeof e==="string"?e:e.type;return this.schemas(t,this.blockContributions)}schemas(e,t){return Object.freeze((t.get(e)??[]).flatMap((n)=>n.definition.schema?[Object.freeze({plugin:n.plugin,schema:n.definition.schema,inputJsonSchema:n.inputJsonSchema,outputJsonSchema:n.outputJsonSchema})]:[]))}prop(e){return this.propContributions.get(e)}props(e){let t=e?Object.keys(e.data).flatMap((n)=>{let r=this.propContributions.get(n);return r?[r]:[]}):[...this.propContributions.values()];return Object.freeze(t.sort((n,r)=>dn(n.name,r.name)))}has(e,t){return this.propContributions.has(t)&&Object.hasOwn(e.data,t)}value(e,t){return this.has(e,t)?e.data[t]:void 0}registeredQuery(e){return typeof e==="string"?this.queryContributions.get(e):this.queryReferences.get(e)}queries(){return Object.freeze([...this.queryContributions.values()].sort((e,t)=>dn(e.id,t.id)))}querySchema(e){return this.queryDescriptions.get(e)}querySchemas(){return Object.freeze([...this.queryDescriptions.values()].sort((e,t)=>dn(e.id,t.id)))}sourceTypeContributions(e){return e?Object.freeze([...this.sourceContributions.get(e)??[]]):Object.freeze([...this.sourceContributions.values()].flat())}blockTypeContributions(e){return e?Object.freeze([...this.blockContributions.get(e)??[]]):Object.freeze([...this.blockContributions.values()].flat())}sourceDataSchemas(e){return Object.freeze(this.sourceTypeContributions(e).flatMap((t)=>t.outputJsonSchema?[t.outputJsonSchema]:[]))}blockDataSchemas(e){return Object.freeze(this.blockTypeContributions(e).flatMap((t)=>t.outputJsonSchema?[t.outputJsonSchema]:[]))}propDataSchema(e){return this.propContributions.get(e)?.outputJsonSchema}index(e,t){this.sourceType(e);for(let{plugin:n,definition:r}of this.sourceContributions.get(e.type)??[]){if(!r.schema)continue;Hr(Vr(e,e,n,`${e.type} Source`,r.schema,e.data),t)}for(let n of e.blocks){this.blockType(n);for(let{plugin:r,definition:o}of this.blockContributions.get(n.type)??[]){if(!o.schema)continue;Hr(Vr(e,n,r,`${n.type} Block`,o.schema,n.data),t)}}if(!this.propContributions.size)return;for(let n of[e,...e.blocks])for(let r of Object.keys(n.data)){let o=this.propContributions.get(r);if(!o)continue;Hr(Vr(e,n,o.plugin,`${r} prop`,o.schema,n.data[r]),t)}}observedType(e,t){let n=t.get(e);if(!n)n=Object.freeze({type:e,label:Js(e),icon:"file-text",color:"slate",origin:"observed",plugins:Object.freeze([])}),t.set(e,n);return n}}function Ys(e){return Object.freeze({sourceType:e.sourceType.bind(e),sourceTypes:e.sourceTypes.bind(e),blockType:e.blockType.bind(e),blockTypes:e.blockTypes.bind(e),sourceSchemas:e.sourceSchemas.bind(e),blockSchemas:e.blockSchemas.bind(e),query:e.querySchema.bind(e),queries:e.querySchemas.bind(e),prop:e.prop.bind(e),props:e.props.bind(e),has:e.has.bind(e),value:e.value.bind(e)})}class X extends Error{constructor(e){super(e);this.name="PluginRegistrationError"}}function cm(e){let t=new Map(e.map((n,r)=>[n.id,r]));for(let n of e){if(n.requires===void 0)continue;if(!Array.isArray(n.requires))throw new X(`Plugin ${n.id} requires must be a list of plugin ids.`);let r=new Set;for(let o of n.requires){try{bt(o)}catch(s){throw new X(s instanceof Error?s.message:String(s))}if(o===n.id)throw new X(`Plugin ${n.id} cannot require itself.`);if(r.has(o))throw new X(`Plugin ${n.id} requires ${o} more than once.`);r.add(o);let i=t.get(o);if(i===void 0)throw new X(`Plugin ${n.id} requires missing plugin ${o}.`);if(i>t.get(n.id))throw new X(`Plugin ${n.id} requires plugin ${o} to be registered first.`)}}}class _r{databases;installed=[];ids=new Set;frozen=!1;credentialHost=$r();credentialOwner;credentialClosing;closing;views=new Lr;routes=new qr;actions=new Map;lifecycleContexts=new Map;appContexts=new Map;schemaRegistry=new Ur;schema=Ys(this.schemaRegistry);constructor(e=new Ie(void 0,".pathmx/state")){this.databases=e}get plugins(){return this.installed}has(e){return this.ids.has(e)}register(e){if(this.frozen)throw new X("Plugin registration is frozen after the engine is ready.");let t=ve(e);if(bt(t.id),this.ids.has(t.id))throw new X(`Duplicate plugin id: ${t.id}`);if(t.credentials&&this.credentialOwner)throw new X(`Credential provider already registered by plugin ${this.credentialOwner}.`);let n,r,o,i;try{i=t.database?this.databases.prepare(t.database):void 0,n=this.routes.prepare(t),o=this.schemaRegistry.prepare(t.id,t.schema),r=this.prepareActions(o.actions),this.views.register(t)}catch(s){throw new X(s instanceof Error?s.message:String(s))}if(i)this.databases.register(t.id,i);this.routes.register(n);for(let[s,a]of r)this.actions.set(s,a);if(this.schemaRegistry.register(o),t.credentials)this.credentialHost=t.credentials,this.credentialOwner=t.id;this.ids.add(t.id),this.installed.push(t)}prepareActions(e){for(let[t,n]of e)if(this.actions.has(t))throw Error(`Duplicate Plugin Action: ${t}`);return e}action(e){return this.actions.get(e)}async actionAffordances(e,t,n){let r=await Promise.all([...this.actions].map(([o,i])=>us(o,i,{principal:e,target:t,yaml:n.environment.yaml,can:(s)=>n.hasSourceCapability(e,t,s)})));return Object.freeze(r.filter((o)=>o!==void 0))}freeze(){cm(this.installed),this.frozen=!0}lifecycleContext(e,t){let n=typeof e==="string"?e:e.id,r=this.lifecycleContexts.get(n);if(r)return r;let o=Fs(n,t,this.databases.get(n));return this.lifecycleContexts.set(n,o),o}appContext(e,t){let n=typeof e==="string"?e:e.id,r=this.appContexts.get(n);if(r)return r;let o=Us(this.lifecycleContext(n,t),t,this.componentContext(n,t));return this.appContexts.set(n,o),o}componentContext(e,t){return Object.freeze({claim:(n,r)=>this.replaceAuthoredComponents(n,r),release:(n)=>this.deleteAuthoredComponents(n),has:(n)=>this.hasView(n),replaceData:(n,r)=>this.replaceAuthoredDataComponents(e,n,r),prepareData:(n,r,o,i)=>this.prepareDataComponent(n,r,o,i,t),renderData:(n,r,o)=>this.renderDataComponent(n,r,o,t)})}async setup(e){for(let t of this.installed)await t.setup?.(this.lifecycleContext(t,e))}async shutdown(e){let t=[];try{await this.closeCredentials()}catch(n){t.push(n)}for(let n of[...this.installed].reverse())try{await n.close?.(this.lifecycleContext(n,e))}catch(r){t.push(r)}try{await this.databases.close()}catch(n){t.push(n)}if(t.length)throw AggregateError(t,"Plugin shutdown failed.")}close(e){return this.closing??=this.shutdown(e)}async measure(e,t,n,r,o){let i=performance.now();try{return await o()}finally{r.perf.record(`${e.name??"plugin"}.${t}`,performance.now()-i,n)}}index(e,t,n){this.schemaRegistry.index(e,n);for(let r of this.installed)try{r.index?.(e,this.appContext(r,t))}catch(o){if(!n?.(o))throw o}}unindex(e,t){for(let n of this.installed)n.unindex?.(e,this.appContext(n,t))}async precompile(e,t,n){for(let r of this.installed){if(!r.precompile)continue;e=await this.measure(r,"precompile",t.source.path,n,()=>r.precompile(e,t,this.appContext(r,n)))??e}return this.views.compileSyntax(e,t)}compileVariables(e,t){return this.views.compileVariables(e,t)}async postcompile(e,t,n){if(e=this.views.restoreSyntax(e,t),this.views.hasAny(t.elements))e=this.views.stampOrigins(e,t.source.path,n.environment.rewriteHtml);for(let r of this.installed){if(!r.postcompile)continue;e=await this.measure(r,"postcompile",t.source.path,n,()=>r.postcompile(e,t,this.appContext(r,n)))??e}return e}async page(e,t,n,r){for(let o of this.installed){if(!o.page||o.id===r)continue;e=await this.measure(o,"page",t.source.path,n,()=>o.page(e,t,this.appContext(o,n)))??e}return e}invalidations(e,t){let n=[];for(let r of this.installed){let o=r.invalidate?.(e,this.appContext(r,t));if(o)n.push(o)}return n}async documentAssets(e,t){for(let n of this.installed)await n.documentAssets?.(e,this.appContext(n,t))}replaceAuthoredComponents(e,t){this.views.replaceAuthored(e,t)}replaceAuthoredDataComponents(e,t,n){this.views.replaceData(e,t,n)}deleteAuthoredComponents(e){this.views.deleteAuthored(e)}hasView(e){return this.views.has(e)}prepareDataComponent(e,t,n,r,o){return this.views.prepareData(e,t,n,r,o)}renderDataComponent(e,t,n,r){return this.views.renderData(e,t,n,r)}query(e){return this.schemaRegistry.registeredQuery(e)}queries(){return this.schemaRegistry.queries()}compileViewComponents(e,t,n,r){return this.views.compile(e,t,n,r)}async renderView(e,t,n,r,o){let i=await this.views.renderSegments(e,t,n,r),s=[];for(let c of this.installed){if(!c.streamSelectors)continue;for(let[p,u]of Object.entries(c.streamSelectors(n,this.appContext(c,r))))s.push([p,u])}let a=new Blob(i,{type:"text/html; charset=utf-8"});return r.environment.rewriteHtml(new Response(a,o),s)}resolveCredentials(e,t,n){return n.perf.measureAsync("credentials.resolve",()=>this.credentialHost.resolve(e,t),new URL(e.url).pathname)}credentialRequest(e,t){return this.credentialHost.fetch(e,t)}readyCredentials(e){return this.credentialHost.ready(e)}closeCredentials(){return this.credentialClosing??=this.credentialHost.close()}serverRoute(e,t,n,r=t){return this.routes.dispatch(e,t,n,r)}}function re(e){if(e.type==="source")return e.path;return`plugin:${e.plugin}:${e.key}`}class vt{keys=new Set;depend=(e)=>{this.keys.add(re(e))}}class Qr{outgoing=new Map;incoming=new Map;replaceDependent(e,t){this.deleteDependent(e);let n=new Set(t);if(!n.size)return;this.outgoing.set(e,n);for(let r of n){let o=this.incoming.get(r);if(!o)o=new Set,this.incoming.set(r,o);o.add(e)}}deleteDependent(e){let t=this.outgoing.get(e);if(!t)return;for(let n of t){let r=this.incoming.get(n);if(r?.delete(e),r&&r.size===0)this.incoming.delete(n)}this.outgoing.delete(e)}dependentsOf(e){return this.incoming.get(e)??new Set}dependenciesOf(e){return this.outgoing.get(e)??new Set}}class Wr{engine;plugins;pageCache=new Map;compiling=new Set;pageBuilds=new WeakMap;dependencies=new Qr;viewPlans=new Map;sourceElementTags=new Map;constructor(e,t){this.engine=e;this.plugins=t}indexSource(e){this.sourceElementTags.set(e.path,cn(e.content))}unindexSource(e){this.sourceElementTags.delete(e)}dependentsOf(e){return this.dependencies.dependentsOf(typeof e==="string"?e:re(e))}dependenciesOf(e){return this.dependencies.dependenciesOf(e)}planFor(e){return this.viewPlans.get(e)}isPage(e){return Re(e)}compilePage(e){return this.engine.perf.measureAsync("compile.page",async()=>{let t=new vt,n=Ss(e,await this.compilePageBody(e,t)),{assets:r,addAsset:o,addBrowserBundle:i}=this.engine.documentAssetBag(),s={source:e,addAsset:o,addBrowserBundle:i,depend:t.depend};n=await this.plugins.page(n,s,this.engine);let a=await this.plugins.compileViewComponents(n,e,s,this.engine);if(n=a.html,this.dependencies.replaceDependent(e.path,t.keys),a.plan)this.viewPlans.set(e.path,a.plan);else this.viewPlans.delete(e.path);return Object.freeze({html:n,assets:Object.freeze([...r]),sourceId:e.id,route:y(e)})},e.path)}ensurePage(e){let t=this.pageCache.get(e.path);if(t)return Promise.resolve(t);return this.cachePage(e)}cachePage(e){let t=this.pageBuilds.get(e);if(t)return t;let n=this.compilePage(e).then((r)=>{if(this.engine.repo.atPath(e.path)===e)this.pageCache.set(e.path,r);return r}).finally(()=>this.pageBuilds.delete(e));return this.pageBuilds.set(e,n),n}async compilePageBody(e,t){let n=[];if(e.blocks.length)for(let r of e.blocks)n.push(await this.compileBlock(e,r,t));else n.push(Ar({id:"block-0",path:e.path+"#block-0",type:"block"},await this.compileContent(e,e.body,e.data,void 0,t)));return n.filter(Boolean).join(`
64
- `)}async compileDocument(e,t,n){let r=[];if(e.blocks.length)for(let p of e.blocks)r.push(await this.compileBlockContent(e,p,t));else r.push(await this.compileContent(e,e.body,e.data,void 0,t));let o=r.filter(Boolean).join(`
65
- `),{assets:i,addAsset:s,addBrowserBundle:a}=this.engine.documentAssetBag(),c={source:e,addAsset:s,addBrowserBundle:a,depend:t.depend.bind(t)};return o=await this.plugins.page(o,c,this.engine,n),{html:o,assets:i}}async compileBlock(e,t,n=new vt,r,o="page"){if(this.compiling.has(t.path))return"<p>[Circular Include: "+g(t.path)+"]</p>";this.compiling.add(t.path);try{let i=await this.compileBlockContent(e,t,n,o),s=bs(i);if(s!==void 0)return s;return Ar(t,i,r)}finally{this.compiling.delete(t.path)}}compileBlockContent(e,t,n,r="page"){return this.compileContent(e,t.body,{...e.data,...t.data},t,n,r)}interpolationContext(e,t){return{...t,source:{id:e.id,path:e.path,name:e.name,type:e.type,href:y(e),...te(e)}}}async compileContent(e,t,n,r,o=new vt,i="page"){let s={source:e,block:r,scope:i,slots:[],elements:this.sourceElementTags.get(e.path)??new Set,depend:o.depend},a=this.plugins.compileVariables(t,s);a=dr(a,this.interpolationContext(e,n)),a=await this.plugins.precompile(a,s,this.engine);let c=this.engine.environment.renderMarkdown(a);if(c=ys(c),r){let p=tn(e,r);c=ws(c,p,r.headings)}return this.plugins.postcompile(c,s,this.engine)}buildCache(){return this.engine.perf.measureAsync("cache.build",async()=>{for(let e of this.engine.repo.all())if(this.isPage(e))await this.ensurePage(e)})}async recompilePages(e){let t=new Set;for(let n of e){if(t.has(n))continue;t.add(n);let r=this.engine.repo.atPath(n)??this.engine.repo.get(n);if(!r||!this.isPage(r))continue;if(!this.pageCache.has(r.path))continue;await this.cachePage(r)}}forgetCompiled(e){this.pageCache.delete(e),this.viewPlans.delete(e),this.dependencies.deleteDependent(e)}}function Ks(e){if(!e)return"/";let t=e.startsWith("/")?e:"/"+e;return t.length>1?t.replace(/\/+$/,""):t}class fn{routes=new Map;actors=new Set;add(e,t){let n=Ks(e);if(this.routes.has(n)&&this.routes.get(n)===void 0)return;if(!t){this.routes.set(n,void 0);return}let r=this.routes.get(n)??new Set;r.add(t),this.routes.set(n,r)}addActors(e,t){for(let n of t)this.add(e,n)}addActorTargets(e){for(let t of e)this.actors.add(t)}event(){return{targets:[...[...this.routes].sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>({type:"route",route:e,...t?{actors:[...t].sort()}:{}})),...this.actors.size?[{type:"actor",actors:[...this.actors].sort()}]:[]]}}}function Qe(e){return[...e].map((t)=>({type:"route",route:t.route}))}function Zs(e,t,n){let r=Ks(t);return e.targets.some((o)=>{if(o.type==="actor")return n!=null&&o.actors.includes(n);return o.route===r&&(!o.actors||n!=null&&o.actors.includes(n))})}function H(e,t){let n=t.split("."),r=(i,s)=>{let a=i;for(let c of s){if(a==null||typeof a!=="object")return;a=a[c]}return a},o=r(e,n);if(o!==void 0)return o;if(n[0]==="source"){let i=r(e,["source"]),s=r(i,n.slice(1));if(s!==void 0)return s;let a=r(i,["data"]),c=r(a,n.slice(1));if(c!==void 0)return c}return r(r(e,["data"]),n)}function Ee(e){return e!=null&&typeof e==="object"&&!Array.isArray(e)?e:void 0}function pm(e,t){if(typeof t!=="string"||!t.startsWith("#/"))return;let n=e;for(let r of t.slice(2).split("/")){let o=Ee(n);if(!o)return;let i=r.replaceAll("~1","/").replaceAll("~0","~");n=o[i]}return Ee(n)}function Xr(e,t){return pm(e,t.$ref)??t}function um(e){let t=Array.isArray(e)?e:[e];return t.length>0&&t.every((n)=>n==="string"||n==="number"||n==="integer"||n==="boolean"||n==="null")}function ea(e,t){let n=Xr(e,t);if(um(n.type))return!0;if(Object.hasOwn(n,"const")&&(n.const==null||typeof n.const==="string"||typeof n.const==="number"||typeof n.const==="boolean"))return!0;if(Array.isArray(n.enum)&&n.enum.length>0&&n.enum.every((r)=>r==null||typeof r==="string"||typeof r==="number"||typeof r==="boolean"))return!0;for(let r of[n.anyOf,n.oneOf])if(Array.isArray(r)&&r.length>0&&r.every((o)=>{let i=Ee(o);return i?ea(e,i):!1}))return!0;return!1}function hn(e,t,n,r){let o=Xr(e,t);if(n&&ea(e,o)){r.set(n,Object.freeze({path:n,...typeof o.title==="string"?{label:o.title}:{},...typeof o.description==="string"?{description:o.description}:{},filterable:!0,sortable:!0}));return}let i=Ee(o.properties);if(i)for(let[s,a]of Object.entries(i)){let c=Ee(a);if(!c)continue;hn(e,c,n?`${n}.${s}`:s,r)}if(Array.isArray(o.allOf))for(let s of o.allOf){let a=Ee(s);if(a)hn(e,a,n,r)}}class Jr{fields=new Map;add(e,t){return this.fields.set(e,Object.freeze({path:e,...t?{label:t}:{},filterable:!0,sortable:!0})),this}addObjectSchema(e,t=""){return hn(e,e,t,this.fields),this}addArrayOutput(e){let t=Xr(e,e),n=t.type;if(n!=="array"&&!(Array.isArray(n)&&n.includes("array")))throw Error("Query output JSON Schema must describe an array.");let r=Ee(t.items);if(!r)throw Error("Query output JSON Schema must describe array items.");return hn(e,r,"",this.fields),this}has(e){return this.fields.has(e)}require(e,t){let n=this.fields.get(e);if(!(t==="filter"?n?.filterable:n?.sortable))throw Error(`Field ${e} does not support query ${t}.`)}list(){return Object.freeze([...this.fields.values()].sort((e,t)=>e.path.localeCompare(t.path)))}}function ta(e){return e==null||typeof e==="string"||typeof e==="number"&&Number.isFinite(e)||typeof e==="boolean"}class Gr{sources=new Set;sourcesByPath=new Map;sourcesByType=new Map;sourcesByProp=new Map;blocks=new Set;blocksBySource=new Map;blocksByType=new Map;blocksByProp=new Map;replace(e,t){this.delete(e.path),this.sources.add(e),this.sourcesByPath.set(e.path,e),this.add(this.sourcesByType,e.type,e);for(let r of Object.keys(e.data))if(t.has(r))this.add(this.sourcesByProp,r,e);let n=e.blocks.map((r)=>Object.freeze({source:e,block:r}));this.blocksBySource.set(e.path,n);for(let r of n){this.blocks.add(r),this.add(this.blocksByType,r.block.type,r);for(let o of Object.keys(r.block.data))if(t.has(o))this.add(this.blocksByProp,o,r)}}delete(e){let t=this.sourcesByPath.get(e);if(t){this.sources.delete(t),this.sourcesByPath.delete(e),this.remove(this.sourcesByType,t.type,t);for(let n of Object.keys(t.data))this.remove(this.sourcesByProp,n,t)}for(let n of this.blocksBySource.get(e)??[]){this.blocks.delete(n),this.remove(this.blocksByType,n.block.type,n);for(let r of Object.keys(n.block.data))this.remove(this.blocksByProp,r,n)}this.blocksBySource.delete(e)}sourceCandidates(e){let t=e.type?this.sourcesByType.get(e.type)??[]:this.sources;for(let n of e.has){let r=this.sourcesByProp.get(n)??new Set;t=[...t].filter((o)=>r.has(o))}return t}blockCandidates(e){let t=e.type?this.blocksByType.get(e.type)??[]:this.blocks;for(let n of e.has){let r=this.blocksByProp.get(n)??new Set;t=[...t].filter((o)=>r.has(o))}return t}add(e,t,n){let r=e.get(t)??new Set;r.add(n),e.set(t,r)}remove(e,t,n){let r=e.get(t);if(r?.delete(n),r?.size===0)e.delete(t)}}function na(e){return`actor:${e}`}function lm(e){return e.startsWith("actor:")?e.slice(6):void 0}class Yr{maxScopesPerPlan;byPlan=new Map;byDependency=new Map;constructor(e){this.maxScopesPerPlan=e}replace(e,t,n){let r=this.byPlan.get(e)??new Map,o=r.get(t)??new Set;r.delete(t),r.set(t,new Set(n)),this.byPlan.set(e,r);for(let i of o)if(!n.has(i))this.unlink(i,e,t);for(let i of n)if(!o.has(i))this.link(i,e,t);while(r.size>this.maxScopesPerPlan){let i=r.keys().next().value;if(i===void 0)break;this.deleteScope(e,i)}}deleteScope(e,t){let n=this.byPlan.get(e),r=n?.get(t);if(!n||!r)return;n.delete(t);for(let o of r)this.unlink(o,e,t);if(n.size===0)this.byPlan.delete(e)}clear(e,t){let n=t?t.map(na):[...this.byPlan.get(e)?.keys()??[]];for(let r of n)this.deleteScope(e,r)}hasDependents(e){return this.byDependency.has(e)}dependentsOf(e,t){let n=[];for(let[r,o]of this.byDependency.get(e)??[]){if(t){let s=t.filter((a)=>o.has(na(a)));if(s.length)n.push({key:r,actors:s});continue}if(o.has("anonymous")){n.push({key:r});continue}let i=[...o].flatMap((s)=>{let a=lm(s);return a?[a]:[]});if(i.length)n.push({key:r,actors:i})}return n}link(e,t,n){let r=this.byDependency.get(e)??new Map,o=r.get(t)??new Set;o.add(n),r.set(t,o),this.byDependency.set(e,r)}unlink(e,t,n){let r=this.byDependency.get(e),o=r?.get(t);if(o?.delete(n),o?.size===0)r?.delete(t);if(r?.size===0)this.byDependency.delete(e)}}var dm=new WeakMap,mm=new WeakMap;function kt(e,t=new WeakMap){if(Array.isArray(e)){let o=t.get(e);if(o)return o;let i=[];t.set(e,i);for(let s of e)i.push(kt(s,t));return Object.freeze(i)}if(e==null||typeof e!=="object")return e;let n=t.get(e);if(n)return n;let r=Object.create(null);t.set(e,r);for(let[o,i]of Object.entries(e))r[o]=kt(i,t);return Object.freeze(r)}function ra(e,t){let n=e.get(t);if(!n)n=new WeakMap,e.set(t,n);return n}function fm(e){return Object.freeze({title:e.title,...e.description?{description:e.description}:{},...e.image?{image:e.image}:{}})}function hm(e){return Object.freeze({...e.title?{title:e.title}:{},...e.description?{description:e.description}:{},...e.image?{image:e.image}:{}})}function oa(e,t,n){let r;return Object.freeze({id:t.id,type:t.type,href:`${y(e)}#${encodeURIComponent(t.id)}`,blockType:n.blockType(t),data:kt(t.data),body:t.body,get lists(){return t.lists},get tasks(){return t.tasks},get meta(){return r??=hm(fr(t,e))}})}function Pt(e,t){let n=t.sourceType(e),r=ra(mm,e),o=r.get(n);if(o)return o;let i=Object.freeze({id:e.id,type:e.type,href:y(e),sourceType:n,qualifiers:Object.freeze([...e.qualifiers]),data:kt(e.data),meta:fm(te(e))});return r.set(n,i),i}function Kr(e,t,n){return Object.freeze({...oa(e,t,n),source:Pt(e,n)})}function Zr(e,t){let n=t.sourceType(e),r=ra(dm,e),o=r.get(n);if(o)return o;let i=Pt(e,t),s=Object.freeze({...i,data:kt(e.data),body:e.body,blocks:Object.freeze(e.blocks.map((a)=>oa(e,a,t)))});return r.set(n,s),s}var ia=1000,sa=2000,aa=256,gm="query";function yn(){throw Error("Query inputs and results must contain only JSON values.")}function ua(e){if(e===null||typeof e==="string"||typeof e==="boolean")return e;if(typeof e==="number"&&Number.isFinite(e))return e;return yn()}function la(e){let t=Object.getPrototypeOf(e);if(t!==Object.prototype&&t!==null)yn();return e}function no(e,t=new WeakSet){if(e==null||typeof e!=="object")return ua(e);if(t.has(e))return yn();t.add(e);let n=Array.isArray(e)?e.map((r)=>no(r,t)):Object.fromEntries(Object.entries(la(e)).sort(([r],[o])=>r.localeCompare(o)).map(([r,o])=>[r,no(o,t)]));return t.delete(e),n}function da(e){return JSON.stringify(no(e))}function gn(e,t=new WeakSet){if(e==null||typeof e!=="object")return ua(e);if(t.has(e))return yn();if(t.add(e),Array.isArray(e)){let r=e.map((o)=>gn(o,t));return t.delete(e),Object.freeze(r)}let n=Object.fromEntries(Object.entries(la(e)).map(([r,o])=>[r,gn(o,t)]));return t.delete(e),Object.freeze(n)}async function ma(e,t,n){let r=await e["~standard"].validate(t);if(r.issues)throw Error(`${n}: ${q(r.issues)}`);return r.value}function ym(e){if(e!==void 0&&typeof e!=="string")throw Error("Query from must be a string.");let t=e?.trim()||"/";if(t.startsWith("~/"))return`~${Q(`/${t.slice(2)}`)}`;return Q(t)}function wm(e){if(e==null)return ia;if(!Number.isSafeInteger(e)||e<0)throw Error("Query limit must be a non-negative safe integer.");return Math.min(e,ia)}function xm(e){if(e!==void 0&&(e===null||typeof e!=="object"||Array.isArray(e)))throw Error("Query where must be an object.");let t=Object.entries(e??{}).sort(([n],[r])=>n.localeCompare(r));for(let[n,r]of t){if(!n.trim())throw Error("Query filter fields cannot be empty.");if(!ta(r))throw Error(`Query filter ${n} must compare a scalar value.`)}return Object.freeze(Object.fromEntries(t))}function bm(e){if(e!==void 0&&!Array.isArray(e))throw Error("Query sort must be a list.");return Object.freeze((e??[]).map((t)=>{if(t==null||typeof t!=="object")throw Error("Each query sort must be an object.");let n=t.by?.trim();if(!n)throw Error("Query sort fields cannot be empty.");let r=t.direction??"asc";if(r!=="asc"&&r!=="desc")throw Error(`Unsupported query sort direction: ${r}`);return Object.freeze({by:n,direction:r})}))}function Sm(e){let t=e==null?[]:typeof e==="string"?[e]:e;if(!Array.isArray(t)||t.some((n)=>typeof n!=="string"))throw Error("Query has must be a string or list of strings.");return Object.freeze([...new Set(t.map((n)=>n.trim()))].filter(Boolean).sort((n,r)=>n.localeCompare(r)))}function Rt(e,t){return Object.entries(t).every(([n,r])=>Object.is(H(e,n),r))}function ca(e,t){if(e===t)return 0;if(e===void 0||e===null)return 1;if(t===void 0||t===null)return-1;if(typeof e==="number"&&typeof t==="number")return e<t?-1:1;if(typeof e==="boolean"&&typeof t==="boolean")return e===!1?-1:1;let n=String(e),r=String(t);return n<r?-1:n>r?1:0}function pa(e){if(e!=null&&typeof e==="object"){let t=e;if(typeof t.id==="string"){let n=t.source;if(n!=null&&typeof n==="object"&&typeof n.id==="string")return`${n.id}#${t.id}`;return t.id}}return da(e)}function eo(e,t){return[...e].sort((n,r)=>{for(let o of t){let i=ca(H(n,o.by),H(r,o.by));if(i)return o.direction==="desc"?-i:i}return ca(pa(n),pa(r))})}function to(e,t,n){if(t!=="/"&&e!==t&&!e.startsWith(`${t}/`))return!1;if(n||e===t)return!0;return!(t==="/"?e.slice(1):e.slice(t.length+1)).includes("/")}function fa(e,t,n){let r=new Jr;if(t.query==="sources"||t.query==="blocks"){r.add("id").add("type").add("href").add("meta.title").add("meta.description").add("meta.image");let i=(t.type?[t.type]:t.query==="sources"?e.sourceTypes().map(({type:s})=>s):e.blockTypes().map(({type:s})=>s)).flatMap((s)=>(t.query==="sources"?e.sourceSchemas(s):e.blockSchemas(s)).map(({outputJsonSchema:a})=>a));for(let s of i)r.addObjectSchema(s);for(let s of e.props())r.addObjectSchema(s.outputJsonSchema,s.name);if(t.query==="blocks"){r.add("source.id").add("source.type").add("source.href"),r.add("source.meta.title");for(let s of e.sourceTypes())for(let a of e.sourceSchemas(s.type))r.addObjectSchema(a.outputJsonSchema,"source");for(let s of e.props())r.addObjectSchema(s.outputJsonSchema,`source.${s.name}`)}}else if(n)r.addArrayOutput(n);for(let o of Object.keys(t.where))r.require(o,"filter");for(let o of t.sort)r.require(o.by,"sort");return r}async function vm(e,t,n={}){let r=t==="sources"||t==="blocks",o=r?void 0:e.query(t);if(!r&&!o)throw Error(`Unknown query: ${t}`);let i=n.input;if(o?.input)i=gn(await ma(o.input,n.input,`Invalid ${t} query input`));else if(n.input!==void 0)throw Error(`Query ${t} does not accept input.`);let s=n,a=new Set(["from","input","where","sort","limit",...r?["type","has","recursive"]:[]]);for(let u of Object.keys(n))if(!a.has(u))throw Error(`Unknown query request field: ${u}`);if(r&&s.type!==void 0&&typeof s.type!=="string")throw Error("Query type must be a string.");if(r&&s.recursive!==void 0&&typeof s.recursive!=="boolean")throw Error("Query recursive must be a boolean.");let c={query:t,from:ym(n.from),...o?.input?{input:i}:{},where:xm(n.where),sort:bm(n.sort),limit:wm(n.limit),...r&&s.type?.trim()?{type:s.type.trim()}:{},has:r?Sm(s.has):Object.freeze([]),recursive:r?s.recursive!==!1:!0};for(let u of c.has)if(!e.prop(u))throw Error(`Unknown registered data prop in query has: ${u}`);let p=Object.freeze({...c,key:da(c)});return fa(e,p,o?.outputJsonSchema),p}function Se(e){return{type:"plugin",plugin:gm,key:e.key}}function ro(e,t){let n=t.query==="sources"||t.query==="blocks"?void 0:e.query(t.query);return fa(e,t,n?.outputJsonSchema).list()}class oo{engine;index=new Gr;plans=new Map;caches=new Map;dependencies=new Yr(aa);executingPlans=new Set;registeredProps;constructor(e){this.engine=e}indexSource(e){this.registeredProps??=new Set(this.engine.schema.props().map(({name:t})=>t)),this.index.replace(e,this.registeredProps)}unindexSource(e){this.index.delete(e)}viewQuery(e){return Object.freeze({sources:(t)=>this.execute(e,"sources",t),blocks:(t)=>this.execute(e,"blocks",t),run:(t,n)=>this.execute(e,t,n)})}run(e,t,n){return this.execute(e,t,n)}async prepare(e,t={}){let n=e==="sources"||e==="blocks"?void 0:this.engine.registeredQuery(e),r=typeof e==="string"?e:n?.id;if(!r||r!=="sources"&&r!=="blocks"&&!n)throw Error(`Unknown query: ${typeof e==="string"?e:"unregistered definition"}`);let o=await vm(this.engine.schema,r,t);return this.plans.delete(o.key),this.plans.set(o.key,o),this.prunePlans(o.key),o}async fields(e,t={}){let n=await this.prepare(e,t);return ro(this.engine.schema,n)}dependency(e){return Se(e)}transition(e,t){let n=[];for(let r of this.plans.values()){if(r.query!=="sources"&&r.query!=="blocks")continue;let o=this.transitionActors(r,e,t);if(o===!1)continue;n.push({key:r.key,...o?{actors:Object.freeze([...o].sort())}:{}})}return this.cascade(n)}invalidateDependencies(e){let t=[];for(let n of e)t.push(...this.dependencies.dependentsOf(re(n)));return this.cascade(t)}async execute(e,t,n={},r){let o=await this.prepare(t,n);r?.add(`query:${o.key}`);let i=e.principal.type==="actor"?`actor:${e.principal.actor.id}`:"anonymous",s=this.caches.get(o.key);if(!s)s=new Map,this.caches.set(o.key,s);let a=s.get(i);if(a)return s.delete(i),s.set(i,a),a;this.executingPlans.add(o.key);let c=this.resolve(e,o,i).then((p)=>o.query==="sources"||o.query==="blocks"?p:gn(p)).catch((p)=>{throw s.delete(i),p}).finally(()=>this.executingPlans.delete(o.key));s.set(i,c);while(s.size>aa){let p=s.keys().next().value;if(p===void 0)break;s.delete(p),this.dependencies.deleteScope(o.key,p)}return c}async resolve(e,t,n){let r=this.resolvedScope(e,t.from);if(!r)return Object.freeze([]);if(t.query==="sources"){let p=[];for(let u of this.index.sourceCandidates(t)){if(!to(u.id,r,t.recursive))continue;if(this.engine.readAccess(e.principal,u)==="denied")continue;let l=Pt(u,this.engine.schema);if(Rt(l,t.where))p.push(l)}return Object.freeze(eo(p,t.sort).slice(0,t.limit))}if(t.query==="blocks"){let p=[];for(let u of this.index.blockCandidates(t)){if(!to(u.source.id,r,t.recursive))continue;if(this.engine.readAccess(e.principal,u.source)==="denied")continue;let l=Kr(u.source,u.block,this.engine.schema);if(Rt(l,t.where))p.push(l)}return Object.freeze(eo(p,t.sort).slice(0,t.limit))}let o=this.engine.registeredQuery(t.query);if(!o)throw Error(`Unknown query: ${t.query}`);let i=new Set,s=Object.freeze({sources:(p)=>this.execute(e,"sources",p,i),blocks:(p)=>this.execute(e,"blocks",p,i),run:(p,u)=>this.execute(e,p,u,i)}),a=await o.definition.resolve(t.input,{view:e,from:r,query:s,depend:(p)=>i.add(re(p)),...this.engine.appContext(o.plugin).database?{database:this.engine.appContext(o.plugin).database}:{}}),c=await ma(o.definition.output,a,`Invalid ${o.id} query output`);return this.recordDependencies(t.key,n,i),Object.freeze(eo(c.filter((p)=>Rt(p,t.where)),t.sort).slice(0,t.limit))}resolvedScope(e,t){if(!t.startsWith("~/"))return t;if(e.principal.type!=="actor")return;return Q(this.engine.environment.path.join(e.principal.actor.home,t.slice(2)))}transitionActors(e,t,n){if(!e.from.startsWith("~/"))return this.transitionMatches(e,t,n,e.from)?void 0:!1;let r=new Set;for(let o of[t,n]){if(!o)continue;let i=this.engine.homeActorId(o.path),s=i?this.engine.actor(i):void 0;if(!s)continue;let a=Q(this.engine.environment.path.join(s.home,e.from.slice(2)));if(this.sourceMatches(e,o,a))r.add(s.id)}return r.size?r:!1}transitionMatches(e,t,n,r){return[t,n].some((o)=>o&&this.sourceMatches(e,o,r))}sourceMatches(e,t,n){if(!to(t.id,n,e.recursive))return!1;if(e.query==="sources"){if(e.type&&t.type!==e.type)return!1;if(e.has.some((o)=>!Object.hasOwn(t.data,o)))return!1;let r=Pt(t,this.engine.schema);return Rt(r,e.where)}return t.blocks.some((r)=>{if(e.type&&r.type!==e.type)return!1;if(e.has.some((o)=>!Object.hasOwn(r.data,o)))return!1;return Rt(Kr(t,r,this.engine.schema),e.where)})}recordDependencies(e,t,n){this.dependencies.replace(e,t,n)}invalidateCaches(e,t){if(!t){this.caches.delete(e);return}let n=this.caches.get(e);if(!n)return;for(let r of t)n.delete(`actor:${r}`);if(n.size===0)this.caches.delete(e)}prunePlans(e){if(this.plans.size<=sa)return;for(let t of this.plans.keys()){if(this.plans.size<=sa)break;if(t===e||this.executingPlans.has(t)||this.dependencies.hasDependents(`query:${t}`)||this.engine.dependentsOf(Se({key:t})).size>0)continue;this.removePlan(t)}}removePlan(e){this.plans.delete(e),this.caches.delete(e),this.dependencies.clear(e)}cascade(e){let t=[...e],n=new Map;while(t.length){let r=t.shift(),o=n.get(r.key);if(n.has(r.key)&&o===void 0)continue;let i=r.actors;if(!i)n.set(r.key,void 0);else{if(i=i.filter((a)=>!o?.has(a)),!i.length)continue;let s=o??new Set;for(let a of i)s.add(a);n.set(r.key,s)}this.invalidateCaches(r.key,i),t.push(...this.dependencies.dependentsOf(`query:${r.key}`,i)),this.dependencies.clear(r.key,i)}return Object.freeze([...n].map(([r,o])=>Object.freeze({key:r,...o?{actors:Object.freeze([...o].sort())}:{}})))}}function ha(e,t,n){for(let r of n)for(let o of e.dependentsOf(Se(r))){let i=e.pageCache.get(o);if(!i)continue;if(r.actors)t.addActors(i.route,r.actors);else t.add(i.route)}}function ga(e,t,n){ha(e,t,e.queries.invalidateDependencies(n))}function io(e,t,n,r,o){ha(e,t,[...e.queries.transition(n,r),...e.queries.invalidateDependencies([{type:"source",path:o}])])}class so{engine;plugins;compiler;listeners=new Set;commitQueue=Promise.resolve();constructor(e,t,n){this.engine=e;this.plugins=t;this.compiler=n}onSync(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}emit(e){if(!e.targets.length)return;for(let t of this.listeners)t(e)}referrerPaths(e){return this.engine.graph.linksTo(e).map((t)=>t.from)}addPageInvalidations(e,t){for(let n of t){let r=this.compiler.pageCache.get(n);if(r)e.add(r.route)}}applyPluginInvalidations(e,t,n){for(let r of this.plugins.invalidations(n,this.engine)){let o=[...r.dependencies??[]];ga(this.engine,t,o);for(let i of o)for(let s of this.compiler.dependentsOf(re(i)))e.add(s);for(let i of r.sourceIds??[]){let s=this.engine.repo.get(i);if(s&&this.compiler.isPage(s))e.add(s.path)}for(let i of r.targets??[])if(i.type==="actor")t.addActorTargets(i.actors);else if(i.actors==null)t.add(i.route);else t.addActors(i.route,i.actors)}}async rebuildGraph(){await this.engine.perf.measureAsync("graph.rebuild",()=>this.engine.graph.rebuild())}async refreshTransitions(e){return this.engine.perf.measureAsync("notify",async()=>{let t=new fn,n=new Set;for(let r of e){this.applyPluginInvalidations(n,t,r);let o=this.engine.repo.graphPath(r.path);this.engine.log.debug("rebuild",{path:o});let i=this.compiler.pageCache.get(o);if(i)t.add(i.route);for(let s of this.referrerPaths(o))n.add(s);for(let s of this.compiler.dependentsOf(o))n.add(s);if(!r.after){if(io(this.engine,t,r.before,r.after,o),r.before)this.engine.clearAuthorityError(r.before.id);this.engine.forgetNode(o),this.compiler.forgetCompiled(o);continue}if(this.engine.indexSource(r.after,!0),io(this.engine,t,r.before,r.after,o),this.compiler.isPage(r.after))n.add(r.after.path);else this.compiler.pageCache.delete(r.after.path)}await this.rebuildGraph();for(let r of e)for(let o of this.referrerPaths(r.path))n.add(o);return await this.compiler.recompilePages(n),this.addPageInvalidations(t,n),t.event()},e.map((t)=>t.path).join(","))}dropNode(e){let n=(this.engine.repo.atPath(e)??this.engine.repo.get(e))?.path??this.engine.repo.graphPath(e);this.engine.repo.remove(n),this.engine.forgetNode(n),this.compiler.forgetCompiled(n)}commit(e){return this.commitPrepared(async()=>e)}commitPrepared(e){let t=this.commitQueue.then(async()=>{let n=await e();if(!n.changes.length)return{applied:[]};return this.commitNow(n)});return this.commitQueue=t.then(()=>{return},()=>{return}),t}async commitNow(e){let t=new Map(e.changes.map((r)=>{let o=this.engine.repo.graphPath(r.path);return[o,this.engine.repo.atPath(o)]})),n=await this.engine.repo.commit(e);if(await this.refresh(n,t),n.error)throw n.error;return n}async refresh(e,t=new Map){let n=await this.refreshTransitions(e.applied.map((r)=>{let o=this.engine.repo.graphPath(r.path);return{path:o,before:t.get(o),after:this.engine.repo.atPath(o)}}));this.emit(n)}async syncSource(e){let t=this.engine.repo.graphPath(e),n=this.engine.repo.atPath(t),r=await this.engine.repo.upsert(e,{onError:"preserve"});if(r.type==="error"){this.engine.log.error("source.parse",{path:t,message:r.error.message});return}let o=r.type==="updated"?r.source:void 0;if(o&&o.content===n?.content)return;let i=await this.refreshTransitions([{path:t,before:n,after:o}]);this.emit(i)}invalidateAsset(e){this.invalidateAssets([e])}invalidateAssets(e){let t=[...e];this.engine.bumpAssetRevisions(t);let n=new fn;for(let r of t){let o=this.engine.repo.graphPath(r);this.addPageInvalidations(n,this.compiler.dependentsOf(o))}this.emit(n.event())}async syncFromStorage(e){return this.engine.perf.measureAsync("sync-from-storage",async()=>{if(!this.engine.repo.storagePath(e))return;await this.syncSource(this.engine.repo.graphPath(e).slice(1))},e)}}function Pm(e,t){if(t.type==="file")throw Error(`Browser bundle ${e} emitted unsupported file asset ${t.path}.`);return t.type==="style"?{type:"stylesheet",name:`${e}.css`,text:t.text}:{type:"script",name:`${e}.js`,text:t.text,module:!0}}async function ya(e,t,n){let r=n.replaceAll(":","-"),o=new Set;return(await e.bundle(t)).map((s)=>{let a=Pm(r,s);if(o.has(a.name))throw Error(`Browser bundle ${r} emitted duplicate ${a.name}.`);return o.add(a.name),a}).sort((s,a)=>He(s)-He(a))}function wa(e={}){let t=new Map;for(let n of e.capabilities??[]){let r=t.get(n.plugin);if(!r)r=new Set,t.set(n.plugin,r);r.add(n.key)}return Object.freeze({mode:e.mode??"production",target:e.target??"server",has(n,r){return t.get(n)?.has(r)??!1}})}function Rm(e){return e.type==="authenticated"?Object.freeze({type:"authenticated",subject:e.actor}):Object.freeze({type:"anonymous"})}function Cm(e,t){return t==="/"||e===t||e.startsWith(`${t}/`)}function Am(e,t,n){if(t.type!=="actor"||!n.startsWith("~/"))return;let r=n.slice(2).split(/[?#]/,1)[0];if(!r)return;let o=e.environment.path.join(t.actor.home,r);try{Q(o)}catch{return}if(!Cm(o,t.actor.home))return;return e.repo.get(o)??e.repo.atPath(o)??e.resolve(o)}class ao{#e;identity;principal;query;constructor(e,t,n){this.#e=e,this.identity=t,this.principal=n,this.query=e.queries.viewQuery(this),Object.freeze(this)}readSource(e){let t=this.readableSource(e);if(!t)return;return Zr(t,this.#e.schema)}async describeSource(e){let t=this.readableSource(e);if(!t)return;let n=await this.#e.actionAffordances(this.principal,t);return Object.freeze({source:Zr(t,this.#e.schema),relations:Object.freeze(this.relationsFrom(t)),actions:n})}readableSource(e){let t=this.#e.repo.get(e);return t&&this.#e.readAccess(this.principal,t)!=="denied"?t:void 0}relationsFrom(e){return this.#e.graph.linksFrom(e.path).map((t)=>{let n={rel:t.directive?.name??"link",qualifiers:Object.freeze([...t.directive?.qualifiers??[]]),href:t.href,...t.label?{label:t.label}:{},...t.fragment?{fragment:t.fragment}:{}};if(t.type==="source"&&t.to){let r=this.#e.repo.atPath(t.to);if(r&&this.#e.readAccess(this.principal,r)!=="denied")return Object.freeze({...n,type:"source",target:Object.freeze({type:"source",id:r.id})});return Object.freeze({...n,type:"unresolved"})}if(t.type==="actor-relative"){let r=Am(this.#e,this.principal,t.href);if(r&&this.#e.readAccess(this.principal,r)!=="denied")return Object.freeze({...n,type:"source",target:Object.freeze({type:"source",id:r.id})})}return Object.freeze({...n,type:t.type})})}}function xa(e,t){return new ao(e,Rm(t),Te(t))}function ba(e,t){return new ao(e,t?Object.freeze({type:"inspection",subject:t}):Object.freeze({type:"anonymous"}),t?Object.freeze({type:"actor",actor:t}):{type:"anonymous"})}class co{environment;runtime;repo;graph;profiles;actionsRoot;perf=new yr;log;bundles=new Map;assetRevisions=new Map;generatedAssets;actorIndex;accessPolicy;authorityErrors=new Map;sourceDiagnosticStore;pluginHost;queries;compiler;sourceSync;constructor(e,t,n,r,o,i=new B,s,a="throw",c=U(e.rootPath,".pathmx/state")){this.repo=e,this.environment=t,this.runtime=wa(s),this.generatedAssets=this.runtime.target==="static"?new nn(Number.POSITIVE_INFINITY):new nn,this.graph=new gr(e),this.actorIndex=n,this.profiles=r,this.accessPolicy=o,this.log=i,this.pluginHost=new _r(new Ie(t.database,c)),this.queries=new oo(this),this.compiler=new Wr(this,this.pluginHost),this.sourceSync=new so(this,this.pluginHost,this.compiler),this.sourceDiagnosticStore=new er(a,i),this.actionsRoot=cs(e.rootPath)}registerPlugin(e){this.pluginHost.register(e)}freezePlugins(){this.pluginHost.freeze()}setupPlugins(){return this.pluginHost.setup(this)}appContext(e){return this.pluginHost.appContext(e,this)}get plugins(){return this.pluginHost.plugins}get schema(){return this.pluginHost.schema}registeredQuery(e){return this.pluginHost.query(e)}actor(e){return this.actorIndex.findActorById(e)}get pageCache(){return this.compiler.pageCache}dependentsOf(e){return this.compiler.dependentsOf(e)}dependenciesOf(e){return this.compiler.dependenciesOf(e)}bundle(e){let t=String(e),n=this.bundles.get(t);if(!n)n=this.perf.measureAsync("bundle",()=>this.environment.bundle(e),t),this.bundles.set(t,n);return n}documentAssetBag(e=[]){let t=hs(e);return{...t,addBrowserBundle:async(r,o)=>{t.addAsset(...await ya(this,r,o))}}}async documentAssets(e){let{assets:t,addAsset:n,addBrowserBundle:r}=this.documentAssetBag(),o={page:e,addAsset:n,addBrowserBundle:r};return await this.pluginHost.documentAssets(o,this),n(...e?.assets??[]),t.map((i)=>this.resolveDocumentAsset(i)).sort((i,s)=>He(i)-He(s))}servedAsset(e){return this.generatedAssets.get(e)}generatedAssetEntries(){return this.generatedAssets.entries()}async publishAsset(e,t,n=t.type){return this.generatedAssets.publishBlob(e,t,n)}onSync(e){return this.sourceSync.onSync(e)}resolveDocumentAsset(e){if(e.type==="stylesheet"&&"name"in e)return{type:"stylesheet",href:this.storeNamed(e.name,e.text,"text/css; charset=utf-8"),...e.media?{media:e.media}:{}};if(e.type==="script"&&"name"in e)return{type:"script",href:this.storeNamed(e.name,e.text,"text/javascript; charset=utf-8"),module:e.module};if(e.type==="script"&&"source"in e){let t=this.assetRevisions.get(e.source);return{type:"script",href:t?`${e.source}?pmx=${t}`:e.source,module:e.module}}return e}bumpAssetRevisions(e){for(let t of e){let n=this.repo.graphPath(t);this.assetRevisions.set(n,(this.assetRevisions.get(n)??0)+1)}}storeNamed(e,t,n){return this.generatedAssets.publishText(e,t,n)}async documentHead(e){return gs(await this.documentAssets(e))}resolve(e){let t=qe(this.repo,e);return t?.type==="page"?t.source:void 0}resolveCredentials(e){return this.pluginHost.resolveCredentials(e,this.actorIndex,this)}view(e){return xa(this,e)}credentialRequest(e){return this.pluginHost.credentialRequest(e,this.actorIndex)}readyCredentials(){return this.pluginHost.readyCredentials(this.actorIndex)}serverRoute(e,t=new URL(e.url),n=t){return this.pluginHost.serverRoute(e,t,this,n)}hasPlugin(e){return this.pluginHost.has(e)}pluginAction(e){return this.pluginHost.action(e)}actionAffordances(e,t){return this.pluginHost.actionAffordances(e,t,this)}closeCredentials(){return this.pluginHost.closeCredentials()}close(){return this.pluginHost.close(this)}homeActorId(e){return this.actorIndex.findHomeOwner(e)?.id}runAgentJob(e,t){return ds(this,this.actorIndex,e,t)}readAccess(e,t){return this.accessPolicy.readAccess(e,t)}inspectSourceAccess(e,t){return this.accessPolicy.inspect(e,t)}inspectSourcePermissions(e){return[...this.actorIndex.all().map((t)=>({sourceId:e.id,actorId:t.id,...this.accessPolicy.inspect({type:"actor",actor:t},e)})),{sourceId:e.id,actorId:null,...this.accessPolicy.inspect({type:"anonymous"},e)}]}inspectActorPermissions(e){let t=this.actorIndex.findActorById(e);if(!t)return;let n={type:"actor",actor:t};return this.repo.all().sort((r,o)=>r.id.localeCompare(o.id)).map((r)=>({sourceId:r.id,actorId:e,...this.accessPolicy.inspect(n,r)}))}hasSourceCapability(e,t,n){return this.accessPolicy.hasCapability(e,t,n)}authorizeChange(e,t){return this.accessPolicy.authorizeChange(e,t)}canEmbed(e,t){return this.accessPolicy.canEmbed(e,t)}forgetNode(e){this.compiler.unindexSource(e),this.sourceDiagnosticStore.delete(e),this.pluginHost.unindex(e,this),this.queries.unindexSource(e)}clearAuthorityError(e){this.authorityErrors.delete(e)}sourceDiagnostics(){return this.sourceDiagnosticStore.all()}indexSource(e,t=!1){return this.perf.measure("index.source",()=>{this.forgetNode(e.path),this.compiler.indexSource(e),this.authorityErrors.delete(e.id);let n=(r)=>{if(this.sourceDiagnosticStore.capture(r))return!0;if(!t||!(r instanceof M||r instanceof k))return!1;return this.authorityErrors.set(e.id,r.message),this.log.error("authority.degraded",{source:e.id,message:r.message}),!0};try{or(e,this.environment.yaml)}catch(r){if(!n(r))throw r;return}this.pluginHost.index(e,this,n),this.queries.indexSource(e)},e.path)}async indexAllNodes(){this.log.info("index",{sources:this.repo.all().length});for(let e of this.repo.all())this.indexSource(e);for(let e of Gi(this.repo))this.log.warn("route.index.conflict",{dir:e.dir,winner:e.winner.path,shadowed:e.shadowed.map((t)=>t.path),rule:"first index source by id, codepoint order"});await this.perf.measureAsync("graph.rebuild",()=>this.graph.rebuild())}authorityReadiness(){let e=[...[...this.authorityErrors].map(([t,n])=>({sourceId:t,message:n})),...this.accessPolicy.diagnostics?.()??[]].filter((t,n,r)=>r.findIndex((o)=>o.sourceId===t.sourceId&&o.message===t.message)===n).sort((t,n)=>t.sourceId.localeCompare(n.sourceId)||t.message.localeCompare(n.message));return e.length?{type:"degraded",errors:e}:{type:"ready",errors:[]}}isAuthorized(e,t){return this.readAccess({type:"actor",actor:t},e)!=="denied"}isAuthorizedPath(e,t){let n=this.repo.atPath(e)??this.repo.get(e);if(n)return this.isAuthorized(n,t);return this.readAccess({type:"actor",actor:t},e)!=="denied"}compilePage(e){return this.compiler.compilePage(e)}forgetCompiledPage(e){this.compiler.forgetCompiled(e)}ensurePage(e){return this.compiler.ensurePage(e)}compileDocument(e,t,n){return this.compiler.compileDocument(e,t,n)}compileBlock(e,t,n,r,o){return this.compiler.compileBlock(e,t,n,r,o)}isPage(e){return this.compiler.isPage(e)}buildCache(){return this.compiler.buildCache()}dropNode(e){return this.sourceSync.dropNode(e)}commit(e){return this.sourceSync.commit(e)}commitPrepared(e){return this.sourceSync.commitPrepared(e)}refresh(e,t=new Map){return this.sourceSync.refresh(e,t)}syncSource(e){return this.sourceSync.syncSource(e)}invalidateAsset(e){return this.sourceSync.invalidateAsset(e)}invalidateAssets(e){return this.sourceSync.invalidateAssets(e)}syncFromStorage(e){return this.sourceSync.syncFromStorage(e)}rewrite(e,t,n,r){return this.perf.measureAsync("rewrite",()=>{let o=this.view(e);return this.rewriteWithPlugins(t,{view:o,session:e,principal:o.principal,source:n,route:y(n)},r)},n.path)}async rewriteWithPlugins(e,t,n){return this.pluginHost.renderView(e,this.compiler.planFor(t.source.path),t,this,n)}}function We(e){return{type:"meta",attrs:e}}function Sa(){return{id:"meta",documentAssets(e){e.addAsset(We({charset:"utf-8"}),We({name:"viewport",content:"width=device-width, initial-scale=1"}))},page(e,t,n){if(!n.sources.isPage(t.source))return e;let{title:r,description:o,image:i}=te(t.source);if(t.addAsset({type:"title",text:r},We({property:"og:title",content:r})),o)t.addAsset(We({name:"description",content:o}),We({property:"og:description",content:o}));if(i)t.addAsset(We({property:"og:image",content:i}));return e}}}function va(){return{id:"schema",schema:{sources:{page:{label:"Page",description:"A general rendered document.",icon:"file-text",color:"slate"},map:{label:"Map",description:"Source-type schema and presentation metadata.",icon:"map",color:"teal"}}}}}var Im=Object.freeze({type:"missing"});async function Xe(e,t){if(!await e.exists(t))return Im;return Object.freeze({type:"present",content:await e.readText(t)})}function Ct(e,t){return e.type===t.type&&(e.type==="missing"||t.type==="present"&&e.content===t.content)}var ka=16;class At extends Error{id;existingPath;incomingPath;constructor(e,t,n){super(`Duplicate source id "${e}": ${t} and ${n}`);this.name="DuplicateSourceIdError",this.id=e,this.existingPath=t,this.incomingPath=n}}class It extends Error{path;constructor(e,t){let n=t instanceof Error?t.message:String(t);super(`Failed to load source ${e}: ${n}`);this.name="SourceLoadError",this.path=e,this.cause=t}}class pe extends Error{constructor(e){super(e);this.name="SourceCommitError"}}class wn extends pe{path;constructor(e){super(`Source changed before commit: ${e}`);this.name="SourceConflictError",this.path=e}}function Pa(e){return e instanceof Error&&"code"in e&&e.code==="ENOENT"}class po{rootPath;environment;byId=new Map;byPath=new Map;revisionValue=0;constructor(e,t){this.rootPath=e,this.environment=t}graphPath(e){return this.environment.path.join("/",e.replaceAll("\\","/"))}pathToId(e){return Pe(this.graphPath(e),{})}get(e){return this.byId.get(e)}atPath(e){let t=this.graphPath(e).replace(/\/$/,"")||"/";return this.byPath.get(t)}sourceAtPath(e){return this.atPath(e)}all(){return[...this.byPath.values()]}get revision(){return this.revisionValue}async load(){this.byId.clear(),this.byPath.clear(),this.revisionValue++;let e=[...await this.environment.storage.list(this.rootPath)].filter((t)=>t.endsWith(".md"));for(let t=0;t<e.length;t+=ka){let n=await Promise.all(e.slice(t,t+ka).map((r)=>this.readListedSource(r)));for(let r of n){if(!r)continue;if("error"in r)throw r.error;try{this.put(se(r.path,r.content,this.environment.yaml))}catch(o){if(o instanceof At)throw o;throw new It(r.path,o)}}}}async readListedSource(e){let t=this.graphPath(e),n=this.storagePath(e);if(!n)return;try{return{path:t,content:await this.environment.storage.readText(n)}}catch(r){if(Pa(r))return;try{if(!await this.environment.storage.exists(n))return}catch{}return{error:new It(t,r)}}}put(e){Y(e.id);let t=this.byId.get(e.id);if(t&&t.path!==e.path)throw new At(e.id,t.path,e.path);let n=this.byPath.get(e.path);if(n&&n.id!==e.id)this.byId.delete(n.id);return this.byId.set(e.id,e),this.byPath.set(e.path,e),this.revisionValue++,e}async upsert(e,t={}){let n=t.onError??"preserve",r=this.graphPath(e),o=this.storagePath(e),i=this.atPath(r);if(!o)return this.drop(i),{type:"deleted"};try{if(!await this.environment.storage.exists(o))return this.drop(i),{type:"deleted"};let s=await this.environment.storage.readText(o);if(i&&i.content===s)return{type:"updated",source:i};let a=se(r,s,this.environment.yaml);return this.put(a),{type:"updated",source:a}}catch(s){if(Pa(s))return this.drop(i),{type:"deleted"};if(s instanceof At){if(n==="throw")throw s;return{type:"error",error:new It(r,s),source:i}}let a=new It(r,s);if(n==="throw")throw a;return{type:"error",error:a,source:i}}}storagePath(e){let t=e.replaceAll("\\","/").replace(/^\/+/,"");if(!t||t.split("/").includes(".."))return;let n=this.rootPath.replaceAll("\\","/"),r=n==="/"?"/":n.replace(/\/+$/,"");if(r==="/")return`/${t}`;return r?`${r}/${t}`:t}async isFile(e){let t=this.storagePath(e);if(!t)return!1;try{return await this.environment.storage.exists(t)}catch{return!1}}remove(e){this.drop(this.atPath(e))}async commit(e){let t=e.changes.map((r)=>{if(r.path.split(/[\\/]/).includes(".."))throw new pe(`Path escapes repository: ${r.path}`);return{...r,path:this.graphPath(r.path)}});this.preflight(t),await this.verifyStorage(t);let n=[];try{for(let r of t){let o=this.storagePath(r.path);if(!o)throw new pe(`Path escapes repository: ${r.path}`);if(r.type==="delete"){if(await this.environment.storage.exists(o))await this.environment.storage.delete(o)}else await this.environment.storage.writeText(o,r.content);n.push(r)}}catch(r){return await this.resync(n),{applied:n,error:r instanceof Error?r:Error(String(r))}}return await this.resync(n),{applied:n}}preflight(e){let t=new Map(this.byPath),n=new Map(this.byId);for(let r of e){if(!this.storagePath(r.path))throw new pe(`Path escapes repository: ${r.path}`);let i=t.get(r.path);if(r.type==="delete"){if(!i)throw new pe(`Path does not exist: ${r.path}`);t.delete(r.path),n.delete(i.id);continue}let s=se(r.path,r.content,this.environment.yaml);if(r.type==="create"&&i)throw new pe(`Path already exists: ${r.path}`);if(r.type==="replace"&&!i)throw new pe(`Path does not exist: ${r.path}`);if(i&&i.id!==s.id)n.delete(i.id);let a=n.get(s.id);if(a&&a.path!==r.path)throw new At(s.id,a.path,r.path);t.set(r.path,s),n.set(s.id,s)}}async verifyStorage(e){for(let t of e){let n=this.storagePath(t.path);if(!n)throw new pe(`Path escapes repository: ${t.path}`);let r=this.atPath(t.path);if(t.type!=="create"&&!r)throw new wn(t.path);let o=r?{type:"present",content:r.content}:{type:"missing"},i;try{i=await Xe(this.environment.storage,n)}catch{throw new wn(t.path)}if(!Ct(i,o))throw new wn(t.path)}}async resync(e){for(let t of e){let n=t.path.replace(/^\/+/,"");if(t.type==="delete")this.remove(t.path);else await this.upsert(n,{onError:"throw"})}}drop(e){if(!e)return;this.byId.delete(e.id),this.byPath.delete(e.path),this.revisionValue++}}async function uo(e){let t=new po(e.root,e.environment),n=new hr,r=new kr(t,n),o=new co(t,e.environment,n,n.profiles,r,e.log,e.runtime,e.diagnostics,e.stateRoot??U(e.root,".pathmx/state"));if(e.actionsRoot)o.actionsRoot=e.actionsRoot;try{o.registerPlugin(Wi(n)),o.registerPlugin(is(r)),o.registerPlugin(Sa),o.registerPlugin(va);for(let i of ie(e.plugins??[]))o.registerPlugin(i);if(o.freezePlugins(),await o.setupPlugins(),await o.perf.measureAsync("repo.load",()=>t.load()),await o.indexAllNodes(),e.diagnostics!=="collect")r.validate();if(await o.readyCredentials(),e.buildCache)await o.buildCache();return o}catch(i){throw await o.close().catch(()=>{return}),i}}var Ra='<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-bug" aria-hidden="true" focusable="false"><path d="M12 20v-9"></path><path d="M14 7a4 4 0 0 1 4 4v3a6 6 0 0 1-12 0v-3a4 4 0 0 1 4-4z"></path><path d="M14.12 3.88 16 2"></path><path d="M21 21a4 4 0 0 0-3.81-4"></path><path d="M21 5a4 4 0 0 1-3.55 3.97"></path><path d="M22 13h-4"></path><path d="M3 21a4 4 0 0 1 3.81-4"></path><path d="M3 5a4 4 0 0 0 3.55 3.97"></path><path d="M6 13H2"></path><path d="m8 2 1.88 1.88"></path><path d="M9 7.13V6a3 3 0 1 1 6 0v1.13"></path></svg>';var Ca='<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-chevron-right" aria-hidden="true" focusable="false"><path d="m9 18 6-6-6-6"></path></svg>',xn='<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-circle-check-big lucide-check-circle" aria-hidden="true" focusable="false"><path d="M21.801 10A10 10 0 1 1 17 3.335"></path><path d="m9 11 3 3L22 4"></path></svg>',bn='<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-circle-question-mark lucide-help-circle lucide-circle-help" aria-hidden="true" focusable="false"><circle cx="12" cy="12" r="10"></circle><path d="M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"></path><path d="M12 17h.01"></path></svg>',Sn='<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-clipboard-list" aria-hidden="true" focusable="false"><rect width="8" height="4" x="8" y="2" rx="1" ry="1"></rect><path d="M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"></path><path d="M12 11h4"></path><path d="M12 16h4"></path><path d="M8 11h.01"></path><path d="M8 16h.01"></path></svg>',Aa='<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-copy" aria-hidden="true" focusable="false"><rect width="14" height="14" x="8" y="8" rx="2" ry="2"></rect><path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"></path></svg>',vn='<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-flame" aria-hidden="true" focusable="false"><path d="M12 3q1 4 4 6.5t3 5.5a1 1 0 0 1-14 0 5 5 0 0 1 1-3 1 1 0 0 0 5 0c0-2-1.5-3-1.5-5q0-2 2.5-4"></path></svg>',Ia='<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-info" aria-hidden="true" focusable="false"><circle cx="12" cy="12" r="10"></circle><path d="M12 16v-4"></path><path d="M12 8h.01"></path></svg>',$a='<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-list" aria-hidden="true" focusable="false"><path d="M3 5h.01"></path><path d="M3 12h.01"></path><path d="M3 19h.01"></path><path d="M8 5h13"></path><path d="M8 12h13"></path><path d="M8 19h13"></path></svg>',Ta='<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-list-todo" aria-hidden="true" focusable="false"><path d="M13 5h8"></path><path d="M13 12h8"></path><path d="M13 19h8"></path><path d="m3 17 2 2 4-4"></path><rect x="3" y="4" width="6" height="6" rx="1"></rect></svg>',Ea='<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-moon" aria-hidden="true" focusable="false"><path d="M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401"></path></svg>',lo='<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-pencil" aria-hidden="true" focusable="false"><path d="M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z"></path><path d="m15 5 4 4"></path></svg>',mo='<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-quote" aria-hidden="true" focusable="false"><path d="M16 3a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2 1 1 0 0 1 1 1v1a2 2 0 0 1-2 2 1 1 0 0 0-1 1v2a1 1 0 0 0 1 1 6 6 0 0 0 6-6V5a2 2 0 0 0-2-2z"></path><path d="M5 3a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2 1 1 0 0 1 1 1v1a2 2 0 0 1-2 2 1 1 0 0 0-1 1v2a1 1 0 0 0 1 1 6 6 0 0 0 6-6V5a2 2 0 0 0-2-2z"></path></svg>',Oa='<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-sun" aria-hidden="true" focusable="false"><circle cx="12" cy="12" r="4"></circle><path d="M12 2v2"></path><path d="M12 20v2"></path><path d="m4.93 4.93 1.41 1.41"></path><path d="m17.66 17.66 1.41 1.41"></path><path d="M2 12h2"></path><path d="M20 12h2"></path><path d="m6.34 17.66-1.41 1.41"></path><path d="m19.07 4.93-1.41 1.41"></path></svg>',kn='<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-triangle-alert lucide-alert-triangle" aria-hidden="true" focusable="false"><path d="m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3"></path><path d="M12 9v4"></path><path d="M12 17h.01"></path></svg>',Pn='<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-x" aria-hidden="true" focusable="false"><path d="M18 6 6 18"></path><path d="m6 6 12 12"></path></svg>',fo='<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-zap" aria-hidden="true" focusable="false"><path d="M15.914 4a1.5 1.5 0 00-2.474-1.561l-9 9A1.5 1.5 0 005.5 14h4.002a.5.5 0 01.471.666L8.086 20a1.5 1.5 0 002.475 1.56l9-9A1.5 1.5 0 0018.5 10h-3.997a.5.5 0 01-.472-.667z"></path></svg>';var Ma=`@scope (.pmx-prose) to ([data-pmx-prose="off"]) {
66
- :where(.pmx-callout) {
67
- --pmx-callout-color: var(--pmx-color-accent);
68
- margin-block: var(--pmx-prose-flow);
69
- overflow: clip;
70
- border: 1px solid
71
- color-mix(in oklch, var(--pmx-callout-color) 35%, transparent);
72
- border-inline-start: 0.25em solid var(--pmx-callout-color);
73
- border-radius: var(--pmx-radius-lg);
74
- background: color-mix(
75
- in oklch,
76
- var(--pmx-callout-color) 9%,
77
- var(--pmx-color-bg)
78
- );
79
- color: var(--pmx-color-fg);
80
- }
81
-
82
- :where(.pmx-callout-title) {
83
- display: flex;
84
- gap: 0.6em;
85
- align-items: center;
86
- padding: 0.7em 0.9em;
87
- color: var(--pmx-callout-color);
88
- font-weight: 700;
89
- line-height: 1.35;
90
- list-style: none;
91
- }
92
-
93
- :where(summary.pmx-callout-title) {
94
- cursor: pointer;
95
- }
96
-
97
- summary.pmx-callout-title::-webkit-details-marker {
98
- display: none;
99
- }
100
-
101
- :where(.pmx-callout-icon, .pmx-callout-toggle) {
102
- display: inline-flex;
103
- flex: 0 0 auto;
104
- }
105
-
106
- :where(.pmx-callout-icon svg, .pmx-callout-toggle svg) {
107
- inline-size: 1.1em;
108
- block-size: 1.1em;
109
- stroke-width: 2.2;
110
- }
111
-
112
- :where(.pmx-callout-title-text) {
113
- min-inline-size: 0;
114
- flex: 1;
115
- }
116
-
117
- :where(.pmx-callout-toggle) {
118
- transition: transform 140ms ease-out;
119
- }
120
-
121
- :where(details.pmx-callout[open] > .pmx-callout-title .pmx-callout-toggle) {
122
- transform: rotate(90deg);
123
- }
124
-
125
- :where(.pmx-callout-content) {
126
- padding: 0 0.9em 0.85em;
127
- }
128
-
129
- :where(.pmx-callout-content > :first-child) {
130
- margin-block-start: 0;
131
- }
132
-
133
- :where(.pmx-callout-content > :last-child) {
134
- margin-block-end: 0;
135
- }
136
-
137
- :where(
138
- .pmx-callout[data-callout="abstract"],
139
- .pmx-callout[data-callout="summary"],
140
- .pmx-callout[data-callout="tldr"]
141
- ) {
142
- --pmx-callout-color: light-dark(oklch(0.54 0.12 215), oklch(0.76 0.11 215));
143
- }
144
-
145
- :where(.pmx-callout[data-callout="info"], .pmx-callout[data-callout="todo"]) {
146
- --pmx-callout-color: light-dark(oklch(0.54 0.17 255), oklch(0.76 0.13 250));
147
- }
148
-
149
- :where(
150
- .pmx-callout[data-callout="tip"],
151
- .pmx-callout[data-callout="hint"],
152
- .pmx-callout[data-callout="important"]
153
- ) {
154
- --pmx-callout-color: light-dark(oklch(0.52 0.13 165), oklch(0.76 0.12 165));
155
- }
156
-
157
- :where(
158
- .pmx-callout[data-callout="success"],
159
- .pmx-callout[data-callout="check"],
160
- .pmx-callout[data-callout="done"]
161
- ) {
162
- --pmx-callout-color: light-dark(oklch(0.52 0.15 145), oklch(0.76 0.13 145));
163
- }
164
-
165
- :where(
166
- .pmx-callout[data-callout="question"],
167
- .pmx-callout[data-callout="help"],
168
- .pmx-callout[data-callout="faq"]
169
- ) {
170
- --pmx-callout-color: light-dark(oklch(0.58 0.14 85), oklch(0.82 0.13 85));
171
- }
172
-
173
- :where(
174
- .pmx-callout[data-callout="warning"],
175
- .pmx-callout[data-callout="caution"],
176
- .pmx-callout[data-callout="attention"]
177
- ) {
178
- --pmx-callout-color: light-dark(oklch(0.58 0.17 55), oklch(0.8 0.15 65));
179
- }
180
-
181
- :where(
182
- .pmx-callout[data-callout="failure"],
183
- .pmx-callout[data-callout="fail"],
184
- .pmx-callout[data-callout="missing"],
185
- .pmx-callout[data-callout="danger"],
186
- .pmx-callout[data-callout="error"],
187
- .pmx-callout[data-callout="bug"]
188
- ) {
189
- --pmx-callout-color: var(--pmx-color-danger);
190
- }
191
-
192
- :where(.pmx-callout[data-callout="example"]) {
193
- --pmx-callout-color: light-dark(oklch(0.55 0.16 305), oklch(0.77 0.13 305));
194
- }
195
-
196
- :where(
197
- .pmx-callout[data-callout="quote"],
198
- .pmx-callout[data-callout="cite"]
199
- ) {
200
- --pmx-callout-color: var(--pmx-color-muted);
201
- }
202
- }
203
- `;var Tm=/^\[!([a-z0-9][a-z0-9_-]*)\]([+-]?)(?:[ \t]+(.*?))?[ \t]*$/i,Em={note:lo,abstract:Sn,summary:Sn,tldr:Sn,info:Ia,todo:Ta,tip:vn,hint:vn,important:vn,success:xn,check:xn,done:xn,question:bn,help:bn,faq:bn,warning:kn,caution:kn,attention:kn,failure:Pn,fail:Pn,missing:Pn,danger:fo,error:fo,bug:Ra,example:$a,quote:mo,cite:mo};function ho(e){let t=[],n=0;while(n<e.length){let r=e.slice(n).match(/^( {0,3})>[ \t]?/);if(!r)break;let o=n+r[1].length;n+=r[0].length,t.push({delimiter:o,end:n})}return{depth:t.length,rest:e.slice(n),segments:t}}function Da(e,t,n){if(!n)return e;return e.slice(t.segments[n-1].end)}function Om(e){if(!e.depth)return;let t=e.rest.match(Tm);if(!t)return;let n=t[2]==="+"?"open":t[2]==="-"?"closed":void 0,r=t[3]?.trim();return{type:t[1].toLowerCase(),...r?{title:r}:{},...n?{fold:n}:{}}}function Mm(e){return e.split(/[-_]+/).filter(Boolean).map((t)=>t[0].toUpperCase()+t.slice(1)).join(" ")}function Dm(e){let t=0,n=e.length;while(t<n&&!e[t].trim())t++;while(n>t&&!e[n-1].trim())n--;return e.slice(t,n)}function jm(e,t){if(!t)return e;return e.split(`
204
- `).map((n)=>t+n).join(`
205
- `)}function Lm(e,t,n){let r=e.fold!==void 0,o=r?"details":"aside",i=r?"summary":"div",s=Em[e.type]??lo,a=e.fold==="open"?" open":"",c=t?`
206
- <div class="pmx-callout-content">
207
-
208
- ${t}
209
-
210
- </div>`:"",p=r?`<span class="pmx-callout-toggle">${Ca}</span>`:"",u=`<${o} class="pmx-callout" data-callout="${g(e.type)}"${a}>
211
- <${i} class="pmx-callout-title"><span class="pmx-callout-icon">${s}</span><span class="pmx-callout-title-text">${g(e.title??Mm(e.type))}</span>${p}</${i}>${c}
212
- </${o}>`;return`${jm(u,n)}
213
- ${n}`}function Bm(e,t,n){let r=t+1;while(r<e.length&&ho(e[r]).depth>=n)r++;return r}function ja(e){let t=e.split(/\r?\n/),n=[],r,o=!1;for(let i=0;i<t.length;){let s=t[i],a=me(s,o);o=a.inComment;let c=ho(s);if(r){if(n.push(s),c.depth>=r.depth&&v(Da(s,c,r.depth),r.marker))r=void 0;i++;continue}if(a.line===s){let f=x(c.depth?c.rest:s);if(f){r={marker:f.marker,depth:c.depth},n.push(s),i++;continue}}let p=a.line===s?Om(c):void 0;if(!p){n.push(s),i++;continue}let u=Bm(t,i,c.depth),l=Dm(t.slice(i+1,u).map((f)=>{let h=ho(f);return Da(f,h,c.depth)})),d=l.length?ja(l.join(`
214
- `)):"",m=s.slice(0,c.segments.at(-1).delimiter);n.push(Lm(p,d,m)),i=u}return n.join(`
215
- `)}function La(){return{id:"callout",precompile(e){return e.includes("[!")?ja(e):e},page(e,t){if(!e.includes('class="pmx-callout"'))return e;return t.addAsset({type:"stylesheet",name:"callout.css",text:Ma}),e}}}var Nm=/^ {0,3}:[ \t]+(.*)$/,zm=/(?:^|\n) {0,3}:[ \t]+/,qm=/<div data-pmx-definition-list="\d+:(term|definition)"><\/div>\n?/g;function $t(e){return!e?.trim()}function Ge(e){return e?.match(Nm)?.[1]}function Vm(e){if(!e||$t(e)||/^(?: {4}|\t)/.test(e))return!1;let t=e.trimStart();return!(Ge(e)!==void 0||x(e)||/^(?:#{1,6}(?:[ \t]+|$)|>|[-+*][ \t]+|\d{1,9}[.)][ \t]+)/.test(t)||/^(?:[-*_][ \t]*){3,}$/.test(t))}function Ba(e,t){if(!Vm(e[t]))return;let n=t+1;if($t(e[n]))n++;if(Ge(e[n])===void 0)return;return n}function Hm(e){if(e.startsWith("\t"))return e.slice(1);if(e.startsWith(" "))return e.slice(4);return e}function Fm(e,t){let n=[Ge(e[t])??""],r=t+1;while(r<e.length){if(Ge(e[r])!==void 0)break;if(!$t(e[r])){n.push(Hm(e[r])),r++;continue}let o=r;while(o<e.length&&$t(e[o]))o++;if(Ge(e[o])!==void 0){r=o;break}if(/^(?: {4}|\t)/.test(e[o]??"")){n.push(...e.slice(r,o).map(()=>"")),r=o;continue}break}return{markdown:n.join(`
216
- `).trimEnd(),nextIndex:r}}function Um(e,t){let n=Ba(e,t);if(n===void 0)return;let r=[],o=n;while(Ge(e[o])!==void 0){let i=Fm(e,o);r.push(i.markdown),o=i.nextIndex}return{item:{term:e[t].trim(),definitions:r},nextIndex:o}}function _m(e,t){let n=[],r=t;while(!0){let o=Um(e,r);if(!o)break;n.push(o.item),r=o.nextIndex;let i=r;while(i<e.length&&$t(e[i]))i++;if(i===r||Ba(e,i)===void 0)break;r=i}if(!n.length)return;return{items:n,nextIndex:r}}function Je(e,t){return`<div data-pmx-definition-list="${e}:${t}"></div>`}function Qm(e,t){let n=[Je(t,"start")];for(let r of e.items){n.push("",Je(t,"term"),"",r.term);for(let o of r.definitions)n.push("",Je(t,"definition"),"",o)}return n.push("",Je(t,"end")),n.join(`
217
- `)}function Wm(e){let t=e.split(/\r?\n/),n=[],r=0,o;for(let i=0;i<t.length;){let s=t[i]??"";if(o){if(n.push(s),v(s,o))o=void 0;i++;continue}let a=x(s);if(a){n.push(s),o=a.marker,i++;continue}let c=_m(t,i);if(!c){n.push(s),i++;continue}n.push(Qm(c,r++)),i=c.nextIndex}return{markdown:n.join(`
218
- `),listCount:r}}function Xm(e){let t=e.trim();if(!t.startsWith("<p>")||!t.endsWith("</p>"))return t;let n=t.slice(3,-4);return n.includes("</p>")?t:n}function Jm(e){let t=[],n,r=0;for(let i of e.matchAll(qm)){if(n)t.push({type:n,html:e.slice(r,i.index)});n=i[1],r=i.index+i[0].length}if(n)t.push({type:n,html:e.slice(r)});return`<dl>
219
- ${t.map((i)=>{let s=i.type==="term"?"dt":"dd";return`<${s}>${Xm(i.html)}</${s}>`}).join(`
220
- `)}
221
- </dl>`}function Gm(e,t){for(let n=0;n<t;n++){let r=Je(n,"start"),o=Je(n,"end"),i=e.indexOf(r),s=e.indexOf(o,i+r.length);if(i===-1||s===-1)continue;let a=e.slice(i+r.length,s);e=e.slice(0,i)+Jm(a)+e.slice(s+o.length)}return e}function Na(){let e=new WeakMap;return{id:"definition-list",precompile(t,n){if(!zm.test(t))return e.set(n,0),t;let r=Wm(t);return e.set(n,r.listCount),r.markdown},postcompile(t,n){let r=e.get(n)??0;return e.delete(n),r?Gm(t,r):t}}}var Ym=/<div data-pathmx-include="(\d+)"><\/div>/g;function Km(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Va(e){let t=Km(e);return new RegExp(`\\[@include(?:\\.[A-Za-z][\\w-]*)*(?:\\s+[^\\]]+)?\\]\\(\\s*(?:<${t}>|${t})\\)`)}function Zm(e,t){return t.startsWith("/")?t:new URL(t,`file://${e.path}`).pathname}function za(e,t){return t?`${e}#${t}`:e}function ef(e){return`include-${encodeURIComponent(e)}`}function tf(e,t,n){if(n!=="page"||t.includes("#"))return!1;let r=e.trim(),o=r.match(Va(t));return o?.index===0&&o[0]===r}async function qa(e,t,n,r){return n.compile.block(e,t,r,{id:ef(t.path)})}async function nf(e,t,n,r){let o=t.indexOf("#"),i=o===-1?t:t.slice(0,o),s=o===-1?void 0:t.slice(o+1),a=Zm(e,i);r.depend({type:"source",path:a});let c=n.sources.get(a);if(!c)return`<p>[Broken Include: ${g(za(a,s))}]</p>`;if(!n.access.canEmbed(e.id,c.id))return`<p>[Unavailable Include: ${g(za(a,s))}]</p>`;if(s===void 0){if(!c.blocks.length)return`<p>[Broken Include: ${g(a)}]</p>`;let u=[];for(let l of c.blocks)u.push(await qa(c,l,n,r));return u.join(`
222
- `)}let p=c.blocks.find((u)=>u.id===s);if(!p)return`<p>[Broken Include: ${g(`${a}#${s}`)}]</p>`;return qa(c,p,n,r)}function Ha(){return{id:"include",async precompile(e,t,n){let r=(t.block?.links??t.source.links).filter((i)=>i.directive?.name==="include");if(!r.length)return e;let o=e;for(let i of r){let s=await nf(t.source,i.href,n,t),a=r.length===1&&tf(e,i.href,t.scope)&&s.trimStart().startsWith("<section ");t.slots.push(a?xs(s):s),o=o.replace(Va(i.href),`
223
-
224
- <div data-pathmx-include="${t.slots.length-1}"></div>
225
-
226
- `)}return o},postcompile(e,t){if(!t.slots.length)return e;return e.replace(Ym,(n,r)=>t.slots[Number(r)]??"")}}}import Fa from"highlight.js/lib/common";var rf=new Set(["no-copy","no-select"]),of=/<pre><code([^>]*)>([\s\S]*?)<\/code><\/pre>/g,sf=/\blanguage-([^"'\s]+)/,af=new Set(["plain","plaintext","text"]),go=/^\[(\d+(?:-\d+)?(?:\|\d+(?:-\d+)?)*)\]$/,cf=new URL("./client.ts",import.meta.url);function Ua(e){let t=e.trim().split(/\s+/).filter(Boolean),n=t[0]?.toLowerCase()??"",r=t.slice(1),o=r.find((i)=>go.test(i))?.match(go)?.[1];return{lang:n,meta:{noCopy:r.includes("no-copy"),noSelect:r.includes("no-select"),...o?{steps:o}:{}},nextInfo:[...t.slice(0,1),...r.filter((i)=>!rf.has(i)&&!go.test(i))].join(" ")}}function pf(e){let t=e.split(/\r?\n/),n=[],r;for(let o=0;o<t.length;o++){let i=t[o]??"";if(r){if(v(i,r))r=void 0;continue}let s=x(i);if(!s)continue;let a=Ua(s.info);n.push(a.meta),t[o]=`${s.indent}${s.marker}${a.nextInfo}`,r=s.marker}return{markdown:t.join(`
227
- `),metaByFence:n}}function uf(e,t){let n=t.block?.body??t.source.body;if(e!==n)return;return(t.block?.fences??t.source.fences).map((r)=>Ua(r.info).meta)}function lf(e){return af.has(e.toLowerCase())}function df(e,t){let n=['class="pmx-code-block"'];if(t.noSelect)n.push('data-code-select="false"');if(t.steps)n.push(`data-pmx-code-steps="${g(t.steps)}"`);let r=t.noCopy?"":`<button class="pmx-code-copy" aria-label="Copy code">${Aa}</button>`;return`<div ${n.join(" ")}>${r}${e}</div>`}function mf(e,t){let n=(e.match(sf)?.[1]??"").toLowerCase();if(!n||lf(n)||!Fa.getLanguage(n))return`<pre><code${e}>${t}</code></pre>`;try{let r=Fa.highlight(ee(t),{language:n,ignoreIllegals:!0}).value;return`<pre><code class="hljs language-${g(n)}">${r}</code></pre>`}catch{return`<pre><code${e}>${t}</code></pre>`}}function _a(){let e=new WeakMap;return{id:"code-highlight",precompile(t,n){let r=uf(t,n);if(r){if(e.set(n,r),!r.some((i)=>i.noCopy||i.noSelect||i.steps))return t}else if(!t.includes("```")&&!t.includes("~~~"))return e.set(n,[]),t;let o=pf(t);return e.set(n,o.metaByFence),o.markdown},postcompile(t,n){if(!t.includes("<pre><code"))return t;let r=e.get(n)??[],o=0;return t.replace(of,(i,s,a)=>{if(/\bhljs\b/.test(s))return i;let c=r[o++]??{noCopy:!1,noSelect:!1};return df(mf(s,a),c)})},async page(t,n){if(!t.includes("pmx-code-block"))return t;return await n.addBrowserBundle(cf,"code-highlight"),t}}}import ff from"temml";import hf from"temml/dist/Temml-Local.css"with{type:"text"};var gf=/\$\$([\s\S]+?)\$\$/g,yf=/\$(?!\s)([^$\n]+?)(?<!\s)\$(?!\d)/g,wf=/<(div|span) data-pathmx-math="(\d+)"><\/(?:div|span)>/g,xf=/`[^`\n]+`/g,bf=/\/\*[\s\S]*?\*\/\s*@font-face\s*\{[^}]*\}/g,Sf=hf;function vf(e){let t=[];return{masked:e.replace(xf,(r)=>{let o=t.length;return t.push(r),`\x00${o}\x00`}),slots:t}}function kf(e,t){return e.replace(/\0(\d+)\0/g,(n,r)=>t[Number(r)]??"")}function Pf(e,t){let{masked:n,slots:r}=vf(e),o=n.replace(gf,(i,s)=>{let a=t.length;return t.push({tex:s.trim(),display:!0}),`
228
-
229
- <div data-pathmx-math="${a}"></div>
230
-
231
- `});return o=o.replace(yf,(i,s)=>{let a=t.length;return t.push({tex:s.trim(),display:!1}),`<span data-pathmx-math="${a}"></span>`}),kf(o,r)}function Rf(e){let t=[],n=e.split(/\r?\n/),r=[],o=[],i,s=()=>{if(!o.length)return;r.push(Pf(o.join(`
232
- `),t)),o.length=0};for(let a of n){if(i){if(r.push(a),v(a,i))i=void 0;continue}let c=x(a);if(c){s(),r.push(a),i=c.marker;continue}o.push(a)}return s(),{markdown:r.join(`
233
- `),stash:t}}function Cf(e,t){try{let n=ff.renderToString(e.tex,{displayMode:e.display,throwOnError:!1}),r=e.display?"display":"inline",o=e.display?"div":"span";return`<${o} data-pathmx-math="${r}">${n}</${o}>`}catch(n){t.log.warn("render",{tex:e.tex,error:n instanceof Error?n.message:String(n)});let r=g(e.tex);return e.display?`<pre data-pathmx-math="error"><code>$$${r}$$</code></pre>`:`<code data-pathmx-math="error">$${r}$</code>`}}function Qa(){let e=new WeakMap;return{id:"math",precompile(t,n){if(!t.includes("$"))return e.set(n,[]),t;let r=Rf(t);return e.set(n,r.stash),r.markdown},postcompile(t,n,r){if(!t.includes("data-pathmx-math"))return t;let o=e.get(n)??[];return t.replace(wf,(i,s,a)=>{let c=o[Number(a)];if(!c)return i;return Cf(c,r)})},page(t,n){if(!t.includes("data-pathmx-math"))return t;return n.addAsset({type:"stylesheet",name:"math.css",text:Sf.replace(bf,"").trim()}),t}}}var Oe={autoWrap:!0,className:"pmx-datatype",width:100,weight:400,preload:!0},Af={b:"bar",l:"sparkline",p:"pie"},If=/\{([blp]):([^{}\n]+)\}/g,Ya=/\{[blp]:/,$f=new URL("./Datatype[wdth,wght].woff2",import.meta.url),Tf=new URL("./OFL.txt",import.meta.url),yo="pmx-datatype-root",Wa=`<${yo}>`,Xa=`</${yo}>`,Ef=["code","pre","script","style","textarea"];function Ja(e,t,n,r){if(!Number.isFinite(e))return r;return Math.min(n,Math.max(t,e))}function Ka(e){return e?.trim()||Oe.className}function Ga(e){return e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}function Of(e){return e.split(/\s+/).filter(Boolean).map((t)=>t.replace(/[^a-zA-Z0-9_-]/g,(n)=>`\\${n.codePointAt(0).toString(16)} `)).map((t)=>`.${t}`).join("")}function Mf(e){let t=e.values.join(", ");if(e.type==="bar")return`Bar chart values ${t}`;if(e.type==="sparkline")return`Sparkline values ${t}`;return`Pie chart value ${t}`}function Df(e,t){return`<span class="${g(t)}" data-pathmx-datatype="${e.type}" role="img" aria-label="${g(Mf(e))}">${e.canonical}</span>`}function jf(e){let t=e.match(/^\{([blp]):([^{}\n]+)\}$/);if(!t)return null;let n=t[1],r=t[2].split(",").map((i)=>i.trim());if(!r.length||r.some((i)=>!i))return null;if(n==="p"&&r.length!==1)return null;if(n!=="p"&&r.length>20)return null;let o=r.map((i)=>/^\d+$/.test(i)?Number(i):Number.NaN);if(o.some((i)=>!Number.isInteger(i)||i<0||i>100))return null;return{type:Af[n],code:n,values:o,canonical:`{${n}:${o.join(",")}}`}}function Lf(e,t){return e.replace(If,(n)=>{let r=jf(n);return r?Df(r,t):n})}function Bf(e,t,n={}){if(!Ya.test(e))return e;let r=Ka(n.className),o=0,i="",s=[];for(let c of Ef)s.push([c,{element(p){o++,p.onEndTag(()=>{o--})}}]);return s.push([yo,{text(c){if(o)return;if(i+=c.text,c.remove(),!c.lastInTextNode)return;c.after(Lf(i,r),{html:!0}),i=""}}]),t(`${Wa}${e}${Xa}`,s).slice(Wa.length,-Xa.length)}function Nf(e,t,n,r,o){let i=Of(e);return`/* Datatype font license: ${Ga(n)} */
234
- @font-face {
235
- font-family: "PathMX Datatype";
236
- src: url("${Ga(t)}") format("woff2-variations");
237
- font-weight: 100 900;
238
- font-stretch: 50% 150%;
239
- font-display: swap;
240
- }
241
-
242
- ${i} {
243
- font-family: "PathMX Datatype", "IBM Plex Mono", monospace;
244
- font-variant-ligatures: common-ligatures contextual discretionary-ligatures;
245
- font-feature-settings: "liga" 1, "calt" 1;
246
- font-weight: ${o};
247
- font-stretch: ${r}%;
248
- letter-spacing: 0;
249
- line-height: 1;
250
- white-space: nowrap;
251
- display: inline-block;
252
- vertical-align: -0.08em;
253
- }
254
- `}async function zf(e){let[t,n]=await Promise.all([e.assets.load($f),e.assets.load(Tf)]),[r,o]=await Promise.all([e.assets.publish("datatype-font.woff2",t,"font/woff2"),e.assets.publish("datatype-OFL.txt",n,"text/plain; charset=utf-8")]);return{fontHref:r,licenseHref:o}}function qf(e,t,n){if(e.addAsset({type:"stylesheet",name:"datatype.css",text:Nf(t.className,n.fontHref,n.licenseHref,t.width,t.weight)}),t.preload)e.addAsset({type:"preload",href:n.fontHref,as:"font",contentType:"font/woff2",crossorigin:!0})}function Za(e={}){let t={autoWrap:e.autoWrap??Oe.autoWrap,className:Ka(e.className),width:Ja(e.width??Oe.width,50,150,Oe.width),weight:Ja(e.weight??Oe.weight,100,900,Oe.weight),preload:e.preload??Oe.preload},n;return{id:"datatype",postcompile(r,o,i){if(!t.autoWrap||!Ya.test(r))return r;return Bf(r,i.html.rewrite,t)},async page(r,o,i){if(!r.includes("data-pathmx-datatype"))return r;return n??=zf(i),qf(o,t,await n),r}}}function ec(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Rn(e,t){let n=ec(e),r=ec(t);return new RegExp(`^[ \\t]{0,3}\\[@${n}[^\\]]*\\]:[ \\t]+(?:<${r}>|${r})(?:[ \\t]+(?:"[^"]*"|'[^']*'|\\([^)]*\\)))?[ \\t]*\\n?`,"gm")}var Vf=new Set(["print","screen"]),Hf=/^[a-z][a-z\d+.-]*:/i;function Ff(e,t){return t.startsWith("/")?t:new URL(t,`file://${e.path}`).pathname}function wo(e,t){return t.filter((n)=>n.directive?.name==="styles")}function rc(e,t){if(t.directive?.name!=="styles")return;let n=t.href.split("#")[0]?.split("?")[0]??"";if(!n||Hf.test(n)||n.startsWith("//")||n.startsWith("~/"))return;let r=Ff(e,n);if(!r.endsWith(".css"))return;let o=t.directive.qualifiers.find((i)=>Vf.has(i));return{type:"stylesheet",href:r,...o?{media:o}:{}}}function Cn(e){return e.type==="stylesheet"&&"href"in e?e.href:void 0}function Uf(e,t){let n=Cn(t);if(n&&e.some((r)=>Cn(r)===n))return;e.push(t)}function tc(e,t){let n=Cn(t);if(n)e.depend({type:"source",path:n})}function _f(e){return e.blocks.length?e.blocks.flatMap((t)=>t.links):e.links}function oc(e,t){let n=[];for(let r of wo(e,t)){if(!r.directive?.qualifiers.includes("global"))continue;let o=rc(e,r);if(o)Uf(n,o)}return n}function Qf(e){return e.map((t)=>`${Cn(t)??""}\x00${t.media??""}`).join(`
255
- `)}function nc(e){return Qf(e?oc(e,de(e.body)):[])}function ic(){let e=new Map;return{id:"styles",index(t){let n=oc(t,_f(t));if(n.length)e.set(t.path,n);else e.delete(t.path)},unindex(t){e.delete(t)},precompile(t,n){let r=wo(n.source,n.block?.links??n.source.links);if(!r.length)return t;let o=t;for(let i of r)o=o.replace(Rn("styles",i.href),"");return o},invalidate({before:t,after:n},r){if(nc(t)===nc(n))return;return{targets:Qe(r.sources.builtPages())}},page(t,n){for(let r of e.values())for(let o of r)tc(n,o);for(let r of wo(n.source,n.source.links)){if(r.directive?.qualifiers.includes("global"))continue;let o=rc(n.source,r);if(o)n.addAsset(o),tc(n,o)}return t},documentAssets(t){for(let n of[...e.keys()].sort())for(let r of e.get(n)??[])t.addAsset(r)}}}var Wf=/^[a-z][a-z\d+.-]*:/i;function Xf(e,t){return t.startsWith("/")?t:new URL(t,`file://${e.path}`).pathname}function xo(e){return e.filter((t)=>t.directive?.name==="script")}function cc(e,t){if(t.directive?.name!=="script")return;let n=t.href.split("#")[0]?.split("?")[0]??"";if(!n||Wf.test(n)||n.startsWith("//")||n.startsWith("~/"))return;let r=Xf(e,n);if(!r.endsWith(".js"))return;return{type:"script",source:r,module:!0}}function Jf(e,t){if(e.some((n)=>n.source===t.source))return;e.push(t)}function sc(e,t){e.depend({type:"source",path:t.source})}function Gf(e){return e.blocks.length?e.blocks.flatMap((t)=>t.links):e.links}function pc(e,t){let n=[];for(let r of xo(t)){if(!r.directive?.qualifiers.includes("global"))continue;let o=cc(e,r);if(o)Jf(n,o)}return n}function Yf(e){return e.map((t)=>t.source).join(`
256
- `)}function ac(e){return Yf(e?pc(e,de(e.body)):[])}function uc(){let e=new Map;return{id:"scripts",index(t){let n=pc(t,Gf(t));if(n.length)e.set(t.path,n);else e.delete(t.path)},unindex(t){e.delete(t)},precompile(t,n){let r=xo(n.block?.links??n.source.links);if(!r.length)return t;let o=t;for(let i of r)o=o.replace(Rn("script",i.href),"");return o},invalidate({before:t,after:n},r){if(ac(t)===ac(n))return;let o=r.sources.builtPages();return{sourceIds:o.map((i)=>i.sourceId),targets:Qe(o)}},page(t,n){for(let r of e.values())for(let o of r)sc(n,o);for(let r of xo(n.source.links)){if(r.directive?.qualifiers.includes("global"))continue;let o=cc(n.source,r);if(o)n.addAsset(o),sc(n,o)}return t},documentAssets(t){for(let n of[...e.keys()].sort())for(let r of e.get(n)??[])t.addAsset(r)}}}function bo(e){return{type:"plugin",plugin:"actor-profile",key:e}}function lc(){return{id:"actor-profile",invalidate({before:e,after:t}){let n=t??e;if(!n||!K(n))return;return{dependencies:[bo(n.id)]}},streamSelectors({principal:e},t){return{"[data-pmx-profile-name]":{element(n){let r=n.getAttribute("data-pmx-profile-name")??"",o=t.actors.profile(r);if(n.removeAttribute("data-pmx-profile-name"),o)n.setInnerContent(o.name);else n.remove()}},"[data-pmx-profile-avatar]":{element(n){let r=n.getAttribute("data-pmx-profile-avatar")??"",o=t.actors.profile(r);if(n.removeAttribute("data-pmx-profile-avatar"),o?.avatar)n.setAttribute("src",o.avatar);else n.remove()}},"[data-pmx-owner]":{element(n){let r=n.getAttribute("data-pmx-owner"),o=e.type==="actor"?e.actor:void 0,i=o?.id===r||o?.type==="user"&&o.role==="staff";if(n.removeAttribute("data-pmx-owner"),!i)n.remove()}}}}}}var dc=new URL("./client.ts",import.meta.url),Kf=new Set,Zf=new Map,hc="literate-components:query",eh=xe(hc);class ko extends Map{revision=0;set(e,t){return this.revision++,super.set(e,t)}delete(e){let t=super.delete(e);if(t)this.revision++;return t}clear(){if(!this.size)return;super.clear(),this.revision++}}function Tt(e,t,n){let r=new Map,o=new Set,i=[e];while(i.length){let s=i.pop();for(let a of s.links){if(a.kind!=="definition"||!a.directive)continue;let c=a.href.split(/[?#]/,1)[0];if(!c||c.startsWith("~/")||/^[a-z][a-z\d+.-]*:/i.test(c))continue;let p=c.startsWith("/")?t.sources.path(c):new URL(c,`file://${s.path}`).pathname,u=t.sources.get(p);if(!u||u.type!=="components"||o.has(p))continue;o.add(p),i.push(u);for(let[l,d]of n)if(d.origin===p)r.set(l,d)}}return r}var mc=new WeakMap;function So(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function th(e){return e instanceof ko?e.revision:[...e.keys()].join("\x00")}function gc(e){let t=th(e),n=mc.get(e);if(n?.key===t)return n;let r=[...e.keys()],o=new Map;for(let s of r){let a=So(s);o.set(s,{selfClosing:new RegExp(`<${a}(\\s[^>]*)?\\s*/>`,"gi"),wrapped:new RegExp(`<${a}(\\s[^>]*)?>([\\s\\S]*?)</${a}>`,"gi")})}let i={key:t,tags:new Set(r),matcher:r.length?new RegExp(`<(?:${r.map(So).join("|")})(?:\\s|>|/)`,"i"):void 0,patterns:o};return mc.set(e,i),i}function nh(e){let t=[],n=[],r=[];for(let o of e){let i=o.lang.toLowerCase(),s=o.body.trim();if(!i||!s)continue;if(i==="html"||i==="htm")t.push(s);else if(i==="css")n.push(s);else if(i==="js"||i==="javascript")r.push(s)}return{html:t.join(`
257
- `),css:n.join(`
258
- `),js:r.join(`
259
- `)}}function rh(e,t,n){let r=e.trim();if(!r||r.startsWith("/")||r.startsWith("#")||r.startsWith("?")||r.startsWith("~/")||r.includes("{{")||le(r))return e;let o=r.search(/[?#]/),i=o===-1?r:r.slice(0,o),s=o===-1?"":r.slice(o),a=S.join(S.dirname(t),i),c=n.sources.get(a);return`${c&&n.sources.isPage(c)?y(c):a}${s}`}function oh(e,t,n){if(!e)return e;return n.html.rewrite(e,[["[href], [src]",{element(r){for(let o of["href","src"]){let i=r.getAttribute(o);if(i!=null)r.setAttribute(o,rh(i,t,n))}}}]])}function yc(e,t,n){let r=nh(e);return{...r,html:oh(r.html,t,n)}}function Po(e){return e.trim().toLowerCase()}function ih(e,t){if(e.blocks.length)return e.blocks;return G(e.body).map((n,r)=>dt(e,r,n,{},t.yaml))}function fc(e,t){let n=new Map;if(e?.type!=="components")return n;for(let r of ih(e,t)){let o=typeof r.data.componentName==="string"?Po(r.data.componentName):"";if(!o)continue;let i=yc(r.fences,e.path,t);if(i.html||i.css||i.js)n.set(o,i)}return n}function sh(e,t){return e?.html===t?.html&&e?.css===t?.css&&e?.js===t?.js}function ah(e,t,n){let r=fc(e,n),o=fc(t,n),s=[...new Set([...r.keys(),...o.keys()])].filter((c)=>!sh(r.get(c),o.get(c))),a=[...o.keys()].filter((c)=>!r.has(c));return{changed:s,introduced:a}}function Ye(e){return{type:"plugin",plugin:"literate-components",key:Po(e)}}function ch(e){return new RegExp(`<${So(e)}(?:\\s|>|/)`,"i")}function ph(e){return Object.fromEntries(Object.entries(e).filter(([t])=>t!=="from"&&t!=="as"&&t!=="id"&&t!==N))}function wc(e,t,n="",r){let{dependencies:o,rewriteHtml:i,used:s,stamp:a,originTags:c}=r,p=t[N],u={...t};if(delete u[N],t.as)s?.add(t.as);let l=t.from?`<${eh} from="${g(t.from)}" as="${g(t.as??"")}" />`:n,d=e.replace(/<yield\s*\/?>/gi,l).replace(/\{\{\s*([\w-]+)\s*\}\}/g,(f,h)=>g(u[h]??"")),m=a?xt(d,a.tag,i,a.includeAttrs?ph(u):void 0):d;return p?Mr(m,p,c??Kf,i):m}function vo(e,t,n){let r=gc(t);if(!r.matcher?.test(e))return e;let o=e;for(let i=0;i<8;i++){let s=o;for(let[a,c]of t){let p=c.html;if(!p)continue;let u=r.patterns.get(a);if(!u)continue;let l=(d,m,f="")=>{let h=Fe(m);if(n.allows&&!n.allows(a,h[N]))return d;return n.used?.add(a),wc(p,h,f,{...n,stamp:{tag:a,includeAttrs:Boolean(c.js)},originTags:r.tags})};o=o.replace(u.selfClosing,(d,m)=>l(d,m)),o=o.replace(u.wrapped,(d,m,f)=>l(d,m,f))}if(o===s)break}return o}function uh(e,t){let n=xc(e,t);return[`<script data-pmx-component="${g(e)}">`,n,"</script>"].join(`
260
- `)}function xc(e,t){let n=t.replace(/<\/script/gi,"<\\/script");return`(window.pmxq=window.pmxq||[]).push([${JSON.stringify(e)},function(el,{$,$$,on,attrs,update,cleanup}){
261
- ${n}
262
- }])`}function lh(e,t){let n=[],r=[];for(let o of e){let i=t.get(o);if(!i)continue;if(i.css)n.push(i.css);if(i.js)r.push(uh(o,i.js))}return{css:n,scripts:r}}function bc(e){return Object.entries(e).filter(([,t])=>typeof t==="string"||typeof t==="number"||typeof t==="boolean").map(([t,n])=>`${t}="${g(String(n))}"`).join(" ")}var dh=new Set(["title","subtitle","author","published","isbn","name","message","note","created","heart_count","component"]);function mh(e,t){let n=Object.fromEntries(Object.entries(t.data).filter(([i])=>dh.has(i))),r=typeof t.data.actor==="string"?t.data.actor:"",o=r?e.actors.profile(r):void 0;return{...n,...r?{actor:r}:{},...o?{actor_name:o.name,...o.avatar?{avatar:o.avatar}:{}}:{}}}function fh(e){return Object.fromEntries(Object.entries(e).filter(([t])=>t!=="component"&&t!=="type"&&t!=="id"))}function hh(e){return typeof e.component==="string"?e.component.trim():""}function gh(e,t){return e.replace(/\{\{\s*data\.([A-Za-z_][\w-]*(?:\.[A-Za-z_][\w-]*)*)\s*\}\}/g,(n,r)=>{let o=H(t,r);return o==null?"":g(typeof o==="object"?JSON.stringify(o):String(o))})}async function yh(e,t,n,r,o){let i=(await t.query.sources(n)).filter((s)=>{let a=e.sources.get(s.id);return a?!L(a):!0}).map((s)=>{let a=e.sources.get(s.id),c=bc({...a?mh(e,a):s.data,href:s.href,from:n.from??"/"});return`<${o||s.type} ${c} />`}).join("");return vo(i,r,{rewriteHtml:e.html.rewrite})}function Sc(){let e=new ko,t=D({tag:hc,async compile(n,r,o){let i=n.props.from??"/",a={from:i.startsWith("~/")||i.startsWith("/")?i:S.resolve(S.dirname(n.origin.path),i),...n.props.as?{type:n.props.as}:{},sort:[{by:"meta.title"}]},c=await o.query.prepare("sources",a);return r.depend(Se(c)),Object.freeze(a)},render(n,r,{view:o},i){return yh(i,o,r,Tt(n.origin,i,e),n.props.as||void 0)}});return{id:"literate-components",schema:{sources:{components:{label:"Components",description:"Authored Literate Component definitions.",icon:"boxes",color:"amber"}}},components:[t],index(n,r){if(n.type!=="components")return;let o=[],i=(s,a)=>{s=Po(s);let c=yc(a,n.path,r);if(c.html||c.css||c.js)o.push({tag:s,compiled:c})};for(let s of n.blocks){let a=typeof s.data.componentName==="string"?s.data.componentName.trim():"";if(a)i(a,s.fences)}r.components.claim(n.path,o.map(({tag:s})=>s));for(let{tag:s,compiled:a}of o)e.set(s,{...a,origin:n.path,references:[...cn(a.html)]});r.components.replaceData(n.path,o.map(({tag:s})=>({tag:s,available(a){return Tt(a,r,e).has(s)},async compile(a,c){let p=Tt(a,r,e),u=p.get(s);if(!u)throw Error(`Literate Component <${s}> is not imported by ${a.path}.`);c.depend(Ye(s));for(let l of u.references??[])if(!r.components.has(l))c.depend(Ye(l));if(u.css)c.addAsset({type:"style",text:u.css});if(u.js)c.addAsset({type:"script",text:xc(s,u.js)}),await c.addBrowserBundle(dc,"components");return{template:u,imported:p}},render(a,c,p,u){let{template:l,imported:d}=c,m=wc(gh(l.html,a.data),{...a.props},"",{rewriteHtml:u.html.rewrite,stamp:{tag:s,includeAttrs:Boolean(l.js)},originTags:gc(d).tags});return vo(m,d,{rewriteHtml:u.html.rewrite})}})))},unindex(n,r){r.components.release(n);for(let[o,i]of e)if(i.origin===n)e.delete(o)},invalidate({before:n,after:r},o){let{changed:i,introduced:s}=ah(n,r,o);if(!i.length)return;let a=s.map(ch);return{dependencies:i.map(Ye),sourceIds:a.length?o.sources.builtPages().filter((c)=>a.some((p)=>p.test(c.html))).map((c)=>c.sourceId):[]}},precompile(n,r,o){let{block:i}=r,s=typeof i?.data.actor==="string"?i.data.actor:"";if(s)r.depend(bo(s));let a=i?hh(i.data):"";if(a)r.depend(Ye(a));if(!i||n.trim()||!a||!Tt(r.source,o,e).has(a))return n;let c=bc(fh(i.data)),p=`${N}="${g(r.source.path)}"`;return c?`<${a} ${p} ${c} />`:`<${a} ${p} />`},page(n,r,o){let i=n,s=new Set,a=new Map,c=(l=r.source.path)=>{let d=a.get(l);if(d)return d;let m=o.sources.get(l),f=m?Tt(m,o,e):Zf;return a.set(l,f),f};n=vo(n,e,{allows:(l,d)=>c(d).has(l),dependencies:r,rewriteHtml:o.html.rewrite,used:s});for(let l of s){r.depend(Ye(l));for(let d of e.get(l)?.references??[]){if(o.components.has(d))continue;r.depend(Ye(d))}}if(n===i)return n;let{css:p,scripts:u}=lh(s,e);if(p.length)n+=`
263
- <style>${p.join(`
264
- `)}</style>`;if(u.length)n+=`
265
- ${u.join(`
266
- `)}`;return n},async documentAssets(n){if(!n.page?.html.includes("<script data-pmx-component="))return;await n.addBrowserBundle(dc,"components")}}}function vc(){return{id:"actor-path",streamSelectors({principal:e,source:t}){let n=e.type==="actor"?e.actor:void 0;return{"[href^='~/']":{element(r){let o=r.getAttribute("href");if(!o?.startsWith("~/"))return;if(n)r.setAttribute("href",`${n.home}/${o.slice(2)}`);else r.removeAttribute("href")}},"form[action^='~/']":{element(r){let o=r.getAttribute("action");if(!o?.startsWith("~/"))return;if(n)r.setAttribute("action",`${n.home}/${o.slice(2)}`);else r.remove()}},'form[action^="/actions/"]':{element(r){if(!n){r.remove();return}r.prepend(`<input type="hidden" name="_target" value="${g(t.id)}" />`,{html:!0})}}}}}}function Ke(e){let t=e.indexOf("#"),n=t===-1?e:e.slice(0,t),r=n.indexOf("?");return{pathname:r===-1?n:n.slice(0,r),query:r===-1?"":n.slice(r),fragment:t===-1?"":e.slice(t)}}function Et(e,t,n){return`${e}${t}${n}`}function An(e){return Boolean(e)&&!e.startsWith("/")&&!e.startsWith("~")}function Ro(e){let t=e.data.id;return typeof t==="string"&&t.trim()?t.trim():void 0}function wh(e,t){let n=Ro(t);return Boolean(n&&(e===n||e===`/${n}`))}function kc(e,t,n){let r=S.dirname(e),o=S.relative(r,t);if(!o)o=S.basename(t);if(n.startsWith("./")&&!o.startsWith("../")&&!o.startsWith("/")||!o.startsWith(".")&&!o.startsWith("/"))o=`./${o}`;return o}function Pc(e,t,n){let{pathname:r,query:o,fragment:i}=Ke(e);if(!An(r))return e;let s=S.normalize(S.join(t,r));return Et(kc(S.join(n,"_"),s,e),o,i)}function Co(e,t,n,r){let{pathname:o,query:i,fragment:s}=Ke(e);if(!o)return;if(wh(o,n))return;let c=o.endsWith(".md")?r.path:y(r),p=c.startsWith("/")?c:`/${c}`,u=An(o)?kc(t,p,e):c;return Et(u,i,s)}var xh=new Set(["asset","source"]),Ac="pmx-new-tab-description",bh="data-pmx-default-target";function Sh(e,t){let n=e.getAttribute("class");if(!n)return!1;return n.split(/\s+/).includes(t)}function Ao(e,t){if(Sh(e,t))return;let n=e.getAttribute("class");e.setAttribute("class",n?`${n} ${t}`:t)}function Rc(e,t,n){let r=e.getAttribute(t)?.trim(),o=r?r.split(/\s+/):[];if(o.some((i)=>i.toLowerCase()===n.toLowerCase()))return;e.setAttribute(t,[...o,n].join(" "))}function vh(e){let t=e.trim();return/^(?:https?:)?\/\//i.test(t)}function kh(e){let t=e.getAttribute("class");if(!t)return!1;return t.split(/\s+/).some((n)=>n.startsWith("pmx-"))}function Ph(e,t,n){if(!kh(e))Ao(e,"pmx-link");if(le(t))Ao(e,"pmx-link-external");if(!vh(t)||e.getAttribute("download")!=null)return;if(e.getAttribute("target")==null&&n==="new-tab")e.setAttribute("target","_blank"),e.setAttribute(bh,"new-tab");if(e.getAttribute("target")?.trim().toLowerCase()!=="_blank")return;Ao(e,"pmx-link-new-tab"),Rc(e,"rel","noopener"),Rc(e,"aria-describedby",Ac)}function Cc(e,t,n){let r=new Map;for(let o of n.graph.linksFrom(t.path)){if(!o.to||!xh.has(o.type))continue;let i=_(o.href,t.data),{query:s,fragment:a}=Ke(i);if(o.type==="source"){let c=n.sources.get(o.to);if(c)r.set(i,Et(y(c),s,a));continue}r.set(i,Et(o.to,s,a))}if(!r.size)return e;return n.html.rewrite(e,[["[href], [src]",{element(o){for(let i of["href","src"]){let s=o.getAttribute(i),a=s?ee(s.trim()):void 0,c=a?r.get(a):void 0;if(c)o.setAttribute(i,c)}}}]])}function Ic(e={}){let t=e.externalWebLinks??"new-tab";if(t!=="new-tab"&&t!=="same-tab")throw Error(`Invalid external web-link policy: ${t}`);return{id:"canonical-links",postcompile(n,{source:r,scope:o},i){if(o!=="embedded")return n;return Cc(n,r,i)},page(n,{source:r},o){return Cc(n,r,o)},streamSelectors(){return{body:{element(n){n.prepend(`<span id="${Ac}" hidden>Opens in a new tab</span>`,{html:!0})}},"a[href]":{element(n){let r=n.getAttribute("href");if(r!=null)Ph(n,r,t)}}}}}}var Rh=new URL("./client.ts",import.meta.url),Ch="data-pmx-source-preview";function Ah(e,t,n){let r=e.trim();if(!r)return;let o;try{o=new URL(r,`http://pathmx.local${t.route||"/"}`)}catch{return}if(o.origin!=="http://pathmx.local")return;let i=n.sources.resolve(o.pathname),s=i?t.view.readSource(i.id):void 0;if(!i||!s)return;let a;if(o.hash.length>1)try{a=decodeURIComponent(o.hash.slice(1))}catch{return}let c=a?s.blocks.find((p)=>p.id===a):void 0;if(a&&!c&&i.id===t.source.id)return;return`${i.id}${a?`#${a}`:""}`}function Ih(e){let t=e.indexOf("#");return t===-1?{id:e}:{id:e.slice(0,t),fragment:e.slice(t+1)}}function $h(e,t){return t?`${e}#${encodeURIComponent(t)}`:e}function Ze(){return new Response("Not Found",{status:404})}function $c(){return{id:"source-preview",routes:[ce.get("summary",async(e)=>{let t=e.url.searchParams.get("id")?.trim();if(!t)return Ze();let n=Ih(t);if(!n.id)return Ze();let r=e.source(n.id);if(!r)return Ze();let o=y(r);if(e.resolve(o)?.id!==r.id)return Ze();let i=(await e.view()).readSource(r.id);if(!i)return Ze();let s=n.fragment?i.blocks.find((m)=>m.id===n.fragment):void 0,a=await e.readAccess(r);if(a==="denied")return Ze();let c=s?.meta.title||i.meta.title,p=s?.meta.description??i.meta.description,u=s?.meta.image??i.meta.image,l={id:t,href:$h(o,n.fragment),title:c,...p?{description:p}:{},...u?{image:u}:{},...s?{source:{href:o,title:i.meta.title}}:{}},d=Response.json(l,{headers:{"Cache-Control":"no-cache"}});return be(d,a,await e.session())})],streamSelectors(e,t){let n=0;return{'[data-pmx-prose="off"]':{element(r){n++,r.onEndTag(()=>{n--})}},".pmx-prose a[href]":{element(r){if(n)return;if(r.getAttribute("download")!=null)return;let o=r.getAttribute("href"),i=o?Ah(o,e,t):void 0;if(i)r.setAttribute(Ch,i)}}}},async documentAssets(e){await e.addBrowserBundle(Rh,"source-preview")}}}var Th=new Set(["title","min-depth","max-depth"]),Eh=/<toc\s*\/?>/gi,Tc="table-of-contents:toc",Oh=xe(Tc),Mh=new URL("./client.ts",import.meta.url);function Dh(e){if(e===!1)return;let t=e&&typeof e==="object"&&!Array.isArray(e)?e:{},n=(o,i)=>{let s=t[o];return typeof s==="number"&&Number.isInteger(s)?Math.min(6,Math.max(1,s)):i},r=n("minDepth",2);return{minDepth:r,maxDepth:Math.max(r,n("maxDepth",6)),title:typeof t.title==="string"&&t.title.trim()?t.title.trim():"On this page"}}function jh(e,t){let n=Dh(e.data.toc);if(!n)return;let r=t["min-depth"]?Number(t["min-depth"]):n.minDepth,o=t["max-depth"]?Number(t["max-depth"]):n.maxDepth;return{minDepth:r,maxDepth:Math.max(r,o),title:t.title?.trim()||n.title}}function Lh(e){if(!e.blocks.length)return e.headings.map((n)=>({...n,sourceId:e.id,blockPath:`${e.path}#block-0`}));let t=[];for(let n of e.blocks)for(let r of tn(e,n))t.push({...r,sourceId:e.id,blockPath:n.path});return t}function Bh(e){let t={depth:0,children:[]},n=[t];for(let r of e){while(n.length>1&&n.at(-1).depth>=r.depth)n.pop();let o={...r,children:[]};n.at(-1).children.push(o),n.push(o)}return t.children}function Ec(e){return b`<ol class="pmx-toc-list">
267
- ${e.map((t)=>{let n=t.children.length?Ec(t.children):null;return b`<li class="pmx-toc-item">
268
- <a href="#${t.id}" class="pmx-toc-link">${t.text}</a>${n}
269
- </li>`})}
270
- </ol>`}function Nh(e,t){let n=new Map;return e.filter((r)=>{let o=n.get(r.sourceId);if(o==null)o=t.view.readSource(r.sourceId)!=null,n.set(r.sourceId,o);return o})}var zh={"~standard":{version:1,vendor:"pathmx",validate(e){if(!e||typeof e!=="object"||Array.isArray(e))return{issues:[{message:"expected TOC attributes"}]};let t=e;for(let n of Object.keys(t))if(!Th.has(n))return{issues:[{message:`unexpected ${n} attribute`}]};if("title"in t&&(typeof t.title!=="string"||!t.title.trim()))return{issues:[{message:"title must not be empty"}]};for(let n of["min-depth","max-depth"]){if(!(n in t))continue;if(typeof t[n]!=="string"||!/^[1-6]$/.test(t[n]))return{issues:[{message:`${n} must be an integer from 1 to 6`}]}}if(typeof t["min-depth"]==="string"&&typeof t["max-depth"]==="string"&&Number(t["min-depth"])>Number(t["max-depth"]))return{issues:[{message:"min-depth must not exceed max-depth"}]};return{value:e}}}};function Oc(){return{id:"table-of-contents",components:[D({tag:Tc,props:zh,async compile(t,n){let r=jh(n.source,t.props);if(!r)return;let o={title:r.title,entries:Lh(n.source).filter((i)=>i.depth>=r.minDepth&&i.depth<=r.maxDepth)};if(!o.entries.length)return;return await n.addBrowserBundle(Mh,"toc"),o},render(t,n,r){if(!n)return"";let o=Nh(n.entries,r);if(!o.length)return"";return b`<nav
271
- class="pmx-toc"
272
- aria-label="${n.title}"
273
- data-pmx-toc
274
- >
275
- <p class="pmx-toc__title">${n.title}</p>
276
- <div class="pmx-toc-path-frame">
277
- ${Ec(Bh(o))}
278
- </div>
279
- </nav>`}})],postcompile(t,n){if(!n.elements.has("toc"))return t;let r=g(n.source.path),o=`<${Oh} ${N}="${r}" />`;return t.replace(Eh,o)}}}var Io=`:root {
280
- color-scheme: light dark;
281
- }
282
-
283
- :root[data-pmx-scheme="light"] {
284
- color-scheme: light;
285
- }
286
-
287
- :root[data-pmx-scheme="dark"] {
288
- color-scheme: dark;
289
- }
290
-
291
- :root {
292
- --pmx-default-light-color-bg: oklch(0.985 0 0);
293
- --pmx-default-light-color-fg: oklch(0.22 0.01 250);
294
- --pmx-default-light-color-muted: oklch(0.48 0.02 250);
295
- --pmx-default-light-color-surface: oklch(0.96 0.01 250);
296
- --pmx-default-light-color-link: oklch(0.48 0.16 255);
297
- --pmx-default-light-color-accent: oklch(0.54 0.18 255);
298
- --pmx-default-light-color-danger: oklch(0.54 0.2 25);
299
- --pmx-default-light-color-border: oklch(0.86 0.02 250);
300
- --pmx-default-light-color-focus: oklch(0.54 0.18 255);
301
- --pmx-default-dark-color-bg: oklch(0.18 0.01 250);
302
- --pmx-default-dark-color-fg: oklch(0.94 0.01 250);
303
- --pmx-default-dark-color-muted: oklch(0.72 0.02 250);
304
- --pmx-default-dark-color-surface: oklch(0.24 0.015 250);
305
- --pmx-default-dark-color-link: oklch(0.76 0.13 250);
306
- --pmx-default-dark-color-accent: oklch(0.72 0.16 250);
307
- --pmx-default-dark-color-danger: oklch(0.72 0.18 25);
308
- --pmx-default-dark-color-border: oklch(0.36 0.02 250);
309
- --pmx-default-dark-color-focus: oklch(0.76 0.13 250);
310
-
311
- --pmx-color-bg: light-dark(
312
- var(--pmx-default-light-color-bg),
313
- var(--pmx-default-dark-color-bg)
314
- );
315
- --pmx-color-fg: light-dark(
316
- var(--pmx-default-light-color-fg),
317
- var(--pmx-default-dark-color-fg)
318
- );
319
- --pmx-color-muted: light-dark(
320
- var(--pmx-default-light-color-muted),
321
- var(--pmx-default-dark-color-muted)
322
- );
323
- --pmx-color-surface: light-dark(
324
- var(--pmx-default-light-color-surface),
325
- var(--pmx-default-dark-color-surface)
326
- );
327
- --pmx-color-link: light-dark(
328
- var(--pmx-default-light-color-link),
329
- var(--pmx-default-dark-color-link)
330
- );
331
- --pmx-color-accent: light-dark(
332
- var(--pmx-default-light-color-accent),
333
- var(--pmx-default-dark-color-accent)
334
- );
335
- --pmx-color-danger: light-dark(
336
- var(--pmx-default-light-color-danger),
337
- var(--pmx-default-dark-color-danger)
338
- );
339
- --pmx-color-border: light-dark(
340
- var(--pmx-default-light-color-border),
341
- var(--pmx-default-dark-color-border)
342
- );
343
- --pmx-color-focus: light-dark(
344
- var(--pmx-default-light-color-focus),
345
- var(--pmx-default-dark-color-focus)
346
- );
347
-
348
- --pmx-font-body: ui-sans-serif, system-ui, sans-serif;
349
- --pmx-font-heading: var(--pmx-font-body);
350
- --pmx-font-mono: ui-monospace, SFMono-Regular, Menlo, monospace;
351
- --pmx-prose-size: 1rem;
352
- --pmx-prose-leading: 1.6;
353
- --pmx-prose-flow: 1em;
354
- --pmx-prose-gutter: 1.75rem;
355
- --pmx-radius: 0.5rem;
356
- --pmx-radius-sm: 0.25rem;
357
- --pmx-radius-md: 0.35rem;
358
- --pmx-radius-lg: 0.5rem;
359
- --pmx-radius-xl: 0.75rem;
360
- --pmx-radius-2xl: 1rem;
361
- --pmx-radius-3xl: 1.5rem;
362
- --pmx-radius-4xl: 2rem;
363
- --pmx-radius-full: 9999px;
364
- --pmx-document-measure: 72ch;
365
-
366
- /* Shared viewport chrome contract. Runtime-measured chrome updates insets. */
367
- --pmx-viewport-inset-block-start: 0px;
368
- --pmx-viewport-inset-block-end: 0px;
369
- --pmx-viewport-gutter-block-start: max(1rem, env(safe-area-inset-top, 0px));
370
- --pmx-viewport-gutter-block-end: max(1rem, env(safe-area-inset-bottom, 0px));
371
- --pmx-scroll-offset-block-start: calc(
372
- var(--pmx-viewport-inset-block-start) +
373
- var(--pmx-viewport-gutter-block-start)
374
- );
375
- --pmx-sticky-block-start: var(--pmx-scroll-offset-block-start);
376
- --pmx-sticky-block-end: calc(
377
- var(--pmx-viewport-inset-block-end) + var(--pmx-viewport-gutter-block-end)
378
- );
379
- --pmx-sticky-max-block-size: max(
380
- 0px,
381
- calc(100dvh - var(--pmx-sticky-block-start) - var(--pmx-sticky-block-end))
382
- );
383
- --pmx-sticky-header-transition-duration: 180ms;
384
-
385
- --pmx-default-light-code-bg: oklch(0.955 0.01 250);
386
- --pmx-default-light-code-fg: oklch(0.22 0.01 250);
387
- --pmx-default-light-code-comment: oklch(0.48 0.02 250);
388
- --pmx-default-light-code-keyword: oklch(0.47 0.16 255);
389
- --pmx-default-light-code-string: oklch(0.43 0.12 145);
390
- --pmx-default-light-code-punctuation: oklch(0.42 0.02 250);
391
- --pmx-default-dark-code-bg: oklch(0.22 0.015 250);
392
- --pmx-default-dark-code-fg: oklch(0.9 0.01 250);
393
- --pmx-default-dark-code-comment: oklch(0.68 0.02 250);
394
- --pmx-default-dark-code-keyword: oklch(0.78 0.13 255);
395
- --pmx-default-dark-code-string: oklch(0.78 0.12 145);
396
- --pmx-default-dark-code-punctuation: oklch(0.78 0.02 250);
397
- --pmx-code-bg: light-dark(
398
- var(--pmx-default-light-code-bg),
399
- var(--pmx-default-dark-code-bg)
400
- );
401
- --pmx-code-fg: light-dark(
402
- var(--pmx-default-light-code-fg),
403
- var(--pmx-default-dark-code-fg)
404
- );
405
- --pmx-code-comment: light-dark(
406
- var(--pmx-default-light-code-comment),
407
- var(--pmx-default-dark-code-comment)
408
- );
409
- --pmx-code-keyword: light-dark(
410
- var(--pmx-default-light-code-keyword),
411
- var(--pmx-default-dark-code-keyword)
412
- );
413
- --pmx-code-string: light-dark(
414
- var(--pmx-default-light-code-string),
415
- var(--pmx-default-dark-code-string)
416
- );
417
- --pmx-code-punctuation: light-dark(
418
- var(--pmx-default-light-code-punctuation),
419
- var(--pmx-default-dark-code-punctuation)
420
- );
421
-
422
- /* border radii */
423
- --pmx-radius-sm: 0.25rem;
424
- --pmx-radius-md: 0.35rem;
425
- --pmx-radius-lg: 0.5rem;
426
- --pmx-radius-xl: 0.75rem;
427
- --pmx-radius-2xl: 1rem;
428
- --pmx-radius-3xl: 1.5rem;
429
- --pmx-radius-full: 9999px;
430
-
431
- /* Shadows follow a compact Tailwind-like elevation scale. */
432
- --pmx-shadow-2xs: 0 1px rgb(0 0 0 / 5%);
433
- --pmx-shadow-xs: 0 1px 2px 0 rgb(0 0 0 / 5%);
434
- --pmx-shadow-sm:
435
- 0 1px 3px 0 rgb(0 0 0 / 10%), 0 1px 2px -1px rgb(0 0 0 / 10%);
436
- --pmx-shadow-md:
437
- 0 4px 6px -1px rgb(0 0 0 / 10%), 0 2px 4px -2px rgb(0 0 0 / 10%);
438
- --pmx-shadow-lg:
439
- 0 10px 15px -3px rgb(0 0 0 / 10%), 0 4px 6px -4px rgb(0 0 0 / 10%);
440
- --pmx-shadow-xl:
441
- 0 20px 25px -5px rgb(0 0 0 / 10%), 0 8px 10px -6px rgb(0 0 0 / 10%);
442
- --pmx-shadow-2xl: 0 25px 50px -12px rgb(0 0 0 / 25%);
443
- --pmx-shadow: var(--pmx-shadow-sm);
444
-
445
- /* Material: frosted-glass fills. Thickness is how much sits behind shows through. */
446
- --pmx-material-ultra-thin: color-mix(
447
- in oklch,
448
- var(--pmx-color-bg) 42%,
449
- transparent
450
- );
451
- --pmx-material-thin: color-mix(
452
- in oklch,
453
- var(--pmx-color-bg) 56%,
454
- transparent
455
- );
456
- --pmx-material-regular: color-mix(
457
- in oklch,
458
- var(--pmx-color-bg) 72%,
459
- transparent
460
- );
461
- --pmx-material-thick: color-mix(
462
- in oklch,
463
- var(--pmx-color-bg) 86%,
464
- transparent
465
- );
466
- --pmx-material-ultra-thick: color-mix(
467
- in oklch,
468
- var(--pmx-color-bg) 96%,
469
- transparent
470
- );
471
- --pmx-material: var(--pmx-material-regular);
472
- --pmx-material-filter: blur(1.25rem) saturate(1.8);
473
- }
474
-
475
- @media (prefers-reduced-transparency: reduce) {
476
- :root {
477
- --pmx-material-ultra-thin: color-mix(
478
- in oklch,
479
- var(--pmx-color-bg) 88%,
480
- transparent
481
- );
482
- --pmx-material-thin: color-mix(
483
- in oklch,
484
- var(--pmx-color-bg) 92%,
485
- transparent
486
- );
487
- --pmx-material-regular: var(--pmx-color-bg);
488
- --pmx-material-thick: var(--pmx-color-bg);
489
- --pmx-material-ultra-thick: var(--pmx-color-bg);
490
- --pmx-material-filter: none;
491
- }
492
- }
493
-
494
- html {
495
- scroll-padding-block-start: var(--pmx-scroll-offset-block-start);
496
- scroll-padding-block-end: var(--pmx-sticky-block-end);
497
- }
498
-
499
- body {
500
- margin: 0;
501
- min-height: 100svh;
502
- background: var(--pmx-color-bg);
503
- color: var(--pmx-color-fg);
504
- font-family: var(--pmx-font-body);
505
- font-size: var(--pmx-prose-size);
506
- line-height: var(--pmx-prose-leading);
507
- }
508
-
509
- :where([data-pmx-sticky-header]) {
510
- position: sticky;
511
- z-index: 10;
512
- inset-block-start: 0;
513
- transition:
514
- opacity var(--pmx-sticky-header-transition-duration) ease-out,
515
- transform var(--pmx-sticky-header-transition-duration) ease-out;
516
- }
517
-
518
- :where([data-pmx-sticky-header][data-pmx-hidden]) {
519
- opacity: 0;
520
- pointer-events: none;
521
- transform: translateY(calc(-100% - 1px));
522
- }
523
-
524
- :where([data-pmx-sticky-header]:focus-within) {
525
- opacity: 1;
526
- pointer-events: auto;
527
- transform: none;
528
- }
529
-
530
- @media (prefers-reduced-motion: reduce) {
531
- :where([data-pmx-sticky-header]) {
532
- transition: none;
533
- }
534
- }
535
-
536
- .pmx-document {
537
- max-width: var(--pmx-document-measure);
538
- margin-inline: auto;
539
- padding-block: 1.5rem 3rem;
540
- padding-inline: max(1rem, var(--pmx-prose-gutter));
541
- }
542
-
543
- .pmx-document > * + * {
544
- margin-block-start: var(--pmx-prose-flow);
545
- }
546
-
547
- .pmx-document > [data-pmx-block]:not(:last-of-type) {
548
- padding-block-end: var(--pmx-prose-flow);
549
- border-block-end: 1px solid var(--pmx-color-border);
550
- }
551
-
552
- .pmx-error {
553
- margin-block: 0.75rem;
554
- padding: 0.75rem 1rem;
555
- border: 1px solid var(--pmx-color-danger);
556
- border-radius: var(--pmx-radius);
557
- background: color-mix(
558
- in oklch,
559
- var(--pmx-color-danger) 8%,
560
- var(--pmx-color-bg)
561
- );
562
- color: var(--pmx-color-fg);
563
- }
564
-
565
- .pmx-error strong {
566
- color: var(--pmx-color-danger);
567
- }
568
-
569
- .pmx-error button {
570
- display: block;
571
- margin-block-start: 0.75rem;
572
- }
573
-
574
- /* links */
575
-
576
- .pmx-link {
577
- color: var(--pmx-color-link);
578
- text-decoration: none;
579
- }
580
-
581
- .pmx-link:hover {
582
- text-decoration: underline;
583
- }
584
-
585
- .pmx-link-external {
586
- color: var(--pmx-color-link);
587
- text-decoration: none;
588
- }
589
-
590
- .pmx-link-external:hover {
591
- text-decoration: underline;
592
- }
593
-
594
- .pmx-link-new-tab::after {
595
- content: "";
596
- display: inline-block;
597
- width: 0.8em;
598
- height: 0.8em;
599
- margin-inline-start: 0.2em;
600
- background: currentColor;
601
- vertical-align: 0.05em;
602
- -webkit-mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='black' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M15 3h6v6'/%3E%3Cpath d='m10 14 11-11'/%3E%3Cpath d='M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6'/%3E%3C/svg%3E")
603
- center / contain no-repeat;
604
- mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='black' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M15 3h6v6'/%3E%3Cpath d='m10 14 11-11'/%3E%3Cpath d='M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6'/%3E%3C/svg%3E")
605
- center / contain no-repeat;
606
- }
607
-
608
- :where(
609
- .pmx-material-ultra-thin,
610
- .pmx-material-thin,
611
- .pmx-material-regular,
612
- .pmx-material-thick,
613
- .pmx-material-ultra-thick
614
- ) {
615
- backdrop-filter: var(--pmx-material-filter);
616
- }
617
-
618
- :where(.pmx-material-ultra-thin) {
619
- background: var(--pmx-material-ultra-thin);
620
- }
621
-
622
- :where(.pmx-material-thin) {
623
- background: var(--pmx-material-thin);
624
- }
625
-
626
- :where(.pmx-material-regular) {
627
- background: var(--pmx-material);
628
- }
629
-
630
- :where(.pmx-material-thick) {
631
- background: var(--pmx-material-thick);
632
- }
633
-
634
- :where(.pmx-material-ultra-thick) {
635
- background: var(--pmx-material-ultra-thick);
636
- }
637
- `;var $o=`@scope (.pmx-prose) to ([data-pmx-prose="off"]) {
638
- :where(:scope) {
639
- color: var(--pmx-color-fg);
640
- line-height: var(--pmx-prose-leading);
641
-
642
- > :where(:first-child) {
643
- margin-block-start: 0;
644
- }
645
-
646
- > :where(:last-child) {
647
- margin-block-end: 0;
648
- }
649
-
650
- > :where(h1, h2, h3, h4, h5, h6),
651
- > :where(.pmx-heading) {
652
- margin-block: calc(var(--pmx-prose-flow) * 1.8)
653
- calc(var(--pmx-prose-flow) * 0.75);
654
- }
655
-
656
- > :where(h1, h2, h3, h4, h5, h6),
657
- > :where(.pmx-heading) > :where(h1, h2, h3, h4, h5, h6) {
658
- color: var(--pmx-color-fg);
659
- font-family: var(--pmx-font-heading);
660
- font-weight: 700;
661
- line-height: 1.18;
662
- text-wrap: balance;
663
- scroll-margin-block-start: 0;
664
- }
665
-
666
- > :where(.pmx-heading) {
667
- position: relative;
668
- }
669
-
670
- > :where(.pmx-heading) > :where(h1, h2, h3, h4, h5, h6) {
671
- min-inline-size: 0;
672
- margin: 0;
673
- cursor: pointer;
674
- transition: color 120ms ease-out;
675
- }
676
-
677
- :where(h1, h2, h3, h4, h5, h6) > a[href] {
678
- &,
679
- &:hover {
680
- color: inherit;
681
- font-weight: inherit;
682
- text-decoration: none;
683
- }
684
- }
685
-
686
- > :where(h1),
687
- > :where(.pmx-heading.level-h1) > h1 {
688
- font-size: 2.25em;
689
- }
690
- > :where(h2),
691
- > :where(.pmx-heading.level-h2) > h2 {
692
- font-size: 1.75em;
693
- }
694
- > :where(h3),
695
- > :where(.pmx-heading.level-h3) > h3 {
696
- font-size: 1.35em;
697
- }
698
- > :where(h4),
699
- > :where(.pmx-heading.level-h4) > h4 {
700
- font-size: 1.15em;
701
- }
702
- > :where(h5, h6),
703
- > :where(.pmx-heading.level-h5) > h5,
704
- > :where(.pmx-heading.level-h6) > h6 {
705
- font-size: 1em;
706
- }
707
-
708
- .pmx-heading-anchor {
709
- position: absolute;
710
- inline-size: 1px;
711
- block-size: 1px;
712
- margin: -1px;
713
- overflow: hidden;
714
- clip-path: inset(50%);
715
- white-space: nowrap;
716
- }
717
-
718
- :where(.pmx-heading:hover, .pmx-heading:focus-within)
719
- > :where(h1, h2, h3, h4, h5, h6) {
720
- color: var(--pmx-color-link);
721
- }
722
-
723
- .pmx-heading:has(> .pmx-heading-anchor:focus-visible)
724
- > :where(h1, h2, h3, h4, h5, h6) {
725
- outline: 2px solid var(--pmx-color-focus);
726
- outline-offset: 2px;
727
- border-radius: var(--pmx-radius-sm);
728
- }
729
-
730
- > :where(p, ul, ol, blockquote, pre, table, figure, hr, .pmx-code-block) {
731
- margin-block: var(--pmx-prose-flow);
732
- }
733
-
734
- :where(ul, ol) {
735
- padding-inline-start: 1.5em;
736
- }
737
-
738
- :where(ul) {
739
- list-style-type: disc;
740
-
741
- :where(ul) {
742
- list-style-type: circle;
743
-
744
- :where(ul) {
745
- list-style-type: square;
746
- }
747
- }
748
- }
749
-
750
- :where(ol) {
751
- list-style-type: decimal;
752
- }
753
-
754
- > :where(ul, ol) :where(ul, ol) {
755
- margin-block: 0.35em;
756
- }
757
-
758
- :where(li) {
759
- margin-block: 0.3em;
760
-
761
- &::marker {
762
- color: var(--pmx-color-muted);
763
- }
764
- }
765
-
766
- > :where(ul:has(> li.task-list-item), ol:has(> li.task-list-item)) {
767
- padding-inline-start: 0;
768
- }
769
-
770
- :where(li.task-list-item) {
771
- position: relative;
772
- margin-block: 0.4em;
773
- padding-inline-start: 1.6em;
774
- list-style: none;
775
-
776
- &::marker {
777
- content: "";
778
- }
779
- }
780
-
781
- :where(li.task-list-item > .task-list-item-checkbox:first-child) {
782
- position: absolute;
783
- inset-inline-start: 0;
784
- inset-block-start: 0.27em;
785
- inline-size: 1.05em;
786
- block-size: 1.05em;
787
- margin: 0;
788
- accent-color: var(--pmx-color-accent);
789
- opacity: 1;
790
- }
791
-
792
- :where(li.task-list-item > p) {
793
- margin-block: 0.45em;
794
- }
795
-
796
- :where(li.task-list-item > p:first-of-type) {
797
- margin-block-start: 0;
798
- }
799
-
800
- :where(li.task-list-item > p:last-of-type) {
801
- margin-block-end: 0;
802
- }
803
-
804
- > :where(blockquote) {
805
- border-inline-start: 0.25em solid var(--pmx-color-border);
806
- color: var(--pmx-color-muted);
807
- padding-inline-start: 1em;
808
- }
809
-
810
- :where(table) {
811
- display: block;
812
- inline-size: 100%;
813
- max-inline-size: 100%;
814
- overflow-x: auto;
815
- overscroll-behavior-inline: contain;
816
- -webkit-overflow-scrolling: touch;
817
- border-collapse: collapse;
818
- }
819
-
820
- :where(th, td) {
821
- padding: 0.55em 0.7em;
822
- border-bottom: 1px solid var(--pmx-color-border);
823
- vertical-align: top;
824
- }
825
-
826
- :where(th) {
827
- font-weight: 650;
828
- text-align: start;
829
- white-space: nowrap;
830
- }
831
-
832
- :where(tr > :first-child) {
833
- position: sticky;
834
- inset-inline-start: 0;
835
- z-index: 1;
836
- background: var(--pmx-color-bg);
837
- border-inline-end: 1px solid var(--pmx-color-border);
838
- }
839
-
840
- :where(thead tr > :first-child) {
841
- z-index: 2;
842
- }
843
-
844
- @media (max-width: 40rem) {
845
- :where(tr > :first-child) {
846
- min-inline-size: 8rem;
847
- }
848
-
849
- :where(tr > :not(:first-child)) {
850
- min-inline-size: 12rem;
851
- }
852
- }
853
-
854
- > :where(hr) {
855
- border: 0;
856
- border-block-start: 1px solid var(--pmx-color-border);
857
- }
858
-
859
- :where(a) {
860
- color: var(--pmx-color-link);
861
- text-decoration-line: underline;
862
- text-decoration-color: color-mix(
863
- in srgb,
864
- var(--pmx-color-link) 45%,
865
- transparent
866
- );
867
- text-decoration-thickness: 0.08em;
868
- text-underline-offset: 0.16em;
869
-
870
- &:hover {
871
- text-decoration-color: currentColor;
872
- }
873
- }
874
-
875
- :where(mark) {
876
- background: color-mix(in oklch, var(--pmx-color-accent) 88%, transparent);
877
- color: inherit;
878
- }
879
-
880
- :where(figcaption) {
881
- color: var(--pmx-color-muted);
882
- font-size: 0.92em;
883
- }
884
-
885
- :where(img) {
886
- max-inline-size: 100%;
887
- height: auto;
888
- border-radius: var(--pmx-radius);
889
- }
890
-
891
- :where(.pmx-mermaid) {
892
- overflow-x: auto;
893
- }
894
-
895
- :where(.pmx-mermaid svg) {
896
- display: block;
897
- max-inline-size: 100%;
898
- block-size: auto;
899
- margin-inline: auto;
900
- }
901
-
902
- :where(code) {
903
- font-family: var(--pmx-font-mono);
904
- font-size: 0.92em;
905
- background: var(--pmx-code-bg);
906
- color: var(--pmx-code-fg);
907
- border: 1px solid var(--pmx-color-border);
908
- border-radius: calc(var(--pmx-radius) * 0.65);
909
- padding: 0.08em 0.3em;
910
- }
911
-
912
- :where(pre, .pmx-code-block) :where(code) {
913
- font-size: 0.9em;
914
- background: transparent;
915
- border: 0;
916
- border-radius: 0;
917
- padding: 0;
918
- }
919
- }
920
- }
921
- `;var To=`:root {
922
- --pmx-view-transition-duration: 220ms;
923
- --pmx-view-transition-easing: ease;
924
- --pmx-view-transition-distance: 1.25rem;
925
- }
926
-
927
- @keyframes pmx-view-out-forward {
928
- to {
929
- opacity: 0;
930
- transform: translateX(calc(-1 * var(--pmx-view-transition-distance)));
931
- }
932
- }
933
-
934
- @keyframes pmx-view-in-forward {
935
- from {
936
- opacity: 0;
937
- transform: translateX(var(--pmx-view-transition-distance));
938
- }
939
- }
940
-
941
- @keyframes pmx-view-out-back {
942
- to {
943
- opacity: 0;
944
- transform: translateX(var(--pmx-view-transition-distance));
945
- }
946
- }
947
-
948
- @keyframes pmx-view-in-back {
949
- from {
950
- opacity: 0;
951
- transform: translateX(calc(-1 * var(--pmx-view-transition-distance)));
952
- }
953
- }
954
-
955
- html:active-view-transition-type(pmx-forward) ::view-transition-old(root),
956
- html:active-view-transition-type(pmx-forward) ::view-transition-new(root),
957
- html:active-view-transition-type(pmx-back) ::view-transition-old(root),
958
- html:active-view-transition-type(pmx-back) ::view-transition-new(root) {
959
- mix-blend-mode: normal;
960
- }
961
-
962
- html:active-view-transition-type(pmx-forward) ::view-transition-old(root) {
963
- animation: var(--pmx-view-transition-duration)
964
- var(--pmx-view-transition-easing) both pmx-view-out-forward;
965
- }
966
-
967
- html:active-view-transition-type(pmx-forward) ::view-transition-new(root) {
968
- animation: var(--pmx-view-transition-duration)
969
- var(--pmx-view-transition-easing) both pmx-view-in-forward;
970
- }
971
-
972
- html:active-view-transition-type(pmx-back) ::view-transition-old(root) {
973
- animation: var(--pmx-view-transition-duration)
974
- var(--pmx-view-transition-easing) both pmx-view-out-back;
975
- }
976
-
977
- html:active-view-transition-type(pmx-back) ::view-transition-new(root) {
978
- animation: var(--pmx-view-transition-duration)
979
- var(--pmx-view-transition-easing) both pmx-view-in-back;
980
- }
981
-
982
- @media (prefers-reduced-motion: reduce) {
983
- ::view-transition-group(*),
984
- ::view-transition-old(*),
985
- ::view-transition-new(*) {
986
- animation: none !important;
987
- }
988
- }
989
- `;var Mc=D({tag:"theme:scheme-toggle",client:new URL("./scheme.js",import.meta.url),render(){return`<button class="pmx-scheme-toggle" type="button" aria-label="Toggle color scheme" title="Toggle color scheme"><span data-pmx-scheme-icon="light">${Oa}</span><span data-pmx-scheme-icon="dark">${Ea}</span></button>`}});var Lc={bg:"--pmx-color-bg",fg:"--pmx-color-fg",muted:"--pmx-color-muted",surface:"--pmx-color-surface",link:"--pmx-color-link",accent:"--pmx-color-accent",danger:"--pmx-color-danger",border:"--pmx-color-border",focus:"--pmx-color-focus"},Bc={body:"--pmx-font-body",heading:"--pmx-font-heading",mono:"--pmx-font-mono"},Nc={size:"--pmx-prose-size",leading:"--pmx-prose-leading",flow:"--pmx-prose-flow",gutter:"--pmx-prose-gutter"},zc={radius:"--pmx-radius"},qc={bg:"--pmx-code-bg",fg:"--pmx-code-fg",comment:"--pmx-code-comment",keyword:"--pmx-code-keyword",string:"--pmx-code-string",punctuation:"--pmx-code-punctuation"},Vc=["color","font","prose","shape","code"],XP=[...Vc,"measure","light","dark"];function Bo(e){return Boolean(e)&&typeof e==="object"&&!Array.isArray(e)}function Mo(e){return L(e)&&S.dirname(e.path)==="/"}function Ot(e,t,n,r){if(e===void 0)return;if(!Bo(e)){n?.warn("invalid",{path:r,detail:"Expected an object."});return}let o={};for(let[i,s]of Object.entries(e)){if(!t[i]){n?.warn("unknown",{path:`${r}.${i}`});continue}if(typeof s==="string"||typeof s==="number")o[i]=s}return Object.keys(o).length?o:void 0}function Eo(e,t,n,r=[]){if(e===void 0)return;if(!Bo(e)){t?.warn("invalid",{path:n,detail:"Expected an object."});return}for(let i of Object.keys(e))if(![...Vc,...r].includes(i))t?.warn("unknown",{path:`${n}.${i}`});let o={color:Ot(e.color,Lc,t,`${n}.color`),font:Ot(e.font,Bc,t,`${n}.font`),prose:Ot(e.prose,Nc,t,`${n}.prose`),shape:Ot(e.shape,zc,t,`${n}.shape`),code:Ot(e.code,qc,t,`${n}.code`)};return Object.values(o).some(Boolean)?o:void 0}function Do(e,t){if(e===void 0)return;if(!Bo(e)){t?.warn("invalid",{detail:"Expected an object."});return}let n=Eo(e,t,"theme",["measure","light","dark"]),r=typeof e.measure==="string"?e.measure:void 0,o=Eo(e.light,t,"theme.light"),i=Eo(e.dark,t,"theme.dark"),s={...n??{},...r?{measure:r}:{},...o?{light:o}:{},...i?{dark:i}:{}};return Object.keys(s).length?s:void 0}function Oo(e){if(!e)return[];let t=[],n=(r,o)=>{if(!r)return;for(let[i,s]of Object.entries(r)){let a=o[i];if(a&&s!==void 0)t.push(`${a}: ${s};`)}};if(n(e.color,Lc),n(e.font,Bc),n(e.prose,Nc),n(e.shape,zc),n(e.code,qc),e.measure)t.push(`--pmx-document-measure: ${e.measure};`);return t}function jo(e,t){if(!t.length)return"";return`${e} {
990
- ${t.map((n)=>` ${n}`).join(`
991
- `)}
992
- }`}function Fh(e){return e.split(`
993
- `).map((t)=>t?` ${t}`:t).join(`
994
- `)}function Uh(e,t){return e===":root"?`:root[data-pmx-scheme="${t}"]`:`[data-pmx-scheme="${t}"] ${e}`}function _h(e,t){let n=t==="light"?"dark":"light";return e===":root"?`:root:not([data-pmx-scheme="${n}"])`:`:root:not([data-pmx-scheme="${n}"]) ${e}`}function Dc(e,t,n){if(!n.length)return[];return[jo(Uh(e,t),n),`@media (prefers-color-scheme: ${t}) {
995
- ${Fh(jo(_h(e,t),n))}
996
- }`]}function Lo(e,t){return[jo(t,Oo(e)),...Dc(t,"light",Oo(e.light)),...Dc(t,"dark",Oo(e.dark))].filter(Boolean).join(`
997
-
998
- `)}var Qh="oklch(0.985 0 0)",Wh="oklch(0.18 0.01 250)";function et(e,t){let n=e?.[t]?.color?.bg??e?.color?.bg;if(typeof n==="string"||typeof n==="number")return String(n);return t==="light"?Qh:Wh}function jc(e){if(!e||!Mo(e))return"";let t=Do(e.data.theme);if(!t)return"";return[Lo(t,":root"),et(t,"light"),et(t,"dark")].join(`
999
- `)}function Xh(e,t){let n=e.getAttribute("style")?.trim()??"",r=e.getAttribute("data-pmx-scheme"),o=n?[n.replace(/;?$/,";")]:[`color-scheme: ${r==="light"||r==="dark"?r:"light dark"};`];o.push(`background-color: light-dark(${et(t,"light")}, ${et(t,"dark")});`),e.setAttribute("style",o.join(" "))}function Hc(){let e,t=[];return{id:"theme",index(n,r){if(!Mo(n))return;t=[n.path,n.id],e=Do(n.data.theme,r.log)},unindex(n){if(!t.includes(n))return;e=void 0,t=[]},components:[Mc],documentAssets(n){let r=e?`${Io}
1000
-
1001
- ${$o}
1002
-
1003
- ${To}
1004
-
1005
- ${Lo(e,":root")}`:`${Io}
1006
-
1007
- ${$o}
1008
-
1009
- ${To}`;n.addAsset({type:"stylesheet",name:"theme.css",text:r},{type:"meta",attrs:{name:"color-scheme",content:"light dark"}},{type:"meta",attrs:{name:"theme-color",media:"(prefers-color-scheme: light)",content:et(e,"light")}},{type:"meta",attrs:{name:"theme-color",media:"(prefers-color-scheme: dark)",content:et(e,"dark")}})},streamSelectors(){return{html:{element:(n)=>Xh(n,e)}}},invalidate({before:n,after:r},o){if(jc(n)===jc(r))return;return{targets:Qe(o.sources.builtPages())}},page(n,r,o){if(Mo(r.source))return n;let i=Do(r.source.data.theme,o.log);if(i)r.addAsset({type:"style",text:Lo(i,".pmx-document")});return n}}}var Jh=new URL("./client.ts",import.meta.url),Gh=new URL("./static-client.ts",import.meta.url),Yh=30000;function Kh(e,t,n,r,o=!1){let i=new TextEncoder,s,a,c=()=>{if(s?.(),s=void 0,a)clearInterval(a);a=void 0},p=new ReadableStream({start(l){l.enqueue(i.encode(`: connected
1010
-
1011
- `)),a=setInterval(()=>{try{l.enqueue(i.encode(`: keep-alive
1012
-
1013
- `))}catch{c()}},Yh),s=e.onSync((d)=>{if(!Zs(d,n,r))return;try{l.enqueue(i.encode(`event: sync
1014
- data: changed
1015
-
1016
- `))}catch{c()}}),t.signal.addEventListener("abort",()=>{c();try{l.close()}catch{}},{once:!0})},cancel(){c()}}),u=new Headers({"Content-Type":"text/event-stream","Cache-Control":o?"private, no-store":"no-cache",Connection:"keep-alive"});if(o)u.set("Vary","Cookie");return new Response(p,{headers:u})}function Fc(){return{id:"runtime",name:"RuntimePlugin",routes:[ce.get("live",async(e)=>{let{request:t,url:n}=e,r=n.searchParams.get("route"),o=r?e.resolve(r):void 0;if(!o)return new Response("Unknown live route.",{status:400});let i=await e.session(),s=await e.readAccess(o);if(s==="denied")return new Response("Not Found",{status:404});return Kh(e,t,y(o),i.type==="authenticated"?i.actor.id:void 0,s==="private"||i.type==="authenticated")})],async documentAssets(e,t){await e.addBrowserBundle(t.runtime.target==="static"?Gh:Jh,"runtime")}}}var No="layout",Zh=/<pmx-content\b/gi,eg=/<pmx-content\s*(?:\/\s*>|>\s*<\/pmx-content\s*>)/gi,_c=Object.freeze({type:"plugin",plugin:"layout",key:"default"});function Qc(e){return{type:"plugin",plugin:"layout",key:`type:${e}`}}function F(e,t){throw new R({source:e.path,plugin:"layout",message:`Invalid layout in ${e.path}: ${t}`})}function tg(e,t){if(t&&e.blocks.length)return e.blocks.flatMap((n)=>n.links);if(t&&e.links.length)return e.links;return pt(Qt(e.body).linkFragments)}function In(e,t=!0){if(!e.body.includes("@layout"))return{defaults:new Map};let n=[],r=new Map;for(let o of tg(e,t)){if(o.directive?.name!=="layout")continue;if(o.kind!=="definition")F(e,"@layout must use a reference definition.");let i=o.directive.qualifiers;if(!i.length)n.push(o);else if(i.length===1){let s=i[0];if(r.has(s))F(e,`multiple @layout.${s} definitions.`);r.set(s,o)}else F(e,`@layout accepts one source type qualifier, received ${i.join(".")}.`)}if(n.length>1)F(e,"multiple @layout definitions.");return{local:n[0],defaults:r}}function Uc(e,t){if(!e)return new Map;return new Map([...In(e,t).defaults].map(([n,r])=>[n,r.href]))}function ng(e,t){let n=Uc(e,!0),r=Uc(t,!1),o=[];for(let i of new Set([...n.keys(),...r.keys()])){if(n.get(i)===r.get(i))continue;o.push(i==="default"?_c:Qc(i))}return o}function rg(e,t){let n=t.href.trim();if(!Ht(n))F(e,`@layout must target an exact Markdown Source, received ${n}.`);return n}function og(e,t,n,r){let o=rg(e,n),i=r.graph.linksFrom(e.path).find((a)=>a.href===o&&a.type==="source"),s=i?.to?r.sources.get(i.to):void 0;if(!s)F(e,`layout Source not found: ${o}.`);if(s.type==="components"){r.log.warn("legacy-components",{source:e.path,target:s.path,detail:"Use an authored .layout.md Source for site layout."});return}if(s.type!==No)F(e,`${o} is a ${s.type} Source, not a layout.`);if(!r.access.canEmbed(t.id,s.id))F(t,`cannot embed layout ${s.path}.`);return s}function ig(e,t){let n=[...t.matchAll(Zh)],r=[...t.matchAll(eg)];if(n.length!==1||r.length!==1)F(e,`expected exactly one empty <pmx-content />, found ${n.length}.`);let o=r[0],i=o.index;return{before:t.slice(0,i),after:t.slice(i+o[0].length)}}function sg(){let e=[],t=new Set;return{values:e,depend(n){let r=re(n);if(t.has(r))return;t.add(r),e.push(n)}}}function Wc(){let e=new Map,t=new Map,n=(i,s)=>{if(i.type!==No)F(i,`expected a ${No} Source.`);let a=t.get(i.path);if(a)return a;return a=(async()=>{let c=sg(),p=await s.compile.document(i,c);return{...ig(i,p.html),assets:p.assets,dependencies:c.values}})(),t.set(i.path,a),a},r=(i)=>{if(e.size>1)F(i,"multiple root-owned layout configurations.");let s=e.values().next();return s.done?void 0:s.value},o=(i,s,a)=>{if(i.data.layout===!1)return[];let p=In(i).local,u=i;if(!p){let f=r(i),h=Qc(i.type);if(s.depend(h),p=f?.links.get(i.type),!p)s.depend(_c),p=f?.links.get("default");u=f?.source??i}if(!p)return[];let l=[],d=new Set([i.path]),m=i;while(p){let f=og(u,m,p,a);if(!f)break;if(d.has(f.path))F(i,`layout cycle: ${[...d,f.path].join(" -> ")}.`);d.add(f.path),l.push(f),s.depend({type:"source",path:f.path}),m=f,u=f,p=f.data.layout===!1?void 0:In(f).local}return l};return{id:"layout",schema:{sources:{layout:{label:"Layout",description:"Authored page chrome with one content outlet.",icon:"panels-top-left",color:"violet"}}},index(i,s){let a=In(i);if(e.delete(i.path),!a.defaults.size)return;let c=s.sources.resolve("/");if(!L(i)||c?.path!==i.path){let p=a.defaults.keys().next().value;F(i,`@layout.${p} is owned by the root route Source only.`)}e.set(i.path,{source:i,links:a.defaults})},unindex(i){e.delete(i),t.clear()},invalidate({before:i,after:s}){t.clear();let a=ng(i,s);if(a.length)return{dependencies:a}},async page(i,s,a){let c=o(s.source,s,a);for(let p of c){let u=await n(p,a);for(let l of u.dependencies)s.depend(l);s.addAsset(...u.assets),i=`${u.before}${i}${u.after}`}return i}}}var Xc="navigation";function j(e,t){throw new R({source:e.path,plugin:"navigation",message:`Invalid navigation in ${e.path}: ${t}`})}function Gc(e,t){let n=t.trim();if(!Ht(n))j(e,`links must target exact Markdown Sources, received ${n}.`);return n}function ag(e,t){let n=t.trim();if(n.startsWith("~/")&&n.endsWith(".md")&&!n.includes("?")&&!n.includes("#")&&!n.includes("\\"))return n;return Gc(e,n)}function Yc(e,t){let n=[];for(let r of t){if(r.type!=="unordered")j(e,`line ${r.items[0]?.line??1} must use a Markdown bullet.`);for(let o of r.items){if(o.children.length>1)j(e,`line ${o.children[1]?.items[0]?.line??o.line} has inconsistent indentation.`);let i=lt(o);if(!i)j(e,`line ${o.line} must be a Markdown bullet containing one link.`);let s=ee(ze(i.label));if(!s)j(e,`line ${o.line} has an empty label.`);n.push({label:s,href:ag(e,i.href),children:Yc(e,o.children)})}}return n}function cg(e){let t=Ne(e.body),n=t.other[0];if(n)j(e,n.text.includes("\t")?`line ${n.line} uses a tab for indentation.`:`line ${n.line} must be a Markdown bullet containing one link.`);let r=Yc(e,t.lists);if(!r.length)j(e,"expected at least one link.");return r}function pg(e){return e.blocks.length?e.blocks.flatMap((t)=>t.links):e.links}function ug(e){if(!e.body.includes("@nav"))return;let t=new Map;for(let n of pg(e)){if(n.directive?.name!=="nav")continue;if(n.kind!=="definition")j(e,"@nav must use a reference definition.");let[r,...o]=n.directive.qualifiers;if(!r||o.length)j(e,"@nav requires exactly one name qualifier.");if(t.has(r))j(e,`multiple @nav.${r} definitions.`);Gc(e,n.href),t.set(r,n)}return t}function Kc(e,t,n){return n.graph.linksFrom(e.path).find((r)=>r.href===t)}function Zc(e,t,n){let r=Kc(e,t,n);return r?.to?n.sources.get(r.to):void 0}function Jc(e,t,n,r,o){let i=Kc(e,t.href,r);return r.log.warn("link.unresolved",{source:e.path,href:t.href,label:t.label,reason:o}),{type:"unresolved",label:t.label,href:t.href,...i?.to?{targetPath:i.to}:{},children:n}}function ep(e,t,n){return t.map((r)=>{let o=ep(e,r.children,n),i=Zc(e,r.href,n);if(!i)return Jc(e,r,o,n,"Source not found.");if(!n.sources.isPage(i))return Jc(e,r,o,n,`Target is a ${i.type} Source, not a page.`);let s=L(i)?Yt(i):void 0;return{type:"resolved",label:r.label,href:r.href,targetId:i.id,targetPath:i.path,route:y(i),...s&&s!=="/"?{sectionDir:s}:{},children:o}})}function tp(e,t){for(let n of e){if(n.targetPath)t({type:"source",path:n.targetPath});tp(n.children,t)}}function lg(e,t,n){if(e.type==="unresolved")return;if(e.targetId===n.id)return"page";if(e.sectionDir&&n.path.startsWith(`${e.sectionDir}/`))return"section";if(t.some((r)=>r.active))return"ancestor"}function np(e,t){return e.flatMap((n)=>{let r=np(n.children,t);if(n.type==="resolved"&&!t.view.readSource(n.targetId))return r;let o=lg(n,r,t.source);return[{...n,children:r,...o?{active:o}:{}}]})}class zo{navigations=new Map;relations=new Map;compiledNodes=new Map;visibleViews=new WeakMap;index(e){let t=ug(e);if(t)this.relations.set(e.path,t);else this.relations.delete(e.path);if(e.type===Xc)this.navigations.set(e.path,cg(e))}unindex(e){this.relations.delete(e),this.navigations.delete(e),this.compiledNodes.clear()}compile(e,t,n,r){let o=this.relations.get(t.origin.path)?.get(e);if(!o)j(t.origin,`missing @nav.${e} definition.`);let i=Zc(t.origin,o.href,r);if(!i)j(t.origin,`navigation Source not found: ${o.href}.`);if(i.type!==Xc)j(t.origin,`${o.href} is a ${i.type} Source, not navigation.`);if(!r.access.canEmbed(n.source.id,i.id))j(n.source,`cannot embed navigation ${i.path}.`);let s=this.navigations.get(i.path);if(!s)j(i,"Source was not indexed.");let a=this.compiledNodes.get(i.path);if(!a)a=ep(i,s,r),this.compiledNodes.set(i.path,a);n.depend({type:"source",path:i.path}),tp(a,n.depend);let c=i.data.label;return{name:e,label:typeof c==="string"&&c.trim()?c.trim():e,nodes:a}}visible(e,t){let n=this.visibleViews.get(t);if(!n)n=new Map,this.visibleViews.set(t,n);let r=n.get(e.nodes);if(!r)r=np(e.nodes,t),n.set(e.nodes,r);return r}}function op(e){let t=e.active?b` data-pmx-active="${e.active}"`:null,n=e.active==="page"?b` aria-current="page"`:null,r=e.children.length?b`<ul class="pmx-nav-list">
1017
- ${e.children.map(op)}
1018
- </ul>`:null,o=e.type==="resolved"?b`<a class="pmx-nav-link" href="${e.route}"${t}${n}>${e.label}</a>`:b`<span class="pmx-nav-link" data-pmx-unresolved="true" aria-disabled="true" title="Unresolved: ${e.href}">${e.label}</span>`;return b`<li class="pmx-nav-item" ${t}>${o}${r}</li>`}function ip(e){for(let t of e){if(!t.active)continue;let n=ip(t.children);return n.length?[t,...n]:[t]}return[]}function dg(e){let t=e.active?b` data-pmx-active="${e.active}"`:null,n=e.active==="page"?b`<span class="pmx-breadcrumbs-current" aria-current="page">${e.label}</span>`:e.type==="resolved"?b`<a class="pmx-breadcrumbs-link" href="${e.route}">${e.label}</a>`:b`<span class="pmx-breadcrumbs-link" data-pmx-unresolved="true" aria-disabled="true" title="Unresolved: ${e.href}">${e.label}</span>`;return b`<li class="pmx-breadcrumbs-item" ${t}>${n}</li>`}function mg(e,t,n){let r=n.visible(e,t);return b`<nav
1019
- class="pmx-nav"
1020
- data-pmx-nav="${e.name}"
1021
- aria-label="${e.label}"
1022
- >
1023
- <ul class="pmx-nav-list">
1024
- ${r.map(op)}
1025
- </ul>
1026
- </nav>`}function fg(e,t,n){let r=ip(n.visible(e,t));if(!r.length)return"";return b`<nav
1027
- class="pmx-breadcrumbs"
1028
- data-pmx-breadcrumbs="${e.name}"
1029
- aria-label="Breadcrumb"
1030
- >
1031
- <ol class="pmx-breadcrumbs-list">
1032
- ${r.map(dg)}
1033
- </ol>
1034
- </nav>`}var rp={"~standard":{version:1,vendor:"pathmx",validate(e){if(!e||typeof e!=="object"||Array.isArray(e))return{issues:[{message:"expected one valid name attribute"}]};let t=e,n=Object.keys(t);if(n.length===1&&n[0]==="name"&&typeof t.name==="string"&&/^[A-Za-z][\w-]*$/.test(t.name))return{value:e};return{issues:[{message:"expected one valid name attribute"}]}}}};function sp(){let e=new zo,t=(o,i,s)=>e.compile(o.props.name,o,i,s),n=D({tag:"navigation:nav",props:rp,compile:t,render(o,i,s){return mg(i,s,e)}}),r=D({tag:"navigation:breadcrumbs",props:rp,compile:t,render(o,i,s){return fg(i,s,e)}});return{id:"navigation",schema:{sources:{navigation:{label:"Navigation",description:"An authored navigation tree.",icon:"network",color:"cyan"}}},components:[n,r],index(o){e.index(o)},unindex(o){e.unindex(o)}}}function Mt(e,t){return{issues:[{message:e,...t?{path:[t]}:{}}]}}function cp(e){if(e==null||typeof e!=="object"||Array.isArray(e))return Mt("Expected an object");let t=e,n=Object.keys(t).find((o)=>o!=="state"&&o!=="completion");if(n)return Mt("Unknown Input Response field",n);let r;if(t.state!==void 0){if(typeof t.state!=="string"||!t.state.trim())return Mt("Expected a canonical Source id","state");r=t.state.trim();try{Y(r)}catch{return Mt("Expected a canonical Source id","state")}}if(t.completion!==void 0&&t.completion!==!0)return Mt("Expected true","completion");return{value:Object.freeze({...r?{state:r}:{},...t.completion===!0?{completion:!0}:{}})}}var ap=Object.freeze({type:"object",additionalProperties:!1,properties:{state:{type:"string",pattern:"^/"},completion:{const:!0}}}),pp={"~standard":{version:1,vendor:"pathmx",validate:cp,jsonSchema:{input:()=>ap,output:()=>ap}}};function Me(e){if(!Object.hasOwn(e.data,"input-response"))return;let t=cp(e.data["input-response"]);return"value"in t?t.value:void 0}function qo(e,t=[]){let n=new Set([...e,...t]);return{"~standard":{version:1,vendor:"pathmx",validate(r){let o=r,i=[];for(let s of e)if(typeof o?.[s]!=="string"||!o[s])i.push({message:"Required",path:[s]});for(let s of Object.keys(o??{}))if(!n.has(s))i.push({message:"Unknown prop",path:[s]});return i.length?{issues:i}:{value:o}}}}}var Vo=qo(["name","value","label"],["required","min"]),Ho=qo(["name","label"],["placeholder","required"]),Fo=qo(["label"]);function $n(e,t){let n=e.props.min==null||e.props.min===""?0:Number(e.props.min);if(!Number.isInteger(n)||n<0)throw Error(`Invalid <x-input-${t}> min in ${e.origin.path}.`);return{type:t,name:e.props.name,value:e.props.value,label:e.props.label,required:"required"in e.props,min:n}}function Tn(e,t){return{type:t,name:e.props.name,label:e.props.label,...e.props.placeholder?{placeholder:e.props.placeholder}:{},required:"required"in e.props}}function hg(e,t,n,r){let o=r["~standard"].validate(n);if(o instanceof Promise)throw Error(`Input View Component schema for <${t}> must be synchronous.`);return o.issues?.length?`Invalid <${t}> props in ${e.path}: ${q(o.issues)}`:void 0}function gg(e){if(e==="x-input-text"||e==="x-input-textarea")return Ho;if(e==="x-input-radio"||e==="x-input-checkbox")return Vo;if(e==="x-input-submit")return Fo}function yg(e,t){if(t==="x-input-text")return Tn(e,"text");if(t==="x-input-textarea")return Tn(e,"textarea");if(t==="x-input-radio")return $n(e,"radio");if(t==="x-input-checkbox")return $n(e,"checkbox")}function wg(e){let t=[],n=[],r=[],o=Me(e);if(!o&&!e.body.includes("<x-input-")&&!e.body.includes("input-response:"))return Object.freeze({controls:Object.freeze(t),completion:void 0,issues:Object.freeze(n)});if(o?.completion)n.push(`Input completion must be authored on a Block in ${e.path}.`);for(let i of e.blocks){let s=Me(i);if(s?.state)n.push(`Input state binding must be authored on the Source, not ${i.path}.`);let a=0,c=i.body.includes("<x-input-")?Bs(i.body):[];for(let l of c){let d=gg(l.tag);if(!d)continue;a++;let m=hg(e,l.tag,l.props,d);if(m){n.push(m);continue}let f={props:l.props,origin:e};try{let h=yg(f,l.tag);if(h)t.push(h)}catch(h){n.push(h instanceof Error?h.message:String(h))}}if(!s?.completion)continue;if(!(typeof i.data.id==="string"&&i.data.id.trim()===i.id)){n.push(`Input completion Block ${i.path} must author a stable id.`);continue}let u=`input/${i.id}`;if(u.length>256||!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(i.id)){n.push(`Invalid Input completion Block id ${i.id} in ${e.path}.`);continue}if(!a){n.push(`Input completion Block ${i.path} has no Input controls.`);continue}r.push(Object.freeze({key:u}))}if(r.length>1)n.push(`Input Source ${e.path} may declare only one completion Block.`);if(r.length&&!t.length)n.push(`Input Source ${e.path} has no Input fields to complete.`);return Object.freeze({controls:Object.freeze(t),completion:r.length===1?r[0]:void 0,issues:Object.freeze(n)})}function Uo(e,t=[]){let n=[wg(e),...t.flatMap((i)=>{let s=i.inspect(e);return s?[s]:[]})],r=n.flatMap(({completion:i})=>i?[i]:[]),o=n.flatMap(({issues:i})=>i??[]);if(r.length>1)o.push(`Input Source ${e.path} has multiple completion units.`);return Object.freeze({controls:Object.freeze(n.flatMap(({controls:i})=>[...i])),completion:r.length===1?r[0]:void 0,issues:Object.freeze(o)})}function up(e){return e.type==="radio"||e.type==="checkbox"}function lp(e){return e.type==="radio"||e.type==="checkbox"}function xg(e,t,n){if(n==null||n===""){if(t)throw Error(`Input field ${e} is required.`);return}if(typeof n!=="string")throw Error(`Invalid value for Input field ${e}.`);return n}class _o{sources=new Map;sourceIdByPath=new Map;sourcePathById=new Map;completionBySourceId=new Map;has(e){return Boolean(this.sources.get(e)?.size)}unindex(e){this.sources.delete(e);let t=this.sourceIdByPath.get(e);if(!t)return;this.sourceIdByPath.delete(e),this.sourcePathById.delete(t),this.completionBySourceId.delete(t)}replace(e,t,n){this.unindex(e.path);let r=new Map;for(let o of t)this.add(r,e.path,o);if(!r.size&&!n)return;if(r.size)this.sources.set(e.path,r);if(this.sourceIdByPath.set(e.path,e.id),this.sourcePathById.set(e.id,e.path),n)this.completionBySourceId.set(e.id,n)}add(e,t,n){let r=e.get(n.name);if(!r)r=up(n)?{type:n.type,options:new Set,required:n.required,min:n.min}:{type:n.type,required:n.required},e.set(n.name,r);if(r.type!==n.type)throw Error(`Input field ${n.name} in ${t} mixes ${r.type} and ${n.type}.`);if(r.required||=n.required,up(n)&&lp(r))r.options.add(n.value),r.min=Math.max(r.min,n.min)}completion(e){return this.completionBySourceId.get(e)}validateSource(e,t){let n=this.sourcePathById.get(e);if(!n)throw Error(`No indexed Input Source ${e}.`);return this.validate(n,t)}validate(e,t){let n=this.sources.get(e);if(!n?.size)throw Error(`No indexed Input fields in ${e}.`);let r=Object.keys(t).filter((i)=>i!=="_target"&&!n.has(i));if(r.length)throw Error(`Unknown Input field: ${r.join(", ")}.`);let o={};for(let[i,s]of n){let a=t[i];if(!lp(s)){let u=xg(i,s.required,a);if(u!=null)o[i]=u;continue}if(s.type==="radio"){if(a==null||a===""){if(s.required)throw Error(`Input field ${i} is required.`);continue}if(Array.isArray(a)||!s.options.has(a))throw Error(`Invalid value for Input field ${i}.`);o[i]=a;continue}let c=a==null?[]:Array.isArray(a)?a:[a],p=[...new Set(c)];if(p.some((u)=>!s.options.has(u)))throw Error(`Invalid value for Input field ${i}.`);if(p.length<Math.max(s.min,s.required?1:0))throw Error(`Input field ${i} requires more selections.`);o[i]=p}return o}}function De(e,t){return new R({source:e.path,plugin:"input",message:`Invalid Input state in ${e.path}: ${t}`})}function bg(e){return e!=null&&typeof e==="object"&&!Array.isArray(e)?e:void 0}function Sg(e,t){if(e.type!=="state")return;let n=fe(e.body,t);if(n.data.plugin!=="input")return;let r=Ut(n.body).find((i)=>i.lang==="yaml"&&i.info.split(/\s+/).includes("@state"));if(!r)return;let o=t.parse(r.body);if(!o||typeof o!=="object"||Array.isArray(o))throw De(e,"@state must contain a YAML map.");return o}function vg(e){if(e.status==null)return{submitted:!1};let t=bg(e.status);if(!t)return{submitted:!1,issue:"status must be a map."};if(t.type!=="submitted")return{submitted:!1};if(typeof t.submitted_at!=="string"||!t.submitted_at.trim())return{submitted:!1,issue:"submitted status requires submitted_at."};let n=Date.parse(t.submitted_at);if(!Number.isFinite(n))return{submitted:!1,issue:"submitted_at must be an ISO 8601 timestamp."};return{submitted:!0,submittedAt:new Date(n).toISOString()}}function kg(e,t){let n=t.values;if(n==null)return{};if(typeof n!=="object"||Array.isArray(n))throw De(e,"values must be a map.");let r={};for(let[o,i]of Object.entries(n)){if(typeof i==="string"){r[o]=i;continue}if(Array.isArray(i)&&i.every((s)=>typeof s==="string")){r[o]=[...new Set(i)];continue}throw De(e,`${o} must be a string or string list.`)}return r}function dp(e,t){let n=Sg(e,t.yaml);if(!n)return;let r=typeof e.data.for==="string"?e.data.for.trim():"";if(!r)throw De(e,"frontmatter for is required.");try{Y(r)}catch{throw De(e,"frontmatter for must be a canonical Source id.")}let o=t.actors.homeActorId(e.id);if(!o)throw De(e,"state must be stored in an Actor Home.");let i=vg(n);return{actorId:o,originId:r,source:e,data:n,values:kg(e,n),submitted:i.submitted,...i.submittedAt?{submittedAt:i.submittedAt}:{},...i.issue?{statusIssue:i.issue}:{}}}function Pg(e,t,n,r){let o={...n?.data,values:t,status:{type:"submitted",submitted_at:new Date().toISOString()}},i={...n?.source.data,type:"state",for:e.id};return`${he(i,r)}
1035
- <!--
1036
- plugin: input
1037
- -->
1038
-
1039
- \`\`\`yaml @state
1040
- ${r.stringify(o).trimEnd()}
1041
- \`\`\`
1042
- `}class Qo{statesByPath=new Map;statesById=new Map;statesByActorOrigin=new Map;boundStateByOriginId=new Map;boundOriginByPath=new Map;key(e,t){return`${e}\x00${t}`}index(e,t){let n=Me(e)?.state,r=dp(e,t);if(r){let o=this.key(r.actorId,r.originId),i=this.statesByActorOrigin.get(o);if(i&&i.source.path!==e.path)throw De(e,`duplicate State for ${r.actorId} and ${r.originId}: ${i.source.path} and ${e.path}.`);this.statesByPath.set(e.path,r),this.statesById.set(e.id,r),this.statesByActorOrigin.set(o,r)}if(n)this.boundStateByOriginId.set(e.id,n),this.boundOriginByPath.set(e.path,e.id)}unindex(e){let t=this.boundOriginByPath.get(e);if(t)this.boundStateByOriginId.delete(t);this.boundOriginByPath.delete(e);let n=this.statesByPath.get(e);if(!n)return;this.statesByPath.delete(e),this.statesById.delete(n.source.id),this.statesByActorOrigin.delete(this.key(n.actorId,n.originId))}get(e,t){return this.statesByActorOrigin.get(this.key(e,t))}records(){return Object.freeze([...this.statesByPath.values()])}forActor(e,t){let n=this.boundStateByOriginId.get(t);if(!n)return this.get(e,t);let r=this.statesById.get(n);return r?.actorId===e&&r.originId===t?r:void 0}resolve(e,t){let n=this.boundStateByOriginId.get(e.id);if(!n)return{type:"actor-relative",state:t?this.get(t,e.id):void 0};let r=this.statesById.get(n);if(!r)throw Error(`Invalid input-response config in ${e.path}: bound State does not resolve: ${n}.`);if(r.originId!==e.id)throw Error(`Invalid input-response config in ${e.path}: ${n} points back to ${r.originId}, not ${e.id}.`);return{type:"bound",state:r}}isBound(e,t){return this.boundStateByOriginId.get(e.id)===t}transition(e,t){return e?dp(e,t):void 0}async write(e,t,n,r,o){let i=this.resolve(n,t.id).state,s=Pg(n,r,i,o);if(i){await e.update(i.source.id,s);return}await e.create(`${t.home}/input${n.id}.state`,s)}}var mp=Object.freeze({});function Rg(e,t){return Array.isArray(e)?e.includes(t):e===t}function tt(e,t){return t?b` ${e}`:""}function Cg(e,t,n){let r=tt("checked",Rg(t,e.value)),o=tt("required",e.required),i=tt("disabled",!n);return b`<label class="input-option"
1043
- ><input
1044
- type="${e.type}"
1045
- name="${e.name}"
1046
- value="${e.value}"
1047
- ${r}${o}${i}
1048
- /><span>${e.label}</span></label
1049
- >`}function Ag(e,t,n){let r=typeof t==="string"?t:"",o=tt("required",e.required),i=tt("disabled",!n),s=e.placeholder?b` placeholder="${e.placeholder}"`:"";return e.type==="textarea"?b`<label class="input-field input-textarea"
1050
- ><span>${e.label}</span
1051
- ><textarea name="${e.name}" ${s}${o}${i}>
1052
- ${r}</textarea>
1053
- </label>`:b`<label class="input-field input-text"
1054
- ><span>${e.label}</span
1055
- ><input
1056
- type="text"
1057
- name="${e.name}"
1058
- value="${r}"
1059
- ${s}${o}${i}
1060
- /></label>`}function Wo(e,t){return new R({source:e.path,plugin:"input",message:t})}function Ig(e,t,n){let r=new WeakMap,o=(u,l)=>{try{return t.resolve(u,l)}catch(d){throw Wo(u,d instanceof Error?d.message:String(d))}},i=(u,l,d)=>{let m=r.get(l);if(!m)m=new Map,r.set(l,m);let f=m.get(u.id);if(f)return f;let h=l.session.type==="authenticated"?l.session.actor.id:void 0,w=l.view.principal,T=o(u,h),oe=T.state,Cu=oe?d.access.can(w,oe.source,"read"):!1,Au=oe?d.access.can(w,oe.source,"write"):T.type==="actor-relative"&&h!=null,mi={values:oe&&Cu?e.validate(u.path,oe.values):void 0,editable:Au&&d.access.can(w,u,"execute")};return m.set(u.id,mi),mi},s=(u)=>D({tag:`input:${u}`,props:Vo,compile(l){return o(l.origin),$n(l,u)},render(l,d,m,f){let h=i(l.origin,m,f);return Cg(d,h.values?.[l.props.name],h.editable)}}),a=(u)=>D({tag:`input:${u}`,props:Ho,compile(l){return o(l.origin),Tn(l,u)},render(l,d,m,f){let h=i(l.origin,m,f);return Ag(d,h.values?.[l.props.name],h.editable)}}),c=D({tag:"input:submit",props:Fo,render(u,l,d,m){let f=tt("disabled",!i(u.origin,d,m).editable);return b`<button
1061
- type="submit"
1062
- formaction="/actions/input:submit"
1063
- formmethod="post"
1064
- ${f}
1065
- >
1066
- ${u.props.label}
1067
- </button>`}}),p=Pr({title:"Save response",description:"Save the current actor's response to this Source.",affordance:({target:u,principal:l,can:d})=>e.has(u.path)&&l.type==="actor"&&d("execute"),authorize:({target:u})=>Boolean(u&&e.has(u.path))||"Input Action requires an originating Source.",async execute(u,{actor:l,target:d,tx:m,yaml:f}){if(!d)throw Error("Input Action requires an originating Source.");let h=e.validate(d.path,u);await t.write(m,l,d,h,f)}});return{id:"input",name:"InputPlugin",schema:{props:{"input-response":pp},actions:{submit:p}},components:[a("text"),a("textarea"),s("radio"),s("checkbox"),c],variables:[Br({namespace:"input",render(u,l,d){if(u.path.length!==1)return;let m=i(u.origin,l,d).values?.[u.path[0]];return Array.isArray(m)?m.join(", "):m}})],index(u,l){let d=Uo(u,n);if(d.issues[0])throw Wo(u,d.issues[0]);try{e.replace(u,d.controls,d.completion)}catch(m){throw Wo(u,m instanceof Error?m.message:String(m))}t.index(u,l)},unindex(u){t.unindex(u),e.unindex(u)},lint(u,l){for(let d of l.sources.all()){for(let m of Uo(d,n).issues)u(d,m);if(!Me(d)?.state)continue;try{t.resolve(d)}catch(m){u(d,m instanceof Error?m.message:String(m))}}for(let d of t.records()){if(d.statusIssue)u(d.source,`Invalid Input state in ${d.source.path}: ${d.statusIssue}`);let m=l.sources.get(d.originId);if(!m){u(d.source,`Input State ${d.source.path} targets missing Source ${d.originId}.`);continue}try{e.validate(m.path,d.values)}catch(f){u(d.source,f instanceof Error?f.message:String(f))}}},invalidate(u,l){let d=[];for(let m of[u.before,u.after]){let f=t.transition(m,l);if(!f)continue;let h=l.sources.get(f.originId);if(!h)continue;d.push(t.isBound(h,f.source.id)?{type:"route",route:y(h)}:{type:"route",route:y(h),actors:[f.actorId]})}return d.length?{targets:d}:void 0}}}function fp(e={}){let t=new _o,n=new Qo,r=Object.freeze([...e.authoring??[]]);return Object.freeze({plugin:()=>Ig(t,n,r),completion:Object.freeze({declarations(o){let i=t.completion(o.id);return i?Object.freeze([Object.freeze({key:i.key})]):[]},read(o,i){let s=t.completion(i.source);if(!s||s.key!==i.key)return;let a=n.forActor(o,i.source);if(!a?.submittedAt)return mp;try{return t.validateSource(i.source,a.values),Object.freeze({fact:Object.freeze({outcome:"complete",occurredAt:a.submittedAt})})}catch{return mp}}})})}function hp(){return fp().plugin()}var $g="public, max-age=300",Tg=Object.freeze({});function Eg(e,t){return t.graph.linksTo(e.path).some((n)=>{if(n.from===e.path)return!1;let r=t.source(n.from);return r!=null&&t.isPublic(r)})}function gp(e){return e.sources().filter((t)=>{if(!Re(t)||!e.isPublic(t))return!1;if(e.resolve(y(t))!==t)return!1;return y(t)==="/"||Eg(t,e)}).sort((t,n)=>{let r=y(t),o=y(n);return r<o?-1:r>o?1:0})}function yp(e){let t=`/${e.path}`;if(!e.url.pathname.endsWith(t))return"/";return e.url.pathname.slice(0,-t.length)||"/"}function On(e,t){let n=yp(e);if(n==="/")return t;return t==="/"?n:`${n}${t}`}function Mn(e,t){return new URL(On(e,t),e.url.origin).href}function En(e){return e.replaceAll("\\","\\\\").replaceAll("[","\\[").replaceAll("]","\\]").replace(/\s+/g," ").trim()}function Og(e){let t=gp(e),n=t.find((s)=>y(s)==="/")??t[0],r=n?te(n):void 0,i=[`# ${En(r?.title||"PathMX")}`,"",...r?.description?[`> ${En(r.description)}`,""]:[],"## When to use this site","","Use this PathMX site to read, navigate, or cite its public Sources. The listed links return the authored Markdown representation directly. Use the sitemap for the canonical HTML URL index.","","## Public pages",""];if(!t.length)i.push("No public pages are currently available.");for(let s of t){let a=te(s),c=a.description?` \u2014 ${En(a.description)}`:"";i.push(`- [${En(a.title)}](${Mn(e,s.path)})${c}`)}return i.push("",`- [XML sitemap](${Mn(e,"/sitemap.xml")})`,""),i.join(`
1068
- `)}function Mg(e){let t=yp(e);return["User-agent: *",`Allow: ${t==="/"?"/":`${t}/`}`,`Disallow: ${On(e,"/.pmx/")}`,`Disallow: ${On(e,"/actions/")}`,`Disallow: ${On(e,"/api/runtime/")}`,"",`Host: ${e.url.origin}`,`Sitemap: ${Mn(e,"/sitemap.xml")}`,""].join(`
1069
- `)}function Dg(e){return e.replaceAll("&","&amp;").replaceAll('"',"&quot;").replaceAll("'","&apos;").replaceAll("<","&lt;").replaceAll(">","&gt;")}function jg(e){return['<?xml version="1.0" encoding="UTF-8"?>','<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">',gp(e).map((n)=>` <url><loc>${Dg(Mn(e,y(n)))}</loc></url>`).join(`
1070
- `),"</urlset>",""].join(`
1071
- `)}function Xo(e,t){return new Response(e,{headers:{"Content-Type":t,"Cache-Control":$g}})}function wp(){return{id:_e,name:"AgentBrowsingPlugin",routes:[ce.get("llms.txt",(e)=>Xo(Og(e),"text/plain; charset=utf-8")),ce.get("robots.txt",(e)=>Xo(Mg(e),"text/plain; charset=utf-8")),ce.get("sitemap.xml",(e)=>Xo(jg(e),"application/xml; charset=utf-8"))],publish(e){e.route("/llms.txt"),e.route("/robots.txt"),e.route("/sitemap.xml")},streamSelectors({source:e},t){if(!t.sources.isPage(e))return Tg;let n=g(e.path);return{head:{element(r){r.prepend(`<link rel="alternate" type="text/markdown" href="${n}">`,{html:!0})}}}}}}var xp="query:results",Lg=xe(xp);function Go(e,t){if(e==null||typeof e!=="object"||Array.isArray(e))throw Error(`${t} must be an object.`);return e}function Bg(e){if(e===void 0)return Object.freeze({});let t=Go(e,"Query component props");return Object.freeze(Object.fromEntries(Object.entries(t).map(([n,r])=>{if(r==null||typeof r!=="string"&&typeof r!=="number"&&typeof r!=="boolean")throw Error(`Query component prop ${n} must be a scalar.`);return[n,String(r)]})))}function Jo(e,t,n){for(let r of Object.keys(e))if(!t.includes(r))throw Error(`Unknown ${n} field: ${r}`)}function Ng(e){if(e===void 0)return Object.freeze({type:"list"});if(typeof e==="string"){if(e==="list")return Object.freeze({type:"list"});throw Error(`Unsupported query view: ${e}`)}let t=Go(e,"Query view"),n=t.type??"list";if(n==="list")return Jo(t,["type"],"query list view"),Object.freeze({type:n});if(n==="table"){Jo(t,["type","columns"],"query table view");let r=t.columns??[];if(!Array.isArray(r)||r.some((o)=>typeof o!=="string"||!o.trim()))throw Error("Query table columns must be a list of field names.");return Object.freeze({type:n,columns:Object.freeze(r.map((o)=>o.trim()))})}if(n==="components"){if(Jo(t,["type","component","props"],"query components view"),typeof t.component!=="string"||!t.component.trim())throw Error("Query components view requires component.");return Object.freeze({type:n,component:t.component.trim(),props:Bg(t.props)})}throw Error(`Unsupported query view: ${String(n)}`)}function zg(e,t){let n=S.dirname(t.source.path);if(e===void 0||e===".")return n;if(typeof e!=="string")throw Error("Query from must be a string.");if(e.startsWith("~/")||e.startsWith("/"))return e;return S.resolve(n,e)}function qg(e,t,n){let r=Go(n.yaml.parse(e)??{},"Query fence"),o=r.query??"sources";if(typeof o!=="string"||!o.trim())throw Error("Query fence query must be a string.");let i=Ng(r.view),s={...r,from:zg(r.from,t)};return delete s.query,delete s.view,{query:o.trim(),request:s,view:i}}async function Vg(e,t,n){let r=await n.query.prepare(e.query,e.request);t.depend(Se(r));let o={query:e.query,request:Object.freeze({...e.request})};if(e.view.type==="table"){let i=ro(n.schema,r),s=new Map(i.map((p)=>[p.path,p])),c=(e.view.columns.length?e.view.columns:i.slice(0,8).map(({path:p})=>p)).map((p)=>{let u=s.get(p);if(!u)throw Error(`Unknown query table column: ${p}`);return u});return Object.freeze({...o,view:Object.freeze({type:"table",columns:Object.freeze(c)})})}if(e.view.type==="components"){let i=await n.components.prepareData(e.view.component,e.view.props,t.source,t);return Object.freeze({...o,view:Object.freeze({...e.view,prepared:i})})}return Object.freeze({...o,view:e.view})}async function Hg(e,t,n){if(!/query/i.test(e))return e;let r=e.split(/\r?\n/),o=[];for(let i=0;i<r.length;i++){let s=r[i]??"",a=x(s);if(!a){o.push(s);continue}let c=i+1;while(c<r.length&&!v(r[c],a.marker))c++;if(c===r.length){o.push(...r.slice(i));break}if(a.info.split(/\s+/,1)[0]?.toLowerCase()!=="query"){o.push(...r.slice(i,c+1)),i=c;continue}let u=qg(r.slice(i+1,c).join(`
1072
- `),t,n),l=encodeURIComponent(JSON.stringify(u));o.push(`${a.indent}<${Lg} config="${g(l)}" />`),i=c}return o.join(`
1073
- `)}function Fg(e){for(let t of["meta.title","title","label","name","id"]){let n=H(e,t);if(typeof n==="string"||typeof n==="number")return String(n)}return JSON.stringify(e)}function Ug(e){return`<ul class="pmx-query-list">${e.map((t)=>{let n=g(Fg(t)),r=H(t,"href");return`<li>${typeof r==="string"?`<a href="${g(r)}">${n}</a>`:n}</li>`}).join("")}</ul>`}function _g(e,t){let n=t.map((o)=>`<th>${g(o.label??o.path)}</th>`).join(""),r=e.map((o)=>`<tr>${t.map(({path:i})=>{let s=H(o,i),a=s==null?"":typeof s==="object"?JSON.stringify(s):String(s);return`<td>${g(a)}</td>`}).join("")}</tr>`).join("");return`<table class="pmx-query-table"><thead><tr>${n}</tr></thead><tbody>${r}</tbody></table>`}async function Qg(e,t){if(e.query==="sources")return t.view.query.sources(e.request);if(e.query==="blocks")return t.view.query.blocks(e.request);return t.view.query.run(e.query,e.request)}function bp(){return{id:"query",components:[D({tag:xp,async compile(t,n,r){let o=t.props.config;if(!o)throw Error(`Missing query config in ${t.origin.path}.`);let i=JSON.parse(decodeURIComponent(o));return Vg(i,n,r)},async render(t,n,r,o){let i=await Qg(n,r),s=n.view;if(s.type==="list")return Ug(i);if(s.type==="table")return _g(i,s.columns);return`<div class="pmx-query-components">${(await Promise.all(i.map((c)=>o.components.renderData(s.prepared,c,r)))).join("")}</div>`}})],precompile(t,n,r){return Hg(t,n,r)}}}var Wg=new URL("./client.ts",import.meta.url),Xg=new Set(["new-tab","parent","frame"]);function Sp(e={}){let t=e.externalLinks??"new-tab";if(!Xg.has(t))throw Error(`Invalid embedded external-link policy: ${t}`);return{id:"embedding",name:"EmbeddingPlugin",async documentAssets(n){await n.addBrowserBundle(Wg,"embedding")},streamSelectors(){return{html:{element(n){n.setAttribute("data-pmx-embedding-external-links",t)}}}}}}var vp=`.pmx-document > [data-pmx-block]:has(> img[data-pmx-image="background"]),
1074
- .pmx-document
1075
- > [data-pmx-block]:has(> p > img[data-pmx-image="background"]:only-child) {
1076
- position: relative;
1077
- isolation: isolate;
1078
- }
1079
-
1080
- .pmx-document
1081
- > [data-pmx-block]
1082
- > :is(
1083
- img[data-pmx-image="background"],
1084
- p:has(> img[data-pmx-image="background"]:only-child)
1085
- ) {
1086
- position: absolute;
1087
- z-index: -1;
1088
- inset: 0;
1089
- max-inline-size: none;
1090
- margin: 0;
1091
- overflow: hidden;
1092
- }
1093
-
1094
- .pmx-document
1095
- > [data-pmx-block]
1096
- > :is(
1097
- img[data-pmx-image="background"],
1098
- p:has(> img[data-pmx-image="background"]:only-child)
1099
- )
1100
- > img,
1101
- .pmx-document > [data-pmx-block] > img[data-pmx-image="background"] {
1102
- display: block;
1103
- inline-size: 100%;
1104
- block-size: 100%;
1105
- max-block-size: none;
1106
- border-radius: 0;
1107
- }
1108
-
1109
- img[data-pmx-image-fit="contain"] {
1110
- object-fit: contain;
1111
- }
1112
-
1113
- img[data-pmx-image-fit="cover"] {
1114
- object-fit: cover;
1115
- }
1116
- `;var Gg=Object.freeze({fit:{role:"content",fit:"contain"},fill:{role:"content",fit:"cover"},background:{role:"background",fit:"cover"},"background.fit":{role:"background",fit:"contain"}});function Yg(e){let t=Kn(e);if(t.directive?.name.toLowerCase()!=="image")return;let n=t.directive.qualifiers.map((o)=>o.toLowerCase()).join("."),r=Gg[n];if(!r)return;return{...r,alt:t.label??""}}function Kg(e,t){if(!e.includes("<img"))return e;return t.html.rewrite(e,[["img",{element(n){if(n.getAttribute("data-pmx-image"))return;let r=Yg(n.getAttribute("alt")??"");if(!r)return;n.setAttribute("alt",r.alt),n.setAttribute("data-pmx-image",r.role),n.setAttribute("data-pmx-image-fit",r.fit)}}]])}function kp(){return{id:"image",postcompile(e,t,n){return Kg(e,n)},page(e,t){if(!e.includes("data-pmx-image"))return e;return t.addAsset({type:"stylesheet",name:"image.css",text:vp}),e}}}var Pp=`.pmx-document [data-pmx-block-layout="center"] {
1117
- text-align: center;
1118
- }
1119
-
1120
- .pmx-document
1121
- :is(
1122
- [data-pmx-block-layout="media-start"],
1123
- [data-pmx-block-layout="media-end"]
1124
- ) {
1125
- display: grid;
1126
- grid-template-columns: repeat(2, minmax(0, 1fr));
1127
- gap: clamp(var(--pmx-prose-flow), 4vw, calc(var(--pmx-prose-flow) * 2));
1128
- align-items: center;
1129
- }
1130
-
1131
- .pmx-document
1132
- [data-pmx-block-layout="media-start"]
1133
- > :is(
1134
- figure,
1135
- picture,
1136
- img:not([data-pmx-image="background"]),
1137
- video,
1138
- iframe,
1139
- p:has(> img:not([data-pmx-image="background"]):only-child),
1140
- p:has(> picture:only-child),
1141
- p:has(> video:only-child),
1142
- p:has(> iframe:only-child)
1143
- ) {
1144
- grid-column: 1;
1145
- grid-row: 1 / span 100;
1146
- }
1147
-
1148
- .pmx-document
1149
- [data-pmx-block-layout="media-start"]
1150
- > :not(
1151
- figure,
1152
- picture,
1153
- img:not([data-pmx-image="background"]),
1154
- video,
1155
- iframe,
1156
- p:has(> img:not([data-pmx-image="background"]):only-child),
1157
- p:has(> picture:only-child),
1158
- p:has(> video:only-child),
1159
- p:has(> iframe:only-child)
1160
- ) {
1161
- grid-column: 2;
1162
- }
1163
-
1164
- .pmx-document
1165
- [data-pmx-block-layout="media-end"]
1166
- > :is(
1167
- figure,
1168
- picture,
1169
- img:not([data-pmx-image="background"]),
1170
- video,
1171
- iframe,
1172
- p:has(> img:not([data-pmx-image="background"]):only-child),
1173
- p:has(> picture:only-child),
1174
- p:has(> video:only-child),
1175
- p:has(> iframe:only-child)
1176
- ) {
1177
- grid-column: 2;
1178
- grid-row: 1 / span 100;
1179
- }
1180
-
1181
- .pmx-document
1182
- [data-pmx-block-layout="media-end"]
1183
- > :not(
1184
- figure,
1185
- picture,
1186
- img:not([data-pmx-image="background"]),
1187
- video,
1188
- iframe,
1189
- p:has(> img:not([data-pmx-image="background"]):only-child),
1190
- p:has(> picture:only-child),
1191
- p:has(> video:only-child),
1192
- p:has(> iframe:only-child)
1193
- ) {
1194
- grid-column: 1;
1195
- }
1196
-
1197
- @media (max-width: 48rem) {
1198
- .pmx-document
1199
- :is(
1200
- [data-pmx-block-layout="media-start"],
1201
- [data-pmx-block-layout="media-end"]
1202
- ) {
1203
- display: block;
1204
- }
1205
- }
1206
- `;var ey=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function ty(e,t){let n=typeof t==="string"?JSON.stringify(t):typeof t;return`Invalid Block layout on ${e}: expected a lowercase slug, received ${n}.`}function Rp(){let e=new Map,t=new Map;function n(r){for(let o of t.get(r)??[])e.delete(o);t.delete(r)}return{id:"block-layout",index(r,o){let i=[];for(let s of r.blocks){let a=s.data.layout;if(a===void 0)continue;if(typeof a==="string"&&ey.test(a)){i.push([s.path,a]);continue}o.diagnostics.invalid(r,ty(s.path,a))}if(n(r.path),!i.length)return;t.set(r.path,i.map(([s])=>s));for(let[s,a]of i)e.set(s,a)},unindex(r){n(r)},page(r,o,i){if(!e.size||!r.includes("data-pmx-block-path"))return r;let s=!1,a=i.html.rewrite(r,[["section[data-pmx-block-path]",{element(c){let p=c.getAttribute("data-pmx-block-path"),u=p?e.get(p):void 0;if(!u)return;s=!0,c.setAttribute("data-pmx-block-layout",u)}}]]);if(s)o.addAsset({type:"stylesheet",name:"block-layout.css",text:Pp});return a}}}var Cp=Object.freeze([La,bp,wp,Hc,Na,Ha,kp,Rp,_a,Qa,Za,ic,uc,Oc,Sc,hp,Ic,$c,Wc,sp,Sp,lc,vc,Fc]);class O extends Error{constructor(e){super(e);this.name="PatternError"}}var ny=/^[a-z0-9]+(?:-[a-z0-9]+)*(?::[a-z0-9]+(?:-[a-z0-9]+)*)?$/;function Ap(e){if(!ny.test(e))throw new O(`Invalid Pattern id: ${e}`);return e}async function ry(e,t){if(!e.input){if(t!==void 0)throw new O(`Pattern ${e.id} does not accept input.`);return}let n=await e.input["~standard"].validate(t);if(n.issues)throw new O(`Invalid input for Pattern ${e.id}: ${q(n.issues)}`);return n.value}function oy(e,t,n){if(n.root!=="paths"&&n.root!=="project")throw new O(`Invalid Pattern root: ${String(n.root)}`);if(typeof n.content!=="string")throw new O(`Pattern file content must be text: ${n.path}`);let r=n.path.replaceAll("\\","/");if(!r||r.startsWith("/")||/^[a-zA-Z]:\//.test(r)||r.split("/").includes(".."))throw new O(`Pattern path escapes its ${n.root} root: ${n.path}`);let o=e.path.normalize(r);if(!o||o===".")throw new O(`Invalid Pattern path: ${n.path}`);let i=t[n.root],s=e.path.join(i,o),a=e.path.relative(i,s);if(!a||a===".."||a.startsWith("../"))throw new O(`Pattern path escapes its ${n.root} root: ${n.path}`);return Object.freeze({...n,path:o,destination:s})}function Ip(e,t,n){if(e.type==="missing")return"create";if(e.content===t)return"unchanged";return n==="overwrite"?"replace":"conflict"}function $p(e="error"){if(e!=="error"&&e!=="preserve"&&e!=="overwrite")throw new O(`Invalid Pattern conflict policy: ${String(e)}`);return e}async function iy(e,t){let n=[];for(let r of[...t].reverse())try{let o=await Xe(e,r.destination);if(Ct(o,r.before))continue;if(o.type!=="present"||o.content!==r.content)throw new O(`Pattern destination changed during rollback: ${r.destination}`);if(r.before.type==="missing")await e.delete(r.destination);else await e.writeText(r.destination,r.before.content)}catch(o){n.push(o)}return n}function Tp(e,t){let n=Object.freeze({...t}),r=(a)=>oy(e,n,a),o=async(a,c,p)=>{let u=Ap(a.id),l=$p(p?.conflicts),m=(await a.generate(await ry(a,c))).map(r),f=new Set;for(let w of m){if(f.has(w.destination))throw new O(`Duplicate Pattern destination: ${w.destination}`);f.add(w.destination)}let h=await Promise.all(m.map(async(w)=>{let T=await Xe(e.storage,w.destination);return Object.freeze({...w,before:T,status:Ip(T,w.content,l)})}));return Object.freeze({pattern:u,conflicts:l,files:Object.freeze(h)})},i=async(a)=>{Ap(a.pattern),$p(a.conflicts);for(let d of a.files){let m=Ip(d.before,d.content,a.conflicts);if(d.status!==m)throw new O(`Invalid Pattern plan: ${d.destination}`)}let c=a.files.filter((d)=>d.status==="conflict");if(a.conflicts==="error"&&c.length)throw new O(`Pattern ${a.pattern} conflicts with existing files: ${c.map((d)=>d.destination).join(", ")}`);let u=a.files.filter((d)=>d.status==="create"||d.status==="replace").map((d)=>{let m=r({root:d.root,path:d.path,content:d.content});if(m.destination!==d.destination)throw new O(`Invalid Pattern plan: ${d.destination}`);return{...d,destination:m.destination}});await Promise.all(u.map(async(d)=>{let m;try{m=await Xe(e.storage,d.destination)}catch{throw new O(`Pattern destination changed before install: ${d.destination}`)}if(!Ct(m,d.before))throw new O(`Pattern destination changed before install: ${d.destination}`)}));let l=[];try{for(let d of u)l.push(d),await e.storage.writeText(d.destination,d.content)}catch(d){let m=await iy(e.storage,l);if(m.length)throw AggregateError([d,...m],`Pattern ${a.pattern} install and rollback failed.`);throw d}return a};return Object.freeze({plan:o,apply:i,install:async(a,c,p)=>{let u=await o(a,c,p);return i(u)}})}function nt(e,t,n){if(!e.headers.get("accept")?.includes("application/problem+json"))return new Response(n,{status:t,headers:{"Content-Type":"text/plain; charset=utf-8",Vary:"Accept"}});return new Response(JSON.stringify({type:"about:blank",title:t===404?"Not Found":t===403?"Forbidden":"Bad Request",status:t,detail:n}),{status:t,headers:{"Content-Type":"application/problem+json",Vary:"Accept"}})}function Ep(e,t){let[n,r]=t.split("/"),o=0,i=-1;for(let s of e.split(",")){let[a="",...c]=s.split(";"),[p,u]=a.trim().toLowerCase().split("/");if(!p||!u||p!=="*"&&p!==n||u!=="*"&&u!==r)continue;let l=(p==="*"?0:1)+(u==="*"?0:1),d=c.map((h)=>h.trim().match(/^q\s*=\s*(.+)$/i)?.[1]).find((h)=>h!==void 0),m=d===void 0?1:Number(d),f=Number.isFinite(m)&&m>=0&&m<=1?m:0;if(l>i||l===i&&f>o)i=l,o=f}return o}function Op(e){let t=e.headers.get("Accept");if(!t)return!1;let n=Ep(t,"text/markdown");return n>0&&n>Ep(t,"text/html")}function sy(e,t){let n=(e.get("Vary")??"").split(",").map((r)=>r.trim()).filter(Boolean);if(!n.some((r)=>r.toLowerCase()===t.toLowerCase()))n.push(t);e.set("Vary",n.join(", "))}function Yo(e,t){if(e.status>=400)return e;sy(e.headers,"Accept");let n=new URL(t,"http://pathmx.local").pathname;return e.headers.append("Link",`<${n}>; rel="alternate"; type="text/markdown"`),e}var ay=Object.freeze({type:"anonymous",signIn:null});function cy(e){let t={};for(let[n,r]of new URLSearchParams(e)){let o=t[n];t[n]=o==null?r:Array.isArray(o)?[...o,r]:[o,r]}return t}function py(e,t,n){let r=t._target,o=typeof r==="string"?r.trim():"";if(o)return{source:e.resolve(o)??e.repo.get(o),required:!0};if(!n)return;try{return{source:e.resolve(new URL(n).pathname),required:!1}}catch{return}}function uy(e,t){let n=e.headers.get("origin");if(n)return n===t.origin;let r=e.headers.get("referer");if(!r)return!1;try{return new URL(r).origin===t.origin}catch{return!1}}async function ly(e,t,n,r){if(t.method!=="POST")return new Response("Method Not Allowed",{status:405});if(r.type!=="authenticated")return V();if(!uy(t,n))return nt(t,403,"Cross-origin mutation denied.");let o=n.pathname.slice(9),i=cy(await t.text()),s=py(e,i,t.headers.get("referer")),a=s?.source;if(s?.required&&!a)return V();if(a&&!e.hasSourceCapability({type:"actor",actor:r.actor},a,"execute"))return V();let c;try{c=await ls(e,o,i,r.actor,a)}catch(p){if(p instanceof ft)return nt(t,404,p.message);if(p instanceof en)return nt(t,400,p.message);if(p instanceof we)return nt(t,403,p.message);let u=p instanceof Error?p.message:"Action failed.";return nt(t,400,u)}if(t.headers.get("accept")?.includes("application/json"))return St(Response.json({ok:!0,action:o,target:a?.id,output:c.value,receipt:{applied:c.commit.applied.length}}));return St(new Response(null,{status:303,headers:{Location:t.headers.get("referer")||"/"}}))}async function Ko(e,t){return jp(e,t,new URL(t.url))}async function Dp(e,t,n){let r=new URL(t.url),o=new URL(n,r.origin);return jp(e,t,o,r)}async function jp(e,t,n,r=n){let o=performance.now();return e.perf.measureAsync("http.request",async()=>{let i=await dy(e,t,n,r),s=performance.now()-o;return i.headers.set("Server-Timing",`render;dur=${s.toFixed(1)}`),e.log.debug("http.perf",{path:n.pathname,ms:Number(s.toFixed(1)),status:i.status}),i},r.pathname)}async function dy(e,t,n,r){if(t.method==="GET"||t.method==="HEAD"){let a=my(e,n.pathname,t.method==="HEAD");if(a)return a}if(ln(n.pathname)&&(t.method==="GET"||t.method==="HEAD")){let a=await Lp(e,n.pathname,t.method==="HEAD",ay,$e);if(a)return a}let o=await e.serverRoute(t,n,r);if(o)return o;if(n.pathname==="/api"||n.pathname.startsWith("/api/"))return V();let i=await e.resolveCredentials(t),s=Te(i);return fy(e,t,n,i,s)}function my(e,t,n){if(!t.startsWith("/.pmx/"))return;let r=e.servedAsset(t);if(!r)return;return new Response(n?null:r.body,{headers:{"Content-Type":r.contentType,"Cache-Control":"public, max-age=31536000, immutable"}})}async function fy(e,t,n,r,o){if(n.pathname.startsWith("/actions/"))return ly(e,t,n,r);if(t.method!=="GET"&&t.method!=="HEAD")return new Response("Method Not Allowed",{status:405});if(n.pathname.length>1&&n.pathname.endsWith("/"))return new Response(null,{status:308,headers:{Location:n.pathname.replace(/\/+$/,"")+n.search}});let i=qe(e.repo,n.pathname);if(i?.type==="source")return Mp(e,t.method==="HEAD",r,o,i.source);if(i?.type==="page"){let s=e.hasPlugin(_e);if(s&&Op(t))return Yo(Mp(e,t.method==="HEAD",r,o,i.source),i.source.path);let a=await pn(e,r,o,i.source,{scheme:un(t)});if(t.method==="HEAD")a=new Response(null,a);return s?Yo(a,i.source.path):a}return await Lp(e,n.pathname,t.method==="HEAD",r,o)??V()}function Mp(e,t,n,r,o){let i=e.readAccess(r,o);if(i==="denied")return V();return be(new Response(t?null:o.content,{headers:{"Content-Type":"text/markdown; charset=utf-8"}}),i,n)}async function Lp(e,t,n,r,o){let i;try{i=decodeURIComponent(t)}catch{return}if(i.includes(".."))return;let s=e.repo.storagePath(i);if(!s||!await e.repo.isFile(i))return;let a=e.readAccess(o,i);if(a==="denied")return V();let c=n?null:await e.environment.storage.readBlob(s);return be(new Response(c),a,r)}function gy(e,t,n){if(!n)return[...e,...t];let r=ie(e).map(ve),o=new Map(r.map((s,a)=>[s.id,a])),i=new Set;for(let s of ie(t).map(ve)){if(i.has(s.id))throw Error(`Duplicate repository plugin id: ${s.id}`);i.add(s.id);let a=o.get(s.id);if(a===void 0)r.push(s);else r[a]=s}return r}async function rt(e={},t={}){let n=typeof e==="string"?{...t,root:e}:{...e,...t},r=n.root??hy(process.cwd(),"paths"),o=n.environment??ue,i=n.log??new B({level:Ki(process.env.PATHMX_LOG)}),s=o===ue?await Vt(r,i):[],a=n.plugins??Cp;return uo({...n,root:r,environment:o,plugins:gy(a,s,n.plugins===void 0),log:i})}function yy(){return Zo(process.cwd(),"paths")}function Dn(e){return e?Zo(e):yy()}function A(e,t){let n=e.optsWithGlobals();return{root:Dn(t??n.root),actionsRoot:n.actions?Zo(n.actions):void 0}}function J(e,t={}){return rt(e,t)}function jn(e,t){if(t)console.log(ot.bold("Dry run"));for(let n of e.writes)console.log(`${ot.green("write")} ${n.path}`);for(let n of e.deletes)console.log(`${ot.red("delete")} ${n}`);if(!e.writes.length&&!e.deletes.length)console.log(ot.dim("No file changes"));for(let n of e.warnings)console.log(`${ot.yellow("warning")} ${n}`)}function I(e){let t=e instanceof Error?e.message:String(e);console.error(ot.red(t)),process.exit(1)}import vy from"@parcel/watcher";import{realpathSync as ky}from"fs";import{relative as Py}from"path";import{posix as Bp}from"path";var wy=/@import\s+(?:url\(\s*(?:"([^"]+)"|'([^']+)'|([^'"\s)]+))\s*\)|"([^"]+)"|'([^']+)')/gi,xy=/^(?:[a-z][a-z\d+.-]*:|\/\/|#)/i;function by(e,t){let n=t.split(/[?#]/,1)[0];if(!n||xy.test(n))return;let r=Bp.resolve(Bp.dirname(e),n);return r.endsWith(".css")?r:void 0}function Sy(e,t){let n=new Set;for(let r of t.matchAll(wy)){let o=r.slice(1).find((s)=>s!==void 0);if(!o)continue;let i=by(e,o);if(i)n.add(i)}return n}class ei{dependencies=new Map;dependents=new Map;replace(e,t){for(let r of this.dependencies.get(e)??[]){let o=this.dependents.get(r);if(o?.delete(e),!o?.size)this.dependents.delete(r)}if(t===void 0){this.dependencies.delete(e);return}let n=Sy(e,t);this.dependencies.set(e,n);for(let r of n){let o=this.dependents.get(r);if(!o)o=new Set,this.dependents.set(r,o);o.add(e)}}affected(e){let t=new Set([e]),n=[e];for(let r of n)for(let o of this.dependents.get(r)??[]){if(t.has(o))continue;t.add(o),n.push(o)}return t}}function Ry(e){let t=new Map;for(let n of e.graph.unresolvedLinks()){let r=`${n.from}\x00${n.href}`;t.set(r,{source:n.from,href:n.href,target:n.to})}return t}function Np(e,t){let n=Ry(e);for(let[r,o]of n){if(t?.has(r))continue;e.log.warn("link.unresolved",o)}if(t)for(let[r,o]of t){if(n.has(r))continue;e.log.info("link.resolved",{source:o.source,href:o.href})}return n}function zp(e,t){let n=ky(t),r=new ei,o=Promise.resolve(),i=Np(e),s=async(u)=>{let l=e.repo.graphPath(u),d=e.repo.storagePath(l);if(!d)return r.replace(l);try{r.replace(l,await e.environment.storage.readText(d))}catch{r.replace(l)}},a=async()=>{let u=[...await e.environment.storage.list(n)].filter((l)=>l.endsWith(".css"));for(let l=0;l<u.length;l+=16)await Promise.all(u.slice(l,l+16).map(s))},c=(u)=>{o=o.then(u).catch((l)=>{if(l instanceof R){e.log.error("source.invalid",l.diagnostic);return}e.log.error("watch.error",{message:l.message})})},p=a().then(()=>vy.subscribe(n,(u,l)=>{if(u){e.log.error("watch.error",{message:u.message});return}c(async()=>{let d=new Set;for(let m of l){let f=Py(n,m.path);if(!f||f.startsWith(".."))continue;if(e.log.debug("watch",{file:f,type:m.type}),f.endsWith(".md"))await e.syncFromStorage(f);else if(f.endsWith(".css")){await s(f);for(let h of r.affected(e.repo.graphPath(f)))d.add(h)}else if(f.endsWith(".js"))e.invalidateAsset(f)}if(d.size)e.invalidateAssets(d);i=Np(e,i)})}));return p.catch((u)=>e.log.error("watch.error",{message:u.message})),{subscription:p,async close(){await(await p.catch(()=>{return}))?.unsubscribe()}}}async function ti(e){let t=e.mode??"serve",n=await rt(e.root,{actionsRoot:e.actionsRoot,runtime:{mode:t==="dev"?"development":"production"},diagnostics:t==="dev"?"collect":"throw"});if(e.verbose)n.log.level="debug";let r=zp(n,e.root);try{await r.subscription;let o=e.port??(Number(process.env.PORT)||3000),i=e.hostname??(t==="dev"?"127.0.0.1":void 0),s=Bun.serve({port:o,...i?{hostname:i}:{},fetch(a,c){if(new URL(a.url).pathname==="/api/runtime/live")c.timeout(a,0);return Ko(n,a)}});return n.log.info("listen",{url:String(s.url),sources:n.repo.all().length,mode:t}),{app:n,server:s,async close(){await r.close(),await n.close(),s.stop(!0)}}}catch(o){throw await r.close(),await n.close(),o}}function ni(e){let t=Number(e);if(!Number.isInteger(t)||t<=0)throw Error(`Invalid port: ${e}`);return t}function qp(e){e.command("serve").description("Start the live production server").argument("[root]","source root (defaults to ./paths)").option("-p, --port <port>","port to listen on",ni).option("--host <hostname>","hostname or address to listen on").action(async(t,n,r)=>{try{let o=A(r,t);await ti({root:o.root,actionsRoot:o.actionsRoot,port:n.port,hostname:n.host,mode:"serve"})}catch(o){I(o)}})}var Fp="PMX_DEV_CHILD";function Up(e){e.command("dev").description("Start the development server (hot-restarts on code changes)").argument("[root]","source root (defaults to ./paths)").option("-p, --port <port>","port to listen on",ni).action(async(t,n,r)=>{let o=A(r,t);if(process.env[Fp]){try{await ti({root:o.root,actionsRoot:o.actionsRoot,port:n.port,verbose:!0,mode:"dev"})}catch(i){console.error(i)}return}try{await Oy(o,n.port)}catch(i){I(i)}})}async function Oy(e,t){let n=Ay(new URL("./index.ts",import.meta.url)),r=[process.execPath,"--watch",n,"dev",e.root];if(e.actionsRoot)r.push("--actions",e.actionsRoot);if(t!==void 0)r.push("--port",String(t));let o=Hp(Xn(e.root)),i=Iy(o),s,a=!1,c=0,p,u=()=>Bun.spawn(r,{env:{...process.env,[Fp]:"1"},stdin:"inherit",stdout:"inherit",stderr:"inherit"}),l=()=>{if(c++,p)clearTimeout(p);p=setTimeout(()=>{p=void 0,s?.kill()},75)},d=await Cy.subscribe(i,(f,h)=>{if(f){console.error(f);return}if(h.some((w)=>My(o,w.path)))l()},{ignore:[Hp(e.root),Vp(i,".git"),Vp(i,"node_modules")]});for(let f of["SIGINT","SIGTERM"])process.on(f,()=>{if(a=!0,p)clearTimeout(p);s?.kill(f)});let m=0;while(!a){let f=c;if(s=u(),m=await s.exited,s=void 0,c===f)break}await d.unsubscribe(),process.exit(m)}function My(e,t){let n=Ty(e,t);return!!n&&!$y(n)&&n!==".."&&!n.startsWith(`..${Ey}`)&&!n.split(/[\\/]/).includes("node_modules")}import{isAbsolute as sw,relative as aw,resolve as tu}from"path";async function it(e,t){let n=Array(e.length),r=0,o=!1,i,s=async()=>{while(!o){let a=r++;if(a>=e.length)return;try{n[a]=await t(e[a])}catch(c){o=!0,i=c}}};if(await Promise.all(Array.from({length:Math.min(16,e.length)},s)),o)throw i;return n}var Ln=3;var Dy="application/vnd.pathmx.artifact-leaf",jy="application/vnd.pathmx.publication-contract",Ly="application/vnd.pathmx.merkle-node";function ri(e,t,n){return gt(n,`${Dy}\x00${e}\x00${t}`)}function By(e,t,n){return gt(new Blob([JSON.stringify({version:Ln,origin:e.origin,basePath:t,routes:n})]),jy)}function Ny(e,t){return gt(new Blob([e,"\x00",t]),Ly)}async function zy(e){let t=[...e];while(t.length>1){let n=t;t=await it(Array.from({length:Math.ceil(n.length/2)},(r,o)=>o*2),(r)=>Ny(n[r],n[r+1]??n[r]))}return t[0]}async function _p(e,t,n,r){let o=await By(e,t,n);return zy([o,...r.map((i)=>i.leaf)])}var qy=new Set(["content-length","content-type","date","server-timing","set-cookie","transfer-encoding"]);class P extends Error{constructor(e){super(e);this.name="PublicationError"}}function je(e,t){return e<t?-1:e>t?1:0}function Bn(e){if(!e.startsWith("/")||e.includes("?")||e.includes("#"))throw new P(`Invalid publication route: ${e}`);if(new URL(e,"https://pathmx.local").pathname!==e||e.split("/").includes(".."))throw new P(`Invalid publication route: ${e}`);return e}function Qp(e="/"){let t=Bn(e||"/");if(t!=="/"&&t.endsWith("/"))throw new P(`Publication base path must not end with a slash: ${e}`);return t}function st(e,t){let n=Bn(t);if(e==="/")return n;return n==="/"?e:`${e}${n}`}function Wp(e){return`.pathmx/artifacts/pages/${e==="/"?"index.html":`${e.replace(/^\/+|\/+$/g,"")}/index.html`}`}function Le(e){let t=e.replace(/^\/+/,"");if(!t)throw new P(`Route requires an artifact: ${e}`);return t}function Xp(e){let t=[...e.headers].filter(([n])=>!qy.has(n.toLowerCase())).sort(([n],[r])=>je(n,r));return t.length?Object.freeze(Object.fromEntries(t)):void 0}function at(e,t,n){return Object.freeze({type:"file",default:!0,artifact:e,contentType:t||"application/octet-stream",...n?{headers:n}:{}})}class oi{routes=new Map;artifacts=new Map;hasRoute(e){return this.routes.has(e)}addRoute(e){if(this.routes.has(e.pathname))throw new P(`Duplicate publication route: ${e.pathname}`);this.routes.set(e.pathname,e)}addArtifact(e){if(this.artifacts.has(e.path))throw new P(`Duplicate publication artifact: ${e.path}`);this.artifacts.set(e.path,{path:e.path,contentType:e.contentType,size:e.size,read:e.read})}async materialize(e){let t=this.sortedArtifacts().filter((n)=>n.leaf===void 0);await it(t,(n)=>this.materializeArtifact(n,e))}async stagePage(e,t){let n=this.requireArtifact(e);if(n.leaf!==void 0)throw new P(`Page artifact was already staged: ${e}`);let r=await n.read();n.leaf=await ri(n.path,n.contentType,r),await this.storeStampedPage(n,r,t)}buildRoot(e,t){return _p(e,t,this.routeList(),this.artifactRecordList())}pageLeaves(){let e=new Map(this.artifactRecordList().map((t)=>[t.path,t]));return Object.freeze(Object.fromEntries(this.routeList().filter((t)=>t.type==="page").map((t)=>{let n=t.representations.find((o)=>o.type==="html")?.artifact,r=n?e.get(n):void 0;if(!r)throw new P(`Page route has no HTML artifact leaf: ${t.pathname}`);return[t.pathname,r.leaf]})))}manifest(e,t,n){return Object.freeze({version:Ln,build:e,origin:t.origin,basePath:n,routes:Object.freeze(this.routeList()),artifacts:Object.freeze(this.artifactRecordList())})}routeList(){return[...this.routes.values()].sort((e,t)=>je(e.pathname,t.pathname)).map((e)=>Object.freeze({...e,representations:Object.freeze([...e.representations])}))}artifactList(){return this.sortedArtifacts().map((e)=>{if(e.size===void 0)throw new P(`Publication artifact was not fingerprinted: ${e.path}`);if(e.leaf===void 0)throw new P(`Publication artifact has no leaf: ${e.path}`);return Object.freeze({path:e.path,contentType:e.contentType,size:e.size,leaf:e.leaf,read:e.read})})}artifactRecordList(){return this.artifactList().map(({read:e,...t})=>t)}requireArtifact(e){let t=this.artifacts.get(e);if(!t)throw new P(`Missing artifact: ${e}`);return t}async materializeArtifact(e,t){if(e.leaf!==void 0)return;let n=await e.read(),r=await ri(e.path,e.contentType,n),o=await t.put(e.path,n);e.size=o.size,e.leaf=r,e.read=o.read}async storeStampedPage(e,t,n){if(!e.leaf)throw new P(`Missing artifact leaf: ${e.path}`);let r=await t.text();if(!r.includes("<html"))throw new P(`HTML artifact has no document root: ${e.path}`);let o=new Blob([r.replace("<html",`<html data-pmx-page="${e.leaf}"`)],{type:e.contentType}),i=await n.put(e.path,o);e.size=i.size,e.read=i.read}sortedArtifacts(){return[...this.artifacts.values()].sort((e,t)=>je(e.path,t.path))}}var Vy=/^(?:[a-z][a-z\d+.-]*:|\/\/)/i;function Hy(e,t){let n=e.representations.find((r)=>r.type==="html")?.artifact;return n?t.get(n):void 0}function Nn(e,t,n){if(Vy.test(e.trim()))return;try{let r=new URL(e,new URL(t,n));return r.origin===n?r.pathname:void 0}catch{return}}function Fy(e,t,n,r){let o=t.sourcePath?e.repo.atPath(t.sourcePath):void 0;if(!o)return new Set;let i=e.isPage(o)?y(o):o.path;return new Set(e.graph.linksFrom(o.path).filter((s)=>s.type==="unresolved").map((s)=>{let a=Nn(_(s.href,o.data),i,n);return a?st(r,a):void 0}).filter((s)=>s!=null))}async function Jp(e,t){let n=new Set(t.manifest.routes.flatMap((i)=>{let s=Nn(i.pathname,"/",t.manifest.origin);return s?[s]:[]})),r=new Map(t.artifacts.map((i)=>[i.path,i])),o=[];for(let i of t.manifest.routes){let s=Hy(i,r);if(!s)continue;let a=Fy(e,i,t.manifest.origin,t.manifest.basePath),c=await(await s.read()).text();e.environment.rewriteHtml(c,[["a[href], link[href], script[src], img[src], source[src], form",{element(p){let u=p.getAttribute("href")!=null?"href":"src",l=p.getAttribute(u);if(l){let h=Nn(l,i.pathname,t.manifest.origin);if(h&&!n.has(h)&&!a.has(h))o.push(`${i.pathname}: ${u} references unpublished route ${h}`)}if(p.tagName!=="form")return;let d=(p.getAttribute("method")||"get").toLowerCase(),m=p.getAttribute("action")||i.pathname,f=Nn(m,i.pathname,t.manifest.origin);if(d==="get"){if(f&&!n.has(f))o.push(`${i.pathname}: GET form references unpublished route ${f}`)}else if(f)o.push(`${i.pathname}: ${d.toUpperCase()} form requires server route ${f}`)}}]])}if(o.length)throw new P(`Static publication contains unavailable routes:
1207
- ${[...new Set(o)].sort().map((i)=>`- ${i}`).join(`
1208
- `)}`)}var Uy=/^(?:[a-z][a-z\d+.-]*:|\/\/)/i,_y=/url\(\s*(?:(["'])(.*?)\1|([^)'"\s][^)]*?))\s*\)/gi,Qy=/(@import\s+)(["'])(.*?)\2/gi;function Wy(e){let t;try{t=new URL(e)}catch{throw new P(`Invalid publication origin: ${e}`)}if(t.protocol!=="http:"&&t.protocol!=="https:"||t.username||t.password||t.pathname!=="/"||t.search||t.hash)throw new P(`Publication origin must be an HTTP(S) origin without a path: ${t}`);return t}function Gp(e,t,n,r){let o=e.trim();if(!o||o.startsWith("#")||Uy.test(o))return;try{let i=new URL(o,new URL(r,t));if(i.origin!==t.origin)return;return`${st(n,i.pathname)}${i.search}${i.hash}`}catch{return}}function ii(e,t,n,r){let o=(i)=>Gp(i,t,n,r);return e.replace(_y,(i,s,a,c)=>{let p=a??c?.trim(),u=p?o(p):void 0;return u?`url(${s??""}${u}${s??""})`:i}).replace(Qy,(i,s,a,c)=>{let p=o(c);return p?`${s}${a}${p}${a}`:i})}function Xy(e,t,n,r,o){let i=st(r,o);return e.environment.rewriteHtml(t,[["html",{element(a){a.setAttribute("data-pmx-base",r)}}],["[data-pmx-route]",{element(a){a.setAttribute("data-pmx-route",i)}}],["[href], [src], [action], [poster], object[data]",{element(a){for(let c of["href","src","action","poster","data"]){let p=a.getAttribute(c),u=p?Gp(p,n,r,o):void 0;if(u)a.setAttribute(c,u)}}}],["[style]",{element(a){let c=a.getAttribute("style");if(c)a.setAttribute("style",ii(c,n,r,o))}}]]).replace(/(<style\b[^>]*>)([\s\S]*?)(<\/style\s*>)/gi,(a,c,p,u)=>`${c}${ii(p,n,r,o)}${u}`)}function Yp(e,t,n){let r=Wy(t),o=Qp(n),i=(s)=>st(o,s);return Object.freeze({origin:r,basePath:o,pathname:i,url:(s)=>new URL(i(s),r),async relocate(s,a,c){if(!c.includes("text/html")&&!c.includes("text/css"))return s;let p=await s.text(),u=c.includes("text/html")?Xy(e,p,r,o,a):ii(p,r,o,a);return new Blob([u],{type:c})}})}var Jy=Object.freeze({type:"anonymous",signIn:null}),Gy=["/actions","/api"],Yy=Object.freeze({async put(e,t){return Object.freeze({size:t.size,read:async()=>t})}});function si(e){return Gy.some((t)=>e===t||e.startsWith(`${t}/`))}function Ky(e,t){return e.readAccess($e,t)==="public"}function Kp(e,t){return e.headers.get("content-type")||t}async function Zp(e,t){if(!e.ok)throw new P(`Publication route ${t} returned ${e.status}.`);return e.blob()}async function Zy(e){let t=new Set,n=[];for(let r of e.plugins){if(!r.publish)continue;let o=Object.freeze({route(i){t.add(Bn(i))},unsupported(i,s){n.push(`${r.id}: ${i.path}: ${s}`)}});await r.publish(o,e.appContext(r.id))}if(n.length)throw new P(`Static publication is unsupported:
1209
- ${n.map((r)=>`- ${r}`).join(`
1210
- `)}`);return[...t].sort(je)}async function ew(e,t,n,r){for(let o of r){let i=n.pathname(o),s=await Dp(e,new Request(n.url(o),{headers:{Accept:"*/*"}}),o),a=Kp(s,"application/octet-stream"),c=Le(i),p=await n.relocate(await Zp(s,o),o,a);t.addArtifact({path:c,contentType:a,read:async()=>p}),t.addRoute({pathname:i,type:"artifact",representations:[at(c,a,Xp(s))]})}}async function tw(e,t,n,r){let o=e.repo.all().filter((a)=>Ky(e,a)).sort((a,c)=>je(a.path,c.path)),i=new Map;for(let a of o){let c=r.pathname(a.path);if(t.hasRoute(c)||si(a.path))continue;let p=Le(c),u="text/markdown; charset=utf-8",l=a.content;t.addArtifact({path:p,contentType:u,read:async()=>new Blob([l],{type:u})}),t.addRoute({pathname:c,type:"source",sourcePath:a.path,representations:[Object.freeze({type:"markdown",default:!0,artifact:p,contentType:u})]}),i.set(a.path,p)}let s=o.filter((a)=>{if(!e.isPage(a))return!1;let c=y(a),p=r.pathname(c);return!t.hasRoute(p)&&!si(c)&&e.resolve(c)===a});await it(s,async(a)=>{let c=y(a),p=r.pathname(c),u=await Ws(e,Jy,$e,a),l=Kp(u,"text/html; charset=utf-8"),d=await r.relocate(await Zp(u,c),c,l),m=Wp(p);t.addArtifact({path:m,contentType:l,read:async()=>d});let f=[Object.freeze({type:"html",default:!0,artifact:m,contentType:l})],h=i.get(a.path);if(h&&e.hasPlugin(_e))f.push(Object.freeze({type:"markdown",accept:"text/markdown",artifact:h,contentType:"text/markdown; charset=utf-8",alternatePath:r.pathname(a.path)}));t.addRoute({pathname:p,type:"page",sourcePath:a.path,representations:f}),await t.stagePage(m,n)})}async function nw(e,t,n){let r=e.environment.storage,o=[...await r.list(e.repo.rootPath)].sort(je);for(let i of o){if(i.endsWith(".md"))continue;let s=e.repo.graphPath(i),a=n.pathname(s);if(t.hasRoute(a)||si(s))continue;if(e.readAccess($e,s)!=="public")continue;let c=e.repo.storagePath(s);if(!c)continue;let u=(await r.readBlob(c)).type||"application/octet-stream",l=Le(a);t.addArtifact({path:l,contentType:u,read:async()=>n.relocate(await r.readBlob(c),s,u)}),t.addRoute({pathname:a,type:"asset",representations:[at(l,u)]})}}function rw(e,t,n){for(let[r,o]of e.generatedAssetEntries()){let i=n.pathname(r);if(t.hasRoute(i))throw new P(`Generated asset route collision: ${r}`);let s=Le(i);t.addArtifact({path:s,contentType:o.contentType,read:async()=>{let a=typeof o.body==="string"?new Blob([o.body],{type:o.contentType}):o.body;return n.relocate(a,r,o.contentType)}}),t.addRoute({pathname:i,type:"asset",representations:[at(s,o.contentType,{"cache-control":"public, max-age=31536000, immutable"})]})}}function ow(e,t,n){let r=n.pathname(`/.pmx/pages-${t}.json`),o=Le(r),i="application/json; charset=utf-8",s=new Blob([JSON.stringify({version:1,build:t,pages:e.pageLeaves()})+`
1211
- `],{type:"application/json; charset=utf-8"});return e.addArtifact({path:o,contentType:"application/json; charset=utf-8",size:s.size,read:async()=>s}),e.addRoute({pathname:r,type:"artifact",representations:[at(o,"application/json; charset=utf-8",{"cache-control":"public, max-age=31536000, immutable"})]}),r}function iw(e,t,n,r){let o=r.pathname("/.pmx/build.json"),i=Le(o),s="application/json; charset=utf-8",a=new Blob([JSON.stringify({version:t,pages:n})+`
1212
- `],{type:"application/json; charset=utf-8"});e.addArtifact({path:i,contentType:"application/json; charset=utf-8",size:a.size,read:async()=>a}),e.addRoute({pathname:o,type:"artifact",representations:[at(i,"application/json; charset=utf-8",{"cache-control":"no-store"})]})}async function eu(e,t){if(e.runtime.target!=="static")throw new P("Static publication requires runtime.target to be static.");let n=Yp(e,t.origin,t.basePath),r=t.store??Yy,o=new oi,i=await Zy(e);await ew(e,o,n,i),await tw(e,o,r,n),await nw(e,o,n),rw(e,o,n),await o.materialize(r);let s=await o.buildRoot(n.origin,n.basePath),a=ow(o,s,n);await o.materialize(r),iw(o,s,a,n),await o.materialize(r);let c=Object.freeze({manifest:o.manifest(s,n.origin,n.basePath),artifacts:Object.freeze(o.artifactList())});return await Jp(e,c),c}function nu(e,t){let n=aw(e,t);return n===""||!n.startsWith("..")&&!sw(n)}function cw(e,t){return nu(e,t)||nu(t,e)}function pw(e,t){let n=tu(t??U(e,"dist"));if(cw(n,tu(e)))throw Error("Export output must not contain or be inside the paths root.");return n}function ru(e){e.command("export").description("Export the public application as a static publication").argument("[root]","source root (defaults to ./paths)").requiredOption("--origin <url>","canonical public HTTP(S) origin").option("--base-path <path>","public mount path (defaults to /)").option("-o, --out <path>","output directory (defaults beside paths)").action(async(t,n,r)=>{let o,i=!1,s;try{let a=A(r,t),c=pw(a.root,n.out),p=await rt(a.root,{actionsRoot:a.actionsRoot,diagnostics:"throw",runtime:{mode:"production",target:"static"}});o=p;let u=await _n(c,async(l)=>{let d=await eu(p,{origin:n.origin,basePath:n.basePath,store:l});return await p.close(),o=void 0,d});console.log(`Exported ${u.routes.length} routes to ${c}`)}catch(a){i=!0,s=a}finally{await o?.close().catch(()=>{return})}if(i)I(s)})}import zn from"picocolors";function uw(e){let t=[];for(let n of e.graph.unresolvedLinks()){let o=e.repo.atPath(n.from)?.links.find((i)=>i.href===n.href);t.push({type:"link.unresolved",source:n.from,href:n.href,...o?.label?{label:o.label}:{}})}return t}function qn(e){return e.type==="link.unresolved"?`${e.type}\x00${e.source}\x00${e.href}\x00${e.label??""}`:`${e.type}\x00${e.source}\x00${e.plugin}\x00${e.message}`}function lw(e,t){return e.type.localeCompare(t.type)||e.source.localeCompare(t.source)||qn(e).localeCompare(qn(t))}function dw(e){let t=e.label?`[${e.label}](${e.href})`:e.href;return`${e.source}: ${t}`}function mw(e){if(!e.length)return zn.green("No issues found");let t=[],n=[];for(let i of e)switch(i.type){case"link.unresolved":t.push(i);break;case"source.invalid":n.push(i);break;default:}let r=[];if(t.length)r.push([zn.bold(`Unresolved links (${t.length})`),...t.map(dw)].join(`
1213
- `));if(n.length)r.push([zn.bold(`Authoring issues (${n.length})`),...n.map((i)=>i.message)].join(`
1214
- `));let o=e.length===1?"issue":"issues";return r.push(zn.red(`${e.length} ${o} found`)),r.join(`
1215
-
1216
- `)}async function fw(e){let t=new Map(uw(e).map((r)=>[qn(r),r])),n=(r)=>{let o={type:"source.invalid",...r};t.set(qn(o),o)};for(let r of e.sourceDiagnostics())n(r);for(let r of e.repo.all()){if(!e.isPage(r))continue;try{await e.compilePage(r)}catch(o){if(!(o instanceof R))throw o;n(o.diagnostic)}}for(let r of e.plugins){if(!r.lint)continue;await r.lint((o,i)=>{let s=i.trim();if(!s)throw Error(`Plugin ${r.id} reported an empty lint message.`);n({source:o.path,plugin:r.id,message:s})},e.appContext(r.id))}return[...t.values()].sort(lw)}function ou(e){e.command("lint").description("Validate authored Sources without starting a server").argument("[root]","source root (defaults to ./paths)").action(async(t,n,r)=>{try{let o=A(r,t),i=await J(o.root,{actionsRoot:o.actionsRoot,buildCache:!1,diagnostics:"collect",log:new B({sink(){}})}),s=await fw(i);if(console.log(mw(s)),!s.length)return;process.exitCode=1}catch(o){I(o)}})}class z extends Error{constructor(e){super(e);this.name="SourceOpError"}}function Dt(){return{writes:[],deletes:[],warnings:[]}}async function jt(e,t){let n=[];for(let r of t.deletes){let o=e.repo.graphPath(r);if(!e.repo.storagePath(o))throw new z(`Path escapes repository: ${r}`);n.push({type:"delete",path:o})}for(let r of t.writes){let o=e.repo.graphPath(r.path);if(!e.repo.storagePath(o))throw new z(`Path escapes repository: ${r.path}`);n.push({type:e.repo.atPath(o)?"replace":"create",path:o,content:r.content})}if(n.length)await e.commit({changes:n})}function hw(e,t){let n=e.repo.graphPath(t),r=e.repo.atPath(n)??e.repo.get(t)??e.repo.get(e.repo.pathToId(n));if(!r)throw new z(`Source not found: ${t}`);if(!r.path.endsWith(".md"))throw new z(`Only markdown sources can be moved: ${t}`);return r}async function gw(e,t){let n=e.repo.graphPath(t);if(!n.endsWith(".md"))throw new z(`Destination must be a markdown path: ${t}`);let r=e.repo.storagePath(n);if(!r)throw new z(`Destination escapes the source root: ${t}`);if(e.repo.atPath(n)||await e.environment.storage.exists(r))throw new z(`Destination already exists: ${n}`);return n}function yw(e){let t=e.indexOf("#");return t===-1?e:e.slice(0,t)}async function ai(e,t,n){let r=hw(e,t),o=await gw(e,n);if(S.normalize(r.path)===S.normalize(o))throw new z(`Source and destination are the same path: ${o}`);let i=se(o,r.content,e.environment.yaml),s=S.dirname(r.path),a=S.dirname(o),c=new Set(e.graph.linksFrom(r.path).filter((m)=>m.to===r.path).map((m)=>m.href)),p=ut(r.content,(m)=>{if(c.has(m))return Co(m,o,r,i);let{pathname:f}=Ke(m);if(An(f))return Pc(m,s,a)}),u=Dt();u.writes.push({path:o,content:p}),u.deletes.push(r.path);let l=e.graph.linksTo(r.path),d=new Map;for(let m of l){let f=yw(m.from);if(f===r.path)continue;let h=d.get(f)??new Set;h.add(m.href),d.set(f,h)}for(let[m,f]of d){let h=e.repo.atPath(m);if(!h)continue;let w=ut(h.content,(T)=>{if(!f.has(T))return;return Co(T,m,r,i)});if(w!==h.content)u.writes.push({path:m,content:w})}if(L(r))u.warnings.push(`Moving index source ${r.path} changes the directory route ${y(r)}`);if(!Ro(r)&&r.id!==i.id)u.warnings.push(`Moving ${r.path} changes its public URL from ${r.id} to ${i.id}`);return u}function ww(e,t){let n=e.repo.graphPath(t),r=e.repo.atPath(n)??e.repo.get(t)??e.repo.get(e.repo.pathToId(n));if(!r)throw new z(`Source not found: ${t}`);if(!r.path.endsWith(".md"))throw new z(`Only markdown sources can be removed: ${t}`);return r}function xw(e){let t=e.indexOf("#");return t===-1?e:e.slice(0,t)}async function ci(e,t){let n=ww(e,t),r=e.graph.linksTo(n.path),o=new Map,i=0;for(let a of r){let c=xw(a.from);if(c===n.path)continue;let p=o.get(c)??new Set;if(p.add(a.href),o.set(c,p),a.fragment&&n.blocks.some((u)=>u.id===a.fragment))i++}let s=Dt();s.deletes.push(n.path);for(let[a,c]of o){let p=e.repo.atPath(a);if(!p)continue;let u=Ft(p.content,(l)=>c.has(l));if(u!==p.content)s.writes.push({path:a,content:u})}if(L(n))s.warnings.push(`Removing index source ${n.path} will 404 the directory route ${y(n)}`);if(i)s.warnings.push(`Removing ${n.path} unlinks ${i} block target${i===1?"":"s"}`);return s}function iu(e){e.command("mv").description("Move a source and rewrite linked references").argument("<old-path>","existing source path").argument("<new-path>","destination markdown path").option("--dry-run","print the plan without writing").action(async(t,n,r,o)=>{try{let{root:i,actionsRoot:s}=A(o),a=await J(i,{actionsRoot:s,buildCache:!1}),c=await ai(a,t,n);if(jn(c,Boolean(r.dryRun)),!r.dryRun)await jt(a,c)}catch(i){I(i)}})}function bw(e){if(e==="text"||e==="json")return e;throw Error(`Unsupported permission format: ${e}`)}function su(e){let t=new Set(e.capabilities);return`${t.has("read")?"r":"-"}${t.has("write")?"w":"-"}${t.has("execute")?"x":"-"}`}function au(e){switch(e.type){case"exact-grant":return e.owner?"owner \xB7 exact grant":"exact grant";case"home-owner":return"Home owner";case"staff-review":return"staff review";case"public-source":return"public Source";case"denied":return e.reason.replaceAll("-"," ")}}function cu(e,t){let n=e.map((r,o)=>Math.max(r.length,...t.map((i)=>i[o]?.length??0)));return[e,...t].map((r)=>r.map((o,i)=>o.padEnd(n[i]??o.length)).join(" ").trimEnd()).join(`
1217
- `)}function Sw(e){if(e.type==="source")return[e.sourceId,cu(["Actor","Caps","Visibility","Basis"],e.permissions.map((t)=>[t.actorId??"anonymous",su(t),t.visibility,au(t.basis)]))].join(`
1218
-
1219
- `);return[e.actorId,cu(["Caps","Source","Visibility","Basis"],e.permissions.map((t)=>[su(t),t.sourceId,t.visibility,au(t.basis)]))].join(`
1220
-
1221
- `)}function vw(e,t){return e.repo.get(t)??e.repo.atPath(t)}function pu(e,t){if(t.source){let r=e.inspectSourcePermissions(t.source);if(t.actorId){if(r=r.filter((o)=>o.actorId===t.actorId),!r.length)throw Error(`Actor not found: ${t.actorId}`)}return{type:"source",sourceId:t.source.id,...t.actorId?{actorId:t.actorId}:{},permissions:r}}let n=e.inspectActorPermissions(t.actorId);if(!n)throw Error(`Actor not found: ${t.actorId}`);return{type:"actor",actorId:t.actorId,permissions:n.filter((r)=>r.capabilities.includes("read"))}}function uu(e){e.command("perms").description("Inspect effective Source permissions").argument("[source]","Source id or path").option("--as <actor>","inspect permissions for an Actor id").option("--format <format>","output format: text or json",bw,"text").action(async(t,n,r)=>{try{let o=A(r),i=await J(o.root,{actionsRoot:o.actionsRoot,buildCache:!1,log:new B({level:"error"})}),s=t?vw(i,t):void 0;if(t&&!s)throw Error(`Source not found: ${t}`);let a;if(s)a=pu(i,{source:s,actorId:n.as});else{if(!n.as)throw Error("Provide a Source or use --as <actor>.");a=pu(i,{actorId:n.as})}console.log(n.format==="json"?JSON.stringify(a,null,2):Sw(a))}catch(o){I(o)}})}function lu(e){e.command("rm").description("Remove a source and unlink references").argument("<path>","source path to remove").option("--dry-run","print the plan without writing").action(async(t,n,r)=>{try{let{root:o,actionsRoot:i}=A(r),s=await J(o,{actionsRoot:i,buildCache:!1}),a=await ci(s,t);if(jn(a,Boolean(n.dryRun)),!n.dryRun)await jt(s,a)}catch(o){I(o)}})}import{basename as kw}from"path";import pi from"picocolors";function du(e,t,n,r){let o=e;for(let i of t){let s=o.children.get(i);if(!s)s={name:i,children:new Map},o.children.set(i,s);o=s}if(n)o.source=n;if(r)o.asset=!0}function Pw(e,t){let n=t.graph.linksFrom(e.path),r=t.graph.linksTo(e.path),o=n.filter((a)=>a.type==="unresolved").length,i=[e.type];if(e.blocks.length)i.push(`${e.blocks.length} block${e.blocks.length===1?"":"s"}`);if(n.length||r.length)i.push(`${n.length}\u2192 ${r.length}\u2190`);let s=o?` \xB7 ${pi.red(`${o} unresolved`)}`:"";return` ${pi.dim(`(${i.join(" \xB7 ")})`)}${s}`}function mu(e,t,n,r,o){let i=n?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",s=e.source?Pw(e.source,o):e.asset?` ${pi.dim("(asset)")}`:"";r.push(`${t}${i}${e.name}${s}`);let a=`${t}${n?" ":"\u2502 "}`,c=[...e.children.values()].sort((p,u)=>p.name.localeCompare(u.name));c.forEach((p,u)=>{mu(p,a,u===c.length-1,r,o)})}function Rw(e,t={}){let n={name:kw(e.repo.rootPath)||"paths",children:new Map};for(let i of e.repo.all()){let s=i.path.replace(/^\/+/,"").split("/").filter(Boolean);du(n,s,i)}if(t.all)for(let i of new Bun.Glob("**/*").scanSync({cwd:e.repo.rootPath,onlyFiles:!0})){if(i.endsWith(".md"))continue;du(n,i.split("/").filter(Boolean),void 0,!0)}let r=[`${n.name}/`],o=[...n.children.values()].sort((i,s)=>i.name.localeCompare(s.name));return o.forEach((i,s)=>{mu(i,"",s===o.length-1,r,e)}),r.join(`
1222
- `)}function fu(e){e.command("tree").description("Show the source/graph tree").argument("[root]","source root (defaults to ./paths)").option("--all","include non-markdown files").action(async(t,n,r)=>{try{let o=A(r,t),i=await J(o.root,{actionsRoot:o.actionsRoot,buildCache:!1});console.log(Rw(i,{all:n.all}))}catch(o){I(o)}})}import{dirname as Cw}from"path";function hu(e,t,n){for(let r=2;r<e.length;r++){let o=e[r];if(o===t||o===n)return e[r+1];if(o?.startsWith(`${t}=`))return o.slice(t.length+1)}}function Aw(e){let t=hu(e,"--actions","-a");return{pathsRoot:Dn(hu(e,"--root","-r")),actionsRoot:t?Dn(t):void 0}}async function gu(e,t){let{pathsRoot:n,actionsRoot:r}=Aw(t),o=Cw(n),i=U(n,".pathmx/state"),s=new B({level:"error"}),a=await Vt(n,s),c=ie(a).map(ve),p=new Ie(ue.database,i),u=Tp(ue,{paths:n,project:o}),l=()=>p.close();try{for(let d of c){if(!d.commands)continue;if(bt(d.id),e.commands.some((f)=>f.name()===d.id))throw Error(`Plugin command conflicts with core command: ${d.id}`);if(d.database)p.register(d.id,d.database);let m=e.command(d.id).description(d.name?`${d.name} administration`:`${d.id} administration`);d.commands(m,Object.freeze({plugin:d.id,pathsRoot:n,actionsRoot:r,projectRoot:o,stateRoot:i,log:Nr(s,d.id),database:p.get(d.id),patterns:u}))}}catch(d){try{await l()}catch(m){throw AggregateError([d,m],"Plugin command registration failed.")}throw d}return l}import{dirname as Tw,join as vu}from"path";var yu={name:"@pathmx/core",version:"0.5.0",module:"core.ts",type:"module",private:!0,bin:{pathmx:"./cli/index.ts",pmx:"./cli/index.ts"},exports:{".":"./core.ts","./bun":"./index.ts","./publish":"./publish/index.ts","./plugins":"./plugins/index.ts"},engines:{bun:">=1.4.0"},pathmxRelease:{channel:"beta",testedBun:"1.4.0"},dependencies:{"@parcel/watcher":"^2.6.0",commander:"^15.0.0","highlight.js":"^11.12.0",morphdom:"^2.7.8",picocolors:"^1.1.1",temml:"^0.13.4"}};var Lt=yu,C=Object.freeze({package:Lt.name,version:Lt.version,channel:Lt.pathmxRelease.channel,minimumBun:Lt.engines.bun.replace(/^>=/,""),testedBun:Lt.pathmxRelease.testedBun});function wu(e){let[t=0,n=0,r=0]=e.replace(/^v/,"").split("-",1)[0].split(".").map((o)=>Number.parseInt(o,10));return[t,n,r]}function Vn(e,t){let n=wu(e),r=wu(t);for(let o=0;o<n.length;o++){let i=n[o]-r[o];if(i)return Math.sign(i)}return 0}function $w(e,t=C.minimumBun,n=C.testedBun){if(Vn(e,t)<0)return{type:"unsupported",message:`PathMX ${C.version} requires Bun ${t} or newer; you are running ${e}. Run \`bun upgrade\` and try again.`};if(Vn(e,n)<0)return{type:"outdated",message:`PathMX ${C.version} is tested with Bun ${n}; you are running ${e}. Run \`bun upgrade\` when convenient.`};return{type:"supported"}}function xu(e=Bun.version){let t=$w(e);if(t.type==="unsupported")throw Error(t.message);if(t.type==="outdated")console.warn(`warning: ${t.message}`)}function bu(e){let t=e.startsWith("@pathmx/")?e.slice(8):e;if(!/^[a-z0-9][a-z0-9._-]*$/.test(t))throw Error(`Invalid PathMX plugin package: ${e}. Use a name such as react or @pathmx/react.`);return`@pathmx/${t}`}function Hn(e){return Tw(A(e).root)}async function ui(e){let t=Bun.file(vu(e,"package.json"));if(!await t.exists())throw Error(`PathMX project package.json not found: ${t.name}`);return await t.json()}function Su(e){let t=new Map;for(let[n,r]of Object.entries(e.dependencies??{}))if(n.startsWith("@pathmx/"))t.set(n,{name:n,spec:r,development:!1});for(let[n,r]of Object.entries(e.optionalDependencies??{}))if(n.startsWith("@pathmx/")&&!t.has(n))t.set(n,{name:n,spec:r,development:!1});for(let[n,r]of Object.entries(e.devDependencies??{}))if(n.startsWith("@pathmx/")&&!t.has(n))t.set(n,{name:n,spec:r,development:!0});return[...t.values()].sort((n,r)=>n.name.localeCompare(r.name))}async function Ew(e,t){let n=Bun.file(vu(e,"node_modules",t,"package.json"));if(!await n.exists())return;return(await n.json()).version}async function li(e,t,n=!1){if(!t.length)return;let r=t.map((a)=>`${a}@${C.channel}`),o=["add","--exact",...n?["--dev"]:[],...r],s=await Bun.spawn([process.execPath,...o],{cwd:e,stdin:"inherit",stdout:"inherit",stderr:"inherit"}).exited;if(s!==0)throw Error(`Bun could not install ${r.join(", ")} (exit ${s}).`)}function ku(e){let t=e.command("plugins").description("manage official @pathmx/* packages");t.command("list").description("list installed @pathmx/* packages").action(async(n,r)=>{let o=Hn(r),i=Su(await ui(o));if(!i.length){console.log("No @pathmx/* packages are installed.");return}for(let s of i){let a=await Ew(o,s.name);console.log(`${s.name} ${s.spec}${a?` (${a})`:" (not installed)"}`)}}),t.command("add").description(`add packages from the PathMX ${C.channel} channel`).argument("<plugins...>","package names, such as react or mermaid").action(async(n,r,o)=>{await ui(Hn(o)),await li(Hn(o),n.map(bu))}),t.command("update").description(`update installed packages from the ${C.channel} channel`).argument("[plugins...]","installed package names; defaults to all").action(async(n,r,o)=>{let i=Hn(o),s=Su(await ui(i)),a=n.length?n.map(bu):s.map(({name:l})=>l),c=a.filter((l)=>!s.some((d)=>d.name===l));if(c.length)throw Error(`${c.join(", ")} ${c.length===1?"is":"are"} not installed; use \`pathmx plugins add\` first.`);if(!a.length){console.log("No @pathmx/* packages are installed.");return}let p=a.filter((l)=>!s.find((d)=>d.name===l)?.development),u=a.filter((l)=>s.find((d)=>d.name===l)?.development);await li(i,p),await li(i,u,!0)})}function di(e,t){return[...t,e]}function Ow(e){let t=Number(e);if(!Number.isSafeInteger(t)||t<0)throw Error(`Invalid query limit: ${e}`);return t}function Mw(e){if(e==="json"||e==="jsonl"||e==="table")return e;throw Error(`Unsupported query format: ${e}`)}function Dw(e){let t=e.trim();if(t==="null")return null;if(t==="true")return!0;if(t==="false")return!1;if(/^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?$/.test(t)){let n=Number(t);if(Number.isFinite(n))return n}if(t.startsWith('"')){let n=JSON.parse(t);if(typeof n!=="string")throw Error(`Query value is not a scalar string: ${e}`);return n}return e}function jw(e){let t={};for(let n of e){let r=n.indexOf("=");if(r<=0)throw Error(`Invalid query filter: ${n}; expected field=value.`);let o=n.slice(0,r).trim();if(!o)throw Error(`Invalid query filter: ${n}`);t[o]=Dw(n.slice(r+1))}return t}function Lw(e){return e.map((t)=>{let[n,r,o]=t.split(":");if(!n?.trim()||o!==void 0)throw Error(`Invalid query sort: ${t}`);if(r&&r!=="asc"&&r!=="desc")throw Error(`Invalid query sort direction: ${r}`);let i=r==="asc"||r==="desc"?r:void 0;return{by:n.trim(),...i?{direction:i}:{}}})}async function Bw(e,t){let n=t==="-"?await new Response(Bun.stdin.stream()).text():await Bun.file(t).text(),r;if(t.endsWith(".yaml")||t.endsWith(".yml"))r=e.environment.yaml.parse(n);else try{r=JSON.parse(n)}catch(o){if(t.endsWith(".json"))throw o;r=e.environment.yaml.parse(n)}if(r==null||typeof r!=="object"||Array.isArray(r))throw Error("Query request must be a JSON or YAML object.");return r}async function Nw(e,t){let n=t.request?await Bw(e,t.request):{},r={...n.where??{},...jw(t.where)},o=[...n.sort??[],...Lw(t.sort)];return{...n,...t.from!==void 0?{from:t.from}:{},...t.input!==void 0?{input:JSON.parse(t.input)}:{},...Object.keys(r).length?{where:r}:{},...o.length?{sort:o}:{},...t.limit!==void 0?{limit:t.limit}:{},...t.type!==void 0?{type:t.type}:{},...t.has.length?{has:t.has}:{},...t.recursive===!1?{recursive:!1}:{}}}function zw(e){if(e==null)return"";return typeof e==="string"?e:String(e)}function qw(e,t){let n=t.map((i)=>e.map(({path:s})=>zw(H(i,s)))),r=e.map(({path:i,label:s})=>s??i),o=r.map((i,s)=>Math.max(i.length,...n.map((a)=>a[s]?.length??0)));return[r,...n].map((i)=>i.map((s,a)=>s.padEnd(o[a]??s.length)).join(" ").trimEnd()).join(`
1223
- `)}async function Vw(e,t,n){let r=await Nw(e,n),o=n.as?e.actor(n.as):void 0;if(n.as&&!o)throw Error(`Actor not found: ${n.as}`);let i=ba(e,o),s=await e.queries.run(i,t,r);if(n.format==="json")return JSON.stringify(s,null,2);if(n.format==="jsonl")return s.map((p)=>JSON.stringify(p)).join(`
1224
- `);let c=(await e.queries.fields(t,r)).filter(({path:p})=>s.some((u)=>H(u,p)!==void 0));return qw(c,s)}function Pu(e){e.command("query").description("Query Sources, Blocks, or an installed named query").argument("<query>","sources, blocks, or plugin:name").option("--from <scope>","canonical or Actor-relative scope").option("--input <json>","named-query input as JSON").option("--where <field=value>","scalar equality filter",di,[]).option("--sort <field[:direction]>","result ordering",di,[]).option("--limit <number>","maximum result count",Ow).option("--type <type>","built-in Source or Block type").option("--has <prop>","required registered data prop",di,[]).option("--no-recursive","exclude nested scopes").option("--as <actor>","inspect through an Actor's effective access").option("--request <file>","JSON/YAML request file, or - for stdin").option("--format <format>","output format: json, jsonl, or table",Mw,"json").action(async(t,n,r)=>{let o;try{let i=A(r);o=await J(i.root,{actionsRoot:i.actionsRoot,buildCache:!1,log:new B({sink(){}})}),console.log(await Vw(o,t,n))}catch(i){I(i)}finally{await o?.close()}})}function Fn(){return`${C.package}@${C.channel}`}async function Hw(e=fetch){let t=await e(`https://registry.npmjs.org/${encodeURIComponent(C.package)}`,{headers:{Accept:"application/json"}});if(!t.ok)throw Error(`Unable to check ${Fn()} (${t.status} ${t.statusText}).`);let r=(await t.json())["dist-tags"]?.[C.channel];if(!r)throw Error(`${Fn()} does not have a published release.`);return r}async function Fw(e){let n=await Bun.spawn([process.execPath,"add","--global",e],{stdin:"inherit",stdout:"inherit",stderr:"inherit"}).exited;if(n!==0)throw Error(`Bun could not install ${e} (exit ${n}).`)}function Ru(e){e.command("update").description(`update the PathMX CLI from the ${C.channel} channel`).option("--check","check for an update without installing it").action(async({check:t})=>{let n=await Hw(),r=Vn(C.version,n);if(r>=0){let o=r>0?"newer than":"matches";console.log(`PathMX ${C.version} ${o} ${Fn()} (${n}).`);return}if(t){console.log(`PathMX ${n} is available on the ${C.channel} channel (installed: ${C.version}).`);return}console.log(`Updating ${C.package} ${C.version} \u2192 ${n}`),await Fw(Fn()),console.log(`PathMX ${n} installed. Run \`pathmx --version\` to verify.`)})}function _w(){let e=new Uw().name("pathmx").description("Manage and serve PathMX projects").version(C.version).option("-r, --root <path>","source root (defaults to ./paths)").option("-a, --actions <path>","actions root");return qp(e),Up(e),ru(e),iu(e),lu(e),fu(e),uu(e),ou(e),Pu(e),ku(e),Ru(e),e}async function Qw(e=process.argv){xu();let t=_w(),n=await gu(t,e);try{await t.parseAsync(e)}finally{await n()}}if(import.meta.main)await Qw();export{_w as createProgram,Qw as runCli};
2
+ import { runCli } from "../cli/index.ts"
3
+ await runCli()