Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

baseSchemas.ts

376 lines14.3 KB

1import * as Effect from "effect/Effect";
2import * as Option from "effect/Option";
3import * as Schema from "effect/Schema";
4import * as SchemaGetter from "effect/SchemaGetter";
5import * as SchemaTransformation from "effect/SchemaTransformation";
6​
7// Hermes copies the string on every `trim()`, even when nothing changes.
8// Returning the original keeps repeated IDs shared after decode.
9const trim = (value: string) => {
10 const trimmed = value.trim();
11 return trimmed.length === value.length ? value : trimmed;
12};
13​
14export const TrimmedString = Schema.String.pipe(
15 Schema.decodeTo(
16 Schema.String,
17 SchemaTransformation.transformEffect({
18 decode: (value) => Effect.succeed(trim(value)),
19 encode: (value) => Effect.succeed(trim(value)),
20 }),
21 ),
22);
23// `make` and encode see untrimmed values; `isNonEmpty` would accept whitespace that encodes to an invalid empty string.
24const isNonBlank = Schema.makeFilter((value: string) => value.trim().length > 0, {
25 expected: "a non-blank string",
26 toJsonSchema: () => [{ minLength: 1 }, true],
27 arbitraryConstraint: { minLength: 1 },
28});
29export const TrimmedNonEmptyString = TrimmedString.check(isNonBlank);
30​
31// Git forbids ASCII space and control characters in ref names but allows Unicode whitespace such
32// as U+00A0 and U+3000, which `String.prototype.trim` would strip from a name's edges.
33export function trimAsciiWhitespace(value: string): string {
34 let start = 0;
35 let end = value.length;
36 while (start < end && isAsciiWhitespace(value.charCodeAt(start))) start++;
37 while (end > start && isAsciiWhitespace(value.charCodeAt(end - 1))) end--;
38 return end - start === value.length ? value : value.slice(start, end);
40​
41function isAsciiWhitespace(code: number): boolean {
42 return code === 0x20 || (code >= 0x09 && code <= 0x0d);
44​
45const isNonBlankGitRefName = Schema.makeFilter(
46 (value: string) => trimAsciiWhitespace(value).length > 0,
47 {
48 expected: "a non-blank string",
49 toJsonSchema: () => [{ minLength: 1 }, true],
50 arbitraryConstraint: { minLength: 1 },
51 },
52);
53/** A branch, ref or remote name. Unlike `TrimmedNonEmptyString`, it keeps Unicode whitespace. */
54export const GitRefName = Schema.String.pipe(
55 Schema.decodeTo(
56 Schema.String,
57 SchemaTransformation.transformEffect({
58 decode: (value) => Effect.succeed(trimAsciiWhitespace(value)),
59 encode: (value) => Effect.succeed(trimAsciiWhitespace(value)),
60 }),
61 ),
62).check(isNonBlankGitRefName);
63​
64export const NonNegativeInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0));
65export const PositiveInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(1));
66export const PortSchema = Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 }));
67​
68export const DpopFailureReason = Schema.Literals([
69 "time_window",
70 "key_mismatch",
71 "request_mismatch",
72 "token_mismatch",
73 "replay",
74 "invalid_proof",
75]);
76export type DpopFailureReason = typeof DpopFailureReason.Type;
77​
78export const IsoDateTime = Schema.String;
79export type IsoDateTime = typeof IsoDateTime.Type;
80​
81export const ForwardCompatibleOptional = <Value extends Schema.Top>(value: Value) => {
82 const decodeValue = Schema.decodeUnknownOption(value as never);
83 // Unreadable values drop the key: an own undefined property is not JSON and fails RPC encoding.
84 return Schema.optionalKey(Schema.Unknown).pipe(
85 Schema.decodeTo(
86 Schema.optionalKey(Schema.UndefinedOr(value)),
87 SchemaTransformation.transformOptional<Value["Encoded"] | undefined, unknown>({
88 decode: (raw) =>
89 Option.isSome(raw) && Option.isSome(decodeValue(raw.value))
90 ? Option.some(raw.value as Value["Encoded"])
91 : Option.none(),
92 encode: (raw) => (Option.isSome(raw) && raw.value !== undefined ? raw : Option.none()),
93 }),
94 ),
95 );
96};
97​
98export const ForwardCompatibleNullable = <Value extends Schema.Top>(value: Value) => {
99 const decodeValue = Schema.decodeUnknownOption(value as never);
100 return Schema.Unknown.pipe(
101 Schema.decodeTo(
102 Schema.NullOr(value),
103 SchemaTransformation.transform<Value["Encoded"] | null, unknown>({
104 decode: (raw) => (Option.isSome(decodeValue(raw)) ? (raw as Value["Encoded"]) : null),
105 encode: (raw) => raw,
106 }),
107 ),
108 );
109};
110​
111/** Missing or unknown values decode to null; null encodes as absent for older clients requiring a literal. */
112export const OmittedWhenNull = <Value extends Schema.Top>(value: Value) => {
113 const decodeValue = Schema.decodeUnknownOption(value as never);
114 return Schema.optionalKey(Schema.Unknown).pipe(
115 Schema.decodeTo(
116 Schema.NullOr(value),
117 SchemaTransformation.transformOptional<Value["Encoded"] | null, unknown>({
118 decode: (raw) =>
119 Option.some(
120 Option.isSome(raw) && Option.isSome(decodeValue(raw.value))
121 ? (raw.value as Value["Encoded"])
122 : null,
123 ),
124 encode: (raw) =>
125 Option.isSome(raw) && raw.value !== null ? Option.some(raw.value) : Option.none(),
126 }),
127 ),
128 );
129};
130​
131const UnknownArrayElement = Schema.Unknown.pipe(
132 Schema.decodeTo(Schema.Undefined, {
133 decode: SchemaGetter.succeed(undefined),
134 encode: SchemaGetter.passthrough(),
135 }),
136);
137​
138/** Prefer {@link ForwardCompatibleUnion} for tagged unions so malformed known members still fail. */
139export const ForwardCompatibleArray = <Element extends Schema.Top>(element: Element) =>
140 // Exit derives its wire codec from the encoded shape, which keeps the union but drops recovery middleware.
141 Schema.Array(
142 Schema.Union([element, UnknownArrayElement]).pipe(
143 Schema.catchEncoding(() => Effect.succeedSome(undefined)),
144 ),
145 ).pipe(
146 Schema.decodeTo(
147 Schema.Array(
148 Schema.UndefinedOr(Schema.toType(element)).pipe(
149 Schema.catchEncoding(() => Effect.succeedSome(undefined)),
150 ),
151 ).check(
152 // Schema.is/make must reject holes; abort before later array checks.
153 Schema.makeFilter(
154 (values) => {
155 // Every index, not `every`, which skips the holes of a sparse array.
156 for (let index = 0; index < values.length; index++) {
157 if (values[index] === undefined) return false;
158 }
159 return true;
160 },
161 { expected: "an array without holes" },
162 true,
163 ),
164 ),
165 SchemaTransformation.transform<
166 ReadonlyArray<Element["Type"]>,
167 ReadonlyArray<Element["Type"] | undefined>
168 >({
169 decode: (values) => values.filter((value) => value !== undefined),
170 encode: (values) => values.filter((value) => value !== undefined),
171 }),
172 ),
173 ) as unknown as ForwardCompatibleArray<Element>;
174export type ForwardCompatibleArray<Element extends Schema.Top> = Schema.Codec<
175 ReadonlyArray<Element["Type"]>,
176 ReadonlyArray<Element["Encoded"]>,
177 Element["DecodingServices"],
178 Element["EncodingServices"]
179>;
180​
181/** Class identity prevents decoded payloads from impersonating unknown members. */
182export class UnknownUnionMember<Tag extends string = string> {
183 readonly tag: Tag;
184 readonly value: string;
185 constructor(tag: Tag, value: string) {
186 this.tag = tag;
187 this.value = value;
188 }
190​
191/** Unknown members are decode-only; encoding one fails. */
192export const ForwardCompatibleUnion = <
193 const Members extends ReadonlyArray<Schema.Top & { readonly fields: object }>,
194 const Tag extends string,
195>(
196 members: Members,
197 tag: Tag,
198) => {
199 const known = knownTags(members, tag);
200 const unknownMember = Schema.Struct({
201 [tag]: Schema.String.check(
202 Schema.makeFilter(
203 (value: string) => !known.has(value) || `A known ${tag} must decode in full.`,
204 ),
205 ),
206 } as Record<Tag, Schema.String>).pipe(
207 Schema.decodeTo(Schema.instanceOf(UnknownUnionMember<Tag>), {
208 decode: SchemaGetter.transform(
209 (raw: Record<string, string>) => new UnknownUnionMember(tag, raw[tag]!),
210 ),
211 encode: SchemaGetter.forbidden(() => `Unknown ${tag} values are never sent.`),
212 }),
213 );
214 return Schema.Union([...members, unknownMember]) as unknown as ForwardCompatibleUnion<
215 Members,
216 Tag
217 >;
218};
219export type ForwardCompatibleUnion<
220 Members extends ReadonlyArray<Schema.Top>,
221 Tag extends string,
222> = Schema.Codec<
223 Members[number]["Type"] | UnknownUnionMember<Tag>,
224 Members[number]["Encoded"],
225 Members[number]["DecodingServices"],
226 Members[number]["EncodingServices"]
227>;
228​
229export const hasUnknownUnionTag = (
230 members: ReadonlyArray<Schema.Top & { readonly fields: object }>,
231 tag: string,
232): ((value: unknown) => boolean) => {
233 const known = knownTags(members, tag);
234 return (value) =>
235 typeof value === "object" &&
236 value !== null &&
237 tag in value &&
238 !known.has((value as Record<string, unknown>)[tag] as string);
239};
240​
241export const isUnknownUnionMember = <A>(
242 value: A,
243): value is Extract<A, UnknownUnionMember<string>> => value instanceof UnknownUnionMember;
244​
245export const ForwardCompatibleUnionArray = <
246 const Members extends ReadonlyArray<Schema.Top & { readonly fields: object }>,
247 const Tag extends string,
248>(
249 members: Members,
250 tag: Tag,
251) =>
252 Schema.Array(ForwardCompatibleUnion(members, tag)).pipe(
253 Schema.decodeTo(
254 Schema.Array(Schema.toType(Schema.Union(members))),
255 SchemaTransformation.transform<
256 ReadonlyArray<Members[number]["Type"]>,
257 ReadonlyArray<Members[number]["Type"] | UnknownUnionMember<Tag>>
258 >({
259 decode: (values) =>
260 values.filter((value) => !isUnknownUnionMember(value)) as ReadonlyArray<
261 Members[number]["Type"]
262 >,
263 encode: (values) => values,
264 }),
265 ),
266 );
267​
268const knownTags = (
269 members: ReadonlyArray<Schema.Top & { readonly fields: object }>,
270 tag: string,
271): ReadonlySet<string> => {
272 const tags = new Set<string>();
273 for (const member of members) {
274 const field = (member.fields as Record<string, unknown>)[tag] as
275 | { readonly literal?: unknown; readonly literals?: ReadonlyArray<unknown> }
276 | undefined;
277 for (const literal of field?.literals ?? [field?.literal]) {
278 if (typeof literal !== "string") {
279 throw new Error(`Every ForwardCompatibleUnion member needs a string literal ${tag}.`);
280 }
281 tags.add(literal);
282 }
283 }
284 return tags;
285};
286​
287const makeEntityId = <Brand extends string>(brand: Parameters<typeof Schema.brand<Brand>>[0]) => {
288 return TrimmedNonEmptyString.pipe(Schema.brand<Brand>(brand));
289};
290​
291export const ThreadId = makeEntityId("ThreadId");
292export type ThreadId = typeof ThreadId.Type;
293export const ProjectId = makeEntityId("ProjectId");
294export type ProjectId = typeof ProjectId.Type;
295export const EnvironmentId = makeEntityId("EnvironmentId");
296export type EnvironmentId = typeof EnvironmentId.Type;
297export const CommandId = makeEntityId("CommandId");
298export type CommandId = typeof CommandId.Type;
299export const EventId = makeEntityId("EventId");
300export type EventId = typeof EventId.Type;
301export const MessageId = makeEntityId("MessageId");
302export type MessageId = typeof MessageId.Type;
303export const TurnId = makeEntityId("TurnId");
304export type TurnId = typeof TurnId.Type;
305export const RunId = makeEntityId("RunId");
306export type RunId = typeof RunId.Type;
307export const RunAttemptId = makeEntityId("RunAttemptId");
308export type RunAttemptId = typeof RunAttemptId.Type;
309export const NodeId = makeEntityId("NodeId");
310export type NodeId = typeof NodeId.Type;
311export const GuestShareId = makeEntityId("GuestShareId");
312export type GuestShareId = typeof GuestShareId.Type;
313export const GuestMessageId = makeEntityId("GuestMessageId");
314export type GuestMessageId = typeof GuestMessageId.Type;
315export const AuthSessionId = makeEntityId("AuthSessionId");
316export type AuthSessionId = typeof AuthSessionId.Type;
317export const RpcClientId = NonNegativeInt.pipe(Schema.brand("RpcClientId"));
318export type RpcClientId = typeof RpcClientId.Type;
319​
320export const ClientSurface = Schema.Literals(["web", "desktop", "mobile", "cli"]);
321export type ClientSurface = typeof ClientSurface.Type;
322​
323export const ClientOs = Schema.Literals([
324 "macOS",
325 "Windows",
326 "Linux",
327 "iOS",
328 "Android",
329 "ChromeOS",
330 "other",
331 "unknown",
332]);
333export type ClientOs = typeof ClientOs.Type;
334​
335export const ClientDeviceType = Schema.Literals(["desktop", "phone", "tablet", "unknown"]);
336export type ClientDeviceType = typeof ClientDeviceType.Type;
337​
338export const ClientWebDeployment = Schema.Literals(["hosted", "server"]);
339export type ClientWebDeployment = typeof ClientWebDeployment.Type;
340​
341export const ClientConnectionMethod = Schema.Literals(["direct", "ssh", "relay", "unknown"]);
342export type ClientConnectionMethod = typeof ClientConnectionMethod.Type;
343​
344export const ProviderItemId = makeEntityId("ProviderItemId");
345export type ProviderItemId = typeof ProviderItemId.Type;
346export const ProviderSessionId = makeEntityId("ProviderSessionId");
347export type ProviderSessionId = typeof ProviderSessionId.Type;
348export const ProviderThreadId = makeEntityId("ProviderThreadId");
349export type ProviderThreadId = typeof ProviderThreadId.Type;
350export const ProviderTurnId = makeEntityId("ProviderTurnId");
351export type ProviderTurnId = typeof ProviderTurnId.Type;
352export const TurnItemId = makeEntityId("TurnItemId");
353export type TurnItemId = typeof TurnItemId.Type;
354export const RuntimeRequestId = makeEntityId("RuntimeRequestId");
355export type RuntimeRequestId = typeof RuntimeRequestId.Type;
356export const ScheduledTaskId = makeEntityId("ScheduledTaskId");
357/** A one-use handle to a secret the user entered for an agent; the agent never sees the value. */
358export const SecretRef = makeEntityId("SecretRef");
359export type SecretRef = typeof SecretRef.Type;
360export type ScheduledTaskId = typeof ScheduledTaskId.Type;
361export const ApprovalRequestId = makeEntityId("ApprovalRequestId");
362export type ApprovalRequestId = typeof ApprovalRequestId.Type;
363export const CheckpointRef = makeEntityId("CheckpointRef");
364export type CheckpointRef = typeof CheckpointRef.Type;
365export const CheckpointId = makeEntityId("CheckpointId");
366export type CheckpointId = typeof CheckpointId.Type;
367export const CheckpointScopeId = makeEntityId("CheckpointScopeId");
368export type CheckpointScopeId = typeof CheckpointScopeId.Type;
369export const ContextHandoffId = makeEntityId("ContextHandoffId");
370export type ContextHandoffId = typeof ContextHandoffId.Type;
371export const ContextTransferId = makeEntityId("ContextTransferId");
372export type ContextTransferId = typeof ContextTransferId.Type;
373export const RawEventId = makeEntityId("RawEventId");
374export type RawEventId = typeof RawEventId.Type;
375export const PlanId = makeEntityId("PlanId");
376export type PlanId = typeof PlanId.Type;