Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs: update README and add JSDoc #212

Closed
wants to merge 5 commits into from
Closed
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
90 changes: 12 additions & 78 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -82,12 +82,20 @@ const { loadConfig, watchConfig } = require("c12");

Load configuration:

```js
```ts
// Get loaded config
const { config } = await loadConfig({});

// Get resolved config and extended layers
const { config, configFile, layers } = await loadConfig({});
type MyConfig = {
option1: boolean;
option2: string;
}

// Get (typed) resolved config and extended layers
const { config, configFile, layers } = await loadConfig<MyConfig>({});

// Export defineConfig utility for type-safety
export const defineMyConfig = createDefineConfig<MyConfig>();
```

## Loading priority
Expand All @@ -104,81 +112,7 @@ c12 merged config sources with [unjs/defu](https://github.com/unjs/defu) by belo

## Options

### `cwd`
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This needs to be kept.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

would maintaining JSDoc not more beneficial?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We have automd generator for jsdocs. (see ufo for example is using it)

For c12, I am happy with current manual readme to have additional docs. We might in the future use jsdocs to auto maintain readme but not for now.


Resolve configuration from this working directory. The default is `process.cwd()`

### `name`

Configuration base name. The default is `config`.

### `configFile`

Configuration file name without extension. Default is generated from `name` (f.e., if `name` is `foo`, the config file will be => `foo.config`).

Set to `false` to avoid loading the config file.

### `rcFile`

RC Config file name. Default is generated from `name` (name=foo => `.foorc`).

Set to `false` to disable loading RC config.

### `globalRC`

Load RC config from the workspace directory and the user's home directory. Only enabled when `rcFile` is provided. Set to `false` to disable this functionality.

### `dotenv`

Loads `.env` file if enabled. It is disabled by default.

### `packageJson`

Loads config from nearest `package.json` file. It is disabled by default.

If `true` value is passed, c12 uses `name` field from `package.json`.

You can also pass either a string or an array of strings as a value to use those fields.

### `defaults`

Specify default configuration. It has the **lowest** priority and is applied **after extending** config.

### `defaultConfig`

Specify default configuration. It is applied **before** extending config.

### `overrides`

Specify override configuration. It has the **highest** priority and is applied **before extending** config.

### `omit$Keys`

Exclude environment-specific and built-in keys start with `$` in the resolved config. The default is `false`.

### `jiti`

Custom [unjs/jiti](https://github.com/unjs/jiti) instance used to import configuration files.

### `jitiOptions`

Custom [unjs/jiti](https://github.com/unjs/jiti) options to import configuration files.

### `giget`

Options passed to [unjs/giget](https://github.com/unjs/giget) when extending layer from git source.

### `merger`

Custom options merger function. Default is [defu](https://github.com/unjs/defu).

**Note:** Custom merge function should deeply merge options with arguments high -> low priority.

### `envName`

Environment name used for [environment specific configuration](#environment-specific-configuration).

The default is `process.env.NODE_ENV`. You can set `envName` to `false` or an empty string to disable the feature.
See [`src/types#L97`](./src/types.ts#L97) for options.

## Extending configuration

Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,8 @@
"pathe": "^1.1.2",
"perfect-debounce": "^1.0.0",
"pkg-types": "^1.2.1",
"rc9": "^2.1.2"
"rc9": "^2.1.2",
"scule": "^1.3.0"
},
"devDependencies": {
"@types/node": "^22.10.2",
Expand Down
3 changes: 3 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

15 changes: 15 additions & 0 deletions src/loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { fileURLToPath } from "mlly";
import * as rc9 from "rc9";
import { defu } from "defu";
import { hash } from "ohash";
import { pascalCase } from "scule";
import { findWorkspaceDir, readPackageJSON } from "pkg-types";
import { setupDotenv } from "./dotenv";

Expand Down Expand Up @@ -61,6 +62,10 @@ export async function loadConfig<
options.configFile ??
(options.name === "config" ? "config" : `${options.name}.config`);
options.rcFile = options.rcFile ?? `.${options.name}rc`;
options.globalDefineConfigFn =
options.globalDefineConfigFn === true
? `define${[...new Set([pascalCase(options.name), "Config"])].join("")}`
: options.globalDefineConfigFn || false;
if (options.extend !== false) {
options.extend = {
extendKey: "extends",
Expand Down Expand Up @@ -108,6 +113,11 @@ export async function loadConfig<
});
}

if (options.globalDefineConfigFn) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please seperate it it new PR

// @ts-expect-error updating globalThis
globalThis[options.globalDefineConfigFn] = (c: any) => c;
}

