@wtf/project-config 0.0.0-stage → 1.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 +21 -0
- package/README.md +78 -2
- package/dist/define.d.ts +26 -0
- package/dist/define.js +7 -0
- package/dist/define.js.map +1 -0
- package/dist/env.d.ts +40 -0
- package/dist/env.js +160 -0
- package/dist/env.js.map +1 -0
- package/dist/errors.d.ts +151 -0
- package/dist/errors.js +175 -0
- package/dist/errors.js.map +1 -0
- package/dist/files.d.ts +51 -0
- package/dist/files.js +120 -0
- package/dist/files.js.map +1 -0
- package/dist/index.d.ts +196 -0
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -0
- package/dist/load.d.ts +82 -0
- package/dist/load.js +140 -0
- package/dist/load.js.map +1 -0
- package/dist/locate.d.ts +71 -0
- package/dist/locate.js +121 -0
- package/dist/locate.js.map +1 -0
- package/dist/merge.d.ts +10 -0
- package/dist/merge.js +33 -0
- package/dist/merge.js.map +1 -0
- package/dist/node.d.ts +20 -0
- package/dist/node.js +90 -0
- package/dist/node.js.map +1 -0
- package/dist/path.d.ts +14 -0
- package/dist/path.js +40 -0
- package/dist/path.js.map +1 -0
- package/dist/placeholder.d.ts +37 -0
- package/dist/placeholder.js +47 -0
- package/dist/placeholder.js.map +1 -0
- package/dist/schema.d.ts +24 -0
- package/dist/schema.js +58 -0
- package/dist/schema.js.map +1 -0
- package/dist/section.d.ts +39 -0
- package/dist/section.js +169 -0
- package/dist/section.js.map +1 -0
- package/dist/text.d.ts +3 -0
- package/dist/text.js +3 -0
- package/dist/text.js.map +1 -0
- package/dist/write.d.ts +35 -0
- package/dist/write.js +209 -0
- package/dist/write.js.map +1 -0
- package/package.json +89 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Mikael Karon
|
|
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
|
@@ -1,3 +1,79 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @wtf/project-config
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
One file for the settings of a project's tools: a `wtf` object with a section for each tool, as
|
|
4
|
+
`wtf.vite` and `wtf.vitest`, kept in `wtf.config.json`, in code as `wtf.config.ts`, or in the
|
|
5
|
+
`wtf` key of package.json. This package finds it, loads it, reads a tool's section with the
|
|
6
|
+
environment's variables over it, checks it by the tool's schema, and writes values back. A repo
|
|
7
|
+
loads its config itself and hands each section to the tool it is for, as a preset's options.
|
|
8
|
+
|
|
9
|
+
| Subpath | What you get |
|
|
10
|
+
| --------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
|
|
11
|
+
| `.` | The types: `NamespaceConfig`, `SectionsOf`, `ResolvedConfig`, `SectionSchema`, `ConfigPlatform`, `ConfigSyncPlatform`, … |
|
|
12
|
+
| `./node` | `loadConfig(folder?)` and `loadConfigSync(folder?)`, of Node's disk and `process.env`; `nodeConfigPlatform()`, `nodeSyncPlatform()` |
|
|
13
|
+
| `./load` | `loadConfig(folder, { platform })`, of code or JSON; `loadConfigSync(folder, { platform })`, of JSON alone; `ignoredWarning` |
|
|
14
|
+
| `./section` | `sectionOf(resolved, name, schema?)` and `sectionOfSync`: a tool's section, the environment over it, checked; `issuesOf`, `mergeSection` |
|
|
15
|
+
| `./locate` | `locateConfig`, `projectRootOf` and their sync twins; `configFilesOf`, `configNamesOf`, `jsonFilesOf`, `DEFAULT_NAMESPACE` |
|
|
16
|
+
| `./env` | `withEnvironment`, `variablesOf`, `envNameOf`, `envPrefixOf`: variables such as `WTF_VITE_COMPRESS` over a value |
|
|
17
|
+
| `./placeholder` | `expandPlaceholders` and `expandString`: each `${env:NAME}` replaced by its variable |
|
|
18
|
+
| `./path` | `configPathOf('vite.compress')`, `textOfConfigPath`, `valueAt` |
|
|
19
|
+
| `./write` | `setConfigValue` and `unsetConfigValue`, in the JSON file or in package.json's key |
|
|
20
|
+
| `./schema` | `namespaceSchema('wtf', sections)`: one JSON Schema for the whole file, of each tool's schema |
|
|
21
|
+
| `./define` | `defineConfig<S>(config)`: a code config, typed by the sections of the tools |
|
|
22
|
+
| `./errors` | `ConfigError` and every other error, each with a stable `code` |
|
|
23
|
+
|
|
24
|
+
```ts
|
|
25
|
+
// vite.config.ts
|
|
26
|
+
import { loadConfig } from '@wtf/project-config/node'
|
|
27
|
+
import { sectionOf } from '@wtf/project-config/section'
|
|
28
|
+
import { baseConfig, type BaseOptions } from '@wtf/project-vite/config'
|
|
29
|
+
|
|
30
|
+
const config = await loadConfig()
|
|
31
|
+
export default baseConfig({ ...(await sectionOf<BaseOptions>(config, 'vite')) })
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
## Where it looks
|
|
35
|
+
|
|
36
|
+
It looks at the root of the workspace the folder is in (the nearest folder up with a
|
|
37
|
+
pnpm-workspace.yaml, or a package.json of `workspaces`), else the nearest package.json's folder.
|
|
38
|
+
There it uses the first of `wtf.config.mjs`, `wtf.config.js`, `wtf.config.ts`, `wtf.config.json`
|
|
39
|
+
and the `wtf` key of package.json, and ignores the others: `ignoredWarning` says which. A tool can
|
|
40
|
+
name another namespace, other files or another key.
|
|
41
|
+
|
|
42
|
+
A JSON file holds plain data. A code config exports its object by default, or a function that
|
|
43
|
+
returns one, and may hold what JSON cannot, as a function, where a tool's options take one. Node
|
|
44
|
+
imports it, `wtf.config.ts` too, as it strips the types itself.
|
|
45
|
+
|
|
46
|
+
## Asynchronous and synchronous
|
|
47
|
+
|
|
48
|
+
`loadConfig` reads every kind of file, as importing code is asynchronous. `loadConfigSync` is for a
|
|
49
|
+
tool that loads its own config synchronously: it reads `wtf.config.json` and package.json's key,
|
|
50
|
+
and throws a `SyncConfigInCodeError` when the config in use is code. `sectionOfSync` checks a
|
|
51
|
+
section synchronously, and throws a `SyncSchemaError` of a schema that answers with a promise.
|
|
52
|
+
|
|
53
|
+
## The environment over it
|
|
54
|
+
|
|
55
|
+
The loads of `./node` keep `process.env`. A variable `WTF_<SECTION>_<KEY>` sets a value of a
|
|
56
|
+
section as it is read, a JSON value or else the text: `WTF_VITE_COMPRESS=false` sets
|
|
57
|
+
`wtf.vite.compress`. A key of camelCase is its words in capitals, so `testTimeout` is
|
|
58
|
+
`TEST_TIMEOUT`. A variable sets a key the section has, or its schema names, and no other. A string in a section can point at a variable with
|
|
59
|
+
`${env:NAME}`, so a secret stays out of the file; `sectionOf` replaces it, and a variable that is
|
|
60
|
+
not set throws an `EnvPlaceholderUnsetError`, which never shows a value.
|
|
61
|
+
|
|
62
|
+
## Checking a section
|
|
63
|
+
|
|
64
|
+
`sectionOf(config, name, schema)` checks a section by a Standard Schema (as each preset's
|
|
65
|
+
`./schema` exports, or zod's), a JSON Schema or a Standard JSON Schema (checked by ajv), or a
|
|
66
|
+
function. What is wrong is an `InvalidSectionError` that names the file, or the variable, and the
|
|
67
|
+
path of each value. `namespaceSchema('wtf', { vite: viteSchema, … })` gives the JSON Schema of the
|
|
68
|
+
whole file, for `$schema` in `wtf.config.json`. A key that starts with `//` is a comment: the
|
|
69
|
+
JSON Schema of the whole takes one beside the sections, and each preset's schema in its section,
|
|
70
|
+
which it leaves out of the options it gives.
|
|
71
|
+
|
|
72
|
+
## Any platform
|
|
73
|
+
|
|
74
|
+
`./load`, `./locate` and `./write` read through the platform you pass: a `Platform` of
|
|
75
|
+
[`@wtf/platform`](https://www.npmjs.com/package/@wtf/platform), whose `navigator.storage` gives
|
|
76
|
+
the root of a WHATWG File System, as a browser's or `@wtf/platform-fs-memory`'s. The sync loads take
|
|
77
|
+
a `ConfigSyncPlatform`, whose files are read synchronously. `./node` gives Node's of each.
|
|
78
|
+
|
|
79
|
+
See the [configuration guide](../project-docs/guides/config.md).
|
package/dist/define.d.ts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A project's configuration, as code writes it: {@link defineConfig}, which gives the object it is
|
|
3
|
+
* given, typed by the sections of the tools it configures, as `wtf.config.ts` exports it by
|
|
4
|
+
* default. The sections are typed by the schemas of the tools, by `SectionsOf` of the root, or by
|
|
5
|
+
* any type of an object of sections. A code config may hold what JSON cannot, as a function, where
|
|
6
|
+
* a tool's options take one.
|
|
7
|
+
*
|
|
8
|
+
* ```ts
|
|
9
|
+
* import type { SectionsOf } from '@wtf/project-config'
|
|
10
|
+
* import { defineConfig } from '@wtf/project-config/define'
|
|
11
|
+
* import type { viteSchema } from '@wtf/project-vite/schema'
|
|
12
|
+
*
|
|
13
|
+
* export default defineConfig<SectionsOf<{ vite: typeof viteSchema }>>({
|
|
14
|
+
* vite: { compress: { threshold: 512 } }
|
|
15
|
+
* })
|
|
16
|
+
* ```
|
|
17
|
+
*
|
|
18
|
+
* @packageDocumentation
|
|
19
|
+
*/
|
|
20
|
+
import type { NamespaceConfig } from './index.ts';
|
|
21
|
+
/**
|
|
22
|
+
* `config`, as it is: a project's configuration, of the sections `S`, each checked by its type, as
|
|
23
|
+
* `SectionsOf<{ vite: typeof viteSchema }>` types them; any other section, of a tool not named, is
|
|
24
|
+
* taken as it is.
|
|
25
|
+
*/
|
|
26
|
+
export declare const defineConfig: <S extends object = Record<never, never>>(config: NamespaceConfig<S>) => NamespaceConfig<S>;
|
package/dist/define.js
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `config`, as it is: a project's configuration, of the sections `S`, each checked by its type, as
|
|
3
|
+
* `SectionsOf<{ vite: typeof viteSchema }>` types them; any other section, of a tool not named, is
|
|
4
|
+
* taken as it is.
|
|
5
|
+
*/
|
|
6
|
+
export const defineConfig = (config) => config;
|
|
7
|
+
//# sourceMappingURL=define.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"define.js","sourceRoot":"","sources":["../src/define.ts"],"names":[],"mappings":"AAqBA;;;;GAIG;AACH,MAAM,CAAC,MAAM,YAAY,GAAG,CAC1B,MAA0B,EACN,EAAE,CAAC,MAAM,CAAA","sourcesContent":["/**\n * A project's configuration, as code writes it: {@link defineConfig}, which gives the object it is\n * given, typed by the sections of the tools it configures, as `wtf.config.ts` exports it by\n * default. The sections are typed by the schemas of the tools, by `SectionsOf` of the root, or by\n * any type of an object of sections. A code config may hold what JSON cannot, as a function, where\n * a tool's options take one.\n *\n * ```ts\n * import type { SectionsOf } from '@wtf/project-config'\n * import { defineConfig } from '@wtf/project-config/define'\n * import type { viteSchema } from '@wtf/project-vite/schema'\n *\n * export default defineConfig<SectionsOf<{ vite: typeof viteSchema }>>({\n * vite: { compress: { threshold: 512 } }\n * })\n * ```\n *\n * @packageDocumentation\n */\nimport type { NamespaceConfig } from './index.ts'\n\n/**\n * `config`, as it is: a project's configuration, of the sections `S`, each checked by its type, as\n * `SectionsOf<{ vite: typeof viteSchema }>` types them; any other section, of a tool not named, is\n * taken as it is.\n */\nexport const defineConfig = <S extends object = Record<never, never>>(\n config: NamespaceConfig<S>\n): NamespaceConfig<S> => config\n"]}
|
package/dist/env.d.ts
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import type { ConfigPath, JsonSchema } from './index.ts';
|
|
2
|
+
/** The variables of an environment, by their names, as a process's environment holds them. */
|
|
3
|
+
export type Environment = Readonly<Record<string, string | undefined>>;
|
|
4
|
+
/** A variable of the environment that set a value of the configuration: its name, and the path
|
|
5
|
+
* of the value. */
|
|
6
|
+
export type EnvironmentValue = {
|
|
7
|
+
readonly variable: string;
|
|
8
|
+
readonly path: ConfigPath;
|
|
9
|
+
};
|
|
10
|
+
/** A value with the environment over it: the value, and each variable that set some of it. */
|
|
11
|
+
export type WithEnvironment = {
|
|
12
|
+
readonly value: unknown;
|
|
13
|
+
readonly set: readonly EnvironmentValue[];
|
|
14
|
+
};
|
|
15
|
+
/**
|
|
16
|
+
* A name as a variable of the environment writes it: its words in capitals, joined by `_`, a word
|
|
17
|
+
* of camelCase its own, as `apiKey` is `API_KEY`, and any other character a `_`.
|
|
18
|
+
*/
|
|
19
|
+
export declare const envNameOf: (name: string) => string;
|
|
20
|
+
/** The prefix of the variables of the environment of `name`, the key of package.json by default:
|
|
21
|
+
* {@link envNameOf} it, and `_`, as `wtf` is `WTF_` and `wtf-vite` `WTF_VITE_`. */
|
|
22
|
+
export declare const envPrefixOf: (name: string) => string;
|
|
23
|
+
/** The variables of `environment` of `prefix`, as {@link envPrefixOf} gives it, each set and not
|
|
24
|
+
* empty, by their names. */
|
|
25
|
+
export declare function variablesOf(environment: Environment, prefix: string): Record<string, string>;
|
|
26
|
+
/**
|
|
27
|
+
* The JSON Schema of `schema`, as a tool checks its section by it: the schema itself, of a JSON
|
|
28
|
+
* Schema; of a Standard Schema that gives one, as zod's does, the JSON Schema of its input; else
|
|
29
|
+
* none, of a function, or a schema that gives none.
|
|
30
|
+
*/
|
|
31
|
+
export declare function jsonSchemaOf(schema: unknown): JsonSchema | undefined;
|
|
32
|
+
/**
|
|
33
|
+
* `value` with the variables `variables` of `prefix` over it: each variable that names a path of
|
|
34
|
+
* a key there is, in `value` or in `schema`, a JSON Schema of it, sets the value at that path,
|
|
35
|
+
* merged over what is there ({@link mergeSection}), and the variable of the prefix itself, without
|
|
36
|
+
* its last `_`, the whole value, a variable of a shorter path first, so `WTF_VITE_COMPRESS_THRESHOLD`
|
|
37
|
+
* is over what `WTF_VITE` sets, of the prefix `WTF_VITE_`. A variable that names no key there
|
|
38
|
+
* is is passed over.
|
|
39
|
+
*/
|
|
40
|
+
export declare function withEnvironment(value: unknown, variables: Readonly<Record<string, string>>, prefix: string, schema?: JsonSchema): WithEnvironment;
|
package/dist/env.js
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
import { mergeSection } from "./merge.js";
|
|
2
|
+
/**
|
|
3
|
+
* A name as a variable of the environment writes it: its words in capitals, joined by `_`, a word
|
|
4
|
+
* of camelCase its own, as `apiKey` is `API_KEY`, and any other character a `_`.
|
|
5
|
+
*/
|
|
6
|
+
export const envNameOf = (name) => name
|
|
7
|
+
.replaceAll(/([a-z\d])([A-Z])/g, '$1_$2')
|
|
8
|
+
.replaceAll(/[^A-Za-z\d]+/g, '_')
|
|
9
|
+
.replaceAll(/^_|_$/g, '')
|
|
10
|
+
.toUpperCase();
|
|
11
|
+
/** The prefix of the variables of the environment of `name`, the key of package.json by default:
|
|
12
|
+
* {@link envNameOf} it, and `_`, as `wtf` is `WTF_` and `wtf-vite` `WTF_VITE_`. */
|
|
13
|
+
export const envPrefixOf = (name) => `${envNameOf(name)}_`;
|
|
14
|
+
/** The variables of `environment` of `prefix`, as {@link envPrefixOf} gives it, each set and not
|
|
15
|
+
* empty, by their names. */
|
|
16
|
+
export function variablesOf(environment, prefix) {
|
|
17
|
+
const variables = {};
|
|
18
|
+
for (const [name, value] of Object.entries(environment))
|
|
19
|
+
if (name.startsWith(prefix) &&
|
|
20
|
+
name.length > prefix.length &&
|
|
21
|
+
value !== undefined &&
|
|
22
|
+
value !== '')
|
|
23
|
+
variables[name] = value;
|
|
24
|
+
return variables;
|
|
25
|
+
}
|
|
26
|
+
const isNode = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
27
|
+
/** The node a `$ref` of the document `root` names, as `#/$defs/api`; the node itself of none. */
|
|
28
|
+
function derefOf(node, root) {
|
|
29
|
+
if (!isNode(node) || typeof node.$ref !== 'string' || !node.$ref.startsWith('#'))
|
|
30
|
+
return node;
|
|
31
|
+
let at = root;
|
|
32
|
+
for (const part of node.$ref.slice(1).split('/').filter(Boolean))
|
|
33
|
+
at = isNode(at) ? at[part.replaceAll('~1', '/').replaceAll('~0', '~')] : undefined;
|
|
34
|
+
return at;
|
|
35
|
+
}
|
|
36
|
+
/** The schemas `node` is, of the document `root`: itself, and each of its `allOf`, `anyOf` and
|
|
37
|
+
* `oneOf`, each by its `$ref`. */
|
|
38
|
+
function schemasOf(node, root, seen = new Set()) {
|
|
39
|
+
const schema = derefOf(node, root);
|
|
40
|
+
if (!isNode(schema) || seen.has(schema))
|
|
41
|
+
return [];
|
|
42
|
+
seen.add(schema);
|
|
43
|
+
const branches = ['allOf', 'anyOf', 'oneOf'].flatMap((key) => Array.isArray(schema[key]) ? schema[key] : []);
|
|
44
|
+
return [schema, ...branches.flatMap((branch) => schemasOf(branch, root, seen))];
|
|
45
|
+
}
|
|
46
|
+
/** The schema of the key `key` of a value of the schema `node`: of each of its `properties` that
|
|
47
|
+
* names it. */
|
|
48
|
+
const propertyOf = (node, root, key) => schemasOf(node, root).flatMap((schema) => isNode(schema.properties) && Object.hasOwn(schema.properties, key)
|
|
49
|
+
? [schema.properties[key]]
|
|
50
|
+
: []);
|
|
51
|
+
/** Whether a value of the schemas `nodes` is only ever a string: of a `type` `string`, a `const`
|
|
52
|
+
* or an `enum` of strings, each branch of it so. */
|
|
53
|
+
function onlyString(nodes, root) {
|
|
54
|
+
const schemas = nodes.flatMap((node) => schemasOf(node, root));
|
|
55
|
+
return schemas.some((schema) => schema.type === 'string' ||
|
|
56
|
+
typeof schema.const === 'string' ||
|
|
57
|
+
(Array.isArray(schema.enum) && schema.enum.every((value) => typeof value === 'string')) ||
|
|
58
|
+
['anyOf', 'oneOf'].some((key) => Array.isArray(schema[key]) &&
|
|
59
|
+
schema[key].every((branch) => onlyString([branch], root))));
|
|
60
|
+
}
|
|
61
|
+
/** The keys a value can have, as the value `value` and the schemas `nodes` name them, the
|
|
62
|
+
* longest of them as a variable names it first, so `API_KEY` is `apiKey` before it is `api.key`. */
|
|
63
|
+
function keysOf(value, nodes, root) {
|
|
64
|
+
const keys = new Set(isNode(value) ? Object.keys(value) : []);
|
|
65
|
+
for (const schema of nodes.flatMap((node) => schemasOf(node, root)))
|
|
66
|
+
if (isNode(schema.properties))
|
|
67
|
+
for (const key of Object.keys(schema.properties))
|
|
68
|
+
keys.add(key);
|
|
69
|
+
return [...keys].toSorted((a, b) => envNameOf(b).length - envNameOf(a).length);
|
|
70
|
+
}
|
|
71
|
+
/** The path the rest of a variable's name, `rest`, names in `value`, of the schemas `nodes`, and
|
|
72
|
+
* the schemas of the value there; `undefined` when it names no key there is. */
|
|
73
|
+
function pathOf(rest, value, nodes, root) {
|
|
74
|
+
for (const key of keysOf(value, nodes, root)) {
|
|
75
|
+
const name = envNameOf(key);
|
|
76
|
+
if (name === '')
|
|
77
|
+
continue;
|
|
78
|
+
const under = nodes.flatMap((node) => propertyOf(node, root, key));
|
|
79
|
+
if (rest === name)
|
|
80
|
+
return { path: [key], nodes: under };
|
|
81
|
+
if (rest.startsWith(`${name}_`)) {
|
|
82
|
+
const found = pathOf(rest.slice(name.length + 1), isNode(value) ? value[key] : undefined, under, root);
|
|
83
|
+
if (found !== undefined)
|
|
84
|
+
return { path: [key, ...found.path], nodes: found.nodes };
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
return undefined;
|
|
88
|
+
}
|
|
89
|
+
/** The value of a variable's text: the text of a value that is only ever a string, else its JSON,
|
|
90
|
+
* else the text. */
|
|
91
|
+
function parsedOf(text, nodes, root) {
|
|
92
|
+
if (onlyString(nodes, root))
|
|
93
|
+
return text;
|
|
94
|
+
try {
|
|
95
|
+
return JSON.parse(text);
|
|
96
|
+
}
|
|
97
|
+
catch {
|
|
98
|
+
return text;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
/** `value` with `over` at `path`, merged over what is there ({@link mergeSection}). */
|
|
102
|
+
function withValueAt(value, path, over) {
|
|
103
|
+
const [key, ...rest] = path;
|
|
104
|
+
if (key === undefined)
|
|
105
|
+
return mergeSection(value, over);
|
|
106
|
+
const object = isNode(value) ? value : {};
|
|
107
|
+
return { ...object, [key]: withValueAt(object[key], rest, over) };
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* The JSON Schema of `schema`, as a tool checks its section by it: the schema itself, of a JSON
|
|
111
|
+
* Schema; of a Standard Schema that gives one, as zod's does, the JSON Schema of its input; else
|
|
112
|
+
* none, of a function, or a schema that gives none.
|
|
113
|
+
*/
|
|
114
|
+
export function jsonSchemaOf(schema) {
|
|
115
|
+
if (typeof schema === 'boolean')
|
|
116
|
+
return schema;
|
|
117
|
+
if (!isNode(schema))
|
|
118
|
+
return undefined;
|
|
119
|
+
if (!('~standard' in schema))
|
|
120
|
+
return schema;
|
|
121
|
+
const converter = schema['~standard']?.jsonSchema;
|
|
122
|
+
if (converter === undefined)
|
|
123
|
+
return undefined;
|
|
124
|
+
try {
|
|
125
|
+
return converter.input({ target: 'draft-2020-12' });
|
|
126
|
+
}
|
|
127
|
+
catch {
|
|
128
|
+
return undefined;
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* `value` with the variables `variables` of `prefix` over it: each variable that names a path of
|
|
133
|
+
* a key there is, in `value` or in `schema`, a JSON Schema of it, sets the value at that path,
|
|
134
|
+
* merged over what is there ({@link mergeSection}), and the variable of the prefix itself, without
|
|
135
|
+
* its last `_`, the whole value, a variable of a shorter path first, so `WTF_VITE_COMPRESS_THRESHOLD`
|
|
136
|
+
* is over what `WTF_VITE` sets, of the prefix `WTF_VITE_`. A variable that names no key there
|
|
137
|
+
* is is passed over.
|
|
138
|
+
*/
|
|
139
|
+
export function withEnvironment(value, variables, prefix, schema) {
|
|
140
|
+
const nodes = schema === undefined ? [] : [schema];
|
|
141
|
+
const whole = prefix.slice(0, -1);
|
|
142
|
+
const found = Object.entries(variables).flatMap(([variable, text]) => {
|
|
143
|
+
const at = variable === whole
|
|
144
|
+
? { path: [], nodes }
|
|
145
|
+
: variable.startsWith(prefix)
|
|
146
|
+
? pathOf(variable.slice(prefix.length), value, nodes, schema)
|
|
147
|
+
: undefined;
|
|
148
|
+
return at === undefined
|
|
149
|
+
? []
|
|
150
|
+
: [{ variable, path: at.path, value: parsedOf(text, at.nodes, schema) }];
|
|
151
|
+
});
|
|
152
|
+
let result = value;
|
|
153
|
+
const set = [];
|
|
154
|
+
for (const { variable, path, value: over } of found.toSorted((a, b) => a.path.length - b.path.length || a.variable.localeCompare(b.variable))) {
|
|
155
|
+
result = withValueAt(result, path, over);
|
|
156
|
+
set.push({ variable, path });
|
|
157
|
+
}
|
|
158
|
+
return { value: result, set };
|
|
159
|
+
}
|
|
160
|
+
//# sourceMappingURL=env.js.map
|
package/dist/env.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"env.js","sourceRoot":"","sources":["../src/env.ts"],"names":[],"mappings":"AAsBA,OAAO,EAAE,YAAY,EAAE,MAAM,YAAY,CAAA;AAkBzC;;;GAGG;AACH,MAAM,CAAC,MAAM,SAAS,GAAG,CAAC,IAAY,EAAU,EAAE,CAChD,IAAI;KACD,UAAU,CAAC,mBAAmB,EAAE,OAAO,CAAC;KACxC,UAAU,CAAC,eAAe,EAAE,GAAG,CAAC;KAChC,UAAU,CAAC,QAAQ,EAAE,EAAE,CAAC;KACxB,WAAW,EAAE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,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,IAAI,KAAK,CAAC,QAAQ,CAC1D,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC,IAAI,CAAC,MAAM,IAAI,CAAC,CAAC,QAAQ,CAAC,aAAa,CAAC,CAAC,CAAC,QAAQ,CAAC,CAChF,EAAE,CAAC;QACF,MAAM,GAAG,WAAW,CAAC,MAAM,EAAE,IAAI,EAAE,IAAI,CAAC,CAAA;QACxC,GAAG,CAAC,IAAI,CAAC,EAAE,QAAQ,EAAE,IAAI,EAAE,CAAC,CAAA;IAC9B,CAAC;IACD,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,EAAE,CAAA;AAC/B,CAAC","sourcesContent":["/**\n * The configuration of a project, as the environment overrides it: a variable of the prefix of its\n * names, of the key of package.json by default, as `WTF_` of the key `wtf` ({@link envPrefixOf}),\n * followed by the path of a value, each key as a variable names it ({@link envNameOf}):\n * `WTF_VITE_COMPRESS` sets `wtf.vite.compress`. A key is one a value under it already has, or one\n * the schema of its section names, so `apiKey` is `API_KEY` and no `_` is ever taken for a key it\n * is not. A value is JSON, else the text as it is, and the text always of a value the schema takes\n * only as a string. {@link variablesOf} gives the variables of a prefix, and\n * {@link withEnvironment} a value with them over it, as `sectionOf` of ./section reads a section.\n * The variables are what a caller gives, as `loadConfig` of ./load takes them: nothing here reads\n * the environment of a process.\n *\n * ```ts\n * withEnvironment({ compress: { threshold: 1024 } }, { WTF_VITE_COMPRESS_THRESHOLD: '512' }, 'WTF_VITE_')\n * // { value: { compress: { threshold: 512 } }, set: [{ variable: 'WTF_VITE_COMPRESS_THRESHOLD', path: ['compress', 'threshold'] }] }\n * ```\n *\n * @packageDocumentation\n */\nimport type { StandardJSONSchemaV1 } from '@standard-schema/spec'\n\nimport type { ConfigPath, JsonSchema } from './index.ts'\nimport { mergeSection } from './merge.ts'\n\n/** The variables of an environment, by their names, as a process's environment holds them. */\nexport type Environment = Readonly<Record<string, string | undefined>>\n\n/** A variable of the environment that set a value of the configuration: its name, and the path\n * of the value. */\nexport type EnvironmentValue = {\n readonly variable: string\n readonly path: ConfigPath\n}\n\n/** A value with the environment over it: the value, and each variable that set some of it. */\nexport type WithEnvironment = {\n readonly value: unknown\n readonly set: readonly EnvironmentValue[]\n}\n\n/**\n * A name as a variable of the environment writes it: its words in capitals, joined by `_`, a word\n * of camelCase its own, as `apiKey` is `API_KEY`, and any other character a `_`.\n */\nexport const envNameOf = (name: string): string =>\n name\n .replaceAll(/([a-z\\d])([A-Z])/g, '$1_$2')\n .replaceAll(/[^A-Za-z\\d]+/g, '_')\n .replaceAll(/^_|_$/g, '')\n .toUpperCase()\n\n/** The prefix of the variables of the environment of `name`, the key of package.json by default:\n * {@link envNameOf} it, and `_`, as `wtf` is `WTF_` and `wtf-vite` `WTF_VITE_`. */\nexport const envPrefixOf = (name: string): string => `${envNameOf(name)}_`\n\n/** The variables of `environment` of `prefix`, as {@link envPrefixOf} gives it, each set and not\n * empty, by their names. */\nexport function variablesOf(environment: Environment, prefix: string): Record<string, string> {\n const variables: Record<string, string> = {}\n for (const [name, value] of Object.entries(environment))\n if (\n name.startsWith(prefix) &&\n name.length > prefix.length &&\n value !== undefined &&\n value !== ''\n )\n variables[name] = value\n return variables\n}\n\ntype Node = Readonly<Record<string, unknown>>\n\nconst isNode = (value: unknown): value is Node =>\n typeof value === 'object' && value !== null && !Array.isArray(value)\n\n/** The node a `$ref` of the document `root` names, as `#/$defs/api`; the node itself of none. */\nfunction derefOf(node: unknown, root: unknown): unknown {\n if (!isNode(node) || typeof node.$ref !== 'string' || !node.$ref.startsWith('#')) return node\n let at: unknown = root\n for (const part of node.$ref.slice(1).split('/').filter(Boolean))\n at = isNode(at) ? at[part.replaceAll('~1', '/').replaceAll('~0', '~')] : undefined\n return at\n}\n\n/** The schemas `node` is, of the document `root`: itself, and each of its `allOf`, `anyOf` and\n * `oneOf`, each by its `$ref`. */\nfunction schemasOf(node: unknown, root: unknown, seen = new Set<unknown>()): Node[] {\n const schema = derefOf(node, root)\n if (!isNode(schema) || seen.has(schema)) return []\n seen.add(schema)\n const branches = ['allOf', 'anyOf', 'oneOf'].flatMap((key) =>\n Array.isArray(schema[key]) ? (schema[key] as unknown[]) : []\n )\n return [schema, ...branches.flatMap((branch) => schemasOf(branch, root, seen))]\n}\n\n/** The schema of the key `key` of a value of the schema `node`: of each of its `properties` that\n * names it. */\nconst propertyOf = (node: unknown, root: unknown, key: string): unknown[] =>\n schemasOf(node, root).flatMap((schema) =>\n isNode(schema.properties) && Object.hasOwn(schema.properties, key)\n ? [schema.properties[key]]\n : []\n )\n\n/** Whether a value of the schemas `nodes` is only ever a string: of a `type` `string`, a `const`\n * or an `enum` of strings, each branch of it so. */\nfunction onlyString(nodes: readonly unknown[], root: unknown): boolean {\n const schemas = nodes.flatMap((node) => schemasOf(node, root))\n return schemas.some(\n (schema) =>\n schema.type === 'string' ||\n typeof schema.const === 'string' ||\n (Array.isArray(schema.enum) && schema.enum.every((value) => typeof value === 'string')) ||\n (['anyOf', 'oneOf'] as const).some(\n (key) =>\n Array.isArray(schema[key]) &&\n (schema[key] as unknown[]).every((branch) => onlyString([branch], root))\n )\n )\n}\n\n/** The keys a value can have, as the value `value` and the schemas `nodes` name them, the\n * longest of them as a variable names it first, so `API_KEY` is `apiKey` before it is `api.key`. */\nfunction keysOf(value: unknown, nodes: readonly unknown[], root: unknown): string[] {\n const keys = new Set(isNode(value) ? Object.keys(value) : [])\n for (const schema of nodes.flatMap((node) => schemasOf(node, root)))\n if (isNode(schema.properties)) for (const key of Object.keys(schema.properties)) keys.add(key)\n return [...keys].toSorted((a, b) => envNameOf(b).length - envNameOf(a).length)\n}\n\n/** The path the rest of a variable's name, `rest`, names in `value`, of the schemas `nodes`, and\n * the schemas of the value there; `undefined` when it names no key there is. */\nfunction pathOf(\n rest: string,\n value: unknown,\n nodes: readonly unknown[],\n root: unknown\n): { readonly path: string[]; readonly nodes: readonly unknown[] } | undefined {\n for (const key of keysOf(value, nodes, root)) {\n const name = envNameOf(key)\n if (name === '') continue\n const under = nodes.flatMap((node) => propertyOf(node, root, key))\n if (rest === name) return { path: [key], nodes: under }\n if (rest.startsWith(`${name}_`)) {\n const found = pathOf(\n rest.slice(name.length + 1),\n isNode(value) ? value[key] : undefined,\n under,\n root\n )\n if (found !== undefined) return { path: [key, ...found.path], nodes: found.nodes }\n }\n }\n return undefined\n}\n\n/** The value of a variable's text: the text of a value that is only ever a string, else its JSON,\n * else the text. */\nfunction parsedOf(text: string, nodes: readonly unknown[], root: unknown): unknown {\n if (onlyString(nodes, root)) return text\n try {\n return JSON.parse(text) as unknown\n } catch {\n return text\n }\n}\n\n/** `value` with `over` at `path`, merged over what is there ({@link mergeSection}). */\nfunction withValueAt(value: unknown, path: ConfigPath, over: unknown): unknown {\n const [key, ...rest] = path\n if (key === undefined) return mergeSection(value, over)\n const object = isNode(value) ? value : {}\n return { ...object, [key]: withValueAt(object[key], rest, over) }\n}\n\n/**\n * The JSON Schema of `schema`, as a tool checks its section by it: the schema itself, of a JSON\n * Schema; of a Standard Schema that gives one, as zod's does, the JSON Schema of its input; else\n * none, of a function, or a schema that gives none.\n */\nexport function jsonSchemaOf(schema: unknown): JsonSchema | undefined {\n if (typeof schema === 'boolean') return schema\n if (!isNode(schema)) return undefined\n if (!('~standard' in schema)) return schema\n const converter = (schema as Partial<StandardJSONSchemaV1>)['~standard']?.jsonSchema\n if (converter === undefined) return undefined\n try {\n return converter.input({ target: 'draft-2020-12' })\n } catch {\n return undefined\n }\n}\n\n/**\n * `value` with the variables `variables` of `prefix` over it: each variable that names a path of\n * a key there is, in `value` or in `schema`, a JSON Schema of it, sets the value at that path,\n * merged over what is there ({@link mergeSection}), and the variable of the prefix itself, without\n * its last `_`, the whole value, a variable of a shorter path first, so `WTF_VITE_COMPRESS_THRESHOLD`\n * is over what `WTF_VITE` sets, of the prefix `WTF_VITE_`. A variable that names no key there\n * is is passed over.\n */\nexport function withEnvironment(\n value: unknown,\n variables: Readonly<Record<string, string>>,\n prefix: string,\n schema?: JsonSchema\n): WithEnvironment {\n const nodes = schema === undefined ? [] : [schema]\n const whole = prefix.slice(0, -1)\n const found = Object.entries(variables).flatMap(([variable, text]) => {\n const at =\n variable === whole\n ? { path: [], nodes }\n : variable.startsWith(prefix)\n ? pathOf(variable.slice(prefix.length), value, nodes, schema)\n : undefined\n return at === undefined\n ? []\n : [{ variable, path: at.path, value: parsedOf(text, at.nodes, schema) }]\n })\n let result = value\n const set: EnvironmentValue[] = []\n for (const { variable, path, value: over } of found.toSorted(\n (a, b) => a.path.length - b.path.length || a.variable.localeCompare(b.variable)\n )) {\n result = withValueAt(result, path, over)\n set.push({ variable, path })\n }\n return { value: result, set }\n}\n"]}
|
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What `@wtf/project-config` throws, each a {@link ConfigError} of a stable `code`:
|
|
3
|
+
* {@link InvalidConfigFileError}, a file of the configuration that holds no object;
|
|
4
|
+
* {@link InvalidSectionError}, a section its tool's schema refuses; {@link ConfigPathError}, a path
|
|
5
|
+
* that names no value; {@link ConfigInCodeError}, a write to a configuration of code;
|
|
6
|
+
* {@link NoConfigFileError}, a write with no package.json to hold it;
|
|
7
|
+
* {@link ConfigFileMismatchError}, a write to a file that is not the one in use;
|
|
8
|
+
* {@link UnwritableConfigFileError}, a write to a file that is never written;
|
|
9
|
+
* {@link NoConfigValueError}, a value asked for that is not set; and
|
|
10
|
+
* {@link EnvPlaceholderUnsetError}, a value that points at a variable of the environment that is
|
|
11
|
+
* not set; {@link SyncConfigInCodeError}, a configuration of code loaded synchronously; and
|
|
12
|
+
* {@link SyncSchemaError}, a section checked synchronously by a schema that checks asynchronously.
|
|
13
|
+
* One that the arguments of a person cause exits 2.
|
|
14
|
+
*
|
|
15
|
+
* @packageDocumentation
|
|
16
|
+
*/
|
|
17
|
+
import type { ConfigIssue, ConfigPath } from './index.ts';
|
|
18
|
+
/** What this package throws: an Error with a stable SCREAMING_SNAKE `code`, and the `exitCode` a
|
|
19
|
+
* command that fails by it exits with, 1 by default. */
|
|
20
|
+
export declare class ConfigError extends Error {
|
|
21
|
+
readonly code: string;
|
|
22
|
+
/** What a command that fails by it exits with. */
|
|
23
|
+
readonly exitCode: number;
|
|
24
|
+
constructor(code: string, message: string, options?: ErrorOptions);
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* A file of the configuration that holds no configuration: no JSON, no object, or a module that
|
|
28
|
+
* fails to load, or exports no object.
|
|
29
|
+
*/
|
|
30
|
+
export declare class InvalidConfigFileError extends ConfigError {
|
|
31
|
+
/** The file, by its absolute path. */
|
|
32
|
+
readonly file: string;
|
|
33
|
+
constructor(file: string, reason: string, options?: ErrorOptions);
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* A section of the configuration that the schema of its tool refuses: each issue, by the file and
|
|
37
|
+
* the path of the value, from the key that names the configuration, the namespace by default.
|
|
38
|
+
*/
|
|
39
|
+
export declare class InvalidSectionError extends ConfigError {
|
|
40
|
+
/** The file of the configuration, by its absolute path. */
|
|
41
|
+
readonly file: string;
|
|
42
|
+
/** The section, by its name. */
|
|
43
|
+
readonly section: string;
|
|
44
|
+
/** What is wrong, each by its path in the section. */
|
|
45
|
+
readonly issues: readonly ConfigIssue[];
|
|
46
|
+
constructor(file: string, namespace: string, section: string, issues: readonly ConfigIssue[], key?: string);
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* A path of the configuration that names no value to read or write: an empty one, or one that
|
|
50
|
+
* goes into a value that is no object or list. A usage failure: it exits 2.
|
|
51
|
+
*/
|
|
52
|
+
export declare class ConfigPathError extends ConfigError {
|
|
53
|
+
/** The path, as it was given. */
|
|
54
|
+
readonly path: string;
|
|
55
|
+
readonly exitCode: number;
|
|
56
|
+
constructor(path: string, reason: string);
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* A write to a configuration of code, as `wtf.config.mjs`, `wtf.config.js` or `wtf.config.ts`: code
|
|
60
|
+
* is changed by a person, and not by a tool. Its message names what is written: the JSON files, and
|
|
61
|
+
* the key of package.json.
|
|
62
|
+
*/
|
|
63
|
+
export declare class ConfigInCodeError extends ConfigError {
|
|
64
|
+
/** The file of code, by its absolute path. */
|
|
65
|
+
readonly file: string;
|
|
66
|
+
constructor(file: string, written: {
|
|
67
|
+
readonly files: readonly string[];
|
|
68
|
+
readonly key: string;
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* A write to the configuration of a project that has none, in the key of package.json, the
|
|
73
|
+
* default, where the root has no package.json. Its message names the key, and the JSON file to make
|
|
74
|
+
* it in instead, if there is one. A usage failure: it exits 2.
|
|
75
|
+
*/
|
|
76
|
+
export declare class NoConfigFileError extends ConfigError {
|
|
77
|
+
/** The root of the project. */
|
|
78
|
+
readonly root: string;
|
|
79
|
+
readonly exitCode: number;
|
|
80
|
+
constructor(root: string, { namespace, key, json }: {
|
|
81
|
+
readonly namespace: string;
|
|
82
|
+
readonly key?: string;
|
|
83
|
+
readonly json?: string | undefined;
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* A write to a file of the configuration that is not the one in use, as its JSON file named where
|
|
88
|
+
* package.json holds it. A usage failure: it exits 2.
|
|
89
|
+
*/
|
|
90
|
+
export declare class ConfigFileMismatchError extends ConfigError {
|
|
91
|
+
/** The file that holds the configuration, by its absolute path. */
|
|
92
|
+
readonly file: string;
|
|
93
|
+
/** The file named. */
|
|
94
|
+
readonly named: string;
|
|
95
|
+
readonly exitCode: number;
|
|
96
|
+
constructor(file: string, named: string);
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* A write to a file that is no JSON file of the names of the configuration, nor package.json: one
|
|
100
|
+
* of code, or one its names do not hold. Its message names those that are written. A usage
|
|
101
|
+
* failure: it exits 2.
|
|
102
|
+
*/
|
|
103
|
+
export declare class UnwritableConfigFileError extends ConfigError {
|
|
104
|
+
/** The file named. */
|
|
105
|
+
readonly named: string;
|
|
106
|
+
readonly exitCode: number;
|
|
107
|
+
constructor(named: string, written: readonly string[]);
|
|
108
|
+
}
|
|
109
|
+
/** A value of the configuration that is not set, which was asked for. */
|
|
110
|
+
export declare class NoConfigValueError extends ConfigError {
|
|
111
|
+
/** The path, as it was given. */
|
|
112
|
+
readonly path: string;
|
|
113
|
+
/** The file of the configuration, by its absolute path, or `undefined` when there is none. */
|
|
114
|
+
readonly file: string | undefined;
|
|
115
|
+
constructor(path: string, file: string | undefined);
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* A value of the configuration that points at a variable of the environment, by a placeholder
|
|
119
|
+
* `${env:NAME}`, which is not set, or is empty. Its message names the path of the value, from the
|
|
120
|
+
* key that names the configuration, and the variable, and holds no value.
|
|
121
|
+
*/
|
|
122
|
+
export declare class EnvPlaceholderUnsetError extends ConfigError {
|
|
123
|
+
/** The path of the value that holds the placeholder. */
|
|
124
|
+
readonly path: ConfigPath;
|
|
125
|
+
/** The name of the variable of the environment. */
|
|
126
|
+
readonly variable: string;
|
|
127
|
+
constructor(path: ConfigPath, variable: string);
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* A configuration of code, as `wtf.config.ts`, loaded synchronously, as `loadConfigSync` of ./load
|
|
131
|
+
* loads it for a tool that reads its config synchronously: code is imported, which is
|
|
132
|
+
* asynchronous. Its message names the files a synchronous load reads, JSON and package.json's key.
|
|
133
|
+
*/
|
|
134
|
+
export declare class SyncConfigInCodeError extends ConfigError {
|
|
135
|
+
/** The file of code, by its absolute path. */
|
|
136
|
+
readonly file: string;
|
|
137
|
+
constructor(file: string, read: {
|
|
138
|
+
readonly files: readonly string[];
|
|
139
|
+
readonly key: string;
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* A section checked synchronously, as `sectionOfSync` of ./section checks it, by a schema that
|
|
144
|
+
* checks asynchronously: a Standard Schema whose `validate` gives a promise, or a function that
|
|
145
|
+
* does.
|
|
146
|
+
*/
|
|
147
|
+
export declare class SyncSchemaError extends ConfigError {
|
|
148
|
+
/** The section, by its name. */
|
|
149
|
+
readonly section: string;
|
|
150
|
+
constructor(section: string);
|
|
151
|
+
}
|