@osdlc/wayfinder 0.7.1 → 0.7.2

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.
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Repository text made safe to print to a terminal.
3
+ *
4
+ * Task names, script bodies, doc comments, config values and directory names
5
+ * come from the repository. A control character in one of them reaches the
6
+ * terminal as a command: `ESC ] 52` writes the clipboard, `ESC ] 0` sets the
7
+ * window title, and a query sequence makes some terminals type a reply into
8
+ * stdin, which the TUI reads as keys. Bidi embedding, override and isolate
9
+ * characters make text display in a different order from the one it runs
10
+ * in. So every human output replaces these characters before printing, and
11
+ * the clipboard gets the same text. JSON output keeps every value exact: it
12
+ * escapes these characters as `\u` escapes instead (see {@link jsonText}).
13
+ *
14
+ * Each control character becomes one U+FFFD, so the text keeps its length and
15
+ * a match offset into it still points at the same character.
16
+ */
17
+ import { type CliIo } from '@osdlc/cli-tool';
18
+ /**
19
+ * `text` with every C0 control character (ESC included), DEL, C1 control
20
+ * character and bidi control replaced by U+FFFD. With `multiline`, tab and
21
+ * newline are kept, for output that is already more than one line.
22
+ */
23
+ export declare function terminalSafe(text: string, opts?: {
24
+ multiline?: boolean;
25
+ }): string;
26
+ /**
27
+ * `JSON.stringify(value, null, indent)` with DEL, C1 and the bidi controls
28
+ * written as `\u` escapes. It parses to the same value, and is safe to print
29
+ * to a terminal.
30
+ */
31
+ export declare function jsonText(value: unknown, indent?: number): string;
32
+ /**
33
+ * `io` with stdout made terminal-safe, tab and newline kept. For a command
34
+ * whose stdout is human text that can name repository paths, such as
35
+ * `way dev status`. For JSON output use {@link safeJsonStdout}.
36
+ */
37
+ export declare function safeStdout(io: CliIo): CliIo;
38
+ /**
39
+ * `io` with stdout made terminal-safe for JSON output, such as
40
+ * `way dev status --json`. DEL, C1 and the bidi controls are written as `\u`
41
+ * escapes, as {@link jsonText} writes them, so every JSON value stays exact.
42
+ * A raw C0 character other than tab and newline becomes U+FFFD; valid JSON
43
+ * has none, since `JSON.stringify` escapes C0.
44
+ */
45
+ export declare function safeJsonStdout(io: CliIo): CliIo;
46
+ /**
47
+ * `io` with stderr made terminal-safe. stderr carries only human text:
48
+ * warnings, errors and notes, which can quote config values and file names.
49
+ */
50
+ export declare function safeStderr(io: CliIo): CliIo;
51
+ /**
52
+ * Runs `run` and returns its exit code. An error it throws is printed to
53
+ * `stderr` as one terminal-safe line, and the code is `EXIT.error`. For the
54
+ * installed `way`, so an error no command caught cannot reach the terminal
55
+ * raw, as Node's own handler would print it.
56
+ */
57
+ export declare function guardedExit(run: () => number | Promise<number>, stderr?: (text: string) => void): Promise<number>;
@@ -0,0 +1,91 @@
1
+ /**
2
+ * Repository text made safe to print to a terminal.
3
+ *
4
+ * Task names, script bodies, doc comments, config values and directory names
5
+ * come from the repository. A control character in one of them reaches the
6
+ * terminal as a command: `ESC ] 52` writes the clipboard, `ESC ] 0` sets the
7
+ * window title, and a query sequence makes some terminals type a reply into
8
+ * stdin, which the TUI reads as keys. Bidi embedding, override and isolate
9
+ * characters make text display in a different order from the one it runs
10
+ * in. So every human output replaces these characters before printing, and
11
+ * the clipboard gets the same text. JSON output keeps every value exact: it
12
+ * escapes these characters as `\u` escapes instead (see {@link jsonText}).
13
+ *
14
+ * Each control character becomes one U+FFFD, so the text keeps its length and
15
+ * a match offset into it still points at the same character.
16
+ */
17
+ import { EXIT } from '@osdlc/cli-tool';
18
+ import { APP } from "./app.js";
19
+ /** C0 (tab and newline included), DEL, C1, and bidi U+202A-202E and U+2066-2069. */
20
+ const CONTROL = /[\u0000-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069]/g;
21
+ /** The same, but tab and newline are kept. */
22
+ const CONTROL_KEEP_LINES = /[\u0000-\u0008\u000b-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069]/g;
23
+ /** C0 without tab and newline. */
24
+ const C0_KEEP_LINES = /[\u0000-\u0008\u000b-\u001f]/g;
25
+ /** What `JSON.stringify` leaves raw of the above: it escapes C0 itself. */
26
+ const JSON_RAW = /[\u007f-\u009f\u202a-\u202e\u2066-\u2069]/g;
27
+ const REPLACEMENT = '�';
28
+ /**
29
+ * `text` with every C0 control character (ESC included), DEL, C1 control
30
+ * character and bidi control replaced by U+FFFD. With `multiline`, tab and
31
+ * newline are kept, for output that is already more than one line.
32
+ */
33
+ export function terminalSafe(text, opts = {}) {
34
+ return text.replace(opts.multiline === true ? CONTROL_KEEP_LINES : CONTROL, REPLACEMENT);
35
+ }
36
+ /**
37
+ * `JSON.stringify(value, null, indent)` with DEL, C1 and the bidi controls
38
+ * written as `\u` escapes. It parses to the same value, and is safe to print
39
+ * to a terminal.
40
+ */
41
+ export function jsonText(value, indent) {
42
+ const json = JSON.stringify(value, null, indent);
43
+ return escapeJsonRaw(json ?? '');
44
+ }
45
+ function escapeJsonRaw(json) {
46
+ return json.replace(JSON_RAW, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, '0')}`);
47
+ }
48
+ /**
49
+ * `io` with stdout made terminal-safe, tab and newline kept. For a command
50
+ * whose stdout is human text that can name repository paths, such as
51
+ * `way dev status`. For JSON output use {@link safeJsonStdout}.
52
+ */
53
+ export function safeStdout(io) {
54
+ return { ...io, stdout: (text) => io.stdout(terminalSafe(text, { multiline: true })) };
55
+ }
56
+ /**
57
+ * `io` with stdout made terminal-safe for JSON output, such as
58
+ * `way dev status --json`. DEL, C1 and the bidi controls are written as `\u`
59
+ * escapes, as {@link jsonText} writes them, so every JSON value stays exact.
60
+ * A raw C0 character other than tab and newline becomes U+FFFD; valid JSON
61
+ * has none, since `JSON.stringify` escapes C0.
62
+ */
63
+ export function safeJsonStdout(io) {
64
+ return {
65
+ ...io,
66
+ stdout: (text) => io.stdout(escapeJsonRaw(text.replace(C0_KEEP_LINES, REPLACEMENT))),
67
+ };
68
+ }
69
+ /**
70
+ * `io` with stderr made terminal-safe. stderr carries only human text:
71
+ * warnings, errors and notes, which can quote config values and file names.
72
+ */
73
+ export function safeStderr(io) {
74
+ return { ...io, stderr: (text) => io.stderr(terminalSafe(text, { multiline: true })) };
75
+ }
76
+ /**
77
+ * Runs `run` and returns its exit code. An error it throws is printed to
78
+ * `stderr` as one terminal-safe line, and the code is `EXIT.error`. For the
79
+ * installed `way`, so an error no command caught cannot reach the terminal
80
+ * raw, as Node's own handler would print it.
81
+ */
82
+ export async function guardedExit(run, stderr = (text) => process.stderr.write(text)) {
83
+ try {
84
+ return await run();
85
+ }
86
+ catch (err) {
87
+ const message = err instanceof Error ? err.message : String(err);
88
+ stderr(`${APP}: ${terminalSafe(message)}\n`);
89
+ return EXIT.error;
90
+ }
91
+ }
package/dist/tools.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Downstream tools: modules that export `ToolDef`s, registered beside the
2
+ * Custom tools: modules that export `ToolDef`s, registered beside the
3
3
  * built-ins. A module is code, so where it was named decides whether it loads:
4
4
  *
5
5
  * --config <module> always; you typed it
@@ -36,9 +36,9 @@ export interface ToolSources {
36
36
  }
37
37
  /**
38
38
  * Load every tool module the sources name, in order: flags, user file,
39
- * project file. Returns the tools and a warning when project entries are
40
- * skipped because the repository is not trusted or execution is off. A tool id that is built in or defined twice is a
41
- * {@link ToolModuleError}.
39
+ * project file. Returns the tools, plus a warning when project entries are
40
+ * skipped because the repository is not trusted or execution is off. A tool id
41
+ * that is built in or defined twice throws {@link ToolModuleError}.
42
42
  */
43
43
  export declare function loadTools(sources: ToolSources): Promise<{
44
44
  tools: LoadedTool[];
package/dist/tools.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Downstream tools: modules that export `ToolDef`s, registered beside the
2
+ * Custom tools: modules that export `ToolDef`s, registered beside the
3
3
  * built-ins. A module is code, so where it was named decides whether it loads:
4
4
  *
5
5
  * --config <module> always; you typed it
@@ -60,9 +60,9 @@ export async function loadToolModule(path) {
60
60
  }
61
61
  /**
62
62
  * Load every tool module the sources name, in order: flags, user file,
63
- * project file. Returns the tools and a warning when project entries are
64
- * skipped because the repository is not trusted or execution is off. A tool id that is built in or defined twice is a
65
- * {@link ToolModuleError}.
63
+ * project file. Returns the tools, plus a warning when project entries are
64
+ * skipped because the repository is not trusted or execution is off. A tool id
65
+ * that is built in or defined twice throws {@link ToolModuleError}.
66
66
  */
67
67
  export async function loadTools(sources) {
68
68
  const { config, home } = sources;
@@ -12,22 +12,21 @@
12
12
  */
13
13
  import { type CliIo } from '@osdlc/cli-tool';
14
14
  /**
15
- * A VIEW of `CliIo`: the same output seam, plus the environment this command
16
- * needs injected — not a third pattern alongside `CliIo` and `ConfigCommandIO`.
15
+ * `CliIo` plus the environment this command needs injected.
17
16
  */
18
17
  export interface TrustCommandIO extends CliIo {
19
18
  /** Defaults to `process.env`. Supplies `XDG_STATE_HOME`. */
20
19
  env?: Record<string, string | undefined>;
21
- /** Defaults to `os.homedir()`. The base for the non-XDG state path. */
20
+ /** Defaults to `homeDir()` from `@osdlc/trust-repo`. The base for the non-XDG state path. */
22
21
  home?: string;
23
22
  }
24
23
  /**
25
24
  * `<tool> trust [--untrust|--show|--list]`. `root` is the resolved project
26
25
  * root. Returns the exit code.
27
26
  *
28
- * Exit codes follow `runConfigCommand`: 2 for a command that cannot run as
29
- * typed, decided from the argument list alone; 1 for a well-formed command that
30
- * failed against the state it found — here, `--untrust` on a root that was
31
- * never trusted, or a project config file that will not parse.
27
+ * Exit codes follow `runConfigCommand`. 2 is a command that cannot run as
28
+ * typed, decided from the arguments alone. 1 is a valid command that failed
29
+ * against the state it found: here, `--untrust` on a root with no marker, or a
30
+ * config file that will not parse.
32
31
  */
33
32
  export declare function runTrustCommand(toolName: string, root: string, argv: string[], io: TrustCommandIO): Promise<number>;
@@ -10,11 +10,11 @@
10
10
  * trust on the developer's machine. The caller strips `-C` with
11
11
  * `takeConfigDir` and hands in a resolved root.
12
12
  */
13
- import { homedir } from 'node:os';
14
13
  import { EXIT } from '@osdlc/cli-tool';
15
- import { policyExecGate } from '@osdlc/trust-repo';
14
+ import { homeDir, policyExecGate } from '@osdlc/trust-repo';
16
15
  import { APP, BIN } from "./app.js";
17
16
  import { ConfigError, PROJECT_CONFIG_FILENAME, loadConfig, trustPolicyFromConfig, trustPolicyOptions, } from "./config.js";
17
+ import { jsonText, terminalSafe } from "./terminal-text.js";
18
18
  import { appTrustStore } from "./trust-store.js";
19
19
  function usage() {
20
20
  return `${BIN} trust — remember that this repository may run subprocesses to be read
