@wtf/project-config 0.0.0-stage → 1.0.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.
Files changed (48) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +76 -2
  3. package/dist/define.d.ts +26 -0
  4. package/dist/define.js +7 -0
  5. package/dist/define.js.map +1 -0
  6. package/dist/env.d.ts +40 -0
  7. package/dist/env.js +160 -0
  8. package/dist/env.js.map +1 -0
  9. package/dist/errors.d.ts +151 -0
  10. package/dist/errors.js +175 -0
  11. package/dist/errors.js.map +1 -0
  12. package/dist/files.d.ts +51 -0
  13. package/dist/files.js +120 -0
  14. package/dist/files.js.map +1 -0
  15. package/dist/index.d.ts +196 -0
  16. package/dist/index.js +2 -0
  17. package/dist/index.js.map +1 -0
  18. package/dist/load.d.ts +82 -0
  19. package/dist/load.js +140 -0
  20. package/dist/load.js.map +1 -0
  21. package/dist/locate.d.ts +71 -0
  22. package/dist/locate.js +121 -0
  23. package/dist/locate.js.map +1 -0
  24. package/dist/merge.d.ts +10 -0
  25. package/dist/merge.js +33 -0
  26. package/dist/merge.js.map +1 -0
  27. package/dist/node.d.ts +20 -0
  28. package/dist/node.js +90 -0
  29. package/dist/node.js.map +1 -0
  30. package/dist/path.d.ts +14 -0
  31. package/dist/path.js +40 -0
  32. package/dist/path.js.map +1 -0
  33. package/dist/placeholder.d.ts +37 -0
  34. package/dist/placeholder.js +47 -0
  35. package/dist/placeholder.js.map +1 -0
  36. package/dist/schema.d.ts +23 -0
  37. package/dist/schema.js +56 -0
  38. package/dist/schema.js.map +1 -0
  39. package/dist/section.d.ts +39 -0
  40. package/dist/section.js +169 -0
  41. package/dist/section.js.map +1 -0
  42. package/dist/text.d.ts +3 -0
  43. package/dist/text.js +3 -0
  44. package/dist/text.js.map +1 -0
  45. package/dist/write.d.ts +35 -0
  46. package/dist/write.js +209 -0
  47. package/dist/write.js.map +1 -0
  48. package/package.json +89 -4
