Open History to see the last commit
1import { describe, expect, it } from "@effect/vitest";
2import * as Arbitrary from "effect/Arbitrary";
3import * as DateTime from "effect/DateTime";
4import * as Effect from "effect/Effect";
5import * as Exit from "effect/Exit";
6import * as Schema from "effect/Schema";
7
8import * as BaseSchemas from "./baseSchemas.ts";
9import {
10 ForwardCompatibleArray,
11 ForwardCompatibleUnion,
12 ForwardCompatibleUnionArray,
13 isUnknownUnionMember,
14 TrimmedNonEmptyString,
15 UnknownUnionMember,
16} from "./baseSchemas.ts";
17
18const at = "2026-10-05T00:00:00.000Z";
19const Shape = Schema.Union([
20 Schema.Struct({ kind: Schema.Literal("circle"), radius: Schema.Number, at: Schema.DateTimeUtc }),
21 Schema.Struct({ kind: Schema.Literal("square"), side: Schema.Number }),
22]);
23const members = Shape.members;
24const fromWire = <S extends Schema.Top>(schema: S) =>
25 Schema.decodeUnknownSync(Schema.toCodecJson(schema) as never) as (value: unknown) => S["Type"];
26
27describe("ForwardCompatibleArray", () => {
28 it("decodes elements through their own codec and drops ones it cannot read", () => {
29 const decoded = fromWire(ForwardCompatibleArray(Shape))([
30 { kind: "circle", radius: 1, at },
31 { kind: "triangle" },
32 { kind: "square", side: "wide" },
33 ]);
34 expect(decoded).toHaveLength(1);
35 expect(DateTime.isDateTime((decoded[0] as { at: unknown }).at)).toBe(true);
36 });
37
38 it("applies decoding defaults instead of failing", () => {
39 const WithDefault = Schema.Struct({
40 name: Schema.String,
41 count: Schema.optionalKey(Schema.Number).pipe(
42 Schema.withDecodingDefaultKey(Effect.succeed(7)),
43 ),
44 });
45 expect(Schema.decodeUnknownSync(ForwardCompatibleArray(WithDefault))([{ name: "a" }])).toEqual([
46 { name: "a", count: 7 },
47 ]);
48 });
49
50 const Named = ForwardCompatibleArray(Schema.Struct({ name: TrimmedNonEmptyString }));
51
52 it("drops an element it cannot encode instead of failing the array", () => {
53 const wire = JSON.parse(
54 JSON.stringify(
55 Schema.encodeUnknownSync(Schema.toCodecJson(Named))([
56 { name: "a" },
57 { name: " " },
58 { name: "b" },
59 ]),
60 ),
61 );
62 expect(wire).toEqual([{ name: "a" }, { name: "b" }]);
63 expect(fromWire(Named)(wire)).toEqual([{ name: "a" }, { name: "b" }]);
64 });
65
66 it("drops it too when a wrapper reads the encoded array as JSON values", () => {
67 const Wrapped = Schema.Array(Schema.Unknown).pipe(Schema.decodeTo(Named));
68 expect(
69 Schema.encodeUnknownSync(Schema.toCodecJson(Wrapped))([{ name: "a" }, { name: " " }]),
70 ).toEqual([{ name: "a" }]);
71 });
72
73 it("still drops the null holes a server on an earlier build sends", () => {
74 expect(fromWire(Named)([{ name: "a" }, null, { name: "b" }])).toEqual([
75 { name: "a" },
76 { name: "b" },
77 ]);
78 });
79
80 it("does not accept holes as a decoded value", () => {
81 expect(Schema.is(Named)([undefined])).toBe(false);
82 const sparse: Array<{ name: string }> = [{ name: "a" }];
83 sparse.length = 2;
84 expect(Schema.is(Named)(sparse)).toBe(false);
85 expect(() => Named.make(sparse)).toThrow();
86 expect(Schema.is(Named)([{ name: "a" }])).toBe(true);
87 });
88});
89
90describe("ForwardCompatibleUnion", () => {
91 const decode = fromWire(ForwardCompatibleUnion(members, "kind"));
92
93 it("decodes a member from a newer server as unknown", () => {
94 const decoded = decode({ kind: "triangle", corners: 3 });
95 expect(isUnknownUnionMember(decoded)).toBe(true);
96 expect(decoded).toEqual(new UnknownUnionMember("kind", "triangle"));
97 });
98
99 it("decodes known members in full, transformations included", () => {
100 const decoded = decode({ kind: "circle", radius: 1, at });
101 expect(isUnknownUnionMember(decoded)).toBe(false);
102 expect(DateTime.isDateTime((decoded as { at: unknown }).at)).toBe(true);
103 });
104
105 it("still fails a known member whose payload is broken", () => {
106 expect(() => decode({ kind: "square", side: "wide" })).toThrow();
107 });
108
109 it("refuses to encode an unknown member", () => {
110 const encode = Schema.encodeSync(ForwardCompatibleUnion(members, "kind") as never);
111 expect(() => encode(new UnknownUnionMember("kind", "triangle") as never)).toThrow();
112 });
113});
114
115describe("ForwardCompatibleUnionArray", () => {
116 it("keeps a known member however its fields are named", () => {
117 const Flagged = Schema.Struct({
118 kind: Schema.Literal("flag"),
119 _unknown: Schema.Literal(true),
120 tag: Schema.String,
121 value: Schema.String,
122 });
123 const flag = { kind: "flag", _unknown: true, tag: "kind", value: "x" };
124 expect(fromWire(ForwardCompatibleUnionArray([Flagged], "kind"))([flag])).toEqual([flag]);
125 });
126
127 const decode = fromWire(ForwardCompatibleUnionArray(members, "kind"));
128
129 it("drops members a newer server added and keeps the rest", () => {
130 const decoded = decode([
131 { kind: "triangle" },
132 { kind: "circle", radius: 1, at },
133 { kind: "square", side: 2 },
134 ]);
135 expect(decoded.map((shape) => shape.kind)).toEqual(["circle", "square"]);
136 });
137
138 it("fails when a known member is broken, so real bugs stay visible", () => {
139 expect(() => decode([{ kind: "square", side: "wide" }])).toThrow();
140 });
141
142 it("encodes as a plain array", () => {
143 const encode = Schema.encodeSync(
144 Schema.toCodecJson(ForwardCompatibleUnionArray(members, "kind")),
145 );
146 const square = { kind: "square" as const, side: 2 };
147 expect(encode([square])).toEqual([square]);
148 });
149});
150
151describe("trimmed non-empty strings", () => {
152 const entityIds = [
153 "ThreadId",
154 "ProjectId",
155 "EnvironmentId",
156 "CommandId",
157 "EventId",
158 "MessageId",
159 "TurnId",
160 "RunId",
161 "RunAttemptId",
162 "NodeId",
163 "AuthSessionId",
164 "ProviderItemId",
165 "ProviderSessionId",
166 "ProviderThreadId",
167 "ProviderTurnId",
168 "RuntimeSessionId",
169 "RuntimeItemId",
170 "TurnItemId",
171 "RuntimeRequestId",
172 "RuntimeTaskId",
173 "ScheduledTaskId",
174 "ApprovalRequestId",
175 "CheckpointRef",
176 "CheckpointId",
177 "CheckpointScopeId",
178 "ContextHandoffId",
179 "ContextTransferId",
180 "RawEventId",
181 "PlanId",
182 ] as const;
183 const schemas = [
184 ["TrimmedNonEmptyString", TrimmedNonEmptyString],
185 ...entityIds.map((name) => [name, BaseSchemas[name]] as const),
186 ] as const;
187
188 const whitespace = Arbitrary.schema(
189 Schema.Literals([" ", "\t", "\n", "\r\n", "\v", "\f", "\u00a0", "\u2028", "\u3000", "\ufeff"]),
190 );
191 const padding = Arbitrary.array(whitespace, { maxLength: 4 }).pipe(
192 Arbitrary.map((parts) => parts.join("")),
193 );
194 const paddedString = Arbitrary.all([padding, Arbitrary.schema(Schema.String), padding]).pipe(
195 Arbitrary.map(([before, value, after]) => before + value + after),
196 );
197 const options = { arbitrary: { runs: 500 } };
198
199 for (const [name, schema] of schemas) {
200 const make = schema.makeOption;
201 const encode = Schema.encodeUnknownExit(schema);
202 const decode = Schema.decodeExit(schema);
203
204 it.prop(
205 `${name}: whatever make accepts encodes to something that decodes back`,
206 [paddedString],
207 ([input]) => {
208 const made = make(input);
209 if (made._tag === "None") {
210 expect(input.trim()).toBe("");
211 return;
212 }
213 const encoded = encode(made.value);
214 expect(encoded).toStrictEqual(Exit.succeed(input.trim()));
215 expect(decode(input.trim())).toStrictEqual(Exit.succeed(input.trim()));
216 },
217 options,
218 );
219
220 it.prop(
221 `${name}: decoding then encoding is stable`,
222 [paddedString],
223 ([input]) => {
224 const decoded = decode(input);
225 if (Exit.isFailure(decoded)) {
226 expect(input.trim()).toBe("");
227 expect(Exit.isFailure(encode(input))).toBe(true);
228 return;
229 }
230 expect(decoded.value).toBe(input.trim());
231 expect(encode(decoded.value)).toStrictEqual(Exit.succeed(decoded.value));
232 },
233 options,
234 );
235
236 it.prop(
237 `${name}: generated values round-trip`,
238 [schema],
239 ([value]) => {
240 const encoded = encode(value);
241 expect(Exit.isSuccess(encoded)).toBe(true);
242 if (Exit.isSuccess(encoded))
243 expect(decode(encoded.value)).toStrictEqual(Exit.succeed(value.trim()));
244 },
245 options,
246 );
247 }
248
249 const isThreadId = Schema.is(BaseSchemas.ThreadId);
250 const encodeThreadId = Schema.encodeUnknownExit(BaseSchemas.ThreadId);
251 const decodeThreadId = Schema.decodeExit(BaseSchemas.ThreadId);
252
253 it("rejects whitespace-only values everywhere", () => {
254 for (const value of [" ", "\t\n", "\u00a0\u3000"]) {
255 expect(() => BaseSchemas.ThreadId.make(value)).toThrow();
256 expect(isThreadId(value)).toBe(false);
257 expect(Exit.isFailure(encodeThreadId(value))).toBe(true);
258 expect(Exit.isFailure(decodeThreadId(value))).toBe(true);
259 }
260 });
261
262 it("keeps the encoded form and JSON Schema of valid values", () => {
263 expect(encodeThreadId(BaseSchemas.ThreadId.make("thread-1"))).toStrictEqual(
264 Exit.succeed("thread-1"),
265 );
266 expect(encodeThreadId(" a b ")).toStrictEqual(Exit.succeed("a b"));
267 expect(Schema.toJsonSchemaDocument(Schema.toType(BaseSchemas.ThreadId)).schema).toEqual({
268 type: "string",
269 minLength: 1,
270 });
271 });
272});