@meltstudio/config-loader 3.0.2 → 3.2.0

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 CHANGED
@@ -1,201 +1,21 @@
1
- Apache License
2
- Version 2.0, January 2004
3
- http://www.apache.org/licenses/
4
-
5
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
-
7
- 1. Definitions.
8
-
9
- "License" shall mean the terms and conditions for use, reproduction,
10
- and distribution as defined by Sections 1 through 9 of this document.
11
-
12
- "Licensor" shall mean the copyright owner or entity authorized by
13
- the copyright owner that is granting the License.
14
-
15
- "Legal Entity" shall mean the union of the acting entity and all
16
- other entities that control, are controlled by, or are under common
17
- control with that entity. For the purposes of this definition,
18
- "control" means (i) the power, direct or indirect, to cause the
19
- direction or management of such entity, whether by contract or
20
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
- outstanding shares, or (iii) beneficial ownership of such entity.
22
-
23
- "You" (or "Your") shall mean an individual or Legal Entity
24
- exercising permissions granted by this License.
25
-
26
- "Source" form shall mean the preferred form for making modifications,
27
- including but not limited to software source code, documentation
28
- source, and configuration files.
29
-
30
- "Object" form shall mean any form resulting from mechanical
31
- transformation or translation of a Source form, including but
32
- not limited to compiled object code, generated documentation,
33
- and conversions to other media types.
34
-
35
- "Work" shall mean the work of authorship, whether in Source or
36
- Object form, made available under the License, as indicated by a
37
- copyright notice that is included in or attached to the work
38
- (an example is provided in the Appendix below).
39
-
40
- "Derivative Works" shall mean any work, whether in Source or Object
41
- form, that is based on (or derived from) the Work and for which the
42
- editorial revisions, annotations, elaborations, or other modifications
43
- represent, as a whole, an original work of authorship. For the purposes
44
- of this License, Derivative Works shall not include works that remain
45
- separable from, or merely link (or bind by name) to the interfaces of,
46
- the Work and Derivative Works thereof.
47
-
48
- "Contribution" shall mean any work of authorship, including
49
- the original version of the Work and any modifications or additions
50
- to that Work or Derivative Works thereof, that is intentionally
51
- submitted to Licensor for inclusion in the Work by the copyright owner
52
- or by an individual or Legal Entity authorized to submit on behalf of
53
- the copyright owner. For the purposes of this definition, "submitted"
54
- means any form of electronic, verbal, or written communication sent
55
- to the Licensor or its representatives, including but not limited to
56
- communication on electronic mailing lists, source code control systems,
57
- and issue tracking systems that are managed by, or on behalf of, the
58
- Licensor for the purpose of discussing and improving the Work, but
59
- excluding communication that is conspicuously marked or otherwise
60
- designated in writing by the copyright owner as "Not a Contribution."
61
-
62
- "Contributor" shall mean Licensor and any individual or Legal Entity
63
- on behalf of whom a Contribution has been received by Licensor and
64
- subsequently incorporated within the Work.
65
-
66
- 2. Grant of Copyright License. Subject to the terms and conditions of
67
- this License, each Contributor hereby grants to You a perpetual,
68
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
- copyright license to reproduce, prepare Derivative Works of,
70
- publicly display, publicly perform, sublicense, and distribute the
71
- Work and such Derivative Works in Source or Object form.
72
-
73
- 3. Grant of Patent License. Subject to the terms and conditions of
74
- this License, each Contributor hereby grants to You a perpetual,
75
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
- (except as stated in this section) patent license to make, have made,
77
- use, offer to sell, sell, import, and otherwise transfer the Work,
78
- where such license applies only to those patent claims licensable
79
- by such Contributor that are necessarily infringed by their
80
- Contribution(s) alone or by combination of their Contribution(s)
81
- with the Work to which such Contribution(s) was submitted. If You
82
- institute patent litigation against any entity (including a
83
- cross-claim or counterclaim in a lawsuit) alleging that the Work
84
- or a Contribution incorporated within the Work constitutes direct
85
- or contributory patent infringement, then any patent licenses
86
- granted to You under this License for that Work shall terminate
87
- as of the date such litigation is filed.
88
-
89
- 4. Redistribution. You may reproduce and distribute copies of the
90
- Work or Derivative Works thereof in any medium, with or without
91
- modifications, and in Source or Object form, provided that You
92
- meet the following conditions:
93
-
94
- (a) You must give any other recipients of the Work or
95
- Derivative Works a copy of this License; and
96
-
97
- (b) You must cause any modified files to carry prominent notices
98
- stating that You changed the files; and
99
-
100
- (c) You must retain, in the Source form of any Derivative Works
101
- that You distribute, all copyright, patent, trademark, and
102
- attribution notices from the Source form of the Work,
103
- excluding those notices that do not pertain to any part of
104
- the Derivative Works; and
105
-
106
- (d) If the Work includes a "NOTICE" text file as part of its
107
- distribution, then any Derivative Works that You distribute must
108
- include a readable copy of the attribution notices contained
109
- within such NOTICE file, excluding those notices that do not
110
- pertain to any part of the Derivative Works, in at least one
111
- of the following places: within a NOTICE text file distributed
112
- as part of the Derivative Works; within the Source form or
113
- documentation, if provided along with the Derivative Works; or,
114
- within a display generated by the Derivative Works, if and
115
- wherever such third-party notices normally appear. The contents
116
- of the NOTICE file are for informational purposes only and
117
- do not modify the License. You may add Your own attribution
118
- notices within Derivative Works that You distribute, alongside
119
- or as an addendum to the NOTICE text from the Work, provided
120
- that such additional attribution notices cannot be construed
121
- as modifying the License.
122
-
123
- You may add Your own copyright statement to Your modifications and
124
- may provide additional or different license terms and conditions
125
- for use, reproduction, or distribution of Your modifications, or
126
- for any such Derivative Works as a whole, provided Your use,
127
- reproduction, and distribution of the Work otherwise complies with
128
- the conditions stated in this License.
129
-
130
- 5. Submission of Contributions. Unless You explicitly state otherwise,
131
- any Contribution intentionally submitted for inclusion in the Work
132
- by You to the Licensor shall be under the terms and conditions of
133
- this License, without any additional terms or conditions.
134
- Notwithstanding the above, nothing herein shall supersede or modify
135
- the terms of any separate license agreement you may have executed
136
- with Licensor regarding such Contributions.
137
-
138
- 6. Trademarks. This License does not grant permission to use the trade
139
- names, trademarks, service marks, or product names of the Licensor,
140
- except as required for reasonable and customary use in describing the
141
- origin of the Work and reproducing the content of the NOTICE file.
142
-
143
- 7. Disclaimer of Warranty. Unless required by applicable law or
144
- agreed to in writing, Licensor provides the Work (and each
145
- Contributor provides its Contributions) on an "AS IS" BASIS,
146
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
- implied, including, without limitation, any warranties or conditions
148
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
- PARTICULAR PURPOSE. You are solely responsible for determining the
150
- appropriateness of using or redistributing the Work and assume any
151
- risks associated with Your exercise of permissions under this License.
152
-
153
- 8. Limitation of Liability. In no event and under no legal theory,
154
- whether in tort (including negligence), contract, or otherwise,
155
- unless required by applicable law (such as deliberate and grossly
156
- negligent acts) or agreed to in writing, shall any Contributor be
157
- liable to You for damages, including any direct, indirect, special,
158
- incidental, or consequential damages of any character arising as a
159
- result of this License or out of the use or inability to use the
160
- Work (including but not limited to damages for loss of goodwill,
161
- work stoppage, computer failure or malfunction, or any and all
162
- other commercial damages or losses), even if such Contributor
163
- has been advised of the possibility of such damages.
164
-
165
- 9. Accepting Warranty or Additional Liability. While redistributing
166
- the Work or Derivative Works thereof, You may choose to offer,
167
- and charge a fee for, acceptance of support, warranty, indemnity,
168
- or other liability obligations and/or rights consistent with this
169
- License. However, in accepting such obligations, You may act only
170
- on Your own behalf and on Your sole responsibility, not on behalf
171
- of any other Contributor, and only if You agree to indemnify,
172
- defend, and hold each Contributor harmless for any liability
173
- incurred by, or claims asserted against, such Contributor by reason
174
- of your accepting any such warranty or additional liability.
175
-
176
- END OF TERMS AND CONDITIONS
177
-
178
- APPENDIX: How to apply the Apache License to your work.
179
-
180
- To apply the Apache License to your work, attach the following
181
- boilerplate notice, with the fields enclosed by brackets "[]"
182
- replaced with your own identifying information. (Don't include
183
- the brackets!) The text should be enclosed in the appropriate
184
- comment syntax for the file format. We also recommend that a
185
- file or class name and description of purpose be included on the
186
- same "printed page" as the copyright notice for easier
187
- identification within third-party archives.
188
-
189
- Copyright [yyyy] [name of copyright owner]
190
-
191
- Licensed under the Apache License, Version 2.0 (the "License");
192
- you may not use this file except in compliance with the License.
193
- You may obtain a copy of the License at
194
-
195
- http://www.apache.org/licenses/LICENSE-2.0
196
-
197
- Unless required by applicable law or agreed to in writing, software
198
- distributed under the License is distributed on an "AS IS" BASIS,
199
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
- See the License for the specific language governing permissions and
201
- limitations under the License.
1
+ MIT License
2
+
3
+ Copyright (c) 2024 MeltStudio
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 CHANGED
@@ -61,6 +61,7 @@ No separate interface to maintain. No `as` casts. The types flow from the schema
61
61
  - **`.env` file support** — load environment variables from `.env` files with automatic line tracking
