@asteby/metacore-runtime-react 53.14.0 → 53.16.0

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.
@@ -0,0 +1,92 @@
1
+ // Comprobación mínima de rangos semver para `manifest.frontend.sdk`
2
+ // (p. ej. "^4.0.0", ">=3.2 <5", "~3.18", "3.x", "^3 || ^4"). Sin dependencias.
3
+ // Un rango que no se entiende devuelve `null` (desconocido): el llamador NO lo
4
+ // trata como incompatible, para no romper addons por un rango exótico.
5
+ function parseVersion(s) {
6
+ const m = /^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:[-+].*)?$/.exec(s.trim());
7
+ if (!m)
8
+ return null;
9
+ return [Number(m[1]), Number(m[2] ?? 0), Number(m[3] ?? 0)];
10
+ }
11
+ function cmp(a, b) {
12
+ for (let i = 0; i < 3; i++)
13
+ if (a[i] !== b[i])
14
+ return a[i] < b[i] ? -1 : 1;
15
+ return 0;
16
+ }
17
+ /** Un comparador simple (`^1.2.3`, `>=1`, `1.x`, `=1.2.3`) contra `v`. null = no se entiende. */
18
+ function matchComparator(token, v) {
19
+ const m = /^(\^|~|>=|<=|>|<|=)?\s*v?([\dxX*]+(?:\.[\dxX*]+){0,2}(?:[-+][\w.-]+)?)$/.exec(token);
20
+ if (!m)
21
+ return null;
22
+ const op = m[1] ?? '';
23
+ const raw = m[2];
24
+ const parts = raw.split(/[-+]/)[0].split('.');
25
+ const isWild = (p) => p === undefined || /^[xX*]$/.test(p);
26
+ const nums = parts.map((p) => (isWild(p) ? null : Number(p)));
27
+ if (nums[0] === null)
28
+ return op === '<' ? false : true; // "*" / "x"
29
+ const lo = [nums[0], nums[1] ?? 0, nums[2] ?? 0];
30
+ const specified = nums.filter((n) => n !== null).length; // 1..3
31
+ // Límite superior exclusivo para comodín / parcial ("1.2" => <1.3.0).
32
+ const bump = (n) => (n === 1 ? [lo[0] + 1, 0, 0] : n === 2 ? [lo[0], lo[1] + 1, 0] : [lo[0], lo[1], lo[2] + 1]);
33
+ switch (op) {
34
+ case '':
35
+ case '=':
36
+ return cmp(v, lo) >= 0 && cmp(v, bump(specified)) < 0;
37
+ case '>=':
38
+ return cmp(v, lo) >= 0;
39
+ case '>':
40
+ return cmp(v, bump(specified)) >= 0;
41
+ case '<':
42
+ return cmp(v, lo) < 0;
43
+ case '<=':
44
+ return cmp(v, bump(specified)) < 0;
45
+ case '~':
46
+ return cmp(v, lo) >= 0 && cmp(v, bump(specified === 1 ? 1 : 2)) < 0;
47
+ case '^': {
48
+ let hi;
49
+ if (lo[0] > 0 || specified === 1)
50
+ hi = [lo[0] + 1, 0, 0];
51
+ else if (lo[1] > 0 || specified === 2)
52
+ hi = [0, lo[1] + 1, 0];
53
+ else
54
+ hi = [0, 0, lo[2] + 1];
55
+ return cmp(v, lo) >= 0 && cmp(v, hi) < 0;
56
+ }
57
+ }
58
+ return null;
59
+ }
60
+ /**
61
+ * ¿`version` cumple `range`? `true`/`false` si ambos se entienden, `null` si
62
+ * alguno no (rango vacío o versión ilegible = sin restricción conocida).
63
+ */
64
+ export function satisfiesSdkRange(version, range) {
65
+ if (!version || !range || !range.trim())
66
+ return null;
67
+ const v = parseVersion(version);
68
+ if (!v)
69
+ return null;
70
+ let unknown = false;
71
+ for (const alt of range.split('||')) {
72
+ // "1.2.3 - 2.0.0" no se soporta: cae en `unknown`.
73
+ const tokens = alt.trim().split(/\s+/).filter(Boolean);
74
+ if (tokens.length === 0) {
75
+ return true;
76
+ }
77
+ let ok = true;
78
+ for (const t of tokens) {
79
+ const r = matchComparator(t, v);
80
+ if (r === null) {
81
+ unknown = true;
82
+ ok = false;
83
+ break;
84
+ }
85
+ if (!r)
86
+ ok = false;
87
+ }
88
+ if (ok)
89
+ return true;
90
+ }
91
+ return unknown ? null : false;
92
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@asteby/metacore-runtime-react",
3
- "version": "53.14.0",
3
+ "version": "53.16.0",
4
4
  "description": "React runtime for metacore hosts — renders addon contributions dynamically",
5
5
  "repository": {
6
6
  "type": "git",
@@ -42,7 +42,7 @@
42
42
  "zod": "^4.3.0"
43
43
  },
44
44
  "peerDependencies": {
45
- "@asteby/metacore-sdk": "^3.18.1",
45
+ "@asteby/metacore-sdk": "^3.19.0",
46
46
  "@asteby/metacore-ui": "^2.32.1",
47
47
  "@tanstack/react-query": ">=5",
48
48
  "@tanstack/react-router": ">=1.100",
@@ -74,7 +74,7 @@
74
74
  }
75
75
  },
