@asteby/metacore-runtime-react 53.0.0 → 53.2.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,215 @@
1
+ // Client side of the backend's cache coherence (metacore-kernel
2
+ // `cachecoherence`): the server keeps one epoch that moves whenever something
3
+ // the UI is derived from changes (addon installed / upgraded / enabled /
4
+ // disabled / uninstalled, server restarted) and tells the browser through
5
+ // `X-Cache-Epoch` on every response and a `CACHE_EPOCH_CHANGED` WebSocket frame.
6
+ //
7
+ // `@asteby/metacore-sdk` owns the comparison (`observeCacheEpoch`,
8
+ // `onCacheEpochChange`, `wireCacheEpochPush`). This package talks to it through
9
+ // the window-event protocol it documents, so neither needs to import the other:
10
+ //
11
+ // "metacore:cache-epoch-observed" { detail: { epoch } } -> report a token
12
+ // "metacore:cache-epoch-changed" { detail: { epoch, previous, source } }
13
+ //
14
+ // What runtime-react adds is what to DROP when the epoch moves: the metadata
15
+ // cache, the read batch (rows, metadata, i18n), the option lists, and the
16
+ // react-query cache.
17
+
18
+ import { useEffect } from 'react'
19
+ import type { QueryClient } from '@tanstack/react-query'
20
+ import { useMetadataCache } from './metadata-cache'
21
+ import { invalidateOptionsCache } from './use-options-resolver'
22
+ import { invalidateQueryBatchAll } from './query-batch'
23
+
24
+ export const CACHE_EPOCH_HEADER = 'x-cache-epoch'
25
+ export const CACHE_EPOCH_OBSERVED_EVENT = 'metacore:cache-epoch-observed'
26
+ export const CACHE_EPOCH_CHANGED_EVENT = 'metacore:cache-epoch-changed'
27
+
28
+ /** Report the epoch token of a response (the SDK core compares it). */
29
+ export function reportCacheEpoch(token: unknown): void {
30
+ if (typeof token !== 'string' || !token.trim()) return
31
+ if (typeof window === 'undefined' || typeof window.dispatchEvent !== 'function') return
32
+ try {
33
+ window.dispatchEvent(new CustomEvent(CACHE_EPOCH_OBSERVED_EVENT, { detail: { epoch: token } }))
34
+ } catch {
35
+ /* non-DOM environment */
36
+ }
37
+ }
38
+
39
+ /** Reads the token out of an axios headers bag (plain object or AxiosHeaders). */
40
+ export function epochFromAxiosHeaders(headers: unknown): string | undefined {
41
+ if (!headers || typeof headers !== 'object') return undefined
42
+ const h = headers as { get?: (k: string) => unknown } & Record<string, unknown>
43
+ if (typeof h.get === 'function') {
44
+ const v = h.get(CACHE_EPOCH_HEADER)
45
+ if (typeof v === 'string') return v
46
+ }
47
+ const v = h[CACHE_EPOCH_HEADER] ?? h['X-Cache-Epoch']
48
+ return typeof v === 'string' ? v : undefined
49
+ }
50
+
51
+ export interface CacheEpochChange {
52
+ epoch: string
53
+ previous: string | null
54
+ source: 'header' | 'push' | 'event'
55
+ }
56
+
57
+ /** Subscribe to "the epoch moved". Returns the unsubscribe fn. */
58
+ export function onCacheEpochChanged(listener: (change: CacheEpochChange) => void): () => void {
59
+ if (typeof window === 'undefined' || typeof window.addEventListener !== 'function') return () => {}
60
+ const handler = (e: Event) => listener((e as CustomEvent<CacheEpochChange>).detail)
61
+ window.addEventListener(CACHE_EPOCH_CHANGED_EVENT, handler)
62
+ return () => window.removeEventListener(CACHE_EPOCH_CHANGED_EVENT, handler)
63
+ }
64
+
65
+ /**
66
+ * Drops every cache this package derives from installed addons: table/modal
67
+ * metadata, the read batch (rows, metadata, i18n) and the option lists. Mounted
68
+ * components refetch on their next render/mount.
69
+ */
70
+ export function dropAddonDerivedCaches(): void {
71
+ useMetadataCache.getState().clearAll()
72
+ invalidateQueryBatchAll()
73
+ invalidateOptionsCache()
74
+ }
75
+
76
+ /**
77
+ * Query keys that belong to the shell rather than to one addon: the installed
78
+ * list, manifests, navigation, permissions, capabilities, metadata, i18n. An
79
+ * addon change can alter any of them.
80
+ */
81
+ export const SHELL_QUERY_ROOTS: readonly string[] = [
82
+ 'marketplace',
83
+ 'metacore',
84
+ 'manifests',
85
+ 'navigation',
86
+ 'sidebar',
87
+ 'permissions',
88
+ 'capabilities',
89
+ 'metadata',
90
+ 'i18n',
91
+ 'installed-addons',
92
+ 'addons',
93
+ ]
94
+
95
+ function keyStrings(key: readonly unknown[]): string[] {
96
+ const out: string[] = []
97
+ const walk = (v: unknown, depth: number) => {
98
+ if (depth > 4 || v == null) return
99
+ if (typeof v === 'string') out.push(v)
100
+ else if (Array.isArray(v)) v.forEach((x) => walk(x, depth + 1))
101
+ else if (typeof v === 'object') Object.values(v as Record<string, unknown>).forEach((x) => walk(x, depth + 1))
102
+ }
103
+ walk(key, 0)
104
+ return out
105
+ }
106
+
107
+ /** True when a react-query key refers to `addonKey` (exact or `<key>.`, `<key>:`, `<key>/` prefixed). */
108
+ export function queryKeyBelongsToAddon(queryKey: readonly unknown[], addonKey: string): boolean {
109
+ if (!addonKey) return false
110
+ return keyStrings(queryKey).some(
111
+ (s) =>
112
+ s === addonKey ||
113
+ s.startsWith(`${addonKey}.`) ||
114
+ s.startsWith(`${addonKey}:`) ||
115
+ s.startsWith(`${addonKey}/`) ||
116
+ s.includes(`/${addonKey}/`) ||
117
+ s.endsWith(`/${addonKey}`),
118
+ )
119
+ }
120
+
121
+ /**
122
+ * Invalidate every query that depends on an addon: the ones whose key mentions
123
+ * it, plus the shell roots (installed list, manifests, navigation, permissions,
124
+ * metadata...). Call after install / upgrade / enable / disable / uninstall.
125
+ * Resolves when the refetches of the active queries settle.
126
+ */
127
+ export function invalidateAddonQueries(
128
+ queryClient: Pick<QueryClient, 'invalidateQueries'>,
129
+ addonKey: string,
130
+ options: { extraRoots?: readonly string[] } = {},
131
+ ): Promise<void> {
132
+ const roots = new Set([...SHELL_QUERY_ROOTS, ...(options.extraRoots ?? [])])
133
+ return queryClient.invalidateQueries({
134
+ predicate: (query) => {
135
+ const key = query.queryKey as readonly unknown[]
136
+ if (queryKeyBelongsToAddon(key, addonKey)) return true
137
+ const root = key[0]
138
+ return typeof root === 'string' && roots.has(root)
139
+ },
140
+ })
141
+ }
142
+
143
+ export interface UseCacheEpochSyncOptions {
144
+ /** When given, the react-query cache is invalidated too. */
145
+ queryClient?: Pick<QueryClient, 'invalidateQueries'>
146
+ /** Extra work on a change (re-prefetch metadata, reload manifests, ...). */
147
+ onChange?: (change: CacheEpochChange) => void
148
+ }
149
+
150
+ /**
151
+ * Mount once high in the tree. When the server's cache epoch moves, every
152
+ * runtime cache derived from installed addons is dropped and react-query is
153
+ * invalidated, so the open tab stops showing the previous world.
154
+ *
155
+ * useCacheEpochSync({ queryClient })
156
+ * useCacheEpochPush(ws) // from @asteby/metacore-sdk/react, optional
157
+ */
158
+ export function useCacheEpochSync({ queryClient, onChange }: UseCacheEpochSyncOptions = {}): void {
159
+ useEffect(
160
+ () =>
161
+ onCacheEpochChanged((change) => {
162
+ dropAddonDerivedCaches()
163
+ void queryClient?.invalidateQueries()
164
+ onChange?.(change)
165
+ }),
166
+ [queryClient, onChange],
167
+ )
168
+ }
169
+
170
+ // ---------------------------------------------------------------------------
171
+ // Stale server state (mirrors @asteby/metacore-sdk `isStaleStateError`)
172
+ // ---------------------------------------------------------------------------
173
+
174
+ const STALE_PATTERNS = [
175
+ /cached plan must not change result type/i,
176
+ /SQLSTATE\s*0A000/i,
177
+ /prepared statement\s+"?[^"\s]*"?\s+does not exist/i,
178
+ /SQLSTATE\s*26000/i,
179
+ /stale[_ -]?(?:plan|state|epoch)/i,
180
+ ]
181
+
182
+ function collectText(err: unknown, out: string[], depth = 0): void {
183
+ if (err == null || depth > 4) return
184
+ if (typeof err === 'string') {
185
+ out.push(err)
186
+ return
187
+ }
188
+ if (typeof err !== 'object') return
189
+ const o = err as Record<string, unknown>
190
+ for (const k of ['message', 'error', 'code', 'detail', 'details']) {
191
+ const v = o[k]
192
+ if (typeof v === 'string') out.push(v)
193
+ else if (v && typeof v === 'object') collectText(v, out, depth + 1)
194
+ }
195
+ if (o.response) collectText(o.response, out, depth + 1)
196
+ if (o.data) collectText(o.data, out, depth + 1)
197
+ }
198
+
199
+ /**
200
+ * True when an error says the SERVER's cached state was out of date (a prepared
201
+ * plan outdated by a migration, SQLSTATE 0A000 / 26000). Those failures happen
202
+ * before the statement ran, and the server has already dropped the stale state,
203
+ * so one retry is safe and enough.
204
+ */
205
+ export function isStaleStateError(err: unknown): boolean {
206
+ const texts: string[] = []
207
+ collectText(err, texts)
208
+ return texts.some((t) => STALE_PATTERNS.some((re) => re.test(t)))
209
+ }
210
+
211
+ /** Marker on a request config that already had its one stale-state retry. */
212
+ export const STALE_RETRIED_FLAG = '__metacoreStaleRetried'
213
+
214
+ /** Pause before the retry, ms. */
215
+ export const STALE_RETRY_DELAY_MS = 200
@@ -100,3 +100,51 @@ export function localizeFieldLabel(
100
100
  if (!CATALOG_KEY_RE.test(label)) return label
101
101
  return translateMetadataLabel(label, translate)
102
102
  }
