@orsetra/shared-ui 1.13.0 → 1.15.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,38 @@
1
+ "use client"
2
+
3
+ import { Info } from "lucide-react"
4
+ import { cn } from "../../lib/utils"
5
+ import { splitDescription } from "../../lib/field-description"
6
+ import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "./tooltip"
7
+
8
+ /**
9
+ * The description of a form field: its summary, and an information icon that shows the whole
10
+ * description on hover or focus when it says more.
11
+ */
12
+ export function FieldDescription({ text, className }: { text?: string | null; className?: string }) {
13
+ if (!text) return null
14
+ const { summary, detail } = splitDescription(text)
15
+ return (
16
+ <p className={cn("text-xs text-ibm-gray-60", className)}>
17
+ {summary}
18
+ {detail && (
19
+ <TooltipProvider delayDuration={150}>
20
+ <Tooltip>
21
+ <TooltipTrigger asChild>
22
+ <button
23
+ type="button"
24
+ aria-label="More about this field"
25
+ className="inline-flex align-text-bottom ml-1 text-ibm-gray-50 hover:text-ibm-blue-60 focus:outline-none focus-visible:text-ibm-blue-60"
26
+ >
27
+ <Info className="h-3.5 w-3.5" />
28
+ </button>
29
+ </TooltipTrigger>
30
+ <TooltipContent side="top" align="start" className="max-w-xs rounded-none text-xs leading-relaxed">
31
+ {detail}
32
+ </TooltipContent>
33
+ </Tooltip>
34
+ </TooltipProvider>
35
+ )}
36
+ </p>
37
+ )
38
+ }
@@ -9,6 +9,7 @@ export { Logo } from './logo'
9
9
  export { UserMenu, type UserMenuItem, type UserMenuConfig } from './user-menu'
10
10
  export { Input } from './input'
11
11
  export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider } from './tooltip'
12
+ export { FieldDescription } from './field-description'
12
13
  export { PageHeader } from './page-header'
13
14
  export { DetailPageHeader, type DetailPageHeaderProps, type DetailPageHeaderTab, type HeaderBreadcrumb } from './detail-page-header'
14
15
  export { ChartContainer, ChartTooltip, ChartTooltipContent, ChartLegend, ChartLegendContent, type ChartConfig } from './chart'
package/index.ts CHANGED
@@ -7,8 +7,10 @@ export * from './lib/config-selection'
7
7
  export * from './lib/environment-context'
8
8
  export * from './lib/environment-controller'
9
9
  export * from './lib/project-requirement'
10
+ export * from './lib/env-services'
10
11
  export * from './lib/quick-access-href'
11
12
  export * from './lib/status-indicator'
13
+ export * from './lib/field-description'
12
14
  export { createPlatformConfigSource, templateFilter, configOfHit, environmentWithTargets, type ConfigSource } from './lib/config-source'
13
15
  export { default as HttpClient, useHttpClient, ApiError } from './lib/http-client'
14
16
 
