@osdlc/wayfinder 0.0.0-stage → 0.7.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/CHANGELOG.md +231 -0
- package/CONTRIBUTING.md +62 -0
- package/LICENSE-APACHE +202 -0
- package/LICENSE-MIT +21 -0
- package/README.md +507 -2
- package/SECURITY.md +44 -0
- package/bin/way.js +18 -0
- package/dist/app.d.ts +24 -0
- package/dist/app.js +24 -0
- package/dist/args.d.ts +44 -0
- package/dist/args.js +93 -0
- package/dist/cache.d.ts +7 -0
- package/dist/cache.js +15 -0
- package/dist/catalog.d.ts +38 -0
- package/dist/catalog.js +61 -0
- package/dist/clean-command.d.ts +43 -0
- package/dist/clean-command.js +274 -0
- package/dist/cli.d.ts +76 -0
- package/dist/cli.js +612 -0
- package/dist/config-command.d.ts +52 -0
- package/dist/config-command.js +342 -0
- package/dist/config.d.ts +367 -0
- package/dist/config.js +700 -0
- package/dist/devlink.d.ts +14 -0
- package/dist/devlink.js +30 -0
- package/dist/groups.d.ts +34 -0
- package/dist/groups.js +38 -0
- package/dist/guide.d.ts +32 -0
- package/dist/guide.js +411 -0
- package/dist/http.d.ts +22 -0
- package/dist/http.js +149 -0
- package/dist/origin-owner.d.ts +14 -0
- package/dist/origin-owner.js +69 -0
- package/dist/page.d.ts +15 -0
- package/dist/page.js +58 -0
- package/dist/providers-command.d.ts +40 -0
- package/dist/providers-command.js +132 -0
- package/dist/serve.d.ts +97 -0
- package/dist/serve.js +678 -0
- package/dist/tools.d.ts +46 -0
- package/dist/tools.js +102 -0
- package/dist/trust-command.d.ts +33 -0
- package/dist/trust-command.js +221 -0
- package/dist/trust-store.d.ts +18 -0
- package/dist/trust-store.js +46 -0
- package/dist/tui.d.ts +178 -0
- package/dist/tui.js +846 -0
- package/dist/web/main.js +2315 -0
- package/dist/web/page.html +110 -0
- package/dist/web/styles.css +1514 -0
- package/dist/xdg.d.ts +10 -0
- package/dist/xdg.js +17 -0
- package/package.json +72 -3
package/dist/config.js
ADDED
|
@@ -0,0 +1,700 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* wayfinder's configuration: layered, and readable without running anything.
|
|
3
|
+
* The settings people want every time (runners to skip, paths that are not
|
|
4
|
+
* project structure, whether execution is allowed, extra tools) are set once,
|
|
5
|
+
* per user and per project; flags stay for the exceptions.
|
|
6
|
+
*
|
|
7
|
+
* ## Layers, lowest precedence first
|
|
8
|
+
*
|
|
9
|
+
* 1. `DEFAULT_CONFIG` — the built-in defaults.
|
|
10
|
+
* 2. USER — `$XDG_CONFIG_HOME/wayfinder/config.json`, or `~/.config/wayfinder/config.json`
|
|
11
|
+
* when `XDG_CONFIG_HOME` is unset.
|
|
12
|
+
* 3. PROJECT — `wayfinder.config.json` at the root `findRoot` resolves.
|
|
13
|
+
* 4. CLI flags — not this module's business. {@link collectOptionsFromConfig}
|
|
14
|
+
* produces the slice a caller spreads its own flags on top of.
|
|
15
|
+
*
|
|
16
|
+
* `allowExec` IS AN EXCEPTION TO THIS ORDER. The project layer may lower it to
|
|
17
|
+
* `false` — a repository asking not to be shelled out for is safe to honour —
|
|
18
|
+
* but it can never raise it to `true`. `wayfinder.config.json` lives INSIDE the
|
|
19
|
+
* repository being scanned, so honouring `allowExec: true` from it would let a
|
|
20
|
+
* repository authorize the execution of its own code. The key is therefore
|
|
21
|
+
* stripped from the project layer before merging, with a warning, and only the
|
|
22
|
+
* user layer and the CLI flags can turn execution on. Granting a repository
|
|
23
|
+
* standing permission is `way trust`, which records the consent outside the
|
|
24
|
+
* repository.
|
|
25
|
+
*
|
|
26
|
+
* `tools` is gated too, because a tool module is code. User-layer entries
|
|
27
|
+
* always load; project-layer entries load only when the repository is trusted
|
|
28
|
+
* and execution is allowed (see `tools.ts`).
|
|
29
|
+
*
|
|
30
|
+
* `trust` IS THE SAME EXCEPTION, more strongly: it has no "lower" state to
|
|
31
|
+
* honour from the project layer at all, so ANY project-layer `trust.paths` or
|
|
32
|
+
* `trust.owners` entry is dropped, with a warning — a repository must not be
|
|
33
|
+
* able to pre-authorize itself, or any class of repositories including
|
|
34
|
+
* itself. Only the USER layer's `trust` reaches `@osdlc/trust-repo`'s
|
|
35
|
+
* `policyExecGate`, which combines it with the marker store that
|
|
36
|
+
* `way trust` writes to. See that package's README for the glob dialect,
|
|
37
|
+
* and `origin-owner.ts` for the origin-remote lookup `trust.owners` rests on.
|
|
38
|
+
*
|
|
39
|
+
* XDG is used on every platform, macOS included, as `gh` does: a developer
|
|
40
|
+
* with a dotfiles repository expects this beside their other tool config.
|
|
41
|
+
*
|
|
42
|
+
* `WAYFINDER_CONFIG=/path/to/file` replaces the USER layer's LOCATION and nothing
|
|
43
|
+
* else. The named file is read INSTEAD OF the XDG path; the project layer is
|
|
44
|
+
* still read from the project root, still merges on top, and cannot be turned
|
|
45
|
+
* off this way. Naming a file that does not exist is an error rather than a
|
|
46
|
+
* silent empty layer — an env var pointing at nothing is a typo, not a choice.
|
|
47
|
+
*
|
|
48
|
+
* ## The old waypost names
|
|
49
|
+
*
|
|
50
|
+
* The tool was called waypost before its first release. Each old name is still
|
|
51
|
+
* read when its new one is absent, so an existing setup keeps working:
|
|
52
|
+
* `WAYPOST_CONFIG` when `WAYFINDER_CONFIG` is unset, `<config>/waypost/config.json`
|
|
53
|
+
* when `<config>/wayfinder/config.json` does not exist, and `waypost.config.json`
|
|
54
|
+
* when `wayfinder.config.json` does not exist. A file found this way is also the
|
|
55
|
+
* one `config set` edits, so a setting never lands in a file that is not read.
|
|
56
|
+
* Each fallback adds a warning that names the new location. When both the old
|
|
57
|
+
* and the new file exist, the new one is read and a warning says the old one
|
|
58
|
+
* is ignored.
|
|
59
|
+
*
|
|
60
|
+
* ## Merge rule
|
|
61
|
+
*
|
|
62
|
+
* Objects merge key-wise; everything else — scalars and arrays alike —
|
|
63
|
+
* REPLACES wholesale. Arrays replace because both of ours are answers to
|
|
64
|
+
* "which ones, in what order", and a project that says `order: ["just"]` means
|
|
65
|
+
* that list, not that list appended to whatever the user happened to have.
|
|
66
|
+
*
|
|
67
|
+
* user { runners: { disabled: ["cargo"], order: ["moon"] } }
|
|
68
|
+
* project { runners: { order: ["just"] } }
|
|
69
|
+
* result { runners: { disabled: ["cargo"], order: ["just"] } }
|
|
70
|
+
*
|
|
71
|
+
* ## Unknown keys and broken files
|
|
72
|
+
*
|
|
73
|
+
* An unknown key is a WARNING naming the file and the key, and the rest of the
|
|
74
|
+
* file still loads — a config written for a newer version must not brick an
|
|
75
|
+
* older one. A file that is malformed, or that holds a wrong-typed value where
|
|
76
|
+
* the type is knowable, is a {@link ConfigError} naming the file and the
|
|
77
|
+
* problem. There is no silent fallback: a setting that quietly did not apply is
|
|
78
|
+
* worse than one that refused to load.
|
|
79
|
+
*/
|
|
80
|
+
import { existsSync } from 'node:fs';
|
|
81
|
+
import { mkdir, writeFile } from 'node:fs/promises';
|
|
82
|
+
import { homedir } from 'node:os';
|
|
83
|
+
import { dirname, join, resolve } from 'node:path';
|
|
84
|
+
import { readParsedFile } from '@osdlc/config-layers';
|
|
85
|
+
import { resolveTrustRoot } from '@osdlc/trust-repo';
|
|
86
|
+
import { APP, BIN, CONFIG_ENV_VAR, LEGACY_APP, LEGACY_CONFIG_ENV_VAR, LEGACY_PROJECT_CONFIG_FILENAME, PROJECT_CONFIG_FILENAME, } from "./app.js";
|
|
87
|
+
import { originOwner } from "./origin-owner.js";
|
|
88
|
+
import { expandTilde } from "./xdg.js";
|
|
89
|
+
export { CONFIG_ENV_VAR, PROJECT_CONFIG_FILENAME };
|
|
90
|
+
/** Directory under `$XDG_CONFIG_HOME` holding the USER layer. */
|
|
91
|
+
export const USER_CONFIG_DIR = APP;
|
|
92
|
+
/** The `tool` key of the trust store (`$XDG_STATE_HOME/<tool>/trusted/`). */
|
|
93
|
+
export const TRUST_STORE_TOOL = APP;
|
|
94
|
+
/** The old {@link USER_CONFIG_DIR}, read when the new user file does not exist. */
|
|
95
|
+
export const LEGACY_USER_CONFIG_DIR = LEGACY_APP;
|
|
96
|
+
/** The old {@link TRUST_STORE_TOOL}. Its grants are still honoured; see `trust-store.ts`. */
|
|
97
|
+
export const LEGACY_TRUST_STORE_TOOL = LEGACY_APP;
|
|
98
|
+
/** The USER layer's filename inside {@link USER_CONFIG_DIR}. */
|
|
99
|
+
export const USER_CONFIG_FILENAME = 'config.json';
|
|
100
|
+
/**
|
|
101
|
+
* The built-in defaults layer.
|
|
102
|
+
*
|
|
103
|
+
* Every leaf is present, which is what makes {@link LoadedConfig.sources}
|
|
104
|
+
* total: a key with no answer anywhere would otherwise have no layer to name.
|
|
105
|
+
*/
|
|
106
|
+
export const DEFAULT_CONFIG = {
|
|
107
|
+
runners: { disabled: [], order: [] },
|
|
108
|
+
allowExec: false,
|
|
109
|
+
discovery: 'auto',
|
|
110
|
+
excludePaths: [],
|
|
111
|
+
trust: { paths: [], owners: [] },
|
|
112
|
+
tools: [],
|
|
113
|
+
};
|
|
114
|
+
/**
|
|
115
|
+
* A configuration file that cannot be honoured — unparseable, or holding a
|
|
116
|
+
* value of the wrong type.
|
|
117
|
+
*/
|
|
118
|
+
export class ConfigError extends Error {
|
|
119
|
+
/**
|
|
120
|
+
* The file the error is about. Empty when the error concerns a value handed
|
|
121
|
+
* in directly, as {@link setConfigValue} does with a bad key or value.
|
|
122
|
+
*/
|
|
123
|
+
file;
|
|
124
|
+
constructor(message, file) {
|
|
125
|
+
super(message);
|
|
126
|
+
this.name = 'ConfigError';
|
|
127
|
+
this.file = file;
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* Every settable key, by dotted path. This is the single list: validation,
|
|
132
|
+
* {@link setConfigValue} and "is that a real setting" all read it, so a new
|
|
133
|
+
* setting cannot be accepted in one path and rejected in another.
|
|
134
|
+
*/
|
|
135
|
+
const FIELDS = {
|
|
136
|
+
'runners.disabled': 'string-array',
|
|
137
|
+
'runners.order': 'string-array',
|
|
138
|
+
allowExec: 'boolean',
|
|
139
|
+
discovery: 'discovery',
|
|
140
|
+
excludePaths: 'string-array',
|
|
141
|
+
'trust.paths': 'string-array',
|
|
142
|
+
'trust.owners': 'string-array',
|
|
143
|
+
tools: 'string-array',
|
|
144
|
+
};
|
|
145
|
+
/**
|
|
146
|
+
* Every settable key, in schema order — the dotted names `config set` accepts.
|
|
147
|
+
*
|
|
148
|
+
* Derived from {@link FIELDS} rather than retyped, so a surface that lists the
|
|
149
|
+
* keys (the `guide` command's config section) cannot fall behind the schema.
|
|
150
|
+
*/
|
|
151
|
+
export const CONFIG_KEYS = Object.keys(FIELDS);
|
|
152
|
+
const DISCOVERY_VALUES = ['git', 'walk', 'auto'];
|
|
153
|
+
/**
|
|
154
|
+
* Canonical key order for writing, schema order rather than alphabetical, so a
|
|
155
|
+
* written file reads like the documented schema. Keys not listed here are
|
|
156
|
+
* unknown to this version and are written after the known ones in the order the
|
|
157
|
+
* file already had them.
|
|
158
|
+
*/
|
|
159
|
+
const KEY_ORDER = {
|
|
160
|
+
'': ['runners', 'allowExec', 'discovery', 'excludePaths', 'trust', 'tools'],
|
|
161
|
+
runners: ['disabled', 'order'],
|
|
162
|
+
trust: ['paths', 'owners'],
|
|
163
|
+
};
|
|
164
|
+
function isPlainObject(value) {
|
|
165
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
166
|
+
}
|
|
167
|
+
function describe(value) {
|
|
168
|
+
if (value === null)
|
|
169
|
+
return 'null';
|
|
170
|
+
if (Array.isArray(value))
|
|
171
|
+
return 'an array';
|
|
172
|
+
return `a ${typeof value}`;
|
|
173
|
+
}
|
|
174
|
+
/** Check one leaf against its declared type, returning it narrowed. */
|
|
175
|
+
function coerceField(key, value, file) {
|
|
176
|
+
const type = FIELDS[key];
|
|
177
|
+
const where = file === '' ? '' : `${file}: `;
|
|
178
|
+
switch (type) {
|
|
179
|
+
case 'boolean':
|
|
180
|
+
if (typeof value !== 'boolean') {
|
|
181
|
+
throw new ConfigError(`${where}${key} must be true or false, got ${describe(value)}`, file);
|
|
182
|
+
}
|
|
183
|
+
return value;
|
|
184
|
+
case 'string-array': {
|
|
185
|
+
if (!Array.isArray(value)) {
|
|
186
|
+
throw new ConfigError(`${where}${key} must be an array of strings, got ${describe(value)}`, file);
|
|
187
|
+
}
|
|
188
|
+
// Name the offending element, not the container: "got an array" reads as
|
|
189
|
+
// a contradiction when an array is exactly what was asked for.
|
|
190
|
+
const bad = value.findIndex((item) => typeof item !== 'string');
|
|
191
|
+
if (bad !== -1) {
|
|
192
|
+
throw new ConfigError(`${where}${key} must be an array of strings, got ${describe(value[bad])} at index ${bad}`, file);
|
|
193
|
+
}
|
|
194
|
+
return [...value];
|
|
195
|
+
}
|
|
196
|
+
case 'discovery':
|
|
197
|
+
if (typeof value !== 'string' ||
|
|
198
|
+
!DISCOVERY_VALUES.includes(value)) {
|
|
199
|
+
throw new ConfigError(`${where}${key} must be one of ${DISCOVERY_VALUES.join(', ')}, got ${JSON.stringify(value)}`, file);
|
|
200
|
+
}
|
|
201
|
+
return value;
|
|
202
|
+
default:
|
|
203
|
+
throw new ConfigError(`${where}unknown setting: ${key}`, file);
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
function unknownKeyWarning(file, key) {
|
|
207
|
+
return `${file}: unknown setting "${key}" (ignored)`;
|
|
208
|
+
}
|
|
209
|
+
/**
|
|
210
|
+
* Resolve where each layer's file lives. `env` and `home` are injectable
|
|
211
|
+
* because a test that consulted the real environment would read the developer's
|
|
212
|
+
* own `~/.config`, and pass or fail according to what is in it. The only other
|
|
213
|
+
* input is whether a file exists, which picks between a new name and its old
|
|
214
|
+
* waypost fallback (see the module docblock).
|
|
215
|
+
*
|
|
216
|
+
* Two details of how a path out of the environment is read:
|
|
217
|
+
*
|
|
218
|
+
* A leading `~` is expanded against `home`. A shell expands it before exec, but
|
|
219
|
+
* `.env` loaders, direnv and CI YAML hand the literal tilde through, and
|
|
220
|
+
* `~/config.json` quietly becoming `<somewhere>/~/config.json` is the silent
|
|
221
|
+
* wrong answer this module refuses to give anywhere else.
|
|
222
|
+
*
|
|
223
|
+
* A RELATIVE path resolves against `root`, not the process working directory.
|
|
224
|
+
* This function is otherwise a pure function of its arguments; reading
|
|
225
|
+
* `process.cwd()` would smuggle an ambient input in, so a library consumer
|
|
226
|
+
* scanning some other directory would get a user-layer path unrelated to the
|
|
227
|
+
* directory being scanned while the project layer tracked it.
|
|
228
|
+
*/
|
|
229
|
+
export function configLocations(root, env = process.env, home = homedir()) {
|
|
230
|
+
const base = resolve(root);
|
|
231
|
+
const absolute = (path) => resolve(base, expandTilde(path, home));
|
|
232
|
+
const fromVar = (name) => {
|
|
233
|
+
const value = env[name]?.trim();
|
|
234
|
+
return value !== undefined && value !== '' ? value : null;
|
|
235
|
+
};
|
|
236
|
+
const named = fromVar(CONFIG_ENV_VAR);
|
|
237
|
+
const legacyNamed = named === null ? fromVar(LEGACY_CONFIG_ENV_VAR) : null;
|
|
238
|
+
const userEnvVar = named !== null ? CONFIG_ENV_VAR : legacyNamed !== null ? LEGACY_CONFIG_ENV_VAR : null;
|
|
239
|
+
const envPath = named ?? legacyNamed;
|
|
240
|
+
const xdg = env['XDG_CONFIG_HOME']?.trim();
|
|
241
|
+
const configHome = xdg !== undefined && xdg !== '' ? absolute(xdg) : join(home, '.config');
|
|
242
|
+
const xdgUser = preferNew(join(configHome, USER_CONFIG_DIR, USER_CONFIG_FILENAME), join(configHome, LEGACY_USER_CONFIG_DIR, USER_CONFIG_FILENAME));
|
|
243
|
+
const project = preferNew(join(base, PROJECT_CONFIG_FILENAME), join(base, LEGACY_PROJECT_CONFIG_FILENAME));
|
|
244
|
+
return {
|
|
245
|
+
user: envPath !== null ? absolute(envPath) : xdgUser.path,
|
|
246
|
+
userFromEnv: envPath !== null,
|
|
247
|
+
userEnvVar,
|
|
248
|
+
userLegacy: envPath === null && xdgUser.legacy,
|
|
249
|
+
userIgnored: envPath === null ? xdgUser.ignored : null,
|
|
250
|
+
project: project.path,
|
|
251
|
+
projectLegacy: project.legacy,
|
|
252
|
+
projectIgnored: project.ignored,
|
|
253
|
+
};
|
|
254
|
+
}
|
|
255
|
+
/**
|
|
256
|
+
* The new path, unless only the old one exists. `ignored` names the old file
|
|
257
|
+
* when both exist, so the caller can say it is not read.
|
|
258
|
+
*/
|
|
259
|
+
function preferNew(path, legacy) {
|
|
260
|
+
const hasNew = existsSync(path);
|
|
261
|
+
const hasLegacy = existsSync(legacy);
|
|
262
|
+
if (!hasNew && hasLegacy)
|
|
263
|
+
return { path: legacy, legacy: true, ignored: null };
|
|
264
|
+
return { path, legacy: false, ignored: hasNew && hasLegacy ? legacy : null };
|
|
265
|
+
}
|
|
266
|
+
/**
|
|
267
|
+
* Validate a parsed JSON document against schema v1.
|
|
268
|
+
*
|
|
269
|
+
* Throws {@link ConfigError} on a type violation; returns the recognized subset
|
|
270
|
+
* plus one warning per unknown key. The returned config holds ONLY known keys,
|
|
271
|
+
* which is why the write path never round-trips through this shape — see
|
|
272
|
+
* {@link readRawConfigFile}.
|
|
273
|
+
*/
|
|
274
|
+
export function validateConfig(raw, file) {
|
|
275
|
+
if (!isPlainObject(raw)) {
|
|
276
|
+
throw new ConfigError(`${file}: expected a JSON object, got ${describe(raw)}`, file);
|
|
277
|
+
}
|
|
278
|
+
const warnings = [];
|
|
279
|
+
const config = {};
|
|
280
|
+
for (const [key, value] of Object.entries(raw)) {
|
|
281
|
+
if (value === undefined)
|
|
282
|
+
continue;
|
|
283
|
+
switch (key) {
|
|
284
|
+
case 'runners': {
|
|
285
|
+
if (!isPlainObject(value)) {
|
|
286
|
+
throw new ConfigError(`${file}: runners must be an object, got ${describe(value)}`, file);
|
|
287
|
+
}
|
|
288
|
+
const runners = {};
|
|
289
|
+
for (const [inner, innerValue] of Object.entries(value)) {
|
|
290
|
+
if (innerValue === undefined)
|
|
291
|
+
continue;
|
|
292
|
+
if (inner === 'disabled' || inner === 'order') {
|
|
293
|
+
runners[inner] = coerceField(`runners.${inner}`, innerValue, file);
|
|
294
|
+
}
|
|
295
|
+
else {
|
|
296
|
+
warnings.push(unknownKeyWarning(file, `runners.${inner}`));
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
config.runners = runners;
|
|
300
|
+
break;
|
|
301
|
+
}
|
|
302
|
+
case 'allowExec':
|
|
303
|
+
config.allowExec = coerceField('allowExec', value, file);
|
|
304
|
+
break;
|
|
305
|
+
case 'discovery':
|
|
306
|
+
config.discovery = coerceField('discovery', value, file);
|
|
307
|
+
break;
|
|
308
|
+
case 'excludePaths':
|
|
309
|
+
config.excludePaths = coerceField('excludePaths', value, file);
|
|
310
|
+
break;
|
|
311
|
+
case 'trust': {
|
|
312
|
+
if (!isPlainObject(value)) {
|
|
313
|
+
throw new ConfigError(`${file}: trust must be an object, got ${describe(value)}`, file);
|
|
314
|
+
}
|
|
315
|
+
const trust = {};
|
|
316
|
+
for (const [inner, innerValue] of Object.entries(value)) {
|
|
317
|
+
if (innerValue === undefined)
|
|
318
|
+
continue;
|
|
319
|
+
if (inner === 'paths' || inner === 'owners') {
|
|
320
|
+
trust[inner] = coerceField(`trust.${inner}`, innerValue, file);
|
|
321
|
+
}
|
|
322
|
+
else {
|
|
323
|
+
warnings.push(unknownKeyWarning(file, `trust.${inner}`));
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
config.trust = trust;
|
|
327
|
+
break;
|
|
328
|
+
}
|
|
329
|
+
case 'tools':
|
|
330
|
+
config.tools = coerceField('tools', value, file);
|
|
331
|
+
break;
|
|
332
|
+
default:
|
|
333
|
+
warnings.push(unknownKeyWarning(file, key));
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
return { config, warnings };
|
|
337
|
+
}
|
|
338
|
+
/**
|
|
339
|
+
* Copy a value deeply enough that the result shares no mutable structure with
|
|
340
|
+
* its source. A shallow spread is not enough here: `DEFAULT_CONFIG` is an
|
|
341
|
+
* exported process-wide singleton that every `loadConfig` merges on top of, so
|
|
342
|
+
* a branch aliased out of it would let one caller mutating `effective` corrupt
|
|
343
|
+
* the built-in defaults for every later load in the process.
|
|
344
|
+
*/
|
|
345
|
+
function cloneValue(value) {
|
|
346
|
+
if (Array.isArray(value))
|
|
347
|
+
return value.map(cloneValue);
|
|
348
|
+
if (isPlainObject(value)) {
|
|
349
|
+
const out = {};
|
|
350
|
+
for (const [key, inner] of Object.entries(value))
|
|
351
|
+
out[key] = cloneValue(inner);
|
|
352
|
+
return out;
|
|
353
|
+
}
|
|
354
|
+
return value;
|
|
355
|
+
}
|
|
356
|
+
function deepMerge(base, over) {
|
|
357
|
+
const out = {};
|
|
358
|
+
for (const key of new Set([...Object.keys(base), ...Object.keys(over)])) {
|
|
359
|
+
const under = base[key];
|
|
360
|
+
const above = over[key];
|
|
361
|
+
if (above === undefined) {
|
|
362
|
+
out[key] = cloneValue(under);
|
|
363
|
+
}
|
|
364
|
+
else if (isPlainObject(under) && isPlainObject(above)) {
|
|
365
|
+
out[key] = deepMerge(under, above);
|
|
366
|
+
}
|
|
367
|
+
else {
|
|
368
|
+
out[key] = cloneValue(above);
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
return out;
|
|
372
|
+
}
|
|
373
|
+
/**
|
|
374
|
+
* Merge `over` onto `base` per the module's rule: objects key-wise, scalars and
|
|
375
|
+
* arrays wholesale.
|
|
376
|
+
*
|
|
377
|
+
* Non-mutating in both directions: neither argument is touched, and the result
|
|
378
|
+
* shares no object or array with either of them — including branches `over`
|
|
379
|
+
* never mentioned. Mutating a loaded config must not reach back into
|
|
380
|
+
* `DEFAULT_CONFIG`.
|
|
381
|
+
*/
|
|
382
|
+
export function mergeConfig(base, over) {
|
|
383
|
+
return deepMerge(base, over);
|
|
384
|
+
}
|
|
385
|
+
/**
|
|
386
|
+
* One layer file as a plain object, read through `@osdlc/config-layers`'s
|
|
387
|
+
* file read (the one read of a config file's bytes). `null` when the file does
|
|
388
|
+
* not exist; a file that is unreadable, not JSON, or not an object throws
|
|
389
|
+
* {@link ConfigError} naming it.
|
|
390
|
+
*/
|
|
391
|
+
async function readJsonFile(file) {
|
|
392
|
+
const read = readParsedFile(file, 'json');
|
|
393
|
+
switch (read.kind) {
|
|
394
|
+
case 'absent':
|
|
395
|
+
return null;
|
|
396
|
+
case 'unreadable':
|
|
397
|
+
throw new ConfigError(`${file}: cannot be read — ${read.message}`, file);
|
|
398
|
+
case 'unparsable':
|
|
399
|
+
throw new ConfigError(`${file}: invalid JSON — ${read.message}`, file);
|
|
400
|
+
case 'ok':
|
|
401
|
+
if (!isPlainObject(read.value)) {
|
|
402
|
+
throw new ConfigError(`${file}: expected a JSON object, got ${describe(read.value)}`, file);
|
|
403
|
+
}
|
|
404
|
+
return read.value;
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
/**
|
|
408
|
+
* The file's parsed object, unvalidated and with every key intact.
|
|
409
|
+
*
|
|
410
|
+
* This is the read half of an edit that preserves what this version does not
|
|
411
|
+
* understand. `set` and `unset` must apply to THIS, not to the validated shape,
|
|
412
|
+
* because validation drops unknown keys — so writing a validated document back
|
|
413
|
+
* would silently delete a setting a newer version had written. `null` when the
|
|
414
|
+
* file does not exist.
|
|
415
|
+
*/
|
|
416
|
+
export async function readRawConfigFile(file) {
|
|
417
|
+
return readJsonFile(file);
|
|
418
|
+
}
|
|
419
|
+
/**
|
|
420
|
+
* Read, parse and validate one layer. `null` when the file does not exist —
|
|
421
|
+
* absence is normal and is not an error. A file that exists and is broken
|
|
422
|
+
* throws {@link ConfigError}.
|
|
423
|
+
*/
|
|
424
|
+
export async function readConfigFile(file) {
|
|
425
|
+
const raw = await readJsonFile(file);
|
|
426
|
+
if (raw === null)
|
|
427
|
+
return null;
|
|
428
|
+
return validateConfig(raw, file);
|
|
429
|
+
}
|
|
430
|
+
function orderedKeys(record, section) {
|
|
431
|
+
const canonical = KEY_ORDER[section] ?? [];
|
|
432
|
+
const known = canonical.filter((key) => key in record);
|
|
433
|
+
const rest = Object.keys(record).filter((key) => !canonical.includes(key));
|
|
434
|
+
return [...known, ...rest];
|
|
435
|
+
}
|
|
436
|
+
function stabilize(record, section) {
|
|
437
|
+
const out = {};
|
|
438
|
+
for (const key of orderedKeys(record, section)) {
|
|
439
|
+
const value = record[key];
|
|
440
|
+
const child = section === '' ? key : `${section}.${key}`;
|
|
441
|
+
out[key] =
|
|
442
|
+
isPlainObject(value) && KEY_ORDER[child] !== undefined ? stabilize(value, child) : value;
|
|
443
|
+
}
|
|
444
|
+
return out;
|
|
445
|
+
}
|
|
446
|
+
/**
|
|
447
|
+
* Write a configuration file: known keys in schema order, unknown keys after
|
|
448
|
+
* them in the order they already had, two-space indent, trailing newline.
|
|
449
|
+
* Parent directories are created.
|
|
450
|
+
*
|
|
451
|
+
* The order is fixed so that writing an unchanged document produces an
|
|
452
|
+
* unchanged file — a config under version control should not churn its diff
|
|
453
|
+
* because a key moved.
|
|
454
|
+
*
|
|
455
|
+
* Accepts a raw record as well as a {@link TaskConfig}, which is what makes the
|
|
456
|
+
* unknown-key-preserving edit path writable.
|
|
457
|
+
*/
|
|
458
|
+
export async function writeConfigFile(file, config) {
|
|
459
|
+
const body = JSON.stringify(stabilize(config, ''), null, 2);
|
|
460
|
+
await mkdir(dirname(file), { recursive: true });
|
|
461
|
+
await writeFile(file, `${body}\n`, 'utf-8');
|
|
462
|
+
}
|
|
463
|
+
function leafPaths(value, prefix) {
|
|
464
|
+
if (!isPlainObject(value))
|
|
465
|
+
return [prefix];
|
|
466
|
+
return Object.entries(value).flatMap(([key, inner]) => leafPaths(inner, prefix === '' ? key : `${prefix}.${key}`));
|
|
467
|
+
}
|
|
468
|
+
/**
|
|
469
|
+
* Load every layer and merge them. `env` and `home` are injectable for the same
|
|
470
|
+
* reason {@link configLocations} takes them.
|
|
471
|
+
*/
|
|
472
|
+
export async function loadConfig(root, env = process.env, home = homedir()) {
|
|
473
|
+
const locations = configLocations(root, env, home);
|
|
474
|
+
const userRead = await readConfigFile(locations.user);
|
|
475
|
+
if (userRead === null && locations.userFromEnv) {
|
|
476
|
+
throw new ConfigError(`${locations.user}: ${locations.userEnvVar ?? CONFIG_ENV_VAR} names a file that does not exist`, locations.user);
|
|
477
|
+
}
|
|
478
|
+
const projectRead = await readConfigFile(locations.project);
|
|
479
|
+
const user = userRead?.config ?? null;
|
|
480
|
+
let project = projectRead?.config ?? null;
|
|
481
|
+
const warnings = [...(userRead?.warnings ?? []), ...(projectRead?.warnings ?? [])];
|
|
482
|
+
warnings.push(...legacyWarnings(locations));
|
|
483
|
+
// A repository cannot grant itself permission to run its own code. Lowering
|
|
484
|
+
// to false is honoured; raising to true is dropped here, BEFORE the merge and
|
|
485
|
+
// before `sources`, so `config list` attributes the value to the layer that
|
|
486
|
+
// really supplied it rather than to the file that was ignored.
|
|
487
|
+
//
|
|
488
|
+
// Not in validateConfig: that function is layer-agnostic and is also the
|
|
489
|
+
// `config set` write path's check. This rule is about which layer a value
|
|
490
|
+
// came from, which only layer resolution knows.
|
|
491
|
+
if (project?.allowExec === true) {
|
|
492
|
+
// Warned even when the user layer already said true. The author's intent —
|
|
493
|
+
// grant exec — is never honoured from this file, and silence would let them
|
|
494
|
+
// believe it worked and rely on it in a repo where it does not.
|
|
495
|
+
warnings.push(`${locations.project}: allowExec: true is ignored in a project file — a repository cannot grant itself permission to run subprocesses; run "${BIN} trust" to trust this repository`);
|
|
496
|
+
const { allowExec: _ignored, ...rest } = project;
|
|
497
|
+
project = rest;
|
|
498
|
+
}
|
|
499
|
+
// Same rule, more strongly: a project-layer `trust` block is dropped
|
|
500
|
+
// whole, whatever it holds — a repository must not be able to pre-authorize
|
|
501
|
+
// itself or any class of repositories, and even an empty `paths: []` would
|
|
502
|
+
// otherwise deep-merge over the user's list and silently narrow it. The
|
|
503
|
+
// warning is for a non-empty block only, matching allowExec's silence on
|
|
504
|
+
// `false`: an empty block granted nothing worth naming.
|
|
505
|
+
if (project?.trust !== undefined) {
|
|
506
|
+
if ((project.trust.paths?.length ?? 0) > 0 || (project.trust.owners?.length ?? 0) > 0) {
|
|
507
|
+
warnings.push(`${locations.project}: trust is ignored in a project file — a repository cannot grant ` +
|
|
508
|
+
`itself trust; set trust.paths/trust.owners in your user config (${locations.user}) instead`);
|
|
509
|
+
}
|
|
510
|
+
const { trust: _ignoredTrust, ...rest } = project;
|
|
511
|
+
project = rest;
|
|
512
|
+
}
|
|
513
|
+
const effective = mergeConfig(mergeConfig(DEFAULT_CONFIG, user ?? {}), project ?? {});
|
|
514
|
+
const sources = new Map();
|
|
515
|
+
for (const key of leafPaths(effective, '')) {
|
|
516
|
+
const layer = project !== null && getConfigValue(project, key) !== undefined
|
|
517
|
+
? 'project'
|
|
518
|
+
: user !== null && getConfigValue(user, key) !== undefined
|
|
519
|
+
? 'user'
|
|
520
|
+
: 'default';
|
|
521
|
+
sources.set(key, layer);
|
|
522
|
+
}
|
|
523
|
+
return {
|
|
524
|
+
effective,
|
|
525
|
+
layers: { default: DEFAULT_CONFIG, user, project },
|
|
526
|
+
sources,
|
|
527
|
+
locations,
|
|
528
|
+
warnings,
|
|
529
|
+
};
|
|
530
|
+
}
|
|
531
|
+
/** One warning per old waypost name in use, naming the new one. */
|
|
532
|
+
function legacyWarnings(locations) {
|
|
533
|
+
const out = [];
|
|
534
|
+
if (locations.userEnvVar === LEGACY_CONFIG_ENV_VAR) {
|
|
535
|
+
out.push(`${LEGACY_CONFIG_ENV_VAR} is the old name; set ${CONFIG_ENV_VAR} instead`);
|
|
536
|
+
}
|
|
537
|
+
if (locations.userLegacy) {
|
|
538
|
+
const target = join(dirname(dirname(locations.user)), USER_CONFIG_DIR, USER_CONFIG_FILENAME);
|
|
539
|
+
out.push(`${locations.user}: read from the old waypost location; move it to ${target}`);
|
|
540
|
+
}
|
|
541
|
+
if (locations.userIgnored !== null) {
|
|
542
|
+
out.push(`${locations.userIgnored} is ignored because ${locations.user} exists; merge it and delete it`);
|
|
543
|
+
}
|
|
544
|
+
if (locations.projectLegacy) {
|
|
545
|
+
out.push(`${locations.project}: the old file name; rename it to ${PROJECT_CONFIG_FILENAME}`);
|
|
546
|
+
}
|
|
547
|
+
if (locations.projectIgnored !== null) {
|
|
548
|
+
out.push(`${locations.projectIgnored} is ignored because ${PROJECT_CONFIG_FILENAME} exists; merge it and delete it`);
|
|
549
|
+
}
|
|
550
|
+
return out;
|
|
551
|
+
}
|
|
552
|
+
/** Read a dotted path — `"runners.order"`, `"allowExec"`. `undefined` when absent. */
|
|
553
|
+
export function getConfigValue(config, key) {
|
|
554
|
+
let cursor = config;
|
|
555
|
+
for (const segment of key.split('.')) {
|
|
556
|
+
if (!isPlainObject(cursor))
|
|
557
|
+
return undefined;
|
|
558
|
+
cursor = cursor[segment];
|
|
559
|
+
}
|
|
560
|
+
return cursor;
|
|
561
|
+
}
|
|
562
|
+
/**
|
|
563
|
+
* Set a dotted path, returning a new document. Non-mutating and creating any
|
|
564
|
+
* intermediate objects, so `set` works on an empty file.
|
|
565
|
+
*
|
|
566
|
+
* The key must be a known setting and the value must match its type; both throw
|
|
567
|
+
* {@link ConfigError} rather than writing something that will fail to load
|
|
568
|
+
* next time, as does an existing intermediate value that is not an object. The
|
|
569
|
+
* generic return means a raw record edits to a raw record with its unknown keys
|
|
570
|
+
* untouched.
|
|
571
|
+
*/
|
|
572
|
+
export function setConfigValue(config, key, value) {
|
|
573
|
+
if (!(key in FIELDS)) {
|
|
574
|
+
throw new ConfigError(`unknown setting: ${key}`, '');
|
|
575
|
+
}
|
|
576
|
+
const checked = coerceField(key, value, '');
|
|
577
|
+
const segments = key.split('.');
|
|
578
|
+
const root = { ...config };
|
|
579
|
+
let cursor = root;
|
|
580
|
+
let walked = '';
|
|
581
|
+
for (const segment of segments.slice(0, -1)) {
|
|
582
|
+
walked = walked === '' ? segment : `${walked}.${segment}`;
|
|
583
|
+
const existing = cursor[segment];
|
|
584
|
+
// A container of the wrong type is a broken file, not a slot to overwrite:
|
|
585
|
+
// silently replacing it would delete whatever the user meant by it.
|
|
586
|
+
if (existing !== undefined && !isPlainObject(existing)) {
|
|
587
|
+
throw new ConfigError(`cannot set ${key}: ${walked} is ${describe(existing)}, not an object`, '');
|
|
588
|
+
}
|
|
589
|
+
const next = existing === undefined ? {} : { ...existing };
|
|
590
|
+
cursor[segment] = next;
|
|
591
|
+
cursor = next;
|
|
592
|
+
}
|
|
593
|
+
cursor[segments[segments.length - 1]] = checked;
|
|
594
|
+
return root;
|
|
595
|
+
}
|
|
596
|
+
/**
|
|
597
|
+
* Remove a dotted path, returning a new document. A container left empty by the
|
|
598
|
+
* removal is removed too, so unsetting the last `runners.*` key does not leave
|
|
599
|
+
* `"runners": {}` behind.
|
|
600
|
+
*
|
|
601
|
+
* Unlike `set`, any key may be unset — including one this version does not know
|
|
602
|
+
* — because removing a stale setting is exactly when you need that.
|
|
603
|
+
*/
|
|
604
|
+
export function unsetConfigValue(config, key) {
|
|
605
|
+
const segments = key.split('.');
|
|
606
|
+
const record = config;
|
|
607
|
+
const head = segments[0];
|
|
608
|
+
if (!(head in record))
|
|
609
|
+
return { ...record };
|
|
610
|
+
if (segments.length === 1) {
|
|
611
|
+
const out = { ...record };
|
|
612
|
+
delete out[head];
|
|
613
|
+
return out;
|
|
614
|
+
}
|
|
615
|
+
const child = record[head];
|
|
616
|
+
if (!isPlainObject(child))
|
|
617
|
+
return { ...record };
|
|
618
|
+
const pruned = unsetConfigValue(child, segments.slice(1).join('.'));
|
|
619
|
+
const out = { ...record };
|
|
620
|
+
if (Object.keys(pruned).length === 0)
|
|
621
|
+
delete out[head];
|
|
622
|
+
else
|
|
623
|
+
out[head] = pruned;
|
|
624
|
+
return out;
|
|
625
|
+
}
|
|
626
|
+
/**
|
|
627
|
+
* Parse a value typed on a command line. JSON first, so `true`, `3` and
|
|
628
|
+
* `["a","b"]` arrive as themselves; a bare word that is not valid JSON falls
|
|
629
|
+
* back to the string, so `moon` does not have to be typed as `"moon"`.
|
|
630
|
+
*/
|
|
631
|
+
export function parseConfigValue(raw) {
|
|
632
|
+
try {
|
|
633
|
+
return JSON.parse(raw);
|
|
634
|
+
}
|
|
635
|
+
catch {
|
|
636
|
+
return raw;
|
|
637
|
+
}
|
|
638
|
+
}
|
|
639
|
+
/**
|
|
640
|
+
* The {@link WayOptions} slice this configuration owns. Only keys the config
|
|
641
|
+
* sets are present, so a caller spreads its own flags after it.
|
|
642
|
+
*/
|
|
643
|
+
export function collectOptionsFromConfig(config) {
|
|
644
|
+
const options = {};
|
|
645
|
+
const disabled = config.runners?.disabled;
|
|
646
|
+
if (disabled !== undefined)
|
|
647
|
+
options.exclude = [...disabled];
|
|
648
|
+
if (config.allowExec !== undefined)
|
|
649
|
+
options.allowExec = config.allowExec;
|
|
650
|
+
if (config.discovery !== undefined)
|
|
651
|
+
options.discovery = config.discovery;
|
|
652
|
+
if (config.excludePaths !== undefined)
|
|
653
|
+
options.excludePaths = [...config.excludePaths];
|
|
654
|
+
return options;
|
|
655
|
+
}
|
|
656
|
+
/** `config.trust`, defaulted to the empty policy `@osdlc/trust-repo` expects. */
|
|
657
|
+
export function trustPolicyFromConfig(config) {
|
|
658
|
+
return { paths: config.trust?.paths ?? [], owners: config.trust?.owners ?? [] };
|
|
659
|
+
}
|
|
660
|
+
/**
|
|
661
|
+
* Expand a `trust.paths` entry's leading `~` against `home`, then
|
|
662
|
+
* symlink-resolve the pattern's static prefix — the part before the first
|
|
663
|
+
* glob character — through `resolveTrustRoot`.
|
|
664
|
+
*
|
|
665
|
+
* The injected `expandPath` `policyExecGate`/`policyDecision` take. Without it, a pattern written against the spelling a person typed
|
|
666
|
+
* (`/tmp/…`, which on macOS is really `/private/tmp/…`) would silently never
|
|
667
|
+
* match the RESOLVED root `@osdlc/trust-repo`'s `policyDecision` compares it
|
|
668
|
+
* against.
|
|
669
|
+
*/
|
|
670
|
+
export async function expandTrustPath(raw, home) {
|
|
671
|
+
const abs = resolve(expandTilde(raw, home));
|
|
672
|
+
const globAt = abs.search(/[*?]/);
|
|
673
|
+
if (globAt === -1)
|
|
674
|
+
return resolveTrustRoot(abs);
|
|
675
|
+
const slash = abs.lastIndexOf('/', globAt);
|
|
676
|
+
const prefix = await resolveTrustRoot(slash <= 0 ? '/' : abs.slice(0, slash));
|
|
677
|
+
return prefix + abs.slice(slash);
|
|
678
|
+
}
|
|
679
|
+
/**
|
|
680
|
+
* The options every `@osdlc/trust-repo` gate call takes: {@link expandTrustPath}
|
|
681
|
+
* against `home`, and the git-backed {@link originOwner} lookup `trust.owners`
|
|
682
|
+
* rests on. One home for the binding, so a call site cannot leave `ownerOf` out
|
|
683
|
+
* and silently stop honouring `trust.owners`.
|
|
684
|
+
*/
|
|
685
|
+
export function trustPolicyOptions(home) {
|
|
686
|
+
return { expandPath: (raw) => expandTrustPath(raw, home), ownerOf: originOwner };
|
|
687
|
+
}
|
|
688
|
+
/**
|
|
689
|
+
* Sort runner-keyed items for display: the ids named in `order` first, in that
|
|
690
|
+
* order, then everything else alphabetically. Alphabetical rather than
|
|
691
|
+
* registry order, so adding a tool does not reshuffle the list.
|
|
692
|
+
*/
|
|
693
|
+
export function orderRunners(items, order) {
|
|
694
|
+
const rank = new Map((order ?? []).map((id, index) => [id, index]));
|
|
695
|
+
const at = (item) => rank.get(item.runner) ?? Number.MAX_SAFE_INTEGER;
|
|
696
|
+
return [...items].sort((a, b) => {
|
|
697
|
+
const diff = at(a) - at(b);
|
|
698
|
+
return diff !== 0 ? diff : a.runner.localeCompare(b.runner);
|
|
699
|
+
});
|
|
700
|
+
}
|