Repository navigation
Expand file tree
/
Copy pathuseNavMemberGates.ts
More file actions
593 lines (563 loc) · 27.9 KB
/
Copy pathuseNavMemberGates.ts
File metadata and controls
593 lines (563 loc) · 27.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
/**
* ObjectUI
* Copyright (c) 2024-present ObjectStack Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/**
* The member gates the console's sidebar draws its navigation through, in ONE
* place, so that every console consumer of an app's navigation tree reads the
* same answer (objectui#12426).
*
* ## What a member is shown
*
* An entry is shown to a member when it survives both halves the sidebar
* applies:
*
* - the object-read prune (`withoutUnreadableObjectEntries`, objectui#12109):
* a `type: 'object'` entry whose object the member may not read is dropped,
* with its subtree;
* - `@object-ui/layout`'s item guard, asked per node through
* `hasVisibleNavigationItems([item], …)`: the `visible` expression or
* boolean, `requiredPermissions`, and the `requiresObject` /
* `requiresService` runtime-capability gates. A `group` survives only
* through a child that does.
*
* The callbacks that guard is handed (`evaluateVisibility`, `checkPermission`,
* `checkCapability`) are built here and nowhere else: `UnifiedSidebar` draws
* with them, and the app root's landing (`AppContent`) picks its first entry
* with them. Before this, the sidebar built them inline and the landing applied
* none, so a member was sent to the first SERVED entry even when the sidebar
* hid it from them (objectui#12426), the same family as the mobile tab bar
* (objectui#11362).
*
* ## Readiness
*
* Nothing here waits on its own. The console mounts `MePermissionsProvider`
* above the whole app shell, and it renders its loading fallback, not its
* children, until it holds an answer; so a consumer of this hook never runs on
* an unchecked member. With no permission provider mounted, `can` answers
* `true`, exactly as it does for the sidebar.
*
* The `visible` evaluation is the exception to that "unknown reads as yes", and
* deliberately (objectui#12700): it goes through `evaluateNavigationVisibility`,
* so a predicate the evaluator cannot answer — `current_user.can(...)` where no
* permissions payload is bound, as on a frame with no permission provider —
* withholds its entry and reports once, instead of drawing it for everyone.
* On a frame that mounts no `ExpressionProvider` at all (the Studio, whose bell
* still walks every app's navigation) the entry is withheld the same way, but
* no warning is printed per predicate: nothing there binds `current_user`, so
* the fault says nothing about the predicate (objectstack#25892).
*
* ## An entry's API binding (objectui#13029)
*
* An entry may declare the spec's API `dataSource`
* (`{ provider: 'api', read: { url }, path? }`, `BaseNavItemSchema.dataSource`):
* its `visible` reads the value the binding selects as `data`
* (`data.total == 1`). Only `visible` reads it: not the label, not the target,
* and not the entry's `children`. {@link useNavVisibility} is the one evaluator
* every navigation surface of the shell hands its guard: the sidebar, the
* landing and the command palette through {@link useNavMemberGates}, the
* `nav:menu` block directly. It reads each binding an app's navigation declares
* through `@object-ui/react`'s element reader (`readElementApi`, the request a
* page element's binding makes, with the host's `apiFetch`), so there is no
* second fetch; and in the open the read is asked in (`ElementApiOpenScope`,
* which the console mounts per visit of a history entry), so a page element bound to the
* same read takes the answer this read already holds instead of asking again
* (objectui#13323). An entry is drawn only once its read has answered and its
* `visible` holds over that value: while the read is pending, when it fails,
* when `path` selects nothing, or when the spec refuses the binding, the entry
* is hidden. An entry without the key is evaluated exactly as before, with no
* read and no wait.
*
* ## An app's AI inquiry entry (objectstack#37833)
*
* An `ai:chat` entry (`type: 'component'`, `componentRef` `ai:chat`, ui
* ADR-0057 Amendment A4) opens a page that runs the platform `ask` agent. It
* is shown only to a member who can get an agent: the access-filtered agent
* catalog `useAiSurfaceEnabled` reads, which is empty on a deployment with no
* AI and for a member with no AI seat. Every surface whose `visible` evaluator
* is built here (the sidebar, so the phone's app menu; the landing; the
* palette; the `nav:menu` block) hides it the same way, and the landing falls
* to the next entry the member is shown. While the catalog has not answered
* the entry is hidden and reads as pending (`readEntry`), as an entry whose
* API read has not answered does: the landing holds rather than choosing, so
* the root neither opens the page and then leaves it, nor opens the next entry
* and then the page. The catalog is asked only while an app in the list, or
* the app being gated, carries such an entry; with none, nothing is asked and
* nothing changes. A direct link to the page is not gated: the page draws its
* own unavailable state.
*
* Internal module: not re-exported by the package entry.
*/
import { useCallback, useContext, useEffect, useMemo, useState } from 'react';
import { hasVisibleNavigationItems, type NavigationVisibilityOptions } from '@object-ui/layout';
import type { NavigationItem } from '@object-ui/types';
import type { ExpressionEvaluator } from '@object-ui/core';
import {
SchemaRendererContext,
isElementApiDataSourceShape,
judgeElementApiDataSource,
readElementApi,
selectElementApiPath,
useElementApiOpen,
type ApiFetch,
} from '@object-ui/react';
import { usePermissions } from '@object-ui/permissions';
import { AI_CHAT_COMPONENT_REF } from '@objectstack/spec/ui';
import { useAiSurfaceEnabled } from './useAiSurface.js';
import { useMetadata } from '../providers/MetadataProvider.js';
import {
useExpressionContext,
useHasExpressionScope,
evaluateNavigationVisibility,
} from '../providers/ExpressionProvider.js';
import { withoutUnreadableObjectEntries, type ObjectReadCheck } from '../utils/navObjectReadGate.js';
import { filterActiveApps } from '../utils/appRoute.js';
import { appRequiredObjectNames, navigationNames, readObjectPresence } from '../console/appObjectScope.js';
import type { ReadNamesWithoutViews } from './useObjectPresence.js';
const NO_MISSING: readonly string[] = [];
/**
* `readObjectScope` with the provider's package-local `batch: true` hand-off
* beside `views: false` (objectstack#29444, `MetadataProvider`): the names not
* asked yet are asked in one `?names=` request.
*/
type ReadNamesInOneRequest = (
scope: { names: readonly string[]; views: false; batch: true },
) => ReturnType<ReadNamesWithoutViews>;
/** No app requires an object: nothing is gated, and nothing is asked. */
const NO_REQUIRED_OBJECTS = Object.freeze({ objects: [] as readonly unknown[], missing: NO_MISSING });
/**
* Every `requiresObject` name the app list carries (objectui#12980): in the
* `navigation` and every `areas[].navigation` of each active app, and of the
* app being rendered (a hidden one is not in the active list). These are all
* the names any consumer of the gate asks it about. Sorted, so the same list
* reads the same names in the same order.
*/
function requiredObjectUnion(apps: unknown, current: Record<string, unknown> | undefined): string[] {
const out = new Set<string>();
const pick = (item: Record<string, unknown>) => item.requiresObject;
const listed = filterActiveApps(Array.isArray(apps) ? (apps as Array<Record<string, unknown>>) : []);
for (const app of current ? [...listed, current] : listed) {
for (const name of navigationNames(app?.navigation, pick)) out.add(name);
const areas: unknown[] = Array.isArray(app?.areas) ? app.areas : [];
for (const area of areas) {
const tree = area && typeof area === 'object' ? (area as { navigation?: unknown }).navigation : undefined;
for (const name of navigationNames(tree, pick)) out.add(name);
}
}
return [...out].sort();
}
/** Where one entry's API binding stands for its `visible` (objectui#13029). */
export type NavEntryDataRead =
| { status: 'absent' }
| { status: 'pending' }
| { status: 'failed' }
| { status: 'ready'; data: unknown };
/** A binding's content: the key its read is shared and remembered under. */
function bindingKey(dataSource: unknown): string {
return JSON.stringify(dataSource);
}
/**
* Every API binding an app's navigation declares, in its `navigation` and every
* `areas[].navigation`, at every group depth: sorted keys, so the same bindings
* read as the same list.
*/
function navBindingKeys(app: unknown): string[] {
const out = new Set<string>();
const visit = (items: unknown): void => {
if (!Array.isArray(items)) return;
for (const item of items) {
if (!item || typeof item !== 'object') continue;
const { dataSource, children } = item as { dataSource?: unknown; children?: unknown };
if (isElementApiDataSourceShape(dataSource)) out.add(bindingKey(dataSource));
visit(children);
}
};
const shape = (app && typeof app === 'object' ? app : {}) as { navigation?: unknown; areas?: unknown };
visit(shape.navigation);
if (Array.isArray(shape.areas)) {
for (const area of shape.areas) {
visit(area && typeof area === 'object' ? (area as { navigation?: unknown }).navigation : undefined);
}
}
return [...out].sort();
}
type SettledRead = { ok: true; data: unknown } | { ok: false };
/**
* Read every API binding `app`'s navigation declares, and answer where a given
* entry's binding stands. Each binding is read once per change of the set,
* through `readElementApi` with the host's `apiFetch` (the page element's
* reader), and its `path` selected with `selectElementApiPath`; a binding the
* spec refuses is judged by `judgeElementApiDataSource` and never read.
*
* Each read is asked in the open the shell is in (objectui#13323), so the page
* that open shows reuses it. A new open does not re-read the navigation's
* bindings: they are read once per change of the set, as before.
*/
function useNavEntryData(app: unknown): (entry: NavigationItem) => NavEntryDataRead {
const context = useContext(SchemaRendererContext);
const doFetch: ApiFetch = context?.apiFetch ?? fetch;
const scope = useElementApiOpen();
const open = scope?.open;
const reads = scope?.reads;
// Keyed on the bindings' CONTENT, never on the identity of the tree that
// holds them (AGENTS.md #10).
const signature = navBindingKeys(app).join('\n');
const [answers, setAnswers] = useState<Record<string, SettledRead>>({});
useEffect(() => {
if (!signature) return;
let cancelled = false;
const settle = (key: string, read: SettledRead) => {
if (!cancelled) setAnswers((prev) => ({ ...prev, [key]: read }));
};
for (const key of signature.split('\n')) {
const judged = judgeElementApiDataSource(JSON.parse(key));
if (judged.status !== 'parsed') continue;
const { read, path } = judged.config;
readElementApi(read.url, doFetch, reads && open !== undefined ? { open, reads } : null).then(
(body) => {
const selected = selectElementApiPath(body, path);
settle(key, selected.found ? { ok: true, data: selected.value } : { ok: false });
},
() => settle(key, { ok: false }),
);
}
return () => {
cancelled = true;
};
// `open` is left out on purpose: a new open does not re-read the set.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [signature, doFetch, reads]);
return useCallback(
(entry: NavigationItem): NavEntryDataRead => {
const dataSource = entry.dataSource;
if (!isElementApiDataSourceShape(dataSource)) return { status: 'absent' };
if (judgeElementApiDataSource(dataSource).status !== 'parsed') return { status: 'failed' };
const answer = answers[bindingKey(dataSource)];
if (!answer) return { status: 'pending' };
return answer.ok ? { status: 'ready', data: answer.data } : { status: 'failed' };
},
[answers],
);
}
/** Is `entry` an app's AI inquiry page (`ai:chat`, ui ADR-0057 Amendment A4)? */
function isAiChatNavEntry(entry: NavigationItem | undefined): boolean {
return (
!!entry &&
entry.type === 'component' &&
(entry as { componentRef?: unknown }).componentRef === AI_CHAT_COMPONENT_REF
);
}
/** Does `items` hold an `ai:chat` entry, at any group depth? */
function treeHasAiChatEntry(items: unknown): boolean {
if (!Array.isArray(items)) return false;
return items.some(
(item) =>
!!item &&
typeof item === 'object' &&
(isAiChatNavEntry(item as NavigationItem) || treeHasAiChatEntry((item as { children?: unknown }).children)),
);
}
/** Does any app of `apps`, or `current`, carry an `ai:chat` entry in its `navigation` or an area's? */
function appsCarryAiChatEntry(apps: unknown, current: unknown): boolean {
const list: unknown[] = Array.isArray(apps) ? [...apps, current] : [current];
return list.some((app) => {
if (!app || typeof app !== 'object') return false;
const { navigation, areas } = app as { navigation?: unknown; areas?: unknown };
if (treeHasAiChatEntry(navigation)) return true;
return (
Array.isArray(areas) &&
areas.some((area) => treeHasAiChatEntry(area && typeof area === 'object' ? (area as { navigation?: unknown }).navigation : undefined))
);
});
}
/** Where the member's agent stands for an `ai:chat` entry (objectstack#37833). */
type AiChatEntryGate = 'pending' | 'shown' | 'hidden';
const AI_CHAT_PENDING: NavEntryDataRead = { status: 'pending' };
/**
* Whether this member is shown an `ai:chat` entry: `shown` when the
* access-filtered agent catalog serves them an agent, `hidden` when it has
* answered with none (no AI on the deployment, no AI seat, or the catalog
* read failed), `pending` until it answers. The catalog is asked only while
* `app` or an app of the list carries such an entry.
*/
function useAiChatEntryGate(app: unknown): AiChatEntryGate {
const { apps } = useMetadata();
const wanted = useMemo(() => appsCarryAiChatEntry(apps, app), [apps, app]);
const { enabled, isLoading } = useAiSurfaceEnabled({ enabled: wanted });
if (enabled) return 'shown';
return isLoading ? 'pending' : 'hidden';
}
/**
* Should this navigation entry be drawn, as far as its `visible` goes? The one
* decision every navigation surface of the shell makes (objectui#13029): an
* entry that declares an API `dataSource` is hidden until its read is `ready`,
* and then its `visible` is evaluated with the selected value bound as `data`;
* any other entry is `evaluateNavigationVisibility`'s answer, as before.
* `scopeBound` is whether the frame mounts an `ExpressionProvider`
* (objectstack#25892): without one, a predicate it cannot answer is withheld
* without a warning of its own.
*/
export function navEntryVisible(
expression: NavigationItem['visible'],
entry: NavigationItem | undefined,
evaluator: ExpressionEvaluator,
readEntry: (entry: NavigationItem) => NavEntryDataRead,
scopeBound: boolean = true,
): boolean {
if (entry && isElementApiDataSourceShape(entry.dataSource)) {
const read = readEntry(entry);
if (read.status !== 'ready') return false;
return evaluateNavigationVisibility(expression, evaluator.withContext({ data: read.data }), scopeBound);
}
return evaluateNavigationVisibility(expression, evaluator, scopeBound);
}
/**
* The `visible` evaluator for `app`'s navigation: {@link navEntryVisible} over
* the shell's expression evaluator and the bindings `app` declares. The sidebar
* and the command palette (through {@link useNavMemberGates}) and the `nav:menu`
* block each build theirs here, so they cannot disagree.
*/
export function useNavVisibility(
app: unknown,
): (expression: NavigationItem['visible'], entry?: NavigationItem) => boolean {
return useNavVisibilityAndReads(app).evaluate;
}
/**
* {@link useNavVisibility}'s evaluator together with the read state it is built
* on, so a consumer that must tell "hidden" from "not answered yet" asks the
* same reads instead of issuing its own (objectui#13097).
*/
function useNavVisibilityAndReads(app: unknown): {
evaluate: (expression: NavigationItem['visible'], entry?: NavigationItem) => boolean;
readEntry: (entry: NavigationItem) => NavEntryDataRead;
} {
const { evaluator } = useExpressionContext();
const scopeBound = useHasExpressionScope();
const readEntryData = useNavEntryData(app);
// objectstack#37833 — an `ai:chat` entry is drawn only for a member who can
// get an agent, and is pending until the catalog says whether they can.
const aiChat = useAiChatEntryGate(app);
const evaluate = useCallback(
(expression: NavigationItem['visible'], entry?: NavigationItem) =>
(aiChat === 'shown' || !isAiChatNavEntry(entry)) &&
navEntryVisible(expression, entry, evaluator, readEntryData, scopeBound),
[evaluator, readEntryData, scopeBound, aiChat],
);
const readEntry = useCallback(
(entry: NavigationItem): NavEntryDataRead =>
aiChat === 'pending' && isAiChatNavEntry(entry) ? AI_CHAT_PENDING : readEntryData(entry),
[readEntryData, aiChat],
);
return { evaluate, readEntry };
}
/** The member's gates, as the sidebar applies them. */
export interface NavMemberGates {
/** The `visible` evaluator handed to `@object-ui/layout`'s item guard. */
evaluateVisibility: NonNullable<NavigationVisibilityOptions['evaluateVisibility']>;
/** The `requiredPermissions` checker handed to the same guard. */
checkPermission: NonNullable<NavigationVisibilityOptions['checkPermission']>;
/** The runtime-capability checker handed to the same guard. */
checkCapability: NonNullable<NavigationVisibilityOptions['checkCapability']>;
/** The object-read verdict the tree is pruned by (objectui#12109). */
can: ObjectReadCheck;
}
/**
* The member's gates, with where each entry's API binding stands
* (objectui#13097): the read state the `visible` evaluator is built on, so the
* app root's landing can tell an entry that is hidden from one whose read has
* not answered yet, without a read of its own. An `ai:chat` entry reads as
* pending while the agent catalog has not answered (objectstack#37833).
*/
export interface NavMemberGatesWithReads extends NavMemberGates {
readEntry: (entry: NavigationItem) => NavEntryDataRead;
}
/**
* The member's gates, built from the providers the console mounts: the
* expression evaluator, `usePermissions()`, and the registered object list.
*
* `forApp` names the app whose navigation is gated when it is not the frame's
* own (objectstack#26892): Home binds no app in its expression scope yet hands
* the palette its host app, whose entries' API bindings and package object
* scope are that app's. Omitted, the frame's app is gated, as before.
*/
export function useNavMemberGates(forApp?: Record<string, unknown>): NavMemberGatesWithReads {
const { app: frameApp } = useExpressionContext();
const app: Record<string, unknown> = forApp ?? frameApp;
// objectui#13029 — the entries of the app this frame renders may bind data.
const { evaluate: evalVis, readEntry } = useNavVisibilityAndReads(app);
// Permission check for nav `requiredPermissions` entries.
//
// Two authored forms:
// - `object:action` → object CRUD gate.
// - bare name → an ADR-0066 system capability, checked against the union of
// the user's permission-set `systemPermissions` (from /me/permissions) —
// the SAME subset rule the server applies to `AppSchema.requiredPermissions`.
// This used to be misread as `can(<name>, 'read')` only, so a nav item
// requiring a capability was hidden even from users whose permission set
// granted it (admins included) — `requiredPermissions` degenerated into a
// "hide from everyone" switch. The object-read fallback stays for nav
// items that gate on a plain object name.
const { can, hasCapabilities } = usePermissions();
const checkPerm = useCallback(
(permissions: string[]) => permissions.every((perm: string) => {
const parts = perm.split(':');
if (parts.length >= 2) {
return can(parts[0], parts[1] as any);
}
return hasCapabilities([perm]) || can(perm, 'read');
}),
[can, hasCapabilities],
);
// Runtime capability gate: hide nav items targeting objects/services
// not registered in this runtime (e.g. cloud-only `sys_app`).
//
// objectui#12811 — inside an app whose served item names its package, and
// while nothing has asked for the whole registry, the gate reads that app's
// object scope (`readObjectScope`): an object the scope holds is registered,
// one the server answered without a definition is not, and any other reads
// as registered, as every object did while the whole list loaded. The gate
// asks for nothing itself: `AppContent` names the objects the app's own
// entries require, so the sidebar's answer is exact, while the bell's
// cross-app roster does not ask another app's objects one by one. Once
// anything has loaded the whole registry, the gate reads it.
//
// objectui#12980 — inside an app whose served item names NO package (an app
// created in the console), on the same condition, the gate reads the
// names-only scope over every `requiresObject` the app list carries, in each
// app's `navigation` and `areas[].navigation`. That is every name any
// consumer gates (the sidebar, the landing, the bell's cross-app roster), so
// each is asked by name and answered exactly as the whole registry answers
// it. A name not answered yet, or whose read failed (objectui#13009: left
// unanswered), shows, as every entry does while the whole list loads or
// after it fails.
//
// objectstack#29121 — outside an app (the home page's feeds, whose roster
// gates every app's navigation) the gate reads the same names-only scope over
// the app list's `requiresObject` union, with `views: false`: it reads which
// objects there are, never their views. It read the whole registry there,
// which the home page then loaded on every visit for these few names. The
// package leg asks without views too: inside an app the bundle answers them
// anyway, and on Home (the palette's gates for its host app) nothing does,
// so composing them read the whole `/meta/view` list.
//
// objectstack#29416 — inside an app with no package the union is asked
// without views as well: the gate reads only which objects there are, and
// the union names other apps' objects, which the app's bundle does not
// hold, so composing them read the whole `/meta/view` list on every route
// of such an app. The route's own objects are composed with their views by
// the route's reader (`AppContent`), not here.
//
// objectstack#29444 — outside an app (a frame whose app has no `name`: the
// home page, a frame that mounts no expression scope) the union is asked in
// ONE `GET /meta/object?names=a,b,c` (`batch: true`, the provider's
// batched names scope), not one by-name read per name. A name the answer
// leaves out is missing, as a by-name 404 was; a read that obtained no
// answer leaves every name unanswered, so each entry shows, as when a
// by-name read failed.
//
// objectstack#34244 — inside an app too: an entry's `requiresObject` is by
// contract a name the host may not register, and a by-name read answered
// such a name 404 on every route. With no package the union is asked in the
// same one `?names=` read. In a packaged app the package's own objects are
// answered by its list, and the app's other required names are asked in the
// presence read the route asks them in (`readObjectPresence`, the same
// names, so one request): the gate hides an entry that read left out, and the
// route asks by name only the ones it answered served.
const metadata = useMetadata();
const packageId = typeof app?._packageId === 'string' && app._packageId ? app._packageId : undefined;
const readObjectScope = metadata.getTypeStatus?.('object') === 'idle' ? metadata.readObjectScope : undefined;
const unionNames = readObjectScope && !packageId ? requiredObjectUnion(metadata.apps, app) : NO_MISSING;
const scope: { objects: readonly unknown[]; missing: readonly string[] } | null = !readObjectScope
? null
: packageId
? (readObjectScope as ReadNamesWithoutViews)({ packageId, views: false })
: unionNames.length === 0
? NO_REQUIRED_OBJECTS
: (readObjectScope as ReadNamesInOneRequest)({ names: unionNames, views: false, batch: true });
const presence =
readObjectScope && packageId
? readObjectPresence(readObjectScope, packageId, appRequiredObjectNames(app)).presence
: NO_REQUIRED_OBJECTS;
const metadataObjects = scope ? scope.objects : metadata.objects;
const missingObjects = scope ? scope.missing : NO_MISSING;
const registeredObjectNames = useMemo(
() =>
new Set<string>(
[...(metadataObjects || []), ...presence.objects].map((o: any) => o?.name).filter(Boolean),
),
[metadataObjects, presence.objects],
);
const missingObjectNames = useMemo(
() => new Set<string>([...missingObjects, ...presence.missing]),
[missingObjects, presence.missing],
);
const checkCap = useCallback(
(kind: 'object' | 'service', name: string): boolean => {
if (kind === 'object') {
if (!readObjectScope) {
if (registeredObjectNames.size === 0) return true;
return registeredObjectNames.has(name);
}
return registeredObjectNames.has(name) || !missingObjectNames.has(name);
}
return true;
},
[registeredObjectNames, missingObjectNames, readObjectScope],
);
return { evaluateVisibility: evalVis, checkPermission: checkPerm, checkCapability: checkCap, can, readEntry };
}
/**
* `items` as this member is shown them: the object-read prune, then every node
* that `@object-ui/layout`'s item guard refuses dropped, at every group depth.
*
* A `separator` is dropped (it is no entry), and an `action` entry is kept: the
* console's sidebar always wires an action dispatcher, so it draws one. A `doc`
* entry is kept as served: the sidebar's doc-readability answer is defence in
* depth behind the server, which already drops an unreadable one
* (objectstack#19790). The console's app-root landing reads these trees and
* does land on a `doc` entry an app's `landing` names (objectstack#28450): it
* opens the in-app docs portal, under the server's audience gate on the doc,
* without the sidebar's doc-readability answer.
*/
export function navEntriesShownToMember(items: NavigationItem[], gates: NavMemberGates): NavigationItem[] {
const guards: NavigationVisibilityOptions = {
evaluateVisibility: gates.evaluateVisibility,
checkPermission: gates.checkPermission,
checkCapability: gates.checkCapability,
hasActionHandler: true,
};
const shown = (list: NavigationItem[]): NavigationItem[] =>
list
.filter((item) => hasVisibleNavigationItems([item], guards))
.map((item) =>
item.type === 'group' && Array.isArray(item.children)
? ({ ...item, children: shown(item.children) } as NavigationItem)
: item,
);
return shown(withoutUnreadableObjectEntries(items, gates.can));
}
/**
* `items` as this member would be shown them if every entry whose API read is
* still pending were shown once it answers (objectui#13097): the same gates as
* {@link navEntriesShownToMember}, except that a pending entry's `visible` is
* not decided yet and keeps it. Every other gate (the object-read prune,
* `requiredPermissions`, the runtime-capability gates, a plain or answered
* `visible`) applies as it does there.
*
* Comparing the two answers tells the app root's landing whether a pending read
* could still change what it chooses: if it cannot, it lands now.
*/
export function navEntriesShownOncePendingReadsShow(
items: NavigationItem[],
gates: NavMemberGatesWithReads,
): NavigationItem[] {
return navEntriesShownToMember(items, {
...gates,
evaluateVisibility: (expression, entry) =>
(entry !== undefined && gates.readEntry(entry).status === 'pending') ||
gates.evaluateVisibility(expression, entry),
});
}