@open-mercato/cli 0.10.1-develop.7756.1.8f5dec1b96 → 0.10.1-develop.7759.1.416727583e

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.
Files changed (120) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/dist/agentic/guides/module-facts.json +162 -162
  3. package/dist/agentic/guides/module-facts.v2.json +162 -162
  4. package/dist/agentic/guides/modules/agent_orchestrator/index.md +1 -1
  5. package/dist/agentic/guides/modules/ai_assistant/index.md +1 -1
  6. package/dist/agentic/guides/modules/api_docs/index.md +1 -1
  7. package/dist/agentic/guides/modules/api_keys/index.md +1 -1
  8. package/dist/agentic/guides/modules/attachments/index.md +1 -1
  9. package/dist/agentic/guides/modules/audit_logs/index.md +1 -1
  10. package/dist/agentic/guides/modules/auth/index.md +1 -1
  11. package/dist/agentic/guides/modules/availability/index.md +1 -1
  12. package/dist/agentic/guides/modules/business_rules/index.md +1 -1
  13. package/dist/agentic/guides/modules/carrier_inpost/index.md +1 -1
  14. package/dist/agentic/guides/modules/cart/index.md +1 -1
  15. package/dist/agentic/guides/modules/catalog/index.md +1 -1
  16. package/dist/agentic/guides/modules/channel_apns/index.md +1 -1
  17. package/dist/agentic/guides/modules/channel_discord/index.md +1 -1
  18. package/dist/agentic/guides/modules/channel_expo/index.md +1 -1
  19. package/dist/agentic/guides/modules/channel_fcm/index.md +1 -1
  20. package/dist/agentic/guides/modules/channel_gmail/index.md +1 -1
  21. package/dist/agentic/guides/modules/channel_imap/index.md +1 -1
  22. package/dist/agentic/guides/modules/channel_resend/index.md +1 -1
  23. package/dist/agentic/guides/modules/channel_ses/index.md +1 -1
  24. package/dist/agentic/guides/modules/channel_smtp/index.md +1 -1
  25. package/dist/agentic/guides/modules/checkout/index.md +1 -1
  26. package/dist/agentic/guides/modules/communication_channels/index.md +1 -1
  27. package/dist/agentic/guides/modules/configs/index.md +1 -1
  28. package/dist/agentic/guides/modules/content/index.md +1 -1
  29. package/dist/agentic/guides/modules/currencies/index.md +1 -1
  30. package/dist/agentic/guides/modules/customer_accounts/index.md +1 -1
  31. package/dist/agentic/guides/modules/customer_groups/index.md +1 -1
  32. package/dist/agentic/guides/modules/customers/index.md +1 -1
  33. package/dist/agentic/guides/modules/dashboards/index.md +1 -1
  34. package/dist/agentic/guides/modules/data_sync/index.md +1 -1
  35. package/dist/agentic/guides/modules/design_system/index.md +1 -1
  36. package/dist/agentic/guides/modules/devices/index.md +1 -1
  37. package/dist/agentic/guides/modules/dictionaries/index.md +1 -1
  38. package/dist/agentic/guides/modules/directory/index.md +1 -1
  39. package/dist/agentic/guides/modules/documents/index.md +1 -1
  40. package/dist/agentic/guides/modules/ecommerce/index.md +1 -1
  41. package/dist/agentic/guides/modules/entities/index.md +1 -1
  42. package/dist/agentic/guides/modules/eudr/index.md +1 -1
  43. package/dist/agentic/guides/modules/events/index.md +1 -1
  44. package/dist/agentic/guides/modules/feature_toggles/index.md +1 -1
  45. package/dist/agentic/guides/modules/forms/index.md +1 -1
  46. package/dist/agentic/guides/modules/gateway_autopay/index.md +1 -1
  47. package/dist/agentic/guides/modules/gateway_stripe/index.md +1 -1
  48. package/dist/agentic/guides/modules/gateway_tpay/index.md +1 -1
  49. package/dist/agentic/guides/modules/generators/index.md +1 -1
  50. package/dist/agentic/guides/modules/inbox_ops/index.md +1 -1
  51. package/dist/agentic/guides/modules/integrations/index.md +1 -1
  52. package/dist/agentic/guides/modules/messages/index.md +1 -1
  53. package/dist/agentic/guides/modules/notifications/index.md +1 -1
  54. package/dist/agentic/guides/modules/onboarding/index.md +1 -1
  55. package/dist/agentic/guides/modules/payment_gateways/index.md +1 -1
  56. package/dist/agentic/guides/modules/perspectives/index.md +1 -1
  57. package/dist/agentic/guides/modules/phone_calls/index.md +1 -1
  58. package/dist/agentic/guides/modules/planner/index.md +1 -1
  59. package/dist/agentic/guides/modules/portal/index.md +1 -1
  60. package/dist/agentic/guides/modules/progress/index.md +1 -1
  61. package/dist/agentic/guides/modules/promotions/index.md +1 -1
  62. package/dist/agentic/guides/modules/push_notifications/index.md +1 -1
  63. package/dist/agentic/guides/modules/query_index/index.md +1 -1
  64. package/dist/agentic/guides/modules/record_locks/index.md +1 -1
  65. package/dist/agentic/guides/modules/resources/index.md +1 -1
  66. package/dist/agentic/guides/modules/sales/index.md +1 -1
  67. package/dist/agentic/guides/modules/scheduler/index.md +1 -1
  68. package/dist/agentic/guides/modules/search/index.md +1 -1
  69. package/dist/agentic/guides/modules/security/index.md +1 -1
  70. package/dist/agentic/guides/modules/seeds/index.md +1 -1
  71. package/dist/agentic/guides/modules/shipping_carriers/index.md +1 -1
  72. package/dist/agentic/guides/modules/sso/index.md +1 -1
  73. package/dist/agentic/guides/modules/staff/index.md +1 -1
  74. package/dist/agentic/guides/modules/storage_s3/index.md +1 -1
  75. package/dist/agentic/guides/modules/sync_akeneo/index.md +1 -1
  76. package/dist/agentic/guides/modules/sync_excel/index.md +1 -1
  77. package/dist/agentic/guides/modules/system_status_overlays/index.md +1 -1
  78. package/dist/agentic/guides/modules/telemetry/index.md +1 -1
  79. package/dist/agentic/guides/modules/tillio/index.md +1 -1
  80. package/dist/agentic/guides/modules/translations/index.md +1 -1
  81. package/dist/agentic/guides/modules/warranty_claims/index.md +1 -1
  82. package/dist/agentic/guides/modules/webhooks/index.md +1 -1
  83. package/dist/agentic/guides/modules/wms/index.md +1 -1
  84. package/dist/agentic/guides/modules/workflows/index.md +1 -1
  85. package/dist/agentic/guides/reference-module-facts.json +1 -1
  86. package/dist/agentic/guides/upstream/manifest.json +1 -1
  87. package/dist/lib/__integration__/TC-INT-007.spec.js +17 -0
  88. package/dist/lib/__integration__/TC-INT-007.spec.js.map +2 -2
  89. package/dist/lib/module-install.js +46 -8
  90. package/dist/lib/module-install.js.map +2 -2
  91. package/dist/lib/module-search-args.js +97 -0
  92. package/dist/lib/module-search-args.js.map +7 -0
  93. package/dist/lib/module-search-index.js +677 -0
  94. package/dist/lib/module-search-index.js.map +7 -0
  95. package/dist/lib/module-search.js +668 -0
  96. package/dist/lib/module-search.js.map +7 -0
  97. package/dist/lib/modules-config.js +105 -27
  98. package/dist/lib/modules-config.js.map +2 -2
  99. package/dist/lib/resolver.js +21 -1
  100. package/dist/lib/resolver.js.map +2 -2
  101. package/dist/mercato.js +32 -15
  102. package/dist/mercato.js.map +2 -2
  103. package/package.json +8 -7
  104. package/src/__tests__/mercato.test.ts +57 -0
  105. package/src/lib/__fixtures__/module-search/README.md +97 -0
  106. package/src/lib/__fixtures__/module-search/built-in.json +235 -0
  107. package/src/lib/__fixtures__/module-search/catalog-parity.json +4076 -0
  108. package/src/lib/__fixtures__/module-search/modules-index.json +1980 -0
  109. package/src/lib/__integration__/TC-INT-007.spec.ts +22 -0
  110. package/src/lib/__tests__/module-install.test.ts +220 -14
  111. package/src/lib/__tests__/module-search.test.ts +929 -0
  112. package/src/lib/__tests__/modules-config.test.ts +273 -1
  113. package/src/lib/__tests__/resolver.enterprise.test.ts +60 -0
  114. package/src/lib/module-install.ts +54 -10
  115. package/src/lib/module-search-args.ts +116 -0
  116. package/src/lib/module-search-index.ts +1033 -0
  117. package/src/lib/module-search.ts +952 -0
  118. package/src/lib/modules-config.ts +153 -36
  119. package/src/lib/resolver.ts +23 -1
  120. package/src/mercato.ts +36 -11
