Files
HiveGrid-Wireframes/hivegrid-cloud/packages/config/src/api.ts
T

168 lines
5.1 KiB
TypeScript

import { getEnvVariableDefinition, validateEnv } from "./index.js";
import { getDomainRoutingConfig } from "./routing.js";
import type { ApiConfig, ApiConfigDiagnostic, ApiConfigErrorDetails, ApiConfigOptions, ApiConfigResult, EnvRecord, RequiredApiConfigOptions } from "./types.js";
const DEFAULT_APP_NAME = "ToolController";
const DEFAULT_NODE_ENV = "development";
const DEFAULT_LISTEN_PORT = 3001;
const MIN_PORT = 1;
const MAX_PORT = 65535;
export class ApiConfigError extends Error {
readonly diagnostics: ApiConfigDiagnostic[];
constructor(diagnostics: readonly ApiConfigDiagnostic[]) {
super(formatApiConfigErrorMessage(diagnostics));
this.name = "ApiConfigError";
this.diagnostics = diagnostics.map(redactDiagnostic);
}
get details(): ApiConfigErrorDetails {
return {
diagnostics: this.diagnostics,
};
}
}
export function loadRequiredApiConfig(env: EnvRecord = process.env, options: RequiredApiConfigOptions = {}): ApiConfig {
const result = loadApiConfig(env, options);
if (result.ok) {
return result.config;
}
throw new ApiConfigError(result.diagnostics);
}
export function loadApiConfig(env: EnvRecord = process.env, options: ApiConfigOptions = {}): ApiConfigResult {
const nodeEnv = options.nodeEnv ?? env.NODE_ENV ?? DEFAULT_NODE_ENV;
const routing = getDomainRoutingConfig({ ...env, NODE_ENV: nodeEnv });
const portResult = normalizeListenPort(env.API_PORT, env.PORT);
const diagnostics: ApiConfigDiagnostic[] = [
...toDiagnostics(
validateEnv(env, {
target: "api",
nodeEnv,
includeOptionalProviders: options.includeOptionalProviders,
extraRequired: options.extraRequired,
}).missing
),
];
if (portResult.diagnostic) {
diagnostics.push(portResult.diagnostic);
}
const config: ApiConfig = {
appName: present(env.APP_NAME) ?? DEFAULT_APP_NAME,
nodeEnv,
revision: present(env.APP_REVISION) ?? "unknown",
listen: {
port: portResult.port,
},
routing,
origins: {
web: present(env.WEB_ORIGIN),
admin: present(env.ADMIN_ORIGIN),
},
apiAccessToken: present(env.API_ACCESS_TOKEN),
jwtSecret: present(env.JWT_SECRET),
analytics: {
token: present(env.ANALYTICS_TOKEN),
},
mailjet: {
webhookSecret: present(env.MAILJET_WEBHOOK_SECRET),
},
stripe: {
secretKey: present(env.STRIPE_SK),
webhookSigningSecret: present(env.STRIPE_WEBHOOK_SIGNING_SECRET),
},
storage: {
endpoint: present(env.STORAGE_ENDPOINT),
region: present(env.STORAGE_REGION),
bucket: present(env.STORAGE_BUCKET),
accessKeyId: present(env.STORAGE_ACCESS_KEY_ID),
secretAccessKey: present(env.STORAGE_SECRET_ACCESS_KEY),
sessionToken: present(env.STORAGE_SESSION_TOKEN),
publicBaseUrl: present(env.STORAGE_PUBLIC_BASE_URL),
forcePathStyle: present(env.STORAGE_FORCE_PATH_STYLE),
},
apiKeys: {
allowLegacyPlaintextFallback: parseBooleanFlag(env.API_KEY_LEGACY_PLAINTEXT_FALLBACK, false),
},
};
return {
ok: diagnostics.length === 0,
config,
diagnostics,
};
}
function parseBooleanFlag(value: string | undefined, defaultValue: boolean): boolean {
const normalized = present(value)?.toLowerCase();
if (normalized === undefined) {
return defaultValue;
}
if (["1", "true", "yes", "on"].includes(normalized)) {
return true;
}
if (["0", "false", "no", "off"].includes(normalized)) {
return false;
}
return defaultValue;
}
function normalizeListenPort(apiPort: string | undefined, port: string | undefined): { port: number; diagnostic?: ApiConfigDiagnostic } {
const selected = present(apiPort) !== undefined ? { name: "API_PORT", value: apiPort } : { name: "PORT", value: port };
const trimmed = selected.value?.trim();
if (!trimmed) {
return { port: DEFAULT_LISTEN_PORT };
}
const parsed = Number(trimmed);
if (!Number.isInteger(parsed) || parsed < MIN_PORT || parsed > MAX_PORT) {
return {
port: DEFAULT_LISTEN_PORT,
diagnostic: {
code: "invalid-port",
name: selected.name,
classification: getEnvVariableDefinition(selected.name)?.classification,
message: `${selected.name} must be an integer between 1 and 65535. Falling back to 3001.`,
},
};
}
return { port: parsed };
}
function toDiagnostics(issues: ReturnType<typeof validateEnv>["missing"]): ApiConfigDiagnostic[] {
return issues.map((issue) => ({
code: "missing-required",
name: issue.name,
classification: issue.classification,
message: issue.message,
}));
}
function formatApiConfigErrorMessage(diagnostics: readonly ApiConfigDiagnostic[]): string {
const summary = diagnostics.map((diagnostic) => `${diagnostic.name}:${diagnostic.code}`).join(", ");
return `Invalid API configuration (${summary}).`;
}
function redactDiagnostic(diagnostic: ApiConfigDiagnostic): ApiConfigDiagnostic {
return {
code: diagnostic.code,
name: diagnostic.name,
classification: diagnostic.classification,
message: diagnostic.message,
};
}
function present(value: string | undefined): string | undefined {
const trimmed = value?.trim();
return trimmed ? trimmed : undefined;
}