config.ts
Language TypeScript2.1 KB60 lines
import { ConfigError } from "./errors.js";/*** Runtime-agnostic configuration.** This module reads no globals (no `process.env`). Config is derived from an* injected source so the same core runs under Node (stdio dev) and under the* Cloudflare Workers isolate runtime, where env arrives as a binding on the* fetch handler and `process` does not exist.*/export interface PlinthConfig {/** Single dispatch endpoint. Methods are selected via the `method` param. */readonly baseUrl: string;/** Static API key with global read scope. Undefined when none is configured. */readonly apiKey: string | undefined;/*** Master safety switch, true only when PLINTH_ALLOW_LIVE_REQUESTS is "true".* While false, plinthRequest() refuses to run, because the API has no* sandbox: every call reads production data.*/readonly allowLiveRequests: boolean;}/*** The subset of environment variables this server reads. Both Node's* `process.env` and a Cloudflare Workers `env` binding are structurally* assignable to this shape.*/export interface PlinthEnvVars {PLINTH_API_BASE_URL?: string;PLINTH_API_KEY?: string;PLINTH_ALLOW_LIVE_REQUESTS?: string;}const DEFAULT_BASE_URL = "https://orders.meridiandisplay.example/api/v2/dispatch";/** Build config from an injected env source (process.env, Workers env, a test double). */export function configFromEnv(source: PlinthEnvVars): PlinthConfig {return {baseUrl: source.PLINTH_API_BASE_URL?.trim() || DEFAULT_BASE_URL,apiKey: source.PLINTH_API_KEY?.trim() || undefined,allowLiveRequests: source.PLINTH_ALLOW_LIVE_REQUESTS === "true",};}/*** Assert the config is safe to make a live call with. Called by plinthRequest()* before any network access.*/export function assertLiveRequestsAllowed(cfg: PlinthConfig): void {if (!cfg.allowLiveRequests) {throw new ConfigError("Live requests are disabled. This server is PRODUCTION-only (no sandbox); " +"set PLINTH_ALLOW_LIVE_REQUESTS=true once you have intentionally wired the handlers.",);}if (!cfg.apiKey) {throw new ConfigError("PLINTH_API_KEY is not set.");}}