Resolve Config With Explicit Source Precedence

A configuration resolver that merges defaults, file, environment and CLI sources in a declared order and records which source won each key.

TypescriptConfig Management

Code

export interface ConfigSource {
  readonly name: string;
  readonly values: Record<string, unknown>;
}

export interface ResolvedConfig<T> {
  readonly value: T;
  readonly provenance: Record<string, string>;
}

export function resolveConfig<T extends Record<string, unknown>>(
  sources: readonly ConfigSource[],
  options: { required?: readonly string[] } = {},
): ResolvedConfig<T> {
  const merged: Record<string, unknown> = {};
  const provenance: Record<string, string> = {};
  const seenNames = new Set<string>();

  for (const source of sources) {
    if (seenNames.has(source.name)) {
      throw new Error("duplicate config source name: " + source.name);
    }
    seenNames.add(source.name);
    if (!source.values || typeof source.values !== "object") {
      throw new TypeError("source " + source.name + " values must be an object");
    }
    for (const [key, value] of Object.entries(source.values)) {
      if (value === undefined) continue;
      merged[key] = value;
      provenance[key] = source.name;
    }
  }

  const missing = (options.required ?? []).filter((key) => !(key in merged));
  if (missing.length > 0) {
    throw new Error("missing required config keys: " + missing.join(", "));
  }

  return { value: merged as T, provenance };
}

Reading config sources in ad hoc order makes precedence accidental, so a value silently comes from the wrong place and differs per machine.

Use case: engineers whose tools read settings from several places at once

Inputs / outputs

  • Input: an ordered list of sources (defaults, file, env, flags), each a partial record
  • Output: the merged config plus a per-key provenance map

Error conditions

  • duplicate source name
  • a source is not an object
  • required key missing after merge

Approach

apply sources in order, later sources overwrite earlier ones; record provenance per key; validate required keys after the merge.

Implementation

export interface ConfigSource {
  readonly name: string;
  readonly values: Record<string, unknown>;
}

export interface ResolvedConfig<T> {
  readonly value: T;
  readonly provenance: Record<string, string>;
}

export function resolveConfig<T extends Record<string, unknown>>(
  sources: readonly ConfigSource[],
  options: { required?: readonly string[] } = {},
): ResolvedConfig<T> {
  const merged: Record<string, unknown> = {};
  const provenance: Record<string, string> = {};
  const seenNames = new Set<string>();

  for (const source of sources) {
    if (seenNames.has(source.name)) {
      throw new Error("duplicate config source name: " + source.name);
    }
    seenNames.add(source.name);
    if (!source.values || typeof source.values !== "object") {
      throw new TypeError("source " + source.name + " values must be an object");
    }
    for (const [key, value] of Object.entries(source.values)) {
      if (value === undefined) continue;
      merged[key] = value;
      provenance[key] = source.name;
    }
  }

  const missing = (options.required ?? []).filter((key) => !(key in merged));
  if (missing.length > 0) {
    throw new Error("missing required config keys: " + missing.join(", "));
  }

  return { value: merged as T, provenance };
}

Verification tests

import { test } from "node:test";
import assert from "node:assert/strict";
import { resolveConfig } from "./example.ts";

const sources = [
  { name: "defaults", values: { host: "localhost", port: 8080, debug: false } },
  { name: "file", values: { port: 9000 } },
  { name: "env", values: { debug: true } },
];

test("later sources win and provenance is recorded", () => {
  const resolved = resolveConfig(sources, { required: ["host", "port"] });
  assert.equal(resolved.value.host, "localhost");
  assert.equal(resolved.value.port, 9000);
  assert.equal(resolved.value.debug, true);
  assert.deepEqual(resolved.provenance, {
    host: "defaults",
    port: "file",
    debug: "env",
  });
});

test("rejects duplicate source names", () => {
  assert.throws(
    () => resolveConfig([{ name: "env", values: {} }, { name: "env", values: {} }]),
    /duplicate config source name/,
  );
});

test("reports missing required keys", () => {
  assert.throws(
    () => resolveConfig([{ name: "defaults", values: { host: "x" } }], { required: ["port"] }),
    /missing required config keys: port/,
  );
});

test("ignores undefined values from a source", () => {
  const resolved = resolveConfig([
    { name: "defaults", values: { port: 1 } },
    { name: "env", values: { port: undefined } },
  ]);
  assert.equal(resolved.value.port, 1);
  assert.equal(resolved.provenance.port, "defaults");
});

Dependencies and running

No external dependencies (standard library only).

Runtime: node >= 18 Entry point: node –experimental-strip-types example.ts

Limitations and error handling

shallow merge only; no schema coercion; no watch or reload.

Verification boundary

execution tests ran offline in an isolated temp dir with a sanitized environment; no network, no writes outside the sandbox

Interactive Tools for This Topic