@dogsbay/search 0.2.0-beta.150 → 0.2.0-beta.152

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
@@ -40,7 +40,9 @@ Every `.html` page is indexed, except redirects and `noindex` pages. The indexer
40
40
  </script>
41
41
  ```
42
42
 
43
- `dogsbay-search.iife.js` is in `dist/` (about 10 KB). URLs in results are relative to the site root the index was built from. The package has no search box of its own: dogsbay-ssg's dialog (`src/client/search.ts` there) is an example.
43
+ Several indexes in one page (a product's versions, or several products): give each its own `scriptData`, and search them together with `searchSources(q, [{ data, boost, collapse }, …])`, which merges results by score and shows a page once across versions. An index that does not load (a version not built yet) or is another format is left out and listed in `missing`. Pages can carry facets (`SearchDoc.facets`, one per taxonomy): `search` and `searchSources` return their counts over every result as `facets`. Over several indexes, a facet filter leaves out every index that does not declare that facet. See `docs-dev/design.md` ("Several indexes").
44
+
45
+ `dogsbay-search.iife.js` is in `dist/` (about 15 KB). URLs in results are relative to the site root the index was built from. The package has no search box of its own: dogsbay-ssg's dialog (`src/client/search.ts` there) is an example.
44
46
 
45
47
  ## Use it from code
46
48
 
@@ -58,7 +60,8 @@ On a large site, call `index.takeReadyFiles()` after each `add` and write what i
58
60
 
59
61
  - `@dogsbay/search/index`: `SearchIndexBuilder`, and `extractText()` for a dogsbay document tree. It reads API reference nodes too: an OpenAPI operation's method and path, summary, description, parameters and schema properties (nested ones included); autodoc symbol names (as headings) and docstrings; and an embedded spec's descriptions. Code (signatures, source, samples) is skipped, as code blocks are.
60
62
  - `@dogsbay/search/html`: `extractHtml()`.
61
- - `@dogsbay/search/query`: `search()`, `parseQuery()`, `scriptData()`, `memoryData()`.
63
+ - `@dogsbay/search/query`: `search()`, `searchSources()`, `querySources()`, `parseQuery()`, `facetCounts()`, `scriptData()`, `memoryData()`.
64
+ - `@dogsbay/search/facets`: pure helpers for a facet column (`shapeFacets`, labels, order, hierarchical trees, filter state in the URL), shared by both pipelines.
62
65
  - `@dogsbay/search/site`: `indexSite(dir)`, for Node.
63
66
 
64
67
  Everything except `site` is Worker- and browser-safe.
@@ -73,6 +76,7 @@ Everything except `site` is Worker- and browser-safe.
73
76
  | `linux OR macos` | Either word. |
74
77
  | `install tag:setup` | Pages tagged `setup`. |
75
78
  | `upgrade section:"Getting started"` | Pages in that section. |
79
+ | `install audience:operator type:how-to` | Pages with those values of the index's declared facets (taxonomies): values of one facet are alternatives, every facet must match. |
76
80
 
77
81
  ## More
78
82
 
@@ -1 +1 @@
1
- "use strict";var DogsbaySearch=(()=>{var z=Object.defineProperty;var X=Object.getOwnPropertyDescriptor;var Z=Object.getOwnPropertyNames;var tt=Object.prototype.hasOwnProperty;var et=(n,t)=>{for(var o in t)z(n,o,{get:t[o],enumerable:!0})},nt=(n,t,o,e)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Z(t))!tt.call(n,r)&&r!==o&&z(n,r,{get:()=>t[r],enumerable:!(e=X(t,r))||e.enumerable});return n};var st=n=>nt(z({},"__esModule",{value:!0}),n);var Et={};et(Et,{loadDetails:()=>K,loadScript:()=>Rt,parseQuery:()=>E,scriptData:()=>J,search:()=>q});var v={docs:"docs.js",shard:n=>`t-${n}.js`,fragment:n=>`f-${n}.js`},$={docs:"docs",shard:n=>n,fragment:n=>`frag:${n}`};var rt={ational:"ate",tional:"tion",enci:"ence",anci:"ance",izer:"ize",bli:"ble",alli:"al",entli:"ent",eli:"e",ousli:"ous",ization:"ize",ation:"ate",ator:"ate",alism:"al",iveness:"ive",fulness:"ful",ousness:"ous",aliti:"al",iviti:"ive",biliti:"ble",logi:"log"},ot={icate:"ic",ative:"",alize:"al",iciti:"ic",ical:"ic",ful:"",ness:""},it="[^aeiou]",F="[aeiouy]",y="("+it+"[^aeiouy]*)",R="("+F+"[aeiou]*)",O=new RegExp("^"+y+"?"+R+y),at=new RegExp("^"+y+"?"+R+y+R+"?$"),D=new RegExp("^"+y+"?("+R+y+"){2,}"),C=new RegExp("^"+y+"?"+F),L=new RegExp("^"+y+F+"[^aeiouwxy]$"),ct=/ll$/,lt=/^(.+?)e$/,ft=/^(.+?)y$/,gt=/^(.+?(s|t))(ion)$/,ut=/^(.+?)(ed|ing)$/,ht=/(at|bl|iz)$/,dt=/^(.+?)eed$/,pt=/^.+?[^s]s$/,mt=/^.+?(ss|i)es$/,wt=/([^aeiouylsz])\1$/,xt=/^(.+?)(ational|tional|enci|anci|izer|bli|alli|entli|eli|ousli|ization|ation|ator|alism|iveness|fulness|ousness|aliti|iviti|biliti|logi)$/,bt=/^(.+?)(icate|ative|alize|iciti|ical|ful|ness)$/,yt=/^(.+?)(al|ance|ence|er|ic|able|ible|ant|ement|ment|ent|ou|ism|ate|iti|ous|ive|ize)$/;function N(n){let t=String(n).toLowerCase();if(t.length<3)return t;let o=!1;t.codePointAt(0)===121&&(o=!0,t="Y"+t.slice(1)),mt.test(t)?t=t.slice(0,-2):pt.test(t)&&(t=t.slice(0,-1));let e;return(e=dt.exec(t))?O.test(e[1])&&(t=t.slice(0,-1)):(e=ut.exec(t))&&C.test(e[1])&&(t=e[1],ht.test(t)?t+="e":wt.test(t)?t=t.slice(0,-1):L.test(t)&&(t+="e")),(e=ft.exec(t))&&C.test(e[1])&&(t=e[1]+"i"),(e=xt.exec(t))&&O.test(e[1])&&(t=e[1]+rt[e[2]]),(e=bt.exec(t))&&O.test(e[1])&&(t=e[1]+ot[e[2]]),(e=yt.exec(t))?D.test(e[1])&&(t=e[1]):(e=gt.exec(t))&&D.test(e[1])&&(t=e[1]),(e=lt.exec(t))&&(D.test(e[1])||at.test(e[1])&&!L.test(e[1]))&&(t=e[1]),ct.test(t)&&D.test(t)&&(t=t.slice(0,-1)),o&&(t="y"+t.slice(1)),t}var j=new Set("a an and are as at be by for from has have in is it its of on or that the this to was were will with you your can not".split(" ")),St=/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u,_;function Mt(n){if(_===void 0)try{_=typeof Intl<"u"&&"Segmenter"in Intl?new Intl.Segmenter(void 0,{granularity:"word"}):null}catch{_=null}if(_)return[..._.segment(n)].filter(e=>e.isWordLike).map(e=>e.segment);let t=[...n];if(t.length<2)return t;let o=[];for(let e=0;e<t.length-1;e++)o.push(t[e]+t[e+1]);return o}function S(n){let t=[];for(let o of n.toLowerCase().normalize("NFKD").replace(/[̀-ͯ]/g,"").normalize("NFC").matchAll(/[\p{L}\p{N}][\p{L}\p{N}_.-]*[\p{L}\p{N}]|[\p{L}\p{N}]/gu)){let e=o[0],r=e.split(/[._-]+/).filter(Boolean);if(r.length>1&&t.push(e),r.length>1&&!/[._]/.test(e)){let s=r.join("");s.length>=3&&!j.has(s)&&t.push(s)}for(let s of r)St.test(s)?t.push(...Mt(s)):s.length>=2&&!j.has(s)&&t.push(s)}return t}function G(n,t){let o="";for(let e of n.slice(0,t))o+=/[a-z0-9]/.test(e)?e:`_${e.codePointAt(0).toString(16)}_`;return o}function P(n){if(!(!n||!/^en(-|$)/i.test(n)))return t=>/^[a-z]{3,}$/.test(t)?N(t):t}function E(n){let t=[],o=[],e=[],r=!1,s={tag:[],section:[]},f={tag:[],section:[]},p=[...n.matchAll(/(?<!\S)(-?)(tag|section):(?:"([^"]*)"?|(\S*))|(-?)"([^"]*)"?|(\S+)/gi)].map(c=>({facetNeg:c[1]==="-",facet:c[2]?.toLowerCase(),value:c[3]??c[4],neg:c[5],phrase:c[6],word:c[7]})),a=!1,u=!1;for(let[c,g]of p.entries()){if(g.facet){let b=Y(g.value??"");b&&(g.facetNeg?f:s)[g.facet].push(b);continue}let l=g.word;if(l==="OR"){u=t.length>0,r=!0;continue}if(l==="NOT"){a=!0,r=!0;continue}if(l==="AND"){r=!0;continue}let h=g.phrase!==void 0,m=a||g.neg==="-"||l?.startsWith("-")&&l.length>1;a=!1;let w=h?g.phrase:m&&l?.startsWith("-")?l.slice(1):l,d=[...new Set(S(w))];if(!d.length){u=!1;continue}if(m){o.push(h?d:[d[0]]),r=!0,u=!1;continue}if(h){u=!1,r=!0,d.length>1&&e.push(S(w).join(" "));for(let b of d)t.push({terms:[b],prefix:!1,exact:!0});continue}let M=c===p.length-1&&!/\s$/.test(n);if(u){t[t.length-1].terms.push(d[0]);for(let b of d.slice(1))t.push({terms:[b],prefix:!1});u=!1;continue}let A=d[0],U=/[._-]/.test(A),V=A.replace(/-/g,"");for(let[b,k]of d.entries())t.push({terms:[k],prefix:M&&k.length>=2&&(b===d.length-1||U&&(k===A||k===V))})}let i=[...new Set(t.flatMap(c=>c.terms))];return{groups:t,not:o,phrases:e,strict:r,highlight:i,filters:s,notFilters:f}}async function _t(n,t){let o=await t.meta(),e=typeof n=="string"?E(n):n,r=new Set;for(let u of e.not){let i;for(let c of u){let[g]=I(c,o),l=g?await t.shard(g):void 0,h=l&&Object.hasOwn(l,c)?l[c]:[],m=new Set;for(let w=0;w<h.length;w+=2)(!i||i.has(h[w]))&&m.add(h[w]);i=m}for(let c of i??[])r.add(c)}let s=vt(e,o);if(!e.groups.length){if(!s)return[];let u=[];return o.docs.forEach(([i,c,g],l)=>s(l)&&!r.has(l)&&u.push({id:l,title:i,url:c,section:o.sections[g]??"",score:1})),u}let f=[];for(let u of e.groups)f.push(await $t(u,o,t));let p=u=>{let i=new Map,c=new Map;for(let l of f)for(let[h,m]of l)i.set(h,(i.get(h)??0)+m),c.set(h,(c.get(h)??0)+1);let g=[];for(let[l,h]of i){if(r.has(l)||s&&!s(l)||u==="and"&&c.get(l)!==f.length)continue;let[m,w,d]=o.docs[l];g.push({id:l,title:m,url:w,section:o.sections[d]??"",score:h*(c.get(l)/f.length)})}return g.sort((l,h)=>h.score-l.score)},a=p("and");return a.length||e.strict?a:p("or")}var x={prefix:.6,stem:.4,titleAll:1.5,titleExact:2,headingAll:1.4,headingExact:1.8,phrase:1.5,typo:.3};function Pt(n,t){if(n===t)return!1;if(n.length===t.length){let s=[];for(let f=0;f<n.length&&s.length<=2;f++)n[f]!==t[f]&&s.push(f);return s.length===1?!0:s.length===2&&s[1]===s[0]+1&&n[s[0]]===t[s[1]]&&n[s[1]]===t[s[0]]}let[o,e]=n.length<t.length?[n,t]:[t,n];if(e.length-o.length!==1)return!1;let r=0;for(;r<o.length&&o[r]===e[r];)r++;return o.slice(r)===e.slice(r+1)}function I(n,t,o=!1){let e=kt(t);for(let s=Math.min(n.length,W);s>=1;s--){let f=G(n,s);if(e.has(f))return!o||s<n.length?[f]:[f,...t.shards.filter(p=>p.length>f.length&&p.startsWith(f)).slice(0,10)]}let r=G(n,Math.min(n.length,W));return o?t.shards.filter(s=>s.startsWith(r)).slice(0,10):[]}var W=3,Q=new WeakMap;function kt(n){let t=Q.get(n);return t||Q.set(n,t=new Set(n.shards)),t}function Y(n){return n.replace(/"/g,"").trim().toLowerCase()}function vt(n,t){let{tag:o,section:e}=n.filters,r=n.notFilters??{tag:[],section:[]};if(!o.length&&!e.length&&!r.tag.length&&!r.section.length)return;let s=(i,c)=>new Set(i.flatMap((g,l)=>c.includes(Y(g))?[l]:[])),f=s(t.sections,e),p=s(t.tags??[],o),a=s(t.sections,r.section),u=s(t.tags??[],r.tag);return i=>{let c=t.docs[i],g=c[3]??[];return!(e.length&&!f.has(c[2])||o.length&&!g.some(l=>p.has(l))||a.has(c[2])||g.some(l=>u.has(l)))}}async function $t(n,t,o){n.corrected=void 0;let e=P(t.lang),r=new Map,s=new Map;for(let i of n.terms)for(let c of I(i,t,n.prefix)){let g=await o.shard(c);if(!g)continue;let l=(d,M)=>{M>(r.get(d)??0)&&(r.set(d,M),s.set(d,g))};Object.hasOwn(g,i)&&l(i,1);let h=e?.(i),m=h?h.slice(0,Math.max(3,h.length-1)):void 0,w=0;for(let d in g)d!==i&&(n.prefix&&d.startsWith(i)&&w++<200&&l(d,x.prefix),h&&m&&d.startsWith(m)&&e(d)===h&&l(d,x.stem));if(!r.size&&!n.exact&&i.length>=4&&!/[._-]/.test(i))for(let d in g)Math.abs(d.length-i.length)<=1&&Pt(i,d)&&l(d,x.typo)}[...r.values()].some(i=>i===x.typo)&&(n.corrected=[...r].filter(([,i])=>i===x.typo).map(([i])=>i));let f=[...r].map(([i,c])=>[s.get(i)[i],c]),p=new Set;for(let[i]of f)for(let c=0;c<i.length;c+=2)p.add(i[c]);let a=Math.log(1+(t.count-p.size+.5)/(p.size+.5)),u=new Map;for(let[i,c]of f)for(let g=0;g<i.length;g+=2)u.set(i[g],Math.max(u.get(i[g])??0,i[g+1]*c*a));return u}async function B(n,t){let o=await t.meta(),e=[...new Set(n.map(s=>Math.floor(s.id/o.block)))],r=new Map;await Promise.all(e.map(async s=>r.set(s,await t.fragment(s))));for(let s of n)s.fragment??(s.fragment=r.get(Math.floor(s.id/o.block))?.[s.id%o.block])}async function Dt(n,t,o,e=10){let r=t.slice(0,e);await B(r,o);let s=n.groups,f=P((await o.meta()).lang),p=(a,u)=>u.terms.some(i=>a===i||u.prefix&&a.startsWith(i)||f!==void 0&&f(a)===f(i))||(u.corrected??[]).includes(a);for(let a of r){let[u,i]=a.fragment??["",[]],c=S(a.title),g=1;s.length&&s.every(h=>c.some(m=>p(m,h)))&&(g=H(c,s,p)?x.titleExact:x.titleAll);let l=[];for(let[h,m]of i){let w=S(h);!s.length||!s.every(d=>w.some(M=>p(M,d)))||(l.push([h,m]),g=Math.max(g,H(w,s,p)?x.headingExact:x.headingAll))}if(a.sections=l.slice(0,3),n.phrases.length){let h=[a.title,u,...i.map(([m])=>m)].map(m=>S(m).join(" ")).join(" \0 ");n.phrases.every(m=>h.includes(m))&&(g*=x.phrase)}a.score*=g}return r.sort((a,u)=>u.score-a.score),[...r,...t.slice(e)]}async function K(n,t,o){await B(t,o);let e=P((await o.meta()).lang),r=(s,f)=>f.terms.some(p=>s===p||f.prefix&&s.startsWith(p)||e!==void 0&&e(s)===e(p))||(f.corrected??[]).includes(s);for(let s of t)!s.fragment||s.sections||(s.sections=s.fragment[1].filter(([f])=>{let p=S(f);return n.groups.length>0&&n.groups.every(a=>p.some(u=>r(u,a)))}).slice(0,3))}function H(n,t,o){return n.every(e=>t.some(r=>o(e,r)))&&t.every(e=>n.some(r=>o(r,e)))}async function q(n,t,o=10){let e=E(n),r=P((await t.meta()).lang);r&&(e.highlight=[...new Set([...e.highlight,...e.highlight.map(r).filter(f=>f.length>=3)])]);let s=await _t(e,t);return e.highlight=[...new Set([...e.highlight,...e.groups.flatMap(f=>f.corrected??[])])],{parsed:e,results:await Dt(e,s,t,o)}}function J(n,t,o=globalThis){let e=new Map,r=o.__DOGSBAY_SEARCH__??{q:[],load(){}};for(let[a,u]of r.q)e.set(a,u);r.q=[],r.load=(a,u)=>{e.set(a,u)},o.__DOGSBAY_SEARCH__=r;let s=async(a,u)=>(e.has(a)||await t(n+u),e.get(a)),f,p={meta:()=>f??(f=s($.docs,v.docs).then(a=>{if(!a||a.format!==4)throw new Error(`search index format ${a?.format??"missing"}, expected ${4}: rebuild the site`);return a})),shard:async a=>(await p.meta()).shards.includes(a)?s($.shard(a),v.shard(a)):void 0,fragment:a=>s($.fragment(a),v.fragment(a))};return p}function Rt(n){return new Promise((t,o)=>{let e=document.createElement("script");e.src=n,e.onload=()=>t(),e.onerror=()=>o(new Error(`failed to load ${n}`)),document.head.append(e)})}return st(Et);})();
1
+ "use strict";var DogsbaySearch=(()=>{var T=Object.defineProperty;var Mt=Object.getOwnPropertyDescriptor;var Rt=Object.getOwnPropertyNames;var Pt=Object.prototype.hasOwnProperty;var kt=(e,t)=>{for(var o in t)T(e,o,{get:t[o],enumerable:!0})},Ft=(e,t,o,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Rt(t))!Pt.call(e,r)&&r!==o&&T(e,r,{get:()=>t[r],enumerable:!(n=Mt(t,r))||n.enumerable});return e};var Dt=e=>Ft(T({},"__esModule",{value:!0}),e);var ee={};kt(ee,{facetCounts:()=>j,facetNames:()=>O,loadDetails:()=>pt,loadScript:()=>te,parseQuery:()=>_,scriptData:()=>wt,search:()=>mt,searchSources:()=>bt});var U=/^[a-z][a-z0-9_-]{0,63}$/,$={docs:"docs.js",shard:e=>`t-${e}.js`,fragment:e=>`f-${e}.js`},E={docs:"docs",shard:e=>e,fragment:e=>`frag:${e}`};var _t={ational:"ate",tional:"tion",enci:"ence",anci:"ance",izer:"ize",bli:"ble",alli:"al",entli:"ent",eli:"e",ousli:"ous",ization:"ize",ation:"ate",ator:"ate",alism:"al",iveness:"ive",fulness:"ful",ousness:"ous",aliti:"al",iviti:"ive",biliti:"ble",logi:"log"},Ot={icate:"ic",ative:"",alize:"al",iciti:"ic",ical:"ic",ful:"",ness:""},vt="[^aeiou]",Q="[aeiouy]",P="("+vt+"[^aeiouy]*)",z="("+Q+"[aeiou]*)",L=new RegExp("^"+P+"?"+z+P),$t=new RegExp("^"+P+"?"+z+P+z+"?$"),A=new RegExp("^"+P+"?("+z+P+"){2,}"),J=new RegExp("^"+P+"?"+Q),V=new RegExp("^"+P+Q+"[^aeiouwxy]$"),Et=/ll$/,At=/^(.+?)e$/,zt=/^(.+?)y$/,Ct=/^(.+?(s|t))(ion)$/,jt=/^(.+?)(ed|ing)$/,Gt=/(at|bl|iz)$/,Nt=/^(.+?)eed$/,Tt=/^.+?[^s]s$/,Lt=/^.+?(ss|i)es$/,Qt=/([^aeiouylsz])\1$/,Wt=/^(.+?)(ational|tional|enci|anci|izer|bli|alli|entli|eli|ousli|ization|ation|ator|alism|iveness|fulness|ousness|aliti|iviti|biliti|logi)$/,It=/^(.+?)(icate|ative|alize|iciti|ical|ful|ness)$/,Ht=/^(.+?)(al|ance|ence|er|ic|able|ible|ant|ement|ment|ent|ou|ism|ate|iti|ous|ive|ize)$/;function X(e){let t=String(e).toLowerCase();if(t.length<3)return t;let o=!1;t.codePointAt(0)===121&&(o=!0,t="Y"+t.slice(1)),Lt.test(t)?t=t.slice(0,-2):Tt.test(t)&&(t=t.slice(0,-1));let n;return(n=Nt.exec(t))?L.test(n[1])&&(t=t.slice(0,-1)):(n=jt.exec(t))&&J.test(n[1])&&(t=n[1],Gt.test(t)?t+="e":Qt.test(t)?t=t.slice(0,-1):V.test(t)&&(t+="e")),(n=zt.exec(t))&&J.test(n[1])&&(t=n[1]+"i"),(n=Wt.exec(t))&&L.test(n[1])&&(t=n[1]+_t[n[2]]),(n=It.exec(t))&&L.test(n[1])&&(t=n[1]+Ot[n[2]]),(n=Ht.exec(t))?A.test(n[1])&&(t=n[1]):(n=Ct.exec(t))&&A.test(n[1])&&(t=n[1]),(n=At.exec(t))&&(A.test(n[1])||$t.test(n[1])&&!V.test(n[1]))&&(t=n[1]),Et.test(t)&&A.test(t)&&(t=t.slice(0,-1)),o&&(t="y"+t.slice(1)),t}var Z=new Set("a an and are as at be by for from has have in is it its of on or that the this to was were will with you your can not".split(" ")),Yt=/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u,F;function Bt(e){if(F===void 0)try{F=typeof Intl<"u"&&"Segmenter"in Intl?new Intl.Segmenter(void 0,{granularity:"word"}):null}catch{F=null}if(F)return[...F.segment(e)].filter(n=>n.isWordLike).map(n=>n.segment);let t=[...e];if(t.length<2)return t;let o=[];for(let n=0;n<t.length-1;n++)o.push(t[n]+t[n+1]);return o}function k(e){let t=[];for(let o of e.toLowerCase().normalize("NFKD").replace(/[̀-ͯ]/g,"").normalize("NFC").matchAll(/[\p{L}\p{N}][\p{L}\p{N}_.-]*[\p{L}\p{N}]|[\p{L}\p{N}]/gu)){let n=o[0],r=n.split(/[._-]+/).filter(Boolean);if(r.length>1&&t.push(n),r.length>1&&!/[._]/.test(n)){let s=r.join("");s.length>=3&&!Z.has(s)&&t.push(s)}for(let s of r)Yt.test(s)?t.push(...Bt(s)):s.length>=2&&!Z.has(s)&&t.push(s)}return t}function W(e,t){let o="";for(let n of e.slice(0,t))o+=/[a-z0-9]/.test(n)?n:`_${n.codePointAt(0).toString(16)}_`;return o}function D(e){if(!(!e||!/^en(-|$)/i.test(e)))return t=>/^[a-z]{3,}$/.test(t)?X(t):t}function _(e,t={}){var x,h;let o=[],n=[],r=[],s=!1,i={tag:[],section:[]},a={tag:[],section:[]},u=Object.create(null),l=Object.create(null),f=["tag","section",...new Set((t.facets??[]).filter(g=>U.test(g)&&g!=="tag"&&g!=="section"))],p=new RegExp(`(?<!\\S)(-?)(${f.join("|")}):(?:"([^"]*)"?|(?!\\/\\/)(\\S*))|(-?)"([^"]*)"?|(\\S+)`,"gi"),S=[...e.matchAll(p)].map(g=>({facetNeg:g[1]==="-",facet:g[2]?.toLowerCase(),value:g[3]??g[4],neg:g[5],phrase:g[6],word:g[7]})),c=!1,d=!1;for(let[g,m]of S.entries()){if(m.facet){let M=B(m.value??"");if(!M)continue;m.facet==="tag"||m.facet==="section"?(m.facetNeg?a:i)[m.facet].push(M):((x=m.facetNeg?l:u)[h=m.facet]??(x[h]=[])).push(M);continue}let w=m.word;if(w==="OR"){d=o.length>0,s=!0;continue}if(w==="NOT"){c=!0,s=!0;continue}if(w==="AND"){s=!0;continue}let G=m.phrase!==void 0,K=c||m.neg==="-"||w?.startsWith("-")&&w.length>1;c=!1;let q=G?m.phrase:K&&w?.startsWith("-")?w.slice(1):w,y=[...new Set(k(q))];if(!y.length){d=!1;continue}if(K){n.push(G?y:[y[0]]),s=!0,d=!1;continue}if(G){d=!1,s=!0,y.length>1&&r.push(k(q).join(" "));for(let M of y)o.push({terms:[M],prefix:!1,exact:!0});continue}let St=g===S.length-1&&!/\s$/.test(e);if(d){o[o.length-1].terms.push(y[0]);for(let M of y.slice(1))o.push({terms:[M],prefix:!1});d=!1;continue}let N=y[0],xt=/[._-]/.test(N),yt=N.replace(/-/g,"");for(let[M,v]of y.entries())o.push({terms:[v],prefix:St&&v.length>=2&&(M===y.length-1||xt&&(v===N||v===yt))})}let b=[...new Set(o.flatMap(g=>g.terms))];return{groups:o,not:n,phrases:r,strict:s,highlight:b,filters:i,notFilters:a,...Object.keys(u).length?{facets:u}:{},...Object.keys(l).length?{notFacets:l}:{}}}async function Kt(e,t){let o=await t.meta(),n=typeof e=="string"?_(e,{facets:O([o])}):e,r=await ot(n,o,t),s=ct(n,o);if(!n.groups.length)return it(o,r,s);let i=[];for(let u of n.groups)i.push(await Jt(u,o,t));let a=H(i,o,r,s,"and").sort(C);return a.length||n.strict?a:H(i,o,r,s,"or").sort(C)}var C=(e,t)=>t.score-e.score;async function ot(e,t,o){let n=new Set;for(let r of e.not){let s;for(let i of r){let[a]=at(i,t),u=a?await o.shard(a):void 0,l=u&&Object.hasOwn(u,i)?u[i]:[],f=new Set;for(let p=0;p<l.length;p+=2)(!s||s.has(l[p]))&&f.add(l[p]);s=f}for(let i of s??[])n.add(i)}return n}function it(e,t,o){if(!o)return[];let n=[];return e.docs.forEach(([r,s,i],a)=>o(a)&&!t.has(a)&&n.push({id:a,title:r,url:s,section:e.sections[i]??"",score:1})),n}function H(e,t,o,n,r){let s=new Map,i=new Map;for(let u of e)for(let[l,f]of u)s.set(l,(s.get(l)??0)+f),i.set(l,(i.get(l)??0)+1);let a=[];for(let[u,l]of s){if(o.has(u)||n&&!n(u)||r==="and"&&i.get(u)!==e.length)continue;let[f,p,S]=t.docs[u];a.push({id:u,title:f,url:p,section:t.sections[S]??"",score:l*(i.get(u)/e.length)})}return a}var R={prefix:.6,stem:.4,titleAll:1.5,titleExact:2,headingAll:1.4,headingExact:1.8,phrase:1.5,typo:.3};function qt(e,t){if(e===t)return!1;if(e.length===t.length){let s=[];for(let i=0;i<e.length&&s.length<=2;i++)e[i]!==t[i]&&s.push(i);return s.length===1?!0:s.length===2&&s[1]===s[0]+1&&e[s[0]]===t[s[1]]&&e[s[1]]===t[s[0]]}let[o,n]=e.length<t.length?[e,t]:[t,e];if(n.length-o.length!==1)return!1;let r=0;for(;r<o.length&&o[r]===n[r];)r++;return o.slice(r)===n.slice(r+1)}function at(e,t,o=!1){let n=Ut(t);for(let s=Math.min(e.length,tt);s>=1;s--){let i=W(e,s);if(n.has(i))return!o||s<e.length?[i]:[i,...t.shards.filter(a=>a.length>i.length&&a.startsWith(i)).slice(0,10)]}let r=W(e,Math.min(e.length,tt));return o?t.shards.filter(s=>s.startsWith(r)).slice(0,10):[]}var tt=3,et=new WeakMap;function Ut(e){let t=et.get(e);return t||et.set(e,t=new Set(e.shards)),t}function B(e){return e.replace(/"/g,"").trim().toLowerCase()}function ct(e,t){let{tag:o,section:n}=e.filters,r=e.notFilters??{tag:[],section:[]},s=Object.entries(e.facets??{}).filter(([,h])=>h.length),i=Object.entries(e.notFacets??{}).filter(([,h])=>h.length);if(!o.length&&!n.length&&!r.tag.length&&!r.section.length&&!s.length&&!i.length)return;let a=(h,g)=>new Set(h.flatMap((m,w)=>g.includes(B(m))?[w]:[])),u=a(t.sections,n),l=a(t.tags??[],o),f=a(t.sections,r.section),p=a(t.tags??[],r.tag),S=h=>(t.facets??[]).findIndex(g=>g.name===h),c=h=>h.map(([g,m])=>{let w=S(g);return[w,w<0?new Set:a(t.facets[w].values,m)]}),d=c(s),b=c(i).filter(([h])=>h>=0),x=(h,[g,m])=>g>=0&&(h[4]?.[g]??[]).some(w=>m.has(w));return h=>{let g=t.docs[h],m=g[3]??[];if(n.length&&!u.has(g[2])||o.length&&!m.some(w=>l.has(w))||f.has(g[2])||m.some(w=>p.has(w)))return!1;for(let w of d)if(!x(g,w))return!1;for(let w of b)if(x(g,w))return!1;return!0}}function O(e){return[...new Set(e.flatMap(t=>(t?.facets??[]).map(o=>o.name)))]}function j(e,t){let o=Object.create(null),n=new Map,r=(s,i)=>{let a=`${s}\0${B(i)}`,u=n.get(a);u===void 0&&n.set(a,u=i);let l=o[s]??(o[s]=Object.create(null));l[u]=(l[u]??0)+1};for(let s of e){let i=typeof t=="function"?t(s):t,a=i?.docs[s.id];if(a){i.sections[a[2]]&&r("section",i.sections[a[2]]);for(let u of new Set(a[3]??[]))i.tags[u]!==void 0&&r("tag",i.tags[u]);(a[4]??[]).forEach((u,l)=>{let f=i.facets?.[l];if(f)for(let p of new Set(u))f.values[p]!==void 0&&r(f.name,f.values[p])})}}return o}async function Jt(e,t,o){let n=await lt(e,t,o,!0);return e.corrected=n.corrected.length?n.corrected:void 0,ut(n,Y(t.count,n.docs.size))}function Y(e,t){return Math.log(1+(e-t+.5)/(t+.5))}function ut(e,t){let o=new Map;for(let[n,r]of e.lists)for(let s=0;s<n.length;s+=2)o.set(n[s],Math.max(o.get(n[s])??0,n[s+1]*r*t));return o}async function lt(e,t,o,n){let r=D(t.lang),s=new Map,i=new Map;for(let f of e.terms)for(let p of at(f,t,e.prefix)){let S=await o.shard(p);if(!S)continue;let c=(h,g)=>{g>(s.get(h)??0)&&(s.set(h,g),i.set(h,S))};Object.hasOwn(S,f)&&c(f,1);let d=r?.(f),b=d?d.slice(0,Math.max(3,d.length-1)):void 0,x=0;for(let h in S)h!==f&&(e.prefix&&h.startsWith(f)&&x++<200&&c(h,R.prefix),d&&b&&h.startsWith(b)&&r(h)===d&&c(h,R.stem));if(n&&!s.size&&!e.exact&&f.length>=4&&!/[._-]/.test(f))for(let h in S)Math.abs(h.length-f.length)<=1&&qt(f,h)&&c(h,R.typo)}let a=[...s].filter(([,f])=>f===R.typo).map(([f])=>f),u=[...s].map(([f,p])=>[i.get(f)[f],p]),l=new Set;for(let[f]of u)for(let p=0;p<f.length;p+=2)l.add(f[p]);return{lists:u,docs:l,corrected:a}}var ft=e=>typeof e=="function"?e:()=>e;async function gt(e,t){let o=ft(t),n=new Map;for(let r of e){let s=o(r),i=n.get(s);i||n.set(s,i=[]),i.push(r)}await Promise.all([...n].map(async([r,s])=>{let i=await r.meta(),a=[...new Set(s.map(l=>Math.floor(l.id/i.block)))],u=new Map;await Promise.all(a.map(async l=>u.set(l,await r.fragment(l))));for(let l of s)l.fragment??(l.fragment=u.get(Math.floor(l.id/i.block))?.[l.id%i.block])}))}async function dt(e){let t=ft(e),o=new Map;return async n=>{let r=t(n),s=o.get(r);if(!s){let i=D((await r.meta()).lang);s=(a,u)=>u.terms.some(l=>a===l||u.prefix&&a.startsWith(l)||i!==void 0&&i(a)===i(l))||(u.corrected??[]).includes(a),o.set(r,s)}return s}}async function ht(e,t,o,n=10){let r=t.slice(0,n);await gt(r,o);let s=e.groups,i=await dt(o);for(let a of r){let u=await i(a),[l,f]=a.fragment??["",[]],p=k(a.title),S=1;s.length&&s.every(d=>p.some(b=>u(b,d)))&&(S=nt(p,s,u)?R.titleExact:R.titleAll);let c=[];for(let[d,b]of f){let x=k(d);!s.length||!s.every(h=>x.some(g=>u(g,h)))||(c.push([d,b]),S=Math.max(S,nt(x,s,u)?R.headingExact:R.headingAll))}if(a.sections=c.slice(0,3),e.phrases.length){let d=[a.title,l,...f.map(([b])=>b)].map(b=>k(b).join(" ")).join(" \0 ");e.phrases.every(b=>d.includes(b))&&(S*=R.phrase)}a.score*=S}return r.sort((a,u)=>u.score-a.score),[...r,...t.slice(n)]}async function pt(e,t,o){await gt(t,o);let n=await dt(o);for(let r of t){if(!r.fragment||r.sections)continue;let s=await n(r);r.sections=r.fragment[1].filter(([i])=>{let a=k(i);return e.groups.length>0&&e.groups.every(u=>a.some(l=>s(l,u)))}).slice(0,3)}}function nt(e,t,o){return e.every(n=>t.some(r=>o(n,r)))&&t.every(n=>e.some(r=>o(r,n)))}async function mt(e,t,o=10){let n=await t.meta(),r=_(e,{facets:O([n])}),s=D(n.lang);s&&(r.highlight=[...new Set([...r.highlight,...r.highlight.map(s).filter(a=>a.length>=3)])]);let i=await Kt(r,t);return r.highlight=[...new Set([...r.highlight,...r.groups.flatMap(a=>a.corrected??[])])],{parsed:r,results:await ht(r,i,t,o),facets:j(i,n)}}async function Vt(e){return Promise.all(e.map(t=>t.data.meta().then(o=>o&&o.format===5?o:void 0,()=>{})))}async function Xt(e,t,o,n){let r=t.flatMap((c,d)=>o[d]?[d]:[]),s=o,i=[],a=[];await Promise.all(r.map(async c=>i[c]=await ot(e,s[c],t[c].data)));for(let c of r)a[c]=ct(e,s[c]);let u=(c,d)=>c.map(b=>({...b,source:d,score:b.score*Zt(t[d])}));if(!e.groups.length)return st(r.flatMap(c=>u(it(s[c],i[c],a[c]),c)).sort(C),t);let l=t.map(()=>[]),f=r.reduce((c,d)=>c+s[d].count,0);for(let c of e.groups){let d=g=>Promise.all(r.map(m=>lt(c,s[m],t[m].data,g))),b=await d(!1);b.every(g=>!g.docs.size)&&(b=await d(!0));let x=[...new Set(b.flatMap(g=>g.corrected))];c.corrected=x.length?x:void 0;let h=b.reduce((g,m)=>g+m.docs.size,0);b.forEach((g,m)=>{let w=r[m];l[w].push(ut(g,n.stats==="own"?Y(s[w].count,g.docs.size):Y(f,h)))})}let p=c=>r.flatMap(d=>u(H(l[d],s[d],i[d],a[d],c),d)).sort(C),S=p("and");return st(S.length||e.strict?S:p("or"),t)}function Zt(e){return typeof e.boost=="number"&&Number.isFinite(e.boost)&&e.boost>=0?e.boost:1}function st(e,t){let o=new Map,n=[];for(let r of e){let s=t[r.source].collapse;if(s===void 0){n.push(r);continue}let i=`${s}\0${r.url}`,a=o.get(i);a?(a.others??(a.others=[])).push({source:r.source,id:r.id,url:r.url,score:r.score}):(o.set(i,r),n.push(r))}return n}async function bt(e,t,o=10,n={}){let r=await Vt(t),s=_(e,{facets:O(r)}),i=t.flatMap((l,f)=>r[f]?[]:[f]);for(let l of new Set(r.flatMap(f=>f?[f.lang]:[]))){let f=D(l);f&&(s.highlight=[...new Set([...s.highlight,...s.highlight.map(f).filter(p=>p.length>=3)])])}let a=await Xt(s,t,r,n);s.highlight=[...new Set([...s.highlight,...s.groups.flatMap(l=>l.corrected??[])])];let u=j(a,l=>r[l.source]);return{parsed:s,results:await ht(s,a,l=>t[l.source].data,o),missing:i,facets:u}}function wt(e,t,o=globalThis){let n=o.document?.baseURI??o.location?.href,r=rt(e,n),s=o.__DOGSBAY_SEARCH__??{q:[],load(){}},i=s.stores??(s.stores=new Map),a=i.get(r)??new Map;i.set(r,a);let u=(c,d,b)=>{let x;if(b){let h="",g=rt(b,n);for(let m of i.keys())g.startsWith(m)&&m.length>h.length&&(h=m);x=h?i.get(h):void 0}!x&&i.size===1&&(x=a),x?x.set(c,d):s.q.push([c,d,b])},l=s.q;s.q=[],s.load=u;for(let[c,d,b]of l)u(c,d,b);o.__DOGSBAY_SEARCH__=s;let f=async(c,d)=>(a.has(c)||await t(e+d),a.get(c)),p,S={meta:()=>p??(p=f(E.docs,$.docs).then(c=>{if(!c||c.format!==5)throw new Error(`search index format ${c?.format??"missing"}, expected ${5}: rebuild the site`);return c}).catch(c=>{throw p=void 0,c})),shard:async c=>(await S.meta()).shards.includes(c)?f(E.shard(c),$.shard(c)):void 0,fragment:c=>f(E.fragment(c),$.fragment(c))};return S}function rt(e,t){try{return new URL(e,t).href}catch{return e}}function te(e){return new Promise((t,o)=>{let n=document.createElement("script");n.src=e,n.onload=()=>t(),n.onerror=()=>o(new Error(`failed to load ${e}`)),document.head.append(n)})}return Dt(ee);})();
package/dist/entry.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- export { BLOCK, Doc, FORMAT, Fragment, Meta, Postings, file, key, wrap, wrapJson } from './format.js';
1
+ export { BLOCK, Doc, FACET_NAME, FORMAT, FacetTable, Fragment, Meta, Postings, file, key, wrap, wrapJson } from './format.js';
2
2
  export { shardKey, stemFor, tokenize } from './text.js';
3
3
  export { RANK, SearchDoc, SearchIndexBuilder, extractText } from './index.js';
4
4
  export { HtmlPage, extractHtml } from './html.js';
5
- export { ParsedQuery, QUERY_RANK, Result, SearchData, loadDetails, loadFragments, memoryData, oneEdit, parseQuery, query, refine, scriptData, search, shardsFor } from './query.js';
5
+ export { DataFor, FacetCounts, ParseOptions, ParsedQuery, QUERY_RANK, Result, SearchData, Source, SourceResult, SourcesOptions, facetCounts, facetNames, idfOf, loadDetails, loadFragments, memoryData, oneEdit, parseQuery, query, querySources, refine, scriptData, search, searchSources, shardsFor } from './query.js';
6
6
  import '@dogsbay/types';
package/dist/entry.js CHANGED
@@ -7,6 +7,11 @@ import {
7
7
  query,
8
8
  refine,
9
9
  search,
10
+ querySources,
11
+ searchSources,
12
+ idfOf,
13
+ facetCounts,
14
+ facetNames,
10
15
  loadFragments,
11
16
  loadDetails,
12
17
  scriptData,
@@ -21,15 +26,20 @@ export {
21
26
  SearchIndexBuilder,
22
27
  extractHtml,
23
28
  extractText,
29
+ facetCounts,
30
+ facetNames,
31
+ idfOf,
24
32
  loadDetails,
25
33
  loadFragments,
26
34
  memoryData,
27
35
  oneEdit,
28
36
  parseQuery,
29
37
  query,
38
+ querySources,
30
39
  refine,
31
40
  scriptData,
32
41
  search,
42
+ searchSources,
33
43
  shardKey,
34
44
  shardsFor,
35
45
  stemFor,
@@ -0,0 +1,279 @@
1
+ /**
2
+ * Pure helpers for a search-facet UI: shaping value counts, labels, facet
3
+ * order, hierarchical trees and filter state in the URL. Shared by both
4
+ * pipelines: docs-layout's SearchDialog (over Pagefind's counts) and
5
+ * dogsbay-ssg (over `facetCounts` from this package). No I/O, no DOM.
6
+ * Moved here from @dogsbay/docs-layout's search-facets.ts, which re-exports it.
7
+ */
8
+ /** A top-level term segment's display (as `taxonomyDisplay.<name>.prefixes`); only `label` is read here. */
9
+ interface PrefixDisplay {
10
+ label?: string;
11
+ }
12
+ /**
13
+ * The display label of a taxonomy term path: `labels[fullSlug]` wins, then a
14
+ * top-level segment's `prefixes[segment].label`, then the leaf segment.
15
+ * Display only: URLs keep the slug path.
16
+ */
17
+ declare function resolveTermLabel(fullPath: readonly string[], prefixes?: Record<string, PrefixDisplay>, labels?: Record<string, string>): string;
18
+ /**
19
+ * Per-taxonomy display config — same shape as
20
+ * `SiteConfig.taxonomyDisplay[name]`. Keyed locally so this module
21
+ * has no runtime dependency on `@dogsbay/types`.
22
+ */
23
+ interface TaxonomyDisplay {
24
+ prefixes?: Record<string, PrefixDisplay>;
25
+ labels?: Record<string, string>;
26
+ /**
27
+ * Sort weight for the facet column in the search dialog. Lower
28
+ * numbers appear first. Facets without an `order` sort
29
+ * alphabetically *after* any pinned ones — so `{ type: { order: 1 } }`
30
+ * promotes "Type" to the top while everything else stays alpha.
31
+ */
32
+ order?: number;
33
+ /**
34
+ * Render this facet as a tree instead of a flat checkbox list.
35
+ * See `buildFacetTree` for the two derivation strategies (slash-
36
+ * encoded vs nav-driven segment-encoded) and the canonical
37
+ * @dogsbay/types definition for full semantics.
38
+ */
39
+ hierarchical?: boolean;
40
+ }
41
+ /**
42
+ * Minimal nav item shape — mirrors `@dogsbay/types`' `NavItem`
43
+ * locally so this module has no runtime dependency on the types
44
+ * package. Used as input to `buildFacetTree` for segment-encoded
45
+ * facets (the auto-`category` case), where the document tree is
46
+ * the source of structure and order.
47
+ */
48
+ interface NavLike {
49
+ label: string;
50
+ href?: string;
51
+ children?: NavLike[];
52
+ }
53
+ /** Map of taxonomy name → display config. */
54
+ type TaxonomyDisplayMap = Record<string, TaxonomyDisplay>;
55
+ /** One facet entry — value plus the count of pages tagged with it. */
56
+ interface FacetEntry {
57
+ /** The slug as Pagefind indexed it (e.g. `"concept/a11y"`, `"how-to"`). */
58
+ value: string;
59
+ /** Page count for this value within the current corpus. */
60
+ count: number;
61
+ }
62
+ /** Map of facet name (taxonomy) → ordered entries. */
63
+ type FacetMap = Record<string, FacetEntry[]>;
64
+ /**
65
+ * Convert a nested count map (`{ facet: { value: count } }`, from
66
+ * `facetCounts` or Pagefind's `filters()`) into a sorted `FacetMap`.
67
+ *
68
+ * Sort order: count descending, then value ascending alphabetically
69
+ * (stable tie-break). Empty value lists are dropped — a facet with
70
+ * zero values isn't worth a row in the UI. Returns an empty
71
+ * `FacetMap` when Pagefind reports no filters at all (Pagefind log
72
+ * still says "Indexed 0 filters" — usually means the head→body fix
73
+ * hasn't propagated, not a real "no-tags" site).
74
+ */
75
+ declare function shapeFacets(raw: Record<string, Record<string, number>> | undefined | null): FacetMap;
76
+ /**
77
+ * Sort facet entries by count descending, then by value
78
+ * ascending alphabetically. Stable for equal-count values so
79
+ * the UI doesn't shuffle between renders.
80
+ */
81
+ declare function sortFacetEntries(entries: FacetEntry[]): FacetEntry[];
82
+ /**
83
+ * Resolve the human display label for one facet value.
84
+ *
85
+ * Maps the slug-form value to the configured display string by
86
+ * looking up the per-taxonomy display config. For slash-nested
87
+ * values (`concept/a11y`), the resolution rules match
88
+ * `<TagList>` chip rendering: explicit label override wins, then
89
+ * prefix label for top-level segments, then leaf segment as a
90
+ * final fallback.
91
+ *
92
+ * Slug paths are split into segments via `/`, mirroring how
93
+ * taxonomies indexes terms.
94
+ */
95
+ declare function resolveFacetLabel(facetName: string, value: string, display?: TaxonomyDisplayMap): string;
96
+ /**
97
+ * Resolve the display label for a facet name itself (the column
98
+ * header text). Looks up `prefixes[facetName].label` for built-in
99
+ * taxonomies (`tags` → "Tags"), falling back to a humanized
100
+ * version of the facet name (`by-audience` → "By audience").
101
+ *
102
+ * Per-taxonomy `prefixes` aren't a perfect fit here (they're keyed
103
+ * by the segment, not by the taxonomy itself), so this is a
104
+ * separate humanizer. Future schema work can add an explicit
105
+ * `taxonomies.<name>.displayName` field if writers want full
106
+ * control.
107
+ */
108
+ declare function resolveFacetTitle(facetName: string): string;
109
+ /**
110
+ * Return facet names in sidebar render order.
111
+ *
112
+ * Pagefind's `filters()` map iterates in index-discovery order
113
+ * (effectively the first page Pagefind happened to read), so without
114
+ * sorting the column order is arbitrary and shifts between builds.
115
+ * Order rule:
116
+ * 1. Facets with a numeric `order` in their `TaxonomyDisplay`
117
+ * come first, ascending — use this to pin "Type" or "Audience"
118
+ * to the top regardless of name.
119
+ * 2. Everything else sorts alphabetically by facet name.
120
+ * Stable within each tier so ties don't shuffle.
121
+ */
122
+ declare function sortFacetNames(names: string[], display?: TaxonomyDisplayMap): string[];
123
+ /**
124
+ * Active filter state — keyed by facet name, value is the set of
125
+ * selected slugs (multi-select per facet, AND across facets).
126
+ */
127
+ type FilterState = Record<string, string[]>;
128
+ /**
129
+ * Build URLSearchParams from the current filter state. Each
130
+ * facet:value combination produces one `filter=<name>:<value>`
131
+ * entry, repeated per selection. The `q` query param is added
132
+ * only when query is non-empty.
133
+ *
134
+ * Resulting URL is shareable — re-loading restores both the
135
+ * search query AND active filters.
136
+ */
137
+ declare function filterStateToUrlParams(query: string, filters: FilterState): URLSearchParams;
138
+ /**
139
+ * Parse `URLSearchParams` back into `{ query, filters }`. The
140
+ * inverse of `filterStateToUrlParams`. Tolerant of malformed
141
+ * `filter=...` entries — anything missing the `:` separator is
142
+ * silently dropped (forward-compat with future schema).
143
+ */
144
+ declare function parseFiltersFromUrl(params: URLSearchParams): {
145
+ query: string;
146
+ filters: FilterState;
147
+ };
148
+ /**
149
+ * Toggle a single (facetName, value) pair in the filter state.
150
+ * Returns a new state object — the input is never mutated, so
151
+ * callers can safely use this with React-style "set state to a
152
+ * new value" patterns or vanilla state diffing.
153
+ */
154
+ declare function toggleFilter(filters: FilterState, name: string, value: string): FilterState;
155
+ /**
156
+ * Count the total number of active filter selections across all
157
+ * facets. Used to render a "Clear all" button only when there's
158
+ * something to clear.
159
+ */
160
+ declare function countActiveFilters(filters: FilterState): number;
161
+ /**
162
+ * One node in a hierarchical facet tree (see `buildFacetTree`).
163
+ *
164
+ * `value` is the canonical Pagefind filter value for this node —
165
+ * for slash-encoded facets the full slash-joined path
166
+ * (`concept/a11y`); for segment-encoded facets a single segment
167
+ * (`installing_aws`). `value` matches Pagefind's value key 1:1
168
+ * for "real" entries; synthetic parents (intermediate trie nodes
169
+ * that don't correspond to a Pagefind entry) reuse the same
170
+ * derived value but carry `hasValue: false` and `count: 0`.
171
+ */
172
+ interface FacetTreeNode {
173
+ value: string;
174
+ label: string;
175
+ count: number;
176
+ depth: number;
177
+ /** True if Pagefind reported this exact value; false for synthetic parents. */
178
+ hasValue: boolean;
179
+ children: FacetTreeNode[];
180
+ }
181
+ /**
182
+ * Build a hierarchical facet tree from Pagefind's flat entry list.
183
+ *
184
+ * Two strategies depending on the values' shape:
185
+ *
186
+ * - **Slash-encoded.** When at least one entry value contains `/`,
187
+ * each value is treated as a path through the tree (`concept/a11y`
188
+ * → `concept → a11y`). Splits on `/`, inserts into a trie.
189
+ * Parent entries that don't have a Pagefind value of their own
190
+ * (e.g. `concept` standalone is unindexed but `concept/a11y` is)
191
+ * appear as synthetic intermediate nodes with `hasValue: false`.
192
+ * Within a parent, children sort by count desc then alpha — the
193
+ * same rule as flat facets.
194
+ *
195
+ * - **Segment-encoded.** When NO entry contains `/`, each value is
196
+ * a single path segment. Hierarchy comes from `nav` — every nav
197
+ * leaf's href segments become a chain in the trie. Counts come
198
+ * from Pagefind's entry list, attached to nodes whose segment
199
+ * name matches an entry value. **Caveat:** Pagefind reports one
200
+ * count per distinct segment name regardless of where in the
201
+ * tree it lives, so a segment that appears at multiple positions
202
+ * (`installing/.../ipi`, `installing_azure/.../ipi`) gets the
203
+ * same total count at every position — clicking selects the
204
+ * shared value, returning pages from every position. This
205
+ * matches the underlying Pagefind filter behaviour and is
206
+ * documented in plans/hierarchical-facets.md.
207
+ *
208
+ * Order is nav-document order, NOT count desc. Pagefind entries
209
+ * not represented in nav are appended as orphans at the root in
210
+ * alpha order.
211
+ *
212
+ * When `nav` is undefined for the segment-encoded case, falls
213
+ * back to a flat list (every entry a root-level node with no
214
+ * children, in count-desc order) — preserves render-ability
215
+ * when nav.json hasn't loaded yet.
216
+ *
217
+ * Returns the top-level nodes. Empty `entries` → empty array.
218
+ */
219
+ declare function buildFacetTree(facetName: string, entries: FacetEntry[], options?: {
220
+ nav?: NavLike[];
221
+ display?: TaxonomyDisplayMap;
222
+ }): FacetTreeNode[];
223
+ /**
224
+ * Walk `nav` and assign each cumulative slash-path (matching a
225
+ * Pagefind facet value in `knownValues`) a sequential index in
226
+ * first-encounter order. Used by `buildSlashTree` to sort children
227
+ * in document order rather than count-desc.
228
+ *
229
+ * Auto-detects and strips a leading basePath: for each nav leaf, we
230
+ * try each starting offset of the href's parent segments. The first
231
+ * offset whose initial cumulative path is in `knownValues` is the
232
+ * "real" content root; the dropped prefix is the basePath. This way
233
+ * the helper works on any site without needing the basePath threaded
234
+ * through explicitly.
235
+ *
236
+ * Hrefs whose parents don't match anything in `knownValues` at any
237
+ * offset are skipped (e.g. top-level pages with no auto-derived
238
+ * category, or pages outside the indexed corpus).
239
+ *
240
+ * Exported for use by `buildFacetTree`. Pure — no I/O.
241
+ */
242
+ declare function buildNavOrderMap(nav: NavLike[], knownValues: Set<string>): Map<string, number>;
243
+ /**
244
+ * Flat list of every "real" Pagefind value at or under `node`
245
+ * (i.e. every node where `hasValue === true`). Synthetic parents
246
+ * are excluded since adding them to the filter would be a no-op
247
+ * (Pagefind has no pages tagged with the synthetic value).
248
+ *
249
+ * Used by `toggleTreeNode` when the user ticks a parent — we add
250
+ * every real descendant value to the selection in one shot.
251
+ */
252
+ declare function collectDescendantValues(node: FacetTreeNode): string[];
253
+ /**
254
+ * Tri-state of a tree node given the current filter state.
255
+ *
256
+ * - `"checked"` — every real descendant value (and self if
257
+ * self has a value) is in `filters[facetName]`.
258
+ * - `"unchecked"` — none of them are.
259
+ * - `"indeterminate"`— at least one is, but not all.
260
+ *
261
+ * Synthetic parents with no real-value descendants resolve to
262
+ * "unchecked" (defensive default — shouldn't occur in valid trees).
263
+ */
264
+ declare function computeTreeState(node: FacetTreeNode, facetName: string, filters: FilterState): "checked" | "unchecked" | "indeterminate";
265
+ /**
266
+ * Toggle a tree node's selection.
267
+ *
268
+ * - If currently checked → remove self + all descendant values
269
+ * from `filters[facetName]`.
270
+ * - If unchecked or indeterminate → add self + all descendant
271
+ * values (auto-select). Matches the decided UX: parent click
272
+ * fans out to children.
273
+ *
274
+ * Returns a new `FilterState` — input is not mutated. Same
275
+ * immutability contract as `toggleFilter`.
276
+ */
277
+ declare function toggleTreeNode(filters: FilterState, facetName: string, node: FacetTreeNode, currentState: "checked" | "unchecked" | "indeterminate"): FilterState;
278
+
279
+ export { type FacetEntry, type FacetMap, type FacetTreeNode, type FilterState, type NavLike, type PrefixDisplay, type TaxonomyDisplay, type TaxonomyDisplayMap, buildFacetTree, buildNavOrderMap, collectDescendantValues, computeTreeState, countActiveFilters, filterStateToUrlParams, parseFiltersFromUrl, resolveFacetLabel, resolveFacetTitle, resolveTermLabel, shapeFacets, sortFacetEntries, sortFacetNames, toggleFilter, toggleTreeNode };