@alxia/graphql 0.3.1 → 0.5.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,52 @@ 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
+ ## Which operation ran
141
+
142
+ Every call is a `POST /graphql`; `graphql()` tells the observers around it
143
+ which operation it executes. Behind `use(logger())` the request's line
144
+ carries `operationName` and `operationType`, and behind
145
+ `use(telemetry({ … }))` its span is named `query GetNotes`, with
146
+ OpenTelemetry's `graphql.operation.name` and `graphql.operation.type`. A
147
+ batched body is one line and one span, `batch`, with every name.
148
+
149
+ ```ts
150
+ const app = alxia()
151
+ .use(logger())
152
+ .use(telemetry({ service: 'notes' }))
153
+ .plugin((app) => graphql(app, { schema }));
154
+ ```
155
+
156
+ A request
157
+ refused before it executes, and an operation over `ws: true`, name none yet.
158
+ See [the endpoint guide](https://github.com/softistx/alxia/blob/develop/packages/graphql/docs/guide/endpoint.md#the-operation-in-the-log-and-the-trace).
159
+
160
+ ## WebSocket
161
+
162
+ `ws: true` serves the endpoint over WebSocket too, with the
163
+ `graphql-transport-ws` protocol of [`graphql-ws`](https://the-guild.dev/graphql/ws),
164
+ the default of Apollo Client's `GraphQLWsLink` and urql's
165
+ `subscriptionExchange`. `graphql-ws` is an optional peer; server-sent
166
+ events stay served at the same path. Install it with `bun add graphql-ws`.
167
+
168
+ ```ts
169
+ const app = base.plugin((app) => graphql(app, { schema, ws: true })); // ws://…/graphql too
170
+ ```
171
+
172
+ ```ts
173
+ import { createClient } from 'graphql-ws';
174
+
175
+ const client = createClient({ url: 'wss://api.example.com/graphql', connectionParams: { device: 'web' } });
176
+ ```
177
+
178
+ The upgrade runs the app's middlewares — a guard's `401` refuses the
179
+ socket, what they add is in the context, beside the `connectionParams`
180
+ the client sent — each operation runs through
181
+ Yoga's plugins, and a shutdown closes the sockets with `1001`, completing
182
+ their subscriptions. `ws: { path, keepAlive }` moves the socket or spaces
183
+ its pings. See [the WebSocket guide](https://github.com/softistx/alxia/blob/develop/packages/graphql/docs/guide/websockets.md),
184
+ Apollo Client's and urql's setup included.
185
+
106
186
  ## Errors, health and shutdown
107
187
 
108
188
  A GraphQL error stays GraphQL's — an entry of `errors[]`, inside a 200 —
@@ -127,7 +207,9 @@ See [the endpoint guide](https://github.com/softistx/alxia/blob/develop/packages
127
207
 
128
208
  | export | |
129
209
  | --- | --- |
130
- | `graphql(app, options)` | the endpoint: `schema`, `path`, `ide`, `sandbox`, and every Yoga option |
210
+ | `graphql(app, options)` | the endpoint: `schema`, `path`, `ide`, `sandbox`, `ws`, and every Yoga option |
211
+ | `GraphQLWsOptions` | `ws`'s options: `path`, `keepAlive` |
212
+ | `GraphQLWsContext` | what an operation over WebSocket adds to the context: `connectionParams` |
131
213
  | `renderSandbox(endpoint, options?)`, `SANDBOX_POLICY` | the Sandbox page, and the policy it loads under |
132
214
  | `SandboxOptions` | its options: `title`, `initialDocument`, `initialHeaders`, `pollForSchemaUpdates`, `includeCookies` |
133
215
  | `GraphQLContext<App, UserContext?>` | what a resolver reads |
@@ -135,7 +217,7 @@ See [the endpoint guide](https://github.com/softistx/alxia/blob/develop/packages
135
217
 
136
218
  ## Documentation
137
219
 
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.
220
+ - [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
221
  - [Troubleshooting](https://github.com/softistx/alxia/blob/develop/packages/graphql/docs/troubleshooting.md): an error message, and what to do about it.
140
222
  - [Roadmap](https://github.com/softistx/alxia/blob/develop/packages/graphql/docs/roadmap.md): what is coming, and what is not planned.
141
223
  - [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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,SAAS,CAAC,GACpE,eAAe,CACd,kBAAkB,GAAG,aAAa,CAAC,GAAG,CAAC,GAAG,OAAO,EACjD,SAAS,CACT,GACA,KAAK,CAAC,GAAG,EAAE,MAAM,CAAC,CAsCpB"}
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,kBAA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AAE,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,153 @@ function endedOnShutdown(response, signal) {
156
161
  });
157
162
  }
158
163
 
164
+ // src/operation.ts
165
+ import { reportOperation } from "@alxia/core";
166
+ import { getOperationAST } from "graphql";
167
+ function report(args) {
168
+ const operation = getOperationAST(args.document, args.operationName);
169
+ if (operation === undefined || operation === null)
170
+ return;
171
+ reportOperation(args.contextValue, {
172
+ type: operation.operation,
173
+ name: operation.name?.value
174
+ });
175
+ }
176
+ function reportsOperations() {
177
+ return {
178
+ onExecute: ({ args }) => report(args),
179
+ onSubscribe: ({ args }) => report(args)
180
+ };
181
+ }
182
+
183
+ // src/ws.ts
184
+ 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";
185
+ function loader() {
186
+ let loading;
187
+ return () => {
188
+ loading ??= import("graphql-ws").catch((cause) => {
189
+ throw new Error(MISSING_PEER, { cause });
190
+ });
191
+ return loading;
192
+ };
193
+ }
194
+ function endpointOf(route, paths) {
195
+ const own = paths.socket === "/" ? "" : paths.socket;
196
+ const at = paths.endpoint === "/" ? "" : paths.endpoint;
197
+ return route.slice(0, route.length - own.length) + at || "/";
198
+ }
199
+ function serverOptions(yogaAt, paths) {
200
+ const enveloped = new WeakMap;
201
+ const of = (args) => enveloped.get(args.contextValue);
202
+ return {
203
+ execute: (args) => of(args).execute(args),
204
+ subscribe: (args) => of(args).subscribe(args),
205
+ async onSubscribe(context, _id, params) {
206
+ const { ctx, request } = context.extra;
207
+ const initial = {
208
+ ...serverContext(ctx),
209
+ request,
210
+ params,
211
+ connectionParams: context.connectionParams
212
+ };
213
+ const { schema, execute, subscribe, contextFactory, parse, validate } = yogaAt(endpointOf(ctx.route, paths)).getEnveloped(initial);
214
+ let document;
215
+ try {
216
+ document = parse(params.query);
217
+ } catch (error) {
218
+ return [error];
219
+ }
220
+ const errors = validate(schema, document);
221
+ if (errors.length > 0)
222
+ return errors;
223
+ const contextValue = await contextFactory();
224
+ enveloped.set(contextValue, { execute, subscribe });
225
+ return {
226
+ schema,
227
+ document,
228
+ operationName: params.operationName,
229
+ variableValues: params.variables,
230
+ contextValue
231
+ };
232
+ }
233
+ };
234
+ }
235
+ function chosen(module, request) {
236
+ const offered = request.headers.get("sec-websocket-protocol") ?? "";
237
+ return module.handleProtocols(offered) || "";
238
+ }
239
+ function operationRequest(upgrade, signal) {
240
+ return new Request(upgrade.url, {
241
+ method: "POST",
242
+ headers: upgrade.headers,
243
+ signal
244
+ });
245
+ }
246
+ function pingEvery(keepAlive) {
247
+ if (keepAlive === undefined)
248
+ return 12000;
249
+ if (keepAlive === false)
250
+ return false;
251
+ if (Number.isFinite(keepAlive) && keepAlive > 0)
252
+ return keepAlive;
253
+ throw new TypeError(`graphql(app, { ws: { keepAlive: ${keepAlive} } }): keepAlive is the milliseconds between pings, a positive number, or false for none`);
254
+ }
255
+ function graphqlSocket(yogaAt, endpoint, options) {
256
+ const paths = { endpoint, socket: options.path ?? endpoint };
257
+ const keepAlive = pingEvery(options.keepAlive);
258
+ const load = loader();
259
+ let module;
260
+ let server;
261
+ const clients = new WeakMap;
262
+ async function graphqlWs(ctx, next) {
263
+ module ??= await load();
264
+ server ??= module.makeServer(serverOptions(yogaAt, paths));
265
+ const protocol = chosen(module, ctx.request);
266
+ if (protocol !== "")
267
+ ctx.set.headers.set("sec-websocket-protocol", protocol);
268
+ return next();
269
+ }
270
+ const handlers = {
271
+ open(socket) {
272
+ const raw = socket.raw;
273
+ const client = { gone: new AbortController };
274
+ clients.set(raw, client);
275
+ const graphqlWsServer = server;
276
+ client.closed = graphqlWsServer.opened({
277
+ protocol: chosen(module, socket.data.request),
278
+ send: (data) => {
279
+ if (raw.readyState === 1)
280
+ raw.sendText(data);
281
+ },
282
+ close: (code, reason) => raw.close(code, reason),
283
+ onMessage: (handle) => {
284
+ client.onMessage = handle;
285
+ }
286
+ }, {
287
+ ctx: socket.data,
288
+ request: operationRequest(socket.data.request, client.gone.signal)
289
+ });
290
+ if (keepAlive !== false) {
291
+ client.pings = setInterval(() => raw.ping(), keepAlive);
292
+ }
293
+ },
294
+ async message(socket, message) {
295
+ const data = typeof message === "string" ? message : new TextDecoder().decode(message);
296
+ await clients.get(socket.raw)?.onMessage?.(data);
297
+ },
298
+ async close(socket, code, reason) {
299
+ const client = clients.get(socket.raw);
300
+ if (client === undefined)
301
+ return;
302
+ clearInterval(client.pings);
303
+ clients.delete(socket.raw);
304
+ client.gone.abort();
305
+ await client.closed?.(code, reason);
306
+ }
307
+ };
308
+ return { path: paths.socket, middleware: graphqlWs, handlers };
309
+ }
310
+
159
311
  // src/graphql.ts
160
312
  function graphql(app, options) {
161
313
  const {
@@ -164,11 +316,13 @@ function graphql(app, options) {
164
316
  ide,
165
317
  graphiql,
166
318
  sandbox,
319
+ ws = false,
167
320
  ...yogaOptions
168
321
  } = options;
169
322
  const page = graphiql ?? true;
170
323
  const yogaAt = yogaServers({
171
324
  ...yogaOptions,
325
+ plugins: [...yogaOptions.plugins ?? [], reportsOperations()],
172
326
  cors,
173
327
  graphiql: ide === undefined ? (_request, context) => isDev(context) && page : ide === "graphiql" ? page : false
174
328
  });
@@ -176,6 +330,10 @@ function graphql(app, options) {
176
330
  const route = app;
177
331
  route.get(path, handler);
178
332
  route.post(path, handler);
333
+ if (ws !== false) {
334
+ const socket = graphqlSocket(yogaAt, path, ws === true ? {} : ws);
335
+ route.ws(socket.path, socket.middleware, socket.handlers);
336
+ }
179
337
  return app;
180
338
  }
181
339
  export {
@@ -184,5 +342,5 @@ export {
184
342
  renderSandbox
185
343
  };
186
344
 
187
- //# debugId=36F374D7B3E2E7EE64756E2164756E21
345
+ //# debugId=FE06B312B406C45364756E2164756E21
188
346
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1,12 +1,14 @@
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/operation.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 { reportsOperations } from './operation';\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\tplugins: [...(yogaOptions.plugins ?? []), reportsOperations()],\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 * The plugin that tells the observers around the endpoint — `@alxia/logger`,\n * `@alxia/telemetry` — which operation each request executes.\n */\nimport { reportOperation } from '@alxia/core';\nimport { getOperationAST } from 'graphql';\nimport type { Plugin } from 'graphql-yoga';\n\ninterface Executed {\n\treadonly document: Parameters<typeof getOperationAST>[0];\n\treadonly operationName?: string | null | undefined;\n\treadonly contextValue: unknown;\n}\n\n/** Reports the operation of `args`: its type, and its name when it has one. */\nfunction report(args: Executed): void {\n\tconst operation = getOperationAST(args.document, args.operationName);\n\tif (operation === undefined || operation === null) return;\n\treportOperation(args.contextValue as object, {\n\t\ttype: operation.operation,\n\t\tname: operation.name?.value,\n\t});\n}\n\n/**\n * A Yoga plugin reporting each operation Yoga executes or subscribes to,\n * through core's `reportOperation`: a batched body reports each of its\n * operations, a request refused before it executes none.\n */\nexport function reportsOperations(): Plugin {\n\treturn {\n\t\tonExecute: ({ args }) => report(args),\n\t\tonSubscribe: ({ args }) => report(args),\n\t};\n}\n",
9
+ "/**\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
10
  ],
9
- "mappings": ";AAAA;AAAA;AAAA;;;ACIA;AACA;AAAA;AAAA;;;ACkBO,IAAM,iBAAiB;AAAA,EAC7B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACD,EAAE,KAAK,IAAI;AAOJ,SAAS,aAAa,CAC5B,UACA,UAA0B,CAAC,GAClB;AAAA,EACT,MAAM,SAAS;AAAA,IACd,QAAQ;AAAA,IACR,iBAAiB;AAAA,IACjB,cAAc;AAAA,MACb,gBAAgB,QAAQ,kBAAkB;AAAA,MAC1C,sBAAsB,QAAQ,wBAAwB;AAAA,SAClD,QAAQ,oBAAoB,YAC7B,CAAC,IACD,EAAE,UAAU,QAAQ,gBAAgB;AAAA,SACnC,QAAQ,mBAAmB,YAC5B,CAAC,IACD,EAAE,SAAS,QAAQ,eAAe;AAAA,IACtC;AAAA,IACA,kBAAkB;AAAA,IAClB,oBAAoB;AAAA,EACrB;AAAA,EACA,OAAO;AAAA;AAAA;AAAA;AAAA;AAAA,SAKC,KAAK,QAAQ,SAAS,kBAAkB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,iBAQhC,OAAO,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAS9B,SAAS,IAAI,CAAC,MAAsB;AAAA,EACnC,OAAO,KAAK,QAAQ,YAAY,CAAC,SAAS,KAAK,KAAK,WAAW,CAAC,IAAI;AAAA;AAIrE,SAAS,MAAM,CAAC,OAAwB;AAAA,EACvC,OAAO,KAAK,UAAU,KA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AAAA,MAC1B,QAAQ,OAAO,OAAO,GAAG;AAAA,MACzB,OAAO,KAAK,MAAM;AAAA,MAClB,MAAM,OAAO,SAAS,MAAM,MAAM;AAAA;AAAA,EAEpC;AAAA,EACA,OAAO,EAAE,MAAM,MAAM,QAAQ,YAAY,WAAW,SAAS;AAAA;;;AJjGvD,SAAS,OAMf,CACA,KACA,SAKqB;AAAA,EACrB;AAAA,IACC,OAAO;AAAA,IACP,OAAO;AAAA,IACP;AAAA,IACA;AAAA,IACA;AAAA,IACA,KAAK;AAAA,OACF;AAAA,MACA;AAAA,EACJ,MAAM,OAAO,YAAY;AAAA,EACzB,MAAM,SAAS,YAAqB;AAAA,OAC/B;AAAA,IACJ,SAAS,CAAC,GAAI,YAAY,WAAW,CAAC,GAAI,kBAAkB,CAAC;AAAA,IAC7D;AAAA,IACA,UAAW,QAAQ,YAChB,CAAC,UAAmB,YAAoB,MAAM,OAAO,KAAK,OAC1D,QAAQ,aACP,OACA;AAAA,EACL,CAAC;AAAA,EACD,MAAM,UAAU,eACf,QACA,QAAQ,mBAAoB,WAAW,CAAC,IAAK,KAC9C;AAAA,EAEA,MAAM,QAAQ;AAAA,EAKd,MAAM,IAAI,MAAM,OAAO;AAAA,EACvB,MAAM,KAAK,MAAM,OAAO;AAAA,EACxB,IAAI,OAAO,OAAO;AAAA,IACjB,MAAM,SAAS,cAAc,QAAQ,MAAM,OAAO,OAAO,CAAC,IAAI,EAAE;AAAA,IAChE,MAAM,GAAG,OAAO,MAAM,OAAO,YAAY,OAAO,QAAQ;AAAA,EACzD;AAAA,EACA,OAAO;AAAA;",
12
+ "debugId": "FE06B312B406C45364756E2164756E21",
11
13
  "names": []
12
14
  }
@@ -0,0 +1,8 @@
1
+ import type { Plugin } from 'graphql-yoga';
2
+ /**
3
+ * A Yoga plugin reporting each operation Yoga executes or subscribes to,
4
+ * through core's `reportOperation`: a batched body reports each of its
5
+ * operations, a request refused before it executes none.
6
+ */
7
+ export declare function reportsOperations(): Plugin;
8
+ //# sourceMappingURL=operation.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"operation.d.ts","sourceRoot":"","sources":["../src/operation.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAkB3C;;;;GAIG;AACH,wBAAgB,iBAAiB,IAAI,MAAM,CAK1C"}
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
 
@@ -155,6 +157,39 @@ POST {} → 200 {"errors":[{"message":"Must provid
155
157
  Both methods answer a body to read as GraphQL, whatever its status, and
156
158
  the replies of the middlewares before them — a guard's `401`, say.
157
159
 
160
+ ## The operation in the log and the trace
161
+
162
+ Every call is a `POST /graphql`, so the route alone cannot tell `GetNotes`
163
+ from `AddNote`. For each operation Yoga executes or subscribes to,
164
+ `graphql()` reports its type and name to the middlewares around it
165
+ (`reportOperation` of `@alxia/core`, a Yoga plugin it adds after yours),
166
+ and no package imports another: `@alxia/logger` adds `operationName` and
167
+ `operationType` to the request's line, and `@alxia/telemetry` names its
168
+ span `query GetNotes` with `graphql.operation.name` and
169
+ `graphql.operation.type`. Give both to `use` before `graphql()`:
170
+
171
+ ```ts
172
+ const app = alxia()
173
+ .use(logger())
174
+ .use(telemetry({ service: 'notes' }))
175
+ .plugin((app) => graphql(app, { schema }));
176
+ ```
177
+
178
+ ```json
179
+ {"message":"POST /graphql 200","status":200,"operationName":"GetNotes","operationType":"query"}
180
+ ```
181
+
182
+ - A batched body (`batching`, an array) is one line and one span: the type
183
+ is `batch`, the names are listed, `GetNotes,AddNote`.
184
+ - An anonymous operation has a type and no name.
185
+ - A request refused before it executes (a syntax error, a document that
186
+ fails validation) names no operation: its line is the plain
187
+ `POST /graphql`.
188
+ - Your own middleware reads it with `operationOf(ctx)` after `next()`.
189
+ - Over `ws: true`, the operations on a socket are not reported: logger and
190
+ telemetry see the upgrade alone, so they are not logged or spanned yet
191
+ ([roadmap](../roadmap.md)).
192
+
158
193
  ## Errors, health and shutdown
159
194
 
160
195
  **GraphQL errors stay GraphQL's.** A resolver that throws, a query that
@@ -232,3 +267,5 @@ describe('graphql', () => {
232
267
  - [Yoga's plugins and options](yoga.md): plugins, errors, subscriptions,
233
268
  CORS.
234
269
  - [GraphiQL and Apollo Sandbox](ide.md): the page a browser gets.
270
+ - [GraphQL over WebSocket](websockets.md): `ws`, for `graphql-ws`
271
+ clients.
@@ -0,0 +1,265 @@
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
+ ## Logging and tracing
146
+
147
+ `@alxia/logger` and `@alxia/telemetry` see the upgrade request, `101`, and
148
+ not the operations on the socket: the request is answered before they run,
149
+ so none of them gets an `operationName` or a span. Log from a Yoga plugin's
150
+ `onExecute` for now; each operation over the socket is on the
151
+ [roadmap](../roadmap.md).
152
+
153
+ ## Errors
154
+
155
+ An error stays GraphQL's. A resolver's arrives in a `next` message with
156
+ `errors[]` — masked to `Unexpected error.` unless `maskedErrors` says
157
+ otherwise — and the subscription goes on or completes as over HTTP. A
158
+ query that does not parse or validate is answered with an `error`
159
+ message, the protocol's, and the socket stays open.
160
+
161
+ ## Shutdown
162
+
163
+ On `SIGTERM`, `SIGINT` or `stop()`, `/ready` turns 503 and every socket is
164
+ closed with `1001 going away`: each subscription on it completes, its
165
+ resolver's iterator returned, so the drain does not wait for it. A
166
+ `graphql-ws` client retries on `1001`, by default, and reaches another
167
+ instance.
168
+
169
+ ## Clients
170
+
171
+ `graphql-ws`'s own client, in Bun or a browser:
172
+
173
+ ```ts no-check
174
+ import { createClient } from 'graphql-ws';
175
+
176
+ const client = createClient({
177
+ url: 'wss://api.example.com/graphql?token=…',
178
+ connectionParams: { device: 'web' },
179
+ });
180
+
181
+ for await (const result of client.iterate({ query: 'subscription { countdown(from: 3) }' })) {
182
+ console.log(result); // { data: { countdown: 3 } }, …
183
+ }
184
+ ```
185
+
186
+ Apollo Client: subscriptions over the socket, the rest over HTTP.
187
+
188
+ ```ts no-check
189
+ import { ApolloClient, ApolloLink, HttpLink, InMemoryCache } from '@apollo/client';
190
+ import { GraphQLWsLink } from '@apollo/client/link/subscriptions';
191
+ import { getMainDefinition } from '@apollo/client/utilities';
192
+ import { createClient } from 'graphql-ws';
193
+
194
+ const ws = new GraphQLWsLink(createClient({ url: 'wss://api.example.com/graphql' }));
195
+ const http = new HttpLink({ uri: 'https://api.example.com/graphql' });
196
+
197
+ const client = new ApolloClient({
198
+ cache: new InMemoryCache(),
199
+ link: ApolloLink.split(({ query }) => {
200
+ const definition = getMainDefinition(query);
201
+ return definition.kind === 'OperationDefinition' && definition.operation === 'subscription';
202
+ }, ws, http),
203
+ });
204
+ ```
205
+
206
+ urql:
207
+
208
+ ```ts no-check
209
+ import { Client, cacheExchange, fetchExchange, subscriptionExchange } from 'urql';
210
+ import { createClient } from 'graphql-ws';
211
+
212
+ const ws = createClient({ url: 'wss://api.example.com/graphql' });
213
+
214
+ const client = new Client({
215
+ url: 'https://api.example.com/graphql',
216
+ exchanges: [
217
+ cacheExchange,
218
+ fetchExchange,
219
+ subscriptionExchange({
220
+ forwardSubscription: (request) => ({
221
+ subscribe: (sink) => ({ unsubscribe: ws.subscribe({ ...request, query: request.query ?? '' }, sink) }),
222
+ }),
223
+ }),
224
+ ],
225
+ });
226
+ ```
227
+
228
+ GraphiQL can subscribe over the socket too: `graphiql: {
229
+ subscriptionsProtocol: 'WS' }`.
230
+
231
+ ## Testing it
232
+
233
+ A socket needs a server: `listen({ port: 0 })`, then `graphql-ws`'s client
234
+ with Bun's `WebSocket`. Here `app` is the guarded one
235
+ [above](#the-upgrade-runs-the-apps-middlewares), its token in the URL.
236
+
237
+ ```ts no-check
238
+ import { afterAll, expect, test } from 'bun:test';
239
+ import { createClient } from 'graphql-ws';
240
+ import { app } from './app';
241
+
242
+ const server = app.listen({ port: 0, signals: false });
243
+ afterAll(() => app.stop(true));
244
+
245
+ test('a subscription over the socket', async () => {
246
+ const url = new URL('/graphql?token=ada', server.url);
247
+ url.protocol = 'ws:';
248
+ const client = createClient({ url: url.href, webSocketImpl: WebSocket, retryAttempts: 0 });
249
+ const results = [];
250
+ for await (const result of client.iterate({ query: 'subscription { countdown(from: 1) }' })) {
251
+ results.push(result);
252
+ }
253
+ expect(results).toEqual([{ data: { countdown: 1 } }, { data: { countdown: 0 } }]);
254
+ await client.dispose();
255
+ });
256
+ ```
257
+
258
+ ## See also
259
+
260
+ - [Yoga's plugins and options](yoga.md#subscriptions): subscriptions over
261
+ server-sent events, `createPubSub`.
262
+ - [Mounting the endpoint](endpoint.md#errors-health-and-shutdown): the
263
+ drain, health probes.
264
+ - [`@alxia/core`'s WebSockets](../../../core/docs/guide/websockets.md):
265
+ 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
@@ -140,6 +141,11 @@ POST [{"query":"{ admin }"},{"query":"{ __typename }"}]
140
141
  200 [{"data":{"admin":"welcome"}},{"data":{"__typename":"Query"}}]
141
142
  ```
142
143
 
144
+ A batch is one request, so one log line and one span: `@alxia/logger` writes
145
+ `operationType: 'batch'` and every name, `operationName: 'GetNotes,AddNote'`,
146
+ and `@alxia/telemetry` names the span `batch GetNotes,AddNote`
147
+ ([endpoint guide](endpoint.md#the-operation-in-the-log-and-the-trace)).
148
+
143
149
  ## Subscriptions
144
150
 
145
151
  Subscriptions are served over server-sent events, Yoga's default: a
@@ -189,8 +195,10 @@ curl -N localhost:3000/graphql -H 'content-type: application/json' -H 'accept: t
189
195
  ```
190
196
 
191
197
  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
198
+ `406`. A client that speaks WebSocket — `graphql-ws`, Apollo Client's
199
+ `GraphQLWsLink`, urql's `subscriptionExchange` — needs `ws: true`
200
+ ([GraphQL over WebSocket](websockets.md)); server-sent events stay served
201
+ beside it. `createPubSub` lives in one
194
202
  process; across several, give it an event target backed by a broker, as
195
203
  [Yoga's subscriptions guide](https://the-guild.dev/graphql/yoga-server/docs/features/subscriptions)
196
204
  describes.
package/docs/roadmap.md CHANGED
@@ -19,10 +19,18 @@ 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
 
25
- Nothing scheduled yet.
33
+ - **Each operation over a socket.** A `ws: true` connection is logged or spanned at its upgrade alone: its operations — a query, a mutation, a subscription's stream — name no operation yet, because the request is answered before they run.
26
34
 
27
35
  ## Later
28
36
 
@@ -30,6 +38,10 @@ Nothing scheduled yet.
30
38
 
31
39
  ## Shipped
32
40
 
41
+ ### Next release
42
+
43
+ - **The operation, told to the observers.** Each operation the endpoint executes is reported to the middlewares around it: `@alxia/logger` writes `operationName` and `operationType` on the request's line, `@alxia/telemetry` names its span `query GetNotes` with `graphql.operation.name` and `graphql.operation.type`. A batched body is one line and one span, `batch`, with every name ([endpoint guide](guide/endpoint.md#the-operation-in-the-log-and-the-trace)).
44
+
33
45
  ### 0.1.0
34
46
 
35
47
  - **GraphQL Yoga as a route.** `graphql(app, options)` serves a schema at
@@ -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
@@ -348,6 +401,24 @@ const base = alxia().use(bearer({ jwt }));
348
401
  const app = base.plugin((app) => graphql(app, { schema }));
349
402
  ```
350
403
 
404
+ ### Every log line and span is an anonymous `POST /graphql`
405
+
406
+ **When:** `@alxia/logger` writes `POST /graphql 200` with no
407
+ `operationName`, and the span of `@alxia/telemetry` is named
408
+ `POST /graphql`.
409
+
410
+ **Why:** an operation is reported only when Yoga executes it. A request
411
+ refused before that (a syntax error, a document that fails validation) names
412
+ none; an operation over `ws: true` is not reported; and a logger or a
413
+ telemetry given to `use` *after* the endpoint, or a version of
414
+ `@alxia/core` older than the one that reports (`operationOf`), never reads
415
+ it.
416
+
417
+ **Fix:** give `logger()` and `telemetry()` to `use` before `graphql()`, and
418
+ update `@alxia/core`, `@alxia/graphql`, `@alxia/logger` and
419
+ `@alxia/telemetry` together. See
420
+ [the endpoint guide](guide/endpoint.md#the-operation-in-the-log-and-the-trace).
421
+
351
422
  ### The logger, CORS or secure headers miss the endpoint
352
423
 
353
424
  **When:** `use(logger())`, `use(cors(…))` or `use(secureHeaders())` comes
@@ -391,17 +462,30 @@ const app = alxia()
391
462
 
392
463
  ### A WebSocket client cannot connect: `Expected 101 status code`
393
464
 
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.
465
+ **When:** a `graphql-ws` client — Apollo Client's `GraphQLWsLink`, urql's
466
+ `subscriptionExchange`, GraphiQL with `subscriptionsProtocol: 'WS'` — opens
467
+ `ws://…/graphql`. Bun's client prints `Expected 101 status code`; a browser
468
+ reports the WebSocket connection as failed.
469
+
470
+ **Why:** `ws` is off, the default: the endpoint serves subscriptions over
471
+ server-sent events, and never upgrades to a WebSocket. With `ws` on, the
472
+ same message means the upgrade was answered otherwise: a guard's `401`, a
473
+ `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),
474
+ or a socket `path` other than the one the client opens.
475
+
476
+ **Fix:** serve WebSocket too ([GraphQL over WebSocket](guide/websockets.md)):
477
+
478
+ ```sh
479
+ bun add graphql-ws
480
+ ```
398
481
 
399
- **Why:** the endpoint serves subscriptions over server-sent events only;
400
- it never upgrades to a WebSocket.
482
+ ```ts
483
+ graphql(app, { schema, ws: true });
484
+ ```
401
485
 
402
- **Fix:** subscribe over SSE, with `Accept: text/event-stream`
403
- ([Subscriptions](guide/yoga.md#subscriptions)), and leave GraphiQL's
404
- protocol at SSE:
486
+ Or leave `ws` off, and subscribe over SSE, with `Accept: text/event-stream`
487
+ ([Subscriptions](guide/yoga.md#subscriptions)), GraphiQL's protocol left at
488
+ SSE:
405
489
 
406
490
  ```ts
407
491
  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.5.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",
@@ -41,16 +41,23 @@
41
41
  ]
42
42
  },
43
43
  "devDependencies": {
44
- "@alxia/core": "^0.6.0",
44
+ "@alxia/core": "^0.7.0",
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
- "@alxia/core": "^0.6.0",
52
+ "@alxia/core": "^0.7.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
  }