@blackbelt-technology/pi-dashboard-mcp-client-plugin 0.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.
@@ -0,0 +1,170 @@
1
+ /**
2
+ * mcp-client-plugin · client hooks.
3
+ *
4
+ * `useEffectiveConfig` reads `/api/mcp-client/effective` through a module-level
5
+ * store that keeps ONE in-flight request per key (global = `""`, else the cwd)
6
+ * and caches the last success, so several components mounting together issue a
7
+ * single request and a remount is free.
8
+ *
9
+ * `useLiveState` reads `/api/mcp-client/live` on mount (page view) and on an
10
+ * explicit refresh only — the command connects to every server, so it is slow.
11
+ *
12
+ * See change: migrate-mcp-to-pi-builtin.
13
+ */
14
+ import { useCallback, useEffect, useState } from "react";
15
+ import type { EffectiveView, LiveState } from "../core/types.js";
16
+ import { ApiError, fetchEffective, fetchLive } from "./api.js";
17
+
18
+ // ─── effective config store ──────────────────────────────────────────────────
19
+
20
+ const cache = new Map<string, EffectiveView>();
21
+ const inflight = new Map<string, Promise<EffectiveView>>();
22
+
23
+ /**
24
+ * Per-cwd 403 cache. The server is the ONLY source of cwd admission (the slot
25
+ * contract passes `{cwd,label}` only), so once a cwd is refused there is no
26
+ * point re-asking until the client's session / pinned-folder list changes —
27
+ * that list is what can turn an unknown folder into a known one. A refused key
28
+ * therefore short-circuits `loadEffective` and re-renders the not-tracked state
29
+ * without touching the network.
30
+ */
31
+ const notTracked = new Map<string, ApiError>();
32
+
33
+ function keyOf(cwd?: string): string {
34
+ return cwd ?? "";
35
+ }
36
+
37
+ /** Test-only: drop every cached 403 so each test starts from a clean slate. */
38
+ export function __resetNotTrackedCache(): void {
39
+ notTracked.clear();
40
+ }
41
+
42
+ /**
43
+ * Load the effective view, sharing one in-flight request per key and reusing
44
+ * the cached success. `force` bypasses both (a user-initiated reload/refresh).
45
+ */
46
+ export function loadEffective(
47
+ cwd?: string,
48
+ opts: { force?: boolean } = {},
49
+ ): Promise<EffectiveView> {
50
+ const key = keyOf(cwd);
51
+ if (!opts.force) {
52
+ const refused = notTracked.get(key);
53
+ if (refused) return Promise.reject(refused);
54
+ const pending = inflight.get(key);
55
+ if (pending) return pending;
56
+ const hit = cache.get(key);
57
+ if (hit) return Promise.resolve(hit);
58
+ }
59
+ const request = fetchEffective(cwd).then(
60
+ (view) => {
61
+ // A superseded request (invalidated, or replaced by a forced reload) must
62
+ // not repopulate the cache with a now-stale body.
63
+ if (inflight.get(key) === request) {
64
+ cache.set(key, view);
65
+ inflight.delete(key);
66
+ notTracked.delete(key);
67
+ }
68
+ return view;
69
+ },
70
+ (err: unknown) => {
71
+ if (inflight.get(key) === request) inflight.delete(key);
72
+ // Remember a cwd refusal so a remount / sibling pill does not re-ask.
73
+ if (err instanceof ApiError && err.isNotAllowed) notTracked.set(key, err);
74
+ throw err;
75
+ },
76
+ );
77
+ inflight.set(key, request);
78
+ return request;
79
+ }
80
+
81
+ /** Drop the cached view — and any cached 403 — for one key after a write. */
82
+ export function invalidateEffective(cwd?: string): void {
83
+ const key = keyOf(cwd);
84
+ cache.delete(key);
85
+ inflight.delete(key);
86
+ notTracked.delete(key);
87
+ }
88
+
89
+ export interface EffectiveState {
90
+ view: EffectiveView | null;
91
+ loading: boolean;
92
+ error: unknown;
93
+ /** Re-fetch, bypassing the cache. */
94
+ reload: () => void;
95
+ }
96
+
97
+ /** The effective view for a cwd (global when omitted). */
98
+ export function useEffectiveConfig(cwd?: string): EffectiveState {
99
+ const [view, setView] = useState<EffectiveView | null>(() => cache.get(keyOf(cwd)) ?? null);
100
+ const [loading, setLoading] = useState(view === null);
101
+ const [error, setError] = useState<unknown>(null);
102
+ const [nonce, setNonce] = useState(0);
103
+
104
+ useEffect(() => {
105
+ let alive = true;
106
+ setLoading(true);
107
+ loadEffective(cwd, nonce > 0 ? { force: true } : {})
108
+ .then((v) => {
109
+ if (!alive) return;
110
+ setView(v);
111
+ setError(null);
112
+ })
113
+ .catch((e: unknown) => {
114
+ if (alive) setError(e);
115
+ })
116
+ .finally(() => {
117
+ if (alive) setLoading(false);
118
+ });
119
+ return () => {
120
+ alive = false;
121
+ };
122
+ }, [cwd, nonce]);
123
+
124
+ const reload = useCallback(() => setNonce((n) => n + 1), []);
125
+ return { view, loading, error, reload };
126
+ }
127
+
128
+ // ─── live state ──────────────────────────────────────────────────────────────
129
+
130
+ export interface LiveStateHook {
131
+ live: LiveState | null;
132
+ loading: boolean;
133
+ /** Re-run the live command (explicit refresh). */
134
+ refresh: () => void;
135
+ }
136
+
137
+ /**
138
+ * Live state for a scope. Fetches on mount (page view) and on `refresh()`
139
+ * only — never on an interval — and renders `null` until the result lands so
140
+ * the list can render from `/effective` first. A failure leaves `live` null
141
+ * (rows read "state unknown"); it is not a page error.
142
+ */
143
+ export function useLiveState(cwd?: string): LiveStateHook {
144
+ const [live, setLive] = useState<LiveState | null>(null);
145
+ const [loading, setLoading] = useState(true);
146
+ const [nonce, setNonce] = useState(0);
147
+
148
+ // biome-ignore lint/correctness/useExhaustiveDependencies: nonce is the explicit-refresh remount key
149
+ useEffect(() => {
150
+ let alive = true;
151
+ setLoading(true);
152
+ // nonce 0 = page view (server cache ok); > 0 = explicit refresh (fresh).
153
+ fetchLive(cwd, nonce > 0 ? { fresh: true } : undefined)
154
+ .then((v) => {
155
+ if (alive) setLive(v);
156
+ })
157
+ .catch(() => {
158
+ if (alive) setLive(null);
159
+ })
160
+ .finally(() => {
161
+ if (alive) setLoading(false);
162
+ });
163
+ return () => {
164
+ alive = false;
165
+ };
166
+ }, [cwd, nonce]);
167
+
168
+ const refresh = useCallback(() => setNonce((n) => n + 1), []);
169
+ return { live, loading, refresh };
170
+ }
@@ -0,0 +1,9 @@
1
+ /**
2
+ * mcp-client-plugin · CLIENT entry — settings section + folder pill + folder page.
3
+ * The folder surfaces (pills + page) land in change extract-mcp-client-plugin
4
+ * section 8.
5
+ */
6
+
7
+ export { FolderMcpPage } from "./FolderMcpPage.js";
8
+ export { FolderMcpSection } from "./FolderMcpSection.js";
9
+ export { McpSettingsClaim } from "./McpSettings.js";
@@ -0,0 +1,442 @@
1
+ /**
2
+ * mcp-client-plugin · client schema model.
3
+ *
4
+ * Turns the published JSON Schema (`GET /api/mcp-client/schema`, authored at
5
+ * `schema/mcp-config.schema.json`) into the editor's field list: widget
6
+ * selection, transport tagging, secret markers — plus the pure helpers the
7
+ * editor and its tests share (clone/equality, redaction sentinels, the
8
+ * whole-entry save builder, save validation).
9
+ *
10
+ * `widgetFor` always ends in a concrete widget or the JSON fallback, so no
11
+ * schema field can ever be silently dropped (spec: any field without a widget
12
+ * falls back to a validated JSON editor). The exposure `codemode-deferred`
13
+ * alias resolves for DISPLAY only — an unchanged draft keeps the stored value.
14
+ *
15
+ * See change: migrate-mcp-to-pi-builtin.
16
+ */
17
+ import { displayExposure, MCP_EXPOSURE_ALIASES } from "../core/pi-rules.js";
18
+
19
+ export type Transport = "command" | "url";
20
+
21
+ export interface JsonSchema {
22
+ type?: string;
23
+ enum?: (string | number)[];
24
+ items?: JsonSchema;
25
+ properties?: Record<string, JsonSchema>;
26
+ additionalProperties?: JsonSchema | boolean;
27
+ oneOf?: JsonSchema[];
28
+ $ref?: string;
29
+ "x-transport"?: string;
30
+ "x-secret"?: boolean;
31
+ "x-global-only"?: boolean;
32
+ [key: string]: unknown;
33
+ }
34
+
35
+ export type WidgetKind =
36
+ | "text"
37
+ | "number"
38
+ | "boolean"
39
+ | "enum"
40
+ | "string-list"
41
+ | "nested-group"
42
+ | "record"
43
+ | "json";
44
+
45
+ export interface FieldSchema {
46
+ /** Dotted path (`oauth.clientSecret`) — also the testid suffix. */
47
+ name: string;
48
+ path: string[];
49
+ schema: JsonSchema;
50
+ widget: WidgetKind;
51
+ transport: Transport | null;
52
+ secret: boolean;
53
+ /** `x-global-only`: pi reads the field only from the global file. */
54
+ globalOnly: boolean;
55
+ enumValues?: string[];
56
+ /** For a record of enums (`toolExposure`): the canonical value options. */
57
+ valueEnum?: string[];
58
+ /**
59
+ * Display resolver for stored aliases (`codemode-deferred` → `codemode`):
60
+ * the control shows the resolved value but keeps the stored one unchanged.
61
+ */
62
+ displayResolver?: (value: unknown) => string;
63
+ /** Sub-widgets of a nested group. */
64
+ children?: FieldSchema[];
65
+ }
66
+
67
+ // ─── schema traversal ────────────────────────────────────────────────────────
68
+
69
+ export function defsOf(doc: Record<string, unknown>): Record<string, JsonSchema> {
70
+ const defs = doc.$defs;
71
+ return defs !== null && typeof defs === "object"
72
+ ? (defs as Record<string, JsonSchema>)
73
+ : {};
74
+ }
75
+
76
+ /** Canonical enum options: the stored alias (`codemode-deferred`) is display-only. */
77
+ function canonicalEnumValues(values: (string | number)[]): string[] {
78
+ return values
79
+ .filter((v): v is string => typeof v === "string")
80
+ .filter((v) => !(v in MCP_EXPOSURE_ALIASES));
81
+ }
82
+
83
+ /** Resolve a `$ref: "#/$defs/X"` node, keeping the referencing node's markers. */
84
+ function resolveRef(schema: JsonSchema, defs: Record<string, JsonSchema>): JsonSchema {
85
+ if (typeof schema.$ref !== "string") return schema;
86
+ const target = defs[schema.$ref.split("/").pop() ?? ""];
87
+ if (!target) return schema;
88
+ const merged: Record<string, unknown> = { ...target };
89
+ for (const key of ["x-transport", "x-secret", "x-global-only"] as const) {
90
+ if (schema[key] !== undefined) merged[key] = schema[key];
91
+ }
92
+ return merged as JsonSchema;
93
+ }
94
+
95
+ function isObjectSchema(s: JsonSchema): boolean {
96
+ return s.type === "object" && s.properties !== undefined && Object.keys(s.properties).length > 0;
97
+ }
98
+
99
+ /** The non-union widget for a concrete `type`; unknown shapes → "json". */
100
+ function simpleWidget(s: JsonSchema): WidgetKind {
101
+ switch (s.type) {
102
+ case "string":
103
+ return "text";
104
+ case "number":
105
+ return "number";
106
+ case "boolean":
107
+ return "boolean";
108
+ case "array":
109
+ return s.items?.type === "string" ? "string-list" : "json";
110
+ case "object":
111
+ return isObjectSchema(s) ? "nested-group" : "record";
112
+ default:
113
+ return "json";
114
+ }
115
+ }
116
+
117
+ /** The widget a field renders as. NEVER null/undefined — unknown shapes → "json". */
118
+ export function widgetFor(schema: JsonSchema, defs: Record<string, JsonSchema> = {}): WidgetKind {
119
+ const s = resolveRef(schema, defs);
120
+ if (Array.isArray(s.enum)) return "enum";
121
+ if (Array.isArray(s.oneOf)) return "json";
122
+ return simpleWidget(s);
123
+ }
124
+
125
+ function enumExtras(resolved: JsonSchema): Pick<FieldSchema, "enumValues" | "displayResolver"> {
126
+ if (!Array.isArray(resolved.enum)) return {};
127
+ const extras: Pick<FieldSchema, "enumValues" | "displayResolver"> = {
128
+ enumValues: canonicalEnumValues(resolved.enum),
129
+ };
130
+ if (resolved.enum.some((v) => typeof v === "string" && v in MCP_EXPOSURE_ALIASES)) {
131
+ extras.displayResolver = displayExposure;
132
+ }
133
+ return extras;
134
+ }
135
+
136
+ function fieldFor(
137
+ name: string,
138
+ prop: JsonSchema,
139
+ defs: Record<string, JsonSchema>,
140
+ parents: string[],
141
+ ): FieldSchema {
142
+ const resolved = resolveRef(prop, defs);
143
+ const field: FieldSchema = {
144
+ name: [...parents, name].join("."),
145
+ path: [...parents, name],
146
+ schema: resolved,
147
+ widget: widgetFor(prop, defs),
148
+ transport:
149
+ resolved["x-transport"] === "command" || resolved["x-transport"] === "url"
150
+ ? resolved["x-transport"]
151
+ : null,
152
+ secret: resolved["x-secret"] === true,
153
+ globalOnly: resolved["x-global-only"] === true,
154
+ };
155
+ Object.assign(field, enumExtras(resolved));
156
+ // A record of enum values (`toolExposure`): rows render a select.
157
+ const additional = resolved.additionalProperties;
158
+ if (field.widget === "record" && additional && typeof additional === "object") {
159
+ const valueSchema = resolveRef(additional, defs);
160
+ if (Array.isArray(valueSchema.enum)) {
161
+ field.valueEnum = canonicalEnumValues(valueSchema.enum);
162
+ if (valueSchema.enum.some((v) => typeof v === "string" && v in MCP_EXPOSURE_ALIASES)) {
163
+ field.displayResolver = displayExposure;
164
+ }
165
+ }
166
+ }
167
+ if (field.widget === "nested-group") {
168
+ field.children = Object.entries(resolved.properties ?? {}).map(([child, childProp]) =>
169
+ fieldFor(child, childProp, defs, [...parents, name]),
170
+ );
171
+ }
172
+ return field;
173
+ }
174
+
175
+ /** The editor's field list, in schema order, from `$defs.ServerEntry`. */
176
+ export function fieldsOf(doc: Record<string, unknown>): FieldSchema[] {
177
+ const defs = defsOf(doc);
178
+ const props = defs.ServerEntry?.properties ?? {};
179
+ return Object.entries(props).map(([name, prop]) => fieldFor(name, prop, defs, []));
180
+ }
181
+
182
+ // ─── transport grouping ──────────────────────────────────────────────────────
183
+
184
+ /**
185
+ * Fields scoped to one transport. `x-transport` tags the two primary fields;
186
+ * the companions are the spec's tab groups (the url tab hides command/args/env,
187
+ * shows url/headers/auth/oauth). Saving drops the INACTIVE transport's keys,
188
+ * so the stored entry always carries one transport.
189
+ */
190
+ export const TRANSPORT_FIELDS: Record<Transport, readonly string[]> = {
191
+ command: ["command", "args", "env", "cwd"],
192
+ url: ["url", "headers", "auth", "oauth"],
193
+ };
194
+
195
+ export function visibleUnderTransport(name: string, tab: Transport): boolean {
196
+ for (const transport of Object.keys(TRANSPORT_FIELDS) as Transport[]) {
197
+ if (transport !== tab && TRANSPORT_FIELDS[transport].includes(name)) return false;
198
+ }
199
+ return true;
200
+ }
201
+
202
+ // ─── secret masking ──────────────────────────────────────────────────────────
203
+
204
+ /** Credential-name pattern — the EXACT regex the server's redaction uses. */
205
+ const SECRET_KEY_PATTERN = /authorization|token|key|secret/i;
206
+
207
+ /** True when an `env`/`headers` key NAME looks like a credential. */
208
+ export function isSecretKeyName(name: string): boolean {
209
+ return SECRET_KEY_PATTERN.test(name);
210
+ }
211
+
212
+ /**
213
+ * A `${NAME}` reference or a leading `!` (a command) is shown AS WRITTEN —
214
+ * it is not itself a secret (spec: values that reference a secret are not
215
+ * masked).
216
+ */
217
+ export function isLiteralValue(value: unknown): boolean {
218
+ return typeof value === "string" && (value.startsWith("!") || /\$\{[^}]+\}/.test(value));
219
+ }
220
+
221
+ /** Whether a record value renders masked: secret field / credential key, and not a literal. */
222
+ export function isMaskedValue(fieldSecret: boolean, key: string, value: unknown): boolean {
223
+ if (isLiteralValue(value)) return false;
224
+ return fieldSecret || isSecretKeyName(key);
225
+ }
226
+
227
+ // ─── redaction sentinels ─────────────────────────────────────────────────────
228
+
229
+ /** `{ redacted: true }` (scalar) or `{ redacted: true, keys: [...] }` (record). */
230
+ export function isRedacted(value: unknown): boolean {
231
+ return (
232
+ typeof value === "object" &&
233
+ value !== null &&
234
+ !Array.isArray(value) &&
235
+ (value as { redacted?: unknown }).redacted === true
236
+ );
237
+ }
238
+
239
+ /**
240
+ * Recursively remove redaction sentinels — a marker the server sent in a
241
+ * project view must never be sent back (an override is a WHOLE entry).
242
+ */
243
+ export function stripRedacted<T>(value: T): T | undefined {
244
+ if (isRedacted(value)) return undefined;
245
+ if (Array.isArray(value)) return value.map((entry) => stripRedacted(entry)) as unknown as T;
246
+ if (value !== null && typeof value === "object") {
247
+ const out: Record<string, unknown> = {};
248
+ for (const [key, entry] of Object.entries(value)) {
249
+ const stripped = stripRedacted(entry);
250
+ if (stripped !== undefined) out[key] = stripped;
251
+ }
252
+ return out as T;
253
+ }
254
+ return value;
255
+ }
256
+
257
+ // ─── draft model ─────────────────────────────────────────────────────────────
258
+
259
+ export function clone<T>(value: T): T {
260
+ return JSON.parse(JSON.stringify(value ?? null)) as T;
261
+ }
262
+
263
+ export function deepEqual(a: unknown, b: unknown): boolean {
264
+ if (a === b) return true;
265
+ if (a === null || b === null || typeof a !== "object" || typeof b !== "object") return false;
266
+ const keysA = Object.keys(a);
267
+ const keysB = Object.keys(b);
268
+ if (keysA.length !== keysB.length) return false;
269
+ return keysA.every((k) =>
270
+ deepEqual((a as Record<string, unknown>)[k], (b as Record<string, unknown>)[k]),
271
+ );
272
+ }
273
+
274
+ /**
275
+ * The WHOLE entry a save writes: every draft key (unknown ones included —
276
+ * pi preserves them), redaction sentinels stripped, the INACTIVE transport's
277
+ * keys dropped, `auth` dropped at project scope (pi reads it only from the
278
+ * global file).
279
+ */
280
+ export function buildEntry(
281
+ draft: Record<string, unknown>,
282
+ tab: Transport,
283
+ scope: { kind: "global" } | { kind: "project"; cwd: string },
284
+ ): Record<string, unknown> {
285
+ const out: Record<string, unknown> = {};
286
+ for (const [key, value] of Object.entries(draft)) {
287
+ const cleaned = stripRedacted(value);
288
+ if (cleaned === undefined) continue;
289
+ out[key] = cleaned;
290
+ }
291
+ const inactive: Transport = tab === "url" ? "command" : "url";
292
+ for (const field of TRANSPORT_FIELDS[inactive]) delete out[field];
293
+ if (scope.kind === "project") delete out.auth;
294
+ return out;
295
+ }
296
+
297
+ export function getPath(obj: unknown, path: string[]): unknown {
298
+ let current: unknown = obj;
299
+ for (const key of path) {
300
+ if (current === null || typeof current !== "object") return undefined;
301
+ current = (current as Record<string, unknown>)[key];
302
+ }
303
+ return current;
304
+ }
305
+
306
+ /** Immutably write (or, when `value === undefined`, delete) `path` in a clone. */
307
+ export function setPath<T extends Record<string, unknown>>(obj: T, path: string[], value: unknown): T {
308
+ const root = clone(obj);
309
+ if (path.length === 0) return root;
310
+ let current: Record<string, unknown> = root;
311
+ for (let i = 0; i < path.length - 1; i++) {
312
+ const key = path[i] as string;
313
+ const next = current[key];
314
+ if (next === null || typeof next !== "object" || Array.isArray(next)) current[key] = {};
315
+ current = current[key] as Record<string, unknown>;
316
+ }
317
+ const last = path[path.length - 1] as string;
318
+ if (value === undefined) delete current[last];
319
+ else current[last] = value;
320
+ return root;
321
+ }
322
+
323
+ // ─── save validation ─────────────────────────────────────────────────────────
324
+
325
+ /** Raw (unparsed) textarea/number text keyed by dotted field name. */
326
+ export type RawText = Record<string, string>;
327
+
328
+ interface ValidationCtx {
329
+ draft: Record<string, unknown>;
330
+ raw: RawText;
331
+ errors: Record<string, string>;
332
+ }
333
+
334
+ type Validator = (field: FieldSchema, value: unknown, ctx: ValidationCtx) => void;
335
+
336
+ function validateNumber(field: FieldSchema, value: unknown, ctx: ValidationCtx): void {
337
+ const rawText = ctx.raw[field.name];
338
+ if (rawText !== undefined && rawText.trim() !== "" && !Number.isFinite(Number(rawText))) {
339
+ ctx.errors[field.name] = "Must be a number";
340
+ } else if (value !== undefined && typeof value !== "number") {
341
+ ctx.errors[field.name] = "Must be a number";
342
+ }
343
+ }
344
+
345
+ function validateEnum(field: FieldSchema, value: unknown, ctx: ValidationCtx): void {
346
+ if (value === undefined) return;
347
+ // A stored alias (`codemode-deferred`) validates against its display form.
348
+ const check = field.displayResolver ? field.displayResolver(value) : value;
349
+ if (!(field.enumValues ?? []).includes(check as string)) {
350
+ ctx.errors[field.name] = "Not a valid option";
351
+ }
352
+ }
353
+
354
+ function validateList(field: FieldSchema, value: unknown, ctx: ValidationCtx): void {
355
+ const rows = Array.isArray(value) ? value : [];
356
+ if (rows.some((row) => typeof row !== "string" || row.trim() === "")) {
357
+ ctx.errors[field.name] = "List items must not be empty";
358
+ }
359
+ }
360
+
361
+ function validateRecord(field: FieldSchema, value: unknown, ctx: ValidationCtx): void {
362
+ if (value === undefined) return;
363
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
364
+ ctx.errors[field.name] = "Must be an object";
365
+ return;
366
+ }
367
+ for (const [key, entry] of Object.entries(value)) {
368
+ if (key.trim() === "") {
369
+ ctx.errors[field.name] = "Keys must not be empty";
370
+ return;
371
+ }
372
+ if (typeof entry === "string") continue;
373
+ const rowRaw = ctx.raw[`${field.name}.${key}`];
374
+ if (rowRaw !== undefined) {
375
+ try {
376
+ JSON.parse(rowRaw);
377
+ } catch {
378
+ ctx.errors[field.name] = `Invalid JSON for ${key}`;
379
+ return;
380
+ }
381
+ }
382
+ }
383
+ }
384
+
385
+ function validateJson(field: FieldSchema, value: unknown, ctx: ValidationCtx): void {
386
+ const text = ctx.raw[field.name] ?? (value === undefined ? "" : JSON.stringify(value));
387
+ if (text.trim() === "") return;
388
+ try {
389
+ JSON.parse(text);
390
+ } catch {
391
+ ctx.errors[field.name] = "Invalid JSON";
392
+ }
393
+ }
394
+
395
+ /** The per-widget validators; `nested-group` recurses (see `validateField`). */
396
+ const VALIDATORS: Partial<Record<WidgetKind, Validator>> = {
397
+ number: validateNumber,
398
+ enum: validateEnum,
399
+ "string-list": validateList,
400
+ record: validateRecord,
401
+ json: validateJson,
402
+ };
403
+
404
+ function validateField(field: FieldSchema, ctx: ValidationCtx): void {
405
+ if (field.widget === "nested-group") {
406
+ for (const child of field.children ?? []) validateField(child, ctx);
407
+ return;
408
+ }
409
+ VALIDATORS[field.widget]?.(field, getPath(ctx.draft, field.path), ctx);
410
+ }
411
+
412
+ /** Validate every field of a draft against its widget. Empty object = writable. */
413
+ function validateFields(
414
+ fields: FieldSchema[],
415
+ draft: Record<string, unknown>,
416
+ raw: RawText,
417
+ ): Record<string, string> {
418
+ const errors: Record<string, string> = {};
419
+ const ctx: ValidationCtx = { draft, raw, errors };
420
+ for (const field of fields) validateField(field, ctx);
421
+ return errors;
422
+ }
423
+
424
+ /**
425
+ * Validate the visible fields of a draft. Returns dotted field name → message
426
+ * (an empty object means the draft is writable). The server re-validates.
427
+ */
428
+ export function validateDraft(
429
+ fields: FieldSchema[],
430
+ draft: Record<string, unknown>,
431
+ tab: Transport,
432
+ raw: RawText,
433
+ ): Record<string, string> {
434
+ const errors: Record<string, string> = {};
435
+ const primary = TRANSPORT_FIELDS[tab][0] as string;
436
+ const primaryValue = draft[primary];
437
+ if (primaryValue === undefined || primaryValue === null || primaryValue === "") {
438
+ errors[primary] = "Required";
439
+ }
440
+ Object.assign(errors, validateFields(fields, draft, raw));
441
+ return errors;
442
+ }
@@ -0,0 +1,29 @@
1
+ /**
2
+ * `useIsNarrow` — a reactive `matchMedia` viewport check.
3
+ *
4
+ * The folder page needs one boolean to switch its presentation below the
5
+ * 640px floor (editor bottom sheet is CSS; the chip's inline remove control is
6
+ * not). jsdom has no `matchMedia`, so the hook degrades to `false` (desktop)
7
+ * and tests stub it when they need the narrow branch. See change:
8
+ * extract-mcp-client-plugin (task 8.4).
9
+ */
10
+ import { useEffect, useState } from "react";
11
+
12
+ export function useIsNarrow(query = "(max-width: 639px)"): boolean {
13
+ const read = (): boolean =>
14
+ typeof window !== "undefined" && typeof window.matchMedia === "function"
15
+ ? window.matchMedia(query).matches
16
+ : false;
17
+ const [narrow, setNarrow] = useState(read);
18
+
19
+ useEffect(() => {
20
+ if (typeof window === "undefined" || typeof window.matchMedia !== "function") return;
21
+ const mql = window.matchMedia(query);
22
+ const onChange = (): void => setNarrow(mql.matches);
23
+ onChange();
24
+ mql.addEventListener?.("change", onChange);
25
+ return () => mql.removeEventListener?.("change", onChange);
26
+ }, [query]);
27
+
28
+ return narrow;
29
+ }