@dogsbay/search 0.2.0-beta.151 → 0.2.0-beta.153
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 +6 -2
- package/dist/dogsbay-search.iife.js +1 -1
- package/dist/entry.d.ts +2 -2
- package/dist/entry.js +10 -0
- package/dist/facets.d.ts +279 -0
- package/dist/facets.js +327 -0
- package/dist/format.d.ts +26 -7
- package/dist/format.js +4 -2
- package/dist/index.d.ts +6 -0
- package/dist/index.js +25 -4
- package/dist/query.d.ts +113 -9
- package/dist/query.js +290 -57
- package/package.json +7 -3
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
|
-
`
|
|
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), is another format, or whose term file fails is left out and listed in `missing`; an excerpt file that fails leaves its results without an excerpt. 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 H=Object.defineProperty;var yt=Object.getOwnPropertyDescriptor;var Mt=Object.getOwnPropertyNames;var Rt=Object.prototype.hasOwnProperty;var Pt=(e,t)=>{for(var o in t)H(e,o,{get:t[o],enumerable:!0})},kt=(e,t,o,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Mt(t))!Rt.call(e,r)&&r!==o&&H(e,r,{get:()=>t[r],enumerable:!(n=yt(t,r))||n.enumerable});return e};var Ft=e=>kt(H({},"__esModule",{value:!0}),e);var ee={};Pt(ee,{facetCounts:()=>W,facetNames:()=>G,loadDetails:()=>bt,loadScript:()=>te,parseQuery:()=>z,scriptData:()=>xt,search:()=>wt,searchSources:()=>St});var X=/^[a-z][a-z0-9_-]{0,63}$/,j={docs:"docs.js",shard:e=>`t-${e}.js`,fragment:e=>`f-${e}.js`},T={docs:"docs",shard:e=>e,fragment:e=>`frag:${e}`};var Dt={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"},_t={icate:"ic",ative:"",alize:"al",iciti:"ic",ical:"ic",ful:"",ness:""},Ot="[^aeiou]",B="[aeiouy]",D="("+Ot+"[^aeiouy]*)",L="("+B+"[aeiou]*)",Y=new RegExp("^"+D+"?"+L+D),vt=new RegExp("^"+D+"?"+L+D+L+"?$"),N=new RegExp("^"+D+"?("+L+D+"){2,}"),Z=new RegExp("^"+D+"?"+B),tt=new RegExp("^"+D+B+"[^aeiouwxy]$"),Et=/ll$/,$t=/^(.+?)e$/,At=/^(.+?)y$/,zt=/^(.+?(s|t))(ion)$/,Gt=/^(.+?)(ed|ing)$/,Ct=/(at|bl|iz)$/,jt=/^(.+?)eed$/,Tt=/^.+?[^s]s$/,Nt=/^.+?(ss|i)es$/,Lt=/([^aeiouylsz])\1$/,Qt=/^(.+?)(ational|tional|enci|anci|izer|bli|alli|entli|eli|ousli|ization|ation|ator|alism|iveness|fulness|ousness|aliti|iviti|biliti|logi)$/,Wt=/^(.+?)(icate|ative|alize|iciti|ical|ful|ness)$/,It=/^(.+?)(al|ance|ence|er|ic|able|ible|ant|ement|ment|ent|ou|ism|ate|iti|ous|ive|ize)$/;function et(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)),Nt.test(t)?t=t.slice(0,-2):Tt.test(t)&&(t=t.slice(0,-1));let n;return(n=jt.exec(t))?Y.test(n[1])&&(t=t.slice(0,-1)):(n=Gt.exec(t))&&Z.test(n[1])&&(t=n[1],Ct.test(t)?t+="e":Lt.test(t)?t=t.slice(0,-1):tt.test(t)&&(t+="e")),(n=At.exec(t))&&Z.test(n[1])&&(t=n[1]+"i"),(n=Qt.exec(t))&&Y.test(n[1])&&(t=n[1]+Dt[n[2]]),(n=Wt.exec(t))&&Y.test(n[1])&&(t=n[1]+_t[n[2]]),(n=It.exec(t))?N.test(n[1])&&(t=n[1]):(n=zt.exec(t))&&N.test(n[1])&&(t=n[1]),(n=$t.exec(t))&&(N.test(n[1])||vt.test(n[1])&&!tt.test(n[1]))&&(t=n[1]),Et.test(t)&&N.test(t)&&(t=t.slice(0,-1)),o&&(t="y"+t.slice(1)),t}var nt=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(" ")),Ht=/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u,$;function Yt(e){if($===void 0)try{$=typeof Intl<"u"&&"Segmenter"in Intl?new Intl.Segmenter(void 0,{granularity:"word"}):null}catch{$=null}if($)return[...$.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 _(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&&!nt.has(s)&&t.push(s)}for(let s of r)Ht.test(s)?t.push(...Yt(s)):s.length>=2&&!nt.has(s)&&t.push(s)}return t}function K(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 A(e){if(!(!e||!/^en(-|$)/i.test(e)))return t=>/^[a-z]{3,}$/.test(t)?et(t):t}function z(e,t={}){var R,d;let o=[],n=[],r=[],s=!1,i={tag:[],section:[]},a={tag:[],section:[]},c=Object.create(null),u=Object.create(null),l=["tag","section",...new Set((t.facets??[]).filter(p=>X.test(p)&&p!=="tag"&&p!=="section"))],f=new RegExp(`(?<!\\S)(-?)(${l.join("|")}):(?:"([^"]*)"?|(?!\\/\\/)(\\S*))|(-?)"([^"]*)"?|(\\S+)`,"gi"),m=[...e.matchAll(f)].map(p=>({facetNeg:p[1]==="-",facet:p[2]?.toLowerCase(),value:p[3]??p[4],neg:p[5],phrase:p[6],word:p[7]})),h=!1,b=!1;for(let[p,S]of m.entries()){if(S.facet){let P=V(S.value??"");if(!P)continue;S.facet==="tag"||S.facet==="section"?(S.facetNeg?a:i)[S.facet].push(P):((R=S.facetNeg?u:c)[d=S.facet]??(R[d]=[])).push(P);continue}let x=S.word;if(x==="OR"){b=o.length>0,s=!0;continue}if(x==="NOT"){h=!0,s=!0;continue}if(x==="AND"){s=!0;continue}let O=S.phrase!==void 0,g=h||S.neg==="-"||x?.startsWith("-")&&x.length>1;h=!1;let w=O?S.phrase:g&&x?.startsWith("-")?x.slice(1):x,M=[...new Set(_(w))];if(!M.length){b=!1;continue}if(g){n.push(O?M:[M[0]]),s=!0,b=!1;continue}if(O){b=!1,s=!0,M.length>1&&r.push(_(w).join(" "));for(let P of M)o.push({terms:[P],prefix:!1,exact:!0});continue}let E=p===m.length-1&&!/\s$/.test(e);if(b){o[o.length-1].terms.push(M[0]);for(let P of M.slice(1))o.push({terms:[P],prefix:!1});b=!1;continue}let v=M[0],I=/[._-]/.test(v),k=v.replace(/-/g,"");for(let[P,C]of M.entries())o.push({terms:[C],prefix:E&&C.length>=2&&(P===M.length-1||I&&(C===v||C===k))})}let y=[...new Set(o.flatMap(p=>p.terms))];return{groups:o,not:n,phrases:r,strict:s,highlight:y,filters:i,notFilters:a,...Object.keys(c).length?{facets:c}:{},...Object.keys(u).length?{notFacets:u}:{}}}async function Bt(e,t){let o=await t.meta(),n=typeof e=="string"?z(e,{facets:G([o])}):e,r=await at(n,o,t),s=lt(n,o);if(!n.groups.length)return ct(o,r,s);let i=[];for(let c of n.groups)i.push(await Ut(c,o,t));let a=U(i,o,r,s,"and").sort(Q);return a.length||n.strict?a:U(i,o,r,s,"or").sort(Q)}var Q=(e,t)=>t.score-e.score;async function at(e,t,o){let n=new Set;for(let r of e.not){let s;for(let i of r){let[a]=ut(i,t),c=a?await o.shard(a):void 0,u=c&&Object.hasOwn(c,i)?c[i]:[],l=new Set;for(let f=0;f<u.length;f+=2)(!s||s.has(u[f]))&&l.add(u[f]);s=l}for(let i of s??[])n.add(i)}return n}function ct(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 U(e,t,o,n,r){let s=new Map,i=new Map;for(let c of e)for(let[u,l]of c)s.set(u,(s.get(u)??0)+l),i.set(u,(i.get(u)??0)+1);let a=[];for(let[c,u]of s){if(o.has(c)||n&&!n(c)||r==="and"&&i.get(c)!==e.length)continue;let[l,f,m]=t.docs[c];a.push({id:c,title:l,url:f,section:t.sections[m]??"",score:u*(i.get(c)/e.length)})}return a}var F={prefix:.6,stem:.4,titleAll:1.5,titleExact:2,headingAll:1.4,headingExact:1.8,phrase:1.5,typo:.3};function Kt(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 ut(e,t,o=!1){let n=qt(t);for(let s=Math.min(e.length,st);s>=1;s--){let i=K(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=K(e,Math.min(e.length,st));return o?t.shards.filter(s=>s.startsWith(r)).slice(0,10):[]}var st=3,rt=new WeakMap;function qt(e){let t=rt.get(e);return t||rt.set(e,t=new Set(e.shards)),t}function V(e){return e.replace(/"/g,"").trim().toLowerCase()}function lt(e,t){let{tag:o,section:n}=e.filters,r=e.notFilters??{tag:[],section:[]},s=Object.entries(e.facets??{}).filter(([,d])=>d.length),i=Object.entries(e.notFacets??{}).filter(([,d])=>d.length);if(!o.length&&!n.length&&!r.tag.length&&!r.section.length&&!s.length&&!i.length)return;let a=(d,p)=>new Set(d.flatMap((S,x)=>p.includes(V(S))?[x]:[])),c=a(t.sections,n),u=a(t.tags??[],o),l=a(t.sections,r.section),f=a(t.tags??[],r.tag),m=d=>(t.facets??[]).findIndex(p=>p.name===d),h=d=>d.map(([p,S])=>{let x=m(p);return[x,x<0?new Set:a(t.facets[x].values,S)]}),b=h(s),y=h(i).filter(([d])=>d>=0),R=(d,[p,S])=>p>=0&&(d[4]?.[p]??[]).some(x=>S.has(x));return d=>{let p=t.docs[d],S=p[3]??[];if(n.length&&!c.has(p[2])||o.length&&!S.some(x=>u.has(x))||l.has(p[2])||S.some(x=>f.has(x)))return!1;for(let x of b)if(!R(p,x))return!1;for(let x of y)if(R(p,x))return!1;return!0}}function G(e){return[...new Set(e.flatMap(t=>(t?.facets??[]).map(o=>o.name)))]}function W(e,t){let o=Object.create(null),n=new Map,r=(s,i)=>{let a=`${s}\0${V(i)}`,c=n.get(a);c===void 0&&n.set(a,c=i);let u=o[s]??(o[s]=Object.create(null));u[c]=(u[c]??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 c of new Set(a[3]??[]))i.tags[c]!==void 0&&r("tag",i.tags[c]);(a[4]??[]).forEach((c,u)=>{let l=i.facets?.[u];if(l)for(let f of new Set(c))l.values[f]!==void 0&&r(l.name,l.values[f])})}}return o}async function Ut(e,t,o){let n=await gt(e,t,o,!0);return e.corrected=n.corrected.length?n.corrected:void 0,ft(n,J(t.count,n.docs.size))}function J(e,t){return Math.log(1+(e-t+.5)/(t+.5))}function ft(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 gt(e,t,o,n){let r=A(t.lang),s=new Map,i=new Map;for(let l of e.terms)for(let f of ut(l,t,e.prefix)){let m=await o.shard(f);if(!m)continue;let h=(d,p)=>{p>(s.get(d)??0)&&(s.set(d,p),i.set(d,m))};Object.hasOwn(m,l)&&h(l,1);let b=r?.(l),y=b?b.slice(0,Math.max(3,b.length-1)):void 0,R=0;for(let d in m)d!==l&&(e.prefix&&d.startsWith(l)&&R++<200&&h(d,F.prefix),b&&y&&d.startsWith(y)&&r(d)===b&&h(d,F.stem));if(n&&!s.size&&!e.exact&&l.length>=4&&!/[._-]/.test(l))for(let d in m)Math.abs(d.length-l.length)<=1&&Kt(l,d)&&h(d,F.typo)}let a=[...s].filter(([,l])=>l===F.typo).map(([l])=>l),c=[...s].map(([l,f])=>[i.get(l)[l],f]),u=new Set;for(let[l]of c)for(let f=0;f<l.length;f+=2)u.add(l[f]);return{lists:c,docs:u,corrected:a}}var dt=e=>typeof e=="function"?e:()=>e;async function ht(e,t){let o=dt(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(u=>Math.floor(u.id/i.block)))],c=new Map;await Promise.all(a.map(async u=>{try{c.set(u,await r.fragment(u))}catch{c.set(u,void 0)}}));for(let u of s)u.fragment??(u.fragment=c.get(Math.floor(u.id/i.block))?.[u.id%i.block])}))}async function pt(e){let t=dt(e),o=new Map;return async n=>{let r=t(n),s=o.get(r);if(!s){let i=A((await r.meta()).lang);s=(a,c)=>c.terms.some(u=>a===u||c.prefix&&a.startsWith(u)||i!==void 0&&i(a)===i(u))||(c.corrected??[]).includes(a),o.set(r,s)}return s}}async function mt(e,t,o,n=10){let r=t.slice(0,n);await ht(r,o);let s=e.groups,i=await pt(o);for(let a of r){let c=await i(a),[u,l]=a.fragment??["",[]],f=_(a.title),m=1;s.length&&s.every(b=>f.some(y=>c(y,b)))&&(m=ot(f,s,c)?F.titleExact:F.titleAll);let h=[];for(let[b,y]of l){let R=_(b);!s.length||!s.every(d=>R.some(p=>c(p,d)))||(h.push([b,y]),m=Math.max(m,ot(R,s,c)?F.headingExact:F.headingAll))}if(a.sections=h.slice(0,3),e.phrases.length){let b=[a.title,u,...l.map(([y])=>y)].map(y=>_(y).join(" ")).join(" \0 ");e.phrases.every(y=>b.includes(y))&&(m*=F.phrase)}a.score*=m}return r.sort((a,c)=>c.score-a.score),[...r,...t.slice(n)]}async function bt(e,t,o){await ht(t,o);let n=await pt(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=_(i);return e.groups.length>0&&e.groups.every(c=>a.some(u=>s(u,c)))}).slice(0,3)}}function ot(e,t,o){return e.every(n=>t.some(r=>o(n,r)))&&t.every(n=>e.some(r=>o(r,n)))}async function wt(e,t,o=10){let n=await t.meta(),r=z(e,{facets:G([n])}),s=A(n.lang);s&&(r.highlight=[...new Set([...r.highlight,...r.highlight.map(s).filter(a=>a.length>=3)])]);let i=await Bt(r,t);return r.highlight=[...new Set([...r.highlight,...r.groups.flatMap(a=>a.corrected??[])])],{parsed:r,results:await mt(r,i,t,o),facets:W(i,n)}}async function Jt(e){return Promise.all(e.map(t=>t.data.meta().then(o=>o&&o.format===5?o:void 0,()=>{})))}async function Vt(e,t,o,n){let r=o,s=new Set,i=[],a=async(g,w)=>{if(!s.has(g))try{return await w()}catch(M){s.add(g),i.push({source:g,error:M});return}},c=t.flatMap((g,w)=>o[w]?[w]:[]),u=[];await Promise.all(c.map(async g=>u[g]=await a(g,()=>at(e,r[g],t[g].data))??new Set));let l=[],f=[],m=(g,w)=>Promise.all(c.map(M=>a(M,()=>gt(g,r[M],t[M].data,w)))),h=g=>g.every((w,M)=>!w?.docs.size||s.has(c[M]));for(let g of e.groups){let w=await m(g,!1);f.push(h(w)),f[f.length-1]&&(w=await m(g,!0)),l.push(w)}for(let[g,w]of e.groups.entries())f[g]||!h(l[g])||(w.corrected=void 0,l[g]=await m(w,!0));if(c.length&&c.every(g=>s.has(g)))throw i[0].error;let b=c.filter(g=>!s.has(g)),y=[];for(let g of b)y[g]=lt(e,r[g]);let R=(g,w)=>g.map(M=>({...M,source:w,score:M.score*Xt(t[w])})),d=g=>({results:Zt(g,t),failed:[...s].sort((w,M)=>w-M),errors:i});if(!e.groups.length)return d(b.flatMap(g=>R(ct(r[g],u[g],y[g]),g)).sort(Q));let p=t.map(()=>[]),S=b.reduce((g,w)=>g+r[w].count,0);e.groups.forEach((g,w)=>{let M=l[w],E=c.flatMap((k,P)=>s.has(k)?[]:[[k,M[P]]]),v=[...new Set(E.flatMap(([,k])=>k.corrected))];g.corrected=v.length?v:void 0;let I=E.reduce((k,[,P])=>k+P.docs.size,0);for(let[k,P]of E)p[k].push(ft(P,n.stats==="own"?J(r[k].count,P.docs.size):J(S,I)))});let x=g=>b.flatMap(w=>R(U(p[w],r[w],u[w],y[w],g),w)).sort(Q),O=x("and");return d(O.length||e.strict?O:x("or"))}function Xt(e){return typeof e.boost=="number"&&Number.isFinite(e.boost)&&e.boost>=0?e.boost:1}function Zt(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 St(e,t,o=10,n={}){let r=await Jt(t),s=z(e,{facets:G(r)}),i=t.flatMap((f,m)=>r[m]?[]:[m]);for(let f of new Set(r.flatMap(m=>m?[m.lang]:[]))){let m=A(f);m&&(s.highlight=[...new Set([...s.highlight,...s.highlight.map(m).filter(h=>h.length>=3)])])}let{results:a,failed:c,errors:u}=await Vt(s,t,r,n);for(let f of c)i.includes(f)||i.push(f);i.sort((f,m)=>f-m),s.highlight=[...new Set([...s.highlight,...s.groups.flatMap(f=>f.corrected??[])])];let l=W(a,f=>r[f.source]);return{parsed:s,results:await mt(s,a,f=>t[f.source].data,o),missing:i,facets:l,errors:u}}function xt(e,t,o=globalThis){let n=o.document?.baseURI??o.location?.href,r=it(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 c=(h,b,y)=>{let R;if(y){let d="",p=it(y,n);for(let S of i.keys())p.startsWith(S)&&S.length>d.length&&(d=S);R=d?i.get(d):void 0}!R&&i.size===1&&(R=a),R?R.set(h,b):s.q.push([h,b,y])},u=s.q;s.q=[],s.load=c;for(let[h,b,y]of u)c(h,b,y);o.__DOGSBAY_SEARCH__=s;let l=async(h,b)=>(a.has(h)||await t(e+b),a.get(h)),f,m={meta:()=>f??(f=l(T.docs,j.docs).then(h=>{if(!h||h.format!==5)throw new Error(`search index format ${h?.format??"missing"}, expected ${5}: rebuild the site`);return h}).catch(h=>{throw f=void 0,h})),shard:async h=>(await m.meta()).shards.includes(h)?l(T.shard(h),j.shard(h)):void 0,fragment:h=>l(T.fragment(h),j.fragment(h))};return m}function it(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 Ft(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, SourceError, 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,
|
package/dist/facets.d.ts
ADDED
|
@@ -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 };
|