@bigmistqke/workpad 0.20.0 → 0.20.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -159,10 +159,11 @@ gets `-2`. The server looks for projects again every few seconds, so a new
159
159
  worktree with a `.workpad/` shows up, and a removed one goes, without a
160
160
  restart.
161
161
 
162
- An entry's `"files": false` makes each of its projects serve none of its own
163
- files and watch only its `.workpad/`, as `files: false` in a project's
164
- config does, for projects with a config and without; a project's config that
165
- sets `files` still has its way. Left out, a project serves its files, as
162
+ An entry's `files` is the default `files` of each of its projects, with a
163
+ config and without: `"files": false` serves none of their own files and
164
+ watches only their `.workpad/`, and `"files": { "include": [...], "exclude":
165
+ [...] }` says which, as in a project's config (below). A project's config
166
+ that sets `files` still has its way. Left out, a project serves its files, as
166
167
  without the machine config.
167
168
 
168
169
  - **`/` is the overview of every project,** as a project's own overview is of
@@ -227,7 +228,8 @@ without the machine config.
227
228
  `url --full`). `$WORKPAD_URL` does the same for a project's own server
228
229
  started with it. By default `http://localhost:<port>`.
229
230
  - `"files": false` on an entry (see above) keeps its projects from
230
- watching more than their `.workpad/`. A page's own folder is watched
231
+ watching more than their `.workpad/`; `"files": { "exclude": ["**/dist"]
232
+ }` leaves out what nothing needs to show. A page's own folder is watched
231
233
  besides, once it is opened, so a page in a folder made and written into
232
234
  at once (which a container's mount may say nothing of) still goes live.
233
235
  - **A project per checkout.** A folder is a project once it has a
@@ -572,8 +574,10 @@ export default defineConfig({
572
574
  ```
573
575
 
574
576
  Without `include`, all files are shown but what `exclude` names.
575
- `node_modules` and `.git` are always left out, at any depth, and never
576
- watched.
577
+ `node_modules` and `.git` are always left out, at any depth (in folders
578
+ whose name starts with a dot too), and never watched. On Linux each folder
579
+ that can hold something shown is watched on its own, so what is left out
580
+ costs no watches; `WORKPAD_WATCH=folders` does the same elsewhere.
577
581
 
578
582
  ## Building a site
579
583
 
package/bin/workpad.ts CHANGED
@@ -195,6 +195,12 @@ async function ensureServer(): Promise<string> {
195
195
  )
196
196
  return base
197
197
  }
198
+ // the first ask timed out and this one was answered: the server is slow (busy), not missing the project
199
+ const mine = server?.projects.find(p => p.dir === proj.dir)
200
+ if (server && mine) {
201
+ console.error(`workpad: the shared server at ${server.origin} was slow to answer; it serves this project`)
202
+ return `${server.origin}${mine.base}`
203
+ }
198
204
  const at = recordedOrigin(machineServerFile())
199
205
  if (!server && at && (await stuckAt(at))) throw new Error(stuck(at, 'its login service log'))
200
206
  throw new Error(
@@ -140,6 +140,11 @@ async function ensureServer() {
140
140
  if (server && compareVersions(VERSION, server.version) > 0) console.error(`workpad: the shared server runs ${server.version}, this is ${VERSION}; restart it to upgrade (\`workpad serve\` takes it over)`);
141
141
  return base;
142
142
  }
143
+ const mine = server?.projects.find((p) => p.dir === proj.dir);
144
+ if (server && mine) {
145
+ console.error(`workpad: the shared server at ${server.origin} was slow to answer; it serves this project`);
146
+ return `${server.origin}${mine.base}`;
147
+ }
143
148
  const at = recordedOrigin(machineServerFile());
144
149
  if (!server && at && await stuckAt(at)) throw new Error(stuck(at, "its login service log"));
145
150
  throw new Error(server ? `the shared server at ${server.origin} does not serve ${proj.dir}; is it in an include of ${machineDir()}/config.json?` : `the shared server is not running. It is started outside the agents' sandboxes: as a login service, or with \`workpad serve\` in a terminal, outside any project`);
@@ -932,7 +932,7 @@ function goTo(target) {
932
932
  }
933
933
  scrollTo({
934
934
  top: Math.max(0, scrollY + target.getBoundingClientRect().top - offset),
935
- behavior: "smooth"
935
+ behavior: "instant"
936
936
  });
937
937
  target.classList.remove("wp-flash");
938
938
  target.offsetWidth;
@@ -18,9 +18,15 @@ function readJson(file) {
18
18
  };
19
19
  }
20
20
  }
21
- /** `$VAR` and `${VAR}` in a command as Claude Code expands them; CLAUDE_PROJECT_DIR is the project. */
21
+ /**
22
+ * `$VAR`, `${VAR}` and `${VAR:-default}` in a command, its args or env as Claude Code expands them
23
+ * (the default when VAR is unset or empty); CLAUDE_PROJECT_DIR is the project.
24
+ */
22
25
  function expand(s, env) {
23
- return s.replace(/\$\{(\w+)\}|\$(\w+)/g, (_, a, b) => env[a ?? b] ?? "");
26
+ return s.replace(/\$\{(\w+)(?::-([^}]*))?\}|\$(\w+)/g, (_, a, fallback, b) => {
27
+ const value = env[a ?? b];
28
+ return fallback !== void 0 && !value ? fallback : value ?? "";
29
+ });
24
30
  }
25
31
  /** Start the channel's command, ask it to initialize, and stop it: whether it answered, or why not. */
26
32
  function probe(command, args, cwd, env) {
@@ -182,10 +188,14 @@ async function channelChecks(pages, claude, home = os.homedir()) {
182
188
  fix: install
183
189
  });
