@dogsbay/search 0.2.0-beta.151 → 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/dist/facets.js ADDED
@@ -0,0 +1,327 @@
1
+ function resolveTermLabel(fullPath, prefixes, labels) {
2
+ if (fullPath.length === 0) return "";
3
+ const slug = fullPath.join("/");
4
+ const override = labels?.[slug];
5
+ if (override && override.length > 0) return override;
6
+ if (fullPath.length === 1) {
7
+ const prefixLabel = prefixes?.[fullPath[0]]?.label;
8
+ if (prefixLabel && prefixLabel.length > 0) return prefixLabel;
9
+ }
10
+ return fullPath[fullPath.length - 1];
11
+ }
12
+ function shapeFacets(raw) {
13
+ if (!raw) return {};
14
+ const out = {};
15
+ for (const [name, valueMap] of Object.entries(raw)) {
16
+ const entries = sortFacetEntries(
17
+ Object.entries(valueMap).map(([value, count]) => ({ value, count }))
18
+ );
19
+ if (entries.length > 0) out[name] = entries;
20
+ }
21
+ return out;
22
+ }
23
+ function sortFacetEntries(entries) {
24
+ return [...entries].sort((a, b) => {
25
+ if (a.count !== b.count) return b.count - a.count;
26
+ return a.value.localeCompare(b.value);
27
+ });
28
+ }
29
+ function resolveFacetLabel(facetName, value, display) {
30
+ const taxonomy = display?.[facetName];
31
+ const fullPath = value.split("/").filter((s) => s.length > 0);
32
+ return resolveTermLabel(fullPath, taxonomy?.prefixes, taxonomy?.labels);
33
+ }
34
+ function resolveFacetTitle(facetName) {
35
+ return facetName.replace(/[-_]/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
36
+ }
37
+ function sortFacetNames(names, display) {
38
+ const withOrder = (name) => {
39
+ const o = display?.[name]?.order;
40
+ return typeof o === "number" ? o : void 0;
41
+ };
42
+ return [...names].sort((a, b) => {
43
+ const oa = withOrder(a);
44
+ const ob = withOrder(b);
45
+ if (oa !== void 0 && ob !== void 0) {
46
+ if (oa !== ob) return oa - ob;
47
+ return a.localeCompare(b);
48
+ }
49
+ if (oa !== void 0) return -1;
50
+ if (ob !== void 0) return 1;
51
+ return a.localeCompare(b);
52
+ });
53
+ }
54
+ function filterStateToUrlParams(query, filters) {
55
+ const params = new URLSearchParams();
56
+ if (query.trim().length > 0) params.set("q", query.trim());
57
+ for (const [name, values] of Object.entries(filters)) {
58
+ for (const value of values) {
59
+ params.append("filter", `${name}:${value}`);
60
+ }
61
+ }
62
+ return params;
63
+ }
64
+ function parseFiltersFromUrl(params) {
65
+ const query = params.get("q") ?? "";
66
+ const filters = {};
67
+ for (const raw of params.getAll("filter")) {
68
+ const colonIdx = raw.indexOf(":");
69
+ if (colonIdx < 1) continue;
70
+ const name = raw.slice(0, colonIdx);
71
+ const value = raw.slice(colonIdx + 1);
72
+ if (!value) continue;
73
+ if (!filters[name]) filters[name] = [];
74
+ if (!filters[name].includes(value)) filters[name].push(value);
75
+ }
76
+ return { query, filters };
77
+ }
78
+ function toggleFilter(filters, name, value) {
79
+ const next = { ...filters };
80
+ const current = next[name] ?? [];
81
+ if (current.includes(value)) {
82
+ const dropped = current.filter((v) => v !== value);
83
+ if (dropped.length === 0) {
84
+ delete next[name];
85
+ } else {
86
+ next[name] = dropped;
87
+ }
88
+ } else {
89
+ next[name] = [...current, value];
90
+ }
91
+ return next;
92
+ }
93
+ function countActiveFilters(filters) {
94
+ let n = 0;
95
+ for (const values of Object.values(filters)) n += values.length;
96
+ return n;
97
+ }
98
+ function buildFacetTree(facetName, entries, options = {}) {
99
+ if (entries.length === 0) return [];
100
+ const slashEncoded = entries.some((e) => e.value.includes("/"));
101
+ if (slashEncoded) {
102
+ const navOrder = options.nav ? buildNavOrderMap(
103
+ options.nav,
104
+ new Set(entries.map((e) => e.value))
105
+ ) : void 0;
106
+ return buildSlashTree(facetName, entries, options.display, navOrder);
107
+ }
108
+ return buildSegmentTree(facetName, entries, options.nav, options.display);
109
+ }
110
+ function buildSlashTree(facetName, entries, display, navOrder) {
111
+ const byPath = /* @__PURE__ */ new Map();
112
+ const rootValues = [];
113
+ for (const entry of entries) {
114
+ const segments = entry.value.split("/").filter((s) => s.length > 0);
115
+ if (segments.length === 0) continue;
116
+ let pathSoFar = "";
117
+ let parent = null;
118
+ for (let i = 0; i < segments.length; i++) {
119
+ pathSoFar = pathSoFar ? `${pathSoFar}/${segments[i]}` : segments[i];
120
+ let node = byPath.get(pathSoFar);
121
+ if (!node) {
122
+ node = {
123
+ value: pathSoFar,
124
+ label: resolveFacetLabel(facetName, pathSoFar, display),
125
+ count: 0,
126
+ depth: i,
127
+ hasValue: false,
128
+ children: []
129
+ };
130
+ byPath.set(pathSoFar, node);
131
+ if (parent) parent.children.push(node);
132
+ else rootValues.push(pathSoFar);
133
+ }
134
+ if (i === segments.length - 1) {
135
+ node.count = entry.count;
136
+ node.hasValue = true;
137
+ }
138
+ parent = node;
139
+ }
140
+ }
141
+ const cmp = (a, b) => {
142
+ if (navOrder) {
143
+ const oa = navOrder.get(a.value);
144
+ const ob = navOrder.get(b.value);
145
+ if (oa !== void 0 && ob !== void 0 && oa !== ob) return oa - ob;
146
+ if (oa !== void 0 && ob === void 0) return -1;
147
+ if (oa === void 0 && ob !== void 0) return 1;
148
+ }
149
+ if (a.count !== b.count) return b.count - a.count;
150
+ return a.value.localeCompare(b.value);
151
+ };
152
+ const sortChildren = (node) => {
153
+ if (node.children.length === 0) return;
154
+ node.children.sort(cmp);
155
+ for (const c of node.children) sortChildren(c);
156
+ };
157
+ const rootList = rootValues.map((v) => byPath.get(v));
158
+ rootList.sort(cmp);
159
+ for (const r of rootList) sortChildren(r);
160
+ return rootList;
161
+ }
162
+ function buildNavOrderMap(nav, knownValues) {
163
+ const order = /* @__PURE__ */ new Map();
164
+ let n = 0;
165
+ const walk = (items) => {
166
+ for (const item of items) {
167
+ if (item.href) {
168
+ const parents = hrefToCategorySegments(item.href);
169
+ for (let start = 0; start < parents.length; start++) {
170
+ const first = parents[start];
171
+ if (!knownValues.has(first)) continue;
172
+ let cumulative = "";
173
+ for (let i = start; i < parents.length; i++) {
174
+ cumulative = cumulative ? `${cumulative}/${parents[i]}` : parents[i];
175
+ if (knownValues.has(cumulative) && !order.has(cumulative)) {
176
+ order.set(cumulative, n++);
177
+ }
178
+ }
179
+ break;
180
+ }
181
+ }
182
+ if (item.children && item.children.length > 0) walk(item.children);
183
+ }
184
+ };
185
+ walk(nav);
186
+ return order;
187
+ }
188
+ function buildSegmentTree(facetName, entries, nav, display) {
189
+ const byValue = /* @__PURE__ */ new Map();
190
+ for (const e of entries) byValue.set(e.value, e);
191
+ if (!nav || nav.length === 0) {
192
+ return entries.map((e) => ({
193
+ value: e.value,
194
+ label: resolveFacetLabel(facetName, e.value, display),
195
+ count: e.count,
196
+ depth: 0,
197
+ hasValue: true,
198
+ children: []
199
+ }));
200
+ }
201
+ const seenValues = /* @__PURE__ */ new Set();
202
+ const roots = [];
203
+ const rootIndex = /* @__PURE__ */ new Map();
204
+ const insertPath = (segments) => {
205
+ if (segments.length === 0) return;
206
+ let parentList = roots;
207
+ let parentIndex = rootIndex;
208
+ for (let i = 0; i < segments.length; i++) {
209
+ const seg = segments[i];
210
+ let node = parentIndex.get(seg);
211
+ if (!node) {
212
+ const entry = byValue.get(seg);
213
+ node = {
214
+ value: seg,
215
+ label: resolveFacetLabel(facetName, seg, display),
216
+ count: entry ? entry.count : 0,
217
+ depth: i,
218
+ hasValue: entry !== void 0,
219
+ children: []
220
+ };
221
+ parentList.push(node);
222
+ parentIndex.set(seg, node);
223
+ if (entry) seenValues.add(seg);
224
+ }
225
+ let nextIndex = childIndex.get(node);
226
+ if (!nextIndex) {
227
+ nextIndex = /* @__PURE__ */ new Map();
228
+ childIndex.set(node, nextIndex);
229
+ }
230
+ parentList = node.children;
231
+ parentIndex = nextIndex;
232
+ }
233
+ };
234
+ const childIndex = /* @__PURE__ */ new Map();
235
+ const walkNav = (items) => {
236
+ for (const item of items) {
237
+ if (item.href) {
238
+ const parents = hrefToCategorySegments(item.href);
239
+ insertPath(parents);
240
+ }
241
+ if (item.children && item.children.length > 0) walkNav(item.children);
242
+ }
243
+ };
244
+ walkNav(nav);
245
+ const orphans = [];
246
+ for (const e of entries) {
247
+ if (seenValues.has(e.value)) continue;
248
+ orphans.push({
249
+ value: e.value,
250
+ label: resolveFacetLabel(facetName, e.value, display),
251
+ count: e.count,
252
+ depth: 0,
253
+ hasValue: true,
254
+ children: []
255
+ });
256
+ }
257
+ orphans.sort((a, b) => a.value.localeCompare(b.value));
258
+ return [...roots, ...orphans];
259
+ }
260
+ function hrefToCategorySegments(href) {
261
+ let path = href;
262
+ try {
263
+ if (/^[a-z]+:\/\//i.test(href)) path = new URL(href).pathname;
264
+ } catch {
265
+ }
266
+ path = path.split("#")[0].split("?")[0];
267
+ const segments = path.split("/").filter((s) => s.length > 0);
268
+ if (segments.length < 2) return [];
269
+ return segments.slice(0, -1);
270
+ }
271
+ function collectDescendantValues(node) {
272
+ const out = [];
273
+ const visit = (n) => {
274
+ if (n.hasValue) out.push(n.value);
275
+ for (const c of n.children) visit(c);
276
+ };
277
+ visit(node);
278
+ return out;
279
+ }
280
+ function computeTreeState(node, facetName, filters) {
281
+ const descendants = collectDescendantValues(node);
282
+ if (descendants.length === 0) return "unchecked";
283
+ const selected = new Set(filters[facetName] ?? []);
284
+ let hits = 0;
285
+ for (const v of descendants) if (selected.has(v)) hits++;
286
+ if (hits === 0) return "unchecked";
287
+ if (hits === descendants.length) return "checked";
288
+ return "indeterminate";
289
+ }
290
+ function toggleTreeNode(filters, facetName, node, currentState) {
291
+ const descendants = collectDescendantValues(node);
292
+ if (descendants.length === 0) return filters;
293
+ const current = filters[facetName] ?? [];
294
+ let nextValues;
295
+ if (currentState === "checked") {
296
+ const drop = new Set(descendants);
297
+ nextValues = current.filter((v) => !drop.has(v));
298
+ } else {
299
+ const merged = new Set(current);
300
+ for (const v of descendants) merged.add(v);
301
+ nextValues = Array.from(merged);
302
+ }
303
+ const next = { ...filters };
304
+ if (nextValues.length === 0) {
305
+ delete next[facetName];
306
+ } else {
307
+ next[facetName] = nextValues;
308
+ }
309
+ return next;
310
+ }
311
+ export {
312
+ buildFacetTree,
313
+ buildNavOrderMap,
314
+ collectDescendantValues,
315
+ computeTreeState,
316
+ countActiveFilters,
317
+ filterStateToUrlParams,
318
+ parseFiltersFromUrl,
319
+ resolveFacetLabel,
320
+ resolveFacetTitle,
321
+ resolveTermLabel,
322
+ shapeFacets,
323
+ sortFacetEntries,
324
+ sortFacetNames,
325
+ toggleFilter,
326
+ toggleTreeNode
327
+ };
package/dist/format.d.ts CHANGED
@@ -1,20 +1,37 @@
1
1
  /**
2
2
  * The search index format: what the indexer writes and the query code
3
3
  * reads. Every file is a classic script that calls
4
- * `window.__DOGSBAY_SEARCH__.load(key, data)`, so it loads from `file://`
5
- * as well as from a server.
4
+ * `window.__DOGSBAY_SEARCH__.load(key, data, src)`, so it loads from
5
+ * `file://` as well as from a server. `src` is the script's own URL
6
+ * (`document.currentScript.src`): it tells which index a file belongs to,
7
+ * so a page can load several (one per product and version) without the
8
+ * files naming their unit, and a unit moved or mirrored still loads.
6
9
  *
7
10
  * docs.js Meta: titles, URLs and sections of every document
8
11
  * t-<k>.js Postings for terms whose first `depth` characters are <k>
9
12
  * f-<n>.js Fragments of documents n·block … n·block+block−1:
10
13
  * excerpt and headings, loaded only for results being shown
11
14
  */
12
- /** Version 4: tags for filters (3 split fragments out of docs.js, 2 added field-weighted scores). */
13
- declare const FORMAT = 4;
15
+ /**
16
+ * Version 5: files pass their own URL to load(), so several indexes load in one page (4 added
17
+ * tags for filters, 3 split fragments out of docs.js, 2 added field-weighted scores).
18
+ */
19
+ declare const FORMAT = 5;
14
20
  /** Documents per fragment file. */
15
21
  declare const BLOCK = 32;
16
- /** Section and tags are indexes into Meta.sections and Meta.tags; tags are left out when there are none. */
17
- type Doc = [title: string, url: string, section: number, tags?: number[]];
22
+ /**
23
+ * Section and tags are indexes into Meta.sections and Meta.tags; tags are left out when there are
24
+ * none. `facets[i]` holds the document's value indexes for `Meta.facets[i]` (trailing empty ones
25
+ * left out; tags written `[]` when a document has facets but no tags).
26
+ */
27
+ type Doc = [title: string, url: string, section: number, tags?: number[], facets?: number[][]];
28
+ /** A declared facet (a taxonomy): its name, as the query writes it (`<name>:<value>`), and its values. */
29
+ interface FacetTable {
30
+ name: string;
31
+ values: string[];
32
+ }
33
+ /** A facet name a query can write: lower-case letters, digits, `-` and `_`, starting with a letter. `tag` and `section` are built in. */
34
+ declare const FACET_NAME: RegExp;
18
35
  interface Meta {
19
36
  format: number;
20
37
  /** Characters of a term that pick its shard: 1, or 2 for large units. */
@@ -23,6 +40,8 @@ interface Meta {
23
40
  shards: string[];
24
41
  sections: string[];
25
42
  tags: string[];
43
+ /** Declared facets (taxonomies), left out when there are none. */
44
+ facets?: FacetTable[];
26
45
  block: number;
27
46
  /** The unit's language, which picks the query-time stemmer. */
28
47
  lang?: string;
@@ -48,4 +67,4 @@ declare function wrap(k: string, data: unknown): string;
48
67
  /** As wrap(), for data already serialised (fragments are kept as JSON strings while building). */
49
68
  declare function wrapJson(k: string, json: string): string;
50
69
 
51
- export { BLOCK, type Doc, FORMAT, type Fragment, type Meta, type Postings, file, key, wrap, wrapJson };
70
+ export { BLOCK, type Doc, FACET_NAME, FORMAT, type FacetTable, type Fragment, type Meta, type Postings, file, key, wrap, wrapJson };
package/dist/format.js CHANGED
@@ -1,5 +1,6 @@
1
- const FORMAT = 4;
1
+ const FORMAT = 5;
2
2
  const BLOCK = 32;
3
+ const FACET_NAME = /^[a-z][a-z0-9_-]{0,63}$/;
3
4
  const file = {
4
5
  docs: "docs.js",
5
6
  shard: (key2) => `t-${key2}.js`,
@@ -15,11 +16,12 @@ function wrap(k, data) {
15
16
  return wrapJson(k, json);
16
17
  }
17
18
  function wrapJson(k, json) {
18
- return `(window.__DOGSBAY_SEARCH__=window.__DOGSBAY_SEARCH__||{q:[],load:function(k,d){this.q.push([k,d])}}).load(${JSON.stringify(k)},${json});
19
+ return `(window.__DOGSBAY_SEARCH__=window.__DOGSBAY_SEARCH__||{q:[],load:function(k,d,s){this.q.push([k,d,s])}}).load(${JSON.stringify(k)},${json},typeof document!="undefined"&&document.currentScript?document.currentScript.src:"");
19
20
  `;
20
21
  }
21
22
  export {
22
23
  BLOCK,
24
+ FACET_NAME,
23
25
  FORMAT,
24
26
  file,
25
27
  key,
package/dist/index.d.ts CHANGED
@@ -15,6 +15,12 @@ interface SearchDoc {
15
15
  anchors?: [text: string, id: string][];
16
16
  /** Tags, for filters (`tag:x`). */
17
17
  tags?: string[];
18
+ /**
19
+ * Values per declared facet (a taxonomy: `audience`, `type`, …), for `<name>:<value>` filters and
20
+ * counts. Names follow `FACET_NAME`; `tag` and `section` are built in. A hierarchical value is
21
+ * written once per level (`api`, `api/rest`), so filtering on a parent finds its children.
22
+ */
23
+ facets?: Record<string, string[]>;
18
24
  }
19
25
  /**
20
26
  * Ranking: each field is scored on its own and the fields are combined
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { detach } from "./detach.js";
2
- import { BLOCK, FORMAT, file, key, wrap, wrapJson } from "./format.js";
2
+ import { BLOCK, FACET_NAME, FORMAT, file, key, wrap, wrapJson } from "./format.js";
3
3
  import { shardKey, tokenize } from "./text.js";
4
4
  const RANK = {
5
5
  k1: 1.2,
@@ -57,6 +57,12 @@ class SearchIndexBuilder {
57
57
  url: detach(doc.url),
58
58
  section: detach(doc.section),
59
59
  tags: (doc.tags ?? []).map(detach),
60
+ facets: Object.entries(doc.facets ?? {}).map(([name, values]) => {
61
+ if (!FACET_NAME.test(name) || name === "tag" || name === "section")
62
+ throw new Error(`SearchIndexBuilder: facet name ${JSON.stringify(name)}: use lower-case letters, digits, "-" and "_", starting with a letter (tag and section are built in)`);
63
+ if (!Array.isArray(values)) throw new Error(`SearchIndexBuilder: facet ${JSON.stringify(name)}: values must be a list of strings`);
64
+ return [name, [...new Set(values.filter((v) => typeof v === "string").map((v) => v.trim()).filter(Boolean))].map(detach)];
65
+ }),
60
66
  fragment: JSON.stringify([doc.excerpt, doc.anchors ?? []]).replace(/<\//g, "<\\/")
61
67
  });
62
68
  const counts = /* @__PURE__ */ new Map();
@@ -189,18 +195,33 @@ class SearchIndexBuilder {
189
195
  const sectionIndex = /* @__PURE__ */ new Map();
190
196
  const tags = [];
191
197
  const tagIndex = /* @__PURE__ */ new Map();
198
+ const facets = [];
199
+ const facetIndex = /* @__PURE__ */ new Map();
192
200
  const docs = this.docs.map((d) => {
193
201
  let i = sectionIndex.get(d.section);
194
202
  if (i === void 0) sectionIndex.set(d.section, i = sections.push(d.section) - 1);
195
- if (!d.tags.length) return [d.title, d.url, i];
196
203
  const t = d.tags.map((tag) => {
197
204
  let j = tagIndex.get(tag);
198
205
  if (j === void 0) tagIndex.set(tag, j = tags.push(tag) - 1);
199
206
  return j;
200
207
  });
201
- return [d.title, d.url, i, t];
208
+ const f = [];
209
+ for (const [name, values] of d.facets) {
210
+ let table = facetIndex.get(name);
211
+ if (!table) facetIndex.set(name, table = { i: facets.push({ name, values: [] }) - 1, values: /* @__PURE__ */ new Map() });
212
+ const ids = values.map((v) => {
213
+ let j = table.values.get(v);
214
+ if (j === void 0) table.values.set(v, j = facets[table.i].values.push(v) - 1);
215
+ return j;
216
+ });
217
+ while (f.length <= table.i) f.push([]);
218
+ f[table.i] = ids;
219
+ }
220
+ while (f.length && !f[f.length - 1].length) f.pop();
221
+ if (f.length) return [d.title, d.url, i, t, f];
222
+ return t.length ? [d.title, d.url, i, t] : [d.title, d.url, i];
202
223
  });
203
- const meta = { format: FORMAT, depth, count: this.docs.length, shards: [...byShard.keys()].sort(), sections, tags, block: BLOCK, lang: this.opts.lang, docs };
224
+ const meta = { format: FORMAT, depth, count: this.docs.length, shards: [...byShard.keys()].sort(), sections, tags, ...facets.length ? { facets } : {}, block: BLOCK, lang: this.opts.lang, docs };
204
225
  yield [file.docs, wrap(key.docs, meta)];
205
226
  for (let b = this.fragmentsOut; b * BLOCK < this.docs.length; b++) yield this.fragmentFile(b);
206
227
  if (!this.grouped) {
package/dist/query.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { Fragment, Meta, Postings } from './format.js';
1
+ import { Meta, Postings, Fragment } from './format.js';
2
2
 
3
3
  /**
4
4
  * The query side: parse a query, rank documents from the postings, then
@@ -53,6 +53,17 @@ interface ParsedQuery {
53
53
  tag: string[];
54
54
  section: string[];
55
55
  };
56
+ /**
57
+ * `<facet>:<value>` for the declared facets the query was parsed with (`parseQuery(q, { facets })`),
58
+ * lower-cased, by facet: values of one facet are alternatives, and every facet must match.
59
+ */
60
+ facets?: Record<string, string[]>;
61
+ /** `-<facet>:<value>`: documents with any of these are excluded. */
62
+ notFacets?: Record<string, string[]>;
63
+ }
64
+ interface ParseOptions {
65
+ /** Declared facet names (from the index's `Meta.facets`): `<name>:<value>` filters on them; any other `x:y` stays a word. */
66
+ facets?: string[];
56
67
  }
57
68
  /**
58
69
  * Query syntax, deliberately small: `"a phrase"` (all its words, with the
@@ -60,7 +71,7 @@ interface ParsedQuery {
60
71
  * (either). Operators are upper case, so ordinary words such as "or" and
61
72
  * "not" in a natural query are not read as operators (they are stop words).
62
73
  */
63
- declare function parseQuery(q: string): ParsedQuery;
74
+ declare function parseQuery(q: string, opts?: ParseOptions): ParsedQuery;
64
75
  /** Rank documents from the postings alone (no fragments). */
65
76
  declare function query(q: string | ParsedQuery, data: SearchData): Promise<Result[]>;
66
77
  /**
@@ -87,34 +98,117 @@ declare function oneEdit(a: string, b: string): boolean;
87
98
  declare function shardsFor(term: string, meta: Meta, prefix?: boolean): string[];
88
99
  /** Filter values compare lower-cased and without quotes ("section:\"Say hi\"" matches the section `Say "hi"`). */
89
100
  declare function facetValue(v: string): string;
90
- /** Load the fragments of these results (one file per block of documents). */
91
- declare function loadFragments(results: Result[], data: SearchData): Promise<void>;
101
+ /** The facet names declared by any of these indexes, for `parseQuery(q, { facets })`. */
102
+ declare function facetNames(metas: (Meta | undefined)[]): string[];
103
+ /**
104
+ * Value → number of results, per facet; `tag` and `section` included. Values that a filter cannot tell
105
+ * apart (case, surrounding space: `facetValue`) are counted as one, under the first spelling met.
106
+ */
107
+ type FacetCounts = Record<string, Record<string, number>>;
108
+ /**
109
+ * Count each facet value over results (all of them, not the page shown: pass what `query` or
110
+ * `querySources` returned). Counts are computed here, in the browser, so the index needs no count
111
+ * files. `metaOf` gives a result's index (one Meta for a single index). The shape is the one
112
+ * `shapeFacets` in `@dogsbay/search/facets` sorts for display.
113
+ */
114
+ declare function facetCounts<R extends Result>(results: R[], metaOf: Meta | ((r: R) => Meta | undefined)): FacetCounts;
115
+ /**
116
+ * Rare query words count for more (BM25's idf). One idf for the whole group, from the number of
117
+ * documents any of its terms appears in: a per-completion idf would let a rare completion
118
+ * ("nodeselector") outrank the word typed ("node"). The stored scores already carry field weights
119
+ * and length normalisation. Over several indexes, `n` and `df` are their sums (combined statistics).
120
+ */
121
+ declare function idfOf(n: number, df: number): number;
122
+ /** The index a result came from: one SearchData, or a function of the result (several indexes). */
123
+ type DataFor = SearchData | ((r: Result) => SearchData);
124
+ /** Load the fragments of these results (one file per block of documents, per index). */
125
+ declare function loadFragments(results: Result[], data: DataFor): Promise<void>;
92
126
  /**
93
127
  * Re-rank the top `n` results with their fragments, which the postings
94
128
  * cannot see: whether one heading holds every query word (the postings only
95
129
  * know that the words are somewhere in the headings), and whether quoted
96
130
  * phrases appear. Also picks the headings to show under each result.
97
131
  */
98
- declare function refine(p: ParsedQuery, results: Result[], data: SearchData, n?: number): Promise<Result[]>;
132
+ declare function refine<R extends Result>(p: ParsedQuery, results: R[], data: DataFor, n?: number): Promise<R[]>;
99
133
  /** Load fragments for results outside the refined top, and pick their matching headings (no re-ranking). */
100
- declare function loadDetails(p: ParsedQuery, results: Result[], data: SearchData): Promise<void>;
134
+ declare function loadDetails(p: ParsedQuery, results: Result[], data: DataFor): Promise<void>;
101
135
  /** Query, then refine the top results: what a search box shows. */
102
136
  declare function search(q: string, data: SearchData, n?: number): Promise<{
103
137
  parsed: ParsedQuery;
104
138
  results: Result[];
139
+ facets: FacetCounts;
140
+ }>;
141
+ /** One index searched with others: a product's version, say. */
142
+ interface Source {
143
+ data: SearchData;
144
+ /** Its scores are multiplied by this (the reader's own product and version ranked higher). Default 1. */
145
+ boost?: number;
146
+ /**
147
+ * Indexes with the same `collapse` value show a page once: results with the same URL (a path inside
148
+ * the index, as the indexer stores it) are one result, the best scored, the others in `others`.
149
+ * Give a product's versions its name; leave it out to show every copy.
150
+ */
151
+ collapse?: string;
152
+ }
153
+ interface SourceResult extends Result {
154
+ /** The index it came from: its place in the sources list. */
155
+ source: number;
156
+ /** The same page in other indexes of its `collapse` group, best first. */
157
+ others?: {
158
+ source: number;
159
+ id: number;
160
+ url: string;
161
+ score: number;
162
+ }[];
163
+ }
164
+ interface SourcesOptions {
165
+ /**
166
+ * How rare a word is, for its weight: `combined` (default) counts its documents across every
167
+ * index searched, so scores from different indexes share one scale; `own` uses each index's
168
+ * own counts, as a search of that index alone would.
169
+ */
170
+ stats?: "combined" | "own";
171
+ }
172
+ /**
173
+ * Rank documents across several indexes from the postings alone: one list, merged by score. An
174
+ * index that does not load or is in another format is left out (`searchSources` lists it).
175
+ */
176
+ declare function querySources(q: string | ParsedQuery, sources: Source[], opts?: SourcesOptions): Promise<SourceResult[]>;
177
+ /**
178
+ * Query several indexes, then refine the top results: a search box over products and versions.
179
+ * `missing` lists the sources left out (not loaded, or another format), by their place in the list.
180
+ */
181
+ declare function searchSources(q: string, sources: Source[], n?: number, opts?: SourcesOptions): Promise<{
182
+ parsed: ParsedQuery;
183
+ results: SourceResult[];
184
+ missing: number[];
185
+ facets: FacetCounts;
105
186
  }>;
106
187
  interface SearchGlobal {
107
- q: [string, unknown][];
108
- load: (k: string, d: unknown) => void;
188
+ /** Files that loaded before any index claimed them: key, data, the script's URL. */
189
+ q: [string, unknown, string?][];
190
+ load: (k: string, d: unknown, src?: string) => void;
191
+ /** Each index's files by its base URL (absolute), shared by every scriptData on the page. */
192
+ stores?: Map<string, Map<string, unknown>>;
109
193
  }
110
194
  /**
111
195
  * SearchData that loads the index files as <script> tags from `base` (the
112
196
  * unit's `_dogsbay/search/` URL), which works from file:// and over HTTP.
197
+ * Several can live on one page, one per index: a file goes to the index
198
+ * whose base its own URL starts with (the longest). A file that does not
199
+ * say where it came from (no `document.currentScript`) goes to the only
200
+ * index on the page, and waits while there are several.
113
201
  */
114
202
  declare function scriptData(base: string, loadScript: (src: string) => Promise<void>, g?: {
115
203
  __DOGSBAY_SEARCH__?: SearchGlobal;
204
+ location?: {
205
+ href: string;
206
+ };
207
+ document?: {
208
+ baseURI?: string;
209
+ };
116
210
  }): SearchData;
117
211
  /** SearchData over already-loaded data, keyed as load() keys it (tests, tools). */
118
212
  declare function memoryData(store: Map<string, unknown>): SearchData;
119
213
 
120
- export { type ParsedQuery, QUERY_RANK, type Result, type SearchData, facetValue, loadDetails, loadFragments, memoryData, oneEdit, parseQuery, query, refine, scriptData, search, shardsFor };
214
+ export { type DataFor, type FacetCounts, type ParseOptions, type ParsedQuery, QUERY_RANK, type Result, type SearchData, type Source, type SourceResult, type SourcesOptions, facetCounts, facetNames, facetValue, idfOf, loadDetails, loadFragments, memoryData, oneEdit, parseQuery, query, querySources, refine, scriptData, search, searchSources, shardsFor };