@asteby/metacore-runtime-react 52.1.0 → 53.0.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.
- package/CHANGELOG.md +18 -0
- package/dist/addon-loader.d.ts +22 -1
- package/dist/addon-loader.d.ts.map +1 -1
- package/dist/addon-loader.js +23 -5
- package/dist/addon-page-host.d.ts +80 -0
- package/dist/addon-page-host.d.ts.map +1 -0
- package/dist/addon-page-host.js +216 -0
- package/dist/addon-page-loader.d.ts +40 -0
- package/dist/addon-page-loader.d.ts.map +1 -0
- package/dist/addon-page-loader.js +87 -0
- package/dist/dynamic-view.d.ts +20 -1
- package/dist/dynamic-view.d.ts.map +1 -1
- package/dist/dynamic-view.js +26 -3
- package/dist/federated-error-boundary.d.ts +46 -0
- package/dist/federated-error-boundary.d.ts.map +1 -0
- package/dist/federated-error-boundary.js +55 -0
- package/dist/host-api.d.ts +22 -0
- package/dist/host-api.d.ts.map +1 -0
- package/dist/host-api.js +113 -0
- package/dist/index.d.ts +6 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +8 -1
- package/dist/testing.d.ts +42 -0
- package/dist/testing.d.ts.map +1 -0
- package/dist/testing.js +53 -0
- package/dist/types.d.ts +13 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/views/calendar-view.d.ts +23 -0
- package/dist/views/calendar-view.d.ts.map +1 -0
- package/dist/views/calendar-view.js +138 -0
- package/dist/views/chart-view.d.ts +14 -0
- package/dist/views/chart-view.d.ts.map +1 -0
- package/dist/views/chart-view.js +77 -0
- package/dist/views/data-source.d.ts +30 -0
- package/dist/views/data-source.d.ts.map +1 -0
- package/dist/views/data-source.js +103 -0
- package/dist/views/index.d.ts +4 -0
- package/dist/views/index.d.ts.map +1 -0
- package/dist/views/index.js +2 -0
- package/dist/views/map-view.d.ts +39 -0
- package/dist/views/map-view.d.ts.map +1 -0
- package/dist/views/map-view.js +143 -0
- package/dist/views/panels.d.ts +13 -0
- package/dist/views/panels.d.ts.map +1 -0
- package/dist/views/panels.js +119 -0
- package/dist/views/registry.d.ts +46 -0
- package/dist/views/registry.d.ts.map +1 -0
- package/dist/views/registry.js +139 -0
- package/dist/views/skeleton.d.ts +5 -0
- package/dist/views/skeleton.d.ts.map +1 -0
- package/dist/views/skeleton.js +6 -0
- package/dist/views/split-view.d.ts +6 -0
- package/dist/views/split-view.d.ts.map +1 -0
- package/dist/views/split-view.js +52 -0
- package/dist/views/timeline-view.d.ts +25 -0
- package/dist/views/timeline-view.d.ts.map +1 -0
- package/dist/views/timeline-view.js +130 -0
- package/dist/views/types.d.ts +87 -0
- package/dist/views/types.d.ts.map +1 -0
- package/dist/views/types.js +1 -0
- package/package.json +16 -4
- package/src/__tests__/addon-page-host.test.tsx +122 -0
- package/src/__tests__/addon-page-loader.test.tsx +201 -0
- package/src/__tests__/declarative-views.test.tsx +351 -0
- package/src/__tests__/host-api.test.ts +87 -0
- package/src/__tests__/index-static-graph.test.ts +18 -0
- package/src/addon-loader.tsx +51 -8
- package/src/addon-page-host.tsx +319 -0
- package/src/addon-page-loader.tsx +203 -0
- package/src/dynamic-view.tsx +61 -3
- package/src/federated-error-boundary.tsx +121 -0
- package/src/host-api.ts +143 -0
- package/src/index.ts +38 -0
- package/src/testing.tsx +108 -0
- package/src/types.ts +13 -0
- package/src/views/calendar-view.tsx +234 -0
- package/src/views/chart-view.tsx +122 -0
- package/src/views/data-source.ts +127 -0
- package/src/views/index.ts +37 -0
- package/src/views/map-view.tsx +217 -0
- package/src/views/panels.tsx +177 -0
- package/src/views/registry.tsx +202 -0
- package/src/views/skeleton.tsx +13 -0
- package/src/views/split-view.tsx +115 -0
- package/src/views/timeline-view.tsx +229 -0
- package/src/views/types.ts +105 -0
|
@@ -0,0 +1,351 @@
|
|
|
1
|
+
// @vitest-environment happy-dom
|
|
2
|
+
//
|
|
3
|
+
// Declarative views (view_type map/timeline/calendar/chart/split) and detail
|
|
4
|
+
// panels: registry by type (lazy), pure mappers each renderer uses, and real
|
|
5
|
+
// renders against an in-memory ViewDataSource. Manifest fragments come from the
|
|
6
|
+
// kernel example (docs/spec/v3/examples/addon-ui-example.json, shipping).
|
|
7
|
+
import { afterEach, describe, expect, it, vi } from 'vitest'
|
|
8
|
+
import { cleanup, render, screen, waitFor } from '@testing-library/react'
|
|
9
|
+
import type { DetailPanel, NavView } from '@asteby/metacore-sdk'
|
|
10
|
+
|
|
11
|
+
vi.mock('react-i18next', () => ({
|
|
12
|
+
useTranslation: () => ({
|
|
13
|
+
t: (k: string, d?: unknown, o?: Record<string, unknown>) => {
|
|
14
|
+
const s = typeof d === 'string' ? d : k
|
|
15
|
+
const vars = (typeof d === 'object' ? d : o) as Record<string, unknown> | undefined
|
|
16
|
+
return s.replace(/\{\{(\w+)\}\}/g, (_, v) => String(vars?.[v] ?? ''))
|
|
17
|
+
},
|
|
18
|
+
}),
|
|
19
|
+
}))
|
|
20
|
+
|
|
21
|
+
class ResizeObserverStub {
|
|
22
|
+
observe() {}
|
|
23
|
+
unobserve() {}
|
|
24
|
+
disconnect() {}
|
|
25
|
+
}
|
|
26
|
+
;(globalThis as any).ResizeObserver = (globalThis as any).ResizeObserver ?? ResizeObserverStub
|
|
27
|
+
|
|
28
|
+
import {
|
|
29
|
+
DeclarativeView,
|
|
30
|
+
DetailPanels,
|
|
31
|
+
hasViewRenderer,
|
|
32
|
+
isDeclarativeViewType,
|
|
33
|
+
preloadViewRenderer,
|
|
34
|
+
registerPanelRenderer,
|
|
35
|
+
registerViewRenderer,
|
|
36
|
+
} from '../views/registry'
|
|
37
|
+
import { createApiViewDataSource, pickItems, resolveCapabilityInput } from '../views/data-source'
|
|
38
|
+
import type { ViewDataSource, ViewRendererProps } from '../views/types'
|
|
39
|
+
import { toTimelineEntries } from '../views/timeline-view'
|
|
40
|
+
import { bucketByDay, monthRange, toCalendarEntries } from '../views/calendar-view'
|
|
41
|
+
import { openInMapHref, rowCoordinates, toMapFeatures, toRoutePoints } from '../views/map-view'
|
|
42
|
+
import { formatStat } from '../views/panels'
|
|
43
|
+
import { hiddenColumnsFor } from '../views/split-view'
|
|
44
|
+
import { resolveViewKind } from '../dynamic-view'
|
|
45
|
+
import type { TableMetadata } from '../types'
|
|
46
|
+
|
|
47
|
+
afterEach(cleanup)
|
|
48
|
+
|
|
49
|
+
const shipments = [
|
|
50
|
+
{ id: 's1', tracking_number: 'TRK-1', carrier: 'dhl', status: 'in_transit', eta: '2026-10-20', dest_lat: 19.43, dest_lng: -99.13 },
|
|
51
|
+
{ id: 's2', tracking_number: 'TRK-2', carrier: 'fedex', status: 'delivered', eta: '2026-10-18', dest_lat: '20.67', dest_lng: '-103.35' },
|
|
52
|
+
{ id: 's3', tracking_number: 'TRK-3', carrier: 'dhl', status: 'created', eta: null, dest_lat: null, dest_lng: null },
|
|
53
|
+
]
|
|
54
|
+
const events = [
|
|
55
|
+
{ id: 'e1', shipment_id: 's1', at: '2026-10-16T10:00:00Z', status: 'picked_up', description: 'Recolectado', lat: 19.4, lng: -99.1 },
|
|
56
|
+
{ id: 'e2', shipment_id: 's1', at: '2026-10-17T09:00:00Z', status: 'in_transit', description: 'En tránsito', lat: 19.9, lng: -100.2 },
|
|
57
|
+
]
|
|
58
|
+
|
|
59
|
+
function memorySource(over: Partial<ViewDataSource> = {}): ViewDataSource & { list: ReturnType<typeof vi.fn> } {
|
|
60
|
+
const list = vi.fn(async (model: string) => {
|
|
61
|
+
if (model === 'ShipmentEvent') return { rows: events, total: events.length }
|
|
62
|
+
return { rows: shipments, total: shipments.length }
|
|
63
|
+
})
|
|
64
|
+
return {
|
|
65
|
+
list,
|
|
66
|
+
record: vi.fn(async (_m: string, id: string) => shipments.find((s) => s.id === id) ?? null),
|
|
67
|
+
chart: vi.fn(async () => ({ series: [{ key: 'dhl', label: 'DHL', value: 2 }] })),
|
|
68
|
+
capability: vi.fn(async () => ({ status: 'in_transit', events })),
|
|
69
|
+
...over,
|
|
70
|
+
} as ViewDataSource & { list: ReturnType<typeof vi.fn> }
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const metadata = {
|
|
74
|
+
title: 'Envíos',
|
|
75
|
+
columns: [
|
|
76
|
+
{ key: 'tracking_number', label: 'Guía' },
|
|
77
|
+
{ key: 'carrier', label: 'Paquetería' },
|
|
78
|
+
{ key: 'status', label: 'Estado' },
|
|
79
|
+
{ key: 'eta', label: 'ETA' },
|
|
80
|
+
{ key: 'cost', label: 'Costo' },
|
|
81
|
+
],
|
|
82
|
+
relations: [{ name: 'events', kind: 'one_to_many', through: 'ShipmentEvent', foreign_key: 'shipment_id' }],
|
|
83
|
+
} as unknown as TableMetadata
|
|
84
|
+
|
|
85
|
+
describe('registry', () => {
|
|
86
|
+
it('knows the declarative types; table/kanban stay with DynamicView', () => {
|
|
87
|
+
for (const t of ['map', 'timeline', 'calendar', 'chart', 'split']) {
|
|
88
|
+
expect(isDeclarativeViewType(t)).toBe(true)
|
|
89
|
+
expect(hasViewRenderer(t)).toBe(true)
|
|
90
|
+
}
|
|
91
|
+
expect(isDeclarativeViewType('table')).toBe(false)
|
|
92
|
+
expect(isDeclarativeViewType('kanban')).toBe(false)
|
|
93
|
+
})
|
|
94
|
+
|
|
95
|
+
it('resolveViewKind needs the view block (hosts that do not serve it keep the table)', () => {
|
|
96
|
+
expect(resolveViewKind('map', { view: { map: { point: { lat: 'a', lng: 'b' } } } })).toBe('declarative')
|
|
97
|
+
expect(resolveViewKind('map', {})).toBe('table')
|
|
98
|
+
expect(resolveViewKind('kanban', null)).toBe('kanban')
|
|
99
|
+
expect(resolveViewKind(undefined, null)).toBe('table')
|
|
100
|
+
})
|
|
101
|
+
|
|
102
|
+
it('preloads a renderer chunk by type and reports unknown ones', async () => {
|
|
103
|
+
await expect(preloadViewRenderer('timeline')).resolves.toBe(true)
|
|
104
|
+
await expect(preloadViewRenderer('gantt')).resolves.toBe(false)
|
|
105
|
+
})
|
|
106
|
+
|
|
107
|
+
it('a maps package can replace the map renderer; restore brings the fallback back', async () => {
|
|
108
|
+
function FakeMap(p: ViewRendererProps<'map'>) {
|
|
109
|
+
return <div data-testid="real-map">{p.model}</div>
|
|
110
|
+
}
|
|
111
|
+
const restore = registerViewRenderer('map', async () => ({ default: FakeMap }))
|
|
112
|
+
const view: NavView = { map: { point: { lat: 'dest_lat', lng: 'dest_lng' } } }
|
|
113
|
+
render(<DeclarativeView viewType="map" view={view} model="Shipment" data={memorySource()} />)
|
|
114
|
+
await waitFor(() => expect(screen.getByTestId('real-map').textContent).toBe('Shipment'))
|
|
115
|
+
restore()
|
|
116
|
+
cleanup()
|
|
117
|
+
render(<DeclarativeView viewType="map" view={view} model="Shipment" data={memorySource()} />)
|
|
118
|
+
await waitFor(() => expect(screen.getByTestId('map-view-fallback')).toBeTruthy())
|
|
119
|
+
})
|
|
120
|
+
|
|
121
|
+
it('unknown type or missing block renders the fallback', () => {
|
|
122
|
+
render(
|
|
123
|
+
<DeclarativeView
|
|
124
|
+
viewType="gantt"
|
|
125
|
+
view={{}}
|
|
126
|
+
model="Shipment"
|
|
127
|
+
data={memorySource()}
|
|
128
|
+
fallback={<p data-testid="table">table</p>}
|
|
129
|
+
/>,
|
|
130
|
+
)
|
|
131
|
+
expect(screen.getByTestId('table')).toBeTruthy()
|
|
132
|
+
})
|
|
133
|
+
})
|
|
134
|
+
|
|
135
|
+
describe('data source helpers', () => {
|
|
136
|
+
it('maps capability input from the record (record.<col> | const:<lit>)', () => {
|
|
137
|
+
expect(
|
|
138
|
+
resolveCapabilityInput({ tracking_number: 'record.tracking_number', carrier: 'const:dhl' }, shipments[0]),
|
|
139
|
+
).toEqual({ tracking_number: 'TRK-1', carrier: 'dhl' })
|
|
140
|
+
expect(() => resolveCapabilityInput({ x: '$record.y' }, {})).toThrow(/unsupported reference/)
|
|
141
|
+
})
|
|
142
|
+
|
|
143
|
+
it('picks the items array by dot path', () => {
|
|
144
|
+
expect(pickItems({ data: { events } }, 'data.events')).toHaveLength(2)
|
|
145
|
+
expect(pickItems({ events: 'nope' }, 'events')).toEqual([])
|
|
146
|
+
})
|
|
147
|
+
|
|
148
|
+
it('default api source speaks the kernel list syntax and the host chart endpoint', async () => {
|
|
149
|
+
const api = {
|
|
150
|
+
get: vi.fn(async () => ({ data: { success: true, data: shipments, meta: { total: 3 } } })),
|
|
151
|
+
post: vi.fn(async () => ({ data: { success: true, data: { value: 3 } } })),
|
|
152
|
+
put: vi.fn(),
|
|
153
|
+
delete: vi.fn(),
|
|
154
|
+
}
|
|
155
|
+
const ds = createApiViewDataSource(api)
|
|
156
|
+
await expect(ds.list('Shipment', { per_page: 5 })).resolves.toEqual({ rows: shipments, total: 3 })
|
|
157
|
+
expect(api.get).toHaveBeenCalledWith('/data/Shipment', { params: { per_page: 5 } })
|
|
158
|
+
await ds.chart({ model: 'Shipment', query: { model: 'Shipment', group_by: 'carrier' } })
|
|
159
|
+
expect(api.post).toHaveBeenCalledWith('/views/chart', expect.objectContaining({ model: 'Shipment' }))
|
|
160
|
+
})
|
|
161
|
+
})
|
|
162
|
+
|
|
163
|
+
describe('pure mappers', () => {
|
|
164
|
+
it('timeline: newest first, status/description/group', () => {
|
|
165
|
+
const entries = toTimelineEntries(events, {
|
|
166
|
+
date_field: 'at',
|
|
167
|
+
title_field: 'description',
|
|
168
|
+
status_field: 'status',
|
|
169
|
+
group_by: 'shipment_id',
|
|
170
|
+
})
|
|
171
|
+
expect(entries.map((e) => e.title)).toEqual(['En tránsito', 'Recolectado'])
|
|
172
|
+
expect(entries[0].status).toBe('in_transit')
|
|
173
|
+
expect(entries[0].group).toBe('s1')
|
|
174
|
+
})
|
|
175
|
+
|
|
176
|
+
it('calendar: month range, entries without start dropped, multi-day spans', () => {
|
|
177
|
+
expect(monthRange(new Date(2026, 1, 10))).toEqual({ first: '2026-02-01', last: '2026-02-28' })
|
|
178
|
+
const entries = toCalendarEntries(
|
|
179
|
+
[...shipments, { id: 'x', tracking_number: 'TRK-X', eta: '2026-10-21', end: '2026-10-23' }],
|
|
180
|
+
{ start_field: 'eta', end_field: 'end', title_field: 'tracking_number', color_by: 'status' },
|
|
181
|
+
)
|
|
182
|
+
expect(entries.map((e) => e.title)).toEqual(['TRK-1', 'TRK-2', 'TRK-X'])
|
|
183
|
+
expect(entries[0].allDay).toBe(true)
|
|
184
|
+
const days = bucketByDay(entries)
|
|
185
|
+
expect(days.get('2026-10-22')?.map((e) => e.title)).toEqual(['TRK-X'])
|
|
186
|
+
expect(days.get('2026-10-20')?.[0].color).toBe('in_transit')
|
|
187
|
+
})
|
|
188
|
+
|
|
189
|
+
it('map: numeric/string coords, invalid rows skipped, GeoJSON points, routes in order', () => {
|
|
190
|
+
const features = toMapFeatures(shipments, {
|
|
191
|
+
point: { lat: 'dest_lat', lng: 'dest_lng' },
|
|
192
|
+
color_by: 'status',
|
|
193
|
+
popup: ['tracking_number', 'carrier'],
|
|
194
|
+
})
|
|
195
|
+
expect(features.map((f) => f.key)).toEqual(['s1', 's2'])
|
|
196
|
+
expect(features[1]).toMatchObject({ lat: 20.67, lng: -103.35, color: 'delivered' })
|
|
197
|
+
expect(features[0].popup).toEqual([
|
|
198
|
+
{ field: 'tracking_number', value: 'TRK-1' },
|
|
199
|
+
{ field: 'carrier', value: 'dhl' },
|
|
200
|
+
])
|
|
201
|
+
expect(rowCoordinates({ g: '{"type":"Point","coordinates":[-99.1,19.4]}' }, undefined, 'g')).toEqual({ lat: 19.4, lng: -99.1 })
|
|
202
|
+
expect(rowCoordinates({ a: 95, b: 0 }, { lat: 'a', lng: 'b' }, undefined)).toBeNull()
|
|
203
|
+
expect(
|
|
204
|
+
toRoutePoints([events[1], events[0]], { relation: 'events', point: { lat: 'lat', lng: 'lng' }, order_by: 'at' }),
|
|
205
|
+
).toEqual([{ lat: 19.4, lng: -99.1 }, { lat: 19.9, lng: -100.2 }])
|
|
206
|
+
expect(openInMapHref(19.4, -99.1)).toContain('mlat=19.4&mlon=-99.1')
|
|
207
|
+
})
|
|
208
|
+
|
|
209
|
+
it('stats: format without computing business values', () => {
|
|
210
|
+
const now = new Date('2026-10-17T12:00:00Z')
|
|
211
|
+
expect(formatStat(1234.5, 'currency', { locale: 'es-MX', currency: 'MXN' })).toMatch(/1,234\.50/)
|
|
212
|
+
expect(formatStat(0.25, 'percent', { locale: 'en-US' })).toBe('25%')
|
|
213
|
+
expect(formatStat('2026-10-20T12:00:00Z', 'relative_date', { locale: 'en-US', now })).toBe('in 3 days')
|
|
214
|
+
expect(formatStat(null, 'number')).toBe('—')
|
|
215
|
+
expect(formatStat('abc', 'number')).toBe('abc')
|
|
216
|
+
})
|
|
217
|
+
|
|
218
|
+
it('split: hides every metadata column not listed', () => {
|
|
219
|
+
expect(hiddenColumnsFor(['a', 'b', 'c'], ['b'])).toEqual(['a', 'c'])
|
|
220
|
+
expect(hiddenColumnsFor(['a', 'b'], undefined)).toEqual([])
|
|
221
|
+
})
|
|
222
|
+
})
|
|
223
|
+
|
|
224
|
+
describe('renderers', () => {
|
|
225
|
+
it('timeline view lists the model rows newest first', async () => {
|
|
226
|
+
const data = memorySource()
|
|
227
|
+
render(
|
|
228
|
+
<DeclarativeView
|
|
229
|
+
viewType="timeline"
|
|
230
|
+
view={{ timeline: { date_field: 'at', title_field: 'description', status_field: 'status' } }}
|
|
231
|
+
model="ShipmentEvent"
|
|
232
|
+
data={data}
|
|
233
|
+
locale="es-MX"
|
|
234
|
+
/>,
|
|
235
|
+
)
|
|
236
|
+
await waitFor(() => expect(screen.getByTestId('timeline')).toBeTruthy())
|
|
237
|
+
expect(screen.getAllByRole('listitem').map((li) => li.textContent)).toEqual([
|
|
238
|
+
expect.stringContaining('En tránsito'),
|
|
239
|
+
expect.stringContaining('Recolectado'),
|
|
240
|
+
])
|
|
241
|
+
expect(data.list).toHaveBeenCalledWith('ShipmentEvent', expect.objectContaining({ sortBy: 'at', order: 'desc' }))
|
|
242
|
+
})
|
|
243
|
+
|
|
244
|
+
it('calendar view requests one month with the RANGE filter', async () => {
|
|
245
|
+
const data = memorySource()
|
|
246
|
+
render(
|
|
247
|
+
<DeclarativeView
|
|
248
|
+
viewType="calendar"
|
|
249
|
+
view={{ calendar: { start_field: 'eta', title_field: 'tracking_number' } }}
|
|
250
|
+
model="Shipment"
|
|
251
|
+
data={data}
|
|
252
|
+
/>,
|
|
253
|
+
)
|
|
254
|
+
await waitFor(() => expect(screen.getByRole('grid')).toBeTruthy())
|
|
255
|
+
const params = data.list.mock.calls[0][1] as Record<string, string>
|
|
256
|
+
expect(params.f_eta).toMatch(/^RANGE:\d{4}-\d{2}-01,\d{4}-\d{2}-\d{2}$/)
|
|
257
|
+
})
|
|
258
|
+
|
|
259
|
+
it('chart view asks the host for the declared query and paints the widget card', async () => {
|
|
260
|
+
const data = memorySource()
|
|
261
|
+
render(
|
|
262
|
+
<DeclarativeView
|
|
263
|
+
viewType="chart"
|
|
264
|
+
view={{ chart: { kind: 'bar', query: { model: 'Shipment', group_by: 'carrier', range: 'last_30_days' } } }}
|
|
265
|
+
model="Shipment"
|
|
266
|
+
metadata={metadata}
|
|
267
|
+
data={data}
|
|
268
|
+
/>,
|
|
269
|
+
)
|
|
270
|
+
await waitFor(() => expect(screen.getByTestId('chart-view').getAttribute('data-kind')).toBe('bar'))
|
|
271
|
+
expect(data.chart).toHaveBeenCalledWith({
|
|
272
|
+
model: 'Shipment',
|
|
273
|
+
query: { model: 'Shipment', group_by: 'carrier', range: 'last_30_days' },
|
|
274
|
+
})
|
|
275
|
+
expect(screen.getByText('Envíos')).toBeTruthy()
|
|
276
|
+
})
|
|
277
|
+
|
|
278
|
+
it('detail panels: stats, relation and capability timeline, each lazy and isolated', async () => {
|
|
279
|
+
const data = memorySource()
|
|
280
|
+
const panels: DetailPanel[] = [
|
|
281
|
+
{ key: 'figures', kind: 'stats', title: 'shipping.panel.figures', stats: { items: [{ field: 'carrier' }, { field: 'cost', format: 'currency' }] } },
|
|
282
|
+
{ key: 'history', kind: 'relation', title: 'shipping.panel.history', relation: { name: 'events', columns: ['status'], limit: 5 } },
|
|
283
|
+
{
|
|
284
|
+
key: 'tracking',
|
|
285
|
+
kind: 'timeline',
|
|
286
|
+
title: 'shipping.panel.tracking',
|
|
287
|
+
span: 'half',
|
|
288
|
+
timeline: {
|
|
289
|
+
date_field: 'at',
|
|
290
|
+
title_field: 'description',
|
|
291
|
+
source: {
|
|
292
|
+
capability: 'commerce.shipping.track',
|
|
293
|
+
input: { tracking_number: 'record.tracking_number', carrier: 'record.carrier' },
|
|
294
|
+
items: 'events',
|
|
295
|
+
},
|
|
296
|
+
},
|
|
297
|
+
},
|
|
298
|
+
{ key: 'mystery', kind: 'custom', title: 'x', expose: './panels/x' },
|
|
299
|
+
]
|
|
300
|
+
render(<DetailPanels model="Shipment" panels={panels} record={shipments[0]} metadata={metadata} data={data} />)
|
|
301
|
+
await waitFor(() => expect(screen.getByTestId('stats-panel')).toBeTruthy())
|
|
302
|
+
await waitFor(() => expect(screen.getByTestId('relation-panel')).toBeTruthy())
|
|
303
|
+
await waitFor(() => expect(screen.getByTestId('timeline')).toBeTruthy())
|
|
304
|
+
expect(screen.getByText('Paquetería')).toBeTruthy()
|
|
305
|
+
expect(data.capability).toHaveBeenCalledWith('commerce.shipping.track', { tracking_number: 'TRK-1', carrier: 'dhl' })
|
|
306
|
+
expect(data.list).toHaveBeenCalledWith('ShipmentEvent', { f_shipment_id: 'eq:s1', per_page: 5 })
|
|
307
|
+
// `custom` has no built-in renderer until the host registers one.
|
|
308
|
+
expect(screen.getByTestId('panel-unsupported').textContent).toBe('custom')
|
|
309
|
+
})
|
|
310
|
+
|
|
311
|
+
it('a host-registered custom panel renders; a crashing panel stays contained', async () => {
|
|
312
|
+
const spy = vi.spyOn(console, 'error').mockImplementation(() => {})
|
|
313
|
+
const restoreCustom = registerPanelRenderer('custom', async () => ({
|
|
314
|
+
default: ({ panel }) => <p data-testid="custom-panel">{panel.expose}</p>,
|
|
315
|
+
}))
|
|
316
|
+
const restoreStats = registerPanelRenderer('stats', async () => ({
|
|
317
|
+
default: () => {
|
|
318
|
+
throw new Error('boom')
|
|
319
|
+
},
|
|
320
|
+
}))
|
|
321
|
+
render(
|
|
322
|
+
<DetailPanels
|
|
323
|
+
model="Shipment"
|
|
324
|
+
panels={[
|
|
325
|
+
{ key: 'c', kind: 'custom', title: 'c', expose: './panels/route-planner' },
|
|
326
|
+
{ key: 's', kind: 'stats', title: 's', stats: { items: [{ field: 'cost' }] } },
|
|
327
|
+
]}
|
|
328
|
+
record={shipments[0]}
|
|
329
|
+
data={memorySource()}
|
|
330
|
+
/>,
|
|
331
|
+
)
|
|
332
|
+
await waitFor(() => expect(screen.getByTestId('custom-panel').textContent).toBe('./panels/route-planner'))
|
|
333
|
+
await waitFor(() => expect(screen.getByTestId('federated-error')).toBeTruthy())
|
|
334
|
+
restoreCustom()
|
|
335
|
+
restoreStats()
|
|
336
|
+
spy.mockRestore()
|
|
337
|
+
})
|
|
338
|
+
|
|
339
|
+
it('panel permission hides the panel', () => {
|
|
340
|
+
render(
|
|
341
|
+
<DetailPanels
|
|
342
|
+
model="Shipment"
|
|
343
|
+
panels={[{ key: 's', kind: 'stats', title: 'secret', permission: 'shipping.cost.read', stats: { items: [{ field: 'cost' }] } }]}
|
|
344
|
+
record={shipments[0]}
|
|
345
|
+
data={memorySource()}
|
|
346
|
+
can={() => false}
|
|
347
|
+
/>,
|
|
348
|
+
)
|
|
349
|
+
expect(screen.queryByText('secret')).toBeNull()
|
|
350
|
+
})
|
|
351
|
+
})
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
// createHostApi is the boundary between the host transport (axios with the
|
|
2
|
+
// bearer token in config.headers) and remote code: bodies only, sanitized errors.
|
|
3
|
+
import { describe, expect, it, vi } from 'vitest'
|
|
4
|
+
import { HostApiError } from '@asteby/metacore-sdk'
|
|
5
|
+
import { createHostApi, toHostApiError } from '../host-api'
|
|
6
|
+
import type { ApiClient } from '../api-context'
|
|
7
|
+
|
|
8
|
+
const TOKEN = 'Bearer secret-jwt'
|
|
9
|
+
|
|
10
|
+
function axiosLike(): ApiClient & { patch: ApiClient['put'] } {
|
|
11
|
+
const respond = (url: string, data: unknown) =>
|
|
12
|
+
Promise.resolve({
|
|
13
|
+
data,
|
|
14
|
+
headers: { 'x-thing': '1' },
|
|
15
|
+
config: { url, headers: { Authorization: TOKEN } },
|
|
16
|
+
})
|
|
17
|
+
return {
|
|
18
|
+
get: vi.fn((url: string) => respond(url, { success: true, data: [{ id: 1 }] })),
|
|
19
|
+
post: vi.fn((url: string, body?: unknown) => respond(url, { echo: body })),
|
|
20
|
+
put: vi.fn((url: string) => respond(url, { ok: true })),
|
|
21
|
+
patch: vi.fn((url: string) => respond(url, { patched: true })),
|
|
22
|
+
delete: vi.fn((url: string) => respond(url, { deleted: true })),
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
describe('createHostApi', () => {
|
|
27
|
+
it('resolves to the body only (no headers, no config with the token)', async () => {
|
|
28
|
+
const api = createHostApi(axiosLike())
|
|
29
|
+
const body = await api.get('/data/Shipment')
|
|
30
|
+
expect(body).toEqual({ success: true, data: [{ id: 1 }] })
|
|
31
|
+
expect(JSON.stringify(body)).not.toContain('secret-jwt')
|
|
32
|
+
expect(await api.patch('/data/Shipment/1', { a: 1 })).toEqual({ patched: true })
|
|
33
|
+
expect(await api.delete('/data/Shipment/1')).toEqual({ deleted: true })
|
|
34
|
+
})
|
|
35
|
+
|
|
36
|
+
it('forwards params and signal, nothing else', async () => {
|
|
37
|
+
const client = axiosLike()
|
|
38
|
+
const api = createHostApi(client)
|
|
39
|
+
const ctrl = new AbortController()
|
|
40
|
+
await api.get('/data/Shipment', { params: { f_status: 'eq:late' }, signal: ctrl.signal })
|
|
41
|
+
expect(client.get).toHaveBeenCalledWith('/data/Shipment', { params: { f_status: 'eq:late' }, signal: ctrl.signal })
|
|
42
|
+
await api.get('/plain')
|
|
43
|
+
expect(client.get).toHaveBeenLastCalledWith('/plain')
|
|
44
|
+
})
|
|
45
|
+
|
|
46
|
+
it('posts capability queries to the host endpoint', async () => {
|
|
47
|
+
const client = axiosLike()
|
|
48
|
+
const api = createHostApi(client, { capabilityPath: '/caps' })
|
|
49
|
+
const out = await api.capability('commerce.shipping.track', { tracking_number: 'X1' })
|
|
50
|
+
expect(client.post).toHaveBeenCalledWith('/caps', {
|
|
51
|
+
capability: 'commerce.shipping.track',
|
|
52
|
+
input: { tracking_number: 'X1' },
|
|
53
|
+
})
|
|
54
|
+
expect(out).toEqual({ echo: { capability: 'commerce.shipping.track', input: { tracking_number: 'X1' } } })
|
|
55
|
+
})
|
|
56
|
+
|
|
57
|
+
it('is frozen: a remote cannot swap methods for the next remote', () => {
|
|
58
|
+
const api = createHostApi(axiosLike())
|
|
59
|
+
expect(Object.isFrozen(api)).toBe(true)
|
|
60
|
+
})
|
|
61
|
+
|
|
62
|
+
it('re-throws transport errors without config/request (no token leak)', async () => {
|
|
63
|
+
const client = axiosLike()
|
|
64
|
+
client.post = vi.fn(() =>
|
|
65
|
+
Promise.reject({
|
|
66
|
+
message: 'Request failed with status code 422',
|
|
67
|
+
config: { headers: { Authorization: TOKEN } },
|
|
68
|
+
request: { _header: `Authorization: ${TOKEN}` },
|
|
69
|
+
response: { status: 422, data: { message: 'Paquetería inválida', code: 'invalid_carrier' } },
|
|
70
|
+
}),
|
|
71
|
+
)
|
|
72
|
+
const api = createHostApi(client)
|
|
73
|
+
const err = await api.post('/data/Shipment', {}).catch((e) => e)
|
|
74
|
+
expect(err).toBeInstanceOf(HostApiError)
|
|
75
|
+
expect(err.status).toBe(422)
|
|
76
|
+
expect(err.code).toBe('invalid_carrier')
|
|
77
|
+
expect(err.message).toBe('Paquetería inválida')
|
|
78
|
+
expect(JSON.stringify({ ...err, message: err.message })).not.toContain('secret-jwt')
|
|
79
|
+
expect('config' in err).toBe(false)
|
|
80
|
+
})
|
|
81
|
+
|
|
82
|
+
it('maps network errors to status 0', () => {
|
|
83
|
+
const e = toHostApiError(new TypeError('Failed to fetch'))
|
|
84
|
+
expect(e.status).toBe(0)
|
|
85
|
+
expect(e.message).toBe('Network error')
|
|
86
|
+
})
|
|
87
|
+
})
|
|
@@ -58,6 +58,24 @@ describe('runtime-react index static graph', () => {
|
|
|
58
58
|
expect(hit && `${hit[0]} imported from ${hit[1]}`).toBeUndefined()
|
|
59
59
|
})
|
|
60
60
|
|
|
61
|
+
it.each([
|
|
62
|
+
'views/chart-view.tsx',
|
|
63
|
+
'views/timeline-view.tsx',
|
|
64
|
+
'views/calendar-view.tsx',
|
|
65
|
+
'views/split-view.tsx',
|
|
66
|
+
'views/map-view.tsx',
|
|
67
|
+
'views/panels.tsx',
|
|
68
|
+
'testing.tsx',
|
|
69
|
+
])('loads %s lazily (declarative renderers by type, test helpers never)', (file) => {
|
|
70
|
+
expect(seen.has(join(SRC, file))).toBe(false)
|
|
71
|
+
})
|
|
72
|
+
|
|
73
|
+
it('reaches the view registry and the federated page host (light modules)', () => {
|
|
74
|
+
expect(seen.has(join(SRC, 'views/registry.tsx'))).toBe(true)
|
|
75
|
+
expect(seen.has(join(SRC, 'addon-page-loader.tsx'))).toBe(true)
|
|
76
|
+
expect(external.has('@testing-library/react')).toBe(false)
|
|
77
|
+
})
|
|
78
|
+
|
|
61
79
|
it('keeps the recharts-backed module out of the static graph', () => {
|
|
62
80
|
expect(seen.has(join(SRC, 'widgets/charts.tsx'))).toBe(false)
|
|
63
81
|
expect(seen.has(join(SRC, 'widgets/lazy-charts.tsx'))).toBe(true)
|
package/src/addon-loader.tsx
CHANGED
|
@@ -24,7 +24,9 @@ function getMfRuntime(): Promise<MfRuntime> {
|
|
|
24
24
|
return mfRuntime
|
|
25
25
|
}
|
|
26
26
|
import type { AddonAPI, AddonLayout, Registry } from '@asteby/metacore-sdk'
|
|
27
|
+
import { ensureRemoteIntegrity, RemoteIntegrityError } from '@asteby/metacore-sdk'
|
|
27
28
|
import { useDeclareAddonLayout } from './addon-layout-context'
|
|
29
|
+
import { FederatedErrorBoundary, type FederatedErrorInfo } from './federated-error-boundary'
|
|
28
30
|
import {
|
|
29
31
|
composeDisposables,
|
|
30
32
|
disposableFromRegisterResult,
|
|
@@ -80,6 +82,18 @@ export interface AddonLoaderProps {
|
|
|
80
82
|
* — the loader sets the context value via {@link useDeclareAddonLayout}.
|
|
81
83
|
*/
|
|
82
84
|
layout?: AddonLayout
|
|
85
|
+
/**
|
|
86
|
+
* SRI of `remoteEntry.js` (`manifest.frontend.integrity`). When set, the
|
|
87
|
+
* entry is verified before the MF runtime imports it and a mismatch fails
|
|
88
|
+
* the load permanently (no retry). Unset = previous behaviour.
|
|
89
|
+
*/
|
|
90
|
+
integrity?: string
|
|
91
|
+
/**
|
|
92
|
+
* Render errors thrown by `children` (the addon's UI mounted under this
|
|
93
|
+
* fiber) are contained by a {@link FederatedErrorBoundary}; this reports
|
|
94
|
+
* them (ops: reportFrontendIncident).
|
|
95
|
+
*/
|
|
96
|
+
onRenderError?: (error: Error, info: FederatedErrorInfo) => void
|
|
83
97
|
children?: React.ReactNode
|
|
84
98
|
}
|
|
85
99
|
|
|
@@ -108,6 +122,7 @@ function isRuntimeNotReady(e: unknown): boolean {
|
|
|
108
122
|
|
|
109
123
|
/** Transient network / gateway failures while the host API is restarting. */
|
|
110
124
|
function isTransientRemoteLoadError(e: unknown): boolean {
|
|
125
|
+
if (e instanceof RemoteIntegrityError) return false
|
|
111
126
|
if (isRuntimeNotReady(e)) return true
|
|
112
127
|
const msg = e instanceof Error ? e.message : String(e)
|
|
113
128
|
return (
|
|
@@ -134,11 +149,20 @@ async function withRemoteLoadRetry<T>(op: () => T | Promise<T>): Promise<T> {
|
|
|
134
149
|
}
|
|
135
150
|
}
|
|
136
151
|
|
|
137
|
-
|
|
152
|
+
/**
|
|
153
|
+
* Load one exposed module of a federated remote through the MF runtime:
|
|
154
|
+
* verifies `integrity` (SRI) first, (re)registers the remote when its URL
|
|
155
|
+
* changed, then `loadRemote("<scope>/<expose>")`. Transient failures (host
|
|
156
|
+
* boot race, gateway blips) are retried; an integrity mismatch is not.
|
|
157
|
+
* Shared by {@link AddonLoader} (`./register`) and `AddonPageLoader` (pages).
|
|
158
|
+
*/
|
|
159
|
+
export async function loadFederatedModule<T = unknown>(
|
|
138
160
|
scope: string,
|
|
139
161
|
url: string,
|
|
140
162
|
module: string,
|
|
141
|
-
|
|
163
|
+
integrity?: string,
|
|
164
|
+
): Promise<T | null> {
|
|
165
|
+
if (integrity) await withRemoteLoadRetry(() => ensureRemoteIntegrity(url, integrity))
|
|
142
166
|
// Re-register whenever the `?v=` URL changes so a fiber swap actually
|
|
143
167
|
// fetches the new remoteEntry. `force: true` wipes that remote's module
|
|
144
168
|
// cache — without it, loadRemote would keep serving the previous bundle.
|
|
@@ -151,12 +175,19 @@ async function loadAddon(
|
|
|
151
175
|
markRemoteRegistered(scope, url)
|
|
152
176
|
}
|
|
153
177
|
return withRemoteLoadRetry(() =>
|
|
154
|
-
getMfRuntime().then((mf) =>
|
|
155
|
-
mf.loadRemote<AddonRegisterModule>(remoteId(scope, module)),
|
|
156
|
-
),
|
|
178
|
+
getMfRuntime().then((mf) => mf.loadRemote<T>(remoteId(scope, module))),
|
|
157
179
|
)
|
|
158
180
|
}
|
|
159
181
|
|
|
182
|
+
async function loadAddon(
|
|
183
|
+
scope: string,
|
|
184
|
+
url: string,
|
|
185
|
+
module: string,
|
|
186
|
+
integrity?: string,
|
|
187
|
+
): Promise<AddonRegisterModule | null> {
|
|
188
|
+
return loadFederatedModule<AddonRegisterModule>(scope, url, module, integrity)
|
|
189
|
+
}
|
|
190
|
+
|
|
160
191
|
export function AddonLoader({
|
|
161
192
|
scope,
|
|
162
193
|
url,
|
|
@@ -169,6 +200,8 @@ export function AddonLoader({
|
|
|
169
200
|
onReady,
|
|
170
201
|
onError,
|
|
171
202
|
layout,
|
|
203
|
+
integrity,
|
|
204
|
+
onRenderError,
|
|
172
205
|
children,
|
|
173
206
|
}: AddonLoaderProps) {
|
|
174
207
|
const [status, setStatus] = useState<'loading' | 'ready' | 'error'>('loading')
|
|
@@ -189,7 +222,7 @@ export function AddonLoader({
|
|
|
189
222
|
try {
|
|
190
223
|
setStatus('loading')
|
|
191
224
|
if (key) await purgeAddonFrontendCache(key)
|
|
192
|
-
const mod = await loadAddon(scope, url, module)
|
|
225
|
+
const mod = await loadAddon(scope, url, module, integrity)
|
|
193
226
|
if (cancelled) return
|
|
194
227
|
const plugin = resolvePluginExports(mod)
|
|
195
228
|
if (typeof plugin.register !== 'function') {
|
|
@@ -225,7 +258,7 @@ export function AddonLoader({
|
|
|
225
258
|
// api identity is expected to be stable per addon; including it would
|
|
226
259
|
// re-register on every parent render. Fiber identity is (scope, url, module).
|
|
227
260
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
228
|
-
}, [scope, url, module, addonKey, unbindKey, hostRegistry])
|
|
261
|
+
}, [scope, url, module, addonKey, unbindKey, hostRegistry, integrity])
|
|
229
262
|
|
|
230
263
|
if (status === 'loading') return <>{fallback}</>
|
|
231
264
|
if (status === 'error') {
|
|
@@ -236,5 +269,15 @@ export function AddonLoader({
|
|
|
236
269
|
if (onError) return null
|
|
237
270
|
return <div className="text-sm text-red-500">Addon load error: {error?.message}</div>
|
|
238
271
|
}
|
|
239
|
-
return
|
|
272
|
+
if (children === undefined || children === null) return null
|
|
273
|
+
return (
|
|
274
|
+
<FederatedErrorBoundary
|
|
275
|
+
addonKey={addonKey || api.manifest?.key || scope}
|
|
276
|
+
expose={module}
|
|
277
|
+
onError={onRenderError}
|
|
278
|
+
resetKeys={[url]}
|
|
279
|
+
>
|
|
280
|
+
{children}
|
|
281
|
+
</FederatedErrorBoundary>
|
|
282
|
+
)
|
|
240
283
|
}
|