@nirelc/microconf 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 ilyhalight
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,106 @@
1
+ <div align="center">
2
+ <h1>microconf</h1>
3
+ <p>Lightweight and simple type-safety config library over <a href="https://github.com/Nirelc/microtype">microtype</a></p>
4
+ <img src="./assets/hero.svg" width="100%" alt="microconf banner">
5
+ </div>
6
+
7
+ ---
8
+
9
+ ## Install
10
+
11
+ NPM
12
+
13
+ ```bash
14
+ npm install @nirelc/microconf
15
+ ```
16
+
17
+ Bun
18
+
19
+ ```bash
20
+ bun install @nirelc/microconf
21
+ ```
22
+
23
+ ## Usage
24
+
25
+ ```ts
26
+ import { defineConfig, t, env } from "@nirelc/microconf";
27
+
28
+ const config = defineConfig({
29
+ schema: {
30
+ port: t.number().min(0).max(65535).default(8080),
31
+ },
32
+ // optional. With no sources (or sources: []), use schema defaults only
33
+ sources: [env()],
34
+ });
35
+ ```
36
+
37
+ ## Sources
38
+
39
+ For each field, sources are checked in array order:
40
+
41
+ - missing value allows the next source to run
42
+ - invalid value cause `ParseConfigError`, other sources and defaults can't replace it
43
+ - if every source is missing the value, the schema is parsed with `undefined` and `.default()` or `.optional()` are applied
44
+
45
+ Sources return `undefined` from `load(meta)` only for missing values. For existing values, return the schema's `ParseResult`, including validation failures. A successful result containing `data: undefined` is still a resolved value, not a missing one.
46
+
47
+ Available sources:
48
+
49
+ ### `defaults()`
50
+
51
+ `defaults()` loads from schema `.default()` values
52
+
53
+ Defaults are always applied last by `defineConfig`, including with `sources: []`. You don't need to add `defaults()` explicitly
54
+
55
+ ### `env()`
56
+
57
+ `env()` loads from env variables. We doesn't load `.env` files!
58
+
59
+ Schema keys are converted to env variable names by:
60
+
61
+ - add prefix if provided. e.g., with prefix `APP_`, `token` becomes `APP_TOKEN`
62
+ - camelCase -> camel_Case
63
+ - all chars -> UPPERCASE
64
+ - nested keys are converted to flat env variable names by delimiter (default: `__`)
65
+
66
+ e.g.:
67
+
68
+ ```js
69
+ // index.ts
70
+ const config = defineConfig({
71
+ schema: {
72
+ nested: {
73
+ key: t.string(),
74
+ },
75
+ },
76
+ sources: [env()],
77
+ });
78
+
79
+ // .env
80
+ NESTED__KEY = hello;
81
+ ```
82
+
83
+ this source can be configured with options:
84
+
85
+ ```ts
86
+ env({
87
+ prefix: "APP_", // optional, default: undefined
88
+ delimiter: "__", // optional, default: "__"
89
+ forceCoerce: true, // optional, default: true
90
+ });
91
+ ```
92
+
93
+ `prefix` - prefix for env variable names. e.g., with prefix `APP_`, `token` becomes `APP_TOKEN`
94
+ `delimiter` - delimiter for nested keys. default: `__`
95
+ `forceCoerce` - boolean to force type coercion. default: `true`. e.g. if set to `false`, `t.boolean()` willn't coerce `"true"` to `true` and will return a parse error instead
96
+
97
+ ## Errors
98
+
99
+ With `APP_PORT=abc`, `prefix: "APP_"` and a numeric `port` schema:
100
+
101
+ ```text
102
+ Config parsing failed with 1 issue(s):
103
+ - APP_PORT from env: expected number
104
+ ```
105
+
106
+ `ParseConfigError.issues` preserves the validation message and full field `path`, with `source` and the environment `key`. Missing required values are reported against the final `defaults` source.
@@ -0,0 +1,4 @@
1
+ import { Config, InferSchema, Schema } from "./types.mjs";
2
+ //#region src/define.d.ts
3
+ export declare function defineConfig<const S extends Schema>({ schema, sources }: Config<S>): InferSchema<S>;
4
+ //#endregion
@@ -0,0 +1,33 @@
1
+ import { isRecord } from "./guards/object.mjs";
2
+ import { DefaultsSource, defaults } from "./sources/defaults.mjs";
3
+ import { setObjValueByPath } from "./utils.mjs";
4
+ import { ParseConfigError, ParseSchemaError, parseSchema } from "./parse.mjs";
5
+ import { formatPath } from "@nirelc/microtype";
6
+ //#region src/define.ts
7
+ function defineConfig({ schema, sources = [] }) {
8
+ if (!isRecord(schema)) throw new ParseSchemaError([{ message: "Schema must be an object" }]);
9
+ const metas = parseSchema(schema);
10
+ if (!metas.success) throw new ParseSchemaError(metas.issues);
11
+ const unparsedFields = new Map(metas.data.map((meta) => [formatPath(meta.path), meta]));
12
+ const issues = [];
13
+ const result = {};
14
+ for (const source of [...sources.filter((source) => !(source instanceof DefaultsSource)), defaults()]) for (const [key, meta] of unparsedFields.entries()) {
15
+ const data = source.load(meta);
16
+ if (data === void 0) continue;
17
+ unparsedFields.delete(key);
18
+ if (!data.success) {
19
+ const sourceIssues = data.issues.length ? data.issues : [{ message: "Invalid value" }];
20
+ issues.push(...sourceIssues.map((issue) => ({
21
+ ...issue,
22
+ path: [...meta.path, ...issue.path ?? []],
23
+ source: source.name
24
+ })));
25
+ continue;
26
+ }
27
+ setObjValueByPath(result, meta.path, data.data);
28
+ }
29
+ if (issues.length) throw new ParseConfigError(issues);
30
+ return result;
31
+ }
32
+ //#endregion
33
+ export { defineConfig };
@@ -0,0 +1,3 @@
1
+ //#region src/guards/object.d.ts
2
+ export declare function isRecord(value: unknown): value is Record<string, unknown>;
3
+ //#endregion
@@ -0,0 +1,6 @@
1
+ //#region src/guards/object.ts
2
+ function isRecord(value) {
3
+ return typeof value === "object" && value !== null && !Array.isArray(value);
4
+ }
5
+ //#endregion
6
+ export { isRecord };
@@ -0,0 +1,7 @@
1
+ import { Config, ConfigIssue, InferSchema, Schema, SchemaMeta, Source } from "./types.mjs";
2
+ import { defineConfig } from "./define.mjs";
3
+ import { env } from "./sources/env.mjs";
4
+ import { defaults } from "./sources/defaults.mjs";
5
+ import { ParseConfigError, ParseError, ParseSchemaError } from "./parse.mjs";
6
+ import * as t from "@nirelc/microtype";
7
+ export { Config, ConfigIssue, InferSchema, ParseConfigError, ParseError, ParseSchemaError, Schema, SchemaMeta, Source, defaults, defineConfig, env, t };
package/dist/index.mjs ADDED
@@ -0,0 +1,6 @@
1
+ import { defaults } from "./sources/defaults.mjs";
2
+ import { ParseConfigError, ParseError, ParseSchemaError } from "./parse.mjs";
3
+ import { defineConfig } from "./define.mjs";
4
+ import { env } from "./sources/env.mjs";
5
+ import * as t from "@nirelc/microtype";
6
+ export { ParseConfigError, ParseError, ParseSchemaError, defaults, defineConfig, env, t };
@@ -0,0 +1,18 @@
1
+ import { ConfigIssue, Schema as Schema$1, SchemaMeta } from "./types.mjs";
2
+ import { Issue, ParseResult } from "@nirelc/microtype";
3
+ //#region src/parse.d.ts
4
+ export declare class ParseError extends Error {
5
+ readonly issues: Issue[];
6
+ readonly context: string;
7
+ constructor(issues: Issue[], context: string);
8
+ }
9
+ export declare class ParseConfigError extends ParseError {
10
+ override readonly issues: ConfigIssue[];
11
+ constructor(issues: ConfigIssue[]);
12
+ }
13
+ export declare class ParseSchemaError extends ParseError {
14
+ override readonly issues: Issue[];
15
+ constructor(issues: Issue[]);
16
+ }
17
+ export declare function parseSchema(schema: Schema$1, path?: PropertyKey[]): ParseResult<SchemaMeta[]>;
18
+ //#endregion
package/dist/parse.mjs ADDED
@@ -0,0 +1,67 @@
1
+ import { isRecord } from "./guards/object.mjs";
2
+ import { BaseSchema, formatIssue, formatPath } from "@nirelc/microtype";
3
+ //#region src/parse.ts
4
+ var ParseError = class extends Error {
5
+ issues;
6
+ context;
7
+ constructor(issues, context) {
8
+ super(`${context} failed with ${issues.length} issue(s):\n${issues.map((issue) => {
9
+ if (issue.source === void 0) return `- ${formatIssue(issue)}`;
10
+ const location = issue.key ?? formatPath(issue.path ?? []);
11
+ const message = issue.message.replace(/^[A-Z]/, (char) => char.toLowerCase());
12
+ return `- ${location} from ${issue.source}: ${message}`;
13
+ }).join("\n")}`);
14
+ this.issues = issues;
15
+ this.context = context;
16
+ this.name = "ParseError";
17
+ }
18
+ };
19
+ var ParseConfigError = class extends ParseError {
20
+ issues;
21
+ constructor(issues) {
22
+ super(issues, "Config parsing");
23
+ this.issues = issues;
24
+ this.name = "ParseConfigError";
25
+ }
26
+ };
27
+ var ParseSchemaError = class extends ParseError {
28
+ issues;
29
+ constructor(issues) {
30
+ super(issues, "Schema parsing");
31
+ this.issues = issues;
32
+ this.name = "ParseSchemaError";
33
+ }
34
+ };
35
+ function parseSchema(schema, path = []) {
36
+ if (!isRecord(schema)) return {
37
+ success: false,
38
+ issues: [{ message: `Field '${formatPath(path)}' must be a 'TSchema | Schema' object` }]
39
+ };
40
+ const meta = [];
41
+ const issues = [];
42
+ for (const [key, value] of Object.entries(schema)) {
43
+ if (value instanceof BaseSchema) {
44
+ meta.push({
45
+ key,
46
+ path: [...path, key],
47
+ schema: value
48
+ });
49
+ continue;
50
+ }
51
+ const result = parseSchema(value, [...path, key]);
52
+ if (!result.success) {
53
+ issues.push(...result.issues);
54
+ continue;
55
+ }
56
+ meta.push(...result.data);
57
+ }
58
+ return issues.length ? {
59
+ success: false,
60
+ issues
61
+ } : {
62
+ success: true,
63
+ data: meta
64
+ };
65
+ }
66
+ //#endregion
67
+ export { ParseConfigError, ParseError, ParseSchemaError, parseSchema };
@@ -0,0 +1,9 @@
1
+ import { SchemaMeta, Source } from "../types.mjs";
2
+ import { ParseResult } from "@nirelc/microtype";
3
+ //#region src/sources/defaults.d.ts
4
+ export declare class DefaultsSource implements Source {
5
+ name: string;
6
+ load(meta: SchemaMeta): ParseResult<unknown>;
7
+ }
8
+ export declare function defaults(): DefaultsSource;
9
+ //#endregion
@@ -0,0 +1,12 @@
1
+ //#region src/sources/defaults.ts
2
+ var DefaultsSource = class {
3
+ name = "defaults";
4
+ load(meta) {
5
+ return meta.schema._parse(void 0);
6
+ }
7
+ };
8
+ function defaults() {
9
+ return new DefaultsSource();
10
+ }
11
+ //#endregion
12
+ export { DefaultsSource, defaults };
@@ -0,0 +1,24 @@
1
+ import { SchemaMeta, Source } from "../types.mjs";
2
+ import { ParseResult } from "@nirelc/microtype";
3
+ //#region src/sources/env.d.ts
4
+ export type EnvSourceOptions = {
5
+ prefix?: string;
6
+ delimiter?: string;
7
+ /**
8
+ * force set the coerce option to true for all schemas
9
+ * useful, because env variables are always strings, and we want to coerce them to the correct type
10
+ */
11
+ forceCoerce?: boolean;
12
+ };
13
+ export declare class EnvSource implements Source {
14
+ prefix: string;
15
+ delimiter: string;
16
+ forceCoerce: boolean;
17
+ name: string;
18
+ constructor({ prefix, delimiter, forceCoerce }?: EnvSourceOptions);
19
+ getKeyByPath(path: PropertyKey[]): string;
20
+ getValueByPath(path: PropertyKey[]): string | undefined;
21
+ load(meta: SchemaMeta): ParseResult<unknown> | undefined;
22
+ }
23
+ export declare function env(opts?: EnvSourceOptions): EnvSource;
24
+ //#endregion
@@ -0,0 +1,47 @@
1
+ import { insertWordSep } from "../utils.mjs";
2
+ import { DefaultSchema, OptionalSchema } from "@nirelc/microtype";
3
+ //#region src/sources/env.ts
4
+ function enableCoercion(schema) {
5
+ if (schema instanceof DefaultSchema || schema instanceof OptionalSchema) return enableCoercion(schema.inner);
6
+ if ("coerce" in schema && typeof schema.coerce === "function") return schema.coerce(true);
7
+ return schema;
8
+ }
9
+ var EnvSource = class {
10
+ prefix;
11
+ delimiter;
12
+ forceCoerce;
13
+ name = "env";
14
+ constructor({ prefix = "", delimiter = "__", forceCoerce = true } = {}) {
15
+ this.prefix = prefix.trim();
16
+ this.delimiter = delimiter;
17
+ this.forceCoerce = forceCoerce;
18
+ }
19
+ getKeyByPath(path) {
20
+ return `${this.prefix}${path.map((p) => {
21
+ if (typeof p === "string") return insertWordSep(p);
22
+ return p;
23
+ }).join(this.delimiter)}`.toUpperCase();
24
+ }
25
+ getValueByPath(path) {
26
+ return process.env[this.getKeyByPath(path)];
27
+ }
28
+ load(meta) {
29
+ const value = this.getValueByPath(meta.path);
30
+ if (value === void 0) return;
31
+ const result = (this.forceCoerce ? enableCoercion(meta.schema) : meta.schema)._parse(value);
32
+ if (result.success) return result;
33
+ const key = this.getKeyByPath(meta.path);
34
+ return {
35
+ success: false,
36
+ issues: result.issues.map((issue) => ({
37
+ ...issue,
38
+ key
39
+ }))
40
+ };
41
+ }
42
+ };
43
+ function env(opts) {
44
+ return new EnvSource(opts);
45
+ }
46
+ //#endregion
47
+ export { EnvSource, env };
@@ -0,0 +1,24 @@
1
+ import { Issue, ParseResult, Schema as Schema$1 } from "@nirelc/microtype";
2
+ //#region src/types.d.ts
3
+ export type Schema = {
4
+ [key: string]: Schema$1 | Schema;
5
+ };
6
+ export type InferSchema<S extends Schema> = { -readonly [K in keyof S]: S[K] extends Schema$1<infer T> ? T : S[K] extends Schema ? InferSchema<S[K]> : never; };
7
+ export type Config<S extends Schema = Schema> = {
8
+ schema: S;
9
+ sources?: Source[];
10
+ };
11
+ export type SchemaMeta = {
12
+ key: string;
13
+ path: PropertyKey[];
14
+ schema: Schema$1;
15
+ };
16
+ export type ConfigIssue = Issue & {
17
+ source?: string;
18
+ key?: string;
19
+ };
20
+ export interface Source {
21
+ name: string;
22
+ load(meta: SchemaMeta): ParseResult<unknown> | undefined;
23
+ }
24
+ //#endregion
package/dist/types.mjs ADDED
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,4 @@
1
+ //#region src/utils.d.ts
2
+ export declare const insertWordSep: (word: string) => string;
3
+ export declare function setObjValueByPath(obj: Record<string, unknown>, path: PropertyKey[], value: unknown): undefined;
4
+ //#endregion
package/dist/utils.mjs ADDED
@@ -0,0 +1,17 @@
1
+ import { isRecord } from "./guards/object.mjs";
2
+ //#region src/utils.ts
3
+ const insertWordSep = (word) => {
4
+ return word.replace(/([a-z0-9])([A-Z])/g, "$1_$2");
5
+ };
6
+ function setObjValueByPath(obj, path, value) {
7
+ if (!path.length) return;
8
+ const key = path[0];
9
+ if (path.length === 1) {
10
+ obj[key] = value;
11
+ return;
12
+ }
13
+ if (!isRecord(obj[key])) obj[key] = {};
14
+ return setObjValueByPath(obj[key], path.slice(1), value);
15
+ }
16
+ //#endregion
17
+ export { insertWordSep, setObjValueByPath };
package/package.json ADDED
@@ -0,0 +1,71 @@
1
+ {
2
+ "name": "@nirelc/microconf",
3
+ "description": "Lightweight and simple type-safety config library over microtype",
4
+ "author": "Toil",
5
+ "version": "0.0.1",
6
+ "license": "MIT",
7
+ "type": "module",
8
+ "homepage": "https://github.com/nirelc/microconf#readme",
9
+ "bugs": {
10
+ "url": "https://github.com/nirelc/microconf/issues"
11
+ },
12
+ "keywords": [
13
+ "config",
14
+ "env",
15
+ "configuration",
16
+ "conf",
17
+ "micro",
18
+ "type",
19
+ "safe",
20
+ "system",
21
+ "typings",
22
+ "fast",
23
+ "lightweight",
24
+ "lib"
25
+ ],
26
+ "publishConfig": {
27
+ "access": "public"
28
+ },
29
+ "devDependencies": {
30
+ "@types/bun": "latest",
31
+ "publint": "^0.3.24",
32
+ "tsdown": "^0.23.0",
33
+ "typescript": "^7.0.2"
34
+ },
35
+ "exports": {
36
+ ".": {
37
+ "types": "./dist/index.d.mts",
38
+ "import": "./dist/index.mjs"
39
+ },
40
+ "./define": {
41
+ "types": "./dist/define.d.mts",
42
+ "import": "./dist/define.mjs"
43
+ },
44
+ "./types": {
45
+ "types": "./dist/types.d.mts",
46
+ "import": "./dist/types.mjs"
47
+ },
48
+ "./utils": {
49
+ "types": "./dist/utils.d.mts",
50
+ "import": "./dist/utils.mjs"
51
+ },
52
+ "./sources/*": {
53
+ "types": "./dist/sources/*.d.mts",
54
+ "import": "./dist/sources/*.mjs"
55
+ }
56
+ },
57
+ "scripts": {
58
+ "build": "tsdown",
59
+ "build:bun": "bunx tsdown"
60
+ },
61
+ "main": "./dist/index.mjs",
62
+ "module": "./dist/index.mjs",
63
+ "types": "./dist/index.d.mts",
64
+ "files": [
65
+ "./dist"
66
+ ],
67
+ "sideEffects": false,
68
+ "dependencies": {
69
+ "@nirelc/microtype": "^0.0.2"
70
+ }
71
+ }