-
Notifications
You must be signed in to change notification settings - Fork 73
Expand file tree
/
Copy pathNodeRemote.ts
More file actions
71 lines (61 loc) · 1.82 KB
/
NodeRemote.ts
File metadata and controls
71 lines (61 loc) · 1.82 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
import * as os from 'node:os';
import { ILogger } from 'js-logger';
import {
AbstractRemote,
AbstractRemoteOptions,
BSONImplementation,
DEFAULT_REMOTE_LOGGER,
FetchImplementation,
FetchImplementationProvider,
RemoteConnector
} from '@powersync/common';
import { BSON } from 'bson';
import Agent from 'proxy-agent';
import { EnvHttpProxyAgent, Dispatcher } from 'undici';
import { WebSocket } from 'ws';
export const STREAMING_POST_TIMEOUT_MS = 30_000;
class NodeFetchProvider extends FetchImplementationProvider {
getFetch(): FetchImplementation {
return fetch.bind(globalThis);
}
}
export type NodeRemoteOptions = AbstractRemoteOptions & {
dispatcher?: Dispatcher;
};
export class NodeRemote extends AbstractRemote {
constructor(
protected connector: RemoteConnector,
protected logger: ILogger = DEFAULT_REMOTE_LOGGER,
options?: Partial<NodeRemoteOptions>
) {
// EnvHttpProxyAgent automatically uses relevant env vars for HTTP
const dispatcher = options?.dispatcher ?? new EnvHttpProxyAgent();
super(connector, logger, {
...(options ?? {}),
fetchImplementation: options?.fetchImplementation ?? new NodeFetchProvider(),
fetchOptions: {
dispatcher
}
});
}
protected createSocket(url: string): globalThis.WebSocket {
return new WebSocket(url, {
// Automatically uses relevant env vars for web sockets
agent: new Agent.ProxyAgent(),
headers: {
'User-Agent': this.getUserAgent()
}
}) as any as globalThis.WebSocket; // This is compatible in Node environments
}
getUserAgent(): string {
return [
super.getUserAgent(),
`powersync-node`,
`node/${process.versions.node}`,
`${os.platform()}/${os.release()}`
].join(' ');
}
async getBSON(): Promise<BSONImplementation> {
return BSON;
}
}