-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
Copy pathauth.ts
104 lines (90 loc) · 2.52 KB
/
auth.ts
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
94
95
96
97
98
99
100
101
102
103
104
import { Readable } from "stream";
import {
AbstractStream,
ensureAuthOptionScopes,
GoogleAbstractedClient,
GoogleAbstractedClientOps,
GoogleConnectionParams,
JsonStream,
SseJsonStream,
SseStream,
} from "@langchain/google-common";
import { GoogleAuth, GoogleAuthOptions } from "google-auth-library";
export class NodeAbstractStream implements AbstractStream {
private baseStream: AbstractStream;
constructor(baseStream: AbstractStream, data: Readable) {
this.baseStream = baseStream;
const decoder = new TextDecoder("utf-8");
data.on("data", (data) => {
const text = decoder.decode(data, { stream: true });
this.appendBuffer(text);
});
data.on("end", () => {
const rest = decoder.decode();
this.appendBuffer(rest);
this.closeBuffer();
});
}
appendBuffer(data: string): void {
return this.baseStream.appendBuffer(data);
}
closeBuffer(): void {
return this.baseStream.closeBuffer();
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
nextChunk(): Promise<any> {
return this.baseStream.nextChunk();
}
get streamDone(): boolean {
return this.baseStream.streamDone;
}
}
export class NodeJsonStream extends NodeAbstractStream {
constructor(data: Readable) {
super(new JsonStream(), data);
}
}
export class NodeSseStream extends NodeAbstractStream {
constructor(data: Readable) {
super(new SseStream(), data);
}
}
export class NodeSseJsonStream extends NodeAbstractStream {
constructor(data: Readable) {
super(new SseJsonStream(), data);
}
}
export class GAuthClient implements GoogleAbstractedClient {
gauth: GoogleAuth;
constructor(fields?: GoogleConnectionParams<GoogleAuthOptions>) {
const options = ensureAuthOptionScopes<GoogleAuthOptions>(
fields?.authOptions,
"scopes",
fields?.platformType
);
this.gauth = new GoogleAuth(options);
}
get clientType(): string {
return "gauth";
}
async getProjectId(): Promise<string> {
return this.gauth.getProjectId();
}
async request(opts: GoogleAbstractedClientOps): Promise<unknown> {
const ret = await this.gauth.request(opts);
const [contentType] = ret?.headers?.["content-type"]?.split(/;/) ?? [""];
if (opts.responseType !== "stream") {
return ret;
} else if (contentType === "text/event-stream") {
return {
...ret,
data: new NodeSseJsonStream(ret.data),
};
} else {
return {
...ret,
data: new NodeJsonStream(ret.data),
};
}
}
}