@@ -53,9 +53,10 @@ the marker is gone.
53
53
  /**
54
54
  * Split the mode flag off the argument list.
55
55
  *
56
- * The three modes contradict each other and two of them WRITE, so a
57
- * last-one-wins reading would act on a store the user named the other of. A
58
- * pair is a usage error instead, as `--user` and `--project` are for `config`.
56
+ * The three mode flags ask different things, and `--untrust` writes. If the
57
+ * last flag won, a run meant only to read could change the store. Two
58
+ * different modes are a usage error instead, as `--user` and `--project` are
59
+ * for `config`.
59
60
  */
60
61
  function takeMode(argv) {
61
62
  let mode;
@@ -66,8 +67,8 @@ function takeMode(argv) {
66
67
  help = true;
67
68
  }
68
69
  else if (arg === '--json') {
69
- // Not a mode: it asks the SAME question in the machine form, so it
70
- // combines with each of the three rather than contradicting them.
70
+ // Not a mode: it asks the same question in JSON form, so it combines
71
+ // with each of the modes.
71
72
  json = true;
72
73
  }
73
74
  else if (arg === '--untrust' || arg === '--show' || arg === '--list') {
@@ -87,12 +88,11 @@ function takeMode(argv) {
87
88
  return { ...(mode !== undefined ? { mode } : {}), help, json };
88
89
  }
89
90
  /**
90
- * The USER-layer trust.paths/trust.owners policy for `root`, or the rendered
91
- * message when the project's config file will not parse. Lazy — computed only
92
- * by the modes that need a per-root decision (`show`, `untrust`, the plain
93
- * grant), so `--list` and `--help` ask nothing about a particular root and a
94
- * broken project config cannot break them, matching how `main()` only loads
95
- * config for the collection path.
91
+ * The user-layer trust.paths/trust.owners policy for `root`, or the error
92
+ * message when a config file will not parse. Only the modes that decide about
93
+ * one root call it (`show`, `untrust`, the plain grant). So a broken config
94
+ * file cannot break `--list` or `--help`, just as `main()` loads config only
95
+ * when it collects tasks.
96
96
  */
97
97
  async function loadPolicy(root, toolName, env, home) {
98
98
  try {
@@ -109,16 +109,16 @@ async function loadPolicy(root, toolName, env, home) {
109
109
  * `<tool> trust [--untrust|--show|--list]`. `root` is the resolved project
110
110
  * root. Returns the exit code.
111
111
  *
112
- * Exit codes follow `runConfigCommand`: 2 for a command that cannot run as
113
- * typed, decided from the argument list alone; 1 for a well-formed command that
114
- * failed against the state it found — here, `--untrust` on a root that was
115
- * never trusted, or a project config file that will not parse.
112
+ * Exit codes follow `runConfigCommand`. 2 is a command that cannot run as
113
+ * typed, decided from the arguments alone. 1 is a valid command that failed
114
+ * against the state it found: here, `--untrust` on a root with no marker, or a
115
+ * config file that will not parse.
116
116
  */
117
117
  export async function runTrustCommand(toolName, root, argv, io) {
118
118
  const env = io.env ?? process.env;
119
- const home = io.home ?? homedir();
120
- // Keyed on the app name, not `toolName`, so a grant lands in one store
121
- // whichever name the caller printed.
119
+ const home = io.home ?? homeDir();
120
+ // Keyed on the app name, not `toolName`, so every grant lands in one store
121
+ // whatever name the caller prints.
122
122
  const store = appTrustStore({ env, home });
123
123
  const policyOptions = trustPolicyOptions(home);
124
124
  const taken = takeMode(argv);
@@ -131,40 +131,39 @@ export async function runTrustCommand(toolName, root, argv, io) {
131
131
  return EXIT.ok;
132
132
  }
133
133
  /**
134
- * The machine form of every root-scoped answer, in ONE shape across `trust`,
135
- * `--untrust` and `--show`: which root was decided on, whether it is trusted
136
- * now, whether THIS invocation changed the store, and which layer decided
137
- * (`by`/`rule`, mirroring `sdlc repo trust --show`). Three questions with
138
- * three JSON shapes would make a caller branch on the flag it just passed.
134
+ * The JSON answer for `trust`, `--untrust` and `--show`, in one shape: the
135
+ * root decided on, whether it is trusted now, whether this run changed the
136
+ * store, and which layer decided (`by`/`rule`, as `sdlc repo trust --show`
137
+ * reports). One shape means a caller does not branch on the flag it passed.
139
138
  */
140
- const rootAnswer = (path, trusted, changed, by, rule) => `${JSON.stringify({ root: path, trusted, changed, by, rule })}\n`;
139
+ const rootAnswer = (path, trusted, changed, by, rule) => `${jsonText({ root: path, trusted, changed, by, rule })}\n`;
141
140
  switch (taken.mode) {
142
141
  case 'list': {
143
142
  const paths = await store.list();
144
143
  if (taken.json)
145
- io.stdout(`${JSON.stringify({ trusted: paths })}\n`);
144
+ io.stdout(`${jsonText({ trusted: paths })}\n`);
146
145
  else
147
146
  for (const path of paths)
148
- io.stdout(`${path}\n`);
147
+ io.stdout(`${terminalSafe(path)}\n`);
149
148
  return EXIT.ok;
150
149
  }
151
150
  case 'show': {
152
- // Both answers are exit 0: "not trusted" is a fact this command was asked
153
- // for, not a failure to report it.
151
+ // Both answers exit 0. "Not trusted" is the answer that was asked for,
152
+ // not a failure.
154
153
  const policy = await loadPolicy(root, toolName, env, home);
155
154
  if ('error' in policy) {
156
155
  io.stderr(`${toolName}: ${policy.error}\n`);
157
156
  return EXIT.error;
158
157
  }
159
- // Decided through the SAME function that gates a real run
160
- // (`policyExecGate`), so this answer cannot drift from what actually
161
- // governs execution. `configured: true` asks "if execution were on,
162
- // would this root's marker or policy allow it" — the only question
163
- // `--show` has, so `allowExec`/`reason` are unused here.
158
+ // Decided by the same function that checks a real run
159
+ // (`policyExecGate`), so this answer always matches what controls
160
+ // execution. `configured: true` asks "if execution were on, would this
161
+ // root's marker or policy allow it". That is the only question `--show`
162
+ // asks, so `allowExec` and `reason` are unused here.
164
163
  const gate = await policyExecGate(store, policy, { root, configured: true }, policyOptions);
165
164
  io.stdout(taken.json
166
165
  ? rootAnswer(gate.root, gate.trusted, false, gate.by, gate.rule)
167
- : `${gate.trusted ? 'trusted' : 'not trusted'} ${gate.root}\n`);
166
+ : `${gate.trusted ? 'trusted' : 'not trusted'} ${terminalSafe(gate.root)}\n`);
168
167
  return EXIT.ok;
169
168
  }
170
169
  case 'untrust': {
@@ -174,17 +173,16 @@ export async function runTrustCommand(toolName, root, argv, io) {
174
173
  return EXIT.error;
175
174
  }
176
175
  // Resolved first so the message names the path the store is keyed on,
177
- // which is the path a later --list will show.
176
+ // which is the path a later --list shows.
178
177
  const resolved = await store.resolveRoot(root);
179
178
  const removed = await store.untrust(resolved);
180
- // Independent of the marker either way, so it answers the same question
181
- // whether or not this call removed one — the root may still be trusted
182
- // by policy after its marker is gone.
179
+ // Checked whether or not a marker was removed: the root may still be
180
+ // trusted by policy after its marker is gone.
183
181
  const after = await policyExecGate(store, policy, { root, configured: true }, policyOptions);
184
- // The answer goes to stdout either way. A --json caller that gets exit 1
185
- // still gets a document saying what the store held; the failure itself is
186
- // the exit code and the line on stderr, which is where every other aside
187
- // in this package already goes.
182
+ // The JSON answer goes to stdout either way, so a --json caller that gets
183
+ // exit 1 still gets a document. The failure is reported by the exit code
184
+ // and a line on stderr, where every other side message in this package
185
+ // goes.
188
186
  if (taken.json)
189
187
  io.stdout(rootAnswer(resolved, after.trusted, removed, after.by, after.rule));
190
188
  if (!removed) {
@@ -192,9 +190,9 @@ export async function runTrustCommand(toolName, root, argv, io) {
192
190
  return EXIT.error;
193
191
  }
194
192
  if (!taken.json) {
195
- io.stdout(`untrusted ${resolved}\n`);
196
- // Mirrors `sdlc repo untrust`'s note: removing the marker did not
197
- // change the answer when a policy rule covers this root regardless.
193
+ io.stdout(`untrusted ${terminalSafe(resolved)}\n`);
194
+ // Matches `sdlc repo untrust`'s note: when a policy rule covers this
195
+ // root, removing the marker did not change the answer.
198
196
  if (after.trusted) {
199
197
  io.stderr(`note: ${resolved} is still trusted by ${toolName}'s trust.${after.by}s ` +
200
198
  `('${after.rule ?? ''}'); removing the marker changes nothing\n`);
@@ -209,12 +207,12 @@ export async function runTrustCommand(toolName, root, argv, io) {
209
207
  return EXIT.error;
210
208
  }
211
209
  const result = await store.trust(root);
212
- // After granting (or confirming) the marker, the marker itself is
213
- // always why this root is trusted — `trustDecision` checks it first.
210
+ // After the marker is written (or found), the marker is always the
211
+ // reason this root is trusted, because the marker is checked first.
214
212
  const decision = await policyExecGate(store, policy, { root, configured: true }, policyOptions);
215
213
  io.stdout(taken.json
216
214
  ? rootAnswer(result.root, true, !result.alreadyTrusted, decision.by, decision.rule)
217
- : `${result.alreadyTrusted ? 'already trusted' : 'trusted'} ${result.root}\n`);
215
+ : `${result.alreadyTrusted ? 'already trusted' : 'trusted'} ${terminalSafe(result.root)}\n`);
218
216
  return EXIT.ok;
219
217
  }
220
218
  }
@@ -11,7 +11,7 @@ import { type TrustStore } from '@osdlc/trust-repo';
11
11
  export interface AppTrustStoreOptions {
12
12
  /** Defaults to `process.env`. Supplies `XDG_STATE_HOME`. */
13
13
  env?: Record<string, string | undefined>;
14
- /** Defaults to `os.homedir()`. The base for the non-XDG state path. */
14
+ /** Defaults to `homeDir()` from `@osdlc/trust-repo`. The base for the non-XDG state path. */
15
15
  home?: string;
16
16
  }
17
17
  /** The app's trust store: the wayfinder store, plus grants from the waypost one. */