@wasit-dev/cli 0.7.0 → 0.8.0-beta.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.
package/dist/style.js ADDED
@@ -0,0 +1,205 @@
1
+ /**
2
+ * Colours and line layout for a person watching the terminal (Najmi,
3
+ * 2026-11-19): Wasit's own look, in the palette the site and the dashboard use
4
+ * (`dashboard/theme.ts`), a spinner while a check runs, and the run's duration.
5
+ *
6
+ * Colour is a layer over the plain text, never a second wording: every line is
7
+ * sanitised first (`sanitizeText`), then styled, so nothing a service sent can
8
+ * carry an escape sequence of its own. Output that a program reads stays plain:
9
+ * `--json`, a pipe, CI and `NO_COLOR` all get the exact text Wasit printed
10
+ * before colours existed.
11
+ */
12
+ import { THEME } from "./dashboard/theme.js";
13
+ function set(value) {
14
+ return value !== undefined && value !== "";
15
+ }
16
+ /**
17
+ * True when lines may carry colour: `NO_COLOR` set turns it off, `FORCE_COLOR`
18
+ * set (and not "0") turns it on, a dumb terminal and CI are plain, otherwise a
19
+ * TTY is coloured and anything else is not.
20
+ */
21
+ export function colorEnabled(stream, env) {
22
+ if (set(env["NO_COLOR"]))
23
+ return false;
24
+ if (set(env["FORCE_COLOR"]) && env["FORCE_COLOR"] !== "0")
25
+ return true;
26
+ if (env["TERM"] === "dumb")
27
+ return false;
28
+ if (set(env["CI"]) || set(env["GITHUB_ACTIONS"]))
29
+ return false;
30
+ return stream.isTTY === true;
31
+ }
32
+ /**
33
+ * True when a line may be rewritten in place (the running line and its
34
+ * spinner): colour on, and a real terminal. A forced colour into a pipe gets
35
+ * colour but no cursor movement.
36
+ */
37
+ export function liveEnabled(stream, env) {
38
+ return colorEnabled(stream, env) && stream.isTTY === true && !set(env["CI"]) && !set(env["GITHUB_ACTIONS"]);
39
+ }
40
+ /** True when the terminal says it shows 24-bit colour; the brand colours are then exact. */
41
+ export function truecolorEnabled(env) {
42
+ const value = (env["COLORTERM"] ?? "").toLowerCase();
43
+ return value === "truecolor" || value === "24bit";
44
+ }
45
+ export function colorDepth(env) {
46
+ if (truecolorEnabled(env))
47
+ return 24;
48
+ if ((env["TERM"] ?? "").includes("256"))
49
+ return 256;
50
+ return 16;
51
+ }
52
+ /** Each role: its brand colour, and the 16-colour code a plain terminal gets instead. */
53
+ const ROLES = {
54
+ accent: { hex: THEME.accent, basic: 35 },
55
+ muted: { hex: THEME.muted, basic: 90 },
56
+ success: { hex: THEME.success, basic: 32 },
57
+ warning: { hex: THEME.warning, basic: 33 },
58
+ danger: { hex: THEME.danger, basic: 31 },
59
+ error: { hex: "#d946ef", basic: 95 },
60
+ };
61
+ function rgb(hex) {
62
+ const value = Number.parseInt(hex.slice(1), 16);
63
+ return `${(value >> 16) & 255};${(value >> 8) & 255};${value & 255}`;
64
+ }
65
+ /** Black ink on the light backgrounds (green, yellow), white on the dark ones (red, magenta). */
66
+ const BADGE_DARK_INK = { success: true, warning: true, danger: false, error: false };
67
+ /** The 256-colour backgrounds nearest the brand colours. */
68
+ const BADGE_256 = { success: 41, warning: 214, danger: 203, error: 171 };
69
+ const BADGE_16 = { success: 42, warning: 43, danger: 41, error: 45 };
70
+ /**
71
+ * The SGR parameters of a badge. The ink is given exactly (24-bit or 256-colour
72
+ * black and white), never as a bold colour of the 16: a terminal that draws bold
73
+ * text in bright colours (VS Code and iTerm2 by default) turns bold black into
74
+ * grey, which melts into a green or yellow background. On a 16-colour terminal
75
+ * black ink is not bold, for the same reason.
76
+ */
77
+ function badgeParams(role, depth) {
78
+ const dark = BADGE_DARK_INK[role];
79
+ if (depth === 24)
80
+ return `1;${dark ? "38;2;0;0;0" : "38;2;255;255;255"};48;2;${rgb(ROLES[role].hex)}`;
81
+ if (depth === 256)
82
+ return `1;${dark ? "38;5;16" : "38;5;231"};48;5;${BADGE_256[role]}`;
83
+ return dark ? `30;${BADGE_16[role]}` : `1;97;${BADGE_16[role]}`;
84
+ }
85
+ /**
86
+ * A styler. `depth` is the terminal's colour depth (`colorDepth`); `true` is
87
+ * read as 24-bit, `false` or nothing as the 16 colours of every terminal.
88
+ */
89
+ export function styler(enabled, depth = 16) {
90
+ const bits = depth === true ? 24 : depth === false ? 16 : depth;
91
+ const truecolor = bits === 24;
92
+ return {
93
+ enabled,
94
+ badge(label, role) {
95
+ if (!enabled)
96
+ return label;
97
+ return `\u001b[${badgeParams(role, bits)}m ${label} \u001b[22;39;49m`;
98
+ },
99
+ paint(text, ...roles) {
100
+ if (!enabled || roles.length === 0 || text === "")
101
+ return text;
102
+ let open = "";
103
+ let close = "";
104
+ for (const role of roles) {
105
+ if (role === "bold" || role === "dim") {
106
+ open += role === "bold" ? "\u001b[1m" : "\u001b[2m";
107
+ close = `\u001b[22m${close}`;
108
+ continue;
109
+ }
110
+ const { hex, basic } = ROLES[role];
111
+ open += truecolor ? `\u001b[38;2;${rgb(hex)}m` : `\u001b[${basic}m`;
112
+ close = `\u001b[39m${close}`;
113
+ }
114
+ return `${open}${text}${close}`;
115
+ },
116
+ };
117
+ }
118
+ /** The SGR sequences this module writes, and only those, for measuring a line. */
119
+ const SGR = /\u001b\[[0-9;]*m/g;
120
+ /** The width a line takes on screen: its length without the colour codes. */
121
+ export function visibleLength(text) {
122
+ return [...text.replace(SGR, "")].length;
123
+ }
124
+ /**
125
+ * A check's status as a mark and a badge that agree (Najmi, 2026-11-20):
126
+ * ✓ PASS, ✗ FAIL, ○ SKIP, ! ERROR (the check could not run). Text marks, not
127
+ * emoji: an emoji takes two columns in many terminals and breaks the columns.
128
+ */
129
+ export const MARKS = {
130
+ PASS: { mark: "✓", markRole: "success", badge: "PASS", badgeRole: "success" },
131
+ FAIL: { mark: "✗", markRole: "danger", badge: "FAIL", badgeRole: "danger" },
132
+ SKIP: { mark: "○", markRole: "warning", badge: "SKIP", badgeRole: "warning" },
133
+ ERROR: { mark: "!", markRole: "error", badge: "ERROR", badgeRole: "error" },
134
+ };
135
+ /** The spinner's frames, as the dashboard draws them, one every 80 ms. */
136
+ export const SPINNER_FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
137
+ export const SPINNER_MS = 80;
138
+ /** "12ms" under a second, "6.82s" from a second on. */
139
+ export function duration(ms) {
140
+ if (ms < 1000)
141
+ return `${Math.max(0, Math.round(ms))}ms`;
142
+ return `${(ms / 1000).toFixed(2)}s`;
143
+ }
144
+ /**
145
+ * `left` and `right` on one line, `right` flush with the width. A line that
146
+ * does not fit keeps two spaces between them and runs over.
147
+ */
148
+ export function spread(left, right, width) {
149
+ if (right === "")
150
+ return left;
151
+ const gap = Math.max(2, width - visibleLength(left) - visibleLength(right));
152
+ return `${left}${" ".repeat(gap)}${right}`;
153
+ }
154
+ /** Cuts plain text to `max` characters, ending in "…". */
155
+ export function truncate(text, max) {
156
+ const chars = [...text];
157
+ if (chars.length <= max)
158
+ return text;
159
+ if (max <= 1)
160
+ return "…".slice(0, Math.max(0, max));
161
+ return `${chars.slice(0, max - 1).join("")}…`;
162
+ }
163
+ /**
164
+ * A wrapped line that would start with a workflow command once the runner trims
165
+ * its indent (`::name::`, `##[name]`), broken the way the sanitiser breaks one
166
+ * at the start of a text. Wrapping makes new line starts out of words in the
167
+ * middle of a text, after the sanitiser ran, so each one is checked here.
168
+ */
169
+ function breakCommandStart(line) {
170
+ return line.replace(/^(::|##\[)/, (command) => (command === "::" ? ": :" : "# #["));
171
+ }
172
+ /**
173
+ * Plain text wrapped to `width` columns, every line after `indent`. A word
174
+ * longer than a line (a URL, a hash) is kept whole and runs over. No line
175
+ * starts with a workflow command (`breakCommandStart`).
176
+ */
177
+ export function wrap(text, width, indent) {
178
+ const room = Math.max(20, width - [...indent].length);
179
+ const lines = [];
180
+ let current = "";
181
+ for (const word of text.split(/\s+/).filter((part) => part !== "")) {
182
+ if (current === "")
183
+ current = word;
184
+ else if ([...current].length + 1 + [...word].length <= room)
185
+ current += ` ${word}`;
186
+ else {
187
+ lines.push(current);
188
+ current = word;
189
+ }
190
+ }
191
+ if (current !== "")
192
+ lines.push(current);
193
+ return lines.map((line) => `${indent}${breakCommandStart(line)}`);
194
+ }
195
+ /**
196
+ * The width lines are laid out to: one column less than the terminal's (a line
197
+ * as wide as the screen makes some terminals start a new line), at most 100,
198
+ * 80 when unknown.
199
+ */
200
+ export function lineWidth(stream) {
201
+ const columns = stream.columns;
202
+ if (columns === undefined || !Number.isFinite(columns) || columns <= 0)
203
+ return 80;
204
+ return Math.max(20, Math.min(100, Math.floor(columns) - 1));
205
+ }
@@ -0,0 +1,26 @@
1
+ /**
2
+ * `wasit test` for a person at a terminal: the same checks, notes and exit code
3
+ * as the plain output, drawn live (a RUNNING line with a timer while a check is
4
+ * in flight, each result as it arrives, the counts and the duration at the end).
5
+ *
6
+ * Its own module so that a test can drive it with a stream, an environment and
7
+ * stand-in checks, and hold it to what the plain output promises: every text a
8
+ * service chose is sanitised, and no secret of the environment is printed.
9
+ */
10
+ import { runX402PaymentChecks, runX402ReadChecks } from "@wasit-dev/core";
11
+ import { type LiveStream } from "./live.js";
12
+ export interface LiveTestShape {
13
+ method?: string;
14
+ body?: string;
15
+ headers?: Record<string, string>;
16
+ }
17
+ export interface LiveTestDeps {
18
+ /** Where the output goes: `process.stdout` in the CLI. */
19
+ readonly stream: LiveStream;
20
+ /** The environment the payer key and the secrets are read from: `process.env` in the CLI. */
21
+ readonly env: Readonly<Record<string, string | undefined>>;
22
+ /** The checks, replaceable in tests. */
23
+ readonly readChecks?: typeof runX402ReadChecks;
24
+ readonly paymentChecks?: typeof runX402PaymentChecks;
25
+ }
26
+ export declare function liveX402Test(opts: Record<string, unknown>, shape: LiveTestShape, deps: LiveTestDeps): Promise<number>;
@@ -0,0 +1,81 @@
1
+ /**
2
+ * `wasit test` for a person at a terminal: the same checks, notes and exit code
3
+ * as the plain output, drawn live (a RUNNING line with a timer while a check is
4
+ * in flight, each result as it arrives, the counts and the duration at the end).
5
+ *
6
+ * Its own module so that a test can drive it with a stream, an environment and
7
+ * stand-in checks, and hold it to what the plain output promises: every text a
8
+ * service chose is sanitised, and no secret of the environment is printed.
9
+ */
10
+ import { X402_PAYMENT_CHECK_IDS, catalogueEntry, deniedEnvValues, endpointOutcome, networkClass, paymentChainFor, runX402PaymentChecks, runX402ReadChecks, sanitizeText, } from "@wasit-dev/core";
11
+ import { LiveReport } from "./live.js";
12
+ import { exitCodeFor, verdictNotes } from "./output.js";
13
+ import { colorDepth, liveEnabled } from "./style.js";
14
+ import { CLI_VERSION } from "./version.js";
15
+ export async function liveX402Test(opts, shape, deps) {
16
+ const { stream, env } = deps;
17
+ const readChecks = deps.readChecks ?? runX402ReadChecks;
18
+ const paymentChecks = deps.paymentChecks ?? runX402PaymentChecks;
19
+ const secrets = deniedEnvValues(env);
20
+ const live = new LiveReport({
21
+ stream,
22
+ live: liveEnabled(stream, env),
23
+ depth: colorDepth(env),
24
+ clean: (text) => sanitizeText(text, { redact: secrets }),
25
+ });
26
+ const target = opts["target"];
27
+ const network = opts["network"];
28
+ live.header(CLI_VERSION, "x402 conformance", [
29
+ ["target", `${target}${shape.method !== undefined ? ` ${shape.method.toUpperCase()}` : ""}`],
30
+ ["network", network],
31
+ ]);
32
+ live.phase("challenge", [["no payment"]]);
33
+ live.running("X402-01..05", "Challenge checks");
34
+ const results = await readChecks({ target, ...shape, onResult: (result) => live.result(result) });
35
+ live.gap();
36
+ const keyEnv = paymentChainFor(network)?.payerKeyEnv ?? "STELLAR_PRIVATE_KEY";
37
+ const payerKey = opts["payerKey"] ?? env[keyEnv];
38
+ if (opts["readOnly"] === true) {
39
+ live.phase("payment", [["not run"]]);
40
+ live.note("--read-only set: the payment checks were not run.");
41
+ }
42
+ else if (!payerKey) {
43
+ live.phase("payment", [["not run"]]);
44
+ live.note(`No payer key: set ${keyEnv} in .env or pass --payer-key. The payment checks were not run.`);
45
+ }
46
+ else if (networkClass(network) !== "test") {
47
+ // Not a test network: the guard refuses the payment checks before anything
48
+ // is signed (the PREFLIGHT line says why), so no money moves.
49
+ live.phase("payment", [[network], ["not a test network: refused", "danger"]]);
50
+ }
51
+ else {
52
+ live.phase("payment", [[network], ["testnet funds move", "warning"]]);
53
+ live.note(`When the target offers a ${network} option, X402-06 settles a real payment and X402-07..10 send ` +
54
+ "payments it must refuse.");
55
+ }
56
+ if (opts["readOnly"] !== true && payerKey) {
57
+ const order = X402_PAYMENT_CHECK_IDS;
58
+ const startAt = (index) => {
59
+ const id = order[index];
60
+ if (id !== undefined)
61
+ live.running(id, catalogueEntry(id)?.name ?? id);
62
+ };
63
+ startAt(0);
64
+ results.push(...(await paymentChecks({
65
+ target,
66
+ network,
67
+ payerSecretKey: payerKey,
68
+ ...(opts["rpcUrl"] ? { rpcUrl: opts["rpcUrl"] } : {}),
69
+ ...shape,
70
+ onResult: (result) => {
71
+ live.result(result);
72
+ const index = order.indexOf(result.id);
73
+ if (index >= 0)
74
+ startAt(index + 1);
75
+ },
76
+ onProgress: (line) => live.progress(line),
77
+ })));
78
+ }
79
+ live.finish(results, endpointOutcome(results, "x402"), verdictNotes(results, "x402"));
80
+ return exitCodeFor(results, "x402");
81
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wasit-dev/cli",
3
- "version": "0.7.0",
3
+ "version": "0.8.0-beta.2",
4
4
  "description": "CLI for x402/MPP protocol-conformance testing on Stellar — verifies a service's payment flow settles on-chain per spec.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -37,11 +37,11 @@
37
37
  },
38
38
  "scripts": {
39
39
  "build": "tsc -p tsconfig.json",
40
- "test": "node --import tsx --test \"test/unit/**/*.test.ts*\"",
40
+ "test": "node --import tsx --test --test-timeout=120000 \"test/unit/**/*.test.ts*\"",
41
41
  "typecheck": "tsc -p test/tsconfig.json"
42
42
  },
43
43
  "dependencies": {
44
- "@wasit-dev/core": "^0.7.0",
44
+ "@wasit-dev/core": "^0.8.0-beta.2",
45
45
  "cfonts": "^3.3.1",
46
46
  "commander": "^15.0.0",
47
47
  "dotenv": "^17.4.2",