@asteby/metacore-runtime-react 53.6.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 (84) hide show
  1. package/CHANGELOG.md +38 -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/setup/addon-config-surface.d.ts +7 -1
  42. package/dist/setup/addon-config-surface.d.ts.map +1 -1
  43. package/dist/setup/addon-config-surface.js +128 -10
  44. package/dist/setup/messages.d.ts.map +1 -1
  45. package/dist/setup/messages.js +10 -0
  46. package/dist/use-option-ids.d.ts.map +1 -1
  47. package/dist/use-option-ids.js +3 -1
  48. package/dist/use-options-resolver.d.ts +4 -1
  49. package/dist/use-options-resolver.d.ts.map +1 -1
  50. package/dist/use-options-resolver.js +27 -16
  51. package/dist/widgets/charts.d.ts.map +1 -1
  52. package/dist/widgets/charts.js +11 -43
  53. package/dist/widgets/widget-format.d.ts +1 -41
  54. package/dist/widgets/widget-format.d.ts.map +1 -1
  55. package/dist/widgets/widget-format.js +3 -138
  56. package/package.json +4 -4
  57. package/src/__tests__/addon-config-surface.test.tsx +55 -0
  58. package/src/__tests__/charts-reexport.test.ts +30 -0
  59. package/src/action-modal-dispatcher.tsx +3 -1
  60. package/src/api-context.tsx +14 -0
  61. package/src/cache-scope-inflight.test.ts +369 -0
  62. package/src/cache-scope.test.ts +234 -0
  63. package/src/cache-scope.ts +202 -0
  64. package/src/capability-providers/index.ts +46 -0
  65. package/src/capability-providers/model.test.ts +186 -0
  66. package/src/capability-providers/model.ts +464 -0
  67. package/src/capability-providers/provider-sortable-list.test.tsx +284 -0
  68. package/src/capability-providers/provider-sortable-list.tsx +452 -0
  69. package/src/capability-providers/reorder.ts +29 -0
  70. package/src/dashboard-types.ts +2 -11
  71. package/src/dynamic-kanban.tsx +9 -4
  72. package/src/dynamic-relation.tsx +5 -2
  73. package/src/dynamic-table.tsx +41 -10
  74. package/src/dynamic-view.tsx +3 -1
  75. package/src/index.ts +13 -0
  76. package/src/metadata-cache.ts +85 -15
  77. package/src/query-batch.ts +71 -30
  78. package/src/setup/addon-config-surface.tsx +202 -18
  79. package/src/setup/messages.ts +10 -0
  80. package/src/use-option-ids.ts +3 -1
  81. package/src/use-options-resolver.ts +28 -15
  82. package/src/widgets/charts.tsx +26 -189
  83. package/src/widgets/widget-format.ts +14 -181
  84. package/vitest.setup.ts +16 -0
