@asteby/metacore-runtime-react 53.7.0 → 53.8.1

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 (76) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/dist/action-modal-dispatcher.d.ts.map +1 -1
  3. package/dist/action-modal-dispatcher.js +3 -1
  4. package/dist/api-context.d.ts.map +1 -1
  5. package/dist/api-context.js +15 -0
  6. package/dist/cache-scope.d.ts +52 -0
  7. package/dist/cache-scope.d.ts.map +1 -0
  8. package/dist/cache-scope.js +200 -0
  9. package/dist/capability-providers/index.d.ts +4 -0
  10. package/dist/capability-providers/index.d.ts.map +1 -0
  11. package/dist/capability-providers/index.js +3 -0
  12. package/dist/capability-providers/model.d.ts +201 -0
  13. package/dist/capability-providers/model.d.ts.map +1 -0
  14. package/dist/capability-providers/model.js +293 -0
  15. package/dist/capability-providers/provider-sortable-list.d.ts +86 -0
  16. package/dist/capability-providers/provider-sortable-list.d.ts.map +1 -0
  17. package/dist/capability-providers/provider-sortable-list.js +263 -0
  18. package/dist/capability-providers/reorder.d.ts +10 -0
  19. package/dist/capability-providers/reorder.d.ts.map +1 -0
  20. package/dist/capability-providers/reorder.js +31 -0
  21. package/dist/dashboard-types.d.ts +2 -4
  22. package/dist/dashboard-types.d.ts.map +1 -1
  23. package/dist/dynamic-kanban.d.ts.map +1 -1
  24. package/dist/dynamic-kanban.js +9 -4
  25. package/dist/dynamic-relation.d.ts.map +1 -1
  26. package/dist/dynamic-relation.js +5 -2
  27. package/dist/dynamic-table.d.ts +2 -0
  28. package/dist/dynamic-table.d.ts.map +1 -1
  29. package/dist/dynamic-table.js +40 -6
  30. package/dist/dynamic-view.d.ts.map +1 -1
  31. package/dist/dynamic-view.js +3 -1
  32. package/dist/index.d.ts +4 -1
  33. package/dist/index.d.ts.map +1 -1
  34. package/dist/index.js +5 -1
  35. package/dist/metadata-cache.d.ts +22 -2
  36. package/dist/metadata-cache.d.ts.map +1 -1
  37. package/dist/metadata-cache.js +73 -13
  38. package/dist/query-batch.d.ts +12 -0
  39. package/dist/query-batch.d.ts.map +1 -1
  40. package/dist/query-batch.js +70 -29
  41. package/dist/use-option-ids.d.ts.map +1 -1
  42. package/dist/use-option-ids.js +3 -1
  43. package/dist/use-options-resolver.d.ts +4 -1
  44. package/dist/use-options-resolver.d.ts.map +1 -1
  45. package/dist/use-options-resolver.js +27 -16
  46. package/dist/widgets/charts.d.ts.map +1 -1
  47. package/dist/widgets/charts.js +11 -43
  48. package/dist/widgets/widget-format.d.ts +1 -41
  49. package/dist/widgets/widget-format.d.ts.map +1 -1
  50. package/dist/widgets/widget-format.js +3 -138
  51. package/package.json +4 -4
  52. package/src/__tests__/charts-reexport.test.ts +30 -0
  53. package/src/action-modal-dispatcher.tsx +3 -1
  54. package/src/api-context.tsx +14 -0
  55. package/src/cache-scope-inflight.test.ts +369 -0
  56. package/src/cache-scope.test.ts +234 -0
  57. package/src/cache-scope.ts +202 -0
  58. package/src/capability-providers/index.ts +46 -0
  59. package/src/capability-providers/model.test.ts +186 -0
  60. package/src/capability-providers/model.ts +464 -0
  61. package/src/capability-providers/provider-sortable-list.test.tsx +284 -0
  62. package/src/capability-providers/provider-sortable-list.tsx +452 -0
  63. package/src/capability-providers/reorder.ts +29 -0
  64. package/src/dashboard-types.ts +2 -11
  65. package/src/dynamic-kanban.tsx +9 -4
  66. package/src/dynamic-relation.tsx +5 -2
  67. package/src/dynamic-table.tsx +41 -10
  68. package/src/dynamic-view.tsx +3 -1
  69. package/src/index.ts +13 -0
  70. package/src/metadata-cache.ts +85 -15
  71. package/src/query-batch.ts +71 -30
  72. package/src/use-option-ids.ts +3 -1
  73. package/src/use-options-resolver.ts +28 -15
  74. package/src/widgets/charts.tsx +26 -189
  75. package/src/widgets/widget-format.ts +14 -181
  76. package/vitest.setup.ts +16 -0
