-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathsearch.mjs
More file actions
714 lines (669 loc) · 24.9 KB
/
Copy pathsearch.mjs
File metadata and controls
714 lines (669 loc) · 24.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
// Copyright (c) Meta Platforms, Inc. and affiliates.
/**
* @file Programmatic API for the unified `search` command.
*
* Returns the same typed envelope { type, data } that `xds --json search`
* outputs. The CLI command handler is a thin wrapper around this function.
*
* `search(query)` is the single "I'm looking for X" entry point across ALL
* content domains — components, hooks, docs topics, and templates (page +
* block). Today, finding the right thing requires four separate list calls
* (`component --list`, `hook --list`, `docs`, `template --list`) plus manual
* scanning; this collapses them into one ranked, typed result set.
*
* Scoring is keyword + fuzzy ranking (NOT semantic / embeddings — that is a
* deliberate future follow-up). It reuses the same signal weighting as the
* component fuzzy resolver in lib/string-utils.mjs:
*
* 100 exact name match
* 90 exact keyword match
* 80 name Levenshtein distance 1
* 70 keyword substring / distance 1
* 60 name substring (>=4 chars, >=50% coverage)
* 50 description / prose mentions the term
* 40 name Levenshtein distance 2
* 30 keyword Levenshtein distance 2
* 20 name Levenshtein distance 3
*
* Name + keyword signals always outweigh description/prose, so an exact match
* sorts above an incidental mention.
*
* Keywords come in two grades. Authored ones — a component's `keywords`, a
* block's `componentsUsed`, a page's `category` — score the ladder above at
* face value. Derived ones — the component names read back out of a page
* template's own source — score it scaled by {@link derivedKeywordWeight},
* because "this page renders a <List> somewhere" is weaker evidence than "this
* page is about lists", and weaker still the more components the page renders.
*/
import {pathToFileURL} from 'node:url';
import {findCoreDir} from '../../foundation/fs/paths.mjs';
import {
discoverComponents,
findComponentReadme,
resolveImportPath,
} from '../../foundation/discovery/component-discovery.mjs';
import {discoverHooks, findHookDoc} from '../../foundation/discovery/hook-discovery.mjs';
import {levenshteinDistance} from '../../foundation/text/string-utils.mjs';
import {discoverTemplates, extractComponents} from '../template/template.mjs';
import {loadDocsCatalog, loadTopicDoc} from '../docs/_adapter.mjs';
import {AstryxError} from '../error.mjs';
import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';
/**
* A search candidate gathered from one content domain. Extra underscore-
* prefixed fields carry domain-specific payload used only by {@link toResult}.
* @typedef {object} Candidate
* @property {'component'|'hook'|'doc'|'template'} domain
* @property {string} name
* @property {string[]} [keywords]
* @property {string[]} [derivedKeywords] - Read back from source, not authored; weighted down by breadth.
* @property {string} [description]
* @property {string[]} [prose]
* @property {string} [_import]
* @property {string} [_title]
* @property {string} [_displayName]
* @property {'page'|'block'} [_kind]
*/
/**
* Synonym / intent map: product-language terms an agent is likely to type,
* expanded to the catalog's vocabulary so oblique queries still rank. Keys and
* values are matched bidirectionally (typing any value also pulls in the key
* and its siblings). Lowercase, single words or short phrases.
*/
const SYNONYMS = {
dashboard: ['overview', 'analytics', 'kpi', 'kpis', 'metrics', 'stats', 'reporting', 'insights', 'control'],
login: ['signin', 'auth', 'authentication', 'sso', 'credentials', 'account'],
signup: ['register', 'registration', 'onboarding'],
payment: ['checkout', 'billing', 'card', 'pay', 'purchase', 'order'],
pricing: ['plans', 'plan', 'tiers', 'tier', 'subscription', 'subscriptions'],
chat: ['messaging', 'message', 'messages', 'conversation', 'inbox', 'dm'],
settings: ['preferences', 'config', 'configuration', 'account'],
calendar: ['schedule', 'scheduling', 'events', 'event', 'month', 'agenda'],
table: ['list', 'rows', 'records', 'grid', 'spreadsheet', 'datatable'],
gallery: ['photos', 'photo', 'images', 'image', 'pictures'],
hero: ['banner', 'splash', 'headline', 'landing'],
form: ['fields', 'input', 'inputs', 'survey'],
profile: ['bio', 'avatar', 'user'],
documentation: ['docs', 'reference', 'guide', 'api'],
navigation: ['nav', 'menu', 'sidebar'],
};
// Flatten into a token -> Set(expansions) lookup (bidirectional).
const SYNONYM_INDEX = (() => {
/** @type {Map<string, Set<string>>} */
const idx = new Map();
/**
* @param {string} a
* @param {string} b
*/
const add = (a, b) => {
let set = idx.get(a);
if (!set) {
set = new Set();
idx.set(a, set);
}
set.add(b);
};
for (const [key, vals] of Object.entries(SYNONYMS)) {
for (const v of vals) {
add(key, v);
add(v, key);
for (const v2 of vals) if (v2 !== v) add(v, v2);
}
}
return idx;
})();
/**
* Light stemmer: strips common English suffixes so "charts"/"charting" and
* "chart" share a root. Deliberately crude (no Porter) — good enough to bridge
* plural/gerund gaps without a dependency.
* @param {string} w
* @returns {string}
*/
export function stem(w) {
let s = w;
for (const suf of ['ing', 'ed', 'ies', 'es', 's']) {
if (s.length > suf.length + 2 && s.endsWith(suf)) {
s = suf === 'ies' ? s.slice(0, -3) + 'y' : s.slice(0, -suf.length);
break;
}
}
return s;
}
/** Valid domain filters for `--type`. */
export const SEARCH_DOMAINS = ['component', 'hook', 'doc', 'template'];
/**
* Filler words stripped from multi-word queries so natural-language phrasing
* ("a page where you can see business stats") ranks on its content words.
*/
const STOPWORDS = new Set([
'a', 'an', 'the', 'of', 'for', 'to', 'with', 'and', 'or', 'in', 'on', 'at',
'by', 'that', 'this', 'my', 'your', 'our', 'their', 'is', 'are', 'be', 'it',
'its', 'as', 'from', 'page', 'screen', 'app', 'application', 'view', 'where',
'you', 'can', 'some', 'like', 'just', 'basically', 'kinda', 'want', 'wants',
'need', 'needs', 'something', 'thing', 'things', 'build', 'make', 'create',
'i', 'me', 'we', 'us', 'so', 'up', 'out', 'over', 'side', 'one', 'big',
]);
/**
* Split a query into meaningful content tokens (lowercased, stopwords + very
* short words removed). Empty for single-word queries (callers fall back to
* whole-phrase scoring).
* @param {string} term - Already-lowercased query.
* @returns {string[]}
*/
export function tokenizeQuery(term) {
return term
.split(/\s+/)
// Strip only leading/trailing punctuation; keep joined identifiers intact
// (e.g. "foo_bar" stays one token) so gibberish stays gibberish.
.map(t => t.replace(/^[^a-z0-9]+|[^a-z0-9]+$/g, ''))
.filter(t => t.length >= 2 && !STOPWORDS.has(t));
}
/**
* Score a candidate against a query, handling multi-word natural language.
* Tries the whole phrase (so exact/near matches still win) AND a per-token
* pass (so "data table with filters" matches `table-page` via table+filter),
* and returns whichever is stronger.
*
* @param {string} term - Lowercased full query.
* @param {string[]} tokens - Content tokens from tokenizeQuery(term).
* @param {object} candidate
* @returns {{score: number, reason: string} | null}
*/
/**
* Minimum per-token score (in the multi-word pass) to count as a real match.
* 50 = a genuine name/keyword/description hit; below that is loose Levenshtein
* fuzz that would otherwise turn gibberish queries into noise.
*/
const MIN_TOKEN_SCORE = 50;
/**
* Best score for a token against a candidate, fanning out through synonyms
* (synonym hits are discounted so a direct hit always wins).
* @param {string} tok
* @param {Candidate} candidate
* @returns {{score: number, reason: string} | null}
*/
function bestForToken(tok, candidate) {
let best = scoreCandidate(tok, candidate);
const syns = SYNONYM_INDEX.get(tok);
if (syns) {
for (const s of syns) {
const h = scoreCandidate(s, candidate);
if (h) {
const score = Math.round(h.score * 0.85);
if (!best || score > best.score) best = {score, reason: `${h.reason} (~${tok})`};
}
}
}
return best;
}
/**
* @param {string} term - Lowercased full query.
* @param {string[]} tokens - Content tokens from tokenizeQuery(term).
* @param {Candidate} candidate
* @returns {{score: number, reason: string} | null}
*/
export function scoreQuery(term, tokens, candidate) {
const full = scoreCandidate(term, candidate);
// 0–1 content tokens: keep whole-phrase fuzzy matching (typo tolerance for
// single words), but if stopwords left exactly one DIFFERENT token (e.g.
// "pricing page" → "pricing"), score that token too and take the stronger.
if (tokens.length <= 1) {
const single = tokens.length === 1 ? bestForToken(tokens[0], candidate) : null;
if (full && (!single || full.score >= single.score)) return full;
return single;
}
// Multi-word natural language: score each content token, counting only
// strong hits, then reward coverage so candidates matching more terms win.
let sum = 0;
let matched = 0;
/** @type {string[]} */
const hitTerms = [];
for (const tok of tokens) {
const h = bestForToken(tok, candidate);
if (h && h.score >= MIN_TOKEN_SCORE) {
sum += h.score;
matched++;
hitTerms.push(tok);
}
}
if (matched === 0) return full;
// Reward the AVERAGE strength of the concepts that matched (not divided by
// total query length — that penalizes verbose / low-fidelity prompts), plus
// a bonus per additional matched concept and a coverage term. A candidate
// that matches several of the query's concepts beats one matching a single
// incidental word.
const avgMatched = sum / matched;
const coverage = matched / tokens.length;
const tokenScore = Math.round(avgMatched + Math.min(matched - 1, 3) * 12 + coverage * 15);
if (full && full.score >= tokenScore) return full;
return {
score: tokenScore,
reason: `matches ${matched}/${tokens.length} terms: ${hitTerms.join(', ')}`,
};
}
/**
* Pivot for the derived-keyword falloff `PIVOT / (PIVOT + count)`. Tuned so a
* focused page (~5 rendered components) lands an exact derived hit on the
* "related keyword" rung (70) rather than the "authored keyword" rung (90) —
* derived evidence enters one rung below what a template author declared — and
* a page past ~14 components no longer clears {@link MIN_TOKEN_SCORE} on one,
* so a kitchen-sink page stops claiming a concept it only brushes against. For
* scale: the median page template renders 13 components, the widest renders 51.
*/
const DERIVED_SURFACE_PIVOT = 18;
/**
* Length-normalize a derived keyword hit by how many keywords were derived
* alongside it. A page rendering five components is plausibly *about* any one
* of them; a page rendering fifty is about none of them. Without this every
* page that renders a `<List>` scored an identical 90 on "list" and the
* ranking degenerated into `name.localeCompare`.
*
* @param {number} count - How many keywords were derived for this candidate.
* @returns {number} Multiplier in (0, 1); 0 when nothing was derived.
*/
function derivedKeywordWeight(count) {
if (count <= 0) return 0;
return DERIVED_SURFACE_PIVOT / (DERIVED_SURFACE_PIVOT + count);
}
/**
* Run the keyword ladder (exact 90 / substring + distance-1 70 / distance-2 30)
* over one keyword list, scaled by `weight`, feeding each hit to `consider`.
*
* @param {string} term - Lowercased search term.
* @param {string[]} keywords
* @param {number} weight - 1 for authored keywords; see {@link derivedKeywordWeight}.
* @param {string} label - How the hit reads in the `reason` ("keyword" / "renders").
* @param {(score: number, why: string) => void} consider
*/
function considerKeywords(term, keywords, weight, label, consider) {
/** @param {number} score */
const scaled = score => Math.round(score * weight);
for (const kw of keywords) {
const kwLower = String(kw).toLowerCase();
if (kwLower === term) {
consider(scaled(90), `${label} "${kw}"`);
continue;
}
const s = term.length < kwLower.length ? term : kwLower;
const l = term.length < kwLower.length ? kwLower : term;
if (s.length >= 4 && l.includes(s) && s.length / l.length >= 0.5) {
consider(scaled(70), `${label} "${kw}"`);
}
const dist = levenshteinDistance(term, kwLower);
if (dist === 1) consider(scaled(70), `${label} "${kw}" (distance ${dist})`);
else if (dist === 2) consider(scaled(30), `${label} "${kw}" (distance ${dist})`);
}
}
/**
* Score a single candidate against the search term across name, keywords,
* and prose signals. Returns the best (highest) score plus a human reason,
* or null if nothing matched above the floor.
*
* @param {string} term - Lowercased search term.
* @param {object} candidate
* @param {string} candidate.name - Primary identifier (component/hook name, topic, template name).
* @param {string[]} [candidate.keywords] - Authored keywords; scored at face value.
* @param {string[]} [candidate.derivedKeywords] - Read back from source; scored down by breadth.
* @param {string} [candidate.description]
* @param {string[]} [candidate.prose] - Extra free-text blobs (doc section text, best practices).
* @returns {{score: number, reason: string} | null}
*/
export function scoreCandidate(
term,
{name, keywords = [], derivedKeywords = [], description = '', prose = []},
) {
let best = 0;
let reason = '';
/**
* @param {number} score
* @param {string} why
*/
const consider = (score, why) => {
if (score > best) {
best = score;
reason = why;
}
};
const nameLower = name.toLowerCase();
// ── Name signals ────────────────────────────────────────────────
if (nameLower === term) {
consider(100, 'exact name');
} else {
// Substring (both directions), min 4 chars, >=50% coverage.
const shorter = term.length < nameLower.length ? term : nameLower;
const longer = term.length < nameLower.length ? nameLower : term;
if (shorter.length >= 4 && longer.includes(shorter) && shorter.length / longer.length >= 0.5) {
consider(60, `name contains "${shorter}"`);
}
const dist = levenshteinDistance(term, nameLower);
if (dist === 1) consider(80, `similar name (distance ${dist})`);
else if (dist === 2) consider(40, `similar name (distance ${dist})`);
else if (dist === 3) consider(20, `similar name (distance ${dist})`);
}
// ── Keyword signals ─────────────────────────────────────────────
considerKeywords(term, keywords, 1, 'keyword', consider);
// ── Derived keyword signals (length-normalized) ─────────────────
considerKeywords(
term,
derivedKeywords,
derivedKeywordWeight(derivedKeywords.length),
'renders',
consider,
);
// ── Prose / description signals (stem-tolerant whole word) ──────
// Match the term's stem as a whole word, tolerating plural/gerund suffixes
// so "chart" matches "charts" and "filter" matches "filtering".
if (term.length >= 3) {
const root = stem(term);
const escaped = root.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const re = new RegExp(`\\b${escaped}(s|es|ing|ed|ies)?\\b`);
if (description && re.test(description.toLowerCase())) {
consider(50, `description mentions "${term}"`);
} else {
for (const blob of prose) {
if (blob && re.test(String(blob).toLowerCase())) {
consider(50, `docs mention "${term}"`);
break;
}
}
}
}
return best > 0 ? {score: best, reason} : null;
}
/**
* Load a doc module's `docs`/`doc` export, swallowing errors.
* @param {string} docPath
* @param {string} [exportName]
* @returns {Promise<any>}
*/
async function loadModuleDoc(docPath, exportName = 'docs') {
try {
const mod = await import(pathToFileURL(docPath).href);
return mod[exportName] ?? null;
} catch {
return null;
}
}
/**
* Build component candidates: name + keywords + usage/description from the
* component's .doc.mjs.
* @param {string} coreDir
* @returns {Promise<Candidate[]>}
*/
async function gatherComponents(coreDir) {
const grouped = discoverComponents(coreDir);
const names = Object.values(grouped).flat();
/** @type {Candidate[]} */
const candidates = [];
for (const comp of names) {
const readme = findComponentReadme(coreDir, comp);
/** @type {string[]} */
let keywords = [];
let description = '';
if (readme && readme.endsWith('.doc.mjs')) {
const doc = await loadModuleDoc(readme);
if (doc) {
keywords = Array.isArray(doc.keywords) ? doc.keywords : [];
description = doc.usage?.description || doc.description || '';
}
}
candidates.push({
domain: 'component',
name: comp,
keywords,
description,
_import: resolveImportPath(coreDir, comp),
});
}
return candidates;
}
/**
* Build hook candidates: name + keywords + usage/description from the hook's
* .doc.mjs.
* @param {string} coreDir
* @returns {Promise<Candidate[]>}
*/
async function gatherHooks(coreDir) {
const grouped = discoverHooks(coreDir);
const names = Object.values(grouped).flat();
/** @type {Candidate[]} */
const candidates = [];
for (const hookName of names) {
const docPath = findHookDoc(coreDir, hookName);
/** @type {string[]} */
let keywords = [];
let description = '';
let importPath = '@astryxdesign/core/hooks';
if (docPath) {
const doc = await loadModuleDoc(docPath);
if (doc) {
keywords = Array.isArray(doc.keywords) ? doc.keywords : [];
description = doc.usage?.description || doc.description || '';
importPath = doc.importPath || importPath;
}
}
candidates.push({
domain: 'hook',
name: hookName,
keywords,
description,
_import: importPath,
});
}
return candidates;
}
/**
* Build doc-topic candidates: topic name + description + section prose.
*
* Reads the project's catalog rather than the CLI's own docs directory, so a
* topic an integration contributed (or replaced) is searchable exactly like a
* built-in one — otherwise the replacement is served by `astryx docs` but
* invisible to the command whose job is finding it.
* @param {string} cwd
* @returns {Promise<Candidate[]>}
*/
async function gatherDocs(cwd) {
/** @type {Candidate[]} */
const candidates = [];
let entries;
try {
entries = (await loadDocsCatalog(cwd)).entries();
} catch {
return candidates;
}
for (const entry of entries) {
let doc = null;
try {
doc = await loadTopicDoc(entry);
} catch {
// A topic that cannot be loaded is reported by the commands that own
// integration issues; search just cannot index it.
}
let description = '';
/** @type {string[]} */
const prose = [];
if (doc) {
description = doc.description || '';
for (const section of doc.sections || []) {
if (section.title) prose.push(section.title);
for (const block of section.content || []) {
if (block.type === 'prose' && block.text) prose.push(block.text);
}
}
}
candidates.push({
domain: 'doc',
name: entry.name,
keywords: [],
description,
prose,
_title: doc?.title || entry.title || entry.name,
});
}
return candidates;
}
/**
* Build template candidates (page + block) from the template discovery API.
* @param {string} cwd
* @returns {Promise<Candidate[]>}
*/
async function gatherTemplates(cwd) {
let templates;
try {
templates = await discoverTemplates(cwd);
} catch {
return [];
}
return templates.map(t => {
// Blocks ship componentsUsed; page templates usually don't, so read them
// back out of the source. Category words (e.g. "Dashboard - Analytics") are
// strong intent signal for pages, which otherwise only index on name +
// description.
const keywords = Array.isArray(t.componentsUsed) ? [...t.componentsUsed] : [];
/** @type {string[]} */
let derivedKeywords = [];
if (t.type === 'page') {
if (t.filePath) {
try {
// Source-read, not authored: a page rendering a <List> in a sidebar
// must not claim "list" as loudly as one whose category says so.
derivedKeywords = extractComponents(t.filePath);
} catch {
// Best-effort: skip keyword enrichment if the source can't be read.
}
}
if (t.category) keywords.push(...t.category.split(/[^A-Za-z0-9]+/).filter(Boolean));
}
return {
domain: 'template',
name: t.dirName,
keywords,
derivedKeywords,
description: t.description || '',
_displayName: t.name,
_kind: t.type, // 'page' | 'block'
};
});
}
/**
* Map a scored candidate to its public, actionable result shape. Each result
* carries enough to act on it: the domain, name, a one-line description, and
* the follow-up command (and import path where relevant).
*
* @param {Candidate} c - candidate
* @param {number} score
* @param {string} reason
*/
function toResult(c, score, reason) {
const base = {
domain: c.domain,
name: c.name,
score,
reason,
description: c.description || '',
};
switch (c.domain) {
case 'component':
return {
...base,
import: c._import,
command: `astryx component ${c.name}`,
};
case 'hook':
return {
...base,
import: c._import,
command: `astryx hook ${c.name}`,
};
case 'doc':
return {
...base,
title: c._title,
command: `astryx docs ${c.name}`,
};
case 'template':
return {
...base,
displayName: c._displayName,
kind: c._kind,
command: `astryx template ${c.name}`,
};
default:
return base;
}
}
/**
* Unified ranked search across components, hooks, docs, and templates.
*
* @param {string} query - Free-text search term.
* @param {object} [options]
* @param {string} [options.cwd]
* @param {'component'|'hook'|'doc'|'template'} [options.type] - Restrict to one domain.
* @param {number} [options.limit] - Max results (default 20).
* @returns {Promise<{type: 'search', data: {query: string, results: Array<object>}}>}
*/
export async function search(query, options = {}) {
const {cwd = process.cwd(), type, limit = 20} = options;
if (!query || !String(query).trim()) {
throw new AstryxError(
'A search query is required',
[{name: 'astryx search button', reason: 'example'}],
ERROR_CODES.ERR_INVALID_ARGUMENT,
);
}
if (type && !SEARCH_DOMAINS.includes(type)) {
throw new AstryxError(
`Unknown --type "${type}"`,
SEARCH_DOMAINS.map(d => ({name: d, reason: 'valid type'})),
ERROR_CODES.ERR_INVALID_ARGUMENT,
);
}
// Validate limit here (not just in the CLI) so direct API callers get the same
// contract: a non-positive or non-integer limit is an error, never a silent
// "return everything". (Previously `limit <= 0` fell through to the full set.)
if (
limit != null &&
(!Number.isInteger(limit) || limit <= 0)
) {
throw new AstryxError(
`Invalid limit "${limit}". Must be a positive integer.`,
undefined,
ERROR_CODES.ERR_INVALID_ARGUMENT,
);
}
const term = String(query).trim().toLowerCase();
const tokens = tokenizeQuery(term);
const coreDir = findCoreDir(cwd);
if (!coreDir) {
throw new AstryxError('Could not find @astryxdesign/core package');
}
// Gather candidates from each requested domain in parallel.
/** @param {string} d */
const wants = d => !type || type === d;
const [components, hooks, docTopics, templates] = await Promise.all([
wants('component') ? gatherComponents(coreDir) : [],
wants('hook') ? gatherHooks(coreDir) : [],
wants('doc') ? gatherDocs(cwd) : [],
wants('template') ? gatherTemplates(cwd) : [],
]);
const all = [...components, ...hooks, ...docTopics, ...templates];
// Score every candidate on its own merits. The consumer groups results by
// role (page / block / component) and takes the top of each, so there's no
// cross-role competition to engineer — a target page only needs to be the
// strongest PAGE, not outrank every component.
const scored = [];
for (const candidate of all) {
const hit = scoreQuery(term, tokens, candidate);
if (hit) scored.push(toResult(candidate, hit.score, hit.reason));
}
// Sort by score desc, then domain (stable order), then name.
/** @type {Record<string, number>} */
const domainOrder = {component: 0, hook: 1, doc: 2, template: 3};
scored.sort(
(a, b) =>
b.score - a.score ||
(domainOrder[a.domain] ?? 9) - (domainOrder[b.domain] ?? 9) ||
a.name.localeCompare(b.name),
);
const limited = scored.slice(0, limit);
return {type: 'search', data: {query: String(query).trim(), results: limited}};
}