@@ -0,0 +1,202 @@
1
+ /**
2
+ * Scope of every client-side cache that holds server answers shaped by who is
3
+ * asking: `org:user:lang`.
4
+ *
5
+ * Metadata carries the user's permissions (`actions[]`, `can*` flags) and the
6
+ * operator's language, and rows depend on the organization. On a shared
7
+ * browser a cache keyed by anything less shows the first paint of the previous
8
+ * account. The scope is read from what the SDK already knows: the host session
9
+ * (`auth_user` in localStorage: `organization_id`, `id`) and the UI language
10
+ * (`i18nextLng`, or `<html lang>`; a host with another source calls
11
+ * {@link setCacheScopeLanguageProvider}).
12
+ *
13
+ * Fails closed: when the organization, the user or the language is unknown the
14
+ * scope is `null` and nothing is served from nor stored in a cache.
15
+ */
16
+
17
+ type ScopeListener = (next: string | null, prev: string | null) => void
18
+
19
+ let languageProvider: (() => string | null | undefined) | null = null
20
+ let scopeProvider: (() => CacheScopeParts | null | undefined) | null = null
21
+
22
+ export interface CacheScopeParts {
23
+ org?: string | null
24
+ user?: string | null
25
+ lang?: string | null
26
+ }
27
+ const listeners = new Set<ScopeListener>()
28
+ let lastScope: string | null | undefined
29
+
30
+ /** Lets a host with its own language source (not i18next / `<html lang>`) feed the scope. */
31
+ export function setCacheScopeLanguageProvider(fn: (() => string | null | undefined) | null): void {
32
+ languageProvider = fn
33
+ }
34
+
35
+ /**
36
+ * Lets the host feed the whole scope from its own session store instead of
37
+ * `localStorage`. Takes precedence over `auth_user` and the token check; a
38
+ * missing `lang` falls back to the language sources above. Returning `null`
39
+ * (no session) makes the scope unknown, so nothing is cached. Pass `null` to
40
+ * go back to reading `localStorage`.
41
+ *
42
+ * The provider MUST change with every user AND every organization (a switch of
43
+ * either has to yield different `org`/`user`). A scope that stays the same
44
+ * across accounts defeats the protection: caches would be served to the next
45
+ * account as if nothing changed.
46
+ */
47
+ export function setCacheScopeProvider(fn: (() => CacheScopeParts | null | undefined) | null): void {
48
+ scopeProvider = fn
49
+ }
50
+
51
+ // One-entry memo: peekCacheScope runs on every render (inScope) and the token
52
+ // rarely changes, so decode it once per distinct text.
53
+ let lastDecoded: { token: string; claims: Record<string, unknown> | null } | null = null
54
+
55
+ function decodeJwtClaims(token: string): Record<string, unknown> | null {
56
+ if (lastDecoded && lastDecoded.token === token) return lastDecoded.claims
57
+ const claims = decodeJwtClaimsUncached(token)
58
+ lastDecoded = { token, claims }
59
+ return claims
60
+ }
61
+
62
+ function decodeJwtClaimsUncached(token: string): Record<string, unknown> | null {
63
+ const parts = token.split('.')
64
+ if (parts.length !== 3 || !parts[1]) return null
65
+ try {
66
+ const b64 = parts[1].replace(/-/g, '+').replace(/_/g, '/')
67
+ const padded = b64 + '='.repeat((4 - (b64.length % 4)) % 4)
68
+ const json =
69
+ typeof atob === 'function'
70
+ ? decodeURIComponent(
71
+ Array.from(atob(padded), (c) => '%' + c.charCodeAt(0).toString(16).padStart(2, '0')).join(''),
72
+ )
73
+ : ''
74
+ const claims = JSON.parse(json)
75
+ return claims && typeof claims === 'object' ? (claims as Record<string, unknown>) : null
76
+ } catch {
77
+ return null
78
+ }
79
+ }
80
+
81
+ function claimOf(claims: Record<string, unknown>, keys: string[]): string {
82
+ for (const k of keys) {
83
+ const v = claims[k]
84
+ if (v != null && String(v).trim()) return String(v).trim()
85
+ }
86
+ return ''
87
+ }
88
+
89
+ /**
90
+ * `auth_user` is written by the host after `/auth/me`, while the token
91
+ * (`auth_token`) may already be the NEW one (SSO plants it first). Decodes the
92
+ * stored JWT WITHOUT verifying it (the server verifies; here it is only a
93
+ * consistency check) and returns false when the user/org it carries is not the
94
+ * one in `auth_user`: the identity is in transition, so the scope is unknown.
95
+ * A missing or non-JWT token (opaque/session tokens) keeps trusting `auth_user`
96
+ * alone; that is the documented limit — such hosts should use
97
+ * {@link setCacheScopeProvider}.
98
+ */
99
+ function tokenMatches(org: string, user: string): boolean {
100
+ let token = ''
101
+ try {
102
+ token = localStorage.getItem('auth_token') ?? ''
103
+ // The auth store may keep it JSON-encoded.
104
+ if (token.startsWith('"')) token = String(JSON.parse(token))
105
+ } catch {
106
+ return true
107
+ }
108
+ token = token.replace(/^Bearer\s+/i, '').trim()
109
+ if (!token) return true
110
+ const claims = decodeJwtClaims(token)
111
+ if (!claims) return true
112
+ const tUser = claimOf(claims, ['sub', 'ID', 'id', 'user_id', 'UserID'])
113
+ const tOrg = claimOf(claims, ['org', 'OrganizationID', 'organization_id', 'org_id'])
114
+ if (tUser && tUser !== user) return false
115
+ if (tOrg && tOrg !== org) return false
116
+ return true
117
+ }
118
+
119
+ function readLang(): string {
120
+ try {
121
+ if (languageProvider) return String(languageProvider() ?? '').trim()
122
+ if (typeof localStorage !== 'undefined') {
123
+ const l = localStorage.getItem('i18nextLng')
124
+ if (l) return l.trim()
125
+ }
126
+ if (typeof document !== 'undefined') return (document.documentElement?.lang ?? '').trim()
127
+ } catch {
128
+ /* unreadable storage: unknown language */
129
+ }
130
+ return ''
131
+ }
132
+
133
+ /** Reads the scope without notifying anyone (safe inside render/selectors). */
134
+ export function peekCacheScope(): string | null {
135
+ if (scopeProvider) {
136
+ try {
137
+ const p = scopeProvider()
138
+ if (!p) return null
139
+ const org = String(p.org ?? '').trim()
140
+ const user = String(p.user ?? '').trim()
141
+ const lang = String(p.lang ?? '').trim() || readLang()
142
+ if (!org || !user || !lang) return null
143
+ return [org, user, lang].map(encodeURIComponent).join(':')
144
+ } catch {
145
+ return null
146
+ }
147
+ }
148
+ if (typeof localStorage === 'undefined') return null
149
+ let org = ''
150
+ let user = ''
151
+ try {
152
+ const raw = localStorage.getItem('auth_user')
153
+ if (!raw) return null
154
+ const parsed = JSON.parse(raw) as { organization_id?: unknown; id?: unknown }
155
+ org = String(parsed.organization_id ?? '').trim()
156
+ user = String(parsed.id ?? '').trim()
157
+ } catch {
158
+ return null
159
+ }
160
+ const lang = readLang()
161
+ if (!org || !user || !lang) return null
162
+ if (!tokenMatches(org, user)) return null
163
+ return [org, user, lang].map(encodeURIComponent).join(':')
164
+ }
165
+
166
+ /**
167
+ * Current `org:user:lang` scope, or `null` when any part is unknown (callers
168
+ * must then neither read nor write caches). When the scope moved since the
169
+ * last call, every registered cache is told to drop what it holds.
170
+ */
171
+ export function cacheScope(): string | null {
172
+ const next = peekCacheScope()
173
+ if (lastScope !== undefined && next !== lastScope) {
174
+ const prev = lastScope
175
+ lastScope = next
176
+ for (const fn of [...listeners]) {
177
+ try {
178
+ fn(next, prev)
179
+ } catch {
180
+ /* a cache failing to clear must not break the others */
181
+ }
182
+ }
183
+ }
184
+ lastScope = next
185
+ return next
186
+ }
187
+
188
+ /** Re-reads the scope and clears caches if it changed (login, logout, org/user/lang switch). */
189
+ export function syncCacheScope(): void {
190
+ cacheScope()
191
+ }
192
+
193
+ /** Registers a cache to be cleared when the scope changes. Returns the unsubscribe. */
194
+ export function onCacheScopeChange(fn: ScopeListener): () => void {
195
+ listeners.add(fn)
196
+ return () => listeners.delete(fn)
197
+ }
198
+
199
+ /** Test helper: forget the last seen scope without notifying. */
200
+ export function resetCacheScopeTracking(): void {
201
+ lastScope = undefined
202
+ }
@@ -0,0 +1,46 @@
1
+ export {
2
+ pickText,
3
+ domainOf,
4
+ humanizeSegment,
5
+ servesMarket,
6
+ resolveCapability,
7
+ recommendProvider,
8
+ groupByDomain,
9
+ activeMarkets,
10
+ bundleSelections,
11
+ storedSelections,
12
+ choiceBlock,
13
+ checkoutBlockers,
14
+ changeImpact,
15
+ providerStatus,
16
+ usableCapabilities,
17
+ needsProviderChoice,
18
+ competingProviderAddons,
19
+ // Named to avoid clashing with CapabilityProvider from ./capability-gate.
20
+ type CapabilityProvider as CapabilityProviderBinding,
21
+ type I18nText as ProviderI18nText,
22
+ type CapabilityView,
23
+ type CapabilityDomain,
24
+ type ConnectionState,
25
+ type ProviderInfo,
26
+ type Market,
27
+ type CapabilitiesPayload,
28
+ type ResolutionReason,
29
+ type Resolution,
30
+ type CellStatus,
31
+ type DomainCell,
32
+ type DomainGroup,
33
+ type ChoiceBlock,
34
+ type ChangeImpact,
35
+ type UsableCapability,
36
+ type ProviderStatus,
37
+ } from './model'
38
+ export { moveItem, moveId, dropIndexFromPointer } from './reorder'
39
+ export {
40
+ ProviderSortableList,
41
+ sortableOrder,
42
+ DEFAULT_PROVIDER_LIST_LABELS,
43
+ type ProviderSortableItem,
44
+ type ProviderSortableListLabels,
45
+ type ProviderSortableListProps,
46
+ } from './provider-sortable-list'
@@ -0,0 +1,186 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import {
3
+ bundleSelections,
4
+ competingProviderAddons,
5
+ changeImpact,
6
+ groupByDomain,
7
+ needsProviderChoice,
8
+ usableCapabilities,
9
+ type CapabilitiesPayload,
10
+ type CapabilityView,
11
+ type Market,
12
+ } from './model'
13
+
14
+ const send = 'messaging.whatsapp.send'
15
+
16
+ describe('usableCapabilities', () => {
17
+ it('hides capabilities with no installed provider', () => {
18
+ expect(
19
+ usableCapabilities([
20
+ {
21
+ key: send,
22
+ providers: [
23
+ { addon_key: 'whatsapp', installed: false, default: false },
24
+ ],
25
+ },
26
+ ])
27
+ ).toEqual([])
28
+ })
29
+
30
+ it('a single installed provider is the one in use', () => {
31
+ const [row] = usableCapabilities([
32
+ {
33
+ key: send,
34
+ providers: [
35
+ { addon_key: 'connector_whatsapp', installed: true, default: false },
36
+ { addon_key: 'whatsapp', installed: false, default: false },
37
+ ],
38
+ },
39
+ ])
40
+ expect(row.current?.addon_key).toBe('connector_whatsapp')
41
+ expect(row.ambiguous).toBe(false)
42
+ })
43
+
44
+ it('several installed providers need a default, which then wins', () => {
45
+ const both = (def: boolean) => [
46
+ { addon_key: 'connector_whatsapp', installed: true, default: false },
47
+ { addon_key: 'whatsapp', installed: true, default: def },
48
+ ]
49
+ expect(
50
+ usableCapabilities([{ key: send, providers: both(false) }])[0].ambiguous
51
+ ).toBe(true)
52
+ const [row] = usableCapabilities([{ key: send, providers: both(true) }])
53
+ expect(row.ambiguous).toBe(false)
54
+ expect(row.current?.addon_key).toBe('whatsapp')
55
+ })
56
+ })
57
+
58
+ // ─── agrupado por negocio, un selector por mercado, impacto y vista previa ──
59
+
60
+ const mx: Market = { code: 'mx', name: 'México', countries: ['MX'], is_default: true }
61
+ const us: Market = { code: 'us', name: 'Estados Unidos', countries: ['US'] }
62
+
63
+ const prov = (addon_key: string, extra: object = {}) => ({
64
+ addon_key,
65
+ installed: true,
66
+ default: false,
67
+ ...extra,
68
+ })
69
+
70
+ const payload: CapabilitiesPayload = {
71
+ domains: [
72
+ { key: 'commerce.shipping', order: 20, title: { es: 'Envíos' } },
73
+ { key: 'commerce.payments', order: 10, title: { es: 'Pagos' } },
74
+ ],
75
+ data: [
76
+ {
77
+ key: 'commerce.payments.session',
78
+ domain: 'commerce.payments',
79
+ checkout: true,
80
+ providers: [prov('mercadopago', { countries: ['MX'] }), prov('stripe')],
81
+ },
82
+ {
83
+ key: 'commerce.payments.confirm',
84
+ domain: 'commerce.payments',
85
+ providers: [prov('mercadopago', { countries: ['MX'] }), prov('stripe')],
86
+ },
87
+ {
88
+ key: 'commerce.shipping.rates',
89
+ domain: 'commerce.shipping',
90
+ fanout: true,
91
+ providers: [prov('skydropx')],
92
+ },
93
+ ],
94
+ }
95
+
96
+ describe('groupByDomain', () => {
97
+ const groups = groupByDomain(payload, [mx, us])
98
+
99
+ it('agrupa por negocio en el orden del catálogo, no por contrato técnico', () => {
100
+ expect(groups.map((g) => g.key)).toEqual(['commerce.payments', 'commerce.shipping'])
101
+ expect(groups[0].capabilities).toHaveLength(2)
102
+ })
103
+
104
+ it('un solo resultado por mercado: pide elegir cuando hay dos candidatos', () => {
105
+ const pagos = groups[0]
106
+ expect(pagos.cells.map((c) => c.market?.code)).toEqual(['mx', 'us'])
107
+ expect(pagos.cells[0].status).toBe('needs_choice')
108
+ // Mercado Pago no sirve en US: solo Stripe es candidato y responde solo.
109
+ expect(pagos.cells[1].candidates).toEqual(['stripe'])
110
+ expect(pagos.cells[1]).toMatchObject({ status: 'ok', provider: 'stripe' })
111
+ })
112
+
113
+ it('los envíos que responden todos no piden elegir', () => {
114
+ expect(groups[1].fanoutOnly).toBe(true)
115
+ expect(groups[1].cells[0].status).toBe('fanout')
116
+ })
117
+ })
118
+
119
+ describe('bundleSelections / changeImpact', () => {
120
+ const pagos = groupByDomain(payload, [mx, us])[0]
121
+
122
+ it('elegir un proveedor aplica a todo el paquete que ofrece y sirve', () => {
123
+ expect(bundleSelections(pagos, 'mercadopago', mx)).toEqual({
124
+ 'commerce.payments.session': 'mercadopago',
125
+ 'commerce.payments.confirm': 'mercadopago',
126
+ })
127
+ // No sirve en US: no se escribe nada.
128
+ expect(bundleSelections(pagos, 'mercadopago', us)).toEqual({})
129
+ })
130
+
131
+ it('el aviso de impacto lista lo que se escribe y marca lo que ya estaba', () => {
132
+ const impact = changeImpact(pagos, 'mercadopago', mx)
133
+ expect(impact.keys).toHaveLength(2)
134
+ expect(impact.saveable).toBe(true)
135
+ expect(impact.sameProvider).toBe(false)
136
+ expect(changeImpact(pagos, 'mercadopago', us).saveable).toBe(false)
137
+ })
138
+ })
139
+
140
+ describe('needsProviderChoice', () => {
141
+ const one = (installed: boolean[], extra: object = {}) => ({
142
+ key: 'commerce.payments.session',
143
+ providers: installed.map((i, n) => ({ addon_key: `p${n}`, installed: i, default: false })),
144
+ ...extra,
145
+ })
146
+ const mx: Market = { code: 'MX', active: true }
147
+ const us: Market = { code: 'US', active: true }
148
+
149
+ it('stays hidden with one market and one provider per function', () => {
150
+ expect(needsProviderChoice([one([true])], [mx])).toBe(false)
151
+ expect(needsProviderChoice([], [])).toBe(false)
152
+ expect(needsProviderChoice(undefined, undefined)).toBe(false)
153
+ })
154
+ it('shows with more than one active market', () => {
155
+ expect(needsProviderChoice([one([true])], [mx, us])).toBe(true)
156
+ })
157
+ it('ignores inactive markets', () => {
158
+ expect(needsProviderChoice([one([true])], [mx, { ...us, active: false }])).toBe(false)
159
+ })
160
+ it('shows when a function has several installed providers', () => {
161
+ expect(needsProviderChoice([one([true, true])], [mx])).toBe(true)
162
+ })
163
+ it('does not count uninstalled providers nor fan-out functions', () => {
164
+ expect(needsProviderChoice([one([true, false])], [mx])).toBe(false)
165
+ expect(needsProviderChoice([one([true, true], { fanout: true })], [mx])).toBe(false)
166
+ })
167
+ })
168
+
169
+ describe('competingProviderAddons', () => {
170
+ const cap = (key: string, providers: [string, boolean][], extra = {}): CapabilityView => ({
171
+ key,
172
+ providers: providers.map(([addon_key, installed]) => ({ addon_key, installed, default: false })),
173
+ ...extra,
174
+ })
175
+ it('lists installed addons that share a function', () => {
176
+ const set = competingProviderAddons([
177
+ cap('commerce.payments.session', [['mercadopago', true], ['payments_manual', true]]),
178
+ cap('commerce.tax.calculate', [['solo', true], ['other', false]]),
179
+ ])
180
+ expect([...set].sort()).toEqual(['mercadopago', 'payments_manual'])
181
+ })
182
+ it('ignores fan-out functions and undefined', () => {
183
+ expect(competingProviderAddons([cap('commerce.shipping.rates', [['a', true], ['b', true]], { fanout: true })]).size).toBe(0)
184
+ expect(competingProviderAddons(undefined).size).toBe(0)
185
+ })
186
+ })