@@ -0,0 +1,224 @@
1
+ import { applicationReadiness, environmentReadiness, type EnvironmentReadiness, type ReadableStatus } from "./readiness"
2
+ import { ENV_SERVICE_PLACES, PLATFORM_SERVICE_TYPES, envComponentName } from "./places"
3
+
4
+ export interface AppComponents {
5
+ components: { name: string; type?: string; componentType?: string }[]
6
+ appExists: boolean
7
+ }
8
+
9
+ export interface ServiceLocation {
10
+ /** Application the service lives in, or will be created in. */
11
+ appName: string
12
+ /** Whether that application exists. */
13
+ appExists: boolean
14
+ /** Whether the service is configured. */
15
+ exists: boolean
16
+ /** Whether its application holds something to deploy: the service, or what it holds besides. */
17
+ active?: boolean
18
+ /**
19
+ * Its own application, when the service itself lives in the shared one and what it holds
20
+ * besides lives there: both are then to be deployed.
21
+ */
22
+ besidesApp?: string
23
+ /**
24
+ * Whether it is deployed on its own, from its own page, and never with the rest of the
25
+ * environment: what it carries is too sensitive to go out with something else.
26
+ */
27
+ standalone?: boolean
28
+ /** Whether it still lives in an application it shares, from before it had its own. */
29
+ legacy?: boolean
30
+ }
31
+
32
+ const LINK_TYPE = "private-link"
33
+ const LINK_KEY = "link:"
34
+
35
+ /** The application a private link has to itself: one link, one application, deployed alone. */
36
+ export function linkAppName(envName: string, linkName: string): string {
37
+ return `${envName}-link-${linkName}`
38
+ }
39
+
40
+ /** The link an application of an environment is the application of; nothing when it is none. */
41
+ export function linkOfApp(envName: string, appName: string): string | null {
42
+ const prefix = `${envName}-link-`
43
+ return appName.startsWith(prefix) && appName.length > prefix.length ? appName.slice(prefix.length) : null
44
+ }
45
+
46
+ /** What a link is known by among the things an environment deploys. */
47
+ export function linkKey(linkName: string): string {
48
+ return `${LINK_KEY}${linkName}`
49
+ }
50
+
51
+ /** The link a key names; nothing when the key is the one of a service. */
52
+ export function linkOfKey(key: string): string | null {
53
+ return key.startsWith(LINK_KEY) && key.length > LINK_KEY.length ? key.slice(LINK_KEY.length) : null
54
+ }
55
+
56
+ /**
57
+ * Where each link of an environment lives: in its own application, or — for a link made
58
+ * before links had their own — still in the application of the network.
59
+ */
60
+ export function linkLocations(envName: string, existingApps: string[], network: AppComponents): Record<string, ServiceLocation> {
61
+ const locations: Record<string, ServiceLocation> = {}
62
+ for (const appName of existingApps) {
63
+ const linkName = linkOfApp(envName, appName)
64
+ if (linkName) locations[linkKey(linkName)] = { appName, appExists: true, exists: true, standalone: true }
65
+ }
66
+ const shared = envServiceAppName(envName, "network")
67
+ for (const component of network.appExists ? network.components : []) {
68
+ const key = linkKey(component.name)
69
+ if ((component.type ?? component.componentType) !== LINK_TYPE || locations[key]) continue
70
+ locations[key] = { appName: shared, appExists: true, exists: true, standalone: true, legacy: true }
71
+ }
72
+ return locations
73
+ }
74
+
75
+ const POLICY_TYPE = "networkpolicy"
76
+ const POLICY_KEY = "policy:"
77
+
78
+ /** The application a network policy has to itself: one policy, one application, deployed alone. */
79
+ export function policyAppName(envName: string, policyName: string): string {
80
+ return `${envName}-policy-${policyName}`
81
+ }
82
+
83
+ /** The policy an application of an environment is the application of; nothing when it is none. */
84
+ export function policyOfApp(envName: string, appName: string): string | null {
85
+ const prefix = `${envName}-policy-`
86
+ return appName.startsWith(prefix) && appName.length > prefix.length ? appName.slice(prefix.length) : null
87
+ }
88
+
89
+ /** What a policy is known by among the things an environment deploys. */
90
+ export function policyKey(policyName: string): string {
91
+ return `${POLICY_KEY}${policyName}`
92
+ }
93
+
94
+ /** The policy a key names; nothing when the key is the one of a service or of a link. */
95
+ export function policyOfKey(key: string): string | null {
96
+ return key.startsWith(POLICY_KEY) && key.length > POLICY_KEY.length ? key.slice(POLICY_KEY.length) : null
97
+ }
98
+
99
+ /**
100
+ * Where each network policy of an environment lives: in its own application, or — for the
101
+ * rules written when an environment had a single policy — still in the application of the
102
+ * network, or in the one that used to hold every service.
103
+ */
104
+ export function policyLocations(envName: string, existingApps: string[], network: AppComponents, shared: AppComponents): Record<string, ServiceLocation> {
105
+ const locations: Record<string, ServiceLocation> = {}
106
+ for (const appName of existingApps) {
107
+ const policyName = policyOfApp(envName, appName)
108
+ if (policyName) locations[policyKey(policyName)] = { appName, appExists: true, exists: true, standalone: true }
109
+ }
110
+ const older: [string, AppComponents][] = [[envServiceAppName(envName, "network"), network], [sharedEnvAppName(envName), shared]]
111
+ for (const [appName, held] of older) {
112
+ for (const component of held.appExists ? held.components : []) {
113
+ const key = policyKey(component.name)
114
+ if ((component.type ?? component.componentType) !== POLICY_TYPE || locations[key]) continue
115
+ locations[key] = { appName, appExists: true, exists: true, standalone: true, legacy: true }
116
+ }
117
+ }
118
+ return locations
119
+ }
120
+
121
+ export type OpenItemKind = "link" | "policy"
122
+
123
+ /** What a key names when it is not a service: a link or a policy, with its name. */
124
+ export function itemOfKey(key: string): { kind: OpenItemKind; name: string } | null {
125
+ const link = linkOfKey(key)
126
+ if (link !== null) return { kind: "link", name: link }
127
+ const policy = policyOfKey(key)
128
+ return policy !== null ? { kind: "policy", name: policy } : null
129
+ }
130
+
131
+ export function keyOfItem(kind: OpenItemKind, name: string): string {
132
+ return kind === "link" ? linkKey(name) : policyKey(name)
133
+ }
134
+
135
+ export type AppStatus = ReadableStatus
136
+
137
+ export type EnvHealth = "neutral" | "success" | "warning" | "failed"
138
+
139
+ /** Application a service of an environment has to itself. */
140
+ export function envServiceAppName(envName: string, routingKey: string): string {
141
+ return `${envName}-${ENV_SERVICE_PLACES[routingKey]?.appSuffix ?? routingKey}`
142
+ }
143
+
144
+ /** Application that used to hold every service of an environment. */
145
+ export function sharedEnvAppName(envName: string): string {
146
+ return envName
147
+ }
148
+
149
+ /** Every application the services of an environment may live in. */
150
+ export function envAppCandidates(envName: string): string[] {
151
+ return [...PLATFORM_SERVICE_TYPES.map(key => envServiceAppName(envName, key)), sharedEnvAppName(envName)]
152
+ }
153
+
154
+ function holds(app: AppComponents, compName: string): boolean {
155
+ return app.appExists && app.components.some(component => component.name === compName)
156
+ }
157
+
158
+ /**
159
+ * Where a service lives: in its own application, or in the shared one when it was
160
+ * configured there before services were separated. A service not configured yet goes to
161
+ * its own application.
162
+ */
163
+ export function locateService(envName: string, routingKey: string, own: AppComponents, shared: AppComponents): ServiceLocation {
164
+ const compName = envComponentName(envName, routingKey)
165
+ const besides = holdsBesides(routingKey, own)
166
+ if (holds(own, compName)) {
167
+ return { appName: envServiceAppName(envName, routingKey), appExists: true, exists: true, ...(besides ? { active: true } : {}) }
168
+ }
169
+ if (holds(shared, compName)) {
170
+ return {
171
+ appName: sharedEnvAppName(envName), appExists: true, exists: true,
172
+ ...(besides ? { besidesApp: envServiceAppName(envName, routingKey) } : {}),
173
+ }
174
+ }
175
+ return { appName: envServiceAppName(envName, routingKey), appExists: own.appExists, exists: false, ...(besides ? { active: true } : {}) }
176
+ }
177
+
178
+ /** Whether the application of a service holds any of what the service holds besides itself. */
179
+ export function holdsBesides(routingKey: string, own: AppComponents): boolean {
180
+ const types = ENV_SERVICE_PLACES[routingKey]?.holds ?? []
181
+ return own.appExists && own.components.some(component => types.includes(component.type ?? component.componentType ?? ""))
182
+ }
183
+
184
+ /** Whether there is something of a service to deploy. */
185
+ export function isActive(location: ServiceLocation | null | undefined): boolean {
186
+ return !!location && (location.exists || location.active === true)
187
+ }
188
+
189
+ /** The applications of one service that hold something to deploy. */
190
+ export function appsOf(location: ServiceLocation | null | undefined): string[] {
191
+ if (!location || !isActive(location)) return []
192
+ return location.besidesApp && location.besidesApp !== location.appName
193
+ ? [location.appName, location.besidesApp]
194
+ : [location.appName]
195
+ }
196
+
197
+ /** Applications to act on when acting on the whole environment: those holding something to deploy. */
198
+ export function configuredApps(locations: Record<string, ServiceLocation>): string[] {
199
+ return Array.from(new Set(Object.values(locations).flatMap(appsOf)))
200
+ }
201
+
202
+ /** The status of one of the applications a service lives in, as it was last read. */
203
+ export function statusIn<S>(service: (ServiceLocation & { status: S | null; besidesStatus?: S | null }) | null | undefined, appName: string): S | null {
204
+ if (!service) return null
205
+ if (service.appName === appName) return service.status
206
+ if (service.besidesApp === appName) return service.besidesStatus ?? null
207
+ return null
208
+ }
209
+
210
+ const HEALTH_OF: Record<EnvironmentReadiness, EnvHealth> = {
211
+ notConfigured: "neutral",
212
+ ready: "success",
213
+ deploying: "neutral",
214
+ notReady: "warning",
215
+ failed: "failed",
216
+ }
217
+
218
+ export function summarizeHealth(statuses: (AppStatus | null | undefined)[]): { health: EnvHealth; message: string | null } {
219
+ const overall = environmentReadiness(statuses.map(status => applicationReadiness(status)))
220
+ const reported = statuses
221
+ .flatMap(status => status?.status?.services ?? [])
222
+ .find(service => service.message)?.message ?? null
223
+ return { health: HEALTH_OF[overall.state], message: overall.reason ?? reported }
224
+ }
@@ -0,0 +1,64 @@
1
+ import { BaseService, type AuthHeadersProvider } from "../base-service"
2
+ import type { AppComponents } from "./apps"
3
+ import type { EnvAppStatus, EnvServiceBackend } from "./reader"
4
+
5
+ const statusOfError = (error: any): number | undefined =>
6
+ error?.status ?? error?.statusCode ?? error?.response?.status ?? error?.raw?.status
7
+
8
+ /**
9
+ * The three questions about the services of an environment, asked to the backend
10
+ * (`/platform/v1/env-configs`), with the business unit of the page.
11
+ */
12
+ export class EnvServicesClient extends BaseService {
13
+ constructor(apiUrl: string, authHeaders?: AuthHeadersProvider) {
14
+ super(apiUrl, authHeaders)
15
+ }
16
+
17
+ private headers(project: string) {
18
+ return { headers: { "x-business-unit-id": project } }
19
+ }
20
+
21
+ /** The names of the applications of an environment. */
22
+ async listApps(envName: string, project: string): Promise<string[]> {
23
+ const data = await this.httpClient.get<{ applications?: { name: string }[] }>(
24
+ `/platform/v1/env-configs?env=${encodeURIComponent(envName)}`,
25
+ this.headers(project),
26
+ )
27
+ return (data?.applications ?? []).map(application => application.name)
28
+ }
29
+
30
+ /**
31
+ * What an application holds. An environment with no service yet has no application: that
32
+ * is an answer, not a failure. Anything else is one, and saying "nothing" would hide it.
33
+ */
34
+ async components(appName: string, project: string): Promise<AppComponents> {
35
+ try {
36
+ const data = await this.httpClient.get<{ components?: AppComponents["components"] }>(
37
+ `/platform/v1/env-configs/${appName}/components`,
38
+ this.headers(project),
39
+ )
40
+ return { components: data?.components ?? [], appExists: true }
41
+ } catch (error) {
42
+ if (statusOfError(error) === 404) return { components: [], appExists: false }
43
+ throw error
44
+ }
45
+ }
46
+
47
+ /** The status of an application in the environment. */
48
+ async status(appName: string, envName: string, project: string): Promise<EnvAppStatus> {
49
+ const data = await this.httpClient.get<{ status?: EnvAppStatus[] }>(
50
+ `/platform/v1/env-configs/${appName}/status`,
51
+ this.headers(project),
52
+ )
53
+ return Array.isArray(data?.status) && data.status.length > 0 ? data.status[0] : { envName, status: null }
54
+ }
55
+ }
56
+
57
+ /** The client as a backend of the reader, for one business unit. */
58
+ export function envServicesBackend(client: EnvServicesClient, project: string): EnvServiceBackend {
59
+ return {
60
+ listApps: envName => client.listApps(envName, project),
61
+ components: appName => client.components(appName, project),
62
+ status: (appName, envName) => client.status(appName, envName, project),
63
+ }
64
+ }
@@ -0,0 +1,6 @@
1
+ export * from "./signal"
2
+ export * from "./readiness"
3
+ export * from "./places"
4
+ export * from "./apps"
5
+ export * from "./reader"
6
+ export * from "./client"
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Where each service of an environment lives: the application it has to itself,
3
+ * `<environment>-<appSuffix>`, and the component it is there, `<environment>-<compType>`.
4
+ */
5
+ export interface EnvServicePlace {
6
+ /** Suffix of the application the service has to itself: `<environment>-<suffix>`. */
7
+ appSuffix: string
8
+ /** The component type, when it is not the key of the service. */
9
+ compType?: string
10
+ /** Component types the application of the service also holds, any number of each. */
11
+ holds?: string[]
12
+ /** False for a service that only configures, with nothing running to follow. */
13
+ hasRuntimeStatus?: boolean
14
+ }
15
+
16
+ export const ENV_SERVICE_PLACES: Record<string, EnvServicePlace> = {
17
+ "camel-integration-service": { appSuffix: "camel" },
18
+ "camel-messaging-service": { appSuffix: "messaging" },
19
+ "logging": { appSuffix: "logging" },
20
+ "network": { appSuffix: "network", compType: "networkpolicy", hasRuntimeStatus: false },
21
+ "network-policy": { appSuffix: "network", compType: "networkpolicy", hasRuntimeStatus: false },
22
+ "private-link": { appSuffix: "network" },
23
+ }
24
+
25
+ /** The services an environment can have. */
26
+ export const PLATFORM_SERVICE_TYPES = [
27
+ "camel-integration-service",
28
+ "camel-messaging-service",
29
+ "logging",
30
+ "network",
31
+ ] as const
32
+ export type PlatformServiceType = typeof PLATFORM_SERVICE_TYPES[number]
33
+
34
+ /** Component name a platform service takes inside an environment's config app. */
35
+ export function envComponentName(envName: string, routingKey: string): string {
36
+ return `${envName}-${ENV_SERVICE_PLACES[routingKey]?.compType ?? routingKey}`
37
+ }
@@ -0,0 +1,116 @@
1
+ /**
2
+ * Reading the services of an environment: where each lives, the status of its application, and
3
+ * how it is doing. Every application of the console reads them this way, through a backend that
4
+ * answers three questions: which applications the environment has, what one holds, and its status.
5
+ */
6
+ import { ENV_SERVICE_PLACES, PLATFORM_SERVICE_TYPES, envComponentName } from "./places"
7
+ import {
8
+ configuredApps, envAppCandidates, envServiceAppName, isActive, linkLocations, locateService, policyLocations,
9
+ sharedEnvAppName, summarizeHealth, type AppComponents, type EnvHealth, type ServiceLocation,
10
+ } from "./apps"
11
+ import { serviceReadiness, type ReadableStatus, type Readiness } from "./readiness"
12
+
13
+ /** The status of an application of an environment, as the backend gives it. */
14
+ export interface EnvAppStatus extends ReadableStatus {
15
+ envName: string
16
+ }
17
+
18
+ export interface EnvServiceBackend<S extends ReadableStatus = EnvAppStatus> {
19
+ /** The names of the applications of the environment. */
20
+ listApps(envName: string): Promise<string[]>
21
+ /** What an application holds; an application that is not there holds nothing. */
22
+ components(appName: string): Promise<AppComponents>
23
+ /** Its status in the environment; null when it has none. */
24
+ status(appName: string, envName: string): Promise<S | null>
25
+ }
26
+
27
+ export interface EnvServiceState<S = EnvAppStatus> extends ServiceLocation {
28
+ /** Status of the application the service lives in (null until deployed, or when it cannot be read). */
29
+ status: S | null
30
+ /** Status of its own application, when what it holds besides lives apart from it. */
31
+ besidesStatus?: S | null
32
+ }
33
+
34
+ export type EnvServices<S = EnvAppStatus> = Record<string, EnvServiceState<S>>
35
+
36
+ const NO_APP: AppComponents = { components: [], appExists: false }
37
+
38
+ function withStatuses<S>(location: ServiceLocation, statuses: Map<string, S | null>): EnvServiceState<S> {
39
+ return {
40
+ ...location,
41
+ status: isActive(location) ? statuses.get(location.appName) ?? null : null,
42
+ ...(location.besidesApp ? { besidesStatus: statuses.get(location.besidesApp) ?? null } : {}),
43
+ }
44
+ }
45
+
46
+ /** The statuses of applications; one that cannot be read is null, and the others are kept. */
47
+ async function statusesOf<S extends ReadableStatus>(appNames: string[], envName: string, backend: EnvServiceBackend<S>): Promise<Map<string, S | null>> {
48
+ const statuses = await Promise.all(appNames.map(appName => backend.status(appName, envName).catch(() => null)))
49
+ return new Map(appNames.map((appName, index) => [appName, statuses[index]]))
50
+ }
51
+
52
+ /**
53
+ * What an application of an environment holds. An application that is not among those of
54
+ * the environment is not asked for: it holds nothing, and asking would be refused.
55
+ */
56
+ function componentsOf<S extends ReadableStatus>(appName: string, existing: string[], backend: EnvServiceBackend<S>): Promise<AppComponents> {
57
+ return existing.includes(appName) ? backend.components(appName) : Promise.resolve(NO_APP)
58
+ }
59
+
60
+ /** Where each service of an environment lives, and the status of the application it lives in. */
61
+ export async function readEnvServices<S extends ReadableStatus>(envName: string, backend: EnvServiceBackend<S>): Promise<EnvServices<S>> {
62
+ const keys = [...PLATFORM_SERVICE_TYPES]
63
+ const existing = await backend.listApps(envName)
64
+ const [shared, ...own] = await Promise.all([
65
+ componentsOf(sharedEnvAppName(envName), existing, backend),
66
+ ...keys.map(key => componentsOf(envServiceAppName(envName, key), existing, backend)),
67
+ ])
68
+
69
+ const locations: Record<string, ServiceLocation> = {}
70
+ keys.forEach((key, index) => {
71
+ locations[key] = locateService(envName, key, own[index] ?? NO_APP, shared ?? NO_APP)
72
+ })
73
+
74
+ // Links are not services: each lives in an application of its own and is deployed alone.
75
+ // They are located with the rest so that their statuses are followed the same way.
76
+ const network = own[keys.indexOf("network" as typeof keys[number])] ?? NO_APP
77
+ Object.assign(locations, linkLocations(envName, existing, network))
78
+ Object.assign(locations, policyLocations(envName, existing, network, shared ?? NO_APP))
79
+
80
+ const statuses = await statusesOf(configuredApps(locations), envName, backend)
81
+ const services: EnvServices<S> = {}
82
+ for (const key of Object.keys(locations)) {
83
+ services[key] = withStatuses(locations[key], statuses)
84
+ }
85
+ return services
86
+ }
87
+
88
+ /** The same services with their statuses read again. */
89
+ export async function readEnvServiceStatuses<S extends ReadableStatus>(
90
+ envName: string, services: EnvServices<S>, backend: EnvServiceBackend<S>,
91
+ ): Promise<EnvServices<S>> {
92
+ const statuses = await statusesOf(configuredApps(services), envName, backend)
93
+ const refreshed: EnvServices<S> = {}
94
+ for (const [key, service] of Object.entries(services)) {
95
+ refreshed[key] = withStatuses(service, statuses)
96
+ }
97
+ return refreshed
98
+ }
99
+
100
+ /** One state for an environment, read from the applications its services live in. */
101
+ export async function readEnvHealth<S extends ReadableStatus>(envName: string, backend: EnvServiceBackend<S>): Promise<{ health: EnvHealth; message: string | null }> {
102
+ const existing = await backend.listApps(envName)
103
+ const statuses = await statusesOf(envAppCandidates(envName).filter(appName => existing.includes(appName)), envName, backend)
104
+ return summarizeHealth(Array.from(statuses.values()))
105
+ }
106
+
107
+ /**
108
+ * How each service of the environment is doing: `none` when it is not configured, `ready`,
109
+ * `deploying`, `notReady` or `failed` otherwise, with the reason.
110
+ */
111
+ export function readinessOfServices<S extends ReadableStatus>(envName: string, services: EnvServices<S>): Record<string, Readiness> {
112
+ return Object.fromEntries(PLATFORM_SERVICE_TYPES.map(key => [
113
+ key,
114
+ serviceReadiness(envComponentName(envName, key), services[key], ENV_SERVICE_PLACES[key]?.hasRuntimeStatus !== false),
115
+ ]))
116
+ }
@@ -0,0 +1,189 @@
1
+ import { combineSignals, type Signal } from "./signal"
2
+
3
+ export type ServiceReadiness = "none" | "deploying" | "ready" | "notReady" | "failed"
4
+
5
+ export interface Readiness {
6
+ state: ServiceReadiness
7
+ reason: string | null
8
+ }
9
+
10
+ interface ReportedService {
11
+ name?: string
12
+ healthy?: boolean
13
+ message?: string
14
+ }
15
+
16
+ interface ReportedCondition {
17
+ type?: string
18
+ status?: string
19
+ message?: string
20
+ }
21
+
22
+ export interface ReadableStatus {
23
+ status?: {
24
+ status?: string
25
+ services?: ReportedService[]
26
+ conditions?: ReportedCondition[]
27
+ workflow?: { steps?: { phase?: string; message?: string }[] }
28
+ } | null
29
+ }
30
+
31
+ const DEPLOYING_PHASES = new Set(["starting", "rendering", "generatingpolicy", "runningworkflow", "workflowsuspending"])
32
+ const FAILED_PHASES = new Set(["workflowfailed", "workflowterminated"])
33
+ const PREPARE_CONDITIONS = new Set(["Parsed", "Revision", "Policy", "Render", "Workflow"])
34
+ const NEVER_CLEARED_CONDITIONS = new Set(["StateKeep", "GC"])
35
+ const REASON_LIMIT = 240
36
+
37
+ function clean(value: unknown): string | null {
38
+ if (typeof value !== "string") return null
39
+ const flat = value.replace(/\s+/g, " ").trim()
40
+ if (!flat) return null
41
+ return flat.length > REASON_LIMIT ? `${flat.slice(0, REASON_LIMIT - 1)}…` : flat
42
+ }
43
+
44
+ function phaseOf(status: ReadableStatus | null | undefined): string {
45
+ return (status?.status?.status || "").toLowerCase()
46
+ }
47
+
48
+ function failedCondition(status: ReadableStatus | null | undefined, only?: ReadonlySet<string>): string | null {
49
+ const condition = (status?.status?.conditions ?? [])
50
+ .find(candidate => candidate.status !== "True" && !NEVER_CLEARED_CONDITIONS.has(candidate.type ?? "")
51
+ && (!only || only.has(candidate.type ?? "")) && clean(candidate.message))
52
+ return condition ? clean(condition.message) : null
53
+ }
54
+
55
+ function failedStep(status: ReadableStatus | null | undefined): string | null {
56
+ const step = (status?.status?.workflow?.steps ?? [])
57
+ .find(candidate => (candidate.phase || "").toLowerCase() === "failed" && clean(candidate.message))
58
+ return step ? clean(step.message) : null
59
+ }
60
+
61
+ export function applicationReadiness(status: ReadableStatus | null | undefined): Readiness {
62
+ const phase = phaseOf(status)
63
+ if (!phase) return { state: "none", reason: null }
64
+
65
+ const cannotPrepare = failedCondition(status, PREPARE_CONDITIONS)
66
+ if (FAILED_PHASES.has(phase) || phase.includes("error")) {
67
+ return { state: "failed", reason: failedStep(status) ?? failedCondition(status) }
68
+ }
69
+ if (DEPLOYING_PHASES.has(phase)) {
70
+ return cannotPrepare ? { state: "failed", reason: cannotPrepare } : { state: "deploying", reason: null }
71
+ }
72
+
73
+ const unhealthy = (status?.status?.services ?? []).find(service => service.healthy === false)
74
+ if (unhealthy) return { state: "notReady", reason: clean(unhealthy.message) }
75
+ if (phase !== "running") return { state: "notReady", reason: failedCondition(status) }
76
+ return { state: "ready", reason: null }
77
+ }
78
+
79
+ export interface ServiceElement {
80
+ name: string
81
+ readiness: Readiness
82
+ }
83
+
84
+ interface ReadableService {
85
+ exists?: boolean
86
+ status?: ReadableStatus | null
87
+ besidesApp?: string
88
+ besidesStatus?: ReadableStatus | null
89
+ }
90
+
91
+ const SIGNAL_OF: Record<ServiceReadiness, Signal> = {
92
+ none: "gray",
93
+ deploying: "gray",
94
+ ready: "green",
95
+ notReady: "orange",
96
+ failed: "red",
97
+ }
98
+
99
+ const READY: Readiness = { state: "ready", reason: null }
100
+ const NOTHING: Readiness = { state: "none", reason: null }
101
+
102
+ function isSettled(readiness: Readiness): boolean {
103
+ return readiness.state === "ready" || readiness.state === "notReady"
104
+ }
105
+
106
+ function firstIn(parts: readonly Readiness[], state: ServiceReadiness): Readiness | undefined {
107
+ return parts.find(part => part.state === state)
108
+ }
109
+
110
+ function ownReadiness(componentName: string, status: ReadableStatus | null | undefined, reportsRuntime: boolean): Readiness {
111
+ const application = applicationReadiness(status)
112
+ if (application.state === "none") return { state: "notReady", reason: "Not deployed yet" }
113
+ if (!isSettled(application) || !reportsRuntime) return application
114
+
115
+ const own = (status?.status?.services ?? []).find(candidate => candidate.name === componentName)
116
+ if (!own) return { state: "notReady", reason: "Deployed, but it reports nothing yet" }
117
+ if (own.healthy === false) return { state: "notReady", reason: clean(own.message) }
118
+ return READY
119
+ }
120
+
121
+ function reportedElements(status: ReadableStatus | null | undefined, except?: string): ServiceElement[] {
122
+ return (status?.status?.services ?? [])
123
+ .filter(reported => reported.name && reported.name !== except)
124
+ .map(reported => ({
125
+ name: reported.name as string,
126
+ readiness: reported.healthy === false ? { state: "notReady", reason: clean(reported.message) } : READY,
127
+ }))
128
+ }
129
+
130
+ function besidesElements(service: ReadableService): ServiceElement[] {
131
+ const application = applicationReadiness(service.besidesStatus)
132
+ if (application.state === "none") return []
133
+ const reported = isSettled(application) ? reportedElements(service.besidesStatus) : []
134
+ return reported.length > 0 ? reported : [{ name: service.besidesApp ?? "", readiness: application }]
135
+ }
136
+
137
+ export function serviceElements(
138
+ componentName: string,
139
+ service: ReadableService | null | undefined,
140
+ reportsRuntime: boolean,
141
+ ): ServiceElement[] {
142
+ if (!service?.exists) return []
143
+ const own = ownReadiness(componentName, service.status, reportsRuntime)
144
+ const others = isSettled(applicationReadiness(service.status)) ? reportedElements(service.status, componentName) : []
145
+ return [{ name: componentName, readiness: own }, ...others, ...besidesElements(service)]
146
+ }
147
+
148
+ export function combineReadiness(parts: readonly Readiness[]): Readiness {
149
+ const signal = combineSignals(parts.map(part => SIGNAL_OF[part.state]))
150
+ if (signal === "red") return firstIn(parts, "failed") ?? NOTHING
151
+ if (signal === "orange") return firstIn(parts, "notReady") ?? NOTHING
152
+ return firstIn(parts, "deploying") ?? (signal === "green" ? READY : NOTHING)
153
+ }
154
+
155
+ export function serviceReadiness(
156
+ componentName: string,
157
+ service: ReadableService | null | undefined,
158
+ reportsRuntime: boolean,
159
+ ): Readiness {
160
+ return combineReadiness(serviceElements(componentName, service, reportsRuntime).map(element => element.readiness))
161
+ }
162
+
163
+ export type EnvironmentReadiness = "notConfigured" | "ready" | "deploying" | "notReady" | "failed"
164
+
165
+ export function environmentReadiness(parts: readonly Readiness[]): { state: EnvironmentReadiness; reason: string | null } {
166
+ const signal = combineSignals(parts.map(part => SIGNAL_OF[part.state]))
167
+ if (signal === "red") return { state: "failed", reason: firstIn(parts, "failed")?.reason ?? null }
168
+ if (signal === "orange") return { state: "notReady", reason: firstIn(parts, "notReady")?.reason ?? null }
169
+ if (signal === "green") return { state: "ready", reason: null }
170
+ return { state: firstIn(parts, "deploying") ? "deploying" : "notConfigured", reason: null }
171
+ }
172
+
173
+ export interface ReadinessMark {
174
+ loading: boolean
175
+ tone: "success" | "warning" | "error" | null
176
+ label: string
177
+ }
178
+
179
+ const MARK_OF: Record<ServiceReadiness, ReadinessMark | null> = {
180
+ none: null,
181
+ deploying: { loading: true, tone: null, label: "Deploying" },
182
+ ready: { loading: false, tone: "success", label: "Ready" },
183
+ notReady: { loading: false, tone: "warning", label: "Not ready" },
184
+ failed: { loading: false, tone: "error", label: "Failed" },
185
+ }
186
+
187
+ export function readinessMark(readiness: Readiness): ReadinessMark | null {
188
+ return MARK_OF[readiness.state]
189
+ }
@@ -0,0 +1,7 @@
1
+ export type Signal = "green" | "orange" | "red" | "gray"
2
+
3
+ export function combineSignals(signals: readonly Signal[]): Signal {
4
+ if (signals.includes("red")) return "red"
5
+ if (signals.includes("orange")) return "orange"
6
+ return signals.includes("green") ? "green" : "gray"
7
+ }
@@ -0,0 +1,28 @@
1
+ /**
2
+ * The description of a form field, as a form shows it: a summary under the field, and the whole
3
+ * text behind an information icon when it says more than the summary.
4
+ */
5
+ export interface FieldDescriptionParts {
6
+ summary: string
7
+ /** The whole description, or null when the summary is all of it. */
8
+ detail: string | null
9
+ }
10
+
11
+ /** Past this length, a first sentence is cut at its first colon or semicolon. */
12
+ const LONG_SUMMARY = 100
13
+
14
+ /**
15
+ * The summary is the first sentence: a period, a question or an exclamation mark followed by a
16
+ * capital, so that "e.g.", "0.5" or "500Mi." inside a sentence do not end it. A first sentence
17
+ * longer than a line is cut at its first colon or semicolon, when it has one.
18
+ */
19
+ export function splitDescription(text: string | null | undefined): FieldDescriptionParts {
20
+ const whole = (text ?? "").trim().replace(/\s+/g, " ")
21
+ const sentence = whole.match(/^(.+?[.!?])\s+(?=["'(«`]?[A-Z])/)?.[1] ?? whole
22
+ let summary = sentence
23
+ if (summary.length > LONG_SUMMARY) {
24
+ const cut = summary.search(/[:;]\s/)
25
+ if (cut > 0) summary = summary.slice(0, cut) + "."
26
+ }
27
+ return { summary, detail: summary === whole ? null : whole }
28
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@orsetra/shared-ui",
3
- "version": "1.13.0",
3
+ "version": "1.15.0",
4
4
  "description": "Shared UI components for Orsetra platform",
5
5
  "main": "./index.ts",
6
6
  "types": "./index.ts",
@@ -10,6 +10,7 @@
10
10
  "./components/layout": "./components/layout/index.ts",
11
11
  "./hooks": "./hooks/index.ts",
12
12
  "./auth": "./auth/index.ts",
13
+ "./env-services": "./lib/env-services/index.ts",
13
14
  "./lib/*": "./lib/*.ts"
14
15
  },
15
16
  "files": [