@@ -0,0 +1,1033 @@
1
+ // Ranking and lookups behind `mercato module search|info`, kept identical to the Open Mercato Modules catalog
2
+ // (https://modules.openmercato.com, `lib/core/search.ts` and `lib/core/refs.ts`): same MiniSearch options, tokenizer,
3
+ // stop words, boosts and built-in rules, so the CLI, the catalog site and its MCP server rank the same way.
4
+ // `__tests__/module-search.test.ts` holds this file to the catalog's own output on a fixture built from real data.
5
+ import MiniSearch, { type Options, type SearchResult } from 'minisearch'
6
+ import { satisfies } from 'semver'
7
+
8
+ export type CellStatus = string
9
+ export type OriginType = 'official' | 'community' | '3rd-party'
10
+ export type EntryKind = 'module' | 'provider' | 'library' | 'tool'
11
+ export type LicenseKind = 'osi' | 'proprietary' | 'enterprise' | 'unknown'
12
+ export type ReceiptSource = 'ci' | 'preview'
13
+
14
+ export type AgentPolicy = {
15
+ decision: 'allow' | 'ask' | 'refuse'
16
+ reasons: { code: string; text: string }[]
17
+ until?: string
18
+ consentText?: string
19
+ }
20
+
21
+ export type CatalogLine = {
22
+ key: string
23
+ version: string
24
+ source: 'latest' | 'previous' | 'develop'
25
+ }
26
+
27
+ export type AnatomyLists = {
28
+ aclFeatures?: string[]
29
+ eventsEmitted?: string[]
30
+ eventsConsumed?: string[]
31
+ env?: string[]
32
+ hosts?: string[]
33
+ tables?: string[]
34
+ publicRoutes?: string[]
35
+ credentials?: { key: string; type?: string; required?: boolean }[]
36
+ }
37
+
38
+ export type AnatomySummary = {
39
+ version: string
40
+ counts?: Record<string, number | null>
41
+ lists?: AnatomyLists
42
+ callout?: string | null
43
+ }
44
+
45
+ export type CellSummary = { status: CellStatus; at: string | null; moduleVersion?: string | null }
46
+
47
+ export type BuiltFor = { range: string | null; kind: string; lines: string[]; ranges?: Record<string, string> }
48
+
49
+ export type CatalogEntry = {
50
+ locator: string
51
+ path: string
52
+ npm: string | null
53
+ title: string
54
+ summary: string
55
+ whenToUse: string
56
+ type: OriginType
57
+ kind: EntryKind
58
+ category: string
59
+ tags: string[]
60
+ providers: { name: string; label: string }[]
61
+ moduleIds: string[]
62
+ /** What the package needs; an adapter's catalog libraries among them join its `yarn add` (`peerLibrarySpecs`). */
63
+ requires?: { raw: string; resolvesTo?: string | null }[]
64
+ renamedFrom: string[]
65
+ status: string
66
+ listed: boolean
67
+ featured: boolean
68
+ license: { spdx: string | null; kind: LicenseKind; mismatch?: boolean }
69
+ version: {
70
+ latest: string | null
71
+ preview: string | null
72
+ installableFrom: string | null
73
+ gitRef: string | null
74
+ recommended: Record<string, string | null>
75
+ }
76
+ compat: {
77
+ lines: Record<string, CellSummary>
78
+ verifiedOn: string[]
79
+ builtFor?: BuiltFor
80
+ inPresets?: string[]
81
+ inEmptyPreset?: string[]
82
+ ships?: Record<string, string>
83
+ isolation?: Record<string, { status: CellStatus; moduleVersion: string | null }>
84
+ }
85
+ anatomy: AnatomySummary | null
86
+ signals?: {
87
+ supplyChain?: { status: string; reasons: string[] }
88
+ hygiene?: { status: string; failing: string[] }
89
+ anatomy?: string
90
+ }
91
+ tier: 'listed' | 'verified' | null
92
+ quality: unknown
93
+ agentPolicy: Record<string, AgentPolicy>
94
+ install: { cli: string; cmm?: string; needsAllowThirdParty?: boolean; moduleFlag: string | null }
95
+ links: { page: string; md: string; json?: string; npm?: string | null; repo?: string | null }
96
+ _meta?: Record<string, unknown>
97
+ }
98
+
99
+ export type CatalogIndex = {
100
+ schemaVersion: 1
101
+ generatedAt: string
102
+ dataVersion: string
103
+ site: string
104
+ lines: CatalogLine[]
105
+ entries: CatalogEntry[]
106
+ dataAsOf?: { source?: ReceiptSource | null }
107
+ builtIn?: { coreVersion: string; count: number; href: string }
108
+ }
109
+
110
+ export type BuiltInModule = {
111
+ id: string
112
+ title: string
113
+ description: string
114
+ category: string
115
+ requires?: string[]
116
+ inPresets?: string[]
117
+ inEmptyPreset?: string[]
118
+ anatomy: AnatomySummary | null
119
+ install: string
120
+ page: string
121
+ }
122
+
123
+ export type BuiltInIndex = {
124
+ schemaVersion: 1
125
+ coreVersion: string
126
+ generatedAt: string
127
+ modules: BuiltInModule[]
128
+ }
129
+
130
+ export type ModuleCard = {
131
+ locator: string
132
+ path: string
133
+ title: string
134
+ summary: string
135
+ whenToUse: string
136
+ type: OriginType
137
+ kind: EntryKind
138
+ category: string
139
+ license: { spdx: string | null; kind: LicenseKind }
140
+ tier: 'listed' | 'verified' | null
141
+ omQuality: boolean
142
+ verifiedOn: string[]
143
+ line: string | null
144
+ status: CellStatus | null
145
+ agentPolicy: AgentPolicy | null
146
+ installableFrom: string | null
147
+ install: string
148
+ matchedOn: string[]
149
+ card: string
150
+ presetNote?: string
151
+ installEmptyPreset?: string | null
152
+ }
153
+
154
+ export type BuiltInCard = {
155
+ id: string
156
+ title: string
157
+ description: string
158
+ category: string
159
+ enabled: boolean | null
160
+ install: string
161
+ page: string
162
+ matchedOn: string[]
163
+ presetNote: string | null
164
+ }
165
+
166
+ export type SearchModulesInput = {
167
+ query?: string
168
+ omVersion?: string
169
+ category?: string
170
+ type?: OriginType[]
171
+ kind?: (EntryKind | 'built-in')[]
172
+ verifiedOnly?: boolean
173
+ verifiedModulesOnly?: boolean
174
+ includeBuiltIn?: boolean
175
+ includeExamples?: boolean
176
+ emits?: string
177
+ consumes?: string
178
+ provider?: string
179
+ limit?: number
180
+ }
181
+
182
+ export type SearchModulesOutput = {
183
+ results: ModuleCard[]
184
+ builtIn: BuiltInCard[]
185
+ total: number
186
+ line: string | null
187
+ dataVersion: string
188
+ generatedAt: string
189
+ receiptSource?: ReceiptSource | null
190
+ didYouMean?: string
191
+ }
192
+
193
+ export const SEARCH_BOOST = {
194
+ title: 3,
195
+ npm: 3,
196
+ summary: 2,
197
+ whenToUse: 2,
198
+ providers: 2,
199
+ tags: 1.5,
200
+ aliases: 1.5,
201
+ renamedFrom: 1,
202
+ category: 1,
203
+ anatomy: 1,
204
+ } as const
205
+ type SearchField = keyof typeof SEARCH_BOOST
206
+ const SEARCH_FIELDS = Object.keys(SEARCH_BOOST) as SearchField[]
207
+
208
+ export const ALIASES_META_KEY = 'com.openmercato.modules/aliases'
209
+ export const INSTALLABLE_META_KEY = 'com.openmercato.modules/installable'
210
+ export const BUILTIN_MAX = 5
211
+ export const BUILTIN_RATIO = 0.5
212
+ export const BOOST_VERIFIED = 0.15
213
+ export const BOOST_OFFICIAL = 0.1
214
+ export const MIN_AND_RESULTS = 3
215
+ /** An OR hit that matched no query word as typed and scores below this share of the best hit is dropped. */
216
+ export const WEAK_HIT_RATIO = 0.2
217
+ export const SEARCH_MAX_LIMIT = 20
218
+ export const SEARCH_DEFAULTS = { verifiedOnly: false, includeBuiltIn: true, includeExamples: false, limit: 10 } as const
219
+ export const CORE_PACKAGE = '@open-mercato/core'
220
+ export const ENTERPRISE_PACKAGE = '@open-mercato/enterprise'
221
+ export const ENTERPRISE_ENABLE_STEP = 'echo OM_ENABLE_ENTERPRISE_MODULES=true >> .env'
222
+ export const PREVIEW_LINE =
223
+ "Receipts: Preview run in Docker on the maintainer's machine, not CI. The first nightly CI run replaces it."
224
+ const VERDICT_STATES: ReadonlySet<CellStatus> = new Set(['verified', 'broken', 'harness-red', 'infra-error'])
225
+
226
+ const STOPWORDS = new Set([
227
+ 'a', 'an', 'and', 'are', 'as', 'at', 'be', 'by', 'for', 'from', 'i', 'in', 'into', 'is', 'it', 'its', 'me',
228
+ 'module', 'modules', 'my', 'of', 'on', 'or', 'our', 'that', 'the', 'this', 'to', 'via', 'we', 'with', 'you', 'your',
229
+ 'can', 'do', 'does', 'how', 'need', 'needs', 'use', 'used', 'uses', 'want', 'wants', 'what', 'when', 'which',
230
+ ])
231
+
232
+ export function tokenize(text: string): string[] {
233
+ const lower = text.toLowerCase()
234
+ const tokens = lower.split(/[^a-z0-9*]+/).filter((token) => token !== '')
235
+ for (const match of lower.matchAll(/[a-z0-9]+(?:[._-][a-z0-9*]+)+/g)) tokens.push(match[0])
236
+ return tokens
237
+ }
238
+
239
+ export function processTerm(term: string): string | null {
240
+ return term.length < 2 || STOPWORDS.has(term) ? null : term
241
+ }
242
+
243
+ export type SearchDoc = {
244
+ id: string
245
+ group: 'module' | 'builtin'
246
+ title: string
247
+ npm: string
248
+ summary: string
249
+ whenToUse: string
250
+ providers: string
251
+ tags: string
252
+ aliases: string
253
+ renamedFrom: string
254
+ category: string
255
+ anatomy: string
256
+ }
257
+
258
+ const SEARCH_OPTIONS: Options<SearchDoc> = {
259
+ idField: 'id',
260
+ fields: SEARCH_FIELDS,
261
+ storeFields: ['group'],
262
+ tokenize,
263
+ processTerm,
264
+ searchOptions: { prefix: true, fuzzy: 0.2, boost: { ...SEARCH_BOOST } },
265
+ }
266
+
267
+ export type AnatomyIds = {
268
+ event: string[]
269
+ emits: string[]
270
+ consumes: string[]
271
+ entity: string[]
272
+ permission: string[]
273
+ env: string[]
274
+ host: string[]
275
+ setting: string[]
276
+ module: string[]
277
+ }
278
+
279
+ export type ModuleMeta = {
280
+ entry: CatalogEntry
281
+ example: boolean
282
+ omQuality: boolean
283
+ ids: AnatomyIds
284
+ }
285
+
286
+ export type BuiltInMeta = {
287
+ module: BuiltInModule
288
+ ids: AnatomyIds
289
+ }
290
+
291
+ export type CatalogSearcher = {
292
+ miniSearch: MiniSearch<SearchDoc>
293
+ index: CatalogIndex
294
+ builtIn: BuiltInIndex | null
295
+ site: string
296
+ modules: Map<string, ModuleMeta>
297
+ builtInModules: Map<string, BuiltInMeta>
298
+ }
299
+
300
+ function anatomyIds(anatomy: AnatomySummary | null | undefined, moduleIds: readonly string[]): AnatomyIds {
301
+ const lists = anatomy?.lists
302
+ return {
303
+ event: [...new Set([...(lists?.eventsEmitted ?? []), ...(lists?.eventsConsumed ?? [])])],
304
+ emits: [...(lists?.eventsEmitted ?? [])],
305
+ consumes: [...(lists?.eventsConsumed ?? [])],
306
+ entity: lists?.tables ?? [],
307
+ permission: lists?.aclFeatures ?? [],
308
+ env: lists?.env ?? [],
309
+ host: lists?.hosts ?? [],
310
+ setting: (lists?.credentials ?? []).map((credential) => credential.key),
311
+ module: [...moduleIds],
312
+ }
313
+ }
314
+
315
+ const anatomyText = (ids: AnatomyIds) =>
316
+ [...ids.module, ...ids.entity, ...ids.event, ...ids.permission, ...ids.setting, ...ids.env, ...ids.host].join(' ')
317
+
318
+ function aliasesOf(entry: CatalogEntry): string[] {
319
+ const value = entry._meta?.[ALIASES_META_KEY]
320
+ return Array.isArray(value) ? value.filter((item): item is string => typeof item === 'string') : []
321
+ }
322
+
323
+ function moduleDoc(entry: CatalogEntry, ids: AnatomyIds): SearchDoc {
324
+ return {
325
+ id: entry.locator,
326
+ group: 'module',
327
+ title: entry.title,
328
+ npm: [entry.npm ?? entry.locator.replace(/^github:/, ''), entry.path].join(' '),
329
+ summary: entry.summary,
330
+ whenToUse: entry.whenToUse,
331
+ providers: entry.providers.map((provider) => `${provider.name} ${provider.label}`).join(' '),
332
+ tags: entry.tags.join(' '),
333
+ aliases: aliasesOf(entry).join(' '),
334
+ renamedFrom: entry.renamedFrom.map((locator) => locator.replace(/^(npm|github):/, '')).join(' '),
335
+ category: entry.category,
336
+ anatomy: anatomyText(ids),
337
+ }
338
+ }
339
+
340
+ function builtInDoc(coreModule: BuiltInModule, ids: AnatomyIds): SearchDoc {
341
+ return {
342
+ id: `core:${coreModule.id}`,
343
+ group: 'builtin',
344
+ title: coreModule.title,
345
+ npm: coreModule.id,
346
+ summary: coreModule.description,
347
+ whenToUse: '',
348
+ providers: '',
349
+ tags: '',
350
+ aliases: '',
351
+ renamedFrom: '',
352
+ category: coreModule.category,
353
+ anatomy: anatomyText(ids),
354
+ }
355
+ }
356
+
357
+ export function createCatalogSearcher(index: CatalogIndex, builtIn: BuiltInIndex | null): CatalogSearcher {
358
+ const miniSearch = new MiniSearch<SearchDoc>(SEARCH_OPTIONS)
359
+ const modules = new Map<string, ModuleMeta>()
360
+ const builtInModules = new Map<string, BuiltInMeta>()
361
+ const docs: SearchDoc[] = []
362
+ for (const entry of index.entries.filter((candidate) => candidate.listed)) {
363
+ const ids = anatomyIds(entry.anatomy, entry.moduleIds)
364
+ modules.set(entry.locator, {
365
+ entry,
366
+ ids,
367
+ example: entry.tags.includes('example'),
368
+ omQuality: entry.quality !== null && entry.quality !== undefined,
369
+ })
370
+ docs.push(moduleDoc(entry, ids))
371
+ }
372
+ for (const coreModule of builtIn?.modules ?? []) {
373
+ const ids = anatomyIds(coreModule.anatomy, [coreModule.id])
374
+ builtInModules.set(coreModule.id, { module: coreModule, ids })
375
+ docs.push(builtInDoc(coreModule, ids))
376
+ }
377
+ miniSearch.addAll(docs)
378
+ const loaded = MiniSearch.loadJS<SearchDoc>(miniSearch.toJSON(), SEARCH_OPTIONS)
379
+ return { miniSearch: loaded, index, builtIn, site: index.site.replace(/\/+$/, ''), modules, builtInModules }
380
+ }
381
+
382
+ const absolute = (site: string, page: string) => (/^https?:\/\//.test(page) ? page : `${site}${page}`)
383
+
384
+ export function latestLine(lines: readonly CatalogLine[]): CatalogLine | null {
385
+ return lines.find((line) => line.source === 'latest') ?? null
386
+ }
387
+
388
+ const SEMVER = /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/
389
+
390
+ export function resolveLine(
391
+ omVersion: string | null | undefined,
392
+ lines: readonly CatalogLine[],
393
+ ): { line: string | null; version: string | null; note: string | null } {
394
+ const found = (line: CatalogLine | null) =>
395
+ line ? { line: line.key, version: line.version, note: null } : { line: null, version: null, note: null }
396
+ const raw = (omVersion ?? '').trim()
397
+ if (raw === '') return found(latestLine(lines))
398
+ const byKey = lines.find((line) => line.key === raw)
399
+ if (byKey) return found(byKey)
400
+ const version = raw.replace(/^(?:v|=|\^|~|>=)\s*/, '')
401
+ const exact = lines.find((line) => line.version === version)
402
+ if (exact) return found(exact)
403
+ const semver = SEMVER.exec(version)
404
+ if (semver && semver[4] && /(^|[.-])develop([.-]|$)/.test(semver[4])) {
405
+ const next = lines.find((line) => line.source === 'develop')
406
+ if (next) return found(next)
407
+ }
408
+ const majorMinor = /^(\d+)\.(\d+)(?:\.\d+)?(?:-[0-9A-Za-z.-]+)?$/.exec(version)
409
+ if (!majorMinor) return { line: null, version: null, note: 'Unknown Open Mercato version.' }
410
+ const key = `${Number(majorMinor[1])}.${Number(majorMinor[2])}`
411
+ const line = lines.find((candidate) => candidate.key === key)
412
+ if (line) return found(line)
413
+ return { line: null, version: null, note: `Line ${key} is not tested by the catalog.` }
414
+ }
415
+
416
+ function matchedOn(
417
+ match: SearchResult['match'],
418
+ meta: { providers?: readonly { name: string; label: string }[]; tags?: readonly string[]; ids: AnatomyIds; category?: string },
419
+ queryTerms: readonly string[] = [],
420
+ ): string[] {
421
+ const chips: string[] = []
422
+ const add = (chip: string) => {
423
+ if (!chips.includes(chip)) chips.push(chip)
424
+ }
425
+ const has = (id: string, term: string) => tokenize(id).includes(term)
426
+ const order: SearchField[] = ['title', 'npm', 'aliases', 'renamedFrom', 'providers', 'anatomy', 'summary', 'whenToUse', 'tags', 'category']
427
+ const typed = new Set(queryTerms)
428
+ const fieldsByTerm = Object.entries(match).sort(
429
+ (left, right) => Number(typed.has(right[0])) - Number(typed.has(left[0])) || right[0].length - left[0].length,
430
+ )
431
+ for (const field of order) {
432
+ for (const [term, fields] of fieldsByTerm) {
433
+ if (!fields.includes(field)) continue
434
+ if (field === 'title' || field === 'npm' || field === 'aliases' || field === 'renamedFrom') add('name')
435
+ else if (field === 'summary' || field === 'whenToUse') add('summary')
436
+ else if (field === 'tags') {
437
+ const tag = meta.tags?.find((candidate) => has(candidate, term))
438
+ add(tag ? `tag ${tag}` : 'summary')
439
+ } else if (field === 'category' && meta.category) add(`category ${meta.category}`)
440
+ else if (field === 'providers') {
441
+ const provider = meta.providers?.find((candidate) => has(candidate.name, term) || has(candidate.label, term))
442
+ add(provider ? `provider ${provider.label}` : 'provider')
443
+ } else if (field === 'anatomy') anatomyChips(meta.ids, fieldsByTerm, has).forEach(add)
444
+ }
445
+ }
446
+ return chips.slice(0, 5)
447
+ }
448
+
449
+ function anatomyChips(
450
+ ids: AnatomyIds,
451
+ fieldsByTerm: readonly (readonly [string, readonly string[]])[],
452
+ has: (id: string, term: string) => boolean,
453
+ ): string[] {
454
+ const kinds: (keyof AnatomyIds)[] = ['event', 'entity', 'permission', 'env', 'setting', 'host', 'module']
455
+ const terms = fieldsByTerm.filter(([, fields]) => fields.includes('anatomy')).map(([term]) => term)
456
+ const left = new Set(terms)
457
+ const chips: string[] = []
458
+ while (left.size > 0) {
459
+ let best: { chip: string; covers: string[]; exact: boolean; first: number } | null = null
460
+ for (const kind of kinds)
461
+ for (const id of ids[kind]) {
462
+ const covers = terms.filter((term) => left.has(term) && (id === term || has(id, term)))
463
+ if (covers.length === 0) continue
464
+ const exact = covers.includes(id)
465
+ const first = terms.indexOf(covers[0] as string)
466
+ const better =
467
+ !best ||
468
+ covers.length > best.covers.length ||
469
+ (covers.length === best.covers.length && (exact && !best.exact ? true : exact === best.exact && first < best.first))
470
+ if (better) best = { chip: `${kind} ${id}`, covers, exact, first }
471
+ }
472
+ if (!best) break
473
+ chips.push(best.chip)
474
+ for (const term of best.covers) left.delete(term)
475
+ }
476
+ return chips
477
+ }
478
+
479
+ const STABLE_VERSION = /^\d+\.\d+\.\d+$/
480
+
481
+ function satisfiesRange(version: string, range: string): boolean {
482
+ try {
483
+ return satisfies(version, range, { includePrerelease: true })
484
+ } catch {
485
+ return false
486
+ }
487
+ }
488
+
489
+ export function lineVersion(entry: CatalogEntry, line: string | null): string | null {
490
+ return (line !== null ? entry.compat.ships?.[line] : undefined) ?? installVersion(entry, line)
491
+ }
492
+
493
+ /** A cell whose receipt judged another version than the one a fresh app gets on the line is no verdict on that line. */
494
+ function judgedCell(entry: CatalogEntry, line: string): CellSummary | null {
495
+ const cell = entry.compat.lines[line] ?? null
496
+ if (!cell || cell.moduleVersion === null || cell.moduleVersion === undefined || !VERDICT_STATES.has(cell.status)) return cell
497
+ const installs = lineVersion(entry, line)
498
+ return installs === null || cell.moduleVersion === installs ? cell : null
499
+ }
500
+
501
+ export function statusOn(entry: CatalogEntry, line: string): CellStatus {
502
+ if (entry.version.recommended[line]) return 'verified'
503
+ return judgedCell(entry, line)?.status ?? 'untested'
504
+ }
505
+
506
+ function installableOn(entry: CatalogEntry, line: string | null): string | null | undefined {
507
+ if (line === null) return undefined
508
+ const map = entry._meta?.[INSTALLABLE_META_KEY]
509
+ if (!map || typeof map !== 'object') return undefined
510
+ const value = (map as Record<string, unknown>)[line]
511
+ return typeof value === 'string' ? value : value === null ? null : undefined
512
+ }
513
+
514
+ export function installVersion(entry: CatalogEntry, line: string | null): string | null {
515
+ return (
516
+ (line !== null ? entry.version.recommended[line] : null) ??
517
+ installableOn(entry, line) ??
518
+ entry.version.latest ??
519
+ entry.version.preview ??
520
+ null
521
+ )
522
+ }
523
+
524
+ function declaredRangeOf(entry: CatalogEntry, version: string): string | null {
525
+ const builtFor = entry.compat.builtFor
526
+ if (!builtFor || builtFor.kind === 'missing' || builtFor.kind === 'star') return null
527
+ if (builtFor.ranges) {
528
+ for (const [line, range] of Object.entries(builtFor.ranges)) if (lineVersion(entry, line) === version) return range
529
+ return null
530
+ }
531
+ const lines = new Set([...Object.keys(entry.compat.lines), ...Object.keys(entry.compat.ships ?? {})])
532
+ return [...lines].some((line) => lineVersion(entry, line) === version) ? builtFor.range : null
533
+ }
534
+
535
+ /**
536
+ * The version an app from the empty preset installs: the one a new app ships where the install version broke in
537
+ * isolation there, or where its declared peers reject the version that line ships.
538
+ */
539
+ export function emptyPresetVersion(entry: CatalogEntry, line: string | null): string | null {
540
+ const version = installVersion(entry, line)
541
+ if (line === null || !version) return version
542
+ const ships = entry.compat.ships?.[line]
543
+ if (!ships || ships === version) return version
544
+ const isolation = entry.compat.isolation?.[line]
545
+ if (isolation?.moduleVersion === version) return isolation.status === 'broken' ? ships : version
546
+ const range = declaredRangeOf(entry, version)
547
+ return STABLE_VERSION.test(ships) && range !== null && !satisfiesRange(ships, range) ? ships : version
548
+ }
549
+
550
+ export function builtInEnableCommand(id: string): string {
551
+ return `yarn mercato module enable ${CORE_PACKAGE} --module ${id}`
552
+ }
553
+
554
+ /** A provider without a module of its own: an adapter `yarn add` adds and `yarn generate` registers. */
555
+ export const isAdapter = (entry: Pick<CatalogEntry, 'kind' | 'moduleIds'>): boolean =>
556
+ entry.kind === 'provider' && entry.moduleIds.length === 0
557
+
558
+ /** Finds a catalog entry by locator (`npm:<name>`). */
559
+ export type PeerLookup = (locator: string) => CatalogEntry | null | undefined
560
+
561
+ /**
562
+ * The catalog libraries an adapter peers on, as `name@version` for its `yarn add` (catalog `peerLibrarySpecs`). An
563
+ * @open-mercato peer of an @open-mercato adapter comes from the same release and takes the adapter's version; any
564
+ * other peer takes its own install version on the line. Empty for every other kind.
565
+ */
566
+ export function peerLibrarySpecs(
567
+ entry: CatalogEntry,
568
+ version: string | null,
569
+ line: string | null,
570
+ find: PeerLookup | undefined,
571
+ ): string[] {
572
+ if (!find || !entry.npm || !isAdapter(entry)) return []
573
+ const specs: string[] = []
574
+ for (const requirement of entry.requires ?? []) {
575
+ const peer = requirement.resolvesTo?.startsWith('npm:') ? find(requirement.resolvesTo) : null
576
+ if (!peer?.npm || peer.kind !== 'library' || peer.npm === entry.npm) continue
577
+ const sameRelease = Boolean(version) && peer.npm.startsWith('@open-mercato/') && entry.npm.startsWith('@open-mercato/')
578
+ const peerVersion = sameRelease ? version : installVersion(peer, line)
579
+ const spec = peerVersion ? `${peer.npm}@${peerVersion}` : peer.npm
580
+ if (!specs.includes(spec)) specs.push(spec)
581
+ }
582
+ return specs
583
+ }
584
+
585
+ function packageCommand(entry: CatalogEntry, spec: string, peers: readonly string[] = []): string | null {
586
+ if (entry.kind === 'tool') return entry.tags.includes('cli') ? `npx ${spec}` : `yarn add ${spec}`
587
+ if (isAdapter(entry)) return `yarn add ${[...peers, spec].join(' ')}`
588
+ return entry.kind === 'library' ? `yarn add ${spec}` : null
589
+ }
590
+
591
+ function inPreset(entry: CatalogEntry, enabled: readonly { id: string; from: string }[] | null): boolean {
592
+ if (!enabled || !entry.npm || entry.moduleIds.length === 0) return false
593
+ return entry.moduleIds.every((id) => enabled.some((item) => item.id === id && item.from === entry.npm))
594
+ }
595
+
596
+ function installCli(
597
+ entry: CatalogEntry,
598
+ line: string | null,
599
+ preset: readonly { id: string; from: string }[] | null,
600
+ version: string | null = installVersion(entry, line),
601
+ find?: PeerLookup,
602
+ ): string {
603
+ if (entry.npm === null) {
604
+ const repo = entry.locator.replace(/^github:/, '')
605
+ const ref = entry.version.gitRef ? ` --ref ${entry.version.gitRef}` : ''
606
+ return `npx create-mercato-module install ${repo}${ref}`
607
+ }
608
+ const spec = version ? `${entry.npm}@${version}` : entry.npm
609
+ const own = packageCommand(entry, spec, peerLibrarySpecs(entry, version, line, find))
610
+ if (own) return own
611
+ if (inPreset(entry, preset)) return `yarn add ${spec}`
612
+ const moduleFlag = entry.install.moduleFlag ?? null
613
+ if (entry.npm === ENTERPRISE_PACKAGE && !moduleFlag) return `${ENTERPRISE_ENABLE_STEP} && yarn generate`
614
+ const thirdParty = entry.npm.startsWith('@open-mercato/') ? '' : ' --allow-third-party'
615
+ if (!moduleFlag && entry.moduleIds.length > 1) {
616
+ return entry.moduleIds.map((id) => `yarn mercato module add ${spec}${thirdParty} --module ${id}`).join(' && ')
617
+ }
618
+ return `yarn mercato module add ${spec}${thirdParty}${moduleFlag ? ` --module ${moduleFlag}` : ''}`
619
+ }
620
+
621
+ /** The command of an app that does not register the package yet (an app from the empty preset) on a line. */
622
+ export function installCommand(
623
+ entry: CatalogEntry,
624
+ line: string | null,
625
+ latest: string | null,
626
+ find?: PeerLookup,
627
+ ): string {
628
+ if (line === null || line === latest) return entry.install.cli
629
+ const both = entry.npm !== null && (entry.compat.inEmptyPreset ?? []).includes(line)
630
+ const version = (entry.compat.inPresets ?? []).includes(line)
631
+ ? emptyPresetVersion(entry, line)
632
+ : installVersion(entry, line)
633
+ const npm = entry.npm
634
+ return installCli(entry, line, both && npm ? entry.moduleIds.map((id) => ({ id, from: npm })) : null, version, find)
635
+ }
636
+
637
+ function listAnd(items: readonly string[]): string {
638
+ return items.length <= 1 ? (items[0] ?? '') : `${items.slice(0, -1).join(', ')} and ${items[items.length - 1]}`
639
+ }
640
+
641
+ const EMPTY_PRESET_LEAD = 'In an app from the empty preset:'
642
+
643
+ function presetInstallText(moduleIds: readonly string[]): string {
644
+ return `Nothing to install: a new app already registers ${moduleIds.length ? listAnd(moduleIds) : 'it'} in src/modules.ts.`
645
+ }
646
+
647
+ export function newAppInstallText(moduleIds: readonly string[], emptyCommand: string | null): string {
648
+ return emptyCommand ? `${presetInstallText(moduleIds)} ${EMPTY_PRESET_LEAD} ${emptyCommand}` : presetInstallText(moduleIds)
649
+ }
650
+
651
+ /**
652
+ * Where a new app (classic preset) of the line already registers the package, `install` is that sentence, `presetNote`
653
+ * the whole install sentence and `installEmptyPreset` the command of an app from the empty preset (null when that
654
+ * preset registers it too). Elsewhere `install` is the command.
655
+ */
656
+ export function installFields(
657
+ entry: CatalogEntry,
658
+ line: string | null,
659
+ latest: string | null,
660
+ find?: PeerLookup,
661
+ ): Pick<ModuleCard, 'install' | 'presetNote' | 'installEmptyPreset'> {
662
+ const command = installCommand(entry, line, latest, find)
663
+ if (line === null || !(entry.compat.inPresets ?? []).includes(line)) return { install: command }
664
+ const empty = (entry.compat.inEmptyPreset ?? []).includes(line) ? null : command
665
+ return {
666
+ install: presetInstallText(entry.moduleIds),
667
+ presetNote: newAppInstallText(entry.moduleIds, empty),
668
+ installEmptyPreset: empty,
669
+ }
670
+ }
671
+
672
+ /** What a new app (classic preset) of the line has of a built-in module; null when a new app has it off. */
673
+ export function builtInPresetText(coreModule: BuiltInModule, line: string | null): string | null {
674
+ if (!line || !coreModule.inPresets?.includes(line)) return null
675
+ const on = `On in a new app on ${line}: nothing to enable.`
676
+ if (coreModule.inEmptyPreset?.includes(line)) return on
677
+ return `${on} ${EMPTY_PRESET_LEAD} ${coreModule.install || builtInEnableCommand(coreModule.id)}`
678
+ }
679
+
680
+ /** The `get_module` warnings of a built-in module. */
681
+ export function builtInNotes(coreModule: BuiltInModule, line: string | null): string[] {
682
+ const text = builtInPresetText(coreModule, line)
683
+ if (text) return [`Built into Open Mercato core as ${coreModule.id}.`, text]
684
+ return [`Built into Open Mercato core as ${coreModule.id}. Enable it: ${builtInEnableCommand(coreModule.id)}`]
685
+ }
686
+
687
+ /** Order without a query: OM Quality, Verified, Listed, then featured, receipt freshness on the line, title. */
688
+ function relevanceCompare(line: string | null) {
689
+ const level = (meta: ModuleMeta) =>
690
+ meta.omQuality ? 0 : meta.entry.tier === 'verified' ? 1 : meta.entry.tier === 'listed' ? 2 : 3
691
+ const fresh = (meta: ModuleMeta) => {
692
+ const at = line ? judgedCell(meta.entry, line)?.at : null
693
+ return at ? Date.parse(at) : 0
694
+ }
695
+ return (left: ModuleMeta, right: ModuleMeta) =>
696
+ level(left) - level(right) ||
697
+ Number(right.entry.featured) - Number(left.entry.featured) ||
698
+ fresh(right) - fresh(left) ||
699
+ left.entry.title.localeCompare(right.entry.title)
700
+ }
701
+
702
+ /** The query with one swap of two adjacent letters undone in one word (`stirpe` -> `stripe`); at most 60 variants. */
703
+ export function swapVariants(query: string): string[] {
704
+ const words = query.trim().toLowerCase().split(/\s+/).filter(Boolean)
705
+ if (words.length > 6) return []
706
+ const variants: string[] = []
707
+ words.forEach((word, wordIndex) => {
708
+ if (word.length < 3 || word.length > 24 || !/^[a-z0-9]+$/.test(word) || processTerm(word) === null) return
709
+ for (let index = 0; index < word.length - 1; index++) {
710
+ if (word[index] === word[index + 1]) continue
711
+ const swapped = `${word.slice(0, index)}${word[index + 1]}${word[index]}${word.slice(index + 2)}`
712
+ variants.push([...words.slice(0, wordIndex), swapped, ...words.slice(wordIndex + 1)].join(' '))
713
+ }
714
+ })
715
+ return [...new Set(variants)].slice(0, 60)
716
+ }
717
+
718
+ export type RankedModule = { meta: ModuleMeta; matchedOn: string[] }
719
+
720
+ export type RankedSearch = {
721
+ line: string | null
722
+ latest: string | null
723
+ modules: RankedModule[]
724
+ builtIn: BuiltInCard[]
725
+ didYouMean: string | null
726
+ }
727
+
728
+ type Hits = {
729
+ modules: { meta: ModuleMeta; result: SearchResult }[]
730
+ builtIns: { meta: BuiltInMeta; result: SearchResult }[]
731
+ }
732
+
733
+ /**
734
+ * `search_modules` ranking (tools@1): AND first, then OR with weak hits cut, then one swapped pair of letters. Without
735
+ * a query (blank, or only stop words next to a filter) the filters alone pick the modules, in relevance order.
736
+ */
737
+ export function rankModules(searcher: CatalogSearcher, rawInput: SearchModulesInput): RankedSearch {
738
+ const input = {
739
+ ...rawInput,
740
+ query: rawInput.query ?? '',
741
+ verifiedOnly: rawInput.verifiedOnly ?? SEARCH_DEFAULTS.verifiedOnly,
742
+ includeBuiltIn: rawInput.includeBuiltIn ?? SEARCH_DEFAULTS.includeBuiltIn,
743
+ includeExamples: rawInput.includeExamples ?? SEARCH_DEFAULTS.includeExamples,
744
+ }
745
+ const lines = searcher.index.lines
746
+ const latest = latestLine(lines)?.key ?? null
747
+ const line = input.omVersion ? resolveLine(input.omVersion, lines).line : latest
748
+ const boostDocument = (id: unknown) => {
749
+ const meta = searcher.modules.get(String(id))
750
+ if (!meta) return 1
751
+ const verified = line !== null && statusOn(meta.entry, line) === 'verified' ? 1 : 0
752
+ return 1 + BOOST_VERIFIED * verified + BOOST_OFFICIAL * (meta.entry.type === 'official' ? 1 : 0)
753
+ }
754
+ const wantKinds = input.kind
755
+ const provider = input.provider?.toLowerCase()
756
+ const providerMatches = (item: { name: string; label: string }) => item.name === provider || item.label.toLowerCase() === provider
757
+ const moduleOk = (meta: ModuleMeta) => {
758
+ const entry = meta.entry
759
+ return (
760
+ entry.listed &&
761
+ (input.includeExamples || !meta.example) &&
762
+ (!input.category || entry.category === input.category) &&
763
+ (!input.type || input.type.includes(entry.type)) &&
764
+ (!wantKinds || wantKinds.includes(entry.kind)) &&
765
+ (!input.verifiedOnly || (line !== null && statusOn(entry, line) === 'verified')) &&
766
+ (!input.verifiedModulesOnly || entry.kind !== 'module' || (line !== null && Boolean(entry.version.recommended[line]))) &&
767
+ (!input.emits || meta.ids.emits.includes(input.emits)) &&
768
+ (!input.consumes || meta.ids.consumes.includes(input.consumes)) &&
769
+ (!provider || entry.providers.some(providerMatches))
770
+ )
771
+ }
772
+ const builtInOk = (meta: BuiltInMeta) =>
773
+ input.includeBuiltIn &&
774
+ (!wantKinds || wantKinds.includes('built-in')) &&
775
+ (!input.type || input.type.includes('official')) &&
776
+ (!input.category || meta.module.category === input.category) &&
777
+ !input.provider &&
778
+ !input.verifiedOnly &&
779
+ (!input.emits || meta.ids.emits.includes(input.emits)) &&
780
+ (!input.consumes || meta.ids.consumes.includes(input.consumes))
781
+ const builtInCard = (meta: BuiltInMeta, chips: string[]): BuiltInCard => ({
782
+ id: meta.module.id,
783
+ title: meta.module.title,
784
+ description: meta.module.description,
785
+ category: meta.module.category,
786
+ enabled: null,
787
+ install: meta.module.install || builtInEnableCommand(meta.module.id),
788
+ page: absolute(searcher.site, meta.module.page),
789
+ matchedOn: chips,
790
+ presetNote: builtInPresetText(meta.module, line),
791
+ })
792
+
793
+ const filtered = Boolean(
794
+ input.category || input.emits || input.consumes || input.provider || input.type || wantKinds || input.verifiedOnly,
795
+ )
796
+ const words = tokenize(input.query).some((term) => processTerm(term) !== null)
797
+ if (input.query.trim() === '' || (filtered && !words)) {
798
+ const filterChips = (category: string, providers: readonly { name: string; label: string }[]): string[] => [
799
+ ...(input.emits ? [`event ${input.emits}`] : []),
800
+ ...(input.consumes && input.consumes !== input.emits ? [`event ${input.consumes}`] : []),
801
+ ...(provider ? providers.filter(providerMatches).slice(0, 1).map((item) => `provider ${item.label}`) : []),
802
+ ...(input.category ? [`category ${category}`] : []),
803
+ ]
804
+ const modules = [...searcher.modules.values()].filter(moduleOk).sort(relevanceCompare(line))
805
+ const narrowed = Boolean(input.category || input.emits || input.consumes || wantKinds)
806
+ const builtIns = narrowed
807
+ ? [...searcher.builtInModules.values()].filter(builtInOk).sort((left, right) => left.module.title.localeCompare(right.module.title))
808
+ : []
809
+ return {
810
+ line,
811
+ latest,
812
+ modules: modules.map((meta) => ({ meta, matchedOn: filterChips(meta.entry.category, meta.entry.providers) })),
813
+ builtIn: builtIns.slice(0, BUILTIN_MAX).map((meta) => builtInCard(meta, filterChips(meta.module.category, []))),
814
+ didYouMean: null,
815
+ }
816
+ }
817
+
818
+ const run = (combineWith: 'AND' | 'OR', query: string = input.query): Hits => {
819
+ const hits = searcher.miniSearch.search(query, {
820
+ combineWith,
821
+ prefix: true,
822
+ fuzzy: 0.2,
823
+ boost: { ...SEARCH_BOOST },
824
+ boostDocument,
825
+ })
826
+ const modules: Hits['modules'] = []
827
+ const builtIns: Hits['builtIns'] = []
828
+ for (const result of hits) {
829
+ const id = String(result.id)
830
+ if (result['group'] === 'builtin') {
831
+ const meta = searcher.builtInModules.get(id.replace(/^core:/, ''))
832
+ if (meta && builtInOk(meta)) builtIns.push({ meta, result })
833
+ } else {
834
+ const meta = searcher.modules.get(id)
835
+ if (meta && moduleOk(meta)) modules.push({ meta, result })
836
+ }
837
+ }
838
+ return { modules, builtIns }
839
+ }
840
+ const none = (hits: Hits) => hits.modules.length === 0 && hits.builtIns.length === 0
841
+ const topOf = (hits: Hits) => Math.max(hits.modules[0]?.result.score ?? 0, hits.builtIns[0]?.result.score ?? 0)
842
+ const typed = new Set(tokenize(input.query).filter((term) => processTerm(term) !== null))
843
+ const strong = <T extends { result: SearchResult }>(hits: readonly T[], top: number): T[] =>
844
+ hits.filter((hit) => hit.result.score >= WEAK_HIT_RATIO * top || Object.keys(hit.result.match).some((term) => typed.has(term)))
845
+ let found = run('AND')
846
+ let didYouMean: string | null = null
847
+ if (none(found)) {
848
+ const orHits = run('OR')
849
+ const top = topOf(orHits)
850
+ found = { modules: strong(orHits.modules, top), builtIns: strong(orHits.builtIns, top) }
851
+ if (none(found)) {
852
+ let best: { variant: string; hits: Hits; top: number } | null = null
853
+ for (const variant of swapVariants(input.query)) {
854
+ const hits = run('AND', variant)
855
+ const top = topOf(hits)
856
+ if (!none(hits) && (!best || top > best.top)) best = { variant, hits, top }
857
+ }
858
+ if (best) {
859
+ found = best.hits
860
+ didYouMean = best.variant
861
+ }
862
+ }
863
+ } else if (found.modules.length < MIN_AND_RESULTS && tokenize(input.query).filter((term) => processTerm(term)).length > 1) {
864
+ const orHits = run('OR')
865
+ const top = Math.max(topOf(found), topOf(orHits))
866
+ const seen = new Set(found.modules.map((hit) => hit.meta.entry.locator))
867
+ found = {
868
+ modules: [...found.modules, ...strong(orHits.modules, top).filter((hit) => !seen.has(hit.meta.entry.locator))],
869
+ builtIns: found.builtIns,
870
+ }
871
+ }
872
+
873
+ const best = found.modules[0]?.result.score ?? 0
874
+ const query = (didYouMean ?? input.query).trim().toLowerCase()
875
+ const builtIn = found.builtIns
876
+ .filter(
877
+ ({ meta, result }) =>
878
+ result.score >= BUILTIN_RATIO * best ||
879
+ meta.module.title.toLowerCase() === query ||
880
+ meta.module.id === query.replace(/[\s-]+/g, '_'),
881
+ )
882
+ .slice(0, BUILTIN_MAX)
883
+ .map(({ meta, result }) => builtInCard(meta, matchedOn(result.match, { ids: meta.ids }, result.queryTerms)))
884
+ const modules = found.modules.map(({ meta, result }) => ({
885
+ meta,
886
+ matchedOn: matchedOn(
887
+ result.match,
888
+ { providers: meta.entry.providers, tags: meta.entry.tags, ids: meta.ids, category: meta.entry.category },
889
+ result.queryTerms,
890
+ ),
891
+ }))
892
+ return { line, latest, modules, builtIn, didYouMean }
893
+ }
894
+
895
+ export function toModuleCard(searcher: CatalogSearcher, hit: RankedModule, line: string | null, latest: string | null): ModuleCard {
896
+ const entry = hit.meta.entry
897
+ return {
898
+ locator: entry.locator,
899
+ path: entry.path,
900
+ title: entry.title,
901
+ summary: entry.summary,
902
+ whenToUse: entry.whenToUse,
903
+ type: entry.type,
904
+ kind: entry.kind,
905
+ category: entry.category,
906
+ license: { spdx: entry.license.spdx, kind: entry.license.kind },
907
+ tier: entry.tier,
908
+ omQuality: hit.meta.omQuality,
909
+ verifiedOn: entry.compat.verifiedOn,
910
+ line,
911
+ status: line ? statusOn(entry, line) : null,
912
+ agentPolicy: line ? (entry.agentPolicy[line] ?? null) : null,
913
+ installableFrom: entry.version.installableFrom,
914
+ ...installFields(entry, line, latest, peerLookup(searcher)),
915
+ matchedOn: hit.matchedOn,
916
+ card: absolute(searcher.site, entry.links.page),
917
+ }
918
+ }
919
+
920
+ /** The listed entries of the search index, where the catalog looks up an adapter's peer libraries. */
921
+ export function peerLookup(searcher: CatalogSearcher): PeerLookup {
922
+ return (locator) => searcher.modules.get(locator)?.entry
923
+ }
924
+
925
+ export function receiptSourceOf(searcher: CatalogSearcher): ReceiptSource | null {
926
+ const source = searcher.index.dataAsOf?.source
927
+ return source === 'ci' || source === 'preview' ? source : null
928
+ }
929
+
930
+ export function searchModules(searcher: CatalogSearcher, input: SearchModulesInput): SearchModulesOutput {
931
+ const limit = Math.min(SEARCH_MAX_LIMIT, Math.max(1, Math.floor(input.limit ?? SEARCH_DEFAULTS.limit)))
932
+ const ranked = rankModules(searcher, input)
933
+ return {
934
+ results: ranked.modules.slice(0, limit).map((hit) => toModuleCard(searcher, hit, ranked.line, ranked.latest)),
935
+ builtIn: ranked.builtIn,
936
+ total: ranked.modules.length,
937
+ line: ranked.line,
938
+ dataVersion: searcher.index.dataVersion,
939
+ generatedAt: searcher.index.generatedAt,
940
+ receiptSource: receiptSourceOf(searcher),
941
+ ...(ranked.didYouMean ? { didYouMean: ranked.didYouMean } : {}),
942
+ }
943
+ }
944
+
945
+ export function stripVersion(ref: string): { name: string; version: string | null } {
946
+ const match = /^(.+?)@(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)$/.exec(ref.trim())
947
+ return match ? { name: match[1] as string, version: match[2] as string } : { name: ref.trim(), version: null }
948
+ }
949
+
950
+ export type ResolvedRef =
951
+ | { kind: 'entry'; entry: CatalogEntry; candidates: string[] }
952
+ | { kind: 'builtin'; builtIn: BuiltInModule; candidates: string[] }
953
+ | { kind: 'none'; candidates: string[] }
954
+
955
+ const normalizeRef = (value: string) => value.trim().toLowerCase()
956
+ const rankEntry = (entry: CatalogEntry) => (entry.type === 'official' ? 0 : 2) + (entry.tier === 'verified' ? 0 : 1)
957
+
958
+ export function resolveRef(ref: string, entries: readonly CatalogEntry[], builtIn: readonly BuiltInModule[]): ResolvedRef {
959
+ const wanted = normalizeRef(stripVersion(ref).name)
960
+ const direct = entries.find(
961
+ (entry) =>
962
+ normalizeRef(entry.locator) === wanted ||
963
+ (entry.npm !== null && normalizeRef(entry.npm) === wanted) ||
964
+ normalizeRef(entry.path) === wanted ||
965
+ normalizeRef(`/m/${entry.path}`) === wanted ||
966
+ entry.renamedFrom.some((previous) => normalizeRef(previous) === wanted || normalizeRef(previous) === `npm:${wanted}`),
967
+ )
968
+ if (direct) return { kind: 'entry', entry: direct, candidates: [] }
969
+ const githubPath = wanted.startsWith('github:')
970
+ ? `github/${wanted.slice(7)}`
971
+ : wanted.replace(/^https:\/\/github\.com\//, 'github/')
972
+ const github = entries.find((entry) => normalizeRef(entry.path) === githubPath)
973
+ if (github) return { kind: 'entry', entry: github, candidates: [] }
974
+
975
+ const id = wanted.replace(/^core:/, '')
976
+ const byId = entries.filter((entry) => entry.moduleIds.includes(id)).sort((left, right) => rankEntry(left) - rankEntry(right))
977
+ const core = builtIn.find((coreModule) => coreModule.id === id)
978
+ if (core) return { kind: 'builtin', builtIn: core, candidates: byId.map((entry) => entry.locator).slice(0, 10) }
979
+ if (byId.length === 1) return { kind: 'entry', entry: byId[0] as CatalogEntry, candidates: [] }
980
+ if (byId.length > 1) return { kind: 'none', candidates: byId.map((entry) => entry.locator).slice(0, 10) }
981
+
982
+ const loose = entries
983
+ .filter(
984
+ (entry) =>
985
+ wanted.length >= 3 &&
986
+ (normalizeRef(entry.locator).includes(wanted) || entry.moduleIds.some((moduleId) => moduleId.includes(wanted.replace(/-/g, '_')))),
987
+ )
988
+ .sort((left, right) => rankEntry(left) - rankEntry(right))
989
+ return { kind: 'none', candidates: loose.map((entry) => entry.locator).slice(0, 10) }
990
+ }
991
+
992
+ const clip = (text: string, max = 200) => (text.length > max ? `${text.slice(0, max - 3)}...` : text)
993
+
994
+ export function entryWarnings(
995
+ entry: CatalogEntry,
996
+ today: string,
997
+ line: string | null,
998
+ receiptSource: ReceiptSource | null = null,
999
+ ): string[] {
1000
+ const warnings: string[] = []
1001
+ if (!entry.listed) warnings.push(`Not listed: ${(line ? entry.agentPolicy[line] : null)?.reasons[0]?.text ?? 'see the card.'}`)
1002
+ if (entry.status !== 'active') warnings.push(`Status: ${entry.status}.`)
1003
+ if (entry.version.installableFrom && entry.version.installableFrom > today)
1004
+ warnings.push(
1005
+ `${entry.version.latest ?? 'The newest release'} is installable from ${entry.version.installableFrom} (Yarn age gate).`,
1006
+ )
1007
+ if (entry.license.mismatch) warnings.push('License sources disagree. See the card.')
1008
+ const supplyChain = entry.signals?.supplyChain
1009
+ if (supplyChain && supplyChain.status !== 'ok')
1010
+ warnings.push(`Supply chain ${supplyChain.status}: ${supplyChain.reasons.join('; ') || 'see the card'}.`)
1011
+ const hygiene = entry.signals?.hygiene
1012
+ if (hygiene && hygiene.status !== 'ok') warnings.push(`Hygiene ${hygiene.status}: ${hygiene.failing.join(', ') || 'see the card'}.`)
1013
+ if (entry.signals?.anatomy === 'hidden') warnings.push('Anatomy is not published for this entry.')
1014
+ return [...(receiptSource === 'preview' ? [PREVIEW_LINE] : []), ...warnings.map((warning) => clip(warning))].slice(0, 10)
1015
+ }
1016
+
1017
+ export function unknownModuleMessage(ref: string, candidates: readonly string[]): string {
1018
+ return candidates.length > 0
1019
+ ? `Unknown module "${ref.slice(0, 80)}". Did you mean: ${candidates.join(', ')}?`
1020
+ : `Unknown module "${ref.slice(0, 80)}".`
1021
+ }
1022
+
1023
+ export function builtInWarnings(coreModule: BuiltInModule, line: string | null): string[] {
1024
+ return builtInNotes(coreModule, line).map((note) => clip(note))
1025
+ }
1026
+
1027
+ export function sharedModuleIdWarning(id: string, count: number): string {
1028
+ return clip(`Module ID ${id} is provided by ${count} entries. Pick one of the candidates.`)
1029
+ }
1030
+
1031
+ export function cardUrl(searcher: CatalogSearcher, page: string): string {
1032
+ return absolute(searcher.site, page)
1033
+ }