@encore.dev/frontend 0.0.0-placeholder.0 → 2.0.0-beta.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +362 -0
- package/README.md +18 -1
- package/client.ts +158 -0
- package/config.ts +31 -0
- package/dist/client.d.ts +76 -0
- package/dist/client.js +105 -0
- package/dist/client.js.map +1 -0
- package/dist/config.d.ts +17 -0
- package/dist/config.js +28 -0
- package/dist/config.js.map +1 -0
- package/dist/graphql-ws.d.ts +35 -0
- package/dist/graphql-ws.js +130 -0
- package/dist/graphql-ws.js.map +1 -0
- package/dist/graphql.d.ts +16 -0
- package/dist/graphql.js +14 -0
- package/dist/graphql.js.map +1 -0
- package/dist/mod.d.ts +16 -0
- package/dist/mod.js +13 -0
- package/dist/mod.js.map +1 -0
- package/dist/sse.d.ts +25 -0
- package/dist/sse.js +101 -0
- package/dist/sse.js.map +1 -0
- package/graphql-ws.ts +160 -0
- package/graphql.ts +20 -0
- package/mod.ts +26 -0
- package/package.json +38 -6
- package/sse.ts +107 -0
package/graphql-ws.ts
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Minimal `graphql-transport-ws` client used by generated GraphQL subscription
|
|
3
|
+
* methods. Opens one WebSocket per subscription with zero external dependencies.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import type { GraphQLError } from "./graphql.js";
|
|
7
|
+
|
|
8
|
+
/** A GraphQL request payload. */
|
|
9
|
+
export interface GraphQLRequest {
|
|
10
|
+
query: string;
|
|
11
|
+
variables?: Record<string, unknown>;
|
|
12
|
+
operationName?: string;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** Error thrown when a GraphQL subscription fails or receives server-side errors. */
|
|
16
|
+
export class GraphQLSubscriptionError extends Error {
|
|
17
|
+
constructor(public readonly errors: GraphQLError[]) {
|
|
18
|
+
super(errors.map((e) => e.message).join("; ") || "subscription error");
|
|
19
|
+
this.name = "GraphQLSubscriptionError";
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface SubscribeOptions {
|
|
24
|
+
/** The WebSocket URL of the GraphQL endpoint (`ws://` or `wss://`). */
|
|
25
|
+
url: string;
|
|
26
|
+
/** Payload sent with `connection_init` (such as auth credentials), evaluated per connection. */
|
|
27
|
+
connectionParams?: () =>
|
|
28
|
+
| Record<string, unknown>
|
|
29
|
+
| Promise<Record<string, unknown>>;
|
|
30
|
+
/** Overrides the WebSocket implementation (defaults to the global `WebSocket`). */
|
|
31
|
+
webSocket?: typeof WebSocket;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** The `graphql-transport-ws` subprotocol name. */
|
|
35
|
+
export const GRAPHQL_TRANSPORT_WS = "graphql-transport-ws";
|
|
36
|
+
|
|
37
|
+
type ServerMessage =
|
|
38
|
+
| { type: "connection_ack" }
|
|
39
|
+
| { type: "ping"; payload?: unknown }
|
|
40
|
+
| { type: "pong" }
|
|
41
|
+
| { type: "next"; id: string; payload: { data?: unknown; errors?: GraphQLError[] } }
|
|
42
|
+
| { type: "error"; id: string; payload: GraphQLError[] }
|
|
43
|
+
| { type: "complete"; id: string };
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Executes `request` as a GraphQL subscription over `graphql-transport-ws`,
|
|
47
|
+
* yielding `data` from each `next` message. Completes when the server ends the
|
|
48
|
+
* subscription, and throws `GraphQLSubscriptionError` on GraphQL or protocol
|
|
49
|
+
* errors. Breaking out of the loop sends `complete` and closes the socket.
|
|
50
|
+
*/
|
|
51
|
+
export async function* graphqlSubscribe<T = unknown>(
|
|
52
|
+
opts: SubscribeOptions,
|
|
53
|
+
request: GraphQLRequest,
|
|
54
|
+
): AsyncGenerator<T, void, undefined> {
|
|
55
|
+
const WS = opts.webSocket ?? globalThis.WebSocket;
|
|
56
|
+
if (WS === undefined) {
|
|
57
|
+
throw new Error("no WebSocket implementation available; pass webSocket in the options");
|
|
58
|
+
}
|
|
59
|
+
const socket = new WS(opts.url, GRAPHQL_TRANSPORT_WS);
|
|
60
|
+
const id = "1"; // one subscription per socket
|
|
61
|
+
|
|
62
|
+
// Pump socket events into a pull queue so the generator can await them.
|
|
63
|
+
const queue: ServerMessage[] = [];
|
|
64
|
+
let notify: (() => void) | undefined;
|
|
65
|
+
let closed: { code: number; reason: string } | undefined;
|
|
66
|
+
let socketError: Error | undefined;
|
|
67
|
+
const wake = () => {
|
|
68
|
+
notify?.();
|
|
69
|
+
notify = undefined;
|
|
70
|
+
};
|
|
71
|
+
socket.onmessage = (ev: MessageEvent) => {
|
|
72
|
+
queue.push(JSON.parse(String(ev.data)) as ServerMessage);
|
|
73
|
+
wake();
|
|
74
|
+
};
|
|
75
|
+
socket.onerror = () => {
|
|
76
|
+
socketError = new Error("WebSocket error");
|
|
77
|
+
wake();
|
|
78
|
+
};
|
|
79
|
+
socket.onclose = (ev: CloseEvent) => {
|
|
80
|
+
closed = { code: ev.code, reason: ev.reason };
|
|
81
|
+
wake();
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
const next = async (): Promise<ServerMessage> => {
|
|
85
|
+
for (;;) {
|
|
86
|
+
const msg = queue.shift();
|
|
87
|
+
if (msg !== undefined) return msg;
|
|
88
|
+
if (socketError !== undefined) throw socketError;
|
|
89
|
+
if (closed !== undefined) {
|
|
90
|
+
throw new Error(
|
|
91
|
+
`WebSocket closed (${closed.code}${closed.reason ? `: ${closed.reason}` : ""})`,
|
|
92
|
+
);
|
|
93
|
+
}
|
|
94
|
+
await new Promise<void>((resolve) => {
|
|
95
|
+
notify = resolve;
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
};
|
|
99
|
+
const send = (msg: unknown) => socket.send(JSON.stringify(msg));
|
|
100
|
+
|
|
101
|
+
try {
|
|
102
|
+
await new Promise<void>((resolve, reject) => {
|
|
103
|
+
socket.onopen = () => resolve();
|
|
104
|
+
const prevError = socket.onerror;
|
|
105
|
+
socket.onerror = (ev) => {
|
|
106
|
+
reject(new Error("WebSocket connection failed"));
|
|
107
|
+
prevError?.call(socket, ev);
|
|
108
|
+
};
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
const payload = opts.connectionParams === undefined ? undefined : await opts.connectionParams();
|
|
112
|
+
send({ type: "connection_init", ...(payload !== undefined ? { payload } : {}) });
|
|
113
|
+
for (;;) {
|
|
114
|
+
const msg = await next();
|
|
115
|
+
if (msg.type === "connection_ack") break;
|
|
116
|
+
if (msg.type === "ping") send({ type: "pong" });
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
send({ type: "subscribe", id, payload: request });
|
|
120
|
+
for (;;) {
|
|
121
|
+
const msg = await next();
|
|
122
|
+
switch (msg.type) {
|
|
123
|
+
case "next":
|
|
124
|
+
if (msg.id !== id) continue;
|
|
125
|
+
if (msg.payload.errors !== undefined && msg.payload.errors.length > 0) {
|
|
126
|
+
throw new GraphQLSubscriptionError(msg.payload.errors);
|
|
127
|
+
}
|
|
128
|
+
yield msg.payload.data as T;
|
|
129
|
+
break;
|
|
130
|
+
case "error":
|
|
131
|
+
if (msg.id !== id) continue;
|
|
132
|
+
throw new GraphQLSubscriptionError(msg.payload);
|
|
133
|
+
case "complete":
|
|
134
|
+
if (msg.id !== id) continue;
|
|
135
|
+
return;
|
|
136
|
+
case "ping":
|
|
137
|
+
send({ type: "pong" });
|
|
138
|
+
break;
|
|
139
|
+
default:
|
|
140
|
+
break;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
} finally {
|
|
144
|
+
if (closed === undefined) {
|
|
145
|
+
try {
|
|
146
|
+
send({ type: "complete", id });
|
|
147
|
+
} catch {
|
|
148
|
+
// Socket already failed; closing is all that's left.
|
|
149
|
+
}
|
|
150
|
+
socket.close(1000, "done");
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** Derives the WebSocket URL for a gateway path from an HTTP base URL. */
|
|
156
|
+
export function websocketURL(baseURL: string, path: string): string {
|
|
157
|
+
const url = new URL(baseURL.replace(/\/+$/, "") + path);
|
|
158
|
+
url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
|
|
159
|
+
return url.toString();
|
|
160
|
+
}
|
package/graphql.ts
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/** GraphQL response errors, shared by the query and subscription paths. */
|
|
2
|
+
|
|
3
|
+
/** A single error entry from a GraphQL response. */
|
|
4
|
+
export interface GraphQLError {
|
|
5
|
+
message: string;
|
|
6
|
+
path?: (string | number)[];
|
|
7
|
+
extensions?: unknown;
|
|
8
|
+
[key: string]: unknown;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Error thrown when a GraphQL response contains one or more errors. Partial
|
|
13
|
+
* data is discarded.
|
|
14
|
+
*/
|
|
15
|
+
export class GraphQLRequestError extends Error {
|
|
16
|
+
constructor(public readonly errors: GraphQLError[]) {
|
|
17
|
+
super("graphql: " + errors.map((e) => e.message).join("; "));
|
|
18
|
+
this.name = "GraphQLRequestError";
|
|
19
|
+
}
|
|
20
|
+
}
|
package/mod.ts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Encore's frontend SDK.
|
|
3
|
+
*
|
|
4
|
+
* Provides the client runtime used by generated Gateway Clients
|
|
5
|
+
* (`encore_gen/gateway/<name>.ts`), in the browser and on the server.
|
|
6
|
+
* Pure TypeScript with no backend runtime dependencies.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
export { resolveBaseURL } from "./config.js";
|
|
10
|
+
|
|
11
|
+
export { APIError, CallClient } from "./client.js";
|
|
12
|
+
export type { AuthFn, ClientOptions, Fetcher, QueryValue, RequestSpec } from "./client.js";
|
|
13
|
+
|
|
14
|
+
export { sseEvents, sseStream } from "./sse.js";
|
|
15
|
+
export type { SSEEvent } from "./sse.js";
|
|
16
|
+
|
|
17
|
+
export { GraphQLRequestError } from "./graphql.js";
|
|
18
|
+
export type { GraphQLError } from "./graphql.js";
|
|
19
|
+
|
|
20
|
+
export {
|
|
21
|
+
graphqlSubscribe,
|
|
22
|
+
websocketURL,
|
|
23
|
+
GraphQLSubscriptionError,
|
|
24
|
+
GRAPHQL_TRANSPORT_WS,
|
|
25
|
+
} from "./graphql-ws.js";
|
|
26
|
+
export type { GraphQLRequest, SubscribeOptions } from "./graphql-ws.js";
|
package/package.json
CHANGED
|
@@ -1,10 +1,42 @@
|
|
|
1
1
|
{
|
|
2
|
-
"
|
|
3
|
-
|
|
4
|
-
|
|
2
|
+
"bugs": {
|
|
3
|
+
"url": "https://github.com/encoredev/encore/issues"
|
|
4
|
+
},
|
|
5
|
+
"description": "Encore's frontend SDK: the client runtime and streaming primitives for generated Gateway Clients",
|
|
6
|
+
"devDependencies": {
|
|
7
|
+
"@types/node": "^20.11.0",
|
|
8
|
+
"typescript": "^5.5.0"
|
|
9
|
+
},
|
|
10
|
+
"engines": {
|
|
11
|
+
"node": ">=18.0.0"
|
|
12
|
+
},
|
|
13
|
+
"exports": {
|
|
14
|
+
".": {
|
|
15
|
+
"bun": "./mod.ts",
|
|
16
|
+
"default": "./dist/mod.js",
|
|
17
|
+
"types": "./dist/mod.d.ts"
|
|
18
|
+
}
|
|
19
|
+
},
|
|
20
|
+
"files": [
|
|
21
|
+
"dist",
|
|
22
|
+
"*.ts",
|
|
23
|
+
"!*.test.ts",
|
|
24
|
+
"!dist/tsconfig.tsbuildinfo",
|
|
25
|
+
"README.md",
|
|
26
|
+
"LICENSE"
|
|
27
|
+
],
|
|
5
28
|
"license": "MPL-2.0",
|
|
29
|
+
"name": "@encore.dev/frontend",
|
|
6
30
|
"repository": {
|
|
31
|
+
"directory": "sdk/frontend",
|
|
7
32
|
"type": "git",
|
|
8
|
-
"url": "
|
|
9
|
-
}
|
|
10
|
-
|
|
33
|
+
"url": "https://github.com/encoredev/encore"
|
|
34
|
+
},
|
|
35
|
+
"scripts": {
|
|
36
|
+
"build": "tsc -b",
|
|
37
|
+
"test": "bun test"
|
|
38
|
+
},
|
|
39
|
+
"sideEffects": false,
|
|
40
|
+
"type": "module",
|
|
41
|
+
"version": "2.0.0-beta.16"
|
|
42
|
+
}
|
package/sse.ts
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Server-sent events (SSE) parser that turns a `text/event-stream` response
|
|
3
|
+
* into a typed async iterable. Used by generated streaming methods.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
/** A single parsed SSE event. */
|
|
7
|
+
export interface SSEEvent {
|
|
8
|
+
/** The `event:` field, if sent by the server. */
|
|
9
|
+
event?: string;
|
|
10
|
+
/** The concatenated `data:` lines. */
|
|
11
|
+
data: string;
|
|
12
|
+
/** The `id:` field, if sent by the server. */
|
|
13
|
+
id?: string;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Parses a `text/event-stream` response body into SSE events according to the
|
|
18
|
+
* WHATWG EventSource format. Fields accumulate until a blank line dispatches
|
|
19
|
+
* an event, comment lines starting with `:` are ignored, and multiple `data:`
|
|
20
|
+
* lines are joined with newlines.
|
|
21
|
+
*/
|
|
22
|
+
export async function* sseEvents(resp: Response): AsyncGenerator<SSEEvent, void, undefined> {
|
|
23
|
+
if (resp.body === null) return;
|
|
24
|
+
|
|
25
|
+
const decoder = new TextDecoder();
|
|
26
|
+
let buffer = "";
|
|
27
|
+
// Whether the last line ended in a CR at the end of what was read: an LF
|
|
28
|
+
// read next is that CRLF's second half, not a line end of its own.
|
|
29
|
+
let afterCR = false;
|
|
30
|
+
let data: string[] = [];
|
|
31
|
+
let event: string | undefined;
|
|
32
|
+
let id: string | undefined;
|
|
33
|
+
|
|
34
|
+
const dispatch = function* (): Generator<SSEEvent> {
|
|
35
|
+
if (data.length === 0) {
|
|
36
|
+
event = undefined;
|
|
37
|
+
return;
|
|
38
|
+
}
|
|
39
|
+
yield { event, data: data.join("\n"), id };
|
|
40
|
+
data = [];
|
|
41
|
+
event = undefined;
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
const handleLine = function* (line: string): Generator<SSEEvent> {
|
|
45
|
+
if (line === "") {
|
|
46
|
+
yield* dispatch();
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
if (line.startsWith(":")) return; // comment
|
|
50
|
+
const colon = line.indexOf(":");
|
|
51
|
+
const field = colon === -1 ? line : line.slice(0, colon);
|
|
52
|
+
let value = colon === -1 ? "" : line.slice(colon + 1);
|
|
53
|
+
if (value.startsWith(" ")) value = value.slice(1);
|
|
54
|
+
switch (field) {
|
|
55
|
+
case "data":
|
|
56
|
+
data.push(value);
|
|
57
|
+
break;
|
|
58
|
+
case "event":
|
|
59
|
+
event = value;
|
|
60
|
+
break;
|
|
61
|
+
case "id":
|
|
62
|
+
if (!value.includes("\0")) id = value;
|
|
63
|
+
break;
|
|
64
|
+
// "retry" configures EventSource reconnection; meaningless here.
|
|
65
|
+
}
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
const reader = resp.body.getReader();
|
|
69
|
+
try {
|
|
70
|
+
for (;;) {
|
|
71
|
+
const { done, value } = await reader.read();
|
|
72
|
+
if (done) break;
|
|
73
|
+
buffer += decoder.decode(value, { stream: true });
|
|
74
|
+
if (afterCR && buffer !== "") {
|
|
75
|
+
if (buffer.startsWith("\n")) buffer = buffer.slice(1);
|
|
76
|
+
afterCR = false;
|
|
77
|
+
}
|
|
78
|
+
// Line endings per the spec: CRLF, CR, or LF.
|
|
79
|
+
for (;;) {
|
|
80
|
+
const match = /\r\n|\r|\n/.exec(buffer);
|
|
81
|
+
if (match === null) break;
|
|
82
|
+
const line = buffer.slice(0, match.index);
|
|
83
|
+
buffer = buffer.slice(match.index + match[0].length);
|
|
84
|
+
afterCR = match[0] === "\r" && buffer === "";
|
|
85
|
+
yield* handleLine(line);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
buffer += decoder.decode();
|
|
89
|
+
if (buffer !== "") yield* handleLine(buffer);
|
|
90
|
+
// A final event without a trailing blank line still dispatches.
|
|
91
|
+
yield* dispatch();
|
|
92
|
+
} finally {
|
|
93
|
+
reader.releaseLock();
|
|
94
|
+
// Stop the transfer if the consumer broke out early.
|
|
95
|
+
await resp.body.cancel().catch(() => {});
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Parses a `text/event-stream` response and yields each event's JSON-decoded
|
|
101
|
+
* `data` payload.
|
|
102
|
+
*/
|
|
103
|
+
export async function* sseStream<T = unknown>(resp: Response): AsyncGenerator<T, void, undefined> {
|
|
104
|
+
for await (const event of sseEvents(resp)) {
|
|
105
|
+
yield JSON.parse(event.data) as T;
|
|
106
|
+
}
|
|
107
|
+
}
|