@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
@@ -16,7 +16,7 @@ import { createContext, useContext, useEffect, useId, useRef, useState } from 'r
16
16
  import { useMutation } from '@tanstack/react-query'
17
17
  import { useTranslation } from 'react-i18next'
18
18
  import { toast } from 'sonner'
19
- import { AlertCircle, Cable, Check, Link2, Loader2, RefreshCw, Settings } from 'lucide-react'
19
+ import { AlertCircle, Cable, Check, Eye, EyeOff, Link2, Loader2, Pencil, RefreshCw, Settings, X } from 'lucide-react'
20
20
  import {
21
21
  Badge,
22
22
  Button,
@@ -151,6 +151,12 @@ export interface AddonConfigSurfaceProps {
151
151
  * Default true.
152
152
  */
153
153
  canManageIssuer?: boolean
154
+ /**
155
+ * Owner-only: lets the eye on a stored secret fetch its value on demand
156
+ * (GET /integrations/:provider/values/:key/reveal). Default false: the
157
+ * secret stays write-only and the eye is hidden.
158
+ */
159
+ canRevealSecrets?: boolean
154
160
  /** Active branch (for per-branch settings); null/absent hides the branch picker. */
155
161
  activeBranch?: { id: string; name?: string } | null
156
162
  /** Pulls the addon's own i18n bundle when its labels do not resolve yet. */
@@ -218,12 +224,21 @@ function ConnectorCredentialFieldControl({
218
224
  connected,
219
225
  provider,
220
226
  onChange,
227
+ stored = false,
228
+ onReveal,
229
+ resetKey,
221
230
  }: {
222
231
  field: ConnectorCredentialField
223
232
  value: string
224
233
  connected: boolean
225
234
  provider: string
226
235
  onChange: (value: string) => void
236
+ /** The backend already holds a value for this field (secret or not). */
237
+ stored?: boolean
238
+ /** Fetches a stored secret's value (owner only); absent → no eye while locked. */
239
+ onReveal?: (key: string) => Promise<string>
240
+ /** Changes when the stored values were swapped (environment flipped): relock. */
241
+ resetKey?: string
227
242
  }) {
228
243
  const { t } = useTranslation()
229
244
  const st = useSetupT()
@@ -240,6 +255,55 @@ function ConnectorCredentialFieldControl({
240
255
  : ''
241
256
  const isSecret = isSecretCredential(field)
242
257
  const isDynamic = field.type === 'dynamic_select' || !!field.options_source
258
+ // A stored field opens LOCKED (pencil to edit, eye to view) so a value is
259
+ // never changed by accident; a fresh field is editable straight away.
260
+ const [editing, setEditing] = useState(false)
261
+ const [visible, setVisible] = useState(false)
262
+ const [revealed, setRevealed] = useState<string | null>(null)
263
+ const [revealing, setRevealing] = useState(false)
264
+ const [armed, setArmed] = useState(false)
265
+ const initial = useRef('')
266
+ const locked = stored && !editing
267
+ useEffect(() => {
268
+ setEditing(false)
269
+ setVisible(false)
270
+ setRevealed(null)
271
+ }, [resetKey])
272
+ const canEye = isSecret ? (locked ? !!onReveal : true) : false
273
+ const toggleEye = async () => {
274
+ if (visible) {
275
+ setVisible(false)
276
+ setRevealed(null)
277
+ return
278
+ }
279
+ if (locked && onReveal) {
280
+ setRevealing(true)
281
+ try {
282
+ setRevealed(await onReveal(field.key))
283
+ setVisible(true)
284
+ } catch {
285
+ setRevealed(null)
286
+ } finally {
287
+ setRevealing(false)
288
+ }
289
+ return
290
+ }
291
+ setVisible(true)
292
+ }
293
+ const startEdit = () => {
294
+ initial.current = value
295
+ if (isSecret) onChange('')
296
+ setVisible(false)
297
+ setRevealed(null)
298
+ setArmed(true)
299
+ setEditing(true)
300
+ requestAnimationFrame(() => document.getElementById(`${form.idPrefix}-cred-${field.key}`)?.focus())
301
+ }
302
+ const cancelEdit = () => {
303
+ onChange(initial.current)
304
+ setVisible(false)
305
+ setEditing(false)
306
+ }
243
307
  const error = form.errors[field.key]
244
308
  const mismatch = shapeMismatch(field, value, form.fields)
245
309
  const target = mismatch?.suggestedKey
@@ -282,23 +346,69 @@ function ConnectorCredentialFieldControl({
282
346
  </SelectContent>
283
347
  </Select>
284
348
  ) : (
285
- <Input
286
- id={`${form.idPrefix}-cred-${field.key}`}
287
- type={isSecret ? 'password' : 'text'}
288
- // A secret must never be offered to (or filled by) the browser's
289
- // password manager: "new-password" is the value browsers respect.
290
- autoComplete={isSecret ? 'new-password' : 'off'}
291
- data-1p-ignore={isSecret ? true : undefined}
292
- data-lpignore={isSecret ? 'true' : undefined}
293
- spellCheck={false}
294
- autoCapitalize='off'
295
- aria-invalid={!!error || undefined}
296
- aria-describedby={error ? `${form.idPrefix}-cred-${field.key}-error` : undefined}
297
- className={cn(error && 'border-destructive focus-visible:ring-destructive/40')}
298
- placeholder={connected && isSecret ? '••••••••' : ''}
299
- value={value}
300
- onChange={(e) => onChange(e.target.value)}
301
- />
349
+ <div className='flex items-center gap-1.5'>
350
+ <Input
351
+ id={`${form.idPrefix}-cred-${field.key}`}
352
+ name={`cfg_${field.key}`}
353
+ type={isSecret && !visible ? 'password' : 'text'}
354
+ // Browsers ignore autocomplete=off and fill the text field that
355
+ // precedes a password input; a field stays read-only until the user
356
+ // focuses it (and while locked) so nothing is filled behind their back.
357
+ autoComplete={isSecret ? 'new-password' : 'off'}
358
+ data-1p-ignore
359
+ data-lpignore='true'
360
+ data-form-type='other'
361
+ readOnly={locked || !armed}
362
+ onFocus={() => setArmed(true)}
363
+ spellCheck={false}
364
+ autoCapitalize='off'
365
+ aria-invalid={!!error || undefined}
366
+ aria-describedby={error ? `${form.idPrefix}-cred-${field.key}-error` : undefined}
367
+ className={cn(
368
+ error && 'border-destructive focus-visible:ring-destructive/40',
369
+ locked && 'bg-muted/40 text-muted-foreground',
370
+ )}
371
+ placeholder={(connected || stored) && isSecret ? '••••••••' : ''}
372
+ value={locked && isSecret ? (revealed ?? '') : value}
373
+ onChange={(e) => onChange(e.target.value)}
374
+ />
375
+ {canEye && (
376
+ <Button
377
+ type='button'
378
+ variant='ghost'
379
+ size='icon'
380
+ className='size-9 shrink-0'
381
+ disabled={revealing}
382
+ aria-label={visible ? st('installed_addons.field_hide', { defaultValue: 'Ocultar' }) : st('installed_addons.field_view', { defaultValue: 'Ver' })}
383
+ onClick={() => void toggleEye()}
384
+ >
385
+ {revealing ? <Loader2 className='size-4 animate-spin' /> : visible ? <EyeOff className='size-4' /> : <Eye className='size-4' />}
386
+ </Button>
387
+ )}
388
+ {locked ? (
389
+ <Button
390
+ type='button'
391
+ variant='ghost'
392
+ size='icon'
393
+ className='size-9 shrink-0'
394
+ aria-label={st('installed_addons.field_edit', { defaultValue: 'Editar' })}
395
+ onClick={startEdit}
396
+ >
397
+ <Pencil className='size-4' />
398
+ </Button>
399
+ ) : stored ? (
400
+ <Button
401
+ type='button'
402
+ variant='ghost'
403
+ size='icon'
404
+ className='size-9 shrink-0'
405
+ aria-label={st('installed_addons.field_cancel_edit', { defaultValue: 'Cancelar edición' })}
406
+ onClick={cancelEdit}
407
+ >
408
+ <X className='size-4' />
409
+ </Button>
410
+ ) : null}
411
+ </div>
302
412
  )}
303
413
  {error ? (
304
414
  <p id={`${form.idPrefix}-cred-${field.key}-error`} role='alert' className='text-xs text-destructive'>
@@ -482,6 +592,7 @@ export function AddonConfigSurface({
482
592
  onOpenChange,
483
593
  onSaved,
484
594
  canManageIssuer = true,
595
+ canRevealSecrets = false,
485
596
  activeBranch = null,
486
597
  ensureAddonBundle,
487
598
  notify = toast,
@@ -526,6 +637,16 @@ export function AddonConfigSurface({
526
637
  // credentials not saved yet (an action tests what is STORED: it saves first).
527
638
  const [blockResults, setBlockResults] = useState<Record<string, BlockResult | undefined>>({})
528
639
  const [credDirty, setCredDirty] = useState(false)
640
+ // Credential keys the backend already holds (non-secret values + secrets_set).
641
+ const [storedKeys, setStoredKeys] = useState<Set<string>>(new Set())
642
+ // Credentials that differ between sandbox and production (served by /values) and
643
+ // the environment the stored values were loaded for: flipping the selector swaps them.
644
+ const envScoped = useRef<Set<string>>(new Set())
645
+ const loadedEnv = useRef<string | null>(null)
646
+ const envField = credFields.find(
647
+ (f) => f.type === 'select' && ['environment', 'mode', 'env'].includes(f.key),
648
+ )
649
+ const envValue = envField ? (credValues[envField.key] ?? '') : ''
529
650
  const stepHeadingRef = useRef<HTMLHeadingElement>(null)
530
651
  const stepMoved = useRef(false)
531
652
  const setCred = (key: string, val: string) => {
@@ -586,6 +707,9 @@ export function AddonConfigSurface({
586
707
  setFieldErrors({})
587
708
  setBlockResults({})
588
709
  setCredDirty(false)
710
+ setStoredKeys(new Set())
711
+ envScoped.current = new Set()
712
+ loadedEnv.current = null
589
713
  if (!canManageIssuer || !connector?.provider || credFields.length === 0) return
590
714
  let cancelled = false
591
715
  api
@@ -593,6 +717,12 @@ export function AddonConfigSurface({
593
717
  .then((res) => {
594
718
  const stored = (res.data?.data?.values ?? {}) as Record<string, string>
595
719
  if (cancelled) return
720
+ const secretsSet = (res.data?.data?.secrets_set ?? []) as string[]
721
+ envScoped.current = new Set((res.data?.data?.env_scoped ?? []) as string[])
722
+ if (envField) loadedEnv.current = stored[envField.key] ?? ''
723
+ setStoredKeys(
724
+ new Set([...Object.keys(stored).filter((k) => stored[k] !== ''), ...secretsSet]),
725
+ )
596
726
  // Only fields the user has not touched yet.
597
727
  setCredValues((prev) => {
598
728
  const next = { ...prev }
@@ -614,6 +744,37 @@ export function AddonConfigSurface({
614
744
  // eslint-disable-next-line react-hooks/exhaustive-deps
615
745
  }, [open, connector?.provider, canManageIssuer])
616
746
 
747
+ // Sandbox and production keep their own credentials: flipping the selector
748
+ // swaps the environment-scoped fields for the ones stored for that environment
749
+ // (locked when it has them, empty when it does not) instead of making the
750
+ // operator paste every key again. Nothing is saved until «Guardar».
751
+ useEffect(() => {
752
+ if (!open || !envField || !envValue || !canManageIssuer || !connector?.provider) return
753
+ if (loadedEnv.current === null || loadedEnv.current === envValue) return
754
+ let cancelled = false
755
+ api
756
+ .get(`/integrations/${connector.provider}/values?environment=${encodeURIComponent(envValue)}`)
757
+ .then((res) => {
758
+ if (cancelled) return
759
+ const stored = (res.data?.data?.values ?? {}) as Record<string, string>
760
+ const secretsSet = (res.data?.data?.secrets_set ?? []) as string[]
761
+ loadedEnv.current = envValue
762
+ setStoredKeys(new Set([...Object.keys(stored).filter((k) => stored[k] !== ''), ...secretsSet]))
763
+ setCredValues((prev) => {
764
+ const next = { ...prev }
765
+ for (const k of envScoped.current) next[k] = stored[k] ?? ''
766
+ return next
767
+ })
768
+ })
769
+ .catch(() => {
770
+ /* keep what is on screen */
771
+ })
772
+ return () => {
773
+ cancelled = true
774
+ }
775
+ // eslint-disable-next-line react-hooks/exhaustive-deps
776
+ }, [open, envValue])
777
+
617
778
  // Load stored settings values + definitions. The backend returns the
618
779
  // manifest's setting definitions alongside the stored values; fall back to
619
780
  // the manifest we already have so custom (declarative) addons whose lifecycle
@@ -865,12 +1026,32 @@ export function AddonConfigSurface({
865
1026
  )
866
1027
  const canSync = !!connector?.sync_endpoint && !!connector?.connected
867
1028
 
1029
+ const revealSecret = async (key: string) => {
1030
+ try {
1031
+ const res = await api.get(
1032
+ `/integrations/${connector?.provider}/values/${encodeURIComponent(key)}/reveal${
1033
+ envValue ? `?environment=${encodeURIComponent(envValue)}` : ''
1034
+ }`,
1035
+ )
1036
+ return String(res.data?.data?.value ?? '')
1037
+ } catch (err) {
1038
+ notify.error(st('installed_addons.field_reveal_error', { defaultValue: 'No se pudo mostrar el valor.' }))
1039
+ throw err
1040
+ }
1041
+ }
1042
+ const storedProps = (key: string) => ({
1043
+ stored: storedKeys.has(key),
1044
+ resetKey: envValue,
1045
+ onReveal: canRevealSecrets ? revealSecret : undefined,
1046
+ })
1047
+
868
1048
  const renderCred = (f: ConnectorCredentialField) => (
869
1049
  <ConnectorCredentialFieldControl
870
1050
  key={f.key}
871
1051
  field={f}
872
1052
  connected={!!connector?.connected}
873
1053
  provider={connector?.provider ?? ''}
1054
+ {...storedProps(f.key)}
874
1055
  value={credValues[f.key] ?? ''}
875
1056
  onChange={(val) => setCred(f.key, val)}
876
1057
  />
@@ -1298,6 +1479,7 @@ export function AddonConfigSurface({
1298
1479
  field={f}
1299
1480
  connected={!!connector?.connected}
1300
1481
  provider={connector?.provider ?? ''}
1482
+ {...storedProps(f.key)}
1301
1483
  value={credValues[f.key] ?? ''}
1302
1484
  onChange={(val) => setCred(f.key, val)}
1303
1485
  />
@@ -1314,6 +1496,7 @@ export function AddonConfigSurface({
1314
1496
  field={f}
1315
1497
  connected={!!connector?.connected}
1316
1498
  provider={connector?.provider ?? ''}
1499
+ {...storedProps(f.key)}
1317
1500
  value={credValues[f.key] ?? ''}
1318
1501
  onChange={(val) => setCred(f.key, val)}
1319
1502
  />
@@ -1333,6 +1516,7 @@ export function AddonConfigSurface({
1333
1516
  field={f}
1334
1517
  connected={!!connector?.connected}
1335
1518
  provider={connector?.provider ?? ''}
1519
+ {...storedProps(f.key)}
1336
1520
  value={credValues[f.key] ?? ''}
1337
1521
  onChange={(val) => setCred(f.key, val)}
1338
1522
  />
@@ -147,6 +147,11 @@ export const SETUP_MESSAGES_ES: Dict = {
147
147
  'installed_addons.whole_org': 'Toda la organización',
148
148
  'installed_addons.only_branch': 'Solo {{name}}',
149
149
  'installed_addons.secret_stored': 'Hay un valor guardado. Déjalo vacío para conservarlo.',
150
+ 'installed_addons.field_view': 'Ver',
151
+ 'installed_addons.field_hide': 'Ocultar',
152
+ 'installed_addons.field_edit': 'Editar',
153
+ 'installed_addons.field_cancel_edit': 'Cancelar edición',
154
+ 'installed_addons.field_reveal_error': 'No se pudo mostrar el valor.',
150
155
  'common.back': 'Atrás',
151
156
  'common.next': 'Siguiente',
152
157
  'common.cancel': 'Cancelar',
@@ -292,6 +297,11 @@ export const SETUP_MESSAGES_EN: Dict = {
292
297
  'installed_addons.whole_org': 'Whole organization',
293
298
  'installed_addons.only_branch': 'Only {{name}}',
294
299
  'installed_addons.secret_stored': 'A value is stored. Leave it empty to keep it.',
300
+ 'installed_addons.field_view': 'View',
301
+ 'installed_addons.field_hide': 'Hide',
302
+ 'installed_addons.field_edit': 'Edit',
303
+ 'installed_addons.field_cancel_edit': 'Cancel editing',
304
+ 'installed_addons.field_reveal_error': 'Could not show the value.',
295
305
  'common.back': 'Back',
296
306
  'common.next': 'Next',
297
307
  'common.cancel': 'Cancel',
@@ -146,7 +146,9 @@ export function useResolveOptionIds(args: UseResolveOptionIdsArgs): UseResolveOp
146
146
  queries: (active ? list : []).map((id) => ({
147
147
  queryKey: [QUERY_ROOT, scope, url, effectiveField, id],
148
148
  queryFn: () => enqueue(api, scope, url, effectiveField, id),
149
- staleTime: OPTION_IDS_TTL_MS,
149
+ // Unknown identity: nothing may be reused from a previous account.
150
+ staleTime: scope ? OPTION_IDS_TTL_MS : 0,
151
+ ...(scope ? {} : { gcTime: 0 }),
150
152
  retry: false,
151
153
  refetchOnWindowFocus: false,
152
154
  })),
@@ -12,6 +12,7 @@
12
12
  // free; legacy callers that still ship `searchEndpoint` keep working.
13
13
  import { useEffect, useMemo, useRef, useState } from 'react'
14
14
  import { useApi } from './api-context'
15
+ import { cacheScope, onCacheScopeChange } from './cache-scope'
15
16
  import { applyOptionFilter, type OptionFilterRule } from './option-filter'
16
17
  import { loadQueryPart, optionsBatchToken, optionsModelFromUrl } from './query-batch'
17
18
  import type { OptionDisplayData } from './option-display'
@@ -157,6 +158,9 @@ export function invalidateOptionsCache(): void {
157
158
 
158
159
  const invalidationListeners = new Set<() => void>()
159
160
 
161
+ // Options are shaped by who asks (permissions, org): drop them with the scope.
162
+ onCacheScopeChange(() => invalidateOptionsCache())
163
+
160
164
  /** Runs `fn` on every invalidateOptionsCache (id-label lookups drop with it). */
161
165
  export function onOptionsCacheInvalidated(fn: () => void): () => void {
162
166
  invalidationListeners.add(fn)
@@ -200,18 +204,20 @@ function contextKey(context: Record<string, string> | undefined): string {
200
204
  .join('&')
201
205
  }
202
206
 
203
- /** Org + branch of the host session: part of every options cache key. */
207
+ /**
208
+ * `org:user:lang` scope + branch of the host session: part of every options
209
+ * cache key. Empty when the identity is unknown (callers then skip the cache).
210
+ */
204
211
  export function optionsScope(): string {
205
- if (typeof localStorage === 'undefined') return ''
206
- let org = ''
212
+ const scope = cacheScope()
213
+ if (!scope) return ''
214
+ let branch = ''
207
215
  try {
208
- const raw = localStorage.getItem('auth_user')
209
- if (raw) org = String((JSON.parse(raw) as { organization_id?: string }).organization_id ?? '')
216
+ branch = typeof localStorage === 'undefined' ? '' : (localStorage.getItem('active_branch_id') ?? '')
210
217
  } catch {
211
- org = ''
218
+ branch = ''
212
219
  }
213
- const branch = localStorage.getItem('active_branch_id') ?? ''
214
- return `${org}|${branch}`
220
+ return `${scope}|${branch}`
215
221
  }
216
222
 
217
223
  function readOptionsEnvelope(body: any): OptionsPayload {
@@ -285,8 +291,11 @@ export function useOptionsResolver(args: UseOptionsResolverArgs): UseOptionsReso
285
291
  return
286
292
  }
287
293
 
294
+ const askedScope = optionsScope()
295
+ // Unknown identity: no cache, no shared in-flight request.
296
+ const scoped = askedScope !== ''
288
297
  const key = optionsRequestKey(
289
- optionsScope(),
298
+ askedScope,
290
299
  url,
291
300
  effectiveField,
292
301
  query ?? '',
@@ -302,7 +311,7 @@ export function useOptionsResolver(args: UseOptionsResolverArgs): UseOptionsReso
302
311
  }
303
312
  const epoch = optionsEpoch.get(key) ?? 0
304
313
  const generation = optionsGeneration
305
- const cached = optionsCache.get(key)
314
+ const cached = scoped ? optionsCache.get(key) : undefined
306
315
  if (cached && Date.now() - cached.at < OPTIONS_TTL_MS) {
307
316
  setOptions(cached.payload.options)
308
317
  setMeta(cached.payload.meta)
@@ -314,7 +323,7 @@ export function useOptionsResolver(args: UseOptionsResolverArgs): UseOptionsReso
314
323
  setLoading(true)
315
324
  setError(null)
316
325
 
317
- let pending = optionsInflight.get(key)
326
+ let pending = scoped ? optionsInflight.get(key) : undefined
318
327
  if (!pending) {
319
328
  const params: Record<string, string | number> = { field: effectiveField }
320
329
  if (query) params.q = query
@@ -337,13 +346,17 @@ export function useOptionsResolver(args: UseOptionsResolverArgs): UseOptionsReso
337
346
  data: part.data,
338
347
  meta: part.meta,
339
348
  })
340
- if ((optionsEpoch.get(key) ?? 0) === epoch && optionsGeneration === generation) {
349
+ if (scoped && optionsScope() === askedScope && (optionsEpoch.get(key) ?? 0) === epoch && optionsGeneration === generation) {
341
350
  optionsCache.set(key, { payload, at: Date.now() })
342
351
  }
343
352
  return payload
344
353
  } catch (err) {
345
354
  const msg = err instanceof Error ? err.message : ''
346
- const batchMiss = msg === 'batch unavailable' || msg === 'batch part missing'
355
+ const batchMiss =
356
+ msg === 'batch unavailable' ||
357
+ msg === 'batch part missing' ||
358
+ msg === 'batch scope changed' ||
359
+ msg === 'batch cache cleared'
347
360
  if (!batchMiss) throw err
348
361
  }
349
362
  }
@@ -353,14 +366,14 @@ export function useOptionsResolver(args: UseOptionsResolverArgs): UseOptionsReso
353
366
  throw new Error(body?.message || 'options resolver: unsuccessful response')
354
367
  }
355
368
  const payload = readOptionsEnvelope(body)
356
- if ((optionsEpoch.get(key) ?? 0) === epoch && optionsGeneration === generation) {
369
+ if (scoped && optionsScope() === askedScope && (optionsEpoch.get(key) ?? 0) === epoch && optionsGeneration === generation) {
357
370
  optionsCache.set(key, { payload, at: Date.now() })
358
371
  }
359
372
  return payload
360
373
  })().finally(() => {
361
374
  if (optionsInflight.get(key) === pending) optionsInflight.delete(key)
362
375
  })
363
- optionsInflight.set(key, pending)
376
+ if (scoped) optionsInflight.set(key, pending)
364
377
  }
365
378
 
366
379
  let cancelled = false