Read configuration files
Parse JSON with comments and trailing commas, point a mistake at its line and column, validate the result, and hand it to every command of a command line.
Last updated by
After reading this guide, you will know
- How to parse JSONC with comments and trailing commas
- How to point a mistake at its line and column and validate the shape
- How to hand the parsed config to every command of a command line
A configuration file is written by people, so it wants comments that say why a setting is set,
and it forgives the trailing comma left behind when a line is deleted. That is JSONC, the
format of tsconfig.json, editor settings and many tools' own files: JSON plus // and
/* */ comments and trailing commas in objects and arrays.
This guide reads a deploy.jsonc for a deploy tool with @sdxc/jsonc, which
parses JSONC into exactly what JSON.parse would produce and answers a mistake with its line
and column, in a Result.
npm add @sdxc/cli @sdxc/jsonc @sdxc/result remixWrite the file
{
// The bucket the site is uploaded to
"bucket": "assets-production",
"regions": [
"eu-west",
"us-east", // added for the launch
],
/* Seconds a CDN may keep a page */
"maxAge": 300,
}Everything else follows JSON exactly: unquoted keys and single-quoted strings, which JSON5 allows, are mistakes here.
Parse it and point at the mistake
parse answers the value, or a JSONCParseError whose message ends with the position:
import { readFile } from "node:fs/promises";
import { parse } from "@sdxc/jsonc";
import { failure, isFailure, success, wrap } from "@sdxc/result";
export async function readConfigText(path: string) {
let text = await wrap(() => readFile(path, "utf8"));
if (isFailure(text)) return failure(new Error(`${path} could not be read`));
let parsed = parse(text.data);
if (isFailure(parsed)) {
let { reason, line, column } = parsed.error;
return failure(new Error(`${path}:${line}:${column}: ${reason}`));
}
return success(parsed.data);
}Written as path:line:column, the position is one an editor or a terminal opens straight at the
character, and it reads the same on Node, Bun, Deno and Cloudflare Workers. line and column
count from one.
Validate the shape
A file that parses can still hold the wrong thing: a missing bucket, a string where a number goes. Check the value with a schema once it parses, and report both kinds of mistake with the file's name:
import * as s from "remix/data-schema";
import { min } from "remix/data-schema/checks";
const DEPLOY_CONFIG = s.object({
bucket: s.string(),
regions: s.array(s.string()),
maxAge: s.defaulted(s.number().pipe(min(0)), 300),
});
export type DeployConfig = s.InferOutput<typeof DEPLOY_CONFIG>;
export async function loadConfig(path: string) {
let value = await readConfigText(path);
if (isFailure(value)) return value;
let checked = s.parseSafe(DEPLOY_CONFIG, value.data);
if (!checked.success) {
let messages = checked.issues.map((issue) => issue.message).join("; ");
return failure(new Error(`${path}: ${messages}`));
}
return success(checked.value);
}defaulted fills maxAge when the file leaves it out, so the rest of the tool reads a number
and never checks for absence.
Hand it to every command
A command line reads its configuration once per run, in middleware, and every handler receives it typed:
import type { CommandMiddleware } from "@sdxc/cli";
import { join } from "node:path";
import { isFailure } from "@sdxc/result";
import { createContextKey } from "remix/router";
import type { DeployConfig } from "../config.js";
import { loadConfig } from "../config.js";
export const Config = createContextKey<DeployConfig>();
export function config(): CommandMiddleware<{
key: typeof Config;
value: DeployConfig;
property: "config";
}> {
return async (ctx, next) => {
let loaded = await loadConfig(join(ctx.cwd, "deploy.jsonc"));
if (isFailure(loaded)) return loaded;
ctx.set(Config, loaded.data, { property: "config" });
await next();
};
}A failure returned from the middleware ends the run with its message, before any handler, so
deploy.jsonc:10:1: Unexpected character '}' is the whole output of a run against a broken file.
Build a command line writes the rest of the
tool.
Test it
loadConfig reads a path, so a test writes the file it needs into a temporary folder and
checks both answers: the parsed value with its default filled in, and a mistake reported at its
line and column.
import { mkdtemp, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { failure, success } from "@sdxc/result";
import { expect, test } from "vitest";
import { loadConfig } from "./config.js";
async function write(...lines: string[]) {
let path = join(await mkdtemp(join(tmpdir(), "deploy-")), "deploy.jsonc");
await writeFile(path, lines.join("\n"));
return path;
}
test("reads comments and trailing commas, and fills maxAge", async () => {
let path = await write(
"{",
"// production",
'"bucket": "assets",',
'"regions": ["eu-west",],',
"}",
);
expect(await loadConfig(path)).toEqual(
success({ bucket: "assets", regions: ["eu-west"], maxAge: 300 }),
);
});
test("points a mistake at its line and column", async () => {
let path = await write("{", '"bucket": assets', "}");
expect(await loadConfig(path)).toEqual(
failure(new Error(`${path}:2:11: Unexpected character 'a'`)),
);
});Run it from the terminal
sdxc pkg jsonc checks the same file before a deploy reads it, which suits a CI step, and
prints it as plain JSON for a tool that only reads JSON:
sdxc pkg jsonc check deploy.jsonc
sdxc pkg jsonc check deploy.jsonc --json
sdxc pkg jsonc strip deploy.jsonc --indent 2 > deploy.jsoncheck prints the same file:line:column the loader reports and exits 1 on a mistake.
strip without --indent keeps every line and column where it was, and exits 2 on text that
is not JSONC, so its output is always valid JSON. See
Use a package from the terminal for the
conventions every package command line shares.
Where to go next
Build a command line — the commands this configuration is handed to.
Standard Schema validation — the schemas that check the parsed value.
@sdxc/jsonc— every field of the parse error.