62
62
  - **Nested objects and arrays** — deeply nested configs with full type safety
63
63
  - **Structured errors** — typed `ConfigLoadError` with per-field error details and warnings
64
+ - **Schema validation** — optional per-field validation via [Standard Schema](https://github.com/standard-schema/standard-schema) (Zod, Valibot, ArkType, or custom)
64
65
  - **Strict mode** — promote warnings to errors for production safety
65
66
  - **Default values** — static or computed (via functions)
66
67
  - **Multiple files / directory loading** — load from a list of files or an entire directory
@@ -252,6 +253,74 @@ c.array({
252
253
  }); // { name: string; age: number }[]
253
254
  ```
254
255
 
256
+ ## Validation
257
+
258
+ Add per-field validation using the `validate` option. config-loader accepts any [Standard Schema v1](https://github.com/standard-schema/standard-schema) implementation — including **Zod**, **Valibot**, and **ArkType** — or a custom validator.
259
+
260
+ Validation runs **after** type coercion, so validators see the final typed value (e.g., the number `3000`, not the string `"3000"` from an env var).
261
+
262
+ ### With Zod
263
+
264
+ ```typescript
265
+ import c from "@meltstudio/config-loader";
266
+ import { z } from "zod";
267
+
268
+ const config = c
269
+ .schema({
270
+ port: c.number({
271
+ required: true,
272
+ env: "PORT",
273
+ validate: z.number().min(1).max(65535),
274
+ }),
275
+ host: c.string({
276
+ required: true,
277
+ validate: z.string().url(),
278
+ }),
279
+ env: c.string({
280
+ defaultValue: "development",
281
+ validate: z.enum(["development", "staging", "production"]),
282
+ }),
283
+ })
284
+ .load({ env: true, args: false, files: "./config.yaml" });
285
+ ```
286
+
287
+ ### With a custom validator
288
+
289
+ Any object with a `~standard.validate()` method works:
290
+
291
+ ```typescript
292
+ const portValidator = {
293
+ "~standard": {
294
+ version: 1,
295
+ vendor: "my-app",
296
+ validate(value: unknown) {
297
+ if (typeof value === "number" && value >= 1 && value <= 65535) {
298
+ return { value };
299
+ }
300
+ return { issues: [{ message: "must be a valid port (1-65535)" }] };
301
+ },
302
+ },
303
+ };
304
+
305
+ c.number({ required: true, env: "PORT", validate: portValidator });
306
+ ```
307
+
308
+ Validation errors are collected alongside other config errors and thrown as `ConfigLoadError` with `kind: "validation"`:
309
+
310
+ ```typescript
311
+ try {
312
+ const config = c.schema({ ... }).load({ ... });
313
+ } catch (err) {
314
+ if (err instanceof ConfigLoadError) {
315
+ for (const entry of err.errors) {
316
+ if (entry.kind === "validation") {
317
+ console.error(`Validation: ${entry.path} — ${entry.message}`);
318
+ }
319
+ }
320
+ }
321
+ }
322
+ ```
323
+
255
324
  ## Loading Sources
256
325
 
257
326
  ```typescript
@@ -313,6 +382,41 @@ console.log(data.port.variableName); // "PORT"
313
382
 
314
383
  This is useful for debugging configuration resolution, building admin UIs that show where each setting originated, or auditing which sources are active.
315
384
 
385
+ ### Debug Helper
386
+
387
+ Use `printConfig()` to format the result of `loadExtended()` as a readable table:
388
+
389
+ ```typescript
390
+ import c, { printConfig } from "@meltstudio/config-loader";
391
+
392
+ const result = c
393
+ .schema({
394
+ host: c.string({ defaultValue: "localhost" }),
395
+ port: c.number({ env: "PORT" }),
396
+ debug: c.bool({ cli: true }),
397
+ })
398
+ .loadExtended({ env: true, args: true, files: "./config.yaml" });
399
+
400
+ printConfig(result);
401
+ ```
402
+
403
+ Output:
404
+
405
+ ```
406
+ ┌───────┬───────────┬─────────┬────────────────┐
407
+ │ Path │ Value │ Source │ Detail │
408
+ ├───────┼───────────┼─────────┼────────────────┤
409
+ │ host │ localhost │ default │ │
410
+ │ port │ 8080 │ env │ PORT │
411
+ │ debug │ true │ args │ --debug │
412
+ └───────┴───────────┴─────────┴────────────────┘
413
+ ```
414
+
415
+ Options:
416
+
417
+ - `printConfig(result, { silent: true })` — returns the string without printing to console
418
+ - `printConfig(result, { maxValueLength: 30 })` — truncate long values (default: 50)
419
+
316
420
  ## Error Handling
317
421
 
318
422
  When validation fails, config-loader throws a `ConfigLoadError` with structured error details:
@@ -353,6 +457,35 @@ Enable `strict: true` to promote all warnings to errors, causing `ConfigLoadErro
353
457
 
354
458
  This is useful in production environments where you want to catch type coercions, null values, and other ambiguous config early rather than silently accepting them.
355
459
 
460
+ ## TypeScript Utilities
461
+
462
+ config-loader exports several types for advanced use cases:
463
+
464
+ ```typescript
465
+ import c, {
466
+ type SchemaValue, // Infer the resolved config type from a schema
467
+ type SettingsSources, // Type for the sources object passed to load()
468
+ type ExtendedResult, // Return type of loadExtended()
469
+ type NodeTree, // Tree of ConfigNode objects (ExtendedResult.data)
470
+ ConfigNode, // Class representing a resolved value with source metadata
471
+ ConfigNodeArray, // Class representing an array of ConfigNode values
472
+ type RecursivePartial, // Deep partial utility used by the defaults option
473
+ type StandardSchemaV1, // Standard Schema v1 interface for validators
474
+ } from "@meltstudio/config-loader";
475
+ ```
476
+
477
+ The most commonly needed is `SchemaValue`, which infers the plain TypeScript type from a schema:
478
+
479
+ ```typescript
480
+ const mySchema = {
481
+ port: c.number({ env: "PORT" }),
482
+ db: c.object({ item: { host: c.string(), port: c.number() } }),
483
+ };
484
+
485
+ type MyConfig = SchemaValue<typeof mySchema>;
486
+ // { port: number; db: { host: string; port: number } }
487
+ ```
488
+
356
489
  ## CLI Arguments
357
490
 
358
491
  Set `cli: true` on an option to allow overriding via command line:
@@ -612,4 +745,4 @@ These files follow the [llms.txt standard](https://llmstxt.org/) and are generat
612
745
 
613
746
  ## License
614
747
 
615
- This package is licensed under the Apache License 2.0. See the [LICENSE](./LICENSE) file for details.
748
+ This package is licensed under the MIT License. See the [LICENSE](./LICENSE) file for details.
package/dist/index.d.ts CHANGED
@@ -23,7 +23,7 @@ interface ConfigErrorEntry {
23
23
  /** The source where the error originated (e.g. file path, `"env"`, `"cli"`). */
24
24
  source?: string;
25
25
  /** Classification of the error. */
26
- kind?: "required" | "type_conversion" | "invalid_path" | "invalid_state" | "file_validation" | "null_value" | "strict";
26
+ kind?: "required" | "type_conversion" | "invalid_path" | "invalid_state" | "file_validation" | "null_value" | "strict" | "validation";
27
27
  /** Line number in the config file where the error occurred, if applicable. */
28
28
  line?: number;
29
29
  /** Column number in the config file where the error occurred, if applicable. */
@@ -61,6 +61,7 @@ interface OptionClassParams<T extends OptionKind> {
61
61
  cli: boolean;
62
62
  help: string;
63
63
  defaultValue?: TypedDefaultValue<T>;
64
+ validate?: StandardSchemaV1;
64
65
  }
65
66
  declare class OptionBase<T extends OptionKind = OptionKind> {
66
67
  readonly params: OptionClassParams<T>;
@@ -79,6 +80,8 @@ declare class OptionBase<T extends OptionKind = OptionKind> {
79
80
  } | undefined;
80
81
  } | null;
81
82
  }, envFileResults?: EnvFileResult[], errors?: OptionErrors): ConfigNode | null;
83
+ private resolveValue;
84
+ private runValidation;
82
85
  private resolveFromFileData;
83
86
  checkType(val: Value, path: Path, sourceOfVal: string, errors?: OptionErrors): Value;
84
87
  protected findInObject(obj: ConfigFileData, path: Path, errors?: OptionErrors): Value | ArrayValue;
@@ -149,11 +152,37 @@ interface ConfigFileData extends ConfigFileStructure<ConfigFileData> {
149
152
  type ArrayValue = Array<string | number | boolean | ConfigFileData>;
150
153
  declare class InvalidValue {
151
154
  }
155
+ /**
156
+ * A single issue returned by a Standard Schema validator.
157
+ * Mirrors the Standard Schema v1 spec (https://github.com/standard-schema/standard-schema).
158
+ */
159
+ interface StandardSchemaIssue {
160
+ message: string;
161
+ path?: ReadonlyArray<PropertyKey | object>;
162
+ }
163
+ type StandardSchemaResult<Output> = {
164
+ value: Output;
165
+ } | {
166
+ issues: ReadonlyArray<StandardSchemaIssue>;
167
+ };
168
+ /**
169
+ * Minimal Standard Schema v1 interface for value validation.
170
+ * Any object with a `~standard.validate()` method is accepted — this covers
171
+ * Zod 3.24+/4+, Valibot 1.0+, ArkType 2.1+, and custom validators.
172
+ */
173
+ interface StandardSchemaV1<Output = unknown> {
174
+ "~standard": {
175
+ version: 1;
176
+ vendor: string;
177
+ validate(value: unknown): StandardSchemaResult<Output> | Promise<StandardSchemaResult<Output>>;
178
+ };
179
+ }
152
180
 
153
181
  interface ArrayOptionClassParams<T extends OptionTypes> {
154
182
  required: boolean;
155
183
  defaultValue?: SchemaValue<T>[] | (() => SchemaValue<T>[]);
156
184
  item: T;
185
+ validate?: StandardSchemaV1;
157
186
  }
158
187
  declare class ArrayOption<T extends OptionTypes> extends OptionBase<"array"> {
159
188
  item: T;
@@ -165,6 +194,7 @@ declare class ArrayOption<T extends OptionTypes> extends OptionBase<"array"> {
165
194
  interface ObjectOptionClassParams<T extends Node> {
166
195
  required: boolean;
167
196
  item: T;
197
+ validate?: StandardSchemaV1;
168
198
  }
169
199
  declare class ObjectOption<T extends Node = Node> extends OptionBase<"object"> {
170
200
  item: T;
@@ -193,6 +223,31 @@ declare class SettingsBuilder<T extends Node> {
193
223
  loadExtended(sources: SettingsSources<SchemaValue<T>>): ExtendedResult;
194
224
  }
195
225
 
226
+ declare class ConfigNodeArray {
227
+ arrayValues: ConfigNode[];
228
+ constructor(arrayValues: ConfigNode[]);
229
+ }
230
+
231
+ /**
232
+ * Formats the result of `loadExtended()` as a readable table showing each
233
+ * resolved value and where it came from.
234
+ *
235
+ * @param result - The `ExtendedResult` returned by `loadExtended()`.
236
+ * @param options - Optional settings.
237
+ * @param options.maxValueLength - Maximum length for value column (default: 50). Values longer than this are truncated.
238
+ * @returns The formatted table string. Also printed to `console.log` unless `options.silent` is `true`.
239
+ *
240
+ * @example
241
+ * ```ts
242
+ * const result = c.schema({ port: c.number({ env: "PORT" }) }).loadExtended({ env: true, args: false });
243
+ * printConfig(result);
244
+ * ```
245
+ */
246
+ declare function printConfig(result: ExtendedResult, options?: {
247
+ silent?: boolean;
248
+ maxValueLength?: number;
249
+ }): string;
250
+
196
251
  /** Options for configuring a primitive (`string`, `number`, `bool`) schema field. */
197
252
  interface OptionPropsArgs<T> {
198
253
  /** Whether the field must be present in at least one source. */
@@ -205,6 +260,8 @@ interface OptionPropsArgs<T> {
205
260
  defaultValue?: T | (() => T);
206
261
  /** Help text shown in CLI `--help` output. */
207
262
  help?: string;
263
+ /** Standard Schema validator run after type coercion. Accepts Zod, Valibot, ArkType, or any Standard Schema v1 implementation. */
264
+ validate?: StandardSchemaV1;
208
265
  }
209
266
  /** Options for configuring an `array` schema field. */
210
267
  interface ArrayOptionPropsArgs<T extends OptionTypes> {
@@ -214,6 +271,8 @@ interface ArrayOptionPropsArgs<T extends OptionTypes> {
214
271
  item: T;
215
272
  /** Static default value or factory function returning one. */
216
273
  defaultValue?: SchemaValue<T>[] | (() => SchemaValue<T>[]);
274
+ /** Standard Schema validator run on the resolved array. Accepts Zod, Valibot, ArkType, or any Standard Schema v1 implementation. */
275
+ validate?: StandardSchemaV1;
217
276
  }
218
277
  /** Options for configuring a nested `object` schema field. */
219
278
  interface ObjectOptionPropsArgs<T extends Node> {
@@ -221,6 +280,8 @@ interface ObjectOptionPropsArgs<T extends Node> {
221
280
  required?: boolean;
222
281
  /** Schema definition for the nested object's shape. */
223
282
  item: T;
283
+ /** Standard Schema validator run on the resolved object. Accepts Zod, Valibot, ArkType, or any Standard Schema v1 implementation. */
284
+ validate?: StandardSchemaV1;
224
285
  }
225
286
  /**
226
287
  * Config-loader entry point. Provides factory functions to define a typed configuration schema.
@@ -244,4 +305,4 @@ declare const option: {
244
305
  schema: <T extends Node>(theSchema: T) => SettingsBuilder<T>;
245
306
  };
246
307
 
247
- export { type ConfigErrorEntry, ConfigFileError, ConfigLoadError, type ExtendedResult, option as default };
308
+ export { type ConfigErrorEntry, ConfigFileError, ConfigLoadError, ConfigNode, ConfigNodeArray, type ExtendedResult, type NodeTree, type RecursivePartial, type SchemaValue, type SettingsSources, type StandardSchemaV1, option as default, printConfig };
package/dist/index.js CHANGED
@@ -32,7 +32,10 @@ var index_exports = {};
32
32
  __export(index_exports, {
33
33
  ConfigFileError: () => ConfigFileError,
34
34
  ConfigLoadError: () => ConfigLoadError,
35
- default: () => index_default
35
+ ConfigNode: () => configNode_default,
36
+ ConfigNodeArray: () => configNodeArray_default,
37
+ default: () => index_default,
38
+ printConfig: () => printConfig
36
39
  });
37
40
  module.exports = __toCommonJS(index_exports);
38
41
 
@@ -46,7 +49,14 @@ var ConfigLoadError = class extends Error {
46
49
  /** Non-fatal warnings collected during loading. */
47
50
  warnings;
48
51
  constructor(errors, warnings) {
49
- const message = `Configuration loading failed with ${errors.length} error${errors.length === 1 ? "" : "s"}`;
52
+ const count = errors.length;
53
+ const summary = `Configuration loading failed with ${count} error${count === 1 ? "" : "s"}`;
54
+ const details = errors.slice(0, 10).map((e, i) => ` ${i + 1}. ${e.message}`).join("\n");
55
+ const message = count > 0 ? `${summary}:
56
+ ${details}` : (
57
+ /* istanbul ignore next */
58
+ summary
59
+ );
50
60
  super(message);
51
61
  this.name = "ConfigLoadError";
52
62
  this.errors = errors;
@@ -272,11 +282,27 @@ var OptionBase = class {
272
282
  this.params = params;
273
283
  }
274
284
  getValue(sourceFile, env, args, path2, defaultValues, objectFromArray, envFileResults, errors) {
285
+ const resolved = this.resolveValue(
286
+ sourceFile,
287
+ env,
288
+ args,
289
+ path2,
290
+ defaultValues,
291
+ objectFromArray,
292
+ envFileResults,
293
+ errors
294
+ );
295
+ if (resolved && this.params.validate) {
296
+ this.runValidation(resolved, path2, errors);
297
+ }
298
+ return resolved;
299
+ }
300
+ resolveValue(sourceFile, env, args, path2, defaultValues, objectFromArray, envFileResults, errors) {
275
301
  const ident = path2.join(".");
276
302
  if (this.params.cli && args) {
277
303
  if (ident in args) {
278
304
  return new configNode_default(
279
- this.checkType(args[ident], path2, "args", errors),
305
+ this.checkType(args[ident], path2, `CLI argument --${ident}`, errors),
280
306
  ident,
281
307
  "args",
282
308
  null,
@@ -296,7 +322,12 @@ var OptionBase = class {
296
322
  );
297
323
  if (envFileSource) {
298
324
  return new configNode_default(
299
- this.checkType(val, path2, "envFile", errors),
325
+ this.checkType(
326
+ val,
327
+ path2,
328
+ `env file ${envFileSource.filePath} (${this.params.env})`,
329
+ errors
330
+ ),
300
331
  ident,
301
332
  "envFile",
302
333
  envFileSource.filePath,
@@ -307,7 +338,12 @@ var OptionBase = class {
307
338
  );
308
339
  }
309
340
  return new configNode_default(
310
- this.checkType(val, path2, "env", errors),
341
+ this.checkType(
342
+ val,
343
+ path2,
344
+ `environment variable ${this.params.env}`,
345
+ errors
346
+ ),
311
347
  ident,
312
348
  "env",
313
349
  null,
@@ -405,14 +441,47 @@ var OptionBase = class {
405
441
  }
406
442
  }
407
443
  if (this.params.required) {
444
+ const hints = [];
445
+ if (this.params.env)
446
+ hints.push(`environment variable ${this.params.env}`);
447
+ if (this.params.cli) hints.push(`CLI argument --${ident}`);
448
+ hints.push(`config file key: ${ident}`);
449
+ const hint = hints.join(", ");
408
450
  errors?.errors.push({
409
- message: `Required option '${ident}' not provided.`,
451
+ message: `Required option '${ident}' is missing. Set it via ${hint}.`,
410
452
  path: ident,
411
453
  kind: "required"
412
454
  });
413
455
  }
414
456
  return null;
415
457
  }
458
+ runValidation(node, path2, errors) {
459
+ const validator = this.params.validate;
460
+ if (!validator) return;
461
+ const value = node.value;
462
+ if (valueIsInvalid(value)) return;
463
+ const result = validator["~standard"].validate(value);
464
+ if (result instanceof Promise) {
465
+ throw new Error(
466
+ "Async validators are not supported. The validate function must return a synchronous result."
467
+ );
468
+ }
469
+ if ("issues" in result && result.issues) {
470
+ const ident = path2.join(".");
471
+ const source = node.file ?? node.variableName ?? node.argName ?? node.sourceType;
472
+ for (const issue of result.issues) {
473
+ const sourceLabel = source !== node.sourceType ? ` (source: ${source})` : "";
474
+ errors?.errors.push({
475
+ message: `Validation failed for '${ident}'${sourceLabel}: ${issue.message}`,
476
+ path: ident,
477
+ source,
478
+ kind: "validation",
479
+ line: node.line ?? void 0,
480
+ column: node.column ?? void 0
481
+ });
482
+ }
483
+ }
484
+ }
416
485
  resolveFromFileData(data, file, sourceMap, path2, ident, errors) {
417
486
  const val = this.findInObject(data, path2, errors);
418
487
  const loc = lookupLocation(sourceMap, path2);
@@ -504,28 +573,28 @@ var OptionBase = class {
504
573
  const val = obj[child];
505
574
  if (typeof val === "string") {
506
575
  errors?.errors.push({
507
- message: `Cant get path from string value '${val}'`,
576
+ message: `Cannot traverse into '${path2.join(".")}': expected an object but found a string '${val}'`,
508
577
  kind: "invalid_path"
509
578
  });
510
579
  return new InvalidValue();
511
580
  }
512
581
  if (typeof val === "number") {
513
582
  errors?.errors.push({
514
- message: `Cant get path from number value '${val}'`,
583
+ message: `Cannot traverse into '${path2.join(".")}': expected an object but found a number '${val}'`,
515
584
  kind: "invalid_path"
516
585
  });
517
586
  return new InvalidValue();
518
587
  }
519
588
  if (typeof val === "boolean") {
520
589
  errors?.errors.push({
521
- message: `Cant get path from boolean value '${val.toString()}'`,
590
+ message: `Cannot traverse into '${path2.join(".")}': expected an object but found a boolean '${val.toString()}'`,
522
591
  kind: "invalid_path"
523
592
  });
524
593
  return new InvalidValue();
525
594
  }
526
595
  if (Array.isArray(val)) {
527
596
  errors?.errors.push({
528
- message: `Cant get path from array value '${valueToString(val)}'`,
597
+ message: `Cannot traverse into '${path2.join(".")}': expected an object but found an array '${valueToString(val)}'`,
529
598
  kind: "invalid_path"
530
599
  });
531
600
  return new InvalidValue();
@@ -700,7 +769,7 @@ function validateFiles(files, dir) {
700
769
  const result = [];
701
770
  files.forEach((file) => {
702
771
  if (!fs3.existsSync(file)) {
703
- throw new ConfigFileError(`Invalid config file '${file}'`);
772
+ throw new ConfigFileError(`Config file '${file}' does not exist`);
704
773
  } else {
705
774
  result.push(file);
706
775
  }
@@ -708,14 +777,16 @@ function validateFiles(files, dir) {
708
777
  sourceFile = result;
709
778
  } else {
710
779
  if (!fs3.existsSync(files)) {
711
- throw new ConfigFileError(`Invalid config file '${files}'`);
780
+ throw new ConfigFileError(`Config file '${files}' does not exist`);
712
781
  }
713
782
  sourceFile = files;
714
783
  }
715
784
  }
716
785
  if (dir) {
717
786
  if (!(fs3.existsSync(dir) && fs3.lstatSync(dir).isDirectory())) {
718
- throw new ConfigFileError(`'${dir}' not exists or is not a dir`);
787
+ throw new ConfigFileError(
788
+ `Config directory '${dir}' does not exist or is not a directory`
789
+ );
719
790
  }
720
791
  const filesInDirectory = fs3.readdirSync(dir).sort();
721
792
  if (filesInDirectory.length === 0) {
@@ -1013,6 +1084,127 @@ var SettingsBuilder = class {
1013
1084
  }
1014
1085
  };
1015
1086
 
1087
+ // src/printConfig.ts
1088
+ function truncate(str, max) {
1089
+ if (str.length <= max) return str;
1090
+ return str.slice(0, max - 3) + "...";
1091
+ }
1092
+ function formatValue(val) {
1093
+ if (val === null || val === void 0) return "";
1094
+ if (typeof val === "object") return JSON.stringify(val) ?? "";
1095
+ if (typeof val === "string") return val;
1096
+ return `${val}`;
1097
+ }
1098
+ function formatDetail(node) {
1099
+ const parts = [];
1100
+ if (node.sourceType === "file" || node.sourceType === "envFile") {
1101
+ if (node.file) {
1102
+ let loc = node.file;
1103
+ if (node.line != null) {
1104
+ loc += `:${node.line}`;
1105
+ if (node.column != null) loc += `:${node.column}`;
1106
+ }
1107
+ parts.push(loc);
1108
+ }
1109
+ if (node.sourceType === "envFile" && node.variableName) {
1110
+ parts.push(`(${node.variableName})`);
1111
+ }
1112
+ } else if (node.sourceType === "env" && node.variableName) {
1113
+ parts.push(node.variableName);
1114
+ } else if (node.sourceType === "args" && node.argName) {
1115
+ parts.push(`--${node.argName}`);
1116
+ }
1117
+ return parts.join(" ");
1118
+ }
1119
+ function flattenTree(tree, prefix = "") {
1120
+ const rows = [];
1121
+ for (const [key, entry] of Object.entries(tree)) {
1122
+ const path2 = prefix ? `${prefix}.${key}` : key;
1123
+ if (entry instanceof configNode_default) {
1124
+ if (entry.value instanceof configNodeArray_default) {
1125
+ for (let i = 0; i < entry.value.arrayValues.length; i++) {
1126
+ const child = entry.value.arrayValues[i];
1127
+ const arrayPath = `${path2}[${i}]`;
1128
+ if (child.value && typeof child.value === "object" && !(child.value instanceof configNodeArray_default)) {
1129
+ const nested = child.value;
1130
+ rows.push(...flattenTree(nested, arrayPath));
1131
+ } else {
1132
+ rows.push({
1133
+ path: arrayPath,
1134
+ value: formatValue(child.value),
1135
+ source: child.sourceType,
1136
+ detail: formatDetail(child)
1137
+ });
1138
+ }
1139
+ }
1140
+ } else {
1141
+ rows.push({
1142
+ path: path2,
1143
+ value: formatValue(entry.value),
1144
+ source: entry.sourceType,
1145
+ detail: formatDetail(entry)
1146
+ });
1147
+ }
1148
+ } else {
1149
+ rows.push(...flattenTree(entry, path2));
1150
+ }
1151
+ }
1152
+ return rows;
1153
+ }
1154
+ function padRight(str, len) {
1155
+ return str + " ".repeat(Math.max(0, len - str.length));
1156
+ }
1157
+ function buildTable(rows) {
1158
+ const headers = {
1159
+ path: "Path",
1160
+ value: "Value",
1161
+ source: "Source",
1162
+ detail: "Detail"
1163
+ };
1164
+ const widths = {
1165
+ path: Math.max(headers.path.length, ...rows.map((r) => r.path.length)),
1166
+ value: Math.max(headers.value.length, ...rows.map((r) => r.value.length)),
1167
+ source: Math.max(
1168
+ headers.source.length,
1169
+ ...rows.map((r) => r.source.length)
1170
+ ),
1171
+ detail: Math.max(
1172
+ headers.detail.length,
1173
+ ...rows.map((r) => r.detail.length)
1174
+ )
1175
+ };
1176
+ const hr = `\u251C${"\u2500".repeat(widths.path + 2)}\u253C${"\u2500".repeat(widths.value + 2)}\u253C${"\u2500".repeat(widths.source + 2)}\u253C${"\u2500".repeat(widths.detail + 2)}\u2524`;
1177
+ const top = `\u250C${"\u2500".repeat(widths.path + 2)}\u252C${"\u2500".repeat(widths.value + 2)}\u252C${"\u2500".repeat(widths.source + 2)}\u252C${"\u2500".repeat(widths.detail + 2)}\u2510`;
1178
+ const bottom = `\u2514${"\u2500".repeat(widths.path + 2)}\u2534${"\u2500".repeat(widths.value + 2)}\u2534${"\u2500".repeat(widths.source + 2)}\u2534${"\u2500".repeat(widths.detail + 2)}\u2518`;
1179
+ const formatRow = (r) => `\u2502 ${padRight(r.path, widths.path)} \u2502 ${padRight(r.value, widths.value)} \u2502 ${padRight(r.source, widths.source)} \u2502 ${padRight(r.detail, widths.detail)} \u2502`;
1180
+ const lines = [top, formatRow(headers), hr, ...rows.map(formatRow), bottom];
1181
+ return lines.join("\n");
1182
+ }
1183
+ function printConfig(result, options) {
1184
+ const maxLen = options?.maxValueLength ?? 50;
1185
+ const rows = flattenTree(result.data).map((r) => ({
1186
+ ...r,
1187
+ value: truncate(r.value, maxLen)
1188
+ }));
1189
+ let output;
1190
+ if (rows.length === 0) {
1191
+ output = "No configuration values loaded.";
1192
+ } else {
1193
+ output = buildTable(rows);
1194
+ }
1195
+ if (result.warnings.length > 0) {
1196
+ output += "\n\nWarnings:";
1197
+ for (const w of result.warnings) {
1198
+ output += `
1199
+ - ${w}`;
1200
+ }
1201
+ }
1202
+ if (!options?.silent) {
1203
+ console.log(output);
1204
+ }
1205
+ return output;
1206
+ }
1207
+
1016
1208
  // src/index.ts
1017
1209
  var DEFAULTS = {
1018
1210
  required: false,
@@ -1068,5 +1260,8 @@ var index_default = option;
1068
1260
  // Annotate the CommonJS export names for ESM import in node:
1069
1261
  0 && (module.exports = {
1070
1262
  ConfigFileError,
1071
- ConfigLoadError
1263
+ ConfigLoadError,
1264
+ ConfigNode,
1265
+ ConfigNodeArray,
1266
+ printConfig
1072
1267
  });
package/package.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@meltstudio/config-loader",
3
- "version": "3.0.2",
4
- "description": "Melt Studio's tool for loading configurations into a Node.js application.",
3
+ "version": "3.2.0",
4
+ "description": "Type-safe configuration loader with full TypeScript inference. Load from YAML, JSON, .env, environment variables, and CLI args.",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
7
7
  "repository": "https://github.com/MeltStudio/config-loader",
8
8
  "author": "MeltStudio <dev@meltstudio.co>",
9
- "license": "Apache-2.0",
9
+ "license": "MIT",
10
10
  "engines": {
11
11
  "node": ">=20"
12
12
  },
@@ -14,8 +14,18 @@
14
14
  "configuration",
15
15
  "config",
16
16
  "yaml",
17
+ "json",
17
18
  "loader",
18
- "config-node"
19
+ "env",
20
+ "environment",
21
+ "dotenv",
22
+ "cli",
23
+ "type-safe",
24
+ "typescript",
25
+ "schema",
26
+ "validation",
27
+ "zod",
28
+ "settings"
19
29
  ],
20
30
  "files": [
21
31
  "dist",
@@ -73,6 +83,7 @@
73
83
  "tsconfig-paths": "^4.2.0",
74
84
  "tsup": "^8.0.0",
75
85
  "typescript": "^5.0.4",
76
- "typescript-eslint": "^8.24.0"
86
+ "typescript-eslint": "^8.24.0",
87
+ "zod": "^4.3.6"
77
88
  }
78
89
  }