Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(infra): derive the saved built-in mode from host pins and selection
Yudhi Armyndharis1dd6a7913a1b
diff --git a/openapi.json b/openapi.jsonindex 7500e60a5..dad08c321 100644--- a/openapi.json+++ b/openapi.json@@ -22235,7 +22235,7 @@},"builtInSet": {"type": "boolean",- "description": "Whether the built-in flag is stored, in the saved file or pinned by the environment. When false, builtIn is false only because nothing says otherwise (a Compose deployment that pins the bundled host never writes it): read what runs from /infra/status.",+ "description": "Whether the saved configuration states the built-in mode of this service. False when a host pinned by the environment decides it (builtIn then reports the pin: true for the bundled host), when the saved file does not select the service (the first boot writes every flag as false next to a service that is not in use), and when nothing is saved. When false, read what runs from /infra/status.","example": true},"host": {@@ -22306,7 +22306,7 @@},"builtInSet": {"type": "boolean",- "description": "Whether the built-in flag is stored, in the saved file or pinned by the environment. When false, builtIn is false only because nothing says otherwise (a Compose deployment that pins the bundled host never writes it): read what runs from /infra/status.",+ "description": "Whether the saved configuration states the built-in mode of this service. False when a host pinned by the environment decides it (builtIn then reports the pin: true for the bundled host), when the saved file does not select the service (the first boot writes every flag as false next to a service that is not in use), and when nothing is saved. When false, read what runs from /infra/status.","example": true},"host": {@@ -22362,7 +22362,7 @@},"builtInSet": {"type": "boolean",- "description": "Whether the built-in flag is stored, in the saved file or pinned by the environment. When false, builtIn is false only because nothing says otherwise (a Compose deployment that pins the bundled host never writes it): read what runs from /infra/status.",+ "description": "Whether the saved configuration states the built-in mode of this service. False when a host pinned by the environment decides it (builtIn then reports the pin: true for the bundled host), when the saved file does not select the service (the first boot writes every flag as false next to a service that is not in use), and when nothing is saved. When false, read what runs from /infra/status.","example": true},"localPath": {diff --git a/src/modules/infra/dto/infra-response.dto.ts b/src/modules/infra/dto/infra-response.dto.tsindex 8fe1150cd..50e85ee0f 100644--- a/src/modules/infra/dto/infra-response.dto.ts+++ b/src/modules/infra/dto/infra-response.dto.ts@@ -236,9 +236,10 @@ export class InfraUpdateCheckResponseDto {// ---------- GET /infra/config ----------const BUILT_IN_SET_DESCRIPTION =- 'Whether the built-in flag is stored, in the saved file or pinned by the environment. When false, builtIn is ' +- 'false only because nothing says otherwise (a Compose deployment that pins the bundled host never writes it): ' +- 'read what runs from /infra/status.';+ 'Whether the saved configuration states the built-in mode of this service. False when a host pinned by the ' ++ 'environment decides it (builtIn then reports the pin: true for the bundled host), when the saved file does not ' ++ 'select the service (the first boot writes every flag as false next to a service that is not in use), and when ' ++ 'nothing is saved. When false, read what runs from /infra/status.';export class InfraConfigDatabaseDto {@ApiProperty({ enum: ['sqlite', 'postgres'], example: 'postgres' })diff --git a/src/modules/infra/infra-config.controller.spec.ts b/src/modules/infra/infra-config.controller.spec.tsindex 59ae8c4d7..b705b34da 100644--- a/src/modules/infra/infra-config.controller.spec.ts+++ b/src/modules/infra/infra-config.controller.spec.ts@@ -34,6 +34,19 @@ import { SaveConfigDto } from './dto/save-config.dto';import { AuditAction } from '../audit/entities/audit-log.entity';import { recordOsEnvKeys, recordPinnedEnvKeys } from '../../config/env-precedence';import { resolveStorageRoot } from '../../config/storage-root';+import {+ EXPECTED_MODE,+ FILE_STATES,+ PIN_STATES,+ SERVICES,+ SERVICE_NAMES,+ fileLines,+ pinnedHost,+ type FileState,+ type PinState,+ type SavedMode,+ type ServiceName,+} from '../../../test/fixtures/builtin-mode-cases';// With no boot snapshot every process.env key counts as host-supplied, so a shell exporting the// CI Postgres or compose Redis settings would otherwise feed the save guard and the pin checks.@@ -1401,54 +1414,96 @@ describe('InfraConfigController.getConfig reflects environment-pinned values (#1});});-// A Compose deployment that pins DATABASE_HOST=postgres, REDIS_HOST=redis or S3_ENDPOINT in .env never writes the-// *_BUILTIN keys, so a false flag there only means nothing says otherwise: the form must tell it from a flag-// that was saved as false.-describe('InfraConfigController.getConfig reports whether each built-in flag is stored', () => {+// The saved built-in mode, for every state of the saved file and of what the environment pins for the service's host+// key (the rule is in test/fixtures/builtin-mode-cases.ts). Each case also fills the OTHER two services with the+// opposite state and pin, so a service reading another one's keys gets the wrong answer.+describe('InfraConfigController.getConfig answers the saved built-in mode for every file and pin state', () => {const newController = () => new InfraConfigController({} as never, {} as never, {} as never);- const withFile = (contents: string) => {+ const otherState = (state: FileState): FileState => (state === 'stored-true' ? 'stored-false' : 'stored-true');+ const otherPin = (pin: PinState): PinState => (pin === 'external' ? 'bundled' : 'external');+ let pinnedKeys: string[] = [];++ const arrange = (service: ServiceName, state: FileState, pin: PinState) => {+ const lines: string[] = [];+ const pins: Record<string, string> = {};+ for (const name of SERVICE_NAMES) {+ const own = name === service;+ lines.push(...fileLines(name, own ? state : otherState(state)));+ const host = pinnedHost(name, own ? pin : otherPin(pin));+ if (host !== undefined) pins[SERVICES[name].host] = host;+ }+ recordPinnedEnvKeys(pins);+ for (const [key, value] of Object.entries(pins)) process.env[key] = value;+ pinnedKeys = Object.keys(pins);(fs.existsSync as jest.Mock).mockReturnValue(true);- (fs.readFileSync as jest.Mock).mockReturnValue(contents);+ (fs.readFileSync as jest.Mock).mockReturnValue(`${lines.join('\n')}\n`);};- const flags = (cfg: ReturnType<InfraConfigController['getConfig']>) => ({- database: [cfg.database.builtIn, cfg.database.builtInSet],- redis: [cfg.redis.builtIn, cfg.redis.builtInSet],- storage: [cfg.storage.builtIn, cfg.storage.builtInSet],- });afterEach(() => {- (fs.existsSync as jest.Mock).mockReturnValue(false);- (fs.readFileSync as jest.Mock).mockReturnValue('');+ for (const key of pinnedKeys) delete process.env[key];+ pinnedKeys = [];delete process.env.POSTGRES_BUILTIN;+ delete process.env.REDIS_BUILTIN;+ delete process.env.MINIO_BUILTIN;recordPinnedEnvKeys({});+ (fs.existsSync as jest.Mock).mockReturnValue(false);+ (fs.readFileSync as jest.Mock).mockReturnValue('');});- it('a file that holds no flag reports every flag as not stored', () => {- withFile('DATABASE_TYPE=postgres\nDATABASE_HOST=postgres\nREDIS_HOST=redis\nS3_ENDPOINT=http://minio:9000\n');+ const modeOf = (cfg: ReturnType<InfraConfigController['getConfig']>, service: ServiceName): SavedMode => {+ const section = cfg[service];+ return { builtIn: section.builtIn, builtInSet: section.builtInSet };+ };- expect(flags(newController().getConfig())).toEqual({- database: [false, false],- redis: [false, false],- storage: [false, false],- });+ describe.each(SERVICE_NAMES)('%s', service => {+ for (const state of FILE_STATES) {+ for (const pin of PIN_STATES) {+ it(`a ${state} file with ${pin === 'none' ? 'no host pin' : `the host pinned ${pin}`}`, () => {+ arrange(service, state, pin);++ expect(modeOf(newController().getConfig(), service)).toEqual(EXPECTED_MODE[state][pin]);+ });+ }+ }});- it('a flag saved as false is stored, as is one saved as true', () => {- withFile('POSTGRES_BUILTIN=false\nREDIS_BUILTIN=true\n');+ // The first boot writes every flag false next to a service that is not selected. With the compose .env pinning+ // the bundled hosts and the containers running, that file must not read as three saved external services.+ it('the first-boot file under the compose .env pins reads as bundled, never as a saved external choice', () => {+ for (const service of SERVICE_NAMES) {+ arrange(service, 'template', 'bundled');+ expect(modeOf(newController().getConfig(), service)).toEqual({ builtIn: true, builtInSet: false });+ }+ });- expect(flags(newController().getConfig())).toEqual({- database: [false, true],- redis: [true, true],- storage: [false, false],- });+ it('an external pin over a flag saved true reads as external, not as a pending switch to built-in', () => {+ for (const service of SERVICE_NAMES) {+ arrange(service, 'stored-true', 'external');+ expect(modeOf(newController().getConfig(), service)).toEqual({ builtIn: false, builtInSet: false });+ }});- it('a flag only the environment pins is stored', () => {- recordPinnedEnvKeys({ POSTGRES_BUILTIN: 'true' });+ // An operator who pins the flag itself has decided it, whatever the file or the hosts say, unless a host pin does.+ it('a flag pinned by the environment counts as stored, and a pinned host still outranks it', () => {+ recordPinnedEnvKeys({+ POSTGRES_BUILTIN: 'true',+ REDIS_BUILTIN: 'false',+ MINIO_BUILTIN: 'true',+ S3_ENDPOINT: 'https://s3.external.example',+ });process.env.POSTGRES_BUILTIN = 'true';- withFile('');+ process.env.REDIS_BUILTIN = 'false';+ process.env.MINIO_BUILTIN = 'true';+ process.env.S3_ENDPOINT = 'https://s3.external.example';+ pinnedKeys = ['S3_ENDPOINT'];+ (fs.existsSync as jest.Mock).mockReturnValue(true);+ (fs.readFileSync as jest.Mock).mockReturnValue('POSTGRES_BUILTIN=false\nREDIS_BUILTIN=true\nMINIO_BUILTIN=false\n');++ const cfg = newController().getConfig();- expect(flags(newController().getConfig()).database).toEqual([true, true]);+ expect(modeOf(cfg, 'database')).toEqual({ builtIn: true, builtInSet: true });+ expect(modeOf(cfg, 'redis')).toEqual({ builtIn: false, builtInSet: true });+ expect(modeOf(cfg, 'storage')).toEqual({ builtIn: false, builtInSet: false });});});diff --git a/src/modules/infra/infra-config.controller.ts b/src/modules/infra/infra-config.controller.tsindex bc175dcd9..0db13f326 100644--- a/src/modules/infra/infra-config.controller.ts+++ b/src/modules/infra/infra-config.controller.ts@@ -30,6 +30,7 @@ import * as fs from 'fs';import * as path from 'path';import * as dotenv from 'dotenv';import { encodeGeneratedEnvValue, generatedEnvPath, readGeneratedEnv } from './generated-env';+import { savedBuiltInMode } from './saved-builtin-mode';import {applyDatabaseSection,applyEngineSection,@@ -143,8 +144,7 @@ export class InfraConfigController {return {database: {type: effective('DATABASE_TYPE') === 'postgres' ? 'postgres' : 'sqlite',- builtIn: effective('POSTGRES_BUILTIN') === 'true',- builtInSet: Boolean(effective('POSTGRES_BUILTIN')),+ ...savedBuiltInMode('database', saved),host: effective('DATABASE_HOST') || '',port: effective('DATABASE_PORT') || '',username: effective('DATABASE_USERNAME') || '',@@ -157,8 +157,7 @@ export class InfraConfigController {},redis: {enabled: effective('REDIS_ENABLED') === 'true',- builtIn: effective('REDIS_BUILTIN') === 'true',- builtInSet: Boolean(effective('REDIS_BUILTIN')),+ ...savedBuiltInMode('redis', saved),host: effective('REDIS_HOST') || '',port: effective('REDIS_PORT') || '',passwordSet: Boolean(effective('REDIS_PASSWORD')),@@ -166,8 +165,7 @@ export class InfraConfigController {queue: { enabled: effective('QUEUE_ENABLED') === 'true' },storage: {type: effective('STORAGE_TYPE') === 's3' ? 's3' : 'local',- builtIn: effective('MINIO_BUILTIN') === 'true',- builtInSet: Boolean(effective('MINIO_BUILTIN')),+ ...savedBuiltInMode('storage', saved),localPath: effective('STORAGE_LOCAL_PATH') || '',s3Bucket: effective('S3_BUCKET') || '',s3Region: effective('S3_REGION') || '',diff --git a/src/modules/infra/infra-status.controller.spec.ts b/src/modules/infra/infra-status.controller.spec.tsindex 2d6bfd228..c9e069881 100644--- a/src/modules/infra/infra-status.controller.spec.ts+++ b/src/modules/infra/infra-status.controller.spec.ts@@ -18,6 +18,18 @@ jest.mock('fs', () => {import { InfraStatusController } from './infra-status.controller';import { recordPinnedEnvKeys } from '../../config/env-precedence';import { producerConnectWaitMs } from '../queue/redis-connection';+import * as fs from 'fs';+import {+ EXPECTED_MODE,+ FILE_STATES,+ PIN_STATES,+ SERVICES,+ SERVICE_NAMES,+ fileLines,+ pinnedHost,+ type FileState,+ type PinState,+} from '../../../test/fixtures/builtin-mode-cases';describe('InfraStatusController.getStatus DB health (active SELECT 1 probe, not just isInitialized)', () => {const build = (query: jest.Mock) => {@@ -281,3 +293,59 @@ describe('InfraStatusController.getStatus envPinned', () => {expect((await buildController().getStatus()).envPinned).toEqual([]);});});++// With Docker unreachable the status falls back to the saved built-in mode, and it must be the one GET /infra/config+// answers with, or the page claims a switch that no restart makes. Every file and pin state, each service.+describe('InfraStatusController.getStatus built-in fallback agrees with the saved mode when Docker is unreachable', () => {+ const build = () => {+ const config = { get: (k: string, def?: unknown) => (k === 'engine.type' ? 'baileys' : def) };+ const ds = { isInitialized: true, query: jest.fn().mockResolvedValue([{ '1': 1 }]) };+ return new InfraStatusController(+ config as never,+ ds as never,+ ds as never,+ { create: jest.fn() } as never,+ { isDockerAvailable: () => false, getRunningBuiltinServices: jest.fn() } as never,+ { isAvailable: jest.fn().mockResolvedValue(false) } as never,+ { refreshS3Availability: jest.fn() } as never,+ undefined as never,+ );+ };+ const otherState = (state: FileState): FileState => (state === 'stored-true' ? 'stored-false' : 'stored-true');+ const otherPin = (pin: PinState): PinState => (pin === 'external' ? 'bundled' : 'external');+ let pinnedKeys: string[] = [];++ afterEach(() => {+ for (const key of pinnedKeys) delete process.env[key];+ pinnedKeys = [];+ recordPinnedEnvKeys({});+ (fs.existsSync as jest.Mock).mockReturnValue(false);+ (fs.readFileSync as jest.Mock).mockReturnValue('');+ });++ for (const service of SERVICE_NAMES) {+ for (const state of FILE_STATES) {+ for (const pin of PIN_STATES) {+ it(`${service}: a ${state} file with ${pin === 'none' ? 'no host pin' : `the host pinned ${pin}`}`, async () => {+ const lines: string[] = [];+ const pins: Record<string, string> = {};+ for (const name of SERVICE_NAMES) {+ const own = name === service;+ lines.push(...fileLines(name, own ? state : otherState(state)));+ const host = pinnedHost(name, own ? pin : otherPin(pin));+ if (host !== undefined) pins[SERVICES[name].host] = host;+ }+ recordPinnedEnvKeys(pins);+ for (const [key, value] of Object.entries(pins)) process.env[key] = value;+ pinnedKeys = Object.keys(pins);+ (fs.existsSync as jest.Mock).mockReturnValue(true);+ (fs.readFileSync as jest.Mock).mockReturnValue(`${lines.join('\n')}\n`);++ const status = await build().getStatus();++ expect(status[service].builtIn).toBe(EXPECTED_MODE[state][pin].builtIn);+ });+ }+ }+ }+});diff --git a/src/modules/infra/infra-status.controller.ts b/src/modules/infra/infra-status.controller.tsindex 022286592..90a7b7f07 100644--- a/src/modules/infra/infra-status.controller.ts+++ b/src/modules/infra/infra-status.controller.ts@@ -23,6 +23,7 @@ import { CacheService } from '../../common/cache/cache.service';import { StorageService } from '../../common/storage/storage.service';import { createLogger } from '../../common/services/logger.service';import { readGeneratedEnv } from './generated-env';+import { savedBuiltInMode } from './saved-builtin-mode';import { isEnvPinned } from '../../config/env-precedence';import { DEFAULT_PUPPETEER_ARGS } from '../../config/configuration';import { checkForUpdate, type UpdateCheck } from './update-check';@@ -242,14 +243,17 @@ export class InfraStatusController {};}- /** Saved built-in intent flags from data/.env.generated — the fallback when Docker isn't reachable. */+ /**+ * The saved built-in mode, the fallback when Docker isn't reachable. The same answer GET /infra/config gives,+ * so a host the environment pins decides here too and the page never claims a switch no restart makes.+ */private readSavedBuiltinFlags(): { database: boolean; cache: boolean; storage: boolean } {try {const saved = readGeneratedEnv();return {- database: saved.POSTGRES_BUILTIN === 'true',- cache: saved.REDIS_BUILTIN === 'true',- storage: saved.MINIO_BUILTIN === 'true',+ database: savedBuiltInMode('database', saved).builtIn,+ cache: savedBuiltInMode('redis', saved).builtIn,+ storage: savedBuiltInMode('storage', saved).builtIn,};} catch {return { database: false, cache: false, storage: false };diff --git a/src/modules/infra/saved-builtin-mode.ts b/src/modules/infra/saved-builtin-mode.tsnew file mode 100644index 000000000..b9f569d03--- /dev/null+++ b/src/modules/infra/saved-builtin-mode.ts@@ -0,0 +1,65 @@+import { isEnvPinned } from '../../config/env-precedence';++/**+ * The built-in (bundled container) mode the saved configuration states for each datastore, shared by+ * GET /infra/config and the Docker-unreachable fallback of GET /infra/status so the two cannot disagree.+ *+ * `flag` is what the dashboard saves, `host` is what the next boot connects to, and `selection` is the+ * file's own record that the service is in use at all.+ */+const SERVICES = {+ database: {+ flag: 'POSTGRES_BUILTIN',+ host: 'DATABASE_HOST',+ bundledHost: 'postgres',+ selection: 'DATABASE_TYPE',+ selected: 'postgres',+ },+ redis: {+ flag: 'REDIS_BUILTIN',+ host: 'REDIS_HOST',+ bundledHost: 'redis',+ selection: 'REDIS_ENABLED',+ selected: 'true',+ },+ storage: {+ flag: 'MINIO_BUILTIN',+ host: 'S3_ENDPOINT',+ bundledHost: 'http://minio:9000',+ selection: 'STORAGE_TYPE',+ selected: 's3',+ },+} as const;++export type BuiltInService = keyof typeof SERVICES;++export interface SavedBuiltInMode {+ /** The mode the saved configuration implies: bundled container or not. */+ builtIn: boolean;+ /**+ * Whether that mode is a saved choice. False when a host pin decides it, when the file does not select the+ * service (the first boot writes every flag false next to a service that is not in use), and when nothing+ * says anything at all: a reader then follows what runs.+ */+ builtInSet: boolean;+}++/**+ * Rules, in order:+ * 1. A host pinned by the environment (or the project .env) decides, as it does at boot and in+ * requestRestart: the bundled host is built-in, any other is not, and no saved flag can be a pending+ * switch because the pin outranks it.+ * 2. Otherwise the flag counts as saved when the environment pins it, or when the file stores it for a+ * service the file also selects.+ * 3. Otherwise there is nothing saved.+ */+export function savedBuiltInMode(service: BuiltInService, saved: Record<string, string>): SavedBuiltInMode {+ const spec = SERVICES[service];+ if (isEnvPinned(spec.host)) {+ return { builtIn: process.env[spec.host] === spec.bundledHost, builtInSet: false };+ }+ const flagPinned = isEnvPinned(spec.flag);+ const flag = (flagPinned ? process.env[spec.flag] : undefined) ?? saved[spec.flag];+ const selectedInFile = saved[spec.selection] === spec.selected;+ return { builtIn: flag === 'true', builtInSet: flag !== undefined && (flagPinned || selectedInFile) };+}diff --git a/test/fixtures/builtin-mode-cases.ts b/test/fixtures/builtin-mode-cases.tsnew file mode 100644index 000000000..320186642--- /dev/null+++ b/test/fixtures/builtin-mode-cases.ts@@ -0,0 +1,128 @@+// The saved built-in mode GET /infra/config answers with, for every state of the saved file and of what the+// environment pins for the service's host key. One table for both halves of the Infrastructure page: the+// controller specs assert the answer, the dashboard page tests render the form from it.+//+// The rule, per service (database, redis, storage):+// 1. A host pinned by the environment decides: pinned to the bundled host is built-in, anything else is not,+// and the saved flag says nothing (builtInSet false).+// 2. Otherwise the saved flag counts (builtInSet true) only when the file also selects the service. The first+// boot writes every flag as false next to a service that is not selected, which is a default, not a choice.+// 3. Otherwise nothing is saved (builtInSet false) and the page follows what runs.++export type FileState = 'absent' | 'template' | 'stored-false' | 'stored-true' | 'unselected-true';+export type PinState = 'none' | 'bundled' | 'external';+export type ServiceName = 'database' | 'redis' | 'storage';++export interface SavedMode {+ builtIn: boolean;+ builtInSet: boolean;+}++export const FILE_STATES: readonly FileState[] = [+ 'absent',+ 'template',+ 'stored-false',+ 'stored-true',+ 'unselected-true',+];+export const PIN_STATES: readonly PinState[] = ['none', 'bundled', 'external'];+export const SERVICE_NAMES: readonly ServiceName[] = ['database', 'redis', 'storage'];++export const SERVICES: Record<+ ServiceName,+ {+ flag: string;+ host: string;+ bundledHost: string;+ externalHost: string;+ selection: string;+ selected: string;+ unselected: string;+ }+> = {+ database: {+ flag: 'POSTGRES_BUILTIN',+ host: 'DATABASE_HOST',+ bundledHost: 'postgres',+ externalHost: 'db.external.example',+ selection: 'DATABASE_TYPE',+ selected: 'postgres',+ unselected: 'sqlite',+ },+ redis: {+ flag: 'REDIS_BUILTIN',+ host: 'REDIS_HOST',+ bundledHost: 'redis',+ externalHost: 'cache.external.example',+ selection: 'REDIS_ENABLED',+ selected: 'true',+ unselected: 'false',+ },+ storage: {+ flag: 'MINIO_BUILTIN',+ host: 'S3_ENDPOINT',+ bundledHost: 'http://minio:9000',+ externalHost: 'https://s3.external.example',+ selection: 'STORAGE_TYPE',+ selected: 's3',+ unselected: 'local',+ },+};++const PINNED_BUNDLED: SavedMode = { builtIn: true, builtInSet: false };+const PINNED_EXTERNAL: SavedMode = { builtIn: false, builtInSet: false };++export const EXPECTED_MODE: Record<FileState, Record<PinState, SavedMode>> = {+ // Nothing in the file about the service.+ absent: {+ none: { builtIn: false, builtInSet: false },+ bundled: PINNED_BUNDLED,+ external: PINNED_EXTERNAL,+ },+ // What the first boot writes: the flag false, the service not selected.+ template: {+ none: { builtIn: false, builtInSet: false },+ bundled: PINNED_BUNDLED,+ external: PINNED_EXTERNAL,+ },+ // Saved from the dashboard with the service selected.+ 'stored-false': {+ none: { builtIn: false, builtInSet: true },+ bundled: PINNED_BUNDLED,+ external: PINNED_EXTERNAL,+ },+ 'stored-true': {+ none: { builtIn: true, builtInSet: true },+ bundled: PINNED_BUNDLED,+ external: PINNED_EXTERNAL,+ },+ // A flag left true beside a service the file does not select.+ 'unselected-true': {+ none: { builtIn: true, builtInSet: false },+ bundled: PINNED_BUNDLED,+ external: PINNED_EXTERNAL,+ },+};++/** The lines a saved file holds about one service in a given state. */+export function fileLines(service: ServiceName, state: FileState): string[] {+ const spec = SERVICES[service];+ switch (state) {+ case 'absent':+ return [];+ case 'template':+ return [`${spec.selection}=${spec.unselected}`, `${spec.flag}=false`];+ case 'stored-false':+ return [`${spec.selection}=${spec.selected}`, `${spec.flag}=false`];+ case 'stored-true':+ return [`${spec.selection}=${spec.selected}`, `${spec.flag}=true`];+ case 'unselected-true':+ return [`${spec.selection}=${spec.unselected}`, `${spec.flag}=true`];+ }+}++/** The host the environment pins for a service, or undefined when it pins none. */+export function pinnedHost(service: ServiceName, pin: PinState): string | undefined {+ const spec = SERVICES[service];+ return pin === 'none' ? undefined : pin === 'bundled' ? spec.bundledHost : spec.externalHost;+}