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

errors.ts

375 lines10.0 KB

1import * as Schema from "effect/Schema";
2import type * as SchemaIssue from "effect/SchemaIssue";
3​
4import * as AcpSchema from "./_generated/schema.gen.ts";
5​
6export const AcpRequestOperation = Schema.Literals([
7 "decode-extension-request-payload",
8 "encode-extension-response",
9 "handle-request",
10 "handle-extension-request",
11 "receive-response",
12 "receive-streaming-response",
13]);
14export type AcpRequestOperation = typeof AcpRequestOperation.Type;
15​
16export const AcpSchemaIssueKind = Schema.Literals([
17 "Filter",
18 "Encoding",
19 "Pointer",
20 "Composite",
21 "AnyOf",
22 "InvalidType",
23 "InvalidValue",
24 "MissingKey",
25 "UnexpectedKey",
26 "Forbidden",
27 "OneOf",
28]);
29export type AcpSchemaIssueKind = typeof AcpSchemaIssueKind.Type;
30​
31export interface AcpSchemaIssueDiagnostics {
32 readonly issueCount: number;
33 readonly issueKinds: ReadonlyArray<AcpSchemaIssueKind>;
34 readonly maximumPathDepth: number;
36​
37const schemaIssueDiagnostics = (root: SchemaIssue.Issue): AcpSchemaIssueDiagnostics => {
38 let issueCount = 0;
39 let maximumPathDepth = 0;
40 const issueKinds = new Set<AcpSchemaIssueKind>();
41​
42 const visit = (issue: SchemaIssue.Issue, pathDepth: number): void => {
43 issueCount += 1;
44 issueKinds.add(issue._tag);
45 maximumPathDepth = Math.max(maximumPathDepth, pathDepth);
46 switch (issue._tag) {
47 case "Filter":
48 case "Encoding":
49 visit(issue.issue, pathDepth);
50 break;
51 case "Pointer":
52 visit(issue.issue, pathDepth + issue.path.length);
53 break;
54 case "Composite":
55 case "AnyOf":
56 for (const child of issue.issues) visit(child, pathDepth);
57 break;
58 }
59 };
60​
61 visit(root, 0);
62 return {
63 issueCount,
64 issueKinds: [...issueKinds],
65 maximumPathDepth,
66 };
67};
68​
69export interface AcpRequestDiagnostics {
70 readonly method?: string;
71 readonly requestId?: string;
72 readonly operation?: AcpRequestOperation;
73 readonly cause?: unknown;
74 readonly issueCount?: number;
75 readonly issueKinds?: ReadonlyArray<AcpSchemaIssueKind>;
76 readonly maximumPathDepth?: number;
78​
79export class AcpSpawnError extends Schema.TaggedErrorClass<AcpSpawnError>()("AcpSpawnError", {
80 command: Schema.optional(Schema.String),
81 cause: Schema.Defect(),
82}) {
83 override get message() {
84 return this.command
85 ? `Failed to spawn ACP process for command: ${this.command}`
86 : "Failed to spawn ACP process";
87 }
89​
90export class AcpProcessExitedError extends Schema.TaggedErrorClass<AcpProcessExitedError>()(
91 "AcpProcessExitedError",
92 {
93 code: Schema.optional(Schema.Number),
94 pid: Schema.optionalKey(Schema.Int),
95 cause: Schema.optional(Schema.Defect()),
96 },
97) {
98 override get message() {
99 return this.code === undefined
100 ? "ACP process exited"
101 : `ACP process exited with code ${this.code}`;
102 }
104​
105export const AcpProtocolParseOperation = Schema.Literals([
106 "encode-message",
107 "decode-wire-message",
108 "decode-notification-payload",
109]);
110export type AcpProtocolParseOperation = typeof AcpProtocolParseOperation.Type;
111​
112export class AcpProtocolParseError extends Schema.TaggedErrorClass<AcpProtocolParseError>()(
113 "AcpProtocolParseError",
114 {
115 operation: AcpProtocolParseOperation,
116 method: Schema.optionalKey(Schema.String),
117 requestId: Schema.optionalKey(Schema.String),
118 issueCount: Schema.optionalKey(Schema.Number),
119 issueKinds: Schema.optionalKey(Schema.Array(AcpSchemaIssueKind)),
120 maximumPathDepth: Schema.optionalKey(Schema.Number),
121 cause: Schema.Defect(),
122 },
123) {
124 override get message() {
125 const method = this.method === undefined ? "" : ` for method '${this.method}'`;
126 return `ACP protocol operation '${this.operation}' failed${method}.`;
127 }
128​
129 static fromSchemaError(
130 operation: AcpProtocolParseOperation,
131 method: string,
132 cause: Schema.SchemaError,
133 ) {
134 return new AcpProtocolParseError({
135 operation,
136 method,
137 ...schemaIssueDiagnostics(cause.issue),
138 cause,
139 });
140 }
141​
142 static fromEncodingError(
143 method: string | undefined,
144 requestId: string | undefined,
145 cause: unknown,
146 ) {
147 return new AcpProtocolParseError({
148 operation: "encode-message",
149 ...(method === undefined ? {} : { method }),
150 ...(requestId === undefined ? {} : { requestId }),
151 cause,
152 });
153 }
155​
156export class AcpTransportError extends Schema.TaggedErrorClass<AcpTransportError>()(
157 "AcpTransportError",
158 {
159 operation: Schema.optional(
160 Schema.Literals(["call-rpc", "read-input-stream", "read-process-exit-status"]),
161 ),
162 method: Schema.optional(Schema.String),
163 detail: Schema.optional(Schema.String),
164 pid: Schema.optionalKey(Schema.Int),
165 cause: Schema.Defect(),
166 },
167) {
168 override get message() {
169 const method = this.method ? ` for method ${this.method}` : "";
170 return this.operation
171 ? `ACP transport operation ${this.operation} failed${method}.`
172 : "ACP transport operation failed.";
173 }
175​
176export class AcpInputStreamEndedError extends Schema.TaggedErrorClass<AcpInputStreamEndedError>()(
177 "AcpInputStreamEndedError",
178 {},
179) {
180 override get message() {
181 return "ACP input stream ended.";
182 }
184​
185export class AcpRequestError extends Schema.TaggedErrorClass<AcpRequestError>()("AcpRequestError", {
186 code: AcpSchema.ErrorCode,
187 errorMessage: Schema.String,
188 data: Schema.optional(Schema.Unknown),
189 method: Schema.optionalKey(Schema.String),
190 requestId: Schema.optionalKey(Schema.String),
191 operation: Schema.optionalKey(AcpRequestOperation),
192 issueCount: Schema.optionalKey(Schema.Number),
193 issueKinds: Schema.optionalKey(Schema.Array(AcpSchemaIssueKind)),
194 maximumPathDepth: Schema.optionalKey(Schema.Number),
195 cause: Schema.optionalKey(Schema.Defect()),
196}) {
197 override get message() {
198 return this.errorMessage;
199 }
200​
201 static fromProtocolError(
202 error: AcpSchema.Error,
203 context: {
204 readonly method: string;
205 readonly requestId?: string;
206 readonly cause?: unknown;
207 },
208 ) {
209 return new AcpRequestError({
210 code: error.code,
211 errorMessage: error.message,
212 ...(error.data !== undefined ? { data: error.data } : {}),
213 method: context.method,
214 ...(context.requestId === undefined ? {} : { requestId: context.requestId }),
215 operation: "receive-response",
216 cause: context.cause ?? error,
217 });
218 }
219​
220 static fromExtensionResponseFailure(method: string, requestId: string, cause: unknown) {
221 return AcpRequestError.internalError("Extension request failed", undefined, {
222 method,
223 requestId,
224 operation: "receive-response",
225 cause,
226 });
227 }
228​
229 static fromExtensionResponseEncodingError(
230 method: string,
231 requestId: string,
232 cause: AcpProtocolParseError,
233 ) {
234 return AcpRequestError.internalError("Internal error", undefined, {
235 method,
236 requestId,
237 operation: "encode-extension-response",
238 cause,
239 });
240 }
241​
242 static unsupportedStreamingResponse(method: string, requestId: string) {
243 return AcpRequestError.internalError(
244 "Streaming extension responses are not supported",
245 undefined,
246 {
247 method,
248 requestId,
249 operation: "receive-streaming-response",
250 },
251 );
252 }
253​
254 static fromCoreHandlerError(error: AcpError, method: string) {
255 if (error._tag === "AcpRequestError") {
256 return error;
257 }
258 return AcpRequestError.internalError(
259 `ACP request handler failed for method '${method}'`,
260 undefined,
261 {
262 method,
263 operation: "handle-request",
264 cause: error,
265 },
266 );
267 }
268​
269 static fromExtensionHandlerError(error: AcpError, method: string) {
270 if (error._tag === "AcpRequestError") {
271 return error;
272 }
273 return AcpRequestError.internalError(
274 `ACP extension request handler failed for method '${method}'`,
275 undefined,
276 {
277 method,
278 operation: "handle-extension-request",
279 cause: error,
280 },
281 );
282 }
283​
284 static parseError(message = "Parse error", data?: unknown) {
285 return new AcpRequestError({
286 code: -32700,
287 errorMessage: message,
288 ...(data !== undefined ? { data } : {}),
289 });
290 }
291​
292 static invalidRequest(message = "Invalid request", data?: unknown) {
293 return new AcpRequestError({
294 code: -32600,
295 errorMessage: message,
296 ...(data !== undefined ? { data } : {}),
297 });
298 }
299​
300 static methodNotFound(method: string) {
301 return new AcpRequestError({
302 code: -32601,
303 errorMessage: `Method not found: ${method}`,
304 });
305 }
306​
307 static invalidParams(message = "Invalid params", data?: unknown) {
308 return new AcpRequestError({
309 code: -32602,
310 errorMessage: message,
311 ...(data !== undefined ? { data } : {}),
312 });
313 }
314​
315 static invalidExtensionPayload(method: string, cause: Schema.SchemaError) {
316 const diagnostics = schemaIssueDiagnostics(cause.issue);
317 return new AcpRequestError({
318 code: -32602,
319 errorMessage: `Invalid payload for ACP extension method '${method}'.`,
320 data: diagnostics,
321 method,
322 operation: "decode-extension-request-payload",
323 ...diagnostics,
324 cause,
325 });
326 }
327​
328 static internalError(
329 message = "Internal error",
330 data?: unknown,
331 diagnostics: AcpRequestDiagnostics = {},
332 ) {
333 return new AcpRequestError({
334 code: -32603,
335 errorMessage: message,
336 ...(data !== undefined ? { data } : {}),
337 ...diagnostics,
338 });
339 }
340​
341 static authRequired(message = "Authentication required", data?: unknown) {
342 return new AcpRequestError({
343 code: -32000,
344 errorMessage: message,
345 ...(data !== undefined ? { data } : {}),
346 });
347 }
348​
349 static resourceNotFound(message = "Resource not found", data?: unknown) {
350 return new AcpRequestError({
351 code: -32002,
352 errorMessage: message,
353 ...(data !== undefined ? { data } : {}),
354 });
355 }
356​
357 toProtocolError() {
358 return AcpSchema.Error.make({
359 code: this.code,
360 message: this.errorMessage,
361 ...(this.data !== undefined ? { data: this.data } : {}),
362 });
363 }
365​
366export const AcpError = Schema.Union([
367 AcpRequestError,
368 AcpSpawnError,
369 AcpProcessExitedError,
370 AcpProtocolParseError,
371 AcpTransportError,
372 AcpInputStreamEndedError,
373]);
374​
375export type AcpError = typeof AcpError.Type;