@alxia/graphql 0.3.1 → 0.4.0

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/README.md CHANGED
@@ -12,6 +12,7 @@ bun add -d typescript
12
12
  ```
13
13
 
14
14
  `graphql-yoga` and `graphql` are peers: the package declares no dependency.
15
+ `graphql-ws` is an optional one, for [`ws`](#websocket) alone.
15
16
  `graphql` 16 and 17 both work; with 17, `graphql-yoga` must be 5.22 or
16
17
  later, the first to accept it.
17
18
 
@@ -62,6 +63,39 @@ what the app does not build is a compile error:
62
63
  the schema's resolvers read a context the app does not build: missing user
63
64
  ```
64
65
 
66
+ ## Batching (N+1)
67
+
68
+ A field that loads a record per parent — `Note.author` over 50 notes — is
69
+ 51 queries. Build [DataLoaders](https://github.com/graphql/dataloader) in
70
+ the `context` option and type them through `GraphQLContext`'s second
71
+ argument. (Yoga's `batching` option, below, is another thing: several
72
+ operations in one HTTP request.)
73
+
74
+ ```sh
75
+ bun add dataloader
76
+ ```
77
+
78
+ ```ts
79
+ import DataLoader from 'dataloader';
80
+
81
+ const createLoaders = () => ({
82
+ user: new DataLoader(async (ids: readonly string[]) => findUsers(ids)), // one query for all ids
83
+ });
84
+ type Loaders = ReturnType<typeof createLoaders>;
85
+
86
+ const schema = createSchema<GraphQLContext<typeof base, { loaders: Loaders }>>({
87
+ typeDefs,
88
+ resolvers: { Note: { author: (note: { authorId: string }, _, { loaders }) => loaders.user.load(note.authorId) } },
89
+ });
90
+
91
+ const app = base.plugin((app) => graphql(app, { schema, context: () => ({ loaders: createLoaders() }) }));
92
+ ```
93
+
94
+ Per request, never once for the process: a DataLoader caches what it
95
+ loads, so a shared one would serve stale records and hand one user's data
96
+ to the next. Over WebSocket, `context` runs for each operation. See
97
+ [Batching with DataLoader](https://github.com/softistx/alxia/blob/develop/packages/graphql/docs/guide/context.md#batching-with-dataloader-n1).
98
+
65
99
  ## Yoga's plugins
66
100
 
67
101
  Every Yoga option passes through, but `graphqlEndpoint`, which `path`
@@ -82,7 +116,7 @@ graphql(app, {
82
116
 
83
117
  - **Subscriptions** are served over server-sent events, Yoga's default:
84
118
  `async *subscribe` in a resolver, `Accept: text/event-stream` on the
85
- request. `@alxia/compress` leaves an event stream alone by default.
119
+ request; over WebSocket too with [`ws: true`](#websocket). `@alxia/compress` leaves an event stream alone by default.
86
120
  - **An IDE** answers a `GET` from a browser at the endpoint, with a
87
121
  `Content-Security-Policy` that lets it load — its pinned files on unpkg
88
122
  alone, framed by no one — which `@alxia/secure-headers` keeps. By
@@ -103,6 +137,32 @@ graphql(app, {
103
137
  - **CORS** is `@alxia/cors`'s for the whole app: Yoga's own is off unless
104
138
  `cors` is given.
105
139
 
140
+ ## WebSocket
141
+
142
+ `ws: true` serves the endpoint over WebSocket too, with the
143
+ `graphql-transport-ws` protocol of [`graphql-ws`](https://the-guild.dev/graphql/ws),
144
+ the default of Apollo Client's `GraphQLWsLink` and urql's
145
+ `subscriptionExchange`. `graphql-ws` is an optional peer; server-sent
146
+ events stay served at the same path. Install it with `bun add graphql-ws`.
147
+
148
+ ```ts
149
+ const app = base.plugin((app) => graphql(app, { schema, ws: true })); // ws://…/graphql too
150
+ ```
151
+
152
+ ```ts
153
+ import { createClient } from 'graphql-ws';
154
+
155
+ const client = createClient({ url: 'wss://api.example.com/graphql', connectionParams: { device: 'web' } });
156
+ ```
157
+
158
+ The upgrade runs the app's middlewares — a guard's `401` refuses the
159
+ socket, what they add is in the context, beside the `connectionParams`
160
+ the client sent — each operation runs through
161
+ Yoga's plugins, and a shutdown closes the sockets with `1001`, completing
162
+ their subscriptions. `ws: { path, keepAlive }` moves the socket or spaces
163
+ its pings. See [the WebSocket guide](https://github.com/softistx/alxia/blob/develop/packages/graphql/docs/guide/websockets.md),
164
+ Apollo Client's and urql's setup included.
165
+
106
166
  ## Errors, health and shutdown
107
167
 
108
168
  A GraphQL error stays GraphQL's — an entry of `errors[]`, inside a 200 —
@@ -127,7 +187,9 @@ See [the endpoint guide](https://github.com/softistx/alxia/blob/develop/packages
127
187
 
128
188
  | export | |
129
189
  | --- | --- |
130
- | `graphql(app, options)` | the endpoint: `schema`, `path`, `ide`, `sandbox`, and every Yoga option |
190
+ | `graphql(app, options)` | the endpoint: `schema`, `path`, `ide`, `sandbox`, `ws`, and every Yoga option |
191
+ | `GraphQLWsOptions` | `ws`'s options: `path`, `keepAlive` |
192
+ | `GraphQLWsContext` | what an operation over WebSocket adds to the context: `connectionParams` |
131
193
  | `renderSandbox(endpoint, options?)`, `SANDBOX_POLICY` | the Sandbox page, and the policy it loads under |
132
194
  | `SandboxOptions` | its options: `title`, `initialDocument`, `initialHeaders`, `pollForSchemaUpdates`, `includeCookies` |
133
195
  | `GraphQLContext<App, UserContext?>` | what a resolver reads |
@@ -135,7 +197,7 @@ See [the endpoint guide](https://github.com/softistx/alxia/blob/develop/packages
135
197
 
136
198
  ## Documentation
137
199
 
138
- - [Guide](https://github.com/softistx/alxia/tree/develop/packages/graphql/docs): a page per area — mounting the endpoint, the typed context, Yoga's plugins and options, and GraphiQL and Apollo Sandbox.
200
+ - [Guide](https://github.com/softistx/alxia/tree/develop/packages/graphql/docs): a page per area — mounting the endpoint, the typed context, Yoga's plugins and options, GraphQL over WebSocket, and GraphiQL and Apollo Sandbox.
139
201
  - [Troubleshooting](https://github.com/softistx/alxia/blob/develop/packages/graphql/docs/troubleshooting.md): an error message, and what to do about it.
140
202
  - [Roadmap](https://github.com/softistx/alxia/blob/develop/packages/graphql/docs/roadmap.md): what is coming, and what is not planned.
141
203
  - [Recipes](https://github.com/softistx/alxia/blob/develop/docs/recipes/README.md): [A GraphQL API](https://github.com/softistx/alxia/blob/develop/docs/recipes/graphql-api.md), [Authenticate requests](https://github.com/softistx/alxia/blob/develop/docs/recipes/authentication.md), [Test an alxia app](https://github.com/softistx/alxia/blob/develop/docs/recipes/testing.md), [Health checks and graceful shutdown](https://github.com/softistx/alxia/blob/develop/docs/recipes/health-and-shutdown.md), and more.
package/dist/graphql.d.ts CHANGED
@@ -2,6 +2,7 @@ import { type Alxia, type BaseContext, type Empty, type RoutePath } from '@alxia
2
2
  import type { GraphQLSchemaWithContext, YogaInitialContext, YogaServerOptions } from 'graphql-yoga';
3
3
  import { type YogaContext } from './handler';
4
4
  import type { SandboxOptions } from './sandbox';
5
+ import { type GraphQLWsOptions } from './ws';
5
6
  /** The parts of a route's context Yoga owns, or that mean nothing to a resolver. */
6
7
  type RouteOnly = 'params' | 'query' | 'headers' | 'cookies' | 'body' | 'reply' | 'redirect';
7
8
  /**
@@ -11,8 +12,16 @@ type RouteOnly = 'params' | 'query' | 'headers' | 'cookies' | 'body' | 'reply' |
11
12
  */
12
13
  export type ServerContext<Ctx> = Omit<BaseContext & Ctx, RouteOnly>;
13
14
  /**
14
- * What a resolver reads as its context: Yoga's own, the app's, and what
15
- * the `context` option adds. Type a schema with it:
15
+ * What an operation over WebSocket adds to its context (`ws` on): the
16
+ * `connectionParams` the client sent when it connected. `undefined` over
17
+ * HTTP, and for a client that sent none.
18
+ */
19
+ export interface GraphQLWsContext {
20
+ readonly connectionParams?: Readonly<Record<string, unknown>>;
21
+ }
22
+ /**
23
+ * What a resolver reads as its context: Yoga's own, the app's, what
24
+ * the `context` option adds, and over WebSocket the `connectionParams`. Type a schema with it:
16
25
  *
17
26
  * ```ts
18
27
  * const base = alxia().use(bearer({ jwt }));
@@ -21,7 +30,7 @@ export type ServerContext<Ctx> = Omit<BaseContext & Ctx, RouteOnly>;
21
30
  */
22
31
  export type GraphQLContext<App, UserContext = Empty> = App extends {
23
32
  readonly '~context': infer Ctx;
24
- } ? YogaInitialContext & ServerContext<Ctx> & UserContext : {
33
+ } ? YogaInitialContext & ServerContext<Ctx> & GraphQLWsContext & UserContext : {
25
34
  readonly '~error': 'GraphQLContext needs the type of an app: GraphQLContext<typeof app>';
26
35
  };
27
36
  export interface GraphQLOptions<ServerCtx extends YogaContext, UserCtx extends YogaContext, Path extends RoutePath, SchemaCtx = unknown> extends Omit<YogaServerOptions<ServerCtx, UserCtx>, 'graphqlEndpoint' | 'cors' | 'schema' | 'graphiql'> {
@@ -49,6 +58,14 @@ export interface GraphQLOptions<ServerCtx extends YogaContext, UserCtx extends Y
49
58
  * app, this endpoint included.
50
59
  */
51
60
  readonly cors?: YogaServerOptions<ServerCtx, UserCtx>['cors'];
61
+ /**
62
+ * GraphQL over WebSocket too, the `graphql-transport-ws` protocol of
63
+ * Apollo Client's and urql's default link, served by the optional peer
64
+ * `graphql-ws` at the endpoint's path: `true`, or where and how often it
65
+ * pings. Off by default: subscriptions are served over server-sent
66
+ * events, which stay served beside it.
67
+ */
68
+ readonly ws?: boolean | GraphQLWsOptions;
52
69
  }
53
70
  /**
54
71
  * The check Yoga's types leave out: the context the app builds must hold
@@ -64,7 +81,8 @@ type ProvidesContext<Provided, Required> = Provided extends Required ? unknown :
64
81
  * before it. A guard before it guards it; what the middlewares added is in each
65
82
  * resolver's context, typed. Yoga's options pass through — `plugins`
66
83
  * (Envelop's and Yoga's), `graphiql`, `maskedErrors`, `batching`… —
67
- * and subscriptions are served over server-sent events.
84
+ * and subscriptions are served over server-sent events, and over
85
+ * WebSocket too with `ws: true`.
68
86
  *
69
87
  * ```ts
70
88
  * const app = alxia()
@@ -1 +1 @@
1
- {"version":3,"file":"graphql.d.ts","sourceRoot":"","sources":["../src/graphql.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,KAAK,KAAK,EACV,KAAK,WAAW,EAChB,KAAK,KAAK,EAEV,KAAK,SAAS,EACd,MAAM,aAAa,CAAC;AACrB,OAAO,KAAK,EACX,wBAAwB,EACxB,kBAAkB,EAClB,iBAAiB,EACjB,MAAM,cAAc,CAAC;AACtB,OAAO,EAAkB,KAAK,WAAW,EAAe,MAAM,WAAW,CAAC;AAC1E,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAEhD,oFAAoF;AACpF,KAAK,SAAS,GACX,QAAQ,GACR,OAAO,GACP,SAAS,GACT,SAAS,GACT,MAAM,GACN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C;IACrB;;;OAGG;IACH,QAAQ,CAAC,IAAI,CAAC,EAAE,iBAAiB,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC,MAAM,CAAC,CAAC;IAC9D;;;;;;OAMG;IACH,QAAQ,CAAC,EAAE,CAAC,EAAE,OAAO,GAAG,gBAAgB,CAAC;CACzC;AAED;;;;GAIG;AACH,KAAK,eAAe,CAAC,QAAQ,EAAE,QAAQ,IAAI,QAAQ,SAAS,QAAQ,GACjE,OAAO,GACP;IACA,QAAQ,CAAC,MAAM,EAAE,yEAAyE,OAAO,CAChG,MAAM,QAAQ,EACd,MAAM,QAAQ,CACd,GACA,MAAM,EAAE,CAAC;CACV,CAAC;AAEJ;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,OAAO,CACtB,GAAG,SAAS,MAAM,EAClB,MAAM,SAAS,MAAM,EACrB,SAAS,EACT,OAAO,SAAS,WAAW,GAAG,KAAK,EACnC,KAAK,CAAC,IAAI,SAAS,SAAS,GAAG,UAAU,EAEzC,GAAG,EAAE,KAAK,CAAC,GAAG,EAAE,MAAM,CAAC,EACvB,OAAO,EAAE,cAAc,CAAC,aAAa,CAAC,GAAG,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,SAAS,CAAC,GACpE,eAAe,CACd,kBAAkB,GAAG,aAAa,CAAC,GAAG,CAAC,GAAG,OAAO,EACjD,SAAS,CACT,GACA,KAAK,CAAC,GAAG,EAAE,MAAM,CAAC,CAqCpB"}
package/dist/handler.d.ts CHANGED
@@ -21,6 +21,11 @@ export declare function graphiqlPolicy(html: string): string;
21
21
  * GraphiQL must ask that one.
22
22
  */
23
23
  export declare function yogaServers<UserCtx extends YogaContext>(options: Omit<YogaServerOptions<YogaContext, UserCtx>, 'graphqlEndpoint'>): (endpoint: string) => YogaServerInstance<YogaContext, UserCtx>;
24
+ /**
25
+ * What Yoga is handed as its server context: the route's context — the
26
+ * middlewares' work — minus what a resolver has no use for.
27
+ */
28
+ export declare function serverContext(ctx: Record<string, unknown>): Record<string, unknown>;
24
29
  /**
25
30
  * The handler of the endpoint's `GET` and `POST`: Apollo Sandbox's page to
26
31
  * a browser when `sandbox` is not `false`, else the request to Yoga, with
@@ -1 +1 @@
1
- {"version":3,"file":"handler.d.ts","sourceRoot":"","sources":["../src/handler.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAE,KAAK,WAAW,EAAE,KAAK,UAAU,EAAkB,MAAM,aAAa,CAAC;AAChF,OAAO,EAEN,KAAK,kBAAkB,EACvB,KAAK,iBAAiB,EACtB,MAAM,cAAc,CAAC;AACtB,OAAO,EAAiC,KAAK,cAAc,EAAE,MAAM,WAAW,CAAC;AAE/E,MAAM,MAAM,WAAW,GAAG,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;AAM9C;;;;;;;GAOG;AACH,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAanD;AAED;;;;GAIG;AACH,wBAAgB,WAAW,CAAC,OAAO,SAAS,WAAW,EACtD,OAAO,EAAE,IAAI,CAAC,iBAAiB,CAAC,WAAW,EAAE,OAAO,CAAC,EAAE,iBAAiB,CAAC,GACvE,CAAC,QAAQ,EAAE,MAAM,KAAK,kBAAkB,CAAC,WAAW,EAAE,OAAO,CAAC,CAahE;AAED;;;;;GAKG;AACH,wBAAgB,cAAc,CAAC,OAAO,SAAS,WAAW,EACzD,MAAM,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,kBAAkB,CAAC,WAAW,EAAE,OAAO,CAAC,EACtE,OAAO,EAAE,cAAc,GAAG,KAAK,IAK9B,KAAK,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,WAAW,GAAG;IAAE,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAA;CAAE,qJA2CxE"}
1
+ {"version":3,"file":"handler.d.ts","sourceRoot":"","sources":["../src/handler.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAE,KAAK,WAAW,EAAE,KAAK,UAAU,EAAkB,MAAM,aAAa,CAAC;AAChF,OAAO,EAEN,KAAK,kBAAkB,EACvB,KAAK,iBAAiB,EACtB,MAAM,cAAc,CAAC;AACtB,OAAO,EAAiC,KAAK,cAAc,EAAE,MAAM,WAAW,CAAC;AAE/E,MAAM,MAAM,WAAW,GAAG,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;AAM9C;;;;;;;GAOG;AACH,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAanD;AAED;;;;GAIG;AACH,wBAAgB,WAAW,CAAC,OAAO,SAAS,WAAW,EACtD,OAAO,EAAE,IAAI,CAAC,iBAAiB,CAAC,WAAW,EAAE,OAAO,CAAC,EAAE,iBAAiB,CAAC,GACvE,CAAC,QAAQ,EAAE,MAAM,KAAK,kBAAkB,CAAC,WAAW,EAAE,OAAO,CAAC,CAahE;AAED;;;GAGG;AACH,wBAAgB,aAAa,CAC5B,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAC1B,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAYzB;AAED;;;;;GAKG;AACH,wBAAgB,cAAc,CAAC,OAAO,SAAS,WAAW,EACzD,MAAM,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,kBAAkB,CAAC,WAAW,EAAE,OAAO,CAAC,EACtE,OAAO,EAAE,cAAc,GAAG,KAAK,IAK9B,KAAK,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,WAAW,GAAG;IAAE,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAA;CAAE,qJAmCxE"}
package/dist/index.d.ts CHANGED
@@ -1,3 +1,4 @@
1
- export { type GraphQLContext, type GraphQLOptions, graphql, type ServerContext, } from './graphql';
1
+ export { type GraphQLContext, type GraphQLOptions, type GraphQLWsContext, graphql, type ServerContext, } from './graphql';
2
2
  export { renderSandbox, SANDBOX_POLICY, type SandboxOptions } from './sandbox';
3
+ export type { GraphQLWsOptions } from './ws';
3
4
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,KAAK,cAAc,EACnB,KAAK,cAAc,EACnB,OAAO,EACP,KAAK,aAAa,GAClB,MAAM,WAAW,CAAC;AACnB,OAAO,EAAE,aAAa,EAAE,cAAc,EAAE,KAAK,cAAc,EAAE,MAAM,WAAW,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,KAAK,cAAc,EACnB,KAAK,cAAc,EACnB,KAAK,gBAAgB,EACrB,OAAO,EACP,KAAK,aAAa,GAClB,MAAM,WAAW,CAAC;AACnB,OAAO,EAAE,aAAa,EAAE,cAAc,EAAE,KAAK,cAAc,EAAE,MAAM,WAAW,CAAC;AAC/E,YAAY,EAAE,gBAAgB,EAAE,MAAM,MAAM,CAAC"}
package/dist/index.js CHANGED
@@ -89,18 +89,23 @@ function yogaServers(options) {
89
89
  return yoga;
90
90
  };
91
91
  }
92
+ function serverContext(ctx) {
93
+ const {
94
+ params: _params,
95
+ query: _query,
96
+ headers: _headers,
97
+ cookies: _cookies,
98
+ body: _body,
99
+ reply: _reply,
100
+ redirect: _redirect,
101
+ ...server
102
+ } = ctx;
103
+ return server;
104
+ }
92
105
  function graphqlHandler(yogaAt, sandbox) {
93
106
  return async function graphql(ctx) {
94
- const {
95
- params: _params,
96
- query: _query,
97
- headers: _headers,
98
- cookies: _cookies,
99
- body: _body,
100
- reply,
101
- redirect: _redirect,
102
- ...server
103
- } = ctx;
107
+ const { reply } = ctx;
108
+ const server = serverContext(ctx);
104
109
  if (sandbox !== false && ctx.request.method === "GET" && ctx.request.headers.get("accept")?.includes("text/html") && !ctx.url.searchParams.has("query")) {
105
110
  return reply(200, renderSandbox(ctx.route, sandbox), {
106
111
  headers: {
@@ -156,6 +161,134 @@ function endedOnShutdown(response, signal) {
156
161
  });
157
162
  }
158
163
 
164
+ // src/ws.ts
165
+ var MISSING_PEER = "@alxia/graphql: graphql(app, { ws }) serves GraphQL over WebSocket with the optional peer graphql-ws, which is not installed: bun add graphql-ws";
166
+ function loader() {
167
+ let loading;
168
+ return () => {
169
+ loading ??= import("graphql-ws").catch((cause) => {
170
+ throw new Error(MISSING_PEER, { cause });
171
+ });
172
+ return loading;
173
+ };
174
+ }
175
+ function endpointOf(route, paths) {
176
+ const own = paths.socket === "/" ? "" : paths.socket;
177
+ const at = paths.endpoint === "/" ? "" : paths.endpoint;
178
+ return route.slice(0, route.length - own.length) + at || "/";
179
+ }
180
+ function serverOptions(yogaAt, paths) {
181
+ const enveloped = new WeakMap;
182
+ const of = (args) => enveloped.get(args.contextValue);
183
+ return {
184
+ execute: (args) => of(args).execute(args),
185
+ subscribe: (args) => of(args).subscribe(args),
186
+ async onSubscribe(context, _id, params) {
187
+ const { ctx, request } = context.extra;
188
+ const initial = {
189
+ ...serverContext(ctx),
190
+ request,
191
+ params,
192
+ connectionParams: context.connectionParams
193
+ };
194
+ const { schema, execute, subscribe, contextFactory, parse, validate } = yogaAt(endpointOf(ctx.route, paths)).getEnveloped(initial);
195
+ let document;
196
+ try {
197
+ document = parse(params.query);
198
+ } catch (error) {
199
+ return [error];
200
+ }
201
+ const errors = validate(schema, document);
202
+ if (errors.length > 0)
203
+ return errors;
204
+ const contextValue = await contextFactory();
205
+ enveloped.set(contextValue, { execute, subscribe });
206
+ return {
207
+ schema,
208
+ document,
209
+ operationName: params.operationName,
210
+ variableValues: params.variables,
211
+ contextValue
212
+ };
213
+ }
214
+ };
215
+ }
216
+ function chosen(module, request) {
217
+ const offered = request.headers.get("sec-websocket-protocol") ?? "";
218
+ return module.handleProtocols(offered) || "";
219
+ }
220
+ function operationRequest(upgrade, signal) {
221
+ return new Request(upgrade.url, {
222
+ method: "POST",
223
+ headers: upgrade.headers,
224
+ signal
225
+ });
226
+ }
227
+ function pingEvery(keepAlive) {
228
+ if (keepAlive === undefined)
229
+ return 12000;
230
+ if (keepAlive === false)
231
+ return false;
232
+ if (Number.isFinite(keepAlive) && keepAlive > 0)
233
+ return keepAlive;
234
+ throw new TypeError(`graphql(app, { ws: { keepAlive: ${keepAlive} } }): keepAlive is the milliseconds between pings, a positive number, or false for none`);
235
+ }
236
+ function graphqlSocket(yogaAt, endpoint, options) {
237
+ const paths = { endpoint, socket: options.path ?? endpoint };
238
+ const keepAlive = pingEvery(options.keepAlive);
239
+ const load = loader();
240
+ let module;
241
+ let server;
242
+ const clients = new WeakMap;
243
+ async function graphqlWs(ctx, next) {
244
+ module ??= await load();
245
+ server ??= module.makeServer(serverOptions(yogaAt, paths));
246
+ const protocol = chosen(module, ctx.request);
247
+ if (protocol !== "")
248
+ ctx.set.headers.set("sec-websocket-protocol", protocol);
249
+ return next();
250
+ }
251
+ const handlers = {
252
+ open(socket) {
253
+ const raw = socket.raw;
254
+ const client = { gone: new AbortController };
255
+ clients.set(raw, client);
256
+ const graphqlWsServer = server;
257
+ client.closed = graphqlWsServer.opened({
258
+ protocol: chosen(module, socket.data.request),
259
+ send: (data) => {
260
+ if (raw.readyState === 1)
261
+ raw.sendText(data);
262
+ },
263
+ close: (code, reason) => raw.close(code, reason),
264
+ onMessage: (handle) => {
265
+ client.onMessage = handle;
266
+ }
267
+ }, {
268
+ ctx: socket.data,
269
+ request: operationRequest(socket.data.request, client.gone.signal)
270
+ });
271
+ if (keepAlive !== false) {
272
+ client.pings = setInterval(() => raw.ping(), keepAlive);
273
+ }
274
+ },
275
+ async message(socket, message) {
276
+ const data = typeof message === "string" ? message : new TextDecoder().decode(message);
277
+ await clients.get(socket.raw)?.onMessage?.(data);
278
+ },
279
+ async close(socket, code, reason) {
280
+ const client = clients.get(socket.raw);
281
+ if (client === undefined)
282
+ return;
283
+ clearInterval(client.pings);
284
+ clients.delete(socket.raw);
285
+ client.gone.abort();
286
+ await client.closed?.(code, reason);
287
+ }
288
+ };
289
+ return { path: paths.socket, middleware: graphqlWs, handlers };
290
+ }
291
+
159
292
  // src/graphql.ts
160
293
  function graphql(app, options) {
161
294
  const {
@@ -164,6 +297,7 @@ function graphql(app, options) {
164
297
  ide,
165
298
  graphiql,
166
299
  sandbox,
300
+ ws = false,
167
301
  ...yogaOptions
168
302
  } = options;
169
303
  const page = graphiql ?? true;
@@ -176,6 +310,10 @@ function graphql(app, options) {
176
310
  const route = app;
177
311
  route.get(path, handler);
178
312
  route.post(path, handler);
313
+ if (ws !== false) {
314
+ const socket = graphqlSocket(yogaAt, path, ws === true ? {} : ws);
315
+ route.ws(socket.path, socket.middleware, socket.handlers);
316
+ }
179
317
  return app;
180
318
  }
181
319
  export {
@@ -184,5 +322,5 @@ export {
184
322
  renderSandbox
185
323
  };
186
324
 
187
- //# debugId=36F374D7B3E2E7EE64756E2164756E21
325
+ //# debugId=E799A72AD243BAC264756E2164756E21
188
326
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1,12 +1,13 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../src/graphql.ts", "../src/handler.ts", "../src/sandbox.ts"],
3
+ "sources": ["../src/graphql.ts", "../src/handler.ts", "../src/sandbox.ts", "../src/ws.ts"],
4
4
  "sourcesContent": [
5
- "import {\n\ttype Alxia,\n\ttype BaseContext,\n\ttype Empty,\n\tisDev,\n\ttype RoutePath,\n} from '@alxia/core';\nimport type {\n\tGraphQLSchemaWithContext,\n\tYogaInitialContext,\n\tYogaServerOptions,\n} from 'graphql-yoga';\nimport { graphqlHandler, type YogaContext, yogaServers } from './handler';\nimport type { SandboxOptions } from './sandbox';\n\n/** The parts of a route's context Yoga owns, or that mean nothing to a resolver. */\ntype RouteOnly =\n\t| 'params'\n\t| 'query'\n\t| 'headers'\n\t| 'cookies'\n\t| 'body'\n\t| 'reply'\n\t| 'redirect';\n\n/**\n * What alxia hands Yoga for each request: the context its middlewares built —\n * `user`, `db`, `log`… — with `request`, `url`, `ip` and `set`, through\n * which a resolver sets a cookie or a header on the response.\n */\nexport type ServerContext<Ctx> = Omit<BaseContext & Ctx, RouteOnly>;\n\n/**\n * What a resolver reads as its context: Yoga's own, the app's, and what\n * the `context` option adds. Type a schema with it:\n *\n * ```ts\n * const base = alxia().use(bearer({ jwt }));\n * const schema = createSchema<GraphQLContext<typeof base>>({ ... });\n * ```\n */\nexport type GraphQLContext<App, UserContext = Empty> = App extends {\n\treadonly '~context': infer Ctx;\n}\n\t? YogaInitialContext & ServerContext<Ctx> & UserContext\n\t: // Not `never`: a schema typed with `never` would let every resolver\n\t\t// read anything until `graphql()` refused it.\n\t\t{\n\t\t\treadonly '~error': 'GraphQLContext needs the type of an app: GraphQLContext<typeof app>';\n\t\t};\n\nexport interface GraphQLOptions<\n\tServerCtx extends YogaContext,\n\tUserCtx extends YogaContext,\n\tPath extends RoutePath,\n\tSchemaCtx = unknown,\n> extends Omit<\n\t\tYogaServerOptions<ServerCtx, UserCtx>,\n\t\t'graphqlEndpoint' | 'cors' | 'schema' | 'graphiql'\n\t> {\n\t/**\n\t * What a browser gets at the endpoint: Yoga's GraphiQL, Apollo Sandbox,\n\t * or nothing. By default, GraphiQL in the serving app's dev alone\n\t * (`isDev`: `alxia({ dev })`, else `NODE_ENV=development`), nothing\n\t * otherwise; `graphiql` or `apollo-sandbox` serves one everywhere.\n\t */\n\treadonly ide?: 'graphiql' | 'apollo-sandbox' | false;\n\t/** GraphiQL's options, Yoga's own, when `ide` is `graphiql`. */\n\treadonly graphiql?: Exclude<\n\t\tYogaServerOptions<ServerCtx, UserCtx>['graphiql'],\n\t\tboolean\n\t>;\n\t/** Apollo Sandbox's options, when `ide` is `apollo-sandbox`. */\n\treadonly sandbox?: SandboxOptions;\n\t/**\n\t * The schema, from Yoga's `createSchema`, Pothos, or any tool that types\n\t * its context. Its context must be one the app builds: a resolver that\n\t * reads `user` behind no middleware that adds one is a compile error.\n\t */\n\treadonly schema: GraphQLSchemaWithContext<SchemaCtx>;\n\t/** Where the endpoint is, under the app's prefix. `/graphql` by default. */\n\treadonly path?: Path;\n\t/**\n\t * Yoga's own CORS. Off by default: `@alxia/cors` answers for the whole\n\t * app, this endpoint included.\n\t */\n\treadonly cors?: YogaServerOptions<ServerCtx, UserCtx>['cors'];\n}\n\n/**\n * The check Yoga's types leave out: the context the app builds must hold\n * what the schema's resolvers read. A mistake comes back as a `schema`\n * whose type is the message.\n */\ntype ProvidesContext<Provided, Required> = Provided extends Required\n\t? unknown\n\t: {\n\t\t\treadonly schema: `the schema's resolvers read a context the app does not build: missing ${Exclude<\n\t\t\t\tkeyof Required,\n\t\t\t\tkeyof Provided\n\t\t\t> &\n\t\t\t\tstring}`;\n\t\t};\n\n/**\n * A GraphQL endpoint on `app`, served by [GraphQL Yoga](https://the-guild.dev/graphql/yoga-server):\n * `GET` and `POST` at `path`, behind every middleware given to `use` on `app`\n * before it. A guard before it guards it; what the middlewares added is in each\n * resolver's context, typed. Yoga's options pass through — `plugins`\n * (Envelop's and Yoga's), `graphiql`, `maskedErrors`, `batching`… —\n * and subscriptions are served over server-sent events.\n *\n * ```ts\n * const app = alxia()\n * .use(bearer({ jwt }))\n * .plugin((app) => graphql(app, { schema, plugins: [useDepthLimit()] }));\n * ```\n */\nexport function graphql<\n\tCtx extends object,\n\tPrefix extends string,\n\tSchemaCtx,\n\tUserCtx extends YogaContext = Empty,\n\tconst Path extends RoutePath = '/graphql',\n>(\n\tapp: Alxia<Ctx, Prefix>,\n\toptions: GraphQLOptions<ServerContext<Ctx>, UserCtx, Path, SchemaCtx> &\n\t\tProvidesContext<\n\t\t\tYogaInitialContext & ServerContext<Ctx> & UserCtx,\n\t\t\tSchemaCtx\n\t\t>,\n): Alxia<Ctx, Prefix> {\n\tconst {\n\t\tpath = '/graphql' as Path,\n\t\tcors = false,\n\t\tide,\n\t\tgraphiql,\n\t\tsandbox,\n\t\t...yogaOptions\n\t} = options;\n\tconst page = graphiql ?? true;\n\tconst yogaAt = yogaServers<UserCtx>({\n\t\t...(yogaOptions as YogaServerOptions<YogaContext, UserCtx>),\n\t\tcors,\n\t\tgraphiql: (ide === undefined\n\t\t\t? (_request: Request, context: object) => isDev(context) && page\n\t\t\t: ide === 'graphiql'\n\t\t\t\t? page\n\t\t\t\t: false) as YogaServerOptions<YogaContext, UserCtx>['graphiql'],\n\t});\n\tconst handler = graphqlHandler(\n\t\tyogaAt,\n\t\tide === 'apollo-sandbox' ? (sandbox ?? {}) : false,\n\t);\n\n\tconst route = app as unknown as {\n\t\tget(path: string, handler: unknown): unknown;\n\t\tpost(path: string, handler: unknown): unknown;\n\t};\n\troute.get(path, handler);\n\troute.post(path, handler);\n\treturn app as never;\n}\n",
6
- "/**\n * The endpoint behind `graphql()`: one Yoga per path it is served at, and\n * the route handler that hands each request to it.\n */\nimport { type BaseContext, type StatusCode, shutdownSignal } from '@alxia/core';\nimport {\n\tcreateYoga,\n\ttype YogaServerInstance,\n\ttype YogaServerOptions,\n} from 'graphql-yoga';\nimport { renderSandbox, SANDBOX_POLICY, type SandboxOptions } from './sandbox';\n\nexport type YogaContext = Record<string, any>;\n\n/** Where Yoga's GraphiQL page loads its files from: one pinned version on unpkg. */\nconst GRAPHIQL_FILES =\n\t/https:\\/\\/unpkg\\.com\\/@graphql-yoga\\/graphiql@[\\w.-]+\\//;\n\n/**\n * What GraphiQL's page may load: its scripts, styles and Monaco's\n * workers from the exact version of `@graphql-yoga/graphiql` the page\n * names, fetched and run as blobs; queries to this server alone; framed\n * by no one. A page that names none (a `renderGraphiQL` of the app's own)\n * gets this server alone. `@alxia/secure-headers` keeps a policy a\n * response already has.\n */\nexport function graphiqlPolicy(html: string): string {\n\tconst files = html.match(GRAPHIQL_FILES)?.[0] ?? '';\n\tconst from = files === '' ? '' : ` ${files}`;\n\treturn [\n\t\t\"default-src 'self'\",\n\t\t`script-src 'self' 'unsafe-inline'${from}`,\n\t\t`style-src 'self' 'unsafe-inline'${from}`,\n\t\t\"img-src 'self' data: https:\",\n\t\t`font-src 'self' data:${from}`,\n\t\t\"worker-src 'self' blob:\",\n\t\t`connect-src 'self'${from}`,\n\t\t\"frame-ancestors 'none'\",\n\t].join('; ');\n}\n\n/**\n * The Yoga serving `endpoint`, created on first use. One per path: a plugin\n * mounted under a prefix serves the same routes at a longer path, and\n * GraphiQL must ask that one.\n */\nexport function yogaServers<UserCtx extends YogaContext>(\n\toptions: Omit<YogaServerOptions<YogaContext, UserCtx>, 'graphqlEndpoint'>,\n): (endpoint: string) => YogaServerInstance<YogaContext, UserCtx> {\n\tconst servers = new Map<string, YogaServerInstance<YogaContext, UserCtx>>();\n\treturn (endpoint) => {\n\t\tlet yoga = servers.get(endpoint);\n\t\tif (yoga === undefined) {\n\t\t\tyoga = createYoga<YogaContext, UserCtx>({\n\t\t\t\t...options,\n\t\t\t\tgraphqlEndpoint: endpoint,\n\t\t\t});\n\t\t\tservers.set(endpoint, yoga);\n\t\t}\n\t\treturn yoga;\n\t};\n}\n\n/**\n * The handler of the endpoint's `GET` and `POST`: Apollo Sandbox's page to\n * a browser when `sandbox` is not `false`, else the request to Yoga, with\n * the route's context — the middlewares' work, minus what a resolver has no use\n * for — as Yoga's server context.\n */\nexport function graphqlHandler<UserCtx extends YogaContext>(\n\tyogaAt: (endpoint: string) => YogaServerInstance<YogaContext, UserCtx>,\n\tsandbox: SandboxOptions | false,\n) {\n\t// A handler's context: its route is the one it was declared at. Named\n\t// `graphql`, the name the route table `listen` prints in dev shows.\n\treturn async function graphql(\n\t\tctx: Record<string, unknown> & BaseContext & { readonly route: string },\n\t) {\n\t\tconst {\n\t\t\tparams: _params,\n\t\t\tquery: _query,\n\t\t\theaders: _headers,\n\t\t\tcookies: _cookies,\n\t\t\tbody: _body,\n\t\t\treply,\n\t\t\tredirect: _redirect,\n\t\t\t...server\n\t\t} = ctx;\n\t\tif (\n\t\t\tsandbox !== false &&\n\t\t\tctx.request.method === 'GET' &&\n\t\t\tctx.request.headers.get('accept')?.includes('text/html') &&\n\t\t\t!ctx.url.searchParams.has('query')\n\t\t) {\n\t\t\t// A path: the page resolves it against its own address, so behind\n\t\t\t// a TLS proxy the Sandbox asks over https, as the browser did.\n\t\t\treturn reply(200, renderSandbox(ctx.route, sandbox), {\n\t\t\t\theaders: {\n\t\t\t\t\t'content-type': 'text/html;charset=utf-8',\n\t\t\t\t\t'content-security-policy': SANDBOX_POLICY,\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\t\tconst response = await yogaAt(ctx.route).fetch(ctx.request, server);\n\t\tconst headers = new Headers(response.headers);\n\t\tif (\n\t\t\theaders.get('content-type')?.startsWith('text/html') &&\n\t\t\t!headers.has('content-security-policy')\n\t\t) {\n\t\t\t// GraphiQL's page: its policy names the files it loads.\n\t\t\tconst html = await response.text();\n\t\t\theaders.set('content-security-policy', graphiqlPolicy(html));\n\t\t\treturn reply(response.status as StatusCode, html, { headers });\n\t\t}\n\t\tconst body = endedOnShutdown(response, shutdownSignal(ctx));\n\t\treturn reply(response.status as StatusCode, body ?? undefined, {\n\t\t\theaders,\n\t\t});\n\t};\n}\n\n/**\n * A subscription's or an incremental delivery's body, which streams until\n * its reader stops: ended when the app starts shutting down — Yoga's\n * stream cancelled, as when the client leaves, and the client reading its\n * end — so the drain does not wait for it. Any other body finishes within\n * the drain as it is.\n */\nfunction endedOnShutdown(\n\tresponse: Response,\n\tsignal: AbortSignal,\n): ReadableStream<Uint8Array> | null {\n\tconst body = response.body;\n\tconst type = response.headers.get('content-type') ?? '';\n\tif (body === null || !/text\\/event-stream|multipart\\/mixed/.test(type)) {\n\t\treturn body;\n\t}\n\tconst reader = body.getReader();\n\treturn new ReadableStream<Uint8Array>({\n\t\tstart(controller) {\n\t\t\tconst end = () => {\n\t\t\t\tvoid reader.cancel();\n\t\t\t\ttry {\n\t\t\t\t\tcontroller.close();\n\t\t\t\t} catch {\n\t\t\t\t\t// Closed already: the stream had ended.\n\t\t\t\t}\n\t\t\t};\n\t\t\tif (signal.aborted) end();\n\t\t\telse signal.addEventListener('abort', end, { once: true });\n\t\t},\n\t\tasync pull(controller) {\n\t\t\tconst { value, done } = await reader.read();\n\t\t\tif (done) {\n\t\t\t\ttry {\n\t\t\t\t\tcontroller.close();\n\t\t\t\t} catch {\n\t\t\t\t\t// Closed already: the shutdown ended it.\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcontroller.enqueue(value);\n\t\t},\n\t\tcancel: (reason) => reader.cancel(reason),\n\t});\n}\n",
7
- "/**\n * [Apollo Sandbox](https://www.apollographql.com/docs/graphos/platform/sandbox),\n * embedded: the page a browser gets at the endpoint when the IDE is\n * `apollo-sandbox`. `@nxgt/shared-graphql`'s `renderSandbox`, kept twice: the\n * Sandbox asks the address the page was opened at, as there since\n * nxgt-core#171, but here the page resolves the path itself, so a TLS proxy\n * in front changes nothing.\n */\n\nexport interface SandboxOptions {\n\t/** The page's title. `Sandbox Explorer` by default. */\n\treadonly title?: string;\n\t/** The operation the Sandbox opens with. */\n\treadonly initialDocument?: string;\n\t/** Headers every operation sends, shown and editable in the Sandbox. */\n\treadonly initialHeaders?: Readonly<Record<string, string>>;\n\t/** Whether the Sandbox polls the schema as it changes. On by default. */\n\treadonly pollForSchemaUpdates?: boolean;\n\t/** Whether operations send the browser's cookies: a session cookie. On by default. */\n\treadonly includeCookies?: boolean;\n}\n\n/** What the page loads: the Sandbox's script, its frame, and operations to this server. */\nexport const SANDBOX_POLICY = [\n\t\"default-src 'self'\",\n\t\"script-src 'self' 'unsafe-inline' https://embeddable-sandbox.cdn.apollographql.com\",\n\t\"style-src 'self' 'unsafe-inline'\",\n\t'frame-src https://sandbox.embed.apollographql.com',\n\t\"img-src 'self' data: https:\",\n\t\"connect-src 'self'\",\n].join('; ');\n\n/**\n * The page, its endpoint `endpoint`: a URL, or a path the page resolves\n * against its own address. Every value is escaped into its JavaScript and\n * HTML.\n */\nexport function renderSandbox(\n\tendpoint: string,\n\toptions: SandboxOptions = {},\n): string {\n\tconst config = {\n\t\ttarget: '#sandbox',\n\t\tinitialEndpoint: endpoint,\n\t\tinitialState: {\n\t\t\tincludeCookies: options.includeCookies ?? true,\n\t\t\tpollForSchemaUpdates: options.pollForSchemaUpdates ?? true,\n\t\t\t...(options.initialDocument === undefined\n\t\t\t\t? {}\n\t\t\t\t: { document: options.initialDocument }),\n\t\t\t...(options.initialHeaders === undefined\n\t\t\t\t? {}\n\t\t\t\t: { headers: options.initialHeaders }),\n\t\t},\n\t\thideCookieToggle: false,\n\t\tendpointIsEditable: false,\n\t};\n\treturn `<!doctype html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\" />\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n<title>${html(options.title ?? 'Sandbox Explorer')}</title>\n<style>html, body { margin: 0; height: 100%; } #sandbox { position: absolute; inset: 0; }</style>\n</head>\n<body>\n<div id=\"sandbox\"></div>\n<script src=\"https://embeddable-sandbox.cdn.apollographql.com/_latest/embeddable-sandbox.umd.production.min.js\"></script>\n<script>\n{\nconst config = ${script(config)};\nconfig.initialEndpoint = new URL(config.initialEndpoint, location.href).href;\nnew window.EmbeddedSandbox(config);\n}\n</script>\n</body>\n</html>`;\n}\n\nfunction html(text: string): string {\n\treturn text.replace(/[&<>\"']/g, (char) => `&#${char.charCodeAt(0)};`);\n}\n\n/** JSON that cannot close the `<script>` it is written in. */\nfunction script(value: unknown): string {\n\treturn JSON.stringify(value)\n\t\t.replace(/</g, '\\\\u003c')\n\t\t.replace(/>/g, '\\\\u003e')\n\t\t.replace(/\\u2028/g, '\\\\u2028')\n\t\t.replace(/\\u2029/g, '\\\\u2029');\n}\n"
5
+ "import {\n\ttype Alxia,\n\ttype BaseContext,\n\ttype Empty,\n\tisDev,\n\ttype RoutePath,\n} from '@alxia/core';\nimport type {\n\tGraphQLSchemaWithContext,\n\tYogaInitialContext,\n\tYogaServerOptions,\n} from 'graphql-yoga';\nimport { graphqlHandler, type YogaContext, yogaServers } from './handler';\nimport type { SandboxOptions } from './sandbox';\nimport { type GraphQLWsOptions, graphqlSocket } from './ws';\n\n/** The parts of a route's context Yoga owns, or that mean nothing to a resolver. */\ntype RouteOnly =\n\t| 'params'\n\t| 'query'\n\t| 'headers'\n\t| 'cookies'\n\t| 'body'\n\t| 'reply'\n\t| 'redirect';\n\n/**\n * What alxia hands Yoga for each request: the context its middlewares built —\n * `user`, `db`, `log`… — with `request`, `url`, `ip` and `set`, through\n * which a resolver sets a cookie or a header on the response.\n */\nexport type ServerContext<Ctx> = Omit<BaseContext & Ctx, RouteOnly>;\n\n/**\n * What an operation over WebSocket adds to its context (`ws` on): the\n * `connectionParams` the client sent when it connected. `undefined` over\n * HTTP, and for a client that sent none.\n */\nexport interface GraphQLWsContext {\n\treadonly connectionParams?: Readonly<Record<string, unknown>>;\n}\n\n/**\n * What a resolver reads as its context: Yoga's own, the app's, what\n * the `context` option adds, and over WebSocket the `connectionParams`. Type a schema with it:\n *\n * ```ts\n * const base = alxia().use(bearer({ jwt }));\n * const schema = createSchema<GraphQLContext<typeof base>>({ ... });\n * ```\n */\nexport type GraphQLContext<App, UserContext = Empty> = App extends {\n\treadonly '~context': infer Ctx;\n}\n\t? YogaInitialContext & ServerContext<Ctx> & GraphQLWsContext & UserContext\n\t: // Not `never`: a schema typed with `never` would let every resolver\n\t\t// read anything until `graphql()` refused it.\n\t\t{\n\t\t\treadonly '~error': 'GraphQLContext needs the type of an app: GraphQLContext<typeof app>';\n\t\t};\n\nexport interface GraphQLOptions<\n\tServerCtx extends YogaContext,\n\tUserCtx extends YogaContext,\n\tPath extends RoutePath,\n\tSchemaCtx = unknown,\n> extends Omit<\n\t\tYogaServerOptions<ServerCtx, UserCtx>,\n\t\t'graphqlEndpoint' | 'cors' | 'schema' | 'graphiql'\n\t> {\n\t/**\n\t * What a browser gets at the endpoint: Yoga's GraphiQL, Apollo Sandbox,\n\t * or nothing. By default, GraphiQL in the serving app's dev alone\n\t * (`isDev`: `alxia({ dev })`, else `NODE_ENV=development`), nothing\n\t * otherwise; `graphiql` or `apollo-sandbox` serves one everywhere.\n\t */\n\treadonly ide?: 'graphiql' | 'apollo-sandbox' | false;\n\t/** GraphiQL's options, Yoga's own, when `ide` is `graphiql`. */\n\treadonly graphiql?: Exclude<\n\t\tYogaServerOptions<ServerCtx, UserCtx>['graphiql'],\n\t\tboolean\n\t>;\n\t/** Apollo Sandbox's options, when `ide` is `apollo-sandbox`. */\n\treadonly sandbox?: SandboxOptions;\n\t/**\n\t * The schema, from Yoga's `createSchema`, Pothos, or any tool that types\n\t * its context. Its context must be one the app builds: a resolver that\n\t * reads `user` behind no middleware that adds one is a compile error.\n\t */\n\treadonly schema: GraphQLSchemaWithContext<SchemaCtx>;\n\t/** Where the endpoint is, under the app's prefix. `/graphql` by default. */\n\treadonly path?: Path;\n\t/**\n\t * Yoga's own CORS. Off by default: `@alxia/cors` answers for the whole\n\t * app, this endpoint included.\n\t */\n\treadonly cors?: YogaServerOptions<ServerCtx, UserCtx>['cors'];\n\t/**\n\t * GraphQL over WebSocket too, the `graphql-transport-ws` protocol of\n\t * Apollo Client's and urql's default link, served by the optional peer\n\t * `graphql-ws` at the endpoint's path: `true`, or where and how often it\n\t * pings. Off by default: subscriptions are served over server-sent\n\t * events, which stay served beside it.\n\t */\n\treadonly ws?: boolean | GraphQLWsOptions;\n}\n\n/**\n * The check Yoga's types leave out: the context the app builds must hold\n * what the schema's resolvers read. A mistake comes back as a `schema`\n * whose type is the message.\n */\ntype ProvidesContext<Provided, Required> = Provided extends Required\n\t? unknown\n\t: {\n\t\t\treadonly schema: `the schema's resolvers read a context the app does not build: missing ${Exclude<\n\t\t\t\tkeyof Required,\n\t\t\t\tkeyof Provided\n\t\t\t> &\n\t\t\t\tstring}`;\n\t\t};\n\n/**\n * A GraphQL endpoint on `app`, served by [GraphQL Yoga](https://the-guild.dev/graphql/yoga-server):\n * `GET` and `POST` at `path`, behind every middleware given to `use` on `app`\n * before it. A guard before it guards it; what the middlewares added is in each\n * resolver's context, typed. Yoga's options pass through — `plugins`\n * (Envelop's and Yoga's), `graphiql`, `maskedErrors`, `batching`… —\n * and subscriptions are served over server-sent events, and over\n * WebSocket too with `ws: true`.\n *\n * ```ts\n * const app = alxia()\n * .use(bearer({ jwt }))\n * .plugin((app) => graphql(app, { schema, plugins: [useDepthLimit()] }));\n * ```\n */\nexport function graphql<\n\tCtx extends object,\n\tPrefix extends string,\n\tSchemaCtx,\n\tUserCtx extends YogaContext = Empty,\n\tconst Path extends RoutePath = '/graphql',\n>(\n\tapp: Alxia<Ctx, Prefix>,\n\toptions: GraphQLOptions<ServerContext<Ctx>, UserCtx, Path, SchemaCtx> &\n\t\tProvidesContext<\n\t\t\tYogaInitialContext & ServerContext<Ctx> & UserCtx,\n\t\t\tSchemaCtx\n\t\t>,\n): Alxia<Ctx, Prefix> {\n\tconst {\n\t\tpath = '/graphql' as Path,\n\t\tcors = false,\n\t\tide,\n\t\tgraphiql,\n\t\tsandbox,\n\t\tws = false,\n\t\t...yogaOptions\n\t} = options;\n\tconst page = graphiql ?? true;\n\tconst yogaAt = yogaServers<UserCtx>({\n\t\t...(yogaOptions as YogaServerOptions<YogaContext, UserCtx>),\n\t\tcors,\n\t\tgraphiql: (ide === undefined\n\t\t\t? (_request: Request, context: object) => isDev(context) && page\n\t\t\t: ide === 'graphiql'\n\t\t\t\t? page\n\t\t\t\t: false) as YogaServerOptions<YogaContext, UserCtx>['graphiql'],\n\t});\n\tconst handler = graphqlHandler(\n\t\tyogaAt,\n\t\tide === 'apollo-sandbox' ? (sandbox ?? {}) : false,\n\t);\n\n\tconst route = app as unknown as {\n\t\tget(path: string, handler: unknown): unknown;\n\t\tpost(path: string, handler: unknown): unknown;\n\t\tws(path: string, ...rest: unknown[]): unknown;\n\t};\n\troute.get(path, handler);\n\troute.post(path, handler);\n\tif (ws !== false) {\n\t\tconst socket = graphqlSocket(yogaAt, path, ws === true ? {} : ws);\n\t\troute.ws(socket.path, socket.middleware, socket.handlers);\n\t}\n\treturn app as never;\n}\n",
6
+ "/**\n * The endpoint behind `graphql()`: one Yoga per path it is served at, and\n * the route handler that hands each request to it.\n */\nimport { type BaseContext, type StatusCode, shutdownSignal } from '@alxia/core';\nimport {\n\tcreateYoga,\n\ttype YogaServerInstance,\n\ttype YogaServerOptions,\n} from 'graphql-yoga';\nimport { renderSandbox, SANDBOX_POLICY, type SandboxOptions } from './sandbox';\n\nexport type YogaContext = Record<string, any>;\n\n/** Where Yoga's GraphiQL page loads its files from: one pinned version on unpkg. */\nconst GRAPHIQL_FILES =\n\t/https:\\/\\/unpkg\\.com\\/@graphql-yoga\\/graphiql@[\\w.-]+\\//;\n\n/**\n * What GraphiQL's page may load: its scripts, styles and Monaco's\n * workers from the exact version of `@graphql-yoga/graphiql` the page\n * names, fetched and run as blobs; queries to this server alone; framed\n * by no one. A page that names none (a `renderGraphiQL` of the app's own)\n * gets this server alone. `@alxia/secure-headers` keeps a policy a\n * response already has.\n */\nexport function graphiqlPolicy(html: string): string {\n\tconst files = html.match(GRAPHIQL_FILES)?.[0] ?? '';\n\tconst from = files === '' ? '' : ` ${files}`;\n\treturn [\n\t\t\"default-src 'self'\",\n\t\t`script-src 'self' 'unsafe-inline'${from}`,\n\t\t`style-src 'self' 'unsafe-inline'${from}`,\n\t\t\"img-src 'self' data: https:\",\n\t\t`font-src 'self' data:${from}`,\n\t\t\"worker-src 'self' blob:\",\n\t\t`connect-src 'self'${from}`,\n\t\t\"frame-ancestors 'none'\",\n\t].join('; ');\n}\n\n/**\n * The Yoga serving `endpoint`, created on first use. One per path: a plugin\n * mounted under a prefix serves the same routes at a longer path, and\n * GraphiQL must ask that one.\n */\nexport function yogaServers<UserCtx extends YogaContext>(\n\toptions: Omit<YogaServerOptions<YogaContext, UserCtx>, 'graphqlEndpoint'>,\n): (endpoint: string) => YogaServerInstance<YogaContext, UserCtx> {\n\tconst servers = new Map<string, YogaServerInstance<YogaContext, UserCtx>>();\n\treturn (endpoint) => {\n\t\tlet yoga = servers.get(endpoint);\n\t\tif (yoga === undefined) {\n\t\t\tyoga = createYoga<YogaContext, UserCtx>({\n\t\t\t\t...options,\n\t\t\t\tgraphqlEndpoint: endpoint,\n\t\t\t});\n\t\t\tservers.set(endpoint, yoga);\n\t\t}\n\t\treturn yoga;\n\t};\n}\n\n/**\n * What Yoga is handed as its server context: the route's context — the\n * middlewares' work — minus what a resolver has no use for.\n */\nexport function serverContext(\n\tctx: Record<string, unknown>,\n): Record<string, unknown> {\n\tconst {\n\t\tparams: _params,\n\t\tquery: _query,\n\t\theaders: _headers,\n\t\tcookies: _cookies,\n\t\tbody: _body,\n\t\treply: _reply,\n\t\tredirect: _redirect,\n\t\t...server\n\t} = ctx;\n\treturn server;\n}\n\n/**\n * The handler of the endpoint's `GET` and `POST`: Apollo Sandbox's page to\n * a browser when `sandbox` is not `false`, else the request to Yoga, with\n * the route's context — the middlewares' work, minus what a resolver has no use\n * for — as Yoga's server context.\n */\nexport function graphqlHandler<UserCtx extends YogaContext>(\n\tyogaAt: (endpoint: string) => YogaServerInstance<YogaContext, UserCtx>,\n\tsandbox: SandboxOptions | false,\n) {\n\t// A handler's context: its route is the one it was declared at. Named\n\t// `graphql`, the name the route table `listen` prints in dev shows.\n\treturn async function graphql(\n\t\tctx: Record<string, unknown> & BaseContext & { readonly route: string },\n\t) {\n\t\tconst { reply } = ctx;\n\t\tconst server = serverContext(ctx);\n\t\tif (\n\t\t\tsandbox !== false &&\n\t\t\tctx.request.method === 'GET' &&\n\t\t\tctx.request.headers.get('accept')?.includes('text/html') &&\n\t\t\t!ctx.url.searchParams.has('query')\n\t\t) {\n\t\t\t// A path: the page resolves it against its own address, so behind\n\t\t\t// a TLS proxy the Sandbox asks over https, as the browser did.\n\t\t\treturn reply(200, renderSandbox(ctx.route, sandbox), {\n\t\t\t\theaders: {\n\t\t\t\t\t'content-type': 'text/html;charset=utf-8',\n\t\t\t\t\t'content-security-policy': SANDBOX_POLICY,\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\t\tconst response = await yogaAt(ctx.route).fetch(ctx.request, server);\n\t\tconst headers = new Headers(response.headers);\n\t\tif (\n\t\t\theaders.get('content-type')?.startsWith('text/html') &&\n\t\t\t!headers.has('content-security-policy')\n\t\t) {\n\t\t\t// GraphiQL's page: its policy names the files it loads.\n\t\t\tconst html = await response.text();\n\t\t\theaders.set('content-security-policy', graphiqlPolicy(html));\n\t\t\treturn reply(response.status as StatusCode, html, { headers });\n\t\t}\n\t\tconst body = endedOnShutdown(response, shutdownSignal(ctx));\n\t\treturn reply(response.status as StatusCode, body ?? undefined, {\n\t\t\theaders,\n\t\t});\n\t};\n}\n\n/**\n * A subscription's or an incremental delivery's body, which streams until\n * its reader stops: ended when the app starts shutting down — Yoga's\n * stream cancelled, as when the client leaves, and the client reading its\n * end — so the drain does not wait for it. Any other body finishes within\n * the drain as it is.\n */\nfunction endedOnShutdown(\n\tresponse: Response,\n\tsignal: AbortSignal,\n): ReadableStream<Uint8Array> | null {\n\tconst body = response.body;\n\tconst type = response.headers.get('content-type') ?? '';\n\tif (body === null || !/text\\/event-stream|multipart\\/mixed/.test(type)) {\n\t\treturn body;\n\t}\n\tconst reader = body.getReader();\n\treturn new ReadableStream<Uint8Array>({\n\t\tstart(controller) {\n\t\t\tconst end = () => {\n\t\t\t\tvoid reader.cancel();\n\t\t\t\ttry {\n\t\t\t\t\tcontroller.close();\n\t\t\t\t} catch {\n\t\t\t\t\t// Closed already: the stream had ended.\n\t\t\t\t}\n\t\t\t};\n\t\t\tif (signal.aborted) end();\n\t\t\telse signal.addEventListener('abort', end, { once: true });\n\t\t},\n\t\tasync pull(controller) {\n\t\t\tconst { value, done } = await reader.read();\n\t\t\tif (done) {\n\t\t\t\ttry {\n\t\t\t\t\tcontroller.close();\n\t\t\t\t} catch {\n\t\t\t\t\t// Closed already: the shutdown ended it.\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcontroller.enqueue(value);\n\t\t},\n\t\tcancel: (reason) => reader.cancel(reason),\n\t});\n}\n",
7
+ "/**\n * [Apollo Sandbox](https://www.apollographql.com/docs/graphos/platform/sandbox),\n * embedded: the page a browser gets at the endpoint when the IDE is\n * `apollo-sandbox`. `@nxgt/shared-graphql`'s `renderSandbox`, kept twice: the\n * Sandbox asks the address the page was opened at, as there since\n * nxgt-core#171, but here the page resolves the path itself, so a TLS proxy\n * in front changes nothing.\n */\n\nexport interface SandboxOptions {\n\t/** The page's title. `Sandbox Explorer` by default. */\n\treadonly title?: string;\n\t/** The operation the Sandbox opens with. */\n\treadonly initialDocument?: string;\n\t/** Headers every operation sends, shown and editable in the Sandbox. */\n\treadonly initialHeaders?: Readonly<Record<string, string>>;\n\t/** Whether the Sandbox polls the schema as it changes. On by default. */\n\treadonly pollForSchemaUpdates?: boolean;\n\t/** Whether operations send the browser's cookies: a session cookie. On by default. */\n\treadonly includeCookies?: boolean;\n}\n\n/** What the page loads: the Sandbox's script, its frame, and operations to this server. */\nexport const SANDBOX_POLICY = [\n\t\"default-src 'self'\",\n\t\"script-src 'self' 'unsafe-inline' https://embeddable-sandbox.cdn.apollographql.com\",\n\t\"style-src 'self' 'unsafe-inline'\",\n\t'frame-src https://sandbox.embed.apollographql.com',\n\t\"img-src 'self' data: https:\",\n\t\"connect-src 'self'\",\n].join('; ');\n\n/**\n * The page, its endpoint `endpoint`: a URL, or a path the page resolves\n * against its own address. Every value is escaped into its JavaScript and\n * HTML.\n */\nexport function renderSandbox(\n\tendpoint: string,\n\toptions: SandboxOptions = {},\n): string {\n\tconst config = {\n\t\ttarget: '#sandbox',\n\t\tinitialEndpoint: endpoint,\n\t\tinitialState: {\n\t\t\tincludeCookies: options.includeCookies ?? true,\n\t\t\tpollForSchemaUpdates: options.pollForSchemaUpdates ?? true,\n\t\t\t...(options.initialDocument === undefined\n\t\t\t\t? {}\n\t\t\t\t: { document: options.initialDocument }),\n\t\t\t...(options.initialHeaders === undefined\n\t\t\t\t? {}\n\t\t\t\t: { headers: options.initialHeaders }),\n\t\t},\n\t\thideCookieToggle: false,\n\t\tendpointIsEditable: false,\n\t};\n\treturn `<!doctype html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\" />\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n<title>${html(options.title ?? 'Sandbox Explorer')}</title>\n<style>html, body { margin: 0; height: 100%; } #sandbox { position: absolute; inset: 0; }</style>\n</head>\n<body>\n<div id=\"sandbox\"></div>\n<script src=\"https://embeddable-sandbox.cdn.apollographql.com/_latest/embeddable-sandbox.umd.production.min.js\"></script>\n<script>\n{\nconst config = ${script(config)};\nconfig.initialEndpoint = new URL(config.initialEndpoint, location.href).href;\nnew window.EmbeddedSandbox(config);\n}\n</script>\n</body>\n</html>`;\n}\n\nfunction html(text: string): string {\n\treturn text.replace(/[&<>\"']/g, (char) => `&#${char.charCodeAt(0)};`);\n}\n\n/** JSON that cannot close the `<script>` it is written in. */\nfunction script(value: unknown): string {\n\treturn JSON.stringify(value)\n\t\t.replace(/</g, '\\\\u003c')\n\t\t.replace(/>/g, '\\\\u003e')\n\t\t.replace(/\\u2028/g, '\\\\u2028')\n\t\t.replace(/\\u2029/g, '\\\\u2029');\n}\n",
8
+ "/**\n * GraphQL over WebSocket, the `graphql-transport-ws` protocol of\n * `graphql-ws`, on a socket route of the app: the upgrade runs the app's\n * middlewares, each operation runs through Yoga's envelop — its plugins,\n * its `context` — and the app's shutdown closes the sockets with 1001.\n */\nimport type { BaseContext, NextFunction, RoutePath, Socket } from '@alxia/core';\nimport type { Server, ServerOptions, SubscribePayload } from 'graphql-ws';\nimport type { YogaInitialContext, YogaServerInstance } from 'graphql-yoga';\nimport { serverContext, type YogaContext } from './handler';\n\n/** `graphql(app, { ws })`: GraphQL over WebSocket beside the HTTP endpoint. */\nexport interface GraphQLWsOptions {\n\t/**\n\t * Where a client opens its socket, under the app's prefix. The\n\t * endpoint's own path by default: one URL, `http(s)://` for queries and\n\t * server-sent events, `ws(s)://` for the socket.\n\t */\n\treadonly path?: RoutePath;\n\t/**\n\t * Milliseconds between the WebSocket pings the server sends each open\n\t * socket, so a proxy does not close an idle subscription. `12_000` by\n\t * default, as `graphql-ws`'s own server for Node; `false` for none.\n\t */\n\treadonly keepAlive?: number | false;\n}\n\n/**\n * What `graphql-ws` keeps of each socket: the context its upgrade built,\n * and the request each of its operations reads as Yoga's `request`.\n */\ninterface Extra {\n\treadonly ctx: Record<string, unknown> & BaseContext;\n\treadonly request: Request;\n}\n\ntype Module = typeof import('graphql-ws');\n\n/** What the missing optional peer is answered with: the package to add. */\nexport const MISSING_PEER =\n\t'@alxia/graphql: graphql(app, { ws }) serves GraphQL over WebSocket with the optional peer graphql-ws, which is not installed: bun add graphql-ws';\n\n/** `graphql-ws`, imported once; a missing peer rejects with `MISSING_PEER`. */\nfunction loader(): () => Promise<Module> {\n\tlet loading: Promise<Module> | undefined;\n\treturn () => {\n\t\tloading ??= import('graphql-ws').catch((cause: unknown) => {\n\t\t\tthrow new Error(MISSING_PEER, { cause });\n\t\t});\n\t\treturn loading;\n\t};\n}\n\n/** The rest of each operation, run by the functions Yoga's envelop gave it. */\ninterface Enveloped {\n\treadonly execute: (args: never) => unknown;\n\treadonly subscribe: (args: never) => unknown;\n}\n\n/** Where the socket route is, and the endpoint whose Yoga it runs. */\ninterface Paths {\n\treadonly endpoint: string;\n\treadonly socket: string;\n}\n\n/**\n * The Yoga of the endpoint a socket route serves: the HTTP one, so its\n * plugins are set up once. The socket's route is its full path, the\n * prefix of each app it is mounted into included, then its own `path`.\n */\nfunction endpointOf(route: string, paths: Paths): string {\n\t// A path of `/` adds nothing to a prefix: `/api` + `/` is `/api`.\n\tconst own = paths.socket === '/' ? '' : paths.socket;\n\tconst at = paths.endpoint === '/' ? '' : paths.endpoint;\n\treturn route.slice(0, route.length - own.length) + at || '/';\n}\n\n/**\n * `graphql-ws`'s options: each operation parsed, validated, executed and\n * subscribed through Yoga's envelop, with the context the upgrade built,\n * the operation's `params` and the client's `connectionParams`.\n */\nfunction serverOptions<UserCtx extends YogaContext>(\n\tyogaAt: (endpoint: string) => YogaServerInstance<YogaContext, UserCtx>,\n\tpaths: Paths,\n): ServerOptions<Record<string, unknown> | undefined, Extra> {\n\t// Each operation's envelop, found by its context: one object per\n\t// operation, which the root resolvers' `parent` is not.\n\tconst enveloped = new WeakMap<object, Enveloped>();\n\tconst of = (args: { contextValue?: unknown }) =>\n\t\tenveloped.get(args.contextValue as object) as Enveloped;\n\treturn {\n\t\texecute: (args) => of(args).execute(args as never) as never,\n\t\tsubscribe: (args) => of(args).subscribe(args as never) as never,\n\t\tasync onSubscribe(context, _id, params: SubscribePayload) {\n\t\t\tconst { ctx, request } = context.extra;\n\t\t\tconst initial = {\n\t\t\t\t...serverContext(ctx),\n\t\t\t\trequest,\n\t\t\t\tparams,\n\t\t\t\tconnectionParams: context.connectionParams,\n\t\t\t} as unknown as YogaInitialContext & YogaContext;\n\t\t\tconst { schema, execute, subscribe, contextFactory, parse, validate } =\n\t\t\t\tyogaAt(endpointOf(ctx.route as string, paths)).getEnveloped(initial);\n\t\t\tlet document: ReturnType<typeof parse>;\n\t\t\ttry {\n\t\t\t\tdocument = parse(params.query);\n\t\t\t} catch (error) {\n\t\t\t\treturn [error as never];\n\t\t\t}\n\t\t\tconst errors = validate(schema, document);\n\t\t\tif (errors.length > 0) return errors;\n\t\t\tconst contextValue = await contextFactory();\n\t\t\tenveloped.set(contextValue, { execute, subscribe });\n\t\t\treturn {\n\t\t\t\tschema,\n\t\t\t\tdocument,\n\t\t\t\toperationName: params.operationName,\n\t\t\t\tvariableValues: params.variables,\n\t\t\t\tcontextValue,\n\t\t\t};\n\t\t},\n\t};\n}\n\n/** The subprotocol the upgrade request offers that `graphql-ws` serves, or `''`. */\nfunction chosen(module: Module, request: Request): string {\n\tconst offered = request.headers.get('sec-websocket-protocol') ?? '';\n\treturn module.handleProtocols(offered) || '';\n}\n\n/**\n * The request an operation over the socket reads: the upgrade's URL and\n * headers, as a `POST`, which it is to Yoga — a `GET` may not run a\n * mutation, and the upgrade is one — its signal aborted when the socket\n * closes.\n */\nfunction operationRequest(upgrade: Request, signal: AbortSignal): Request {\n\treturn new Request(upgrade.url, {\n\t\tmethod: 'POST',\n\t\theaders: upgrade.headers,\n\t\tsignal,\n\t});\n}\n\n/** `keepAlive` checked where `graphql()` is declared: a positive number of milliseconds, or `false`. */\nfunction pingEvery(keepAlive: number | false | undefined): number | false {\n\tif (keepAlive === undefined) return 12_000;\n\tif (keepAlive === false) return false;\n\tif (Number.isFinite(keepAlive) && keepAlive > 0) return keepAlive;\n\tthrow new TypeError(\n\t\t`graphql(app, { ws: { keepAlive: ${keepAlive} } }): keepAlive is the milliseconds between pings, a positive number, or false for none`,\n\t);\n}\n\n/** What one socket holds: the message handler `graphql-ws` registered, its end, its pings. */\ninterface Client {\n\tonMessage?: (data: string) => Promise<void>;\n\tclosed?: (code?: number, reason?: string) => Promise<void>;\n\tpings?: ReturnType<typeof setInterval>;\n\treadonly gone: AbortController;\n}\n\n/**\n * The socket route's middleware and handlers: the upgrade loads\n * `graphql-ws` and names the subprotocol it serves in the `101`; each\n * open socket is a `graphql-ws` client, ended when it closes.\n */\nexport function graphqlSocket<UserCtx extends YogaContext>(\n\tyogaAt: (endpoint: string) => YogaServerInstance<YogaContext, UserCtx>,\n\tendpoint: string,\n\toptions: GraphQLWsOptions,\n) {\n\tconst paths: Paths = { endpoint, socket: options.path ?? endpoint };\n\tconst keepAlive = pingEvery(options.keepAlive);\n\tconst load = loader();\n\tlet module: Module | undefined;\n\tlet server: Server<Extra> | undefined;\n\tconst clients = new WeakMap<object, Client>();\n\n\t// Named `graphqlWs`, the name the route table shows.\n\tasync function graphqlWs(ctx: BaseContext, next: NextFunction) {\n\t\tmodule ??= await load();\n\t\tserver ??= module.makeServer(serverOptions(yogaAt, paths));\n\t\tconst protocol = chosen(module, ctx.request);\n\t\tif (protocol !== '')\n\t\t\tctx.set.headers.set('sec-websocket-protocol', protocol);\n\t\treturn next();\n\t}\n\n\ttype GraphQLSocket = Socket<Record<string, unknown> & BaseContext, unknown>;\n\tconst handlers = {\n\t\topen(socket: GraphQLSocket) {\n\t\t\tconst raw = socket.raw;\n\t\t\tconst client: Client = { gone: new AbortController() };\n\t\t\tclients.set(raw, client);\n\t\t\t// The upgrade loaded both: a socket opens behind its middleware alone.\n\t\t\tconst graphqlWsServer = server as NonNullable<typeof server>;\n\t\t\tclient.closed = graphqlWsServer.opened(\n\t\t\t\t{\n\t\t\t\t\t// Anything else is closed by graphql-ws: 4406, Subprotocol not acceptable.\n\t\t\t\t\tprotocol: chosen(module as Module, socket.data.request),\n\t\t\t\t\tsend: (data: string) => {\n\t\t\t\t\t\tif (raw.readyState === 1) raw.sendText(data);\n\t\t\t\t\t},\n\t\t\t\t\tclose: (code?: number, reason?: string) => raw.close(code, reason),\n\t\t\t\t\tonMessage: (handle: (data: string) => Promise<void>) => {\n\t\t\t\t\t\tclient.onMessage = handle;\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tctx: socket.data,\n\t\t\t\t\trequest: operationRequest(socket.data.request, client.gone.signal),\n\t\t\t\t},\n\t\t\t);\n\t\t\tif (keepAlive !== false) {\n\t\t\t\tclient.pings = setInterval(() => raw.ping(), keepAlive);\n\t\t\t}\n\t\t},\n\t\tasync message(socket: GraphQLSocket, message: unknown) {\n\t\t\tconst data =\n\t\t\t\ttypeof message === 'string'\n\t\t\t\t\t? message\n\t\t\t\t\t: new TextDecoder().decode(message as Uint8Array);\n\t\t\tawait clients.get(socket.raw)?.onMessage?.(data);\n\t\t},\n\t\tasync close(socket: GraphQLSocket, code: number, reason: string) {\n\t\t\tconst client = clients.get(socket.raw);\n\t\t\tif (client === undefined) return;\n\t\t\tclearInterval(client.pings);\n\t\t\tclients.delete(socket.raw);\n\t\t\tclient.gone.abort();\n\t\t\tawait client.closed?.(code, reason);\n\t\t},\n\t};\n\treturn { path: paths.socket, middleware: graphqlWs, handlers };\n}\n"
8
9
  ],
9
- "mappings": ";AAAA;AAAA;AAAA;;;ACIA;AACA;AAAA;AAAA;;;ACkBO,IAAM,iBAAiB;AAAA,EAC7B;AAAA,EACA;AAAA,EACA;AAAA,EACA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AAI,EAAE;AAAA,IAChE,MAAM,GAAG,OAAO,MAAM,OAAO,YAAY,OAAO,QAAQ;AAAA,EACzD;AAAA,EACA,OAAO;AAAA;",
11
+ "debugId": "E799A72AD243BAC264756E2164756E21",
11
12
  "names": []
12
13
  }
package/dist/ws.d.ts ADDED
@@ -0,0 +1,41 @@
1
+ /**
2
+ * GraphQL over WebSocket, the `graphql-transport-ws` protocol of
3
+ * `graphql-ws`, on a socket route of the app: the upgrade runs the app's
4
+ * middlewares, each operation runs through Yoga's envelop — its plugins,
5
+ * its `context` — and the app's shutdown closes the sockets with 1001.
6
+ */
7
+ import type { BaseContext, NextFunction, RoutePath, Socket } from '@alxia/core';
8
+ import type { YogaServerInstance } from 'graphql-yoga';
9
+ import { type YogaContext } from './handler';
10
+ /** `graphql(app, { ws })`: GraphQL over WebSocket beside the HTTP endpoint. */
11
+ export interface GraphQLWsOptions {
12
+ /**
13
+ * Where a client opens its socket, under the app's prefix. The
14
+ * endpoint's own path by default: one URL, `http(s)://` for queries and
15
+ * server-sent events, `ws(s)://` for the socket.
16
+ */
17
+ readonly path?: RoutePath;
18
+ /**
19
+ * Milliseconds between the WebSocket pings the server sends each open
20
+ * socket, so a proxy does not close an idle subscription. `12_000` by
21
+ * default, as `graphql-ws`'s own server for Node; `false` for none.
22
+ */
23
+ readonly keepAlive?: number | false;
24
+ }
25
+ /** What the missing optional peer is answered with: the package to add. */
26
+ export declare const MISSING_PEER = "@alxia/graphql: graphql(app, { ws }) serves GraphQL over WebSocket with the optional peer graphql-ws, which is not installed: bun add graphql-ws";
27
+ /**
28
+ * The socket route's middleware and handlers: the upgrade loads
29
+ * `graphql-ws` and names the subprotocol it serves in the `101`; each
30
+ * open socket is a `graphql-ws` client, ended when it closes.
31
+ */
32
+ export declare function graphqlSocket<UserCtx extends YogaContext>(yogaAt: (endpoint: string) => YogaServerInstance<YogaContext, UserCtx>, endpoint: string, options: GraphQLWsOptions): {
33
+ path: string;
34
+ middleware: (ctx: BaseContext, next: NextFunction) => Promise<import("@alxia/core").Next<import("@alxia/core").Empty, import("@alxia/core").Empty>>;
35
+ handlers: {
36
+ open(socket: Socket<Record<string, unknown> & BaseContext, unknown>): void;
37
+ message(socket: Socket<Record<string, unknown> & BaseContext, unknown>, message: unknown): Promise<void>;
38
+ close(socket: Socket<Record<string, unknown> & BaseContext, unknown>, code: number, reason: string): Promise<void>;
39
+ };
40
+ };
41
+ //# sourceMappingURL=ws.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ws.d.ts","sourceRoot":"","sources":["../src/ws.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,KAAK,EAAE,WAAW,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAEhF,OAAO,KAAK,EAAsB,kBAAkB,EAAE,MAAM,cAAc,CAAC;AAC3E,OAAO,EAAiB,KAAK,WAAW,EAAE,MAAM,WAAW,CAAC;AAE5D,+EAA+E;AAC/E,MAAM,WAAW,gBAAgB;IAChC;;;;OAIG;IACH,QAAQ,CAAC,IAAI,CAAC,EAAE,SAAS,CAAC;IAC1B;;;;OAIG;IACH,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,GAAG,KAAK,CAAC;CACpC;AAaD,2EAA2E;AAC3E,eAAO,MAAM,YAAY,qJAC0H,CAAC;AA2HpJ;;;;GAIG;AACH,wBAAgB,aAAa,CAAC,OAAO,SAAS,WAAW,EACxD,MAAM,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,kBAAkB,CAAC,WAAW,EAAE,OAAO,CAAC,EACtE,QAAQ,EAAE,MAAM,EAChB,OAAO,EAAE,gBAAgB;;sBAUK,WAAW,QAAQ,YAAY;;;yFAsCd,OAAO;oFAOZ,MAAM,UAAU,MAAM;;EAUhE"}
package/docs/README.md CHANGED
@@ -11,6 +11,7 @@ a realistic example for each.
11
11
  | [Mounting the endpoint](guide/endpoint.md) | adding GraphQL to an app, choosing its path under a prefix, putting it behind a guard, reading what it answers, telling GraphQL errors from the problem details of the HTTP layer around it, adding `health()` probes and draining it on `SIGTERM`, or testing it without a server |
12
12
  | [The typed context](guide/context.md) | typing a schema with the app's context, reading `user` or a database handle in a resolver, setting a cookie, adding per-request loaders, or reading the `missing …` compile error |
13
13
  | [Yoga's plugins and options](guide/yoga.md) | adding Yoga or Envelop plugins, exposing or masking errors, batching, serving subscriptions, or calling the endpoint from another origin |
14
+ | [GraphQL over WebSocket](guide/websockets.md) | serving Apollo Client's, urql's or `graphql-ws`'s WebSocket clients with `ws: true`, guarding the upgrade, reading `connectionParams`, the subprotocol, closing the sockets on shutdown, or testing a subscription over a socket |
14
15
  | [GraphiQL and Apollo Sandbox](guide/ide.md) | choosing the IDE a browser gets, configuring it, keeping it working under a strict `Content-Security-Policy`, or serving it outside dev with `ide: 'graphiql'` |
15
16
  | [Troubleshooting](troubleshooting.md) | something went wrong and you have the message |
16
17
  | [Roadmap](roadmap.md) | wondering what is coming, and what is not planned |
@@ -226,6 +226,10 @@ of one tick and calls your batch function once. Build the loaders in the
226
226
  `context` option, so each request has its own, and type them through
227
227
  `GraphQLContext`'s second argument, so every resolver reads `loaders` typed:
228
228
 
229
+ ```sh
230
+ bun add dataloader
231
+ ```
232
+
229
233
  ```ts
230
234
  import DataLoader from 'dataloader';
231
235
 
@@ -51,9 +51,10 @@ routes on `base` and returns it.
51
51
  | --- | --- | --- | --- |
52
52
  | `schema` | `GraphQLSchemaWithContext<SchemaCtx>` | — | The schema, from Yoga's `createSchema` or any tool that types its context. Its context is checked against the app's: see [The typed context](context.md). |
53
53
  | `path` | `` `/${string}` `` | `'/graphql'` | Where the endpoint is, under the app's prefix. |
54
- | `ide` | `'graphiql' \| 'apollo-sandbox' \| false` | `'graphiql'` | What a browser gets at the endpoint: see [GraphiQL and Apollo Sandbox](ide.md). |
54
+ | `ide` | `'graphiql' \| 'apollo-sandbox' \| false` | GraphiQL in dev (`isDev`), none otherwise | What a browser gets at the endpoint: see [GraphiQL and Apollo Sandbox](ide.md). |
55
55
  | `graphiql` | Yoga's `GraphiQLOptions` | Yoga's | GraphiQL's options, when `ide` is `'graphiql'`. |
56
56
  | `sandbox` | `SandboxOptions` | — | Apollo Sandbox's options, when `ide` is `'apollo-sandbox'`. |
57
+ | `ws` | `boolean \| { path?, keepAlive? }` | `false` | GraphQL over WebSocket too, with the optional peer `graphql-ws`: see [GraphQL over WebSocket](websockets.md). |
57
58
  | `cors` | Yoga's `cors` | `false` | Yoga's own CORS. Off: use `@alxia/cors` for the whole app instead ([Yoga's plugins and options](yoga.md#cors)). |
58
59
  | every other Yoga option | | Yoga's | `plugins`, `context`, `maskedErrors`, `batching`, `logging`… passed to `createYoga` as they are: see [Yoga's plugins and options](yoga.md). |
59
60
 
@@ -143,6 +144,7 @@ IDE page ([GraphiQL and Apollo Sandbox](ide.md)).
143
144
  | `POST` with `{"query": …}` | `200` and `{"data": …}`, with `errors` beside it when a resolver failed |
144
145
  | `GET ?query=…` | the same, for a query; a mutation is a `405` |
145
146
  | `POST` a subscription with `Accept: text/event-stream` | `200`, a `text/event-stream` of results ([subscriptions](yoga.md#subscriptions)) |
147
+ | a WebSocket upgrade offering `graphql-transport-ws`, `ws` on | `101`, then queries, mutations and subscriptions over the socket ([GraphQL over WebSocket](websockets.md)); with `ws` off, no `101` |
146
148
  | `GET` from a browser (`Accept: text/html`), no `query` | the IDE page; with `ide: false`, a GraphQL answer (`Must provide query string.`) |
147
149
  | a middleware replied first | that middleware's reply, such as a `401` |
148
150
 
@@ -232,3 +234,5 @@ describe('graphql', () => {
232
234
  - [Yoga's plugins and options](yoga.md): plugins, errors, subscriptions,
233
235
  CORS.
234
236
  - [GraphiQL and Apollo Sandbox](ide.md): the page a browser gets.
237
+ - [GraphQL over WebSocket](websockets.md): `ws`, for `graphql-ws`
238
+ clients.
@@ -0,0 +1,257 @@
1
+ # GraphQL over WebSocket
2
+
3
+ This page covers `ws`: serving the endpoint over WebSocket too, with the
4
+ [`graphql-transport-ws`](https://github.com/enisdenjo/graphql-ws/blob/master/PROTOCOL.md)
5
+ protocol of [`graphql-ws`](https://the-guild.dev/graphql/ws) — the default
6
+ of Apollo Client's `GraphQLWsLink` and urql's `subscriptionExchange` — beside
7
+ the HTTP endpoint and its server-sent events.
8
+
9
+ ```sh
10
+ bun add graphql-ws
11
+ ```
12
+
13
+ ```ts
14
+ import { alxia } from '@alxia/core';
15
+ import { graphql } from '@alxia/graphql';
16
+ import { createSchema } from 'graphql-yoga';
17
+
18
+ const schema = createSchema({
19
+ typeDefs: /* GraphQL */ `
20
+ type Query { hello: String! }
21
+ type Subscription { countdown(from: Int!): Int! }
22
+ `,
23
+ resolvers: {
24
+ Query: { hello: () => 'world' },
25
+ Subscription: {
26
+ countdown: {
27
+ async *subscribe(_, { from }: { from: number }) {
28
+ for (let n = from; n >= 0; n--) yield { countdown: n };
29
+ },
30
+ },
31
+ },
32
+ },
33
+ });
34
+
35
+ const app = alxia().plugin((app) => graphql(app, { schema, ws: true }));
36
+ app.listen(3000); // http://localhost:3000/graphql and ws://localhost:3000/graphql
37
+ ```
38
+
39
+ `graphql-ws` is an optional peer: an app that leaves `ws` off never loads
40
+ it. Server-sent events stay served at the same path either way, so a client
41
+ of each kind works against one deployment.
42
+
43
+ ## `ws`
44
+
45
+ | `ws` | |
46
+ | --- | --- |
47
+ | `false`, or none (default) | subscriptions over server-sent events alone: a WebSocket client gets no `101` |
48
+ | `true` | a socket route at the endpoint's `path`, under the app's prefix |
49
+ | `{ path?, keepAlive? }` | the same, with these options |
50
+
51
+ | Option | Type | Default | Effect |
52
+ | --- | --- | --- | --- |
53
+ | `path` | `` `/${string}` `` | the endpoint's `path` | where a client opens its socket, under the app's prefix |
54
+ | `keepAlive` | `number \| false` | `12_000` | milliseconds between the WebSocket pings the server sends each socket, so a proxy does not close an idle subscription; `false` for none. Anything but a finite positive number throws where `graphql()` is declared |
55
+
56
+ ```ts no-check
57
+ graphql(app, { schema, ws: { path: '/graphql/ws', keepAlive: 30_000 } });
58
+ ```
59
+
60
+ A socket at a path of its own runs the endpoint's Yoga: its plugins are
61
+ set up once, for both. Queries, mutations and subscriptions all run over a
62
+ socket. The socket
63
+ route shows in the route table `listen` prints in dev, as `WS /graphql`.
64
+
65
+ ## The upgrade runs the app's middlewares
66
+
67
+ The socket is a route of `@alxia/core` ([WebSockets](../../../core/docs/guide/websockets.md)):
68
+ the upgrade request runs every middleware given to `use` before
69
+ `graphql()`, every `derive` and `decorate`, then opens. A guard refuses the
70
+ socket with its own answer — a `401` — and the client never connects; what
71
+ the middlewares add is in every resolver's context, typed as over HTTP:
72
+
73
+ ```ts
74
+ import { alxia, defineMiddleware } from '@alxia/core';
75
+ import { type GraphQLContext, graphql } from '@alxia/graphql';
76
+ import { createSchema } from 'graphql-yoga';
77
+
78
+ // A browser cannot set a header on a WebSocket: the token comes in the URL
79
+ // or a cookie there. A server-side client can send `authorization`.
80
+ const viewer = defineMiddleware(({ url, reply }, next) => {
81
+ const token = url.searchParams.get('token');
82
+ return token === null ? reply(401, { error: 'unauthorized' as const }) : next({ viewer: token });
83
+ });
84
+
85
+ const base = alxia().use(viewer);
86
+
87
+ const schema = createSchema<GraphQLContext<typeof base>>({
88
+ typeDefs: /* GraphQL */ `
89
+ type Query { me: String! }
90
+ type Subscription { countdown(from: Int!): Int! }
91
+ `,
92
+ resolvers: {
93
+ Query: { me: (_, __, { viewer }) => viewer }, // over HTTP and over the socket
94
+ Subscription: {
95
+ countdown: {
96
+ async *subscribe(_, { from }: { from: number }) {
97
+ for (let n = from; n >= 0; n--) yield { countdown: n };
98
+ },
99
+ },
100
+ },
101
+ },
102
+ });
103
+
104
+ export const app = base.plugin((app) => graphql(app, { schema, ws: true }));
105
+ ```
106
+
107
+ The upgrade names `graphql-transport-ws` in its `101` when the client
108
+ offers it; a client that offers only another subprotocol is closed with
109
+ `4406 Subprotocol not acceptable` ([Troubleshooting](../troubleshooting.md#4406-subprotocol-not-acceptable)).
110
+
111
+ ## The context of an operation over the socket
112
+
113
+ Each operation runs through Yoga's envelop, as over HTTP: its plugins
114
+ apply — Envelop's and Yoga's, masked errors, depth limits — and its
115
+ `context` option is called. The context holds:
116
+
117
+ - what the upgrade's middlewares added, `set` and `ip` included;
118
+ - `params`: the operation's `query`, `variables`, `operationName`;
119
+ - `request`: the upgrade's URL and headers, as a `POST` — to Yoga an
120
+ operation over the socket is one, so a mutation runs — its `signal`
121
+ aborted when the socket closes;
122
+ - `connectionParams`: what the client sent when it connected
123
+ (`connectionParams` of `createClient`), `undefined` over HTTP.
124
+
125
+ ```ts
126
+ import type { GraphQLContext } from '@alxia/graphql';
127
+ import { createSchema } from 'graphql-yoga';
128
+ import type { app } from './app';
129
+
130
+ const schema = createSchema<GraphQLContext<typeof app>>({
131
+ typeDefs: /* GraphQL */ 'type Query { device: String }',
132
+ resolvers: {
133
+ Query: {
134
+ device: (_, __, { connectionParams }) => String(connectionParams?.['device'] ?? 'unknown'),
135
+ },
136
+ },
137
+ });
138
+ ```
139
+
140
+ `connectionParams` is `Readonly<Record<string, unknown>>`: parse it
141
+ before you trust it. A header the upgrade's middlewares set with
142
+ `set.headers` is sent with the `101`; set during an operation, it goes
143
+ nowhere.
144
+
145
+ ## Errors
146
+
147
+ An error stays GraphQL's. A resolver's arrives in a `next` message with
148
+ `errors[]` — masked to `Unexpected error.` unless `maskedErrors` says
149
+ otherwise — and the subscription goes on or completes as over HTTP. A
150
+ query that does not parse or validate is answered with an `error`
151
+ message, the protocol's, and the socket stays open.
152
+
153
+ ## Shutdown
154
+
155
+ On `SIGTERM`, `SIGINT` or `stop()`, `/ready` turns 503 and every socket is
156
+ closed with `1001 going away`: each subscription on it completes, its
157
+ resolver's iterator returned, so the drain does not wait for it. A
158
+ `graphql-ws` client retries on `1001`, by default, and reaches another
159
+ instance.
160
+
161
+ ## Clients
162
+
163
+ `graphql-ws`'s own client, in Bun or a browser:
164
+
165
+ ```ts no-check
166
+ import { createClient } from 'graphql-ws';
167
+
168
+ const client = createClient({
169
+ url: 'wss://api.example.com/graphql?token=…',
170
+ connectionParams: { device: 'web' },
171
+ });
172
+
173
+ for await (const result of client.iterate({ query: 'subscription { countdown(from: 3) }' })) {
174
+ console.log(result); // { data: { countdown: 3 } }, …
175
+ }
176
+ ```
177
+
178
+ Apollo Client: subscriptions over the socket, the rest over HTTP.
179
+
180
+ ```ts no-check
181
+ import { ApolloClient, ApolloLink, HttpLink, InMemoryCache } from '@apollo/client';
182
+ import { GraphQLWsLink } from '@apollo/client/link/subscriptions';
183
+ import { getMainDefinition } from '@apollo/client/utilities';
184
+ import { createClient } from 'graphql-ws';
185
+
186
+ const ws = new GraphQLWsLink(createClient({ url: 'wss://api.example.com/graphql' }));
187
+ const http = new HttpLink({ uri: 'https://api.example.com/graphql' });
188
+
189
+ const client = new ApolloClient({
190
+ cache: new InMemoryCache(),
191
+ link: ApolloLink.split(({ query }) => {
192
+ const definition = getMainDefinition(query);
193
+ return definition.kind === 'OperationDefinition' && definition.operation === 'subscription';
194
+ }, ws, http),
195
+ });
196
+ ```
197
+
198
+ urql:
199
+
200
+ ```ts no-check
201
+ import { Client, cacheExchange, fetchExchange, subscriptionExchange } from 'urql';
202
+ import { createClient } from 'graphql-ws';
203
+
204
+ const ws = createClient({ url: 'wss://api.example.com/graphql' });
205
+
206
+ const client = new Client({
207
+ url: 'https://api.example.com/graphql',
208
+ exchanges: [
209
+ cacheExchange,
210
+ fetchExchange,
211
+ subscriptionExchange({
212
+ forwardSubscription: (request) => ({
213
+ subscribe: (sink) => ({ unsubscribe: ws.subscribe({ ...request, query: request.query ?? '' }, sink) }),
214
+ }),
215
+ }),
216
+ ],
217
+ });
218
+ ```
219
+
220
+ GraphiQL can subscribe over the socket too: `graphiql: {
221
+ subscriptionsProtocol: 'WS' }`.
222
+
223
+ ## Testing it
224
+
225
+ A socket needs a server: `listen({ port: 0 })`, then `graphql-ws`'s client
226
+ with Bun's `WebSocket`. Here `app` is the guarded one
227
+ [above](#the-upgrade-runs-the-apps-middlewares), its token in the URL.
228
+
229
+ ```ts no-check
230
+ import { afterAll, expect, test } from 'bun:test';
231
+ import { createClient } from 'graphql-ws';
232
+ import { app } from './app';
233
+
234
+ const server = app.listen({ port: 0, signals: false });
235
+ afterAll(() => app.stop(true));
236
+
237
+ test('a subscription over the socket', async () => {
238
+ const url = new URL('/graphql?token=ada', server.url);
239
+ url.protocol = 'ws:';
240
+ const client = createClient({ url: url.href, webSocketImpl: WebSocket, retryAttempts: 0 });
241
+ const results = [];
242
+ for await (const result of client.iterate({ query: 'subscription { countdown(from: 1) }' })) {
243
+ results.push(result);
244
+ }
245
+ expect(results).toEqual([{ data: { countdown: 1 } }, { data: { countdown: 0 } }]);
246
+ await client.dispose();
247
+ });
248
+ ```
249
+
250
+ ## See also
251
+
252
+ - [Yoga's plugins and options](yoga.md#subscriptions): subscriptions over
253
+ server-sent events, `createPubSub`.
254
+ - [Mounting the endpoint](endpoint.md#errors-health-and-shutdown): the
255
+ drain, health probes.
256
+ - [`@alxia/core`'s WebSockets](../../../core/docs/guide/websockets.md):
257
+ socket routes, the upgrade.
@@ -1,7 +1,8 @@
1
1
  # Yoga's plugins and options
2
2
 
3
3
  This page covers what passes through to GraphQL Yoga: its plugins and
4
- Envelop's, error masking, batching, subscriptions over server-sent events,
4
+ Envelop's, error masking, batching, subscriptions over server-sent events
5
+ (and over WebSocket with [`ws`](websockets.md)),
5
6
  and how CORS and compression meet the endpoint.
6
7
 
7
8
  ```ts
@@ -189,8 +190,10 @@ curl -N localhost:3000/graphql -H 'content-type: application/json' -H 'accept: t
189
190
  ```
190
191
 
191
192
  A subscription asked for with `Accept: application/json` is refused with
192
- `406`. WebSockets (`graphql-ws`) are not served: a client must speak
193
- server-sent events. `createPubSub` lives in one
193
+ `406`. A client that speaks WebSocket — `graphql-ws`, Apollo Client's
194
+ `GraphQLWsLink`, urql's `subscriptionExchange` — needs `ws: true`
195
+ ([GraphQL over WebSocket](websockets.md)); server-sent events stay served
196
+ beside it. `createPubSub` lives in one
194
197
  process; across several, give it an event target backed by a broker, as
195
198
  [Yoga's subscriptions guide](https://the-guild.dev/graphql/yoga-server/docs/features/subscriptions)
196
199
  describes.
package/docs/roadmap.md CHANGED
@@ -19,6 +19,14 @@ number on it. Every release, with each change it made, is in
19
19
  exits without waiting for it; `health()` probes mount beside the
20
20
  endpoint, and GraphQL errors stay in `errors[]` under core's problem
21
21
  details ([endpoint guide](guide/endpoint.md#errors-health-and-shutdown)).
22
+ - **GraphQL over WebSocket.** `ws: true` serves the endpoint over
23
+ WebSocket too, with the `graphql-transport-ws` protocol of `graphql-ws`
24
+ — Apollo Client's and urql's default — beside server-sent events: the
25
+ upgrade runs the app's middlewares, so a guard refuses the socket and a
26
+ resolver reads what they added; each operation runs through Yoga's
27
+ plugins, with the client's `connectionParams` in its context; a
28
+ shutdown closes the sockets with 1001 and completes their subscriptions
29
+ ([WebSocket guide](guide/websockets.md)).
22
30
 
23
31
  ## Next
24
32
 
@@ -8,6 +8,7 @@ symptom.
8
8
  **Install**
9
9
 
10
10
  - [`Cannot find package 'graphql-yoga' from '…/@alxia/graphql/dist/index.js'`](#cannot-find-package-graphql-yoga-from-alxiagraphqldistindexjs)
11
+ - [`@alxia/graphql: graphql(app, { ws }) serves GraphQL over WebSocket with the optional peer graphql-ws, which is not installed: bun add graphql-ws`](#alxiagraphql-graphqlapp--ws--serves-graphql-over-websocket-with-the-optional-peer-graphql-ws-which-is-not-installed-bun-add-graphql-ws)
11
12
 
12
13
  **Types**
13
14
 
@@ -22,6 +23,7 @@ symptom.
22
23
  **Startup**
23
24
 
24
25
  - [`TypeError: GET /graphql is declared twice`](#typeerror-get-graphql-is-declared-twice)
26
+ - [`TypeError: graphql(app, { ws: { keepAlive: 0 } }): keepAlive is the milliseconds between pings, a positive number, or false for none`](#typeerror-graphqlapp--ws--keepalive-0---keepalive-is-the-milliseconds-between-pings-a-positive-number-or-false-for-none)
25
27
 
26
28
  **Responses**
27
29
 
@@ -30,6 +32,7 @@ symptom.
30
32
  - [`405 {"errors":[{"message":"Can only perform a mutation operation from a POST request."}]}`](#405-errorsmessagecan-only-perform-a-mutation-operation-from-a-post-request)
31
33
  - [`406` with an empty body](#406-with-an-empty-body)
32
34
  - [`{"errors":[{"message":"Must provide query string."}]}`](#errorsmessagemust-provide-query-string)
35
+ - [`4406 Subprotocol not acceptable`](#4406-subprotocol-not-acceptable)
33
36
 
34
37
  **Traps**
35
38
 
@@ -62,6 +65,22 @@ With `graphql` 17, `graphql-yoga` must be 5.22 or later: an older Yoga
62
65
  declares `graphql ^15.2.0 || ^16.0.0`, and `bun install` warns about an
63
66
  incorrect peer. `bun add graphql-yoga@latest` updates it.
64
67
 
68
+ ### `@alxia/graphql: graphql(app, { ws }) serves GraphQL over WebSocket with the optional peer graphql-ws, which is not installed: bun add graphql-ws`
69
+
70
+ **When:** a client opens a socket on an endpoint mounted with `ws` on. The
71
+ upgrade is answered with a `500`, and the server logs this error; the
72
+ client sees its socket fail to open (`Expected 101 status code` in Bun).
73
+
74
+ **Why:** `graphql-ws` is an optional peer, loaded on the first upgrade: an
75
+ app that leaves `ws` off never needs it, so it is not installed with
76
+ `@alxia/graphql`.
77
+
78
+ **Fix:**
79
+
80
+ ```sh
81
+ bun add graphql-ws
82
+ ```
83
+
65
84
  ## Types
66
85
 
67
86
  These are what `tsc` prints. Codes are those with `exactOptionalPropertyTypes`
@@ -220,6 +239,20 @@ const app = alxia()
220
239
  .plugin((app) => graphql(app, { schema: admin, path: '/admin/graphql' }));
221
240
  ```
222
241
 
242
+ ### `TypeError: graphql(app, { ws: { keepAlive: 0 } }): keepAlive is the milliseconds between pings, a positive number, or false for none`
243
+
244
+ **When:** declaring `graphql(app, { ws: { keepAlive } })` with `0`, a
245
+ negative number, `NaN` or `Infinity` — anything but a finite positive number; the message names the value given.
246
+
247
+ **Why:** `keepAlive` is the interval of each socket's pings: `0` would
248
+ ping in a loop.
249
+
250
+ **Fix:** give the milliseconds between pings, or `false` for none:
251
+
252
+ ```ts
253
+ graphql(app, { schema, ws: { keepAlive: 30_000 } });
254
+ ```
255
+
223
256
  ## Responses
224
257
 
225
258
  ### `200 {"errors":[{"message":"Unexpected error.", … "code":"INTERNAL_SERVER_ERROR"}}]}`
@@ -328,6 +361,26 @@ await app.request(`/graphql?query=${encodeURIComponent('{ me }')}`, {
328
361
  });
329
362
  ```
330
363
 
364
+ ### `4406 Subprotocol not acceptable`
365
+
366
+ **When:** a socket opens on an endpoint with `ws` on, then closes at once
367
+ with this code and reason.
368
+
369
+ **Why:** the client offered no subprotocol, or only one the endpoint does
370
+ not serve. `ws` serves `graphql-transport-ws`, the protocol of
371
+ `graphql-ws`; the legacy `subscriptions-transport-ws` client
372
+ offers `graphql-ws`, its own, older protocol, and a bare `new WebSocket(url)`
373
+ offers none.
374
+
375
+ **Fix:** connect with `graphql-ws`'s `createClient`, or with a client built
376
+ on it (Apollo Client's `GraphQLWsLink` from
377
+ `@apollo/client/link/subscriptions`, urql's `subscriptionExchange` given a
378
+ `graphql-ws` client). A hand-written socket names the protocol:
379
+
380
+ ```ts
381
+ const socket = new WebSocket('ws://localhost:3000/graphql', 'graphql-transport-ws');
382
+ ```
383
+
331
384
  ## Traps
332
385
 
333
386
  ### The endpoint answers without a guard declared after it
@@ -391,17 +444,30 @@ const app = alxia()
391
444
 
392
445
  ### A WebSocket client cannot connect: `Expected 101 status code`
393
446
 
394
- **When:** a `graphql-ws` client, or GraphiQL with
395
- `subscriptionsProtocol: 'WS'`, opens `ws://…/graphql`. Bun's client prints
396
- `Expected 101 status code`; a browser reports the WebSocket connection as
397
- failed.
447
+ **When:** a `graphql-ws` client — Apollo Client's `GraphQLWsLink`, urql's
448
+ `subscriptionExchange`, GraphiQL with `subscriptionsProtocol: 'WS'` — opens
449
+ `ws://…/graphql`. Bun's client prints `Expected 101 status code`; a browser
450
+ reports the WebSocket connection as failed.
398
451
 
399
- **Why:** the endpoint serves subscriptions over server-sent events only;
400
- it never upgrades to a WebSocket.
452
+ **Why:** `ws` is off, the default: the endpoint serves subscriptions over
453
+ server-sent events, and never upgrades to a WebSocket. With `ws` on, the
454
+ same message means the upgrade was answered otherwise: a guard's `401`, a
455
+ `500` naming [the missing peer](#alxiagraphql-graphqlapp--ws--serves-graphql-over-websocket-with-the-optional-peer-graphql-ws-which-is-not-installed-bun-add-graphql-ws),
456
+ or a socket `path` other than the one the client opens.
457
+
458
+ **Fix:** serve WebSocket too ([GraphQL over WebSocket](guide/websockets.md)):
459
+
460
+ ```sh
461
+ bun add graphql-ws
462
+ ```
463
+
464
+ ```ts
465
+ graphql(app, { schema, ws: true });
466
+ ```
401
467
 
402
- **Fix:** subscribe over SSE, with `Accept: text/event-stream`
403
- ([Subscriptions](guide/yoga.md#subscriptions)), and leave GraphiQL's
404
- protocol at SSE:
468
+ Or leave `ws` off, and subscribe over SSE, with `Accept: text/event-stream`
469
+ ([Subscriptions](guide/yoga.md#subscriptions)), GraphiQL's protocol left at
470
+ SSE:
405
471
 
406
472
  ```ts
407
473
  graphql(app, { schema, graphiql: { subscriptionsProtocol: 'SSE' } });
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@alxia/graphql",
3
- "version": "0.3.1",
4
- "description": "GraphQL for alxia with GraphQL Yoga: its plugins, subscriptions over SSE and GraphiQL, behind the app's hooks, its resolvers reading the app's typed context",
3
+ "version": "0.4.0",
4
+ "description": "GraphQL for alxia with GraphQL Yoga: its plugins, subscriptions over SSE or WebSocket (graphql-ws) and GraphiQL, behind the app's hooks, its resolvers reading the app's typed context",
5
5
  "license": "MIT",
6
6
  "type": "module",
7
7
  "main": "./dist/index.js",
@@ -45,12 +45,19 @@
45
45
  "@types/bun": "^1.4.2",
46
46
  "dataloader": "^2.2.3",
47
47
  "graphql": "^16.11.0",
48
+ "graphql-ws": "^6.3.0",
48
49
  "graphql-yoga": "^5.16.0"
49
50
  },
50
51
  "peerDependencies": {
51
52
  "@alxia/core": "^0.6.0",
52
53
  "graphql": "^16.11.0 || ^17.0.0",
54
+ "graphql-ws": "^6.1.0",
53
55
  "graphql-yoga": "^5.16.0",
54
56
  "typescript": "^6.0.3 || ^7.0.0"
57
+ },
58
+ "peerDependenciesMeta": {
59
+ "graphql-ws": {
60
+ "optional": true
61
+ }
55
62
  }
56
63
  }