返回源码地图

packages/ai/test/json-parse.test.ts

v1.3.0 · 71023aec1546 · 04:完整读取合法/畸形最终JSON边界,未本机执行上游suite

完整原文供逐行核对;页面收录不代表每行都经过人工语义审核。MIT 许可见 许可证。

1import { describe, expect, it } from "vitest";
2import { parseStreamingJson, parseToolCallArguments } from "../src/utils/json-parse.ts";
3
4describe("parseStreamingJson", () => {
5 // #10868
6 it("keeps invalid \\u escapes as literal text without dropping fields", () => {
7 expect(parseStreamingJson(String.raw`{"text":"\url{x}"}`)).toEqual({ text: "\\url{x}" });
8 expect(parseStreamingJson(String.raw`{"path":"a.tex","content":"\usepackage{x}","mode":"w"}`)).toEqual({
9 path: "a.tex",
10 content: "\\usepackage{x}",
11 mode: "w",
12 });
13 });
14
15 it("decodes valid \\u escapes", () => {
16 expect(parseStreamingJson(String.raw`{"text":"caf\u00e9 \url"}`)).toEqual({ text: "café \\url" });
17 });
18
19 it("omits a \\u escape that is cut off mid-stream", () => {
20 expect(parseStreamingJson(String.raw`{"text":"ab\u00`)).toEqual({ text: "ab" });
21 });
22});
23
24// #10897
25describe("parseToolCallArguments", () => {
26 it("parses complete JSON and repairs invalid escapes", () => {
27 expect(parseToolCallArguments(String.raw`{"kind":"seek","note":"\url"}`)).toEqual({
28 arguments: { kind: "seek", note: "\\url" },
29 });
30 });
31
32 it("uses empty arguments for empty text", () => {
33 expect(parseToolCallArguments("")).toEqual({ arguments: {} });
34 });
35
36 it("does not keep the valid prefix of malformed JSON", () => {
37 const raw = '{"action":"apply","actions":[{"kind":"seek","time":.5}]}';
38 const result = parseToolCallArguments(raw);
39 expect(result.arguments).toEqual({});
40 expect(result.argumentsError).toMatch(/\n\nReceived arguments:\n/);
41 expect(result.argumentsError?.endsWith(raw)).toBe(true);
42 });
43
44 it("does not complete cut-off JSON", () => {
45 const raw = '{"kind":"seek","clipId":"clip-fl';
46 const result = parseToolCallArguments(raw);
47 expect(result.arguments).toEqual({});
48 expect(result.argumentsError?.endsWith(raw)).toBe(true);
49 });
50
51 it("rejects JSON that is not an object", () => {
52 expect(parseToolCallArguments("[1,2]")).toEqual({
53 arguments: {},
54 argumentsError: "Tool arguments must be a JSON object\n\nReceived arguments:\n[1,2]",
55 });
56 });
57});