184
190
  else {
185
- const env = {
191
+ const base = {
186
192
  ...process.env,
187
- CLAUDE_PROJECT_DIR: dir,
188
- ...entry.env ?? {}
193
+ CLAUDE_PROJECT_DIR: dir
194
+ };
195
+ const own = Object.entries(entry.env ?? {}).map(([k, v]) => [k, expand(String(v), base)]);
196
+ const env = {
197
+ ...base,
198
+ ...Object.fromEntries(own)
189
199
  };
190
200
  const why = await probe(expand(entry.command, env), (entry.args ?? []).map((a) => expand(a, env)), dir, env);
191
201
  const shown = [entry.command, ...entry.args ?? []].join(" ");
@@ -1 +1 @@
1
- const e=(e,t)=>`${e}\n${t}`,t=e=>typeof e==`number`&&Number.isFinite(e)?e:null;function n(n){let r=/* @__PURE__ */ new Map;for(let i of n){if(i.type!==`progress:update`||i.from!==`cli`)continue;let n=i.data??{},a=typeof n.id==`string`?n.id:``;if(!a)continue;let o=e(i.page,a),s=r.get(o),c=n.state===`done`||n.state===`failed`?n.state:`running`,l=t(n.n),u=t(n.total),d=!s||s.state!==`running`,f=d?i.ts:s.started,p=d?null:s.first;r.set(o,{page:i.page,id:a,n:l,total:u,note:typeof n.note==`string`?n.note:``,state:c,eta:t(n.eta),ts:i.ts,started:f,first:p??(l==null?null:{n:l,ts:i.ts}),by:i.by??null,event:i.id})}return r}const r=(e,t)=>[...n(e.filter(e=>e.page===t)).values()];function i(e,t){if(e.state!==`running`)return null;let n=Date.parse(e.ts);if(e.eta!=null)return n+e.eta*1e3-t;if(e.n==null||e.total==null||!e.first||e.n<=e.first.n)return null;let r=(e.n-e.first.n)/(n-Date.parse(e.first.ts));return r>0?n+(e.total-e.n)/r-t:null}function a(e,t,n=9e5){return e.state===`running`?t-Date.parse(e.ts)>=n||e.eta!=null&&Date.parse(e.ts)+e.eta*1e3<t:!1}const o=e=>e.toLocaleString(`en-US`),s=e=>e.n!=null&&e.total!=null?`${o(e.n)} / ${o(e.total)}`:``;function c(e){let t=Math.max(0,Math.round(e/1e3));if(t<60)return`${t} s`;let n=Math.round(t/60);if(n<60)return`${n} min`;let r=Math.floor(n/60),i=n%60;return i?`${r} h ${i} min`:`${r} h`}const l=e=>e<1e4?`just now`:`${c(e)} ago`;function u(e,t){let n=i(e,t);return n==null||n<=0?``:`~${c(n)} left`}function d(e,t,n){let r=document.createElement(e);return r.className=t,n!=null&&(r.textContent=n),r}const f=e=>new Date(e).toLocaleTimeString([],{hour:`2-digit`,minute:`2-digit`,hourCycle:`h23`}),p=e=>e.n!=null&&e.total?e.n/e.total:null,m={running:`running`,done:`done`,failed:`failed`};function h(e,t,n,r){let i=e.querySelector(`:scope > .wp-progress-body`);if(!i)return;if(!t){e.dataset.wpProgress=`waiting`,e.removeAttribute(`data-wp-stale`),i.replaceChildren(d(`span`,`wp-progress-note`,`waiting to start`));return}let o=a(t,n,r);e.dataset.wpProgress=t.state,e.toggleAttribute(`data-wp-stale`,o);let h=[],g=p(t);if(t.state===`running`&&g!=null){let e=d(`span`,`wp-progress-bar`),n=d(`span`,``);n.style.width=`${Math.round(g*1e3)/10}%`,e.append(n),e.setAttribute(`role`,`progressbar`),e.setAttribute(`aria-valuemin`,`0`),e.setAttribute(`aria-valuemax`,String(t.total)),e.setAttribute(`aria-valuenow`,String(t.n)),h.push(e,d(`span`,`wp-progress-count`,s(t)))}else h.push(d(`span`,`wp-progress-state`,m[t.state]));t.note&&h.push(d(`span`,`wp-progress-note`,t.note));let _=[];if(t.state!==`running`)_.push(f(t.ts));else if(o)_.push(`no update for ${c(n-Date.parse(t.ts))}`);else{let e=u(t,n);e&&_.push(e),_.push(l(n-Date.parse(t.ts)))}h.push(d(`span`,`wp-progress-when`,_.join(` · `))),i.replaceChildren(...h),e.title=`${t.id}: ${t.state}${t.by?`, moved by ${t.by}`:``}`}function g(e,t,n){let r=e.state===`running`?s(e)||e.note:e.note||m[e.state],i=`${e.state===`done`?`✓ `:e.state===`failed`?`✗ `:``}${e.id}${r?` · ${r}`:``}`;return e.state===`running`?{text:i,meta:a(e,t,n)?`no update ${c(t-Date.parse(e.ts))}`:u(e,t)||l(t-Date.parse(e.ts)),bar:{value:p(e),tone:`accent`}}:{text:i,meta:l(t-Date.parse(e.ts)),bar:{value:1,tone:e.state===`done`?`good`:`bad`}}}const _=(e,t,n)=>{if(!t.live)return;let i=Number(document.querySelector(`meta[name=wp-progress]`)?.dataset.staleAfter)||9e5,a=`wp-progress-seen:${location.pathname}`,o=/* @__PURE__ */ new Set;try{o=new Set(JSON.parse(localStorage.getItem(a)??`[]`))}catch{}let s=e=>{o.add(e);try{localStorage.setItem(a,JSON.stringify([...o].slice(-200)))}catch{}},c=/* @__PURE__ */ new Map,l=/* @__PURE__ */ new Map,u=/* @__PURE__ */ new Map,d=t=>[...e.querySelectorAll(`.wp-progress[data-progress]`)].filter(e=>e.dataset.progress===t);function f(e){let t=l.get(e);t&&t.state!==`running`&&(s(t.event),c.get(e)?.close(),c.delete(e));let n=d(e);if(!n.length)return;let r=((u.get(e)??-1)+1)%n.length;u.set(e,r);let i=n[r];i.scrollIntoView({block:`center`,behavior:`smooth`}),i.classList.remove(`wp-flash`),i.offsetWidth,i.classList.add(`wp-flash`)}function p(){let t=Date.now(),a=r(n.events(),n.page),s=new Map(a.map(e=>[e.id,e]));for(let n of e.querySelectorAll(`.wp-progress[data-progress]`))h(n,s.get(n.dataset.progress),t,i);for(let e of a){let r=e.state===`running`||!o.has(e.event),a=c.get(e.id);if(!r){a?.close(),c.delete(e.id);continue}l.set(e.id,e);let{text:s,meta:u,bar:d}=g(e,t,i);a?a.update(s,{meta:u??null,bar:d??null}):(a=n.toast(s,{kind:`quiet`,ms:0,name:`progress-${e.id}`,order:-3,meta:u,bar:d,onClick:()=>f(e.id)}),c.set(e.id,a))}for(let[e,t]of c)s.has(e)||(t.close(),c.delete(e))}p(),n.events.on(p),n.onRendered(p),setInterval(p,1e4)};export{_ as default};
1
+ const e=(e,t)=>`${e}\n${t}`,t=e=>typeof e==`number`&&Number.isFinite(e)?e:null;function n(n){let r=/* @__PURE__ */ new Map;for(let i of n){if(i.type!==`progress:update`||i.from!==`cli`)continue;let n=i.data??{},a=typeof n.id==`string`?n.id:``;if(!a)continue;let o=e(i.page,a),s=r.get(o),c=n.state===`done`||n.state===`failed`?n.state:`running`,l=t(n.n),u=t(n.total),d=!s||s.state!==`running`,f=d?i.ts:s.started,p=d?null:s.first;r.set(o,{page:i.page,id:a,n:l,total:u,note:typeof n.note==`string`?n.note:``,state:c,eta:t(n.eta),ts:i.ts,started:f,first:p??(l==null?null:{n:l,ts:i.ts}),by:i.by??null,event:i.id})}return r}const r=(e,t)=>[...n(e.filter(e=>e.page===t)).values()];function i(e,t){if(e.state!==`running`)return null;let n=Date.parse(e.ts);if(e.eta!=null)return n+e.eta*1e3-t;if(e.n==null||e.total==null||!e.first||e.n<=e.first.n)return null;let r=(e.n-e.first.n)/(n-Date.parse(e.first.ts));return r>0?n+(e.total-e.n)/r-t:null}function a(e,t,n=9e5){return e.state===`running`?t-Date.parse(e.ts)>=n||e.eta!=null&&Date.parse(e.ts)+e.eta*1e3<t:!1}const o=e=>e.toLocaleString(`en-US`),s=e=>e.n!=null&&e.total!=null?`${o(e.n)} / ${o(e.total)}`:``;function c(e){let t=Math.max(0,Math.round(e/1e3));if(t<60)return`${t} s`;let n=Math.round(t/60);if(n<60)return`${n} min`;let r=Math.floor(n/60),i=n%60;return i?`${r} h ${i} min`:`${r} h`}const l=e=>e<1e4?`just now`:`${c(e)} ago`;function u(e,t){let n=i(e,t);return n==null||n<=0?``:`~${c(n)} left`}function d(e,t,n){let r=document.createElement(e);return r.className=t,n!=null&&(r.textContent=n),r}const f=e=>new Date(e).toLocaleTimeString([],{hour:`2-digit`,minute:`2-digit`,hourCycle:`h23`}),p=e=>e.n!=null&&e.total?e.n/e.total:null,m={running:`running`,done:`done`,failed:`failed`};function h(e,t,n,r){let i=e.querySelector(`:scope > .wp-progress-body`);if(!i)return;if(!t){e.dataset.wpProgress=`waiting`,e.removeAttribute(`data-wp-stale`),i.replaceChildren(d(`span`,`wp-progress-note`,`waiting to start`));return}let o=a(t,n,r);e.dataset.wpProgress=t.state,e.toggleAttribute(`data-wp-stale`,o);let h=[],g=p(t);if(t.state===`running`&&g!=null){let e=d(`span`,`wp-progress-bar`),n=d(`span`,``);n.style.width=`${Math.round(g*1e3)/10}%`,e.append(n),e.setAttribute(`role`,`progressbar`),e.setAttribute(`aria-valuemin`,`0`),e.setAttribute(`aria-valuemax`,String(t.total)),e.setAttribute(`aria-valuenow`,String(t.n)),h.push(e,d(`span`,`wp-progress-count`,s(t)))}else h.push(d(`span`,`wp-progress-state`,m[t.state]));t.note&&h.push(d(`span`,`wp-progress-note`,t.note));let _=[];if(t.state!==`running`)_.push(f(t.ts));else if(o)_.push(`no update for ${c(n-Date.parse(t.ts))}`);else{let e=u(t,n);e&&_.push(e),_.push(l(n-Date.parse(t.ts)))}h.push(d(`span`,`wp-progress-when`,_.join(` · `))),i.replaceChildren(...h),e.title=`${t.id}: ${t.state}${t.by?`, moved by ${t.by}`:``}`}function g(e,t,n){let r=e.state===`running`?s(e)||e.note:e.note||m[e.state],i=`${e.state===`done`?`✓ `:e.state===`failed`?`✗ `:``}${e.id}${r?` · ${r}`:``}`;return e.state===`running`?{text:i,meta:a(e,t,n)?`no update ${c(t-Date.parse(e.ts))}`:u(e,t)||l(t-Date.parse(e.ts)),bar:{value:p(e),tone:`accent`}}:{text:i,meta:l(t-Date.parse(e.ts)),bar:{value:1,tone:e.state===`done`?`good`:`bad`}}}const _=(e,t,n)=>{if(!t.live)return;let i=Number(document.querySelector(`meta[name=wp-progress]`)?.dataset.staleAfter)||9e5,a=`wp-progress-seen:${location.pathname}`,o=/* @__PURE__ */ new Set;try{o=new Set(JSON.parse(localStorage.getItem(a)??`[]`))}catch{}let s=e=>{o.add(e);try{localStorage.setItem(a,JSON.stringify([...o].slice(-200)))}catch{}},c=/* @__PURE__ */ new Map,l=/* @__PURE__ */ new Map,u=/* @__PURE__ */ new Map,d=t=>[...e.querySelectorAll(`.wp-progress[data-progress]`)].filter(e=>e.dataset.progress===t);function f(e){let t=l.get(e);t&&t.state!==`running`&&(s(t.event),c.get(e)?.close(),c.delete(e));let n=d(e);if(!n.length)return;let r=((u.get(e)??-1)+1)%n.length;u.set(e,r);let i=n[r];i.scrollIntoView({block:`center`,behavior:`instant`}),i.classList.remove(`wp-flash`),i.offsetWidth,i.classList.add(`wp-flash`)}function p(){let t=Date.now(),a=r(n.events(),n.page),s=new Map(a.map(e=>[e.id,e]));for(let n of e.querySelectorAll(`.wp-progress[data-progress]`))h(n,s.get(n.dataset.progress),t,i);for(let e of a){let r=e.state===`running`||!o.has(e.event),a=c.get(e.id);if(!r){a?.close(),c.delete(e.id);continue}l.set(e.id,e);let{text:s,meta:u,bar:d}=g(e,t,i);a?a.update(s,{meta:u??null,bar:d??null}):(a=n.toast(s,{kind:`quiet`,ms:0,name:`progress-${e.id}`,order:-3,meta:u,bar:d,onClick:()=>f(e.id)}),c.set(e.id,a))}for(let[e,t]of c)s.has(e)||(t.close(),c.delete(e))}p(),n.events.on(p),n.onRendered(p),setInterval(p,1e4)};export{_ as default};
@@ -1 +1 @@
1
- const e=document.createElement(`nav`);e.className=`wp-toc`,e.setAttribute(`aria-label`,`Contents`);const t=document.createElement(`ol`);e.append(t);const n=document.createElement(`button`);n.type=`button`,n.className=`wp-toc-toggle`,n.title=n.ariaLabel=`Contents`,n.setAttribute(`aria-expanded`,`false`),n.innerHTML=`<svg viewBox="0 0 16 16" width="14" height="14" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round"><path d="M2.5 4h11M2.5 8h11M2.5 12h7"/></svg>`;let r,i,a=[];const o=()=>document.querySelector(`.wp-nav`)?.getBoundingClientRect().height??0,s=()=>document.documentElement.clientWidth-r.offsetWidth-16-40;function c(){let t=parseFloat(getComputedStyle(e).minWidth)||0;return s()>=t}const l=e=>{let t=/^(\d+(?:\.\d+)?)(px|em|rem|ch|vw)?$/.exec(String(e??``).trim());return t&&Number(t[1])>0?t[1]+(t[2]??`px`):null};function u(){let t=document.querySelector(`meta[name=wp-toc]`),n=f.settings(),r=n&&typeof n==`object`?n:{};for(let[n,i]of[[`minWidth`,`--wp-toc-min-width`],[`maxWidth`,`--wp-toc-max-width`]]){let a=l(r[n])??l(t?.dataset[n]);a?e.style.setProperty(i,a):e.style.removeProperty(i)}}function d(t){let n=document.documentElement.style;if(e.style.setProperty(`--wp-toc-room`,`${s()}px`),!t)return n.removeProperty(`--wp-aside`);n.setProperty(`--wp-aside`,`${16+e.getBoundingClientRect().width}px`)}let f;function p(t){e.classList.toggle(`wp-toc-open`,t),e.hidden=!t,n.setAttribute(`aria-expanded`,String(t))}function m(){let e=f.settings(),t=document.querySelector(`meta[name=wp-toc]`)?.getAttribute(`content`)===`always`;return e===!1?!1:e===!0||e&&typeof e==`object`?!0:t}function h(e){let t=e.cloneNode(!0);return t.querySelectorAll(`.wp-badge, .wp-when`).forEach(e=>e.remove()),t.textContent?.trim()??``}function g(){a=m()?[...r.querySelectorAll(`:scope > :is(h2, h3, h4, h5, h6)`)]:[];let i=[0,0,0,0,0],o=[{level:1,list:t}];t.replaceChildren(),a.forEach((e,t)=>{let n=Number(e.tagName[1]);for(i[n-2]++,i.fill(0,n-1);o.length>1&&o.at(-1).level>=n;)o.pop();let r=o.at(-1);r.item&&!r.item.querySelector(`:scope > ol`)&&r.item.append(document.createElement(`ol`));let a=r.item?r.item.querySelector(`:scope > ol`):r.list,s=document.createElement(`li`);s.dataset.level=String(n);let c=document.createElement(`a`);c.href=`#`,c.dataset.index=String(t),c.innerHTML=`<span class="wp-toc-number"></span><span class="wp-toc-text"></span>`,c.querySelector(`.wp-toc-number`).textContent=i.slice(0,n-1).join(`.`),c.querySelector(`.wp-toc-text`).textContent=h(e),s.append(c),a.append(s),o.push({level:n,list:a,item:s})});let s=a.length>1;u();let l=s&&c();n.hidden=!s||l,e.hidden=!s||!l&&!e.classList.contains(`wp-toc-open`),e.classList.toggle(`wp-toc-docked`,l),d(l),v(),y()}function _(e){let t=-1;for(let n=0;n<a.length&&a[n].compareDocumentPosition(e)&Node.DOCUMENT_POSITION_FOLLOWING;n++)t=n;return t}function v(){let e=/* @__PURE__ */ new Set,n=new Set(i.unread().map(e=>e.id)),o=[...r.querySelectorAll(`form[data-wp-open]`),...[...r.querySelectorAll(`[data-wp-message]`)].filter(e=>n.has(e.dataset.wpMessage))];for(let t of o)e.add(_(t));for(let t of document.querySelectorAll(`[data-wp-holds]`)){if(!t.dataset.wpHolds.split(` `).some(e=>n.has(e)))continue;let r=t.getBoundingClientRect().top,i=-1;a.forEach((e,t)=>{e.getBoundingClientRect().top<=r&&(i=t)}),e.add(i)}t.querySelectorAll(`a`).forEach((t,n)=>t.toggleAttribute(`data-waiting`,e.has(n)))}function y(){let e=o()+40,n=0;a.forEach((t,r)=>{t.getBoundingClientRect().top<=e&&(n=r)}),t.querySelectorAll(`a`).forEach((e,t)=>e.toggleAttribute(`aria-current`,t===n&&a.length>0))}function b(e){let t=a[e];t&&(scrollTo({top:Math.max(0,scrollY+t.getBoundingClientRect().top-o()-12),behavior:`smooth`}),c()||p(!1))}const x=(a,o,s)=>{if(o.kind!==`page`&&o.kind!==`file`)return;f=o,r=a.querySelector(`#wp-main`)??a,i=s,s.slot(`aside`,t=>(t.append(e),()=>e.remove())),s.slot(`header`,e=>(e.append(n),()=>n.remove())),t.addEventListener(`click`,e=>{let t=e.target.closest(`a[data-index]`);t&&(e.preventDefault(),b(Number(t.dataset.index)))}),n.addEventListener(`click`,()=>p(!e.classList.contains(`wp-toc-open`))),document.addEventListener(`keydown`,t=>{t.key===`Escape`&&e.classList.contains(`wp-toc-open`)&&n.click()});let c=0,l=e=>()=>{cancelAnimationFrame(c),c=requestAnimationFrame(e)};addEventListener(`scroll`,l(y),{passive:!0}),addEventListener(`resize`,l(g)),i.onRendered(g),o.settings.on(g),i.forms.on(()=>v()),i.events.on(()=>requestAnimationFrame(v)),g()};export{x as default};
1
+ const e=document.createElement(`nav`);e.className=`wp-toc`,e.setAttribute(`aria-label`,`Contents`);const t=document.createElement(`ol`);e.append(t);const n=document.createElement(`button`);n.type=`button`,n.className=`wp-toc-toggle`,n.title=n.ariaLabel=`Contents`,n.setAttribute(`aria-expanded`,`false`),n.innerHTML=`<svg viewBox="0 0 16 16" width="14" height="14" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round"><path d="M2.5 4h11M2.5 8h11M2.5 12h7"/></svg>`;let r,i,a=[];const o=()=>document.querySelector(`.wp-nav`)?.getBoundingClientRect().height??0,s=()=>document.documentElement.clientWidth-r.offsetWidth-16-40;function c(){let t=parseFloat(getComputedStyle(e).minWidth)||0;return s()>=t}const l=e=>{let t=/^(\d+(?:\.\d+)?)(px|em|rem|ch|vw)?$/.exec(String(e??``).trim());return t&&Number(t[1])>0?t[1]+(t[2]??`px`):null};function u(){let t=document.querySelector(`meta[name=wp-toc]`),n=f.settings(),r=n&&typeof n==`object`?n:{};for(let[n,i]of[[`minWidth`,`--wp-toc-min-width`],[`maxWidth`,`--wp-toc-max-width`]]){let a=l(r[n])??l(t?.dataset[n]);a?e.style.setProperty(i,a):e.style.removeProperty(i)}}function d(t){let n=document.documentElement.style;if(e.style.setProperty(`--wp-toc-room`,`${s()}px`),!t)return n.removeProperty(`--wp-aside`);n.setProperty(`--wp-aside`,`${16+e.getBoundingClientRect().width}px`)}let f;function p(t){e.classList.toggle(`wp-toc-open`,t),e.hidden=!t,n.setAttribute(`aria-expanded`,String(t))}function m(){let e=f.settings(),t=document.querySelector(`meta[name=wp-toc]`)?.getAttribute(`content`)===`always`;return e===!1?!1:e===!0||e&&typeof e==`object`?!0:t}function h(e){let t=e.cloneNode(!0);return t.querySelectorAll(`.wp-badge, .wp-when`).forEach(e=>e.remove()),t.textContent?.trim()??``}function g(){a=m()?[...r.querySelectorAll(`:scope > :is(h2, h3, h4, h5, h6)`)]:[];let i=[0,0,0,0,0],o=[{level:1,list:t}];t.replaceChildren(),a.forEach((e,t)=>{let n=Number(e.tagName[1]);for(i[n-2]++,i.fill(0,n-1);o.length>1&&o.at(-1).level>=n;)o.pop();let r=o.at(-1);r.item&&!r.item.querySelector(`:scope > ol`)&&r.item.append(document.createElement(`ol`));let a=r.item?r.item.querySelector(`:scope > ol`):r.list,s=document.createElement(`li`);s.dataset.level=String(n);let c=document.createElement(`a`);c.href=`#`,c.dataset.index=String(t),c.innerHTML=`<span class="wp-toc-number"></span><span class="wp-toc-text"></span>`,c.querySelector(`.wp-toc-number`).textContent=i.slice(0,n-1).join(`.`),c.querySelector(`.wp-toc-text`).textContent=h(e),s.append(c),a.append(s),o.push({level:n,list:a,item:s})});let s=a.length>1;u();let l=s&&c();n.hidden=!s||l,e.hidden=!s||!l&&!e.classList.contains(`wp-toc-open`),e.classList.toggle(`wp-toc-docked`,l),d(l),v(),y()}function _(e){let t=-1;for(let n=0;n<a.length&&a[n].compareDocumentPosition(e)&Node.DOCUMENT_POSITION_FOLLOWING;n++)t=n;return t}function v(){let e=/* @__PURE__ */ new Set,n=new Set(i.unread().map(e=>e.id)),o=[...r.querySelectorAll(`form[data-wp-open]`),...[...r.querySelectorAll(`[data-wp-message]`)].filter(e=>n.has(e.dataset.wpMessage))];for(let t of o)e.add(_(t));for(let t of document.querySelectorAll(`[data-wp-holds]`)){if(!t.dataset.wpHolds.split(` `).some(e=>n.has(e)))continue;let r=t.getBoundingClientRect().top,i=-1;a.forEach((e,t)=>{e.getBoundingClientRect().top<=r&&(i=t)}),e.add(i)}t.querySelectorAll(`a`).forEach((t,n)=>t.toggleAttribute(`data-waiting`,e.has(n)))}function y(){let e=o()+40,n=0;a.forEach((t,r)=>{t.getBoundingClientRect().top<=e&&(n=r)}),t.querySelectorAll(`a`).forEach((e,t)=>e.toggleAttribute(`aria-current`,t===n&&a.length>0))}function b(e){let t=a[e];t&&(scrollTo({top:Math.max(0,scrollY+t.getBoundingClientRect().top-o()-12),behavior:`instant`}),c()||p(!1))}const x=(a,o,s)=>{if(o.kind!==`page`&&o.kind!==`file`)return;f=o,r=a.querySelector(`#wp-main`)??a,i=s,s.slot(`aside`,t=>(t.append(e),()=>e.remove())),s.slot(`header`,e=>(e.append(n),()=>n.remove())),t.addEventListener(`click`,e=>{let t=e.target.closest(`a[data-index]`);t&&(e.preventDefault(),b(Number(t.dataset.index)))}),n.addEventListener(`click`,()=>p(!e.classList.contains(`wp-toc-open`))),document.addEventListener(`keydown`,t=>{t.key===`Escape`&&e.classList.contains(`wp-toc-open`)&&n.click()});let c=0,l=e=>()=>{cancelAnimationFrame(c),c=requestAnimationFrame(e)};addEventListener(`scroll`,l(y),{passive:!0}),addEventListener(`resize`,l(g)),i.onRendered(g),o.settings.on(g),i.forms.on(()=>v()),i.events.on(()=>requestAnimationFrame(v)),g()};export{x as default};
@@ -662,7 +662,7 @@ function update$1() {
662
662
  function go(dir) {
663
663
  const { above, below } = split();
664
664
  (dir === "up" ? above : below)[0]?.scrollIntoView({
665
- behavior: "smooth",
665
+ behavior: "instant",
666
666
  block: "start"
667
667
  });
668
668
  }
@@ -1125,7 +1125,7 @@ function jumpTo(target) {
1125
1125
  scrolledTo = Math.max(0, Math.min(scrollY + r.top + r.height / 2 - viewBottom() / 2, document.documentElement.scrollHeight - innerHeight));
1126
1126
  scrollTo({
1127
1127
  top: scrolledTo,
1128
- behavior: "smooth"
1128
+ behavior: "instant"
1129
1129
  });
1130
1130
  if (target instanceof HTMLFormElement) {
1131
1131
  if (target.hasAttribute("data-wp-open")) target.querySelector("input:not([type=hidden]), textarea, select, button")?.focus({ preventScroll: true });
@@ -69,11 +69,15 @@ function readMachineConfig(dir = machineDir()) {
69
69
  if (!Array.isArray(v) || v.some((x) => typeof x !== "string")) throw new Error(`${file}: entries.${name}.${what} must be a list of globs`);
70
70
  return v;
71
71
  };
72
- if (e?.files != null && typeof e.files !== "boolean") throw new Error(`${file}: entries.${name}.files must be true or false`);
72
+ const files = e?.files;
73
+ if (files != null && typeof files !== "boolean" && (typeof files !== "object" || Array.isArray(files))) throw new Error(`${file}: entries.${name}.files must be true, false or { "include": [...], "exclude": [...] }`);
73
74
  entries[name] = {
74
75
  include: list(e?.include, "include"),
75
76
  exclude: list(e?.exclude, "exclude"),
76
- ...e?.files != null && { files: e.files }
77
+ ...files != null && { files: typeof files === "boolean" ? files : {
78
+ ...files.include != null && { include: list(files.include, "files.include") },
79
+ ...files.exclude != null && { exclude: list(files.exclude, "files.exclude") }
80
+ } }
77
81
  };
78
82
  }
79
83
  const port = raw.port == null ? void 0 : Number(raw.port);
package/dist/src/files.js CHANGED
@@ -2,7 +2,40 @@ import path from "node:path";
2
2
  // src/files.ts
3
3
  /** Left out always: what a repository keeps for its tools. */
4
4
  const ALWAYS_EXCLUDED = ["**/node_modules", "**/.git"];
5
- const glob = (rel, g) => path.posix.matchesGlob(rel, g);
5
+ /**
6
+ * Does `rel` match `g`? As `path.posix.matchesGlob`, but a `**` takes in folders whose name starts
7
+ * with a dot as well: matchesGlob's doesn't, so `**\/node_modules` left out nothing under `.claude/`,
8
+ * and an install in a worktree kept there reached the watcher as thousands of changes. Segment by
9
+ * segment: `**` stands for any number of folders, every other segment is matched by matchesGlob.
10
+ */
11
+ function glob(rel, g) {
12
+ const parts = g.split("/");
13
+ const segs = rel.split("/");
14
+ const segment = (name, part) => {
15
+ const key = `${part}\0${name}`;
16
+ let hit = SEGMENTS.get(key);
17
+ if (hit === void 0) {
18
+ if (SEGMENTS.size > 1e5) SEGMENTS.clear();
19
+ SEGMENTS.set(key, hit = path.posix.matchesGlob(name, part));
20
+ }
21
+ return hit;
22
+ };
23
+ const seen = /* @__PURE__ */ new Set();
24
+ const at = (i, j) => {
25
+ if (i === parts.length) return j === segs.length;
26
+ const key = `${i},${j}`;
27
+ if (seen.has(key)) return false;
28
+ seen.add(key);
29
+ if (parts[i] === "**") {
30
+ for (let k = j; k <= segs.length; k++) if (at(i + 1, k)) return true;
31
+ return false;
32
+ }
33
+ return j < segs.length && segment(segs[j], parts[i]) && at(i + 1, j + 1);
34
+ };
35
+ return at(0, 0);
36
+ }
37
+ const SEGMENTS = /* @__PURE__ */ new Map();
38
+ const ALWAYS_NAMES = new Set(ALWAYS_EXCLUDED.map((g) => g.slice(3)));
6
39
  /** The path and each folder above it: `a/b/c` → `a/b/c`, `a/b`, `a`. */
7
40
  function* upward(rel) {
8
41
  for (let p = rel; p && p !== "."; p = path.posix.dirname(p)) yield p;
@@ -28,8 +61,21 @@ function fileFilter(files) {
28
61
  const config = typeof files === "object" && files ? files : {};
29
62
  const exclude = [...ALWAYS_EXCLUDED, ...config.exclude ?? []];
30
63
  const include = config.include?.length ? config.include : null;
31
- const excluded = (rel) => [...upward(rel)].some((p) => exclude.some((g) => glob(p, g)));
32
- const included = (rel) => !include || [...upward(rel)].some((p) => include.some((g) => glob(p, g)));
64
+ const memo = (test) => {
65
+ const seen = /* @__PURE__ */ new Map();
66
+ return (p) => {
67
+ let hit = seen.get(p);
68
+ if (hit === void 0) {
69
+ if (seen.size > 5e4) seen.clear();
70
+ seen.set(p, hit = test(p));
71
+ }
72
+ return hit;
73
+ };
74
+ };
75
+ const excludes = memo((p) => exclude.some((g) => glob(p, g)));
76
+ const includes = memo((p) => !!include?.some((g) => glob(p, g)));
77
+ const excluded = (rel) => rel.split("/").some((s) => ALWAYS_NAMES.has(s)) || [...upward(rel)].some(excludes);
78
+ const included = (rel) => !include || [...upward(rel)].some(includes);
33
79
  return {
34
80
  key: JSON.stringify({
35
81
  include,
@@ -44,4 +90,4 @@ function fileFilter(files) {
44
90
  }
45
91
  };
46
92
  }
47
- export { ALWAYS_EXCLUDED, fileFilter };
93
+ export { ALWAYS_EXCLUDED, fileFilter, glob };
package/dist/src/hub.js CHANGED
@@ -46,7 +46,7 @@ function createHub({ dir = machineDir(), state = stateDir(), home, interval, onS
46
46
  };
47
47
  function sync(projects) {
48
48
  setImmediate(() => touch());
49
- const wanted = new Map(projects.map((p) => [`${p.base}\n${p.dir}\n${p.files ?? ""}`, p]));
49
+ const wanted = new Map(projects.map((p) => [`${p.base}\n${p.dir}\n${JSON.stringify(p.files ?? null)}`, p]));
50
50
  for (const [key, s] of served) if (!wanted.has(key)) {
51
51
  for (const el of entryListens) release(s, el);
52
52
  for (const ul of unfollowedListens) letGo(s, ul);
@@ -99,14 +99,17 @@ function createHub({ dir = machineDir(), state = stateDir(), home, interval, onS
99
99
  });
100
100
  let touching;
101
101
  const changes = /* @__PURE__ */ new Set();
102
+ let toldAt = 0;
102
103
  const touch = () => {
103
- clearTimeout(touching);
104
+ if (touching) return;
104
105
  touching = setTimeout(() => {
106
+ touching = void 0;
107
+ toldAt = Date.now();
105
108
  root.touch();
106
109
  const from = [...changes];
107
110
  changes.clear();
108
111
  for (const s of served.values()) if (from.some((b) => b !== s.base)) s.server.elsewhere();
109
- }, 150);
112
+ }, Math.max(150, toldAt + 1e3 - Date.now()));
110
113
  };
111
114
  const changed = (base) => {
112
115
  changes.add(base);
@@ -87,8 +87,8 @@ function checkPlugin(e, where) {
87
87
  */
88
88
  const RETRY_FAILED_MS = 5e3;
89
89
  /**
90
- * `files`: whether the project serves its own files when its config doesn't say (a machine config's
91
- * entry can say false for all of its projects; see EntryConfig).
90
+ * `files`: which of its own files the project serves when its config doesn't say (a machine config's
91
+ * entry can say it for all of its projects; see EntryConfig).
92
92
  */
93
93
  function createConfigLoader(proj, { pages: withPages = true, files: filesDefault = true } = {}) {
94
94
  let cached = null;
@@ -140,8 +140,8 @@ function createConfigLoader(proj, { pages: withPages = true, files: filesDefault
140
140
  forReader: new Map([...declared("forReader")].map((type) => [type, requires.get(type) ?? []])),
141
141
  requires,
142
142
  publicDirs,
143
- files: config?.files == null ? filesDefault : config.files !== false,
144
- fileFilter: fileFilter(config?.files),
143
+ files: (config?.files ?? filesDefault) !== false,
144
+ fileFilter: fileFilter(config?.files ?? filesDefault),
145
145
  build: config?.build ?? {},
146
146
  commands: configCommands(config?.commands, {
147
147
  taken: RESERVED,
@@ -107,7 +107,7 @@ const MARKDOWN = /\.(md|markdown)$/i;
107
107
  * built copies and dependencies stay out; elsewhere a walk that skips the usual build and
108
108
  * dependency folders. The project's own pages (.workpad/) are listed apart.
109
109
  */
110
- function documentsIn(dir, shows = (rel) => fileFilter().shows(rel)) {
110
+ function documentsIn(dir, { shows, mayHold } = fileFilter()) {
111
111
  let files;
112
112
  try {
113
113
  files = execFileSync("git", [
@@ -136,9 +136,12 @@ function documentsIn(dir, shows = (rel) => fileFilter().shows(rel)) {
136
136
  } catch {
137
137
  return;
138
138
  }
139
- for (const e of entries) if (e.isDirectory()) {
140
- if (!SKIP.has(e.name) && !e.name.startsWith(".")) walk(path.posix.join(rel, e.name));
141
- } else if (MARKDOWN.test(e.name)) files.push(path.posix.join(rel, e.name));
139
+ for (const e of entries) {
140
+ const child = path.posix.join(rel, e.name);
141
+ if (e.isDirectory()) {
142
+ if (!SKIP.has(e.name) && !e.name.startsWith(".") && (!mayHold || mayHold(child))) walk(child);
143
+ } else if (MARKDOWN.test(e.name)) files.push(child);
144
+ }
142
145
  };
143
146
  walk("");
144
147
  }
@@ -246,7 +249,11 @@ async function filesFold(dir, base) {
246
249
  * written here), by when last updated, or by title; each row carries what it is sorted by.
247
250
  */
248
251
  function documentList(ctx) {
249
- return documentsOf(ctx.project.dir, ctx.base ?? "", ctx.urlFor, false, ctx.project.shows);
252
+ const { shows, mayHold } = ctx.project;
253
+ return documentsOf(ctx.project.dir, ctx.base ?? "", ctx.urlFor, false, shows && {
254
+ shows,
255
+ mayHold
256
+ });
250
257
  }
251
258
  /**
252
259
  * A project's documents by the folder they are in, each folder a fold with how many it holds, the
@@ -312,8 +319,8 @@ function documentFolders(docs, dir, base, urlFor) {
312
319
  * A project's documents, as its overview lists them: from its folder, linked where it serves them.
313
320
  * `folded`: in a fold that says how many (the shared server's overview, where each project has them).
314
321
  */
315
- function documentsOf(dir, base, urlFor, folded = false, shows, open = false) {
316
- const docs = documentsIn(dir, shows).map((f) => docOf(dir, f));
322
+ function documentsOf(dir, base, urlFor, folded = false, filter, open = false) {
323
+ const docs = documentsIn(dir, filter).map((f) => docOf(dir, f));
317
324
  if (!docs.length) return "";
318
325
  if (folded) return documentTree(docs, dir, base, urlFor, open);
319
326
  const ctx = {
@@ -22,6 +22,13 @@ import fs from "node:fs";
22
22
  import path from "node:path";
23
23
  import crypto from "node:crypto";
24
24
  // src/server.ts
25
+ /**
26
+ * Watch a project's files folder by folder (each that can hold something shown, at any depth), not
27
+ * a recursive watch per top-level folder: where a recursive watch costs a watch per folder below
28
+ * it, whatever it holds (Linux's inotify). `$WORKPAD_WATCH`: `folders` or `recursive`, else by
29
+ * platform. See setFiles.
30
+ */
31
+ const WATCH_BY_FOLDER = process.env.WORKPAD_WATCH ? process.env.WORKPAD_WATCH === "folders" : process.platform !== "darwin" && process.platform !== "win32";
25
32
  const ENGINE_DIR = PACKAGE_DIR;
26
33
  const MIME = {
27
34
  ".css": "text/css",
@@ -63,7 +70,7 @@ const API_LISTS = [
63
70
  "subscriptions",
64
71
  "agents"
65
72
  ];
66
- function createServer(project, { base = "", entry, label, name, files: filesOption, filesDefault, overview, onChange, origins = () => [] } = {}) {
73
+ function createServer(project, { base = "", entry, label, name, files: filesOption, filesDefault, watchByFolder = WATCH_BY_FOLDER, overview, onChange, origins = () => [] } = {}) {
67
74
  const projectName = () => name ?? project.name;
68
75
  const loader = createConfigLoader(project, { files: filesDefault });
69
76
  const auth = createAuth(project.wp, base, origins);
@@ -71,10 +78,25 @@ function createServer(project, { base = "", entry, label, name, files: filesOpti
71
78
  const streams = /* @__PURE__ */ new Set();
72
79
  const watch = (dir, options, fn) => {
73
80
  try {
74
- watchers.add(fs.watch(dir, options, (_evt, name) => {
81
+ const w = fs.watch(dir, options, (_evt, name) => {
75
82
  if (name) fn(String(name));
76
- }));
77
- } catch {}
83
+ });
84
+ w.on("error", (err) => {
85
+ outOfWatches(err);
86
+ w.close();
87
+ watchers.delete(w);
88
+ });
89
+ watchers.add(w);
90
+ } catch (err) {
91
+ outOfWatches(err);
92
+ }
93
+ };
94
+ let told = false;
95
+ const outOfWatches = (err) => {
96
+ const code = err?.code;
97
+ if (told || code !== "EMFILE" && code !== "ENOSPC") return;
98
+ told = true;
99
+ console.error(`workpad: ${project.dir}: out of watches (${code}); some of its files won't go live. Narrow the config's files, or raise the limit`);
78
100
  };
79
101
  const setups = /* @__PURE__ */ new WeakMap();
80
102
  const pluginDirs = /* @__PURE__ */ new Set();
@@ -186,7 +208,8 @@ function createServer(project, { base = "", entry, label, name, files: filesOpti
186
208
  name: projectName(),
187
209
  dir: project.dir,
188
210
  files: !!FILES,
189
- shows: (rel) => FILTER.shows(rel)
211
+ shows: (rel) => FILTER.shows(rel),
212
+ mayHold: (rel) => FILTER.mayHold(rel)
190
213
  },
191
214
  asset,
192
215
  urlFor,
@@ -645,15 +668,24 @@ function createServer(project, { base = "", entry, label, name, files: filesOpti
645
668
  let FILES = null;
646
669
  let FILTER = fileFilter();
647
670
  let projectWatchers = /* @__PURE__ */ new Map();
671
+ let watchRound = 0;
648
672
  function setFiles(files, filter = fileFilter()) {
649
673
  if (files === FILES && filter.key === FILTER.key) return;
650
674
  FILES = files;
651
675
  FILTER = filter;
676
+ const round = ++watchRound;
652
677
  for (const w of projectWatchers.values()) {
653
678
  w.close();
654
679
  watchers.delete(w);
655
680
  }
656
681
  projectWatchers = /* @__PURE__ */ new Map();
682
+ const drop = (key) => {
683
+ for (const [k, w] of projectWatchers) if (k === key || k.startsWith(key + "/")) {
684
+ w.close();
685
+ watchers.delete(w);
686
+ projectWatchers.delete(k);
687
+ }
688
+ };
657
689
  const add = (key, dir, recursive, prefix) => {
658
690
  try {
659
691
  const w = fs.watch(dir, { recursive }, (evt, filename) => {
@@ -661,32 +693,46 @@ function createServer(project, { base = "", entry, label, name, files: filesOpti
661
693
  const name = filename.toString().replace(/\\/g, "/");
662
694
  fileChanged(prefix + name);
663
695
  if (!recursive && evt === "rename") {
664
- const old = projectWatchers.get(name);
665
- if (old) {
666
- old.close();
667
- watchers.delete(old);
668
- projectWatchers.delete(name);
669
- }
670
- watchFolder(name);
696
+ const child = prefix + name;
697
+ drop(child);
698
+ watchFolder(child);
671
699
  }
672
700
  });
673
- w.on("error", () => {
674
- w.close();
675
- watchers.delete(w);
676
- projectWatchers.delete(key);
701
+ w.on("error", (err) => {
702
+ outOfWatches(err);
703
+ drop(key);
677
704
  });
678
705
  projectWatchers.set(key, w);
679
706
  watchers.add(w);
680
- } catch {}
707
+ } catch (err) {
708
+ outOfWatches(err);
709
+ }
681
710
  };
682
- const watchFolder = (name) => {
683
- if (projectWatchers.has(name) || name.includes("/") || name !== ".workpad" && !FILTER.mayHold(name)) return;
684
- const dir = path.join(project.dir, name);
685
- let isDir = false;
711
+ const isDir = (dir) => {
686
712
  try {
687
- isDir = fs.statSync(dir).isDirectory();
688
- } catch {}
689
- if (isDir) add(name, dir, true, name + "/");
713
+ return fs.statSync(dir).isDirectory();
714
+ } catch {
715
+ return false;
716
+ }
717
+ };
718
+ const watchFolder = (rel) => {
719
+ if (round !== watchRound || projectWatchers.has(rel)) return;
720
+ if (rel !== ".workpad" && !FILTER.mayHold(rel)) return;
721
+ if (!!rel.includes("/") && !watchByFolder) return;
722
+ const dir = path.join(project.dir, rel);
723
+ if (!isDir(dir)) return;
724
+ if (rel === ".workpad" || !watchByFolder) return add(rel, dir, true, rel + "/");
725
+ add(rel, dir, false, rel + "/");
726
+ walk(rel);
727
+ };
728
+ const walk = async (rel) => {
729
+ let ents;
730
+ try {
731
+ ents = await fs.promises.readdir(path.join(project.dir, rel), { withFileTypes: true });
732
+ } catch {
733
+ return;
734
+ }
735
+ for (const ent of ents) if (ent.isDirectory()) watchFolder(rel ? `${rel}/${ent.name}` : ent.name);
690
736
  };
691
737
  if (!files) return add(".workpad", project.wp, true, ".workpad/");
692
738
  add("", project.dir, false, "");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bigmistqke/workpad",
3
- "version": "0.20.0",
3
+ "version": "0.20.2",
4
4
  "description": "A workpad for you and your agent: it writes markdown pages you read live in the browser, you answer through forms it waits on",
5
5
  "keywords": [
6
6
  "agent",
@@ -40,9 +40,15 @@ function readJson(file: string): { value: any; why?: string } | null {
40
40
  }
41
41
  }
42
42
 
43
- /** `$VAR` and `${VAR}` in a command as Claude Code expands them; CLAUDE_PROJECT_DIR is the project. */
43
+ /**
44
+ * `$VAR`, `${VAR}` and `${VAR:-default}` in a command, its args or env as Claude Code expands them
45
+ * (the default when VAR is unset or empty); CLAUDE_PROJECT_DIR is the project.
46
+ */
44
47
  export function expand(s: string, env: Record<string, string | undefined>): string {
45
- return s.replace(/\$\{(\w+)\}|\$(\w+)/g, (_, a, b) => env[a ?? b] ?? '')
48
+ return s.replace(/\$\{(\w+)(?::-([^}]*))?\}|\$(\w+)/g, (_, a, fallback, b) => {
49
+ const value = env[a ?? b]
50
+ return fallback !== undefined && !value ? fallback : (value ?? '')
51
+ })
46
52
  }
47
53
 
48
54
  /** Start the channel's command, ask it to initialize, and stop it: whether it answered, or why not. */
@@ -177,7 +183,9 @@ export async function channelChecks(
177
183
  else if (mcp.value === undefined) lines.push({ mark: 'fail', text: `${mcpFile}: ${mcp.why}`, fix: 'fix the file' })
178
184
  else if (!entry?.command) lines.push({ mark: 'fail', text: `${mcpFile} has no "${SERVER}" server`, fix: install })
179
185
  else {
180
- const env = { ...process.env, CLAUDE_PROJECT_DIR: dir, ...(entry.env ?? {}) }
186
+ const base = { ...process.env, CLAUDE_PROJECT_DIR: dir }
187
+ const own = Object.entries((entry.env ?? {}) as Record<string, string>).map(([k, v]) => [k, expand(String(v), base)])
188
+ const env = { ...base, ...Object.fromEntries(own) }
181
189
  const command = expand(entry.command, env)
182
190
  const args = ((entry.args ?? []) as string[]).map(a => expand(a, env))
183
191
  const why = await probe(command, args, dir, env)
@@ -120,7 +120,7 @@ const mount: PluginMount = (root: HTMLElement, page: PageHandle, api: Api) => {
120
120
  const i = ((turn.get(id) ?? -1) + 1) % list.length
121
121
  turn.set(id, i)
122
122
  const el = list[i]!
123
- el.scrollIntoView({ block: 'center', behavior: 'smooth' })
123
+ el.scrollIntoView({ block: 'center', behavior: 'instant' })
124
124
  el.classList.remove('wp-flash')
125
125
  void el.offsetWidth
126
126
  el.classList.add('wp-flash')
@@ -191,7 +191,7 @@ function current() {
191
191
  function go(i: number) {
192
192
  const h = headings[i]
193
193
  if (!h) return
194
- scrollTo({ top: Math.max(0, scrollY + h.getBoundingClientRect().top - navHeight() - 12), behavior: 'smooth' })
194
+ scrollTo({ top: Math.max(0, scrollY + h.getBoundingClientRect().top - navHeight() - 12), behavior: 'instant' })
195
195
  if (!fits()) setOpen(false)
196
196
  }
197
197
 
@@ -228,7 +228,7 @@ function update() {
228
228
 
229
229
  function go(dir: 'up' | 'down') {
230
230
  const { above, below } = split()
231
- ;(dir === 'up' ? above : below)[0]?.scrollIntoView({ behavior: 'smooth', block: 'start' })
231
+ ;(dir === 'up' ? above : below)[0]?.scrollIntoView({ behavior: 'instant', block: 'start' })
232
232
  }
233
233
  const seeAll = () => {
234
234
  for (const el of [...unseen]) markSeen(el)
@@ -231,7 +231,8 @@ function jumpTo(target: HTMLElement) {
231
231
  0,
232
232
  Math.min(scrollY + r.top + r.height / 2 - viewBottom() / 2, document.documentElement.scrollHeight - innerHeight),
233
233
  )
234
- scrollTo({ top: scrolledTo, behavior: 'smooth' })
234
+ // at once, not scrolled to: the reader asked to be there (the overview's count, a toast)
235
+ scrollTo({ top: scrolledTo, behavior: 'instant' })
235
236
  if (target instanceof HTMLFormElement) {
236
237
  if (target.hasAttribute('data-wp-open'))
237
238
  target
@@ -80,7 +80,7 @@ function goTo(target: HTMLElement | null): boolean {
80
80
  const summary = d.querySelector<HTMLElement>(':scope > summary')
81
81
  if (summary && summary !== target) offset += summary.getBoundingClientRect().height
82
82
  }
83
- scrollTo({ top: Math.max(0, scrollY + target.getBoundingClientRect().top - offset), behavior: 'smooth' })
83
+ scrollTo({ top: Math.max(0, scrollY + target.getBoundingClientRect().top - offset), behavior: 'instant' })
84
84
  target.classList.remove('wp-flash')
85
85
  void target.offsetWidth
86
86
  target.classList.add('wp-flash')
package/src/define.ts CHANGED
@@ -571,9 +571,16 @@ export interface PagesSource extends StoredBase {
571
571
  export interface RenderContext {
572
572
  /**
573
573
  * `files`: whether its own files are served; `shows`: which of them (a path in the project
574
- * folder, with `/`), as its `files` setting says
575
- */
576
- project: { name: string; dir: string; files: boolean; shows?: (rel: string) => boolean }
574
+ * folder, with `/`), as its `files` setting says; `mayHold`: whether a folder can hold one, so a
575
+ * walk looking for them goes into no other
576
+ */
577
+ project: {
578
+ name: string
579
+ dir: string
580
+ files: boolean
581
+ shows?: (rel: string) => boolean
582
+ mayHold?: (rel: string) => boolean
583
+ }
577
584
  /**
578
585
  * The URL the browser loads a file from: a client module, a stylesheet, an image next to a
579
586
  * block. Files are served only once asked for, and are watched from then on:
package/src/entries.ts CHANGED
@@ -14,16 +14,18 @@
14
14
  import fs from 'node:fs'
15
15
  import os from 'node:os'
16
16
  import path from 'node:path'
17
+ import type { FilesConfig } from './files.ts'
17
18
 
18
19
  /** One entry of the machine config: which folders are its projects. */
19
20
  export interface EntryConfig {
20
21
  include: string[]
21
22
  exclude?: string[]
22
23
  /**
23
- * whether its projects serve and watch their own files, when a project's config doesn't say:
24
- * false watches only `.workpad/` (default: true, as a project's config has it)
24
+ * which of their own files its projects serve and watch, when a project's config doesn't say, as
25
+ * a project's config has it: false none (only `.workpad/` is watched), `{ include, exclude }`
26
+ * some (default: true, all but node_modules and .git)
25
27
  */
26
- files?: boolean
28
+ files?: boolean | FilesConfig
27
29
  }
28
30
 
29
31
  /** The machine config: the shared server's port and its entries. */
@@ -49,7 +51,7 @@ export interface EntryProject {
49
51
  /** the URL path it is served under, without a trailing slash: /<entry>/<path> */
50
52
  base: string
51
53
  /** its entry's `files`, when the entry sets it */
52
- files?: boolean
54
+ files?: boolean | FilesConfig
53
55
  }
54
56
 
55
57
  /**
@@ -130,12 +132,21 @@ export function readMachineConfig(dir = machineDir()): MachineConfig | null {
130
132
  throw new Error(`${file}: entries.${name}.${what} must be a list of globs`)
131
133
  return v
132
134
  }
133
- if (e?.files != null && typeof e.files !== 'boolean')
134
- throw new Error(`${file}: entries.${name}.files must be true or false`)
135
+ const files = e?.files
136
+ if (files != null && typeof files !== 'boolean' && (typeof files !== 'object' || Array.isArray(files)))
137
+ throw new Error(`${file}: entries.${name}.files must be true, false or { "include": [...], "exclude": [...] }`)
135
138
  entries[name] = {
136
139
  include: list(e?.include, 'include'),
137
140
  exclude: list(e?.exclude, 'exclude'),
138
- ...(e?.files != null && { files: e.files as boolean }),
141
+ ...(files != null && {
142
+ files:
143
+ typeof files === 'boolean'
144
+ ? files
145
+ : {
146
+ ...(files.include != null && { include: list(files.include, 'files.include') }),
147
+ ...(files.exclude != null && { exclude: list(files.exclude, 'files.exclude') }),
148
+ },
149
+ }),
139
150
  }
140
151
  }
141
152
  const port = raw.port == null ? undefined : Number(raw.port)
package/src/files.ts CHANGED
@@ -26,7 +26,46 @@ export interface FileFilter {
26
26
  mayHold(rel: string): boolean
27
27
  }
28
28
 
29
- const glob = (rel: string, g: string) => path.posix.matchesGlob(rel, g)
29
+ /**
30
+ * Does `rel` match `g`? As `path.posix.matchesGlob`, but a `**` takes in folders whose name starts
31
+ * with a dot as well: matchesGlob's doesn't, so `**\/node_modules` left out nothing under `.claude/`,
32
+ * and an install in a worktree kept there reached the watcher as thousands of changes. Segment by
33
+ * segment: `**` stands for any number of folders, every other segment is matched by matchesGlob.
34
+ */
35
+ export function glob(rel: string, g: string): boolean {
36
+ const parts = g.split('/')
37
+ const segs = rel.split('/')
38
+ // matchesGlob compiles its pattern on each call, and a project's paths repeat the same few names
39
+ // (docs, README.md) in every folder and worktree: each name and segment is matched once
40
+ const segment = (name: string, part: string) => {
41
+ const key = `${part}\0${name}`
42
+ let hit = SEGMENTS.get(key)
43
+ if (hit === undefined) {
44
+ if (SEGMENTS.size > 100_000) SEGMENTS.clear()
45
+ SEGMENTS.set(key, (hit = path.posix.matchesGlob(name, part)))
46
+ }
47
+ return hit
48
+ }
49
+ const seen = new Set<string>()
50
+ const at = (i: number, j: number): boolean => {
51
+ if (i === parts.length) return j === segs.length
52
+ const key = `${i},${j}`
53
+ if (seen.has(key)) return false
54
+ seen.add(key)
55
+ if (parts[i] === '**') {
56
+ for (let k = j; k <= segs.length; k++) if (at(i + 1, k)) return true
57
+ return false
58
+ }
59
+ return j < segs.length && segment(segs[j]!, parts[i]!) && at(i + 1, j + 1)
60
+ }
61
+ return at(0, 0)
62
+ }
63
+
64
+ // a glob segment against a name: whether it matches, as matchesGlob said the first time
65
+ const SEGMENTS = new Map<string, boolean>()
66
+
67
+ // the always-excluded by folder name: checked first, it settles most of a burst cheaply
68
+ const ALWAYS_NAMES = new Set(ALWAYS_EXCLUDED.map(g => g.slice('**/'.length)))
30
69
 
31
70
  /** The path and each folder above it: `a/b/c` → `a/b/c`, `a/b`, `a`. */
32
71
  function* upward(rel: string) {
@@ -56,10 +95,24 @@ export function fileFilter(files?: boolean | FilesConfig): FileFilter {
56
95
  const config = typeof files === 'object' && files ? files : {}
57
96
  const exclude = [...ALWAYS_EXCLUDED, ...(config.exclude ?? [])]
58
97
  const include = config.include?.length ? config.include : null
98
+ // what a path itself matches, kept: each file's folders are asked again for every file in them
99
+ const memo = (test: (p: string) => boolean) => {
100
+ const seen = new Map<string, boolean>()
101
+ return (p: string) => {
102
+ let hit = seen.get(p)
103
+ if (hit === undefined) {
104
+ if (seen.size > 50_000) seen.clear()
105
+ seen.set(p, (hit = test(p)))
106
+ }
107
+ return hit
108
+ }
109
+ }
110
+ const excludes = memo(p => exclude.some(g => glob(p, g)))
111
+ const includes = memo(p => !!include?.some(g => glob(p, g)))
59
112
  // left out: it, or a folder it is in, matches an exclude
60
- const excluded = (rel: string) => [...upward(rel)].some(p => exclude.some(g => glob(p, g)))
113
+ const excluded = (rel: string) => rel.split('/').some(s => ALWAYS_NAMES.has(s)) || [...upward(rel)].some(excludes)
61
114
  // taken in: it, or a folder it is in, matches an include
62
- const included = (rel: string) => !include || [...upward(rel)].some(p => include.some(g => glob(p, g)))
115
+ const included = (rel: string) => !include || [...upward(rel)].some(includes)
63
116
  return {
64
117
  key: JSON.stringify({ include, exclude }),
65
118
  shows: rel => !!rel && !excluded(rel) && included(rel),
package/src/hub.ts CHANGED
@@ -151,7 +151,7 @@ export function createHub({
151
151
  // projects come and go: the overview lists them
152
152
  setImmediate(() => touch())
153
153
  // a project whose entry's files changed is made again with it
154
- const wanted = new Map(projects.map(p => [`${p.base}\n${p.dir}\n${p.files ?? ''}`, p]))
154
+ const wanted = new Map(projects.map(p => [`${p.base}\n${p.dir}\n${JSON.stringify(p.files ?? null)}`, p]))
155
155
  for (const [key, s] of served)
156
156
  if (!wanted.has(key)) {
157
157
  for (const el of entryListens) release(s, el)
@@ -210,14 +210,22 @@ export function createHub({
210
210
  // the projects that changed since: each other project's open pages are told, for their menu of
211
211
  // what waits elsewhere (pushed, so no page has to ask every project now and then)
212
212
  const changes = new Set<string>()
213
+ // told 150 ms after the first change, then at most once a second: a burst of changes (an install
214
+ // writing into a shown folder) re-renders the overview's clients once a second, not at each pause
215
+ let toldAt = 0
213
216
  const touch = () => {
214
- clearTimeout(touching)
215
- touching = setTimeout(() => {
216
- root.touch()
217
- const from = [...changes]
218
- changes.clear()
219
- for (const s of served.values()) if (from.some(b => b !== s.base)) s.server.elsewhere()
220
- }, 150)
217
+ if (touching) return
218
+ touching = setTimeout(
219
+ () => {
220
+ touching = undefined
221
+ toldAt = Date.now()
222
+ root.touch()
223
+ const from = [...changes]
224
+ changes.clear()
225
+ for (const s of served.values()) if (from.some(b => b !== s.base)) s.server.elsewhere()
226
+ },
227
+ Math.max(150, toldAt + 1000 - Date.now()),
228
+ )
221
229
  }
222
230
  const changed = (base: string) => {
223
231
  changes.add(base)
package/src/loader.ts CHANGED
@@ -4,7 +4,7 @@
4
4
  // the pages (how markdown is rendered with their blocks).
5
5
  import fs from 'node:fs'
6
6
  import path from 'node:path'
7
- import { fileFilter, type FileFilter } from './files.ts'
7
+ import { fileFilter, type FileFilter, type FilesConfig } from './files.ts'
8
8
  import { fileURLToPath } from 'node:url'
9
9
  import { importFresh, importOwn } from './load.ts'
10
10
  import { createPages, type Pages } from './pages/index.ts'
@@ -126,12 +126,12 @@ function checkPlugin(e: Plugin, where: string | null) {
126
126
  const RETRY_FAILED_MS = 5000
127
127
 
128
128
  /**
129
- * `files`: whether the project serves its own files when its config doesn't say (a machine config's
130
- * entry can say false for all of its projects; see EntryConfig).
129
+ * `files`: which of its own files the project serves when its config doesn't say (a machine config's
130
+ * entry can say it for all of its projects; see EntryConfig).
131
131
  */
132
132
  export function createConfigLoader(
133
133
  proj: Project,
134
- { pages: withPages = true, files: filesDefault = true }: { pages?: boolean; files?: boolean } = {},
134
+ { pages: withPages = true, files: filesDefault = true }: { pages?: boolean; files?: boolean | FilesConfig } = {},
135
135
  ) {
136
136
  let cached: Promise<LoadedConfig> | null = null
137
137
  let failedAt: number | null = null
@@ -193,8 +193,8 @@ export function createConfigLoader(
193
193
  forReader: new Map([...declared('forReader')].map(type => [type, requires.get(type) ?? []])),
194
194
  requires,
195
195
  publicDirs,
196
- files: config?.files == null ? filesDefault : config.files !== false,
197
- fileFilter: fileFilter(config?.files),
196
+ files: (config?.files ?? filesDefault) !== false,
197
+ fileFilter: fileFilter(config?.files ?? filesDefault),
198
198
  build: config?.build ?? {},
199
199
  commands: configCommands(config?.commands, { taken: RESERVED, plugins: plugins.map(p => p.name), where: configFile }),
200
200
  }
@@ -2,7 +2,7 @@
2
2
  // directives and fences handed to the plugins' blocks (markdown.ts); repository files show as highlighted
3
3
  // code, folders as listings with their README on top; around all of it goes the page's frame.
4
4
  // What the page draws itself is built with `html` (../html.ts), which escapes every value.
5
- import { fileFilter } from '../files.ts'
5
+ import { fileFilter, type FileFilter } from '../files.ts'
6
6
  import { FRONTMATTER } from '../site.ts'
7
7
  import fs from 'node:fs'
8
8
  import os from 'node:os'
@@ -135,7 +135,7 @@ const MARKDOWN = /\.(md|markdown)$/i
135
135
  * built copies and dependencies stay out; elsewhere a walk that skips the usual build and
136
136
  * dependency folders. The project's own pages (.workpad/) are listed apart.
137
137
  */
138
- function documentsIn(dir: string, shows: (rel: string) => boolean = rel => fileFilter().shows(rel)) {
138
+ function documentsIn(dir: string, { shows, mayHold }: Pick<FileFilter, 'shows'> & Partial<Pick<FileFilter, 'mayHold'>> = fileFilter()) {
139
139
  let files: string[]
140
140
  try {
141
141
  files = execFileSync(
@@ -155,9 +155,12 @@ function documentsIn(dir: string, shows: (rel: string) => boolean = rel => fileF
155
155
  return
156
156
  }
157
157
  for (const e of entries) {
158
+ const child = path.posix.join(rel, e.name)
158
159
  if (e.isDirectory()) {
159
- if (!SKIP.has(e.name) && !e.name.startsWith('.')) walk(path.posix.join(rel, e.name))
160
- } else if (MARKDOWN.test(e.name)) files.push(path.posix.join(rel, e.name))
160
+ // only into a folder that can hold something shown: with an include naming docs, a few
161
+ // folders, not each of a checkout's thousands (a container without git walks)
162
+ if (!SKIP.has(e.name) && !e.name.startsWith('.') && (!mayHold || mayHold(child))) walk(child)
163
+ } else if (MARKDOWN.test(e.name)) files.push(child)
161
164
  }
162
165
  }
163
166
  walk('')
@@ -267,7 +270,8 @@ export async function filesFold(dir: string, base: string): Promise<{ count: num
267
270
  * written here), by when last updated, or by title; each row carries what it is sorted by.
268
271
  */
269
272
  function documentList(ctx: RenderContext) {
270
- return documentsOf(ctx.project.dir, ctx.base ?? '', ctx.urlFor, false, ctx.project.shows)
273
+ const { shows, mayHold } = ctx.project
274
+ return documentsOf(ctx.project.dir, ctx.base ?? '', ctx.urlFor, false, shows && { shows, mayHold })
271
275
  }
272
276
 
273
277
  /**
@@ -349,10 +353,10 @@ function documentsOf(
349
353
  base: string,
350
354
  urlFor: (abs: string) => string | null,
351
355
  folded = false,
352
- shows?: (rel: string) => boolean,
356
+ filter?: Pick<FileFilter, 'shows'> & Partial<Pick<FileFilter, 'mayHold'>>,
353
357
  open = false,
354
358
  ) {
355
- const docs = documentsIn(dir, shows).map(f => docOf(dir, f))
359
+ const docs = documentsIn(dir, filter).map(f => docOf(dir, f))
356
360
  if (!docs.length) return ''
357
361
  if (folded) return documentTree(docs, dir, base, urlFor, open)
358
362
  const ctx = { project: { dir }, base, urlFor }
package/src/server.ts CHANGED
@@ -74,7 +74,17 @@ import {
74
74
  type ProjectStatus,
75
75
  } from './status.ts'
76
76
  import { formsIn, messageForms } from './pages/markdown.ts'
77
- import { fileFilter, type FileFilter } from './files.ts'
77
+ import { fileFilter, type FileFilter, type FilesConfig } from './files.ts'
78
+
79
+ /**
80
+ * Watch a project's files folder by folder (each that can hold something shown, at any depth), not
81
+ * a recursive watch per top-level folder: where a recursive watch costs a watch per folder below
82
+ * it, whatever it holds (Linux's inotify). `$WORKPAD_WATCH`: `folders` or `recursive`, else by
83
+ * platform. See setFiles.
84
+ */
85
+ const WATCH_BY_FOLDER = process.env.WORKPAD_WATCH
86
+ ? process.env.WORKPAD_WATCH === 'folders'
87
+ : process.platform !== 'darwin' && process.platform !== 'win32'
78
88
  import { titleOf } from './pages/render.ts'
79
89
  import { createRegistry, follows, holdStream, listenerOf } from './listeners.ts'
80
90
  import { inPublic } from './public.ts'
@@ -189,8 +199,10 @@ export interface ServerOptions {
189
199
  name?: string
190
200
  /** serve and watch the project's files, over the config's `files` */
191
201
  files?: boolean
192
- /** serve and watch the project's files when its config doesn't say (its entry's `files`); default true */
193
- filesDefault?: boolean
202
+ /** which of the project's files are served and watched when its config doesn't say (its entry's `files`); default true */
203
+ filesDefault?: boolean | FilesConfig
204
+ /** watch the project's files folder by folder, not recursively (default: by platform, WATCH_BY_FOLDER) */
205
+ watchByFolder?: boolean
194
206
  /** the overview at / lists these instead of the project's pages (the shared server's own project) */
195
207
  overview?: () => Promise<Pick<PagesSource, 'projects' | 'note'>>
196
208
  /** a page of the project changed, or its log grew: the shared server's overview follows it */
@@ -208,6 +220,7 @@ export function createServer(
208
220
  name,
209
221
  files: filesOption,
210
222
  filesDefault,
223
+ watchByFolder = WATCH_BY_FOLDER,
211
224
  overview,
212
225
  onChange,
213
226
  origins = () => [],
@@ -221,15 +234,30 @@ export function createServer(
221
234
  const streams = new Set<() => void>()
222
235
  const watch = (dir: string, options: fs.WatchOptions, fn: (name: string) => void) => {
223
236
  try {
224
- watchers.add(
225
- fs.watch(dir, options, (_evt, name) => {
226
- if (name) fn(String(name))
227
- }),
228
- )
229
- } catch {
230
- /* gone, or not built */
237
+ const w = fs.watch(dir, options, (_evt, name) => {
238
+ if (name) fn(String(name))
239
+ })
240
+ // an error later (the folder gone, the system out of watches) ends this watch, not the server
241
+ w.on('error', err => {
242
+ outOfWatches(err)
243
+ w.close()
244
+ watchers.delete(w)
245
+ })
246
+ watchers.add(w)
247
+ } catch (err) {
248
+ outOfWatches(err) /* else gone, or not built */
231
249
  }
232
250
  }
251
+ // the system out of watches or open files (EMFILE, ENOSPC): said once, and what was asked goes unwatched
252
+ let told = false
253
+ const outOfWatches = (err: unknown) => {
254
+ const code = (err as NodeJS.ErrnoException)?.code
255
+ if (told || (code !== 'EMFILE' && code !== 'ENOSPC')) return
256
+ told = true
257
+ console.error(
258
+ `workpad: ${project.dir}: out of watches (${code}); some of its files won't go live. Narrow the config's files, or raise the limit`,
259
+ )
260
+ }
233
261
 
234
262
  // ---- plugins --------------------------------------------------------------------------------
235
263
  // Behaviour on every page: each one's setup runs once per loaded config.
@@ -360,7 +388,13 @@ export function createServer(
360
388
  }
361
389
 
362
390
  const context = () => ({
363
- project: { name: projectName(), dir: project.dir, files: !!FILES, shows: (rel: string) => FILTER.shows(rel) },
391
+ project: {
392
+ name: projectName(),
393
+ dir: project.dir,
394
+ files: !!FILES,
395
+ shows: (rel: string) => FILTER.shows(rel),
396
+ mayHold: (rel: string) => FILTER.mayHold(rel),
397
+ },
364
398
  asset,
365
399
  urlFor,
366
400
  base,
@@ -885,65 +919,97 @@ export function createServer(
885
919
  // With files on, the whole project folder is watched (repository views stay live); with files off,
886
920
  // only .workpad/, so a project in a large folder such as the home folder stays cheap. A folder
887
921
  // that holds nothing shown (node_modules, .git, what the config's `files` leaves out: src/files.ts)
888
- // is never watched: an install or a checkout changes thousands of files there that nothing shows,
889
- // and on Linux a recursive watch holds a watch for every folder below it. So the project folder
890
- // itself is watched without recursing, and each folder in it that can hold something shown
891
- // recursively, one made later too. One left out deeper down (a package's own node_modules) is
892
- // watched, its changes passed over (fileChanged).
922
+ // is never watched: an install or a checkout changes thousands of files there that nothing shows.
923
+ // How, by platform (watchByFolder): on Linux a recursive watch is one inotify watch per folder
924
+ // below it, node_modules and nested checkouts' dependencies too (10 checkouts: 113,899 watches,
925
+ // the first request blocked for minutes while they were set up), so each folder that can hold
926
+ // something shown is watched on its own, at any depth, found without blocking, and one made later
927
+ // too. On macOS a recursive watch is a single FSEvents stream, cheap however deep, and a watch
928
+ // per folder would rebuild it at every one added: the project folder is watched without
929
+ // recursing, each folder in it that can hold something shown recursively, and what is left out
930
+ // deeper down (a package's own node_modules) is passed over (fileChanged), cheaply.
893
931
  let FILES: boolean | null = null
894
932
  // which of the project's files are shown (the config's `files`, src/files.ts)
895
933
  let FILTER: FileFilter = fileFilter()
934
+ // a watcher per folder watched, by its path in the project folder ('' the project folder itself)
896
935
  let projectWatchers = new Map<string, fs.FSWatcher>()
936
+ // counts each setFiles: a walk still finding folders for an earlier one stops
937
+ let watchRound = 0
897
938
  function setFiles(files: boolean, filter: FileFilter = fileFilter()) {
898
939
  if (files === FILES && filter.key === FILTER.key) return
899
940
  FILES = files
900
941
  FILTER = filter
942
+ const round = ++watchRound
901
943
  for (const w of projectWatchers.values()) {
902
944
  w.close()
903
945
  watchers.delete(w)
904
946
  }
905
947
  projectWatchers = new Map()
948
+ const drop = (key: string) => {
949
+ for (const [k, w] of projectWatchers)
950
+ if (k === key || k.startsWith(key + '/')) {
951
+ w.close()
952
+ watchers.delete(w)
953
+ projectWatchers.delete(k)
954
+ }
955
+ }
906
956
  const add = (key: string, dir: string, recursive: boolean, prefix: string) => {
907
957
  try {
908
958
  const w = fs.watch(dir, { recursive }, (evt, filename) => {
909
959
  if (!filename) return
910
960
  const name = filename.toString().replace(/\\/g, '/')
911
961
  fileChanged(prefix + name)
912
- // a folder made, removed or made again in the project folder: watched afresh, if it is there
962
+ // a folder made, removed or made again in a folder watched on its own: watched afresh, if it is there
913
963
  if (!recursive && evt === 'rename') {
914
- const old = projectWatchers.get(name)
915
- if (old) {
916
- old.close()
917
- watchers.delete(old)
918
- projectWatchers.delete(name)
919
- }
920
- watchFolder(name)
964
+ const child = prefix + name
965
+ drop(child)
966
+ watchFolder(child)
921
967
  }
922
968
  })
923
969
  // a folder that goes: its watcher with it
924
- w.on('error', () => {
925
- w.close()
926
- watchers.delete(w)
927
- projectWatchers.delete(key)
970
+ w.on('error', err => {
971
+ outOfWatches(err)
972
+ drop(key)
928
973
  })
929
974
  projectWatchers.set(key, w)
930
975
  watchers.add(w)
976
+ } catch (err) {
977
+ outOfWatches(err) /* else gone meanwhile */
978
+ }
979
+ }
980
+ const isDir = (dir: string) => {
981
+ try {
982
+ return fs.statSync(dir).isDirectory()
931
983
  } catch {
932
- /* gone meanwhile */
984
+ return false
933
985
  }
934
986
  }
935
- const watchFolder = (name: string) => {
936
- // .workpad always; of the rest, a folder that can hold something shown
937
- if (projectWatchers.has(name) || name.includes('/') || (name !== '.workpad' && !FILTER.mayHold(name))) return
938
- const dir = path.join(project.dir, name)
939
- let isDir = false
987
+ // a folder in the project folder (`src`, `src/lib` by folder): watched, if it can hold something shown
988
+ const watchFolder = (rel: string) => {
989
+ if (round !== watchRound || projectWatchers.has(rel)) return
990
+ if (rel !== '.workpad' && !FILTER.mayHold(rel)) return
991
+ const top = !rel.includes('/')
992
+ if (!top && !watchByFolder) return
993
+ const dir = path.join(project.dir, rel)
994
+ if (!isDir(dir)) return
995
+ // .workpad recursively, everywhere: it is small, and its pages' folders come and go
996
+ if (rel === '.workpad' || !watchByFolder) return add(rel, dir, true, rel + '/')
997
+ add(rel, dir, false, rel + '/')
998
+ void walk(rel)
999
+ }
1000
+ // the folders in a folder watched on its own, each watched in turn; read off the event loop
1001
+ const walk = async (rel: string) => {
1002
+ let ents: fs.Dirent[]
940
1003
  try {
941
- isDir = fs.statSync(dir).isDirectory()
942
- } catch {}
943
- if (isDir) add(name, dir, true, name + '/')
1004
+ ents = await fs.promises.readdir(path.join(project.dir, rel), { withFileTypes: true })
1005
+ } catch {
1006
+ return
1007
+ }
1008
+ for (const ent of ents) if (ent.isDirectory()) watchFolder(rel ? `${rel}/${ent.name}` : ent.name)
944
1009
  }
945
1010
  if (!files) return add('.workpad', project.wp, true, '.workpad/')
946
1011
  add('', project.dir, false, '')
1012
+ // the folders in the project folder at once, as it starts; deeper ones as they are found
947
1013
  for (const ent of fs.readdirSync(project.dir, { withFileTypes: true })) if (ent.isDirectory()) watchFolder(ent.name)
948
1014
  }
949
1015