@@ -0,0 +1,464 @@
1
+ // Pure model of GET /api/capabilities + GET /api/markets, kept free of
2
+ // runtime imports so it is unit-testable without the app's api client.
3
+ //
4
+ // A host screen groups the technical capability contracts
5
+ // (e.g. commerce.<domain>.<operation>) by business DOMAIN and lets the admin
6
+ // choose ONE provider per domain and market; the choice is applied to every
7
+ // contract of the bundle the provider offers. The resolution below mirrors the
8
+ // kernel's capability.Select v1 (market selection, org default, only eligible
9
+ // provider). It does NOT model Select v2 (per-market priority and provider
10
+ // state), which is pending the kernel's F2 release: until then the order
11
+ // produced by ProviderSortableList is a display/intent order this model does
12
+ // not consume, so a host must not present it as what dispatch will do.
13
+
14
+ export type I18nText = Record<string, string>
15
+
16
+ export type CapabilityProvider = {
17
+ addon_key: string
18
+ /** Addon i18n key of the binding label (e.g. mercadopago.capability.session.label). */
19
+ label?: string
20
+ installed: boolean
21
+ /** Org-level default (used where a market has no selection of its own). */
22
+ default: boolean
23
+ /** Market codes this provider is explicitly selected for. */
24
+ markets?: string[]
25
+ /** ISO countries the provider declared it serves; empty = any. */
26
+ countries?: string[]
27
+ }
28
+
29
+ export type CapabilityView = {
30
+ key: string
31
+ providers: CapabilityProvider[]
32
+ domain?: string
33
+ title?: I18nText
34
+ description?: I18nText
35
+ /** A buyer-facing flow needs a provider for it in every market. */
36
+ checkout?: boolean
37
+ /** Every eligible provider answers (shipping rates…): nothing to choose. */
38
+ fanout?: boolean
39
+ /** Follow-ups go to the provider that created the operation. */
40
+ pinned?: boolean
41
+ }
42
+
43
+ export type CapabilityDomain = {
44
+ key: string
45
+ title?: I18nText
46
+ description?: I18nText
47
+ icon?: string
48
+ order?: number
49
+ }
50
+
51
+ export type ConnectionState = 'connected' | 'missing_credentials' | 'not_required'
52
+
53
+ export type ProviderInfo = {
54
+ addon_key: string
55
+ name?: I18nText
56
+ icon?: string
57
+ connection?: {
58
+ state: ConnectionState
59
+ environment?: 'sandbox' | 'production' | ''
60
+ connector?: string
61
+ testable?: boolean
62
+ }
63
+ }
64
+
65
+ export type Market = {
66
+ code: string
67
+ name?: string
68
+ countries?: string[]
69
+ currency?: string
70
+ is_default?: boolean
71
+ active?: boolean
72
+ }
73
+
74
+ export type CapabilitiesPayload = {
75
+ data: CapabilityView[]
76
+ domains?: CapabilityDomain[]
77
+ providers?: Record<string, ProviderInfo>
78
+ }
79
+
80
+ /** Pick a locale's text: exact, base language, es, en, any. */
81
+ export function pickText(text: I18nText | undefined, locale?: string): string {
82
+ if (!text) return ''
83
+ const l = (locale ?? '').trim()
84
+ if (l && text[l]) return text[l]
85
+ const baseLang = l.split(/[-_]/)[0]?.toLowerCase()
86
+ if (baseLang && text[baseLang]) return text[baseLang]
87
+ for (const k of ['es', 'en', 'default']) if (text[k]) return text[k]
88
+ return Object.values(text).find(Boolean) ?? ''
89
+ }
90
+
91
+ /** "commerce.payments.session" → "commerce.payments" (fallback when the API has no domain). */
92
+ export function domainOf(key: string): string {
93
+ const parts = key.split('.')
94
+ return parts.length > 2 ? parts.slice(0, 2).join('.') : key
95
+ }
96
+
97
+ /** Readable title from a key segment, never the dotted id ("loyalty" → "Loyalty"). */
98
+ export function humanizeSegment(key: string): string {
99
+ const seg = key.split('.').pop() ?? key
100
+ return seg.replace(/[_-]+/g, ' ').replace(/^\w/, (m) => m.toUpperCase())
101
+ }
102
+
103
+ export function servesMarket(p: CapabilityProvider, m: Market | null): boolean {
104
+ if (!m) return true
105
+ const pc = p.countries ?? []
106
+ const mc = m.countries ?? []
107
+ if (pc.length === 0 || mc.length === 0) return true
108
+ return pc.some((c) => mc.some((x) => x.toUpperCase() === c.toUpperCase()))
109
+ }
110
+
111
+ export type ResolutionReason =
112
+ | 'selected' // explicitly chosen for the market
113
+ | 'default' // org default
114
+ | 'only' // the only eligible provider
115
+ | 'fanout' // every eligible provider answers
116
+ | 'ambiguous' // several eligible, none chosen: dispatch fails
117
+ | 'none' // nobody installed serves this market
118
+
119
+ export type Resolution = {
120
+ key: string
121
+ addon?: string
122
+ /** Fan-out: every provider that will answer. */
123
+ addons?: string[]
124
+ reason: ResolutionReason
125
+ eligible: string[]
126
+ }
127
+
128
+ /**
129
+ * Which provider answers capability `c` in market `m` (null = organization
130
+ * level). Mirrors kernel capability.Select v1 (today's rule): market
131
+ * selection, then org default among eligible, then the only eligible
132
+ * provider. Select v2 (priority and provider state) is pending kernel F2 and
133
+ * is not modeled here.
134
+ */
135
+ export function resolveCapability(c: CapabilityView, m: Market | null): Resolution {
136
+ const installed = c.providers.filter((p) => p.installed)
137
+ const selected = m ? installed.filter((p) => (p.markets ?? []).includes(m.code)) : []
138
+ const eligible = installed.filter((p) => servesMarket(p, m))
139
+ const eligibleKeys = eligible.map((p) => p.addon_key)
140
+ if (c.fanout) {
141
+ const answering = selected.length ? selected : eligible
142
+ if (answering.length === 0) return { key: c.key, reason: 'none', eligible: eligibleKeys }
143
+ return { key: c.key, reason: 'fanout', addons: answering.map((p) => p.addon_key), eligible: eligibleKeys }
144
+ }
145
+ if (selected.length === 1) return { key: c.key, addon: selected[0].addon_key, reason: 'selected', eligible: eligibleKeys }
146
+ if (selected.length > 1) return { key: c.key, reason: 'ambiguous', eligible: eligibleKeys }
147
+ const defaults = eligible.filter((p) => p.default)
148
+ if (defaults.length === 1) return { key: c.key, addon: defaults[0].addon_key, reason: 'default', eligible: eligibleKeys }
149
+ if (defaults.length > 1) return { key: c.key, reason: 'ambiguous', eligible: eligibleKeys }
150
+ if (eligible.length === 1) return { key: c.key, addon: eligible[0].addon_key, reason: 'only', eligible: eligibleKeys }
151
+ if (eligible.length === 0) return { key: c.key, reason: 'none', eligible: eligibleKeys }
152
+ return { key: c.key, reason: 'ambiguous', eligible: eligibleKeys }
153
+ }
154
+
155
+ export type CellStatus =
156
+ | 'ok' // one provider for the whole bundle
157
+ | 'mixed' // several providers split the bundle (chosen at contract level)
158
+ | 'needs_choice' // several candidates and nobody chosen
159
+ | 'no_provider' // nobody installed serves this market
160
+ | 'fanout' // every compatible provider answers
161
+
162
+ export type DomainCell = {
163
+ market: Market | null
164
+ status: CellStatus
165
+ /** The provider of the bundle when status is ok. */
166
+ provider?: string
167
+ /** Providers in use (mixed / fanout). */
168
+ providers: string[]
169
+ resolutions: Resolution[]
170
+ /** Providers that can be chosen for the bundle in this market. */
171
+ candidates: string[]
172
+ /** Installed providers of the domain that do NOT serve this market. */
173
+ blocked: string[]
174
+ /** One-click suggestion when exactly one candidate is ready. */
175
+ recommended?: string
176
+ /** Checkout contracts left without a provider in this market. */
177
+ checkoutGaps: string[]
178
+ }
179
+
180
+ export type DomainGroup = {
181
+ key: string
182
+ domain: CapabilityDomain
183
+ capabilities: CapabilityView[]
184
+ /** Installed providers of any capability of the domain, sorted. */
185
+ providers: string[]
186
+ /** Capability keys each provider offers in this domain. */
187
+ provides: Record<string, string[]>
188
+ cells: DomainCell[]
189
+ fanoutOnly: boolean
190
+ }
191
+
192
+ const isReady = (info?: ProviderInfo) => !info?.connection || info.connection.state !== 'missing_credentials'
193
+
194
+ export function recommendProvider(
195
+ candidates: string[],
196
+ providers: Record<string, ProviderInfo> | undefined,
197
+ ): string | undefined {
198
+ if (candidates.length === 0) return undefined
199
+ if (candidates.length === 1) return candidates[0]
200
+ const connected = candidates.filter((a) => providers?.[a]?.connection?.state === 'connected')
201
+ if (connected.length === 1) return connected[0]
202
+ const ready = candidates.filter((a) => isReady(providers?.[a]))
203
+ if (ready.length === 1) return ready[0]
204
+ return undefined
205
+ }
206
+
207
+ function buildCell(
208
+ caps: CapabilityView[],
209
+ m: Market | null,
210
+ provides: Record<string, string[]>,
211
+ providers: Record<string, ProviderInfo> | undefined,
212
+ ): DomainCell {
213
+ const resolutions = caps.map((c) => resolveCapability(c, m))
214
+ const chosen = caps.filter((c) => !c.fanout)
215
+ const single = resolutions.filter((_, i) => !caps[i].fanout)
216
+ const inUse = [...new Set(single.map((r) => r.addon).filter((a): a is string => !!a))]
217
+ const checkoutGaps = caps
218
+ .filter((c, i) => c.checkout && (resolutions[i].reason === 'none' || resolutions[i].reason === 'ambiguous'))
219
+ .map((c) => c.key)
220
+ // Candidates: providers that serve this market for at least one
221
+ // choosable contract of the domain.
222
+ const candidates = Object.keys(provides)
223
+ .filter((a) => chosen.some((c) => c.providers.some((p) => p.addon_key === a && p.installed && servesMarket(p, m))))
224
+ .sort()
225
+ const blocked = Object.keys(provides)
226
+ .filter((a) => !candidates.includes(a) && chosen.length > 0)
227
+ .sort()
228
+ const base = { market: m, resolutions, candidates, blocked, checkoutGaps }
229
+ if (chosen.length === 0) {
230
+ const answering = [...new Set(resolutions.flatMap((r) => r.addons ?? []))].sort()
231
+ return { ...base, status: answering.length ? 'fanout' : 'no_provider', providers: answering }
232
+ }
233
+ if (single.some((r) => r.reason === 'ambiguous')) {
234
+ return { ...base, status: 'needs_choice', providers: inUse, recommended: recommendProvider(candidates, providers) }
235
+ }
236
+ if (inUse.length > 1) return { ...base, status: 'mixed', providers: inUse }
237
+ if (inUse.length === 0) return { ...base, status: 'no_provider', providers: [] }
238
+ return { ...base, status: 'ok', provider: inUse[0], providers: inUse }
239
+ }
240
+
241
+ /**
242
+ * Group the usable capabilities (at least one installed provider) by domain
243
+ * and resolve each domain per market. With no active market the single
244
+ * column is the organization level (market null).
245
+ */
246
+ export function groupByDomain(
247
+ payload: CapabilitiesPayload,
248
+ markets: Market[],
249
+ ): DomainGroup[] {
250
+ const usable = payload.data.filter((c) => c.providers.some((p) => p.installed))
251
+ const domainMeta = new Map((payload.domains ?? []).map((d) => [d.key, d]))
252
+ const byDomain = new Map<string, CapabilityView[]>()
253
+ for (const c of usable) {
254
+ const d = c.domain || domainOf(c.key)
255
+ byDomain.set(d, [...(byDomain.get(d) ?? []), c])
256
+ }
257
+ const columns: (Market | null)[] = activeMarkets(markets).length ? activeMarkets(markets) : [null]
258
+ const groups: DomainGroup[] = []
259
+ for (const [key, caps] of byDomain) {
260
+ const provides: Record<string, string[]> = {}
261
+ for (const c of caps)
262
+ for (const p of c.providers)
263
+ if (p.installed) provides[p.addon_key] = [...(provides[p.addon_key] ?? []), c.key]
264
+ groups.push({
265
+ key,
266
+ domain: domainMeta.get(key) ?? { key, order: 1000 },
267
+ capabilities: caps,
268
+ providers: Object.keys(provides).sort(),
269
+ provides,
270
+ cells: columns.map((m) => buildCell(caps, m, provides, payload.providers)),
271
+ fanoutOnly: caps.every((c) => c.fanout),
272
+ })
273
+ }
274
+ return groups.sort(
275
+ (a, b) => (a.domain.order ?? 1000) - (b.domain.order ?? 1000) || a.key.localeCompare(b.key),
276
+ )
277
+ }
278
+
279
+ /** Active markets, default first, then by name. */
280
+ export function activeMarkets(markets: Market[]): Market[] {
281
+ return markets
282
+ .filter((m) => m.active !== false)
283
+ .sort((a, b) => Number(!!b.is_default) - Number(!!a.is_default) || (a.name ?? a.code).localeCompare(b.name ?? b.code))
284
+ }
285
+
286
+ /**
287
+ * The selections to send when `addon` becomes the provider of the whole
288
+ * domain in market m: every choosable contract of the domain the addon
289
+ * provides and serves there. Contracts it does not provide are left as they
290
+ * are.
291
+ */
292
+ export function bundleSelections(group: DomainGroup, addon: string, m: Market | null): Record<string, string> {
293
+ const out: Record<string, string> = {}
294
+ for (const c of group.capabilities) {
295
+ if (c.fanout) continue
296
+ const p = c.providers.find((x) => x.addon_key === addon && x.installed)
297
+ if (p && servesMarket(p, m)) out[c.key] = addon
298
+ }
299
+ return out
300
+ }
301
+
302
+ /**
303
+ * What is stored today for these keys in market m ("" = nothing chosen), so
304
+ * the host can send it back as is (undo).
305
+ */
306
+ export function storedSelections(group: DomainGroup, keys: string[], m: Market | null): Record<string, string> {
307
+ const out: Record<string, string> = {}
308
+ for (const k of keys) {
309
+ const c = group.capabilities.find((x) => x.key === k)
310
+ const hit = c?.providers.find((p) => p.installed && (m ? (p.markets ?? []).includes(m.code) : p.default))
311
+ out[k] = hit?.addon_key ?? ''
312
+ }
313
+ return out
314
+ }
315
+
316
+ export type ChoiceBlock = { addon: string; reason: 'market' | 'not_provided'; countries?: string[] }
317
+
318
+ /** Why `addon` cannot be the domain provider in market m (null = it can). */
319
+ export function choiceBlock(group: DomainGroup, addon: string, m: Market | null): ChoiceBlock | null {
320
+ const offers = group.capabilities.filter((c) => !c.fanout && c.providers.some((p) => p.addon_key === addon && p.installed))
321
+ if (offers.length === 0) return { addon, reason: 'not_provided' }
322
+ const serving = offers.filter((c) => servesMarket(c.providers.find((p) => p.addon_key === addon)!, m))
323
+ if (serving.length === 0) {
324
+ const countries = offers[0].providers.find((p) => p.addon_key === addon)?.countries
325
+ return { addon, reason: 'market', countries }
326
+ }
327
+ return null
328
+ }
329
+
330
+ /** Markets whose checkout lacks a provider for a contract it needs. */
331
+ export function checkoutBlockers(groups: DomainGroup[]): { group: DomainGroup; cell: DomainCell }[] {
332
+ const out: { group: DomainGroup; cell: DomainCell }[] = []
333
+ for (const g of groups) for (const cell of g.cells) if (cell.checkoutGaps.length) out.push({ group: g, cell })
334
+ return out
335
+ }
336
+
337
+ export type ChangeImpact = {
338
+ /** Contracts the change writes (the bundle the provider offers and serves). */
339
+ keys: string[]
340
+ /** Providers answering those contracts today (effective, not only stored). */
341
+ from: string[]
342
+ /** Every key already resolves to the provider. */
343
+ sameProvider: boolean
344
+ /** Every key already STORES this provider as an explicit selection. */
345
+ alreadyStored: boolean
346
+ /** Something would change on save (a different provider or an explicit pin). */
347
+ saveable: boolean
348
+ }
349
+
350
+ /** Impact preview of making `addon` the provider of the domain in market m. */
351
+ export function changeImpact(group: DomainGroup, addon: string, m: Market | null): ChangeImpact {
352
+ const keys = Object.keys(bundleSelections(group, addon, m))
353
+ const idx = group.cells.findIndex((c) => (c.market?.code ?? '') === (m?.code ?? ''))
354
+ const res = idx >= 0 ? group.cells[idx].resolutions.filter((r) => keys.includes(r.key)) : []
355
+ const from = [...new Set(res.map((r) => r.addon).filter((a): a is string => !!a))]
356
+ const sameProvider = res.length > 0 && res.every((r) => r.addon === addon)
357
+ const stored = storedSelections(group, keys, m)
358
+ const alreadyStored = keys.length > 0 && keys.every((k) => stored[k] === addon)
359
+ return { keys, from, sameProvider, alreadyStored, saveable: keys.length > 0 && !alreadyStored }
360
+ }
361
+
362
+ // ─── Legacy flat view (kept for callers that list capabilities one by one) ──
363
+
364
+ export type UsableCapability = CapabilityView & {
365
+ installed: CapabilityProvider[]
366
+ /** The provider the host routes to today, if any. */
367
+ current?: CapabilityProvider
368
+ /** Several installed providers and none marked default: dispatch fails. */
369
+ ambiguous: boolean
370
+ }
371
+
372
+ // Only capabilities the org can actually use (at least one provider
373
+ // installed), mirroring the host's choice: the marked default, else the only
374
+ // installed provider; several without a default is ambiguous.
375
+ export function usableCapabilities(data: CapabilityView[]): UsableCapability[] {
376
+ return data
377
+ .map((c) => {
378
+ const installed = c.providers.filter((p) => p.installed)
379
+ const current =
380
+ installed.find((p) => p.default) ??
381
+ (installed.length === 1 ? installed[0] : undefined)
382
+ return {
383
+ ...c,
384
+ installed,
385
+ current,
386
+ ambiguous: installed.length > 1 && !current,
387
+ }
388
+ })
389
+ .filter((c) => c.installed.length > 0)
390
+ }
391
+
392
+ /**
393
+ * Is there anything to decide on the provider-choice screen? Only when the
394
+ * organization sells in more than one market, or some function can be served
395
+ * by more than one installed provider. With a single market and one provider
396
+ * per function the screen would only repeat what is already installed
397
+ * («MX» under «MX»), so the entry stays out of the way until it matters.
398
+ */
399
+ export function needsProviderChoice(
400
+ capabilities: readonly CapabilityView[] | undefined,
401
+ markets: readonly Market[] | undefined,
402
+ ): boolean {
403
+ const activeMarkets = (markets ?? []).filter((m) => m.active !== false)
404
+ if (activeMarkets.length > 1) return true
405
+ return (capabilities ?? []).some(
406
+ (c) => !c.fanout && c.providers.filter((p) => p.installed).length > 1,
407
+ )
408
+ }
409
+
410
+ /**
411
+ * Installed addons that compete with another installed addon for the same
412
+ * function (a non-fan-out capability with 2+ installed providers). The host
413
+ * links their card in the installed-addons list to the provider-choice
414
+ * screen, where the choice is made.
415
+ */
416
+ export function competingProviderAddons(
417
+ capabilities: readonly CapabilityView[] | undefined,
418
+ ): Set<string> {
419
+ const out = new Set<string>()
420
+ for (const c of capabilities ?? []) {
421
+ if (c.fanout) continue
422
+ const installed = c.providers.filter((p) => p.installed)
423
+ if (installed.length > 1) installed.forEach((p) => out.add(p.addon_key))
424
+ }
425
+ return out
426
+ }
427
+
428
+ // ─── Status of a provider for a market (feeds ProviderSortableList) ─────────
429
+
430
+ /**
431
+ * Badge of a provider for a market. `missing_credentials` is the kernel's
432
+ * `not_configured`; `disabled` is the row's own `enabled = false`;
433
+ * `unhealthy` is a connected provider whose health check is failing;
434
+ * `unavailable` does not serve the market (or is not installed).
435
+ */
436
+ export type ProviderStatus =
437
+ | 'ready'
438
+ | 'missing_credentials'
439
+ | 'sandbox'
440
+ | 'unhealthy'
441
+ | 'unavailable'
442
+ | 'disabled'
443
+
444
+ /**
445
+ * The badge a provider deserves in market `m`, first match wins:
446
+ * `unavailable` when it is not installed or does not serve the market,
447
+ * `disabled` when `opts.enabled === false`, `missing_credentials` when it
448
+ * still needs to be connected, `unhealthy` when `opts.healthy === false`,
449
+ * `sandbox` when it runs against a test environment, else `ready`.
450
+ * Providers that need no connection are ready.
451
+ */
452
+ export function providerStatus(
453
+ provider: CapabilityProvider,
454
+ info: ProviderInfo | undefined,
455
+ m: Market | null,
456
+ opts?: { enabled?: boolean; healthy?: boolean },
457
+ ): ProviderStatus {
458
+ if (!provider.installed || !servesMarket(provider, m)) return 'unavailable'
459
+ if (opts?.enabled === false) return 'disabled'
460
+ if (info?.connection?.state === 'missing_credentials') return 'missing_credentials'
461
+ if (opts?.healthy === false) return 'unhealthy'
462
+ if (info?.connection?.state === 'connected' && info.connection.environment === 'sandbox') return 'sandbox'
463
+ return 'ready'
464
+ }