@wtf/project-config 1.1.0 → 2.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.
- package/README.md +44 -27
- package/dist/env.js +51 -9
- package/dist/env.js.map +1 -1
- package/dist/errors.d.ts +26 -8
- package/dist/errors.js +19 -4
- package/dist/errors.js.map +1 -1
- package/dist/index.d.ts +4 -4
- package/dist/index.js.map +1 -1
- package/dist/load.d.ts +56 -30
- package/dist/load.js +25 -42
- package/dist/load.js.map +1 -1
- package/dist/locate.d.ts +3 -2
- package/dist/locate.js +5 -2
- package/dist/locate.js.map +1 -1
- package/dist/named.d.ts +40 -13
- package/dist/named.js +98 -32
- package/dist/named.js.map +1 -1
- package/dist/node.d.ts +11 -24
- package/dist/node.js +56 -79
- package/dist/node.js.map +1 -1
- package/dist/section.d.ts +5 -5
- package/dist/section.js +5 -5
- package/dist/section.js.map +1 -1
- package/dist/write.js +5 -4
- package/dist/write.js.map +1 -1
- package/package.json +4 -4
package/dist/node.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"node.js","sourceRoot":"","sources":["../src/node.ts"],"names":[],"mappings":";;;;;;;;AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,OAAO,EAAE,WAAW,EAAE,YAAY,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAA;AAC7D,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAA;AAC3C,OAAO,EAAE,UAAU,EAAE,IAAI,EAAE,MAAM,WAAW,CAAA;AAC5C,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAA;
|
|
1
|
+
{"version":3,"file":"node.js","sourceRoot":"","sources":["../src/node.ts"],"names":[],"mappings":";;;;;;;;AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,OAAO,EAAE,WAAW,EAAE,YAAY,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAA;AAC7D,OAAO,EAAE,aAAa,EAAE,MA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AAI,EACJ,GAAG,EAC6B,EAAoB,EAAE,CAAC,CAAC;IACxD,IAAI;IACJ,IAAI;IACJ,GAAG;IACH,KAAK,EAAE,aAAa;CACrB,CAAC,CAAA;AAEF;;;;GAIG;AACH,SAAS,MAAM,CAAC,MAAc,EAAE,IAAY,EAAE,MAAgC;IAC5E,IAAI,UAAU,CAAC,MAAM,CAAC;QAAE,OAAO,MAAM,CAAA;IACrC,IAAI,YAAY,CAAC,IAAI,CAAC,MAAM,CAAC;QAAE,OAAO,IAAI,CAAC,IAAI,EAAE,MAAM,CAAC,CAAA;IACxD,IAAI,CAAC;QACH,OAAO,aAAa,CAAC,IAAI,CAAC,IAAI,EAAE,cAAc,CAAC,CAAC,CAAC,OAAO,CAAC,MAAM,CAAC,CAAA;IAClE,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,MAAM,KAAK,SAAS;YAAE,MAAM,KAAK,CAAA;QACrC,IAAI,CAAC;YACH,OAAO,aAAa,CAAC,MAAM,CAAC,CAAC,OAAO,CAAC,MAAM,CAAC,CAAA;QAC9C,CAAC;QAAC,MAAM,CAAC;YACP,MAAM,KAAK,CAAA;QACb,CAAC;IACH,CAAC;AACH,CAAC;AAED;;;;;;;;;;;;GAYG;AACH,MAAM,CAAC,MAAM,cAAc,GACzB,CAAC,IAAY,EAAE,MAAqB,EAAc,EAAE,CACpD,KAAK,EAAE,MAAM,EAAE,EAAE,CACf,MAAM,kCAAC,aAAa,CAAC,MAAM,CAAC,MAAM,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC,CAAC,IAAI,EAAC,CAAA","sourcesContent":["/**\n * What of the configuration is Node's by nature: {@link nodeSyncPlatform}, a platform's files read\n * synchronously, by `node:fs`, as no handle of the File System Standard reads them, for\n * `loadConfigSync` of ./load; and {@link nodeLoadModule}, what loads a module a reference of\n * ./named names, by Node's resolution and `import()`. Neither reads anything of the process: the\n * entry point gives the platform, and the root of the project:\n *\n * ```ts\n * import { nodeStorage } from '@wtf/platform-fs-node/storage'\n * import { nodePlatform } from '@wtf/platform-node/platform'\n *\n * import { loadConfigSync } from '@wtf/project-config/load'\n * import { nodeLoadModule, nodeSyncPlatform } from '@wtf/project-config/node'\n *\n * const platform = nodePlatform({ fetch, storage: nodeStorage() })\n * const resolved = loadConfigSync({ platform: nodeSyncPlatform(platform) })\n * const load = nodeLoadModule(resolved.root, import.meta.url)\n * ```\n *\n * @packageDocumentation\n */\nimport { readdirSync, readFileSync, statSync } from 'node:fs'\nimport { createRequire } from 'node:module'\nimport { isAbsolute, join } from 'node:path'\nimport { pathToFileURL } from 'node:url'\n\nimport type { SyncFiles } from './index.ts'\nimport type { LoadSyncPlatform } from './load.ts'\nimport type { LoadModule } from './named.ts'\n\n/** Whether `error` is Node's of a file or a folder not there, or of the other kind. */\nconst isMissing = (error: unknown): boolean =>\n ['ENOENT', 'ENOTDIR', 'EISDIR'].includes((error as NodeJS.ErrnoException | undefined)?.code ?? '')\n\n/** Node's files, read synchronously by `node:fs`, by their absolute paths. */\nconst nodeSyncFiles: SyncFiles = {\n text: (path) => {\n try {\n return readFileSync(path, 'utf8')\n } catch (error) {\n if (isMissing(error)) return undefined\n throw error\n }\n },\n files: (folder) => {\n try {\n // A link is what it links to, as a handle of the disk reads it.\n return new Set(\n readdirSync(folder).filter((name) => {\n try {\n return statSync(join(folder, name)).isFile()\n } catch {\n return false\n }\n })\n )\n } catch (error) {\n if (isMissing(error)) return new Set<string>()\n throw error\n }\n }\n}\n\n/**\n * The platform the configuration is read by synchronously, of `platform`: its paths, its working\n * folder and its environment, as they are, and the disk, read synchronously by `node:fs`, as its\n * files. `loadConfigSync` of ./load reads by it.\n */\nexport const nodeSyncPlatform = ({\n path,\n dirs,\n env\n}: Omit<LoadSyncPlatform, 'files'>): LoadSyncPlatform => ({\n path,\n dirs,\n env,\n files: nodeSyncFiles\n})\n\n/**\n * The file of the module `module`: of an absolute path, itself; of a path from the root, `./` or\n * `../`, of `root`; of a package, the one `root` installs, as a devDependency of the project, else\n * the one installed beside `beside`, as of a global install of a tool and its plugins.\n */\nfunction fileOf(module: string, root: string, beside: string | URL | undefined): string {\n if (isAbsolute(module)) return module\n if (/^\\.{1,2}\\//.test(module)) return join(root, module)\n try {\n return createRequire(join(root, 'package.json')).resolve(module)\n } catch (error) {\n if (beside === undefined) throw error\n try {\n return createRequire(beside).resolve(module)\n } catch {\n throw error\n }\n }\n}\n\n/**\n * Node's loader of the modules a reference of ./named names, by `import()` of its file: a path, of\n * `root`, the root of the project, as the entry point gives it; a package, the one `root`\n * installs, else the one installed beside `beside`, as a tool gives its own `import.meta.url`, so a\n * package a global install puts beside the tool is found too. What fails to resolve or load fails\n * of the error of `root`'s resolve, or of the import.\n *\n * ```ts\n * import { nodeLoadModule } from '@wtf/project-config/node'\n *\n * const load = nodeLoadModule(resolved.root, import.meta.url)\n * ```\n */\nexport const nodeLoadModule =\n (root: string, beside?: string | URL): LoadModule =>\n async (module) =>\n import(pathToFileURL(fileOf(module, root, beside)).href)\n"]}
|
package/dist/section.d.ts
CHANGED
|
@@ -20,11 +20,11 @@ export declare function issuesOfSync<T>(value: unknown, schema: SectionSchema<T>
|
|
|
20
20
|
/**
|
|
21
21
|
* The section `name` of the configuration, as its tool reads it: the project's, merged over the
|
|
22
22
|
* section of the `defaults` of the tool's package when it gives some ({@link mergeSection}), with
|
|
23
|
-
* the environment
|
|
24
|
-
* section or of its schema, as `WTF_VITE_COMPRESS` (`withEnvironment` of
|
|
25
|
-
* none has one, which the tool takes as its own defaults. Each string in it is then read for
|
|
26
|
-
* placeholders `${env:NAME}`, taken from
|
|
27
|
-
*
|
|
23
|
+
* the variables of the environment of the platform the tool gave `loadConfig` over both, each that
|
|
24
|
+
* names a key of the section or of its schema, as `WTF_VITE_COMPRESS` (`withEnvironment` of
|
|
25
|
+
* ./env); `undefined` when none has one, which the tool takes as its own defaults. Each string in it is then read for
|
|
26
|
+
* placeholders `${env:NAME}`, taken from that whole environment (`expandPlaceholders` of
|
|
27
|
+
* ./placeholder); a variable not set, or of a configuration read of no environment, is an
|
|
28
28
|
* `EnvPlaceholderUnsetError`. Only this, and {@link sectionOfSync}, expand them, so what shows or
|
|
29
29
|
* writes the configuration never holds a secret it points at. With a `schema` it is checked, and
|
|
30
30
|
* what is wrong is an {@link InvalidSectionError}, which names where the value came from and the
|
package/dist/section.js
CHANGED
|
@@ -129,11 +129,11 @@ function invalidOf(resolved, name, { own, environment }, issues) {
|
|
|
129
129
|
/**
|
|
130
130
|
* The section `name` of the configuration, as its tool reads it: the project's, merged over the
|
|
131
131
|
* section of the `defaults` of the tool's package when it gives some ({@link mergeSection}), with
|
|
132
|
-
* the environment
|
|
133
|
-
* section or of its schema, as `WTF_VITE_COMPRESS` (`withEnvironment` of
|
|
134
|
-
* none has one, which the tool takes as its own defaults. Each string in it is then read for
|
|
135
|
-
* placeholders `${env:NAME}`, taken from
|
|
136
|
-
*
|
|
132
|
+
* the variables of the environment of the platform the tool gave `loadConfig` over both, each that
|
|
133
|
+
* names a key of the section or of its schema, as `WTF_VITE_COMPRESS` (`withEnvironment` of
|
|
134
|
+
* ./env); `undefined` when none has one, which the tool takes as its own defaults. Each string in it is then read for
|
|
135
|
+
* placeholders `${env:NAME}`, taken from that whole environment (`expandPlaceholders` of
|
|
136
|
+
* ./placeholder); a variable not set, or of a configuration read of no environment, is an
|
|
137
137
|
* `EnvPlaceholderUnsetError`. Only this, and {@link sectionOfSync}, expand them, so what shows or
|
|
138
138
|
* writes the configuration never holds a secret it points at. With a `schema` it is checked, and
|
|
139
139
|
* what is wrong is an {@link InvalidSectionError}, which names where the value came from and the
|
package/dist/section.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"section.js","sourceRoot":"","sources":["../src/section.ts"],"names":[],"mappings":"AAuBA,OAAO,EAAE,OAAO,EAA2C,MAAM,kBAAkB,CAAA;AAEnF,OAAO,EAAE,SAAS,EAAE,YAAY,EAAE,eAAe,EAAwB,MAAM,UAAU,CAAA;AACzF,OAA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jD,IAAI,CAAC,OAAO,CAAC,KAAK;QAAE,OAAO,SAAS,CAAA;IACpC,IAAI,MAAM,KAAK,SAAS;QAAE,OAAO,OAAO,CAAC,OAAY,CAAA;IACrD,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,GAAG,MAAM,QAAQ,CAAC,OAAO,CAAC,OAAO,EAAE,MAAM,CAAC,CAAA;IACjE,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,KAAK,CAAA;IACrC,MAAM,SAAS,CAAC,QAAQ,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,CAAC,CAAA;AAClD,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,aAAa,CAC3B,QAAwB,EACxB,IAAY,EACZ,MAAyB;IAEzB,MAAM,OAAO,GAAG,SAAS,CAAC,QAAQ,EAAE,IAAI,EAAE,MAAM,CAAC,CAAA;IACjD,IAAI,CAAC,OAAO,CAAC,KAAK;QAAE,OAAO,SAAS,CAAA;IACpC,IAAI,MAAM,KAAK,SAAS;QAAE,OAAO,OAAO,CAAC,OAAY,CAAA;IACrD,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,GAAG,YAAY,CAAC,OAAO,CAAC,OAAO,EAAE,MAAM,EAAE,IAAI,CAAC,CAAA;IACrE,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,KAAK,CAAA;IACrC,MAAM,SAAS,CAAC,QAAQ,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,CAAC,CAAA;AAClD,CAAC","sourcesContent":["/**\n * A tool's section of the configuration: {@link sectionOf}, the section of a name, the project's\n * merged over the defaults of the tool's package ({@link mergeSection}), with the environment's\n * variables the tool gives over both, each placeholder `${env:NAME}` in it replaced by the variable\n * it names, and checked by the schema the tool gives; {@link sectionOfSync}, the same, checked\n * synchronously; and {@link issuesOf} and {@link issuesOfSync}, what a schema finds wrong with a\n * value. A schema is a Standard Schema, as each preset's `./schema` exports one, a JSON Schema or a\n * Standard JSON Schema, which ajv checks, or a function. What is wrong is an\n * `InvalidSectionError` of ./errors, which names the file and the path of each value.\n *\n * ```ts\n * import { loadConfig } from '@wtf/project-config/node'\n * import { sectionOf } from '@wtf/project-config/section'\n * import { baseConfig } from '@wtf/project-vite/config'\n * import { viteSchema } from '@wtf/project-vite/schema'\n *\n * const config = await loadConfig(process.cwd())\n * export default baseConfig({ ...(await sectionOf(config, 'vite', viteSchema)) })\n * ```\n *\n * @packageDocumentation\n */\nimport type { StandardSchemaV1 } from '@standard-schema/spec'\nimport { Ajv2020, type ErrorObject, type ValidateFunction } from 'ajv/dist/2020.js'\n\nimport { envNameOf, jsonSchemaOf, withEnvironment, type WithEnvironment } from './env.ts'\nimport { InvalidSectionError, SyncSchemaError } from './errors.ts'\nimport type {\n ConfigIssue,\n ConfigPath,\n JsonSchema,\n ResolvedConfig,\n SectionSchema,\n ValidateSection\n} from './index.ts'\nimport { mergeSection } from './merge.ts'\nimport { expandPlaceholders } from './placeholder.ts'\n\nexport { mergeSection } from './merge.ts'\n\n/** What a schema found of a value: what is wrong with it, none when it is valid, and the value as\n * the schema reads it. */\nexport type Checked<T> = { readonly issues: readonly ConfigIssue[]; readonly value: T }\n\nconst isNode = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null\n\n/** Whether `schema` is a Standard Schema that validates: its `~standard` has `validate`. */\nconst validatorOf = (schema: unknown): StandardSchemaV1['~standard'] | undefined => {\n if (!isNode(schema) || !('~standard' in schema)) return undefined\n const standard = schema['~standard']\n return isNode(standard) && typeof standard['validate'] === 'function'\n ? (standard as unknown as StandardSchemaV1['~standard'])\n : undefined\n}\n\n/**\n * The JSON Schemas compiled, by ajv, for draft 2020-12: every fault and not the first, no check\n * of a `format`, and the keywords of an editor's own, as `markdownDescription`, taken.\n */\nlet ajv: Ajv2020 | undefined\nconst compiled = new WeakMap<object, ValidateFunction>()\n\nconst compile = (schema: JsonSchema): ValidateFunction => {\n ajv ??= new Ajv2020({ allErrors: true, strict: false, validateFormats: false, logger: false })\n if (typeof schema === 'boolean') return ajv.compile(schema)\n let validate = compiled.get(schema)\n if (validate === undefined) {\n validate = ajv.compile(schema)\n compiled.set(schema, validate)\n }\n return validate\n}\n\n/** The keys of a JSON Pointer, as ajv gives the place of a value: `/compress/threshold`. */\nconst keysOfPointer = (pointer: string): string[] =>\n pointer === ''\n ? []\n : pointer\n .slice(1)\n .split('/')\n .map((key) => key.replaceAll('~1', '/').replaceAll('~0', '~'))\n\n/** What ajv found wrong, as an issue: a key the schema does not take at its own path. */\nconst issueOfAjv = ({ instancePath, keyword, params, message }: ErrorObject): ConfigIssue => {\n const path = keysOfPointer(instancePath)\n const extra: unknown =\n keyword === 'additionalProperties' ? params['additionalProperty'] : undefined\n return typeof extra === 'string'\n ? { path: [...path, extra], message: 'is no key that the section takes' }\n : { path, message: message ?? keyword }\n}\n\n/** The keys of a Standard Schema's path, each as text. */\nconst pathOfStandard = (path: StandardSchemaV1.Issue['path']): ConfigPath =>\n (path ?? []).map((segment) =>\n String(typeof segment === 'object' && segment !== null ? segment.key : segment)\n )\n\n/** What a Standard Schema's result says, as issues. */\nconst checkedOfResult = <T>(result: StandardSchemaV1.Result<T>, value: unknown): Checked<T> =>\n result.issues === undefined\n ? { issues: [], value: result.value }\n : {\n issues: result.issues.map(({ path, message }) => ({ path: pathOfStandard(path), message })),\n value: value as T\n }\n\n/** What ajv finds wrong with `value` by the JSON Schema of `schema`; nothing of a schema that gives\n * none. */\nconst checkedOfJson = <T>(value: unknown, schema: unknown): Checked<T> => {\n const json = jsonSchemaOf(schema)\n if (json === undefined) return { issues: [], value: value as T }\n const validate = compile(json)\n validate(value)\n return { issues: (validate.errors ?? []).map(issueOfAjv), value: value as T }\n}\n\n/**\n * What `schema` finds wrong with `value`, none when it is valid, and the value as it reads it: a\n * Standard Schema's output, or `value` itself. A Standard Schema that validates is asked; a JSON\n * Schema, or a Standard JSON Schema of none, is checked by ajv; a function is called.\n */\nexport async function issuesOf<T>(value: unknown, schema: SectionSchema<T>): Promise<Checked<T>> {\n if (typeof schema === 'function')\n return { issues: await (schema as ValidateSection)(value), value: value as T }\n const standard = validatorOf(schema)\n if (standard !== undefined)\n return checkedOfResult((await standard.validate(value)) as StandardSchemaV1.Result<T>, value)\n return checkedOfJson(value, schema)\n}\n\n/**\n * What `schema` finds wrong with `value`, as {@link issuesOf} checks it, checked synchronously: a\n * schema that answers with a promise is a {@link SyncSchemaError} of the section `section`.\n */\nexport function issuesOfSync<T>(\n value: unknown,\n schema: SectionSchema<T>,\n section: string = 'configuration'\n): Checked<T> {\n if (typeof schema === 'function') {\n const issues = (schema as ValidateSection)(value)\n if (issues instanceof Promise) throw new SyncSchemaError(section)\n return { issues, value: value as T }\n }\n const standard = validatorOf(schema)\n if (standard !== undefined) {\n const result = standard.validate(value)\n if (result instanceof Promise) throw new SyncSchemaError(section)\n return checkedOfResult(result as StandardSchemaV1.Result<T>, value)\n }\n return checkedOfJson(value, schema)\n}\n\n/** Whether `path` is `under` or a path under it. */\nconst isUnder = (path: ConfigPath, under: ConfigPath): boolean =>\n under.every((key, index) => path[index] === key)\n\n/** The section of `name` as the layers give it, before it is checked, and whether any gave one. */\ntype Layered = {\n readonly section: unknown\n readonly given: boolean\n readonly own: boolean\n readonly environment: WithEnvironment\n}\n\n/** The section `name` of the layers of `resolved`, read for placeholders, before it is checked. */\nfunction layeredOf(resolved: ResolvedConfig, name: string, schema: unknown): Layered {\n const own = Object.hasOwn(resolved.config, name)\n const defaults = resolved.defaults?.config\n const layered = defaults !== undefined && Object.hasOwn(defaults, name)\n const filed = mergeSection(layered ? defaults[name] : undefined, resolved.config[name])\n const environment =\n resolved.environment === undefined\n ? { value: filed, set: [] }\n : withEnvironment(\n filed,\n resolved.environment.variables,\n `${resolved.environment.prefix}${envNameOf(name)}_`,\n jsonSchemaOf(schema)\n )\n const given = own || layered || environment.set.length > 0\n // No environment given is one of no variable: each placeholder is refused, never left as text.\n const section = given\n ? expandPlaceholders(\n environment.value,\n [resolved.key, name],\n resolved.environment?.values ?? {}\n )\n : undefined\n return { section, given, own, environment }\n}\n\n/** The error of what a schema found wrong with a section: of the variables that set a value it\n * refuses, else of the project's file, or the defaults', of a section the project gives none of. */\nfunction invalidOf(\n resolved: ResolvedConfig,\n name: string,\n { own, environment }: Layered,\n issues: readonly ConfigIssue[]\n): InvalidSectionError {\n const variables = environment.set.filter(({ path }) =>\n issues.some((issue) => isUnder(issue.path, path))\n )\n if (variables.length > 0)\n return new InvalidSectionError(\n variables.map(({ variable }) => variable).join(', '),\n resolved.namespace,\n name,\n issues.filter((issue) => variables.some(({ path }) => isUnder(issue.path, path))),\n resolved.key\n )\n return own || resolved.defaults === undefined\n ? new InvalidSectionError(\n resolved.source?.path ?? resolved.root,\n resolved.namespace,\n name,\n issues,\n resolved.key\n )\n : new InvalidSectionError(resolved.defaults.path, resolved.namespace, name, issues)\n}\n\n/**\n * The section `name` of the configuration, as its tool reads it: the project's, merged over the\n * section of the `defaults` of the tool's package when it gives some ({@link mergeSection}), with\n * the environment's variables the tool gave `loadConfig` over both, each that names a key of the\n * section or of its schema, as `WTF_VITE_COMPRESS` (`withEnvironment` of ./env); `undefined` when\n * none has one, which the tool takes as its own defaults. Each string in it is then read for\n * placeholders `${env:NAME}`, taken from the whole environment the tool gave (`expandPlaceholders`\n * of ./placeholder); a variable not set, or of no environment given, is an\n * `EnvPlaceholderUnsetError`. Only this, and {@link sectionOfSync}, expand them, so what shows or\n * writes the configuration never holds a secret it points at. With a `schema` it is checked, and\n * what is wrong is an {@link InvalidSectionError}, which names where the value came from and the\n * path of each value, as `wtf.vite.compress`.\n */\nexport async function sectionOf<T = unknown>(\n resolved: ResolvedConfig,\n name: string,\n schema?: SectionSchema<T>\n): Promise<T | undefined> {\n const layered = layeredOf(resolved, name, schema)\n if (!layered.given) return undefined\n if (schema === undefined) return layered.section as T\n const { issues, value } = await issuesOf(layered.section, schema)\n if (issues.length === 0) return value\n throw invalidOf(resolved, name, layered, issues)\n}\n\n/**\n * The section `name` of the configuration, as {@link sectionOf} reads it, checked synchronously,\n * as a tool that reads its config synchronously reads it with `loadConfigSync` of ./load. A schema\n * that checks asynchronously is a {@link SyncSchemaError}.\n */\nexport function sectionOfSync<T = unknown>(\n resolved: ResolvedConfig,\n name: string,\n schema?: SectionSchema<T>\n): T | undefined {\n const layered = layeredOf(resolved, name, schema)\n if (!layered.given) return undefined\n if (schema === undefined) return layered.section as T\n const { issues, value } = issuesOfSync(layered.section, schema, name)\n if (issues.length === 0) return value\n throw invalidOf(resolved, name, layered, issues)\n}\n"]}
|
|
1
|
+
{"version":3,"file":"section.js","sourceRoot":"","sources":["../src/section.ts"],"names":[],"mappings":"AA2BA,OAAO,EAAE,OAAO,EAA2C,MAAM,kBAAkB,CAAA;AAEnF,OAAO,EAAE,SAAS,EAAE,YAAY,EAAE,eAAe,EAAwB,MAAM,UAAU,CAAA;AACzF,OAAO,EAAE,mBAAmB,EAAE,eAAe,EAAE,MAAM,aAAa,CAAA;AASlE,OAAO,EAAE,YAAY,EAAE,MAAM,YAAY,CAAA;AACzC,OAAO,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAA;AAErD,OAAO,EAAE,YAAY,EAAE,MAAM,YAAY,CAAA;AAMzC,MAAM,MAAM,GAAG,CAAC,KAAc,EAAoC,EAAE,CAClE,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,CAAA;AAE7C,4FAA4F;AAC5F,MAAM,WAAW,GAAG,CAAC,MAAe,EAA6C,EAAE;IACjF,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,WAAW,IAAI,MAAM,CAAC;QAAE,OAAO,SAAS,CAAA;IACjE,MAAM,QAAQ,GAAG,MAAM,CAAC,WAAW,CAAC,CAAA;IACpC,OAAO,MAAM,CAAC,QAAQ,CAAC,IAAI,OAAO,QAAQ,CAAC,UAAU,CAAC,KAAK,UAAU;QACnE,CAAC,CAAE,QAAqD;QACxD,CAAC,CAAC,SAAS,C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MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,GAAG,YAAY,CAAC,OAAO,CAAC,OAAO,EAAE,MAAM,EAAE,IAAI,CAAC,CAAA;IACrE,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,KAAK,CAAA;IACrC,MAAM,SAAS,CAAC,QAAQ,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,CAAC,CAAA;AAClD,CAAC","sourcesContent":["/**\n * A tool's section of the configuration: {@link sectionOf}, the section of a name, the project's\n * merged over the defaults of the tool's package ({@link mergeSection}), with the environment's\n * variables the tool gives over both, each placeholder `${env:NAME}` in it replaced by the variable\n * it names, and checked by the schema the tool gives; {@link sectionOfSync}, the same, checked\n * synchronously; and {@link issuesOf} and {@link issuesOfSync}, what a schema finds wrong with a\n * value. A schema is a Standard Schema, as each preset's `./schema` exports one, a JSON Schema or a\n * Standard JSON Schema, which ajv checks, or a function. What is wrong is an\n * `InvalidSectionError` of ./errors, which names the file and the path of each value.\n *\n * ```ts\n * import { nodeStorage } from '@wtf/platform-fs-node/storage'\n * import { nodePlatform } from '@wtf/platform-node/platform'\n *\n * import { loadConfig } from '@wtf/project-config/load'\n * import { sectionOf } from '@wtf/project-config/section'\n * import { baseConfig } from '@wtf/project-vite/config'\n * import { viteSchema } from '@wtf/project-vite/schema'\n *\n * const platform = nodePlatform({ fetch, storage: nodeStorage() })\n * const config = await loadConfig({ platform })\n * export default baseConfig({ platform, ...(await sectionOf(config, 'vite', viteSchema)) })\n * ```\n *\n * @packageDocumentation\n */\nimport type { StandardSchemaV1 } from '@standard-schema/spec'\nimport { Ajv2020, type ErrorObject, type ValidateFunction } from 'ajv/dist/2020.js'\n\nimport { envNameOf, jsonSchemaOf, withEnvironment, type WithEnvironment } from './env.ts'\nimport { InvalidSectionError, SyncSchemaError } from './errors.ts'\nimport type {\n ConfigIssue,\n ConfigPath,\n JsonSchema,\n ResolvedConfig,\n SectionSchema,\n ValidateSection\n} from './index.ts'\nimport { mergeSection } from './merge.ts'\nimport { expandPlaceholders } from './placeholder.ts'\n\nexport { mergeSection } from './merge.ts'\n\n/** What a schema found of a value: what is wrong with it, none when it is valid, and the value as\n * the schema reads it. */\nexport type Checked<T> = { readonly issues: readonly ConfigIssue[]; readonly value: T }\n\nconst isNode = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null\n\n/** Whether `schema` is a Standard Schema that validates: its `~standard` has `validate`. */\nconst validatorOf = (schema: unknown): StandardSchemaV1['~standard'] | undefined => {\n if (!isNode(schema) || !('~standard' in schema)) return undefined\n const standard = schema['~standard']\n return isNode(standard) && typeof standard['validate'] === 'function'\n ? (standard as unknown as StandardSchemaV1['~standard'])\n : undefined\n}\n\n/**\n * The JSON Schemas compiled, by ajv, for draft 2020-12: every fault and not the first, no check\n * of a `format`, and the keywords of an editor's own, as `markdownDescription`, taken.\n */\nlet ajv: Ajv2020 | undefined\nconst compiled = new WeakMap<object, ValidateFunction>()\n\nconst compile = (schema: JsonSchema): ValidateFunction => {\n ajv ??= new Ajv2020({ allErrors: true, strict: false, validateFormats: false, logger: false })\n if (typeof schema === 'boolean') return ajv.compile(schema)\n let validate = compiled.get(schema)\n if (validate === undefined) {\n validate = ajv.compile(schema)\n compiled.set(schema, validate)\n }\n return validate\n}\n\n/** The keys of a JSON Pointer, as ajv gives the place of a value: `/compress/threshold`. */\nconst keysOfPointer = (pointer: string): string[] =>\n pointer === ''\n ? []\n : pointer\n .slice(1)\n .split('/')\n .map((key) => key.replaceAll('~1', '/').replaceAll('~0', '~'))\n\n/** What ajv found wrong, as an issue: a key the schema does not take at its own path. */\nconst issueOfAjv = ({ instancePath, keyword, params, message }: ErrorObject): ConfigIssue => {\n const path = keysOfPointer(instancePath)\n const extra: unknown =\n keyword === 'additionalProperties' ? params['additionalProperty'] : undefined\n return typeof extra === 'string'\n ? { path: [...path, extra], message: 'is no key that the section takes' }\n : { path, message: message ?? keyword }\n}\n\n/** The keys of a Standard Schema's path, each as text. */\nconst pathOfStandard = (path: StandardSchemaV1.Issue['path']): ConfigPath =>\n (path ?? []).map((segment) =>\n String(typeof segment === 'object' && segment !== null ? segment.key : segment)\n )\n\n/** What a Standard Schema's result says, as issues. */\nconst checkedOfResult = <T>(result: StandardSchemaV1.Result<T>, value: unknown): Checked<T> =>\n result.issues === undefined\n ? { issues: [], value: result.value }\n : {\n issues: result.issues.map(({ path, message }) => ({ path: pathOfStandard(path), message })),\n value: value as T\n }\n\n/** What ajv finds wrong with `value` by the JSON Schema of `schema`; nothing of a schema that gives\n * none. */\nconst checkedOfJson = <T>(value: unknown, schema: unknown): Checked<T> => {\n const json = jsonSchemaOf(schema)\n if (json === undefined) return { issues: [], value: value as T }\n const validate = compile(json)\n validate(value)\n return { issues: (validate.errors ?? []).map(issueOfAjv), value: value as T }\n}\n\n/**\n * What `schema` finds wrong with `value`, none when it is valid, and the value as it reads it: a\n * Standard Schema's output, or `value` itself. A Standard Schema that validates is asked; a JSON\n * Schema, or a Standard JSON Schema of none, is checked by ajv; a function is called.\n */\nexport async function issuesOf<T>(value: unknown, schema: SectionSchema<T>): Promise<Checked<T>> {\n if (typeof schema === 'function')\n return { issues: await (schema as ValidateSection)(value), value: value as T }\n const standard = validatorOf(schema)\n if (standard !== undefined)\n return checkedOfResult((await standard.validate(value)) as StandardSchemaV1.Result<T>, value)\n return checkedOfJson(value, schema)\n}\n\n/**\n * What `schema` finds wrong with `value`, as {@link issuesOf} checks it, checked synchronously: a\n * schema that answers with a promise is a {@link SyncSchemaError} of the section `section`.\n */\nexport function issuesOfSync<T>(\n value: unknown,\n schema: SectionSchema<T>,\n section: string = 'configuration'\n): Checked<T> {\n if (typeof schema === 'function') {\n const issues = (schema as ValidateSection)(value)\n if (issues instanceof Promise) throw new SyncSchemaError(section)\n return { issues, value: value as T }\n }\n const standard = validatorOf(schema)\n if (standard !== undefined) {\n const result = standard.validate(value)\n if (result instanceof Promise) throw new SyncSchemaError(section)\n return checkedOfResult(result as StandardSchemaV1.Result<T>, value)\n }\n return checkedOfJson(value, schema)\n}\n\n/** Whether `path` is `under` or a path under it. */\nconst isUnder = (path: ConfigPath, under: ConfigPath): boolean =>\n under.every((key, index) => path[index] === key)\n\n/** The section of `name` as the layers give it, before it is checked, and whether any gave one. */\ntype Layered = {\n readonly section: unknown\n readonly given: boolean\n readonly own: boolean\n readonly environment: WithEnvironment\n}\n\n/** The section `name` of the layers of `resolved`, read for placeholders, before it is checked. */\nfunction layeredOf(resolved: ResolvedConfig, name: string, schema: unknown): Layered {\n const own = Object.hasOwn(resolved.config, name)\n const defaults = resolved.defaults?.config\n const layered = defaults !== undefined && Object.hasOwn(defaults, name)\n const filed = mergeSection(layered ? defaults[name] : undefined, resolved.config[name])\n const environment =\n resolved.environment === undefined\n ? { value: filed, set: [] }\n : withEnvironment(\n filed,\n resolved.environment.variables,\n `${resolved.environment.prefix}${envNameOf(name)}_`,\n jsonSchemaOf(schema)\n )\n const given = own || layered || environment.set.length > 0\n // No environment given is one of no variable: each placeholder is refused, never left as text.\n const section = given\n ? expandPlaceholders(\n environment.value,\n [resolved.key, name],\n resolved.environment?.values ?? {}\n )\n : undefined\n return { section, given, own, environment }\n}\n\n/** The error of what a schema found wrong with a section: of the variables that set a value it\n * refuses, else of the project's file, or the defaults', of a section the project gives none of. */\nfunction invalidOf(\n resolved: ResolvedConfig,\n name: string,\n { own, environment }: Layered,\n issues: readonly ConfigIssue[]\n): InvalidSectionError {\n const variables = environment.set.filter(({ path }) =>\n issues.some((issue) => isUnder(issue.path, path))\n )\n if (variables.length > 0)\n return new InvalidSectionError(\n variables.map(({ variable }) => variable).join(', '),\n resolved.namespace,\n name,\n issues.filter((issue) => variables.some(({ path }) => isUnder(issue.path, path))),\n resolved.key\n )\n return own || resolved.defaults === undefined\n ? new InvalidSectionError(\n resolved.source?.path ?? resolved.root,\n resolved.namespace,\n name,\n issues,\n resolved.key\n )\n : new InvalidSectionError(resolved.defaults.path, resolved.namespace, name, issues)\n}\n\n/**\n * The section `name` of the configuration, as its tool reads it: the project's, merged over the\n * section of the `defaults` of the tool's package when it gives some ({@link mergeSection}), with\n * the variables of the environment of the platform the tool gave `loadConfig` over both, each that\n * names a key of the section or of its schema, as `WTF_VITE_COMPRESS` (`withEnvironment` of\n * ./env); `undefined` when none has one, which the tool takes as its own defaults. Each string in it is then read for\n * placeholders `${env:NAME}`, taken from that whole environment (`expandPlaceholders` of\n * ./placeholder); a variable not set, or of a configuration read of no environment, is an\n * `EnvPlaceholderUnsetError`. Only this, and {@link sectionOfSync}, expand them, so what shows or\n * writes the configuration never holds a secret it points at. With a `schema` it is checked, and\n * what is wrong is an {@link InvalidSectionError}, which names where the value came from and the\n * path of each value, as `wtf.vite.compress`.\n */\nexport async function sectionOf<T = unknown>(\n resolved: ResolvedConfig,\n name: string,\n schema?: SectionSchema<T>\n): Promise<T | undefined> {\n const layered = layeredOf(resolved, name, schema)\n if (!layered.given) return undefined\n if (schema === undefined) return layered.section as T\n const { issues, value } = await issuesOf(layered.section, schema)\n if (issues.length === 0) return value\n throw invalidOf(resolved, name, layered, issues)\n}\n\n/**\n * The section `name` of the configuration, as {@link sectionOf} reads it, checked synchronously,\n * as a tool that reads its config synchronously reads it with `loadConfigSync` of ./load. A schema\n * that checks asynchronously is a {@link SyncSchemaError}.\n */\nexport function sectionOfSync<T = unknown>(\n resolved: ResolvedConfig,\n name: string,\n schema?: SectionSchema<T>\n): T | undefined {\n const layered = layeredOf(resolved, name, schema)\n if (!layered.given) return undefined\n if (schema === undefined) return layered.section as T\n const { issues, value } = issuesOfSync(layered.section, schema, name)\n if (issues.length === 0) return value\n throw invalidOf(resolved, name, layered, issues)\n}\n"]}
|
package/dist/write.js
CHANGED
|
@@ -9,12 +9,13 @@
|
|
|
9
9
|
* platform it is given.
|
|
10
10
|
*
|
|
11
11
|
* ```ts
|
|
12
|
-
* import {
|
|
12
|
+
* import { nodeStorage } from '@wtf/platform-fs-node/storage'
|
|
13
|
+
* import { nodePlatform } from '@wtf/platform-node/platform'
|
|
14
|
+
*
|
|
13
15
|
* import { setConfigValue } from '@wtf/project-config/write'
|
|
14
16
|
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
* })
|
|
17
|
+
* const platform = nodePlatform({ fetch, storage: nodeStorage() })
|
|
18
|
+
* await setConfigValue(platform.dirs.cwd, ['vite', 'compress'], false, { platform })
|
|
18
19
|
* ```
|
|
19
20
|
*
|
|
20
21
|
* @packageDocumentation
|
package/dist/write.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"write.js","sourceRoot":"","sources":["../src/write.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,OAAO,EAAE,UAAU,EAAE,MAAM,EAA0B,MAAM,EAAE,MAAM,cAAc,CAAA;AAEjF,OAAO,EACL,uBAAuB,EACvB,iBAAiB,EACjB,eAAe,EACf,sBAAsB,EACtB,iBAAiB,EACjB,yBAAyB,EAC1B,MAAM,aAAa,CAAA;AACpB,OAAO,EAAc,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,YAAY,CAAA;AAEhF,OAAO,EAAE,aAAa,EAAE,WAAW,EAAE,YAAY,EAAsB,MAAM,aAAa,CAAA;AAC1F,OAAO,EAAE,gBAAgB,EAAE,OAAO,EAAE,MAAM,WAAW,CAAA;AAsBrD;;;GAGG;AACH,KAAK,UAAU,QAAQ,CAAC,MAAc,EAAE,EAAE,IAAI,EAAE,GAAG,OAAO,EAAgB;IACxE,MAAM,IAAI,GAAG,WAAW,CAAC,OAAO,CAAC,CAAA;IACjC,IAAI,IAAI,KAAK,SAAS,IAAI,IAAI,KAAK,YAAY,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC;QACrE,MAAM,IAAI,yBAAyB,CAAC,IAAI,EAAE,IAAI,CAAC,CAAA;IACjD,MAAM,EAAE,IAAI,EAAE,GAAG,EAAE,OAAO,EAAE,GAAG,MAAM,YAAY,CAAC,MAAM,EAAE,O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,EAAE,KAAK;SACf,CAAA;IACH,OAAO,OAAO,CAAC,EAAE,IAAI,EAAE,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,EAAE,IAAI,EAAE,SAAS,EAAE,OAAO,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC,CAAA;AAC5F,CAAC","sourcesContent":["/**\n * A value of a project's configuration written: {@link setConfigValue}, a value set at a path, and\n * {@link unsetConfigValue}, a value taken away. Each writes the file in use, the key of\n * package.json (`wtf` by default) or a JSON file of its names (`wtf.config.json` by default); with\n * none, a set makes it in the key of package.json, or in the JSON file that is named; and it never\n * writes a file of code, as `wtf.config.ts`. The text of the file is changed in place, by\n * jsonc-parser, so what the write does not change stays as it was: its indent, its line ends and\n * the order of its keys, and a new key is the last of its object. Each reads and writes by the\n * platform it is given.\n *\n * ```ts\n * import { nodeConfigPlatform } from '@wtf/project-config/node'\n * import { setConfigValue } from '@wtf/project-config/write'\n *\n * await setConfigValue(process.cwd(), ['vite', 'compress'], false, {\n * platform: nodeConfigPlatform()\n * })\n * ```\n *\n * @packageDocumentation\n */\nimport { applyEdits, format, type FormattingOptions, modify } from 'jsonc-parser'\n\nimport {\n ConfigFileMismatchError,\n ConfigInCodeError,\n ConfigPathError,\n InvalidConfigFileError,\n NoConfigFileError,\n UnwritableConfigFileError\n} from './errors.ts'\nimport { type Files, filesOf, isObject, kindOf, PACKAGE_JSON } from './files.ts'\nimport type { ConfigPath, ConfigSource, ConfigWrite } from './index.ts'\nimport { configNamesOf, jsonFilesOf, locateConfig, type LocateOptions } from './locate.ts'\nimport { textOfConfigPath, valueAt } from './path.ts'\n\n/** How a value of the configuration is written: where it is looked for, of the namespace and the\n * names of `ConfigNames`, each its default when it is not given, and the file to write. */\nexport type WriteOptions = LocateOptions & {\n /**\n * The file to write: where none holds the configuration, the one to make it in, the key of\n * package.json (`package.json`) by default, or a JSON file of the names, as\n * `<namespace>.config.json`; where one does, it must be that one, or the write is a\n * `ConfigFileMismatchError`. Any other file is an `UnwritableConfigFileError`.\n */\n readonly file?: string\n}\n\n/** The file of the configuration that a write changes: the one in use, which is no code. */\ntype Target = {\n readonly root: string\n readonly key: string\n readonly source: ConfigSource | undefined\n readonly ignored: readonly ConfigSource[]\n}\n\n/**\n * The file in use, of the project in `folder`, checked against the file named: no code, and the\n * one named, if one is, which is a JSON file of the names, or package.json.\n */\nasync function targetOf(folder: string, { file, ...options }: WriteOptions): Promise<Target> {\n const json = jsonFilesOf(options)\n if (file !== undefined && file !== PACKAGE_JSON && !json.includes(file))\n throw new UnwritableConfigFileError(file, json)\n const { root, key, sources } = await locateConfig(folder, options)\n const [source, ...ignored] = sources\n if (source === undefined) return { root, key, source: undefined, ignored }\n if (kindOf(source.file) === 'code') throw new ConfigInCodeError(source.path, { files: json, key })\n if (file !== undefined && file !== source.file)\n throw new ConfigFileMismatchError(source.path, file)\n return { root, key, source, ignored }\n}\n\n/** How the text of a file is laid out: its indent, by the first line that has one, and its line\n * ends. Two spaces, and `\\n`, where it says nothing. */\nfunction formattingOf(text: string): FormattingOptions {\n const indent = /^([ \\t]+)\\S/m.exec(text)?.[1]\n const eol = text.includes('\\r\\n') ? '\\r\\n' : '\\n'\n if (indent === undefined) return { insertSpaces: true, tabSize: 2, eol }\n return indent.startsWith('\\t')\n ? { insertSpaces: false, tabSize: 1, eol }\n : { insertSpaces: true, tabSize: indent.length, eol }\n}\n\n/** The keys of `path` for jsonc-parser, from the top of the file: the index of a list as a\n * number. A value on the way that is no object or list is a {@link ConfigPathError}. */\nfunction keysOf(value: unknown, path: ConfigPath, shown: string): (string | number)[] {\n const keys: (string | number)[] = []\n let at: unknown = value\n for (const [index, key] of path.entries()) {\n if (at === undefined) {\n keys.push(key)\n continue\n }\n if (Array.isArray(at)) {\n if (!/^\\d+$/.test(key))\n throw new ConfigPathError(\n shown,\n `goes into ${textOfConfigPath(path.slice(0, index)) || 'the configuration'}, a list, by ${key}, which is no index.`\n )\n keys.push(Number(key))\n at = at[Number(key)]\n } else if (isObject(at)) {\n keys.push(key)\n at = Object.hasOwn(at, key) ? at[key] : undefined\n } else\n throw new ConfigPathError(\n shown,\n `goes into ${textOfConfigPath(path.slice(0, index))}, which is ${JSON.stringify(at)}, and holds no value.`\n )\n }\n return keys\n}\n\n/** The JSON of the file at `path`, and its text. */\nasync function jsonAt(\n path: string,\n files: Files\n): Promise<{ readonly text: string; readonly json: unknown }> {\n const text = (await files.text(path)) ?? ''\n try {\n return { text, json: JSON.parse(text) }\n } catch (error) {\n throw new InvalidConfigFileError(path, 'is no JSON.', { cause: error })\n }\n}\n\n/** Whether two JSON values are the same. */\nconst same = (a: unknown, b: unknown): boolean => JSON.stringify(a) === JSON.stringify(b)\n\nconst isSpace = (char: string | undefined): boolean =>\n char !== undefined && ' \\t\\r\\n'.includes(char)\n\n/** The range of `text` from `start` to `end` that a change's layout is given to: with the space on\n * each side of it, whole, and the token past that, so the space between the change and its\n * neighbours is laid out too, and no line end is cut in two. */\nfunction rangeOf(text: string, start: number, end: number): { offset: number; length: number } {\n let from = start\n while (from > 0 && isSpace(text[from - 1])) from -= 1\n let to = end\n while (to < text.length && isSpace(text[to])) to += 1\n const offset = Math.max(0, from - 1)\n return { offset, length: Math.min(text.length, to + 1) - offset }\n}\n\n/**\n * The text of `text` with `value` at `keys`, from the top of the file; `undefined` takes the value\n * away. jsonc-parser makes the change, and the layout of the file is given to what it writes, and\n * to the space beside it, and to nothing else: its own formatting of a change would lay out the\n * whole line it is on again, as an object on one line beside it.\n */\nfunction edited(text: string, keys: (string | number)[], value: unknown): string {\n // One edit, or none, of a value to take away that is not there.\n const [edit] = modify(text, keys, value, {})\n if (edit === undefined) return text\n const result = applyEdits(text, [edit])\n const range = rangeOf(result, edit.offset, edit.offset + edit.content.length)\n return applyEdits(result, format(result, range, { ...formattingOf(text), keepLines: false }))\n}\n\n/** The keys of the configuration in `file`, from the top of it: of package.json, its key. */\nconst prefixOf = (file: string, key: string): string[] => (kindOf(file) === 'package' ? [key] : [])\n\n/** Write `value`, or take it away (`undefined`), at `path` of the configuration in `source`. */\nasync function writeAt(\n target: Target & { readonly source: ConfigSource },\n path: ConfigPath,\n value: unknown,\n files: Files\n): Promise<ConfigWrite> {\n const { root, key, source, ignored } = target\n const inPackage = kindOf(source.file) === 'package'\n const { text, json } = await jsonAt(source.path, files)\n const config: unknown = inPackage && isObject(json) ? json[key] : json\n if (!isObject(config))\n throw new InvalidConfigFileError(\n source.path,\n inPackage ? `its \"${key}\" key is no JSON object.` : 'is no JSON object.'\n )\n const previous = valueAt(config, path)\n const changed = !same(previous, value)\n // A value taken away that is not there is no change, wherever the path goes.\n if (changed) {\n const keys = keysOf(config, path, textOfConfigPath(path))\n await files.write(source.path, edited(text, [...prefixOf(source.file, key), ...keys], value))\n }\n return { root, key, source, ignored, path, previous, value, changed, created: false }\n}\n\n/** A path with at least one key: the whole configuration is no value to set or unset. */\nfunction checked(path: ConfigPath): ConfigPath {\n if (path.length === 0 || path.some((key) => key === ''))\n throw new ConfigPathError(textOfConfigPath(path), 'is no path: give at least one key.')\n return path\n}\n\n/**\n * Set `value` at `path` of the configuration of the project in `folder`: in the file in use, the\n * key of package.json (the namespace by default) or a JSON file of the names\n * (`<namespace>.config.json` by default); with none, in the key, added to the package.json at the\n * root, by default, or in the JSON file `options.file` names, made. An object on the way that is\n * not there is made. Nothing is written when the value is already so.\n *\n * Throws a `ConfigInCodeError` when the configuration is code, as `<namespace>.config.ts`; a\n * `NoConfigFileError` when there is none, and no package.json at the root to hold it, and no JSON\n * file is named; a `ConfigFileMismatchError` when the file named is not the one in use; an\n * `UnwritableConfigFileError` when the file named is neither a JSON file of the names nor\n * package.json; and a `ConfigPathError` when the path goes into a value that is no object or list.\n */\nexport async function setConfigValue(\n folder: string,\n path: ConfigPath,\n value: unknown,\n options: WriteOptions\n): Promise<ConfigWrite> {\n if (value === undefined) throw new TypeError('A value of JSON is set, and not undefined.')\n checked(path)\n const { file = PACKAGE_JSON } = options\n const { namespace } = configNamesOf(options)\n const files = filesOf(options.platform)\n const target = await targetOf(folder, options)\n if (target.source !== undefined)\n return writeAt({ ...target, source: target.source }, path, value, files)\n const { root, key, ignored } = target\n const source: ConfigSource = { file, path: options.platform.path.join(root, file) }\n const keys = keysOf({}, path, textOfConfigPath(path))\n const made = { root, key, source, ignored, path, previous: undefined, value }\n if (kindOf(file) === 'json') {\n await files.write(source.path, edited('{}\\n', keys, value))\n return { ...made, changed: true, created: true }\n }\n const manifest = await files.text(source.path)\n if (manifest === undefined)\n throw new NoConfigFileError(root, { namespace, key, json: jsonFilesOf(options)[0] })\n await files.write(source.path, edited(manifest, [key, ...keys], value))\n return { ...made, changed: true, created: true }\n}\n\n/**\n * Take away the value at `path` of the configuration of the project in `folder`, in the file in\n * use: a JSON file of the names (`<namespace>.config.json` by default) or the key of package.json\n * (the namespace by default). Nothing is written when no value is there, or no configuration:\n * `changed` is false. An object it leaves empty stays. Throws a `ConfigInCodeError` when the\n * configuration is code, and a `ConfigFileMismatchError` when the file named is not the one in use.\n */\nexport async function unsetConfigValue(\n folder: string,\n path: ConfigPath,\n options: WriteOptions\n): Promise<ConfigWrite> {\n checked(path)\n const target = await targetOf(folder, options)\n const { root, key, source, ignored } = target\n if (source === undefined)\n return {\n root,\n key,\n source,\n ignored,\n path,\n previous: undefined,\n value: undefined,\n changed: false,\n created: false\n }\n return writeAt({ root, key, source, ignored }, path, undefined, filesOf(options.platform))\n}\n"]}
|
|
1
|
+
{"version":3,"file":"write.js","sourceRoot":"","sources":["../src/write.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,OAAO,EAAE,UAAU,EAAE,MAAM,EAA0B,MAAM,EAAE,MAAM,cAAc,CAAA;AAEjF,OAAO,EACL,uBAAuB,EACvB,iBAAiB,EACjB,eAAe,EACf,sBAAsB,EACtB,iBAAiB,EACjB,yBAAyB,EAC1B,MAAM,aAAa,CAAA;AACpB,OAAO,EAAc,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,YAAY,EAAE,MAA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AO,EAAE,GAAG,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,CAAA;AAClD,CAAC;AAED;;;;;;GAMG;AACH,MAAM,CAAC,KAAK,UAAU,gBAAgB,CACpC,MAAc,EACd,IAAgB,EAChB,OAAqB;IAErB,OAAO,CAAC,IAAI,CAAC,CAAA;IACb,MAAM,MAAM,GAAG,MAAM,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;IAC9C,MAAM,EAAE,IAAI,EAAE,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,GAAG,MAAM,CAAA;IAC7C,IAAI,MAAM,KAAK,SAAS;QACtB,OAAO;YACL,IAAI;YACJ,GAAG;YACH,MAAM;YACN,OAAO;YACP,IAAI;YACJ,QAAQ,EAAE,SAAS;YACnB,KAAK,EAAE,SAAS;YAChB,OAAO,EAAE,KAAK;YACd,OAAO,EAAE,KAAK;SACf,CAAA;IACH,OAAO,OAAO,CAAC,EAAE,IAAI,EAAE,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,EAAE,IAAI,EAAE,SAAS,EAAE,OAAO,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC,CAAA;AAC5F,CAAC","sourcesContent":["/**\n * A value of a project's configuration written: {@link setConfigValue}, a value set at a path, and\n * {@link unsetConfigValue}, a value taken away. Each writes the file in use, the key of\n * package.json (`wtf` by default) or a JSON file of its names (`wtf.config.json` by default); with\n * none, a set makes it in the key of package.json, or in the JSON file that is named; and it never\n * writes a file of code, as `wtf.config.ts`. The text of the file is changed in place, by\n * jsonc-parser, so what the write does not change stays as it was: its indent, its line ends and\n * the order of its keys, and a new key is the last of its object. Each reads and writes by the\n * platform it is given.\n *\n * ```ts\n * import { nodeStorage } from '@wtf/platform-fs-node/storage'\n * import { nodePlatform } from '@wtf/platform-node/platform'\n *\n * import { setConfigValue } from '@wtf/project-config/write'\n *\n * const platform = nodePlatform({ fetch, storage: nodeStorage() })\n * await setConfigValue(platform.dirs.cwd, ['vite', 'compress'], false, { platform })\n * ```\n *\n * @packageDocumentation\n */\nimport { applyEdits, format, type FormattingOptions, modify } from 'jsonc-parser'\n\nimport {\n ConfigFileMismatchError,\n ConfigInCodeError,\n ConfigPathError,\n InvalidConfigFileError,\n NoConfigFileError,\n UnwritableConfigFileError\n} from './errors.ts'\nimport { type Files, filesOf, isObject, kindOf, PACKAGE_JSON } from './files.ts'\nimport type { ConfigPath, ConfigSource, ConfigWrite } from './index.ts'\nimport { configNamesOf, jsonFilesOf, locateConfig, type LocateOptions } from './locate.ts'\nimport { textOfConfigPath, valueAt } from './path.ts'\n\n/** How a value of the configuration is written: where it is looked for, of the namespace and the\n * names of `ConfigNames`, each its default when it is not given, and the file to write. */\nexport type WriteOptions = LocateOptions & {\n /**\n * The file to write: where none holds the configuration, the one to make it in, the key of\n * package.json (`package.json`) by default, or a JSON file of the names, as\n * `<namespace>.config.json`; where one does, it must be that one, or the write is a\n * `ConfigFileMismatchError`. Any other file is an `UnwritableConfigFileError`.\n */\n readonly file?: string\n}\n\n/** The file of the configuration that a write changes: the one in use, which is no code. */\ntype Target = {\n readonly root: string\n readonly key: string\n readonly source: ConfigSource | undefined\n readonly ignored: readonly ConfigSource[]\n}\n\n/**\n * The file in use, of the project in `folder`, checked against the file named: no code, and the\n * one named, if one is, which is a JSON file of the names, or package.json.\n */\nasync function targetOf(folder: string, { file, ...options }: WriteOptions): Promise<Target> {\n const json = jsonFilesOf(options)\n if (file !== undefined && file !== PACKAGE_JSON && !json.includes(file))\n throw new UnwritableConfigFileError(file, json)\n const { root, key, sources } = await locateConfig(folder, options)\n const [source, ...ignored] = sources\n if (source === undefined) return { root, key, source: undefined, ignored }\n if (kindOf(source.file) === 'code') throw new ConfigInCodeError(source.path, { files: json, key })\n if (file !== undefined && file !== source.file)\n throw new ConfigFileMismatchError(source.path, file)\n return { root, key, source, ignored }\n}\n\n/** How the text of a file is laid out: its indent, by the first line that has one, and its line\n * ends. Two spaces, and `\\n`, where it says nothing. */\nfunction formattingOf(text: string): FormattingOptions {\n const indent = /^([ \\t]+)\\S/m.exec(text)?.[1]\n const eol = text.includes('\\r\\n') ? '\\r\\n' : '\\n'\n if (indent === undefined) return { insertSpaces: true, tabSize: 2, eol }\n return indent.startsWith('\\t')\n ? { insertSpaces: false, tabSize: 1, eol }\n : { insertSpaces: true, tabSize: indent.length, eol }\n}\n\n/** The keys of `path` for jsonc-parser, from the top of the file: the index of a list as a\n * number. A value on the way that is no object or list is a {@link ConfigPathError}. */\nfunction keysOf(value: unknown, path: ConfigPath, shown: string): (string | number)[] {\n const keys: (string | number)[] = []\n let at: unknown = value\n for (const [index, key] of path.entries()) {\n if (at === undefined) {\n keys.push(key)\n continue\n }\n if (Array.isArray(at)) {\n if (!/^\\d+$/.test(key))\n throw new ConfigPathError(\n shown,\n `goes into ${textOfConfigPath(path.slice(0, index)) || 'the configuration'}, a list, by ${key}, which is no index.`\n )\n keys.push(Number(key))\n at = at[Number(key)]\n } else if (isObject(at)) {\n keys.push(key)\n at = Object.hasOwn(at, key) ? at[key] : undefined\n } else\n throw new ConfigPathError(\n shown,\n `goes into ${textOfConfigPath(path.slice(0, index))}, which is ${JSON.stringify(at)}, and holds no value.`\n )\n }\n return keys\n}\n\n/** The JSON of the file at `path`, and its text. */\nasync function jsonAt(\n path: string,\n files: Files\n): Promise<{ readonly text: string; readonly json: unknown }> {\n const text = (await files.text(path)) ?? ''\n try {\n return { text, json: JSON.parse(text) }\n } catch (error) {\n throw new InvalidConfigFileError(path, 'is no JSON.', { cause: error })\n }\n}\n\n/** Whether two JSON values are the same. */\nconst same = (a: unknown, b: unknown): boolean => JSON.stringify(a) === JSON.stringify(b)\n\nconst isSpace = (char: string | undefined): boolean =>\n char !== undefined && ' \\t\\r\\n'.includes(char)\n\n/** The range of `text` from `start` to `end` that a change's layout is given to: with the space on\n * each side of it, whole, and the token past that, so the space between the change and its\n * neighbours is laid out too, and no line end is cut in two. */\nfunction rangeOf(text: string, start: number, end: number): { offset: number; length: number } {\n let from = start\n while (from > 0 && isSpace(text[from - 1])) from -= 1\n let to = end\n while (to < text.length && isSpace(text[to])) to += 1\n const offset = Math.max(0, from - 1)\n return { offset, length: Math.min(text.length, to + 1) - offset }\n}\n\n/**\n * The text of `text` with `value` at `keys`, from the top of the file; `undefined` takes the value\n * away. jsonc-parser makes the change, and the layout of the file is given to what it writes, and\n * to the space beside it, and to nothing else: its own formatting of a change would lay out the\n * whole line it is on again, as an object on one line beside it.\n */\nfunction edited(text: string, keys: (string | number)[], value: unknown): string {\n // One edit, or none, of a value to take away that is not there.\n const [edit] = modify(text, keys, value, {})\n if (edit === undefined) return text\n const result = applyEdits(text, [edit])\n const range = rangeOf(result, edit.offset, edit.offset + edit.content.length)\n return applyEdits(result, format(result, range, { ...formattingOf(text), keepLines: false }))\n}\n\n/** The keys of the configuration in `file`, from the top of it: of package.json, its key. */\nconst prefixOf = (file: string, key: string): string[] => (kindOf(file) === 'package' ? [key] : [])\n\n/** Write `value`, or take it away (`undefined`), at `path` of the configuration in `source`. */\nasync function writeAt(\n target: Target & { readonly source: ConfigSource },\n path: ConfigPath,\n value: unknown,\n files: Files\n): Promise<ConfigWrite> {\n const { root, key, source, ignored } = target\n const inPackage = kindOf(source.file) === 'package'\n const { text, json } = await jsonAt(source.path, files)\n const config: unknown = inPackage && isObject(json) ? json[key] : json\n if (!isObject(config))\n throw new InvalidConfigFileError(\n source.path,\n inPackage ? `its \"${key}\" key is no JSON object.` : 'is no JSON object.'\n )\n const previous = valueAt(config, path)\n const changed = !same(previous, value)\n // A value taken away that is not there is no change, wherever the path goes.\n if (changed) {\n const keys = keysOf(config, path, textOfConfigPath(path))\n await files.write(source.path, edited(text, [...prefixOf(source.file, key), ...keys], value))\n }\n return { root, key, source, ignored, path, previous, value, changed, created: false }\n}\n\n/** A path with at least one key: the whole configuration is no value to set or unset. */\nfunction checked(path: ConfigPath): ConfigPath {\n if (path.length === 0 || path.some((key) => key === ''))\n throw new ConfigPathError(textOfConfigPath(path), 'is no path: give at least one key.')\n return path\n}\n\n/**\n * Set `value` at `path` of the configuration of the project in `folder`: in the file in use, the\n * key of package.json (the namespace by default) or a JSON file of the names\n * (`<namespace>.config.json` by default); with none, in the key, added to the package.json at the\n * root, by default, or in the JSON file `options.file` names, made. An object on the way that is\n * not there is made. Nothing is written when the value is already so.\n *\n * Throws a `ConfigInCodeError` when the configuration is code, as `<namespace>.config.ts`; a\n * `NoConfigFileError` when there is none, and no package.json at the root to hold it, and no JSON\n * file is named; a `ConfigFileMismatchError` when the file named is not the one in use; an\n * `UnwritableConfigFileError` when the file named is neither a JSON file of the names nor\n * package.json; and a `ConfigPathError` when the path goes into a value that is no object or list.\n */\nexport async function setConfigValue(\n folder: string,\n path: ConfigPath,\n value: unknown,\n options: WriteOptions\n): Promise<ConfigWrite> {\n if (value === undefined) throw new TypeError('A value of JSON is set, and not undefined.')\n checked(path)\n const { file = PACKAGE_JSON } = options\n const { namespace } = configNamesOf(options)\n const files = filesOf(options.platform)\n const target = await targetOf(folder, options)\n if (target.source !== undefined)\n return writeAt({ ...target, source: target.source }, path, value, files)\n const { root, key, ignored } = target\n const source: ConfigSource = { file, path: options.platform.path.join(root, file) }\n const keys = keysOf({}, path, textOfConfigPath(path))\n const made = { root, key, source, ignored, path, previous: undefined, value }\n if (kindOf(file) === 'json') {\n await files.write(source.path, edited('{}\\n', keys, value))\n return { ...made, changed: true, created: true }\n }\n const manifest = await files.text(source.path)\n if (manifest === undefined)\n throw new NoConfigFileError(root, { namespace, key, json: jsonFilesOf(options)[0] })\n await files.write(source.path, edited(manifest, [key, ...keys], value))\n return { ...made, changed: true, created: true }\n}\n\n/**\n * Take away the value at `path` of the configuration of the project in `folder`, in the file in\n * use: a JSON file of the names (`<namespace>.config.json` by default) or the key of package.json\n * (the namespace by default). Nothing is written when no value is there, or no configuration:\n * `changed` is false. An object it leaves empty stays. Throws a `ConfigInCodeError` when the\n * configuration is code, and a `ConfigFileMismatchError` when the file named is not the one in use.\n */\nexport async function unsetConfigValue(\n folder: string,\n path: ConfigPath,\n options: WriteOptions\n): Promise<ConfigWrite> {\n checked(path)\n const target = await targetOf(folder, options)\n const { root, key, source, ignored } = target\n if (source === undefined)\n return {\n root,\n key,\n source,\n ignored,\n path,\n previous: undefined,\n value: undefined,\n changed: false,\n created: false\n }\n return writeAt({ root, key, source, ignored }, path, undefined, filesOf(options.platform))\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@wtf/project-config",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "2.0.0",
|
|
4
4
|
"description": "Read and write a project's configuration of its tools: one object under a namespace, wtf by default, with a section for each tool, in wtf.config.{mjs,js,ts,json} or the wtf key of package.json, the first found. Find it (./locate); load it, asynchronously with code, or synchronously of JSON and package.json alone (./load); read a tool's section, checked by its Standard Schema, a JSON Schema or a function, with WTF_<SECTION>_<KEY> variables over it (./section, ./env); replace ${env:NAME} placeholders (./placeholder); get a value by its path (./path); write a value (./write); the JSON Schema of the whole (./schema); a code config, typed (./define); a value or a function named in JSON, by a name, a name with options or the export of a module, of sets merged in order (./named); Node's platform, loads and loader of modules (./node); and the errors (./errors).",
|
|
5
5
|
"homepage": "https://gitlab.com/wetryfun/project/project/-/tree/main/packages/project-config",
|
|
6
6
|
"bugs": {
|
|
@@ -81,13 +81,13 @@
|
|
|
81
81
|
"@standard-schema/spec": "^1.1.0",
|
|
82
82
|
"@wtf/platform": "^2.0.0",
|
|
83
83
|
"@wtf/platform-fs": "^1.1.0",
|
|
84
|
-
"@wtf/platform-fs-node": "^1.1.0",
|
|
85
|
-
"@wtf/platform-node": "^2.0.0",
|
|
86
84
|
"ajv": "^8.20.0",
|
|
87
85
|
"jsonc-parser": "^3.3.1"
|
|
88
86
|
},
|
|
89
87
|
"devDependencies": {
|
|
90
|
-
"@wtf/platform-fs-memory": "^1.1.0"
|
|
88
|
+
"@wtf/platform-fs-memory": "^1.1.0",
|
|
89
|
+
"@wtf/platform-fs-node": "^1.1.0",
|
|
90
|
+
"@wtf/platform-node": "^2.0.0"
|
|
91
91
|
},
|
|
92
92
|
"engines": {
|
|
93
93
|
"node": ">=24.15.0"
|