103
+
104
+ /** An option as the table cell paints it (`labelKey` is the unresolved catalog key the host could not translate). */
105
+ export interface CellOption {
106
+ value: string | boolean
107
+ label: string
108
+ labelKey?: string
109
+ icon?: string
110
+ color?: string
111
+ }
112
+
113
+ /**
114
+ * The options a table cell must use to paint an enum/status value, so the cell
115
+ * never shows the raw value («Ready») when a translated label exists:
116
+ *
117
+ * 1. the column's own `options`, or — for the model's stage column
118
+ * (`stage_field`) with none — the `stages[]` labels (Listo, Cumplido…);
119
+ * 2. every label is resolved: an unresolved catalog key (`labelKey`, or a
120
+ * label that is itself a key) goes through the client catalog and, failing
121
+ * that, is humanized. A human label is returned untouched.
122
+ *
123
+ * Returns undefined when there is nothing to paint from (the cell then
124
+ * humanizes the token as its last resort).
125
+ */
126
+ export function resolveColumnOptions(args: {
127
+ columnKey: string
128
+ options?: CellOption[]
129
+ stages?: { key: string; label?: string; color?: string }[]
130
+ stageField?: string
131
+ translate?: MetadataTranslator
132
+ }): CellOption[] | undefined {
133
+ const { columnKey, options, stages, stageField, translate } = args
134
+ let base: CellOption[] | undefined = options && options.length > 0 ? options : undefined
135
+ if (!base && stageField && columnKey === stageField && stages && stages.length > 0) {
136
+ base = stages
137
+ .filter((st) => st && st.key)
138
+ .map((st) => ({ value: st.key, label: st.label || '', color: st.color }))
139
+ }
140
+ if (!base) return undefined
141
+ return base.map((opt) => {
142
+ const source = opt.labelKey || opt.label
143
+ const label = opt.labelKey
144
+ ? translateMetadataLabel(opt.labelKey, translate)
145
+ : opt.label
146
+ ? localizeFieldLabel(opt.label, translate)
147
+ : humanizeToken(String(opt.value))
148
+ return source === label && !opt.labelKey ? opt : { ...opt, label }
149
+ })
150
+ }
@@ -40,7 +40,7 @@ import {
40
40
  import { Progress } from './dialogs/_primitives'
41
41
  import { useSystemActor } from './org-runtime-context'
42
42
  import { AuthorshipCell, hasSpecialAuthorship } from './provenance'
43
- import { humanizeToken, translateMetadataLabel } from './dynamic-columns-helpers'
43
+ import { humanizeToken, resolveColumnOptions, translateMetadataLabel } from './dynamic-columns-helpers'
44
44
  import { objectLabel } from './dynamic-relation-helpers'
45
45
  import {
46
46
  OptionBadge,
@@ -1004,10 +1004,33 @@ export function makeDefaultGetDynamicColumns(
1004
1004
  },
1005
1005
  ]
1006
1006
 
1007
- metadata.columns.forEach((col) => {
1007
+ const stageField = lifecycleStageField(metadata)
1008
+ metadata.columns.forEach((rawCol) => {
1008
1009
  // Honors both the legacy `hidden` boolean and the kernel's
1009
1010
  // `visibility` scope (skips `'modal'` and `'list'`).
1010
- if (!isColumnVisibleInTable(col)) return
1011
+ if (!isColumnVisibleInTable(rawCol)) return
1012
+
1013
+ // Enum/status cells paint from translated option labels: the
1014
+ // column's own options, or the stage labels for the stage column
1015
+ // («Listo», not the humanized raw value «Ready»).
1016
+ const resolvedOptions = resolveColumnOptions({
1017
+ columnKey: rawCol.key,
1018
+ options: rawCol.options as any,
1019
+ stages: metadata.stages,
1020
+ stageField,
1021
+ translate: t,
1022
+ })
1023
+ const fromStages = !!resolvedOptions && !(rawCol.options && rawCol.options.length > 0)
1024
+ const col: typeof rawCol = resolvedOptions
1025
+ ? {
1026
+ ...rawCol,
1027
+ options: resolvedOptions as any,
1028
+ // A stage column served as plain text paints as a status badge.
1029
+ ...(fromStages && !rawCol.cellStyle && (!rawCol.type || rawCol.type === 'text')
1030
+ ? { type: 'status' as any }
1031
+ : {}),
1032
+ } as typeof rawCol
1033
+ : rawCol
1011
1034
 
1012
1035
  const translatedLabel = translateMetadataLabel(col.label, t)
1013
1036
  const filterConfig = filterConfigs?.get(col.key)
package/src/host-api.ts CHANGED
@@ -81,15 +81,37 @@ function toConfig(opts?: HostApiRequestOptions): Record<string, unknown> | undef
81
81
  const config: Record<string, unknown> = {}
82
82
  if (opts.params) config.params = opts.params
83
83
  if (opts.signal) config.signal = opts.signal
84
+ if (opts.responseType === 'blob') config.responseType = 'blob'
84
85
  return config
85
86
  }
86
87
 
87
- async function bodyOf<T>(p: Promise<{ data: unknown }>): Promise<T> {
88
+ // With `responseType: 'blob'` axios also delivers the error body as a Blob.
89
+ // Decode it back to JSON so `code`/`message` survive; non-JSON bodies are dropped.
90
+ async function decodeBlobError(e: unknown): Promise<unknown> {
91
+ const resp = (e as AxiosLikeError | null)?.response
92
+ if (!resp || typeof Blob === 'undefined' || !(resp.data instanceof Blob)) return e
93
+ let data: unknown
94
+ try {
95
+ data = JSON.parse(await resp.data.text())
96
+ } catch {
97
+ data = undefined
98
+ }
99
+ return { ...(e as object), response: { ...resp, data } }
100
+ }
101
+
102
+ async function bodyOf<T>(p: Promise<{ data: unknown }>, opts?: HostApiRequestOptions): Promise<T> {
88
103
  try {
89
104
  const res = await p
105
+ if (opts?.responseType === 'blob') {
106
+ const d = res.data
107
+ if (typeof Blob !== 'undefined' && d instanceof Blob) return d as T
108
+ // Some transports hand back raw bytes; normalize so callers always get a Blob.
109
+ if (d instanceof ArrayBuffer || ArrayBuffer.isView(d)) return new Blob([d as BlobPart]) as T
110
+ throw new HostApiError('Expected a binary response', 0)
111
+ }
90
112
  return res.data as T
91
113
  } catch (e) {
92
- throw toHostApiError(e)
114
+ throw toHostApiError(opts?.responseType === 'blob' ? await decodeBlobError(e) : e)
93
115
  }
94
116
  }
95
117
 
@@ -106,20 +128,21 @@ export function createHostApi(client: ApiClient, options: CreateHostApiOptions =
106
128
  return Object.freeze({
107
129
  get: <T,>(path: string, opts?: HostApiRequestOptions) => {
108
130
  const args = withConfig([path], opts) as [string, { params?: Record<string, unknown> }?]
109
- return bodyOf<T>(options.batchGets ? batchGet(client, ...args) : client.get(...args))
131
+ const batch = options.batchGets && opts?.responseType !== 'blob'
132
+ return bodyOf<T>(batch ? batchGet(client, ...args) : client.get(...args), opts)
110
133
  },
111
134
  post: <T,>(path: string, body?: unknown, opts?: HostApiRequestOptions) =>
112
- bodyOf<T>(client.post(...(withConfig([path, body], opts) as [string, unknown, unknown?]))),
135
+ bodyOf<T>(client.post(...(withConfig([path, body], opts) as [string, unknown, unknown?])), opts),
113
136
  put: <T,>(path: string, body?: unknown, opts?: HostApiRequestOptions) =>
114
- bodyOf<T>(client.put(...(withConfig([path, body], opts) as [string, unknown, unknown?]))),
137
+ bodyOf<T>(client.put(...(withConfig([path, body], opts) as [string, unknown, unknown?])), opts),
115
138
  patch: <T,>(path: string, body?: unknown, opts?: HostApiRequestOptions) => {
116
139
  if (typeof patch !== 'function') {
117
140
  return Promise.reject(new HostApiError('PATCH is not supported by this host', 0))
118
141
  }
119
- return bodyOf<T>(patch.call(client, ...(withConfig([path, body], opts) as [string, unknown, unknown?])))
142
+ return bodyOf<T>(patch.call(client, ...(withConfig([path, body], opts) as [string, unknown, unknown?])), opts)
120
143
  },
121
144
  delete: <T,>(path: string, opts?: HostApiRequestOptions) =>
122
- bodyOf<T>(client.delete(...(withConfig([path], opts) as [string, unknown?]))),
145
+ bodyOf<T>(client.delete(...(withConfig([path], opts) as [string, unknown?])), opts),
123
146
  q: async <T,>(path: string, opts?: Pick<HostApiRequestOptions, 'params'>): Promise<HostQueryPart<T>> => {
124
147
  try {
125
148
  const url = path.startsWith('/') ? path : `/${path}`
package/src/index.ts CHANGED
@@ -418,6 +418,7 @@ export * from './org-runtime-provider'
418
418
  export * from './navigation-builder'
419
419
  export * from './i18n-provider'
420
420
  export * from './api-context'
421
+ export * from './cache-coherence'
421
422
  export * from './use-addon-settings'
422
423
  export * from './use-edge-device'
423
424
  export * from './use-print-document'
@@ -202,6 +202,16 @@ export function invalidateQueryBatchData(): void {
202
202
  }
203
203
  entityCache.clear()
204
204
  }
205
+ /**
206
+ * Forgets EVERYTHING the batch remembered, metadata and i18n reads included
207
+ * (invalidateQueryBatchData keeps those on purpose: a save does not change
208
+ * them). Used when the cache epoch moves — an addon was installed, upgraded,
209
+ * enabled, disabled or uninstalled — because then they are exactly what is stale.
210
+ */
211
+ export function invalidateQueryBatchAll(): void {
212
+ partCache.clear()
213
+ entityCache.clear()
214
+ }
205
215
  let waiters: Waiter[] = []
206
216
  let timer: ReturnType<typeof setTimeout> | null = null
207
217
  let transport: ApiClient | null = null