| 1 | import type { EnvironmentId } from "@t3tools/contracts"; |
| 2 | import type { RelayClientEnvironmentRecord } from "@t3tools/contracts/relay"; |
| 3 | import type { ConnectedEnvironmentSummary } from "../../state/remote-runtime-types"; |
| 4 | |
| 5 | export interface EnvironmentSectionsInput { |
| 6 | readonly connectedEnvironments: ReadonlyArray<ConnectedEnvironmentSummary>; |
| 7 | readonly cloudEnvironments: ReadonlyArray<RelayClientEnvironmentRecord> | null; |
| 8 | } |
| 9 | |
| 10 | export interface EnvironmentSections { |
| 11 | readonly localEnvironments: ReadonlyArray<ConnectedEnvironmentSummary>; |
| 12 | readonly connectedCloudEnvironments: ReadonlyArray<ConnectedEnvironmentSummary>; |
| 13 | readonly availableCloudEnvironments: ReadonlyArray<RelayClientEnvironmentRecord>; |
| 14 | } |
| 15 | |
| 16 | /** |
| 17 | * Ids of the environments that already occupy a T3 Connect slot. A backend saved directly is |
| 18 | * not one of them, so it must not suppress the cloud environment that happens to share its id. |
| 19 | */ |
| 20 | export function relayManagedEnvironmentIds( |
| 21 | environments: ReadonlyArray<{ |
| 22 | readonly environmentId: EnvironmentId; |
| 23 | readonly isRelayManaged: boolean; |
| 24 | }>, |
| 25 | ): ReadonlySet<EnvironmentId> { |
| 26 | return new Set( |
| 27 | environments |
| 28 | .filter((environment) => environment.isRelayManaged) |
| 29 | .map((environment) => environment.environmentId), |
| 30 | ); |
| 31 | } |
| 32 | |
| 33 | export function splitEnvironmentSections(input: EnvironmentSectionsInput): EnvironmentSections { |
| 34 | const savedEnvironmentIds = relayManagedEnvironmentIds(input.connectedEnvironments); |
| 35 | |
| 36 | return { |
| 37 | localEnvironments: input.connectedEnvironments.filter( |
| 38 | (environment) => !environment.isRelayManaged, |
| 39 | ), |
| 40 | connectedCloudEnvironments: input.connectedEnvironments.filter( |
| 41 | (environment) => environment.isRelayManaged, |
| 42 | ), |
| 43 | availableCloudEnvironments: (input.cloudEnvironments ?? []).filter( |
| 44 | (environment) => !savedEnvironmentIds.has(environment.environmentId), |
| 45 | ), |
| 46 | }; |
| 47 | } |