Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
* [@w5s/core-type](packages/core-type) - Core type modules
* [@w5s/database](packages/database) - Database client module
* [@w5s/env](packages/env) - Environment variable module
* [@w5s/config](packages/config) - Configuration explorer module
* [@w5s/error](packages/error) - Error module
* [@w5s/http](packages/http) - HTTP client module
* [@w5s/iterable](packages/iterable) - Iterable and AsyncIterable modules
Expand Down
21 changes: 21 additions & 0 deletions packages/config/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2019-2025 Julien Polo

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
52 changes: 52 additions & 0 deletions packages/config/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
<!-- AUTO-GENERATED-CONTENT:START (PKG_JSON:template=# W5S ${description} _(${name})_&unknownTxt= ) -->
# W5S Configuration explorer module _(@w5s/config)_
<!-- AUTO-GENERATED-CONTENT:END -->

[![NPM Version][package-version-svg]][package-url]
[![License][license-image]][license-url]

## Installation

<!-- AUTO-GENERATED-CONTENT:START (PKG_JSON:template=```sh\nnpm install ${name}\n```) -->
```sh
npm install @w5s/config
```
<!-- AUTO-GENERATED-CONTENT:END -->

## Usage

<!-- AUTO-GENERATED-CONTENT:START (CODE:src=./example/usage.ts) -->
<!-- The below code snippet is automatically added from ./example/usage.ts -->
```ts
import { Config } from '@w5s/config';
import { Task } from '@w5s/task';

export async function main(): Promise<void> {
const explorer = Config('my-app');
const result = await Task.run(explorer.search());

if (result.ok && result.value != null) {
console.log(result.value.config);
}
}
```
<!-- AUTO-GENERATED-CONTENT:END -->

## License

[MIT][license-url] © Julien Polo [julien.polo@gmail.com](mailto:julien.polo@gmail.com)

<!-- VARIABLES -->

<!-- AUTO-GENERATED-CONTENT:START (PKG_JSON:template=[package-version-svg]: https://img.shields.io/npm/v/${name}.svg?style=flat-square) -->
[package-version-svg]: https://img.shields.io/npm/v/@w5s/config.svg?style=flat-square
<!-- AUTO-GENERATED-CONTENT:END -->
<!-- AUTO-GENERATED-CONTENT:START (PKG_JSON:template=[package-url]: https://www.npmjs.com/package/${name}) -->
[package-url]: https://www.npmjs.com/package/@w5s/config
<!-- AUTO-GENERATED-CONTENT:END -->
<!-- AUTO-GENERATED-CONTENT:START (PKG_JSON:template=[license-image]: https://img.shields.io/badge/license-${license}-green.svg?style=flat-square) -->
[license-image]: https://img.shields.io/badge/license-MIT-green.svg?style=flat-square
<!-- AUTO-GENERATED-CONTENT:END -->
<!-- AUTO-GENERATED-CONTENT:START (PKG_JSON:template=[license-url]: https://www.npmjs.com/package/${name}) -->
[license-url]: https://www.npmjs.com/package/@w5s/config
<!-- AUTO-GENERATED-CONTENT:END -->
11 changes: 11 additions & 0 deletions packages/config/example/usage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { Config } from '@w5s/config';
import { Task } from '@w5s/task';

export async function main(): Promise<void> {
const explorer = Config('my-app');
const result = await Task.run(explorer.search());

if (result.ok && result.value != null) {
console.log(result.value.config);
}
}
79 changes: 79 additions & 0 deletions packages/config/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
{
"name": "@w5s/config",
"version": "1.0.0-alpha.0",
"description": "Configuration explorer module",
"keywords": [
"fp",
"functional",
"config",
"configuration",
"cosmiconfig"
],
"homepage": "https://github.com/w5s/std/tree/master/packages/config#readme",
"bugs": {
"url": "https://github.com/w5s/std/issues"
},
"repository": {
"type": "git",
"url": "git@github.com:w5s/std.git",
"directory": "packages/config"
},
"license": "MIT",
"author": "Julien Polo <julien.polo@gmail.com>",
"type": "module",
"exports": {
".": "./dist/index.js",
"./dist/*": "./dist/*"
},
"typings": "./dist/index.d.ts",
"files": [
"dist/",
"src/",
"!*.d.ts.map",
"!**/*.spec.*",
"!**/__tests__/**"
],
"scripts": {
"build": "pnpm run \"/^build:.*/\"",
"build:tsc": "tsc -b tsconfig.build.json",
"clean": "pnpm run \"/^clean:.*/\"",
"clean:tsc": "rm -rf dist",
"docs": "node '../../markdown.mjs'",
"format": "pnpm run \"/^format:.*/\"",
"format:src": "eslint . --fix --ext=mjs,cjs,js,jsx,ts,tsx,json,jsonc,json5,yml,yaml",
"lint": "pnpm run \"/^lint:.*/\"",
"lint:src": "eslint .",
"size-limit": "size-limit",
"spellcheck": "cspell --no-progress '**'",
"test": "pnpm run \"/^test:.*/\"",
"test:src": "vitest run",
"tsc": "tsc",
"validate": "npm run lint && npm run build && npm run test"
},
"dependencies": {
"@w5s/core": "workspace:^1.0.0-alpha.0",
"@w5s/error": "workspace:^1.0.0-alpha.0",
"@w5s/system": "workspace:^1.0.0-alpha.0",
"@w5s/task": "workspace:^1.0.0-alpha.0"
},
"devDependencies": {
"typescript": "5.9.3",
"vitest": "latest"
},
"peerDependencies": {
"typescript": "^3.8.0 || ^4.0.0 || ^5.0.0"
},
"engines": {
"node": ">=20.0.0"
},
"publishConfig": {
"access": "public"
},
"size-limit": [
{
"path": "dist/index.js",
"limit": "5 kB"
}
],
"sideEffect": false
}
159 changes: 159 additions & 0 deletions packages/config/src/Config.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
import { describe, it, expect } from 'vitest';
import * as fs from 'node:fs/promises';
import nodePath from 'node:path';
import os from 'node:os';
import { Config } from './Config.js';
import { Task } from '@w5s/task';
import type { FilePath } from '@w5s/system';
import { ConfigErrorType } from './ConfigError.js';

const asFilePath = (value: string) => value as FilePath;

async function createTempDir(): Promise<string> {
return fs.mkdtemp(nodePath.join(os.tmpdir(), 'w5s-config-'));
}

async function writeFile(filePath: string, content: string): Promise<void> {
await fs.mkdir(nodePath.dirname(filePath), { recursive: true });
await fs.writeFile(filePath, content, 'utf8');
}

describe('Config', () => {
it('searches the nearest configuration first', async () => {
const root = await createTempDir();
const child = nodePath.join(root, 'child');

await writeFile(nodePath.join(root, '.myapprc.json'), '{"root": true}');
await writeFile(nodePath.join(child, '.myapprc.json'), '{"child": true}');

const explorer = Config<{ child?: boolean }>('myapp');
const result = await Task.run(explorer.search(asFilePath(child)));

expect(result.ok).toBe(true);
expect(result.value?.filepath).toBe(nodePath.join(child, '.myapprc.json'));
expect(result.value?.config).toEqual({ child: true });
});

it('respects stopDir when searching', async () => {
const root = await createTempDir();
const child = nodePath.join(root, 'child');
const grandChild = nodePath.join(child, 'grand');

await writeFile(nodePath.join(root, '.myapprc.json'), '{"root": true}');

const explorer = Config('myapp', { stopDir: asFilePath(child) });
const result = await Task.run(explorer.search(asFilePath(grandChild)));

expect(result.ok).toBe(true);
expect(result.value).toBeUndefined();
});

it('loads JSON config files', async () => {
const root = await createTempDir();
const filePath = nodePath.join(root, '.myapprc.json');

await writeFile(filePath, '{"value": 123}');

const explorer = Config<{ value: number }>('myapp');
const result = await Task.run(explorer.load(asFilePath(filePath)));

expect(result.ok).toBe(true);
expect(result.value?.config).toEqual({ value: 123 });
});

it('loads JS module config files', async () => {
const root = await createTempDir();
const mjsPath = nodePath.join(root, 'myapp.config.mjs');
const cjsPath = nodePath.join(root, 'myapp.config.cjs');

await writeFile(mjsPath, 'export default { value: 42 };');
await writeFile(cjsPath, 'module.exports = { value: 77 };');

const explorer = Config<{ value: number }>('myapp');

const mjsResult = await Task.run(explorer.load(asFilePath(mjsPath)));
expect(mjsResult.ok).toBe(true);
expect(mjsResult.value?.config).toEqual({ value: 42 });

const cjsResult = await Task.run(explorer.load(asFilePath(cjsPath)));
expect(cjsResult.ok).toBe(true);
expect(cjsResult.value?.config).toEqual({ value: 77 });
});

it('loads config from package.json', async () => {
const root = await createTempDir();
const packagePath = nodePath.join(root, 'package.json');

await writeFile(packagePath, '{"name": "demo", "myapp": {"enabled": true}}');

const explorer = Config<{ enabled: boolean }>('myapp');
const result = await Task.run(explorer.load(asFilePath(packagePath)));

expect(result.ok).toBe(true);
expect(result.value?.config).toEqual({ enabled: true });
});

it('marks empty JSON files as empty configs', async () => {
const root = await createTempDir();
const filePath = nodePath.join(root, '.myapprc');

await writeFile(filePath, '');

const explorer = Config('myapp');
const result = await Task.run(explorer.search(asFilePath(root)));

expect(result.ok).toBe(true);
expect(result.value?.filepath).toBe(filePath);
expect(result.value?.isEmpty).toBe(true);
});

it('returns ParseError for invalid JSON', async () => {
const root = await createTempDir();
const filePath = nodePath.join(root, '.myapprc.json');

await writeFile(filePath, '{ invalid }');

const explorer = Config('myapp');
const result = await Task.run(explorer.load(asFilePath(filePath)));

expect(result.ok).toBe(false);
if (!result.ok) {
expect(result.error.configErrorType).toBe(ConfigErrorType.ParseError);
}
});

it('returns NotFound when loading a missing file', async () => {
const root = await createTempDir();
const filePath = nodePath.join(root, '.missingrc');

const explorer = Config('myapp');
const result = await Task.run(explorer.load(asFilePath(filePath)));

expect(result.ok).toBe(false);
if (!result.ok) {
expect(result.error.configErrorType).toBe(ConfigErrorType.NotFound);
}
});

it('caches load results when enabled', async () => {
const root = await createTempDir();
const filePath = nodePath.join(root, '.myapprc.json');

await writeFile(filePath, '{"value": 1}');

let calls = 0;
const explorer = Config<{ value: number }>('myapp', {
loaders: {
'.json': (filepath, content) => {
calls += 1;
return Config.defaultLoaders<{ value: number }>('myapp')['.json'](filepath, content);
},
},
});

await Task.run(explorer.load(asFilePath(filePath)));
await Task.run(explorer.load(asFilePath(filePath)));

expect(calls).toBe(1);
});
});
Loading
Loading