76
76
  "devDependencies": {
77
- "@asteby/metacore-sdk": "3.18.1",
77
+ "@asteby/metacore-sdk": "3.19.0",
78
78
  "@asteby/metacore-ui": "2.32.1",
79
79
  "@tanstack/react-query": "^5.95.0",
80
80
  "@tanstack/react-router": "^1.168.0",
@@ -325,3 +325,30 @@ describe('AddonConfigSurface', () => {
325
325
  expect(screen.queryByText('Serie N1')).toBeNull()
326
326
  })
327
327
  })
328
+
329
+ describe('host-generated (auto) credentials', () => {
330
+ const autoConnector: ConnectorEntry = {
331
+ addon_key: 'pay',
332
+ provider: 'local_reviews',
333
+ connected: true,
334
+ credentials: [{ key: 'api_key', type: 'secret', required: true, auto: 'storefront_bearer', label: 'pay.token' }],
335
+ auto_credentials: { api_key: 'generated' },
336
+ }
337
+
338
+ it('hides the field, shows the state and rotates showing the value once', async () => {
339
+ const { calls } = setup(
340
+ { connector: autoConnector },
341
+ { 'POST /integrations/local_reviews/auto/api_key/rotate': { data: { value: 'mcs_NEWSECRET' } } },
342
+ )
343
+ expect(await screen.findByText('Conectada automáticamente')).toBeTruthy()
344
+ expect(screen.queryByLabelText(/Token/)).toBeNull()
345
+ fireEvent.click(screen.getByText('Rotar'))
346
+ await waitFor(() => expect(screen.getByText('mcs_NEWSECRET')).toBeTruthy())
347
+ expect(calls.some((c) => c.m === 'POST' && c.url === '/integrations/local_reviews/auto/api_key/rotate')).toBe(true)
348
+ })
349
+
350
+ it('asks for action when it was never generated', async () => {
351
+ setup({ connector: { ...autoConnector, auto_credentials: { api_key: 'missing' } } })
352
+ expect(await screen.findByText('Requiere acción')).toBeTruthy()
353
+ })
354
+ })
@@ -0,0 +1,299 @@
1
+ // @vitest-environment happy-dom
2
+ //
3
+ // AddonSlot: orden (order, luego priority), aislamiento de fallos entre
4
+ // hermanos y del shell, timeout de un remoto colgado, requireIntegrity,
5
+ // rango frontend.sdk y unificación con el slot store.
6
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
7
+ import { act, cleanup, render, screen } from '@testing-library/react'
8
+ import { __resetRemoteIntegrityCache, slotStore } from '@asteby/metacore-sdk'
9
+
10
+
11
+
12
+ const mf = vi.hoisted(() => ({ registerRemotes: vi.fn(), loadRemote: vi.fn() }))
13
+ vi.mock('@module-federation/runtime', () => mf)
14
+
15
+ import {
16
+ AddonSlot,
17
+ AddonSlotProvider,
18
+ satisfiesSdkRange,
19
+ sortSlotItems,
20
+ resolveSlotTimeout,
21
+ type AddonSlotManifest,
22
+ type AddonSlotFailure,
23
+ } from '../slots'
24
+
25
+ const remote = (text: string) => ({
26
+ default: ({ context, props }: any) => (
27
+ <span data-testid={`remote-${text}`}>
28
+ {text}:{String(context.invoiceId)}:{String(props.tone ?? '')}
29
+ </span>
30
+ ),
31
+ })
32
+
33
+ function manifest(key: string, over: Partial<AddonSlotManifest> = {}, order?: number): AddonSlotManifest {
34
+ return {
35
+ key,
36
+ frontend: { entry: `/api/addons/${key}/remoteEntry.js`},
37
+ contributions: { slots: [{ slot_kind: 'invoice.footer', entry: `./slots/${key}`, order, props: { tone: 'info' } }] },
38
+ ...over,
39
+ }
40
+ }
41
+
42
+ let quiet: ReturnType<typeof vi.spyOn>
43
+ beforeEach(() => {
44
+ mf.registerRemotes.mockReset()
45
+ mf.registerRemotes.mockResolvedValue(undefined)
46
+ mf.loadRemote.mockReset()
47
+ __resetRemoteIntegrityCache()
48
+ vi.stubGlobal('fetch', vi.fn(async () => new Response('x')))
49
+ quiet = vi.spyOn(console, 'error').mockImplementation(() => {})
50
+ })
51
+ afterEach(() => {
52
+ cleanup()
53
+ quiet.mockRestore()
54
+ vi.restoreAllMocks()
55
+ vi.useRealTimers()
56
+ vi.unstubAllGlobals()
57
+ })
58
+
59
+ function Shell({ manifests, onEvent, ...rest }: { manifests: AddonSlotManifest[]; onEvent?: any } & Record<string, any>) {
60
+ return (
61
+ <AddonSlotProvider manifests={manifests} onEvent={onEvent} {...rest}>
62
+ <nav data-testid="shell">shell</nav>
63
+ <AddonSlot kind="invoice.footer" context={{ invoiceId: 7 }} fallback={(f) => <i data-testid={`fb-${f.addon}`}>{f.reason}</i>} />
64
+ </AddonSlotProvider>
65
+ )
66
+ }
67
+
68
+ describe('AddonSlot', () => {
69
+ it('pinta los remotos con context y props, ordenados por order', async () => {
70
+ mf.loadRemote.mockImplementation(async (id: string) => remote(id.split('/').pop()!))
71
+ const { container } = render(<Shell manifests={[manifest('b', {}, 20), manifest('a', {}, 10)]} />)
72
+ await screen.findByTestId('remote-a')
73
+ await screen.findByTestId('remote-b')
74
+ const order = [...container.querySelectorAll('[data-addon-slot-item]')].map((n) => n.getAttribute('data-addon-slot-item'))
75
+ expect(order).toEqual(['a', 'b'])
76
+ expect(screen.getByTestId('remote-a').textContent).toBe('a:7:info')
77
+ })
78
+
79
+ it('un remoto que lanza al renderizar no desmonta a sus hermanos ni al shell', async () => {
80
+ mf.loadRemote.mockImplementation(async (id: string) =>
81
+ id.endsWith('bad')
82
+ ? {
83
+ default: () => {
84
+ throw new Error('boom')
85
+ },
86
+ }
87
+ : remote('ok'),
88
+ )
89
+ const events: AddonSlotFailure[] = []
90
+ render(
91
+ <Shell
92
+ manifests={[manifest('bad', {}, 1), manifest('ok', {}, 2)]}
93
+ onEvent={(e: string, d: AddonSlotFailure) => {
94
+ expect(e).toBe('addon_slot_failed')
95
+ events.push(d)
96
+ }}
97
+ />,
98
+ )
99
+ await screen.findByTestId('remote-ok')
100
+ await screen.findByTestId('fb-bad')
101
+ expect(screen.getByTestId('shell')).toBeTruthy()
102
+ expect(screen.getByTestId('remote-ok')).toBeTruthy()
103
+ expect(events).toEqual([{ addon: 'bad', kind: 'invoice.footer', reason: 'render', message: 'boom' }])
104
+ })
105
+
106
+ it('un remoto cuya carga falla emite telemetría y no afecta a los hermanos', async () => {
107
+ mf.loadRemote.mockImplementation(async (id: string) => {
108
+ if (id.endsWith('bad')) throw new Error('404 expose')
109
+ return remote('ok')
110
+ })
111
+ const onEvent = vi.fn()
112
+ render(<Shell manifests={[manifest('bad'), manifest('ok')]} onEvent={onEvent} />)
113
+ await screen.findByTestId('remote-ok')
114
+ await screen.findByTestId('fb-bad')
115
+ expect(onEvent).toHaveBeenCalledWith('addon_slot_failed', expect.objectContaining({ addon: 'bad', reason: 'load' }))
116
+ })
117
+
118
+ it('slots[].fallback=notice pinta el aviso del SDK; hide conserva el fallback del host', async () => {
119
+ mf.loadRemote.mockImplementation(async (id: string) => {
120
+ if (id.endsWith('bad') || id.endsWith('quiet')) throw new Error('404 expose')
121
+ return remote('ok')
122
+ })
123
+ const withFallback = (key: string, fb: 'hide' | 'notice'): AddonSlotManifest => {
124
+ const m = manifest(key)
125
+ m.contributions!.slots![0].fallback = fb
126
+ return m
127
+ }
128
+ render(<Shell manifests={[withFallback('bad', 'notice'), withFallback('quiet', 'hide'), manifest('ok')]} />)
129
+ await screen.findByTestId('remote-ok')
130
+ const notice = await screen.findByRole('status')
131
+ expect(notice.getAttribute('data-addon-slot-notice')).toBe('bad')
132
+ expect(notice.textContent).not.toContain('404')
133
+ expect(screen.queryByTestId('fb-bad')).toBeNull()
134
+ expect(screen.getByTestId('fb-quiet')).toBeTruthy()
135
+ })
136
+
137
+ it('un remoto colgado muestra el fallback tras timeoutMs y el hermano sí pinta', async () => {
138
+ vi.useFakeTimers()
139
+ mf.loadRemote.mockImplementation((id: string) =>
140
+ id.endsWith('slow') ? new Promise(() => {}) : Promise.resolve(remote('ok')),
141
+ )
142
+ const onEvent = vi.fn()
143
+ render(<Shell manifests={[manifest('slow'), manifest('ok')]} onEvent={onEvent} timeoutMs={1500} />)
144
+ await act(async () => {
145
+ await vi.advanceTimersByTimeAsync(1000)
146
+ })
147
+ expect(screen.queryByTestId('fb-slow')).toBeNull()
148
+ expect(screen.getByTestId('remote-ok')).toBeTruthy()
149
+ await act(async () => {
150
+ await vi.advanceTimersByTimeAsync(600)
151
+ })
152
+ expect(screen.getByTestId('fb-slow').textContent).toBe('timeout')
153
+ expect(onEvent).toHaveBeenCalledWith('addon_slot_failed', expect.objectContaining({ addon: 'slow', reason: 'timeout' }))
154
+ })
155
+
156
+ it('timeout_ms del manifest manda sobre el del host', async () => {
157
+ vi.useFakeTimers()
158
+ mf.loadRemote.mockImplementation(() => new Promise(() => {}))
159
+ const m = manifest('slow')
160
+ m.contributions!.slots![0].timeout_ms = 1000
161
+ render(<Shell manifests={[m]} timeoutMs={60000} />)
162
+ await act(async () => {
163
+ await vi.advanceTimersByTimeAsync(1050)
164
+ })
165
+ expect(screen.getByTestId('fb-slow').textContent).toBe('timeout')
166
+ })
167
+
168
+ it('requireIntegrity rechaza un remoto sin integrity sin bajarlo; por omisión carga como hoy', async () => {
169
+ mf.loadRemote.mockImplementation(async () => remote('x'))
170
+ const noInt = manifest('x', { frontend: { entry: '/x.js' } })
171
+ const onEvent = vi.fn()
172
+ const { unmount } = render(<Shell manifests={[noInt]} onEvent={onEvent} requireIntegrity />)
173
+ await screen.findByTestId('fb-x')
174
+ expect(screen.getByTestId('fb-x').textContent).toBe('integrity_required')
175
+ expect(mf.loadRemote).not.toHaveBeenCalled()
176
+ unmount()
177
+ render(<Shell manifests={[noInt]} />)
178
+ await screen.findByTestId('remote-x')
179
+ })
180
+
181
+ it('integrity real: el hash correcto carga y el incorrecto falla sin montar el remoto', async () => {
182
+ const bytes = new TextEncoder().encode('export default {}')
183
+ const digest = btoa(String.fromCharCode(...new Uint8Array(await crypto.subtle.digest('SHA-384', bytes))))
184
+ vi.stubGlobal('fetch', vi.fn(async () => new Response(bytes)))
185
+ vi.spyOn(Object.getPrototypeOf(document.createElement('link').relList), 'supports').mockReturnValue(false) // fuerza la ruta fetch+hash
186
+ mf.loadRemote.mockImplementation(async () => remote('p'))
187
+ const good = manifest('p', { frontend: { entry: '/p.js', integrity: `sha384-${digest}` } })
188
+ const { unmount } = render(<Shell manifests={[good]} requireIntegrity />)
189
+ await screen.findByTestId('remote-p')
190
+ unmount()
191
+ __resetRemoteIntegrityCache()
192
+ mf.loadRemote.mockClear()
193
+ const badHash = btoa(String.fromCharCode(...new Uint8Array(48)))
194
+ const bad = manifest('q', { frontend: { entry: '/q.js', integrity: `sha384-${badHash}` } })
195
+ const onEvent = vi.fn()
196
+ render(<Shell manifests={[bad]} requireIntegrity onEvent={onEvent} />)
197
+ await screen.findByTestId('fb-q')
198
+ expect(mf.loadRemote).not.toHaveBeenCalled()
199
+ expect(onEvent).toHaveBeenCalledWith('addon_slot_failed', expect.objectContaining({ addon: 'q', reason: 'load' }))
200
+ })
201
+
202
+ it('timeout_ms 0 o negativo del manifest no anula el timeout del host', async () => {
203
+ vi.useFakeTimers()
204
+ mf.loadRemote.mockImplementation(() => new Promise(() => {}))
205
+ const m = manifest('slow')
206
+ m.contributions!.slots![0].timeout_ms = 0
207
+ render(<Shell manifests={[m]} timeoutMs={2000} />)
208
+ await act(async () => {
209
+ await vi.advanceTimersByTimeAsync(2100)
210
+ })
211
+ expect(screen.getByTestId('fb-slow').textContent).toBe('timeout')
212
+ })
213
+
214
+ it('frontend.sdk incompatible con el SDK del host: fallback y telemetría, sin cargar', async () => {
215
+ const onEvent = vi.fn()
216
+ const m = manifest('old', { frontend: { entry: '/o.js', sdk: '^3.0.0' } })
217
+ render(<Shell manifests={[m]} onEvent={onEvent} sdkVersion="4.1.0" />)
218
+ await screen.findByTestId('fb-old')
219
+ expect(screen.getByTestId('fb-old').textContent).toBe('sdk_incompatible')
220
+ expect(mf.loadRemote).not.toHaveBeenCalled()
221
+ expect(onEvent).toHaveBeenCalledWith('addon_slot_failed', expect.objectContaining({ reason: 'sdk_incompatible' }))
222
+ })
223
+
224
+ it('unifica con el slot store: contribución en proceso ordenada por priority y aislada', async () => {
225
+ mf.loadRemote.mockImplementation(async () => remote('r'))
226
+ const off1 = slotStore.register('invoice.footer', () => <b data-testid="local-hi">hi</b>, { priority: 10, owner: 'localhi' })
227
+ const off2 = slotStore.register(
228
+ 'invoice.footer',
229
+ () => {
230
+ throw new Error('local boom')
231
+ },
232
+ { priority: 1, owner: 'localbad' },
233
+ )
234
+ const onEvent = vi.fn()
235
+ const { container } = render(<Shell manifests={[manifest('r', {}, 0)]} onEvent={onEvent} />)
236
+ await screen.findByTestId('remote-r')
237
+ // order 0 empata: priority desc => localhi(10), r(0 en remoto), localbad(1)... remoto tiene priority 0
238
+ const order = [...container.querySelectorAll('[data-addon-slot-item]')].map((n) => n.getAttribute('data-addon-slot-item'))
239
+ expect(order).toEqual(['localhi', 'localbad', 'r'])
240
+ expect(screen.getByTestId('local-hi')).toBeTruthy()
241
+ expect(screen.getByTestId('fb-localbad')).toBeTruthy()
242
+ expect(screen.getByTestId('shell')).toBeTruthy()
243
+ off1()
244
+ off2()
245
+ })
246
+
247
+ it('sin manifests ni store no pinta nada', () => {
248
+ const { container } = render(<AddonSlot kind="nada" />)
249
+ expect(container.innerHTML).toBe('')
250
+ })
251
+ })
252
+
253
+ describe('sortSlotItems', () => {
254
+ it('order asc, priority desc, inserción estable', () => {
255
+ const r = sortSlotItems([
256
+ { id: 'a', order: 1, priority: 0 },
257
+ { id: 'b', order: 0, priority: 1 },
258
+ { id: 'c', order: 0, priority: 5 },
259
+ { id: 'd', order: 0, priority: 1 },
260
+ ])
261
+ expect(r.map((x) => x.id)).toEqual(['c', 'b', 'd', 'a'])
262
+ })
263
+ })
264
+
265
+ describe('resolveSlotTimeout', () => {
266
+ it('acota a 1000..30000 y cae al host si no es válido', () => {
267
+ expect(resolveSlotTimeout(5, 9000)).toBe(1000)
268
+ expect(resolveSlotTimeout(99999, 9000)).toBe(30000)
269
+ expect(resolveSlotTimeout(8000, 9000)).toBe(8000)
270
+ expect(resolveSlotTimeout(0, 9000)).toBe(9000)
271
+ expect(resolveSlotTimeout(-1, 9000)).toBe(9000)
272
+ expect(resolveSlotTimeout(NaN, 9000)).toBe(9000)
273
+ expect(resolveSlotTimeout('abc', 9000)).toBe(9000)
274
+ expect(resolveSlotTimeout(undefined, 9000)).toBe(9000)
275
+ })
276
+ })
277
+
278
+ describe('satisfiesSdkRange', () => {
279
+ it.each([
280
+ ['4.1.0', '^4.0.0', true],
281
+ ['4.1.0', '^3.0.0', false],
282
+ ['3.18.1', '~3.18', true],
283
+ ['3.19.0', '~3.18.0', false],
284
+ ['3.5.0', '>=3.2 <5', true],
285
+ ['5.0.0', '>=3.2 <5', false],
286
+ ['3.9.9', '3.x', true],
287
+ ['4.0.0', '^3 || ^4', true],
288
+ ['0.2.5', '^0.2.1', true],
289
+ ['0.3.0', '^0.2.1', false],
290
+ ])('%s vs %s => %s', (v, r, want) => {
291
+ expect(satisfiesSdkRange(v, r as string)).toBe(want)
292
+ })
293
+ it('desconocido => null (no bloquea)', () => {
294
+ expect(satisfiesSdkRange(undefined, '^4')).toBeNull()
295
+ expect(satisfiesSdkRange('4.0.0', undefined)).toBeNull()
296
+ expect(satisfiesSdkRange('4.0.0', 'latest')).toBeNull()
297
+ expect(satisfiesSdkRange('4.0.0', '1.0.0 - 2.0.0')).toBeNull()
298
+ })
299
+ })
@@ -0,0 +1,34 @@
1
+ // @vitest-environment happy-dom
2
+ // Regresion de <Slot> (API historica): no cambia al existir <AddonSlot>.
3
+ import { describe, expect, it, vi } from 'vitest'
4
+ import { render, screen } from '@testing-library/react'
5
+ import { Slot, slotRegistry } from '../slot'
6
+
7
+ describe('<Slot> legacy', () => {
8
+ it('esparce props tal cual, incluso una clave llamada "props", sin wrapper', () => {
9
+ const name = `legacy.props.${Math.random()}`
10
+ const C = (p: any) => <b data-testid="c">{String(p.props)}|{String(p.x)}</b>
11
+ const off = slotRegistry.register(name, C)
12
+ const { container } = render(<Slot name={name} props={{ props: 'a', x: 1 }} />)
13
+ expect(screen.getByTestId('c').textContent).toBe('a|1')
14
+ expect(container.firstElementChild?.tagName).toBe('B')
15
+ off()
16
+ })
17
+
18
+ it('un error de render NO se traga (se propaga como siempre)', () => {
19
+ const name = `legacy.err.${Math.random()}`
20
+ const Boom = () => {
21
+ throw new Error('boom')
22
+ }
23
+ const off = slotRegistry.register(name, Boom)
24
+ const spy = vi.spyOn(console, 'error').mockImplementation(() => {})
25
+ expect(() => render(<Slot name={name} />)).toThrow('boom')
26
+ spy.mockRestore()
27
+ off()
28
+ })
29
+
30
+ it('sin contribuciones pinta el fallback', () => {
31
+ render(<Slot name={`legacy.none.${Math.random()}`} fallback={<i data-testid="fb" />} />)
32
+ expect(screen.getByTestId('fb')).toBeTruthy()
33
+ })
34
+ })
package/src/index.ts CHANGED
@@ -334,6 +334,7 @@ export {
334
334
  type AddonLayoutProviderProps,
335
335
  } from './addon-layout-context'
