@inkeep/open-knowledge 0.0.0-dev-20260421183856 → 0.0.0-dev-20260421192027

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/cli.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{a as e,i as t}from"./constants-D6bAkegd.mjs";import{D as n,O as r,s as i}from"./src-ViJPkmPW.mjs";import{n as a,t as o}from"./paths-BIa6zXQi.mjs";import{G as s,H as c,U as l,W as u,X as d,l as f}from"./src-BrZIzHKR.mjs";import{c as p,f as m,r as h}from"./server-lock-B4frNnOB.mjs";import{i as g}from"./init-DA7kkHUA.mjs";import{t as _}from"./is-object-B4GcZahG.mjs";import{r as v}from"./init-CiURMJ2p.mjs";import{i as y,n as b,t as x}from"./loader-xn8pJrM1.mjs";import{a as S,o as C}from"./start-BevXBjPW.mjs";import"./src-DdjBWEcP.mjs";import{Command as w}from"commander";import{appendFileSync as T,closeSync as E,existsSync as D,mkdirSync as O,openSync as ee,readFileSync as k,readdirSync as te,statSync as ne,unlinkSync as re,writeFileSync as ie}from"node:fs";import{homedir as ae,hostname as oe}from"node:os";import{basename as se,dirname as ce,isAbsolute as le,join as ue,relative as de,resolve as A}from"node:path";import{parse as fe,stringify as pe}from"yaml";import{createOAuthDeviceAuth as me}from"@octokit/auth-oauth-device";import he from"@inquirer/password";import{Octokit as ge}from"@octokit/rest";import{fileURLToPath as _e}from"node:url";import{randomUUID as ve}from"node:crypto";import{execFileSync as ye,spawn as be}from"node:child_process";import xe from"simple-git";import{readFile as Se,readdir as Ce,stat as we}from"node:fs/promises";import{createServer as Te,request as Ee}from"node:http";import De from"picomatch";import{z as j}from"zod";import{McpServer as Oe}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as ke}from"@modelcontextprotocol/sdk/server/stdio.js";import{RootsListChangedNotificationSchema as Ae}from"@modelcontextprotocol/sdk/types.js";import{Bash as je,ReadWriteFs as Me}from"just-bash";import Ne from"shell-quote";const Pe=`open-knowledge`;var Fe=class{backend=`keyring`;async get(e){let{Entry:t}=await import(`@napi-rs/keyring`);try{let n=new t(Pe,e).getPassword();return n==null?null:JSON.parse(n)}catch{return null}}async set(e,t,n,r){let{Entry:i}=await import(`@napi-rs/keyring`),a=new i(Pe,e),o={login:t,token:n,...r};a.setPassword(JSON.stringify(o))}async clear(e){let{Entry:t}=await import(`@napi-rs/keyring`);try{new t(Pe,e).deletePassword()}catch{}}},Ie=class{backend=`file`;authFile;constructor(e){this.authFile=e??ue(ae(),`.open-knowledge`,`auth.yml`)}read(){if(!D(this.authFile))return{};try{return fe(k(this.authFile,`utf-8`))??{}}catch(e){let t=e instanceof Error?e.message:`unknown error`;return process.stderr.write(`[auth] Failed to parse ${this.authFile}: ${t}. Starting with empty credentials.\n`),{}}}write(e){let t=ce(this.authFile);D(t)||O(t,{recursive:!0,mode:448}),ie(this.authFile,pe(e),{mode:384})}async get(e){return this.read()[e]??null}async set(e,t,n,r){let i=this.read();i[e]={login:t,token:n,...r},this.write(i)}async clear(e){let t=this.read();delete t[e],this.write(t)}};async function Le(e){try{let{Entry:e}=await import(`@napi-rs/keyring`);return new e(Pe,`__probe__`),process.stderr.write(`[auth] token storage: OS keychain
2
+ import{a as e,i as t}from"./constants-BLW6shM6.mjs";import{D as n,O as r,s as i}from"./src-ViJPkmPW.mjs";import{n as a,t as o}from"./paths-DxI4FHOZ.mjs";import{G as s,H as c,U as l,W as u,X as d,l as f}from"./src-DcVg7_6f.mjs";import{c as p,f as m,r as h}from"./server-lock-B4frNnOB.mjs";import{i as g}from"./init-DeoOI04P.mjs";import{t as _}from"./is-object-B4GcZahG.mjs";import{r as v}from"./init-WENor_lZ.mjs";import{i as y,n as b,t as x}from"./loader-BNuhNFOT.mjs";import{a as S,o as C}from"./start-CNULXoun.mjs";import"./src-D9A_jCdV.mjs";import{Command as w}from"commander";import{appendFileSync as T,closeSync as E,existsSync as D,mkdirSync as O,openSync as ee,readFileSync as k,readdirSync as te,statSync as ne,unlinkSync as re,writeFileSync as ie}from"node:fs";import{homedir as ae,hostname as oe}from"node:os";import{basename as se,dirname as ce,isAbsolute as le,join as ue,relative as de,resolve as A}from"node:path";import{parse as fe,stringify as pe}from"yaml";import{createOAuthDeviceAuth as me}from"@octokit/auth-oauth-device";import he from"@inquirer/password";import{Octokit as ge}from"@octokit/rest";import{fileURLToPath as _e}from"node:url";import{randomUUID as ve}from"node:crypto";import{execFileSync as ye,spawn as be}from"node:child_process";import xe from"simple-git";import{readFile as Se,readdir as Ce,stat as we}from"node:fs/promises";import{createServer as Te,request as Ee}from"node:http";import De from"picomatch";import{z as j}from"zod";import{McpServer as Oe}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as ke}from"@modelcontextprotocol/sdk/server/stdio.js";import{RootsListChangedNotificationSchema as Ae}from"@modelcontextprotocol/sdk/types.js";import{Bash as je,ReadWriteFs as Me}from"just-bash";import Ne from"shell-quote";const Pe=`open-knowledge`;var Fe=class{backend=`keyring`;async get(e){let{Entry:t}=await import(`@napi-rs/keyring`);try{let n=new t(Pe,e).getPassword();return n==null?null:JSON.parse(n)}catch{return null}}async set(e,t,n,r){let{Entry:i}=await import(`@napi-rs/keyring`),a=new i(Pe,e),o={login:t,token:n,...r};a.setPassword(JSON.stringify(o))}async clear(e){let{Entry:t}=await import(`@napi-rs/keyring`);try{new t(Pe,e).deletePassword()}catch{}}},Ie=class{backend=`file`;authFile;constructor(e){this.authFile=e??ue(ae(),`.open-knowledge`,`auth.yml`)}read(){if(!D(this.authFile))return{};try{return fe(k(this.authFile,`utf-8`))??{}}catch(e){let t=e instanceof Error?e.message:`unknown error`;return process.stderr.write(`[auth] Failed to parse ${this.authFile}: ${t}. Starting with empty credentials.\n`),{}}}write(e){let t=ce(this.authFile);D(t)||O(t,{recursive:!0,mode:448}),ie(this.authFile,pe(e),{mode:384})}async get(e){return this.read()[e]??null}async set(e,t,n,r){let i=this.read();i[e]={login:t,token:n,...r},this.write(i)}async clear(e){let t=this.read();delete t[e],this.write(t)}};async function Le(e){try{let{Entry:e}=await import(`@napi-rs/keyring`);return new e(Pe,`__probe__`),process.stderr.write(`[auth] token storage: OS keychain
3
3
  `),new Fe}catch{return process.stderr.write(`[auth] token storage: file (~/.open-knowledge/auth.yml)
4
4
  `),new Ie(e)}}async function Re(e,t,n){let r=ze(await Be(e)).host??``;if(!r)return 1;let i=await n.get(r);if(i==null)return 1;let a=e=>e.replace(/[\r\n]/g,``);return t.write(`username=${a(i.login)}\npassword=${a(i.token)}\n`),0}function ze(e){let t={};for(let n of e.split(`
5
5
  `)){let e=n.trim();if(e===``)continue;let r=e.indexOf(`=`);r!==-1&&(t[e.slice(0,r)]=e.slice(r+1))}return t}function Be(e){return new Promise((t,n)=>{let r=[];e.on(`data`,e=>r.push(e)),e.on(`end`,()=>t(Buffer.concat(r).toString(`utf-8`))),e.on(`error`,n)})}function Ve(e){let t=new w(`git-credential`);return t.description(`Git credential helper (git credential-helper protocol)`),t.command(`get`).description(`Lookup credentials from TokenStore (called by git)`).action(async()=>{let t=await e(),n=await Re(process.stdin,process.stdout,t);process.exit(n)}),t}async function He(e){let{clientId:t,scopes:n=[`repo`,`read:user`,`user:email`],onVerification:r,host:i}=e,a=i&&i!==`github.com`?`https://${i}/api/v3`:`https://api.github.com`,o=me({clientType:`oauth-app`,clientId:t,scopes:n,onVerification:async e=>{await r({verificationUri:e.verification_uri,userCode:e.user_code,expiresIn:e.expires_in,interval:e.interval})},request:a===`https://api.github.com`?void 0:(await import(`@octokit/request`)).request.defaults({baseUrl:a})}),s;try{s=await o({type:`oauth`})}catch(e){if(e instanceof Error){let t=e.message.toLowerCase();throw t.includes(`access_denied`)?Error(`Device-flow authorization was denied.`):t.includes(`expired_token`)||t.includes(`timeout`)||t.includes(`timed out`)?Error(`Device-flow code expired before authorization — please try again.`):Error(`GitHub sign-in failed: ${e.message}`)}throw e}return{token:s.token,tokenType:s.tokenType,scopes:s.scopes??[]}}function Ue(e){return process.env.OPEN_KNOWLEDGE_GITHUB_CLIENT_ID??e?.github?.oauthAppClientId??`Ov23liqlSd0V1MwR6rhI`}const We=new Set([`gitlab.com`,`bitbucket.org`,`codeberg.org`,`gitea.com`,`sr.ht`,`sourcehut.org`]);function Ge(e){let t=e.toLowerCase().replace(/:\d+$/,``);We.has(t)&&(process.stderr.write(`Error: ${e} is not a GitHub host. Only GitHub and GitHub Enterprise Server are supported.\n`),process.exit(1))}function Ke(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}async function qe(e,t,n,r=He){let i=Ue(n),{host:a,json:o}=e;Ge(a),o||process.stderr.write(`Logging in to ${a}…\n`);let s=await r({clientId:i,host:a===`github.com`?void 0:a,onVerification:e=>{e.userCode,e.verificationUri,o?Ke(!0,{type:`verification`,user_code:e.userCode,verification_uri:e.verificationUri,expires_in:e.expiresIn}):process.stderr.write(`Open: ${e.verificationUri}\nEnter code: ${e.userCode}\n`)}}),c=`unknown`,l,u;try{let e=a===`github.com`?`https://api.github.com`:`https://${a}/api/v3`,t=await fetch(`${e}/user`,{headers:{Authorization:`Bearer ${s.token}`,"User-Agent":`open-knowledge-cli`,Accept:`application/vnd.github+json`}});if(t.ok){let e=await t.json();c=e.login??c,l=e.name??void 0,u=e.email??void 0}}catch{}await t.set(a,c,s.token,{gitProtocol:`https`,name:l,email:u}),o?Ke(!0,{type:`complete`,host:a,login:c}):process.stderr.write(`✓ Logged in as ${c} on ${a}\n`)}function Je(e,t){return new w(`login`).description(`Authenticate with GitHub via Device Flow`).option(`--host <host>`,`GitHub or GitHub Enterprise hostname`,`github.com`).option(`--json`,`Output JSONL progress events`,!1).action(async n=>{await qe(n,await t(),e())})}async function Ye(e,t,n){let{host:r,json:i}=e;Ge(r);let a=await(n??(()=>he({message:`Enter PAT:`})))();a||(process.stderr.write(`No token provided
@@ -7,7 +7,7 @@ import{a as e,i as t}from"./constants-D6bAkegd.mjs";import{D as n,O as r,s as i}
7
7
  `),process.exit(1)}await t.set(r,c,a,{gitProtocol:`https`,name:l,email:u}),i?process.stdout.write(`${JSON.stringify({type:`complete`,host:r,login:c})}\n`):process.stderr.write(`✓ PAT stored for ${c} on ${r}\n`)}function Xe(e){return new w(`pat`).description(`Store a Personal Access Token`).option(`--host <host>`,`GitHub or GitHub Enterprise hostname`,`github.com`).option(`--json`,`Output JSON`,!1).action(async t=>{await Ye(t,await e())})}async function Ze(e,t){let{host:n,json:r}=e;Ge(n);let i=await t.get(n);i??(process.stderr.write(`Not logged in to ${n}\n`),process.exit(1));let a=n===`github.com`?void 0:`https://${n}/api/v3`,o=new ge({auth:i.token,...a?{baseUrl:a}:{}}),s=[];for await(let e of o.paginate.iterator(o.repos.listForAuthenticatedUser,{per_page:100,sort:`updated`}))for(let t of e.data)s.push({full_name:t.full_name,clone_url:t.clone_url,private:t.private});if(r)process.stdout.write(`${JSON.stringify({type:`repos`,host:n,repos:s})}\n`);else for(let e of s)process.stdout.write(`${e.full_name} ${e.clone_url}\n`)}function Qe(e){return new w(`repos`).description(`List accessible repositories`).option(`--host <host>`,`GitHub or GitHub Enterprise hostname`,`github.com`).option(`--json`,`Output JSON`,!1).action(async t=>{await Ze(t,await e())})}async function $e(e,t){let{host:n}=e;await t.clear(n),process.stderr.write(`✓ Signed out from ${n}\n`)}function et(e){return new w(`signout`).description(`Remove stored credentials`).option(`--host <host>`,`GitHub hostname`,`github.com`).action(async t=>{await $e(t,await e())})}async function tt(e,t){let{host:n,json:r}=e;Ge(n);let i=await t.get(n);i??(r?process.stdout.write(`${JSON.stringify({type:`status`,host:n,authenticated:!1})}\n`):process.stderr.write(`Not logged in to ${n}\n`),process.exit(1));let a=n===`github.com`?void 0:`https://${n}/api/v3`,o=new ge({auth:i.token,...a?{baseUrl:a}:{}});try{let{data:e}=await o.users.getAuthenticated();r?process.stdout.write(`${JSON.stringify({type:`status`,host:n,authenticated:!0,login:e.login,name:e.name,email:e.email})}\n`):process.stderr.write(`✓ Logged in as ${e.login} on ${n}\n`)}catch{r?process.stdout.write(JSON.stringify({type:`status`,host:n,authenticated:!1,error:`token invalid`})+`
8
8
  `):process.stderr.write(`✗ Token invalid for ${n}\n`),process.exit(1)}}function nt(e){return new w(`status`).description(`Show authentication status`).option(`--host <host>`,`GitHub or GitHub Enterprise hostname`,`github.com`).option(`--json`,`Output JSON`,!1).action(async t=>{await tt(t,await e())})}function rt(e){let t=new w(`auth`);t.description(`GitHub authentication management`);let n=()=>Le(),r=e??(()=>({}));return t.addCommand(Je(r,n)),t.addCommand(nt(n)),t.addCommand(Qe(n)),t.addCommand(et(n)),t.addCommand(Xe(n)),t.addCommand(Ve(n)),t}function it(e,t,n={}){let r=p(e,t);if(!D(r))return{status:`missing`,lockPath:r};let i;try{i=JSON.parse(k(r,`utf-8`))}catch{return{status:`corrupt`,lockPath:r}}if(!i||typeof i!=`object`||typeof i.pid!=`number`)return{status:`corrupt`,lockPath:r};let a=i,o=n.host??oe();return a.hostname===o?(n.isAlive??m)(a.pid)?{status:`alive`,lockPath:r,lock:a}:{status:`dead-pid`,lockPath:r,lock:a}:{status:`foreign-host`,lockPath:r,lock:a}}function at(e,t){let n=[];for(let[r,i]of[[`server`,e],[`ui`,t]])(i.status===`dead-pid`||i.status===`corrupt`)&&n.push({name:r,lockPath:i.lockPath,reason:i.status});return{prune:n}}function ot(e){let t=e.inspect??(t=>it(e.lockDir,t)),n=e.unlink??(e=>re(e)),r=e.log??(e=>console.log(e)),i=e.error??(e=>console.error(e)),a=at(t(`server`),t(`ui`));if(a.prune.length===0)return r(`No stale locks.`),{pruned:[],failed:[]};let o=[],s=[];for(let e of a.prune)try{n(e.lockPath),o.push(e)}catch(t){s.push({target:e,error:t instanceof Error?t.message:String(t)})}if(o.length>0){let e=o.map(e=>`${e.name} (${e.reason})`).join(`, `);r(`Pruned ${o.length} stale lock${o.length===1?``:`s`}: ${e}`)}return s.length>0&&i(`Failed to prune: ${s.map(({target:e,error:t})=>`${e.name} (${e.lockPath}): ${t}`).join(`; `)}`),{pruned:o,failed:s}}function st(e){return new w(`clean`).description(`Prune stale / corrupt open-knowledge lock files (never touches live locks)`).action(()=>{ot({lockDir:a(o(e(),process.cwd()))}).failed.length>0&&(process.exitCode=1)})}function ct(){try{let e=ye(`gh`,[`auth`,`token`],{encoding:`utf-8`,stdio:[`ignore`,`pipe`,`pipe`],timeout:5e3}).trim();return e.length===0?{available:!1}:{available:!0,token:e}}catch{return{available:!1}}}async function lt(e,t,n={},r=ct){if(!n.skipGhDetect&&r().available)return{tier:`A`,credentialArgs:[`-c`,`credential.helper=!gh auth git-credential`]};let i=await t.get(e);return i==null?{tier:`none`,credentialArgs:[]}:{tier:i.gitProtocol===`ssh`?`C`:`B`,credentialArgs:[`-c`,`credential.helper=!open-knowledge auth git-credential`]}}function ut(e){return e.replace(/:\d+$/,``)}function dt(e){let t=e.trim();if(!t)return null;{let e=/^https?:\/\/([^/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`https`,hostname:ut(e[1]),owner:e[2],name:e[3]}}{let e=/^ssh:\/\/(?:[\w.-]+@)?([^/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`ssh`,hostname:ut(e[1]),owner:e[2],name:e[3]}}{let e=/^git:\/\/([^/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`git`,hostname:ut(e[1]),owner:e[2],name:e[3]}}{let e=/^(?:[\w.-]+@)?([\w.-]+):([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?$/.exec(t);if(e?.[1].includes(`.`)||e&&t.startsWith(`git@`))return{protocol:`ssh`,hostname:e[1],owner:e[2],name:e[3]}}{let e=/^git:([\w.-]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`git`,hostname:e[1],owner:e[2],name:e[3]}}if(!t.includes(`://`)&&!t.includes(`@`)&&!t.startsWith(`/`)){let e=/^([\w.-]+)\/([\w.\-~%]+?)(?:\.git)?$/.exec(t);if(e)return{protocol:`https`,hostname:`github.com`,owner:e[1],name:e[2]}}return null}const ft=[[`count`,0,10],[`compress`,10,20],[`receiv`,20,60],[`resolv`,60,100]];function pt(e){let t=/^([\w ]+):\s+(\d+)%/.exec(e.trim());if(!t)return null;let n=t[1].toLowerCase(),r=Number(t[2]);for(let[e,i,a]of ft)if(n.includes(e))return{stage:t[1],pct:Math.round(i+r/100*(a-i))};return null}function mt(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}async function ht(e,t,n,r=process.cwd()){let i=dt(e);if(!i)throw Error(`Invalid git URL: ${e}`);let a=t.dir?A(r,t.dir):A(r,i.name);if(D(a)&&te(a).length>0)throw Error(`Target directory is not empty: ${a}`);let o=await Le(),s=await lt(i.hostname,o,{}),c=xe({baseDir:r,config:s.credentialArgs.length>=2?[s.credentialArgs[1]]:[],unsafe:{allowUnsafeCredentialHelper:!0}}).env({GIT_TERMINAL_PROMPT:`0`}),l=-1;if(c.outputHandler((e,n,r)=>{r.on(`data`,e=>{let n=e.toString(`utf-8`);for(let e of n.split(`
9
9
  `)){let n=pt(e);n&&n.pct!==l&&(l=n.pct,mt(t.json,{type:`progress`,pct:n.pct,stage:n.stage}),t.json||process.stderr.write(`\r Cloning… ${n.pct}%`))}})}),await c.clone(e,a,[`--progress`]),t.json||process.stderr.write(`
10
- `),!D(A(a,`.open-knowledge`)))try{let[{runInit:e},{ensureOkGitignoredAtRoot:t}]=await Promise.all([import(`./init-CBXekJ0k.mjs`),import(`./init-BY4cw3Zr.mjs`)]);e({cwd:a,mcp:!1});try{t(a)}catch{}}catch{}return a}function gt(e){return new w(`clone`).description(`Clone a git repository and open it`).argument(`<url>`,`Repository URL or owner/repo shorthand`).argument(`[dir]`,`Target directory (default: ./<repo-name>)`).option(`--json`,`Output JSONL progress events`,!1).action(async(t,n,r)=>{let i=e();try{let a=await ht(t,{json:r.json,dir:n},i);if(r.json)mt(!0,{type:`complete`,dir:a});else{process.stderr.write(`✓ Cloned to ${a}\n`),process.chdir(a);let{startCommand:t}=await import(`./start-DtvE4FeJ.mjs`);await t(e).parseAsync([],{from:`user`})}}catch(e){let t=e instanceof Error?e.message:String(e);r.json?mt(!0,{type:`error`,message:t}):process.stderr.write(`✗ ${t}\n`),process.exitCode=1}})}var _t=class e{sessionId;corrId;component;constructor(e=`mcp`,t){this.sessionId=t??ve().slice(0,12),this.corrId=ve().slice(0,8),this.component=e}info(e,t={}){this.emit(`info`,e,t)}warn(e,t={}){this.emit(`warn`,e,t)}error(e,t,n={}){let r=t?{error:t instanceof Error?t.message:String(t),...n}:n;this.emit(`error`,e,r)}debug(e,t={}){(process.env.MCP_DEBUG===`1`||process.env.DEBUG?.includes(`mcp`))&&this.emit(`debug`,e,t)}child(t){return new e(t??this.component,this.sessionId)}asCallback(){return e=>this.info(e)}emit(e,t,n){let r={ts:new Date().toISOString(),level:e,sessionId:this.sessionId,corrId:this.corrId,component:this.component,msg:t,...n},i=`${JSON.stringify(r)}\n`;process.stderr.write(i);let a=process.env.OK_LOG_FILE;if(a)try{T(a,i)}catch(e){console.warn(`[mcp-logger] Failed to write to OK_LOG_FILE: ${e instanceof Error?e.message:e}`)}}};function vt(e=`mcp`){return new _t(e)}const M="Absolute host path to resolve the request against. Defaults only when the MCP client advertises exactly one root; otherwise pass `cwd` explicitly.";function N(e,t){return{content:[{type:`text`,text:e}],...t?{isError:!0}:{}}}function P(e,t,n){return{content:[{type:`text`,text:e}],structuredContent:t,...n?{isError:!0}:{}}}const F="Error: Hocuspocus server is not running. Start it with `open-knowledge start`, then retry.\nFor disk-only writes without real-time sync, use your native Edit tool directly.";async function yt(e,t){return typeof e==`function`?await e(t):e}async function bt(e,t){return typeof e==`function`?await e(t):e}async function I(e,t,n){let r;try{r=await e(n)}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}try{let e=await bt(t,r);return{ok:!0,cwd:r,config:e}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}}async function L(e,t,n,r){let i=await I(e,t,r);if(!i.ok)return i;let{cwd:a,config:o}=i;try{return{ok:!0,cwd:a,config:o,url:await yt(n,a)}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}}function R(e){let t=e.toLowerCase();return t.endsWith(`.md`)?{ok:!0,docName:e.slice(0,-3)}:t.endsWith(`.mdx`)?{ok:!0,docName:e.slice(0,-4)}:t.endsWith(`.markdown`)?{ok:!1,error:`Error: docName "${e}" ends in ".markdown", which is not a supported extension. Use ".md" or ".mdx", or strip the extension to let the server auto-detect.`}:{ok:!0,docName:e}}async function z(e,t){let n;try{n=await fetch(`${e}${t}`,{signal:AbortSignal.timeout(3e4)})}catch(e){return{ok:!1,error:`Server unreachable: ${e instanceof Error?e.message:e}`}}try{return await n.json()}catch{return{ok:!1,error:`Server returned HTTP ${n.status} with non-JSON body`}}}async function B(e,t,n){let r;try{r=await fetch(`${e}${t}`,{method:`POST`,headers:{"Content-Type":`application/json`},body:n?JSON.stringify(n):void 0,signal:AbortSignal.timeout(3e4)})}catch(e){return{ok:!1,error:`Server unreachable: ${e instanceof Error?e.message:e}`}}try{return await r.json()}catch{return{ok:!1,error:`Server returned HTTP ${r.status} with non-JSON body`}}}function xt(e,t){return`Promote existing research on this topic into a canonical article inside the project content directory. **Canonical, not provisional** — the output is the source of truth for future agents.
10
+ `),!D(A(a,`.open-knowledge`)))try{let[{runInit:e},{ensureOkGitignoredAtRoot:t}]=await Promise.all([import(`./init-B6g8iwyX.mjs`),import(`./init-CyxGRu4t.mjs`)]);e({cwd:a,mcp:!1});try{t(a)}catch{}}catch{}return a}function gt(e){return new w(`clone`).description(`Clone a git repository and open it`).argument(`<url>`,`Repository URL or owner/repo shorthand`).argument(`[dir]`,`Target directory (default: ./<repo-name>)`).option(`--json`,`Output JSONL progress events`,!1).action(async(t,n,r)=>{let i=e();try{let a=await ht(t,{json:r.json,dir:n},i);if(r.json)mt(!0,{type:`complete`,dir:a});else{process.stderr.write(`✓ Cloned to ${a}\n`),process.chdir(a);let{startCommand:t}=await import(`./start-BPpXybFr.mjs`);await t(e).parseAsync([],{from:`user`})}}catch(e){let t=e instanceof Error?e.message:String(e);r.json?mt(!0,{type:`error`,message:t}):process.stderr.write(`✗ ${t}\n`),process.exitCode=1}})}var _t=class e{sessionId;corrId;component;constructor(e=`mcp`,t){this.sessionId=t??ve().slice(0,12),this.corrId=ve().slice(0,8),this.component=e}info(e,t={}){this.emit(`info`,e,t)}warn(e,t={}){this.emit(`warn`,e,t)}error(e,t,n={}){let r=t?{error:t instanceof Error?t.message:String(t),...n}:n;this.emit(`error`,e,r)}debug(e,t={}){(process.env.MCP_DEBUG===`1`||process.env.DEBUG?.includes(`mcp`))&&this.emit(`debug`,e,t)}child(t){return new e(t??this.component,this.sessionId)}asCallback(){return e=>this.info(e)}emit(e,t,n){let r={ts:new Date().toISOString(),level:e,sessionId:this.sessionId,corrId:this.corrId,component:this.component,msg:t,...n},i=`${JSON.stringify(r)}\n`;process.stderr.write(i);let a=process.env.OK_LOG_FILE;if(a)try{T(a,i)}catch(e){console.warn(`[mcp-logger] Failed to write to OK_LOG_FILE: ${e instanceof Error?e.message:e}`)}}};function vt(e=`mcp`){return new _t(e)}const M="Absolute host path to resolve the request against. Defaults only when the MCP client advertises exactly one root; otherwise pass `cwd` explicitly.";function N(e,t){return{content:[{type:`text`,text:e}],...t?{isError:!0}:{}}}function P(e,t,n){return{content:[{type:`text`,text:e}],structuredContent:t,...n?{isError:!0}:{}}}const F="Error: Hocuspocus server is not running. Start it with `open-knowledge start`, then retry.\nFor disk-only writes without real-time sync, use your native Edit tool directly.";async function yt(e,t){return typeof e==`function`?await e(t):e}async function bt(e,t){return typeof e==`function`?await e(t):e}async function I(e,t,n){let r;try{r=await e(n)}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}try{let e=await bt(t,r);return{ok:!0,cwd:r,config:e}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}}async function L(e,t,n,r){let i=await I(e,t,r);if(!i.ok)return i;let{cwd:a,config:o}=i;try{return{ok:!0,cwd:a,config:o,url:await yt(n,a)}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}}function R(e){let t=e.toLowerCase();return t.endsWith(`.md`)?{ok:!0,docName:e.slice(0,-3)}:t.endsWith(`.mdx`)?{ok:!0,docName:e.slice(0,-4)}:t.endsWith(`.markdown`)?{ok:!1,error:`Error: docName "${e}" ends in ".markdown", which is not a supported extension. Use ".md" or ".mdx", or strip the extension to let the server auto-detect.`}:{ok:!0,docName:e}}async function z(e,t){let n;try{n=await fetch(`${e}${t}`,{signal:AbortSignal.timeout(3e4)})}catch(e){return{ok:!1,error:`Server unreachable: ${e instanceof Error?e.message:e}`}}try{return await n.json()}catch{return{ok:!1,error:`Server returned HTTP ${n.status} with non-JSON body`}}}async function B(e,t,n){let r;try{r=await fetch(`${e}${t}`,{method:`POST`,headers:{"Content-Type":`application/json`},body:n?JSON.stringify(n):void 0,signal:AbortSignal.timeout(3e4)})}catch(e){return{ok:!1,error:`Server unreachable: ${e instanceof Error?e.message:e}`}}try{return await r.json()}catch{return{ok:!1,error:`Server returned HTTP ${r.status} with non-JSON body`}}}function xt(e,t){return`Promote existing research on this topic into a canonical article inside the project content directory. **Canonical, not provisional** — the output is the source of truth for future agents.
11
11
 
12
12
  Topic: ${e}
13
13
 
@@ -590,6 +590,6 @@ Folder metadata lives in \`config.yml\`, **not** in content files — this is in
590
590
  ${Object.entries(ti).map(([e,t])=>`### \`${e}\`\n${t}`).join(`
591
591
 
592
592
  `)}
593
- `}async function ci(e,t){try{let t=e.replace(`ws://`,`http://`).replace(`wss://`,`https://`);return(await fetch(`${t}/api/agent-undo-status`,{signal:AbortSignal.timeout(2e3)})).ok}catch(n){return t.warn(`Hocuspocus probe failed`,{serverUrl:e,error:n instanceof Error?n.message:String(n)}),!1}}async function li(n){let{projectDir:r,serverUrl:i,config:a,startupConfig:o,bypassProjectSelection:s=!1}=n;if(X=vt(),X.info(`MCP server starting`,{startupCwd:r,bypassProjectSelection:s,serverUrlType:typeof i==`string`?`explicit`:`lazy`}),typeof i==`string`){let e=await ci(i,X);X.info(`Hocuspocus detection complete`,{serverUrl:i,available:e})}else X.info(`server discovery is lazy per effective cwd`);let c=new Oe({name:t,version:e},{instructions:si(o,{dynamicConfig:typeof a==`function`&&!s})}),l=ai({startupCwd:r,bypassProjectSelection:s,listRoots:()=>c.server.listRoots(),logger:X}),u=oi({startupCwd:r,resolveCwd:l.resolveCwd,bypassProjectSelection:s}),d=u.resolveCwdForTools;c.server.setNotificationHandler(Ae,async()=>{l.invalidateRoots()});let f=async e=>{if(typeof i==`string`)return i.replace(`ws://`,`http://`).replace(`wss://`,`https://`);let t=e??await d();return(typeof i==`function`?await i(t):i)?.replace(`ws://`,`http://`).replace(`wss://`,`https://`)},p=ve(),m=process.env.AGENT_LABEL||void 0,h={current:{connectionId:p,label:m,displayName:m??`Agent`,colorSeed:m??p}};c.server.oninitialized=()=>{let e=c.server.getClientVersion();h.current={connectionId:p,clientInfo:e?{name:e.name,version:e.version}:void 0,label:m,displayName:m??e?.name??`Agent`,colorSeed:m??e?.name??p},X?.info(`agent identity established`,{displayName:h.current.displayName,connectionId:p.slice(0,8),clientName:e?.name})},ni(c,{serverUrl:f,resolveCwd:d,config:a,identityRef:h,logger:X});let g=new ke;await c.connect(g),X.info(`MCP server running on stdio`);let{startKeepalive:_}=await import(`./keepalive-BI3oBFIq.mjs`),v=_({resolveWsUrl:async()=>{let e=await u.getKeepaliveCwd();if(!e)return;let t=await f(e);if(t)return t.replace(/^http:/,`ws:`).replace(/^https:/,`wss:`)},logger:X.child(`keepalive`)}),y=e=>{X?.info(`MCP server shutting down`,{signal:e});try{v.close()}catch{}process.exit(0)};process.on(`SIGINT`,()=>y(`SIGINT`)),process.on(`SIGTERM`,()=>y(`SIGTERM`))}function ui(e){if(e===void 0||e===``)return;let t=Number.parseInt(e,10);if(!(Number.isNaN(t)||t<=0))return t}function di(e){if(e.portOverride!==void 0){let t=Number.parseInt(e.portOverride,10);if(Number.isNaN(t))return{action:`disk-only`,message:`invalid --port value '${e.portOverride}' — disk-only mode`};if(t>0){let n=`ws://${e.host}:${t}`;return{action:`connect`,url:n,message:`using --port override, connecting to ${n}`}}return{action:`disk-only`,message:`--port=0 — disk-only mode`}}let t=e.readLock();if(t&&t.port>0&&e.isAlive(t.pid)){let e=`ws://localhost:${t.port}`;return{action:`connect`,url:e,message:`connected to running instance at ${e} (pid ${t.pid})`}}return e.envAutoStart===`0`?{action:`disk-only`,message:`auto-spawn disabled via OK_MCP_AUTOSTART=0 — disk-only mode`}:e.configAutoStart?t?{action:`spawn`,message:`existing lock is not usable (port=${t.port}, pid=${t.pid}) — spawning ok start`}:{action:`spawn`,message:`no running instance — spawning ok start`}:{action:`disk-only`,message:`auto-spawn disabled via config.mcp.autoStart=false — disk-only mode`}}async function fi(e){let t=e.readLock??(()=>h(e.lockDir)),n=e.isAlive??m,r=e.sleep??(e=>new Promise(t=>setTimeout(t,e))),i=e.spawn??be,a=e.readErrorLog??(e=>D(e)?k(e,`utf-8`).trim():``),o=e.openErrorLog??(e=>ee(e,`w`)),s=e.closeFd??(e=>E(e)),c=e.timeoutMs??5e3,l=e.pollIntervalMs??100,u=di({host:e.host,portOverride:e.portOverride,envAutoStart:e.envAutoStart,configAutoStart:e.configAutoStart,readLock:t,isAlive:n});if(e.logger?.info(`auto-start decision`,{action:u.action,message:u.message,contentDir:e.contentDir}),u.action===`connect`)return{serverUrl:u.url,message:u.message};if(u.action===`disk-only`)return{serverUrl:void 0,message:u.message};D(e.lockDir)||O(e.lockDir,{recursive:!0});let d=ue(e.lockDir,`last-spawn-error.log`),f=o(d),p,g,_=C();e.logger?.info(`spawning server`,{command:_.command,cwd:e.contentDir,timeoutMs:c});try{try{p=i(_.command,[..._.prefixArgs,`start`],{detached:!0,stdio:[`ignore`,`ignore`,f],cwd:e.contentDir}),p.on(`error`,e=>{g=e instanceof Error?e.message:String(e)}),p.unref()}catch(e){g=e instanceof Error?e.message:String(e)}}finally{try{s(f)}catch{}}let v=Date.now()+c;for(;Date.now()<v;){if(g){let t=a(d);throw e.logger?.error(`spawn failed`,void 0,{error:g,stderr:t}),Error(`Error: spawn failed: ${g}${t?` stderr:\n${t}`:``}`)}await r(l);let i=t();if(i&&i.port>0&&n(i.pid)){let t=`ws://localhost:${i.port}`;return e.logger?.info(`server ready after spawn`,{url:t,pid:i.pid}),{serverUrl:t,message:`spawned ok start; connected at ${t} (pid ${i.pid})`}}}if(g){let t=a(d);throw e.logger?.error(`spawn failed (post-deadline)`,void 0,{error:g,stderr:t}),Error(`Error: spawn failed: ${g}${t?` stderr:\n${t}`:``}`)}let y=a(d),b=(c/1e3).toFixed(c%1e3==0?0:2),x=p?.pid,S=``;throw typeof x==`number`&&(S=n(x)?` child pid=${x} is still running — raise OK_MCP_SPAWN_TIMEOUT_MS if this is a slow boot.`:` child pid=${x} exited — check last-spawn-error.log.`),e.logger?.error(`spawn poll timeout`,void 0,{timeoutMs:c,childPid:x,childAlive:typeof x==`number`?n(x):void 0,stderr:y||void 0}),Error(`Error: server did not start within ${b}s.${S}${y?` stderr:\n${y}`:``}`)}function pi(e){if(e.portOverride!==void 0){let t=Number.parseInt(e.portOverride,10);if(Number.isNaN(t)||t<=0)return async()=>void 0;let n=`ws://${e.host}:${t}`;return async()=>n}let t=e.ensureServerRunningFn??fi,n=e.cacheMs??1e3,r=new Map,i=new Map;return async s=>{let c=await y(s??e.startupCwd),l=Date.now(),u=r.get(c);if(u&&u.expiresAt>l)return e.logger?.debug(`server url cache hit`,{cwd:c,url:u.url}),u.url;let d=i.get(c);if(d)return e.logger?.debug(`server url resolution pending`,{cwd:c}),await d;e.logger?.debug(`server url cache miss`,{cwd:c});let f=(async()=>{let i=await e.resolveConfig(c),s=o(i,c),l=a(s),u=e.readLock,d=u?()=>u(l):void 0,f=await t({lockDir:l,contentDir:s,host:i.server.host,portOverride:void 0,envAutoStart:e.envAutoStart,configAutoStart:i.mcp.autoStart,logger:e.logger,timeoutMs:e.timeoutMs,pollIntervalMs:e.pollIntervalMs,spawn:e.spawn,readLock:d,isAlive:e.isAlive,sleep:e.sleep,readErrorLog:e.readErrorLog,openErrorLog:e.openErrorLog,closeFd:e.closeFd});return r.set(c,{url:f.serverUrl,expiresAt:Date.now()+n}),f.serverUrl})();i.set(c,f);try{return await f}finally{i.delete(c)}}}function mi(e){return new w(`mcp`).description(`Start MCP stdio server for project knowledge base`).option(`-p, --port <port>`,`Override port discovery and connect to this port (0 = disk-only)`,void 0).action(async t=>{try{let n=e(),r=process.cwd(),i=x({startupCwd:r,startupConfig:n}),a=ui(process.env.OK_MCP_SPAWN_TIMEOUT_MS),o,s;if(t.port!==void 0){let e=Number.parseInt(t.port,10);Number.isNaN(e)?(o=void 0,s=`invalid --port value '${t.port}' — disk-only mode`):e>0?(o=`ws://${n.server.host}:${e}`,s=`using --port override, connecting to ${o}`):(o=void 0,s=`--port=0 — disk-only mode`)}else o=pi({startupCwd:r,resolveConfig:i,host:n.server.host,portOverride:void 0,envAutoStart:process.env.OK_MCP_AUTOSTART,timeoutMs:a}),s=`project server discovery/autostart is lazy per effective cwd`;process.stderr.write(`[mcp] ${s}\n`),await li({projectDir:r,serverUrl:o,config:i,startupConfig:n,bypassProjectSelection:t.port!==void 0})}catch(e){process.stderr.write(`MCP server failed to start: ${e instanceof Error?e.message:String(e)}\n`),process.exitCode=1}})}function hi(e){return new w(`preview`).description(`Show what content the watcher will track (read-only)`).action(async()=>{let{previewContent:t,formatPreviewBlock:n}=await import(`./preview-rUPh_bsX.mjs`),r=e(),i=process.cwd(),a=o(r,i),s;try{s=t({projectDir:i,contentDir:a,include:r.content.include,exclude:r.content.exclude})}catch(e){console.error(`Content preview failed: ${e instanceof Error?e.message:String(e)}`),process.exitCode=1;return}process.stdout.write(`${n(s,i)}\n`),s.totalCount===0&&s.warnings.length>0&&(process.exitCode=1)})}function Z(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}async function gi(e,t,n=process.cwd()){let r=e.op??`sync`,i=h(a(o(t,n)));if(i&&i.port>0){let t=`http://127.0.0.1:${i.port}/api/sync/trigger`;e.json||process.stderr.write(`Triggering ${r} via running server (port ${i.port})…\n`);try{let n=await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({op:r})});if(!n.ok){let e=await n.json().catch(()=>({}));throw Error(e.error??`Server responded with ${n.status}`)}Z(e.json,{type:`triggered`,op:r,port:i.port}),e.json||process.stderr.write(`✓ ${r} triggered\n`);return}catch(t){let n=t instanceof Error?t.message:String(t);e.json||process.stderr.write(`Server trigger failed (${n}), running directly…\n`)}}e.json||process.stderr.write(`Running ${r} directly (no live server)…\n`);let s=xe({baseDir:n});if(r===`sync`||r===`pull`){Z(e.json,{type:`step`,step:`pull`});let t=await s.pull();Z(e.json,{type:`pull`,summary:t.summary}),e.json||process.stderr.write(` pull: ${t.summary.changes} changes\n`)}(r===`sync`||r===`push`)&&(Z(e.json,{type:`step`,step:`push`}),await s.push(),Z(e.json,{type:`push`,ok:!0}),e.json||process.stderr.write(` push: ok
594
- `)),Z(e.json,{type:`complete`,op:r}),e.json||process.stderr.write(`✓ ${r} complete\n`)}function _i(e){return new w(`sync`).description(`Commit, pull, and push to the remote`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{try{await gi({json:t.json,op:`sync`},e())}catch(e){let n=e instanceof Error?e.message:String(e);t.json?process.stdout.write(`${JSON.stringify({type:`error`,message:n})}\n`):process.stderr.write(`✗ sync failed: ${n}\n`),process.exit(1)}})}function vi(e){return new w(`pull`).description(`Pull changes from the remote`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{try{await gi({json:t.json,op:`pull`},e())}catch(e){let n=e instanceof Error?e.message:String(e);t.json?process.stdout.write(`${JSON.stringify({type:`error`,message:n})}\n`):process.stderr.write(`✗ pull failed: ${n}\n`),process.exit(1)}})}function yi(e){return new w(`push`).description(`Push commits to the remote`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{try{await gi({json:t.json,op:`push`},e())}catch(e){let n=e instanceof Error?e.message:String(e);t.json?process.stdout.write(`${JSON.stringify({type:`error`,message:n})}\n`):process.stderr.write(`✗ push failed: ${n}\n`),process.exit(1)}})}function bi(e,t){return{server:xi(`server`,e),ui:xi(`ui`,t)}}function xi(e,t){switch(t.status){case`missing`:return{name:e,state:`missing`,alive:!1};case`corrupt`:return{name:e,state:`corrupt`,alive:!1};case`foreign-host`:return{name:e,state:`foreign-host`,pid:t.lock.pid,port:t.lock.port,startedAt:t.lock.startedAt,host:t.lock.hostname,alive:`unknown`};case`dead-pid`:return{name:e,state:`dead-pid`,pid:t.lock.pid,port:t.lock.port,startedAt:t.lock.startedAt,host:t.lock.hostname,alive:!1};case`alive`:return{name:e,state:`alive`,pid:t.lock.pid,port:t.lock.port,startedAt:t.lock.startedAt,host:t.lock.hostname,alive:!0}}}function Si(e){return`${Ci(e.server)}\n${Ci(e.ui)}`}function Ci(e){let t=e.name===`server`?`server`:`ui `;return e.state===`missing`?`${t} not running`:e.state===`corrupt`?`${t} lock file corrupt — run \`ok clean\``:e.state===`foreign-host`?`${t} foreign host (${e.host}) pid=${e.pid} port=${e.port}`:e.state===`dead-pid`?`${t} stale (dead pid=${e.pid}) — run \`ok clean\``:`${t} alive pid=${e.pid} port=${e.port} started=${e.startedAt}`}function wi(e){let t=e.inspect??(t=>it(e.lockDir,t)),n=e.log??(e=>console.log(e)),r=bi(t(`server`),t(`ui`));return e.json?n(JSON.stringify(r,null,2)):n(Si(r)),r}function Ti(e){return new w(`status`).description(`Show live state of the server + ui lockfiles for this project`).option(`--json`,`Emit structured JSON instead of formatted text`).action(t=>{wi({lockDir:a(o(e(),process.cwd())),json:t.json===!0})})}function Ei(e,t){let n=[];return e.status===`alive`&&n.push({name:`server`,pid:e.lock.pid,port:e.lock.port}),t.status===`alive`&&n.push({name:`ui`,pid:t.lock.pid,port:t.lock.port}),{targets:n}}function Di(e){let t=e.inspect??(t=>it(e.lockDir,t)),n=e.kill??((e,t)=>process.kill(e,t)),r=e.log??(e=>console.log(e)),i=e.error??(e=>console.error(e)),a=Ei(t(`server`),t(`ui`));if(a.targets.length===0)return r(`No running open-knowledge processes.`),{stopped:[],failed:[],hadTargets:!1};let o=[],s=[];for(let e of a.targets)try{n(e.pid,`SIGTERM`),o.push(e)}catch(t){s.push({target:e,error:t instanceof Error?t.message:String(t)})}return o.length>0&&r(`Stopped: ${o.map(e=>`${e.name} (pid=${e.pid}, port=${e.port})`).join(`, `)}`),s.length>0&&i(`Failed to stop: ${s.map(({target:e,error:t})=>`${e.name} (pid=${e.pid}): ${t}`).join(`; `)}`),{stopped:o,failed:s,hadTargets:!0}}function Oi(e){return new w(`stop`).description(`Stop the running open-knowledge server and UI (live only)`).action(()=>{Di({lockDir:a(o(e(),process.cwd()))}).failed.length>0&&(process.exitCode=1)})}const ki=1e4,Ai=[`connection`,`keep-alive`,`proxy-authenticate`,`proxy-authorization`,`te`,`trailer`,`transfer-encoding`,`upgrade`,`cookie`,`set-cookie`];async function ji(e){let t=e.upstreamTimeoutMs??ki,n=Te((n,r)=>{Ni(n,r,e.upstreamHost,e.upstreamPort,t)});await new Promise((t,r)=>{let i=e=>r(e);n.once(`error`,i),n.listen(e.listenPort,e.host,()=>{n.off(`error`,i),t()})});let r=n.address();return{httpServer:n,port:typeof r==`object`&&r?r.port:e.listenPort,close:()=>new Promise(e=>{n.close(()=>e())})}}function Mi(e,t,n){Ni(e,t,n.upstreamHost,n.upstreamPort,n.upstreamTimeoutMs??ki)}function Ni(e,t,n,r,i){let a={...e.headers};delete a.host;for(let e of Ai)delete a[e];e.setTimeout(3e4,()=>{if(t.headersSent)try{t.end()}catch{}else try{t.writeHead(408,{"Content-Type":`text/plain`}),t.end(`Request Timeout`)}catch{}try{e.socket?.destroy()}catch{}});let o=Ee({host:n,port:r,method:e.method,path:e.url,headers:{...a,host:`${n}:${r}`}},e=>{let n={...e.headers};for(let e of Ai)delete n[e];t.writeHead(e.statusCode??502,n),e.pipe(t),e.once(`error`,()=>{try{t.end()}catch{}})});i>0&&o.setTimeout(i,()=>{if(!t.headersSent)t.writeHead(504,{"Content-Type":`text/plain`}),t.end(`Gateway Timeout`);else try{t.end()}catch{}o.destroy()}),o.on(`error`,()=>{if(!t.headersSent)t.writeHead(502,{"Content-Type":`text/plain`}),t.end(`Bad Gateway`);else try{t.end()}catch{}}),e.on(`error`,()=>{o.destroy()}),e.pipe(o)}async function Pi(e){await Promise.all(e.map(e=>new Promise(t=>{e.close(()=>t())})))}async function Fi(e){let{existsSync:t}=await import(`node:fs`),{createServer:n}=await import(`node:http`),{resolve:r}=await import(`node:path`),{acquireUiLock:a,readServerLock:o,releaseUiLock:s,updateUiLockPort:c}=await import(`./src-DCuvj6a2.mjs`),{default:l}=await import(`sirv`),{resolveContentDir:u,resolveLockDir:d}=await import(`./paths-CP2voPwK.mjs`),f=u(e.config,e.cwd),p=d(f);a(p,{port:0,worktreeRoot:e.cwd});let m=import.meta.dirname??new URL(`.`,import.meta.url).pathname,h=[r(m,`public`),r(m,`../../app/dist`),r(m,`../../../app/dist`)].find(e=>t(e)),g=h?l(h,{single:!0,gzip:!0,immutable:!0}):null,_=t(f)?l(f,{dotfiles:!1,dev:!0}):null,v=e.port,y=null,b=(e,t)=>{let n=e.url?.split(`?`)[0];if(n===`/api/config`&&(e.method===`GET`||e.method===`HEAD`)){y?.();let n=o(p),r=n&&n.port>0?`ws://localhost:${n.port}/collab`:null,i=JSON.stringify({collabUrl:r,previewUrl:null,port:v});t.setHeader(`Content-Type`,`application/json`),t.setHeader(`Cache-Control`,`no-store`),t.setHeader(`X-Content-Type-Options`,`nosniff`),t.statusCode=200,e.method===`HEAD`?t.end():t.end(i);return}if(n?.startsWith(`/api/`)){y?.();let r=o(p);if(!r||r.port<=0){t.writeHead(503,{"Content-Type":`application/json`,"Cache-Control":`no-store`}),t.end(JSON.stringify({error:"Collab server not running. Start `ok start` or run `ok status`.",path:n}));return}Mi(e,t,{upstreamHost:`localhost`,upstreamPort:r.port});return}if(decodeURIComponent(n?.replace(/^\//,``)??``)&&_){t.setHeader(`X-Content-Type-Options`,`nosniff`),_(e,t,()=>{g?g(e,t):Ii(t)});return}if(g){g(e,t);return}Ii(t)},x=e.host===void 0?[`::1`,`127.0.0.1`]:[e.host],S=[],C=e.port;try{for(let e of x){let t=n(b);S.push(t),await new Promise((n,r)=>{let i=e=>r(e);t.once(`error`,i),t.listen(C,e,()=>{t.off(`error`,i);let e=t.address();typeof e==`object`&&e&&(C=e.port),n()})})}}catch(e){await Promise.all(S.map(e=>new Promise(t=>{try{e.close(()=>t())}catch{t()}})));try{s(p)}catch{}throw e}let w=C;v=w,c(p,w);let T=e.scheduler??i,E=e.safetyNetMs??432e5,D=null,O=!1,ee=!1,k=()=>{O||(O=!0,D!==null&&(T.clearTimeout(D),D=null))},te=()=>{if(k(),!ee){ee=!0;try{s(p)}catch{}}},ne=()=>{O||E<=0||(D!==null&&(T.clearTimeout(D),D=null),D=T.setTimeout(()=>{D=null,console.warn(`[ui] safety-net (${E}ms) reached — shutting down (D-025 backstop)`);try{e.onSafetyNet?.()}catch{}for(let e of S)try{e.close()}catch{}te()},E))},re=()=>{O||E<=0||ne()};return y=re,ne(),{httpServers:S,port:w,release:te,detachSafetyNet:k,nudgeSafetyNet:re}}function Ii(e){e.writeHead(404),e.end(`Not found`)}function Li(e,t){if(e!==void 0){let t=Number.parseInt(e,10);if(Number.isNaN(t)||t<0||t>65535)throw Error(`Invalid --port value '${e}'`);return t}if(t!==void 0&&t!==``){let e=Number.parseInt(t,10);if(Number.isNaN(e)||e<0||e>65535)throw Error(`Invalid PORT env value '${t}'`);return e}return 0}async function Ri(e){let t=e.readLock??(async()=>{let{readUiLock:t}=await import(`./src-DCuvj6a2.mjs`);return t(e.lockDir)}),n=await t();if(!n)throw Error(`UI lock collision reported but the lock disappeared before handling — retry acquiring.`);if(n.port===e.requestedPort&&n.port>0)return{mode:`already-running`,port:n.port};let r=n.port;if(r===0){let n=Date.now()+(e.pollDeadlineMs??2e3),i=e.pollIntervalMs??100;for(;Date.now()<n;){await new Promise(e=>{setTimeout(e,i)});let e=await t();if(e&&e.port>0){r=e.port;break}}if(r===0)throw Error("UI did not bind within 2s; run `ok clean`");if(r===e.requestedPort)return{mode:`already-running`,port:r}}return{mode:`proxy`,handle:await ji({listenPort:e.requestedPort,host:e.host,upstreamHost:`localhost`,upstreamPort:r}),upstreamPort:r}}function zi(e){return new w(`ui`).description(`Serve the Open Knowledge React editor UI`).option(`-p, --port <port>`,`UI port (default: $PORT env or 0 / kernel-allocated)`).option(`-H, --host <host>`,"UI host. Default: two-socket loopback bind (`[::1]` + `127.0.0.1`) so cross-family collisions fail loud (D-033). Pass an explicit host (e.g. `127.0.0.1`, `0.0.0.0`) to bind a single socket on that host.").action(async t=>{let{dim:n}=await import(`./colors-BNRrOlZZ.mjs`),{UiLockCollisionError:r}=await import(`./src-DCuvj6a2.mjs`),{resolveContentDir:i,resolveLockDir:a}=await import(`./paths-CP2voPwK.mjs`),o=e(),s=t.host,c;try{c=Li(t.port,process.env.PORT)}catch(e){console.error(e instanceof Error?e.message:String(e)),process.exitCode=1;return}try{let e=await Fi({config:o,cwd:process.cwd(),port:c,host:s}),t=s===void 0||s===`::`||s===`0.0.0.0`?`localhost`:s;console.log(`${n(`[ui]`)} listening on http://${t}:${e.port}`);let r=!1,i=t=>{if(r)return;r=!0,console.log(n(`\n[ui] Shutting down (${t})...`)),e.detachSafetyNet();let i=()=>{try{e.release()}finally{process.exit(process.exitCode??0)}};Pi(e.httpServers).then(i,i),setTimeout(i,2e3).unref()};process.once(`SIGINT`,()=>i(`SIGINT`)),process.once(`SIGTERM`,()=>i(`SIGTERM`));return}catch(e){if(!(e instanceof r))throw e;let t=a(i(o,process.cwd())),l=s??`localhost`,u;try{u=await Ri({requestedPort:c,host:l,lockDir:t})}catch(e){console.error(e instanceof Error?e.message:String(e)),process.exit(1)}u.mode===`already-running`&&(console.log(`UI already running at http://${l}:${u.port}`),process.exit(0)),console.log(`UI running at http://${l}:${u.upstreamPort}; acting as HTTP proxy on port ${u.handle.port}`);let d=!1,f=e=>{d||(d=!0,console.log(n(`\n[ui-proxy] Shutting down (${e})...`)),u.handle.close().finally(()=>process.exit(process.exitCode??0)),setTimeout(()=>process.exit(process.exitCode??0),2e3).unref())};process.once(`SIGINT`,()=>f(`SIGINT`)),process.once(`SIGTERM`,()=>f(`SIGTERM`))}})}process.argv.includes(`--no-color`)?(process.env.NO_COLOR=`1`,delete process.env.FORCE_COLOR):process.argv.includes(`--color`)&&(process.env.FORCE_COLOR=`1`,delete process.env.NO_COLOR);const Q=new w;let $;Q.name(`open-knowledge`).description(`Local-first knowledge base with CRDT collaboration`).version(e).option(`--cwd <path>`,`Working directory`).option(`--log-level <level>`,`Log level`,`info`).option(`--no-color`,`Disable color output`).option(`--color`,`Force color output`).hook(`preAction`,e=>{let t=e.opts(),n=t.cwd;n!==void 0&&process.chdir(n);let{config:r}=b(n),i=e.args.length===0?t:e.commands[0]?.opts()??{};i.port!==void 0&&(r.server.port=Number(i.port)),i.host!==void 0&&(r.server.host=i.host),process.env.PORT&&(r.server.port=Number(process.env.PORT)),process.env.HOST&&(r.server.host=process.env.HOST),$=r});const Bi=S(()=>$);Q.addCommand(Bi,{isDefault:!0});const Vi=mi(()=>$);Q.addCommand(Vi),Q.addCommand(v());const Hi=hi(()=>$);Q.addCommand(Hi);const Ui=zi(()=>$);Q.addCommand(Ui),Q.addCommand(Oi(()=>$)),Q.addCommand(st(()=>$)),Q.addCommand(Ti(()=>$)),Q.addCommand(rt(()=>$)),Q.addCommand(gt(()=>$)),Q.addCommand(_i(()=>$)),Q.addCommand(yi(()=>$)),Q.addCommand(vi(()=>$)),await Q.parseAsync();export{};
593
+ `}async function ci(e,t){try{let t=e.replace(`ws://`,`http://`).replace(`wss://`,`https://`);return(await fetch(`${t}/api/agent-undo-status`,{signal:AbortSignal.timeout(2e3)})).ok}catch(n){return t.warn(`Hocuspocus probe failed`,{serverUrl:e,error:n instanceof Error?n.message:String(n)}),!1}}async function li(n){let{projectDir:r,serverUrl:i,config:a,startupConfig:o,bypassProjectSelection:s=!1}=n;if(X=vt(),X.info(`MCP server starting`,{startupCwd:r,bypassProjectSelection:s,serverUrlType:typeof i==`string`?`explicit`:`lazy`}),typeof i==`string`){let e=await ci(i,X);X.info(`Hocuspocus detection complete`,{serverUrl:i,available:e})}else X.info(`server discovery is lazy per effective cwd`);let c=new Oe({name:t,version:e},{instructions:si(o,{dynamicConfig:typeof a==`function`&&!s})}),l=ai({startupCwd:r,bypassProjectSelection:s,listRoots:()=>c.server.listRoots(),logger:X}),u=oi({startupCwd:r,resolveCwd:l.resolveCwd,bypassProjectSelection:s}),d=u.resolveCwdForTools;c.server.setNotificationHandler(Ae,async()=>{l.invalidateRoots()});let f=async e=>{if(typeof i==`string`)return i.replace(`ws://`,`http://`).replace(`wss://`,`https://`);let t=e??await d();return(typeof i==`function`?await i(t):i)?.replace(`ws://`,`http://`).replace(`wss://`,`https://`)},p=ve(),m=process.env.AGENT_LABEL||void 0,h={current:{connectionId:p,label:m,displayName:m??`Agent`,colorSeed:m??p}};c.server.oninitialized=()=>{let e=c.server.getClientVersion();h.current={connectionId:p,clientInfo:e?{name:e.name,version:e.version}:void 0,label:m,displayName:m??e?.name??`Agent`,colorSeed:m??e?.name??p},X?.info(`agent identity established`,{displayName:h.current.displayName,connectionId:p.slice(0,8),clientName:e?.name})},ni(c,{serverUrl:f,resolveCwd:d,config:a,identityRef:h,logger:X});let g=new ke;await c.connect(g),X.info(`MCP server running on stdio`);let{startKeepalive:_}=await import(`./keepalive-BI3oBFIq.mjs`),v=_({resolveWsUrl:async()=>{let e=await u.getKeepaliveCwd();if(!e)return;let t=await f(e);if(t)return t.replace(/^http:/,`ws:`).replace(/^https:/,`wss:`)},logger:X.child(`keepalive`)}),y=e=>{X?.info(`MCP server shutting down`,{signal:e});try{v.close()}catch{}process.exit(0)};process.on(`SIGINT`,()=>y(`SIGINT`)),process.on(`SIGTERM`,()=>y(`SIGTERM`))}function ui(e){if(e===void 0||e===``)return;let t=Number.parseInt(e,10);if(!(Number.isNaN(t)||t<=0))return t}function di(e){if(e.portOverride!==void 0){let t=Number.parseInt(e.portOverride,10);if(Number.isNaN(t))return{action:`disk-only`,message:`invalid --port value '${e.portOverride}' — disk-only mode`};if(t>0){let n=`ws://${e.host}:${t}`;return{action:`connect`,url:n,message:`using --port override, connecting to ${n}`}}return{action:`disk-only`,message:`--port=0 — disk-only mode`}}let t=e.readLock();if(t&&t.port>0&&e.isAlive(t.pid)){let e=`ws://localhost:${t.port}`;return{action:`connect`,url:e,message:`connected to running instance at ${e} (pid ${t.pid})`}}return e.envAutoStart===`0`?{action:`disk-only`,message:`auto-spawn disabled via OK_MCP_AUTOSTART=0 — disk-only mode`}:e.configAutoStart?t?{action:`spawn`,message:`existing lock is not usable (port=${t.port}, pid=${t.pid}) — spawning ok start`}:{action:`spawn`,message:`no running instance — spawning ok start`}:{action:`disk-only`,message:`auto-spawn disabled via config.mcp.autoStart=false — disk-only mode`}}async function fi(e){let t=e.readLock??(()=>h(e.lockDir)),n=e.isAlive??m,r=e.sleep??(e=>new Promise(t=>setTimeout(t,e))),i=e.spawn??be,a=e.readErrorLog??(e=>D(e)?k(e,`utf-8`).trim():``),o=e.openErrorLog??(e=>ee(e,`w`)),s=e.closeFd??(e=>E(e)),c=e.timeoutMs??5e3,l=e.pollIntervalMs??100,u=di({host:e.host,portOverride:e.portOverride,envAutoStart:e.envAutoStart,configAutoStart:e.configAutoStart,readLock:t,isAlive:n});if(e.logger?.info(`auto-start decision`,{action:u.action,message:u.message,contentDir:e.contentDir}),u.action===`connect`)return{serverUrl:u.url,message:u.message};if(u.action===`disk-only`)return{serverUrl:void 0,message:u.message};D(e.lockDir)||O(e.lockDir,{recursive:!0});let d=ue(e.lockDir,`last-spawn-error.log`),f=o(d),p,g,_=C();e.logger?.info(`spawning server`,{command:_.command,cwd:e.contentDir,timeoutMs:c});try{try{p=i(_.command,[..._.prefixArgs,`start`],{detached:!0,stdio:[`ignore`,`ignore`,f],cwd:e.contentDir}),p.on(`error`,e=>{g=e instanceof Error?e.message:String(e)}),p.unref()}catch(e){g=e instanceof Error?e.message:String(e)}}finally{try{s(f)}catch{}}let v=Date.now()+c;for(;Date.now()<v;){if(g){let t=a(d);throw e.logger?.error(`spawn failed`,void 0,{error:g,stderr:t}),Error(`Error: spawn failed: ${g}${t?` stderr:\n${t}`:``}`)}await r(l);let i=t();if(i&&i.port>0&&n(i.pid)){let t=`ws://localhost:${i.port}`;return e.logger?.info(`server ready after spawn`,{url:t,pid:i.pid}),{serverUrl:t,message:`spawned ok start; connected at ${t} (pid ${i.pid})`}}}if(g){let t=a(d);throw e.logger?.error(`spawn failed (post-deadline)`,void 0,{error:g,stderr:t}),Error(`Error: spawn failed: ${g}${t?` stderr:\n${t}`:``}`)}let y=a(d),b=(c/1e3).toFixed(c%1e3==0?0:2),x=p?.pid,S=``;throw typeof x==`number`&&(S=n(x)?` child pid=${x} is still running — raise OK_MCP_SPAWN_TIMEOUT_MS if this is a slow boot.`:` child pid=${x} exited — check last-spawn-error.log.`),e.logger?.error(`spawn poll timeout`,void 0,{timeoutMs:c,childPid:x,childAlive:typeof x==`number`?n(x):void 0,stderr:y||void 0}),Error(`Error: server did not start within ${b}s.${S}${y?` stderr:\n${y}`:``}`)}function pi(e){if(e.portOverride!==void 0){let t=Number.parseInt(e.portOverride,10);if(Number.isNaN(t)||t<=0)return async()=>void 0;let n=`ws://${e.host}:${t}`;return async()=>n}let t=e.ensureServerRunningFn??fi,n=e.cacheMs??1e3,r=new Map,i=new Map;return async s=>{let c=await y(s??e.startupCwd),l=Date.now(),u=r.get(c);if(u&&u.expiresAt>l)return e.logger?.debug(`server url cache hit`,{cwd:c,url:u.url}),u.url;let d=i.get(c);if(d)return e.logger?.debug(`server url resolution pending`,{cwd:c}),await d;e.logger?.debug(`server url cache miss`,{cwd:c});let f=(async()=>{let i=await e.resolveConfig(c),s=o(i,c),l=a(s),u=e.readLock,d=u?()=>u(l):void 0,f=await t({lockDir:l,contentDir:s,host:i.server.host,portOverride:void 0,envAutoStart:e.envAutoStart,configAutoStart:i.mcp.autoStart,logger:e.logger,timeoutMs:e.timeoutMs,pollIntervalMs:e.pollIntervalMs,spawn:e.spawn,readLock:d,isAlive:e.isAlive,sleep:e.sleep,readErrorLog:e.readErrorLog,openErrorLog:e.openErrorLog,closeFd:e.closeFd});return r.set(c,{url:f.serverUrl,expiresAt:Date.now()+n}),f.serverUrl})();i.set(c,f);try{return await f}finally{i.delete(c)}}}function mi(e){return new w(`mcp`).description(`Start MCP stdio server for project knowledge base`).option(`-p, --port <port>`,`Override port discovery and connect to this port (0 = disk-only)`,void 0).action(async t=>{try{let n=e(),r=process.cwd(),i=x({startupCwd:r,startupConfig:n}),a=ui(process.env.OK_MCP_SPAWN_TIMEOUT_MS),o,s;if(t.port!==void 0){let e=Number.parseInt(t.port,10);Number.isNaN(e)?(o=void 0,s=`invalid --port value '${t.port}' — disk-only mode`):e>0?(o=`ws://${n.server.host}:${e}`,s=`using --port override, connecting to ${o}`):(o=void 0,s=`--port=0 — disk-only mode`)}else o=pi({startupCwd:r,resolveConfig:i,host:n.server.host,portOverride:void 0,envAutoStart:process.env.OK_MCP_AUTOSTART,timeoutMs:a}),s=`project server discovery/autostart is lazy per effective cwd`;process.stderr.write(`[mcp] ${s}\n`),await li({projectDir:r,serverUrl:o,config:i,startupConfig:n,bypassProjectSelection:t.port!==void 0})}catch(e){process.stderr.write(`MCP server failed to start: ${e instanceof Error?e.message:String(e)}\n`),process.exitCode=1}})}function hi(e){return new w(`preview`).description(`Show what content the watcher will track (read-only)`).action(async()=>{let{previewContent:t,formatPreviewBlock:n}=await import(`./preview-BGOwfgOL.mjs`),r=e(),i=process.cwd(),a=o(r,i),s;try{s=t({projectDir:i,contentDir:a,include:r.content.include,exclude:r.content.exclude})}catch(e){console.error(`Content preview failed: ${e instanceof Error?e.message:String(e)}`),process.exitCode=1;return}process.stdout.write(`${n(s,i)}\n`),s.totalCount===0&&s.warnings.length>0&&(process.exitCode=1)})}function Z(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}async function gi(e,t,n=process.cwd()){let r=e.op??`sync`,i=h(a(o(t,n)));if(i&&i.port>0){let t=`http://127.0.0.1:${i.port}/api/sync/trigger`;e.json||process.stderr.write(`Triggering ${r} via running server (port ${i.port})…\n`);try{let n=await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({op:r})});if(!n.ok){let e=await n.json().catch(()=>({}));throw Error(e.error??`Server responded with ${n.status}`)}Z(e.json,{type:`triggered`,op:r,port:i.port}),e.json||process.stderr.write(`✓ ${r} triggered\n`);return}catch(t){let n=t instanceof Error?t.message:String(t);e.json||process.stderr.write(`Server trigger failed (${n}), running directly…\n`)}}e.json||process.stderr.write(`Running ${r} directly (no live server)…\n`);let s=xe({baseDir:n});if(r===`sync`||r===`pull`){Z(e.json,{type:`step`,step:`pull`});let t=await s.pull();Z(e.json,{type:`pull`,summary:t.summary}),e.json||process.stderr.write(` pull: ${t.summary.changes} changes\n`)}(r===`sync`||r===`push`)&&(Z(e.json,{type:`step`,step:`push`}),await s.push(),Z(e.json,{type:`push`,ok:!0}),e.json||process.stderr.write(` push: ok
594
+ `)),Z(e.json,{type:`complete`,op:r}),e.json||process.stderr.write(`✓ ${r} complete\n`)}function _i(e){return new w(`sync`).description(`Commit, pull, and push to the remote`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{try{await gi({json:t.json,op:`sync`},e())}catch(e){let n=e instanceof Error?e.message:String(e);t.json?process.stdout.write(`${JSON.stringify({type:`error`,message:n})}\n`):process.stderr.write(`✗ sync failed: ${n}\n`),process.exit(1)}})}function vi(e){return new w(`pull`).description(`Pull changes from the remote`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{try{await gi({json:t.json,op:`pull`},e())}catch(e){let n=e instanceof Error?e.message:String(e);t.json?process.stdout.write(`${JSON.stringify({type:`error`,message:n})}\n`):process.stderr.write(`✗ pull failed: ${n}\n`),process.exit(1)}})}function yi(e){return new w(`push`).description(`Push commits to the remote`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{try{await gi({json:t.json,op:`push`},e())}catch(e){let n=e instanceof Error?e.message:String(e);t.json?process.stdout.write(`${JSON.stringify({type:`error`,message:n})}\n`):process.stderr.write(`✗ push failed: ${n}\n`),process.exit(1)}})}function bi(e,t){return{server:xi(`server`,e),ui:xi(`ui`,t)}}function xi(e,t){switch(t.status){case`missing`:return{name:e,state:`missing`,alive:!1};case`corrupt`:return{name:e,state:`corrupt`,alive:!1};case`foreign-host`:return{name:e,state:`foreign-host`,pid:t.lock.pid,port:t.lock.port,startedAt:t.lock.startedAt,host:t.lock.hostname,alive:`unknown`};case`dead-pid`:return{name:e,state:`dead-pid`,pid:t.lock.pid,port:t.lock.port,startedAt:t.lock.startedAt,host:t.lock.hostname,alive:!1};case`alive`:return{name:e,state:`alive`,pid:t.lock.pid,port:t.lock.port,startedAt:t.lock.startedAt,host:t.lock.hostname,alive:!0}}}function Si(e){return`${Ci(e.server)}\n${Ci(e.ui)}`}function Ci(e){let t=e.name===`server`?`server`:`ui `;return e.state===`missing`?`${t} not running`:e.state===`corrupt`?`${t} lock file corrupt — run \`ok clean\``:e.state===`foreign-host`?`${t} foreign host (${e.host}) pid=${e.pid} port=${e.port}`:e.state===`dead-pid`?`${t} stale (dead pid=${e.pid}) — run \`ok clean\``:`${t} alive pid=${e.pid} port=${e.port} started=${e.startedAt}`}function wi(e){let t=e.inspect??(t=>it(e.lockDir,t)),n=e.log??(e=>console.log(e)),r=bi(t(`server`),t(`ui`));return e.json?n(JSON.stringify(r,null,2)):n(Si(r)),r}function Ti(e){return new w(`status`).description(`Show live state of the server + ui lockfiles for this project`).option(`--json`,`Emit structured JSON instead of formatted text`).action(t=>{wi({lockDir:a(o(e(),process.cwd())),json:t.json===!0})})}function Ei(e,t){let n=[];return e.status===`alive`&&n.push({name:`server`,pid:e.lock.pid,port:e.lock.port}),t.status===`alive`&&n.push({name:`ui`,pid:t.lock.pid,port:t.lock.port}),{targets:n}}function Di(e){let t=e.inspect??(t=>it(e.lockDir,t)),n=e.kill??((e,t)=>process.kill(e,t)),r=e.log??(e=>console.log(e)),i=e.error??(e=>console.error(e)),a=Ei(t(`server`),t(`ui`));if(a.targets.length===0)return r(`No running open-knowledge processes.`),{stopped:[],failed:[],hadTargets:!1};let o=[],s=[];for(let e of a.targets)try{n(e.pid,`SIGTERM`),o.push(e)}catch(t){s.push({target:e,error:t instanceof Error?t.message:String(t)})}return o.length>0&&r(`Stopped: ${o.map(e=>`${e.name} (pid=${e.pid}, port=${e.port})`).join(`, `)}`),s.length>0&&i(`Failed to stop: ${s.map(({target:e,error:t})=>`${e.name} (pid=${e.pid}): ${t}`).join(`; `)}`),{stopped:o,failed:s,hadTargets:!0}}function Oi(e){return new w(`stop`).description(`Stop the running open-knowledge server and UI (live only)`).action(()=>{Di({lockDir:a(o(e(),process.cwd()))}).failed.length>0&&(process.exitCode=1)})}const ki=1e4,Ai=[`connection`,`keep-alive`,`proxy-authenticate`,`proxy-authorization`,`te`,`trailer`,`transfer-encoding`,`upgrade`,`cookie`,`set-cookie`];async function ji(e){let t=e.upstreamTimeoutMs??ki,n=Te((n,r)=>{Ni(n,r,e.upstreamHost,e.upstreamPort,t)});await new Promise((t,r)=>{let i=e=>r(e);n.once(`error`,i),n.listen(e.listenPort,e.host,()=>{n.off(`error`,i),t()})});let r=n.address();return{httpServer:n,port:typeof r==`object`&&r?r.port:e.listenPort,close:()=>new Promise(e=>{n.close(()=>e())})}}function Mi(e,t,n){Ni(e,t,n.upstreamHost,n.upstreamPort,n.upstreamTimeoutMs??ki)}function Ni(e,t,n,r,i){let a={...e.headers};delete a.host;for(let e of Ai)delete a[e];e.setTimeout(3e4,()=>{if(t.headersSent)try{t.end()}catch{}else try{t.writeHead(408,{"Content-Type":`text/plain`}),t.end(`Request Timeout`)}catch{}try{e.socket?.destroy()}catch{}});let o=Ee({host:n,port:r,method:e.method,path:e.url,headers:{...a,host:`${n}:${r}`}},e=>{let n={...e.headers};for(let e of Ai)delete n[e];t.writeHead(e.statusCode??502,n),e.pipe(t),e.once(`error`,()=>{try{t.end()}catch{}})});i>0&&o.setTimeout(i,()=>{if(!t.headersSent)t.writeHead(504,{"Content-Type":`text/plain`}),t.end(`Gateway Timeout`);else try{t.end()}catch{}o.destroy()}),o.on(`error`,()=>{if(!t.headersSent)t.writeHead(502,{"Content-Type":`text/plain`}),t.end(`Bad Gateway`);else try{t.end()}catch{}}),e.on(`error`,()=>{o.destroy()}),e.pipe(o)}async function Pi(e){await Promise.all(e.map(e=>new Promise(t=>{e.close(()=>t())})))}async function Fi(e){let{existsSync:t}=await import(`node:fs`),{createServer:n}=await import(`node:http`),{resolve:r}=await import(`node:path`),{acquireUiLock:a,readServerLock:o,releaseUiLock:s,updateUiLockPort:c}=await import(`./src-NsJfsnSl.mjs`),{default:l}=await import(`sirv`),{resolveContentDir:u,resolveLockDir:d}=await import(`./paths-xS3o7pK2.mjs`),f=u(e.config,e.cwd),p=d(f);a(p,{port:0,worktreeRoot:e.cwd});let m=import.meta.dirname??new URL(`.`,import.meta.url).pathname,h=[r(m,`public`),r(m,`../../app/dist`),r(m,`../../../app/dist`)].find(e=>t(e)),g=h?l(h,{single:!0,gzip:!0,immutable:!0}):null,_=t(f)?l(f,{dotfiles:!1,dev:!0}):null,v=e.port,y=null,b=(e,t)=>{let n=e.url?.split(`?`)[0];if(n===`/api/config`&&(e.method===`GET`||e.method===`HEAD`)){y?.();let n=o(p),r=n&&n.port>0?`ws://localhost:${n.port}/collab`:null,i=JSON.stringify({collabUrl:r,previewUrl:null,port:v});t.setHeader(`Content-Type`,`application/json`),t.setHeader(`Cache-Control`,`no-store`),t.setHeader(`X-Content-Type-Options`,`nosniff`),t.statusCode=200,e.method===`HEAD`?t.end():t.end(i);return}if(n?.startsWith(`/api/`)){y?.();let r=o(p);if(!r||r.port<=0){t.writeHead(503,{"Content-Type":`application/json`,"Cache-Control":`no-store`}),t.end(JSON.stringify({error:"Collab server not running. Start `ok start` or run `ok status`.",path:n}));return}Mi(e,t,{upstreamHost:`localhost`,upstreamPort:r.port});return}if(decodeURIComponent(n?.replace(/^\//,``)??``)&&_){t.setHeader(`X-Content-Type-Options`,`nosniff`),_(e,t,()=>{g?g(e,t):Ii(t)});return}if(g){g(e,t);return}Ii(t)},x=e.host===void 0?[`::1`,`127.0.0.1`]:[e.host],S=[],C=e.port;try{for(let e of x){let t=n(b);S.push(t),await new Promise((n,r)=>{let i=e=>r(e);t.once(`error`,i),t.listen(C,e,()=>{t.off(`error`,i);let e=t.address();typeof e==`object`&&e&&(C=e.port),n()})})}}catch(e){await Promise.all(S.map(e=>new Promise(t=>{try{e.close(()=>t())}catch{t()}})));try{s(p)}catch{}throw e}let w=C;v=w,c(p,w);let T=e.scheduler??i,E=e.safetyNetMs??432e5,D=null,O=!1,ee=!1,k=()=>{O||(O=!0,D!==null&&(T.clearTimeout(D),D=null))},te=()=>{if(k(),!ee){ee=!0;try{s(p)}catch{}}},ne=()=>{O||E<=0||(D!==null&&(T.clearTimeout(D),D=null),D=T.setTimeout(()=>{D=null,console.warn(`[ui] safety-net (${E}ms) reached — shutting down (D-025 backstop)`);try{e.onSafetyNet?.()}catch{}for(let e of S)try{e.close()}catch{}te()},E))},re=()=>{O||E<=0||ne()};return y=re,ne(),{httpServers:S,port:w,release:te,detachSafetyNet:k,nudgeSafetyNet:re}}function Ii(e){e.writeHead(404),e.end(`Not found`)}function Li(e,t){if(e!==void 0){let t=Number.parseInt(e,10);if(Number.isNaN(t)||t<0||t>65535)throw Error(`Invalid --port value '${e}'`);return t}if(t!==void 0&&t!==``){let e=Number.parseInt(t,10);if(Number.isNaN(e)||e<0||e>65535)throw Error(`Invalid PORT env value '${t}'`);return e}return 0}async function Ri(e){let t=e.readLock??(async()=>{let{readUiLock:t}=await import(`./src-NsJfsnSl.mjs`);return t(e.lockDir)}),n=await t();if(!n)throw Error(`UI lock collision reported but the lock disappeared before handling — retry acquiring.`);if(n.port===e.requestedPort&&n.port>0)return{mode:`already-running`,port:n.port};let r=n.port;if(r===0){let n=Date.now()+(e.pollDeadlineMs??2e3),i=e.pollIntervalMs??100;for(;Date.now()<n;){await new Promise(e=>{setTimeout(e,i)});let e=await t();if(e&&e.port>0){r=e.port;break}}if(r===0)throw Error("UI did not bind within 2s; run `ok clean`");if(r===e.requestedPort)return{mode:`already-running`,port:r}}return{mode:`proxy`,handle:await ji({listenPort:e.requestedPort,host:e.host,upstreamHost:`localhost`,upstreamPort:r}),upstreamPort:r}}function zi(e){return new w(`ui`).description(`Serve the Open Knowledge React editor UI`).option(`-p, --port <port>`,`UI port (default: $PORT env or 0 / kernel-allocated)`).option(`-H, --host <host>`,"UI host. Default: two-socket loopback bind (`[::1]` + `127.0.0.1`) so cross-family collisions fail loud (D-033). Pass an explicit host (e.g. `127.0.0.1`, `0.0.0.0`) to bind a single socket on that host.").action(async t=>{let{dim:n}=await import(`./colors-BNRrOlZZ.mjs`),{UiLockCollisionError:r}=await import(`./src-NsJfsnSl.mjs`),{resolveContentDir:i,resolveLockDir:a}=await import(`./paths-xS3o7pK2.mjs`),o=e(),s=t.host,c;try{c=Li(t.port,process.env.PORT)}catch(e){console.error(e instanceof Error?e.message:String(e)),process.exitCode=1;return}try{let e=await Fi({config:o,cwd:process.cwd(),port:c,host:s}),t=s===void 0||s===`::`||s===`0.0.0.0`?`localhost`:s;console.log(`${n(`[ui]`)} listening on http://${t}:${e.port}`);let r=!1,i=t=>{if(r)return;r=!0,console.log(n(`\n[ui] Shutting down (${t})...`)),e.detachSafetyNet();let i=()=>{try{e.release()}finally{process.exit(process.exitCode??0)}};Pi(e.httpServers).then(i,i),setTimeout(i,2e3).unref()};process.once(`SIGINT`,()=>i(`SIGINT`)),process.once(`SIGTERM`,()=>i(`SIGTERM`));return}catch(e){if(!(e instanceof r))throw e;let t=a(i(o,process.cwd())),l=s??`localhost`,u;try{u=await Ri({requestedPort:c,host:l,lockDir:t})}catch(e){console.error(e instanceof Error?e.message:String(e)),process.exit(1)}u.mode===`already-running`&&(console.log(`UI already running at http://${l}:${u.port}`),process.exit(0)),console.log(`UI running at http://${l}:${u.upstreamPort}; acting as HTTP proxy on port ${u.handle.port}`);let d=!1,f=e=>{d||(d=!0,console.log(n(`\n[ui-proxy] Shutting down (${e})...`)),u.handle.close().finally(()=>process.exit(process.exitCode??0)),setTimeout(()=>process.exit(process.exitCode??0),2e3).unref())};process.once(`SIGINT`,()=>f(`SIGINT`)),process.once(`SIGTERM`,()=>f(`SIGTERM`))}})}process.argv.includes(`--no-color`)?(process.env.NO_COLOR=`1`,delete process.env.FORCE_COLOR):process.argv.includes(`--color`)&&(process.env.FORCE_COLOR=`1`,delete process.env.NO_COLOR);const Q=new w;let $;Q.name(`open-knowledge`).description(`Local-first knowledge base with CRDT collaboration`).version(e).option(`--cwd <path>`,`Working directory`).option(`--log-level <level>`,`Log level`,`info`).option(`--no-color`,`Disable color output`).option(`--color`,`Force color output`).hook(`preAction`,e=>{let t=e.opts(),n=t.cwd;n!==void 0&&process.chdir(n);let{config:r}=b(n),i=e.args.length===0?t:e.commands[0]?.opts()??{};i.port!==void 0&&(r.server.port=Number(i.port)),i.host!==void 0&&(r.server.host=i.host),process.env.PORT&&(r.server.port=Number(process.env.PORT)),process.env.HOST&&(r.server.host=process.env.HOST),$=r});const Bi=S(()=>$);Q.addCommand(Bi,{isDefault:!0});const Vi=mi(()=>$);Q.addCommand(Vi),Q.addCommand(v());const Hi=hi(()=>$);Q.addCommand(Hi);const Ui=zi(()=>$);Q.addCommand(Ui),Q.addCommand(Oi(()=>$)),Q.addCommand(st(()=>$)),Q.addCommand(Ti(()=>$)),Q.addCommand(rt(()=>$)),Q.addCommand(gt(()=>$)),Q.addCommand(_i(()=>$)),Q.addCommand(yi(()=>$)),Q.addCommand(vi(()=>$)),await Q.parseAsync();export{};
595
595
  //# sourceMappingURL=cli.mjs.map
@@ -0,0 +1,2 @@
1
+ import"./src-ViJPkmPW.mjs";var e=`0.0.0-dev-20260421192027`;const t=`AGENTS.md`,n=`config.yml`,r=`cache`,i=e,a=`open-knowledge`;export{i as a,a as i,r as n,n as r,t};
2
+ //# sourceMappingURL=constants-BLW6shM6.mjs.map
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{n as e,r as t}from"./loader-xn8pJrM1.mjs";import"./src-DdjBWEcP.mjs";export{t as ConfigSchema,e as loadConfig};
1
+ import{n as e,r as t}from"./loader-BNuhNFOT.mjs";import"./src-D9A_jCdV.mjs";export{t as ConfigSchema,e as loadConfig};
@@ -0,0 +1 @@
1
+ import{a as e,i as t,n,r,t as i}from"./init-WENor_lZ.mjs";export{i as detectInstalledEditors,n as formatInitResult,r as initCommand,t as parseEditorFlag,e as runInit};
@@ -1 +1 @@
1
- import{a as e,i as t,n,o as r,r as i,s as a,t as o}from"./init-DA7kkHUA.mjs";export{o as CLAUDE_MD_SECTION,n as OK_MARKER_BEGIN,i as OK_MARKER_END,t as PREVIEW_GUIDANCE,e as ensureOkGitignoredAtRoot,r as initContent,a as upsertRootInstructions};
1
+ import{a as e,i as t,n,o as r,r as i,s as a,t as o}from"./init-DeoOI04P.mjs";export{o as CLAUDE_MD_SECTION,n as OK_MARKER_BEGIN,i as OK_MARKER_END,t as PREVIEW_GUIDANCE,e as ensureOkGitignoredAtRoot,r as initContent,a as upsertRootInstructions};
@@ -1,4 +1,4 @@
1
- import{n as e,r as t,t as n}from"./constants-D6bAkegd.mjs";import{D as r}from"./src-ViJPkmPW.mjs";import{existsSync as i,mkdirSync as a,readFileSync as o,realpathSync as s,writeFileSync as c}from"node:fs";import{join as l,resolve as u}from"node:path";const d=`<!-- open-knowledge:begin -->`,f=`<!-- open-knowledge:end -->`,p=/<!-- open-knowledge:begin -->[\s\S]*?<!-- open-knowledge:end -->/,m=`# ${r}/ — Open Knowledge config
1
+ import{n as e,r as t,t as n}from"./constants-BLW6shM6.mjs";import{D as r}from"./src-ViJPkmPW.mjs";import{existsSync as i,mkdirSync as a,readFileSync as o,realpathSync as s,writeFileSync as c}from"node:fs";import{join as l,resolve as u}from"node:path";const d=`<!-- open-knowledge:begin -->`,f=`<!-- open-knowledge:end -->`,p=/<!-- open-knowledge:begin -->[\s\S]*?<!-- open-knowledge:end -->/,m=`# ${r}/ — Open Knowledge config
2
2
 
3
3
  This directory holds Open Knowledge's configuration for this project. It's **not** where content lives — content lives wherever \`content.dir\` + \`content.include\` in \`config.yml\` point. The default is the repo root with \`**/*.md\`, so any markdown file in the project is fair game. Inspect \`config.yml\` for the actual setting.
4
4
 
@@ -227,4 +227,4 @@ ${f}`;function v(e,t,r){let a=[n,...r??[]],u=new Set,d=[];for(let n of a){let r=
227
227
 
228
228
  `)?`
229
229
  `:``}${n}`,`utf-8`),`appended`)}const x=[{name:n,content:m},{name:`.gitignore`,content:`${e}/\nserver.lock\nui.lock\nsync-state.json\n`},{name:t,content:h}];function S(t){let n=u(t,r),i=[],o=[];a(n,{recursive:!0}),a(l(n,e),{recursive:!0});for(let e of x)y(l(n,e.name),e.content)?i.push(e.name):o.push(e.name);return{created:i,skipped:o}}export{b as a,g as i,d as n,S as o,f as r,v as s,_ as t};
230
- //# sourceMappingURL=init-DA7kkHUA.mjs.map
230
+ //# sourceMappingURL=init-DeoOI04P.mjs.map
@@ -1,5 +1,5 @@
1
- import{i as e}from"./constants-D6bAkegd.mjs";import{D as t}from"./src-ViJPkmPW.mjs";import{o as n,s as r}from"./init-DA7kkHUA.mjs";import{t as i}from"./preview-Bv6qni6t.mjs";import{o as a}from"./colors-CoV_NlQL.mjs";import{t as o}from"./is-object-B4GcZahG.mjs";import{Command as s}from"commander";import{existsSync as c,mkdirSync as l,readFileSync as u,writeFileSync as d}from"node:fs";import{homedir as f}from"node:os";import{basename as p,dirname as m,isAbsolute as h,join as g,posix as _,relative as v,resolve as y,sep as b,win32 as x}from"node:path";import{parse as ee,stringify as S}from"smol-toml";const C=[`claude`,`claude-desktop`,`cursor`,`vscode`,`windsurf`,`codex`],w=[`@inkeep/open-knowledge`,`mcp`],T={MCP_DEBUG:`1`,OK_LOG_FILE:`/tmp/ok-mcp.log`};function E(e=process.argv[1]){if(!e)throw Error(`Cannot infer the local CLI entry for --dev-mcp because process.argv[1] is empty.`);let t=y(e);if(p(t)===`cli.mjs`&&p(m(t))===`dist`)return t;let n=t.split(b),r=n.lastIndexOf(`packages`);if(r===-1||n[r+1]!==`cli`)throw Error(`Cannot infer the repo root for --dev-mcp from ${t}. Run the local CLI from this repo so the built dist path can be derived.`);let i=n.slice(0,r);return g(i.length===0?b:i.join(b),`packages`,`cli`,`dist`,`cli.mjs`)}function D(e={}){return e.mode===`dev`?{command:`node`,args:[E(e.cliEntryPath),`mcp`],env:{...T}}:{command:`npx`,args:[...w]}}function O(e){return e===`win32`?x:_}function k(e={}){let t=e.platformName??process.platform,n=e.home??f(),r=e.env??process.env,i=O(t);return t===`darwin`?i.join(n,`Library`,`Application Support`):t===`win32`?r.APPDATA??i.join(n,`AppData`,`Roaming`):r.XDG_CONFIG_HOME??i.join(n,`.config`)}function te(e={}){let t=e.platformName??process.platform,n=e.home??f();return O(t).join(n,`.claude.json`)}function A(e={}){let t=e.platformName??process.platform,n=e.home??f(),r=e.env??process.env;if(t===`darwin`)return _.join(n,`Library`,`Application Support`,`Claude`,`claude_desktop_config.json`);if(t===`win32`){let e=r.APPDATA??x.join(n,`AppData`,`Roaming`);return x.join(e,`Claude`,`claude_desktop_config.json`)}throw Error(`Claude Desktop is not available on ${t}. Supported: macOS, Windows.`)}function j(e={}){let t=e.platformName??process.platform,n=e.home??f();return O(t).join(n,`.cursor`,`mcp.json`)}function M(e={}){return O(e.platformName??process.platform).join(k(e),`Code`,`User`,`mcp.json`)}function N(e={}){let t=e.platformName??process.platform,n=e.home??f();return O(t).join(n,`.codeium`,`windsurf`,`mcp_config.json`)}function P(e={}){let t=e.platformName??process.platform,n=e.home??f();return(e.env??process.env).CODEX_HOME??O(t).join(n,`.codex`)}function F(e={}){return O(e.platformName??process.platform).join(P(e),`config.toml`)}function I(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length&&e.every((e,n)=>I(e,t[n]));if(o(e)&&o(t)){let n=Object.keys(e).sort(),r=Object.keys(t).sort();return n.length===r.length&&n.every((e,t)=>e===r[t])&&n.every(n=>I(e[n],t[n]))}return!1}function ne(e,t){return Object.entries(t).every(([t,n])=>I(e[t],n))}function re(e,t){return{...e,...t}}function L(e){return{...e,isCompatible(t,n,r){return ne(t,e.buildEntry(n,r))},mergeManagedFields(t,n,r){return re(t,e.buildEntry(n,r))}}}const R={claude:L({id:`claude`,label:`Claude Code`,configPath:(e,t)=>te({home:t}),format:`json`,topLevelKey:`mcpServers`,serverName:()=>e,buildEntry:(e,t)=>D(t),scope:`global`,detectPath:(e,t)=>g(t??f(),`.claude`),legacyProjectConfigPath:e=>g(e,`.mcp.json`),instructionsPath:e=>g(e,`CLAUDE.md`)}),"claude-desktop":L({id:`claude-desktop`,label:`Claude Desktop`,configPath:(e,t)=>A({home:t}),format:`json`,topLevelKey:`mcpServers`,serverName:()=>e,buildEntry:(e,t)=>D(t),scope:`global`,detectPath:(e,t)=>m(A({home:t}))}),cursor:L({id:`cursor`,label:`Cursor`,configPath:(e,t)=>j({home:t}),format:`json`,topLevelKey:`mcpServers`,serverName:()=>e,buildEntry:(e,t)=>D(t),scope:`global`,detectPath:(e,t)=>m(j({home:t})),legacyProjectConfigPath:e=>g(e,`.cursor`,`mcp.json`)}),vscode:L({id:`vscode`,label:`VS Code`,configPath:(e,t)=>M({home:t}),format:`json`,topLevelKey:`servers`,serverName:()=>e,buildEntry:(e,t)=>({type:`stdio`,...D(t)}),scope:`global`,detectPath:(e,t)=>m(M({home:t})),legacyProjectConfigPath:e=>g(e,`.vscode`,`mcp.json`)}),windsurf:L({id:`windsurf`,label:`Windsurf`,configPath:(e,t)=>N({home:t}),format:`json`,topLevelKey:`mcpServers`,serverName:()=>e,buildEntry:(e,t)=>D(t),scope:`global`,detectPath:(e,t)=>m(N({home:t}))}),codex:L({id:`codex`,label:`Codex`,configPath:(e,t)=>F({home:t}),format:`toml`,topLevelKey:`mcp_servers`,serverName:()=>e,buildEntry:(e,t)=>D(t),scope:`global`,detectPath:(e,t)=>m(F({home:t})),legacyProjectConfigPath:e=>g(e,`.codex`,`config.toml`)})};function z(e){let t=e.filter(e=>!(e in R));if(t.length>0)throw Error(`Unknown editor(s): ${t.join(`, `)}. Valid options: ${C.join(`, `)}`);return e.map(e=>R[e])}function B(e){if(!c(e))return{};let t=u(e,`utf-8`).trim();if(t===``)return{};try{let n=JSON.parse(t);if(o(n))return n;throw Error(`${e} root must be a JSON object`)}catch(t){throw t instanceof SyntaxError?Error(`${e} contains invalid JSON: ${t.message}`):t}}function V(e){if(!c(e))return{};let t=u(e,`utf-8`).trim();if(t===``)return{};try{let n=ee(t);if(o(n))return n;throw Error(`${e} root must be a TOML table`)}catch(t){throw Error(`${e} contains invalid TOML: ${t instanceof Error?t.message:String(t)}`)}}function H(e,t){l(m(e),{recursive:!0}),d(e,`${JSON.stringify(t,null,2)}\n`,`utf-8`)}function U(e,t){l(m(e),{recursive:!0});let n=S(t);d(e,n.endsWith(`
1
+ import{i as e}from"./constants-BLW6shM6.mjs";import{D as t}from"./src-ViJPkmPW.mjs";import{o as n,s as r}from"./init-DeoOI04P.mjs";import{t as i}from"./preview-oS_HbHIz.mjs";import{o as a}from"./colors-CoV_NlQL.mjs";import{t as o}from"./is-object-B4GcZahG.mjs";import{Command as s}from"commander";import{existsSync as c,mkdirSync as l,readFileSync as u,writeFileSync as d}from"node:fs";import{homedir as f}from"node:os";import{basename as p,dirname as m,isAbsolute as h,join as g,posix as _,relative as v,resolve as y,sep as b,win32 as x}from"node:path";import{parse as ee,stringify as S}from"smol-toml";const C=[`claude`,`claude-desktop`,`cursor`,`vscode`,`windsurf`,`codex`],w=[`@inkeep/open-knowledge`,`mcp`],T={MCP_DEBUG:`1`,OK_LOG_FILE:`/tmp/ok-mcp.log`};function E(e=process.argv[1]){if(!e)throw Error(`Cannot infer the local CLI entry for --dev-mcp because process.argv[1] is empty.`);let t=y(e);if(p(t)===`cli.mjs`&&p(m(t))===`dist`)return t;let n=t.split(b),r=n.lastIndexOf(`packages`);if(r===-1||n[r+1]!==`cli`)throw Error(`Cannot infer the repo root for --dev-mcp from ${t}. Run the local CLI from this repo so the built dist path can be derived.`);let i=n.slice(0,r);return g(i.length===0?b:i.join(b),`packages`,`cli`,`dist`,`cli.mjs`)}function D(e={}){return e.mode===`dev`?{command:`node`,args:[E(e.cliEntryPath),`mcp`],env:{...T}}:{command:`npx`,args:[...w]}}function O(e){return e===`win32`?x:_}function k(e={}){let t=e.platformName??process.platform,n=e.home??f(),r=e.env??process.env,i=O(t);return t===`darwin`?i.join(n,`Library`,`Application Support`):t===`win32`?r.APPDATA??i.join(n,`AppData`,`Roaming`):r.XDG_CONFIG_HOME??i.join(n,`.config`)}function te(e={}){let t=e.platformName??process.platform,n=e.home??f();return O(t).join(n,`.claude.json`)}function A(e={}){let t=e.platformName??process.platform,n=e.home??f(),r=e.env??process.env;if(t===`darwin`)return _.join(n,`Library`,`Application Support`,`Claude`,`claude_desktop_config.json`);if(t===`win32`){let e=r.APPDATA??x.join(n,`AppData`,`Roaming`);return x.join(e,`Claude`,`claude_desktop_config.json`)}throw Error(`Claude Desktop is not available on ${t}. Supported: macOS, Windows.`)}function j(e={}){let t=e.platformName??process.platform,n=e.home??f();return O(t).join(n,`.cursor`,`mcp.json`)}function M(e={}){return O(e.platformName??process.platform).join(k(e),`Code`,`User`,`mcp.json`)}function N(e={}){let t=e.platformName??process.platform,n=e.home??f();return O(t).join(n,`.codeium`,`windsurf`,`mcp_config.json`)}function P(e={}){let t=e.platformName??process.platform,n=e.home??f();return(e.env??process.env).CODEX_HOME??O(t).join(n,`.codex`)}function F(e={}){return O(e.platformName??process.platform).join(P(e),`config.toml`)}function I(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length&&e.every((e,n)=>I(e,t[n]));if(o(e)&&o(t)){let n=Object.keys(e).sort(),r=Object.keys(t).sort();return n.length===r.length&&n.every((e,t)=>e===r[t])&&n.every(n=>I(e[n],t[n]))}return!1}function ne(e,t){return Object.entries(t).every(([t,n])=>I(e[t],n))}function re(e,t){return{...e,...t}}function L(e){return{...e,isCompatible(t,n,r){return ne(t,e.buildEntry(n,r))},mergeManagedFields(t,n,r){return re(t,e.buildEntry(n,r))}}}const R={claude:L({id:`claude`,label:`Claude Code`,configPath:(e,t)=>te({home:t}),format:`json`,topLevelKey:`mcpServers`,serverName:()=>e,buildEntry:(e,t)=>D(t),scope:`global`,detectPath:(e,t)=>g(t??f(),`.claude`),legacyProjectConfigPath:e=>g(e,`.mcp.json`),instructionsPath:e=>g(e,`CLAUDE.md`)}),"claude-desktop":L({id:`claude-desktop`,label:`Claude Desktop`,configPath:(e,t)=>A({home:t}),format:`json`,topLevelKey:`mcpServers`,serverName:()=>e,buildEntry:(e,t)=>D(t),scope:`global`,detectPath:(e,t)=>m(A({home:t}))}),cursor:L({id:`cursor`,label:`Cursor`,configPath:(e,t)=>j({home:t}),format:`json`,topLevelKey:`mcpServers`,serverName:()=>e,buildEntry:(e,t)=>D(t),scope:`global`,detectPath:(e,t)=>m(j({home:t})),legacyProjectConfigPath:e=>g(e,`.cursor`,`mcp.json`)}),vscode:L({id:`vscode`,label:`VS Code`,configPath:(e,t)=>M({home:t}),format:`json`,topLevelKey:`servers`,serverName:()=>e,buildEntry:(e,t)=>({type:`stdio`,...D(t)}),scope:`global`,detectPath:(e,t)=>m(M({home:t})),legacyProjectConfigPath:e=>g(e,`.vscode`,`mcp.json`)}),windsurf:L({id:`windsurf`,label:`Windsurf`,configPath:(e,t)=>N({home:t}),format:`json`,topLevelKey:`mcpServers`,serverName:()=>e,buildEntry:(e,t)=>D(t),scope:`global`,detectPath:(e,t)=>m(N({home:t}))}),codex:L({id:`codex`,label:`Codex`,configPath:(e,t)=>F({home:t}),format:`toml`,topLevelKey:`mcp_servers`,serverName:()=>e,buildEntry:(e,t)=>D(t),scope:`global`,detectPath:(e,t)=>m(F({home:t})),legacyProjectConfigPath:e=>g(e,`.codex`,`config.toml`)})};function z(e){let t=e.filter(e=>!(e in R));if(t.length>0)throw Error(`Unknown editor(s): ${t.join(`, `)}. Valid options: ${C.join(`, `)}`);return e.map(e=>R[e])}function B(e){if(!c(e))return{};let t=u(e,`utf-8`).trim();if(t===``)return{};try{let n=JSON.parse(t);if(o(n))return n;throw Error(`${e} root must be a JSON object`)}catch(t){throw t instanceof SyntaxError?Error(`${e} contains invalid JSON: ${t.message}`):t}}function V(e){if(!c(e))return{};let t=u(e,`utf-8`).trim();if(t===``)return{};try{let n=ee(t);if(o(n))return n;throw Error(`${e} root must be a TOML table`)}catch(t){throw Error(`${e} contains invalid TOML: ${t instanceof Error?t.message:String(t)}`)}}function H(e,t){l(m(e),{recursive:!0}),d(e,`${JSON.stringify(t,null,2)}\n`,`utf-8`)}function U(e,t){l(m(e),{recursive:!0});let n=S(t);d(e,n.endsWith(`
2
2
  `)?n:`${n}\n`,`utf-8`)}const W=`0.0.1`,G=`open-knowledge-ui`;function K(e,t){let n=[];e.runtimeExecutable!==t.runtimeExecutable&&n.push(`runtimeExecutable`);let r=e.runtimeArgs;return Array.isArray(r)&&r.length===t.runtimeArgs.length&&r.every((e,n)=>e===t.runtimeArgs[n])||n.push(`runtimeArgs`),e.port!==t.port&&n.push(`port`),n}function q(e,t,n={}){let r=g(e,`.claude`,`launch.json`),i=n.mode===`dev`,a=n.mode===`dev`?{name:G,runtimeExecutable:`node`,runtimeArgs:[E(n.cliEntryPath),`ui`],port:3e3}:{name:G,runtimeExecutable:`npx`,runtimeArgs:[`@inkeep/open-knowledge`,`ui`],port:3e3};try{if(!c(r))return l(m(r),{recursive:!0}),d(r,`${JSON.stringify({version:W,configurations:[a]},null,2)}\n`,`utf-8`),{action:`created`,configPath:r};let e=u(r,`utf-8`).trim(),n=e?JSON.parse(e):{};if(!o(n))return{action:`failed`,configPath:r,error:`launch.json root is not an object`};let s=Array.isArray(n.configurations)?n.configurations:[],f=s.findIndex(e=>o(e)&&e.name===G);if(f>=0&&!t){let e=s[f],t=K(e,a);if(t.length>0){if(!i)return{action:`skipped-stale`,configPath:r,staleFields:t}}else return{action:`skipped-existing`,configPath:r}}f>=0?s[f]=a:s.push(a);let p={...n,version:n.version??W,configurations:s};return d(r,`${JSON.stringify(p,null,2)}\n`,`utf-8`),{action:`merged`,configPath:r}}catch(e){return{action:`failed`,configPath:r,error:e instanceof Error?e.message:String(e)}}}function J(e,t,n,r,i){let a=e.serverName(t),s;try{s=e.configPath(t,i)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:``,serverName:a,error:t instanceof Error?t.message:String(t)}}let c;try{c=e.format===`toml`?V(s):B(s)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:s,serverName:a,error:t instanceof Error?t.message:String(t)}}let l=c[e.topLevelKey]??{},u=l[a],d=r.mode===`dev`,f;try{if(u!==void 0&&!n){if(o(u)&&e.isCompatible(u,t,r))return{editorId:e.id,label:e.label,action:`skipped-existing`,configPath:s,serverName:a};if(!d)return{editorId:e.id,label:e.label,action:`skipped-conflict`,configPath:s,serverName:a}}f=o(u)&&(n||d)?e.mergeManagedFields(u,t,r):e.buildEntry(t,r)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:s,serverName:a,error:t instanceof Error?t.message:String(t)}}let p={...c,[e.topLevelKey]:{...l,[a]:f}};try{e.format===`toml`?U(s,p):H(s,p)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:s,serverName:a,error:t instanceof Error?t.message:String(t)}}return{editorId:e.id,label:e.label,action:u===void 0?`written`:`overwritten`,configPath:s,serverName:a}}function Y(e,t){let n=e.legacyProjectConfigPath?.(t);if(!(!n||!c(n)))return{editorId:e.id,label:e.label,path:n}}function X(e={}){let t=y(e.cwd??process.cwd()),i={mode:e.devMcp?`dev`:`published`,cliEntryPath:e.cliEntryPath},a;try{a=n(t)}catch(n){return{contentCreated:[],contentSkipped:[],editors:[],legacyProjectConfigs:[],rootInstructions:[],mcpAction:`failed`,mcpPath:R.claude.configPath(t,e.home),mcpError:`Content scaffolding failed: ${n instanceof Error?n.message:String(n)}`}}let o=e.editors??[`claude`],s=z(o),c=[];for(let n of s){if(e.mcp===!1){let r=``;try{r=n.configPath(t,e.home)}catch{}c.push({editorId:n.id,label:n.label,action:`skipped-flag`,configPath:r,serverName:n.serverName(t)});continue}c.push(J(n,t,e.force??!1,i,e.home))}let l=e.mcp===!1?[]:s.map(e=>Y(e,t)).filter(e=>e!==void 0),u=o.includes(`claude`)&&e.mcp!==!1?q(t,e.force??!1,i):void 0,d=s.map(e=>e.instructionsPath?.(t)).filter(e=>e!==void 0).map(e=>h(e)?v(t,e):e),f=e.rootInstructions===!1?[]:r(t,e.force??!1,d),p=c.find(e=>e.editorId===`claude`)??c[0]??{action:`skipped-flag`,configPath:R.claude.configPath(t,e.home)};return{contentCreated:a.created,contentSkipped:a.skipped,editors:c,legacyProjectConfigs:l,rootInstructions:f,launchJson:u,mcpAction:p.action,mcpPath:p.configPath,mcpError:`error`in p?p.error:void 0}}function Z(e,n){let r=[],o=g(n,t);if(e.contentCreated.length>0?(r.push(`Content scaffolded at ${o}/`),r.push(` Created: ${e.contentCreated.join(`, `)}`)):r.push(`Content already present at ${o}/`),e.contentSkipped.length>0&&r.push(` Skipped (already exist): ${e.contentSkipped.join(`, `)}`),r.push(``),e.editors.length===0)e.mcpError&&r.push(`Warning: ${e.mcpError}`);else{let t=e.editors.some(e=>e.action===`written`||e.action===`overwritten`),o=e.editors.some(e=>e.action===`failed`);if(e.editors.every(e=>e.action===`skipped-flag`))r.push(`MCP config not written — use without --no-mcp to configure editors`);else{r.push(`MCP server configuration:`);for(let t of e.editors){let e=t.configPath.startsWith(n)?v(n,t.configPath):t.configPath.replace(/^\/Users\/[^/]+/,`~`),i=t.serverName===`open-knowledge`?``:` (${t.serverName})`,a=` `.repeat(Math.max(1,14-t.label.length)),o=t.editorId===`claude-desktop`&&(t.action===`written`||t.action===`overwritten`)?` — quit and relaunch Claude Desktop to activate`:``;switch(t.action){case`written`:r.push(` ${t.label}${a}${e} registered${i}${o}`);break;case`overwritten`:r.push(` ${t.label}${a}${e} updated${i}${o}`);break;case`skipped-existing`:r.push(` ${t.label}${a}${e} already configured${i}`);break;case`skipped-conflict`:r.push(` ${t.label}${a}${e} managed MCP fields differ from current defaults${i}; re-run with --force to update`);break;case`failed`:r.push(` ${t.label}${a}${e} FAILED: ${t.error}`);break;case`skipped-flag`:break}}}if(o&&(r.push(``),r.push(`For failed editors, add the MCP server entry manually. See:`),r.push(` https://github.com/inkeep/open-knowledge#mcp-setup`)),e.legacyProjectConfigs.length>0){r.push(``),r.push(`Legacy project MCP configs detected:`);for(let t of e.legacyProjectConfigs)r.push(` ${t.label} ${v(n,t.path)}`);r.push(` These project-local files may override the new global config. Remove them if you want fully user-scoped MCP setup in this project.`)}if(e.launchJson){let t=e.launchJson,i=t.configPath.startsWith(n)?v(n,t.configPath):t.configPath;switch(t.action){case`created`:r.push(` launch.json ${i} created (preview_start("${G}") ready)`);break;case`merged`:r.push(` launch.json ${i} merged open-knowledge entry`);break;case`skipped-existing`:r.push(` launch.json ${i} already has open-knowledge entry`);break;case`skipped-stale`:r.push(` launch.json ${i} ${a(`⚠ existing open-knowledge entry is out of date`)}`),t.staleFields&&t.staleFields.length>0&&r.push(` ${a(`${t.staleFields.join(`, `)} differ from current defaults`)}`),r.push(` ${a(`re-run with --force to update`)}`);break;case`failed`:r.push(` launch.json ${i} FAILED: ${t.error}`);break}}if(e.rootInstructions.length>0){let t=e.rootInstructions.filter(e=>e.action!==`skipped-symlink`);if(t.length>0){r.push(``),r.push(`Root instructions:`);for(let e of t){let t=e.path.startsWith(n)?v(n,e.path):e.path,i=` `.repeat(Math.max(1,14-e.file.length));switch(e.action){case`created`:r.push(` ${e.file}${i}${t} created`);break;case`appended`:r.push(` ${e.file}${i}${t} appended Open Knowledge section`);break;case`replaced`:r.push(` ${e.file}${i}${t} replaced Open Knowledge section (--force)`);break;case`skipped-existing`:r.push(` ${e.file}${i}${t} already has Open Knowledge section`);break}}}}if(e.preview?(r.push(``),r.push(i(e.preview,n))):e.previewWarning&&(r.push(``),r.push(`Content preview unavailable: ${e.previewWarning}`)),t){let t=e.editors.filter(e=>e.action===`written`||e.action===`overwritten`).map(e=>e.label);r.push(``),r.push(`Next steps:`),r.push(` 1. Open your editor (${t.join(` / `)})`),r.push(` 2. Approve the MCP server when prompted`),r.push(` 3. The knowledge base is ready — use the three workflow tools:`),r.push(` - mcp__open-knowledge__init-content — bootstrap articles from the codebase`),r.push(` - mcp__open-knowledge__ingest — capture an external source`),r.push(` - mcp__open-knowledge__research — gather sources and write findings`)}}return r.join(`
3
3
  `)}function ie(e){switch(e){case`claude_desktop`:return`claude-desktop`;default:return e}}function Q(e){if(e===`all`)return[...C];let t=e.split(`,`).map(e=>e.trim()).map(ie);return z(t),t}function $(e,t){let n=[];for(let r of C){let i=R[r],a;try{a=i.detectPath?.(e,t)??m(i.configPath(e,t))}catch{continue}c(a)&&n.push(r)}return n}function ae(){return new s(`init`).description(`Scaffold ${t}/ in the current directory and register the MCP server for your editor(s)`).option(`--mcp`,`Register the MCP server for selected editors (default: true)`,!0).option(`--no-mcp`,`Scaffold the ${t}/ directory but do not touch MCP config`).option(`--force`,`Overwrite existing open-knowledge MCP entries (default: skip)`).option(`--dev-mcp`,`Register a local dev MCP entry using node + packages/cli/dist/cli.mjs with debug logging`).option(`--editor <editors>`,`Target editor(s): ${C.join(`, `)}, all (comma-separated) — default: all detected editors (non-TTY) / preselects detected editors (TTY)`).action(async e=>{let t=process.cwd(),n;if(e.editor)try{n=Q(e.editor)}catch(e){process.stderr.write(`${e instanceof Error?e.message:String(e)}\n`),process.exitCode=1;return}else if(e.mcp!==!1&&process.stdin.isTTY){let{multiselect:e,isCancel:r}=await import(`@clack/prompts`),i=new Set($(t));i.size===0&&process.stdout.write(`No MCP-capable editors detected — select manually, or cancel and use --editor <all|${C.join(`|`)}>.\n`);let a=await e({message:`Which tools do you use? (space to toggle, enter to confirm)`,options:C.flatMap(e=>{let n=R[e];try{let r=n.configPath(t),a=n.scope===`global`?r.replace(/^\/Users\/[^/]+/,`~`):v(t,r);return[{value:e,label:n.label,hint:a,initialValue:i.has(e)}]}catch{return[]}}),required:!0});if(r(a)){process.stdout.write(`Init cancelled.
4
- `);return}n=a}else if(n=$(t),n.length===0){process.stderr.write(`No MCP-capable editors detected. Use --editor <all|${C.join(`|`)}> to force.\n`),process.exitCode=1;return}let r=X({cwd:t,mcp:e.mcp,force:e.force,devMcp:e.devMcp,editors:n});try{let{previewContent:e}=await import(`./preview-rUPh_bsX.mjs`),{loadConfig:n}=await import(`./loader-BuzwKwaw.mjs`),{resolveContentDir:i}=await import(`./paths-CP2voPwK.mjs`),{config:a}=n(t);r.preview=e({projectDir:t,contentDir:i(a,t),include:a.content.include,exclude:a.content.exclude})}catch(e){r.previewWarning=e instanceof Error?e.message:String(e)}process.stdout.write(`${Z(r,t)}\n`),(r.editors.some(e=>e.action===`failed`)||r.mcpAction===`failed`)&&(process.exitCode=1)})}export{X as a,Q as i,Z as n,ae as r,$ as t};
5
- //# sourceMappingURL=init-CiURMJ2p.mjs.map
4
+ `);return}n=a}else if(n=$(t),n.length===0){process.stderr.write(`No MCP-capable editors detected. Use --editor <all|${C.join(`|`)}> to force.\n`),process.exitCode=1;return}let r=X({cwd:t,mcp:e.mcp,force:e.force,devMcp:e.devMcp,editors:n});try{let{previewContent:e}=await import(`./preview-BGOwfgOL.mjs`),{loadConfig:n}=await import(`./loader-bM_eCxHL.mjs`),{resolveContentDir:i}=await import(`./paths-xS3o7pK2.mjs`),{config:a}=n(t);r.preview=e({projectDir:t,contentDir:i(a,t),include:a.content.include,exclude:a.content.exclude})}catch(e){r.previewWarning=e instanceof Error?e.message:String(e)}process.stdout.write(`${Z(r,t)}\n`),(r.editors.some(e=>e.action===`failed`)||r.mcpAction===`failed`)&&(process.exitCode=1)})}export{X as a,Q as i,Z as n,ae as r,$ as t};
5
+ //# sourceMappingURL=init-WENor_lZ.mjs.map
@@ -1,3 +1,3 @@
1
- import{r as e}from"./constants-D6bAkegd.mjs";import{D as t}from"./src-ViJPkmPW.mjs";import{t as n}from"./is-object-B4GcZahG.mjs";import{existsSync as r,readFileSync as i}from"node:fs";import{homedir as a}from"node:os";import{resolve as o}from"node:path";import{parse as s}from"yaml";import{realpath as c}from"node:fs/promises";import{z as l}from"zod";async function u(e){let t=o(e);try{return await c(t)}catch(e){if(e.code!==`ENOENT`){let n=e instanceof Error?e.message:String(e);console.warn(`[normalize-cwd] realpath failed for ${t}: ${n}`)}return t}}const d=l.object({title:l.string().optional(),description:l.string().optional(),tags:l.array(l.string()).optional()}).strict(),f=l.object({match:l.string().min(1,"`match` must be a non-empty glob pattern (e.g. 'specs/**' or 'reports/*/**')"),frontmatter:d}).strict(),p=l.object({content:l.object({dir:l.string().default(`.`),include:l.array(l.string()).min(1).default([`**/*.md`,`**/*.mdx`]),exclude:l.array(l.string()).default([])}).default({dir:`.`,include:[`**/*.md`,`**/*.mdx`],exclude:[]}),github:l.object({oauthAppClientId:l.string().default(`Ov23liqlSd0V1MwR6rhI`)}).default({oauthAppClientId:`Ov23liqlSd0V1MwR6rhI`}),sync:l.object({enabled:l.boolean().optional(),pushIntervalSeconds:l.number().int().min(1).default(60),pullIntervalSeconds:l.number().int().min(1).default(30),autoCommit:l.boolean().default(!0),autoPush:l.boolean().default(!0),autoPull:l.boolean().default(!0),commitMessage:l.string().default(`auto`)}).default({pushIntervalSeconds:60,pullIntervalSeconds:30,autoCommit:!0,autoPush:!0,autoPull:!0,commitMessage:`auto`}),server:l.object({port:l.number().int().min(0).max(65535).default(0),host:l.string().regex(/^[\w.\-:]+$/,`Invalid hostname`).default(`localhost`),openOnAgentEdit:l.boolean().default(!1)}).default({port:0,host:`localhost`,openOnAgentEdit:!1}),persistence:l.object({debounceMs:l.number().int().min(0).default(2e3),maxDebounceMs:l.number().int().min(0).default(1e4)}).default({debounceMs:2e3,maxDebounceMs:1e4}),preview:l.object({baseUrl:l.url().optional()}).default({}),folders:l.array(f).default([]),mcp:l.object({autoStart:l.boolean().default(!0),tools:l.object({read_document:l.object({historyDepth:l.number().int().min(0).default(5)}).default({historyDepth:5}),search:l.object({maxResults:l.number().int().min(1).default(50)}).default({maxResults:50})}).default({read_document:{historyDepth:5},search:{maxResults:50}})}).default({autoStart:!0,tools:{read_document:{historyDepth:5},search:{maxResults:50}}})});function m(e,t){let r={...e};for(let i of Object.keys(t)){let a=e[i],o=t[i];n(o)&&n(a)?r[i]=m(a,o):o!==void 0&&(r[i]=o)}return r}function h(e){if(!r(e))return null;try{let t=s(i(e,`utf-8`));return n(t)?t:null}catch(t){return console.warn(`[config] Failed to parse ${e}: ${t instanceof Error?t.message:t}`),null}}function g(n){let r=n??process.cwd(),i=[],s=o(a(),t,e),c={},l=h(s);l&&(c=m(c,l),i.push(s));let u=o(r,t,e),d=h(u);d&&(c=m(c,d),i.push(u));let f=p.safeParse(c);if(!f.success){let e=f.error.issues.map(e=>` ${e.path.join(`.`)}: ${e.message}`);throw Error(`Invalid configuration:\n${e.join(`
1
+ import{r as e}from"./constants-BLW6shM6.mjs";import{D as t}from"./src-ViJPkmPW.mjs";import{t as n}from"./is-object-B4GcZahG.mjs";import{existsSync as r,readFileSync as i}from"node:fs";import{homedir as a}from"node:os";import{resolve as o}from"node:path";import{parse as s}from"yaml";import{realpath as c}from"node:fs/promises";import{z as l}from"zod";async function u(e){let t=o(e);try{return await c(t)}catch(e){if(e.code!==`ENOENT`){let n=e instanceof Error?e.message:String(e);console.warn(`[normalize-cwd] realpath failed for ${t}: ${n}`)}return t}}const d=l.object({title:l.string().optional(),description:l.string().optional(),tags:l.array(l.string()).optional()}).strict(),f=l.object({match:l.string().min(1,"`match` must be a non-empty glob pattern (e.g. 'specs/**' or 'reports/*/**')"),frontmatter:d}).strict(),p=l.object({content:l.object({dir:l.string().default(`.`),include:l.array(l.string()).min(1).default([`**/*.md`,`**/*.mdx`]),exclude:l.array(l.string()).default([])}).default({dir:`.`,include:[`**/*.md`,`**/*.mdx`],exclude:[]}),github:l.object({oauthAppClientId:l.string().default(`Ov23liqlSd0V1MwR6rhI`)}).default({oauthAppClientId:`Ov23liqlSd0V1MwR6rhI`}),sync:l.object({enabled:l.boolean().optional(),pushIntervalSeconds:l.number().int().min(1).default(60),pullIntervalSeconds:l.number().int().min(1).default(30),autoCommit:l.boolean().default(!0),autoPush:l.boolean().default(!0),autoPull:l.boolean().default(!0),commitMessage:l.string().default(`auto`)}).default({pushIntervalSeconds:60,pullIntervalSeconds:30,autoCommit:!0,autoPush:!0,autoPull:!0,commitMessage:`auto`}),server:l.object({port:l.number().int().min(0).max(65535).default(0),host:l.string().regex(/^[\w.\-:]+$/,`Invalid hostname`).default(`localhost`),openOnAgentEdit:l.boolean().default(!1)}).default({port:0,host:`localhost`,openOnAgentEdit:!1}),persistence:l.object({debounceMs:l.number().int().min(0).default(2e3),maxDebounceMs:l.number().int().min(0).default(1e4)}).default({debounceMs:2e3,maxDebounceMs:1e4}),preview:l.object({baseUrl:l.url().optional()}).default({}),folders:l.array(f).default([]),mcp:l.object({autoStart:l.boolean().default(!0),tools:l.object({read_document:l.object({historyDepth:l.number().int().min(0).default(5)}).default({historyDepth:5}),search:l.object({maxResults:l.number().int().min(1).default(50)}).default({maxResults:50})}).default({read_document:{historyDepth:5},search:{maxResults:50}})}).default({autoStart:!0,tools:{read_document:{historyDepth:5},search:{maxResults:50}}})});function m(e,t){let r={...e};for(let i of Object.keys(t)){let a=e[i],o=t[i];n(o)&&n(a)?r[i]=m(a,o):o!==void 0&&(r[i]=o)}return r}function h(e){if(!r(e))return null;try{let t=s(i(e,`utf-8`));return n(t)?t:null}catch(t){return console.warn(`[config] Failed to parse ${e}: ${t instanceof Error?t.message:t}`),null}}function g(n){let r=n??process.cwd(),i=[],s=o(a(),t,e),c={},l=h(s);l&&(c=m(c,l),i.push(s));let u=o(r,t,e),d=h(u);d&&(c=m(c,d),i.push(u));let f=p.safeParse(c);if(!f.success){let e=f.error.issues.map(e=>` ${e.path.join(`.`)}: ${e.message}`);throw Error(`Invalid configuration:\n${e.join(`
2
2
  `)}`)}return{config:f.data,sources:i}}function _(e,t=process.env){let n=e;return t.PORT&&(n={...n,server:{...n.server,port:Number(t.PORT)}}),t.HOST&&(n={...n,server:{...n.server,host:t.HOST}}),n}function v(e){let t=e.env??process.env,n=e.cacheMs??1e3,r=e.loadConfigFn??g,i=new Map,a=new Map,o=u(e.startupCwd);return async s=>{let c=await u(s??e.startupCwd),l=Date.now(),d=i.get(c);if(d&&d.expiresAt>l)return d.config;let f=a.get(c);if(f)return await f;let p=(async()=>{if(c===await o){let r=_(e.startupConfig,t);return i.set(c,{config:r,expiresAt:Date.now()+n}),r}let a=_(r(c).config,t);return i.set(c,{config:a,expiresAt:Date.now()+n}),a})();a.set(c,p);try{return await p}finally{a.delete(c)}}}export{u as i,g as n,p as r,v as t};
3
- //# sourceMappingURL=loader-xn8pJrM1.mjs.map
3
+ //# sourceMappingURL=loader-BNuhNFOT.mjs.map
@@ -0,0 +1 @@
1
+ import{n as e}from"./loader-BNuhNFOT.mjs";export{e as loadConfig};
@@ -1,2 +1,2 @@
1
- import"./constants-D6bAkegd.mjs";import{D as e}from"./src-ViJPkmPW.mjs";import{resolve as t}from"node:path";function n(e,n){return t(n,e.content.dir)}function r(n){return t(n,e)}export{r as n,n as t};
2
- //# sourceMappingURL=paths-BIa6zXQi.mjs.map
1
+ import"./constants-BLW6shM6.mjs";import{D as e}from"./src-ViJPkmPW.mjs";import{resolve as t}from"node:path";function n(e,n){return t(n,e.content.dir)}function r(n){return t(n,e)}export{r as n,n as t};
2
+ //# sourceMappingURL=paths-DxI4FHOZ.mjs.map
@@ -0,0 +1 @@
1
+ import{n as e,t}from"./paths-DxI4FHOZ.mjs";export{t as resolveContentDir,e as resolveLockDir};
@@ -0,0 +1 @@
1
+ import{n as e,t}from"./preview-oS_HbHIz.mjs";export{t as formatPreviewBlock,e as previewContent};
@@ -1,3 +1,3 @@
1
- import"./constants-D6bAkegd.mjs";import{D as e}from"./src-ViJPkmPW.mjs";import{l as t}from"./src-BrZIzHKR.mjs";import{existsSync as n,lstatSync as r,readdirSync as i,realpathSync as a,statSync as o}from"node:fs";import{join as s,relative as c}from"node:path";function l(e){let{projectDir:n,contentDir:l,include:u,exclude:d,sampleCap:f=5}=e,p=[],m=[];try{r(l)}catch(e){return{totalCount:0,sample:[],contentDir:l,include:u,exclude:d,warnings:[`cannot access content directory ${l}: ${e instanceof Error?e.message:String(e)}`]}}let h;try{h=t({projectDir:n,contentDir:l,includePatterns:u,excludePatterns:d})}catch(e){return{totalCount:0,sample:[],contentDir:l,include:u,exclude:d,warnings:[e instanceof Error?e.message:String(e)]}}function g(e){let t;try{t=i(e,{withFileTypes:!0})}catch(t){let n=t instanceof Error?t.message:String(t);p.push(`could not read directory ${c(l,e)||`.`}: ${n}`);return}for(let n of t){let t=s(e,n.name);if(n.isSymbolicLink()){let e;try{e=a(t)}catch(e){let n=e.code;n===`ENOENT`||n===`ELOOP`?p.push(`broken or cyclic symlink: ${c(l,t)}`):p.push(`cannot resolve symlink ${c(l,t)}: ${n??`unknown error`}`);continue}let n;try{n=o(e)}catch{continue}if(n.isDirectory()){let e=c(l,t);if(h.isDirExcluded(e))continue;g(t)}else if(n.isFile()){let e=c(l,t);if(h.isExcluded(e))continue;m.push(e)}}else if(n.isDirectory()){let e=c(l,t);if(h.isDirExcluded(e))continue;g(t)}else if(n.isFile()){let e=c(l,t);if(h.isExcluded(e))continue;m.push(e)}}}return g(l),{totalCount:m.length,sample:m.slice(0,f),contentDir:l,include:u,exclude:d,warnings:p}}function u(t,r){let i=[],a=c(r,t.contentDir),o=a===``?`./`:`./${a}`;i.push(`Content:`),i.push(` Found ${t.totalCount} markdown files in ${o}`);let l=t.include.join(`, `),u=t.exclude.length>0?t.exclude.join(`, `):`(none)`;if(i.push(` Scope: include=${l} exclude=${u}`),t.sample.length>0){let e=t.sample.join(`, `),n=t.totalCount>t.sample.length?`, …`:``;i.push(` Sample: ${e}${n}`)}if(t.warnings.length>0)for(let e of t.warnings)i.push(` Warning: ${e}`);return i.push(``),n(s(r,`.open-knowledge`,`config.yml`))?(i.push(` To adjust, edit ${e}/config.yml:`),i.push(` content:`),i.push(` include: ${JSON.stringify(t.include)}`),i.push(` exclude: ${JSON.stringify(t.exclude)}`)):(i.push(" Run `open-knowledge init` to scaffold config, then adjust:"),i.push(` ${e}/config.yml → content.include / content.exclude`)),i.push(``),i.push(` Re-check anytime: open-knowledge preview`),i.join(`
1
+ import"./constants-BLW6shM6.mjs";import{D as e}from"./src-ViJPkmPW.mjs";import{l as t}from"./src-DcVg7_6f.mjs";import{existsSync as n,lstatSync as r,readdirSync as i,realpathSync as a,statSync as o}from"node:fs";import{join as s,relative as c}from"node:path";function l(e){let{projectDir:n,contentDir:l,include:u,exclude:d,sampleCap:f=5}=e,p=[],m=[];try{r(l)}catch(e){return{totalCount:0,sample:[],contentDir:l,include:u,exclude:d,warnings:[`cannot access content directory ${l}: ${e instanceof Error?e.message:String(e)}`]}}let h;try{h=t({projectDir:n,contentDir:l,includePatterns:u,excludePatterns:d})}catch(e){return{totalCount:0,sample:[],contentDir:l,include:u,exclude:d,warnings:[e instanceof Error?e.message:String(e)]}}function g(e){let t;try{t=i(e,{withFileTypes:!0})}catch(t){let n=t instanceof Error?t.message:String(t);p.push(`could not read directory ${c(l,e)||`.`}: ${n}`);return}for(let n of t){let t=s(e,n.name);if(n.isSymbolicLink()){let e;try{e=a(t)}catch(e){let n=e.code;n===`ENOENT`||n===`ELOOP`?p.push(`broken or cyclic symlink: ${c(l,t)}`):p.push(`cannot resolve symlink ${c(l,t)}: ${n??`unknown error`}`);continue}let n;try{n=o(e)}catch{continue}if(n.isDirectory()){let e=c(l,t);if(h.isDirExcluded(e))continue;g(t)}else if(n.isFile()){let e=c(l,t);if(h.isExcluded(e))continue;m.push(e)}}else if(n.isDirectory()){let e=c(l,t);if(h.isDirExcluded(e))continue;g(t)}else if(n.isFile()){let e=c(l,t);if(h.isExcluded(e))continue;m.push(e)}}}return g(l),{totalCount:m.length,sample:m.slice(0,f),contentDir:l,include:u,exclude:d,warnings:p}}function u(t,r){let i=[],a=c(r,t.contentDir),o=a===``?`./`:`./${a}`;i.push(`Content:`),i.push(` Found ${t.totalCount} markdown files in ${o}`);let l=t.include.join(`, `),u=t.exclude.length>0?t.exclude.join(`, `):`(none)`;if(i.push(` Scope: include=${l} exclude=${u}`),t.sample.length>0){let e=t.sample.join(`, `),n=t.totalCount>t.sample.length?`, …`:``;i.push(` Sample: ${e}${n}`)}if(t.warnings.length>0)for(let e of t.warnings)i.push(` Warning: ${e}`);return i.push(``),n(s(r,`.open-knowledge`,`config.yml`))?(i.push(` To adjust, edit ${e}/config.yml:`),i.push(` content:`),i.push(` include: ${JSON.stringify(t.include)}`),i.push(` exclude: ${JSON.stringify(t.exclude)}`)):(i.push(" Run `open-knowledge init` to scaffold config, then adjust:"),i.push(` ${e}/config.yml → content.include / content.exclude`)),i.push(``),i.push(` Re-check anytime: open-knowledge preview`),i.join(`
2
2
  `)}export{l as n,u as t};
3
- //# sourceMappingURL=preview-Bv6qni6t.mjs.map
3
+ //# sourceMappingURL=preview-oS_HbHIz.mjs.map
@@ -0,0 +1 @@
1
+ import"./loader-BNuhNFOT.mjs";export{};
@@ -67,13 +67,13 @@ caused by: `+i(o,t)):a},a=e=>i(e,new Set),o=(e,t,i)=>{if(!n(e))return``;let a=i?
67
67
  `)||e.startsWith(`---\r
68
68
  `)){let n=e.indexOf(`
69
69
  ---`,3);n!==-1&&(t=e.slice(n+4))}let n=[],r=new Map,i=S();for(let e of t.split(`
70
- `)){if(i(e))continue;let t=e.match(/^(#{1,6})\s+(.+)$/);if(t){let e=t[2].trim(),i=b(e,r);i&&n.push({level:t[1].length,text:e,slug:i})}}return n}function Qh(e){return!(e.includes(`..`)||e.startsWith(`/`)||e.includes(`\0`)||e.includes(`\\`))}function $h(e){let{hocuspocus:t,sessionManager:n,contentDir:r,getFileIndex:i,getAliasMap:a,enableTestRoutes:o=!1,shadowRef:s,flushGitCommit:l,getCurrentBranch:d,contentRoot:f,backlinkIndex:m,signalChannel:h,agentFocusBroadcaster:g,onAgentWrite:_,getSyncEngine:y,localOpCliArgs:b=[`open-knowledge`],projectDir:x}=e,S=Dm();function C(e){if(!Qh(e))return null;let t=V(r),n=V(t,`${e}${Af(e)}`);return!n.startsWith(`${t}/`)&&n!==t?null:n}function w(e){let t=C(e);if(!t||!L(t))return e;try{return hf(R(t,`utf-8`),e)}catch{return e}}let T={cluster:void 0,category:void 0,tags:void 0};function E(e){try{let n=t.documents.get(e);if(n){let e=n.getMap(`metadata`).get(`frontmatter`);if(typeof e==`string`&&e)return gf(e)}}catch{}try{let t=C(e);if(!t||!L(t))return T;let{frontmatter:n}=A(R(t,`utf-8`));return n?gf(n):T}catch{return T}}function D(e){if(m)try{if(m.getBacklinks(e).length>0)return;let t=performance.now(),n=nf(e,i()),r=performance.now()-t;return r>5&&Ih.debug({docName:e,elapsedMs:r,candidateCount:n.length},`[orphan-hint] findHubCandidates slow`),n.length===0?void 0:[{type:`orphan`,parentCandidates:n,message:`This doc has no backlinks yet. To make it discoverable, consider linking from a parent hub doc (index/overview files in the folder tree): ${n.map(e=>`[[${e}]]`).join(`, `)}.`}]}catch(e){console.warn(`[orphan-hint] computeOrphanHints failed:`,e);return}}function O(e){return a?.().get(e)??e}function k(e){try{return t.documents.get(e)?.connections.size??0}catch{return 0}}function j(e,n){let r=`onStoreDocument-${e}`;(t.debouncer.isDebounced(r)?t.debouncer.executeNow(r):Promise.resolve()).then(()=>l?.()).catch(e=>{Ih.warn({err:e},`[${n}] post-write flush failed`)})}function M(){let e=new Set;for(let[t,n]of i()){e.add(t);for(let t of n.aliases)e.add(t)}return e}function ee(){let e=Promise.resolve();return async function(t){let n=e,r=()=>{};e=new Promise(e=>{r=e}),await n;try{return await t()}finally{r()}}}let N=ee();function te(e){return e instanceof Error&&(e.message===`Managed rename requires backlink index support`||e.message.startsWith(`Cannot rename missing document:`)||e.message.startsWith(`symlink-escape:`))?e.message:`Failed to rename document`}async function ne(e){let r=new Map;for(let n of e){let e=t.documents.get(n);e&&r.set(n,e.getText(`source`).toString())}for(let t of e)await n.closeAllForDoc(t).catch(e=>{console.warn(`[file-ops] Failed to close agent session for ${t}:`,e)});for(let n of e){let e=t.documents.get(n);Bp(n),e&&(t.closeConnections(n),await t.unloadDocument(e))}return r}function P(e,t){for(let{fromDocName:n,toDocName:i}of e){let e=Mp(i,r),a=t.get(n);typeof a==`string`&&z(e,a,`utf-8`);let o=typeof a==`string`?a:L(e)?R(e,`utf-8`):null;typeof o==`string`&&em(e,nm(o))}}function F(e,t){return e.map(e=>{let n=t.get(e);if(typeof n==`string`)return{docName:e,content:n};let i=Mp(e,r);if(!L(i))throw Error(`Cannot snapshot missing document: ${e}`);return{docName:e,content:R(i,`utf-8`)}})}function ie(e){let n=t.documents.get(e);if(n)return n.getText(`source`).toString();let i=Yh(r,`file`,e);return L(i)?R(i,`utf-8`):null}function I(e,t){let n=Yh(r,`file`,e);le(xe(n),{recursive:!0}),z(n,t,`utf-8`),em(n,nm(t)),zp(e,t);let a=i();a instanceof Map&&dm({kind:`update`,path:n,docName:e,content:t},a)}function oe(e,n,r){let i=t.documents.get(e);if(!i)throw Error(`Document is not loaded: ${e}`);let a={markdown:``,rewrites:0};return i.transact(()=>{let t=i.getXmlFragment(`default`),o=i.getText(`source`),s=o.toString();if(a=qh(s,e,n,r),a.rewrites===0)return;let{body:c}=A(a.markdown),l=el.parseWithFallback(c);ls(i,t,tl.nodeFromJSON(l),{mapping:new Map,isOMark:new Map}),p(o,s,a.markdown)},Fh),a}async function se(e,n){return N(async()=>{if(!m)throw Error(`Managed rename requires backlink index support`);let a=Yh(r,`file`,e),o=Yh(r,`file`,n),s=[{fromDocName:e,toDocName:n}],c=[...new Set(m.getBacklinks(e).map(e=>e.source))].sort((e,t)=>e.localeCompare(t)),l=new Map,u=[],d=[];for(let t of[e,...c]){if(l.has(t))continue;let n=ie(t);typeof n==`string`?(l.set(t,n),t!==e&&u.push(t)):t!==e&&d.push(t)}if(typeof l.get(e)!=`string`)throw Error(`Cannot rename missing document: ${e}`);let f=Mm({sourceDocName:e,destinationDocName:n,snapshots:F([...l.keys()],l)}),p=[];return await Rm(r,f,async()=>{for(let e of d)m.deleteDocument(e);for(let r of u){let i=t.documents.get(r)?oe(r,e,n):qh(l.get(r)??``,r,e,n);i.rewrites>0&&(I(r,i.markdown),p.push({docName:r,rewrites:i.rewrites})),m.updateDocumentFromMarkdown(r,i.markdown)}let r=qh((await ne([e])).get(e)??l.get(e)??R(a,`utf-8`),e,e,n);le(xe(o),{recursive:!0}),pe(a,o),P(s,new Map([[e,r.markdown]])),zp(n,r.markdown);let c=i();c instanceof Map&&dm({kind:`rename`,oldPath:a,newPath:o,oldDocName:e,newDocName:n,content:r.markdown},c),m.renameDocument(e,n,r.markdown),r.rewrites>0&&p.push({docName:n,rewrites:r.rewrites})}),m.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist managed rename cache for ${e} -> ${n}:`,t)}),h?.(`files`),h?.(`backlinks`),h?.(`graph`),p.sort((e,t)=>e.docName.localeCompare(t.docName)),{renamed:s,rewrittenDocs:p}})}let ce=/^[a-zA-Z0-9_-]+$/;function ue(e){let t=typeof e.agentId==`string`?e.agentId:void 0;t!==void 0&&!ce.test(t)&&(t=void 0);let n=t?`agent-${t}`:`claude-1`,r=typeof e.agentName==`string`?e.agentName.slice(0,128).replace(/[\r\n]/g,``):`Claude`,i=typeof e.clientName==`string`?e.clientName:void 0;i!==void 0&&(i=i.slice(0,128).replace(/[\r\n]/g,``));let a=typeof e.colorSeed==`string`&&e.colorSeed.length>0?e.colorSeed.slice(0,128):t??n;return{rawAgentId:t,agentId:n,agentName:r,colorSeed:a,clientName:i}}async function _e(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}try{let r;try{r=await Xh(e)}catch{J(t,413,{ok:!1,error:`Payload too large`});return}let i;try{i=r.length>0?JSON.parse(r.toString()):{}}catch{J(t,400,{ok:!1,error:`Invalid JSON`});return}let a=typeof i.docName==`string`&&i.docName.length>0?i.docName:`test-doc`;if(!Qh(a)){J(t,400,{ok:!1,error:`Invalid docName`});return}let o=O(a);if(q(o)){J(t,400,{ok:!1,error:`'${o}' is a reserved document name`});return}let{agentId:s,agentName:c,colorSeed:l,clientName:u}=ue(i),d=await n.getSession(o,s,{displayName:c,colorSeed:l,clientName:u}),f=new Date().toISOString(),p=typeof i.content==`string`?i.content:`Hello from the agent! ${f}`;d.document.awareness.setLocalStateField(`mode`,`editing`);try{d.document.transact(()=>{al(d.document,`${p}\n`,`append`),d.document.getMap(`activity`).set(s,{agentId:s,timestamp:Date.now(),type:`insert`,description:`Added (${c}): ${p.slice(0,50)}`})},rl),Zd(o,s,c,l)}finally{d.document.awareness.setLocalStateField(`mode`,`idle`)}j(o,`agent-write`),J(t,200,{ok:!0,timestamp:f})}catch(e){Ih.error({err:e},`[agent-write] handler failed`),J(t,500,{ok:!1,error:`Internal server error`})}}async function ve(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}try{let r;try{r=await Xh(e)}catch{J(t,413,{ok:!1,error:`Payload too large`});return}let i;try{i=JSON.parse(r.toString())}catch{J(t,400,{ok:!1,error:`Invalid JSON`});return}if(!i||typeof i!=`object`||Array.isArray(i)){J(t,400,{ok:!1,error:`Body must be a JSON object`});return}let{markdown:a,position:o}=i;if(!a||typeof a!=`string`){J(t,400,{ok:!1,error:`markdown field required`});return}let s=o===`prepend`?`prepend`:o===`replace`?`replace`:`append`,c=i.docName,l=typeof c==`string`&&c.length>0?c:`test-doc`;if(!Qh(l)){J(t,400,{ok:!1,error:`Invalid docName`});return}let u=O(l);if(q(u)){J(t,400,{ok:!1,error:`'${u}' is a reserved document name`});return}let{agentId:d,agentName:f,colorSeed:p,clientName:m}=ue(i),h=await n.getSession(u,d,{displayName:f,colorSeed:p,clientName:m}),v=new Date().toISOString();h.document.awareness.setLocalStateField(`mode`,`editing`);try{h.document.transact(()=>{al(h.document,a,s),h.document.getMap(`activity`).set(d,{agentId:d,timestamp:Date.now(),type:`insert`,description:`Added (${f}): ${a.trim().slice(0,50)}`})},rl),Zd(u,d,f,p)}finally{h.document.awareness.setLocalStateField(`mode`,`idle`)}j(u,`agent-write-md`),g?.setFocus(d,{agentName:f,currentDoc:u,writeKind:`write`,ts:Date.now()}),_?.();let y=D(u);J(t,200,{ok:!0,timestamp:v,subscriberCount:k(u),...y?{hints:y}:{}})}catch(e){Ih.error({err:e},`[agent-write-md] handler failed`),J(t,500,{ok:!1,error:`Internal server error`})}}async function ye(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}try{let r=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)||`test-doc`;if(!Qh(r)){J(t,400,{ok:!1,error:`Invalid docName`});return}let i=O(r);if(q(i)){J(t,400,{ok:!1,error:`'${i}' is a reserved document name`});return}J(t,200,{ok:!0,docName:i,content:(await n.getSession(i)).document.getText(`source`).toString()})}catch(e){console.error(`[document-read]`,e),J(t,500,{ok:!1,error:`Internal server error`})}}async function be(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}try{let n=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`dir`);if(n)try{Uh(r,n)}catch{J(t,400,{ok:!1,error:`Invalid directory parameter`});return}let a=i(),o=[];for(let[e,t]of a)if(!(n&&!e.startsWith(`${n}/`)&&e!==n)){o.push({docName:e,size:t.size,modified:t.modified,isSymlink:!1,canonicalDocName:null,targetPath:null});for(let i of t.aliases){if(n&&!i.startsWith(`${n}/`)&&i!==n)continue;let a=B(r,t.canonicalPath);o.push({docName:i,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:a})}}o.sort((e,t)=>e.docName.localeCompare(t.docName)),J(t,200,{ok:!0,documents:o})}catch(e){console.error(`[document-list]`,e),J(t,500,{ok:!1,error:`Internal server error`})}}async function Se(e,t){if(e.method!==`GET`){J(t,405,{ok:!1,error:`Method not allowed`});return}if(!m){J(t,503,{ok:!1,error:`Backlink index not configured`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!n){J(t,400,{ok:!1,error:`Missing docName parameter`});return}if(!Qh(n)){J(t,400,{ok:!1,error:`Invalid docName`});return}J(t,200,{ok:!0,docName:n,backlinks:m.getBacklinks(n).map(e=>({source:e.source,anchor:e.anchor,title:w(e.source),snippet:e.snippet}))})}catch(e){console.error(`[backlinks]`,e),J(t,500,{ok:!1,error:`Failed to read backlinks`})}}async function Ce(e,t){if(e.method!==`GET`){J(t,405,{ok:!1,error:`Method not allowed`});return}if(!m){J(t,503,{ok:!1,error:`Backlink index not configured`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`docNames`);if(!n){J(t,400,{ok:!1,error:`Missing docNames parameter`});return}let r={};for(let e of n.split(`,`)){let t=e.trim();!t||!Qh(t)||(r[t]=m.getBacklinkCount(t))}J(t,200,{ok:!0,counts:r})}catch(e){console.error(`[backlink-counts]`,e),J(t,500,{ok:!1,error:`Failed to read backlink counts`})}}async function we(e,t){if(e.method!==`GET`){J(t,405,{ok:!1,error:`Method not allowed`});return}if(!m){J(t,503,{ok:!1,error:`Backlink index not configured`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!n){J(t,400,{ok:!1,error:`Missing docName parameter`});return}if(!Qh(n)){J(t,400,{ok:!1,error:`Invalid docName`});return}J(t,200,{ok:!0,docName:n,forwardLinks:m.getForwardLinkEntries(n).map(e=>e.kind===`doc`?{kind:`doc`,docName:e.target,anchor:e.anchor,title:w(e.target),snippet:e.snippet}:{kind:`external`,url:e.url,title:e.label??e.url,snippet:e.snippet})})}catch(e){console.error(`[forward-links]`,e),J(t,500,{ok:!1,error:`Failed to read forward links`})}}async function Ee(e,t){if(e.method!==`GET`){J(t,405,{ok:!1,error:`Method not allowed`});return}if(!m){J(t,503,{ok:!1,error:`Backlink index not configured`});return}try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`docName`);if(r&&!Qh(r)){J(t,400,{ok:!1,error:`Invalid docName`});return}let i=n.searchParams.get(`degrees`);if(i&&!r){J(t,400,{ok:!1,error:`docName is required when degrees is provided`});return}let a,o;if(i&&r){let e=Number.parseInt(i,10);if(!Number.isFinite(e)||e<0){J(t,400,{ok:!1,error:`degrees must be a non-negative integer`});return}({nodes:a,links:o}=m.getLinkGraphNeighborhood(r,e))}else ({nodes:a,links:o}=m.getLinkGraph());J(t,200,{ok:!0,nodes:a.map(e=>{if(e.kind===`doc`){let t=E(e.docName);return{id:e.id,kind:`doc`,docName:e.docName,anchor:e.anchor??null,label:w(e.docName),cluster:t.cluster??null,category:t.category??null,tags:t.tags??null}}return{id:e.id,kind:`external`,url:e.url,label:e.label??e.url}}),links:o})}catch(e){console.error(`[link-graph]`,e),J(t,500,{ok:!1,error:`Failed to read link graph`})}}async function De(e,t){if(e.method!==`GET`){J(t,405,{ok:!1,error:`Method not allowed`});return}if(!m){J(t,503,{ok:!1,error:`Backlink index not configured`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`mode`)??`both`;if(!v(n)){J(t,400,{ok:!1,error:`Invalid orphan mode. Allowed values: incoming, outgoing, both`});return}J(t,200,{ok:!0,orphans:m.getOrphans([...i().keys()],n).map(e=>({docName:e,title:w(e)}))})}catch(e){console.error(`[orphans]`,e),J(t,500,{ok:!1,error:`Failed to read orphan pages`})}}async function Oe(e,t){if(e.method!==`GET`){J(t,405,{ok:!1,error:`Method not allowed`});return}if(!m){J(t,503,{ok:!1,error:`Backlink index not configured`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`limit`),r=n?Number.parseInt(n,10):20,i=Number.isFinite(r)&&r>0?r:20;J(t,200,{ok:!0,hubs:m.getHubs(i).map(e=>({docName:e.docName,title:w(e.docName),count:e.count}))})}catch(e){console.error(`[hubs]`,e),J(t,500,{ok:!1,error:`Failed to read hub pages`})}}async function ke(e,t){if(e.method!==`GET`){J(t,405,{ok:!1,error:`Method not allowed`});return}if(!m){J(t,503,{ok:!1,error:`Backlink index not configured`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.getAll(`sourceDocName`);if(n.some(e=>e.length===0||!Qh(e))){J(t,400,{ok:!1,error:`Invalid sourceDocName`});return}let r=n.length?[...new Set(n.map(e=>O(e)))]:void 0;J(t,200,{ok:!0,deadLinks:m.getDeadLinks(M(),r).map(e=>({target:e.target,sources:e.sources.map(e=>({source:e.source,title:w(e.source),snippet:e.snippet}))}))})}catch(e){console.error(`[dead-links]`,e),J(t,500,{ok:!1,error:`Failed to read dead links`})}}async function Ae(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}try{let r;try{r=await Xh(e)}catch{J(t,413,{ok:!1,error:`Payload too large`});return}let i;try{i=JSON.parse(r.toString())}catch{J(t,400,{ok:!1,error:`Invalid JSON`});return}if(!i||typeof i!=`object`||Array.isArray(i)){J(t,400,{ok:!1,error:`Body must be a JSON object`});return}let{find:a,replace:o,docName:s,offset:c}=i;if(typeof a!=`string`||a.length===0){J(t,400,{ok:!1,error:`find field required`});return}if(typeof o!=`string`){J(t,400,{ok:!1,error:`replace field required`});return}let l=Object.hasOwn(i,`offset`),d;if(l){if(typeof c!=`number`||!Number.isInteger(c)||c<0){J(t,400,{ok:!1,error:`offset must be a non-negative integer`});return}d=c}let f=typeof s==`string`&&s.length>0?s:`test-doc`;if(!Qh(f)){J(t,400,{ok:!1,error:`Invalid docName`});return}let p=O(f);if(q(p)){J(t,400,{ok:!1,error:`'${p}' is a reserved document name`});return}let{agentId:m,agentName:h,colorSeed:v,clientName:y}=ue(i),b=await n.getSession(p,m,{displayName:h,colorSeed:v,clientName:y}),x=new Date().toISOString(),S=!1,C=!1;b.document.awareness.setLocalStateField(`mode`,`editing`);try{b.document.transact(()=>{let e=b.document.getXmlFragment(`default`),t=b.document.getMap(`metadata`),n=t.get(`frontmatter`)??``,r=u(n,el.serialize(fs(e,tl).toJSON())),i=d==null?r.indexOf(a):r.slice(d,d+a.length)===a?d:-1;if(i===-1){d==null?S=!0:C=!0;return}let{frontmatter:s,body:c}=A(r.slice(0,i)+o+r.slice(i+a.length));s!==n&&t.set(`frontmatter`,s),al(b.document,c,`replace`),b.document.getMap(`activity`).set(m,{agentId:m,timestamp:Date.now(),type:`insert`,description:`Patched (${h}): ${a.slice(0,50)}`})},rl),!S&&!C&&Zd(p,m,h,v)}finally{b.document.awareness.setLocalStateField(`mode`,`idle`)}if(C){J(t,409,{ok:!1,error:`Target text no longer matches at the requested offset`});return}if(S){J(t,404,{ok:!1,error:`Text not found in document`});return}j(p,`agent-patch`),g?.setFocus(m,{agentName:h,currentDoc:p,writeKind:`edit`,ts:Date.now()}),_?.(),J(t,200,{ok:!0,timestamp:x,subscriberCount:k(p)})}catch(e){Ih.error({err:e},`[agent-patch] handler failed`),J(t,500,{ok:!1,error:`Internal server error`})}}async function Me(e,i){if(e.method!==`POST`){i.writeHead(405),i.end(`Method not allowed`);return}try{let a=O(new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)??`test-doc`),o;try{o=Mp(a,r)}catch(e){console.error(`[test-reset] safeContentPath rejected docName:`,a,e),J(i,400,{ok:!1,error:`Invalid docName`});return}await n.closeAll(a),t.closeConnections(a);let s=`onStoreDocument-${a}`;t.debouncer.isDebounced(s)&&await t.debouncer.executeNow(s);let c=t.documents.get(a);c&&await t.unloadDocument(c),z(o,``,`utf-8`),m&&(m.deleteDocument(a),m.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist cache after test-reset for ${a}:`,e)}),h?.(`backlinks`),h?.(`graph`)),h?.(`files`),J(i,200,{ok:!0})}catch(e){console.error(`[test-reset]`,e),J(i,500,{ok:!1,error:`Internal server error`})}}async function Pe(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}let n=s?.current;if(!n){J(t,400,{ok:!1,error:`Shadow repo not configured`});return}try{let r;try{r=await Xh(e)}catch{J(t,413,{ok:!1,error:`Payload too large`});return}let i=/^[a-zA-Z0-9_-]+$/,a=[],o;if(r.length>0){let e;try{e=JSON.parse(r.toString())}catch{J(t,400,{ok:!1,error:`Invalid JSON`});return}typeof e.message==`string`&&e.message.trim()&&(o=e.message.replace(/[\r\n]/g,` `).slice(0,256)),Array.isArray(e.writers)&&(a=e.writers.map(e=>{let t=e.id??`unknown`;if(!i.test(t))throw Error(`Invalid writer id: ${t}`);return{id:t,name:(e.name??`unknown`).replace(/[\r\n]/g,``),email:(e.email??`noreply@openknowledge.local`).replace(/[\r\n]/g,``)}}))}a.length===0&&(a=[{id:`server`,name:`openknowledge-server`,email:`noreply@openknowledge.local`}]);let s=f??`content`,c=await Ap(n,s,a);console.log(`[shadow] checkpoint ${c.checkpointRef}`);let l;if(x)try{l=await ae(async()=>{let e=Ne({baseDir:x,timeout:{block:15e3}}),t=(await e.tags([`--list`,`ok/v*`])).all.length+1,n=`ok/v${t}`,r=o??`Checkpoint v${t}`,i=s||`.`;return await e.add(i),await e.commit(r,{"--allow-empty":null}),await e.addTag(n),console.log(`[checkpoint] parent-git commit + tag ${n}`),n})}catch(e){console.warn(`[checkpoint] parent-git commit failed (non-fatal):`,e)}J(t,200,{ok:!0,checkpointRef:c.checkpointRef,...l?{versionTag:l}:{}})}catch(e){console.error(`[save-version]`,e),J(t,500,{ok:!1,error:`Internal server error`})}}async function Fe(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}let n=s?.current;if(!n){J(t,400,{ok:!1,error:`Shadow repo not configured`});return}let r=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),i=r.searchParams.get(`docName`)??``,a=r.searchParams.get(`branch`)??d?.()??`main`;if(!i){J(t,400,{ok:!1,error:`docName query parameter is required`});return}if(a.includes(`..`)||!/^[a-zA-Z0-9][a-zA-Z0-9._/-]*$/.test(a)){J(t,400,{ok:!1,error:`Invalid branch name`});return}let o=Number(r.searchParams.get(`limit`)??`50`),c=Number(r.searchParams.get(`offset`)??`0`),l=Math.min(200,Number.isFinite(o)?o:50),u=Number.isFinite(c)?c:0,p=r.searchParams.get(`type`)??void 0,m=r.searchParams.get(`author`)??void 0,h=r.searchParams.get(`excludeAuthor`)??void 0,g=Date.now();try{let e=await Mh(n,{docName:i,branch:a,limit:l,offset:u,type:p,author:m,excludeAuthor:h},f??`content`),r=Date.now()-g;console.log(`[timeline] query docName=${i} entries=${e.entries.length} duration=${r}ms`),J(t,200,{ok:!0,...e})}catch(e){console.error(`[history]`,e),J(t,500,{ok:!1,error:e instanceof Error?e.message:String(e)})}}async function Ie(e,t,n){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}let r=s?.current;if(!r){J(t,400,{ok:!1,error:`Shadow repo not configured`});return}let i=Lh(new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)??``,f??`content`);if(`error`in i){J(t,400,{ok:!1,error:i.error});return}let a=i.path,o=vp(r);if(!/^[0-9a-f]{40}$/i.test(n)){J(t,400,{ok:!1,error:`Invalid commit SHA`});return}try{try{await o.raw(`cat-file`,`-e`,`${n}:${a}`)}catch{J(t,404,{ok:!1,error:`Document did not exist at this version`});return}let e=await o.raw(`show`,`${n}:${a}`),[r=``,i=``]=(await o.raw(`log`,`-1`,`--format=%aI%x00%an`,n)).trim().split(`\0`);J(t,200,{ok:!0,sha:n,content:e,timestamp:r,author:i})}catch(e){console.error(`[history-version]`,e),J(t,500,{ok:!1,error:`Internal server error`})}}async function Le(e,n){if(e.method!==`GET`){n.writeHead(405),n.end(`Method not allowed`);return}let r=s?.current;if(!r){J(n,400,{ok:!1,error:`Shadow repo not configured`});return}let i=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),a=i.searchParams.get(`docName`)??``,o=i.searchParams.get(`from`)??``,c=i.searchParams.get(`to`)??``;if(!c||!/^[0-9a-f]{40}$/i.test(c)){J(n,400,{ok:!1,error:`'to' must be a valid 40-char commit SHA`});return}let l=Lh(a,f??`content`);if(`error`in l){J(n,400,{ok:!1,error:l.error});return}let u=l.path,d=vp(r);try{let e;try{e=await d.raw(`show`,`${c}:${u}`)}catch{J(n,404,{ok:!1,error:`Document did not exist at the target version`});return}let r;if(o&&/^[0-9a-f]{40}$/i.test(o))try{r=await d.raw(`show`,`${o}:${u}`)}catch{J(n,404,{ok:!1,error:`Document did not exist at the source version`});return}else{let e=t.documents.get(a);if(!e){J(n,409,{ok:!1,error:`Document is not currently open — open it in the editor first`});return}r=e.getText(`source`).toString()}let i=A(r).body,s=A(e).body,l=kl(i,s),f=[],p=0,m=0;for(let e of l){let t=e.value.replace(/\n$/,``).split(`
71
- `),n=e.added?`added`:e.removed?`removed`:`unchanged`;for(let e of t)f.push({type:n,text:e});e.added&&(p+=t.length),e.removed&&(m+=t.length)}J(n,200,{ok:!0,lines:f,additions:p,deletions:m})}catch(e){console.error(`[diff]`,e),J(n,500,{ok:!1,error:`Internal server error`})}}async function Re(e,n){if(e.method!==`POST`){n.writeHead(405),n.end(`Method not allowed`);return}let r=s?.current;if(!r){J(n,400,{ok:!1,error:`Shadow repo not configured`});return}let i;try{i=await Xh(e)}catch{J(n,413,{ok:!1,error:`Payload too large`});return}let a;try{a=i.length>0?JSON.parse(i.toString()):{}}catch{J(n,400,{ok:!1,error:`Invalid JSON`});return}if(!a||typeof a!=`object`||Array.isArray(a)){J(n,400,{ok:!1,error:`Body must be a JSON object`});return}let{docName:o,commitSha:c,versionTag:u}=a,d=typeof o==`string`?o:``,p=typeof c==`string`?c:``,m=typeof u==`string`?u:void 0;if(!d){J(n,400,{ok:!1,error:`docName required`});return}if(!p||!/^[0-9a-f]{40}$/i.test(p)){J(n,400,{ok:!1,error:`commitSha must be a valid 40-char commit SHA`});return}let h=f??`content`,g=Lh(d,h);if(`error`in g){J(n,400,{ok:!1,error:g.error});return}let _=g.path,v=vp(r),y=Date.now();try{try{await v.raw(`cat-file`,`-e`,`${p}:${_}`)}catch{J(n,404,{ok:!1,error:`Document did not exist at this version`});return}let e=await v.raw(`show`,`${p}:${_}`),i=new Date().toISOString();await Tp(r,h,{action:`rollback`,context:{docName:d,targetSha:p}});let a=t.documents.get(d);if(!a){J(n,409,{ok:!1,error:`Document is not currently open — open it in the editor first`});return}let{frontmatter:o,body:s}=A(e),c=el.parseWithFallback(s),u=tl.nodeFromJSON(c),g=a.getXmlFragment(`default`);a.transact(()=>{ls(a,g,u,{mapping:new Map,isOMark:new Map});let t=a.getText(`source`),n=t.toString();n!==e&&(t.delete(0,n.length),t.insert(0,e)),a.getMap(`metadata`).set(`frontmatter`,o)},Ph),zp(d,e),l&&l().catch(e=>{console.warn(`[rollback] flush git commit failed:`,e)});let b=Date.now()-y;if(console.log(`[rollback] docName=${d} from=${p.slice(0,8)} duration=${b}ms`),x){let e=`Restored to ${m??p.slice(0,8)}: ${d}`,t=f??`content`;ae(async()=>{let n=Ne({baseDir:x,timeout:{block:15e3}}),r=t||`.`;await n.add(r),await n.commit(e,{"--allow-empty":null}),console.log(`[rollback] parent-git commit: ${e}`)}).catch(e=>{console.warn(`[rollback] parent-git commit failed (non-fatal):`,e)})}J(n,200,{ok:!0,restoredFrom:p,timestamp:i})}catch(e){console.error(`[rollback]`,e),J(n,500,{ok:!1,error:e instanceof Error?e.message:String(e)})}}async function ze(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}J(t,200,Qc())}async function Be(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}J(t,200,c())}async function Ve(e,t){if(!Om(e.socket.remoteAddress)){J(t,403,{ok:!1,error:`loopback-required`});return}if(!km(e.headers.host)){J(t,403,{ok:!1,error:`host-header-not-allowed`});return}if(e.method!==`GET`){J(t,405,{ok:!1,error:`Method not allowed`});return}let n=V(r),i=n,a=!0;try{i=fe(n)}catch(e){let r=e?.code;if(r===`ENOENT`)console.warn(`[workspace] contentDir does not exist; returning unresolved path`,{path:n}),a=!1;else{console.warn(`[workspace] realpath failed for contentDir`,{path:n,err:e}),J(t,500,{ok:!1,error:`workspace-realpath-failed`,code:r??null});return}}J(t,200,{ok:!0,contentDir:i,pathSeparator:Te,symlinkResolved:a})}let He=1440*60*1e3;async function Ue(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}if(!s?.current){J(t,200,[]);return}let n=Date.now(),r=[],i=V(s.current.gitDir,`rescue`);if(L(i))try{let e=de(i).filter(e=>Tf(e));for(let t of e){let e=V(i,t),a=he(e);if(n-a.mtimeMs>He){try{ge(e)}catch(e){console.debug(`[rescue] cleanup failed (non-critical):`,e)}continue}r.push({docName:Ef(t),timestamp:a.mtime.toISOString(),size:a.size,source:`flat`})}}catch(e){console.error(`[rescue] Failed to list flat-file rescue buffers:`,e)}try{let e=d?.()??`main`,t=await Dp(s.current,e);for(let e of t)r.push({...e,source:`timeline`})}catch(e){console.error(`[rescue] Failed to list timeline-ref rescue checkpoints:`,e)}J(t,200,r)}async function We(e,t,n){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}if(!s?.current){t.writeHead(404),t.end(`Not found`);return}let r=V(s.current.gitDir,`rescue`),i=V(r,`${n}${Af(n)}`);if(!i.startsWith(`${r}/`)){t.writeHead(400),t.end(`Invalid document name`);return}if(L(i)){let e=he(i);if(Date.now()-e.mtimeMs>He)try{ge(i)}catch{}else{let e=R(i,`utf-8`);t.writeHead(200,{"Content-Type":`text/markdown`,"X-Content-Type-Options":`nosniff`}),t.end(e);return}}try{let e=d?.()??`main`,r=(await Dp(s.current,e)).filter(e=>e.docName===n).sort((e,t)=>t.timestamp.localeCompare(e.timestamp))[0];if(r){let e=vp(s.current),n=((await e.raw(`ls-tree`,`-r`,r.sha)).trim().split(`
72
- `)[0]??``).split(/\s+/)[2];if(n){let r=await e.raw(`cat-file`,`-p`,n);t.writeHead(200,{"Content-Type":`text/markdown`,"X-Content-Type-Options":`nosniff`}),t.end(r);return}}}catch(e){console.warn(`[rescue] timeline-ref fallback failed:`,e)}t.writeHead(404),t.end(`Not found`)}async function Ge(e,t){if(e.method!==`POST`){J(t,405,{ok:!1,error:`Method not allowed`});return}try{let n;try{n=await Xh(e)}catch{J(t,413,{ok:!1,error:`Payload too large`});return}let a;try{a=JSON.parse(n.toString())}catch{J(t,400,{ok:!1,error:`Invalid JSON`});return}if(!a||typeof a!=`object`||Array.isArray(a)){J(t,400,{ok:!1,error:`Body must be a JSON object`});return}let{path:o}=a;if(!o||typeof o!=`string`||o.length===0){J(t,400,{ok:!1,error:`path is required`});return}if(!Tf(o)){J(t,400,{ok:!1,error:`path must end with .md or .mdx`});return}if(o.includes(`..`)||o.startsWith(`/`)||o.includes(`\0`)||o.includes(`\\`)){J(t,400,{ok:!1,error:`path must not contain .. or start with /`});return}let s=V(r),c=V(s,o);if(!c.startsWith(`${s}/`)&&c!==s){J(t,400,{ok:!1,error:`path must not escape content directory`});return}let l=Ef(o);if(q(l)){J(t,400,{ok:!1,error:`'${l}' is a reserved document name`});return}le(xe(c),{recursive:!0});try{z(c,``,{encoding:`utf-8`,flag:`wx`})}catch(e){if(e.code===`EEXIST`){J(t,409,{ok:!1,error:`File already exists`});return}throw e}let u=Ef(o),d=typeof i==`function`?i():null;d instanceof Map&&dm({kind:`create`,path:c,docName:u,content:``},d),m&&(m.updateDocumentFromMarkdown(u,``),m.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist create-page cache for ${u}:`,e)}),h?.(`backlinks`),h?.(`graph`)),h?.(`files`),J(t,200,{ok:!0,docName:u})}catch(e){console.error(`[create-page]`,e),J(t,500,{ok:!1,error:`Failed to create page`})}}async function Ke(e,t){if(e.method!==`GET`){J(t,405,{ok:!1,error:`Method not allowed`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!n||typeof n!=`string`||n.length===0){J(t,400,{ok:!1,error:`Missing docName parameter`});return}if(!Qh(n)){J(t,400,{ok:!1,error:`Invalid docName`});return}let r=C(n);if(!r){J(t,400,{ok:!1,error:`Invalid docName`});return}if(!L(r)){J(t,404,{ok:!1,error:`Page not found`});return}J(t,200,{ok:!0,docName:n,headings:Zh(R(r,`utf-8`))})}catch(e){console.error(`[page-headings]`,e),J(t,500,{ok:!1,error:`Failed to read headings`})}}async function qe(e,t){if(e.method!==`POST`){J(t,405,{ok:!1,error:`Method not allowed`});return}try{let n;try{n=await Xh(e)}catch{J(t,413,{ok:!1,error:`Payload too large`});return}let i;try{i=JSON.parse(n.toString())}catch{J(t,400,{ok:!1,error:`Invalid JSON`});return}if(!i||typeof i!=`object`||Array.isArray(i)){J(t,400,{ok:!1,error:`Body must be a JSON object`});return}let{docName:a,newDocName:o}=i;if(typeof a!=`string`||typeof o!=`string`){J(t,400,{ok:!1,error:`docName and newDocName are required`});return}if(!Wh(a)||!Wh(o)){J(t,400,{ok:!1,error:`Document names must be relative content paths`});return}if(q(a)||q(o)){J(t,400,{ok:!1,error:`Reserved document names cannot be renamed`});return}if(a===o){J(t,200,{ok:!0,renamed:[],rewrittenDocs:[]});return}if(!m){J(t,503,{ok:!1,error:`Backlink index unavailable`});return}let s=Yh(r,`file`,a),c=Yh(r,`file`,o);if(!L(s)){J(t,404,{ok:!1,error:`Document does not exist`});return}if(L(c)){J(t,409,{ok:!1,error:`Destination already exists`});return}let l=await se(a,o);J(t,200,{ok:!0,renamed:l.renamed,rewrittenDocs:l.rewrittenDocs})}catch(e){console.error(`[rename]`,e),J(t,500,{ok:!1,error:te(e)})}}async function Je(e,t){if(e.method!==`POST`){J(t,405,{ok:!1,error:`Method not allowed`});return}try{let n;try{n=await Xh(e)}catch{J(t,413,{ok:!1,error:`Payload too large`});return}let a;try{a=JSON.parse(n.toString())}catch{J(t,400,{ok:!1,error:`Invalid JSON`});return}if(!a||typeof a!=`object`||Array.isArray(a)){J(t,400,{ok:!1,error:`Body must be a JSON object`});return}let{kind:o,fromPath:s,toPath:c}=a;if(o!==`file`&&o!==`folder`){J(t,400,{ok:!1,error:`kind must be "file" or "folder"`});return}if(typeof s!=`string`||typeof c!=`string`){J(t,400,{ok:!1,error:`fromPath and toPath are required`});return}if(!Wh(s)||!Wh(c)){J(t,400,{ok:!1,error:`Paths must be relative content paths`});return}if(s===c){J(t,200,{ok:!0,renamed:[]});return}let l=Yh(r,o,s),u=Yh(r,o,c);if(!L(l)){J(t,404,{ok:!1,error:`${o} does not exist`});return}if(L(u)){J(t,409,{ok:!1,error:`Destination already exists`});return}let d=he(l);if(o===`file`&&!d.isFile()||o===`folder`&&!d.isDirectory()){J(t,400,{ok:!1,error:`Source path is not a ${o}`});return}let f=Gh(i(),o,s),p=o===`file`?[{fromDocName:s,toDocName:c}]:f.map(e=>({fromDocName:e,toDocName:Kh(e,o,s,c)})),m=await ne(p.map(({fromDocName:e})=>e)),h=()=>{le(xe(u),{recursive:!0}),pe(l,u),P(p,m)};o===`file`?await Rm(r,Mm({sourceDocName:s,destinationDocName:c,snapshots:F(p.map(({fromDocName:e})=>e),m)}),h):h(),J(t,200,{ok:!0,renamed:p})}catch(e){console.error(`[rename-path]`,e),J(t,500,{ok:!1,error:`Failed to rename path`})}}async function Ye(e,t){if(e.method!==`POST`){J(t,405,{ok:!1,error:`Method not allowed`});return}try{let n;try{n=await Xh(e)}catch{J(t,413,{ok:!1,error:`Payload too large`});return}let a;try{a=JSON.parse(n.toString())}catch{J(t,400,{ok:!1,error:`Invalid JSON`});return}if(!a||typeof a!=`object`||Array.isArray(a)){J(t,400,{ok:!1,error:`Body must be a JSON object`});return}let{kind:o,path:s}=a;if(o!==`file`&&o!==`folder`){J(t,400,{ok:!1,error:`kind must be "file" or "folder"`});return}if(typeof s!=`string`||!Wh(s)){J(t,400,{ok:!1,error:`path must be a relative content path`});return}let c=Yh(r,o,s);if(!L(c)){J(t,404,{ok:!1,error:`${o} does not exist`});return}let l=he(c);if(o===`file`&&!l.isFile()||o===`folder`&&!l.isDirectory()){J(t,400,{ok:!1,error:`Target path is not a ${o}`});return}let u=o===`file`?[s]:Gh(i(),o,s);await ne(u),o===`file`?ge(c):me(c,{recursive:!0,force:!1}),J(t,200,{ok:!0,deletedDocNames:u})}catch(e){console.error(`[delete-path]`,e),J(t,500,{ok:!1,error:`Failed to delete path`})}}async function Xe(e,t){if(e.method!==`GET`){J(t,405,{ok:!1,error:`Method not allowed`});return}try{let e=i(),n=[];for(let[t,i]of e){let e=t;try{e=hf(R(V(r,`${t}${Af(t)}`),`utf-8`),t)}catch(e){console.warn(`[pages] Failed to read title for ${t}:`,e)}n.push({docName:t,title:e,size:i.size,modified:i.modified})}n.sort((e,t)=>e.docName.localeCompare(t.docName)),J(t,200,{ok:!0,pages:n})}catch(e){console.error(`[pages]`,e),J(t,500,{ok:!1,error:`Failed to list pages`})}}async function Ze(e,n){if(e.method!==`GET`){J(n,405,{ok:!1,error:`Method not allowed`});return}try{let r=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!r){J(n,400,{ok:!1,error:`Missing docName parameter`});return}if(!Qh(r)){J(n,400,{ok:!1,error:`Invalid docName`});return}if(q(r)){J(n,400,{ok:!1,error:`'${r}' is a reserved document name`});return}J(n,200,{ok:!0,...await Th({hocuspocus:t,fileIndex:i(),docName:r})})}catch(e){if(e instanceof rh){J(n,404,{ok:!1,error:`Page not found`});return}console.error(`[suggest-links]`,e),J(n,500,{ok:!1,error:`Failed to suggest links`})}}async function Qe(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}let n;try{n=await Hh(e,10485760)}catch(e){let n=e instanceof Error?e.message:String(e);n===`Payload too large`?J(t,413,{ok:!1,error:`Payload too large`}):n===`No file received`?J(t,400,{ok:!1,error:`No file received`}):J(t,400,{ok:!1,error:`Failed to parse upload: ${n}`});return}let{filename:i,buffer:a,parentDocName:o}=n;if(!o){J(t,400,{ok:!1,error:`parentDocName is required`});return}if(o.includes(`\0`)||o.includes(`..`)||o.startsWith(`/`)){J(t,400,{ok:!1,error:`path-escape`});return}let s=V(r),c=V(s,xe(o));if(!Np(c,s)){J(t,400,{ok:!1,error:`path-escape`});return}try{let e=fe(c),n;try{n=fe(s)}catch{n=s}if(!Np(e,n)){J(t,400,{ok:!1,error:`path-escape`});return}}catch(e){if(e.code!==`ENOENT`){J(t,400,{ok:!1,error:`path-escape`});return}}let l=await Jd(a),u=l?.mime,d=l?.ext;if(!u){let e=a.subarray(0,256).toString(`utf-8`).trimStart();(e.startsWith(`<svg`)||e.startsWith(`<?xml`)&&e.includes(`<svg`))&&(u=`image/svg+xml`,d=`svg`)}if(!u||!d||!Rh.has(u)){J(t,400,{ok:!1,error:`Unsupported file type${u?`: ${u}`:``}`});return}let f;f=!i||i===`upload`||zh.test(i)?`pasted-${new Date().toISOString().replace(/[-:T]/g,``).slice(0,14).replace(/(\d{8})(\d{6})/,`$1-$2`)}.${d}`:Bh(i),le(c,{recursive:!0});try{let e=Vh(c,f,a),n=B(r,V(c,e));console.log(`[upload] ok ${n} ${a.length}`),J(t,200,{ok:!0,src:e})}catch(e){let n=e instanceof Error?e.message:String(e);console.error(`[upload] error ${f} ${a.length} ${n}`),J(t,500,{ok:!1,error:`Failed to save file`})}}let $e=`/api/local-op/clone`,et=`/api/local-op/open`,tt=600*1e3;async function nt(e,t){if(!Em(e,t,J))return;if(e.method!==`POST`){J(t,405,{ok:!1,error:`Method not allowed`});return}let n,r;try{let i=await Xh(e),a=JSON.parse(i.toString());if(typeof a.url!=`string`||!a.url){J(t,400,{ok:!1,error:`Missing or invalid url`});return}if(typeof a.dir!=`string`||!a.dir){J(t,400,{ok:!1,error:`Missing or invalid dir`});return}n=a.url,r=a.dir}catch{J(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!xm(n)){J(t,400,{ok:!1,error:`URL protocol not allowed`});return}if(!Cm(r)){J(t,400,{ok:!1,error:`dir must be within the user home directory`});return}if(!S.tryAcquire($e)){J(t,429,{ok:!1,error:`A clone operation is already in progress`});return}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let i=Sm(r),[a,...o]=b,s=[...o,`clone`,`--json`,n,i],c=!1,l=!1,u=null,d=``,f=je(a,s,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),p=setTimeout(()=>{c=!0,f.kill(`SIGTERM`)},tt);f.stdout.on(`data`,e=>{d+=e.toString(`utf-8`);let n=d.split(`
73
- `);d=n.pop()??``;for(let e of n){if(!e.trim())continue;let n=null;try{n=JSON.parse(e)}catch{}if(n&&n.type===`complete`&&typeof n.dir==`string`){u=n.dir;continue}t.writableEnded||t.write(`${e}\n`)}});let m=[];f.stderr.on(`data`,e=>{m.push(e),Ih.debug({msg:e.toString(`utf-8`).trim()},`[local-op/clone] stderr`)}),f.on(`close`,e=>{clearTimeout(p);let i=Buffer.concat(m).toString(`utf-8`).trim();if(l){S.release($e);return}l=!0,(async()=>{try{if(c&&!t.writableEnded)t.write(`${JSON.stringify({type:`error`,message:`Clone timed out after 10 minutes`})}\n`);else if(e!==0&&!t.writableEnded){i&&Ih.warn({code:e,stderr:i,url:n,dir:r},`[local-op/clone] clone failed`);let a=i?` — ${i}`:``;t.write(`${JSON.stringify({type:`error`,message:`Clone process exited with code ${e}${a}`})}\n`)}else if(e===0&&u&&!t.writableEnded){let e=await rt(u);t.writableEnded||(`port`in e?t.write(`${JSON.stringify({type:`complete`,port:e.port})}\n`):t.write(`${JSON.stringify({type:`error`,message:e.error})}\n`))}}finally{t.writableEnded||t.end(),S.release($e)}})()}),f.on(`error`,e=>{clearTimeout(p),l||(l=!0,t.writableEnded||(t.write(`${JSON.stringify({type:`error`,message:e.message})}\n`),t.end())),S.release($e)})}async function rt(e){let t=V(Sm(e)),n=V(t,`.open-knowledge`),r=Sf(n);if(r&&r.port>0)return{port:r.port};let i=re(n),[a,...o]=b,s=i&&i.port>0?`ui`:`start`,c=je(a,[...o,s],{cwd:t,detached:!0,stdio:[`ignore`,`ignore`,`pipe`],env:{...process.env}}),l=[];c.stderr?.on(`data`,e=>{l.push(e),Ih.warn({cwd:t,cliCmd:s,msg:e.toString(`utf-8`).trim()},`[local-op/open] child stderr`)});let u=null;c.on(`exit`,e=>{u=e??-1}),c.unref();let d=Date.now()+45e3;for(;Date.now()<d;){await new Promise(e=>setTimeout(e,500));let e=Sf(n);if(e&&e.port>0)return{port:e.port};if(u!==null){let e=Buffer.concat(l).toString(`utf-8`).trim();return{error:`\`ok ${s}\` exited (code ${u})${e?` — ${e}`:``}`}}}let f=Buffer.concat(l).toString(`utf-8`).trim();return{error:`UI did not start within the expected time${f?` — ${f}`:``}`}}async function it(e,t){if(!Em(e,t,J))return;if(e.method!==`POST`){J(t,405,{ok:!1,error:`Method not allowed`});return}let n;try{let r=await Xh(e),i=JSON.parse(r.toString());if(typeof i.dir!=`string`||!i.dir){J(t,400,{ok:!1,error:`Missing or invalid dir`});return}n=i.dir}catch{J(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!Cm(n)){J(t,400,{ok:!1,error:`dir must be within the user home directory`});return}if(!S.tryAcquire(et)){J(t,429,{ok:!1,error:`A server-open operation is already in progress`});return}try{let e=await rt(n);`port`in e?J(t,200,{port:e.port}):J(t,504,{ok:!1,error:e.error})}finally{S.release(et)}}let at=`/api/local-op/auth/login`,ot=`/api/local-op/auth/status`,st=`/api/local-op/auth/repos`,ct=`/api/local-op/auth/signout`,lt=`/api/local-op/auth/pat`;async function ut(e,t){if(!Em(e,t,J))return;if(e.method!==`POST`){J(t,405,{ok:!1,error:`Method not allowed`});return}let n=`github.com`;try{let t=await Xh(e),r=JSON.parse(t.toString());typeof r.host==`string`&&r.host&&(n=r.host)}catch{J(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!S.tryAcquire(at)){J(t,429,{ok:!1,error:`An auth login operation is already in progress`});return}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let[r,...i]=b,a=[...i,`auth`,`login`,`--json`,`--host`,n],o=!1,s=!1,c=``,l=je(r,a,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),u=setTimeout(()=>{l.kill(`SIGTERM`)},tt),d=()=>{l.killed||l.kill(`SIGTERM`)};t.on(`close`,d),l.stdout.on(`data`,e=>{t.writableEnded||t.write(e),c+=e.toString(`utf-8`);let n=c.split(`
74
- `);c=n.pop()??``;for(let e of n)if(e.trim())try{let t=JSON.parse(e);(t.type===`complete`||t.type===`error`)&&(s=!0)}catch{}}),l.stderr.on(`data`,e=>{Ih.debug({msg:e.toString(`utf-8`).trim()},`[local-op/auth/login] stderr`)}),l.on(`close`,e=>{clearTimeout(u),t.off(`close`,d),o||(o=!0,t.writableEnded||(e===0&&!s?t.write(`${JSON.stringify({type:`complete`,host:n,login:``})}\n`):e!==0&&t.write(`${JSON.stringify({type:`error`,message:`auth login exited with code ${e}`})}\n`)),t.end()),S.release(at)}),l.on(`error`,e=>{clearTimeout(u),t.off(`close`,d),o||(o=!0,t.writableEnded||(t.write(`${JSON.stringify({type:`error`,message:e.message})}\n`),t.end())),S.release(at)})}async function dt(e,t){if(!Em(e,t,J))return;if(e.method!==`POST`){J(t,405,{ok:!1,error:`Method not allowed`});return}let n=`github.com`;try{let t=(await Xh(e)).toString().trim();if(t.length>0){let e=JSON.parse(t);typeof e.host==`string`&&e.host&&(n=e.host)}}catch{J(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!S.tryAcquire(ot)){J(t,429,{ok:!1,error:`An auth status operation is already in progress`});return}try{let[e,...r]=b,i=[...r,`auth`,`status`,`--json`,`--host`,n],a=(await new Promise((t,n)=>{let r=je(e,i,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),a=setTimeout(()=>{r.kill(`SIGTERM`)},3e4),o=[];r.stdout.on(`data`,e=>o.push(e)),r.on(`close`,()=>{clearTimeout(a),t(Buffer.concat(o).toString(`utf-8`))}),r.on(`error`,e=>{clearTimeout(a),n(e)})})).split(`
75
- `).map(e=>e.trim()).filter(Boolean),o=null;for(let e=a.length-1;e>=0;e--)try{o=JSON.parse(a[e]);break}catch{}o===null?J(t,200,{authenticated:!1}):J(t,200,o)}catch(e){J(t,500,{ok:!1,error:e instanceof Error?e.message:`auth status failed`})}finally{S.release(ot)}}async function ft(e,t){if(!Em(e,t,J))return;if(e.method!==`POST`){J(t,405,{ok:!1,error:`Method not allowed`});return}let n=`github.com`;try{let t=(await Xh(e)).toString().trim();if(t.length>0){let e=JSON.parse(t);typeof e.host==`string`&&e.host&&(n=e.host)}}catch{J(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!S.tryAcquire(st)){J(t,429,{ok:!1,error:`An auth repos operation is already in progress`});return}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let[r,...i]=b,a=[...i,`auth`,`repos`,`--json`,`--host`,n],o=!1,s=je(r,a,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),c=setTimeout(()=>{s.kill(`SIGTERM`)},tt);s.stdout.on(`data`,e=>{t.writableEnded||t.write(e)}),s.stderr.on(`data`,e=>{Ih.debug({msg:e.toString(`utf-8`).trim()},`[local-op/auth/repos] stderr`)}),s.on(`close`,e=>{clearTimeout(c),o||(o=!0,e!==0&&!t.writableEnded&&t.write(`${JSON.stringify({type:`error`,message:`auth repos exited with code ${e}`})}\n`),t.end()),S.release(st)}),s.on(`error`,e=>{clearTimeout(c),o||(o=!0,t.writableEnded||(t.write(`${JSON.stringify({type:`error`,message:e.message})}\n`),t.end())),S.release(st)})}async function pt(e,t){if(!Em(e,t,J))return;if(e.method!==`POST`){J(t,405,{ok:!1,error:`Method not allowed`});return}let n=`github.com`;try{let t=await Xh(e),r=JSON.parse(t.toString());typeof r.host==`string`&&r.host&&(n=r.host)}catch{J(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!S.tryAcquire(ct)){J(t,429,{ok:!1,error:`An auth signout operation is already in progress`});return}try{let[e,...r]=b,i=[...r,`auth`,`signout`,`--host`,n];await new Promise((t,n)=>{let r=je(e,i,{stdio:`ignore`,env:{...process.env}}),a=setTimeout(()=>{r.kill(`SIGTERM`)},3e4);r.on(`close`,()=>{clearTimeout(a),t()}),r.on(`error`,e=>{clearTimeout(a),n(e)})}),J(t,200,{ok:!0})}catch(e){J(t,500,{ok:!1,error:e instanceof Error?e.message:`auth signout failed`})}finally{S.release(ct)}}async function mt(e,t){if(!Em(e,t,J))return;if(e.method!==`POST`){J(t,405,{ok:!1,error:`Method not allowed`});return}let n=`github.com`,r;try{let i=await Xh(e),a=JSON.parse(i.toString());if(typeof a.pat!=`string`||!a.pat){J(t,400,{ok:!1,error:`Missing or invalid pat`});return}r=a.pat,typeof a.host==`string`&&a.host&&(n=a.host)}catch{J(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!S.tryAcquire(lt)){J(t,429,{ok:!1,error:`An auth pat operation is already in progress`});return}try{let[e,...i]=b,a=[...i,`auth`,`pat`,`--json`,`--host`,n],o=(await new Promise((t,n)=>{let i=je(e,a,{stdio:[`pipe`,`pipe`,`pipe`],env:{...process.env}}),o=setTimeout(()=>{i.kill(`SIGTERM`)},3e4);i.stdin.write(`${r}\n`),i.stdin.end();let s=[];i.stdout.on(`data`,e=>s.push(e)),i.on(`close`,e=>{clearTimeout(o),e===0?t(Buffer.concat(s).toString(`utf-8`)):n(Error(`auth pat exited with code ${e}`))}),i.on(`error`,e=>{clearTimeout(o),n(e)})})).split(`
76
- `).map(e=>e.trim()).filter(Boolean),s=null;for(let e=o.length-1;e>=0;e--)try{s=JSON.parse(o[e]);break}catch{}s===null?J(t,200,{ok:!0}):J(t,200,s)}catch(e){J(t,500,{ok:!1,error:e instanceof Error?e.message:`auth pat failed`})}finally{S.release(lt)}}async function ht(e,t){if(Em(e,t,J)){if(e.method!==`GET`){J(t,405,{ok:!1,error:`Method not allowed`});return}if(!x){J(t,400,{ok:!1,error:`No project directory configured`});return}try{J(t,200,{ok:!0,identity:await _m(x)})}catch(e){J(t,500,{ok:!1,error:e instanceof Error?e.message:`identity resolution failed`})}}}let gt=`/api/local-op/auth/set-identity`;async function _t(e,t){if(!Em(e,t,J))return;if(e.method!==`POST`){J(t,405,{ok:!1,error:`Method not allowed`});return}let n,r;try{let i=await Xh(e),a=JSON.parse(i.toString());if(typeof a.name!=`string`||!a.name.trim()){J(t,400,{ok:!1,error:`Missing or invalid name`});return}if(typeof a.email!=`string`||!a.email.trim()){J(t,400,{ok:!1,error:`Missing or invalid email`});return}n=a.name.trim(),r=a.email.trim()}catch{J(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!x){J(t,400,{ok:!1,error:`No project directory configured`});return}if(!S.tryAcquire(gt)){J(t,429,{ok:!1,error:`A set-identity operation is already in progress`});return}try{vm(x,n,r),y?.()?.refreshIdentity().catch(()=>{}),J(t,200,{ok:!0})}catch(e){J(t,500,{ok:!1,error:e instanceof Error?e.message:`set-identity failed`})}finally{S.release(gt)}}async function vt(e,t){if(!Em(e,t,J))return;if(e.method!==`GET`){J(t,405,{ok:!1,error:`Method not allowed`});return}let n=y?.();if(!n){J(t,200,{state:`dormant`,lastSyncUtc:null,lastFetchUtc:null,lastPushedSha:null,ahead:0,behind:0,consecutiveFailures:0,conflictCount:0,hasRemote:!1,syncEnabled:!1,identityUnresolved:!1});return}J(t,200,n.getStatus())}async function yt(e,t){if(!Em(e,t,J))return;if(e.method!==`POST`){J(t,405,{ok:!1,error:`Method not allowed`});return}let n=y?.();if(!n){J(t,503,{ok:!1,error:`Sync engine not active`});return}let r=`sync`;try{let t=await Xh(e);if(t.length>0){let e=JSON.parse(t.toString());(e.op===`push`||e.op===`pull`||e.op===`sync`)&&(r=e.op)}}catch{}J(t,202,{ok:!0,op:r}),n.trigger(r)}async function bt(e,t){if(!Em(e,t,J))return;if(e.method!==`POST`){J(t,405,{ok:!1,error:`Method not allowed`});return}let n=y?.();if(!n){J(t,503,{ok:!1,error:`Sync engine not active`});return}let r;try{let n=await Xh(e),i=JSON.parse(n.toString());if(typeof i.enabled!=`boolean`){J(t,400,{ok:!1,error:`enabled must be a boolean`});return}r=i.enabled}catch{J(t,400,{ok:!1,error:`Invalid JSON body`});return}await n.setEnabled(r),J(t,200,{ok:!0,status:n.getStatus()})}async function H(e,t){if(!Em(e,t,J))return;if(e.method!==`GET`){J(t,405,{ok:!1,error:`Method not allowed`});return}let n=y?.();J(t,200,{conflicts:n?n.getConflicts():[]})}async function xt(e,t){if(!Em(e,t,J))return;if(e.method!==`POST`){J(t,405,{ok:!1,error:`Method not allowed`});return}let n=y?.();if(!n){J(t,503,{ok:!1,error:`Sync engine not active`});return}let r;try{let t=await Xh(e);r=JSON.parse(t.toString())}catch{J(t,400,{ok:!1,error:`Invalid JSON body`});return}let{file:i,strategy:a,content:o}=r;if(!i||typeof i!=`string`){J(t,400,{ok:!1,error:`Missing required field: file`});return}if(a!==`mine`&&a!==`theirs`&&a!==`content`){J(t,400,{ok:!1,error:`Invalid strategy: must be 'mine', 'theirs', or 'content'`});return}try{await n.resolveConflict(i,a,o),J(t,200,{ok:!0})}catch(e){J(t,500,{ok:!1,error:e instanceof Error?e.message:String(e)})}}async function St(e,t){if(!Em(e,t,J))return;if(e.method!==`GET`){J(t,405,{ok:!1,error:`Method not allowed`});return}if(!x){J(t,503,{ok:!1,error:`Project repo not configured`});return}let n=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`file`);if(!n){J(t,400,{ok:!1,error:`Missing required query param: file`});return}if(n.includes(`..`)||n.startsWith(`/`)){J(t,400,{ok:!1,error:`Invalid file path`});return}let r=Ne({baseDir:x,timeout:{block:15e3}});async function i(e){try{return await r.raw([`show`,`:${e}:${n}`])}catch{return``}}try{let[e,r,a]=await Promise.all([i(1),i(2),i(3)]);J(t,200,{ok:!0,file:n,base:e,ours:r,theirs:a})}catch(e){J(t,500,{ok:!1,error:e instanceof Error?e.message:String(e)})}}async function Ct(e,t){if(!Em(e,t,J))return;if(e.method!==`POST`){J(t,405,{ok:!1,error:`Method not allowed`});return}let n=y?.();if(!n){J(t,503,{ok:!1,error:`Sync engine not active`});return}try{await n.abortMerge(),J(t,200,{ok:!0})}catch(e){J(t,500,{ok:!1,error:e instanceof Error?e.message:String(e)})}}let wt={"/api/document":ye,"/api/documents":be,"/api/backlinks":Se,"/api/backlink-counts":Ce,"/api/forward-links":we,"/api/link-graph":Ee,"/api/dead-links":ke,"/api/orphans":De,"/api/hubs":Oe,"/api/pages":Xe,"/api/suggest-links":Ze,"/api/page-headings":Ke,"/api/create-page":Ge,"/api/rename":qe,"/api/rename-path":Je,"/api/delete-path":Ye,"/api/upload-image":Qe,"/api/agent-write":_e,"/api/agent-write-md":ve,"/api/agent-patch":Ae,"/api/save-version":Pe,"/api/history":Fe,"/api/diff":Le,"/api/rollback":Re,"/api/metrics/reconciliation":ze,"/api/metrics/parse-health":Be,"/api/rescue":Ue,"/api/workspace":Ve,"/api/sync/status":vt,"/api/sync/trigger":yt,"/api/sync/set-enabled":bt,"/api/sync/conflicts":H,"/api/sync/conflict-content":St,"/api/sync/resolve-conflict":xt,"/api/sync/abort-merge":Ct,"/api/local-op/clone":nt,"/api/local-op/open":it,"/api/local-op/auth/login":ut,"/api/local-op/auth/status":dt,"/api/local-op/auth/repos":ft,"/api/local-op/auth/signout":pt,"/api/local-op/auth/pat":mt,"/api/local-op/auth/identity":ht,"/api/local-op/auth/set-identity":_t};return o&&(wt[`/api/test-reset`]=Me),{priority:100,async onRequest({request:e,response:t}){let n=e.url?.split(`?`)[0];if(!n)return;if(n.startsWith(`/api/`)&&(typeof t.setHeader==`function`&&(t.setHeader(`Access-Control-Allow-Origin`,`*`),t.setHeader(`Access-Control-Allow-Methods`,`GET, POST, PUT, DELETE, OPTIONS`),t.setHeader(`Access-Control-Allow-Headers`,`Content-Type, Authorization`)),e.method===`OPTIONS`)){t.writeHead(204),t.end();return}let r=wt[n];if(r){await r(e,t);return}if(n.startsWith(`/api/rescue/`)){let r=decodeURIComponent(n.slice(12));r&&await We(e,t,r);return}if(n.startsWith(`/api/history/`)){let r=decodeURIComponent(n.slice(13));r&&await Ie(e,t,r);return}}}}function eg(e){let t=e.scheduler??T,n=e.warnBeforeMs??3e5,r=0,i=null,a=null,o=!1,s=!1;function c(){i!==null&&(t.clearTimeout(i),i=null),a!==null&&(t.clearTimeout(a),a=null)}function l(){c(),!(s||o)&&r===0&&(n>0&&n<e.thresholdMs&&(a=t.setTimeout(()=>{a=null,r===0&&!o&&e.log?.warn({msUntilShutdown:n,webSocketClientCount:0},`idle shutdown pending: no WebSocket clients`)},e.thresholdMs-n)),i=t.setTimeout(()=>{if(i=null,!(s||o)&&r===0){o=!0,e.log?.info({webSocketClientCount:0},`idle shutdown firing`);try{let t=e.onShutdown();t&&typeof t.then==`function`&&t.catch(t=>{e.log?.error({err:t},`idle shutdown handler rejected`)})}catch(t){e.log?.error({err:t},`idle shutdown handler threw`)}}},e.thresholdMs))}let u=(e,t)=>{e.url?.startsWith(`/collab`)&&(r++,c(),t.once(`close`,()=>{r--,r<0&&(r=0),r===0&&l()}))};return e.httpServer.on(`upgrade`,u),l(),{detach:()=>{s||(s=!0,e.httpServer.off(`upgrade`,u),c())}}}const tg=Math.floor,ng=(e,t)=>e<t?e:t,rg=(e,t)=>e>t?e:t;Number.isNaN,Number.isInteger,Number.isNaN,Number.parseInt;const ig=String.fromCharCode;String.fromCodePoint,ig(65535);const ag=e=>{let t=unescape(encodeURIComponent(e)),n=t.length,r=new Uint8Array(n);for(let e=0;e<n;e++)r[e]=t.codePointAt(e);return r},og=typeof TextEncoder<`u`?new TextEncoder:null,sg=og?e=>og.encode(e):ag;let cg=typeof TextDecoder>`u`?null:new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0});cg&&cg.decode(new Uint8Array).length===1&&(cg=null);const lg=(e,t)=>{let n=e.cbuf.length;e.cpos===n&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(n*2),e.cpos=0),e.cbuf[e.cpos++]=t},ug=(e,t)=>{for(;t>127;)lg(e,128|127&t),t=tg(t/128);lg(e,127&t)},dg=new Uint8Array(3e4),fg=dg.length/3,pg=og&&og.encodeInto?(e,t)=>{if(t.length<fg){let n=og.encodeInto(t,dg).written||0;ug(e,n);for(let t=0;t<n;t++)lg(e,dg[t])}else hg(e,sg(t))}:(e,t)=>{let n=unescape(encodeURIComponent(t)),r=n.length;ug(e,r);for(let t=0;t<r;t++)lg(e,n.codePointAt(t))},mg=(e,t)=>{let n=e.cbuf.length,r=e.cpos,i=ng(n-r,t.length),a=t.length-i;e.cbuf.set(t.subarray(0,i),r),e.cpos+=i,a>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(rg(n*2,a)),e.cbuf.set(t.subarray(i)),e.cpos=a)},hg=(e,t)=>{ug(e,t.byteLength),mg(e,t)},gg=e=>Error(e);gg(`Unexpected end of array`),gg(`Integer out of Range`);let _g=function(e){return e[e.Token=0]=`Token`,e[e.PermissionDenied=1]=`PermissionDenied`,e[e.Authenticated=2]=`Authenticated`,e}({});const vg=(e,t)=>{ug(e,_g.PermissionDenied),pg(e,t)},yg=(e,t)=>{ug(e,_g.Authenticated),pg(e,t)},bg=e=>{ug(e,_g.Token)},xg={code:4205,reason:`Reset Connection`},Sg={code:4401,reason:`Unauthorized`},Cg={code:4403,reason:`Forbidden`},wg={code:4408,reason:`Connection Timeout`},Tg=e=>Array.from(e.entries()).map(([e,t])=>({clientId:e,...t}));var Eg=class extends Error{constructor(e){super(e??`Further hooks skipped`),this.name=`SkipFurtherHooksError`}};let Dg=function(e){return e[e.Connecting=0]=`Connecting`,e[e.Open=1]=`Open`,e[e.Closing=2]=`Closing`,e[e.Closed=3]=`Closed`,e}({});const Og=Error(`request for lock canceled`);var kg=function(e,t,n,r){function i(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){e.done?n(e.value):i(e.value).then(o,s)}c((r=r.apply(e,t||[])).next())})},Ag=class{constructor(e,t=Og){this._value=e,this._cancelError=t,this._queue=[],this._weightedWaiters=[]}acquire(e=1,t=0){if(e<=0)throw Error(`invalid weight ${e}: must be positive`);return new Promise((n,r)=>{let i={resolve:n,reject:r,weight:e,priority:t},a=Mg(this._queue,e=>t<=e.priority);a===-1&&e<=this._value?this._dispatchItem(i):this._queue.splice(a+1,0,i)})}runExclusive(e){return kg(this,arguments,void 0,function*(e,t=1,n=0){let[r,i]=yield this.acquire(t,n);try{return yield e(r)}finally{i()}})}waitForUnlock(e=1,t=0){if(e<=0)throw Error(`invalid weight ${e}: must be positive`);return this._couldLockImmediately(e,t)?Promise.resolve():new Promise(n=>{this._weightedWaiters[e-1]||(this._weightedWaiters[e-1]=[]),jg(this._weightedWaiters[e-1],{resolve:n,priority:t})})}isLocked(){return this._value<=0}getValue(){return this._value}setValue(e){this._value=e,this._dispatchQueue()}release(e=1){if(e<=0)throw Error(`invalid weight ${e}: must be positive`);this._value+=e,this._dispatchQueue()}cancel(){this._queue.forEach(e=>e.reject(this._cancelError)),this._queue=[]}_dispatchQueue(){for(this._drainUnlockWaiters();this._queue.length>0&&this._queue[0].weight<=this._value;)this._dispatchItem(this._queue.shift()),this._drainUnlockWaiters()}_dispatchItem(e){let t=this._value;this._value-=e.weight,e.resolve([t,this._newReleaser(e.weight)])}_newReleaser(e){let t=!1;return()=>{t||(t=!0,this.release(e))}}_drainUnlockWaiters(){if(this._queue.length===0)for(let e=this._value;e>0;e--){let t=this._weightedWaiters[e-1];t&&(t.forEach(e=>e.resolve()),this._weightedWaiters[e-1]=[])}else{let e=this._queue[0].priority;for(let t=this._value;t>0;t--){let n=this._weightedWaiters[t-1];if(!n)continue;let r=n.findIndex(t=>t.priority<=e);(r===-1?n:n.splice(0,r)).forEach((e=>e.resolve()))}}}_couldLockImmediately(e,t){return(this._queue.length===0||this._queue[0].priority<t)&&e<=this._value}};function jg(e,t){let n=Mg(e,e=>t.priority<=e.priority);e.splice(n+1,0,t)}function Mg(e,t){for(let n=e.length-1;n>=0;n--)if(t(e[n]))return n;return-1}var Ng=function(e,t,n,r){function i(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){e.done?n(e.value):i(e.value).then(o,s)}c((r=r.apply(e,t||[])).next())})},Pg=class{constructor(e){this._semaphore=new Ag(1,e)}acquire(){return Ng(this,arguments,void 0,function*(e=0){let[,t]=yield this._semaphore.acquire(1,e);return t})}runExclusive(e,t=0){return this._semaphore.runExclusive(()=>e(),1,t)}isLocked(){return this._semaphore.isLocked()}waitForUnlock(e=0){return this._semaphore.waitForUnlock(1,e)}release(){this._semaphore.isLocked()&&this._semaphore.release()}cancel(){return this._semaphore.cancel()}};let Fg,Ig,Lg,Rg,zg=!0;typeof process<`u`&&({FORCE_COLOR:Fg,NODE_DISABLE_COLORS:Ig,NO_COLOR:Lg,TERM:Rg}=process.env||{},zg=process.stdout&&process.stdout.isTTY);const Y={enabled:!Ig&&Lg==null&&Rg!==`dumb`&&(Fg!=null&&Fg!==`0`||zg),reset:X(0,0),bold:X(1,22),dim:X(2,22),italic:X(3,23),underline:X(4,24),inverse:X(7,27),hidden:X(8,28),strikethrough:X(9,29),black:X(30,39),red:X(31,39),green:X(32,39),yellow:X(33,39),blue:X(34,39),magenta:X(35,39),cyan:X(36,39),white:X(37,39),gray:X(90,39),grey:X(90,39),bgBlack:X(40,49),bgRed:X(41,49),bgGreen:X(42,49),bgYellow:X(43,49),bgBlue:X(44,49),bgMagenta:X(45,49),bgCyan:X(46,49),bgWhite:X(47,49)};function Bg(e,t){let n=0,r,i=``,a=``;for(;n<e.length;n++)r=e[n],i+=r.open,a+=r.close,~t.indexOf(r.close)&&(t=t.replace(r.rgx,r.close+r.open));return i+t+a}function Vg(e,t){let n={has:e,keys:t};return n.reset=Y.reset.bind(n),n.bold=Y.bold.bind(n),n.dim=Y.dim.bind(n),n.italic=Y.italic.bind(n),n.underline=Y.underline.bind(n),n.inverse=Y.inverse.bind(n),n.hidden=Y.hidden.bind(n),n.strikethrough=Y.strikethrough.bind(n),n.black=Y.black.bind(n),n.red=Y.red.bind(n),n.green=Y.green.bind(n),n.yellow=Y.yellow.bind(n),n.blue=Y.blue.bind(n),n.magenta=Y.magenta.bind(n),n.cyan=Y.cyan.bind(n),n.white=Y.white.bind(n),n.gray=Y.gray.bind(n),n.grey=Y.grey.bind(n),n.bgBlack=Y.bgBlack.bind(n),n.bgRed=Y.bgRed.bind(n),n.bgGreen=Y.bgGreen.bind(n),n.bgYellow=Y.bgYellow.bind(n),n.bgBlue=Y.bgBlue.bind(n),n.bgMagenta=Y.bgMagenta.bind(n),n.bgCyan=Y.bgCyan.bind(n),n.bgWhite=Y.bgWhite.bind(n),n}function X(e,t){let n={open:`\x1b[${e}m`,close:`\x1b[${t}m`,rgx:RegExp(`\\x1b\\[${t}m`,`g`)};return function(t){return this!==void 0&&this.has!==void 0?(~this.has.indexOf(e)||(this.has.push(e),this.keys.push(n)),t===void 0?this:Y.enabled?Bg(this.keys,t+``):t+``):t===void 0?Vg([e],[n]):Y.enabled?Bg([n],t+``):t+``}}const Hg=Math.floor,Ug=(e,t)=>e<t?e:t,Wg=(e,t)=>e>t?e:t;Number.isNaN;const Gg=2**53-1;Number.isInteger,Number.isNaN,Number.parseInt;const Kg=()=>new Set,qg=Array.from;Array.isArray;const Jg=String.fromCharCode;String.fromCodePoint,Jg(65535);const Yg=e=>{let t=unescape(encodeURIComponent(e)),n=t.length,r=new Uint8Array(n);for(let e=0;e<n;e++)r[e]=t.codePointAt(e);return r},Xg=typeof TextEncoder<`u`?new TextEncoder:null,Zg=Xg?e=>Xg.encode(e):Yg;let Qg=typeof TextDecoder>`u`?null:new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0});Qg&&Qg.decode(new Uint8Array).length===1&&(Qg=null);const $g=e=>Error(e);var e_=class{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}};const t_=()=>new e_,n_=e=>{let t=e.cpos;for(let n=0;n<e.bufs.length;n++)t+=e.bufs[n].length;return t},r_=e=>{let t=new Uint8Array(n_(e)),n=0;for(let r=0;r<e.bufs.length;r++){let i=e.bufs[r];t.set(i,n),n+=i.length}return t.set(new Uint8Array(e.cbuf.buffer,0,e.cpos),n),t},i_=(e,t)=>{let n=e.cbuf.length;e.cpos===n&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(n*2),e.cpos=0),e.cbuf[e.cpos++]=t},Z=(e,t)=>{for(;t>127;)i_(e,128|127&t),t=Hg(t/128);i_(e,127&t)},a_=new Uint8Array(3e4),o_=a_.length/3,s_=Xg&&Xg.encodeInto?(e,t)=>{if(t.length<o_){let n=Xg.encodeInto(t,a_).written||0;Z(e,n);for(let t=0;t<n;t++)i_(e,a_[t])}else l_(e,Zg(t))}:(e,t)=>{let n=unescape(encodeURIComponent(t)),r=n.length;Z(e,r);for(let t=0;t<r;t++)i_(e,n.codePointAt(t))},c_=(e,t)=>{let n=e.cbuf.length,r=e.cpos,i=Ug(n-r,t.length),a=t.length-i;e.cbuf.set(t.subarray(0,i),r),e.cpos+=i,a>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(Wg(n*2,a)),e.cbuf.set(t.subarray(i)),e.cpos=a)},l_=(e,t)=>{Z(e,t.byteLength),c_(e,t)},u_=$g(`Unexpected end of array`),d_=$g(`Integer out of Range`);var f_=class{constructor(e){this.arr=e,this.pos=0}};const p_=e=>new f_(e),m_=e=>e.pos!==e.arr.length,h_=(e,t)=>{let n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n},g_=e=>h_(e,v_(e)),__=e=>e.arr[e.pos++],v_=e=>{let t=0,n=1,r=e.arr.length;for(;e.pos<r;){let r=e.arr[e.pos++];if(t+=(r&127)*n,n*=128,r<128)return t;if(t>Gg)throw d_}throw u_},y_=Qg?e=>Qg.decode(g_(e)):e=>{let t=v_(e);if(t===0)return``;{let n=String.fromCodePoint(__(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(__(e));else for(;t>0;){let r=t<1e4?t:1e4,i=e.arr.subarray(e.pos,e.pos+r);e.pos+=r,n+=String.fromCodePoint.apply(null,i),t-=r}return decodeURIComponent(escape(n))}};var b_=class{constructor(e){e instanceof Uint8Array||(e=new Uint8Array(e)),this.decoder=p_(e)}get encoder(){return this.encoderInternal||=t_(),this.encoderInternal}readVarUint8Array(){return g_(this.decoder)}peekVarUint8Array(){let{pos:e}=this.decoder,t=g_(this.decoder);return this.decoder.pos=e,t}readVarUint(){return v_(this.decoder)}readVarString(){return y_(this.decoder)}toUint8Array(){return r_(this.encoder)}writeVarUint(e){Z(this.encoder,e)}writeVarString(e){s_(this.encoder,e)}get length(){return n_(this.encoder)}};const x_=Date.now,S_=()=>new Map,C_=(e,t,n)=>{let r=e.get(t);return r===void 0&&e.set(t,r=n()),r};var w_=class{constructor(){this._observers=S_()}on(e,t){C_(this._observers,e,Kg).add(t)}once(e,t){let n=(...r)=>{this.off(e,n),t(...r)};this.on(e,n)}off(e,t){let n=this._observers.get(e);n!==void 0&&(n.delete(t),n.size===0&&this._observers.delete(e))}emit(e,t){return qg((this._observers.get(e)||S_()).values()).forEach(e=>e(...t))}destroy(){this._observers=S_()}};const T_=Symbol(`Equality`),E_=Object.keys,D_=e=>E_(e).length,O_=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),k_=(e,t)=>{if(e===t)return!0;if(e==null||t==null||e.constructor!==t.constructor&&(e.constructor||Object)!==(t.constructor||Object))return!1;if(e[T_]!=null)return e[T_](t);switch(e.constructor){case ArrayBuffer:e=new Uint8Array(e),t=new Uint8Array(t);case Uint8Array:if(e.byteLength!==t.byteLength)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;break;case Set:if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;break;case Map:if(e.size!==t.size)return!1;for(let n of e.keys())if(!t.has(n)||!k_(e.get(n),t.get(n)))return!1;break;case void 0:case Object:if(D_(e)!==D_(t))return!1;for(let n in e)if(!O_(e,n)||!k_(e[n],t[n]))return!1;break;case Array:if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!k_(e[n],t[n]))return!1;break;default:return!1}return!0},A_=3e4;var j_=class extends w_{constructor(e){super(),this.doc=e,this.clientID=e.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{let e=x_();this.getLocalState()!==null&&A_/2<=e-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());let t=[];this.meta.forEach((n,r)=>{r!==this.clientID&&A_<=e-n.lastUpdated&&this.states.has(r)&&t.push(r)}),t.length>0&&M_(this,t,`timeout`)},Hg(A_/10)),e.on(`destroy`,()=>{this.destroy()}),this.setLocalState({})}destroy(){this.emit(`destroy`,[this]),this.setLocalState(null),super.destroy(),clearInterval(this._checkInterval)}getLocalState(){return this.states.get(this.clientID)||null}setLocalState(e){let t=this.clientID,n=this.meta.get(t),r=n===void 0?0:n.clock+1,i=this.states.get(t);e===null?this.states.delete(t):this.states.set(t,e),this.meta.set(t,{clock:r,lastUpdated:x_()});let a=[],o=[],s=[],c=[];e===null?c.push(t):i==null?e!=null&&a.push(t):(o.push(t),k_(i,e)||s.push(t)),(a.length>0||s.length>0||c.length>0)&&this.emit(`change`,[{added:a,updated:s,removed:c},`local`]),this.emit(`update`,[{added:a,updated:o,removed:c},`local`])}setLocalStateField(e,t){let n=this.getLocalState();n!==null&&this.setLocalState({...n,[e]:t})}getStates(){return this.states}};const M_=(e,t,n)=>{let r=[];for(let n=0;n<t.length;n++){let i=t[n];if(e.states.has(i)){if(e.states.delete(i),i===e.clientID){let t=e.meta.get(i);e.meta.set(i,{clock:t.clock+1,lastUpdated:x_()})}r.push(i)}}r.length>0&&(e.emit(`change`,[{added:[],updated:[],removed:r},n]),e.emit(`update`,[{added:[],updated:[],removed:r},n]))},N_=(e,t,n=e.states)=>{let r=t.length,i=t_();Z(i,r);for(let a=0;a<r;a++){let r=t[a],o=n.get(r)||null,s=e.meta.get(r).clock;Z(i,r),Z(i,s),s_(i,JSON.stringify(o))}return r_(i)},P_=(e,t,n)=>{let r=p_(t),i=x_(),a=[],o=[],s=[],c=[],l=v_(r);for(let t=0;t<l;t++){let t=v_(r),n=v_(r),l=JSON.parse(y_(r)),u=e.meta.get(t),d=e.states.get(t),f=u===void 0?0:u.clock;(f<n||f===n&&l===null&&e.states.has(t))&&(l===null?t===e.clientID&&e.getLocalState()!=null?n++:e.states.delete(t):e.states.set(t,l),e.meta.set(t,{clock:n,lastUpdated:i}),u===void 0&&l!==null?a.push(t):u!==void 0&&l===null?c.push(t):l!==null&&(k_(l,d)||s.push(t),o.push(t)))}(a.length>0||s.length>0||c.length>0)&&e.emit(`change`,[{added:a,updated:s,removed:c},n]),(a.length>0||o.length>0||c.length>0)&&e.emit(`update`,[{added:a,updated:o,removed:c},n])},F_=(e,t)=>{Z(e,0),l_(e,qr(t))},I_=(e,t,n)=>{Z(e,1),l_(e,Vr(t,n))},L_=(e,t,n)=>I_(t,n,g_(e)),R_=(e,t,n,r)=>{try{Rr(t,g_(e),n)}catch(e){r?.(e),console.error(`Caught error while handling a Yjs update`,e)}},z_=(e,t)=>{Z(e,2),l_(e,t)},B_=R_;function V_(e){return typeof e==`object`&&!!e&&`source`in e&&(e.source===`connection`||e.source===`redis`||e.source===`local`)}function H_(e){if(!V_(e))return!1;switch(e.source){case`connection`:return!1;case`redis`:return!0;case`local`:return e.skipStoreHooks??!1}}let Q=function(e){return e[e.Unknown=-1]=`Unknown`,e[e.Sync=0]=`Sync`,e[e.Awareness=1]=`Awareness`,e[e.Auth=2]=`Auth`,e[e.QueryAwareness=3]=`QueryAwareness`,e[e.SyncReply=4]=`SyncReply`,e[e.Stateless=5]=`Stateless`,e[e.BroadcastStateless=6]=`BroadcastStateless`,e[e.CLOSE=7]=`CLOSE`,e[e.SyncStatus=8]=`SyncStatus`,e[e.Ping=9]=`Ping`,e[e.Pong=10]=`Pong`,e}({});var U_=class{constructor(e){this.encoder=t_(),s_(this.encoder,e)}createSyncMessage(){return this.type=Q.Sync,Z(this.encoder,Q.Sync),this}createSyncReplyMessage(){return this.type=Q.SyncReply,Z(this.encoder,Q.SyncReply),this}createAwarenessUpdateMessage(e,t){this.type=Q.Awareness,this.category=`Update`;let n=N_(e,t||Array.from(e.getStates().keys()));return Z(this.encoder,Q.Awareness),l_(this.encoder,n),this}writeQueryAwareness(){return this.type=Q.QueryAwareness,this.category=`Update`,Z(this.encoder,Q.QueryAwareness),this}writeTokenSyncRequest(){return this.type=Q.Auth,this.category=`TokenSync`,Z(this.encoder,Q.Auth),bg(this.encoder),this}writeAuthenticated(e){return this.type=Q.Auth,this.category=`Authenticated`,Z(this.encoder,Q.Auth),yg(this.encoder,e?`readonly`:`read-write`),this}writePermissionDenied(e){return this.type=Q.Auth,this.category=`PermissionDenied`,Z(this.encoder,Q.Auth),vg(this.encoder,e),this}writeFirstSyncStepFor(e){return this.category=`SyncStep1`,F_(this.encoder,e),this}writeUpdate(e){return this.category=`Update`,z_(this.encoder,e),this}writeStateless(e){return this.category=`Stateless`,Z(this.encoder,Q.Stateless),s_(this.encoder,e),this}writeBroadcastStateless(e){return this.category=`Stateless`,Z(this.encoder,Q.BroadcastStateless),s_(this.encoder,e),this}writeSyncStatus(e){return this.category=`SyncStatus`,Z(this.encoder,Q.SyncStatus),Z(this.encoder,e?1:0),this}writeCloseMessage(e){return this.type=Q.CLOSE,Z(this.encoder,Q.CLOSE),s_(this.encoder,e),this}toUint8Array(){return r_(this.encoder)}},W_=class{constructor(e,t){this.message=e,this.defaultTransactionOrigin=t}async apply(e,t,n){let{message:r}=this,i=r.readVarUint(),a=r.length;switch(i){case Q.Sync:case Q.SyncReply:r.writeVarUint(Q.Sync),await this.readSyncMessage(r,e,t,n,i!==Q.SyncReply),r.length>a+1&&(n?n(r.toUint8Array()):t&&t.send(r.toUint8Array()));break;case Q.Awareness:P_(e.awareness,r.readVarUint8Array(),t??null);break;case Q.QueryAwareness:this.applyQueryAwarenessMessage(e,t,n);break;case Q.Stateless:t?.callbacks.statelessCallback({connection:t,documentName:e.name,document:e,payload:y_(r.decoder)});break;case Q.BroadcastStateless:{let t=r.readVarString();e.getConnections().forEach(e=>{e.sendStateless(t)});break}case Q.CLOSE:t?.close({code:1e3,reason:`provider_initiated`});break;case Q.Auth:if(r.readVarUint()===_g.Token){t?.callbacks.onTokenSyncCallback({token:r.readVarString()});break}console.error(`Received an authentication message on a connection that is already fully authenticated. Probably your provider has been destroyed + recreated really fast.`);break;default:console.error(`Unable to handle message of type ${i}: no handler defined! Are your provider/server versions aligned?`)}}async readSyncMessage(e,t,n,r,i=!0){let a=e.readVarUint(),o=n?.messageAddress??t.name;switch(n&&await n.callbacks.beforeSync(n,{type:a,payload:e.peekVarUint8Array()}),a){case 0:if(L_(e.decoder,e.encoder,t),r&&i)r(new U_(o).createSyncReplyMessage().writeFirstSyncStepFor(t).toUint8Array());else if(n){let e=new U_(o).createSyncMessage().writeFirstSyncStepFor(t);n.send(e.toUint8Array())}break;case 1:if(n?.readOnly){if(ci(ii(t),g_(e.decoder))){let e=new U_(o).writeSyncStatus(!0);n.send(e.toUint8Array())}else{let e=new U_(o).writeSyncStatus(!1);n.send(e.toUint8Array())}break}R_(e.decoder,t,n?{source:`connection`,connection:n}:this.defaultTransactionOrigin??{source:`local`}),n&&n.send(new U_(o).writeSyncStatus(!0).toUint8Array());break;case 2:if(n?.readOnly){n.send(new U_(o).writeSyncStatus(!1).toUint8Array());break}B_(e.decoder,t,n?{source:`connection`,connection:n}:this.defaultTransactionOrigin??{source:`local`}),n&&n.send(new U_(o).writeSyncStatus(!0).toUint8Array());break;default:throw Error(`Received a message with an unknown type: ${a}`)}return a}applyQueryAwarenessMessage(e,t,n){let r=new U_(t?.messageAddress??e.name).createAwarenessUpdateMessage(e.awareness);n&&n(r.toUint8Array())}},G_=class{get messageAddress(){return this.sessionId?`${this.document.name}\0${this.sessionId}`:this.document.name}constructor(e,t,n,r,i,a=!1,o,s){this.callbacks={onClose:[(e,t)=>{}],beforeHandleMessage:(e,t)=>Promise.resolve(),beforeSync:(e,t)=>Promise.resolve(),statelessCallback:e=>Promise.resolve(),onTokenSyncCallback:e=>Promise.resolve()},this.messageQueue=[],this.processingPromise=Promise.resolve(),this.webSocket=e,this.context=i,this.document=n,this.request=t,this.socketId=r,this.readOnly=a,this.sessionId=o??null,this.providerVersion=s??null,this.document.addConnection(this),this.sendCurrentAwareness()}onClose(e){return this.callbacks.onClose.push(e),this}onStatelessCallback(e){return this.callbacks.statelessCallback=e,this}beforeHandleMessage(e){return this.callbacks.beforeHandleMessage=e,this}beforeSync(e){return this.callbacks.beforeSync=e,this}onTokenSyncCallback(e){return this.callbacks.onTokenSyncCallback=e,this}waitForPendingMessages(){return this.processingPromise}send(e){if(this.webSocket.readyState===Dg.Closing||this.webSocket.readyState===Dg.Closed){this.close();return}try{this.webSocket.send(e)}catch{this.close()}}sendStateless(e){let t=new U_(this.messageAddress).writeStateless(e);this.send(t.toUint8Array())}requestToken(){let e=new U_(this.messageAddress).writeTokenSyncRequest();this.send(e.toUint8Array())}close(e){if(this.document.hasConnection(this)){this.document.removeConnection(this),this.callbacks.onClose.forEach(t=>t(this.document,e));let t=new U_(this.messageAddress);t.writeCloseMessage(e?.reason??`Server closed the connection`),this.send(t.toUint8Array())}}sendCurrentAwareness(){if(!this.document.hasAwarenessStates())return;let e=new U_(this.messageAddress).createAwarenessUpdateMessage(this.document.awareness);this.send(e.toUint8Array())}handleMessage(e){this.messageQueue.push(e),this.messageQueue.length===1&&(this.processingPromise=this.processMessages())}async processMessages(){for(;this.messageQueue.length>0;){let e=this.messageQueue.at(0),t=new b_(e),n=t.readVarString(),r=n.indexOf(`\0`),i=r===-1?n:n.substring(0,r);if(i!==this.document.name){this.messageQueue.shift();continue}t.writeVarString(this.messageAddress);try{await this.callbacks.beforeHandleMessage(this,e),await new W_(t).apply(this.document,this)}catch(e){console.error(`closing connection ${this.socketId} (while handling ${i}) because of exception`,e),this.close({code:`code`in e&&typeof e.code==`number`?e.code:xg.code,reason:`reason`in e?e.reason:xg.reason})}this.messageQueue.shift()}}},K_=class extends Sr{constructor(e,t){super(t),this.callbacks={onUpdate:(e,t,n)=>{},beforeBroadcastStateless:(e,t)=>{}},this.connections=new Map,this.directConnectionsCount=0,this.isDestroyed=!1,this.saveMutex=new Pg,this.lastChangeTime=0,this.name=e,this.awareness=new j_(this),this.awareness.setLocalState(null),this.awareness.on(`update`,this.handleAwarenessUpdate.bind(this)),this.on(`update`,this.handleUpdate.bind(this)),this.isLoading=!0}isEmpty(e){return!this.get(e)._start&&!this.get(e)._map.size}merge(e){return(Array.isArray(e)?e:[e]).forEach(e=>{Rr(this,Vr(e))}),this}onUpdate(e){return this.callbacks.onUpdate=e,this}beforeBroadcastStateless(e){return this.callbacks.beforeBroadcastStateless=e,this}addConnection(e){return this.connections.set(e,{clients:new Set}),this}hasConnection(e){return this.connections.has(e)}removeConnection(e){let t=this.connections.get(e);return t&&M_(this.awareness,Array.from(t.clients),null),this.connections.delete(e),this}addDirectConnection(){return this.directConnectionsCount+=1,this}removeDirectConnection(){return this.directConnectionsCount>0&&--this.directConnectionsCount,this}getConnectionsCount(){return this.connections.size+this.directConnectionsCount}getConnections(){return Array.from(this.connections.keys())}getClients(e){let t=this.connections.get(e);return t?.clients===void 0?new Set:t.clients}hasAwarenessStates(){return this.awareness.getStates().size>0}applyAwarenessUpdate(e,t){return P_(this.awareness,t,e),this}handleAwarenessUpdate({added:e,updated:t,removed:n},r){let i=e.concat(t,n);if(r!==null){let t=this.connections.get(r);t&&(e.forEach(e=>t.clients.add(e)),n.forEach(e=>t.clients.delete(e)))}for(let e of this.getConnections()){let t=new U_(e.messageAddress).createAwarenessUpdateMessage(this.awareness,i);e.send(t.toUint8Array())}return this}handleUpdate(e,t){this.callbacks.onUpdate(this,t,e);for(let t of this.getConnections()){let n=new U_(t.messageAddress).createSyncMessage().writeUpdate(e);t.send(n.toUint8Array())}return this}broadcastStateless(e,t){this.callbacks.beforeBroadcastStateless(this,e),(t?this.getConnections().filter(t):this.getConnections()).forEach(t=>{t.sendStateless(e)})}destroy(){super.destroy(),this.isDestroyed=!0}},q_=`4.0.0-rc.1`;function J_(e){let t=e?.url;return t?t.includes(`://`)?new URL(t).searchParams:new URLSearchParams(t.split(`?`)[1]||``):new URLSearchParams}var Y_=class{constructor(e,t,n,r,i,a={}){this.websocket=e,this.request=t,this.documentProvider=n,this.hooks=r,this.opts=i,this.defaultContext=a,this.documentConnections={},this.incomingMessageQueue={},this.documentConnectionsEstablished=new Set,this.hookPayloads={},this.callbacks={onClose:[(e,t)=>{}]},this.socketId=De.randomUUID(),this.lastMessageReceivedAt=Date.now(),this.check=()=>{Date.now()-this.lastMessageReceivedAt>this.timeout&&this.close(wg)},this.setUpNewConnection=async(e,t,n)=>{let r=this.hookPayloads[e],i=await this.documentProvider.createDocument(t,r.request,r.socketId,r.connectionConfig,r.context),a=this.createConnection(this.websocket,i,r,n,r.providerVersion);if(a.onClose((t,n)=>{delete this.hookPayloads[e],delete this.documentConnections[e],delete this.incomingMessageQueue[e],this.documentConnectionsEstablished.delete(e)}),a.onTokenSyncCallback(async e=>{try{return await this.hooks(`onTokenSync`,{...r,...e,document:i,connection:a,documentName:t},e=>{r.context={...r.context,...e}})}catch(e){console.error(e);let t={...Sg,...e};a.close({code:t.code,reason:t.reason})}}),this.documentConnections[e]=a,this.websocket.readyState===Dg.Closing||this.websocket.readyState===Dg.Closed){this.close();return}this.incomingMessageQueue[e]?.forEach(e=>{a.handleMessage(e)}),await this.hooks(`connected`,{...r,documentName:t,context:r.context,connection:a})},this.handleQueueingMessage=async(e,t,n)=>{try{let r=new b_(e);if(y_(r.decoder),!(v_(r.decoder)===Q.Auth&&!this.documentConnectionsEstablished.has(t))){this.incomingMessageQueue[t].push(e);return}this.documentConnectionsEstablished.add(t),v_(r.decoder);let i=y_(r.decoder),a=null;m_(r.decoder)&&(a=y_(r.decoder));let o=t.indexOf(`\0`),s=o===-1?null:t.substring(o+1),c=t;try{let e=this.hookPayloads[t];e.providerVersion=a,await this.hooks(`onConnect`,{...e,documentName:n},t=>{e.context={...e.context,...t}}),await this.hooks(`onAuthenticate`,{token:i,...e,documentName:n},t=>{e.context={...e.context,...t}}),e.connectionConfig.isAuthenticated=!0;let r=new U_(c).writeAuthenticated(e.connectionConfig.readOnly);this.websocket.send(r.toUint8Array()),await this.setUpNewConnection(t,n,s)}catch(e){let n=e||Cg,r=new U_(c).writePermissionDenied(n.reason??`permission-denied`);this.websocket.send(r.toUint8Array()),this.documentConnectionsEstablished.delete(t),delete this.hookPayloads[t],delete this.incomingMessageQueue[t]}}catch(e){console.error(e),this.websocket.close(xg.code,xg.reason)}},this.handleMessage=e=>{this.lastMessageReceivedAt=Date.now();try{let t=y_(new b_(e).decoder),n=t.indexOf(`\0`),r=n===-1?t:t.substring(0,n),i=this.documentConnections[t]??this.documentConnections[r];if(i){i.handleMessage(e);return}if(this.incomingMessageQueue[t]===void 0){if(this.incomingMessageQueue[t]=[],this.hookPayloads[t])throw Error(`first message, but hookPayloads exists`);this.hookPayloads[t]={instance:this.documentProvider,request:this.request,connectionConfig:{readOnly:!1,isAuthenticated:!1},requestHeaders:this.request.headers,requestParameters:J_(this.request),socketId:this.socketId,context:{...this.defaultContext},providerVersion:null}}this.handleQueueingMessage(e,t,r)}catch(e){console.error(e),this.websocket.close(Sg.code,Sg.reason)}},this.timeout=i.timeout,this.pingInterval=setInterval(this.check,this.timeout)}handleClose(e){this.close(e),clearInterval(this.pingInterval)}close(e){Object.values(this.documentConnections).forEach(t=>t.close(e))}onClose(e){return this.callbacks.onClose.push(e),this}createConnection(e,t,n,r,i){let a=new G_(e,n.request,t,n.socketId,n.context,n.connectionConfig.readOnly,r,i);return a.onClose(async(e,t)=>{await a.waitForPendingMessages();let r={instance:this.documentProvider,clientsCount:e.getConnectionsCount(),context:n.context,document:e,socketId:n.socketId,documentName:e.name,requestHeaders:n.request.headers,requestParameters:J_(n.request)};await this.hooks(`onDisconnect`,r),this.callbacks.onClose.forEach(t=>t(e,r))}),a.onStatelessCallback(async e=>{try{return await this.hooks(`onStateless`,e)}catch(e){if(e?.message)throw e}}),a.beforeHandleMessage((e,r)=>{let i={instance:this.documentProvider,clientsCount:t.getConnectionsCount(),context:n.context,document:t,socketId:n.socketId,connection:e,documentName:t.name,requestHeaders:n.request.headers,requestParameters:J_(n.request),update:r};return this.hooks(`beforeHandleMessage`,i)}),a.beforeSync((e,r)=>{let i={clientsCount:t.getConnectionsCount(),context:n.context,document:t,documentName:t.name,connection:e,type:r.type,payload:r.payload};return this.hooks(`beforeSync`,i)}),a}},X_=class{constructor(e,t,n){this.document=null,this.document=e,this.instance=t,this.context=n??{},this.document.addDirectConnection()}async transact(e){if(!this.document)throw Error(`direct connection closed`);this.document.transact(t=>{e(this.document)},{source:`local`,context:this.context})}async disconnect(){this.document&&=(this.document?.removeDirectConnection(),await this.instance.storeDocumentHooks(this.document,{clientsCount:this.document.getConnectionsCount(),lastContext:this.context,lastTransactionOrigin:{source:`local`,context:this.context},document:this.document,documentName:this.document.name,instance:this.instance},!0),this.document.getConnectionsCount()===0&&!this.document.saveMutex.isLocked()&&(await this.instance.hooks(`onDisconnect`,{instance:this.instance,clientsCount:this.document.getConnectionsCount(),context:this.context,document:this.document,socketId:`server`,documentName:this.document.name,requestHeaders:new Headers,requestParameters:new Ee}),await this.instance.unloadDocument(this.document)),null)}};const Z_=()=>{let e=new Map,t=new Map;return{debounce:async(n,r,i,a)=>{let o=e.get(n),s=o?.start||Date.now(),c=async()=>{t.has(n)&&await t.get(n),e.delete(n);let i=r();t.set(n,i);let a=await i;return t.delete(n),a};if(o?.timeout&&clearTimeout(o.timeout),i===0||Date.now()-s>=a)return c();e.set(n,{start:s,timeout:setTimeout(c,i),func:c})},isDebounced:t=>e.has(t),isCurrentlyExecuting:e=>t.has(e),executeNow:t=>{let n=e.get(t);if(n)return clearTimeout(n.timeout),n.func()}}},Q_={name:null,timeout:6e4,debounce:2e3,maxDebounce:1e4,quiet:!1,yDocOptions:{gc:!0,gcFilter:()=>!0},unloadImmediately:!0};var $_=class{constructor(e){this.configuration={...Q_,extensions:[],onConfigure:()=>new Promise(e=>e(null)),onListen:()=>new Promise(e=>e(null)),onUpgrade:()=>new Promise(e=>e(null)),onConnect:()=>new Promise(e=>e(null)),connected:()=>new Promise(e=>e(null)),beforeHandleMessage:()=>new Promise(e=>e(null)),beforeSync:()=>new Promise(e=>e(null)),beforeBroadcastStateless:()=>new Promise(e=>e(null)),onStateless:()=>new Promise(e=>e(null)),onChange:()=>new Promise(e=>e(null)),onCreateDocument:()=>new Promise(e=>e(null)),onLoadDocument:()=>new Promise(e=>e(null)),onStoreDocument:()=>new Promise(e=>e(null)),afterStoreDocument:()=>new Promise(e=>e(null)),onAwarenessUpdate:()=>new Promise(e=>e(null)),onRequest:()=>new Promise(e=>e(null)),onDisconnect:()=>new Promise(e=>e(null)),onDestroy:()=>new Promise(e=>e(null))},this.loadingDocuments=new Map,this.unloadingDocuments=new Map,this.documents=new Map,this.debouncer=Z_(),e&&this.configure(e)}configure(e){return this.configuration={...this.configuration,...e},this.configuration.extensions.sort((e,t)=>{let n=e.priority===void 0?100:e.priority,r=t.priority===void 0?100:t.priority;return n>r?-1:n<r?1:0}),this.configuration.extensions.push({onConfigure:this.configuration.onConfigure,onListen:this.configuration.onListen,onUpgrade:this.configuration.onUpgrade,onConnect:this.configuration.onConnect,connected:this.configuration.connected,onAuthenticate:this.configuration.onAuthenticate,onTokenSync:this.configuration.onTokenSync,onLoadDocument:this.configuration.onLoadDocument,afterLoadDocument:this.configuration.afterLoadDocument,beforeHandleMessage:this.configuration.beforeHandleMessage,beforeBroadcastStateless:this.configuration.beforeBroadcastStateless,beforeSync:this.configuration.beforeSync,onStateless:this.configuration.onStateless,onChange:this.configuration.onChange,onStoreDocument:this.configuration.onStoreDocument,afterStoreDocument:this.configuration.afterStoreDocument,onAwarenessUpdate:this.configuration.onAwarenessUpdate,onRequest:this.configuration.onRequest,beforeUnloadDocument:this.configuration.beforeUnloadDocument,afterUnloadDocument:this.configuration.afterUnloadDocument,onDisconnect:this.configuration.onDisconnect,onDestroy:this.configuration.onDestroy}),this.hooks(`onConfigure`,{configuration:this.configuration,version:q_,instance:this}),this}getDocumentsCount(){return this.documents.size}getConnectionsCount(){let e=new Set,t=Array.from(this.documents.values()).reduce((t,n)=>(n.getConnections().forEach(({socketId:t})=>{e.add(t)}),t+n.directConnectionsCount),0);return e.size+t}flushPendingStores(){this.documents.forEach(e=>{let t=`onStoreDocument-${e.name}`;!e.isLoading&&this.debouncer.isDebounced(t)&&this.debouncer.executeNow(t)})}closeConnections(e){this.documents.forEach(t=>{e&&t.name!==e||t.connections.forEach((e,t)=>{t.close(xg)})})}handleConnection(e,t,n={}){let r=new Y_(e,t,this,this.hooks.bind(this),{timeout:this.configuration.timeout},n);return r.onClose((e,t)=>{e.getConnectionsCount()>0||(!e.isLoading&&this.debouncer.isDebounced(`onStoreDocument-${e.name}`)?this.configuration.unloadImmediately&&this.debouncer.executeNow(`onStoreDocument-${e.name}`):this.unloadDocument(e))}),r}handleDocumentUpdate(e,t,n){let r=V_(t)&&t.source===`connection`?t.connection:void 0,i=r?.request,a=V_(t)?t.source===`connection`?t.connection.context:t.source===`local`?t.context??{}:{}:{},o={instance:this,clientsCount:e.getConnectionsCount(),document:e,documentName:e.name,requestHeaders:i?.headers??new Headers,requestParameters:J_(i),socketId:r?.socketId??``,update:n,transactionOrigin:t,connection:r,context:a};if(this.hooks(`onChange`,o),H_(t))return;let s={instance:this,clientsCount:e.getConnectionsCount(),document:e,lastContext:a,lastTransactionOrigin:t,documentName:e.name};this.storeDocumentHooks(e,s)}async createDocument(e,t,n,r,i){if(!e.trim())throw Error(`Document name must not be empty`);let a=this.loadingDocuments.get(e);if(a)return a;let o=this.documents.get(e);if(o)return Promise.resolve(o);let s=this.loadDocument(e,t,n,r,i);this.loadingDocuments.set(e,s);try{let t=await s;return this.documents.set(e,t),this.loadingDocuments.delete(e),t}catch(t){throw this.loadingDocuments.delete(e),t}}async loadDocument(e,t,n,r,i){let a=t.headers,o=J_(t),s=i??{},c=await this.hooks(`onCreateDocument`,{documentName:e,requestHeaders:a,requestParameters:o,connectionConfig:r,context:s,socketId:n,instance:this}),l=new K_(e,{...this.configuration.yDocOptions,...c}),u={instance:this,context:s,connectionConfig:r,document:l,documentName:e,socketId:n,requestHeaders:a,requestParameters:o};try{await this.hooks(`onLoadDocument`,u,e=>{e instanceof Sr?Rr(l,Vr(e)):e instanceof Uint8Array&&Rr(l,e)})}catch(t){throw this.closeConnections(e),this.unloadDocument(l),t}return l.isLoading=!1,l.onUpdate((e,t,n)=>{e.lastChangeTime=Date.now(),this.handleDocumentUpdate(e,t,n)}),await this.hooks(`afterLoadDocument`,u),l.beforeBroadcastStateless((e,t)=>{let n={document:e,documentName:e.name,payload:t};this.hooks(`beforeBroadcastStateless`,n)}),l.awareness.on(`update`,(t,n)=>{this.hooks(`onAwarenessUpdate`,{document:l,documentName:e,instance:this,...t,transactionOrigin:n,connection:V_(n)&&n.source===`connection`?n.connection:void 0,awareness:l.awareness,states:Tg(l.awareness.getStates())})}),l}storeDocumentHooks(e,t,n){let r=`onStoreDocument-${e.name}`;return this.debouncer.debounce(r,async()=>{try{await e.saveMutex.runExclusive(async()=>{await this.hooks(`onStoreDocument`,t),await this.hooks(`afterStoreDocument`,t)})}catch(t){if(t instanceof Eg){setTimeout(()=>{this.shouldUnloadDocument(e)&&this.unloadDocument(e)},0);return}console.error(`Caught error during storeDocumentHooks. Document stays in memory to avoid data loss`,t);return}setTimeout(()=>{this.shouldUnloadDocument(e)&&this.unloadDocument(e)},0)},n?0:this.configuration.debounce,this.configuration.maxDebounce)}hooks(e,t,n=null){let{extensions:r}=this.configuration,i=Promise.resolve();return r.filter(t=>typeof t[e]==`function`).forEach(r=>{i=i.then(()=>r[e]?.(t)).catch(t=>{throw t?.message&&console.error(`[${e}]`,t.message),t}),n&&(i=i.then((...e)=>n(...e)))}),i}shouldUnloadDocument(e){return(this.debouncer.isDebounced(`onStoreDocument-${e.name}`)||this.debouncer.isCurrentlyExecuting(`onStoreDocument-${e.name}`)||e.saveMutex.isLocked())===!1&&e.getConnectionsCount()===0}async unloadDocument(e){let t=e.name;if(!this.shouldUnloadDocument(e)||!this.documents.has(t))return;if(this.unloadingDocuments.has(t))return this.unloadingDocuments.get(t);let n=(async()=>{try{await this.hooks(`beforeUnloadDocument`,{instance:this,documentName:t,document:e})}catch{return}this.shouldUnloadDocument(e)&&(this.documents.delete(t),e.destroy(),await this.hooks(`afterUnloadDocument`,{instance:this,documentName:t}))})();this.unloadingDocuments.set(t,Promise.resolve(n)),await n,this.unloadingDocuments.delete(t)}async openDirectConnection(e,t){return new X_(await this.createDocument(e,new Request(`http://localhost`),De.randomUUID(),{isAuthenticated:!0,readOnly:!1},t),this,t)}},ev=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),tv=oe(import.meta.url),nv=ev(((e,t)=>{let n=[`nodebuffer`,`arraybuffer`,`fragments`],r=typeof Blob<`u`;r&&n.push(`blob`),t.exports={BINARY_TYPES:n,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:`258EAFA5-E914-47DA-95CA-C5AB0DC85B11`,hasBlob:r,kForOnEventAttribute:Symbol(`kIsForOnEventAttribute`),kListener:Symbol(`kListener`),kStatusCode:Symbol(`status-code`),kWebSocket:Symbol(`websocket`),NOOP:()=>{}}})),rv=ev(((e,t)=>{let{EMPTY_BUFFER:n}=nv(),r=Buffer[Symbol.species];function i(e,t){if(e.length===0)return n;if(e.length===1)return e[0];let i=Buffer.allocUnsafe(t),a=0;for(let t=0;t<e.length;t++){let n=e[t];i.set(n,a),a+=n.length}return a<t?new r(i.buffer,i.byteOffset,a):i}function a(e,t,n,r,i){for(let a=0;a<i;a++)n[r+a]=e[a]^t[a&3]}function o(e,t){for(let n=0;n<e.length;n++)e[n]^=t[n&3]}function s(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)}function c(e){if(c.readOnly=!0,Buffer.isBuffer(e))return e;let t;return e instanceof ArrayBuffer?t=new r(e):ArrayBuffer.isView(e)?t=new r(e.buffer,e.byteOffset,e.byteLength):(t=Buffer.from(e),c.readOnly=!1),t}if(t.exports={concat:i,mask:a,toArrayBuffer:s,toBuffer:c,unmask:o},!process.env.WS_NO_BUFFER_UTIL)try{let e=tv(`bufferutil`);t.exports.mask=function(t,n,r,i,o){o<48?a(t,n,r,i,o):e.mask(t,n,r,i,o)},t.exports.unmask=function(t,n){t.length<32?o(t,n):e.unmask(t,n)}}catch{}})),iv=ev(((e,t)=>{let n=Symbol(`kDone`),r=Symbol(`kRun`);t.exports=class{constructor(e){this[n]=()=>{this.pending--,this[r]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[r]()}[r](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[n])}}}})),av=ev(((e,t)=>{let n=tv(`zlib`),r=rv(),i=iv(),{kStatusCode:a}=nv(),o=Buffer[Symbol.species],s=Buffer.from([0,0,255,255]),c=Symbol(`permessage-deflate`),l=Symbol(`total-length`),u=Symbol(`callback`),d=Symbol(`buffers`),f=Symbol(`error`),p;t.exports=class{constructor(e,t,n){this._maxPayload=n|0,this._options=e||{},this._threshold=this._options.threshold===void 0?1024:this._options.threshold,this._isServer=!!t,this._deflate=null,this._inflate=null,this.params=null,p||=new i(this._options.concurrencyLimit===void 0?10:this._options.concurrencyLimit)}static get extensionName(){return`permessage-deflate`}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits??(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&=(this._inflate.close(),null),this._deflate){let e=this._deflate[u];this._deflate.close(),this._deflate=null,e&&e(Error(`The deflate stream was closed while data was being processed`))}}acceptAsServer(e){let t=this._options,n=e.find(e=>!(t.serverNoContextTakeover===!1&&e.server_no_context_takeover||e.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits==`number`&&t.serverMaxWindowBits>e.server_max_window_bits)||typeof t.clientMaxWindowBits==`number`&&!e.client_max_window_bits));if(!n)throw Error(`None of the extension offers can be accepted`);return t.serverNoContextTakeover&&(n.server_no_context_takeover=!0),t.clientNoContextTakeover&&(n.client_no_context_takeover=!0),typeof t.serverMaxWindowBits==`number`&&(n.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits==`number`?n.client_max_window_bits=t.clientMaxWindowBits:(n.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete n.client_max_window_bits,n}acceptAsClient(e){let t=e[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw Error(`Unexpected parameter "client_no_context_takeover"`);if(!t.client_max_window_bits)typeof this._options.clientMaxWindowBits==`number`&&(t.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits==`number`&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw Error(`Unexpected or invalid parameter "client_max_window_bits"`);return t}normalizeParams(e){return e.forEach(e=>{Object.keys(e).forEach(t=>{let n=e[t];if(n.length>1)throw Error(`Parameter "${t}" must have only a single value`);if(n=n[0],t===`client_max_window_bits`){if(n!==!0){let e=+n;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else if(!this._isServer)throw TypeError(`Invalid value for parameter "${t}": ${n}`)}else if(t===`server_max_window_bits`){let e=+n;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else if(t===`client_no_context_takeover`||t===`server_no_context_takeover`){if(n!==!0)throw TypeError(`Invalid value for parameter "${t}": ${n}`)}else throw Error(`Unknown parameter "${t}"`);e[t]=n})}),e}decompress(e,t,n){p.add(r=>{this._decompress(e,t,(e,t)=>{r(),n(e,t)})})}compress(e,t,n){p.add(r=>{this._compress(e,t,(e,t)=>{r(),n(e,t)})})}_decompress(e,t,i){let a=this._isServer?`client`:`server`;if(!this._inflate){let e=`${a}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:n.Z_DEFAULT_WINDOWBITS;this._inflate=n.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[c]=this,this._inflate[l]=0,this._inflate[d]=[],this._inflate.on(`error`,g),this._inflate.on(`data`,h)}this._inflate[u]=i,this._inflate.write(e),t&&this._inflate.write(s),this._inflate.flush(()=>{let e=this._inflate[f];if(e){this._inflate.close(),this._inflate=null,i(e);return}let n=r.concat(this._inflate[d],this._inflate[l]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[l]=0,this._inflate[d]=[],t&&this.params[`${a}_no_context_takeover`]&&this._inflate.reset()),i(null,n)})}_compress(e,t,i){let a=this._isServer?`server`:`client`;if(!this._deflate){let e=`${a}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:n.Z_DEFAULT_WINDOWBITS;this._deflate=n.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[l]=0,this._deflate[d]=[],this._deflate.on(`data`,m)}this._deflate[u]=i,this._deflate.write(e),this._deflate.flush(n.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let e=r.concat(this._deflate[d],this._deflate[l]);t&&(e=new o(e.buffer,e.byteOffset,e.length-4)),this._deflate[u]=null,this._deflate[l]=0,this._deflate[d]=[],t&&this.params[`${a}_no_context_takeover`]&&this._deflate.reset(),i(null,e)})}};function m(e){this[d].push(e),this[l]+=e.length}function h(e){if(this[l]+=e.length,this[c]._maxPayload<1||this[l]<=this[c]._maxPayload){this[d].push(e);return}this[f]=RangeError(`Max payload size exceeded`),this[f].code=`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`,this[f][a]=1009,this.removeListener(`data`,h),this.reset()}function g(e){if(this[c]._inflate=null,this[f]){this[u](this[f]);return}e[a]=1007,this[u](e)}})),ov=ev(((e,t)=>{let{isUtf8:n}=tv(`buffer`),{hasBlob:r}=nv(),i=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function a(e){return e>=1e3&&e<=1014&&e!==1004&&e!==1005&&e!==1006||e>=3e3&&e<=4999}function o(e){let t=e.length,n=0;for(;n<t;)if(!(e[n]&128))n++;else if((e[n]&224)==192){if(n+1===t||(e[n+1]&192)!=128||(e[n]&254)==192)return!1;n+=2}else if((e[n]&240)==224){if(n+2>=t||(e[n+1]&192)!=128||(e[n+2]&192)!=128||e[n]===224&&(e[n+1]&224)==128||e[n]===237&&(e[n+1]&224)==160)return!1;n+=3}else if((e[n]&248)==240){if(n+3>=t||(e[n+1]&192)!=128||(e[n+2]&192)!=128||(e[n+3]&192)!=128||e[n]===240&&(e[n+1]&240)==128||e[n]===244&&e[n+1]>143||e[n]>244)return!1;n+=4}else return!1;return!0}function s(e){return r&&typeof e==`object`&&typeof e.arrayBuffer==`function`&&typeof e.type==`string`&&typeof e.stream==`function`&&(e[Symbol.toStringTag]===`Blob`||e[Symbol.toStringTag]===`File`)}if(t.exports={isBlob:s,isValidStatusCode:a,isValidUTF8:o,tokenChars:i},n)t.exports.isValidUTF8=function(e){return e.length<24?o(e):n(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let e=tv(`utf-8-validate`);t.exports.isValidUTF8=function(t){return t.length<32?o(t):e(t)}}catch{}})),sv=ev(((e,t)=>{let{Writable:n}=tv(`stream`),r=av(),{BINARY_TYPES:i,EMPTY_BUFFER:a,kStatusCode:o,kWebSocket:s}=nv(),{concat:c,toArrayBuffer:l,unmask:u}=rv(),{isValidStatusCode:d,isValidUTF8:f}=ov(),p=Buffer[Symbol.species];t.exports=class extends n{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents===void 0?!0:e.allowSynchronousEvents,this._binaryType=e.binaryType||i[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[s]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=0}_write(e,t,n){if(this._opcode===8&&this._state==0)return n();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(n)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let t=this._buffers[0];return this._buffers[0]=new p(t.buffer,t.byteOffset+e,t.length-e),new p(t.buffer,t.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let n=this._buffers[0],r=t.length-e;e>=n.length?t.set(this._buffers.shift(),r):(t.set(new Uint8Array(n.buffer,n.byteOffset,e),r),this._buffers[0]=new p(n.buffer,n.byteOffset+e,n.length-e)),e-=n.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case 0:this.getInfo(e);break;case 1:this.getPayloadLength16(e);break;case 2:this.getPayloadLength64(e);break;case 3:this.getMask();break;case 4:this.getData(e);break;case 5:case 6:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if(t[0]&48){e(this.createError(RangeError,`RSV2 and RSV3 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_2_3`));return}let n=(t[0]&64)==64;if(n&&!this._extensions[r.extensionName]){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(this._fin=(t[0]&128)==128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(n){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(!this._fragmented){e(this.createError(RangeError,`invalid opcode 0`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}this._compressed=n}else if(this._opcode>7&&this._opcode<11){if(!this._fin){e(this.createError(RangeError,`FIN must be set`,!0,1002,`WS_ERR_EXPECTED_FIN`));return}if(n){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){e(this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,`WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH`));return}}else{e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)==128,this._isServer){if(!this._masked){e(this.createError(RangeError,`MASK must be set`,!0,1002,`WS_ERR_EXPECTED_MASK`));return}}else if(this._masked){e(this.createError(RangeError,`MASK must be clear`,!0,1002,`WS_ERR_UNEXPECTED_MASK`));return}this._payloadLength===126?this._state=1:this._payloadLength===127?this._state=2:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let t=this.consume(8),n=t.readUInt32BE(0);if(n>2**21-1){e(this.createError(RangeError,`Unsupported WebSocket frame: payload length > 2^53 - 1`,!1,1009,`WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH`));return}this._payloadLength=n*2**32+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){e(this.createError(RangeError,`Max payload size exceeded`,!1,1009,`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`));return}this._masked?this._state=3:this._state=4}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=4}getData(e){let t=a;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&u(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=5,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[r.extensionName].decompress(e,this._fin,(e,n)=>{if(e)return t(e);if(n.length){if(this._messageLength+=n.length,this._messageLength>this._maxPayload&&this._maxPayload>0){t(this.createError(RangeError,`Max payload size exceeded`,!1,1009,`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`));return}this._fragments.push(n)}this.dataMessage(t),this._state===0&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=0;return}let t=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let r;r=this._binaryType===`nodebuffer`?c(n,t):this._binaryType===`arraybuffer`?l(c(n,t)):this._binaryType===`blob`?new Blob(n):n,this._allowSynchronousEvents?(this.emit(`message`,r,!0),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,r,!0),this._state=0,this.startLoop(e)}))}else{let r=c(n,t);if(!this._skipUTF8Validation&&!f(r)){e(this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`));return}this._state===5||this._allowSynchronousEvents?(this.emit(`message`,r,!1),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,r,!1),this._state=0,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit(`conclude`,1005,a),this.end();else{let n=e.readUInt16BE(0);if(!d(n)){t(this.createError(RangeError,`invalid status code ${n}`,!0,1002,`WS_ERR_INVALID_CLOSE_CODE`));return}let r=new p(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!f(r)){t(this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`));return}this._loop=!1,this.emit(`conclude`,n,r),this.end()}this._state=0;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0):(this._state=6,setImmediate(()=>{this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0,this.startLoop(t)}))}createError(e,t,n,r,i){this._loop=!1,this._errored=!0;let a=new e(n?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(a,this.createError),a.code=i,a[o]=r,a}}})),cv=ev(((e,t)=>{let{Duplex:n}=tv(`stream`),{randomFillSync:r}=tv(`crypto`),i=av(),{EMPTY_BUFFER:a,kWebSocket:o,NOOP:s}=nv(),{isBlob:c,isValidStatusCode:l}=ov(),{mask:u,toBuffer:d}=rv(),f=Symbol(`kByteLength`),p=Buffer.alloc(4),m=8*1024,h,g=m;t.exports=class e{constructor(e,t,n){this._extensions=t||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=0,this.onerror=s,this[o]=void 0}static frame(e,t){let n,i=!1,a=2,o=!1;t.mask&&(n=t.maskBuffer||p,t.generateMask?t.generateMask(n):(g===m&&(h===void 0&&(h=Buffer.alloc(m)),r(h,0,m),g=0),n[0]=h[g++],n[1]=h[g++],n[2]=h[g++],n[3]=h[g++]),o=(n[0]|n[1]|n[2]|n[3])===0,a=6);let s;typeof e==`string`?(!t.mask||o)&&t[f]!==void 0?s=t[f]:(e=Buffer.from(e),s=e.length):(s=e.length,i=t.mask&&t.readOnly&&!o);let c=s;s>=65536?(a+=8,c=127):s>125&&(a+=2,c=126);let l=Buffer.allocUnsafe(i?s+a:a);return l[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(l[0]|=64),l[1]=c,c===126?l.writeUInt16BE(s,2):c===127&&(l[2]=l[3]=0,l.writeUIntBE(s,4,6)),!t.mask||(l[1]|=128,l[a-4]=n[0],l[a-3]=n[1],l[a-2]=n[2],l[a-1]=n[3],o)?[l,e]:i?(u(e,n,l,a,s),[l]):(u(e,n,e,0,s),[l,e])}close(t,n,r,i){let o;if(t===void 0)o=a;else if(typeof t!=`number`||!l(t))throw TypeError(`First argument must be a valid error code number`);else if(n===void 0||!n.length)o=Buffer.allocUnsafe(2),o.writeUInt16BE(t,0);else{let e=Buffer.byteLength(n);if(e>123)throw RangeError(`The message must not be greater than 123 bytes`);o=Buffer.allocUnsafe(2+e),o.writeUInt16BE(t,0),typeof n==`string`?o.write(n,2):o.set(n,2)}let s={[f]:o.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state===0?this.sendFrame(e.frame(o,s),i):this.enqueue([this.dispatch,o,!1,s,i])}ping(t,n,r){let i,a;if(typeof t==`string`?(i=Buffer.byteLength(t),a=!1):c(t)?(i=t.size,a=!1):(t=d(t),i=t.length,a=d.readOnly),i>125)throw RangeError(`The data size must not be greater than 125 bytes`);let o={[f]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:a,rsv1:!1};c(t)?this._state===0?this.getBlobData(t,!1,o,r):this.enqueue([this.getBlobData,t,!1,o,r]):this._state===0?this.sendFrame(e.frame(t,o),r):this.enqueue([this.dispatch,t,!1,o,r])}pong(t,n,r){let i,a;if(typeof t==`string`?(i=Buffer.byteLength(t),a=!1):c(t)?(i=t.size,a=!1):(t=d(t),i=t.length,a=d.readOnly),i>125)throw RangeError(`The data size must not be greater than 125 bytes`);let o={[f]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:a,rsv1:!1};c(t)?this._state===0?this.getBlobData(t,!1,o,r):this.enqueue([this.getBlobData,t,!1,o,r]):this._state===0?this.sendFrame(e.frame(t,o),r):this.enqueue([this.dispatch,t,!1,o,r])}send(e,t,n){let r=this._extensions[i.extensionName],a=t.binary?2:1,o=t.compress,s,l;typeof e==`string`?(s=Buffer.byteLength(e),l=!1):c(e)?(s=e.size,l=!1):(e=d(e),s=e.length,l=d.readOnly),this._firstFragment?(this._firstFragment=!1,o&&r&&r.params[r._isServer?`server_no_context_takeover`:`client_no_context_takeover`]&&(o=s>=r._threshold),this._compress=o):(o=!1,a=0),t.fin&&(this._firstFragment=!0);let u={[f]:s,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:a,readOnly:l,rsv1:o};c(e)?this._state===0?this.getBlobData(e,this._compress,u,n):this.enqueue([this.getBlobData,e,this._compress,u,n]):this._state===0?this.dispatch(e,this._compress,u,n):this.enqueue([this.dispatch,e,this._compress,u,n])}getBlobData(t,n,r,i){this._bufferedBytes+=r[f],this._state=2,t.arrayBuffer().then(t=>{if(this._socket.destroyed){let e=Error(`The socket was closed while the blob was being read`);process.nextTick(_,this,e,i);return}this._bufferedBytes-=r[f];let a=d(t);n?this.dispatch(a,n,r,i):(this._state=0,this.sendFrame(e.frame(a,r),i),this.dequeue())}).catch(e=>{process.nextTick(v,this,e,i)})}dispatch(t,n,r,a){if(!n){this.sendFrame(e.frame(t,r),a);return}let o=this._extensions[i.extensionName];this._bufferedBytes+=r[f],this._state=1,o.compress(t,r.fin,(t,n)=>{if(this._socket.destroyed){_(this,Error(`The socket was closed while data was being compressed`),a);return}this._bufferedBytes-=r[f],this._state=0,r.readOnly=!1,this.sendFrame(e.frame(n,r),a),this.dequeue()})}dequeue(){for(;this._state===0&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][f],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][f],this._queue.push(e)}sendFrame(e,t){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};function _(e,t,n){typeof n==`function`&&n(t);for(let n=0;n<e._queue.length;n++){let r=e._queue[n],i=r[r.length-1];typeof i==`function`&&i(t)}}function v(e,t,n){_(e,t,n),e.onerror(t)}})),lv=ev(((e,t)=>{let{kForOnEventAttribute:n,kListener:r}=nv(),i=Symbol(`kCode`),a=Symbol(`kData`),o=Symbol(`kError`),s=Symbol(`kMessage`),c=Symbol(`kReason`),l=Symbol(`kTarget`),u=Symbol(`kType`),d=Symbol(`kWasClean`);var f=class{constructor(e){this[l]=null,this[u]=e}get target(){return this[l]}get type(){return this[u]}};Object.defineProperty(f.prototype,`target`,{enumerable:!0}),Object.defineProperty(f.prototype,`type`,{enumerable:!0});var p=class extends f{constructor(e,t={}){super(e),this[i]=t.code===void 0?0:t.code,this[c]=t.reason===void 0?``:t.reason,this[d]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[i]}get reason(){return this[c]}get wasClean(){return this[d]}};Object.defineProperty(p.prototype,`code`,{enumerable:!0}),Object.defineProperty(p.prototype,`reason`,{enumerable:!0}),Object.defineProperty(p.prototype,`wasClean`,{enumerable:!0});var m=class extends f{constructor(e,t={}){super(e),this[o]=t.error===void 0?null:t.error,this[s]=t.message===void 0?``:t.message}get error(){return this[o]}get message(){return this[s]}};Object.defineProperty(m.prototype,`error`,{enumerable:!0}),Object.defineProperty(m.prototype,`message`,{enumerable:!0});var h=class extends f{constructor(e,t={}){super(e),this[a]=t.data===void 0?null:t.data}get data(){return this[a]}};Object.defineProperty(h.prototype,`data`,{enumerable:!0}),t.exports={CloseEvent:p,ErrorEvent:m,Event:f,EventTarget:{addEventListener(e,t,i={}){for(let a of this.listeners(e))if(!i[n]&&a[r]===t&&!a[n])return;let a;if(e===`message`)a=function(e,n){let r=new h(`message`,{data:n?e:e.toString()});r[l]=this,g(t,this,r)};else if(e===`close`)a=function(e,n){let r=new p(`close`,{code:e,reason:n.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});r[l]=this,g(t,this,r)};else if(e===`error`)a=function(e){let n=new m(`error`,{error:e,message:e.message});n[l]=this,g(t,this,n)};else if(e===`open`)a=function(){let e=new f(`open`);e[l]=this,g(t,this,e)};else return;a[n]=!!i[n],a[r]=t,i.once?this.once(e,a):this.on(e,a)},removeEventListener(e,t){for(let i of this.listeners(e))if(i[r]===t&&!i[n]){this.removeListener(e,i);break}}},MessageEvent:h};function g(e,t,n){typeof e==`object`&&e.handleEvent?e.handleEvent.call(e,n):e.call(t,n)}})),uv=ev(((e,t)=>{let{tokenChars:n}=ov();function r(e,t,n){e[t]===void 0?e[t]=[n]:e[t].push(n)}function i(e){let t=Object.create(null),i=Object.create(null),a=!1,o=!1,s=!1,c,l,u=-1,d=-1,f=-1,p=0;for(;p<e.length;p++)if(d=e.charCodeAt(p),c===void 0)if(f===-1&&n[d]===1)u===-1&&(u=p);else if(p!==0&&(d===32||d===9))f===-1&&u!==-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let n=e.slice(u,f);d===44?(r(t,n,i),i=Object.create(null)):c=n,u=f=-1}else throw SyntaxError(`Unexpected character at index ${p}`);else if(l===void 0)if(f===-1&&n[d]===1)u===-1&&(u=p);else if(d===32||d===9)f===-1&&u!==-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p),r(i,e.slice(u,f),!0),d===44&&(r(t,c,i),i=Object.create(null),c=void 0),u=f=-1}else if(d===61&&u!==-1&&f===-1)l=e.slice(u,p),u=f=-1;else throw SyntaxError(`Unexpected character at index ${p}`);else if(o){if(n[d]!==1)throw SyntaxError(`Unexpected character at index ${p}`);u===-1?u=p:a||=!0,o=!1}else if(s)if(n[d]===1)u===-1&&(u=p);else if(d===34&&u!==-1)s=!1,f=p;else if(d===92)o=!0;else throw SyntaxError(`Unexpected character at index ${p}`);else if(d===34&&e.charCodeAt(p-1)===61)s=!0;else if(f===-1&&n[d]===1)u===-1&&(u=p);else if(u!==-1&&(d===32||d===9))f===-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let n=e.slice(u,f);a&&=(n=n.replace(/\\/g,``),!1),r(i,l,n),d===44&&(r(t,c,i),i=Object.create(null),c=void 0),l=void 0,u=f=-1}else throw SyntaxError(`Unexpected character at index ${p}`);if(u===-1||s||d===32||d===9)throw SyntaxError(`Unexpected end of input`);f===-1&&(f=p);let m=e.slice(u,f);return c===void 0?r(t,m,i):(l===void 0?r(i,m,!0):a?r(i,l,m.replace(/\\/g,``)):r(i,l,m),r(t,c,i)),t}function a(e){return Object.keys(e).map(t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map(e=>[t].concat(Object.keys(e).map(t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map(e=>e===!0?t:`${t}=${e}`).join(`; `)})).join(`; `)).join(`, `)}).join(`, `)}t.exports={format:a,parse:i}})),dv=ev(((e,t)=>{let n=tv(`events`),r=tv(`https`),i=tv(`http`),a=tv(`net`),o=tv(`tls`),{randomBytes:s,createHash:c}=tv(`crypto`),{Duplex:l,Readable:u}=tv(`stream`),{URL:d}=tv(`url`),f=av(),p=sv(),m=cv(),{isBlob:h}=ov(),{BINARY_TYPES:g,CLOSE_TIMEOUT:_,EMPTY_BUFFER:v,GUID:y,kForOnEventAttribute:b,kListener:x,kStatusCode:S,kWebSocket:C,NOOP:w}=nv(),{EventTarget:{addEventListener:T,removeEventListener:E}}=lv(),{format:D,parse:O}=uv(),{toBuffer:k}=rv(),A=Symbol(`kAborted`),j=[8,13],M=[`CONNECTING`,`OPEN`,`CLOSING`,`CLOSED`],ee=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;var N=class e extends n{constructor(t,n,r){super(),this._binaryType=g[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=v,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol=``,this._readyState=e.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,t===null?(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0):(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?n=[]:Array.isArray(n)||(typeof n==`object`&&n?(r=n,n=[]):n=[n]),te(this,t,n,r))}get binaryType(){return this._binaryType}set binaryType(e){g.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(t,n,r){let i=new p({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),a=new m(t,this._extensions,r.generateMask);this._receiver=i,this._sender=a,this._socket=t,i[C]=this,a[C]=this,t[C]=this,i.on(`conclude`,ae),i.on(`drain`,I),i.on(`error`,oe),i.on(`message`,L),i.on(`ping`,ce),i.on(`pong`,le),a.onerror=R,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),n.length>0&&t.unshift(n),t.on(`close`,fe),t.on(`data`,pe),t.on(`end`,me),t.on(`error`,he),this._readyState=e.OPEN,this.emit(`open`)}emitClose(){if(!this._socket){this._readyState=e.CLOSED,this.emit(`close`,this._closeCode,this._closeMessage);return}this._extensions[f.extensionName]&&this._extensions[f.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=e.CLOSED,this.emit(`close`,this._closeCode,this._closeMessage)}close(t,n){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){F(this,this._req,`WebSocket was closed before the connection was established`);return}if(this.readyState===e.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=e.CLOSING,this._sender.close(t,n,!this._isServer,e=>{e||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),de(this)}}pause(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!0,this._socket.pause())}ping(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof t==`function`?(r=t,t=n=void 0):typeof n==`function`&&(r=n,n=void 0),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){ie(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(t||v,n,r)}pong(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof t==`function`?(r=t,t=n=void 0):typeof n==`function`&&(r=n,n=void 0),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){ie(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(t||v,n,r)}resume(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof n==`function`&&(r=n,n={}),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){ie(this,t,r);return}let i={binary:typeof t!=`string`,mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[f.extensionName]||(i.compress=!1),this._sender.send(t||v,i,r)}terminate(){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){F(this,this._req,`WebSocket was closed before the connection was established`);return}this._socket&&(this._readyState=e.CLOSING,this._socket.destroy())}}};Object.defineProperty(N,`CONNECTING`,{enumerable:!0,value:M.indexOf(`CONNECTING`)}),Object.defineProperty(N.prototype,`CONNECTING`,{enumerable:!0,value:M.indexOf(`CONNECTING`)}),Object.defineProperty(N,`OPEN`,{enumerable:!0,value:M.indexOf(`OPEN`)}),Object.defineProperty(N.prototype,`OPEN`,{enumerable:!0,value:M.indexOf(`OPEN`)}),Object.defineProperty(N,`CLOSING`,{enumerable:!0,value:M.indexOf(`CLOSING`)}),Object.defineProperty(N.prototype,`CLOSING`,{enumerable:!0,value:M.indexOf(`CLOSING`)}),Object.defineProperty(N,`CLOSED`,{enumerable:!0,value:M.indexOf(`CLOSED`)}),Object.defineProperty(N.prototype,`CLOSED`,{enumerable:!0,value:M.indexOf(`CLOSED`)}),[`binaryType`,`bufferedAmount`,`extensions`,`isPaused`,`protocol`,`readyState`,`url`].forEach(e=>{Object.defineProperty(N.prototype,e,{enumerable:!0})}),[`open`,`error`,`close`,`message`].forEach(e=>{Object.defineProperty(N.prototype,`on${e}`,{enumerable:!0,get(){for(let t of this.listeners(e))if(t[b])return t[x];return null},set(t){for(let t of this.listeners(e))if(t[b]){this.removeListener(e,t);break}typeof t==`function`&&this.addEventListener(e,t,{[b]:!0})}})}),N.prototype.addEventListener=T,N.prototype.removeEventListener=E,t.exports=N;function te(e,t,n,a){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:_,protocolVersion:j[1],maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...a,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:`GET`,host:void 0,path:void 0,port:void 0};if(e._autoPong=o.autoPong,e._closeTimeout=o.closeTimeout,!j.includes(o.protocolVersion))throw RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${j.join(`, `)})`);let l;if(t instanceof d)l=t;else try{l=new d(t)}catch{throw SyntaxError(`Invalid URL: ${t}`)}l.protocol===`http:`?l.protocol=`ws:`:l.protocol===`https:`&&(l.protocol=`wss:`),e._url=l.href;let u=l.protocol===`wss:`,p=l.protocol===`ws+unix:`,m;if(l.protocol!==`ws:`&&!u&&!p?m=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:p&&!l.pathname?m=`The URL's pathname is empty`:l.hash&&(m=`The URL contains a fragment identifier`),m){let t=SyntaxError(m);if(e._redirects===0)throw t;ne(e,t);return}let h=u?443:80,g=s(16).toString(`base64`),v=u?r.request:i.request,b=new Set,x;if(o.createConnection=o.createConnection||(u?re:P),o.defaultPort=o.defaultPort||h,o.port=l.port||h,o.host=l.hostname.startsWith(`[`)?l.hostname.slice(1,-1):l.hostname,o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":g,Connection:`Upgrade`,Upgrade:`websocket`},o.path=l.pathname+l.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&(x=new f(o.perMessageDeflate===!0?{}:o.perMessageDeflate,!1,o.maxPayload),o.headers[`Sec-WebSocket-Extensions`]=D({[f.extensionName]:x.offer()})),n.length){for(let e of n){if(typeof e!=`string`||!ee.test(e)||b.has(e))throw SyntaxError(`An invalid or duplicated subprotocol was specified`);b.add(e)}o.headers[`Sec-WebSocket-Protocol`]=n.join(`,`)}if(o.origin&&(o.protocolVersion<13?o.headers[`Sec-WebSocket-Origin`]=o.origin:o.headers.Origin=o.origin),(l.username||l.password)&&(o.auth=`${l.username}:${l.password}`),p){let e=o.path.split(`:`);o.socketPath=e[0],o.path=e[1]}let S;if(o.followRedirects){if(e._redirects===0){e._originalIpc=p,e._originalSecure=u,e._originalHostOrSocketPath=p?o.socketPath:l.host;let t=a&&a.headers;if(a={...a,headers:{}},t)for(let[e,n]of Object.entries(t))a.headers[e.toLowerCase()]=n}else if(e.listenerCount(`redirect`)===0){let t=p?e._originalIpc?o.socketPath===e._originalHostOrSocketPath:!1:e._originalIpc?!1:l.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!u)&&(delete o.headers.authorization,delete o.headers.cookie,t||delete o.headers.host,o.auth=void 0)}o.auth&&!a.headers.authorization&&(a.headers.authorization=`Basic `+Buffer.from(o.auth).toString(`base64`)),S=e._req=v(o),e._redirects&&e.emit(`redirect`,e.url,S)}else S=e._req=v(o);o.timeout&&S.on(`timeout`,()=>{F(e,S,`Opening handshake has timed out`)}),S.on(`error`,t=>{S===null||S[A]||(S=e._req=null,ne(e,t))}),S.on(`response`,r=>{let i=r.headers.location,s=r.statusCode;if(i&&o.followRedirects&&s>=300&&s<400){if(++e._redirects>o.maxRedirects){F(e,S,`Maximum redirects exceeded`);return}S.abort();let r;try{r=new d(i,t)}catch{ne(e,SyntaxError(`Invalid URL: ${i}`));return}te(e,r,n,a)}else e.emit(`unexpected-response`,S,r)||F(e,S,`Unexpected server response: ${r.statusCode}`)}),S.on(`upgrade`,(t,n,r)=>{if(e.emit(`upgrade`,t),e.readyState!==N.CONNECTING)return;S=e._req=null;let i=t.headers.upgrade;if(i===void 0||i.toLowerCase()!==`websocket`){F(e,n,`Invalid Upgrade header`);return}let a=c(`sha1`).update(g+y).digest(`base64`);if(t.headers[`sec-websocket-accept`]!==a){F(e,n,`Invalid Sec-WebSocket-Accept header`);return}let s=t.headers[`sec-websocket-protocol`],l;if(s===void 0?b.size&&(l=`Server sent no subprotocol`):b.size?b.has(s)||(l=`Server sent an invalid subprotocol`):l=`Server sent a subprotocol but none was requested`,l){F(e,n,l);return}s&&(e._protocol=s);let u=t.headers[`sec-websocket-extensions`];if(u!==void 0){if(!x){F(e,n,`Server sent a Sec-WebSocket-Extensions header but no extension was requested`);return}let t;try{t=O(u)}catch{F(e,n,`Invalid Sec-WebSocket-Extensions header`);return}let r=Object.keys(t);if(r.length!==1||r[0]!==f.extensionName){F(e,n,`Server indicated an extension that was not requested`);return}try{x.accept(t[f.extensionName])}catch{F(e,n,`Invalid Sec-WebSocket-Extensions header`);return}e._extensions[f.extensionName]=x}e.setSocket(n,r,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(S,e):S.end()}function ne(e,t){e._readyState=N.CLOSING,e._errorEmitted=!0,e.emit(`error`,t),e.emitClose()}function P(e){return e.path=e.socketPath,a.connect(e)}function re(e){return e.path=void 0,!e.servername&&e.servername!==``&&(e.servername=a.isIP(e.host)?``:e.host),o.connect(e)}function F(e,t,n){e._readyState=N.CLOSING;let r=Error(n);Error.captureStackTrace(r,F),t.setHeader?(t[A]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(ne,e,r)):(t.destroy(r),t.once(`error`,e.emit.bind(e,`error`)),t.once(`close`,e.emitClose.bind(e)))}function ie(e,t,n){if(t){let n=h(t)?t.size:k(t).length;e._socket?e._sender._bufferedBytes+=n:e._bufferedAmount+=n}if(n){let t=Error(`WebSocket is not open: readyState ${e.readyState} (${M[e.readyState]})`);process.nextTick(n,t)}}function ae(e,t){let n=this[C];n._closeFrameReceived=!0,n._closeMessage=t,n._closeCode=e,n._socket[C]!==void 0&&(n._socket.removeListener(`data`,pe),process.nextTick(ue,n._socket),e===1005?n.close():n.close(e,t))}function I(){let e=this[C];e.isPaused||e._socket.resume()}function oe(e){let t=this[C];t._socket[C]!==void 0&&(t._socket.removeListener(`data`,pe),process.nextTick(ue,t._socket),t.close(e[S])),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e))}function se(){this[C].emitClose()}function L(e,t){this[C].emit(`message`,e,t)}function ce(e){let t=this[C];t._autoPong&&t.pong(e,!this._isServer,w),t.emit(`ping`,e)}function le(e){this[C].emit(`pong`,e)}function ue(e){e.resume()}function R(e){let t=this[C];t.readyState!==N.CLOSED&&(t.readyState===N.OPEN&&(t._readyState=N.CLOSING,de(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e)))}function de(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),e._closeTimeout)}function fe(){let e=this[C];if(this.removeListener(`close`,fe),this.removeListener(`data`,pe),this.removeListener(`end`,me),e._readyState=N.CLOSING,!this._readableState.endEmitted&&!e._closeFrameReceived&&!e._receiver._writableState.errorEmitted&&this._readableState.length!==0){let t=this.read(this._readableState.length);e._receiver.write(t)}e._receiver.end(),this[C]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on(`error`,se),e._receiver.on(`finish`,se))}function pe(e){this[C]._receiver.write(e)||this.pause()}function me(){let e=this[C];e._readyState=N.CLOSING,e._receiver.end(),this.end()}function he(){let e=this[C];this.removeListener(`error`,he),this.on(`error`,w),e&&(e._readyState=N.CLOSING,this.destroy())}})),fv=ev(((e,t)=>{dv();let{Duplex:n}=tv(`stream`);function r(e){e.emit(`close`)}function i(){!this.destroyed&&this._writableState.finished&&this.destroy()}function a(e){this.removeListener(`error`,a),this.destroy(),this.listenerCount(`error`)===0&&this.emit(`error`,e)}function o(e,t){let o=!0,s=new n({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on(`message`,function(t,n){let r=!n&&s._readableState.objectMode?t.toString():t;s.push(r)||e.pause()}),e.once(`error`,function(e){s.destroyed||(o=!1,s.destroy(e))}),e.once(`close`,function(){s.destroyed||s.push(null)}),s._destroy=function(t,n){if(e.readyState===e.CLOSED){n(t),process.nextTick(r,s);return}let i=!1;e.once(`error`,function(e){i=!0,n(e)}),e.once(`close`,function(){i||n(t),process.nextTick(r,s)}),o&&e.terminate()},s._final=function(t){if(e.readyState===e.CONNECTING){e.once(`open`,function(){s._final(t)});return}e._socket!==null&&(e._socket._writableState.finished?(t(),s._readableState.endEmitted&&s.destroy()):(e._socket.once(`finish`,function(){t()}),e.close()))},s._read=function(){e.isPaused&&e.resume()},s._write=function(t,n,r){if(e.readyState===e.CONNECTING){e.once(`open`,function(){s._write(t,n,r)});return}e.send(t,r)},s.on(`end`,i),s.on(`error`,a),s}t.exports=o})),pv=ev(((e,t)=>{let{tokenChars:n}=ov();function r(e){let t=new Set,r=-1,i=-1,a=0;for(;a<e.length;a++){let o=e.charCodeAt(a);if(i===-1&&n[o]===1)r===-1&&(r=a);else if(a!==0&&(o===32||o===9))i===-1&&r!==-1&&(i=a);else if(o===44){if(r===-1)throw SyntaxError(`Unexpected character at index ${a}`);i===-1&&(i=a);let n=e.slice(r,i);if(t.has(n))throw SyntaxError(`The "${n}" subprotocol is duplicated`);t.add(n),r=i=-1}else throw SyntaxError(`Unexpected character at index ${a}`)}if(r===-1||i!==-1)throw SyntaxError(`Unexpected end of input`);let o=e.slice(r,a);if(t.has(o))throw SyntaxError(`The "${o}" subprotocol is duplicated`);return t.add(o),t}t.exports={parse:r}})),mv=ev(((e,t)=>{let n=tv(`events`),r=tv(`http`),{Duplex:i}=tv(`stream`),{createHash:a}=tv(`crypto`),o=uv(),s=av(),c=pv(),l=dv(),{CLOSE_TIMEOUT:u,GUID:d,kWebSocket:f}=nv(),p=/^[+/0-9A-Za-z]{22}==$/;t.exports=class extends n{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:u,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:l,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw TypeError(`One and only one of the "port", "server", or "noServer" options must be specified`);if(e.port==null?e.server&&(this._server=e.server):(this._server=r.createServer((e,t)=>{let n=r.STATUS_CODES[426];t.writeHead(426,{"Content-Length":n.length,"Content-Type":`text/plain`}),t.end(n)}),this._server.listen(e.port,e.host,e.backlog,t)),this._server){let e=this.emit.bind(this,`connection`);this._removeListeners=m(this._server,{listening:this.emit.bind(this,`listening`),error:this.emit.bind(this,`error`),upgrade:(t,n,r)=>{this.handleUpgrade(t,n,r,e)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=0}address(){if(this.options.noServer)throw Error(`The server is operating in "noServer" mode`);return this._server?this._server.address():null}close(e){if(this._state===2){e&&this.once(`close`,()=>{e(Error(`The server is not running`))}),process.nextTick(h,this);return}if(e&&this.once(`close`,e),this._state!==1)if(this._state=1,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients&&this.clients.size?this._shouldEmitClose=!0:process.nextTick(h,this);else{let e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close(()=>{h(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf(`?`);if((t===-1?e.url:e.url.slice(0,t))!==this.options.path)return!1}return!0}handleUpgrade(e,t,n,r){t.on(`error`,g);let i=e.headers[`sec-websocket-key`],a=e.headers.upgrade,l=+e.headers[`sec-websocket-version`];if(e.method!==`GET`){v(this,e,t,405,`Invalid HTTP method`);return}if(a===void 0||a.toLowerCase()!==`websocket`){v(this,e,t,400,`Invalid Upgrade header`);return}if(i===void 0||!p.test(i)){v(this,e,t,400,`Missing or invalid Sec-WebSocket-Key header`);return}if(l!==13&&l!==8){v(this,e,t,400,`Missing or invalid Sec-WebSocket-Version header`,{"Sec-WebSocket-Version":`13, 8`});return}if(!this.shouldHandle(e)){_(t,400);return}let u=e.headers[`sec-websocket-protocol`],d=new Set;if(u!==void 0)try{d=c.parse(u)}catch{v(this,e,t,400,`Invalid Sec-WebSocket-Protocol header`);return}let f=e.headers[`sec-websocket-extensions`],m={};if(this.options.perMessageDeflate&&f!==void 0){let n=new s(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let e=o.parse(f);e[s.extensionName]&&(n.accept(e[s.extensionName]),m[s.extensionName]=n)}catch{v(this,e,t,400,`Invalid or unacceptable Sec-WebSocket-Extensions header`);return}}if(this.options.verifyClient){let a={origin:e.headers[`${l===8?`sec-websocket-origin`:`origin`}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(a,(a,o,s,c)=>{if(!a)return _(t,o||401,s,c);this.completeUpgrade(m,i,d,e,t,n,r)});return}if(!this.options.verifyClient(a))return _(t,401)}this.completeUpgrade(m,i,d,e,t,n,r)}completeUpgrade(e,t,n,r,i,c,l){if(!i.readable||!i.writable)return i.destroy();if(i[f])throw Error(`server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration`);if(this._state>0)return _(i,503);let u=[`HTTP/1.1 101 Switching Protocols`,`Upgrade: websocket`,`Connection: Upgrade`,`Sec-WebSocket-Accept: ${a(`sha1`).update(t+d).digest(`base64`)}`],p=new this.options.WebSocket(null,void 0,this.options);if(n.size){let e=this.options.handleProtocols?this.options.handleProtocols(n,r):n.values().next().value;e&&(u.push(`Sec-WebSocket-Protocol: ${e}`),p._protocol=e)}if(e[s.extensionName]){let t=e[s.extensionName].params,n=o.format({[s.extensionName]:[t]});u.push(`Sec-WebSocket-Extensions: ${n}`),p._extensions=e}this.emit(`headers`,u,r),i.write(u.concat(`\r
70
+ `)){if(i(e))continue;let t=e.match(/^(#{1,6})\s+(.+)$/);if(t){let e=t[2].trim(),i=b(e,r);i&&n.push({level:t[1].length,text:e,slug:i})}}return n}function Qh(e){return!(e.includes(`..`)||e.startsWith(`/`)||e.includes(`\0`)||e.includes(`\\`))}function $h(e){let{hocuspocus:t,sessionManager:n,contentDir:r,getFileIndex:i,getAliasMap:a,enableTestRoutes:o=!1,shadowRef:s,flushGitCommit:l,getCurrentBranch:d,contentRoot:f,backlinkIndex:m,signalChannel:h,agentFocusBroadcaster:g,onAgentWrite:_,getSyncEngine:y,localOpCliArgs:b=[`open-knowledge`],projectDir:x}=e,S=Dm();function C(e){if(!Qh(e))return null;let t=V(r),n=V(t,`${e}${Af(e)}`);return!n.startsWith(`${t}/`)&&n!==t?null:n}function w(e){let t=C(e);if(!t||!L(t))return e;try{return hf(R(t,`utf-8`),e)}catch{return e}}let T={cluster:void 0,category:void 0,tags:void 0};function E(e){try{let n=t.documents.get(e);if(n){let e=n.getMap(`metadata`).get(`frontmatter`);if(typeof e==`string`&&e)return gf(e)}}catch{}try{let t=C(e);if(!t||!L(t))return T;let{frontmatter:n}=A(R(t,`utf-8`));return n?gf(n):T}catch{return T}}function D(e){if(m)try{if(m.getBacklinks(e).length>0)return;let t=performance.now(),n=nf(e,i()),r=performance.now()-t;return r>5&&Ih.debug({docName:e,elapsedMs:r,candidateCount:n.length},`[orphan-hint] findHubCandidates slow`),n.length===0?void 0:[{type:`orphan`,parentCandidates:n,message:`This doc has no backlinks yet. To make it discoverable, consider linking from a parent hub doc (index/overview files in the folder tree): ${n.map(e=>`[[${e}]]`).join(`, `)}.`}]}catch(e){console.warn(`[orphan-hint] computeOrphanHints failed:`,e);return}}function O(e){return a?.().get(e)??e}function k(e){try{return t.documents.get(e)?.connections.size??0}catch{return 0}}function j(e,n){let r=`onStoreDocument-${e}`;(t.debouncer.isDebounced(r)?t.debouncer.executeNow(r):Promise.resolve()).then(()=>l?.()).catch(e=>{Ih.warn({err:e},`[${n}] post-write flush failed`)})}function M(){let e=new Set;for(let[t,n]of i()){e.add(t);for(let t of n.aliases)e.add(t)}return e}function ee(){let e=Promise.resolve();return async function(t){let n=e,r=()=>{};e=new Promise(e=>{r=e}),await n;try{return await t()}finally{r()}}}let N=ee();function te(e){return e instanceof Error&&(e.message===`Managed rename requires backlink index support`||e.message.startsWith(`Cannot rename missing document:`)||e.message.startsWith(`symlink-escape:`))?e.message:`Failed to rename document`}async function ne(e){let r=new Map;for(let n of e){let e=t.documents.get(n);e&&r.set(n,e.getText(`source`).toString())}for(let t of e)await n.closeAllForDoc(t).catch(e=>{console.warn(`[file-ops] Failed to close agent session for ${t}:`,e)});for(let n of e){let e=t.documents.get(n);Bp(n),e&&(t.closeConnections(n),await t.unloadDocument(e))}return r}function P(e,t){for(let{fromDocName:n,toDocName:i}of e){let e=Mp(i,r),a=t.get(n);typeof a==`string`&&z(e,a,`utf-8`);let o=typeof a==`string`?a:L(e)?R(e,`utf-8`):null;typeof o==`string`&&em(e,nm(o))}}function F(e,t){return e.map(e=>{let n=t.get(e);if(typeof n==`string`)return{docName:e,content:n};let i=Mp(e,r);if(!L(i))throw Error(`Cannot snapshot missing document: ${e}`);return{docName:e,content:R(i,`utf-8`)}})}function ie(e){let n=t.documents.get(e);if(n)return n.getText(`source`).toString();let i=Yh(r,`file`,e);return L(i)?R(i,`utf-8`):null}function I(e,t){let n=Yh(r,`file`,e);le(xe(n),{recursive:!0}),z(n,t,`utf-8`),em(n,nm(t)),zp(e,t);let a=i();a instanceof Map&&dm({kind:`update`,path:n,docName:e,content:t},a)}function oe(e,n,r){let i=t.documents.get(e);if(!i)throw Error(`Document is not loaded: ${e}`);let a={markdown:``,rewrites:0};return i.transact(()=>{let t=i.getXmlFragment(`default`),o=i.getText(`source`),s=o.toString();if(a=qh(s,e,n,r),a.rewrites===0)return;let{body:c}=A(a.markdown),l=el.parseWithFallback(c);ls(i,t,tl.nodeFromJSON(l),{mapping:new Map,isOMark:new Map}),p(o,s,a.markdown)},Fh),a}async function se(e,n){return N(async()=>{if(!m)throw Error(`Managed rename requires backlink index support`);let a=Yh(r,`file`,e),o=Yh(r,`file`,n),s=[{fromDocName:e,toDocName:n}],c=[...new Set(m.getBacklinks(e).map(e=>e.source))].sort((e,t)=>e.localeCompare(t)),l=new Map,u=[],d=[];for(let t of[e,...c]){if(l.has(t))continue;let n=ie(t);typeof n==`string`?(l.set(t,n),t!==e&&u.push(t)):t!==e&&d.push(t)}if(typeof l.get(e)!=`string`)throw Error(`Cannot rename missing document: ${e}`);let f=Mm({sourceDocName:e,destinationDocName:n,snapshots:F([...l.keys()],l)}),p=[];return await Rm(r,f,async()=>{for(let e of d)m.deleteDocument(e);for(let r of u){let i=t.documents.get(r)?oe(r,e,n):qh(l.get(r)??``,r,e,n);i.rewrites>0&&(I(r,i.markdown),p.push({docName:r,rewrites:i.rewrites})),m.updateDocumentFromMarkdown(r,i.markdown)}let r=qh((await ne([e])).get(e)??l.get(e)??R(a,`utf-8`),e,e,n);le(xe(o),{recursive:!0}),pe(a,o),P(s,new Map([[e,r.markdown]])),zp(n,r.markdown);let c=i();c instanceof Map&&dm({kind:`rename`,oldPath:a,newPath:o,oldDocName:e,newDocName:n,content:r.markdown},c),m.renameDocument(e,n,r.markdown),r.rewrites>0&&p.push({docName:n,rewrites:r.rewrites})}),m.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist managed rename cache for ${e} -> ${n}:`,t)}),h?.(`files`),h?.(`backlinks`),h?.(`graph`),p.sort((e,t)=>e.docName.localeCompare(t.docName)),{renamed:s,rewrittenDocs:p}})}let ce=/^[a-zA-Z0-9_-]+$/;function ue(e){let t=typeof e.agentId==`string`?e.agentId:void 0;t!==void 0&&!ce.test(t)&&(t=void 0);let n=t?`agent-${t}`:`claude-1`,r=typeof e.agentName==`string`?e.agentName.slice(0,128).replace(/[\r\n]/g,``):`Claude`,i=typeof e.clientName==`string`?e.clientName:void 0;i!==void 0&&(i=i.slice(0,128).replace(/[\r\n]/g,``));let a=typeof e.colorSeed==`string`&&e.colorSeed.length>0?e.colorSeed.slice(0,128):t??n;return{rawAgentId:t,agentId:n,agentName:r,colorSeed:a,clientName:i}}async function _e(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}try{let r;try{r=await Xh(e)}catch{J(t,413,{ok:!1,error:`Payload too large`});return}let i;try{i=r.length>0?JSON.parse(r.toString()):{}}catch{J(t,400,{ok:!1,error:`Invalid JSON`});return}let a=typeof i.docName==`string`&&i.docName.length>0?i.docName:`test-doc`;if(!Qh(a)){J(t,400,{ok:!1,error:`Invalid docName`});return}let o=O(a);if(q(o)){J(t,400,{ok:!1,error:`'${o}' is a reserved document name`});return}let{agentId:s,agentName:c,colorSeed:l,clientName:u}=ue(i),d=await n.getSession(o,s,{displayName:c,colorSeed:l,clientName:u}),f=new Date().toISOString(),p=typeof i.content==`string`?i.content:`Hello from the agent! ${f}`;d.document.awareness.setLocalStateField(`mode`,`editing`);try{d.document.transact(()=>{al(d.document,`${p}\n`,`append`),d.document.getMap(`activity`).set(s,{agentId:s,timestamp:Date.now(),type:`insert`,description:`Added (${c}): ${p.slice(0,50)}`})},rl),Zd(o,s,c,l)}finally{d.document.awareness.setLocalStateField(`mode`,`idle`)}j(o,`agent-write`),J(t,200,{ok:!0,timestamp:f})}catch(e){Ih.error({err:e},`[agent-write] handler failed`),J(t,500,{ok:!1,error:`Internal server error`})}}async function ve(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}try{let r;try{r=await Xh(e)}catch{J(t,413,{ok:!1,error:`Payload too large`});return}let i;try{i=JSON.parse(r.toString())}catch{J(t,400,{ok:!1,error:`Invalid JSON`});return}if(!i||typeof i!=`object`||Array.isArray(i)){J(t,400,{ok:!1,error:`Body must be a JSON object`});return}let{markdown:a,position:o}=i;if(!a||typeof a!=`string`){J(t,400,{ok:!1,error:`markdown field required`});return}let s=o===`prepend`?`prepend`:o===`replace`?`replace`:`append`,c=i.docName,l=typeof c==`string`&&c.length>0?c:`test-doc`;if(!Qh(l)){J(t,400,{ok:!1,error:`Invalid docName`});return}let u=O(l);if(q(u)){J(t,400,{ok:!1,error:`'${u}' is a reserved document name`});return}let{agentId:d,agentName:f,colorSeed:p,clientName:m}=ue(i),h=await n.getSession(u,d,{displayName:f,colorSeed:p,clientName:m}),v=new Date().toISOString();h.document.awareness.setLocalStateField(`mode`,`editing`);try{h.document.transact(()=>{al(h.document,a,s),h.document.getMap(`activity`).set(d,{agentId:d,timestamp:Date.now(),type:`insert`,description:`Added (${f}): ${a.trim().slice(0,50)}`})},rl),Zd(u,d,f,p)}finally{h.document.awareness.setLocalStateField(`mode`,`idle`)}j(u,`agent-write-md`),g?.setFocus(d,{agentName:f,currentDoc:u,writeKind:`write`,ts:Date.now()}),_?.();let y=D(u);J(t,200,{ok:!0,timestamp:v,subscriberCount:k(u),...y?{hints:y}:{}})}catch(e){Ih.error({err:e},`[agent-write-md] handler failed`),J(t,500,{ok:!1,error:`Internal server error`})}}async function ye(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}try{let r=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)||`test-doc`;if(!Qh(r)){J(t,400,{ok:!1,error:`Invalid docName`});return}let i=O(r);if(q(i)){J(t,400,{ok:!1,error:`'${i}' is a reserved document name`});return}J(t,200,{ok:!0,docName:i,content:(await n.getSession(i)).document.getText(`source`).toString()})}catch(e){console.error(`[document-read]`,e),J(t,500,{ok:!1,error:`Internal server error`})}}async function be(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}try{let n=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`dir`);if(n)try{Uh(r,n)}catch{J(t,400,{ok:!1,error:`Invalid directory parameter`});return}let a=i(),o=[];for(let[e,t]of a)if(!(n&&!e.startsWith(`${n}/`)&&e!==n)){o.push({docName:e,size:t.size,modified:t.modified,isSymlink:!1,canonicalDocName:null,targetPath:null});for(let i of t.aliases){if(n&&!i.startsWith(`${n}/`)&&i!==n)continue;let a=B(r,t.canonicalPath);o.push({docName:i,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:a})}}o.sort((e,t)=>e.docName.localeCompare(t.docName)),J(t,200,{ok:!0,documents:o})}catch(e){console.error(`[document-list]`,e),J(t,500,{ok:!1,error:`Internal server error`})}}async function Se(e,t){if(e.method!==`GET`){J(t,405,{ok:!1,error:`Method not allowed`});return}if(!m){J(t,503,{ok:!1,error:`Backlink index not configured`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!n){J(t,400,{ok:!1,error:`Missing docName parameter`});return}if(!Qh(n)){J(t,400,{ok:!1,error:`Invalid docName`});return}J(t,200,{ok:!0,docName:n,backlinks:m.getBacklinks(n).map(e=>({source:e.source,anchor:e.anchor,title:w(e.source),snippet:e.snippet}))})}catch(e){console.error(`[backlinks]`,e),J(t,500,{ok:!1,error:`Failed to read backlinks`})}}async function Ce(e,t){if(e.method!==`GET`){J(t,405,{ok:!1,error:`Method not allowed`});return}if(!m){J(t,503,{ok:!1,error:`Backlink index not configured`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`docNames`);if(!n){J(t,400,{ok:!1,error:`Missing docNames parameter`});return}let r={};for(let e of n.split(`,`)){let t=e.trim();!t||!Qh(t)||(r[t]=m.getBacklinkCount(t))}J(t,200,{ok:!0,counts:r})}catch(e){console.error(`[backlink-counts]`,e),J(t,500,{ok:!1,error:`Failed to read backlink counts`})}}async function we(e,t){if(e.method!==`GET`){J(t,405,{ok:!1,error:`Method not allowed`});return}if(!m){J(t,503,{ok:!1,error:`Backlink index not configured`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!n){J(t,400,{ok:!1,error:`Missing docName parameter`});return}if(!Qh(n)){J(t,400,{ok:!1,error:`Invalid docName`});return}J(t,200,{ok:!0,docName:n,forwardLinks:m.getForwardLinkEntries(n).map(e=>e.kind===`doc`?{kind:`doc`,docName:e.target,anchor:e.anchor,title:w(e.target),snippet:e.snippet}:{kind:`external`,url:e.url,title:e.label??e.url,snippet:e.snippet})})}catch(e){console.error(`[forward-links]`,e),J(t,500,{ok:!1,error:`Failed to read forward links`})}}async function Ee(e,t){if(e.method!==`GET`){J(t,405,{ok:!1,error:`Method not allowed`});return}if(!m){J(t,503,{ok:!1,error:`Backlink index not configured`});return}try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`docName`);if(r&&!Qh(r)){J(t,400,{ok:!1,error:`Invalid docName`});return}let i=n.searchParams.get(`degrees`);if(i&&!r){J(t,400,{ok:!1,error:`docName is required when degrees is provided`});return}let a,o;if(i&&r){let e=Number.parseInt(i,10);if(!Number.isFinite(e)||e<0){J(t,400,{ok:!1,error:`degrees must be a non-negative integer`});return}({nodes:a,links:o}=m.getLinkGraphNeighborhood(r,e))}else ({nodes:a,links:o}=m.getLinkGraph());J(t,200,{ok:!0,nodes:a.map(e=>{if(e.kind===`doc`){let t=E(e.docName);return{id:e.id,kind:`doc`,docName:e.docName,anchor:e.anchor??null,label:w(e.docName),cluster:t.cluster??null,category:t.category??null,tags:t.tags??null}}return{id:e.id,kind:`external`,url:e.url,label:e.label??e.url}}),links:o})}catch(e){console.error(`[link-graph]`,e),J(t,500,{ok:!1,error:`Failed to read link graph`})}}async function De(e,t){if(e.method!==`GET`){J(t,405,{ok:!1,error:`Method not allowed`});return}if(!m){J(t,503,{ok:!1,error:`Backlink index not configured`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`mode`)??`both`;if(!v(n)){J(t,400,{ok:!1,error:`Invalid orphan mode. Allowed values: incoming, outgoing, both`});return}J(t,200,{ok:!0,orphans:m.getOrphans([...i().keys()],n).map(e=>({docName:e,title:w(e)}))})}catch(e){console.error(`[orphans]`,e),J(t,500,{ok:!1,error:`Failed to read orphan pages`})}}async function Oe(e,t){if(e.method!==`GET`){J(t,405,{ok:!1,error:`Method not allowed`});return}if(!m){J(t,503,{ok:!1,error:`Backlink index not configured`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`limit`),r=n?Number.parseInt(n,10):20,i=Number.isFinite(r)&&r>0?r:20;J(t,200,{ok:!0,hubs:m.getHubs(i).map(e=>({docName:e.docName,title:w(e.docName),count:e.count}))})}catch(e){console.error(`[hubs]`,e),J(t,500,{ok:!1,error:`Failed to read hub pages`})}}async function ke(e,t){if(e.method!==`GET`){J(t,405,{ok:!1,error:`Method not allowed`});return}if(!m){J(t,503,{ok:!1,error:`Backlink index not configured`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.getAll(`sourceDocName`);if(n.some(e=>e.length===0||!Qh(e))){J(t,400,{ok:!1,error:`Invalid sourceDocName`});return}let r=n.length?[...new Set(n.map(e=>O(e)))]:void 0;J(t,200,{ok:!0,deadLinks:m.getDeadLinks(M(),r).map(e=>({target:e.target,sources:e.sources.map(e=>({source:e.source,title:w(e.source),snippet:e.snippet}))}))})}catch(e){console.error(`[dead-links]`,e),J(t,500,{ok:!1,error:`Failed to read dead links`})}}async function Ae(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}try{let r;try{r=await Xh(e)}catch{J(t,413,{ok:!1,error:`Payload too large`});return}let i;try{i=JSON.parse(r.toString())}catch{J(t,400,{ok:!1,error:`Invalid JSON`});return}if(!i||typeof i!=`object`||Array.isArray(i)){J(t,400,{ok:!1,error:`Body must be a JSON object`});return}let{find:a,replace:o,docName:s,offset:c}=i;if(typeof a!=`string`||a.length===0){J(t,400,{ok:!1,error:`find field required`});return}if(typeof o!=`string`){J(t,400,{ok:!1,error:`replace field required`});return}let l=Object.hasOwn(i,`offset`),d;if(l){if(typeof c!=`number`||!Number.isInteger(c)||c<0){J(t,400,{ok:!1,error:`offset must be a non-negative integer`});return}d=c}let f=typeof s==`string`&&s.length>0?s:`test-doc`;if(!Qh(f)){J(t,400,{ok:!1,error:`Invalid docName`});return}let p=O(f);if(q(p)){J(t,400,{ok:!1,error:`'${p}' is a reserved document name`});return}let{agentId:m,agentName:h,colorSeed:v,clientName:y}=ue(i),b=await n.getSession(p,m,{displayName:h,colorSeed:v,clientName:y}),x=new Date().toISOString(),S=!1,C=!1;b.document.awareness.setLocalStateField(`mode`,`editing`);try{b.document.transact(()=>{let e=b.document.getXmlFragment(`default`),t=b.document.getMap(`metadata`),n=t.get(`frontmatter`)??``,r=u(n,el.serialize(fs(e,tl).toJSON())),i=d==null?r.indexOf(a):r.slice(d,d+a.length)===a?d:-1;if(i===-1){d==null?S=!0:C=!0;return}let{frontmatter:s,body:c}=A(r.slice(0,i)+o+r.slice(i+a.length));s!==n&&t.set(`frontmatter`,s),al(b.document,c,`replace`),b.document.getMap(`activity`).set(m,{agentId:m,timestamp:Date.now(),type:`insert`,description:`Patched (${h}): ${a.slice(0,50)}`})},rl),!S&&!C&&Zd(p,m,h,v)}finally{b.document.awareness.setLocalStateField(`mode`,`idle`)}if(C){J(t,409,{ok:!1,error:`Target text no longer matches at the requested offset`});return}if(S){J(t,404,{ok:!1,error:`Text not found in document`});return}j(p,`agent-patch`),g?.setFocus(m,{agentName:h,currentDoc:p,writeKind:`edit`,ts:Date.now()}),_?.(),J(t,200,{ok:!0,timestamp:x,subscriberCount:k(p)})}catch(e){Ih.error({err:e},`[agent-patch] handler failed`),J(t,500,{ok:!1,error:`Internal server error`})}}async function Me(e,i){if(e.method!==`POST`){i.writeHead(405),i.end(`Method not allowed`);return}try{let a=O(new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)??`test-doc`),o;try{o=Mp(a,r)}catch(e){console.error(`[test-reset] safeContentPath rejected docName:`,a,e),J(i,400,{ok:!1,error:`Invalid docName`});return}await n.closeAll(a),t.closeConnections(a);let s=`onStoreDocument-${a}`;t.debouncer.isDebounced(s)&&await t.debouncer.executeNow(s);let c=t.documents.get(a);c&&await t.unloadDocument(c),z(o,``,`utf-8`),m&&(m.deleteDocument(a),m.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist cache after test-reset for ${a}:`,e)}),h?.(`backlinks`),h?.(`graph`)),h?.(`files`),J(i,200,{ok:!0})}catch(e){console.error(`[test-reset]`,e),J(i,500,{ok:!1,error:`Internal server error`})}}async function Pe(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}try{if(!m){J(t,503,{ok:!1,error:`Backlink index not configured`});return}m.rebuildFromDisk(),m.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist cache after test-rescan-backlinks:`,e)}),h?.(`backlinks`),h?.(`graph`),J(t,200,{ok:!0})}catch(e){console.error(`[test-rescan-backlinks]`,e),J(t,500,{ok:!1,error:`Internal server error`})}}async function Fe(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}let n=s?.current;if(!n){J(t,400,{ok:!1,error:`Shadow repo not configured`});return}try{let r;try{r=await Xh(e)}catch{J(t,413,{ok:!1,error:`Payload too large`});return}let i=/^[a-zA-Z0-9_-]+$/,a=[],o;if(r.length>0){let e;try{e=JSON.parse(r.toString())}catch{J(t,400,{ok:!1,error:`Invalid JSON`});return}typeof e.message==`string`&&e.message.trim()&&(o=e.message.replace(/[\r\n]/g,` `).slice(0,256)),Array.isArray(e.writers)&&(a=e.writers.map(e=>{let t=e.id??`unknown`;if(!i.test(t))throw Error(`Invalid writer id: ${t}`);return{id:t,name:(e.name??`unknown`).replace(/[\r\n]/g,``),email:(e.email??`noreply@openknowledge.local`).replace(/[\r\n]/g,``)}}))}a.length===0&&(a=[{id:`server`,name:`openknowledge-server`,email:`noreply@openknowledge.local`}]);let s=f??`content`,c=await Ap(n,s,a);console.log(`[shadow] checkpoint ${c.checkpointRef}`);let l;if(x)try{l=await ae(async()=>{let e=Ne({baseDir:x,timeout:{block:15e3}}),t=(await e.tags([`--list`,`ok/v*`])).all.length+1,n=`ok/v${t}`,r=o??`Checkpoint v${t}`,i=s||`.`;return await e.add(i),await e.commit(r,{"--allow-empty":null}),await e.addTag(n),console.log(`[checkpoint] parent-git commit + tag ${n}`),n})}catch(e){console.warn(`[checkpoint] parent-git commit failed (non-fatal):`,e)}J(t,200,{ok:!0,checkpointRef:c.checkpointRef,...l?{versionTag:l}:{}})}catch(e){console.error(`[save-version]`,e),J(t,500,{ok:!1,error:`Internal server error`})}}async function Ie(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}let n=s?.current;if(!n){J(t,400,{ok:!1,error:`Shadow repo not configured`});return}let r=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),i=r.searchParams.get(`docName`)??``,a=r.searchParams.get(`branch`)??d?.()??`main`;if(!i){J(t,400,{ok:!1,error:`docName query parameter is required`});return}if(a.includes(`..`)||!/^[a-zA-Z0-9][a-zA-Z0-9._/-]*$/.test(a)){J(t,400,{ok:!1,error:`Invalid branch name`});return}let o=Number(r.searchParams.get(`limit`)??`50`),c=Number(r.searchParams.get(`offset`)??`0`),l=Math.min(200,Number.isFinite(o)?o:50),u=Number.isFinite(c)?c:0,p=r.searchParams.get(`type`)??void 0,m=r.searchParams.get(`author`)??void 0,h=r.searchParams.get(`excludeAuthor`)??void 0,g=Date.now();try{let e=await Mh(n,{docName:i,branch:a,limit:l,offset:u,type:p,author:m,excludeAuthor:h},f??`content`),r=Date.now()-g;console.log(`[timeline] query docName=${i} entries=${e.entries.length} duration=${r}ms`),J(t,200,{ok:!0,...e})}catch(e){console.error(`[history]`,e),J(t,500,{ok:!1,error:e instanceof Error?e.message:String(e)})}}async function Le(e,t,n){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}let r=s?.current;if(!r){J(t,400,{ok:!1,error:`Shadow repo not configured`});return}let i=Lh(new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)??``,f??`content`);if(`error`in i){J(t,400,{ok:!1,error:i.error});return}let a=i.path,o=vp(r);if(!/^[0-9a-f]{40}$/i.test(n)){J(t,400,{ok:!1,error:`Invalid commit SHA`});return}try{try{await o.raw(`cat-file`,`-e`,`${n}:${a}`)}catch{J(t,404,{ok:!1,error:`Document did not exist at this version`});return}let e=await o.raw(`show`,`${n}:${a}`),[r=``,i=``]=(await o.raw(`log`,`-1`,`--format=%aI%x00%an`,n)).trim().split(`\0`);J(t,200,{ok:!0,sha:n,content:e,timestamp:r,author:i})}catch(e){console.error(`[history-version]`,e),J(t,500,{ok:!1,error:`Internal server error`})}}async function Re(e,n){if(e.method!==`GET`){n.writeHead(405),n.end(`Method not allowed`);return}let r=s?.current;if(!r){J(n,400,{ok:!1,error:`Shadow repo not configured`});return}let i=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),a=i.searchParams.get(`docName`)??``,o=i.searchParams.get(`from`)??``,c=i.searchParams.get(`to`)??``;if(!c||!/^[0-9a-f]{40}$/i.test(c)){J(n,400,{ok:!1,error:`'to' must be a valid 40-char commit SHA`});return}let l=Lh(a,f??`content`);if(`error`in l){J(n,400,{ok:!1,error:l.error});return}let u=l.path,d=vp(r);try{let e;try{e=await d.raw(`show`,`${c}:${u}`)}catch{J(n,404,{ok:!1,error:`Document did not exist at the target version`});return}let r;if(o&&/^[0-9a-f]{40}$/i.test(o))try{r=await d.raw(`show`,`${o}:${u}`)}catch{J(n,404,{ok:!1,error:`Document did not exist at the source version`});return}else{let e=t.documents.get(a);if(!e){J(n,409,{ok:!1,error:`Document is not currently open — open it in the editor first`});return}r=e.getText(`source`).toString()}let i=A(r).body,s=A(e).body,l=kl(i,s),f=[],p=0,m=0;for(let e of l){let t=e.value.replace(/\n$/,``).split(`
71
+ `),n=e.added?`added`:e.removed?`removed`:`unchanged`;for(let e of t)f.push({type:n,text:e});e.added&&(p+=t.length),e.removed&&(m+=t.length)}J(n,200,{ok:!0,lines:f,additions:p,deletions:m})}catch(e){console.error(`[diff]`,e),J(n,500,{ok:!1,error:`Internal server error`})}}async function ze(e,n){if(e.method!==`POST`){n.writeHead(405),n.end(`Method not allowed`);return}let r=s?.current;if(!r){J(n,400,{ok:!1,error:`Shadow repo not configured`});return}let i;try{i=await Xh(e)}catch{J(n,413,{ok:!1,error:`Payload too large`});return}let a;try{a=i.length>0?JSON.parse(i.toString()):{}}catch{J(n,400,{ok:!1,error:`Invalid JSON`});return}if(!a||typeof a!=`object`||Array.isArray(a)){J(n,400,{ok:!1,error:`Body must be a JSON object`});return}let{docName:o,commitSha:c,versionTag:u}=a,d=typeof o==`string`?o:``,p=typeof c==`string`?c:``,m=typeof u==`string`?u:void 0;if(!d){J(n,400,{ok:!1,error:`docName required`});return}if(!p||!/^[0-9a-f]{40}$/i.test(p)){J(n,400,{ok:!1,error:`commitSha must be a valid 40-char commit SHA`});return}let h=f??`content`,g=Lh(d,h);if(`error`in g){J(n,400,{ok:!1,error:g.error});return}let _=g.path,v=vp(r),y=Date.now();try{try{await v.raw(`cat-file`,`-e`,`${p}:${_}`)}catch{J(n,404,{ok:!1,error:`Document did not exist at this version`});return}let e=await v.raw(`show`,`${p}:${_}`),i=new Date().toISOString();await Tp(r,h,{action:`rollback`,context:{docName:d,targetSha:p}});let a=t.documents.get(d);if(!a){J(n,409,{ok:!1,error:`Document is not currently open — open it in the editor first`});return}let{frontmatter:o,body:s}=A(e),c=el.parseWithFallback(s),u=tl.nodeFromJSON(c),g=a.getXmlFragment(`default`);a.transact(()=>{ls(a,g,u,{mapping:new Map,isOMark:new Map});let t=a.getText(`source`),n=t.toString();n!==e&&(t.delete(0,n.length),t.insert(0,e)),a.getMap(`metadata`).set(`frontmatter`,o)},Ph),zp(d,e),l&&l().catch(e=>{console.warn(`[rollback] flush git commit failed:`,e)});let b=Date.now()-y;if(console.log(`[rollback] docName=${d} from=${p.slice(0,8)} duration=${b}ms`),x){let e=`Restored to ${m??p.slice(0,8)}: ${d}`,t=f??`content`;ae(async()=>{let n=Ne({baseDir:x,timeout:{block:15e3}}),r=t||`.`;await n.add(r),await n.commit(e,{"--allow-empty":null}),console.log(`[rollback] parent-git commit: ${e}`)}).catch(e=>{console.warn(`[rollback] parent-git commit failed (non-fatal):`,e)})}J(n,200,{ok:!0,restoredFrom:p,timestamp:i})}catch(e){console.error(`[rollback]`,e),J(n,500,{ok:!1,error:e instanceof Error?e.message:String(e)})}}async function Be(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}J(t,200,Qc())}async function Ve(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}J(t,200,c())}async function He(e,t){if(!Om(e.socket.remoteAddress)){J(t,403,{ok:!1,error:`loopback-required`});return}if(!km(e.headers.host)){J(t,403,{ok:!1,error:`host-header-not-allowed`});return}if(e.method!==`GET`){J(t,405,{ok:!1,error:`Method not allowed`});return}let n=V(r),i=n,a=!0;try{i=fe(n)}catch(e){let r=e?.code;if(r===`ENOENT`)console.warn(`[workspace] contentDir does not exist; returning unresolved path`,{path:n}),a=!1;else{console.warn(`[workspace] realpath failed for contentDir`,{path:n,err:e}),J(t,500,{ok:!1,error:`workspace-realpath-failed`,code:r??null});return}}J(t,200,{ok:!0,contentDir:i,pathSeparator:Te,symlinkResolved:a})}let Ue=1440*60*1e3;async function We(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}if(!s?.current){J(t,200,[]);return}let n=Date.now(),r=[],i=V(s.current.gitDir,`rescue`);if(L(i))try{let e=de(i).filter(e=>Tf(e));for(let t of e){let e=V(i,t),a=he(e);if(n-a.mtimeMs>Ue){try{ge(e)}catch(e){console.debug(`[rescue] cleanup failed (non-critical):`,e)}continue}r.push({docName:Ef(t),timestamp:a.mtime.toISOString(),size:a.size,source:`flat`})}}catch(e){console.error(`[rescue] Failed to list flat-file rescue buffers:`,e)}try{let e=d?.()??`main`,t=await Dp(s.current,e);for(let e of t)r.push({...e,source:`timeline`})}catch(e){console.error(`[rescue] Failed to list timeline-ref rescue checkpoints:`,e)}J(t,200,r)}async function Ge(e,t,n){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}if(!s?.current){t.writeHead(404),t.end(`Not found`);return}let r=V(s.current.gitDir,`rescue`),i=V(r,`${n}${Af(n)}`);if(!i.startsWith(`${r}/`)){t.writeHead(400),t.end(`Invalid document name`);return}if(L(i)){let e=he(i);if(Date.now()-e.mtimeMs>Ue)try{ge(i)}catch{}else{let e=R(i,`utf-8`);t.writeHead(200,{"Content-Type":`text/markdown`,"X-Content-Type-Options":`nosniff`}),t.end(e);return}}try{let e=d?.()??`main`,r=(await Dp(s.current,e)).filter(e=>e.docName===n).sort((e,t)=>t.timestamp.localeCompare(e.timestamp))[0];if(r){let e=vp(s.current),n=((await e.raw(`ls-tree`,`-r`,r.sha)).trim().split(`
72
+ `)[0]??``).split(/\s+/)[2];if(n){let r=await e.raw(`cat-file`,`-p`,n);t.writeHead(200,{"Content-Type":`text/markdown`,"X-Content-Type-Options":`nosniff`}),t.end(r);return}}}catch(e){console.warn(`[rescue] timeline-ref fallback failed:`,e)}t.writeHead(404),t.end(`Not found`)}async function Ke(e,t){if(e.method!==`POST`){J(t,405,{ok:!1,error:`Method not allowed`});return}try{let n;try{n=await Xh(e)}catch{J(t,413,{ok:!1,error:`Payload too large`});return}let a;try{a=JSON.parse(n.toString())}catch{J(t,400,{ok:!1,error:`Invalid JSON`});return}if(!a||typeof a!=`object`||Array.isArray(a)){J(t,400,{ok:!1,error:`Body must be a JSON object`});return}let{path:o}=a;if(!o||typeof o!=`string`||o.length===0){J(t,400,{ok:!1,error:`path is required`});return}if(!Tf(o)){J(t,400,{ok:!1,error:`path must end with .md or .mdx`});return}if(o.includes(`..`)||o.startsWith(`/`)||o.includes(`\0`)||o.includes(`\\`)){J(t,400,{ok:!1,error:`path must not contain .. or start with /`});return}let s=V(r),c=V(s,o);if(!c.startsWith(`${s}/`)&&c!==s){J(t,400,{ok:!1,error:`path must not escape content directory`});return}let l=Ef(o);if(q(l)){J(t,400,{ok:!1,error:`'${l}' is a reserved document name`});return}le(xe(c),{recursive:!0});try{z(c,``,{encoding:`utf-8`,flag:`wx`})}catch(e){if(e.code===`EEXIST`){J(t,409,{ok:!1,error:`File already exists`});return}throw e}let u=Ef(o),d=typeof i==`function`?i():null;d instanceof Map&&dm({kind:`create`,path:c,docName:u,content:``},d),m&&(m.updateDocumentFromMarkdown(u,``),m.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist create-page cache for ${u}:`,e)}),h?.(`backlinks`),h?.(`graph`)),h?.(`files`),J(t,200,{ok:!0,docName:u})}catch(e){console.error(`[create-page]`,e),J(t,500,{ok:!1,error:`Failed to create page`})}}async function qe(e,t){if(e.method!==`GET`){J(t,405,{ok:!1,error:`Method not allowed`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!n||typeof n!=`string`||n.length===0){J(t,400,{ok:!1,error:`Missing docName parameter`});return}if(!Qh(n)){J(t,400,{ok:!1,error:`Invalid docName`});return}let r=C(n);if(!r){J(t,400,{ok:!1,error:`Invalid docName`});return}if(!L(r)){J(t,404,{ok:!1,error:`Page not found`});return}J(t,200,{ok:!0,docName:n,headings:Zh(R(r,`utf-8`))})}catch(e){console.error(`[page-headings]`,e),J(t,500,{ok:!1,error:`Failed to read headings`})}}async function Je(e,t){if(e.method!==`POST`){J(t,405,{ok:!1,error:`Method not allowed`});return}try{let n;try{n=await Xh(e)}catch{J(t,413,{ok:!1,error:`Payload too large`});return}let i;try{i=JSON.parse(n.toString())}catch{J(t,400,{ok:!1,error:`Invalid JSON`});return}if(!i||typeof i!=`object`||Array.isArray(i)){J(t,400,{ok:!1,error:`Body must be a JSON object`});return}let{docName:a,newDocName:o}=i;if(typeof a!=`string`||typeof o!=`string`){J(t,400,{ok:!1,error:`docName and newDocName are required`});return}if(!Wh(a)||!Wh(o)){J(t,400,{ok:!1,error:`Document names must be relative content paths`});return}if(q(a)||q(o)){J(t,400,{ok:!1,error:`Reserved document names cannot be renamed`});return}if(a===o){J(t,200,{ok:!0,renamed:[],rewrittenDocs:[]});return}if(!m){J(t,503,{ok:!1,error:`Backlink index unavailable`});return}let s=Yh(r,`file`,a),c=Yh(r,`file`,o);if(!L(s)){J(t,404,{ok:!1,error:`Document does not exist`});return}if(L(c)){J(t,409,{ok:!1,error:`Destination already exists`});return}let l=await se(a,o);J(t,200,{ok:!0,renamed:l.renamed,rewrittenDocs:l.rewrittenDocs})}catch(e){console.error(`[rename]`,e),J(t,500,{ok:!1,error:te(e)})}}async function Ye(e,t){if(e.method!==`POST`){J(t,405,{ok:!1,error:`Method not allowed`});return}try{let n;try{n=await Xh(e)}catch{J(t,413,{ok:!1,error:`Payload too large`});return}let a;try{a=JSON.parse(n.toString())}catch{J(t,400,{ok:!1,error:`Invalid JSON`});return}if(!a||typeof a!=`object`||Array.isArray(a)){J(t,400,{ok:!1,error:`Body must be a JSON object`});return}let{kind:o,fromPath:s,toPath:c}=a;if(o!==`file`&&o!==`folder`){J(t,400,{ok:!1,error:`kind must be "file" or "folder"`});return}if(typeof s!=`string`||typeof c!=`string`){J(t,400,{ok:!1,error:`fromPath and toPath are required`});return}if(!Wh(s)||!Wh(c)){J(t,400,{ok:!1,error:`Paths must be relative content paths`});return}if(s===c){J(t,200,{ok:!0,renamed:[]});return}let l=Yh(r,o,s),u=Yh(r,o,c);if(!L(l)){J(t,404,{ok:!1,error:`${o} does not exist`});return}if(L(u)){J(t,409,{ok:!1,error:`Destination already exists`});return}let d=he(l);if(o===`file`&&!d.isFile()||o===`folder`&&!d.isDirectory()){J(t,400,{ok:!1,error:`Source path is not a ${o}`});return}let f=Gh(i(),o,s),p=o===`file`?[{fromDocName:s,toDocName:c}]:f.map(e=>({fromDocName:e,toDocName:Kh(e,o,s,c)})),m=await ne(p.map(({fromDocName:e})=>e)),h=()=>{le(xe(u),{recursive:!0}),pe(l,u),P(p,m)};o===`file`?await Rm(r,Mm({sourceDocName:s,destinationDocName:c,snapshots:F(p.map(({fromDocName:e})=>e),m)}),h):h(),J(t,200,{ok:!0,renamed:p})}catch(e){console.error(`[rename-path]`,e),J(t,500,{ok:!1,error:`Failed to rename path`})}}async function Xe(e,t){if(e.method!==`POST`){J(t,405,{ok:!1,error:`Method not allowed`});return}try{let n;try{n=await Xh(e)}catch{J(t,413,{ok:!1,error:`Payload too large`});return}let a;try{a=JSON.parse(n.toString())}catch{J(t,400,{ok:!1,error:`Invalid JSON`});return}if(!a||typeof a!=`object`||Array.isArray(a)){J(t,400,{ok:!1,error:`Body must be a JSON object`});return}let{kind:o,path:s}=a;if(o!==`file`&&o!==`folder`){J(t,400,{ok:!1,error:`kind must be "file" or "folder"`});return}if(typeof s!=`string`||!Wh(s)){J(t,400,{ok:!1,error:`path must be a relative content path`});return}let c=Yh(r,o,s);if(!L(c)){J(t,404,{ok:!1,error:`${o} does not exist`});return}let l=he(c);if(o===`file`&&!l.isFile()||o===`folder`&&!l.isDirectory()){J(t,400,{ok:!1,error:`Target path is not a ${o}`});return}let u=o===`file`?[s]:Gh(i(),o,s);await ne(u),o===`file`?ge(c):me(c,{recursive:!0,force:!1}),J(t,200,{ok:!0,deletedDocNames:u})}catch(e){console.error(`[delete-path]`,e),J(t,500,{ok:!1,error:`Failed to delete path`})}}async function Ze(e,t){if(e.method!==`GET`){J(t,405,{ok:!1,error:`Method not allowed`});return}try{let e=i(),n=[];for(let[t,i]of e){let e=t;try{e=hf(R(V(r,`${t}${Af(t)}`),`utf-8`),t)}catch(e){console.warn(`[pages] Failed to read title for ${t}:`,e)}n.push({docName:t,title:e,size:i.size,modified:i.modified})}n.sort((e,t)=>e.docName.localeCompare(t.docName)),J(t,200,{ok:!0,pages:n})}catch(e){console.error(`[pages]`,e),J(t,500,{ok:!1,error:`Failed to list pages`})}}async function Qe(e,n){if(e.method!==`GET`){J(n,405,{ok:!1,error:`Method not allowed`});return}try{let r=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!r){J(n,400,{ok:!1,error:`Missing docName parameter`});return}if(!Qh(r)){J(n,400,{ok:!1,error:`Invalid docName`});return}if(q(r)){J(n,400,{ok:!1,error:`'${r}' is a reserved document name`});return}J(n,200,{ok:!0,...await Th({hocuspocus:t,fileIndex:i(),docName:r})})}catch(e){if(e instanceof rh){J(n,404,{ok:!1,error:`Page not found`});return}console.error(`[suggest-links]`,e),J(n,500,{ok:!1,error:`Failed to suggest links`})}}async function $e(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}let n;try{n=await Hh(e,10485760)}catch(e){let n=e instanceof Error?e.message:String(e);n===`Payload too large`?J(t,413,{ok:!1,error:`Payload too large`}):n===`No file received`?J(t,400,{ok:!1,error:`No file received`}):J(t,400,{ok:!1,error:`Failed to parse upload: ${n}`});return}let{filename:i,buffer:a,parentDocName:o}=n;if(!o){J(t,400,{ok:!1,error:`parentDocName is required`});return}if(o.includes(`\0`)||o.includes(`..`)||o.startsWith(`/`)){J(t,400,{ok:!1,error:`path-escape`});return}let s=V(r),c=V(s,xe(o));if(!Np(c,s)){J(t,400,{ok:!1,error:`path-escape`});return}try{let e=fe(c),n;try{n=fe(s)}catch{n=s}if(!Np(e,n)){J(t,400,{ok:!1,error:`path-escape`});return}}catch(e){if(e.code!==`ENOENT`){J(t,400,{ok:!1,error:`path-escape`});return}}let l=await Jd(a),u=l?.mime,d=l?.ext;if(!u){let e=a.subarray(0,256).toString(`utf-8`).trimStart();(e.startsWith(`<svg`)||e.startsWith(`<?xml`)&&e.includes(`<svg`))&&(u=`image/svg+xml`,d=`svg`)}if(!u||!d||!Rh.has(u)){J(t,400,{ok:!1,error:`Unsupported file type${u?`: ${u}`:``}`});return}let f;f=!i||i===`upload`||zh.test(i)?`pasted-${new Date().toISOString().replace(/[-:T]/g,``).slice(0,14).replace(/(\d{8})(\d{6})/,`$1-$2`)}.${d}`:Bh(i),le(c,{recursive:!0});try{let e=Vh(c,f,a),n=B(r,V(c,e));console.log(`[upload] ok ${n} ${a.length}`),J(t,200,{ok:!0,src:e})}catch(e){let n=e instanceof Error?e.message:String(e);console.error(`[upload] error ${f} ${a.length} ${n}`),J(t,500,{ok:!1,error:`Failed to save file`})}}let et=`/api/local-op/clone`,tt=`/api/local-op/open`,nt=600*1e3;async function rt(e,t){if(!Em(e,t,J))return;if(e.method!==`POST`){J(t,405,{ok:!1,error:`Method not allowed`});return}let n,r;try{let i=await Xh(e),a=JSON.parse(i.toString());if(typeof a.url!=`string`||!a.url){J(t,400,{ok:!1,error:`Missing or invalid url`});return}if(typeof a.dir!=`string`||!a.dir){J(t,400,{ok:!1,error:`Missing or invalid dir`});return}n=a.url,r=a.dir}catch{J(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!xm(n)){J(t,400,{ok:!1,error:`URL protocol not allowed`});return}if(!Cm(r)){J(t,400,{ok:!1,error:`dir must be within the user home directory`});return}if(!S.tryAcquire(et)){J(t,429,{ok:!1,error:`A clone operation is already in progress`});return}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let i=Sm(r),[a,...o]=b,s=[...o,`clone`,`--json`,n,i],c=!1,l=!1,u=null,d=``,f=je(a,s,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),p=setTimeout(()=>{c=!0,f.kill(`SIGTERM`)},nt);f.stdout.on(`data`,e=>{d+=e.toString(`utf-8`);let n=d.split(`
73
+ `);d=n.pop()??``;for(let e of n){if(!e.trim())continue;let n=null;try{n=JSON.parse(e)}catch{}if(n&&n.type===`complete`&&typeof n.dir==`string`){u=n.dir;continue}t.writableEnded||t.write(`${e}\n`)}});let m=[];f.stderr.on(`data`,e=>{m.push(e),Ih.debug({msg:e.toString(`utf-8`).trim()},`[local-op/clone] stderr`)}),f.on(`close`,e=>{clearTimeout(p);let i=Buffer.concat(m).toString(`utf-8`).trim();if(l){S.release(et);return}l=!0,(async()=>{try{if(c&&!t.writableEnded)t.write(`${JSON.stringify({type:`error`,message:`Clone timed out after 10 minutes`})}\n`);else if(e!==0&&!t.writableEnded){i&&Ih.warn({code:e,stderr:i,url:n,dir:r},`[local-op/clone] clone failed`);let a=i?` — ${i}`:``;t.write(`${JSON.stringify({type:`error`,message:`Clone process exited with code ${e}${a}`})}\n`)}else if(e===0&&u&&!t.writableEnded){let e=await it(u);t.writableEnded||(`port`in e?t.write(`${JSON.stringify({type:`complete`,port:e.port})}\n`):t.write(`${JSON.stringify({type:`error`,message:e.error})}\n`))}}finally{t.writableEnded||t.end(),S.release(et)}})()}),f.on(`error`,e=>{clearTimeout(p),l||(l=!0,t.writableEnded||(t.write(`${JSON.stringify({type:`error`,message:e.message})}\n`),t.end())),S.release(et)})}async function it(e){let t=V(Sm(e)),n=V(t,`.open-knowledge`),r=Sf(n);if(r&&r.port>0)return{port:r.port};let i=re(n),[a,...o]=b,s=i&&i.port>0?`ui`:`start`,c=je(a,[...o,s],{cwd:t,detached:!0,stdio:[`ignore`,`ignore`,`pipe`],env:{...process.env}}),l=[];c.stderr?.on(`data`,e=>{l.push(e),Ih.warn({cwd:t,cliCmd:s,msg:e.toString(`utf-8`).trim()},`[local-op/open] child stderr`)});let u=null;c.on(`exit`,e=>{u=e??-1}),c.unref();let d=Date.now()+45e3;for(;Date.now()<d;){await new Promise(e=>setTimeout(e,500));let e=Sf(n);if(e&&e.port>0)return{port:e.port};if(u!==null){let e=Buffer.concat(l).toString(`utf-8`).trim();return{error:`\`ok ${s}\` exited (code ${u})${e?` — ${e}`:``}`}}}let f=Buffer.concat(l).toString(`utf-8`).trim();return{error:`UI did not start within the expected time${f?` — ${f}`:``}`}}async function at(e,t){if(!Em(e,t,J))return;if(e.method!==`POST`){J(t,405,{ok:!1,error:`Method not allowed`});return}let n;try{let r=await Xh(e),i=JSON.parse(r.toString());if(typeof i.dir!=`string`||!i.dir){J(t,400,{ok:!1,error:`Missing or invalid dir`});return}n=i.dir}catch{J(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!Cm(n)){J(t,400,{ok:!1,error:`dir must be within the user home directory`});return}if(!S.tryAcquire(tt)){J(t,429,{ok:!1,error:`A server-open operation is already in progress`});return}try{let e=await it(n);`port`in e?J(t,200,{port:e.port}):J(t,504,{ok:!1,error:e.error})}finally{S.release(tt)}}let ot=`/api/local-op/auth/login`,st=`/api/local-op/auth/status`,ct=`/api/local-op/auth/repos`,lt=`/api/local-op/auth/signout`,ut=`/api/local-op/auth/pat`;async function dt(e,t){if(!Em(e,t,J))return;if(e.method!==`POST`){J(t,405,{ok:!1,error:`Method not allowed`});return}let n=`github.com`;try{let t=await Xh(e),r=JSON.parse(t.toString());typeof r.host==`string`&&r.host&&(n=r.host)}catch{J(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!S.tryAcquire(ot)){J(t,429,{ok:!1,error:`An auth login operation is already in progress`});return}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let[r,...i]=b,a=[...i,`auth`,`login`,`--json`,`--host`,n],o=!1,s=!1,c=``,l=je(r,a,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),u=setTimeout(()=>{l.kill(`SIGTERM`)},nt),d=()=>{l.killed||l.kill(`SIGTERM`)};t.on(`close`,d),l.stdout.on(`data`,e=>{t.writableEnded||t.write(e),c+=e.toString(`utf-8`);let n=c.split(`
74
+ `);c=n.pop()??``;for(let e of n)if(e.trim())try{let t=JSON.parse(e);(t.type===`complete`||t.type===`error`)&&(s=!0)}catch{}}),l.stderr.on(`data`,e=>{Ih.debug({msg:e.toString(`utf-8`).trim()},`[local-op/auth/login] stderr`)}),l.on(`close`,e=>{clearTimeout(u),t.off(`close`,d),o||(o=!0,t.writableEnded||(e===0&&!s?t.write(`${JSON.stringify({type:`complete`,host:n,login:``})}\n`):e!==0&&t.write(`${JSON.stringify({type:`error`,message:`auth login exited with code ${e}`})}\n`)),t.end()),S.release(ot)}),l.on(`error`,e=>{clearTimeout(u),t.off(`close`,d),o||(o=!0,t.writableEnded||(t.write(`${JSON.stringify({type:`error`,message:e.message})}\n`),t.end())),S.release(ot)})}async function ft(e,t){if(!Em(e,t,J))return;if(e.method!==`POST`){J(t,405,{ok:!1,error:`Method not allowed`});return}let n=`github.com`;try{let t=(await Xh(e)).toString().trim();if(t.length>0){let e=JSON.parse(t);typeof e.host==`string`&&e.host&&(n=e.host)}}catch{J(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!S.tryAcquire(st)){J(t,429,{ok:!1,error:`An auth status operation is already in progress`});return}try{let[e,...r]=b,i=[...r,`auth`,`status`,`--json`,`--host`,n],a=(await new Promise((t,n)=>{let r=je(e,i,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),a=setTimeout(()=>{r.kill(`SIGTERM`)},3e4),o=[];r.stdout.on(`data`,e=>o.push(e)),r.on(`close`,()=>{clearTimeout(a),t(Buffer.concat(o).toString(`utf-8`))}),r.on(`error`,e=>{clearTimeout(a),n(e)})})).split(`
75
+ `).map(e=>e.trim()).filter(Boolean),o=null;for(let e=a.length-1;e>=0;e--)try{o=JSON.parse(a[e]);break}catch{}o===null?J(t,200,{authenticated:!1}):J(t,200,o)}catch(e){J(t,500,{ok:!1,error:e instanceof Error?e.message:`auth status failed`})}finally{S.release(st)}}async function pt(e,t){if(!Em(e,t,J))return;if(e.method!==`POST`){J(t,405,{ok:!1,error:`Method not allowed`});return}let n=`github.com`;try{let t=(await Xh(e)).toString().trim();if(t.length>0){let e=JSON.parse(t);typeof e.host==`string`&&e.host&&(n=e.host)}}catch{J(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!S.tryAcquire(ct)){J(t,429,{ok:!1,error:`An auth repos operation is already in progress`});return}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let[r,...i]=b,a=[...i,`auth`,`repos`,`--json`,`--host`,n],o=!1,s=je(r,a,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),c=setTimeout(()=>{s.kill(`SIGTERM`)},nt);s.stdout.on(`data`,e=>{t.writableEnded||t.write(e)}),s.stderr.on(`data`,e=>{Ih.debug({msg:e.toString(`utf-8`).trim()},`[local-op/auth/repos] stderr`)}),s.on(`close`,e=>{clearTimeout(c),o||(o=!0,e!==0&&!t.writableEnded&&t.write(`${JSON.stringify({type:`error`,message:`auth repos exited with code ${e}`})}\n`),t.end()),S.release(ct)}),s.on(`error`,e=>{clearTimeout(c),o||(o=!0,t.writableEnded||(t.write(`${JSON.stringify({type:`error`,message:e.message})}\n`),t.end())),S.release(ct)})}async function mt(e,t){if(!Em(e,t,J))return;if(e.method!==`POST`){J(t,405,{ok:!1,error:`Method not allowed`});return}let n=`github.com`;try{let t=await Xh(e),r=JSON.parse(t.toString());typeof r.host==`string`&&r.host&&(n=r.host)}catch{J(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!S.tryAcquire(lt)){J(t,429,{ok:!1,error:`An auth signout operation is already in progress`});return}try{let[e,...r]=b,i=[...r,`auth`,`signout`,`--host`,n];await new Promise((t,n)=>{let r=je(e,i,{stdio:`ignore`,env:{...process.env}}),a=setTimeout(()=>{r.kill(`SIGTERM`)},3e4);r.on(`close`,()=>{clearTimeout(a),t()}),r.on(`error`,e=>{clearTimeout(a),n(e)})}),J(t,200,{ok:!0})}catch(e){J(t,500,{ok:!1,error:e instanceof Error?e.message:`auth signout failed`})}finally{S.release(lt)}}async function ht(e,t){if(!Em(e,t,J))return;if(e.method!==`POST`){J(t,405,{ok:!1,error:`Method not allowed`});return}let n=`github.com`,r;try{let i=await Xh(e),a=JSON.parse(i.toString());if(typeof a.pat!=`string`||!a.pat){J(t,400,{ok:!1,error:`Missing or invalid pat`});return}r=a.pat,typeof a.host==`string`&&a.host&&(n=a.host)}catch{J(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!S.tryAcquire(ut)){J(t,429,{ok:!1,error:`An auth pat operation is already in progress`});return}try{let[e,...i]=b,a=[...i,`auth`,`pat`,`--json`,`--host`,n],o=(await new Promise((t,n)=>{let i=je(e,a,{stdio:[`pipe`,`pipe`,`pipe`],env:{...process.env}}),o=setTimeout(()=>{i.kill(`SIGTERM`)},3e4);i.stdin.write(`${r}\n`),i.stdin.end();let s=[];i.stdout.on(`data`,e=>s.push(e)),i.on(`close`,e=>{clearTimeout(o),e===0?t(Buffer.concat(s).toString(`utf-8`)):n(Error(`auth pat exited with code ${e}`))}),i.on(`error`,e=>{clearTimeout(o),n(e)})})).split(`
76
+ `).map(e=>e.trim()).filter(Boolean),s=null;for(let e=o.length-1;e>=0;e--)try{s=JSON.parse(o[e]);break}catch{}s===null?J(t,200,{ok:!0}):J(t,200,s)}catch(e){J(t,500,{ok:!1,error:e instanceof Error?e.message:`auth pat failed`})}finally{S.release(ut)}}async function gt(e,t){if(Em(e,t,J)){if(e.method!==`GET`){J(t,405,{ok:!1,error:`Method not allowed`});return}if(!x){J(t,400,{ok:!1,error:`No project directory configured`});return}try{J(t,200,{ok:!0,identity:await _m(x)})}catch(e){J(t,500,{ok:!1,error:e instanceof Error?e.message:`identity resolution failed`})}}}let _t=`/api/local-op/auth/set-identity`;async function vt(e,t){if(!Em(e,t,J))return;if(e.method!==`POST`){J(t,405,{ok:!1,error:`Method not allowed`});return}let n,r;try{let i=await Xh(e),a=JSON.parse(i.toString());if(typeof a.name!=`string`||!a.name.trim()){J(t,400,{ok:!1,error:`Missing or invalid name`});return}if(typeof a.email!=`string`||!a.email.trim()){J(t,400,{ok:!1,error:`Missing or invalid email`});return}n=a.name.trim(),r=a.email.trim()}catch{J(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!x){J(t,400,{ok:!1,error:`No project directory configured`});return}if(!S.tryAcquire(_t)){J(t,429,{ok:!1,error:`A set-identity operation is already in progress`});return}try{vm(x,n,r),y?.()?.refreshIdentity().catch(()=>{}),J(t,200,{ok:!0})}catch(e){J(t,500,{ok:!1,error:e instanceof Error?e.message:`set-identity failed`})}finally{S.release(_t)}}async function yt(e,t){if(!Em(e,t,J))return;if(e.method!==`GET`){J(t,405,{ok:!1,error:`Method not allowed`});return}let n=y?.();if(!n){J(t,200,{state:`dormant`,lastSyncUtc:null,lastFetchUtc:null,lastPushedSha:null,ahead:0,behind:0,consecutiveFailures:0,conflictCount:0,hasRemote:!1,syncEnabled:!1,identityUnresolved:!1});return}J(t,200,n.getStatus())}async function bt(e,t){if(!Em(e,t,J))return;if(e.method!==`POST`){J(t,405,{ok:!1,error:`Method not allowed`});return}let n=y?.();if(!n){J(t,503,{ok:!1,error:`Sync engine not active`});return}let r=`sync`;try{let t=await Xh(e);if(t.length>0){let e=JSON.parse(t.toString());(e.op===`push`||e.op===`pull`||e.op===`sync`)&&(r=e.op)}}catch{}J(t,202,{ok:!0,op:r}),n.trigger(r)}async function H(e,t){if(!Em(e,t,J))return;if(e.method!==`POST`){J(t,405,{ok:!1,error:`Method not allowed`});return}let n=y?.();if(!n){J(t,503,{ok:!1,error:`Sync engine not active`});return}let r;try{let n=await Xh(e),i=JSON.parse(n.toString());if(typeof i.enabled!=`boolean`){J(t,400,{ok:!1,error:`enabled must be a boolean`});return}r=i.enabled}catch{J(t,400,{ok:!1,error:`Invalid JSON body`});return}await n.setEnabled(r),J(t,200,{ok:!0,status:n.getStatus()})}async function xt(e,t){if(!Em(e,t,J))return;if(e.method!==`GET`){J(t,405,{ok:!1,error:`Method not allowed`});return}let n=y?.();J(t,200,{conflicts:n?n.getConflicts():[]})}async function St(e,t){if(!Em(e,t,J))return;if(e.method!==`POST`){J(t,405,{ok:!1,error:`Method not allowed`});return}let n=y?.();if(!n){J(t,503,{ok:!1,error:`Sync engine not active`});return}let r;try{let t=await Xh(e);r=JSON.parse(t.toString())}catch{J(t,400,{ok:!1,error:`Invalid JSON body`});return}let{file:i,strategy:a,content:o}=r;if(!i||typeof i!=`string`){J(t,400,{ok:!1,error:`Missing required field: file`});return}if(a!==`mine`&&a!==`theirs`&&a!==`content`){J(t,400,{ok:!1,error:`Invalid strategy: must be 'mine', 'theirs', or 'content'`});return}try{await n.resolveConflict(i,a,o),J(t,200,{ok:!0})}catch(e){J(t,500,{ok:!1,error:e instanceof Error?e.message:String(e)})}}async function Ct(e,t){if(!Em(e,t,J))return;if(e.method!==`GET`){J(t,405,{ok:!1,error:`Method not allowed`});return}if(!x){J(t,503,{ok:!1,error:`Project repo not configured`});return}let n=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`file`);if(!n){J(t,400,{ok:!1,error:`Missing required query param: file`});return}if(n.includes(`..`)||n.startsWith(`/`)){J(t,400,{ok:!1,error:`Invalid file path`});return}let r=Ne({baseDir:x,timeout:{block:15e3}});async function i(e){try{return await r.raw([`show`,`:${e}:${n}`])}catch{return``}}try{let[e,r,a]=await Promise.all([i(1),i(2),i(3)]);J(t,200,{ok:!0,file:n,base:e,ours:r,theirs:a})}catch(e){J(t,500,{ok:!1,error:e instanceof Error?e.message:String(e)})}}async function wt(e,t){if(!Em(e,t,J))return;if(e.method!==`POST`){J(t,405,{ok:!1,error:`Method not allowed`});return}let n=y?.();if(!n){J(t,503,{ok:!1,error:`Sync engine not active`});return}try{await n.abortMerge(),J(t,200,{ok:!0})}catch(e){J(t,500,{ok:!1,error:e instanceof Error?e.message:String(e)})}}let Tt={"/api/document":ye,"/api/documents":be,"/api/backlinks":Se,"/api/backlink-counts":Ce,"/api/forward-links":we,"/api/link-graph":Ee,"/api/dead-links":ke,"/api/orphans":De,"/api/hubs":Oe,"/api/pages":Ze,"/api/suggest-links":Qe,"/api/page-headings":qe,"/api/create-page":Ke,"/api/rename":Je,"/api/rename-path":Ye,"/api/delete-path":Xe,"/api/upload-image":$e,"/api/agent-write":_e,"/api/agent-write-md":ve,"/api/agent-patch":Ae,"/api/save-version":Fe,"/api/history":Ie,"/api/diff":Re,"/api/rollback":ze,"/api/metrics/reconciliation":Be,"/api/metrics/parse-health":Ve,"/api/rescue":We,"/api/workspace":He,"/api/sync/status":yt,"/api/sync/trigger":bt,"/api/sync/set-enabled":H,"/api/sync/conflicts":xt,"/api/sync/conflict-content":Ct,"/api/sync/resolve-conflict":St,"/api/sync/abort-merge":wt,"/api/local-op/clone":rt,"/api/local-op/open":at,"/api/local-op/auth/login":dt,"/api/local-op/auth/status":ft,"/api/local-op/auth/repos":pt,"/api/local-op/auth/signout":mt,"/api/local-op/auth/pat":ht,"/api/local-op/auth/identity":gt,"/api/local-op/auth/set-identity":vt};return o&&(Tt[`/api/test-reset`]=Me,Tt[`/api/test-rescan-backlinks`]=Pe),{priority:100,async onRequest({request:e,response:t}){let n=e.url?.split(`?`)[0];if(!n)return;if(n.startsWith(`/api/`)&&(typeof t.setHeader==`function`&&(t.setHeader(`Access-Control-Allow-Origin`,`*`),t.setHeader(`Access-Control-Allow-Methods`,`GET, POST, PUT, DELETE, OPTIONS`),t.setHeader(`Access-Control-Allow-Headers`,`Content-Type, Authorization`)),e.method===`OPTIONS`)){t.writeHead(204),t.end();return}let r=Tt[n];if(r){await r(e,t);return}if(n.startsWith(`/api/rescue/`)){let r=decodeURIComponent(n.slice(12));r&&await Ge(e,t,r);return}if(n.startsWith(`/api/history/`)){let r=decodeURIComponent(n.slice(13));r&&await Le(e,t,r);return}}}}function eg(e){let t=e.scheduler??T,n=e.warnBeforeMs??3e5,r=0,i=null,a=null,o=!1,s=!1;function c(){i!==null&&(t.clearTimeout(i),i=null),a!==null&&(t.clearTimeout(a),a=null)}function l(){c(),!(s||o)&&r===0&&(n>0&&n<e.thresholdMs&&(a=t.setTimeout(()=>{a=null,r===0&&!o&&e.log?.warn({msUntilShutdown:n,webSocketClientCount:0},`idle shutdown pending: no WebSocket clients`)},e.thresholdMs-n)),i=t.setTimeout(()=>{if(i=null,!(s||o)&&r===0){o=!0,e.log?.info({webSocketClientCount:0},`idle shutdown firing`);try{let t=e.onShutdown();t&&typeof t.then==`function`&&t.catch(t=>{e.log?.error({err:t},`idle shutdown handler rejected`)})}catch(t){e.log?.error({err:t},`idle shutdown handler threw`)}}},e.thresholdMs))}let u=(e,t)=>{e.url?.startsWith(`/collab`)&&(r++,c(),t.once(`close`,()=>{r--,r<0&&(r=0),r===0&&l()}))};return e.httpServer.on(`upgrade`,u),l(),{detach:()=>{s||(s=!0,e.httpServer.off(`upgrade`,u),c())}}}const tg=Math.floor,ng=(e,t)=>e<t?e:t,rg=(e,t)=>e>t?e:t;Number.isNaN,Number.isInteger,Number.isNaN,Number.parseInt;const ig=String.fromCharCode;String.fromCodePoint,ig(65535);const ag=e=>{let t=unescape(encodeURIComponent(e)),n=t.length,r=new Uint8Array(n);for(let e=0;e<n;e++)r[e]=t.codePointAt(e);return r},og=typeof TextEncoder<`u`?new TextEncoder:null,sg=og?e=>og.encode(e):ag;let cg=typeof TextDecoder>`u`?null:new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0});cg&&cg.decode(new Uint8Array).length===1&&(cg=null);const lg=(e,t)=>{let n=e.cbuf.length;e.cpos===n&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(n*2),e.cpos=0),e.cbuf[e.cpos++]=t},ug=(e,t)=>{for(;t>127;)lg(e,128|127&t),t=tg(t/128);lg(e,127&t)},dg=new Uint8Array(3e4),fg=dg.length/3,pg=og&&og.encodeInto?(e,t)=>{if(t.length<fg){let n=og.encodeInto(t,dg).written||0;ug(e,n);for(let t=0;t<n;t++)lg(e,dg[t])}else hg(e,sg(t))}:(e,t)=>{let n=unescape(encodeURIComponent(t)),r=n.length;ug(e,r);for(let t=0;t<r;t++)lg(e,n.codePointAt(t))},mg=(e,t)=>{let n=e.cbuf.length,r=e.cpos,i=ng(n-r,t.length),a=t.length-i;e.cbuf.set(t.subarray(0,i),r),e.cpos+=i,a>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(rg(n*2,a)),e.cbuf.set(t.subarray(i)),e.cpos=a)},hg=(e,t)=>{ug(e,t.byteLength),mg(e,t)},gg=e=>Error(e);gg(`Unexpected end of array`),gg(`Integer out of Range`);let _g=function(e){return e[e.Token=0]=`Token`,e[e.PermissionDenied=1]=`PermissionDenied`,e[e.Authenticated=2]=`Authenticated`,e}({});const vg=(e,t)=>{ug(e,_g.PermissionDenied),pg(e,t)},yg=(e,t)=>{ug(e,_g.Authenticated),pg(e,t)},bg=e=>{ug(e,_g.Token)},xg={code:4205,reason:`Reset Connection`},Sg={code:4401,reason:`Unauthorized`},Cg={code:4403,reason:`Forbidden`},wg={code:4408,reason:`Connection Timeout`},Tg=e=>Array.from(e.entries()).map(([e,t])=>({clientId:e,...t}));var Eg=class extends Error{constructor(e){super(e??`Further hooks skipped`),this.name=`SkipFurtherHooksError`}};let Dg=function(e){return e[e.Connecting=0]=`Connecting`,e[e.Open=1]=`Open`,e[e.Closing=2]=`Closing`,e[e.Closed=3]=`Closed`,e}({});const Og=Error(`request for lock canceled`);var kg=function(e,t,n,r){function i(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){e.done?n(e.value):i(e.value).then(o,s)}c((r=r.apply(e,t||[])).next())})},Ag=class{constructor(e,t=Og){this._value=e,this._cancelError=t,this._queue=[],this._weightedWaiters=[]}acquire(e=1,t=0){if(e<=0)throw Error(`invalid weight ${e}: must be positive`);return new Promise((n,r)=>{let i={resolve:n,reject:r,weight:e,priority:t},a=Mg(this._queue,e=>t<=e.priority);a===-1&&e<=this._value?this._dispatchItem(i):this._queue.splice(a+1,0,i)})}runExclusive(e){return kg(this,arguments,void 0,function*(e,t=1,n=0){let[r,i]=yield this.acquire(t,n);try{return yield e(r)}finally{i()}})}waitForUnlock(e=1,t=0){if(e<=0)throw Error(`invalid weight ${e}: must be positive`);return this._couldLockImmediately(e,t)?Promise.resolve():new Promise(n=>{this._weightedWaiters[e-1]||(this._weightedWaiters[e-1]=[]),jg(this._weightedWaiters[e-1],{resolve:n,priority:t})})}isLocked(){return this._value<=0}getValue(){return this._value}setValue(e){this._value=e,this._dispatchQueue()}release(e=1){if(e<=0)throw Error(`invalid weight ${e}: must be positive`);this._value+=e,this._dispatchQueue()}cancel(){this._queue.forEach(e=>e.reject(this._cancelError)),this._queue=[]}_dispatchQueue(){for(this._drainUnlockWaiters();this._queue.length>0&&this._queue[0].weight<=this._value;)this._dispatchItem(this._queue.shift()),this._drainUnlockWaiters()}_dispatchItem(e){let t=this._value;this._value-=e.weight,e.resolve([t,this._newReleaser(e.weight)])}_newReleaser(e){let t=!1;return()=>{t||(t=!0,this.release(e))}}_drainUnlockWaiters(){if(this._queue.length===0)for(let e=this._value;e>0;e--){let t=this._weightedWaiters[e-1];t&&(t.forEach(e=>e.resolve()),this._weightedWaiters[e-1]=[])}else{let e=this._queue[0].priority;for(let t=this._value;t>0;t--){let n=this._weightedWaiters[t-1];if(!n)continue;let r=n.findIndex(t=>t.priority<=e);(r===-1?n:n.splice(0,r)).forEach((e=>e.resolve()))}}}_couldLockImmediately(e,t){return(this._queue.length===0||this._queue[0].priority<t)&&e<=this._value}};function jg(e,t){let n=Mg(e,e=>t.priority<=e.priority);e.splice(n+1,0,t)}function Mg(e,t){for(let n=e.length-1;n>=0;n--)if(t(e[n]))return n;return-1}var Ng=function(e,t,n,r){function i(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){e.done?n(e.value):i(e.value).then(o,s)}c((r=r.apply(e,t||[])).next())})},Pg=class{constructor(e){this._semaphore=new Ag(1,e)}acquire(){return Ng(this,arguments,void 0,function*(e=0){let[,t]=yield this._semaphore.acquire(1,e);return t})}runExclusive(e,t=0){return this._semaphore.runExclusive(()=>e(),1,t)}isLocked(){return this._semaphore.isLocked()}waitForUnlock(e=0){return this._semaphore.waitForUnlock(1,e)}release(){this._semaphore.isLocked()&&this._semaphore.release()}cancel(){return this._semaphore.cancel()}};let Fg,Ig,Lg,Rg,zg=!0;typeof process<`u`&&({FORCE_COLOR:Fg,NODE_DISABLE_COLORS:Ig,NO_COLOR:Lg,TERM:Rg}=process.env||{},zg=process.stdout&&process.stdout.isTTY);const Y={enabled:!Ig&&Lg==null&&Rg!==`dumb`&&(Fg!=null&&Fg!==`0`||zg),reset:X(0,0),bold:X(1,22),dim:X(2,22),italic:X(3,23),underline:X(4,24),inverse:X(7,27),hidden:X(8,28),strikethrough:X(9,29),black:X(30,39),red:X(31,39),green:X(32,39),yellow:X(33,39),blue:X(34,39),magenta:X(35,39),cyan:X(36,39),white:X(37,39),gray:X(90,39),grey:X(90,39),bgBlack:X(40,49),bgRed:X(41,49),bgGreen:X(42,49),bgYellow:X(43,49),bgBlue:X(44,49),bgMagenta:X(45,49),bgCyan:X(46,49),bgWhite:X(47,49)};function Bg(e,t){let n=0,r,i=``,a=``;for(;n<e.length;n++)r=e[n],i+=r.open,a+=r.close,~t.indexOf(r.close)&&(t=t.replace(r.rgx,r.close+r.open));return i+t+a}function Vg(e,t){let n={has:e,keys:t};return n.reset=Y.reset.bind(n),n.bold=Y.bold.bind(n),n.dim=Y.dim.bind(n),n.italic=Y.italic.bind(n),n.underline=Y.underline.bind(n),n.inverse=Y.inverse.bind(n),n.hidden=Y.hidden.bind(n),n.strikethrough=Y.strikethrough.bind(n),n.black=Y.black.bind(n),n.red=Y.red.bind(n),n.green=Y.green.bind(n),n.yellow=Y.yellow.bind(n),n.blue=Y.blue.bind(n),n.magenta=Y.magenta.bind(n),n.cyan=Y.cyan.bind(n),n.white=Y.white.bind(n),n.gray=Y.gray.bind(n),n.grey=Y.grey.bind(n),n.bgBlack=Y.bgBlack.bind(n),n.bgRed=Y.bgRed.bind(n),n.bgGreen=Y.bgGreen.bind(n),n.bgYellow=Y.bgYellow.bind(n),n.bgBlue=Y.bgBlue.bind(n),n.bgMagenta=Y.bgMagenta.bind(n),n.bgCyan=Y.bgCyan.bind(n),n.bgWhite=Y.bgWhite.bind(n),n}function X(e,t){let n={open:`\x1b[${e}m`,close:`\x1b[${t}m`,rgx:RegExp(`\\x1b\\[${t}m`,`g`)};return function(t){return this!==void 0&&this.has!==void 0?(~this.has.indexOf(e)||(this.has.push(e),this.keys.push(n)),t===void 0?this:Y.enabled?Bg(this.keys,t+``):t+``):t===void 0?Vg([e],[n]):Y.enabled?Bg([n],t+``):t+``}}const Hg=Math.floor,Ug=(e,t)=>e<t?e:t,Wg=(e,t)=>e>t?e:t;Number.isNaN;const Gg=2**53-1;Number.isInteger,Number.isNaN,Number.parseInt;const Kg=()=>new Set,qg=Array.from;Array.isArray;const Jg=String.fromCharCode;String.fromCodePoint,Jg(65535);const Yg=e=>{let t=unescape(encodeURIComponent(e)),n=t.length,r=new Uint8Array(n);for(let e=0;e<n;e++)r[e]=t.codePointAt(e);return r},Xg=typeof TextEncoder<`u`?new TextEncoder:null,Zg=Xg?e=>Xg.encode(e):Yg;let Qg=typeof TextDecoder>`u`?null:new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0});Qg&&Qg.decode(new Uint8Array).length===1&&(Qg=null);const $g=e=>Error(e);var e_=class{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}};const t_=()=>new e_,n_=e=>{let t=e.cpos;for(let n=0;n<e.bufs.length;n++)t+=e.bufs[n].length;return t},r_=e=>{let t=new Uint8Array(n_(e)),n=0;for(let r=0;r<e.bufs.length;r++){let i=e.bufs[r];t.set(i,n),n+=i.length}return t.set(new Uint8Array(e.cbuf.buffer,0,e.cpos),n),t},i_=(e,t)=>{let n=e.cbuf.length;e.cpos===n&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(n*2),e.cpos=0),e.cbuf[e.cpos++]=t},Z=(e,t)=>{for(;t>127;)i_(e,128|127&t),t=Hg(t/128);i_(e,127&t)},a_=new Uint8Array(3e4),o_=a_.length/3,s_=Xg&&Xg.encodeInto?(e,t)=>{if(t.length<o_){let n=Xg.encodeInto(t,a_).written||0;Z(e,n);for(let t=0;t<n;t++)i_(e,a_[t])}else l_(e,Zg(t))}:(e,t)=>{let n=unescape(encodeURIComponent(t)),r=n.length;Z(e,r);for(let t=0;t<r;t++)i_(e,n.codePointAt(t))},c_=(e,t)=>{let n=e.cbuf.length,r=e.cpos,i=Ug(n-r,t.length),a=t.length-i;e.cbuf.set(t.subarray(0,i),r),e.cpos+=i,a>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(Wg(n*2,a)),e.cbuf.set(t.subarray(i)),e.cpos=a)},l_=(e,t)=>{Z(e,t.byteLength),c_(e,t)},u_=$g(`Unexpected end of array`),d_=$g(`Integer out of Range`);var f_=class{constructor(e){this.arr=e,this.pos=0}};const p_=e=>new f_(e),m_=e=>e.pos!==e.arr.length,h_=(e,t)=>{let n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n},g_=e=>h_(e,v_(e)),__=e=>e.arr[e.pos++],v_=e=>{let t=0,n=1,r=e.arr.length;for(;e.pos<r;){let r=e.arr[e.pos++];if(t+=(r&127)*n,n*=128,r<128)return t;if(t>Gg)throw d_}throw u_},y_=Qg?e=>Qg.decode(g_(e)):e=>{let t=v_(e);if(t===0)return``;{let n=String.fromCodePoint(__(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(__(e));else for(;t>0;){let r=t<1e4?t:1e4,i=e.arr.subarray(e.pos,e.pos+r);e.pos+=r,n+=String.fromCodePoint.apply(null,i),t-=r}return decodeURIComponent(escape(n))}};var b_=class{constructor(e){e instanceof Uint8Array||(e=new Uint8Array(e)),this.decoder=p_(e)}get encoder(){return this.encoderInternal||=t_(),this.encoderInternal}readVarUint8Array(){return g_(this.decoder)}peekVarUint8Array(){let{pos:e}=this.decoder,t=g_(this.decoder);return this.decoder.pos=e,t}readVarUint(){return v_(this.decoder)}readVarString(){return y_(this.decoder)}toUint8Array(){return r_(this.encoder)}writeVarUint(e){Z(this.encoder,e)}writeVarString(e){s_(this.encoder,e)}get length(){return n_(this.encoder)}};const x_=Date.now,S_=()=>new Map,C_=(e,t,n)=>{let r=e.get(t);return r===void 0&&e.set(t,r=n()),r};var w_=class{constructor(){this._observers=S_()}on(e,t){C_(this._observers,e,Kg).add(t)}once(e,t){let n=(...r)=>{this.off(e,n),t(...r)};this.on(e,n)}off(e,t){let n=this._observers.get(e);n!==void 0&&(n.delete(t),n.size===0&&this._observers.delete(e))}emit(e,t){return qg((this._observers.get(e)||S_()).values()).forEach(e=>e(...t))}destroy(){this._observers=S_()}};const T_=Symbol(`Equality`),E_=Object.keys,D_=e=>E_(e).length,O_=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),k_=(e,t)=>{if(e===t)return!0;if(e==null||t==null||e.constructor!==t.constructor&&(e.constructor||Object)!==(t.constructor||Object))return!1;if(e[T_]!=null)return e[T_](t);switch(e.constructor){case ArrayBuffer:e=new Uint8Array(e),t=new Uint8Array(t);case Uint8Array:if(e.byteLength!==t.byteLength)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;break;case Set:if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;break;case Map:if(e.size!==t.size)return!1;for(let n of e.keys())if(!t.has(n)||!k_(e.get(n),t.get(n)))return!1;break;case void 0:case Object:if(D_(e)!==D_(t))return!1;for(let n in e)if(!O_(e,n)||!k_(e[n],t[n]))return!1;break;case Array:if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!k_(e[n],t[n]))return!1;break;default:return!1}return!0},A_=3e4;var j_=class extends w_{constructor(e){super(),this.doc=e,this.clientID=e.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{let e=x_();this.getLocalState()!==null&&A_/2<=e-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());let t=[];this.meta.forEach((n,r)=>{r!==this.clientID&&A_<=e-n.lastUpdated&&this.states.has(r)&&t.push(r)}),t.length>0&&M_(this,t,`timeout`)},Hg(A_/10)),e.on(`destroy`,()=>{this.destroy()}),this.setLocalState({})}destroy(){this.emit(`destroy`,[this]),this.setLocalState(null),super.destroy(),clearInterval(this._checkInterval)}getLocalState(){return this.states.get(this.clientID)||null}setLocalState(e){let t=this.clientID,n=this.meta.get(t),r=n===void 0?0:n.clock+1,i=this.states.get(t);e===null?this.states.delete(t):this.states.set(t,e),this.meta.set(t,{clock:r,lastUpdated:x_()});let a=[],o=[],s=[],c=[];e===null?c.push(t):i==null?e!=null&&a.push(t):(o.push(t),k_(i,e)||s.push(t)),(a.length>0||s.length>0||c.length>0)&&this.emit(`change`,[{added:a,updated:s,removed:c},`local`]),this.emit(`update`,[{added:a,updated:o,removed:c},`local`])}setLocalStateField(e,t){let n=this.getLocalState();n!==null&&this.setLocalState({...n,[e]:t})}getStates(){return this.states}};const M_=(e,t,n)=>{let r=[];for(let n=0;n<t.length;n++){let i=t[n];if(e.states.has(i)){if(e.states.delete(i),i===e.clientID){let t=e.meta.get(i);e.meta.set(i,{clock:t.clock+1,lastUpdated:x_()})}r.push(i)}}r.length>0&&(e.emit(`change`,[{added:[],updated:[],removed:r},n]),e.emit(`update`,[{added:[],updated:[],removed:r},n]))},N_=(e,t,n=e.states)=>{let r=t.length,i=t_();Z(i,r);for(let a=0;a<r;a++){let r=t[a],o=n.get(r)||null,s=e.meta.get(r).clock;Z(i,r),Z(i,s),s_(i,JSON.stringify(o))}return r_(i)},P_=(e,t,n)=>{let r=p_(t),i=x_(),a=[],o=[],s=[],c=[],l=v_(r);for(let t=0;t<l;t++){let t=v_(r),n=v_(r),l=JSON.parse(y_(r)),u=e.meta.get(t),d=e.states.get(t),f=u===void 0?0:u.clock;(f<n||f===n&&l===null&&e.states.has(t))&&(l===null?t===e.clientID&&e.getLocalState()!=null?n++:e.states.delete(t):e.states.set(t,l),e.meta.set(t,{clock:n,lastUpdated:i}),u===void 0&&l!==null?a.push(t):u!==void 0&&l===null?c.push(t):l!==null&&(k_(l,d)||s.push(t),o.push(t)))}(a.length>0||s.length>0||c.length>0)&&e.emit(`change`,[{added:a,updated:s,removed:c},n]),(a.length>0||o.length>0||c.length>0)&&e.emit(`update`,[{added:a,updated:o,removed:c},n])},F_=(e,t)=>{Z(e,0),l_(e,qr(t))},I_=(e,t,n)=>{Z(e,1),l_(e,Vr(t,n))},L_=(e,t,n)=>I_(t,n,g_(e)),R_=(e,t,n,r)=>{try{Rr(t,g_(e),n)}catch(e){r?.(e),console.error(`Caught error while handling a Yjs update`,e)}},z_=(e,t)=>{Z(e,2),l_(e,t)},B_=R_;function V_(e){return typeof e==`object`&&!!e&&`source`in e&&(e.source===`connection`||e.source===`redis`||e.source===`local`)}function H_(e){if(!V_(e))return!1;switch(e.source){case`connection`:return!1;case`redis`:return!0;case`local`:return e.skipStoreHooks??!1}}let Q=function(e){return e[e.Unknown=-1]=`Unknown`,e[e.Sync=0]=`Sync`,e[e.Awareness=1]=`Awareness`,e[e.Auth=2]=`Auth`,e[e.QueryAwareness=3]=`QueryAwareness`,e[e.SyncReply=4]=`SyncReply`,e[e.Stateless=5]=`Stateless`,e[e.BroadcastStateless=6]=`BroadcastStateless`,e[e.CLOSE=7]=`CLOSE`,e[e.SyncStatus=8]=`SyncStatus`,e[e.Ping=9]=`Ping`,e[e.Pong=10]=`Pong`,e}({});var U_=class{constructor(e){this.encoder=t_(),s_(this.encoder,e)}createSyncMessage(){return this.type=Q.Sync,Z(this.encoder,Q.Sync),this}createSyncReplyMessage(){return this.type=Q.SyncReply,Z(this.encoder,Q.SyncReply),this}createAwarenessUpdateMessage(e,t){this.type=Q.Awareness,this.category=`Update`;let n=N_(e,t||Array.from(e.getStates().keys()));return Z(this.encoder,Q.Awareness),l_(this.encoder,n),this}writeQueryAwareness(){return this.type=Q.QueryAwareness,this.category=`Update`,Z(this.encoder,Q.QueryAwareness),this}writeTokenSyncRequest(){return this.type=Q.Auth,this.category=`TokenSync`,Z(this.encoder,Q.Auth),bg(this.encoder),this}writeAuthenticated(e){return this.type=Q.Auth,this.category=`Authenticated`,Z(this.encoder,Q.Auth),yg(this.encoder,e?`readonly`:`read-write`),this}writePermissionDenied(e){return this.type=Q.Auth,this.category=`PermissionDenied`,Z(this.encoder,Q.Auth),vg(this.encoder,e),this}writeFirstSyncStepFor(e){return this.category=`SyncStep1`,F_(this.encoder,e),this}writeUpdate(e){return this.category=`Update`,z_(this.encoder,e),this}writeStateless(e){return this.category=`Stateless`,Z(this.encoder,Q.Stateless),s_(this.encoder,e),this}writeBroadcastStateless(e){return this.category=`Stateless`,Z(this.encoder,Q.BroadcastStateless),s_(this.encoder,e),this}writeSyncStatus(e){return this.category=`SyncStatus`,Z(this.encoder,Q.SyncStatus),Z(this.encoder,e?1:0),this}writeCloseMessage(e){return this.type=Q.CLOSE,Z(this.encoder,Q.CLOSE),s_(this.encoder,e),this}toUint8Array(){return r_(this.encoder)}},W_=class{constructor(e,t){this.message=e,this.defaultTransactionOrigin=t}async apply(e,t,n){let{message:r}=this,i=r.readVarUint(),a=r.length;switch(i){case Q.Sync:case Q.SyncReply:r.writeVarUint(Q.Sync),await this.readSyncMessage(r,e,t,n,i!==Q.SyncReply),r.length>a+1&&(n?n(r.toUint8Array()):t&&t.send(r.toUint8Array()));break;case Q.Awareness:P_(e.awareness,r.readVarUint8Array(),t??null);break;case Q.QueryAwareness:this.applyQueryAwarenessMessage(e,t,n);break;case Q.Stateless:t?.callbacks.statelessCallback({connection:t,documentName:e.name,document:e,payload:y_(r.decoder)});break;case Q.BroadcastStateless:{let t=r.readVarString();e.getConnections().forEach(e=>{e.sendStateless(t)});break}case Q.CLOSE:t?.close({code:1e3,reason:`provider_initiated`});break;case Q.Auth:if(r.readVarUint()===_g.Token){t?.callbacks.onTokenSyncCallback({token:r.readVarString()});break}console.error(`Received an authentication message on a connection that is already fully authenticated. Probably your provider has been destroyed + recreated really fast.`);break;default:console.error(`Unable to handle message of type ${i}: no handler defined! Are your provider/server versions aligned?`)}}async readSyncMessage(e,t,n,r,i=!0){let a=e.readVarUint(),o=n?.messageAddress??t.name;switch(n&&await n.callbacks.beforeSync(n,{type:a,payload:e.peekVarUint8Array()}),a){case 0:if(L_(e.decoder,e.encoder,t),r&&i)r(new U_(o).createSyncReplyMessage().writeFirstSyncStepFor(t).toUint8Array());else if(n){let e=new U_(o).createSyncMessage().writeFirstSyncStepFor(t);n.send(e.toUint8Array())}break;case 1:if(n?.readOnly){if(ci(ii(t),g_(e.decoder))){let e=new U_(o).writeSyncStatus(!0);n.send(e.toUint8Array())}else{let e=new U_(o).writeSyncStatus(!1);n.send(e.toUint8Array())}break}R_(e.decoder,t,n?{source:`connection`,connection:n}:this.defaultTransactionOrigin??{source:`local`}),n&&n.send(new U_(o).writeSyncStatus(!0).toUint8Array());break;case 2:if(n?.readOnly){n.send(new U_(o).writeSyncStatus(!1).toUint8Array());break}B_(e.decoder,t,n?{source:`connection`,connection:n}:this.defaultTransactionOrigin??{source:`local`}),n&&n.send(new U_(o).writeSyncStatus(!0).toUint8Array());break;default:throw Error(`Received a message with an unknown type: ${a}`)}return a}applyQueryAwarenessMessage(e,t,n){let r=new U_(t?.messageAddress??e.name).createAwarenessUpdateMessage(e.awareness);n&&n(r.toUint8Array())}},G_=class{get messageAddress(){return this.sessionId?`${this.document.name}\0${this.sessionId}`:this.document.name}constructor(e,t,n,r,i,a=!1,o,s){this.callbacks={onClose:[(e,t)=>{}],beforeHandleMessage:(e,t)=>Promise.resolve(),beforeSync:(e,t)=>Promise.resolve(),statelessCallback:e=>Promise.resolve(),onTokenSyncCallback:e=>Promise.resolve()},this.messageQueue=[],this.processingPromise=Promise.resolve(),this.webSocket=e,this.context=i,this.document=n,this.request=t,this.socketId=r,this.readOnly=a,this.sessionId=o??null,this.providerVersion=s??null,this.document.addConnection(this),this.sendCurrentAwareness()}onClose(e){return this.callbacks.onClose.push(e),this}onStatelessCallback(e){return this.callbacks.statelessCallback=e,this}beforeHandleMessage(e){return this.callbacks.beforeHandleMessage=e,this}beforeSync(e){return this.callbacks.beforeSync=e,this}onTokenSyncCallback(e){return this.callbacks.onTokenSyncCallback=e,this}waitForPendingMessages(){return this.processingPromise}send(e){if(this.webSocket.readyState===Dg.Closing||this.webSocket.readyState===Dg.Closed){this.close();return}try{this.webSocket.send(e)}catch{this.close()}}sendStateless(e){let t=new U_(this.messageAddress).writeStateless(e);this.send(t.toUint8Array())}requestToken(){let e=new U_(this.messageAddress).writeTokenSyncRequest();this.send(e.toUint8Array())}close(e){if(this.document.hasConnection(this)){this.document.removeConnection(this),this.callbacks.onClose.forEach(t=>t(this.document,e));let t=new U_(this.messageAddress);t.writeCloseMessage(e?.reason??`Server closed the connection`),this.send(t.toUint8Array())}}sendCurrentAwareness(){if(!this.document.hasAwarenessStates())return;let e=new U_(this.messageAddress).createAwarenessUpdateMessage(this.document.awareness);this.send(e.toUint8Array())}handleMessage(e){this.messageQueue.push(e),this.messageQueue.length===1&&(this.processingPromise=this.processMessages())}async processMessages(){for(;this.messageQueue.length>0;){let e=this.messageQueue.at(0),t=new b_(e),n=t.readVarString(),r=n.indexOf(`\0`),i=r===-1?n:n.substring(0,r);if(i!==this.document.name){this.messageQueue.shift();continue}t.writeVarString(this.messageAddress);try{await this.callbacks.beforeHandleMessage(this,e),await new W_(t).apply(this.document,this)}catch(e){console.error(`closing connection ${this.socketId} (while handling ${i}) because of exception`,e),this.close({code:`code`in e&&typeof e.code==`number`?e.code:xg.code,reason:`reason`in e?e.reason:xg.reason})}this.messageQueue.shift()}}},K_=class extends Sr{constructor(e,t){super(t),this.callbacks={onUpdate:(e,t,n)=>{},beforeBroadcastStateless:(e,t)=>{}},this.connections=new Map,this.directConnectionsCount=0,this.isDestroyed=!1,this.saveMutex=new Pg,this.lastChangeTime=0,this.name=e,this.awareness=new j_(this),this.awareness.setLocalState(null),this.awareness.on(`update`,this.handleAwarenessUpdate.bind(this)),this.on(`update`,this.handleUpdate.bind(this)),this.isLoading=!0}isEmpty(e){return!this.get(e)._start&&!this.get(e)._map.size}merge(e){return(Array.isArray(e)?e:[e]).forEach(e=>{Rr(this,Vr(e))}),this}onUpdate(e){return this.callbacks.onUpdate=e,this}beforeBroadcastStateless(e){return this.callbacks.beforeBroadcastStateless=e,this}addConnection(e){return this.connections.set(e,{clients:new Set}),this}hasConnection(e){return this.connections.has(e)}removeConnection(e){let t=this.connections.get(e);return t&&M_(this.awareness,Array.from(t.clients),null),this.connections.delete(e),this}addDirectConnection(){return this.directConnectionsCount+=1,this}removeDirectConnection(){return this.directConnectionsCount>0&&--this.directConnectionsCount,this}getConnectionsCount(){return this.connections.size+this.directConnectionsCount}getConnections(){return Array.from(this.connections.keys())}getClients(e){let t=this.connections.get(e);return t?.clients===void 0?new Set:t.clients}hasAwarenessStates(){return this.awareness.getStates().size>0}applyAwarenessUpdate(e,t){return P_(this.awareness,t,e),this}handleAwarenessUpdate({added:e,updated:t,removed:n},r){let i=e.concat(t,n);if(r!==null){let t=this.connections.get(r);t&&(e.forEach(e=>t.clients.add(e)),n.forEach(e=>t.clients.delete(e)))}for(let e of this.getConnections()){let t=new U_(e.messageAddress).createAwarenessUpdateMessage(this.awareness,i);e.send(t.toUint8Array())}return this}handleUpdate(e,t){this.callbacks.onUpdate(this,t,e);for(let t of this.getConnections()){let n=new U_(t.messageAddress).createSyncMessage().writeUpdate(e);t.send(n.toUint8Array())}return this}broadcastStateless(e,t){this.callbacks.beforeBroadcastStateless(this,e),(t?this.getConnections().filter(t):this.getConnections()).forEach(t=>{t.sendStateless(e)})}destroy(){super.destroy(),this.isDestroyed=!0}},q_=`4.0.0-rc.1`;function J_(e){let t=e?.url;return t?t.includes(`://`)?new URL(t).searchParams:new URLSearchParams(t.split(`?`)[1]||``):new URLSearchParams}var Y_=class{constructor(e,t,n,r,i,a={}){this.websocket=e,this.request=t,this.documentProvider=n,this.hooks=r,this.opts=i,this.defaultContext=a,this.documentConnections={},this.incomingMessageQueue={},this.documentConnectionsEstablished=new Set,this.hookPayloads={},this.callbacks={onClose:[(e,t)=>{}]},this.socketId=De.randomUUID(),this.lastMessageReceivedAt=Date.now(),this.check=()=>{Date.now()-this.lastMessageReceivedAt>this.timeout&&this.close(wg)},this.setUpNewConnection=async(e,t,n)=>{let r=this.hookPayloads[e],i=await this.documentProvider.createDocument(t,r.request,r.socketId,r.connectionConfig,r.context),a=this.createConnection(this.websocket,i,r,n,r.providerVersion);if(a.onClose((t,n)=>{delete this.hookPayloads[e],delete this.documentConnections[e],delete this.incomingMessageQueue[e],this.documentConnectionsEstablished.delete(e)}),a.onTokenSyncCallback(async e=>{try{return await this.hooks(`onTokenSync`,{...r,...e,document:i,connection:a,documentName:t},e=>{r.context={...r.context,...e}})}catch(e){console.error(e);let t={...Sg,...e};a.close({code:t.code,reason:t.reason})}}),this.documentConnections[e]=a,this.websocket.readyState===Dg.Closing||this.websocket.readyState===Dg.Closed){this.close();return}this.incomingMessageQueue[e]?.forEach(e=>{a.handleMessage(e)}),await this.hooks(`connected`,{...r,documentName:t,context:r.context,connection:a})},this.handleQueueingMessage=async(e,t,n)=>{try{let r=new b_(e);if(y_(r.decoder),!(v_(r.decoder)===Q.Auth&&!this.documentConnectionsEstablished.has(t))){this.incomingMessageQueue[t].push(e);return}this.documentConnectionsEstablished.add(t),v_(r.decoder);let i=y_(r.decoder),a=null;m_(r.decoder)&&(a=y_(r.decoder));let o=t.indexOf(`\0`),s=o===-1?null:t.substring(o+1),c=t;try{let e=this.hookPayloads[t];e.providerVersion=a,await this.hooks(`onConnect`,{...e,documentName:n},t=>{e.context={...e.context,...t}}),await this.hooks(`onAuthenticate`,{token:i,...e,documentName:n},t=>{e.context={...e.context,...t}}),e.connectionConfig.isAuthenticated=!0;let r=new U_(c).writeAuthenticated(e.connectionConfig.readOnly);this.websocket.send(r.toUint8Array()),await this.setUpNewConnection(t,n,s)}catch(e){let n=e||Cg,r=new U_(c).writePermissionDenied(n.reason??`permission-denied`);this.websocket.send(r.toUint8Array()),this.documentConnectionsEstablished.delete(t),delete this.hookPayloads[t],delete this.incomingMessageQueue[t]}}catch(e){console.error(e),this.websocket.close(xg.code,xg.reason)}},this.handleMessage=e=>{this.lastMessageReceivedAt=Date.now();try{let t=y_(new b_(e).decoder),n=t.indexOf(`\0`),r=n===-1?t:t.substring(0,n),i=this.documentConnections[t]??this.documentConnections[r];if(i){i.handleMessage(e);return}if(this.incomingMessageQueue[t]===void 0){if(this.incomingMessageQueue[t]=[],this.hookPayloads[t])throw Error(`first message, but hookPayloads exists`);this.hookPayloads[t]={instance:this.documentProvider,request:this.request,connectionConfig:{readOnly:!1,isAuthenticated:!1},requestHeaders:this.request.headers,requestParameters:J_(this.request),socketId:this.socketId,context:{...this.defaultContext},providerVersion:null}}this.handleQueueingMessage(e,t,r)}catch(e){console.error(e),this.websocket.close(Sg.code,Sg.reason)}},this.timeout=i.timeout,this.pingInterval=setInterval(this.check,this.timeout)}handleClose(e){this.close(e),clearInterval(this.pingInterval)}close(e){Object.values(this.documentConnections).forEach(t=>t.close(e))}onClose(e){return this.callbacks.onClose.push(e),this}createConnection(e,t,n,r,i){let a=new G_(e,n.request,t,n.socketId,n.context,n.connectionConfig.readOnly,r,i);return a.onClose(async(e,t)=>{await a.waitForPendingMessages();let r={instance:this.documentProvider,clientsCount:e.getConnectionsCount(),context:n.context,document:e,socketId:n.socketId,documentName:e.name,requestHeaders:n.request.headers,requestParameters:J_(n.request)};await this.hooks(`onDisconnect`,r),this.callbacks.onClose.forEach(t=>t(e,r))}),a.onStatelessCallback(async e=>{try{return await this.hooks(`onStateless`,e)}catch(e){if(e?.message)throw e}}),a.beforeHandleMessage((e,r)=>{let i={instance:this.documentProvider,clientsCount:t.getConnectionsCount(),context:n.context,document:t,socketId:n.socketId,connection:e,documentName:t.name,requestHeaders:n.request.headers,requestParameters:J_(n.request),update:r};return this.hooks(`beforeHandleMessage`,i)}),a.beforeSync((e,r)=>{let i={clientsCount:t.getConnectionsCount(),context:n.context,document:t,documentName:t.name,connection:e,type:r.type,payload:r.payload};return this.hooks(`beforeSync`,i)}),a}},X_=class{constructor(e,t,n){this.document=null,this.document=e,this.instance=t,this.context=n??{},this.document.addDirectConnection()}async transact(e){if(!this.document)throw Error(`direct connection closed`);this.document.transact(t=>{e(this.document)},{source:`local`,context:this.context})}async disconnect(){this.document&&=(this.document?.removeDirectConnection(),await this.instance.storeDocumentHooks(this.document,{clientsCount:this.document.getConnectionsCount(),lastContext:this.context,lastTransactionOrigin:{source:`local`,context:this.context},document:this.document,documentName:this.document.name,instance:this.instance},!0),this.document.getConnectionsCount()===0&&!this.document.saveMutex.isLocked()&&(await this.instance.hooks(`onDisconnect`,{instance:this.instance,clientsCount:this.document.getConnectionsCount(),context:this.context,document:this.document,socketId:`server`,documentName:this.document.name,requestHeaders:new Headers,requestParameters:new Ee}),await this.instance.unloadDocument(this.document)),null)}};const Z_=()=>{let e=new Map,t=new Map;return{debounce:async(n,r,i,a)=>{let o=e.get(n),s=o?.start||Date.now(),c=async()=>{t.has(n)&&await t.get(n),e.delete(n);let i=r();t.set(n,i);let a=await i;return t.delete(n),a};if(o?.timeout&&clearTimeout(o.timeout),i===0||Date.now()-s>=a)return c();e.set(n,{start:s,timeout:setTimeout(c,i),func:c})},isDebounced:t=>e.has(t),isCurrentlyExecuting:e=>t.has(e),executeNow:t=>{let n=e.get(t);if(n)return clearTimeout(n.timeout),n.func()}}},Q_={name:null,timeout:6e4,debounce:2e3,maxDebounce:1e4,quiet:!1,yDocOptions:{gc:!0,gcFilter:()=>!0},unloadImmediately:!0};var $_=class{constructor(e){this.configuration={...Q_,extensions:[],onConfigure:()=>new Promise(e=>e(null)),onListen:()=>new Promise(e=>e(null)),onUpgrade:()=>new Promise(e=>e(null)),onConnect:()=>new Promise(e=>e(null)),connected:()=>new Promise(e=>e(null)),beforeHandleMessage:()=>new Promise(e=>e(null)),beforeSync:()=>new Promise(e=>e(null)),beforeBroadcastStateless:()=>new Promise(e=>e(null)),onStateless:()=>new Promise(e=>e(null)),onChange:()=>new Promise(e=>e(null)),onCreateDocument:()=>new Promise(e=>e(null)),onLoadDocument:()=>new Promise(e=>e(null)),onStoreDocument:()=>new Promise(e=>e(null)),afterStoreDocument:()=>new Promise(e=>e(null)),onAwarenessUpdate:()=>new Promise(e=>e(null)),onRequest:()=>new Promise(e=>e(null)),onDisconnect:()=>new Promise(e=>e(null)),onDestroy:()=>new Promise(e=>e(null))},this.loadingDocuments=new Map,this.unloadingDocuments=new Map,this.documents=new Map,this.debouncer=Z_(),e&&this.configure(e)}configure(e){return this.configuration={...this.configuration,...e},this.configuration.extensions.sort((e,t)=>{let n=e.priority===void 0?100:e.priority,r=t.priority===void 0?100:t.priority;return n>r?-1:n<r?1:0}),this.configuration.extensions.push({onConfigure:this.configuration.onConfigure,onListen:this.configuration.onListen,onUpgrade:this.configuration.onUpgrade,onConnect:this.configuration.onConnect,connected:this.configuration.connected,onAuthenticate:this.configuration.onAuthenticate,onTokenSync:this.configuration.onTokenSync,onLoadDocument:this.configuration.onLoadDocument,afterLoadDocument:this.configuration.afterLoadDocument,beforeHandleMessage:this.configuration.beforeHandleMessage,beforeBroadcastStateless:this.configuration.beforeBroadcastStateless,beforeSync:this.configuration.beforeSync,onStateless:this.configuration.onStateless,onChange:this.configuration.onChange,onStoreDocument:this.configuration.onStoreDocument,afterStoreDocument:this.configuration.afterStoreDocument,onAwarenessUpdate:this.configuration.onAwarenessUpdate,onRequest:this.configuration.onRequest,beforeUnloadDocument:this.configuration.beforeUnloadDocument,afterUnloadDocument:this.configuration.afterUnloadDocument,onDisconnect:this.configuration.onDisconnect,onDestroy:this.configuration.onDestroy}),this.hooks(`onConfigure`,{configuration:this.configuration,version:q_,instance:this}),this}getDocumentsCount(){return this.documents.size}getConnectionsCount(){let e=new Set,t=Array.from(this.documents.values()).reduce((t,n)=>(n.getConnections().forEach(({socketId:t})=>{e.add(t)}),t+n.directConnectionsCount),0);return e.size+t}flushPendingStores(){this.documents.forEach(e=>{let t=`onStoreDocument-${e.name}`;!e.isLoading&&this.debouncer.isDebounced(t)&&this.debouncer.executeNow(t)})}closeConnections(e){this.documents.forEach(t=>{e&&t.name!==e||t.connections.forEach((e,t)=>{t.close(xg)})})}handleConnection(e,t,n={}){let r=new Y_(e,t,this,this.hooks.bind(this),{timeout:this.configuration.timeout},n);return r.onClose((e,t)=>{e.getConnectionsCount()>0||(!e.isLoading&&this.debouncer.isDebounced(`onStoreDocument-${e.name}`)?this.configuration.unloadImmediately&&this.debouncer.executeNow(`onStoreDocument-${e.name}`):this.unloadDocument(e))}),r}handleDocumentUpdate(e,t,n){let r=V_(t)&&t.source===`connection`?t.connection:void 0,i=r?.request,a=V_(t)?t.source===`connection`?t.connection.context:t.source===`local`?t.context??{}:{}:{},o={instance:this,clientsCount:e.getConnectionsCount(),document:e,documentName:e.name,requestHeaders:i?.headers??new Headers,requestParameters:J_(i),socketId:r?.socketId??``,update:n,transactionOrigin:t,connection:r,context:a};if(this.hooks(`onChange`,o),H_(t))return;let s={instance:this,clientsCount:e.getConnectionsCount(),document:e,lastContext:a,lastTransactionOrigin:t,documentName:e.name};this.storeDocumentHooks(e,s)}async createDocument(e,t,n,r,i){if(!e.trim())throw Error(`Document name must not be empty`);let a=this.loadingDocuments.get(e);if(a)return a;let o=this.documents.get(e);if(o)return Promise.resolve(o);let s=this.loadDocument(e,t,n,r,i);this.loadingDocuments.set(e,s);try{let t=await s;return this.documents.set(e,t),this.loadingDocuments.delete(e),t}catch(t){throw this.loadingDocuments.delete(e),t}}async loadDocument(e,t,n,r,i){let a=t.headers,o=J_(t),s=i??{},c=await this.hooks(`onCreateDocument`,{documentName:e,requestHeaders:a,requestParameters:o,connectionConfig:r,context:s,socketId:n,instance:this}),l=new K_(e,{...this.configuration.yDocOptions,...c}),u={instance:this,context:s,connectionConfig:r,document:l,documentName:e,socketId:n,requestHeaders:a,requestParameters:o};try{await this.hooks(`onLoadDocument`,u,e=>{e instanceof Sr?Rr(l,Vr(e)):e instanceof Uint8Array&&Rr(l,e)})}catch(t){throw this.closeConnections(e),this.unloadDocument(l),t}return l.isLoading=!1,l.onUpdate((e,t,n)=>{e.lastChangeTime=Date.now(),this.handleDocumentUpdate(e,t,n)}),await this.hooks(`afterLoadDocument`,u),l.beforeBroadcastStateless((e,t)=>{let n={document:e,documentName:e.name,payload:t};this.hooks(`beforeBroadcastStateless`,n)}),l.awareness.on(`update`,(t,n)=>{this.hooks(`onAwarenessUpdate`,{document:l,documentName:e,instance:this,...t,transactionOrigin:n,connection:V_(n)&&n.source===`connection`?n.connection:void 0,awareness:l.awareness,states:Tg(l.awareness.getStates())})}),l}storeDocumentHooks(e,t,n){let r=`onStoreDocument-${e.name}`;return this.debouncer.debounce(r,async()=>{try{await e.saveMutex.runExclusive(async()=>{await this.hooks(`onStoreDocument`,t),await this.hooks(`afterStoreDocument`,t)})}catch(t){if(t instanceof Eg){setTimeout(()=>{this.shouldUnloadDocument(e)&&this.unloadDocument(e)},0);return}console.error(`Caught error during storeDocumentHooks. Document stays in memory to avoid data loss`,t);return}setTimeout(()=>{this.shouldUnloadDocument(e)&&this.unloadDocument(e)},0)},n?0:this.configuration.debounce,this.configuration.maxDebounce)}hooks(e,t,n=null){let{extensions:r}=this.configuration,i=Promise.resolve();return r.filter(t=>typeof t[e]==`function`).forEach(r=>{i=i.then(()=>r[e]?.(t)).catch(t=>{throw t?.message&&console.error(`[${e}]`,t.message),t}),n&&(i=i.then((...e)=>n(...e)))}),i}shouldUnloadDocument(e){return(this.debouncer.isDebounced(`onStoreDocument-${e.name}`)||this.debouncer.isCurrentlyExecuting(`onStoreDocument-${e.name}`)||e.saveMutex.isLocked())===!1&&e.getConnectionsCount()===0}async unloadDocument(e){let t=e.name;if(!this.shouldUnloadDocument(e)||!this.documents.has(t))return;if(this.unloadingDocuments.has(t))return this.unloadingDocuments.get(t);let n=(async()=>{try{await this.hooks(`beforeUnloadDocument`,{instance:this,documentName:t,document:e})}catch{return}this.shouldUnloadDocument(e)&&(this.documents.delete(t),e.destroy(),await this.hooks(`afterUnloadDocument`,{instance:this,documentName:t}))})();this.unloadingDocuments.set(t,Promise.resolve(n)),await n,this.unloadingDocuments.delete(t)}async openDirectConnection(e,t){return new X_(await this.createDocument(e,new Request(`http://localhost`),De.randomUUID(),{isAuthenticated:!0,readOnly:!1},t),this,t)}},ev=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),tv=oe(import.meta.url),nv=ev(((e,t)=>{let n=[`nodebuffer`,`arraybuffer`,`fragments`],r=typeof Blob<`u`;r&&n.push(`blob`),t.exports={BINARY_TYPES:n,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:`258EAFA5-E914-47DA-95CA-C5AB0DC85B11`,hasBlob:r,kForOnEventAttribute:Symbol(`kIsForOnEventAttribute`),kListener:Symbol(`kListener`),kStatusCode:Symbol(`status-code`),kWebSocket:Symbol(`websocket`),NOOP:()=>{}}})),rv=ev(((e,t)=>{let{EMPTY_BUFFER:n}=nv(),r=Buffer[Symbol.species];function i(e,t){if(e.length===0)return n;if(e.length===1)return e[0];let i=Buffer.allocUnsafe(t),a=0;for(let t=0;t<e.length;t++){let n=e[t];i.set(n,a),a+=n.length}return a<t?new r(i.buffer,i.byteOffset,a):i}function a(e,t,n,r,i){for(let a=0;a<i;a++)n[r+a]=e[a]^t[a&3]}function o(e,t){for(let n=0;n<e.length;n++)e[n]^=t[n&3]}function s(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)}function c(e){if(c.readOnly=!0,Buffer.isBuffer(e))return e;let t;return e instanceof ArrayBuffer?t=new r(e):ArrayBuffer.isView(e)?t=new r(e.buffer,e.byteOffset,e.byteLength):(t=Buffer.from(e),c.readOnly=!1),t}if(t.exports={concat:i,mask:a,toArrayBuffer:s,toBuffer:c,unmask:o},!process.env.WS_NO_BUFFER_UTIL)try{let e=tv(`bufferutil`);t.exports.mask=function(t,n,r,i,o){o<48?a(t,n,r,i,o):e.mask(t,n,r,i,o)},t.exports.unmask=function(t,n){t.length<32?o(t,n):e.unmask(t,n)}}catch{}})),iv=ev(((e,t)=>{let n=Symbol(`kDone`),r=Symbol(`kRun`);t.exports=class{constructor(e){this[n]=()=>{this.pending--,this[r]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[r]()}[r](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[n])}}}})),av=ev(((e,t)=>{let n=tv(`zlib`),r=rv(),i=iv(),{kStatusCode:a}=nv(),o=Buffer[Symbol.species],s=Buffer.from([0,0,255,255]),c=Symbol(`permessage-deflate`),l=Symbol(`total-length`),u=Symbol(`callback`),d=Symbol(`buffers`),f=Symbol(`error`),p;t.exports=class{constructor(e,t,n){this._maxPayload=n|0,this._options=e||{},this._threshold=this._options.threshold===void 0?1024:this._options.threshold,this._isServer=!!t,this._deflate=null,this._inflate=null,this.params=null,p||=new i(this._options.concurrencyLimit===void 0?10:this._options.concurrencyLimit)}static get extensionName(){return`permessage-deflate`}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits??(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&=(this._inflate.close(),null),this._deflate){let e=this._deflate[u];this._deflate.close(),this._deflate=null,e&&e(Error(`The deflate stream was closed while data was being processed`))}}acceptAsServer(e){let t=this._options,n=e.find(e=>!(t.serverNoContextTakeover===!1&&e.server_no_context_takeover||e.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits==`number`&&t.serverMaxWindowBits>e.server_max_window_bits)||typeof t.clientMaxWindowBits==`number`&&!e.client_max_window_bits));if(!n)throw Error(`None of the extension offers can be accepted`);return t.serverNoContextTakeover&&(n.server_no_context_takeover=!0),t.clientNoContextTakeover&&(n.client_no_context_takeover=!0),typeof t.serverMaxWindowBits==`number`&&(n.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits==`number`?n.client_max_window_bits=t.clientMaxWindowBits:(n.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete n.client_max_window_bits,n}acceptAsClient(e){let t=e[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw Error(`Unexpected parameter "client_no_context_takeover"`);if(!t.client_max_window_bits)typeof this._options.clientMaxWindowBits==`number`&&(t.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits==`number`&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw Error(`Unexpected or invalid parameter "client_max_window_bits"`);return t}normalizeParams(e){return e.forEach(e=>{Object.keys(e).forEach(t=>{let n=e[t];if(n.length>1)throw Error(`Parameter "${t}" must have only a single value`);if(n=n[0],t===`client_max_window_bits`){if(n!==!0){let e=+n;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else if(!this._isServer)throw TypeError(`Invalid value for parameter "${t}": ${n}`)}else if(t===`server_max_window_bits`){let e=+n;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else if(t===`client_no_context_takeover`||t===`server_no_context_takeover`){if(n!==!0)throw TypeError(`Invalid value for parameter "${t}": ${n}`)}else throw Error(`Unknown parameter "${t}"`);e[t]=n})}),e}decompress(e,t,n){p.add(r=>{this._decompress(e,t,(e,t)=>{r(),n(e,t)})})}compress(e,t,n){p.add(r=>{this._compress(e,t,(e,t)=>{r(),n(e,t)})})}_decompress(e,t,i){let a=this._isServer?`client`:`server`;if(!this._inflate){let e=`${a}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:n.Z_DEFAULT_WINDOWBITS;this._inflate=n.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[c]=this,this._inflate[l]=0,this._inflate[d]=[],this._inflate.on(`error`,g),this._inflate.on(`data`,h)}this._inflate[u]=i,this._inflate.write(e),t&&this._inflate.write(s),this._inflate.flush(()=>{let e=this._inflate[f];if(e){this._inflate.close(),this._inflate=null,i(e);return}let n=r.concat(this._inflate[d],this._inflate[l]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[l]=0,this._inflate[d]=[],t&&this.params[`${a}_no_context_takeover`]&&this._inflate.reset()),i(null,n)})}_compress(e,t,i){let a=this._isServer?`server`:`client`;if(!this._deflate){let e=`${a}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:n.Z_DEFAULT_WINDOWBITS;this._deflate=n.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[l]=0,this._deflate[d]=[],this._deflate.on(`data`,m)}this._deflate[u]=i,this._deflate.write(e),this._deflate.flush(n.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let e=r.concat(this._deflate[d],this._deflate[l]);t&&(e=new o(e.buffer,e.byteOffset,e.length-4)),this._deflate[u]=null,this._deflate[l]=0,this._deflate[d]=[],t&&this.params[`${a}_no_context_takeover`]&&this._deflate.reset(),i(null,e)})}};function m(e){this[d].push(e),this[l]+=e.length}function h(e){if(this[l]+=e.length,this[c]._maxPayload<1||this[l]<=this[c]._maxPayload){this[d].push(e);return}this[f]=RangeError(`Max payload size exceeded`),this[f].code=`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`,this[f][a]=1009,this.removeListener(`data`,h),this.reset()}function g(e){if(this[c]._inflate=null,this[f]){this[u](this[f]);return}e[a]=1007,this[u](e)}})),ov=ev(((e,t)=>{let{isUtf8:n}=tv(`buffer`),{hasBlob:r}=nv(),i=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function a(e){return e>=1e3&&e<=1014&&e!==1004&&e!==1005&&e!==1006||e>=3e3&&e<=4999}function o(e){let t=e.length,n=0;for(;n<t;)if(!(e[n]&128))n++;else if((e[n]&224)==192){if(n+1===t||(e[n+1]&192)!=128||(e[n]&254)==192)return!1;n+=2}else if((e[n]&240)==224){if(n+2>=t||(e[n+1]&192)!=128||(e[n+2]&192)!=128||e[n]===224&&(e[n+1]&224)==128||e[n]===237&&(e[n+1]&224)==160)return!1;n+=3}else if((e[n]&248)==240){if(n+3>=t||(e[n+1]&192)!=128||(e[n+2]&192)!=128||(e[n+3]&192)!=128||e[n]===240&&(e[n+1]&240)==128||e[n]===244&&e[n+1]>143||e[n]>244)return!1;n+=4}else return!1;return!0}function s(e){return r&&typeof e==`object`&&typeof e.arrayBuffer==`function`&&typeof e.type==`string`&&typeof e.stream==`function`&&(e[Symbol.toStringTag]===`Blob`||e[Symbol.toStringTag]===`File`)}if(t.exports={isBlob:s,isValidStatusCode:a,isValidUTF8:o,tokenChars:i},n)t.exports.isValidUTF8=function(e){return e.length<24?o(e):n(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let e=tv(`utf-8-validate`);t.exports.isValidUTF8=function(t){return t.length<32?o(t):e(t)}}catch{}})),sv=ev(((e,t)=>{let{Writable:n}=tv(`stream`),r=av(),{BINARY_TYPES:i,EMPTY_BUFFER:a,kStatusCode:o,kWebSocket:s}=nv(),{concat:c,toArrayBuffer:l,unmask:u}=rv(),{isValidStatusCode:d,isValidUTF8:f}=ov(),p=Buffer[Symbol.species];t.exports=class extends n{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents===void 0?!0:e.allowSynchronousEvents,this._binaryType=e.binaryType||i[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[s]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=0}_write(e,t,n){if(this._opcode===8&&this._state==0)return n();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(n)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let t=this._buffers[0];return this._buffers[0]=new p(t.buffer,t.byteOffset+e,t.length-e),new p(t.buffer,t.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let n=this._buffers[0],r=t.length-e;e>=n.length?t.set(this._buffers.shift(),r):(t.set(new Uint8Array(n.buffer,n.byteOffset,e),r),this._buffers[0]=new p(n.buffer,n.byteOffset+e,n.length-e)),e-=n.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case 0:this.getInfo(e);break;case 1:this.getPayloadLength16(e);break;case 2:this.getPayloadLength64(e);break;case 3:this.getMask();break;case 4:this.getData(e);break;case 5:case 6:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if(t[0]&48){e(this.createError(RangeError,`RSV2 and RSV3 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_2_3`));return}let n=(t[0]&64)==64;if(n&&!this._extensions[r.extensionName]){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(this._fin=(t[0]&128)==128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(n){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(!this._fragmented){e(this.createError(RangeError,`invalid opcode 0`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}this._compressed=n}else if(this._opcode>7&&this._opcode<11){if(!this._fin){e(this.createError(RangeError,`FIN must be set`,!0,1002,`WS_ERR_EXPECTED_FIN`));return}if(n){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){e(this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,`WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH`));return}}else{e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)==128,this._isServer){if(!this._masked){e(this.createError(RangeError,`MASK must be set`,!0,1002,`WS_ERR_EXPECTED_MASK`));return}}else if(this._masked){e(this.createError(RangeError,`MASK must be clear`,!0,1002,`WS_ERR_UNEXPECTED_MASK`));return}this._payloadLength===126?this._state=1:this._payloadLength===127?this._state=2:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let t=this.consume(8),n=t.readUInt32BE(0);if(n>2**21-1){e(this.createError(RangeError,`Unsupported WebSocket frame: payload length > 2^53 - 1`,!1,1009,`WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH`));return}this._payloadLength=n*2**32+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){e(this.createError(RangeError,`Max payload size exceeded`,!1,1009,`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`));return}this._masked?this._state=3:this._state=4}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=4}getData(e){let t=a;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&u(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=5,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[r.extensionName].decompress(e,this._fin,(e,n)=>{if(e)return t(e);if(n.length){if(this._messageLength+=n.length,this._messageLength>this._maxPayload&&this._maxPayload>0){t(this.createError(RangeError,`Max payload size exceeded`,!1,1009,`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`));return}this._fragments.push(n)}this.dataMessage(t),this._state===0&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=0;return}let t=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let r;r=this._binaryType===`nodebuffer`?c(n,t):this._binaryType===`arraybuffer`?l(c(n,t)):this._binaryType===`blob`?new Blob(n):n,this._allowSynchronousEvents?(this.emit(`message`,r,!0),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,r,!0),this._state=0,this.startLoop(e)}))}else{let r=c(n,t);if(!this._skipUTF8Validation&&!f(r)){e(this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`));return}this._state===5||this._allowSynchronousEvents?(this.emit(`message`,r,!1),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,r,!1),this._state=0,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit(`conclude`,1005,a),this.end();else{let n=e.readUInt16BE(0);if(!d(n)){t(this.createError(RangeError,`invalid status code ${n}`,!0,1002,`WS_ERR_INVALID_CLOSE_CODE`));return}let r=new p(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!f(r)){t(this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`));return}this._loop=!1,this.emit(`conclude`,n,r),this.end()}this._state=0;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0):(this._state=6,setImmediate(()=>{this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0,this.startLoop(t)}))}createError(e,t,n,r,i){this._loop=!1,this._errored=!0;let a=new e(n?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(a,this.createError),a.code=i,a[o]=r,a}}})),cv=ev(((e,t)=>{let{Duplex:n}=tv(`stream`),{randomFillSync:r}=tv(`crypto`),i=av(),{EMPTY_BUFFER:a,kWebSocket:o,NOOP:s}=nv(),{isBlob:c,isValidStatusCode:l}=ov(),{mask:u,toBuffer:d}=rv(),f=Symbol(`kByteLength`),p=Buffer.alloc(4),m=8*1024,h,g=m;t.exports=class e{constructor(e,t,n){this._extensions=t||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=0,this.onerror=s,this[o]=void 0}static frame(e,t){let n,i=!1,a=2,o=!1;t.mask&&(n=t.maskBuffer||p,t.generateMask?t.generateMask(n):(g===m&&(h===void 0&&(h=Buffer.alloc(m)),r(h,0,m),g=0),n[0]=h[g++],n[1]=h[g++],n[2]=h[g++],n[3]=h[g++]),o=(n[0]|n[1]|n[2]|n[3])===0,a=6);let s;typeof e==`string`?(!t.mask||o)&&t[f]!==void 0?s=t[f]:(e=Buffer.from(e),s=e.length):(s=e.length,i=t.mask&&t.readOnly&&!o);let c=s;s>=65536?(a+=8,c=127):s>125&&(a+=2,c=126);let l=Buffer.allocUnsafe(i?s+a:a);return l[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(l[0]|=64),l[1]=c,c===126?l.writeUInt16BE(s,2):c===127&&(l[2]=l[3]=0,l.writeUIntBE(s,4,6)),!t.mask||(l[1]|=128,l[a-4]=n[0],l[a-3]=n[1],l[a-2]=n[2],l[a-1]=n[3],o)?[l,e]:i?(u(e,n,l,a,s),[l]):(u(e,n,e,0,s),[l,e])}close(t,n,r,i){let o;if(t===void 0)o=a;else if(typeof t!=`number`||!l(t))throw TypeError(`First argument must be a valid error code number`);else if(n===void 0||!n.length)o=Buffer.allocUnsafe(2),o.writeUInt16BE(t,0);else{let e=Buffer.byteLength(n);if(e>123)throw RangeError(`The message must not be greater than 123 bytes`);o=Buffer.allocUnsafe(2+e),o.writeUInt16BE(t,0),typeof n==`string`?o.write(n,2):o.set(n,2)}let s={[f]:o.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state===0?this.sendFrame(e.frame(o,s),i):this.enqueue([this.dispatch,o,!1,s,i])}ping(t,n,r){let i,a;if(typeof t==`string`?(i=Buffer.byteLength(t),a=!1):c(t)?(i=t.size,a=!1):(t=d(t),i=t.length,a=d.readOnly),i>125)throw RangeError(`The data size must not be greater than 125 bytes`);let o={[f]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:a,rsv1:!1};c(t)?this._state===0?this.getBlobData(t,!1,o,r):this.enqueue([this.getBlobData,t,!1,o,r]):this._state===0?this.sendFrame(e.frame(t,o),r):this.enqueue([this.dispatch,t,!1,o,r])}pong(t,n,r){let i,a;if(typeof t==`string`?(i=Buffer.byteLength(t),a=!1):c(t)?(i=t.size,a=!1):(t=d(t),i=t.length,a=d.readOnly),i>125)throw RangeError(`The data size must not be greater than 125 bytes`);let o={[f]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:a,rsv1:!1};c(t)?this._state===0?this.getBlobData(t,!1,o,r):this.enqueue([this.getBlobData,t,!1,o,r]):this._state===0?this.sendFrame(e.frame(t,o),r):this.enqueue([this.dispatch,t,!1,o,r])}send(e,t,n){let r=this._extensions[i.extensionName],a=t.binary?2:1,o=t.compress,s,l;typeof e==`string`?(s=Buffer.byteLength(e),l=!1):c(e)?(s=e.size,l=!1):(e=d(e),s=e.length,l=d.readOnly),this._firstFragment?(this._firstFragment=!1,o&&r&&r.params[r._isServer?`server_no_context_takeover`:`client_no_context_takeover`]&&(o=s>=r._threshold),this._compress=o):(o=!1,a=0),t.fin&&(this._firstFragment=!0);let u={[f]:s,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:a,readOnly:l,rsv1:o};c(e)?this._state===0?this.getBlobData(e,this._compress,u,n):this.enqueue([this.getBlobData,e,this._compress,u,n]):this._state===0?this.dispatch(e,this._compress,u,n):this.enqueue([this.dispatch,e,this._compress,u,n])}getBlobData(t,n,r,i){this._bufferedBytes+=r[f],this._state=2,t.arrayBuffer().then(t=>{if(this._socket.destroyed){let e=Error(`The socket was closed while the blob was being read`);process.nextTick(_,this,e,i);return}this._bufferedBytes-=r[f];let a=d(t);n?this.dispatch(a,n,r,i):(this._state=0,this.sendFrame(e.frame(a,r),i),this.dequeue())}).catch(e=>{process.nextTick(v,this,e,i)})}dispatch(t,n,r,a){if(!n){this.sendFrame(e.frame(t,r),a);return}let o=this._extensions[i.extensionName];this._bufferedBytes+=r[f],this._state=1,o.compress(t,r.fin,(t,n)=>{if(this._socket.destroyed){_(this,Error(`The socket was closed while data was being compressed`),a);return}this._bufferedBytes-=r[f],this._state=0,r.readOnly=!1,this.sendFrame(e.frame(n,r),a),this.dequeue()})}dequeue(){for(;this._state===0&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][f],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][f],this._queue.push(e)}sendFrame(e,t){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};function _(e,t,n){typeof n==`function`&&n(t);for(let n=0;n<e._queue.length;n++){let r=e._queue[n],i=r[r.length-1];typeof i==`function`&&i(t)}}function v(e,t,n){_(e,t,n),e.onerror(t)}})),lv=ev(((e,t)=>{let{kForOnEventAttribute:n,kListener:r}=nv(),i=Symbol(`kCode`),a=Symbol(`kData`),o=Symbol(`kError`),s=Symbol(`kMessage`),c=Symbol(`kReason`),l=Symbol(`kTarget`),u=Symbol(`kType`),d=Symbol(`kWasClean`);var f=class{constructor(e){this[l]=null,this[u]=e}get target(){return this[l]}get type(){return this[u]}};Object.defineProperty(f.prototype,`target`,{enumerable:!0}),Object.defineProperty(f.prototype,`type`,{enumerable:!0});var p=class extends f{constructor(e,t={}){super(e),this[i]=t.code===void 0?0:t.code,this[c]=t.reason===void 0?``:t.reason,this[d]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[i]}get reason(){return this[c]}get wasClean(){return this[d]}};Object.defineProperty(p.prototype,`code`,{enumerable:!0}),Object.defineProperty(p.prototype,`reason`,{enumerable:!0}),Object.defineProperty(p.prototype,`wasClean`,{enumerable:!0});var m=class extends f{constructor(e,t={}){super(e),this[o]=t.error===void 0?null:t.error,this[s]=t.message===void 0?``:t.message}get error(){return this[o]}get message(){return this[s]}};Object.defineProperty(m.prototype,`error`,{enumerable:!0}),Object.defineProperty(m.prototype,`message`,{enumerable:!0});var h=class extends f{constructor(e,t={}){super(e),this[a]=t.data===void 0?null:t.data}get data(){return this[a]}};Object.defineProperty(h.prototype,`data`,{enumerable:!0}),t.exports={CloseEvent:p,ErrorEvent:m,Event:f,EventTarget:{addEventListener(e,t,i={}){for(let a of this.listeners(e))if(!i[n]&&a[r]===t&&!a[n])return;let a;if(e===`message`)a=function(e,n){let r=new h(`message`,{data:n?e:e.toString()});r[l]=this,g(t,this,r)};else if(e===`close`)a=function(e,n){let r=new p(`close`,{code:e,reason:n.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});r[l]=this,g(t,this,r)};else if(e===`error`)a=function(e){let n=new m(`error`,{error:e,message:e.message});n[l]=this,g(t,this,n)};else if(e===`open`)a=function(){let e=new f(`open`);e[l]=this,g(t,this,e)};else return;a[n]=!!i[n],a[r]=t,i.once?this.once(e,a):this.on(e,a)},removeEventListener(e,t){for(let i of this.listeners(e))if(i[r]===t&&!i[n]){this.removeListener(e,i);break}}},MessageEvent:h};function g(e,t,n){typeof e==`object`&&e.handleEvent?e.handleEvent.call(e,n):e.call(t,n)}})),uv=ev(((e,t)=>{let{tokenChars:n}=ov();function r(e,t,n){e[t]===void 0?e[t]=[n]:e[t].push(n)}function i(e){let t=Object.create(null),i=Object.create(null),a=!1,o=!1,s=!1,c,l,u=-1,d=-1,f=-1,p=0;for(;p<e.length;p++)if(d=e.charCodeAt(p),c===void 0)if(f===-1&&n[d]===1)u===-1&&(u=p);else if(p!==0&&(d===32||d===9))f===-1&&u!==-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let n=e.slice(u,f);d===44?(r(t,n,i),i=Object.create(null)):c=n,u=f=-1}else throw SyntaxError(`Unexpected character at index ${p}`);else if(l===void 0)if(f===-1&&n[d]===1)u===-1&&(u=p);else if(d===32||d===9)f===-1&&u!==-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p),r(i,e.slice(u,f),!0),d===44&&(r(t,c,i),i=Object.create(null),c=void 0),u=f=-1}else if(d===61&&u!==-1&&f===-1)l=e.slice(u,p),u=f=-1;else throw SyntaxError(`Unexpected character at index ${p}`);else if(o){if(n[d]!==1)throw SyntaxError(`Unexpected character at index ${p}`);u===-1?u=p:a||=!0,o=!1}else if(s)if(n[d]===1)u===-1&&(u=p);else if(d===34&&u!==-1)s=!1,f=p;else if(d===92)o=!0;else throw SyntaxError(`Unexpected character at index ${p}`);else if(d===34&&e.charCodeAt(p-1)===61)s=!0;else if(f===-1&&n[d]===1)u===-1&&(u=p);else if(u!==-1&&(d===32||d===9))f===-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let n=e.slice(u,f);a&&=(n=n.replace(/\\/g,``),!1),r(i,l,n),d===44&&(r(t,c,i),i=Object.create(null),c=void 0),l=void 0,u=f=-1}else throw SyntaxError(`Unexpected character at index ${p}`);if(u===-1||s||d===32||d===9)throw SyntaxError(`Unexpected end of input`);f===-1&&(f=p);let m=e.slice(u,f);return c===void 0?r(t,m,i):(l===void 0?r(i,m,!0):a?r(i,l,m.replace(/\\/g,``)):r(i,l,m),r(t,c,i)),t}function a(e){return Object.keys(e).map(t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map(e=>[t].concat(Object.keys(e).map(t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map(e=>e===!0?t:`${t}=${e}`).join(`; `)})).join(`; `)).join(`, `)}).join(`, `)}t.exports={format:a,parse:i}})),dv=ev(((e,t)=>{let n=tv(`events`),r=tv(`https`),i=tv(`http`),a=tv(`net`),o=tv(`tls`),{randomBytes:s,createHash:c}=tv(`crypto`),{Duplex:l,Readable:u}=tv(`stream`),{URL:d}=tv(`url`),f=av(),p=sv(),m=cv(),{isBlob:h}=ov(),{BINARY_TYPES:g,CLOSE_TIMEOUT:_,EMPTY_BUFFER:v,GUID:y,kForOnEventAttribute:b,kListener:x,kStatusCode:S,kWebSocket:C,NOOP:w}=nv(),{EventTarget:{addEventListener:T,removeEventListener:E}}=lv(),{format:D,parse:O}=uv(),{toBuffer:k}=rv(),A=Symbol(`kAborted`),j=[8,13],M=[`CONNECTING`,`OPEN`,`CLOSING`,`CLOSED`],ee=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;var N=class e extends n{constructor(t,n,r){super(),this._binaryType=g[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=v,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol=``,this._readyState=e.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,t===null?(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0):(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?n=[]:Array.isArray(n)||(typeof n==`object`&&n?(r=n,n=[]):n=[n]),te(this,t,n,r))}get binaryType(){return this._binaryType}set binaryType(e){g.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(t,n,r){let i=new p({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),a=new m(t,this._extensions,r.generateMask);this._receiver=i,this._sender=a,this._socket=t,i[C]=this,a[C]=this,t[C]=this,i.on(`conclude`,ae),i.on(`drain`,I),i.on(`error`,oe),i.on(`message`,L),i.on(`ping`,ce),i.on(`pong`,le),a.onerror=R,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),n.length>0&&t.unshift(n),t.on(`close`,fe),t.on(`data`,pe),t.on(`end`,me),t.on(`error`,he),this._readyState=e.OPEN,this.emit(`open`)}emitClose(){if(!this._socket){this._readyState=e.CLOSED,this.emit(`close`,this._closeCode,this._closeMessage);return}this._extensions[f.extensionName]&&this._extensions[f.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=e.CLOSED,this.emit(`close`,this._closeCode,this._closeMessage)}close(t,n){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){F(this,this._req,`WebSocket was closed before the connection was established`);return}if(this.readyState===e.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=e.CLOSING,this._sender.close(t,n,!this._isServer,e=>{e||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),de(this)}}pause(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!0,this._socket.pause())}ping(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof t==`function`?(r=t,t=n=void 0):typeof n==`function`&&(r=n,n=void 0),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){ie(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(t||v,n,r)}pong(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof t==`function`?(r=t,t=n=void 0):typeof n==`function`&&(r=n,n=void 0),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){ie(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(t||v,n,r)}resume(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof n==`function`&&(r=n,n={}),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){ie(this,t,r);return}let i={binary:typeof t!=`string`,mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[f.extensionName]||(i.compress=!1),this._sender.send(t||v,i,r)}terminate(){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){F(this,this._req,`WebSocket was closed before the connection was established`);return}this._socket&&(this._readyState=e.CLOSING,this._socket.destroy())}}};Object.defineProperty(N,`CONNECTING`,{enumerable:!0,value:M.indexOf(`CONNECTING`)}),Object.defineProperty(N.prototype,`CONNECTING`,{enumerable:!0,value:M.indexOf(`CONNECTING`)}),Object.defineProperty(N,`OPEN`,{enumerable:!0,value:M.indexOf(`OPEN`)}),Object.defineProperty(N.prototype,`OPEN`,{enumerable:!0,value:M.indexOf(`OPEN`)}),Object.defineProperty(N,`CLOSING`,{enumerable:!0,value:M.indexOf(`CLOSING`)}),Object.defineProperty(N.prototype,`CLOSING`,{enumerable:!0,value:M.indexOf(`CLOSING`)}),Object.defineProperty(N,`CLOSED`,{enumerable:!0,value:M.indexOf(`CLOSED`)}),Object.defineProperty(N.prototype,`CLOSED`,{enumerable:!0,value:M.indexOf(`CLOSED`)}),[`binaryType`,`bufferedAmount`,`extensions`,`isPaused`,`protocol`,`readyState`,`url`].forEach(e=>{Object.defineProperty(N.prototype,e,{enumerable:!0})}),[`open`,`error`,`close`,`message`].forEach(e=>{Object.defineProperty(N.prototype,`on${e}`,{enumerable:!0,get(){for(let t of this.listeners(e))if(t[b])return t[x];return null},set(t){for(let t of this.listeners(e))if(t[b]){this.removeListener(e,t);break}typeof t==`function`&&this.addEventListener(e,t,{[b]:!0})}})}),N.prototype.addEventListener=T,N.prototype.removeEventListener=E,t.exports=N;function te(e,t,n,a){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:_,protocolVersion:j[1],maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...a,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:`GET`,host:void 0,path:void 0,port:void 0};if(e._autoPong=o.autoPong,e._closeTimeout=o.closeTimeout,!j.includes(o.protocolVersion))throw RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${j.join(`, `)})`);let l;if(t instanceof d)l=t;else try{l=new d(t)}catch{throw SyntaxError(`Invalid URL: ${t}`)}l.protocol===`http:`?l.protocol=`ws:`:l.protocol===`https:`&&(l.protocol=`wss:`),e._url=l.href;let u=l.protocol===`wss:`,p=l.protocol===`ws+unix:`,m;if(l.protocol!==`ws:`&&!u&&!p?m=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:p&&!l.pathname?m=`The URL's pathname is empty`:l.hash&&(m=`The URL contains a fragment identifier`),m){let t=SyntaxError(m);if(e._redirects===0)throw t;ne(e,t);return}let h=u?443:80,g=s(16).toString(`base64`),v=u?r.request:i.request,b=new Set,x;if(o.createConnection=o.createConnection||(u?re:P),o.defaultPort=o.defaultPort||h,o.port=l.port||h,o.host=l.hostname.startsWith(`[`)?l.hostname.slice(1,-1):l.hostname,o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":g,Connection:`Upgrade`,Upgrade:`websocket`},o.path=l.pathname+l.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&(x=new f(o.perMessageDeflate===!0?{}:o.perMessageDeflate,!1,o.maxPayload),o.headers[`Sec-WebSocket-Extensions`]=D({[f.extensionName]:x.offer()})),n.length){for(let e of n){if(typeof e!=`string`||!ee.test(e)||b.has(e))throw SyntaxError(`An invalid or duplicated subprotocol was specified`);b.add(e)}o.headers[`Sec-WebSocket-Protocol`]=n.join(`,`)}if(o.origin&&(o.protocolVersion<13?o.headers[`Sec-WebSocket-Origin`]=o.origin:o.headers.Origin=o.origin),(l.username||l.password)&&(o.auth=`${l.username}:${l.password}`),p){let e=o.path.split(`:`);o.socketPath=e[0],o.path=e[1]}let S;if(o.followRedirects){if(e._redirects===0){e._originalIpc=p,e._originalSecure=u,e._originalHostOrSocketPath=p?o.socketPath:l.host;let t=a&&a.headers;if(a={...a,headers:{}},t)for(let[e,n]of Object.entries(t))a.headers[e.toLowerCase()]=n}else if(e.listenerCount(`redirect`)===0){let t=p?e._originalIpc?o.socketPath===e._originalHostOrSocketPath:!1:e._originalIpc?!1:l.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!u)&&(delete o.headers.authorization,delete o.headers.cookie,t||delete o.headers.host,o.auth=void 0)}o.auth&&!a.headers.authorization&&(a.headers.authorization=`Basic `+Buffer.from(o.auth).toString(`base64`)),S=e._req=v(o),e._redirects&&e.emit(`redirect`,e.url,S)}else S=e._req=v(o);o.timeout&&S.on(`timeout`,()=>{F(e,S,`Opening handshake has timed out`)}),S.on(`error`,t=>{S===null||S[A]||(S=e._req=null,ne(e,t))}),S.on(`response`,r=>{let i=r.headers.location,s=r.statusCode;if(i&&o.followRedirects&&s>=300&&s<400){if(++e._redirects>o.maxRedirects){F(e,S,`Maximum redirects exceeded`);return}S.abort();let r;try{r=new d(i,t)}catch{ne(e,SyntaxError(`Invalid URL: ${i}`));return}te(e,r,n,a)}else e.emit(`unexpected-response`,S,r)||F(e,S,`Unexpected server response: ${r.statusCode}`)}),S.on(`upgrade`,(t,n,r)=>{if(e.emit(`upgrade`,t),e.readyState!==N.CONNECTING)return;S=e._req=null;let i=t.headers.upgrade;if(i===void 0||i.toLowerCase()!==`websocket`){F(e,n,`Invalid Upgrade header`);return}let a=c(`sha1`).update(g+y).digest(`base64`);if(t.headers[`sec-websocket-accept`]!==a){F(e,n,`Invalid Sec-WebSocket-Accept header`);return}let s=t.headers[`sec-websocket-protocol`],l;if(s===void 0?b.size&&(l=`Server sent no subprotocol`):b.size?b.has(s)||(l=`Server sent an invalid subprotocol`):l=`Server sent a subprotocol but none was requested`,l){F(e,n,l);return}s&&(e._protocol=s);let u=t.headers[`sec-websocket-extensions`];if(u!==void 0){if(!x){F(e,n,`Server sent a Sec-WebSocket-Extensions header but no extension was requested`);return}let t;try{t=O(u)}catch{F(e,n,`Invalid Sec-WebSocket-Extensions header`);return}let r=Object.keys(t);if(r.length!==1||r[0]!==f.extensionName){F(e,n,`Server indicated an extension that was not requested`);return}try{x.accept(t[f.extensionName])}catch{F(e,n,`Invalid Sec-WebSocket-Extensions header`);return}e._extensions[f.extensionName]=x}e.setSocket(n,r,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(S,e):S.end()}function ne(e,t){e._readyState=N.CLOSING,e._errorEmitted=!0,e.emit(`error`,t),e.emitClose()}function P(e){return e.path=e.socketPath,a.connect(e)}function re(e){return e.path=void 0,!e.servername&&e.servername!==``&&(e.servername=a.isIP(e.host)?``:e.host),o.connect(e)}function F(e,t,n){e._readyState=N.CLOSING;let r=Error(n);Error.captureStackTrace(r,F),t.setHeader?(t[A]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(ne,e,r)):(t.destroy(r),t.once(`error`,e.emit.bind(e,`error`)),t.once(`close`,e.emitClose.bind(e)))}function ie(e,t,n){if(t){let n=h(t)?t.size:k(t).length;e._socket?e._sender._bufferedBytes+=n:e._bufferedAmount+=n}if(n){let t=Error(`WebSocket is not open: readyState ${e.readyState} (${M[e.readyState]})`);process.nextTick(n,t)}}function ae(e,t){let n=this[C];n._closeFrameReceived=!0,n._closeMessage=t,n._closeCode=e,n._socket[C]!==void 0&&(n._socket.removeListener(`data`,pe),process.nextTick(ue,n._socket),e===1005?n.close():n.close(e,t))}function I(){let e=this[C];e.isPaused||e._socket.resume()}function oe(e){let t=this[C];t._socket[C]!==void 0&&(t._socket.removeListener(`data`,pe),process.nextTick(ue,t._socket),t.close(e[S])),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e))}function se(){this[C].emitClose()}function L(e,t){this[C].emit(`message`,e,t)}function ce(e){let t=this[C];t._autoPong&&t.pong(e,!this._isServer,w),t.emit(`ping`,e)}function le(e){this[C].emit(`pong`,e)}function ue(e){e.resume()}function R(e){let t=this[C];t.readyState!==N.CLOSED&&(t.readyState===N.OPEN&&(t._readyState=N.CLOSING,de(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e)))}function de(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),e._closeTimeout)}function fe(){let e=this[C];if(this.removeListener(`close`,fe),this.removeListener(`data`,pe),this.removeListener(`end`,me),e._readyState=N.CLOSING,!this._readableState.endEmitted&&!e._closeFrameReceived&&!e._receiver._writableState.errorEmitted&&this._readableState.length!==0){let t=this.read(this._readableState.length);e._receiver.write(t)}e._receiver.end(),this[C]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on(`error`,se),e._receiver.on(`finish`,se))}function pe(e){this[C]._receiver.write(e)||this.pause()}function me(){let e=this[C];e._readyState=N.CLOSING,e._receiver.end(),this.end()}function he(){let e=this[C];this.removeListener(`error`,he),this.on(`error`,w),e&&(e._readyState=N.CLOSING,this.destroy())}})),fv=ev(((e,t)=>{dv();let{Duplex:n}=tv(`stream`);function r(e){e.emit(`close`)}function i(){!this.destroyed&&this._writableState.finished&&this.destroy()}function a(e){this.removeListener(`error`,a),this.destroy(),this.listenerCount(`error`)===0&&this.emit(`error`,e)}function o(e,t){let o=!0,s=new n({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on(`message`,function(t,n){let r=!n&&s._readableState.objectMode?t.toString():t;s.push(r)||e.pause()}),e.once(`error`,function(e){s.destroyed||(o=!1,s.destroy(e))}),e.once(`close`,function(){s.destroyed||s.push(null)}),s._destroy=function(t,n){if(e.readyState===e.CLOSED){n(t),process.nextTick(r,s);return}let i=!1;e.once(`error`,function(e){i=!0,n(e)}),e.once(`close`,function(){i||n(t),process.nextTick(r,s)}),o&&e.terminate()},s._final=function(t){if(e.readyState===e.CONNECTING){e.once(`open`,function(){s._final(t)});return}e._socket!==null&&(e._socket._writableState.finished?(t(),s._readableState.endEmitted&&s.destroy()):(e._socket.once(`finish`,function(){t()}),e.close()))},s._read=function(){e.isPaused&&e.resume()},s._write=function(t,n,r){if(e.readyState===e.CONNECTING){e.once(`open`,function(){s._write(t,n,r)});return}e.send(t,r)},s.on(`end`,i),s.on(`error`,a),s}t.exports=o})),pv=ev(((e,t)=>{let{tokenChars:n}=ov();function r(e){let t=new Set,r=-1,i=-1,a=0;for(;a<e.length;a++){let o=e.charCodeAt(a);if(i===-1&&n[o]===1)r===-1&&(r=a);else if(a!==0&&(o===32||o===9))i===-1&&r!==-1&&(i=a);else if(o===44){if(r===-1)throw SyntaxError(`Unexpected character at index ${a}`);i===-1&&(i=a);let n=e.slice(r,i);if(t.has(n))throw SyntaxError(`The "${n}" subprotocol is duplicated`);t.add(n),r=i=-1}else throw SyntaxError(`Unexpected character at index ${a}`)}if(r===-1||i!==-1)throw SyntaxError(`Unexpected end of input`);let o=e.slice(r,a);if(t.has(o))throw SyntaxError(`The "${o}" subprotocol is duplicated`);return t.add(o),t}t.exports={parse:r}})),mv=ev(((e,t)=>{let n=tv(`events`),r=tv(`http`),{Duplex:i}=tv(`stream`),{createHash:a}=tv(`crypto`),o=uv(),s=av(),c=pv(),l=dv(),{CLOSE_TIMEOUT:u,GUID:d,kWebSocket:f}=nv(),p=/^[+/0-9A-Za-z]{22}==$/;t.exports=class extends n{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:u,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:l,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw TypeError(`One and only one of the "port", "server", or "noServer" options must be specified`);if(e.port==null?e.server&&(this._server=e.server):(this._server=r.createServer((e,t)=>{let n=r.STATUS_CODES[426];t.writeHead(426,{"Content-Length":n.length,"Content-Type":`text/plain`}),t.end(n)}),this._server.listen(e.port,e.host,e.backlog,t)),this._server){let e=this.emit.bind(this,`connection`);this._removeListeners=m(this._server,{listening:this.emit.bind(this,`listening`),error:this.emit.bind(this,`error`),upgrade:(t,n,r)=>{this.handleUpgrade(t,n,r,e)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=0}address(){if(this.options.noServer)throw Error(`The server is operating in "noServer" mode`);return this._server?this._server.address():null}close(e){if(this._state===2){e&&this.once(`close`,()=>{e(Error(`The server is not running`))}),process.nextTick(h,this);return}if(e&&this.once(`close`,e),this._state!==1)if(this._state=1,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients&&this.clients.size?this._shouldEmitClose=!0:process.nextTick(h,this);else{let e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close(()=>{h(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf(`?`);if((t===-1?e.url:e.url.slice(0,t))!==this.options.path)return!1}return!0}handleUpgrade(e,t,n,r){t.on(`error`,g);let i=e.headers[`sec-websocket-key`],a=e.headers.upgrade,l=+e.headers[`sec-websocket-version`];if(e.method!==`GET`){v(this,e,t,405,`Invalid HTTP method`);return}if(a===void 0||a.toLowerCase()!==`websocket`){v(this,e,t,400,`Invalid Upgrade header`);return}if(i===void 0||!p.test(i)){v(this,e,t,400,`Missing or invalid Sec-WebSocket-Key header`);return}if(l!==13&&l!==8){v(this,e,t,400,`Missing or invalid Sec-WebSocket-Version header`,{"Sec-WebSocket-Version":`13, 8`});return}if(!this.shouldHandle(e)){_(t,400);return}let u=e.headers[`sec-websocket-protocol`],d=new Set;if(u!==void 0)try{d=c.parse(u)}catch{v(this,e,t,400,`Invalid Sec-WebSocket-Protocol header`);return}let f=e.headers[`sec-websocket-extensions`],m={};if(this.options.perMessageDeflate&&f!==void 0){let n=new s(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let e=o.parse(f);e[s.extensionName]&&(n.accept(e[s.extensionName]),m[s.extensionName]=n)}catch{v(this,e,t,400,`Invalid or unacceptable Sec-WebSocket-Extensions header`);return}}if(this.options.verifyClient){let a={origin:e.headers[`${l===8?`sec-websocket-origin`:`origin`}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(a,(a,o,s,c)=>{if(!a)return _(t,o||401,s,c);this.completeUpgrade(m,i,d,e,t,n,r)});return}if(!this.options.verifyClient(a))return _(t,401)}this.completeUpgrade(m,i,d,e,t,n,r)}completeUpgrade(e,t,n,r,i,c,l){if(!i.readable||!i.writable)return i.destroy();if(i[f])throw Error(`server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration`);if(this._state>0)return _(i,503);let u=[`HTTP/1.1 101 Switching Protocols`,`Upgrade: websocket`,`Connection: Upgrade`,`Sec-WebSocket-Accept: ${a(`sha1`).update(t+d).digest(`base64`)}`],p=new this.options.WebSocket(null,void 0,this.options);if(n.size){let e=this.options.handleProtocols?this.options.handleProtocols(n,r):n.values().next().value;e&&(u.push(`Sec-WebSocket-Protocol: ${e}`),p._protocol=e)}if(e[s.extensionName]){let t=e[s.extensionName].params,n=o.format({[s.extensionName]:[t]});u.push(`Sec-WebSocket-Extensions: ${n}`),p._extensions=e}this.emit(`headers`,u,r),i.write(u.concat(`\r
77
77
  `).join(`\r
78
78
  `)),i.removeListener(`error`,g),p.setSocket(i,c,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(p),p.on(`close`,()=>{this.clients.delete(p),this._shouldEmitClose&&!this.clients.size&&process.nextTick(h,this)})),l(p,r)}};function m(e,t){for(let n of Object.keys(t))e.on(n,t[n]);return function(){for(let n of Object.keys(t))e.removeListener(n,t[n])}}function h(e){e._state=2,e.emit(`close`)}function g(){this.destroy()}function _(e,t,n,i){n||=r.STATUS_CODES[t],i={Connection:`close`,"Content-Type":`text/html`,"Content-Length":Buffer.byteLength(n),...i},e.once(`finish`,e.destroy),e.end(`HTTP/1.1 ${t} ${r.STATUS_CODES[t]}\r\n`+Object.keys(i).map(e=>`${e}: ${i[e]}`).join(`\r
79
79
  `)+`\r
@@ -90,4 +90,4 @@ caused by: `+i(o,t)):a},a=e=>i(e,new Set),o=(e,t,i)=>{if(!n(e))return``;let a=i?
90
90
  `).map(e=>e.trim()).filter(Boolean);return n.length===0?!0:(this.error=`External changes pending: ${n.slice(0,3).join(`, `)}${n.length>3?`, +${n.length-3} more`:``}`,this.pausedReason=`external-changes-pending`,this.consecutiveFailures=0,this.transitionTo(`idle`),this.scheduleSaveState(),$.warn({files:n},`[sync] paused — non-content tracked files dirty`),!1)}gatherContentFilesSync(){let e=[],t=n=>{let r;try{r=de(n,{withFileTypes:!0})}catch{return}for(let i of r){let r=Ce(n,i.name);if(i.isDirectory()){if(i.name===`node_modules`||i.name===`.git`||i.name.startsWith(`.`)&&i.name!==`.open-knowledge`)continue;t(r)}else if(i.isFile()){let t=B(this.contentDir,r);if(!t.startsWith(`..`)&&!this.contentFilter.isExcluded(t)){let n=B(this.projectDir,r);e.push({contentRelPath:t,projectRelPath:n})}}}};return L(this.contentDir)&&t(this.contentDir),e}buildCommitMessage(e){return e.length===0?`Auto-save: changes saved`:e.length<=3?`Auto-save: Updated ${e.join(`, `)}`:`Auto-save: ${e.length} files changed`}async handleMergeConflict(){let e=I(this.projectDir,{credentialArgs:this.credentialArgs}),t=[];try{let n=(await e.git.raw([`diff`,`--name-only`,`--diff-filter=U`])).trim();t=n?n.split(`
91
91
  `).map(e=>e.trim()).filter(Boolean):[]}catch(t){$.error({err:t},`[sync] failed to list conflicted files — aborting merge to avoid committing unresolved state`);try{await e.git.raw([`merge`,`--abort`])}catch(e){$.warn({err:e},`[sync] git merge --abort failed during cleanup`)}this.error=`Failed to detect conflict files — merge aborted`,this.pausedReason=void 0,this.transitionTo(`idle`);return}let n=[],r=[];for(let e of t){let t=Ce(this.projectDir,e),i=B(this.contentDir,t);!i.startsWith(`..`)&&!this.contentFilter.isExcluded(i)?n.push(e):r.push(e)}for(let t of r)try{await e.git.raw([`checkout`,`--theirs`,`--`,t]),await e.git.raw([`add`,`--`,t]),$.info({file:t},`[sync] auto-resolved non-content conflict with theirs`)}catch(e){$.warn({err:e,file:t},`[sync] auto-resolve failed — escalating to content conflict`),n.push(t)}if(n.length>0){for(let e of n)this.conflictStore.addConflict({file:e,detectedAt:new Date().toISOString()});this.conflictCount=this.conflictStore.count(),this.pullTimer!==null&&(clearTimeout(this.pullTimer),this.pullTimer=null),this.pushTimer!==null&&(clearTimeout(this.pushTimer),this.pushTimer=null),this.transitionTo(`conflict`),$.warn({files:n},`[sync] content conflicts — sync paused until resolved`)}else try{await e.git.raw([`commit`,`--no-edit`]),this.lastSyncUtc=new Date().toISOString(),this.behind=0,this.transitionTo(`idle`),$.info({},`[sync] all conflicts auto-resolved — merge committed`)}catch(t){$.warn({err:t},`[sync] failed to commit after auto-resolving conflicts — aborting merge`);try{await e.git.raw([`merge`,`--abort`])}catch(e){$.warn({err:e},`[sync] git merge --abort failed during cleanup`)}this.transitionTo(`idle`)}}async abortMerge(){let e=I(this.projectDir,{credentialArgs:this.credentialArgs});try{await e.git.raw([`merge`,`--abort`]),$.info({},`[sync] merge aborted`)}catch(e){$.warn({err:e},`[sync] git merge --abort failed — conflicts.json still cleared`)}this.conflictStore.clear(),this.conflictCount=0,this.transitionTo(`idle`),this.scheduleSaveState()}handleError(e){this.error=e.message,$.warn({class:e.class,subclass:e.subclass,retryable:e.retryable,rawStderr:e.rawStderr},`[sync-error] ${e.message}`),e.class===`auth`?(this.transitionTo(`auth-error`),this.pausedReason=`auth-error`):e.class===`semantic`&&e.subclass===`protected-branch`?(this.syncEnabled=!1,this.transitionTo(`disabled`),this.pausedReason=`protected-branch`):e.class===`local`&&e.subclass===`dirty-tree`?(this.consecutiveFailures++,this.transitionTo(`idle`),this.pausedReason=`dirty-tree`,this.schedulePush(0)):e.retryable?(this.consecutiveFailures++,this.transitionTo(`offline`)):(this.consecutiveFailures++,this.transitionTo(`idle`))}transitionTo(e){if(this.state===e)return;let t=this.state;this.state=e,$.info({from:t,to:e},`[sync] state: ${t} → ${e}`),this.onStateChange?.(e),this.cc1Broadcaster?.signal(`sync-status`)}scheduleSaveState(){this.stateSaveTimer===null&&(this.stateSaveTimer=setTimeout(()=>{this.stateSaveTimer=null,this.saveStateNow()},5e3))}saveStateNow(){try{let e={version:1,lastSyncUtc:this.lastSyncUtc,lastFetchUtc:this.lastFetchUtc,lastPushedSha:this.lastPushedSha,consecutiveFailures:this.consecutiveFailures,pausedReason:this.pausedReason,pausedSinceUtc:this.pausedReason?new Date().toISOString():void 0,inflightConflicts:this.conflictStore.list().map(e=>e.file),syncEnabled:this.syncEnabled};z(this.statePath,JSON.stringify(e,null,2),`utf-8`)}catch(e){$.warn({err:e},`[sync] failed to persist sync state`)}}loadState(){if(L(this.statePath))try{let e=R(this.statePath,`utf-8`),t=JSON.parse(e);if(t.version!==1)return;this.lastSyncUtc=t.lastSyncUtc??null,this.lastFetchUtc=t.lastFetchUtc??null,this.lastPushedSha=t.lastPushedSha??null,this.consecutiveFailures=t.consecutiveFailures??0,this.pausedReason=t.pausedReason,t.syncEnabled!==void 0&&(this.syncEnabled=t.syncEnabled);let n=t.inflightConflicts??[];if(n.length>0){for(let e of n)this.conflictStore.list().some(t=>t.file===e)||this.conflictStore.addConflict({file:e,detectedAt:new Date().toISOString()});this.conflictCount=this.conflictStore.count()}}catch(e){$.warn({err:e},`[sync] failed to load sync state`)}}};function uy(e){let{contentDir:t,projectDir:n=t,quiet:i=!0,debounce:a=2e3,maxDebounce:o=1e4,gitEnabled:s=!0,commitDebounceMs:c=3e4,wipRef:l=`refs/wip/main`,enableTestRoutes:d=!1,shadowRepo:f,contentRoot:p,includePatterns:m=[`**/*.md`,`**/*.mdx`],excludePatterns:h=[],destroyTimeoutMs:g=1e4,localOpCliArgs:_}=e,v=Mc(`server`),y=V(t,`.open-knowledge`);ne(y,{port:e.port??0,worktreeRoot:n});let b,x,S,C,w,T,E=null,D=null;function O(e){E?.signal(e)}try{b=yv({projectDir:n,contentDir:t,includePatterns:m,excludePatterns:h}),x=new ap({projectDir:n,contentDir:t,contentFilter:b}),S={current:f},C=Wp({contentDir:t,projectDir:n,gitEnabled:s,commitDebounceMs:c,wipRef:l,shadowRef:S,contentRoot:p,backlinkIndex:x,getCurrentBranch:()=>ae?.getLastKnownBranch()??null}),w=new $_({quiet:i,debounce:a,maxDebounce:o,extensions:[C.extension]}),E=new $c(w),D=new hv(w),T=new ol(w);let r=Mv({backlinkIndex:x,signalChannel:O});w.configuration.extensions.push(r);let u=$h({hocuspocus:w,sessionManager:T,contentDir:t,getFileIndex:()=>ie?ie.getFileIndex():new Map,getAliasMap:()=>ie?ie.getAliasMap():new Map,enableTestRoutes:d,shadowRef:S,flushGitCommit:()=>C.flushPendingGitCommit(),getCurrentBranch:()=>ae?.getLastKnownBranch()??null,contentRoot:p,backlinkIndex:x,signalChannel:O,agentFocusBroadcaster:D,onAgentWrite:e.onAgentWrite,getSyncEngine:()=>I,localOpCliArgs:_,projectDir:n});w.configuration.extensions.push(u),w.configuration.extensions.push(Lv({mdManager:el,schema:tl,shadowRef:S,contentRoot:p,getCurrentBranch:()=>ae?.getLastKnownBranch()??null}))}catch(e){throw N(y),e}let k=null;function A(e,t){let n=V(e,`rescue`),r=V(n,`${t}${Af(t)}`);return r.startsWith(`${n}/`)?r:null}function j(e){let t=w.documents.get(e);if(!t)return null;let n=fs(t.getXmlFragment(`default`),tl).toJSON(),r=el.serialize(n),i=t.getMap(`metadata`).get(`frontmatter`);return u(typeof i==`string`?i:``,r)}let M=(e,t)=>wv(w,e,t);function ee(e){return e.kind===`rename`?e.newDocName:e.docName}async function te(e){try{switch(e.kind){case`create`:v.info({docName:e.docName},`[reconcile] create: ${e.docName}`),x.updateDocumentFromMarkdown(e.docName,e.content),x.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist create for ${e.docName}:`,t)}),O(`files`),O(`backlinks`),O(`graph`);break;case`update`:{let{docName:t,content:n}=e,r=w.documents.get(t);if(!r){x.updateDocumentFromMarkdown(t,n),x.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist closed-doc update for ${t}:`,e)}),O(`backlinks`),O(`graph`);return}let i=Rp(t)??``,a=j(t)??i,o=Jp({docName:t,base:i,ours:a,theirs:n}),s=nm(i).slice(0,6),c=nm(a).slice(0,6),l=nm(n).slice(0,6);switch(v.info({docName:t,base:s,ours:c,theirs:l,result:o.kind},`[reconcile] ${t} base=${s} ours=${c} theirs=${l} result=${o.kind}`),o.kind){case`noop`:x.updateDocumentFromMarkdown(t,n),x.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist noop update for ${t}:`,e)}),O(`backlinks`),O(`graph`);break;case`clean`:try{M(t,o.newContent),zp(t,o.newContent),Nc(),x.updateDocumentFromMarkdown(t,n),x.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist clean update for ${t}:`,e)}),O(`backlinks`),O(`graph`)}catch(e){v.error({err:e,docName:t},`[reconcile] failed to apply clean content to Y.Doc for ${t}`),zp(t,n)}break;case`merged`:try{M(t,o.newContent),zp(t,o.newContent),Nc(),x.updateDocumentFromMarkdown(t,n),x.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist merged update for ${t}:`,e)}),O(`backlinks`),O(`graph`)}catch(e){v.error({err:e,docName:t},`[reconcile] failed to apply merged content to Y.Doc for ${t}`),zp(t,n)}break;case`conflicts`:try{M(t,o.newContent),zp(t,o.newContent),Nc(),Pc(),x.updateDocumentFromMarkdown(t,n),x.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist conflict update for ${t}:`,e)}),O(`backlinks`),O(`graph`)}catch(e){v.error({err:e,docName:t},`[reconcile] failed to apply conflict content to Y.Doc for ${t}`),zp(t,n)}break;case`refused`:{Pc();let e=r.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,o.reason);break}}break}case`delete`:{let{docName:t}=e,n=w.documents.get(t);if(!n){x.deleteDocument(t),x.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist closed-doc delete for ${t}:`,e)}),O(`files`),O(`backlinks`),O(`graph`);return}let r=Rp(t)??``,i=j(t)??``,a=i!==r;if(a&&S.current){let e=S.current,n=ae?.getLastKnownBranch()??`main`;queueMicrotask(()=>{Ep(e,p??``,{kind:`external-change-rescue`,docName:t,contents:i,label:`External change recovered @ ${new Date().toISOString()}`,branch:n,metadata:{incomingDiskSha:``}}).then(()=>{Lc(),v.info({docName:t},`[reconcile] rescue checkpoint saved (delete): ${t}`)}).catch(e=>{v.error({docName:t,err:e},`[reconcile] rescue checkpoint write failed: ${t}`)})})}n.getMap(`lifecycle`).set(`status`,`deleted-upstream`),Bp(t),x.deleteDocument(t),x.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist delete for ${t}:`,e)}),v.info({docName:t,isDirty:a},`[reconcile] delete: ${t} (dirty=${a})`),w.closeConnections(t),await w.unloadDocument(n),O(`files`),O(`backlinks`),O(`graph`);break}case`rename`:{let{oldDocName:t,newDocName:n,content:r}=e,i=w.documents.get(t);if(Bp(t),zp(n,r),x.renameDocument(t,n,r),x.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist rename for ${t} -> ${n}:`,e)}),i){let e=i.getMap(`lifecycle`);e.set(`status`,`renamed`),e.set(`newPath`,n)}v.info({oldDocName:t,newDocName:n},`[reconcile] rename: ${t} → ${n}`),O(`files`),O(`backlinks`),O(`graph`);break}case`conflict`:{let{docName:t}=e,n=w.documents.get(t);if(!n)return;let r=n.getMap(`lifecycle`);r.set(`status`,`conflict`),r.set(`reason`,`conflict-markers`),v.info({docName:t},`[reconcile] conflict markers detected: ${t}`);break}}}catch(t){v.error({err:t,kind:e.kind,docName:ee(e)},`[reconcile] failed to handle ${e.kind} for ${ee(e)}`)}}let P=[];async function re(e){if(Up()){P.push(e);return}await te(e)}async function F(){let e=P.splice(0,P.length);for(let t of e)await te(t)}let ie=null,ae=null,I=null,oe=null;async function se(e){if(w.documents.size===0)return;let t=!1,n=new Promise(e=>{w.configuration.extensions.push({async afterUnloadDocument({instance:n}){!t&&n.getDocumentsCount()===0&&(t=!0,e())}})}),r=Array.from(w.documents.keys());w.closeConnections(),w.flushPendingStores();let i,a=new Promise((n,a)=>{i=setTimeout(()=>{t=!0;let n=Array.from(w.documents.keys()),i=[],o=[];if(S.current){for(let e of n)if(!q(e))try{let t=j(e);if(t===null){v.warn({docName:e},`[rescue] skipping ${e} — document dropped from map mid-rescue`),o.push(e);continue}let n=A(S.current.gitDir,e);if(!n){v.warn({docName:e,gitDir:S.current.gitDir},`[rescue] path-traversal guard rejected docName: ${e}`),o.push(e);continue}le(xe(n),{recursive:!0}),z(n,t,`utf-8`),Lc(),i.push(e),v.info({docName:e},`[rescue] rescue buffer saved on flush timeout: ${e}`)}catch(t){o.push(e),v.error({err:t,docName:e},`[rescue] failed to write rescue buffer for ${e}`)}}else v.warn({stillLoadedCount:n.length},`[rescue] shadow repo unavailable at flush timeout — ${n.length} doc(s) will be lost: [${n.join(`, `)}]`),o.push(...n);let s=i.length>0||o.length>0?` — rescued [${i.join(`, `)}]${o.length>0?`, lost [${o.join(`, `)}]`:``}`:``;a(Error(`flushAllStoresAndWait timeout after ${e}ms — ${n.length}/${r.length} docs did not unload: [${n.join(`, `)}]${s}`))},e)});try{await Promise.race([n,a])}finally{i!==void 0&&clearTimeout(i)}}async function ce(){return oe||(oe=(async()=>{let e=Date.now(),t=[],r,i=await Promise.race([fe.then(()=>`completed`,e=>(v.debug({err:e},`[server] init incomplete during shutdown`),`failed`)),new Promise(e=>{r=setTimeout(()=>e(`timeout`),5e3)})]);r!==void 0&&clearTimeout(r),i===`timeout`&&v.warn({},`[server] init did not complete within 5s during shutdown`);let a=w.documents.size;try{try{try{ae&&=(await ae.unsubscribe(),null),ie&&=(await ie.unsubscribe(),null)}catch(e){t.push({phase:`watcher-unsubscribe`,error:e instanceof Error?e.message:String(e)}),v.error({err:e},`[server] shutdown phase-1 watcher unsubscribe failed`)}try{E?.destroy(),k&&=(await k.disconnect(),null)}catch(e){t.push({phase:`cc1-teardown`,error:e instanceof Error?e.message:String(e)}),v.error({err:e},`[server] shutdown phase-1b CC1 teardown failed`)}try{await T.closeAll()}catch(e){t.push({phase:`agent-session-drain`,error:e instanceof Error?e.message:String(e)}),v.error({err:e},`[server] shutdown phase-2 agent session drain failed`)}try{await se(g)}catch(e){t.push({phase:`flush-all-stores`,error:e instanceof Error?e.message:String(e)}),v.error({err:e},`[server] shutdown phase-3 flush failed`)}let e;try{await Promise.race([(async()=>{await C.flushPendingGitCommit(),await C.waitForPendingCommits()})(),new Promise((t,n)=>{e=setTimeout(()=>n(Error(`L2 git flush timeout`)),g)})])}catch(e){t.push({phase:`git-commit-flush`,error:e instanceof Error?e.message:String(e)}),v.error({err:e},`[server] shutdown phase-4 git commit flush failed`)}finally{e!==void 0&&clearTimeout(e)}try{I&&=(await I.destroy(),null)}catch(e){t.push({phase:`sync-engine-stop`,error:e instanceof Error?e.message:String(e)}),v.error({err:e},`[server] shutdown sync-engine-stop failed`)}}finally{if(S.current){try{let e=(await Ne({baseDir:n,timeout:{block:5e3}}).revparse(`HEAD`)).trim();e&&z(V(S.current.gitDir,`last-known-head`),e,`utf-8`)}catch{}try{bp(S.current)}catch(e){t.push({phase:`shadow-repo-release`,error:e instanceof Error?e.message:String(e)}),v.error({err:e},`[server] shutdown phase-5 destroyShadowRepo failed`)}}let r=Date.now()-e;t.length===0?v.info({documentCount:a,durationMs:r},`[server] shutdown flushed ${a} documents in ${r}ms`):v.warn({documentCount:a,durationMs:r,phaseErrors:t},`[server] shutdown flushed ${a} documents in ${r}ms with ${t.length} phase error(s)`)}}finally{try{N(y)}catch(e){t.push({phase:`server-lock-release`,error:e instanceof Error?e.message:String(e)}),v.error({err:e},`[server] shutdown phase-6 releaseServerLock failed`)}}})(),oe)}let ue=[];async function de(){if(!S.current)try{S.current=await yp(n),v.info({gitDir:S.current.gitDir},`[server] shadow repo initialized at ${S.current.gitDir}`)}catch(e){v.error({err:e},`[server] shadow repo init failed`),ue.push(`shadow-repo`)}if(S.current)try{await vp(S.current).raw(`rev-parse`,`--git-dir`)}catch(e){let t=e instanceof Error?e.message:String(e);if(t.includes(`not a git repository`)||t.includes(`invalid object`)){v.warn({},`[server] shadow repo appears corrupted — reinitializing`);try{S.current=await yp(n)}catch(e){v.error({err:e},`[server] shadow repo reinit failed`),S.current=void 0,ue.includes(`shadow-repo`)||ue.push(`shadow-repo`)}}else v.error({err:e},`[server] shadow repo check failed (transient?)`)}if(S.current)try{let e=V(S.current.gitDir,`last-known-head`),t=null;try{t=R(e,`utf-8`).trim()||null}catch{}let r=null;try{r=(await Ne({baseDir:n,timeout:{block:1e4}}).revparse(`HEAD`)).trim()||null}catch{}if(r!==null){if(r!==t){let e=`main`;try{let t=(await Ne({baseDir:n,timeout:{block:1e4}}).raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();t&&t!==`HEAD`&&(e=t)}catch{}v.info({lastKnownHead:t,currentHead:r,branch:e},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${r}, action=import`);try{await Cp(S.current,p??``,t,r,e),Ic()}catch(e){v.warn({err:e},`[head-drift] commitUpstreamImport failed — continuing`)}}else v.info({currentHead:r},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${r}, action=noop`);try{z(e,r,`utf-8`)}catch(e){v.warn({err:e},`[head-drift] failed to write last-known-head`)}}}catch(e){v.warn({err:e},`[head-drift] check failed — continuing`)}try{let e=zm(t);e.recovered&&e.journal&&v.warn({sourceDocName:e.journal.sourceDocName,destinationDocName:e.journal.destinationDocName,restoredDocNames:e.restoredDocNames},`[managed-rename] recovered pending rename ${e.journal.sourceDocName} -> ${e.journal.destinationDocName}`)}catch(e){v.error({err:e},`[server] managed rename recovery failed`),ue.push(`managed-rename-recovery`)}try{k=await w.openDirectConnection(r)}catch(e){v.error({err:e},`[server] failed to open __system__ direct connection — CC1 push disabled`),ue.push(`cc1-push`)}try{ie=await hm(t,re,b),x.rebuildFromDisk(Lp()),x.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist startup cache for ${Lp()}:`,e)})}catch(e){v.error({err:e},`[server] disk bridge watcher failed to start`),ue.push(`file-watcher`)}try{ae=await kv(n,async({trigger:e})=>{if(v.info({trigger:e},`[batch] begin trigger=${e}`),Fc(),w.flushPendingStores(),await C.flushPendingGitCommit(),S.current){let e=Lp(),t=[];for(let[e]of w.documents){if(q(e))continue;let n=j(e);if(n===null)continue;let r=Rp(e)??n;t.push({docName:e,markdown:n,diskSnapshot:r})}if(t.length>0)try{let n=await Op(S.current,e,`server`,t);n&&(zc(),v.info({count:t.length,branch:e,sha:n.slice(0,8)},`[shadow] parked ${t.length} docs on ${e} → ${n.slice(0,8)}`))}catch(e){v.error({err:e},`[shadow] park failed`)}}Hp(!0)},async e=>{let n=P.length,r=e.newBranch??`main`;if(Hp(!1),v.info({kind:e.batchKind,headMoved:e.headMoved,docs:n,timeout:!!e.timeout},`[batch] end kind=${e.batchKind} headMoved=${e.headMoved} docs=${n}${e.timeout?` timeout`:``}`),e.batchKind===`within-branch`)await F();else{Rc(),P.splice(0,P.length),Ip(r),x.switchBranch(r);for(let[e,n]of w.documents)if(!q(e))try{let i=Mp(e,t);if(!L(i)){let t=Rp(e)??``,i=j(e)??``;if(i!==t&&S.current){let t=S.current;queueMicrotask(()=>{Ep(t,p??``,{kind:`external-change-rescue`,docName:e,contents:i,label:`External change recovered @ ${new Date().toISOString()}`,branch:r,metadata:{incomingDiskSha:``}}).then(()=>{Lc(),v.info({docName:e},`[reconcile] rescue checkpoint saved on branch switch: ${e}`)}).catch(t=>{v.error({docName:e,err:t},`[reconcile] rescue checkpoint write failed: ${e}`)})})}n.getMap(`lifecycle`).set(`status`,`deleted-upstream`),v.info({docName:e,branch:r},`[branch-switch] tombstone: ${e} (not on ${r})`);continue}let a=R(i,`utf-8`);M(e,a),zp(e,a),v.info({docName:e},`[branch-switch] reset: ${e}`)}catch(t){v.error({err:t,docName:e},`[branch-switch] failed to reset ${e}`)}if(v.info({branch:r,docCount:w.documents.size},`[branch-switch] loaded branch ${r} (${w.documents.size} docs)`),x.rebuildFromDisk(r),x.saveToDisk(r).catch(e=>{console.warn(`[backlinks] Failed to persist branch cache for ${r}:`,e)}),S.current&&e.batchKind===`cross-branch`){let e=0;for(let[t]of w.documents)if(!q(t))try{let n=await kp(S.current,r,`server`,t);if(!n||n.markdown===n.diskSnapshot)continue;let i=Rp(t);if(!i)continue;let a=Jp({docName:t,base:n.diskSnapshot,ours:n.markdown,theirs:i});switch(a.kind){case`merged`:case`clean`:M(t,a.newContent),zp(t,a.newContent),e++;break;case`conflicts`:M(t,a.newContent),zp(t,a.newContent),Pc(),e++;break;case`noop`:case`refused`:break}}catch(e){v.error({err:e,docName:t},`[branch-switch] restore WIP failed for ${t}`)}e>0&&v.info({count:e,branch:r},`[branch-switch] restored ${e} parked docs on ${r}`)}if(e.oldBranch?.startsWith(`detached-`)&&S.current)try{let t=vp(S.current),n=(await t.raw(`for-each-ref`,`refs/wip/${e.oldBranch}/`,`--format=%(refname)`)).trim();if(n){for(let e of n.split(`
92
92
  `))e&&await t.raw(`update-ref`,`-d`,e);v.info({context:e.oldBranch},`[branch-switch] cleaned up detached context ${e.oldBranch}`)}}catch(e){v.error({err:e},`[branch-switch] detached cleanup failed`)}}if(e.headMoved&&e.newHead&&S.current&&n>0){let t=p??`content`;try{let n=await Cp(S.current,t,e.oldHead,e.newHead,r);Ic(),v.info({oldHead:e.oldHead?.slice(0,8)??`null`,newHead:e.newHead.slice(0,8),sha:n.slice(0,8)},`[shadow] upstream-import from ${e.oldHead?.slice(0,8)??`null`}..${e.newHead.slice(0,8)} → ${n.slice(0,8)}`)}catch(e){v.error({err:e},`[shadow] upstream-import failed`)}}})}catch(e){v.error({err:e},`[server] HEAD watcher failed to start`),ue.push(`head-watcher`)}let e=_?.[0]??`open-knowledge`,i=[`-c`,`credential.helper=!${_&&_.length>1?_.join(` `):e} auth git-credential`];try{I=new ly({projectDir:n,contentDir:t,contentFilter:b,contentRoot:p,credentialArgs:i,cc1Broadcaster:E,setBatchInProgress:Hp,onStateChange:e=>{v.info({state:e},`[sync] state → ${e}`)}}),await I.start()}catch(e){v.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),I=null}}let fe=de();return{hocuspocus:w,sessionManager:T,cc1Broadcaster:E,agentFocusBroadcaster:D,contentFilter:b,destroy:ce,ready:fe,degraded:ue,lockDir:y,get syncEngine(){return I}}}async function dy(e){let t=e.skipAutoInit??!1,n=e.attachUiSibling??!0,r=e.idleShutdownMs,i=e.log??Mc(`boot`),{createServer:a}=await import(`node:http`),{WebSocketServer:o}=await import(`./wrapper-BK_jpkDm.mjs`),{updateServerLockPort:s}=await import(`./server-lock-CPmOhzSz.mjs`),c=!1;if(!t&&e.autoInitFn)try{c=!!await e.autoInitFn()}catch(e){i.warn({err:e},`autoInitFn failed`)}let l=uy({contentDir:e.contentDir,projectDir:e.projectDir,contentRoot:e.contentRoot,port:e.port,host:e.host,quiet:e.quiet??!1,debounce:e.debounce,maxDebounce:e.maxDebounce,gitEnabled:e.gitEnabled,commitDebounceMs:e.commitDebounceMs,wipRef:e.wipRef,enableTestRoutes:e.enableTestRoutes,shadowRepo:e.shadowRepo,includePatterns:e.includePatterns,excludePatterns:e.excludePatterns,destroyTimeoutMs:e.destroyTimeoutMs,localOpCliArgs:e.localOpCliArgs,onAgentWrite:e.onAgentWrite}),{hocuspocus:u,destroy:d,ready:f,degraded:p,lockDir:m}=l,h=a((e,t)=>{let n=e.url?.split(`?`)[0];if(n?.startsWith(`/api/`)){u.hooks(`onRequest`,{request:e,response:t}).then(()=>{t.writableEnded||t.headersSent||(t.statusCode=404,t.setHeader(`Content-Type`,`application/json`),t.end(JSON.stringify({error:`API route not found`,path:n})))}).catch(e=>{i.error({err:e},`Unhandled onRequest error`),!t.writableEnded&&!t.headersSent?(t.writeHead(500),t.end(`Internal server error`)):t.writableEnded||t.end()});return}t.writeHead(404,{"Content-Type":`application/json`}),t.end(JSON.stringify({error:"Not found. The React UI is served by `ok ui` (default port 3000).",path:n??`/`}))}),g=new o({noServer:!0});g.on(`error`,e=>{i.error({err:e},`WebSocketServer error`)}),h.on(`upgrade`,(e,t,n)=>{if(e.url?.startsWith(`/collab/keepalive`)){t.on(`error`,e=>{Xc(e)||i.error({err:e},`MCP keepalive socket error`)}),g.handleUpgrade(e,t,n,e=>{let t=setInterval(()=>{try{e.ping()}catch{}},3e4);t.unref?.(),e.on(`close`,()=>clearInterval(t)),e.on(`error`,t=>{Xc(t)||i.error({err:t},`MCP keepalive WS error`),e.terminate()})});return}e.url?.startsWith(`/collab`)&&(t.on(`error`,e=>{Xc(e)||i.error({err:e},`Upgrade socket error`)}),g.handleUpgrade(e,t,n,t=>{let n=u.handleConnection(t,e);t.on(`message`,e=>{n.handleMessage((e instanceof ArrayBuffer,new Uint8Array(e)))}),t.on(`close`,(e,t)=>{n.handleClose({code:e,reason:t.toString()})}),t.on(`error`,e=>{Xc(e)||i.error({err:e},`WebSocket error`),t.terminate()})}))});let _=null;r!==null&&(_=eg({httpServer:h,thresholdMs:r??18e5,log:i,onShutdown:(e.idleShutdownHandler??(e=>async()=>{await e()}))(async()=>{await d()})})),await new Promise((t,n)=>{let r=e=>n(e);h.once(`error`,r),h.listen(e.port,e.host,()=>{h.removeListener(`error`,r),t()})});let v=h.address(),y=typeof v==`object`&&v?v.port:e.port??0;if(s(m,y),n&&e.spawnUiSiblingFn)try{await e.spawnUiSiblingFn({lockDir:m,log:i})}catch(e){i.warn({err:e},`spawnUiSiblingFn failed`)}let b=!1;return{httpServer:h,destroy:async()=>{b||(b=!0,_?.detach(),await new Promise(e=>{h.close(()=>e())}),await d())},lockDir:m,contentDir:e.contentDir,port:y,ready:f,degraded:p,didAutoInit:c,serverInstance:l}}export{Zd as $,Jp as A,Ap as B,em as C,Qp as D,om as E,xp as F,mp as G,cp as H,yp as I,yf as J,ap as K,Dp as L,Wp as M,Mp as N,Gp as O,Cp as P,xf as Q,Tp as R,rm as S,hm as T,lp as U,vp as V,up as W,Sf as X,bf as Y,Cf as Z,cm as _,Mv as a,q as at,lm as b,wv as c,Yc as ct,Fh as d,Mc as dt,rl as et,Ph as f,jc as ft,Xm as g,Zm as h,Nv as i,$c as it,qp as j,Kp as k,yv as l,Wc as lt,Uh as m,uy as n,al as nt,Ov as o,Qc as ot,$h as p,$f as q,Lv as r,il as rt,Cv as s,Xc as st,dy as t,ol as tt,eg as u,Ac as ut,nm as v,sm as w,am as x,tm as y,Ep as z};
93
- //# sourceMappingURL=src-BrZIzHKR.mjs.map
93
+ //# sourceMappingURL=src-DcVg7_6f.mjs.map
@@ -1 +1 @@
1
- import"./src-ViJPkmPW.mjs";import{J as e,Q as t,X as n,Y as r,Z as i,dt as a,t as o}from"./src-BrZIzHKR.mjs";import{f as s,r as c}from"./server-lock-B4frNnOB.mjs";export{e as UiLockCollisionError,r as acquireUiLock,o as bootServer,a as getLogger,s as isProcessAlive,c as readServerLock,n as readUiLock,i as releaseUiLock,t as updateUiLockPort};
1
+ import"./src-ViJPkmPW.mjs";import{J as e,Q as t,X as n,Y as r,Z as i,dt as a,t as o}from"./src-DcVg7_6f.mjs";import{f as s,r as c}from"./server-lock-B4frNnOB.mjs";export{e as UiLockCollisionError,r as acquireUiLock,o as bootServer,a as getLogger,s as isProcessAlive,c as readServerLock,n as readUiLock,i as releaseUiLock,t as updateUiLockPort};
@@ -0,0 +1 @@
1
+ import{a as e}from"./start-CNULXoun.mjs";export{e as startCommand};
@@ -1,2 +1,2 @@
1
- import{a as e}from"./constants-D6bAkegd.mjs";import{D as t}from"./src-ViJPkmPW.mjs";import{Command as n}from"commander";import{closeSync as r,existsSync as i,mkdirSync as a,openSync as o}from"node:fs";import{join as s}from"node:path";import{spawn as c}from"node:child_process";function l(){let e=process.execPath,t=process.argv[1];return t?{command:e,prefixArgs:[t]}:(console.warn(`[self-spawn] process.argv[1] is empty — falling back to \`npx @inkeep/open-knowledge\`. This re-introduces the version-drift surface that re-exec was fixing. Observed argv: ${JSON.stringify(process.argv)}`),{command:`npx`,prefixArgs:[`@inkeep/open-knowledge`]})}function u(e){return e.uiLock?e.isAlive(e.uiLock.pid)?{action:`skip`,reason:`alive`,pid:e.uiLock.pid,port:e.uiLock.port}:{action:`spawn`,reason:`stale`,stalePid:e.uiLock.pid}:{action:`spawn`,reason:`absent`}}function d(e){i(e.lockDir)||a(e.lockDir,{recursive:!0});let t=o(s(e.lockDir,`last-spawn-error.log`),`w`),n=e.spawn??c,{PORT:u,...d}=process.env,f=l();try{let r=n(f.command,[...f.prefixArgs,...e.args??[`ui`]],{detached:!0,stdio:[`ignore`,`ignore`,t],cwd:e.cwd,env:d});return r.unref(),r}finally{try{r(t)}catch{}}}function f(e){let t=e.sigtermGraceMs??1e4,n=e.sigtermPollIntervalMs??200,r=e.sleep??(e=>new Promise(t=>setTimeout(t,e)));return async()=>{try{let i=e.readUiLock();if(i&&e.isAlive(i.pid))try{e.killPid(i.pid,`SIGTERM`),e.log?.info({pid:i.pid,port:i.port},`idle-shutdown: SIGTERM UI sibling`);let a=Date.now()+t;for(;Date.now()<a&&e.isAlive(i.pid);)await r(n);if(e.isAlive(i.pid))try{e.killPid(i.pid,`SIGKILL`),e.log?.warn({pid:i.pid,graceMs:t},`idle-shutdown: SIGTERM grace expired — escalated to SIGKILL`)}catch(t){e.log?.error({pid:i.pid,err:t instanceof Error?t.message:String(t)},`idle-shutdown: SIGKILL failed`)}}catch(t){e.log?.warn({pid:i.pid,err:t instanceof Error?t.message:String(t)},`idle-shutdown: failed to SIGTERM UI sibling`)}}catch(t){e.log?.warn({err:t instanceof Error?t.message:String(t)},`idle-shutdown: UI lookup failed; proceeding with destroy`)}await e.destroy()}}async function p(e){let{config:n,cwd:r}=e,i=e.skipAutoInit??!1,a=e.skipUiAutoSpawn??!1,o=e.idleThresholdMs??18e5,{existsSync:s,mkdirSync:c}=await import(`node:fs`),{resolve:l}=await import(`node:path`),{bootServer:p,getLogger:m,isProcessAlive:h,readUiLock:g}=await import(`./src-DCuvj6a2.mjs`),{resolveContentDir:_}=await import(`./paths-CP2voPwK.mjs`),v=e.log??m(`start`),y=_(n,r);s(y)||(c(y,{recursive:!0}),v.info({contentDir:y},`Created content directory`));let b=!s(l(r,t)),x=i?void 0:async()=>{try{let{initContent:e}=await import(`./init-BY4cw3Zr.mjs`),t=e(r);return b||t.created.length>0}catch(e){return console.warn(`Auto-init failed:`,e instanceof Error?e.message:e),!1}},S=!1,C=l(y,t),w=n.server.openOnAgentEdit?()=>{if(S)return;let e=g(C);if(!e||e.port<=0||!h(e.pid))return;S=!0;let t=`http://localhost:${e.port}`;import(`./open-browser-CfwaLBtR.mjs`).then(({openBrowser:e})=>e(t)).catch(()=>{})}:void 0,T=null,E=await p({contentDir:y,projectDir:r,contentRoot:n.content.dir,port:n.server.port,host:n.server.host,quiet:!1,debounce:n.persistence.debounceMs,maxDebounce:n.persistence.maxDebounceMs,includePatterns:n.content.include,excludePatterns:n.content.exclude,onAgentWrite:w,localOpCliArgs:[process.execPath,process.argv[1]],attachUiSibling:!0,idleShutdownMs:o,skipAutoInit:i,autoInitFn:x,spawnUiSiblingFn:async({lockDir:t})=>{if(T=u({uiLock:g(t),isAlive:h}),T.action===`spawn`&&!a)try{d({lockDir:t,cwd:r,spawn:e.spawn}),v.info({reason:T.reason},`[start] auto-spawned ok ui sibling`)}catch(e){console.warn(`[start] failed to auto-spawn ok ui: ${e instanceof Error?e.message:String(e)}`)}else T.action===`skip`&&v.info({port:T.port,pid:T.pid},`UI already running at port ${T.port}`)},idleShutdownHandler:e=>f({readUiLock:()=>g(E.lockDir),isAlive:h,killPid:(e,t)=>{process.kill(e,t)},destroy:e,log:v}),log:v});return T||={action:`skip`,reason:`alive`,pid:0,port:0},{httpServer:E.httpServer,destroy:E.destroy,lockDir:E.lockDir,contentDir:y,port:E.port,ready:E.ready,degraded:E.degraded,uiSpawnDecision:T,didAutoInit:E.didAutoInit}}function m(r){return new n(`start`).description(`Start the knowledge base collab server`).option(`-p, --port <port>`,`Server port`,void 0).option(`-H, --host <host>`,`Server host`,void 0).option(`--open`,`Open browser after start`).option(`--no-init`,`Skip auto-scaffolding of ${t}/`).action(async n=>{let{renderBanner:i}=await import(`./banner-sRCRfb7A.mjs`),{dim:a,error:o,info:s,warning:c}=await import(`./colors-BNRrOlZZ.mjs`),l=r(),u=process.cwd();n.port!==void 0&&(l.server.port=Number(n.port)),n.host!==void 0&&(l.server.host=n.host);let d;try{d=await p({config:l,cwd:u,skipAutoInit:n.init===!1})}catch(e){console.error(`${o(`Failed to start:`)} ${e instanceof Error?e.stack??e.message:String(e)}`),process.exit(1)}let f=!1,m=async e=>{if(!f){f=!0,console.log(a(`\nShutting down (${e})...`));try{await d.destroy()}catch(e){console.error(`${o(`destroy() failed:`)} ${e instanceof Error?e.stack??e.message:String(e)}`),process.exitCode=1}process.exit(process.exitCode??0)}};process.once(`SIGINT`,()=>{m(`SIGINT`)}),process.once(`SIGTERM`,()=>{m(`SIGTERM`)});let h=`http://${l.server.host}:${d.port}`,g=l.server.host===`0.0.0.0`||l.server.host===`::`?`http://0.0.0.0:${d.port}`:void 0,_=d.uiSpawnDecision,v=_.action===`skip`?_.port:3e3,y=v>0?`http://${l.server.host}:${v}`:h;console.log(i({name:`open-knowledge`,version:e,localUrl:y,apiUrl:y===h?void 0:h,networkUrl:g})),d.didAutoInit&&(console.log(` ${s(`✓`)} Scaffolded ${t}/ (first run)`),console.log(` ${a("Tip: Run `open-knowledge init` to register MCP tools for Claude Code")}\n`));let b={"shadow-repo":`Version history and branch-switch safety unavailable`,"file-watcher":`External file changes will not sync to the editor`,"head-watcher":`Git branch switches may cause document inconsistency`};d.ready.then(async()=>{if(d.degraded.length>0){console.log();for(let e of d.degraded){let t=b[e]??`${e} (check server logs for details)`;console.warn(` ${c(`⚠`)} ${c(e)}: ${a(t)}`)}console.log()}if(d.didAutoInit)try{let{previewContent:e,formatPreviewBlock:t}=await import(`./preview-rUPh_bsX.mjs`),n=e({projectDir:u,contentDir:d.contentDir,include:l.content.include,exclude:l.content.exclude});console.log(`\n${t(n,u)}\n`)}catch(e){console.warn(`Content preview unavailable: ${e instanceof Error?e.message:String(e)}`)}if(n.open){let{openBrowser:e}=await import(`./open-browser-CfwaLBtR.mjs`);e(y)}}).catch(e=>{console.error(` ${o(`Server initialization failed:`)} ${e instanceof Error?e.message:String(e)}`)})})}export{m as a,d as i,f as n,l as o,u as r,p as t};
2
- //# sourceMappingURL=start-BevXBjPW.mjs.map
1
+ import{a as e}from"./constants-BLW6shM6.mjs";import{D as t}from"./src-ViJPkmPW.mjs";import{Command as n}from"commander";import{closeSync as r,existsSync as i,mkdirSync as a,openSync as o}from"node:fs";import{join as s}from"node:path";import{spawn as c}from"node:child_process";function l(){let e=process.execPath,t=process.argv[1];return t?{command:e,prefixArgs:[t]}:(console.warn(`[self-spawn] process.argv[1] is empty — falling back to \`npx @inkeep/open-knowledge\`. This re-introduces the version-drift surface that re-exec was fixing. Observed argv: ${JSON.stringify(process.argv)}`),{command:`npx`,prefixArgs:[`@inkeep/open-knowledge`]})}function u(e){return e.uiLock?e.isAlive(e.uiLock.pid)?{action:`skip`,reason:`alive`,pid:e.uiLock.pid,port:e.uiLock.port}:{action:`spawn`,reason:`stale`,stalePid:e.uiLock.pid}:{action:`spawn`,reason:`absent`}}function d(e){i(e.lockDir)||a(e.lockDir,{recursive:!0});let t=o(s(e.lockDir,`last-spawn-error.log`),`w`),n=e.spawn??c,{PORT:u,...d}=process.env,f=l();try{let r=n(f.command,[...f.prefixArgs,...e.args??[`ui`]],{detached:!0,stdio:[`ignore`,`ignore`,t],cwd:e.cwd,env:d});return r.unref(),r}finally{try{r(t)}catch{}}}function f(e){let t=e.sigtermGraceMs??1e4,n=e.sigtermPollIntervalMs??200,r=e.sleep??(e=>new Promise(t=>setTimeout(t,e)));return async()=>{try{let i=e.readUiLock();if(i&&e.isAlive(i.pid))try{e.killPid(i.pid,`SIGTERM`),e.log?.info({pid:i.pid,port:i.port},`idle-shutdown: SIGTERM UI sibling`);let a=Date.now()+t;for(;Date.now()<a&&e.isAlive(i.pid);)await r(n);if(e.isAlive(i.pid))try{e.killPid(i.pid,`SIGKILL`),e.log?.warn({pid:i.pid,graceMs:t},`idle-shutdown: SIGTERM grace expired — escalated to SIGKILL`)}catch(t){e.log?.error({pid:i.pid,err:t instanceof Error?t.message:String(t)},`idle-shutdown: SIGKILL failed`)}}catch(t){e.log?.warn({pid:i.pid,err:t instanceof Error?t.message:String(t)},`idle-shutdown: failed to SIGTERM UI sibling`)}}catch(t){e.log?.warn({err:t instanceof Error?t.message:String(t)},`idle-shutdown: UI lookup failed; proceeding with destroy`)}await e.destroy()}}async function p(e){let{config:n,cwd:r}=e,i=e.skipAutoInit??!1,a=e.skipUiAutoSpawn??!1,o=e.idleThresholdMs??18e5,{existsSync:s,mkdirSync:c}=await import(`node:fs`),{resolve:l}=await import(`node:path`),{bootServer:p,getLogger:m,isProcessAlive:h,readUiLock:g}=await import(`./src-NsJfsnSl.mjs`),{resolveContentDir:_}=await import(`./paths-xS3o7pK2.mjs`),v=e.log??m(`start`),y=_(n,r);s(y)||(c(y,{recursive:!0}),v.info({contentDir:y},`Created content directory`));let b=!s(l(r,t)),x=i?void 0:async()=>{try{let{initContent:e}=await import(`./init-CyxGRu4t.mjs`),t=e(r);return b||t.created.length>0}catch(e){return console.warn(`Auto-init failed:`,e instanceof Error?e.message:e),!1}},S=!1,C=l(y,t),w=n.server.openOnAgentEdit?()=>{if(S)return;let e=g(C);if(!e||e.port<=0||!h(e.pid))return;S=!0;let t=`http://localhost:${e.port}`;import(`./open-browser-CfwaLBtR.mjs`).then(({openBrowser:e})=>e(t)).catch(()=>{})}:void 0,T=null,E=await p({contentDir:y,projectDir:r,contentRoot:n.content.dir,port:n.server.port,host:n.server.host,quiet:!1,debounce:n.persistence.debounceMs,maxDebounce:n.persistence.maxDebounceMs,includePatterns:n.content.include,excludePatterns:n.content.exclude,onAgentWrite:w,localOpCliArgs:[process.execPath,process.argv[1]],attachUiSibling:!0,idleShutdownMs:o,skipAutoInit:i,autoInitFn:x,spawnUiSiblingFn:async({lockDir:t})=>{if(T=u({uiLock:g(t),isAlive:h}),T.action===`spawn`&&!a)try{d({lockDir:t,cwd:r,spawn:e.spawn}),v.info({reason:T.reason},`[start] auto-spawned ok ui sibling`)}catch(e){console.warn(`[start] failed to auto-spawn ok ui: ${e instanceof Error?e.message:String(e)}`)}else T.action===`skip`&&v.info({port:T.port,pid:T.pid},`UI already running at port ${T.port}`)},idleShutdownHandler:e=>f({readUiLock:()=>g(E.lockDir),isAlive:h,killPid:(e,t)=>{process.kill(e,t)},destroy:e,log:v}),log:v});return T||={action:`skip`,reason:`alive`,pid:0,port:0},{httpServer:E.httpServer,destroy:E.destroy,lockDir:E.lockDir,contentDir:y,port:E.port,ready:E.ready,degraded:E.degraded,uiSpawnDecision:T,didAutoInit:E.didAutoInit}}function m(r){return new n(`start`).description(`Start the knowledge base collab server`).option(`-p, --port <port>`,`Server port`,void 0).option(`-H, --host <host>`,`Server host`,void 0).option(`--open`,`Open browser after start`).option(`--no-init`,`Skip auto-scaffolding of ${t}/`).action(async n=>{let{renderBanner:i}=await import(`./banner-sRCRfb7A.mjs`),{dim:a,error:o,info:s,warning:c}=await import(`./colors-BNRrOlZZ.mjs`),l=r(),u=process.cwd();n.port!==void 0&&(l.server.port=Number(n.port)),n.host!==void 0&&(l.server.host=n.host);let d;try{d=await p({config:l,cwd:u,skipAutoInit:n.init===!1})}catch(e){console.error(`${o(`Failed to start:`)} ${e instanceof Error?e.stack??e.message:String(e)}`),process.exit(1)}let f=!1,m=async e=>{if(!f){f=!0,console.log(a(`\nShutting down (${e})...`));try{await d.destroy()}catch(e){console.error(`${o(`destroy() failed:`)} ${e instanceof Error?e.stack??e.message:String(e)}`),process.exitCode=1}process.exit(process.exitCode??0)}};process.once(`SIGINT`,()=>{m(`SIGINT`)}),process.once(`SIGTERM`,()=>{m(`SIGTERM`)});let h=`http://${l.server.host}:${d.port}`,g=l.server.host===`0.0.0.0`||l.server.host===`::`?`http://0.0.0.0:${d.port}`:void 0,_=d.uiSpawnDecision,v=_.action===`skip`?_.port:3e3,y=v>0?`http://${l.server.host}:${v}`:h;console.log(i({name:`open-knowledge`,version:e,localUrl:y,apiUrl:y===h?void 0:h,networkUrl:g})),d.didAutoInit&&(console.log(` ${s(`✓`)} Scaffolded ${t}/ (first run)`),console.log(` ${a("Tip: Run `open-knowledge init` to register MCP tools for Claude Code")}\n`));let b={"shadow-repo":`Version history and branch-switch safety unavailable`,"file-watcher":`External file changes will not sync to the editor`,"head-watcher":`Git branch switches may cause document inconsistency`};d.ready.then(async()=>{if(d.degraded.length>0){console.log();for(let e of d.degraded){let t=b[e]??`${e} (check server logs for details)`;console.warn(` ${c(`⚠`)} ${c(e)}: ${a(t)}`)}console.log()}if(d.didAutoInit)try{let{previewContent:e,formatPreviewBlock:t}=await import(`./preview-BGOwfgOL.mjs`),n=e({projectDir:u,contentDir:d.contentDir,include:l.content.include,exclude:l.content.exclude});console.log(`\n${t(n,u)}\n`)}catch(e){console.warn(`Content preview unavailable: ${e instanceof Error?e.message:String(e)}`)}if(n.open){let{openBrowser:e}=await import(`./open-browser-CfwaLBtR.mjs`);e(y)}}).catch(e=>{console.error(` ${o(`Server initialization failed:`)} ${e instanceof Error?e.message:String(e)}`)})})}export{m as a,d as i,f as n,l as o,u as r,p as t};
2
+ //# sourceMappingURL=start-CNULXoun.mjs.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inkeep/open-knowledge",
3
- "version": "0.0.0-dev-20260421183856",
3
+ "version": "0.0.0-dev-20260421192027",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "exports": {
@@ -1,2 +0,0 @@
1
- import"./src-ViJPkmPW.mjs";var e=`0.0.0-dev-20260421183856`;const t=`AGENTS.md`,n=`config.yml`,r=`cache`,i=e,a=`open-knowledge`;export{i as a,a as i,r as n,n as r,t};
2
- //# sourceMappingURL=constants-D6bAkegd.mjs.map
@@ -1 +0,0 @@
1
- import{a as e,i as t,n,r,t as i}from"./init-CiURMJ2p.mjs";export{i as detectInstalledEditors,n as formatInitResult,r as initCommand,t as parseEditorFlag,e as runInit};
@@ -1 +0,0 @@
1
- import{n as e}from"./loader-xn8pJrM1.mjs";export{e as loadConfig};
@@ -1 +0,0 @@
1
- import{n as e,t}from"./paths-BIa6zXQi.mjs";export{t as resolveContentDir,e as resolveLockDir};
@@ -1 +0,0 @@
1
- import{n as e,t}from"./preview-Bv6qni6t.mjs";export{t as formatPreviewBlock,e as previewContent};
@@ -1 +0,0 @@
1
- import"./loader-xn8pJrM1.mjs";export{};
@@ -1 +0,0 @@
1
- import{a as e}from"./start-BevXBjPW.mjs";export{e as startCommand};