@serfab/config-check 1.8.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 +39 -0
- package/dist/checkers.d.ts +119 -0
- package/dist/checkers.js +234 -0
- package/dist/checkers.js.map +1 -0
- package/dist/env.d.ts +48 -0
- package/dist/env.js +108 -0
- package/dist/env.js.map +1 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.js +10 -0
- package/dist/index.js.map +1 -0
- package/dist/nearest-key.d.ts +6 -0
- package/dist/nearest-key.js +35 -0
- package/dist/nearest-key.js.map +1 -0
- package/dist/validate.d.ts +30 -0
- package/dist/validate.js +43 -0
- package/dist/validate.js.map +1 -0
- package/package.json +40 -0
- package/src/checkers.ts +311 -0
- package/src/env.ts +145 -0
- package/src/index.ts +10 -0
- package/src/nearest-key.ts +36 -0
- package/src/validate.ts +64 -0
package/README.md
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
# @serfab/config-check
|
|
2
|
+
|
|
3
|
+
Strict checking of a parsed config file, shared by Sereus's own packages (`@serfab/cadre-cli` and `@serfab/cadre-provider` today). It has no runtime dependencies and no Node-specific imports, so a package can use it without taking on the node's networking stack.
|
|
4
|
+
|
|
5
|
+
It is not a general-purpose schema library. It exists so that every Sereus program that reads a config file rejects unknown keys, wrong types and missing required keys the same way, reports every problem in one error, and names the source of each one: the config file, or the environment variable that wrote the offending value.
|
|
6
|
+
|
|
7
|
+
## How it is used
|
|
8
|
+
|
|
9
|
+
A config level is a *field table*: one checker per key, typed against the TypeScript type it validates, so a key added to the type without a checker fails to compile. `objectOf` turns a table into a checker; `validateTree` runs the root checker and throws one `Error` listing every problem.
|
|
10
|
+
|
|
11
|
+
```ts
|
|
12
|
+
import { applyEnvOverrides, booleanValue, nonEmptyString, objectOf, parseBooleanEnv, validateTree } from '@serfab/config-check';
|
|
13
|
+
|
|
14
|
+
interface Config { name: string; verbose?: boolean }
|
|
15
|
+
|
|
16
|
+
const root = objectOf<Config>({ name: nonEmptyString, verbose: booleanValue }, { required: ['name'] });
|
|
17
|
+
|
|
18
|
+
const { tree, provenance } = applyEnvOverrides(parsedFile, process.env, {
|
|
19
|
+
APP_VERBOSE: { path: 'verbose', parse: parseBooleanEnv },
|
|
20
|
+
});
|
|
21
|
+
const config = validateTree(tree, root, { configPath: '/etc/app.yaml', provenance });
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
For a file holding only `nmae: demo`, `validateTree` throws:
|
|
25
|
+
|
|
26
|
+
```
|
|
27
|
+
Config /etc/app.yaml: unknown key nmae (did you mean 'name'?)
|
|
28
|
+
Config /etc/app.yaml: name is required
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
With `APP_VERBOSE=yes` set, `applyEnvOverrides` throws first, from the parser: `Invalid APP_VERBOSE "yes": expected true, false, 1 or 0`. A problem is attributed to `Environment variable X` when a variable's parser accepts text that the checker then rejects, for example a plain string written where `oneOf` expects one of a closed set.
|
|
32
|
+
|
|
33
|
+
## Public functions
|
|
34
|
+
|
|
35
|
+
- `validateTree(tree, root, { configPath, provenance?, suppliersOf?, concealUnder? })` — check a whole tree; empty file = empty mapping. `concealUnder` lists key paths whose whole subtree holds hand-written secrets (cadre-provider's `push` and `billing`): a rejected value at or under one is described by kind only (`a string`, `a mapping`), never echoed.
|
|
36
|
+
- `applyEnvOverrides(raw, env, overrides, onApply?)` — write set variables over a tree without modifying it; returns the merged tree and which variable wrote which path. Empty and whitespace-only values count as unset (`specifiedEnv`).
|
|
37
|
+
- Checkers: `stringValue`, `nonEmptyString`, `secretString` (never echoes the value), `booleanValue`, `finiteNumber`, `positiveNumber`, `nonNegativeNumber`, `nonNegativeInteger`, `numberWhere`, `oneOf`, `arrayOf`, `objectOf` (with `required` and `retired` keys), `recordOf` (a mapping under caller-chosen keys such as tenant ids; a `null` value is reported, not treated as absent), `refine` (rules spanning several keys).
|
|
38
|
+
- Environment text parsers: `parseBooleanEnv`, `parseNumberEnv`, `parseListEnv`.
|
|
39
|
+
- Helpers: `ValidationContext` (for hand-written checkers — describe a rejected value through `ctx.describe(keyPath, value)` so `concealUnder` applies), `describeValue`, `kindOf`, `isPlainObject`, `isPathPrefix`, `nearestKey` (the "did you mean" suggestion).
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The checker mechanism: a problem collector and one small checker per kind of value.
|
|
3
|
+
*
|
|
4
|
+
* There is no schema library and no generic schema interpreter. Each object level is a
|
|
5
|
+
* `FieldTable<T>` — one checker per key — typed against the TypeScript type it validates, so
|
|
6
|
+
* the compiler, not a test, catches a key added to the type without a checker or a checker for
|
|
7
|
+
* a key the type lacks. The accepted-key set at runtime is the table's own keys, which is also
|
|
8
|
+
* what the unknown-key error and its typo suggestion are drawn from.
|
|
9
|
+
*/
|
|
10
|
+
/** One rejected key: where it sits, for attribution, and the operator-facing line. */
|
|
11
|
+
export interface Problem {
|
|
12
|
+
/** Dotted path of the offending key (`network.listenAddr`, `push.fcm.privateKey`; `''` is the root). */
|
|
13
|
+
keyPath: string;
|
|
14
|
+
/** The complete message, already naming the key. */
|
|
15
|
+
text: string;
|
|
16
|
+
}
|
|
17
|
+
/** Collects every problem a validation pass finds, so one start reports them all. */
|
|
18
|
+
export declare class ValidationContext {
|
|
19
|
+
private readonly suppliersOf;
|
|
20
|
+
private readonly concealUnder;
|
|
21
|
+
readonly problems: Problem[];
|
|
22
|
+
/**
|
|
23
|
+
* @param suppliersOf what, besides the config file, could supply a key — the environment
|
|
24
|
+
* variables that write `keyPath` or a key beneath it. Named in "is required" messages.
|
|
25
|
+
* @param concealUnder key paths whose whole subtree holds secrets: a rejected value at or
|
|
26
|
+
* under one is described by kind only (see {@link ValidationContext.describe}).
|
|
27
|
+
*/
|
|
28
|
+
constructor(suppliersOf?: (keyPath: string) => readonly string[], concealUnder?: readonly string[]);
|
|
29
|
+
/** Record a problem and hand back the "failed" result a checker returns. */
|
|
30
|
+
fail(keyPath: string, text: string): undefined;
|
|
31
|
+
/** Record a required key that is absent, naming the variable(s) that could supply it. */
|
|
32
|
+
missing(keyPath: string, condition?: string): undefined;
|
|
33
|
+
/**
|
|
34
|
+
* How a rejected value at `keyPath` is shown in a message: {@link describeValue}'s echo,
|
|
35
|
+
* unless the key is at or under a `concealUnder` prefix, where a private key pasted in the
|
|
36
|
+
* wrong place (`push.fcm: "-----BEGIN PRIVATE KEY…"`) must not be echoed — then its kind only.
|
|
37
|
+
* Every checker in this package describes values through here, so a hand-written checker
|
|
38
|
+
* should too.
|
|
39
|
+
*/
|
|
40
|
+
describe(keyPath: string, value: unknown): string;
|
|
41
|
+
}
|
|
42
|
+
/** Whether `keyPath` is `prefix` itself or a key beneath it (`a.b` is under `a`; `ab` is not). */
|
|
43
|
+
export declare function isPathPrefix(prefix: string, keyPath: string): boolean;
|
|
44
|
+
/**
|
|
45
|
+
* Checks one value at `keyPath`. Returns the accepted, typed value, or `undefined` after
|
|
46
|
+
* recording why on `ctx`. `undefined` is never a valid config value, so it is free to mean
|
|
47
|
+
* "failed".
|
|
48
|
+
*/
|
|
49
|
+
export interface Checker<T> {
|
|
50
|
+
(value: unknown, keyPath: string, ctx: ValidationContext): T | undefined;
|
|
51
|
+
/**
|
|
52
|
+
* Set on checkers built by {@link objectOf} and {@link recordOf}: a `null` at this key means
|
|
53
|
+
* the block is absent. YAML `network:` with every child commented out parses to `null`, and
|
|
54
|
+
* cadre-cli's Docker entrypoint writes exactly that when no address variable is set. A `null`
|
|
55
|
+
* leaf, by contrast, is ill-typed.
|
|
56
|
+
*/
|
|
57
|
+
readonly nullIsAbsent?: true;
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* One checker per key of `T` — the compile-time drift guard. A key added to `T` without a
|
|
61
|
+
* checker fails to compile here; a checker for a key `T` lacks is an excess property.
|
|
62
|
+
*/
|
|
63
|
+
export type FieldTable<T> = {
|
|
64
|
+
[K in keyof T]-?: Checker<NonNullable<T[K]>>;
|
|
65
|
+
};
|
|
66
|
+
export interface ObjectOptions<T> {
|
|
67
|
+
/** Keys that must be present (and, for object-typed keys, not `null`). */
|
|
68
|
+
required?: readonly (keyof T & string)[];
|
|
69
|
+
/** Keys no longer accepted, each with the message that says what replaced it. */
|
|
70
|
+
retired?: ReadonlyMap<string, string>;
|
|
71
|
+
}
|
|
72
|
+
export declare function isPlainObject(value: unknown): value is Record<string, unknown>;
|
|
73
|
+
/** What kind of thing a value is, for a message that must not echo its contents. */
|
|
74
|
+
export declare function kindOf(value: unknown): string;
|
|
75
|
+
/**
|
|
76
|
+
* How a rejected value is shown: scalars in full (long strings cut), containers by kind only.
|
|
77
|
+
*
|
|
78
|
+
* NOTE: a secret pasted where a scalar belongs (`push.fcm: "-----BEGIN PRIVATE KEY..."`) would be
|
|
79
|
+
* echoed by the "must be a mapping" message. The `privateKey` fields themselves go through
|
|
80
|
+
* {@link secretString}, which never shows the value; for a whole subtree that is hand-written
|
|
81
|
+
* and holds secrets, `validateTree`'s `concealUnder` option describes every value under it by
|
|
82
|
+
* kind only (cadre-provider lists `push` and `billing`). cadre-cli has not opted in: its `push`
|
|
83
|
+
* block is written by an orchestrator, not by hand.
|
|
84
|
+
*/
|
|
85
|
+
export declare function describeValue(value: unknown): string;
|
|
86
|
+
export declare const stringValue: Checker<string>;
|
|
87
|
+
export declare const nonEmptyString: Checker<string>;
|
|
88
|
+
/** A string whose value is a secret: the message says only what kind of thing arrived instead. */
|
|
89
|
+
export declare const secretString: Checker<string>;
|
|
90
|
+
export declare const booleanValue: Checker<boolean>;
|
|
91
|
+
/** A finite number `accepts` admits; `expected` completes "must be …" in the message. */
|
|
92
|
+
export declare function numberWhere(accepts: (n: number) => boolean, expected: string): Checker<number>;
|
|
93
|
+
export declare const finiteNumber: Checker<number>;
|
|
94
|
+
export declare const positiveNumber: Checker<number>;
|
|
95
|
+
export declare const nonNegativeNumber: Checker<number>;
|
|
96
|
+
export declare const nonNegativeInteger: Checker<number>;
|
|
97
|
+
/**
|
|
98
|
+
* One of a closed set of strings. The set is written as an object with every member as a
|
|
99
|
+
* key, so it is checked against the union type: `oneOf<NodeProfile>({ transaction: true,
|
|
100
|
+
* storage: true })` stops compiling when cadre-core adds a profile or drops one.
|
|
101
|
+
*/
|
|
102
|
+
export declare function oneOf<T extends string>(members: Record<T, true>): Checker<T>;
|
|
103
|
+
export declare function arrayOf<T>(item: Checker<T>): Checker<T[]>;
|
|
104
|
+
/**
|
|
105
|
+
* A mapping whose every key is checked by `fields`. Keys outside the table are rejected —
|
|
106
|
+
* with the retired-key message when one applies, else with the nearest accepted key as a
|
|
107
|
+
* suggestion. Absent keys are skipped unless `required`; a `null` under an object-typed key
|
|
108
|
+
* counts as absent (see {@link Checker.nullIsAbsent}).
|
|
109
|
+
*/
|
|
110
|
+
export declare function objectOf<T extends object>(fields: FieldTable<T>, opts?: ObjectOptions<T>): Checker<T>;
|
|
111
|
+
/**
|
|
112
|
+
* A mapping whose keys are the operator's own (cadre-provider's tenant ids), each value checked
|
|
113
|
+
* by `value` at `<keyPath>.<key>`. An empty or blank key is a problem. Unlike a key in an
|
|
114
|
+
* {@link objectOf} table, a `null` value is not an absent block: `tenants: { acme: }` is
|
|
115
|
+
* reported, because treating it as absent would silently hand that tenant the defaults.
|
|
116
|
+
*/
|
|
117
|
+
export declare function recordOf<T>(value: Checker<T>): Checker<Record<string, T>>;
|
|
118
|
+
/** Run `check` over a value `base` accepted — for a rule that spans more than one key. */
|
|
119
|
+
export declare function refine<T>(base: Checker<T>, check: (value: T, keyPath: string, ctx: ValidationContext) => T | undefined): Checker<T>;
|
package/dist/checkers.js
ADDED
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The checker mechanism: a problem collector and one small checker per kind of value.
|
|
3
|
+
*
|
|
4
|
+
* There is no schema library and no generic schema interpreter. Each object level is a
|
|
5
|
+
* `FieldTable<T>` — one checker per key — typed against the TypeScript type it validates, so
|
|
6
|
+
* the compiler, not a test, catches a key added to the type without a checker or a checker for
|
|
7
|
+
* a key the type lacks. The accepted-key set at runtime is the table's own keys, which is also
|
|
8
|
+
* what the unknown-key error and its typo suggestion are drawn from.
|
|
9
|
+
*/
|
|
10
|
+
import { nearestKey } from './nearest-key.js';
|
|
11
|
+
/** Collects every problem a validation pass finds, so one start reports them all. */
|
|
12
|
+
export class ValidationContext {
|
|
13
|
+
/**
|
|
14
|
+
* @param suppliersOf what, besides the config file, could supply a key — the environment
|
|
15
|
+
* variables that write `keyPath` or a key beneath it. Named in "is required" messages.
|
|
16
|
+
* @param concealUnder key paths whose whole subtree holds secrets: a rejected value at or
|
|
17
|
+
* under one is described by kind only (see {@link ValidationContext.describe}).
|
|
18
|
+
*/
|
|
19
|
+
constructor(suppliersOf = () => [], concealUnder = []) {
|
|
20
|
+
this.suppliersOf = suppliersOf;
|
|
21
|
+
this.concealUnder = concealUnder;
|
|
22
|
+
this.problems = [];
|
|
23
|
+
}
|
|
24
|
+
/** Record a problem and hand back the "failed" result a checker returns. */
|
|
25
|
+
fail(keyPath, text) {
|
|
26
|
+
this.problems.push({ keyPath, text });
|
|
27
|
+
return undefined;
|
|
28
|
+
}
|
|
29
|
+
/** Record a required key that is absent, naming the variable(s) that could supply it. */
|
|
30
|
+
missing(keyPath, condition) {
|
|
31
|
+
const variables = this.suppliersOf(keyPath);
|
|
32
|
+
const hint = variables.length > 0 ? ` (or set ${variables.join(' and ')})` : '';
|
|
33
|
+
return this.fail(keyPath, `${keyPath} is required${condition ? ` ${condition}` : ''}${hint}`);
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* How a rejected value at `keyPath` is shown in a message: {@link describeValue}'s echo,
|
|
37
|
+
* unless the key is at or under a `concealUnder` prefix, where a private key pasted in the
|
|
38
|
+
* wrong place (`push.fcm: "-----BEGIN PRIVATE KEY…"`) must not be echoed — then its kind only.
|
|
39
|
+
* Every checker in this package describes values through here, so a hand-written checker
|
|
40
|
+
* should too.
|
|
41
|
+
*/
|
|
42
|
+
describe(keyPath, value) {
|
|
43
|
+
const concealed = this.concealUnder.some((prefix) => isPathPrefix(prefix, keyPath));
|
|
44
|
+
return concealed ? kindOf(value) : describeValue(value);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
/** Whether `keyPath` is `prefix` itself or a key beneath it (`a.b` is under `a`; `ab` is not). */
|
|
48
|
+
export function isPathPrefix(prefix, keyPath) {
|
|
49
|
+
return keyPath === prefix || keyPath.startsWith(`${prefix}.`) || keyPath.startsWith(`${prefix}[`);
|
|
50
|
+
}
|
|
51
|
+
export function isPlainObject(value) {
|
|
52
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value))
|
|
53
|
+
return false;
|
|
54
|
+
const proto = Object.getPrototypeOf(value);
|
|
55
|
+
return proto === Object.prototype || proto === null;
|
|
56
|
+
}
|
|
57
|
+
/** What kind of thing a value is, for a message that must not echo its contents. */
|
|
58
|
+
export function kindOf(value) {
|
|
59
|
+
if (value === null)
|
|
60
|
+
return 'null';
|
|
61
|
+
if (Array.isArray(value))
|
|
62
|
+
return 'a list';
|
|
63
|
+
if (value instanceof Date)
|
|
64
|
+
return 'a date';
|
|
65
|
+
if (typeof value === 'object')
|
|
66
|
+
return 'a mapping';
|
|
67
|
+
return `a ${typeof value}`;
|
|
68
|
+
}
|
|
69
|
+
/** A string echoed in a message is cut here: enough to recognise a typo, not a pasted file. */
|
|
70
|
+
const MAX_ECHOED_CHARS = 120;
|
|
71
|
+
/**
|
|
72
|
+
* How a rejected value is shown: scalars in full (long strings cut), containers by kind only.
|
|
73
|
+
*
|
|
74
|
+
* NOTE: a secret pasted where a scalar belongs (`push.fcm: "-----BEGIN PRIVATE KEY..."`) would be
|
|
75
|
+
* echoed by the "must be a mapping" message. The `privateKey` fields themselves go through
|
|
76
|
+
* {@link secretString}, which never shows the value; for a whole subtree that is hand-written
|
|
77
|
+
* and holds secrets, `validateTree`'s `concealUnder` option describes every value under it by
|
|
78
|
+
* kind only (cadre-provider lists `push` and `billing`). cadre-cli has not opted in: its `push`
|
|
79
|
+
* block is written by an orchestrator, not by hand.
|
|
80
|
+
*/
|
|
81
|
+
export function describeValue(value) {
|
|
82
|
+
if (typeof value === 'string') {
|
|
83
|
+
return value.length > MAX_ECHOED_CHARS
|
|
84
|
+
? `${JSON.stringify(value.slice(0, MAX_ECHOED_CHARS))}… (${value.length} characters)`
|
|
85
|
+
: JSON.stringify(value);
|
|
86
|
+
}
|
|
87
|
+
if (typeof value === 'number' || typeof value === 'boolean')
|
|
88
|
+
return String(value);
|
|
89
|
+
return kindOf(value);
|
|
90
|
+
}
|
|
91
|
+
export const stringValue = (value, keyPath, ctx) => typeof value === 'string'
|
|
92
|
+
? value
|
|
93
|
+
: ctx.fail(keyPath, `${keyPath} must be a string, got ${ctx.describe(keyPath, value)}`);
|
|
94
|
+
export const nonEmptyString = (value, keyPath, ctx) => typeof value === 'string' && value.trim() !== ''
|
|
95
|
+
? value
|
|
96
|
+
: ctx.fail(keyPath, `${keyPath} must be a non-empty string, got ${ctx.describe(keyPath, value)}`);
|
|
97
|
+
/** A string whose value is a secret: the message says only what kind of thing arrived instead. */
|
|
98
|
+
export const secretString = (value, keyPath, ctx) => typeof value === 'string'
|
|
99
|
+
? value
|
|
100
|
+
: ctx.fail(keyPath, `${keyPath} must be a string, got ${kindOf(value)}`);
|
|
101
|
+
export const booleanValue = (value, keyPath, ctx) => typeof value === 'boolean'
|
|
102
|
+
? value
|
|
103
|
+
: ctx.fail(keyPath, `${keyPath} must be a boolean (true or false), got ${ctx.describe(keyPath, value)}`);
|
|
104
|
+
/** A finite number `accepts` admits; `expected` completes "must be …" in the message. */
|
|
105
|
+
export function numberWhere(accepts, expected) {
|
|
106
|
+
return (value, keyPath, ctx) => typeof value === 'number' && Number.isFinite(value) && accepts(value)
|
|
107
|
+
? value
|
|
108
|
+
: ctx.fail(keyPath, `${keyPath} must be ${expected}, got ${ctx.describe(keyPath, value)}`);
|
|
109
|
+
}
|
|
110
|
+
export const finiteNumber = numberWhere(() => true, 'a number');
|
|
111
|
+
export const positiveNumber = numberWhere((n) => n > 0, 'a number above zero');
|
|
112
|
+
export const nonNegativeNumber = numberWhere((n) => n >= 0, 'a number of zero or more');
|
|
113
|
+
export const nonNegativeInteger = numberWhere((n) => Number.isSafeInteger(n) && n >= 0, 'a whole number of zero or more');
|
|
114
|
+
/**
|
|
115
|
+
* One of a closed set of strings. The set is written as an object with every member as a
|
|
116
|
+
* key, so it is checked against the union type: `oneOf<NodeProfile>({ transaction: true,
|
|
117
|
+
* storage: true })` stops compiling when cadre-core adds a profile or drops one.
|
|
118
|
+
*/
|
|
119
|
+
export function oneOf(members) {
|
|
120
|
+
const values = Object.keys(members);
|
|
121
|
+
const list = values.map((v) => `'${v}'`).join(', ');
|
|
122
|
+
return (value, keyPath, ctx) => typeof value === 'string' && values.includes(value)
|
|
123
|
+
? value
|
|
124
|
+
: ctx.fail(keyPath, `${keyPath} must be one of ${list}, got ${ctx.describe(keyPath, value)}`);
|
|
125
|
+
}
|
|
126
|
+
export function arrayOf(item) {
|
|
127
|
+
return (value, keyPath, ctx) => {
|
|
128
|
+
if (!Array.isArray(value)) {
|
|
129
|
+
return ctx.fail(keyPath, `${keyPath} must be a list, got ${ctx.describe(keyPath, value)}`);
|
|
130
|
+
}
|
|
131
|
+
const before = ctx.problems.length;
|
|
132
|
+
const out = value.map((entry, i) => item(entry, `${keyPath}[${i}]`, ctx));
|
|
133
|
+
return ctx.problems.length === before ? out : undefined;
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* A mapping whose every key is checked by `fields`. Keys outside the table are rejected —
|
|
138
|
+
* with the retired-key message when one applies, else with the nearest accepted key as a
|
|
139
|
+
* suggestion. Absent keys are skipped unless `required`; a `null` under an object-typed key
|
|
140
|
+
* counts as absent (see {@link Checker.nullIsAbsent}).
|
|
141
|
+
*/
|
|
142
|
+
export function objectOf(fields, opts = {}) {
|
|
143
|
+
const table = fields;
|
|
144
|
+
const accepted = Object.keys(table);
|
|
145
|
+
const required = new Set(opts.required ?? []);
|
|
146
|
+
const retired = opts.retired ?? new Map();
|
|
147
|
+
const checker = (value, keyPath, ctx) => {
|
|
148
|
+
if (!isPlainObject(value)) {
|
|
149
|
+
return ctx.fail(keyPath, `${keyPath} must be a mapping of keys, got ${ctx.describe(keyPath, value)}`);
|
|
150
|
+
}
|
|
151
|
+
const before = ctx.problems.length;
|
|
152
|
+
for (const key of Object.keys(value)) {
|
|
153
|
+
if (!accepted.includes(key))
|
|
154
|
+
rejectKey(joinPath(keyPath, key), key, accepted, retired, ctx);
|
|
155
|
+
}
|
|
156
|
+
const out = {};
|
|
157
|
+
for (const key of accepted) {
|
|
158
|
+
const child = value[key];
|
|
159
|
+
const childPath = joinPath(keyPath, key);
|
|
160
|
+
const field = table[key];
|
|
161
|
+
if (child === undefined || (child === null && field.nullIsAbsent)) {
|
|
162
|
+
if (required.has(key))
|
|
163
|
+
reportMissing(field, childPath, ctx);
|
|
164
|
+
continue;
|
|
165
|
+
}
|
|
166
|
+
const checked = field(child, childPath, ctx);
|
|
167
|
+
if (checked !== undefined)
|
|
168
|
+
out[key] = checked;
|
|
169
|
+
}
|
|
170
|
+
return ctx.problems.length === before ? out : undefined;
|
|
171
|
+
};
|
|
172
|
+
return Object.assign(checker, { nullIsAbsent: true });
|
|
173
|
+
}
|
|
174
|
+
/**
|
|
175
|
+
* A mapping whose keys are the operator's own (cadre-provider's tenant ids), each value checked
|
|
176
|
+
* by `value` at `<keyPath>.<key>`. An empty or blank key is a problem. Unlike a key in an
|
|
177
|
+
* {@link objectOf} table, a `null` value is not an absent block: `tenants: { acme: }` is
|
|
178
|
+
* reported, because treating it as absent would silently hand that tenant the defaults.
|
|
179
|
+
*/
|
|
180
|
+
export function recordOf(value) {
|
|
181
|
+
const checker = (raw, keyPath, ctx) => {
|
|
182
|
+
if (!isPlainObject(raw)) {
|
|
183
|
+
return ctx.fail(keyPath, `${keyPath} must be a mapping of keys, got ${ctx.describe(keyPath, raw)}`);
|
|
184
|
+
}
|
|
185
|
+
const before = ctx.problems.length;
|
|
186
|
+
const out = {};
|
|
187
|
+
for (const [key, entry] of Object.entries(raw)) {
|
|
188
|
+
if (key.trim() === '') {
|
|
189
|
+
ctx.fail(keyPath, `${keyPath} has an empty key`);
|
|
190
|
+
continue;
|
|
191
|
+
}
|
|
192
|
+
const checked = value(entry, joinPath(keyPath, key), ctx);
|
|
193
|
+
if (checked !== undefined)
|
|
194
|
+
out[key] = checked;
|
|
195
|
+
}
|
|
196
|
+
return ctx.problems.length === before ? out : undefined;
|
|
197
|
+
};
|
|
198
|
+
return Object.assign(checker, { nullIsAbsent: true });
|
|
199
|
+
}
|
|
200
|
+
/** Run `check` over a value `base` accepted — for a rule that spans more than one key. */
|
|
201
|
+
export function refine(base, check) {
|
|
202
|
+
const checker = (value, keyPath, ctx) => {
|
|
203
|
+
const accepted = base(value, keyPath, ctx);
|
|
204
|
+
return accepted === undefined ? undefined : check(accepted, keyPath, ctx);
|
|
205
|
+
};
|
|
206
|
+
return base.nullIsAbsent ? Object.assign(checker, { nullIsAbsent: true }) : checker;
|
|
207
|
+
}
|
|
208
|
+
function joinPath(parent, key) {
|
|
209
|
+
return parent === '' ? key : `${parent}.${key}`;
|
|
210
|
+
}
|
|
211
|
+
function rejectKey(keyPath, key, accepted, retired, ctx) {
|
|
212
|
+
const replacement = retired.get(key);
|
|
213
|
+
if (replacement !== undefined) {
|
|
214
|
+
ctx.fail(keyPath, `${keyPath} is no longer supported — ${replacement}`);
|
|
215
|
+
return;
|
|
216
|
+
}
|
|
217
|
+
const nearest = nearestKey(key, accepted);
|
|
218
|
+
ctx.fail(keyPath, `unknown key ${keyPath}${nearest ? ` (did you mean '${nearest}'?)` : ''}`);
|
|
219
|
+
}
|
|
220
|
+
/**
|
|
221
|
+
* A required block that is absent is reported through its own required children when it has
|
|
222
|
+
* any — `controlNetwork.partyId is required (or set CADRE_PARTY_ID)` tells the operator more
|
|
223
|
+
* than `controlNetwork is required` — and as itself otherwise.
|
|
224
|
+
*/
|
|
225
|
+
function reportMissing(field, keyPath, ctx) {
|
|
226
|
+
if (field.nullIsAbsent) {
|
|
227
|
+
const before = ctx.problems.length;
|
|
228
|
+
field({}, keyPath, ctx);
|
|
229
|
+
if (ctx.problems.length > before)
|
|
230
|
+
return;
|
|
231
|
+
}
|
|
232
|
+
ctx.missing(keyPath);
|
|
233
|
+
}
|
|
234
|
+
//# sourceMappingURL=checkers.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"checkers.js","sourceRoot":"","sources":["../src/checkers.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAc9C,qFAAqF;AACrF,MAAM,OAAO,iBAAiB;IAG5B;;;;;OAKG;IACH,YACmB,cAAsD,GAAG,EAAE,CAAC,EAAE,EAC9D,eAAkC,EAAE;QADpC,gBAAW,GAAX,WAAW,CAAmD;QAC9D,iBAAY,GAAZ,YAAY,CAAwB;QAV9C,aAAQ,GAAc,EAAE,CAAC;IAW/B,CAAC;IAEJ,4EAA4E;IAC5E,IAAI,CAAC,OAAe,EAAE,IAAY;QAChC,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC;QACtC,OAAO,SAAS,CAAC;IACnB,CAAC;IAED,yFAAyF;IACzF,OAAO,CAAC,OAAe,EAAE,SAAkB;QACzC,MAAM,SAAS,GAAG,IAAI,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;QAC5C,MAAM,IAAI,GAAG,SAAS,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,YAAY,SAAS,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC;QAChF,OAAO,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,GAAG,OAAO,eAAe,SAAS,CAAC,CAAC,CAAC,IAAI,SAAS,EAAE,CAAC,CAAC,CAAC,EAAE,GAAG,IA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|
3
|
+
*
|
|
4
|
+
* The caller owns the variable names and what each one writes (an {@link EnvOverride} per
|
|
5
|
+
* variable); this module owns how a write lands: which values count as set, how a dotted path is
|
|
6
|
+
* written without touching the caller's objects, and the record of which variable wrote which
|
|
7
|
+
* path, so `validateTree` can blame the variable rather than the file.
|
|
8
|
+
*/
|
|
9
|
+
export interface EnvOverride {
|
|
10
|
+
/** Dotted config path the variable writes, over whatever the config file says there. */
|
|
11
|
+
readonly path: string;
|
|
12
|
+
/** Text → value written at `path`; throws naming `name` when the text cannot be read. */
|
|
13
|
+
readonly parse: (text: string, name: string) => unknown;
|
|
14
|
+
}
|
|
15
|
+
/** What {@link applyEnvOverrides} produces: the merged tree and a record of what the environment wrote. */
|
|
16
|
+
export interface OverrideResult {
|
|
17
|
+
/** The file's tree with every set variable written over it. Unchecked. */
|
|
18
|
+
tree: unknown;
|
|
19
|
+
/**
|
|
20
|
+
* Dotted config path → the variable that wrote it (cadre-cli: `network.listenAddrs → CADRE_LISTEN_ADDRS`,
|
|
21
|
+
* `push → CADRE_PUSH`), so the validator attributes a problem under that path to the
|
|
22
|
+
* variable rather than to the file. A skipped (empty) variable records nothing.
|
|
23
|
+
*/
|
|
24
|
+
provenance: ReadonlyMap<string, string>;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* The variable's value, or `undefined` when it is not specified. An empty or whitespace-only
|
|
28
|
+
* value counts as not specified: a docker-compose default like cadre-cli's `${CADRE_ENABLE_RELAY:-}` must
|
|
29
|
+
* leave the config file's value (or the profile default) alone, and a variable set that way is
|
|
30
|
+
* not checked by name either.
|
|
31
|
+
*/
|
|
32
|
+
export declare function specifiedEnv(value: string | undefined): string | undefined;
|
|
33
|
+
/**
|
|
34
|
+
* Write every specified variable in `overrides` over `raw`, in the table's order. `raw` itself
|
|
35
|
+
* is not modified. `onApply` sees each variable about to be written, for logging; the text may
|
|
36
|
+
* be a secret.
|
|
37
|
+
*/
|
|
38
|
+
export declare function applyEnvOverrides(raw: unknown, env: Readonly<Record<string, string | undefined>>, overrides: Readonly<Record<string, EnvOverride>>, onApply?: (variable: string, text: string) => void): OverrideResult;
|
|
39
|
+
/**
|
|
40
|
+
* A comma-separated list, each entry trimmed, empty entries dropped.
|
|
41
|
+
*
|
|
42
|
+
* NOTE: a separators-only value (e.g. `,`) survives the empty check but yields [], clobbering
|
|
43
|
+
* the file's list. If that shape ever shows up in a real launcher, treat an all-empty split as
|
|
44
|
+
* unspecified here too.
|
|
45
|
+
*/
|
|
46
|
+
export declare function parseListEnv(text: string): string[];
|
|
47
|
+
export declare function parseBooleanEnv(text: string, name: string): boolean;
|
|
48
|
+
export declare function parseNumberEnv(text: string, name: string): number;
|
package/dist/env.js
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Writing environment variables over a parsed config tree, before the tree is checked.
|
|
3
|
+
*
|
|
4
|
+
* The caller owns the variable names and what each one writes (an {@link EnvOverride} per
|
|
5
|
+
* variable); this module owns how a write lands: which values count as set, how a dotted path is
|
|
6
|
+
* written without touching the caller's objects, and the record of which variable wrote which
|
|
7
|
+
* path, so `validateTree` can blame the variable rather than the file.
|
|
8
|
+
*/
|
|
9
|
+
import { describeValue, isPlainObject } from './checkers.js';
|
|
10
|
+
/**
|
|
11
|
+
* The variable's value, or `undefined` when it is not specified. An empty or whitespace-only
|
|
12
|
+
* value counts as not specified: a docker-compose default like cadre-cli's `${CADRE_ENABLE_RELAY:-}` must
|
|
13
|
+
* leave the config file's value (or the profile default) alone, and a variable set that way is
|
|
14
|
+
* not checked by name either.
|
|
15
|
+
*/
|
|
16
|
+
export function specifiedEnv(value) {
|
|
17
|
+
return value === undefined || value.trim() === '' ? undefined : value;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Write every specified variable in `overrides` over `raw`, in the table's order. `raw` itself
|
|
21
|
+
* is not modified. `onApply` sees each variable about to be written, for logging; the text may
|
|
22
|
+
* be a secret.
|
|
23
|
+
*/
|
|
24
|
+
export function applyEnvOverrides(raw, env, overrides, onApply) {
|
|
25
|
+
const provenance = new Map();
|
|
26
|
+
// An empty file parses to undefined/null: an empty mapping the environment may fill. Any
|
|
27
|
+
// other non-mapping root is left for the validator to reject by name — nothing can be
|
|
28
|
+
// written over it.
|
|
29
|
+
const base = raw ?? {};
|
|
30
|
+
if (!isPlainObject(base))
|
|
31
|
+
return { tree: raw, provenance };
|
|
32
|
+
const result = { ...base };
|
|
33
|
+
for (const [variable, { path, parse }] of Object.entries(overrides)) {
|
|
34
|
+
const text = specifiedEnv(env[variable]);
|
|
35
|
+
if (text === undefined)
|
|
36
|
+
continue;
|
|
37
|
+
onApply?.(variable, text);
|
|
38
|
+
setNestedValue(result, path, parse(text, variable), variable);
|
|
39
|
+
provenance.set(path, variable);
|
|
40
|
+
}
|
|
41
|
+
return { tree: result, provenance };
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Write `value` at a dotted path, copying each intermediate object on the way
|
|
45
|
+
* down. {@link applyEnvOverrides} only shallow-copies its input, so
|
|
46
|
+
* writing straight through would mutate the caller's own nested objects (e.g. a
|
|
47
|
+
* shared `network` block) rather than only the returned config.
|
|
48
|
+
*/
|
|
49
|
+
function setNestedValue(obj, pathStr, value, envVar) {
|
|
50
|
+
const parts = pathStr.split('.');
|
|
51
|
+
let current = obj;
|
|
52
|
+
for (let i = 0; i < parts.length - 1; i++) {
|
|
53
|
+
const branch = cloneBranch(current[parts[i]], parts.slice(0, i + 1).join('.'), envVar);
|
|
54
|
+
current[parts[i]] = branch;
|
|
55
|
+
current = branch;
|
|
56
|
+
}
|
|
57
|
+
current[parts[parts.length - 1]] = value;
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Shallow-copy an intermediate config object. Absent or `null` (YAML `storage:` with no
|
|
61
|
+
* children) starts a fresh block. Anything else in the way — `storage: file` where a block
|
|
62
|
+
* belongs — is a file error the variable must not paper over by replacing it with `{}`.
|
|
63
|
+
*/
|
|
64
|
+
function cloneBranch(existing, keyPath, envVar) {
|
|
65
|
+
if (existing === undefined || existing === null)
|
|
66
|
+
return {};
|
|
67
|
+
if (isPlainObject(existing))
|
|
68
|
+
return { ...existing };
|
|
69
|
+
// NOTE: this echoes the scalar in the way, before validation and so before `concealUnder`
|
|
70
|
+
// applies. A secret can reach it only when the file puts one where a block belongs AND a
|
|
71
|
+
// variable writes under that block (cadre-provider: `billing: sk_live_…` plus
|
|
72
|
+
// STRIPE_SECRET_KEY). If that ever shows up in a real report, take a conceal list here too.
|
|
73
|
+
throw new Error(`Cannot apply ${envVar}: config key ${keyPath} is ${describeValue(existing)} where a mapping of keys was expected`);
|
|
74
|
+
}
|
|
75
|
+
// ---------------------------------------------------------------------------
|
|
76
|
+
// Value parsers for `EnvOverride.parse`; `text` is never empty (see specifiedEnv)
|
|
77
|
+
// ---------------------------------------------------------------------------
|
|
78
|
+
/**
|
|
79
|
+
* A comma-separated list, each entry trimmed, empty entries dropped.
|
|
80
|
+
*
|
|
81
|
+
* NOTE: a separators-only value (e.g. `,`) survives the empty check but yields [], clobbering
|
|
82
|
+
* the file's list. If that shape ever shows up in a real launcher, treat an all-empty split as
|
|
83
|
+
* unspecified here too.
|
|
84
|
+
*/
|
|
85
|
+
export function parseListEnv(text) {
|
|
86
|
+
return text.split(',').map((s) => s.trim()).filter(Boolean);
|
|
87
|
+
}
|
|
88
|
+
const BOOLEAN_SPELLINGS = new Map([
|
|
89
|
+
['true', true],
|
|
90
|
+
['1', true],
|
|
91
|
+
['false', false],
|
|
92
|
+
['0', false],
|
|
93
|
+
]);
|
|
94
|
+
export function parseBooleanEnv(text, name) {
|
|
95
|
+
const parsed = BOOLEAN_SPELLINGS.get(text.trim().toLowerCase());
|
|
96
|
+
if (parsed === undefined) {
|
|
97
|
+
throw new Error(`Invalid ${name} ${JSON.stringify(text)}: expected true, false, 1 or 0`);
|
|
98
|
+
}
|
|
99
|
+
return parsed;
|
|
100
|
+
}
|
|
101
|
+
export function parseNumberEnv(text, name) {
|
|
102
|
+
const parsed = Number(text.trim());
|
|
103
|
+
if (!Number.isFinite(parsed)) {
|
|
104
|
+
throw new Error(`Invalid ${name} ${JSON.stringify(text)}: expected a number`);
|
|
105
|
+
}
|
|
106
|
+
return parsed;
|
|
107
|
+
}
|
|
108
|
+
//# sourceMappingURL=env.js.map
|
package/dist/env.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"env.js","sourceRoot":"","sources":["../src/env.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AAqB7D;;;;;GAKG;AACH,MAAM,UAAU,YAAY,CAAC,KAAyB;IACpD,OAAO,KAAK,KAAK,SAAS,IAAI,KAAK,CAAC,IAAI,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,KAAK,CAAC;AACxE,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,iBAAiB,CAC/B,GAAY,EACZ,GAAiD,EACjD,SAAgD,EAChD,OAAkD;IAElD,MAAM,UAAU,GAAG,IAAI,GAAG,EAAkB,CAAC;IAE7C,yFAAyF;IACzF,sFAAsF;IACtF,mBAAmB;IACnB,MAAM,IAAI,GAAG,GAAG,IAAI,EAAE,CAAC;IACvB,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC;QAAE,OAAO,EAAE,IAAI,EAAE,GAAG,EAAE,UAAU,EAAE,CAAC;IAC3D,MAAM,MAAM,GAA4B,EAAE,GAAG,IAAI,EAAE,CAAC;IAEpD,KAAK,MAAM,CAAC,QAAQ,EAAE,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,SAAS,CAAC,EAAE,CAAC;QACpE,MAAM,IAAI,GAAG,YAAY,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC,CAAC;QACzC,IAAI,IAAI,KAAK,SAAS;YAAE,SAAS;QAEjC,OA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C,WAAW,IAAI,IAAI,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,qBAAqB,CAAC,CAAC;IAChF,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC"}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @serfab/config-check — strict checking of a parsed config tree, with environment-variable
|
|
3
|
+
* overrides written over it first. Dependency-free and runtime-neutral, so every Sereus package
|
|
4
|
+
* that reads a config file can share one set of rules and one message format.
|
|
5
|
+
*/
|
|
6
|
+
export * from './checkers.js';
|
|
7
|
+
export * from './env.js';
|
|
8
|
+
export { nearestKey } from './nearest-key.js';
|
|
9
|
+
export { type ValidateOptions, validateTree } from './validate.js';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @serfab/config-check — strict checking of a parsed config tree, with environment-variable
|
|
3
|
+
* overrides written over it first. Dependency-free and runtime-neutral, so every Sereus package
|
|
4
|
+
* that reads a config file can share one set of rules and one message format.
|
|
5
|
+
*/
|
|
6
|
+
export * from './checkers.js';
|
|
7
|
+
export * from './env.js';
|
|
8
|
+
export { nearestKey } from './nearest-key.js';
|
|
9
|
+
export { validateTree } from './validate.js';
|
|
10
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,cAAc,eAAe,CAAC;AAC9B,cAAc,UAAU,CAAC;AACzB,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAC9C,OAAO,EAAwB,YAAY,EAAE,MAAM,eAAe,CAAC"}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The "did you mean" suggestion shared by `objectOf`'s unknown-key message and any caller's own
|
|
3
|
+
* name check (cadre-cli's unknown `CADRE_*` variables).
|
|
4
|
+
*/
|
|
5
|
+
/** The accepted name a typo most likely meant: a case-insensitive match, else within two edits. */
|
|
6
|
+
export declare function nearestKey(key: string, accepted: readonly string[]): string | undefined;
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The "did you mean" suggestion shared by `objectOf`'s unknown-key message and any caller's own
|
|
3
|
+
* name check (cadre-cli's unknown `CADRE_*` variables).
|
|
4
|
+
*/
|
|
5
|
+
/** The accepted name a typo most likely meant: a case-insensitive match, else within two edits. */
|
|
6
|
+
export function nearestKey(key, accepted) {
|
|
7
|
+
const lower = key.toLowerCase();
|
|
8
|
+
const byCase = accepted.find((candidate) => candidate.toLowerCase() === lower);
|
|
9
|
+
if (byCase !== undefined)
|
|
10
|
+
return byCase;
|
|
11
|
+
let nearest;
|
|
12
|
+
let nearestDistance = 3;
|
|
13
|
+
for (const candidate of accepted) {
|
|
14
|
+
const distance = editDistance(key, candidate);
|
|
15
|
+
if (distance < nearestDistance) {
|
|
16
|
+
nearest = candidate;
|
|
17
|
+
nearestDistance = distance;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
return nearest;
|
|
21
|
+
}
|
|
22
|
+
/** Levenshtein distance; names are short, so the plain quadratic table is fine. */
|
|
23
|
+
function editDistance(a, b) {
|
|
24
|
+
let previous = Array.from({ length: b.length + 1 }, (_, j) => j);
|
|
25
|
+
for (let i = 1; i <= a.length; i++) {
|
|
26
|
+
const current = [i];
|
|
27
|
+
for (let j = 1; j <= b.length; j++) {
|
|
28
|
+
const substitution = previous[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1);
|
|
29
|
+
current[j] = Math.min(previous[j] + 1, current[j - 1] + 1, substitution);
|
|
30
|
+
}
|
|
31
|
+
previous = current;
|
|
32
|
+
}
|
|
33
|
+
return previous[b.length];
|
|
34
|
+
}
|
|
35
|
+
//# sourceMappingURL=nearest-key.js.map
|