package/dist/errors.js ADDED
@@ -0,0 +1,175 @@
1
+ import { textOfPath } from "./text.js";
2
+ /** What this package throws: an Error with a stable SCREAMING_SNAKE `code`, and the `exitCode` a
3
+ * command that fails by it exits with, 1 by default. */
4
+ export class ConfigError extends Error {
5
+ code;
6
+ /** What a command that fails by it exits with. */
7
+ exitCode = 1;
8
+ constructor(code, message, options) {
9
+ super(message, options);
10
+ this.code = code;
11
+ this.name = new.target.name;
12
+ }
13
+ }
14
+ /**
15
+ * A file of the configuration that holds no configuration: no JSON, no object, or a module that
16
+ * fails to load, or exports no object.
17
+ */
18
+ export class InvalidConfigFileError extends ConfigError {
19
+ /** The file, by its absolute path. */
20
+ file;
21
+ constructor(file, reason, options) {
22
+ super('INVALID_CONFIG_FILE', `${file}: ${reason}`, options);
23
+ this.file = file;
24
+ }
25
+ }
26
+ /**
27
+ * A section of the configuration that the schema of its tool refuses: each issue, by the file and
28
+ * the path of the value, from the key that names the configuration, the namespace by default.
29
+ */
30
+ export class InvalidSectionError extends ConfigError {
31
+ /** The file of the configuration, by its absolute path. */
32
+ file;
33
+ /** The section, by its name. */
34
+ section;
35
+ /** What is wrong, each by its path in the section. */
36
+ issues;
37
+ constructor(file, namespace, section, issues, key = namespace) {
38
+ super('INVALID_CONFIG_SECTION', [
39
+ `${file}: the ${section} section of the ${namespace} configuration is not valid:`,
40
+ ...issues.map(({ path, message }) => ` ${textOfPath([key, section, ...path])}: ${message}`)
41
+ ].join('\n'));
42
+ this.file = file;
43
+ this.section = section;
44
+ this.issues = issues;
45
+ }
46
+ }
47
+ /**
48
+ * A path of the configuration that names no value to read or write: an empty one, or one that
49
+ * goes into a value that is no object or list. A usage failure: it exits 2.
50
+ */
51
+ export class ConfigPathError extends ConfigError {
52
+ /** The path, as it was given. */
53
+ path;
54
+ exitCode = 2;
55
+ constructor(path, reason) {
56
+ super('INVALID_CONFIG_PATH', `${path === '' ? 'The path' : path} ${reason}`);
57
+ this.path = path;
58
+ }
59
+ }
60
+ /**
61
+ * A write to a configuration of code, as `wtf.config.mjs`, `wtf.config.js` or `wtf.config.ts`: code
62
+ * is changed by a person, and not by a tool. Its message names what is written: the JSON files, and
63
+ * the key of package.json.
64
+ */
65
+ export class ConfigInCodeError extends ConfigError {
66
+ /** The file of code, by its absolute path. */
67
+ file;
68
+ constructor(file, written) {
69
+ const names = [...written.files, `the "${written.key}" key of package.json`];
70
+ super('CONFIG_IN_CODE', `The configuration is code, in ${file}: change it there. Only ${names.join(' and ')} ${names.length === 1 ? 'is' : 'are'} written.`);
71
+ this.file = file;
72
+ }
73
+ }
74
+ /**
75
+ * A write to the configuration of a project that has none, in the key of package.json, the
76
+ * default, where the root has no package.json. Its message names the key, and the JSON file to make
77
+ * it in instead, if there is one. A usage failure: it exits 2.
78
+ */
79
+ export class NoConfigFileError extends ConfigError {
80
+ /** The root of the project. */
81
+ root;
82
+ exitCode = 2;
83
+ constructor(root, { namespace, key = namespace, json }) {
84
+ super('NO_CONFIG_FILE', `No package.json is in ${root} to hold the ${namespace} configuration in its "${key}" key: make one there${json === undefined ? '' : `, or name ${json} to make the configuration in`}.`);
85
+ this.root = root;
86
+ }
87
+ }
88
+ /**
89
+ * A write to a file of the configuration that is not the one in use, as its JSON file named where
90
+ * package.json holds it. A usage failure: it exits 2.
91
+ */
92
+ export class ConfigFileMismatchError extends ConfigError {
93
+ /** The file that holds the configuration, by its absolute path. */
94
+ file;
95
+ /** The file named. */
96
+ named;
97
+ exitCode = 2;
98
+ constructor(file, named) {
99
+ super('CONFIG_FILE_MISMATCH', `The configuration is in ${file}, and not in ${named}: write it there, or move it.`);
100
+ this.file = file;
101
+ this.named = named;
102
+ }
103
+ }
104
+ /**
105
+ * A write to a file that is no JSON file of the names of the configuration, nor package.json: one
106
+ * of code, or one its names do not hold. Its message names those that are written. A usage
107
+ * failure: it exits 2.
108
+ */
109
+ export class UnwritableConfigFileError extends ConfigError {
110
+ /** The file named. */
111
+ named;
112
+ exitCode = 2;
113
+ constructor(named, written) {
114
+ super('UNWRITABLE_CONFIG_FILE', `${named} is no file the configuration is written to: name ${[...written, 'package.json'].join(' or ')}.`);
115
+ this.named = named;
116
+ }
117
+ }
118
+ /** A value of the configuration that is not set, which was asked for. */
119
+ export class NoConfigValueError extends ConfigError {
120
+ /** The path, as it was given. */
121
+ path;
122
+ /** The file of the configuration, by its absolute path, or `undefined` when there is none. */
123
+ file;
124
+ constructor(path, file) {
125
+ super('NO_CONFIG_VALUE', file === undefined
126
+ ? `${path} is not set: the project has no configuration.`
127
+ : `${path} is not set in ${file}.`);
128
+ this.path = path;
129
+ this.file = file;
130
+ }
131
+ }
132
+ /**
133
+ * A value of the configuration that points at a variable of the environment, by a placeholder
134
+ * `${env:NAME}`, which is not set, or is empty. Its message names the path of the value, from the
135
+ * key that names the configuration, and the variable, and holds no value.
136
+ */
137
+ export class EnvPlaceholderUnsetError extends ConfigError {
138
+ /** The path of the value that holds the placeholder. */
139
+ path;
140
+ /** The name of the variable of the environment. */
141
+ variable;
142
+ constructor(path, variable) {
143
+ super('CONFIG_ENV_PLACEHOLDER_UNSET', `${textOfPath(path)}: points at the variable ${variable} of the environment by \${env:${variable}}, which is not set, or is empty.`);
144
+ this.path = path;
145
+ this.variable = variable;
146
+ }
147
+ }
148
+ /**
149
+ * A configuration of code, as `wtf.config.ts`, loaded synchronously, as `loadConfigSync` of ./load
150
+ * loads it for a tool that reads its config synchronously: code is imported, which is
151
+ * asynchronous. Its message names the files a synchronous load reads, JSON and package.json's key.
152
+ */
153
+ export class SyncConfigInCodeError extends ConfigError {
154
+ /** The file of code, by its absolute path. */
155
+ file;
156
+ constructor(file, read) {
157
+ const names = [...read.files, `the "${read.key}" key of package.json`];
158
+ super('CONFIG_IN_CODE_SYNC', `The configuration is code, in ${file}, which a synchronous load cannot import: write it in ${names.join(' or ')}, or load it with loadConfig.`);
159
+ this.file = file;
160
+ }
161
+ }
162
+ /**
163
+ * A section checked synchronously, as `sectionOfSync` of ./section checks it, by a schema that
164
+ * checks asynchronously: a Standard Schema whose `validate` gives a promise, or a function that
165
+ * does.
166
+ */
167
+ export class SyncSchemaError extends ConfigError {
168
+ /** The section, by its name. */
169
+ section;
170
+ constructor(section) {
171
+ super('SCHEMA_NOT_SYNC', `The schema of the ${section} section checks it asynchronously: read it with sectionOf.`);
172
+ this.section = section;
173
+ }
174
+ }
175
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAiBA,OAAO,EAAE,UAAU,EAAE,MAAM,WAAW,CAAA;AAEtC;wDACwD;AACxD,MAAM,OAAO,WAAY,SAAQ,KAAK;IAC3B,IAAI,CAAQ;IACrB,kDAAkD;IACzC,QAAQ,GAAW,CAAC,CAAA;IAE7B,YAAY,IAAY,EAAE,OAAe,EAAE,OAAsB;QAC/D,KAAK,CAAC,OAAO,EAAE,OAAO,CAAC,CAAA;QACvB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAA;QAChB,IAAI,CAAC,IAAI,GAAG,GAAG,CAAC,MAAM,CAAC,IAAI,CAAA;IAC7B,CAAC;CACF;AAED;;;GAGG;AACH,MAAM,OAAO,sBAAuB,SAAQ,WAAW;IACrD,sCAAsC;IAC7B,IAAI,CAAQ;IAErB,YAAY,IAAY,EAAE,MAAc,EAAE,OAAsB;QAC9D,KAAK,CAAC,qBAAqB,EAAE,GAAG,IAAI,KAAK,MAAM,EAAE,EAAE,OAAO,CAAC,CAAA;QAC3D,IAAI,CAAC,IAAI,GAAG,IAAI,CAAA;IAClB,CAAC;CACF;AAED;;;GAGG;AACH,MAAM,OAAO,mBAAoB,SAAQ,WAAW;IAClD,2DAA2D;IAClD,IAAI,CAAQ;IACrB,gCAAgC;IACvB,OAAO,CAAQ;IACxB,sDAAsD;IAC7C,MAAM,CAAwB;IAEvC,YACE,IAAY,EACZ,SAAiB,EACjB,OAAe,EACf,MAA8B,EAC9B,MAAc,SAAS;QAEvB,KAAK,CACH,wBAAwB,EACxB;YACE,GAAG,IAA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A4D,CACzF,CAAA;QACD,IAAI,CAAC,OAAO,GAAG,OAAO,CAAA;IACxB,CAAC;CACF","sourcesContent":["/**\n * What `@wtf/project-config` throws, each a {@link ConfigError} of a stable `code`:\n * {@link InvalidConfigFileError}, a file of the configuration that holds no object;\n * {@link InvalidSectionError}, a section its tool's schema refuses; {@link ConfigPathError}, a path\n * that names no value; {@link ConfigInCodeError}, a write to a configuration of code;\n * {@link NoConfigFileError}, a write with no package.json to hold it;\n * {@link ConfigFileMismatchError}, a write to a file that is not the one in use;\n * {@link UnwritableConfigFileError}, a write to a file that is never written;\n * {@link NoConfigValueError}, a value asked for that is not set; and\n * {@link EnvPlaceholderUnsetError}, a value that points at a variable of the environment that is\n * not set; {@link SyncConfigInCodeError}, a configuration of code loaded synchronously; and\n * {@link SyncSchemaError}, a section checked synchronously by a schema that checks asynchronously.\n * One that the arguments of a person cause exits 2.\n *\n * @packageDocumentation\n */\nimport type { ConfigIssue, ConfigPath } from './index.ts'\nimport { textOfPath } from './text.ts'\n\n/** What this package throws: an Error with a stable SCREAMING_SNAKE `code`, and the `exitCode` a\n * command that fails by it exits with, 1 by default. */\nexport class ConfigError extends Error {\n readonly code: string\n /** What a command that fails by it exits with. */\n readonly exitCode: number = 1\n\n constructor(code: string, message: string, options?: ErrorOptions) {\n super(message, options)\n this.code = code\n this.name = new.target.name\n }\n}\n\n/**\n * A file of the configuration that holds no configuration: no JSON, no object, or a module that\n * fails to load, or exports no object.\n */\nexport class InvalidConfigFileError extends ConfigError {\n /** The file, by its absolute path. */\n readonly file: string\n\n constructor(file: string, reason: string, options?: ErrorOptions) {\n super('INVALID_CONFIG_FILE', `${file}: ${reason}`, options)\n this.file = file\n }\n}\n\n/**\n * A section of the configuration that the schema of its tool refuses: each issue, by the file and\n * the path of the value, from the key that names the configuration, the namespace by default.\n */\nexport class InvalidSectionError extends ConfigError {\n /** The file of the configuration, by its absolute path. */\n readonly file: string\n /** The section, by its name. */\n readonly section: string\n /** What is wrong, each by its path in the section. */\n readonly issues: readonly ConfigIssue[]\n\n constructor(\n file: string,\n namespace: string,\n section: string,\n issues: readonly ConfigIssue[],\n key: string = namespace\n ) {\n super(\n 'INVALID_CONFIG_SECTION',\n [\n `${file}: the ${section} section of the ${namespace} configuration is not valid:`,\n ...issues.map(({ path, message }) => ` ${textOfPath([key, section, ...path])}: ${message}`)\n ].join('\\n')\n )\n this.file = file\n this.section = section\n this.issues = issues\n }\n}\n\n/**\n * A path of the configuration that names no value to read or write: an empty one, or one that\n * goes into a value that is no object or list. A usage failure: it exits 2.\n */\nexport class ConfigPathError extends ConfigError {\n /** The path, as it was given. */\n readonly path: string\n override readonly exitCode: number = 2\n\n constructor(path: string, reason: string) {\n super('INVALID_CONFIG_PATH', `${path === '' ? 'The path' : path} ${reason}`)\n this.path = path\n }\n}\n\n/**\n * A write to a configuration of code, as `wtf.config.mjs`, `wtf.config.js` or `wtf.config.ts`: code\n * is changed by a person, and not by a tool. Its message names what is written: the JSON files, and\n * the key of package.json.\n */\nexport class ConfigInCodeError extends ConfigError {\n /** The file of code, by its absolute path. */\n readonly file: string\n\n constructor(file: string, written: { readonly files: readonly string[]; readonly key: string }) {\n const names = [...written.files, `the \"${written.key}\" key of package.json`]\n super(\n 'CONFIG_IN_CODE',\n `The configuration is code, in ${file}: change it there. Only ${names.join(' and ')} ${names.length === 1 ? 'is' : 'are'} written.`\n )\n this.file = file\n }\n}\n\n/**\n * A write to the configuration of a project that has none, in the key of package.json, the\n * default, where the root has no package.json. Its message names the key, and the JSON file to make\n * it in instead, if there is one. A usage failure: it exits 2.\n */\nexport class NoConfigFileError extends ConfigError {\n /** The root of the project. */\n readonly root: string\n override readonly exitCode: number = 2\n\n constructor(\n root: string,\n {\n namespace,\n key = namespace,\n json\n }: { readonly namespace: string; readonly key?: string; readonly json?: string | undefined }\n ) {\n super(\n 'NO_CONFIG_FILE',\n `No package.json is in ${root} to hold the ${namespace} configuration in its \"${key}\" key: make one there${json === undefined ? '' : `, or name ${json} to make the configuration in`}.`\n )\n this.root = root\n }\n}\n\n/**\n * A write to a file of the configuration that is not the one in use, as its JSON file named where\n * package.json holds it. A usage failure: it exits 2.\n */\nexport class ConfigFileMismatchError extends ConfigError {\n /** The file that holds the configuration, by its absolute path. */\n readonly file: string\n /** The file named. */\n readonly named: string\n override readonly exitCode: number = 2\n\n constructor(file: string, named: string) {\n super(\n 'CONFIG_FILE_MISMATCH',\n `The configuration is in ${file}, and not in ${named}: write it there, or move it.`\n )\n this.file = file\n this.named = named\n }\n}\n\n/**\n * A write to a file that is no JSON file of the names of the configuration, nor package.json: one\n * of code, or one its names do not hold. Its message names those that are written. A usage\n * failure: it exits 2.\n */\nexport class UnwritableConfigFileError extends ConfigError {\n /** The file named. */\n readonly named: string\n override readonly exitCode: number = 2\n\n constructor(named: string, written: readonly string[]) {\n super(\n 'UNWRITABLE_CONFIG_FILE',\n `${named} is no file the configuration is written to: name ${[...written, 'package.json'].join(' or ')}.`\n )\n this.named = named\n }\n}\n\n/** A value of the configuration that is not set, which was asked for. */\nexport class NoConfigValueError extends ConfigError {\n /** The path, as it was given. */\n readonly path: string\n /** The file of the configuration, by its absolute path, or `undefined` when there is none. */\n readonly file: string | undefined\n\n constructor(path: string, file: string | undefined) {\n super(\n 'NO_CONFIG_VALUE',\n file === undefined\n ? `${path} is not set: the project has no configuration.`\n : `${path} is not set in ${file}.`\n )\n this.path = path\n this.file = file\n }\n}\n\n/**\n * A value of the configuration that points at a variable of the environment, by a placeholder\n * `${env:NAME}`, which is not set, or is empty. Its message names the path of the value, from the\n * key that names the configuration, and the variable, and holds no value.\n */\nexport class EnvPlaceholderUnsetError extends ConfigError {\n /** The path of the value that holds the placeholder. */\n readonly path: ConfigPath\n /** The name of the variable of the environment. */\n readonly variable: string\n\n constructor(path: ConfigPath, variable: string) {\n super(\n 'CONFIG_ENV_PLACEHOLDER_UNSET',\n `${textOfPath(path)}: points at the variable ${variable} of the environment by \\${env:${variable}}, which is not set, or is empty.`\n )\n this.path = path\n this.variable = variable\n }\n}\n\n/**\n * A configuration of code, as `wtf.config.ts`, loaded synchronously, as `loadConfigSync` of ./load\n * loads it for a tool that reads its config synchronously: code is imported, which is\n * asynchronous. Its message names the files a synchronous load reads, JSON and package.json's key.\n */\nexport class SyncConfigInCodeError extends ConfigError {\n /** The file of code, by its absolute path. */\n readonly file: string\n\n constructor(file: string, read: { readonly files: readonly string[]; readonly key: string }) {\n const names = [...read.files, `the \"${read.key}\" key of package.json`]\n super(\n 'CONFIG_IN_CODE_SYNC',\n `The configuration is code, in ${file}, which a synchronous load cannot import: write it in ${names.join(' or ')}, or load it with loadConfig.`\n )\n this.file = file\n }\n}\n\n/**\n * A section checked synchronously, as `sectionOfSync` of ./section checks it, by a schema that\n * checks asynchronously: a Standard Schema whose `validate` gives a promise, or a function that\n * does.\n */\nexport class SyncSchemaError extends ConfigError {\n /** The section, by its name. */\n readonly section: string\n\n constructor(section: string) {\n super(\n 'SCHEMA_NOT_SYNC',\n `The schema of the ${section} section checks it asynchronously: read it with sectionOf.`\n )\n this.section = section\n }\n}\n"]}
@@ -0,0 +1,51 @@
1
+ import type { ConfigPlatform, SyncFiles } from './index.ts';
2
+ /** Whether `value` is a JSON object: no list, and not `null`. */
3
+ export declare const isObject: (value: unknown) => value is Record<string, unknown>;
4
+ /** What the configuration is read and written by, asynchronously. */
5
+ export type Files = {
6
+ /** The text of the file at `path`, or `undefined` when no file is there. */
7
+ readonly text: (path: string) => Promise<string | undefined>;
8
+ /** The names of the files in `folder`, none when it is no folder. */
9
+ readonly files: (folder: string) => Promise<ReadonlySet<string>>;
10
+ /** The file at `path` written whole, made where it is not there. */
11
+ readonly write: (path: string, text: string) => Promise<void>;
12
+ };
13
+ /** The files of `platform`, each path walked down from the root of its storage. */
14
+ export declare const filesOf: (platform: ConfigPlatform) => Files;
15
+ /** A read a step of a generator asks for: the text of a file, or the names of a folder's files. */
16
+ export type Read = {
17
+ readonly text: string;
18
+ } | {
19
+ readonly files: string;
20
+ };
21
+ /** A read of the configuration, written once: a generator of the reads it asks for, and its result. */
22
+ export type Reads<T> = Generator<Read, T, unknown>;
23
+ /**
24
+ * What `reads` gives, each read done synchronously by `files`: what a read gives is the value of
25
+ * its step, and what it throws is thrown at its step.
26
+ */
27
+ export declare function readSync<T>(reads: Reads<T>, files: SyncFiles): T;
28
+ /** What `reads` gives, each read done by `files`, as {@link readSync} does them. */
29
+ export declare function readAsync<T>(reads: Reads<T>, files: Files): Promise<T>;
30
+ /** The text of the file at `path`, `undefined` when none is there, asked of the runner. */
31
+ export declare function textOf(path: string): Reads<string | undefined>;
32
+ /** The names of the files of `folder`, asked of the runner. */
33
+ export declare function namesOf(folder: string): Reads<ReadonlySet<string>>;
34
+ /**
35
+ * The package.json at `path`, as an object, or `undefined` when there is none. Its text is JSON of
36
+ * an object, or an {@link InvalidConfigFileError}.
37
+ */
38
+ export declare function manifestAt(path: string): Reads<Record<string, unknown> | undefined>;
39
+ /** The package.json at `path` of `text`, an object, or an {@link InvalidConfigFileError}. */
40
+ export declare function manifestOf(path: string, text: string): Record<string, unknown>;
41
+ /** What a file holds the configuration as: `code`, a module whose default export it is; `json`, a
42
+ * JSON file; or `package`, the key of package.json. */
43
+ export type ConfigKind = 'code' | 'json' | 'package';
44
+ /** The name of package.json, which holds the configuration by its key. */
45
+ export declare const PACKAGE_JSON = "package.json";
46
+ /**
47
+ * What `file` holds the configuration as, by its name: package.json, by its key; code, as Node
48
+ * imports it, `.mjs`, `.js`, `.ts`, `.cjs`, `.mts` or `.cts`; or JSON, `.json`. Any other is a
49
+ * `TypeError`: it names no file the configuration can be read from.
50
+ */
51
+ export declare function kindOf(file: string): ConfigKind;
package/dist/files.js ADDED
@@ -0,0 +1,120 @@
1
+ import { handleAt, isNotFound, readText, writeText } from '@wtf/platform-fs/files';
2
+ import { isFileSystemError } from '@wtf/platform-fs/errors';
3
+ import { InvalidConfigFileError } from "./errors.js";
4
+ /** Whether `value` is a JSON object: no list, and not `null`. */
5
+ export const isObject = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
6
+ /** Whether `error` says no entry of the kind asked for is there: none, or one of the other kind. */
7
+ const isMissing = (error) => isNotFound(error) ||
8
+ isFileSystemError(error, 'TypeMismatchError') ||
9
+ isFileSystemError(error?.cause, 'TypeMismatchError');
10
+ /** What `read` gives, or `fallback` when what it reads is not there. */
11
+ async function orMissing(read, fallback) {
12
+ try {
13
+ return await read();
14
+ }
15
+ catch (error) {
16
+ if (isMissing(error))
17
+ return fallback;
18
+ throw error;
19
+ }
20
+ }
21
+ /** The files of `platform`, each path walked down from the root of its storage. */
22
+ export const filesOf = (platform) => ({
23
+ text: (path) => orMissing(() => readText(platform, path), undefined),
24
+ files: (folder) => orMissing(async () => {
25
+ const names = new Set();
26
+ for await (const [name, entry] of (await handleAt(platform, folder, { kind: 'directory' })).entries())
27
+ if (entry.kind === 'file')
28
+ names.add(name);
29
+ return names;
30
+ }, new Set()),
31
+ write: async (path, text) => {
32
+ await writeText(platform, path, text);
33
+ }
34
+ });
35
+ /**
36
+ * What `reads` gives, each read done synchronously by `files`: what a read gives is the value of
37
+ * its step, and what it throws is thrown at its step.
38
+ */
39
+ export function readSync(reads, files) {
40
+ let step = reads.next();
41
+ while (!step.done) {
42
+ const read = step.value;
43
+ let value;
44
+ try {
45
+ value = 'text' in read ? files.text(read.text) : files.files(read.files);
46
+ }
47
+ catch (error) {
48
+ step = reads.throw(error);
49
+ continue;
50
+ }
51
+ step = reads.next(value);
52
+ }
53
+ return step.value;
54
+ }
55
+ /** What `reads` gives, each read done by `files`, as {@link readSync} does them. */
56
+ export async function readAsync(reads, files) {
57
+ let step = reads.next();
58
+ while (!step.done) {
59
+ const read = step.value;
60
+ let value;
61
+ try {
62
+ // oxlint-disable-next-line no-await-in-loop -- each read follows from the one before
63
+ value = 'text' in read ? await files.text(read.text) : await files.files(read.files);
64
+ }
65
+ catch (error) {
66
+ step = reads.throw(error);
67
+ continue;
68
+ }
69
+ step = reads.next(value);
70
+ }
71
+ return step.value;
72
+ }
73
+ /** The text of the file at `path`, `undefined` when none is there, asked of the runner. */
74
+ export function* textOf(path) {
75
+ return (yield { text: path });
76
+ }
77
+ /** The names of the files of `folder`, asked of the runner. */
78
+ export function* namesOf(folder) {
79
+ return (yield { files: folder });
80
+ }
81
+ /**
82
+ * The package.json at `path`, as an object, or `undefined` when there is none. Its text is JSON of
83
+ * an object, or an {@link InvalidConfigFileError}.
84
+ */
85
+ export function* manifestAt(path) {
86
+ const text = yield* textOf(path);
87
+ if (text === undefined)
88
+ return undefined;
89
+ return manifestOf(path, text);
90
+ }
91
+ /** The package.json at `path` of `text`, an object, or an {@link InvalidConfigFileError}. */
92
+ export function manifestOf(path, text) {
93
+ let manifest;
94
+ try {
95
+ manifest = JSON.parse(text);
96
+ }
97
+ catch (error) {
98
+ throw new InvalidConfigFileError(path, 'is no JSON.', { cause: error });
99
+ }
100
+ if (!isObject(manifest))
101
+ throw new InvalidConfigFileError(path, 'is no JSON object.');
102
+ return manifest;
103
+ }
104
+ /** The name of package.json, which holds the configuration by its key. */
105
+ export const PACKAGE_JSON = 'package.json';
106
+ /**
107
+ * What `file` holds the configuration as, by its name: package.json, by its key; code, as Node
108
+ * imports it, `.mjs`, `.js`, `.ts`, `.cjs`, `.mts` or `.cts`; or JSON, `.json`. Any other is a
109
+ * `TypeError`: it names no file the configuration can be read from.
110
+ */
111
+ export function kindOf(file) {
112
+ if (file === PACKAGE_JSON)
113
+ return 'package';
114
+ if (/\.[cm]?[jt]s$/.test(file))
115
+ return 'code';
116
+ if (file.endsWith('.json'))
117
+ return 'json';
118
+ throw new TypeError(`${file} is no file of the configuration: give a file of code (.mjs, .js, .ts) or of JSON (.json).`);
119
+ }
120
+ //# sourceMappingURL=files.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"files.js","sourceRoot":"","sources":["../src/files.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,QAAQ,EAAE,UAAU,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAA;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AAA;IAC7B,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,IAAI,sBAAsB,CAAC,IAAI,EAAE,aAAa,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,CAAA;IACzE,CAAC;IACD,IAAI,CAAC,QAAQ,CAAC,QAAQ,CAAC;QAAE,MAAM,IAAI,sBAAsB,CAAC,IAAI,EAAE,oBAAoB,CAAC,CAAA;IACrF,OAAO,QAAQ,CAAA;AACjB,CAAC;AAMD,0EAA0E;AAC1E,MAAM,CAAC,MAAM,YAAY,GAAG,cAAc,CAAA;AAE1C;;;;GAIG;AACH,MAAM,UAAU,MAAM,CAAC,IAAY;IACjC,IAAI,IAAI,KAAK,YAAY;QAAE,OAAO,SAAS,CAAA;IAC3C,IAAI,eAAe,CAAC,IAAI,CAAC,IAAI,CAAC;QAAE,OAAO,MAAM,CAAA;IAC7C,IAAI,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC;QAAE,OAAO,MAAM,CAAA;IACzC,MAAM,IAAI,SAAS,CACjB,GAAG,IAAI,4FAA4F,CACpG,CAAA;AACH,CAAC","sourcesContent":["// What the modules of the configuration read and write files by: the files of a platform, by\n// `@wtf/platform-fs/files`, asynchronously, or the files a caller reads synchronously; a read\n// written once, as a generator of the reads it asks for, and run either way; and what a file\n// holds the configuration as. Internal: no export map entry names it.\nimport type { PlatformError } from '@wtf/platform/errors'\nimport { handleAt, isNotFound, readText, writeText } from '@wtf/platform-fs/files'\nimport { isFileSystemError } from '@wtf/platform-fs/errors'\n\nimport { InvalidConfigFileError } from './errors.ts'\nimport type { ConfigPlatform, SyncFiles } from './index.ts'\n\n/** Whether `value` is a JSON object: no list, and not `null`. */\nexport const isObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value)\n\n/** What the configuration is read and written by, asynchronously. */\nexport type Files = {\n /** The text of the file at `path`, or `undefined` when no file is there. */\n readonly text: (path: string) => Promise<string | undefined>\n /** The names of the files in `folder`, none when it is no folder. */\n readonly files: (folder: string) => Promise<ReadonlySet<string>>\n /** The file at `path` written whole, made where it is not there. */\n readonly write: (path: string, text: string) => Promise<void>\n}\n\n/** Whether `error` says no entry of the kind asked for is there: none, or one of the other kind. */\nconst isMissing = (error: unknown): boolean =>\n isNotFound(error) ||\n isFileSystemError(error, 'TypeMismatchError') ||\n isFileSystemError((error as PlatformError | undefined)?.cause, 'TypeMismatchError')\n\n/** What `read` gives, or `fallback` when what it reads is not there. */\nasync function orMissing<T>(read: () => Promise<T>, fallback: T): Promise<T> {\n try {\n return await read()\n } catch (error) {\n if (isMissing(error)) return fallback\n throw error\n }\n}\n\n/** The files of `platform`, each path walked down from the root of its storage. */\nexport const filesOf = (platform: ConfigPlatform): Files => ({\n text: (path) => orMissing(() => readText(platform, path), undefined),\n files: (folder) =>\n orMissing(async () => {\n const names = new Set<string>()\n for await (const [name, entry] of (\n await handleAt(platform, folder, { kind: 'directory' })\n ).entries())\n if (entry.kind === 'file') names.add(name)\n return names\n }, new Set<string>()),\n write: async (path, text) => {\n await writeText(platform, path, text)\n }\n})\n\n/** A read a step of a generator asks for: the text of a file, or the names of a folder's files. */\nexport type Read = { readonly text: string } | { readonly files: string }\n\n/** A read of the configuration, written once: a generator of the reads it asks for, and its result. */\nexport type Reads<T> = Generator<Read, T, unknown>\n\n/**\n * What `reads` gives, each read done synchronously by `files`: what a read gives is the value of\n * its step, and what it throws is thrown at its step.\n */\nexport function readSync<T>(reads: Reads<T>, files: SyncFiles): T {\n let step = reads.next()\n while (!step.done) {\n const read = step.value\n let value: unknown\n try {\n value = 'text' in read ? files.text(read.text) : files.files(read.files)\n } catch (error) {\n step = reads.throw(error)\n continue\n }\n step = reads.next(value)\n }\n return step.value\n}\n\n/** What `reads` gives, each read done by `files`, as {@link readSync} does them. */\nexport async function readAsync<T>(reads: Reads<T>, files: Files): Promise<T> {\n let step = reads.next()\n while (!step.done) {\n const read = step.value\n let value: unknown\n try {\n // oxlint-disable-next-line no-await-in-loop -- each read follows from the one before\n value = 'text' in read ? await files.text(read.text) : await files.files(read.files)\n } catch (error) {\n step = reads.throw(error)\n continue\n }\n step = reads.next(value)\n }\n return step.value\n}\n\n/** The text of the file at `path`, `undefined` when none is there, asked of the runner. */\nexport function* textOf(path: string): Reads<string | undefined> {\n return (yield { text: path }) as string | undefined\n}\n\n/** The names of the files of `folder`, asked of the runner. */\nexport function* namesOf(folder: string): Reads<ReadonlySet<string>> {\n return (yield { files: folder }) as ReadonlySet<string>\n}\n\n/**\n * The package.json at `path`, as an object, or `undefined` when there is none. Its text is JSON of\n * an object, or an {@link InvalidConfigFileError}.\n */\nexport function* manifestAt(path: string): Reads<Record<string, unknown> | undefined> {\n const text = yield* textOf(path)\n if (text === undefined) return undefined\n return manifestOf(path, text)\n}\n\n/** The package.json at `path` of `text`, an object, or an {@link InvalidConfigFileError}. */\nexport function manifestOf(path: string, text: string): Record<string, unknown> {\n let manifest: unknown\n try {\n manifest = JSON.parse(text)\n } catch (error) {\n throw new InvalidConfigFileError(path, 'is no JSON.', { cause: error })\n }\n if (!isObject(manifest)) throw new InvalidConfigFileError(path, 'is no JSON object.')\n return manifest\n}\n\n/** What a file holds the configuration as: `code`, a module whose default export it is; `json`, a\n * JSON file; or `package`, the key of package.json. */\nexport type ConfigKind = 'code' | 'json' | 'package'\n\n/** The name of package.json, which holds the configuration by its key. */\nexport const PACKAGE_JSON = 'package.json'\n\n/**\n * What `file` holds the configuration as, by its name: package.json, by its key; code, as Node\n * imports it, `.mjs`, `.js`, `.ts`, `.cjs`, `.mts` or `.cts`; or JSON, `.json`. Any other is a\n * `TypeError`: it names no file the configuration can be read from.\n */\nexport function kindOf(file: string): ConfigKind {\n if (file === PACKAGE_JSON) return 'package'\n if (/\\.[cm]?[jt]s$/.test(file)) return 'code'\n if (file.endsWith('.json')) return 'json'\n throw new TypeError(\n `${file} is no file of the configuration: give a file of code (.mjs, .js, .ts) or of JSON (.json).`\n )\n}\n"]}
@@ -0,0 +1,196 @@
1
+ /**
2
+ * The types of a project's configuration under a namespace, `wtf` by default: the object
3
+ * ({@link NamespaceConfig}), made of a section for each tool ({@link ConfigSection}), or of the
4
+ * sections the schemas of the tools type ({@link SectionsOf}); the names it is looked for by
5
+ * ({@link ConfigNames}); the file it is in ({@link ConfigSource}); where it is
6
+ * ({@link LocatedConfig}); what a tool reads ({@link ResolvedConfig}); the defaults a tool's
7
+ * package gives ({@link ConfigDefaults}); a path in it ({@link ConfigPath}); what checks a section
8
+ * ({@link SectionSchema}) and what it finds wrong ({@link ConfigIssue}); what a write did
9
+ * ({@link ConfigWrite}); and what it is read by ({@link ConfigPlatform}, {@link ConfigSyncPlatform}).
10
+ * Types only, with no code.
11
+ *
12
+ * @packageDocumentation
13
+ * @module index
14
+ */
15
+ import type { StandardJSONSchemaV1, StandardSchemaV1, StandardTypedV1 } from '@standard-schema/spec';
16
+ import type { FilesPlatform } from '@wtf/platform-fs/files';
17
+ import type { Path } from '@wtf/platform/path';
18
+ /**
19
+ * The section of one tool, by its key `K` and its value `V`, as `ConfigSection<'vite', ViteOptions>`.
20
+ * A section is optional: a project configures the tools it chooses.
21
+ */
22
+ export type ConfigSection<K extends string, V> = {
23
+ readonly [P in K]?: V;
24
+ };
25
+ /**
26
+ * The sections of the schemas `S`, each by its name: the input type of each schema, as
27
+ * `SectionsOf<{ vite: typeof viteSchema }>` is `{ vite?: ViteOptions }`. A code config is typed by
28
+ * it with `defineConfig` of ./define.
29
+ */
30
+ export type SectionsOf<S extends Readonly<Record<string, StandardTypedV1>>> = {
31
+ readonly [K in keyof S]?: StandardTypedV1.InferInput<S[K]>;
32
+ };
33
+ /**
34
+ * The configuration of a project under a namespace: the sections `S`, each checked by its type;
35
+ * the `$schema` a JSON file names its schema by; and any other section, of a tool not named, as it
36
+ * is. A tool reads its own section, and no other.
37
+ *
38
+ * ```ts
39
+ * const config: NamespaceConfig<{ vite?: { compress?: false } }> = { vite: { compress: false } }
40
+ * ```
41
+ */
42
+ export type NamespaceConfig<S extends object = Record<never, never>> = S & {
43
+ /** The JSON Schema of a JSON file of the configuration, as an editor reads it. */
44
+ readonly $schema?: string;
45
+ readonly [section: string]: unknown;
46
+ };
47
+ /**
48
+ * The names the configuration of a namespace is looked for by, each a tool's to give: the files at
49
+ * the root of the project, the key of its package.json, and the prefix of the environment's
50
+ * variables over it. Of the namespace `wtf`, by default, `wtf.config.mjs`, `wtf.config.js`,
51
+ * `wtf.config.ts` and `wtf.config.json`, the `wtf` key, and the variables `WTF_*`.
52
+ */
53
+ export type ConfigNames = {
54
+ /**
55
+ * The files it can be in, in the order the first found is used, each of code (`.mjs`, `.js`,
56
+ * `.ts`, `.cjs`, `.mts` or `.cts`) or of JSON (`.json`). The key of package.json comes last.
57
+ */
58
+ readonly files?: readonly string[];
59
+ /** The key of package.json that holds it when no file does: the namespace by default. */
60
+ readonly key?: string;
61
+ /**
62
+ * The name the environment's variables over it start with: the key by default, so `wtf` is
63
+ * `WTF_`, and `WTF_VITE_COMPRESS` sets `wtf.vite.compress`.
64
+ */
65
+ readonly env?: string;
66
+ };
67
+ /** A file of the configuration found at the root of a project: one of its files, or package.json. */
68
+ export type ConfigSource = {
69
+ /** Its name, as the names give it, or `package.json`. */
70
+ readonly file: string;
71
+ /** Its absolute path. */
72
+ readonly path: string;
73
+ };
74
+ /**
75
+ * Where a project's configuration is: the root of the project, the key of package.json, and each
76
+ * file of it found there, in the order of its files, then package.json. The first is used; the
77
+ * others are ignored.
78
+ */
79
+ export type LocatedConfig = {
80
+ readonly root: string;
81
+ /** The key of package.json, which a path of the configuration starts from: `wtf.vite.compress`. */
82
+ readonly key: string;
83
+ readonly sources: readonly ConfigSource[];
84
+ };
85
+ /**
86
+ * The configuration a tool's package gives under the project's, as its own defaults: each section
87
+ * the project gives is merged over it, value by value, as `sectionOf` of ./section reads it.
88
+ */
89
+ export type ConfigDefaults = {
90
+ /** The object, of the sections of the namespace. */
91
+ readonly config: NamespaceConfig;
92
+ /** The file it is in, by its absolute path, which an error of a section of it names. */
93
+ readonly path: string;
94
+ };
95
+ /**
96
+ * The environment a tool reads the configuration with: the prefix of the variables over it, as
97
+ * `WTF_`; each of those that is set and not empty, by its name; and the whole environment, in
98
+ * `values`, which the placeholders `${env:NAME}` of a section are taken from. Only `sectionOf` of
99
+ * ./section reads `values`: nothing shows or writes it.
100
+ */
101
+ export type ConfigEnvironment = {
102
+ readonly prefix: string;
103
+ readonly variables: Readonly<Record<string, string>>;
104
+ readonly values: Readonly<Record<string, string | undefined>>;
105
+ };
106
+ /** A project's configuration, as a tool reads it. */
107
+ export type ResolvedConfig = {
108
+ /** Its namespace. */
109
+ readonly namespace: string;
110
+ /** The root of the project, where it was looked for. */
111
+ readonly root: string;
112
+ /** The key of package.json it was looked for in, which a path of it starts from. */
113
+ readonly key: string;
114
+ /** The object, `{}` when no file holds one. */
115
+ readonly config: NamespaceConfig;
116
+ /** The file it came from, or `undefined` when no file holds one. */
117
+ readonly source: ConfigSource | undefined;
118
+ /** The other files found, which are ignored, as only the first is used. */
119
+ readonly ignored: readonly ConfigSource[];
120
+ /** The configuration of the tool's package under the project's, when the tool gives one. */
121
+ readonly defaults?: ConfigDefaults | undefined;
122
+ /**
123
+ * The environment the tool gave, which a section is read with: its variables over the project's
124
+ * configuration, and the values its placeholders are taken from. None when no environment was
125
+ * given: then a placeholder names a variable that is not set.
126
+ */
127
+ readonly environment?: ConfigEnvironment | undefined;
128
+ };
129
+ /** A path in the configuration, by its keys from the top: `['vite', 'compress']`. A key of digits
130
+ * is an index of a list. */
131
+ export type ConfigPath = readonly string[];
132
+ /** What is wrong with a value of a section: where it is, by its path in the section, and why. */
133
+ export type ConfigIssue = {
134
+ readonly path: ConfigPath;
135
+ readonly message: string;
136
+ };
137
+ /** A JSON Schema, as the object of its keywords, or `true` or `false`. */
138
+ export type JsonSchema = {
139
+ readonly [keyword: string]: unknown;
140
+ } | boolean;
141
+ /** A function that checks a section: what is wrong with it, none when it is valid. */
142
+ export type ValidateSection = (value: unknown) => readonly ConfigIssue[] | Promise<readonly ConfigIssue[]>;
143
+ /**
144
+ * What a tool checks its section by: a Standard Schema, as a preset's `./schema` exports one, or
145
+ * zod's, whose output is what the section reads as; a JSON Schema of draft 2020-12, or a Standard
146
+ * JSON Schema, which ajv checks; or a function of its own.
147
+ */
148
+ export type SectionSchema<T = unknown> = StandardSchemaV1<unknown, T> | StandardJSONSchemaV1<unknown, T> | JsonSchema | ValidateSection;
149
+ /**
150
+ * What a write did: where, at which path, the value there before and after it, and whether it
151
+ * changed the file, or made it.
152
+ */
153
+ export type ConfigWrite = {
154
+ readonly root: string;
155
+ /** The key of package.json, which a path of the configuration starts from. */
156
+ readonly key: string;
157
+ /** The file written, or `undefined` when nothing was there to unset. */
158
+ readonly source: ConfigSource | undefined;
159
+ /** The other files of the configuration found, which a reader ignores. */
160
+ readonly ignored: readonly ConfigSource[];
161
+ readonly path: ConfigPath;
162
+ /** The value at the path before the write, `undefined` when there was none. */
163
+ readonly previous: unknown;
164
+ /** The value at the path after the write, `undefined` when it was unset. */
165
+ readonly value: unknown;
166
+ /** Whether the file was written: false when the value was already so. */
167
+ readonly changed: boolean;
168
+ /** Whether the file, or the key of package.json, was made by the write. */
169
+ readonly created: boolean;
170
+ };
171
+ /** What imports a file of code, as `wtf.config.ts`, by its absolute path: its module, whose
172
+ * `default` is the configuration. */
173
+ export type ImportModule = (path: string) => Promise<unknown>;
174
+ /**
175
+ * What the configuration is read and written by, asynchronously: the platform's storage, whose
176
+ * `getDirectory()` is the root of its file system, its paths, and its working folder, as
177
+ * `@wtf/platform-fs/files` reads a platform's files. A `Platform` of `@wtf/platform` is one, and
178
+ * `nodeConfigPlatform()` of ./node gives Node's.
179
+ */
180
+ export type ConfigPlatform = FilesPlatform;
181
+ /** What reads a project's files synchronously, by their absolute paths. */
182
+ export type SyncFiles = {
183
+ /** The text of the file at `path`, or `undefined` when no file is there. */
184
+ readonly text: (path: string) => string | undefined;
185
+ /** The names of the files in `folder`, none when it is no folder. */
186
+ readonly files: (folder: string) => ReadonlySet<string>;
187
+ };
188
+ /**
189
+ * What the configuration is read by synchronously: the platform's paths, and its files, read
190
+ * synchronously, as no handle of the File System Standard is. `nodeSyncPlatform()` of ./node gives
191
+ * Node's.
192
+ */
193
+ export type ConfigSyncPlatform = {
194
+ readonly path: Pick<Path, 'resolve' | 'join' | 'dirname'>;
195
+ readonly files: SyncFiles;
196
+ };
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"","sourcesContent":["/**\n * The types of a project's configuration under a namespace, `wtf` by default: the object\n * ({@link NamespaceConfig}), made of a section for each tool ({@link ConfigSection}), or of the\n * sections the schemas of the tools type ({@link SectionsOf}); the names it is looked for by\n * ({@link ConfigNames}); the file it is in ({@link ConfigSource}); where it is\n * ({@link LocatedConfig}); what a tool reads ({@link ResolvedConfig}); the defaults a tool's\n * package gives ({@link ConfigDefaults}); a path in it ({@link ConfigPath}); what checks a section\n * ({@link SectionSchema}) and what it finds wrong ({@link ConfigIssue}); what a write did\n * ({@link ConfigWrite}); and what it is read by ({@link ConfigPlatform}, {@link ConfigSyncPlatform}).\n * Types only, with no code.\n *\n * @packageDocumentation\n * @module index\n */\nimport type { StandardJSONSchemaV1, StandardSchemaV1, StandardTypedV1 } from '@standard-schema/spec'\nimport type { FilesPlatform } from '@wtf/platform-fs/files'\nimport type { Path } from '@wtf/platform/path'\n\n/**\n * The section of one tool, by its key `K` and its value `V`, as `ConfigSection<'vite', ViteOptions>`.\n * A section is optional: a project configures the tools it chooses.\n */\nexport type ConfigSection<K extends string, V> = { readonly [P in K]?: V }\n\n/**\n * The sections of the schemas `S`, each by its name: the input type of each schema, as\n * `SectionsOf<{ vite: typeof viteSchema }>` is `{ vite?: ViteOptions }`. A code config is typed by\n * it with `defineConfig` of ./define.\n */\nexport type SectionsOf<S extends Readonly<Record<string, StandardTypedV1>>> = {\n readonly [K in keyof S]?: StandardTypedV1.InferInput<S[K]>\n}\n\n/**\n * The configuration of a project under a namespace: the sections `S`, each checked by its type;\n * the `$schema` a JSON file names its schema by; and any other section, of a tool not named, as it\n * is. A tool reads its own section, and no other.\n *\n * ```ts\n * const config: NamespaceConfig<{ vite?: { compress?: false } }> = { vite: { compress: false } }\n * ```\n */\nexport type NamespaceConfig<S extends object = Record<never, never>> = S & {\n /** The JSON Schema of a JSON file of the configuration, as an editor reads it. */\n readonly $schema?: string\n readonly [section: string]: unknown\n}\n\n/**\n * The names the configuration of a namespace is looked for by, each a tool's to give: the files at\n * the root of the project, the key of its package.json, and the prefix of the environment's\n * variables over it. Of the namespace `wtf`, by default, `wtf.config.mjs`, `wtf.config.js`,\n * `wtf.config.ts` and `wtf.config.json`, the `wtf` key, and the variables `WTF_*`.\n */\nexport type ConfigNames = {\n /**\n * The files it can be in, in the order the first found is used, each of code (`.mjs`, `.js`,\n * `.ts`, `.cjs`, `.mts` or `.cts`) or of JSON (`.json`). The key of package.json comes last.\n */\n readonly files?: readonly string[]\n /** The key of package.json that holds it when no file does: the namespace by default. */\n readonly key?: string\n /**\n * The name the environment's variables over it start with: the key by default, so `wtf` is\n * `WTF_`, and `WTF_VITE_COMPRESS` sets `wtf.vite.compress`.\n */\n readonly env?: string\n}\n\n/** A file of the configuration found at the root of a project: one of its files, or package.json. */\nexport type ConfigSource = {\n /** Its name, as the names give it, or `package.json`. */\n readonly file: string\n /** Its absolute path. */\n readonly path: string\n}\n\n/**\n * Where a project's configuration is: the root of the project, the key of package.json, and each\n * file of it found there, in the order of its files, then package.json. The first is used; the\n * others are ignored.\n */\nexport type LocatedConfig = {\n readonly root: string\n /** The key of package.json, which a path of the configuration starts from: `wtf.vite.compress`. */\n readonly key: string\n readonly sources: readonly ConfigSource[]\n}\n\n/**\n * The configuration a tool's package gives under the project's, as its own defaults: each section\n * the project gives is merged over it, value by value, as `sectionOf` of ./section reads it.\n */\nexport type ConfigDefaults = {\n /** The object, of the sections of the namespace. */\n readonly config: NamespaceConfig\n /** The file it is in, by its absolute path, which an error of a section of it names. */\n readonly path: string\n}\n\n/**\n * The environment a tool reads the configuration with: the prefix of the variables over it, as\n * `WTF_`; each of those that is set and not empty, by its name; and the whole environment, in\n * `values`, which the placeholders `${env:NAME}` of a section are taken from. Only `sectionOf` of\n * ./section reads `values`: nothing shows or writes it.\n */\nexport type ConfigEnvironment = {\n readonly prefix: string\n readonly variables: Readonly<Record<string, string>>\n readonly values: Readonly<Record<string, string | undefined>>\n}\n\n/** A project's configuration, as a tool reads it. */\nexport type ResolvedConfig = {\n /** Its namespace. */\n readonly namespace: string\n /** The root of the project, where it was looked for. */\n readonly root: string\n /** The key of package.json it was looked for in, which a path of it starts from. */\n readonly key: string\n /** The object, `{}` when no file holds one. */\n readonly config: NamespaceConfig\n /** The file it came from, or `undefined` when no file holds one. */\n readonly source: ConfigSource | undefined\n /** The other files found, which are ignored, as only the first is used. */\n readonly ignored: readonly ConfigSource[]\n /** The configuration of the tool's package under the project's, when the tool gives one. */\n readonly defaults?: ConfigDefaults | undefined\n /**\n * The environment the tool gave, which a section is read with: its variables over the project's\n * configuration, and the values its placeholders are taken from. None when no environment was\n * given: then a placeholder names a variable that is not set.\n */\n readonly environment?: ConfigEnvironment | undefined\n}\n\n/** A path in the configuration, by its keys from the top: `['vite', 'compress']`. A key of digits\n * is an index of a list. */\nexport type ConfigPath = readonly string[]\n\n/** What is wrong with a value of a section: where it is, by its path in the section, and why. */\nexport type ConfigIssue = {\n readonly path: ConfigPath\n readonly message: string\n}\n\n/** A JSON Schema, as the object of its keywords, or `true` or `false`. */\nexport type JsonSchema = { readonly [keyword: string]: unknown } | boolean\n\n/** A function that checks a section: what is wrong with it, none when it is valid. */\nexport type ValidateSection = (\n value: unknown\n) => readonly ConfigIssue[] | Promise<readonly ConfigIssue[]>\n\n/**\n * What a tool checks its section by: a Standard Schema, as a preset's `./schema` exports one, or\n * zod's, whose output is what the section reads as; a JSON Schema of draft 2020-12, or a Standard\n * JSON Schema, which ajv checks; or a function of its own.\n */\nexport type SectionSchema<T = unknown> =\n | StandardSchemaV1<unknown, T>\n | StandardJSONSchemaV1<unknown, T>\n | JsonSchema\n | ValidateSection\n\n/**\n * What a write did: where, at which path, the value there before and after it, and whether it\n * changed the file, or made it.\n */\nexport type ConfigWrite = {\n readonly root: string\n /** The key of package.json, which a path of the configuration starts from. */\n readonly key: string\n /** The file written, or `undefined` when nothing was there to unset. */\n readonly source: ConfigSource | undefined\n /** The other files of the configuration found, which a reader ignores. */\n readonly ignored: readonly ConfigSource[]\n readonly path: ConfigPath\n /** The value at the path before the write, `undefined` when there was none. */\n readonly previous: unknown\n /** The value at the path after the write, `undefined` when it was unset. */\n readonly value: unknown\n /** Whether the file was written: false when the value was already so. */\n readonly changed: boolean\n /** Whether the file, or the key of package.json, was made by the write. */\n readonly created: boolean\n}\n\n/** What imports a file of code, as `wtf.config.ts`, by its absolute path: its module, whose\n * `default` is the configuration. */\nexport type ImportModule = (path: string) => Promise<unknown>\n\n/**\n * What the configuration is read and written by, asynchronously: the platform's storage, whose\n * `getDirectory()` is the root of its file system, its paths, and its working folder, as\n * `@wtf/platform-fs/files` reads a platform's files. A `Platform` of `@wtf/platform` is one, and\n * `nodeConfigPlatform()` of ./node gives Node's.\n */\nexport type ConfigPlatform = FilesPlatform\n\n/** What reads a project's files synchronously, by their absolute paths. */\nexport type SyncFiles = {\n /** The text of the file at `path`, or `undefined` when no file is there. */\n readonly text: (path: string) => string | undefined\n /** The names of the files in `folder`, none when it is no folder. */\n readonly files: (folder: string) => ReadonlySet<string>\n}\n\n/**\n * What the configuration is read by synchronously: the platform's paths, and its files, read\n * synchronously, as no handle of the File System Standard is. `nodeSyncPlatform()` of ./node gives\n * Node's.\n */\nexport type ConfigSyncPlatform = {\n readonly path: Pick<Path, 'resolve' | 'join' | 'dirname'>\n readonly files: SyncFiles\n}\n"]}