336
336
  export * from './slot'
337
+ export * from './slots'
337
338
  export * from './capability-gate'
338
339
  export {
339
340
  PermissionsProvider,
@@ -101,6 +101,11 @@ export interface ConnectorCredentialField {
101
101
  /** Shown only while a sibling credential has this value (kernel Setting.visible_when). */
102
102
  visible_when?: VisibleWhen
103
103
  visibleWhen?: VisibleWhen
104
+ /**
105
+ * Kernel Setting.auto: the HOST generates this secret (e.g. "storefront_bearer"),
106
+ * so the form never asks for it; the surface shows its state and "Rotar".
107
+ */
108
+ auto?: string
104
109
  }
105
110
 
106
111
  export interface ConnectorFormLayoutSection {
@@ -129,6 +134,8 @@ export interface ConnectorEntry {
129
134
  status?: string
130
135
  resources?: string[]
131
136
  credentials?: ConnectorCredentialField[]
137
+ /** State of each host-generated credential: generated | manual | missing. */
138
+ auto_credentials?: Record<string, 'generated' | 'manual' | 'missing' | string>
132
139
  form_layout?: ConnectorFormLayout
133
140
  test_export?: string
134
141
  // ops-native connectors (e.g. `hub`) expose a route "Sincronizar ahora" POSTs to.
@@ -629,7 +636,28 @@ export function AddonConfigSurface({
629
636
  if (!open) clearConnectorLookupCache()
630
637
  }, [open])
631
638
 
632
- const credFields = connector?.credentials ?? []
639
+ const allCredFields = connector?.credentials ?? []
640
+ // Host-generated credentials (auto) are never asked from a person.
641
+ const credFields = allCredFields.filter((f) => !f.auto)
642
+ const autoFields = allCredFields.filter((f) => !!f.auto)
643
+ const [autoState, setAutoState] = useState<Record<string, string>>({})
644
+ const [revealedOnce, setRevealedOnce] = useState<Record<string, string>>({})
645
+ const [rotating, setRotating] = useState<string | null>(null)
646
+ const autoStateOf = (k: string) => autoState[k] ?? connector?.auto_credentials?.[k] ?? 'missing'
647
+ const rotateAuto = async (k: string) => {
648
+ if (!connector) return
649
+ setRotating(k)
650
+ try {
651
+ const res = await api.post(`/integrations/${connector.provider}/auto/${k}/rotate`, {})
652
+ const value = (res as { data?: { data?: { value?: string } } })?.data?.data?.value
653
+ setAutoState((prev) => ({ ...prev, [k]: 'generated' }))
654
+ if (value) setRevealedOnce((prev) => ({ ...prev, [k]: value }))
655
+ } catch {
656
+ toast.error(st('auto.rotate_failed'))
657
+ } finally {
658
+ setRotating(null)
659
+ }
660
+ }
633
661
  // A connector with a form_layout groups its credentials into titled sections
634
662
  // (a light wizard). Fall back to the required/advanced split when absent.
635
663
  const layoutSections = connector?.form_layout?.sections ?? []
@@ -1411,7 +1439,8 @@ export function AddonConfigSurface({
1411
1439
  : 'clean'
1412
1440
 
1413
1441
  const hasAnyBlocks = layoutSections.some((s) => (s.blocks?.length ?? 0) > 0) || extraBlocks.length > 0
1414
- const nothingToConfigure = !hasCredentials && !hasSettings && !isOAuth && !hasAnyBlocks
1442
+ const nothingToConfigure =
1443
+ !hasCredentials && !hasSettings && !isOAuth && !hasAnyBlocks && autoFields.length === 0
1415
1444
  const nothingToSave = !hasCredentials && !hasSettings
1416
1445
 
1417
1446
  return (
@@ -1537,6 +1566,54 @@ export function AddonConfigSurface({
1537
1566
  ) : (
1538
1567
  <>
1539
1568
  {oauthPanel}
1569
+ {/* Credenciales generadas por el host: estado + Rotar, nunca un campo */}
1570
+ {autoFields.length > 0 && (
1571
+ <section className='flex flex-col gap-3' data-testid='auto-credentials'>
1572
+ {autoFields.map((f) => {
1573
+ const state = autoStateOf(f.key)
1574
+ const once = revealedOnce[f.key]
1575
+ return (
1576
+ <div
1577
+ key={f.key}
1578
+ className='flex flex-col gap-2 rounded-md border border-border/60 px-3 py-3'
1579
+ >
1580
+ <div className='flex items-center justify-between gap-2'>
1581
+ <div className='flex flex-col gap-1'>
1582
+ <span className='text-sm font-medium'>
1583
+ {state === 'missing'
1584
+ ? st('auto.needs_action')
1585
+ : state === 'manual'
1586
+ ? st('auto.manual')
1587
+ : st('auto.connected')}
1588
+ </span>
1589
+ <HelpText text={st('auto.help')} />
1590
+ </div>
1591
+ <Button
1592
+ type='button'
1593
+ variant='outline'
1594
+ size='sm'
1595
+ disabled={rotating === f.key || !canManageIssuer}
1596
+ onClick={() => void rotateAuto(f.key)}
1597
+ >
1598
+ {rotating === f.key ? (
1599
+ <Loader2 className='h-4 w-4 animate-spin' />
1600
+ ) : (
1601
+ <RefreshCw className='h-4 w-4' />
1602
+ )}
1603
+ {state === 'missing' ? st('auto.generate') : st('auto.rotate')}
1604
+ </Button>
1605
+ </div>
1606
+ {once && (
1607
+ <div className='flex flex-col gap-1'>
1608
+ <code className='break-all rounded bg-muted px-2 py-1 text-xs'>{once}</code>
1609
+ <HelpText text={st('auto.show_once')} />
1610
+ </div>
1611
+ )}
1612
+ </div>
1613
+ )
1614
+ })}
1615
+ </section>
1616
+ )}
1540
1617
  {/* Credenciales */}
1541
1618
  {hasCredentials && (
1542
1619
  <section className='flex flex-col gap-3'>
@@ -109,6 +109,14 @@ export const SETUP_MESSAGES_ES: Dict = {
109
109
  'oauth.help': 'Este addon se conecta con tu cuenta del proveedor. Te llevamos a su página para autorizarlo.',
110
110
  'oauth.connect': 'Conectar cuenta',
111
111
  'oauth.reconnect': 'Volver a conectar',
112
+ 'auto.connected': 'Conectada automáticamente',
113
+ 'auto.manual': 'Clave manual vigente',
114
+ 'auto.needs_action': 'Requiere acción',
115
+ 'auto.help': 'La clave la genera y guarda el sistema, cifrada. No hay nada que inventar ni pegar.',
116
+ 'auto.rotate': 'Rotar',
117
+ 'auto.generate': 'Generar',
118
+ 'auto.show_once': 'Cópiala ahora: no se vuelve a mostrar. La anterior ya no funciona.',
119
+ 'auto.rotate_failed': 'No se pudo rotar la clave',
112
120
  'empty.title': 'Nada que configurar',
113
121
  'empty.help': 'Este addon funciona sin configuración. Si necesitas cambiar algo, revisa su documentación o abre el addon.',
114
122
  // AddonConfigSurface (same keys the ops host already ships)
@@ -270,6 +278,14 @@ export const SETUP_MESSAGES_EN: Dict = {
270
278
  'installed_addons.configure_title': 'Configure {{name}}',
271
279
  'installed_addons.configure_description': 'Credentials and settings for this addon.',
272
280
  'installed_addons.section_credentials': 'Credentials',
281
+ 'auto.connected': 'Connected automatically',
282
+ 'auto.manual': 'Manual key in use',
283
+ 'auto.needs_action': 'Action required',
284
+ 'auto.help': 'The system generates and stores the key, encrypted. Nothing to invent or paste.',
285
+ 'auto.rotate': 'Rotate',
286
+ 'auto.generate': 'Generate',
287
+ 'auto.show_once': 'Copy it now: it is not shown again. The previous one no longer works.',
288
+ 'auto.rotate_failed': 'Could not rotate the key',
273
289
  'installed_addons.section_settings': 'Settings',
274
290
  'installed_addons.advanced': 'Advanced',
275
291
  'installed_addons.no_settings': 'This addon has nothing to configure.',