forked from CopilotKit/CopilotKit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.ts
More file actions
93 lines (85 loc) · 2.42 KB
/
Copy pathutils.ts
File metadata and controls
93 lines (85 loc) · 2.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import { GraphQLContext } from "../integrations";
import { Logger } from "pino";
import { CopilotKitEndpoint, RemoteActionInfoResponse } from "./types";
import {
Action,
CopilotKitError,
CopilotKitLowLevelError,
ResolvedCopilotKitError,
} from "@copilotkit/shared";
async function fetchRemoteInfo({
url,
onBeforeRequest,
graphqlContext,
logger,
frontendUrl,
}: {
url: string;
onBeforeRequest?: CopilotKitEndpoint["onBeforeRequest"];
graphqlContext: GraphQLContext;
logger: Logger;
frontendUrl?: string;
}): Promise<RemoteActionInfoResponse> {
logger.debug({ url }, "Fetching actions from url");
const headers = createHeaders(onBeforeRequest, graphqlContext);
const fetchUrl = `${url}/info`;
try {
const response = await fetch(fetchUrl, {
method: "POST",
headers,
body: JSON.stringify({
properties: graphqlContext.properties,
frontendUrl,
}),
});
if (!response.ok) {
logger.error(
{ url, status: response.status, body: await response.text() },
"Failed to fetch actions from url",
);
throw new ResolvedCopilotKitError({
status: response.status,
url: fetchUrl,
isRemoteEndpoint: true,
});
}
const json = await response.json();
logger.debug({ json }, "Fetched actions from url");
return json;
} catch (error) {
if (error instanceof CopilotKitError) {
throw error;
}
throw new CopilotKitLowLevelError({ error, url: fetchUrl });
}
}
// Utility to determine if an error is a user configuration issue vs system error
export function isUserConfigurationError(error: any): boolean {
return (
(error instanceof CopilotKitError ||
error instanceof CopilotKitLowLevelError) &&
(error.code === "NETWORK_ERROR" ||
error.code === "AUTHENTICATION_ERROR" ||
error.statusCode === 401 ||
error.statusCode === 403 ||
error.message?.toLowerCase().includes("authentication") ||
error.message?.toLowerCase().includes("api key"))
);
}
export function createHeaders(
onBeforeRequest: CopilotKitEndpoint["onBeforeRequest"],
graphqlContext: GraphQLContext,
) {
const headers = {
"Content-Type": "application/json",
};
if (onBeforeRequest) {
const { headers: additionalHeaders } = onBeforeRequest({
ctx: graphqlContext,
});
if (additionalHeaders) {
Object.assign(headers, additionalHeaders);
}
}
return headers;
}