// Load main config file
const _mainConfig = await resolveConfig(".", options);
if (_mainConfig.configFile) {
Expand Down Expand Up @@ -174,6 +184,11 @@ export async function loadConfig<
r.config = _merger(r.config, ...r.layers!.map((e) => e.config)) as T;
}

if (options.globalDefineConfigFn) {
// @ts-expect-error updating globalThis
delete globalThis[options.globalDefineConfigFn];
}

// Preserve unmerged sources as layers
const baseLayers: ConfigLayer<T, MT>[] = [
configs.overrides && {
Expand Down
77 changes: 77 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,25 +98,77 @@ export interface LoadConfigOptions<
T extends UserInputConfig = UserInputConfig,
MT extends ConfigLayerMeta = ConfigLayerMeta,
> {
/**
* Configuration base name.
*
* @default 'config'
*/
name?: string;
/**
* Resolve configuration from this working directory.
*
* @default process.cwd()
*/
cwd?: string;

/**
* Configuration file name without extension. Default is generated from `name` (f.e., if `name` is `foo`, the config file will be => `foo.config`).
*
* Set to `false` to avoid loading the config file.
*/
configFile?: string;

/**
* RC Config file name. Default is generated from `name` (name=foo => `.foorc`).
*
* Set to `false` to disable loading RC config.
*/
rcFile?: false | string;
/**
* Load RC config from the workspace directory and the user's home directory. Only enabled when `rcFile` is provided. Set to `false` to disable this functionality.
*/
globalRc?: boolean;

/**
* Loads `.env` file if enabled. It is disabled by default.
*/
dotenv?: boolean | DotenvOptions;

/**
* Environment name used for [environment specific configuration](#environment-specific-configuration).
*
* The default is `process.env.NODE_ENV`. You can set `envName` to `false` or an empty string to disable the feature.
*/
envName?: string | false;

/**
* Loads config from nearest `package.json` file. It is disabled by default.
*
* If `true` value is passed, c12 uses `name` field from `package.json`.
*
* You can also pass either a string or an array of strings as a value to use those fields.
*/
packageJson?: boolean | string | string[];

/**
* Specify default configuration. It has the **lowest** priority and is applied **after extending** config.
*/
defaults?: T;

/**
* Specify default configuration. It is applied **before** extending config.
*/
defaultConfig?: ResolvableConfig<T>;
/**
* Specify override configuration. It has the **highest** priority and is applied **before extending** config.
*/
overrides?: ResolvableConfig<T>;

/**
* Exclude environment-specific and built-in keys start with `$` in the resolved config.
*
* @default false
*/
omit$Keys?: boolean;

resolve?: (
Expand All @@ -128,13 +180,38 @@ export interface LoadConfigOptions<
| ResolvedConfig<T, MT>
| Promise<ResolvedConfig<T, MT> | undefined | null>;

/**
* Custom [`unjs/jiti`](https://github.com/unjs/jiti) instance used to import configuration files.
*/
jiti?: Jiti;
/**
* Custom [`unjs/jiti`](https://github.com/unjs/jiti) options to import configuration files.
*/
jitiOptions?: JitiOptions;

/**
* Options passed to [`unjs/giget`](https://github.com/unjs/giget) when extending layer from git source.
*/
giget?: false | DownloadTemplateOptions;

/**
* Custom options merger function. Default is [`defu`](https://github.com/unjs/defu).
*
* **Note:** Custom merge function should deeply merge options with arguments high -> low priority.
*/
merger?: (...sources: Array<T | null | undefined>) => T;

/**
* Load configuration files using defineConfig utility without import statements.
* If true, the utility name is `define${pascalCase(name)}Config`, else use string.
*/
globalDefineConfigFn?: boolean | string;

/**
* Allow extending of configuration.
*
* @see https://github.com/unjs/c12#extending-configuration
*/
extend?:
| false
| {
Expand Down
5 changes: 5 additions & 0 deletions test/fixture/test-global-fn.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export default defineTestGlobalFnConfig({ it: "works" });

declare global {
const defineTestGlobalFnConfig: <T>(c: T) => T;
}
10 changes: 10 additions & 0 deletions test/loader.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -304,4 +304,14 @@ describe("loader", () => {
)!;
expect(Object.keys(baseLayerConfig.config!)).toContain("$env");
});

it("globalDefineConfigFn", async () => {
const { config } = await loadConfig({
name: "test-global-fn",
cwd: r("./fixture"),
globalDefineConfigFn: true,
});

expect(config.it).toBe("works");
});
});