Compare commits

...
Author SHA1 Message Date
l0ng-ai 2d81b1dde3 feat(http-client): Reformat Code formats JSON request bodies
Reformat Code in an .http file reported "No language server available".
The HTTP Client now contributes a formatter that re-indents each request's
JSON body (Content-Type JSON or none, body starting with { or [), keeping
{{variables}} and number literals as written. Headers, response handler
scripts, response references and file inputs are left alone; a selection
limits it to the bodies it touches.

Fixes #4727
2026-11-20 17:49:52 +08:00
3 changed files with 261 additions and 2 deletions

No files matched your search

+116
View File
@@ -0,0 +1,116 @@
import { indentUnit } from "@codemirror/language";
import { EditorState } from "@codemirror/state";
import { describe, expect, it } from "vitest";
import { formatJsonBody, httpBodyFormatter } from "./bodyFormat";
describe("formatJsonBody", () => {
it("indents objects and arrays and keeps values as written", () => {
expect(formatJsonBody('{"id":12345678901234567890,"tags":["a","b"],"meta":{},"list":[],"ok":true}', " ")).toBe(
[
"{",
' "id": 12345678901234567890,',
' "tags": [',
' "a",',
' "b"',
" ],",
' "meta": {},',
' "list": [],',
' "ok": true',
"}",
].join("\n"),
);
});
it("keeps {{variables}} as values, quoted or not", () => {
expect(formatJsonBody('{"user":{{userId}},"name":"{{name}}", "n": {{base}}-1}', " ")).toBe(
["{", ' "user": {{userId}},', ' "name": "{{name}}",', ' "n": {{base}}-1', "}"].join("\n"),
);
});
it("keeps escaped quotes and structural characters inside strings", () => {
expect(formatJsonBody('{"q":"a \\"b\\" {c}, [d]: e"}', " ")).toBe('{\n "q": "a \\"b\\" {c}, [d]: e"\n}');
});
it("leaves text that isn't one JSON value alone", () => {
for (const text of ['{"a":1', '{"a":1}}', '{"a" 1}', "{a:1}", '{"a":1} {"b":2}', "[1,]", "name=value"])
expect(formatJsonBody(text, " ")).toBeNull();
});
});
describe("Reformat Code in .http files (#4727)", () => {
const blocksOf = (text: string) => {
const lines = text.split("\n");
const out: Array<{ line: number; endLine: number }> = [];
lines.forEach((l, i) => {
if (/^(GET|POST|PUT|PATCH|DELETE) /.test(l)) out.push({ line: i, endLine: lines.length - 1 });
});
out.forEach((b, i) => {
const next = out[i + 1];
if (next) b.endLine = next.line - 2;
});
return out;
};
const format = (text: string, range: { from: number; to: number } | null = null) => {
const state = EditorState.create({ doc: text, extensions: [indentUnit.of(" ")] });
const changes = httpBodyFormatter(() => blocksOf(text))(state, range);
return state.update({ changes }).state.doc.toString();
};
it("formats JSON bodies after the headers and keeps the rest of the request", () => {
const text = [
"POST https://example.com/api/users",
" ?debug=true",
"Content-Type: application/json",
"Authorization: Bearer {{token}}",
"",
'{"name":"Ann","roles":["admin"],"id":{{id}}}',
"",
"> {%",
' client.global.set("id", response.body.id);',
"%}",
"",
"###",
"GET https://example.com/api/users/1",
].join("\n");
expect(format(text)).toBe(
[
"POST https://example.com/api/users",
" ?debug=true",
"Content-Type: application/json",
"Authorization: Bearer {{token}}",
"",
"{",
' "name": "Ann",',
' "roles": [',
' "admin"',
" ],",
' "id": {{id}}',
"}",
"",
"> {%",
' client.global.set("id", response.body.id);',
"%}",
"",
"###",
"GET https://example.com/api/users/1",
].join("\n"),
);
});
it("leaves bodies of other content types, form bodies and file inputs alone", () => {
for (const text of [
'POST https://example.com\nContent-Type: text/plain\n\n{"a":1}',
"POST https://example.com\nContent-Type: application/x-www-form-urlencoded\n\na=1&b=2",
"POST https://example.com\nContent-Type: application/json\n\n< ./body.json",
])
expect(format(text)).toBe(text);
});
it("formats only the bodies a selection touches", () => {
const one = 'POST https://example.com/a\n\n{"a":1}';
const two = 'POST https://example.com/b\n\n{"b":2}';
const text = `${one}\n\n###\n${two}`;
const from = text.indexOf('{"b"');
expect(format(text, { from, to: from + 3 })).toBe(`${one}\n\n###\nPOST https://example.com/b\n\n{\n "b": 2\n}`);
});
});
+139
View File
@@ -0,0 +1,139 @@
/**
* Reformat Code in `.http` files: JSON request bodies are re-indented. `{{variables}}` and
* number literals stay as written, so a body that is only JSON once its variables are
* substituted is formatted too.
*/
import { getIndentUnit } from "@codemirror/language";
import type { EditorState } from "@codemirror/state";
import type { ContributedFormatter } from "@/editor/api";
interface Block {
/** 0-based request line. */
line: number;
/** 0-based last line of the block (inclusive). */
endLine: number;
}
type Token = { kind: "punct"; text: "{" | "}" | "[" | "]" | ":" | "," } | { kind: "value"; text: string };
/** Values (strings, numbers, literals, `{{variables}}`) and punctuation; `null` when it can't be JSON. */
function tokenize(text: string): Token[] | null {
const out: Token[] = [];
let i = 0;
while (i < text.length) {
const c = text[i]!;
if (/\s/.test(c)) {
i++;
} else if (text.startsWith("{{", i)) {
const end = text.indexOf("}}", i + 2);
if (end < 0) return null;
// A variable glued to more text (`{{base}}-1`) stays one value.
let j = end + 2;
while (j < text.length && !/[\s{}[\]:,"]/.test(text[j]!)) j++;
out.push({ kind: "value", text: text.slice(i, j) });
i = j;
} else if (c === '"') {
let j = i + 1;
while (j < text.length && text[j] !== '"') j += text[j] === "\\" ? 2 : 1;
if (j >= text.length) return null;
out.push({ kind: "value", text: text.slice(i, j + 1) });
i = j + 1;
} else if ("{}[]:,".includes(c)) {
out.push({ kind: "punct", text: c as "{" });
i++;
} else {
let j = i;
while (j < text.length && !/[\s{}[\]:,"]/.test(text[j]!)) j++;
const word = text.slice(i, j);
if (!/^(-?\d|true$|false$|null$)/.test(word)) return null;
out.push({ kind: "value", text: word });
i = j;
}
}
return out;
}
/** `text` as indented JSON (empty `{}` / `[]` stay inline), or `null` when it isn't one JSON value. */
export function formatJsonBody(text: string, indent: string): string | null {
const tokens = tokenize(text);
if (!tokens?.length) return null;
let i = 0;
const value = (depth: number): string | null => {
const t = tokens[i++];
if (!t) return null;
if (t.kind === "value") return t.text;
if (t.text !== "{" && t.text !== "[") return null;
const object = t.text === "{";
const close = object ? "}" : "]";
if (tokens[i]?.text === close) {
i++;
return object ? "{}" : "[]";
}
const pad = indent.repeat(depth + 1);
const items: string[] = [];
for (;;) {
let key = "";
if (object) {
const k = tokens[i++];
if (k?.kind !== "value" || tokens[i++]?.text !== ":") return null;
key = `${k.text}: `;
}
const v = value(depth + 1);
if (v === null) return null;
items.push(pad + key + v);
const sep = tokens[i++];
if (sep?.text === close) break;
if (sep?.text !== ",") return null;
}
return `${t.text}\n${items.join(",\n")}\n${indent.repeat(depth)}${close}`;
};
const out = value(0);
return out !== null && i === tokens.length ? out : null;
}
const HANDLER_OR_INPUT = /^(> \{%|<>|>>|> |< )/;
/** The body lines of the request at `block`: after its headers, up to a response handler or reference. */
function bodyRange(state: EditorState, block: Block): { from: number; to: number; json: boolean } | null {
const doc = state.doc;
const last = Math.min(block.endLine + 1, doc.lines);
let n = block.line + 2;
// Indented query continuation lines, then headers up to the first blank line.
while (n <= last && /^[ \t]+[?&/]/.test(doc.line(n).text)) n++;
let contentType: string | null = null;
for (; n <= last; n++) {
const text = doc.line(n).text;
if (!text.trim()) break;
const m = /^([^\s:]+)\s*:(.*)$/.exec(text);
if (m && m[1]!.toLowerCase() === "content-type") contentType = m[2]!.trim().toLowerCase();
}
let first = 0;
let end = 0;
for (n++; n <= last; n++) {
const text = doc.line(n).text;
if (HANDLER_OR_INPUT.test(text.trimStart())) break;
if (!text.trim()) continue;
if (!first) first = n;
end = n;
}
if (!first) return null;
const json = contentType === null || contentType.includes("json");
return { from: doc.line(first).from, to: doc.line(end).to, json };
}
/** Reformat Code for the JSON bodies of `blocks` that overlap `range` (all when `null`). */
export function httpBodyFormatter(blocks: (state: EditorState) => readonly Block[]): ContributedFormatter {
return (state, range) => {
const indent = " ".repeat(getIndentUnit(state));
const changes: Array<{ from: number; to: number; insert: string }> = [];
for (const block of blocks(state)) {
const body = bodyRange(state, block);
if (!body?.json || (range && (body.to < range.from || body.from > range.to))) continue;
const text = state.sliceDoc(body.from, body.to);
if (!/^[{[]/.test(text.trimStart())) continue;
const formatted = formatJsonBody(text, indent);
if (formatted !== null && formatted !== text) changes.push({ from: body.from, to: body.to, insert: formatted });
}
return changes;
};
}
+6 -2
View File
@@ -3,11 +3,11 @@
* (like run configurations' gutter) and a toolbar panel above the text with
* the environment selector, Run All and Stop.
*/
import { RangeSet, StateEffect, StateField, type EditorState, type Extension } from "@codemirror/state";
import { EditorState, RangeSet, StateEffect, StateField, type Extension } from "@codemirror/state";
import { EditorView, GutterMarker, ViewPlugin, gutter, showPanel, type Panel, type ViewUpdate } from "@codemirror/view";
import { useEffect } from "react";
import { createRoot } from "react-dom/client";
import { mapLineStart, type EditorDocContext } from "@/editor/api";
import { CONTRIBUTED_FORMAT, mapLineStart, type EditorDocContext } from "@/editor/api";
import { shortcutLabel } from "@/platform/keymap";
import { isVirtualUri } from "@/platform/virtualDocs";
import type { HttpRequestBlock } from "@/platform/ipc";
@@ -23,6 +23,7 @@ import {
setEnvironment,
useHttpClient,
} from "./store";
import { httpBodyFormatter } from "./bodyFormat";
import styles from "./HttpClient.module.css";
export const HTTP_LANGUAGE = "http";
@@ -209,8 +210,11 @@ export function httpEditorExtension(ctx: EditorDocContext): Extension {
}
},
);
// Reformat Code: JSON request bodies (the blocks as last parsed).
const format = httpBodyFormatter((state) => state.field(requestsField, false) ?? []);
return [
requestsField,
EditorState.languageData.of(() => [{ [CONTRIBUTED_FORMAT]: format }]),
detector,
curlPaste,
showPanel.of(toolbarPanel(path)),