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