@alxia/graphql 0.4.0 → 0.6.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 +24 -1
- package/dist/body-refusal.d.ts +24 -0
- package/dist/body-refusal.d.ts.map +1 -0
- package/dist/graphql.d.ts.map +1 -1
- package/dist/handler.d.ts.map +1 -1
- package/dist/index.js +160 -13
- package/dist/index.js.map +10 -6
- package/dist/operation.d.ts +8 -0
- package/dist/operation.d.ts.map +1 -0
- package/dist/ws-operations.d.ts +31 -0
- package/dist/ws-operations.d.ts.map +1 -0
- package/dist/ws-server.d.ts +32 -0
- package/dist/ws-server.d.ts.map +1 -0
- package/dist/ws.d.ts +3 -2
- package/dist/ws.d.ts.map +1 -1
- package/docs/README.md +1 -0
- package/docs/guide/endpoint.md +33 -0
- package/docs/guide/production.md +229 -0
- package/docs/guide/websockets.md +42 -0
- package/docs/guide/yoga.md +6 -0
- package/docs/roadmap.md +5 -0
- package/docs/troubleshooting.md +52 -0
- package/package.json +9 -3
package/README.md
CHANGED
|
@@ -137,6 +137,29 @@ graphql(app, {
|
|
|
137
137
|
- **CORS** is `@alxia/cors`'s for the whole app: Yoga's own is off unless
|
|
138
138
|
`cors` is given.
|
|
139
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 names none. Over `ws: true`, each operation on
|
|
158
|
+
the socket is a line and a span of its own, from its `subscribe` message
|
|
159
|
+
to its end, marked when answered with errors.
|
|
160
|
+
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)
|
|
161
|
+
and [the WebSocket guide](https://github.com/softistx/alxia/blob/develop/packages/graphql/docs/guide/websockets.md#logging-and-tracing).
|
|
162
|
+
|
|
140
163
|
## WebSocket
|
|
141
164
|
|
|
142
165
|
`ws: true` serves the endpoint over WebSocket too, with the
|
|
@@ -197,7 +220,7 @@ See [the endpoint guide](https://github.com/softistx/alxia/blob/develop/packages
|
|
|
197
220
|
|
|
198
221
|
## Documentation
|
|
199
222
|
|
|
200
|
-
- [Guide](https://github.com/softistx/alxia/tree/develop/packages/graphql/docs): a page per area — mounting the endpoint, the typed context, Yoga's plugins and options, GraphQL over WebSocket,
|
|
223
|
+
- [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, GraphiQL and Apollo Sandbox, and [hardening an API for production](https://github.com/softistx/alxia/blob/develop/packages/graphql/docs/guide/production.md) (rate limits, depth limits, introspection, errors, body size, CSRF, persisted operations).
|
|
201
224
|
- [Troubleshooting](https://github.com/softistx/alxia/blob/develop/packages/graphql/docs/troubleshooting.md): an error message, and what to do about it.
|
|
202
225
|
- [Roadmap](https://github.com/softistx/alxia/blob/develop/packages/graphql/docs/roadmap.md): what is coming, and what is not planned.
|
|
203
226
|
- [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.
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Yoga reads the request body itself, and turns any failure of the read
|
|
3
|
+
* into its own 400. A body past core's `bodyLimit` fails the read with a
|
|
4
|
+
* `ContentTooLargeError`; `watchBody` keeps that error, so the handler
|
|
5
|
+
* can throw it again once Yoga has answered, and the app's own boundary
|
|
6
|
+
* answers the 413 in its error format, leaking nothing of Yoga's.
|
|
7
|
+
*/
|
|
8
|
+
import type { ContentTooLargeError } from '@alxia/core';
|
|
9
|
+
export interface WatchedRequest {
|
|
10
|
+
/** The request to hand to Yoga: the same, its body watched. */
|
|
11
|
+
readonly request: Request;
|
|
12
|
+
/** The `ContentTooLargeError` the body's read failed with, if it did. */
|
|
13
|
+
refusal(): ContentTooLargeError | undefined;
|
|
14
|
+
}
|
|
15
|
+
/** `request` with its body's failure recorded; a request with no body is as it is. */
|
|
16
|
+
export declare function watchBody(request: Request): WatchedRequest;
|
|
17
|
+
/**
|
|
18
|
+
* Yoga's 400 for a request it cannot read — a body that is not JSON, a
|
|
19
|
+
* query string that is not valid — carries the parser's own error as
|
|
20
|
+
* `extensions.originalError`. A client reads the message and the code, not
|
|
21
|
+
* what a parser said: the response without it, any other as it is.
|
|
22
|
+
*/
|
|
23
|
+
export declare function withoutOriginalError(response: Response): Promise<Response>;
|
|
24
|
+
//# sourceMappingURL=body-refusal.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"body-refusal.d.ts","sourceRoot":"","sources":["../src/body-refusal.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AAcxD,MAAM,WAAW,cAAc;IAC9B,+DAA+D;IAC/D,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC;IAC1B,yEAAyE;IACzE,OAAO,IAAI,oBAAoB,GAAG,SAAS,CAAC;CAC5C;AAED,sFAAsF;AACtF,wBAAgB,SAAS,CAAC,OAAO,EAAE,OAAO,GAAG,cAAc,CAwB1D;AAMD;;;;;GAKG;AACH,wBAAsB,oBAAoB,CACzC,QAAQ,EAAE,QAAQ,GAChB,OAAO,CAAC,QAAQ,CAAC,CAqBnB"}
|
package/dist/graphql.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"graphql.d.ts","sourceRoot":"","sources":["../src/graphql.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,KAAK,KAAK,EACV,KAAK,WAAW,EAChB,KAAK,KAAK,EAEV,KAAK,SAAS,EACd,MAAM,aAAa,CAAC;AACrB,OAAO,KAAK,EACX,wBAAwB,EACxB,kBAAkB,EAClB,iBAAiB,EACjB,MAAM,cAAc,CAAC;AACtB,OAAO,EAAkB,KAAK,WAAW,EAAe,MAAM,WAAW,CAAC;
|
|
1
|
+
{"version":3,"file":"graphql.d.ts","sourceRoot":"","sources":["../src/graphql.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,KAAK,KAAK,EACV,KAAK,WAAW,EAChB,KAAK,KAAK,EAEV,KAAK,SAAS,EACd,MAAM,aAAa,CAAC;AACrB,OAAO,KAAK,EACX,wBAAwB,EACxB,kBAAkB,EAClB,iBAAiB,EACjB,MAAM,cAAc,CAAC;AACtB,OAAO,EAAkB,KAAK,WAAW,EAAe,MAAM,WAAW,CAAC;AAE1E,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAChD,OAAO,EAAE,KAAK,gBAAgB,EAAiB,MAAM,MAAM,CAAC;AAE5D,oFAAoF;AACpF,KAAK,SAAS,GACX,QAAQ,GACR,OAAO,GACP,SAAS,GACT,SAAS,GACT,MAAM,GACN,OAAO,GACP,UAAU,CAAC;AAEd;;;;GAIG;AACH,MAAM,MAAM,aAAa,CAAC,GAAG,IAAI,IAAI,CAAC,WAAW,GAAG,GAAG,EAAE,SAAS,CAAC,CAAC;AAEpE;;;;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9D;;;;;;OAMG;IACH,QAAQ,CAAC,EAAE,CAAC,EAAE,OAAO,GAAG,gBAAgB,CAAC;CACzC;AAED;;;;GAIG;AACH,KAAK,eAAe,CAAC,QAAQ,EAAE,QAAQ,IAAI,QAAQ,SAAS,QAAQ,GACjE,OAAO,GACP;IACA,QAAQ,CAAC,MAAM,EAAE,yEAAyE,OAAO,CAChG,MAAM,QAAQ,EACd,MAAM,QAAQ,CACd,GACA,MAAM,EAAE,CAAC;CACV,CAAC;AAEJ;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,OAAO,CACtB,GAAG,SAAS,MAAM,EAClB,MAAM,SAAS,MAAM,EACrB,SAAS,EACT,OAAO,SAAS,WAAW,GAAG,KAAK,EACnC,KAAK,CAAC,IAAI,SAAS,SAAS,GAAG,UAAU,EAEzC,GAAG,EAAE,KAAK,CAAC,GAAG,EAAE,MAAM,CAAC,EACvB,OAAO,EAAE,cAAc,CAAC,aAAa,CAAC,GAAG,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,SAAS,CAAC,GACpE,eAAe,CACd,kBAAkB,GAAG,aAAa,CAAC,GAAG,CAAC,GAAG,OAAO,EACjD,SAAS,CACT,GACA,KAAK,CAAC,GAAG,EAAE,MAAM,CAAC,CAsCpB"}
|
package/dist/handler.d.ts.map
CHANGED
|
@@ -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;
|
|
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;AAEtB,OAAO,EAAiC,KAAK,cAAc,EAAE,MAAM,WAAW,CAAC;AAE/E,MAAM,MAAM,WAAW,GAAG,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;AAM9C;;;;;;;GAOG;AACH,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAanD;AAED;;;;GAIG;AACH,wBAAgB,WAAW,CAAC,OAAO,SAAS,WAAW,EACtD,OAAO,EAAE,IAAI,CAAC,iBAAiB,CAAC,WAAW,EAAE,OAAO,CAAC,EAAE,iBAAiB,CAAC,GACvE,CAAC,QAAQ,EAAE,MAAM,KAAK,kBAAkB,CAAC,WAAW,EAAE,OAAO,CAAC,CAahE;AAED;;;GAGG;AACH,wBAAgB,aAAa,CAC5B,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAC1B,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAYzB;AAED;;;;;GAKG;AACH,wBAAgB,cAAc,CAAC,OAAO,SAAS,WAAW,EACzD,MAAM,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,kBAAkB,CAAC,WAAW,EAAE,OAAO,CAAC,EACtE,OAAO,EAAE,cAAc,GAAG,KAAK,IAK9B,KAAK,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,WAAW,GAAG;IAAE,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAA;CAAE,qJA4CxE"}
|
package/dist/index.js
CHANGED
|
@@ -9,6 +9,60 @@ import {
|
|
|
9
9
|
createYoga
|
|
10
10
|
} from "graphql-yoga";
|
|
11
11
|
|
|
12
|
+
// src/body-refusal.ts
|
|
13
|
+
function isTooLarge(error) {
|
|
14
|
+
return error instanceof Error && error.name === "ContentTooLargeError" && typeof error.limit === "number";
|
|
15
|
+
}
|
|
16
|
+
function watchBody(request) {
|
|
17
|
+
const source = request.body;
|
|
18
|
+
if (source === null || request.bodyUsed || source.locked) {
|
|
19
|
+
return { request, refusal: () => {
|
|
20
|
+
return;
|
|
21
|
+
} };
|
|
22
|
+
}
|
|
23
|
+
let refused;
|
|
24
|
+
const reader = source.getReader();
|
|
25
|
+
const body = new ReadableStream({
|
|
26
|
+
async pull(controller) {
|
|
27
|
+
try {
|
|
28
|
+
const { value, done } = await reader.read();
|
|
29
|
+
if (done)
|
|
30
|
+
controller.close();
|
|
31
|
+
else
|
|
32
|
+
controller.enqueue(value);
|
|
33
|
+
} catch (error) {
|
|
34
|
+
if (isTooLarge(error))
|
|
35
|
+
refused = error;
|
|
36
|
+
throw error;
|
|
37
|
+
}
|
|
38
|
+
},
|
|
39
|
+
cancel: (reason) => reader.cancel(reason)
|
|
40
|
+
});
|
|
41
|
+
return {
|
|
42
|
+
request: new Request(request, { body, duplex: "half" }),
|
|
43
|
+
refusal: () => refused
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
async function withoutOriginalError(response) {
|
|
47
|
+
const type = response.headers.get("content-type") ?? "";
|
|
48
|
+
if (response.status !== 400 || !/^application\/(?:[\w.-]+\+)?json/.test(type)) {
|
|
49
|
+
return response;
|
|
50
|
+
}
|
|
51
|
+
const text = await response.text();
|
|
52
|
+
let failure;
|
|
53
|
+
try {
|
|
54
|
+
failure = JSON.parse(text);
|
|
55
|
+
} catch {
|
|
56
|
+
return new Response(text, response);
|
|
57
|
+
}
|
|
58
|
+
for (const error of failure.errors ?? []) {
|
|
59
|
+
delete error.extensions?.["originalError"];
|
|
60
|
+
}
|
|
61
|
+
const headers = new Headers(response.headers);
|
|
62
|
+
headers.delete("content-length");
|
|
63
|
+
return new Response(JSON.stringify(failure), { status: 400, headers });
|
|
64
|
+
}
|
|
65
|
+
|
|
12
66
|
// src/sandbox.ts
|
|
13
67
|
var SANDBOX_POLICY = [
|
|
14
68
|
"default-src 'self'",
|
|
@@ -114,7 +168,14 @@ function graphqlHandler(yogaAt, sandbox) {
|
|
|
114
168
|
}
|
|
115
169
|
});
|
|
116
170
|
}
|
|
117
|
-
const
|
|
171
|
+
const watched = watchBody(ctx.request);
|
|
172
|
+
const answered = await yogaAt(ctx.route).fetch(watched.request, server);
|
|
173
|
+
const refusal = watched.refusal();
|
|
174
|
+
if (refusal !== undefined) {
|
|
175
|
+
answered.body?.cancel();
|
|
176
|
+
throw refusal;
|
|
177
|
+
}
|
|
178
|
+
const response = await withoutOriginalError(answered);
|
|
118
179
|
const headers = new Headers(response.headers);
|
|
119
180
|
if (headers.get("content-type")?.startsWith("text/html") && !headers.has("content-security-policy")) {
|
|
120
181
|
const html = await response.text();
|
|
@@ -161,17 +222,83 @@ function endedOnShutdown(response, signal) {
|
|
|
161
222
|
});
|
|
162
223
|
}
|
|
163
224
|
|
|
164
|
-
// src/
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
225
|
+
// src/operation.ts
|
|
226
|
+
import { reportOperation } from "@alxia/core";
|
|
227
|
+
import { getOperationAST } from "graphql";
|
|
228
|
+
function report(args) {
|
|
229
|
+
const operation = getOperationAST(args.document, args.operationName);
|
|
230
|
+
if (operation === undefined || operation === null)
|
|
231
|
+
return;
|
|
232
|
+
reportOperation(args.contextValue, {
|
|
233
|
+
type: operation.operation,
|
|
234
|
+
name: operation.name?.value
|
|
235
|
+
});
|
|
236
|
+
}
|
|
237
|
+
function reportsOperations() {
|
|
238
|
+
return {
|
|
239
|
+
onExecute: ({ args }) => report(args),
|
|
240
|
+
onSubscribe: ({ args }) => report(args)
|
|
241
|
+
};
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
// src/ws-operations.ts
|
|
245
|
+
import { startOperation } from "@alxia/core";
|
|
246
|
+
import { getOperationAST as getOperationAST2 } from "graphql";
|
|
247
|
+
|
|
248
|
+
class SocketOperations {
|
|
249
|
+
#ctx;
|
|
250
|
+
#open = new Map;
|
|
251
|
+
constructor(ctx) {
|
|
252
|
+
this.#ctx = ctx;
|
|
253
|
+
}
|
|
254
|
+
begin(id, document, operationName) {
|
|
255
|
+
this.end(id);
|
|
256
|
+
const operation = getOperationAST2(document, operationName);
|
|
257
|
+
if (operation === undefined || operation === null)
|
|
258
|
+
return;
|
|
259
|
+
const end = startOperation(this.#ctx, {
|
|
260
|
+
type: operation.operation,
|
|
261
|
+
name: operation.name?.value
|
|
171
262
|
});
|
|
172
|
-
|
|
263
|
+
this.#open.set(id, { end, outcome: "ok" });
|
|
264
|
+
}
|
|
265
|
+
failed(id) {
|
|
266
|
+
const open = this.#open.get(id);
|
|
267
|
+
if (open !== undefined)
|
|
268
|
+
open.outcome = "errors";
|
|
269
|
+
}
|
|
270
|
+
end(id) {
|
|
271
|
+
const open = this.#open.get(id);
|
|
272
|
+
if (open === undefined)
|
|
273
|
+
return;
|
|
274
|
+
this.#open.delete(id);
|
|
275
|
+
open.end(open.outcome);
|
|
276
|
+
}
|
|
277
|
+
closed() {
|
|
278
|
+
for (const id of [...this.#open.keys()]) {
|
|
279
|
+
this.failed(id);
|
|
280
|
+
this.end(id);
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
function following() {
|
|
285
|
+
return {
|
|
286
|
+
onNext({ extra }, id, _payload, _args, result) {
|
|
287
|
+
if (result.errors !== undefined && result.errors.length > 0) {
|
|
288
|
+
extra.operations.failed(id);
|
|
289
|
+
}
|
|
290
|
+
},
|
|
291
|
+
onError({ extra }, id) {
|
|
292
|
+
extra.operations.failed(id);
|
|
293
|
+
extra.operations.end(id);
|
|
294
|
+
},
|
|
295
|
+
onComplete({ extra }, id) {
|
|
296
|
+
extra.operations.end(id);
|
|
297
|
+
}
|
|
173
298
|
};
|
|
174
299
|
}
|
|
300
|
+
|
|
301
|
+
// src/ws-server.ts
|
|
175
302
|
function endpointOf(route, paths) {
|
|
176
303
|
const own = paths.socket === "/" ? "" : paths.socket;
|
|
177
304
|
const at = paths.endpoint === "/" ? "" : paths.endpoint;
|
|
@@ -183,7 +310,8 @@ function serverOptions(yogaAt, paths) {
|
|
|
183
310
|
return {
|
|
184
311
|
execute: (args) => of(args).execute(args),
|
|
185
312
|
subscribe: (args) => of(args).subscribe(args),
|
|
186
|
-
|
|
313
|
+
...following(),
|
|
314
|
+
async onSubscribe(context, id, params) {
|
|
187
315
|
const { ctx, request } = context.extra;
|
|
188
316
|
const initial = {
|
|
189
317
|
...serverContext(ctx),
|
|
@@ -198,6 +326,7 @@ function serverOptions(yogaAt, paths) {
|
|
|
198
326
|
} catch (error) {
|
|
199
327
|
return [error];
|
|
200
328
|
}
|
|
329
|
+
context.extra.operations.begin(id, document, params.operationName);
|
|
201
330
|
const errors = validate(schema, document);
|
|
202
331
|
if (errors.length > 0)
|
|
203
332
|
return errors;
|
|
@@ -213,6 +342,18 @@ function serverOptions(yogaAt, paths) {
|
|
|
213
342
|
}
|
|
214
343
|
};
|
|
215
344
|
}
|
|
345
|
+
|
|
346
|
+
// src/ws.ts
|
|
347
|
+
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";
|
|
348
|
+
function loader() {
|
|
349
|
+
let loading;
|
|
350
|
+
return () => {
|
|
351
|
+
loading ??= import("graphql-ws").catch((cause) => {
|
|
352
|
+
throw new Error(MISSING_PEER, { cause });
|
|
353
|
+
});
|
|
354
|
+
return loading;
|
|
355
|
+
};
|
|
356
|
+
}
|
|
216
357
|
function chosen(module, request) {
|
|
217
358
|
const offered = request.headers.get("sec-websocket-protocol") ?? "";
|
|
218
359
|
return module.handleProtocols(offered) || "";
|
|
@@ -251,7 +392,10 @@ function graphqlSocket(yogaAt, endpoint, options) {
|
|
|
251
392
|
const handlers = {
|
|
252
393
|
open(socket) {
|
|
253
394
|
const raw = socket.raw;
|
|
254
|
-
const client = {
|
|
395
|
+
const client = {
|
|
396
|
+
gone: new AbortController,
|
|
397
|
+
operations: new SocketOperations(socket.data)
|
|
398
|
+
};
|
|
255
399
|
clients.set(raw, client);
|
|
256
400
|
const graphqlWsServer = server;
|
|
257
401
|
client.closed = graphqlWsServer.opened({
|
|
@@ -266,7 +410,8 @@ function graphqlSocket(yogaAt, endpoint, options) {
|
|
|
266
410
|
}
|
|
267
411
|
}, {
|
|
268
412
|
ctx: socket.data,
|
|
269
|
-
request: operationRequest(socket.data.request, client.gone.signal)
|
|
413
|
+
request: operationRequest(socket.data.request, client.gone.signal),
|
|
414
|
+
operations: client.operations
|
|
270
415
|
});
|
|
271
416
|
if (keepAlive !== false) {
|
|
272
417
|
client.pings = setInterval(() => raw.ping(), keepAlive);
|
|
@@ -284,6 +429,7 @@ function graphqlSocket(yogaAt, endpoint, options) {
|
|
|
284
429
|
clients.delete(socket.raw);
|
|
285
430
|
client.gone.abort();
|
|
286
431
|
await client.closed?.(code, reason);
|
|
432
|
+
client.operations.closed();
|
|
287
433
|
}
|
|
288
434
|
};
|
|
289
435
|
return { path: paths.socket, middleware: graphqlWs, handlers };
|
|
@@ -303,6 +449,7 @@ function graphql(app, options) {
|
|
|
303
449
|
const page = graphiql ?? true;
|
|
304
450
|
const yogaAt = yogaServers({
|
|
305
451
|
...yogaOptions,
|
|
452
|
+
plugins: [...yogaOptions.plugins ?? [], reportsOperations()],
|
|
306
453
|
cors,
|
|
307
454
|
graphiql: ide === undefined ? (_request, context) => isDev(context) && page : ide === "graphiql" ? page : false
|
|
308
455
|
});
|
|
@@ -322,5 +469,5 @@ export {
|
|
|
322
469
|
renderSandbox
|
|
323
470
|
};
|
|
324
471
|
|
|
325
|
-
//# debugId=
|
|
472
|
+
//# debugId=3B6C1E44EF9B615164756E2164756E21
|
|
326
473
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1,13 +1,17 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../src/graphql.ts", "../src/handler.ts", "../src/sandbox.ts", "../src/ws.ts"],
|
|
3
|
+
"sources": ["../src/graphql.ts", "../src/handler.ts", "../src/body-refusal.ts", "../src/sandbox.ts", "../src/operation.ts", "../src/ws-operations.ts", "../src/ws-server.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';\nimport { type GraphQLWsOptions, graphqlSocket } from './ws';\n\n/** The parts of a route's context Yoga owns, or that mean nothing to a resolver. */\ntype RouteOnly =\n\t| 'params'\n\t| 'query'\n\t| 'headers'\n\t| 'cookies'\n\t| 'body'\n\t| 'reply'\n\t| 'redirect';\n\n/**\n * What alxia hands Yoga for each request: the context its middlewares built —\n * `user`, `db`, `log`… — with `request`, `url`, `ip` and `set`, through\n * which a resolver sets a cookie or a header on the response.\n */\nexport type ServerContext<Ctx> = Omit<BaseContext & Ctx, RouteOnly>;\n\n/**\n * What an operation over WebSocket adds to its context (`ws` on): the\n * `connectionParams` the client sent when it connected. `undefined` over\n * HTTP, and for a client that sent none.\n */\nexport interface GraphQLWsContext {\n\treadonly connectionParams?: Readonly<Record<string, unknown>>;\n}\n\n/**\n * What a resolver reads as its context: Yoga's own, the app's, what\n * the `context` option adds, and over WebSocket the `connectionParams`. Type a schema with it:\n *\n * ```ts\n * const base = alxia().use(bearer({ jwt }));\n * const schema = createSchema<GraphQLContext<typeof base>>({ ... });\n * ```\n */\nexport type GraphQLContext<App, UserContext = Empty> = App extends {\n\treadonly '~context': infer Ctx;\n}\n\t? YogaInitialContext & ServerContext<Ctx> & GraphQLWsContext & UserContext\n\t: // Not `never`: a schema typed with `never` would let every resolver\n\t\t// read anything until `graphql()` refused it.\n\t\t{\n\t\t\treadonly '~error': 'GraphQLContext needs the type of an app: GraphQLContext<typeof app>';\n\t\t};\n\nexport interface GraphQLOptions<\n\tServerCtx extends YogaContext,\n\tUserCtx extends YogaContext,\n\tPath extends RoutePath,\n\tSchemaCtx = unknown,\n> extends Omit<\n\t\tYogaServerOptions<ServerCtx, UserCtx>,\n\t\t'graphqlEndpoint' | 'cors' | 'schema' | 'graphiql'\n\t> {\n\t/**\n\t * What a browser gets at the endpoint: Yoga's GraphiQL, Apollo Sandbox,\n\t * or nothing. By default, GraphiQL in the serving app's dev alone\n\t * (`isDev`: `alxia({ dev })`, else `NODE_ENV=development`), nothing\n\t * otherwise; `graphiql` or `apollo-sandbox` serves one everywhere.\n\t */\n\treadonly ide?: 'graphiql' | 'apollo-sandbox' | false;\n\t/** GraphiQL's options, Yoga's own, when `ide` is `graphiql`. */\n\treadonly graphiql?: Exclude<\n\t\tYogaServerOptions<ServerCtx, UserCtx>['graphiql'],\n\t\tboolean\n\t>;\n\t/** Apollo Sandbox's options, when `ide` is `apollo-sandbox`. */\n\treadonly sandbox?: SandboxOptions;\n\t/**\n\t * The schema, from Yoga's `createSchema`, Pothos, or any tool that types\n\t * its context. Its context must be one the app builds: a resolver that\n\t * reads `user` behind no middleware that adds one is a compile error.\n\t */\n\treadonly schema: GraphQLSchemaWithContext<SchemaCtx>;\n\t/** Where the endpoint is, under the app's prefix. `/graphql` by default. */\n\treadonly path?: Path;\n\t/**\n\t * Yoga's own CORS. Off by default: `@alxia/cors` answers for the whole\n\t * app, this endpoint included.\n\t */\n\treadonly cors?: YogaServerOptions<ServerCtx, UserCtx>['cors'];\n\t/**\n\t * GraphQL over WebSocket too, the `graphql-transport-ws` protocol of\n\t * Apollo Client's and urql's default link, served by the optional peer\n\t * `graphql-ws` at the endpoint's path: `true`, or where and how often it\n\t * pings. Off by default: subscriptions are served over server-sent\n\t * events, which stay served beside it.\n\t */\n\treadonly ws?: boolean | GraphQLWsOptions;\n}\n\n/**\n * The check Yoga's types leave out: the context the app builds must hold\n * what the schema's resolvers read. A mistake comes back as a `schema`\n * whose type is the message.\n */\ntype ProvidesContext<Provided, Required> = Provided extends Required\n\t? unknown\n\t: {\n\t\t\treadonly schema: `the schema's resolvers read a context the app does not build: missing ${Exclude<\n\t\t\t\tkeyof Required,\n\t\t\t\tkeyof Provided\n\t\t\t> &\n\t\t\t\tstring}`;\n\t\t};\n\n/**\n * A GraphQL endpoint on `app`, served by [GraphQL Yoga](https://the-guild.dev/graphql/yoga-server):\n * `GET` and `POST` at `path`, behind every middleware given to `use` on `app`\n * before it. A guard before it guards it; what the middlewares added is in each\n * resolver's context, typed. Yoga's options pass through — `plugins`\n * (Envelop's and Yoga's), `graphiql`, `maskedErrors`, `batching`… —\n * and subscriptions are served over server-sent events, and over\n * WebSocket too with `ws: true`.\n *\n * ```ts\n * const app = alxia()\n * .use(bearer({ jwt }))\n * .plugin((app) => graphql(app, { schema, plugins: [useDepthLimit()] }));\n * ```\n */\nexport function graphql<\n\tCtx extends object,\n\tPrefix extends string,\n\tSchemaCtx,\n\tUserCtx extends YogaContext = Empty,\n\tconst Path extends RoutePath = '/graphql',\n>(\n\tapp: Alxia<Ctx, Prefix>,\n\toptions: GraphQLOptions<ServerContext<Ctx>, UserCtx, Path, SchemaCtx> &\n\t\tProvidesContext<\n\t\t\tYogaInitialContext & ServerContext<Ctx> & UserCtx,\n\t\t\tSchemaCtx\n\t\t>,\n): Alxia<Ctx, Prefix> {\n\tconst {\n\t\tpath = '/graphql' as Path,\n\t\tcors = false,\n\t\tide,\n\t\tgraphiql,\n\t\tsandbox,\n\t\tws = false,\n\t\t...yogaOptions\n\t} = options;\n\tconst page = graphiql ?? true;\n\tconst yogaAt = yogaServers<UserCtx>({\n\t\t...(yogaOptions as YogaServerOptions<YogaContext, UserCtx>),\n\t\tcors,\n\t\tgraphiql: (ide === undefined\n\t\t\t? (_request: Request, context: object) => isDev(context) && page\n\t\t\t: ide === 'graphiql'\n\t\t\t\t? page\n\t\t\t\t: false) as YogaServerOptions<YogaContext, UserCtx>['graphiql'],\n\t});\n\tconst handler = graphqlHandler(\n\t\tyogaAt,\n\t\tide === 'apollo-sandbox' ? (sandbox ?? {}) : false,\n\t);\n\n\tconst route = app as unknown as {\n\t\tget(path: string, handler: unknown): unknown;\n\t\tpost(path: string, handler: unknown): unknown;\n\t\tws(path: string, ...rest: unknown[]): unknown;\n\t};\n\troute.get(path, handler);\n\troute.post(path, handler);\n\tif (ws !== false) {\n\t\tconst socket = graphqlSocket(yogaAt, path, ws === true ? {} : ws);\n\t\troute.ws(socket.path, socket.middleware, socket.handlers);\n\t}\n\treturn app as never;\n}\n",
|
|
6
|
-
"/**\n * The endpoint behind `graphql()`: one Yoga per path it is served at, and\n * the route handler that hands each request to it.\n */\nimport { type BaseContext, type StatusCode, shutdownSignal } from '@alxia/core';\nimport {\n\tcreateYoga,\n\ttype YogaServerInstance,\n\ttype YogaServerOptions,\n} from 'graphql-yoga';\nimport { renderSandbox, SANDBOX_POLICY, type SandboxOptions } from './sandbox';\n\nexport type YogaContext = Record<string, any>;\n\n/** Where Yoga's GraphiQL page loads its files from: one pinned version on unpkg. */\nconst GRAPHIQL_FILES =\n\t/https:\\/\\/unpkg\\.com\\/@graphql-yoga\\/graphiql@[\\w.-]+\\//;\n\n/**\n * What GraphiQL's page may load: its scripts, styles and Monaco's\n * workers from the exact version of `@graphql-yoga/graphiql` the page\n * names, fetched and run as blobs; queries to this server alone; framed\n * by no one. A page that names none (a `renderGraphiQL` of the app's own)\n * gets this server alone. `@alxia/secure-headers` keeps a policy a\n * response already has.\n */\nexport function graphiqlPolicy(html: string): string {\n\tconst files = html.match(GRAPHIQL_FILES)?.[0] ?? '';\n\tconst from = files === '' ? '' : ` ${files}`;\n\treturn [\n\t\t\"default-src 'self'\",\n\t\t`script-src 'self' 'unsafe-inline'${from}`,\n\t\t`style-src 'self' 'unsafe-inline'${from}`,\n\t\t\"img-src 'self' data: https:\",\n\t\t`font-src 'self' data:${from}`,\n\t\t\"worker-src 'self' blob:\",\n\t\t`connect-src 'self'${from}`,\n\t\t\"frame-ancestors 'none'\",\n\t].join('; ');\n}\n\n/**\n * The Yoga serving `endpoint`, created on first use. One per path: a plugin\n * mounted under a prefix serves the same routes at a longer path, and\n * GraphiQL must ask that one.\n */\nexport function yogaServers<UserCtx extends YogaContext>(\n\toptions: Omit<YogaServerOptions<YogaContext, UserCtx>, 'graphqlEndpoint'>,\n): (endpoint: string) => YogaServerInstance<YogaContext, UserCtx> {\n\tconst servers = new Map<string, YogaServerInstance<YogaContext, UserCtx>>();\n\treturn (endpoint) => {\n\t\tlet yoga = servers.get(endpoint);\n\t\tif (yoga === undefined) {\n\t\t\tyoga = createYoga<YogaContext, UserCtx>({\n\t\t\t\t...options,\n\t\t\t\tgraphqlEndpoint: endpoint,\n\t\t\t});\n\t\t\tservers.set(endpoint, yoga);\n\t\t}\n\t\treturn yoga;\n\t};\n}\n\n/**\n * What Yoga is handed as its server context: the route's context — the\n * middlewares' work — minus what a resolver has no use for.\n */\nexport function serverContext(\n\tctx: Record<string, unknown>,\n): Record<string, unknown> {\n\tconst {\n\t\tparams: _params,\n\t\tquery: _query,\n\t\theaders: _headers,\n\t\tcookies: _cookies,\n\t\tbody: _body,\n\t\treply: _reply,\n\t\tredirect: _redirect,\n\t\t...server\n\t} = ctx;\n\treturn server;\n}\n\n/**\n * The handler of the endpoint's `GET` and `POST`: Apollo Sandbox's page to\n * a browser when `sandbox` is not `false`, else the request to Yoga, with\n * the route's context — the middlewares' work, minus what a resolver has no use\n * for — as Yoga's server context.\n */\nexport function graphqlHandler<UserCtx extends YogaContext>(\n\tyogaAt: (endpoint: string) => YogaServerInstance<YogaContext, UserCtx>,\n\tsandbox: SandboxOptions | false,\n) {\n\t// A handler's context: its route is the one it was declared at. Named\n\t// `graphql`, the name the route table `listen` prints in dev shows.\n\treturn async function graphql(\n\t\tctx: Record<string, unknown> & BaseContext & { readonly route: string },\n\t) {\n\t\tconst { reply } = ctx;\n\t\tconst server = serverContext(ctx);\n\t\tif (\n\t\t\tsandbox !== false &&\n\t\t\tctx.request.method === 'GET' &&\n\t\t\tctx.request.headers.get('accept')?.includes('text/html') &&\n\t\t\t!ctx.url.searchParams.has('query')\n\t\t) {\n\t\t\t// A path: the page resolves it against its own address, so behind\n\t\t\t// a TLS proxy the Sandbox asks over https, as the browser did.\n\t\t\treturn reply(200, renderSandbox(ctx.route, sandbox), {\n\t\t\t\theaders: {\n\t\t\t\t\t'content-type': 'text/html;charset=utf-8',\n\t\t\t\t\t'content-security-policy': SANDBOX_POLICY,\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\t\tconst
|
|
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 { watchBody, withoutOriginalError } from './body-refusal';\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 watched = watchBody(ctx.request);\n\t\tconst answered = await yogaAt(ctx.route).fetch(watched.request, server);\n\t\t// Yoga answered a body past `bodyLimit` with its own 400: core's 413\n\t\t// is the answer, in the app's format.\n\t\tconst refusal = watched.refusal();\n\t\tif (refusal !== undefined) {\n\t\t\tvoid answered.body?.cancel();\n\t\t\tthrow refusal;\n\t\t}\n\t\tconst response = await withoutOriginalError(answered);\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 * Yoga reads the request body itself, and turns any failure of the read\n * into its own 400. A body past core's `bodyLimit` fails the read with a\n * `ContentTooLargeError`; `watchBody` keeps that error, so the handler\n * can throw it again once Yoga has answered, and the app's own boundary\n * answers the 413 in its error format, leaking nothing of Yoga's.\n */\nimport type { ContentTooLargeError } from '@alxia/core';\n\n/**\n * By its name and its limit, not `instanceof`: the copy of core that\n * limited the body may not be the one this package resolves.\n */\nfunction isTooLarge(error: unknown): error is ContentTooLargeError {\n\treturn (\n\t\terror instanceof Error &&\n\t\terror.name === 'ContentTooLargeError' &&\n\t\ttypeof (error as { limit?: unknown }).limit === 'number'\n\t);\n}\n\nexport interface WatchedRequest {\n\t/** The request to hand to Yoga: the same, its body watched. */\n\treadonly request: Request;\n\t/** The `ContentTooLargeError` the body's read failed with, if it did. */\n\trefusal(): ContentTooLargeError | undefined;\n}\n\n/** `request` with its body's failure recorded; a request with no body is as it is. */\nexport function watchBody(request: Request): WatchedRequest {\n\tconst source = request.body;\n\tif (source === null || request.bodyUsed || source.locked) {\n\t\treturn { request, refusal: () => undefined };\n\t}\n\tlet refused: ContentTooLargeError | undefined;\n\tconst reader = source.getReader();\n\tconst body = new ReadableStream<Uint8Array>({\n\t\tasync pull(controller) {\n\t\t\ttry {\n\t\t\t\tconst { value, done } = await reader.read();\n\t\t\t\tif (done) controller.close();\n\t\t\t\telse controller.enqueue(value);\n\t\t\t} catch (error) {\n\t\t\t\tif (isTooLarge(error)) refused = error;\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t},\n\t\tcancel: (reason) => reader.cancel(reason),\n\t});\n\treturn {\n\t\trequest: new Request(request, { body, duplex: 'half' } as RequestInit),\n\t\trefusal: () => refused,\n\t};\n}\n\ninterface Failure {\n\terrors?: { extensions?: Record<string, unknown> }[];\n}\n\n/**\n * Yoga's 400 for a request it cannot read — a body that is not JSON, a\n * query string that is not valid — carries the parser's own error as\n * `extensions.originalError`. A client reads the message and the code, not\n * what a parser said: the response without it, any other as it is.\n */\nexport async function withoutOriginalError(\n\tresponse: Response,\n): Promise<Response> {\n\tconst type = response.headers.get('content-type') ?? '';\n\tif (\n\t\tresponse.status !== 400 ||\n\t\t!/^application\\/(?:[\\w.-]+\\+)?json/.test(type)\n\t) {\n\t\treturn response;\n\t}\n\tconst text = await response.text();\n\tlet failure: Failure;\n\ttry {\n\t\tfailure = JSON.parse(text) as Failure;\n\t} catch {\n\t\treturn new Response(text, response);\n\t}\n\tfor (const error of failure.errors ?? []) {\n\t\tdelete error.extensions?.['originalError'];\n\t}\n\tconst headers = new Headers(response.headers);\n\theaders.delete('content-length');\n\treturn new Response(JSON.stringify(failure), { status: 400, headers });\n}\n",
|
|
7
8
|
"/**\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 *
|
|
9
|
+
"/**\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",
|
|
10
|
+
"/**\n * Each operation of a socket, from its `subscribe` to its end, told to the\n * observers around the socket's upgrade — `@alxia/logger`,\n * `@alxia/telemetry` — through core's `startOperation`: its type and name,\n * then whether it ended with errors.\n */\nimport { type OperationOutcome, startOperation } from '@alxia/core';\nimport { type DocumentNode, getOperationAST } from 'graphql';\nimport type { ServerOptions } from 'graphql-ws';\n\n/** An operation started, until it ends. */\ninterface Open {\n\treadonly end: (outcome: OperationOutcome) => void;\n\toutcome: OperationOutcome;\n}\n\n/** The operations of one socket, by their `graphql-ws` id. */\nexport class SocketOperations {\n\treadonly #ctx: object;\n\treadonly #open = new Map<string, Open>();\n\n\t/** `ctx`: the socket's context, which carries its upgrade's observers. */\n\tconstructor(ctx: object) {\n\t\tthis.#ctx = ctx;\n\t}\n\n\t/** The operation `id` starts: the one of `document` that `operationName` names. */\n\tbegin(\n\t\tid: string,\n\t\tdocument: DocumentNode,\n\t\toperationName: string | null | undefined,\n\t): void {\n\t\t// graphql-ws closes a socket that reuses an open id; end it all the same.\n\t\tthis.end(id);\n\t\tconst operation = getOperationAST(document, operationName);\n\t\tif (operation === undefined || operation === null) return;\n\t\tconst end = startOperation(this.#ctx, {\n\t\t\ttype: operation.operation,\n\t\t\tname: operation.name?.value,\n\t\t});\n\t\tthis.#open.set(id, { end, outcome: 'ok' });\n\t}\n\n\t/** The operation `id` answered with errors: a result's `errors`, or an error message. */\n\tfailed(id: string): void {\n\t\tconst open = this.#open.get(id);\n\t\tif (open !== undefined) open.outcome = 'errors';\n\t}\n\n\t/** The operation `id` ended: completed, stopped by its client, or failed. */\n\tend(id: string): void {\n\t\tconst open = this.#open.get(id);\n\t\tif (open === undefined) return;\n\t\tthis.#open.delete(id);\n\t\topen.end(open.outcome);\n\t}\n\n\t/**\n\t * The socket closed: an operation still open then is one whose run threw,\n\t * which `graphql-ws` answers by closing the socket, and ends with errors.\n\t */\n\tclosed(): void {\n\t\tfor (const id of [...this.#open.keys()]) {\n\t\t\tthis.failed(id);\n\t\t\tthis.end(id);\n\t\t}\n\t}\n}\n\n/** What `graphql-ws` keeps of each socket for its hooks: its operations. */\ninterface Followed {\n\treadonly operations: SocketOperations;\n}\n\n/**\n * `graphql-ws`'s hooks that follow each operation: a result with errors\n * marks it, an error message ends it, and so does its completion — sent,\n * stopped by the client, or cut by the socket's close.\n */\nexport function following<E extends Followed>(): Pick<\n\tServerOptions<Record<string, unknown> | undefined, E>,\n\t'onNext' | 'onError' | 'onComplete'\n> {\n\treturn {\n\t\tonNext({ extra }, id, _payload, _args, result) {\n\t\t\tif (result.errors !== undefined && result.errors.length > 0) {\n\t\t\t\textra.operations.failed(id);\n\t\t\t}\n\t\t},\n\t\tonError({ extra }, id) {\n\t\t\textra.operations.failed(id);\n\t\t\textra.operations.end(id);\n\t\t},\n\t\tonComplete({ extra }, id) {\n\t\t\textra.operations.end(id);\n\t\t},\n\t};\n}\n",
|
|
11
|
+
"/**\n * `graphql-ws`'s server options for a socket route: each operation parsed,\n * validated, executed and subscribed through the endpoint's Yoga, and\n * followed to its end for the observers around the upgrade.\n */\nimport type { BaseContext } from '@alxia/core';\nimport type { ServerOptions, SubscribePayload } from 'graphql-ws';\nimport type { YogaInitialContext, YogaServerInstance } from 'graphql-yoga';\nimport { serverContext, type YogaContext } from './handler';\nimport { following, type SocketOperations } from './ws-operations';\n\n/**\n * What `graphql-ws` keeps of each socket: the context its upgrade built,\n * the request each of its operations reads as Yoga's `request`, and its\n * operations, told to the upgrade's observers.\n */\nexport interface Extra {\n\treadonly ctx: Record<string, unknown> & BaseContext;\n\treadonly request: Request;\n\treadonly operations: SocketOperations;\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. */\nexport interface 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 */\nexport function 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\t...following<Extra>(),\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\tcontext.extra.operations.begin(id, document, params.operationName);\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",
|
|
12
|
+
"/**\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 is told to the observers around the upgrade\n * (`ws-operations.ts`, through `ws-server.ts`'s options), and the app's shutdown closes the sockets with 1001.\n */\nimport type { BaseContext, NextFunction, RoutePath, Socket } from '@alxia/core';\nimport type { Server } from 'graphql-ws';\nimport type { YogaServerInstance } from 'graphql-yoga';\nimport type { YogaContext } from './handler';\nimport { SocketOperations } from './ws-operations';\nimport { type Extra, type Paths, serverOptions } from './ws-server';\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\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 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\treadonly operations: SocketOperations;\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 = {\n\t\t\t\tgone: new AbortController(),\n\t\t\t\toperations: new SocketOperations(socket.data),\n\t\t\t};\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\toperations: client.operations,\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\tclient.operations.closed();\n\t\t},\n\t};\n\treturn { path: paths.socket, middleware: graphqlWs, handlers };\n}\n"
|
|
9
13
|
],
|
|
10
|
-
"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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O,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;",
|
|
15
|
+
"debugId": "3B6C1E44EF9B615164756E2164756E21",
|
|
12
16
|
"names": []
|
|
13
17
|
}
|
|
@@ -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"}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { type DocumentNode } from 'graphql';
|
|
2
|
+
import type { ServerOptions } from 'graphql-ws';
|
|
3
|
+
/** The operations of one socket, by their `graphql-ws` id. */
|
|
4
|
+
export declare class SocketOperations {
|
|
5
|
+
#private;
|
|
6
|
+
/** `ctx`: the socket's context, which carries its upgrade's observers. */
|
|
7
|
+
constructor(ctx: object);
|
|
8
|
+
/** The operation `id` starts: the one of `document` that `operationName` names. */
|
|
9
|
+
begin(id: string, document: DocumentNode, operationName: string | null | undefined): void;
|
|
10
|
+
/** The operation `id` answered with errors: a result's `errors`, or an error message. */
|
|
11
|
+
failed(id: string): void;
|
|
12
|
+
/** The operation `id` ended: completed, stopped by its client, or failed. */
|
|
13
|
+
end(id: string): void;
|
|
14
|
+
/**
|
|
15
|
+
* The socket closed: an operation still open then is one whose run threw,
|
|
16
|
+
* which `graphql-ws` answers by closing the socket, and ends with errors.
|
|
17
|
+
*/
|
|
18
|
+
closed(): void;
|
|
19
|
+
}
|
|
20
|
+
/** What `graphql-ws` keeps of each socket for its hooks: its operations. */
|
|
21
|
+
interface Followed {
|
|
22
|
+
readonly operations: SocketOperations;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* `graphql-ws`'s hooks that follow each operation: a result with errors
|
|
26
|
+
* marks it, an error message ends it, and so does its completion — sent,
|
|
27
|
+
* stopped by the client, or cut by the socket's close.
|
|
28
|
+
*/
|
|
29
|
+
export declare function following<E extends Followed>(): Pick<ServerOptions<Record<string, unknown> | undefined, E>, 'onNext' | 'onError' | 'onComplete'>;
|
|
30
|
+
export {};
|
|
31
|
+
//# sourceMappingURL=ws-operations.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ws-operations.d.ts","sourceRoot":"","sources":["../src/ws-operations.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,KAAK,YAAY,EAAmB,MAAM,SAAS,CAAC;AAC7D,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAQhD,8DAA8D;AAC9D,qBAAa,gBAAgB;;IAI5B,0EAA0E;gBAC9D,GAAG,EAAE,MAAM;IAIvB,mFAAmF;IACnF,KAAK,CACJ,EAAE,EAAE,MAAM,EACV,QAAQ,EAAE,YAAY,EACtB,aAAa,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,GACtC,IAAI;IAYP,yFAAyF;IACzF,MAAM,CAAC,EAAE,EAAE,MAAM,GAAG,IAAI;IAKxB,6EAA6E;IAC7E,GAAG,CAAC,EAAE,EAAE,MAAM,GAAG,IAAI;IAOrB;;;OAGG;IACH,MAAM,IAAI,IAAI;CAMd;AAED,4EAA4E;AAC5E,UAAU,QAAQ;IACjB,QAAQ,CAAC,UAAU,EAAE,gBAAgB,CAAC;CACtC;AAED;;;;GAIG;AACH,wBAAgB,SAAS,CAAC,CAAC,SAAS,QAAQ,KAAK,IAAI,CACpD,aAAa,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,SAAS,EAAE,CAAC,CAAC,EACrD,QAAQ,GAAG,SAAS,GAAG,YAAY,CACnC,CAeA"}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `graphql-ws`'s server options for a socket route: each operation parsed,
|
|
3
|
+
* validated, executed and subscribed through the endpoint's Yoga, and
|
|
4
|
+
* followed to its end for the observers around the upgrade.
|
|
5
|
+
*/
|
|
6
|
+
import type { BaseContext } from '@alxia/core';
|
|
7
|
+
import type { ServerOptions } from 'graphql-ws';
|
|
8
|
+
import type { YogaServerInstance } from 'graphql-yoga';
|
|
9
|
+
import { type YogaContext } from './handler';
|
|
10
|
+
import { type SocketOperations } from './ws-operations';
|
|
11
|
+
/**
|
|
12
|
+
* What `graphql-ws` keeps of each socket: the context its upgrade built,
|
|
13
|
+
* the request each of its operations reads as Yoga's `request`, and its
|
|
14
|
+
* operations, told to the upgrade's observers.
|
|
15
|
+
*/
|
|
16
|
+
export interface Extra {
|
|
17
|
+
readonly ctx: Record<string, unknown> & BaseContext;
|
|
18
|
+
readonly request: Request;
|
|
19
|
+
readonly operations: SocketOperations;
|
|
20
|
+
}
|
|
21
|
+
/** Where the socket route is, and the endpoint whose Yoga it runs. */
|
|
22
|
+
export interface Paths {
|
|
23
|
+
readonly endpoint: string;
|
|
24
|
+
readonly socket: string;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* `graphql-ws`'s options: each operation parsed, validated, executed and
|
|
28
|
+
* subscribed through Yoga's envelop, with the context the upgrade built,
|
|
29
|
+
* the operation's `params` and the client's `connectionParams`.
|
|
30
|
+
*/
|
|
31
|
+
export declare function serverOptions<UserCtx extends YogaContext>(yogaAt: (endpoint: string) => YogaServerInstance<YogaContext, UserCtx>, paths: Paths): ServerOptions<Record<string, unknown> | undefined, Extra>;
|
|
32
|
+
//# sourceMappingURL=ws-server.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ws-server.d.ts","sourceRoot":"","sources":["../src/ws-server.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC/C,OAAO,KAAK,EAAE,aAAa,EAAoB,MAAM,YAAY,CAAC;AAClE,OAAO,KAAK,EAAsB,kBAAkB,EAAE,MAAM,cAAc,CAAC;AAC3E,OAAO,EAAiB,KAAK,WAAW,EAAE,MAAM,WAAW,CAAC;AAC5D,OAAO,EAAa,KAAK,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AAEnE;;;;GAIG;AACH,MAAM,WAAW,KAAK;IACrB,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,WAAW,CAAC;IACpD,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC;IAC1B,QAAQ,CAAC,UAAU,EAAE,gBAAgB,CAAC;CACtC;AAQD,sEAAsE;AACtE,MAAM,WAAW,KAAK;IACrB,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;CACxB;AAcD;;;;GAIG;AACH,wBAAgB,aAAa,CAAC,OAAO,SAAS,WAAW,EACxD,MAAM,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,kBAAkB,CAAC,WAAW,EAAE,OAAO,CAAC,EACtE,KAAK,EAAE,KAAK,GACV,aAAa,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,SAAS,EAAE,KAAK,CAAC,CAwC3D"}
|
package/dist/ws.d.ts
CHANGED
|
@@ -2,11 +2,12 @@
|
|
|
2
2
|
* GraphQL over WebSocket, the `graphql-transport-ws` protocol of
|
|
3
3
|
* `graphql-ws`, on a socket route of the app: the upgrade runs the app's
|
|
4
4
|
* middlewares, each operation runs through Yoga's envelop — its plugins,
|
|
5
|
-
* its `context` — and
|
|
5
|
+
* its `context` — and is told to the observers around the upgrade
|
|
6
|
+
* (`ws-operations.ts`, through `ws-server.ts`'s options), and the app's shutdown closes the sockets with 1001.
|
|
6
7
|
*/
|
|
7
8
|
import type { BaseContext, NextFunction, RoutePath, Socket } from '@alxia/core';
|
|
8
9
|
import type { YogaServerInstance } from 'graphql-yoga';
|
|
9
|
-
import {
|
|
10
|
+
import type { YogaContext } from './handler';
|
|
10
11
|
/** `graphql(app, { ws })`: GraphQL over WebSocket beside the HTTP endpoint. */
|
|
11
12
|
export interface GraphQLWsOptions {
|
|
12
13
|
/**
|
package/dist/ws.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ws.d.ts","sourceRoot":"","sources":["../src/ws.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"ws.d.ts","sourceRoot":"","sources":["../src/ws.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,KAAK,EAAE,WAAW,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAEhF,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AACvD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,WAAW,CAAC;AAI7C,+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;AAID,2EAA2E;AAC3E,eAAO,MAAM,YAAY,qJAC0H,CAAC;AAoDpJ;;;;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;;;yFA0Cd,OAAO;oFAOZ,MAAM,UAAU,MAAM;;EAWhE"}
|
package/docs/README.md
CHANGED
|
@@ -12,6 +12,7 @@ a realistic example for each.
|
|
|
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
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 |
|
|
15
|
+
| [Harden it for production](guide/production.md) | putting a GraphQL API on the internet: rate limiting the endpoint, depth limits, introspection off outside development, masked errors and the errors a client may read, a body limit, CSRF for a cookie session, persisted operations |
|
|
15
16
|
| [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'` |
|
|
16
17
|
| [Troubleshooting](troubleshooting.md) | something went wrong and you have the message |
|
|
17
18
|
| [Roadmap](roadmap.md) | wondering what is coming, and what is not planned |
|
package/docs/guide/endpoint.md
CHANGED
|
@@ -157,6 +157,39 @@ POST {} → 200 {"errors":[{"message":"Must provid
|
|
|
157
157
|
Both methods answer a body to read as GraphQL, whatever its status, and
|
|
158
158
|
the replies of the middlewares before them — a guard's `401`, say.
|
|
159
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`, each operation on a socket is a line and a span of its
|
|
190
|
+
own, told to the observers around the upgrade
|
|
191
|
+
([WebSocket guide](websockets.md#logging-and-tracing)).
|
|
192
|
+
|
|
160
193
|
## Errors, health and shutdown
|
|
161
194
|
|
|
162
195
|
**GraphQL errors stay GraphQL's.** A resolver that throws, a query that
|
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
# Harden a GraphQL API for production
|
|
2
|
+
|
|
3
|
+
A GraphQL endpoint mounted as in [the endpoint guide](endpoint.md) works. What a GraphQL API exposed to the internet also
|
|
4
|
+
needs is not in a schema: one request can ask for a great deal, nothing says
|
|
5
|
+
who may ask how often, and the defaults that help a developer help an
|
|
6
|
+
attacker. Seven points, each a few lines, from the
|
|
7
|
+
[GraphQL API recipe](https://github.com/softistx/alxia/blob/develop/docs/recipes/graphql-api.md),
|
|
8
|
+
whose files they are (`src/context.ts` holds the base, which each app builds on with `base.fork()`). Add the packages the snippets use:
|
|
9
|
+
|
|
10
|
+
```sh
|
|
11
|
+
bun add @alxia/rate-limit @envelop/depth-limit @graphql-yoga/plugin-csrf-prevention @graphql-yoga/plugin-persisted-operations
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
## Rate limit the endpoint
|
|
15
|
+
|
|
16
|
+
`@alxia/rate-limit` goes to `use` before the endpoint, and counts the
|
|
17
|
+
requests to it. Key it by the viewer, so one user's allowance is theirs
|
|
18
|
+
wherever they connect from, and by the client's address for an anonymous
|
|
19
|
+
request. Behind a proxy, the address is the proxy's unless the app reads the
|
|
20
|
+
header it appends to, with core's `forwardedIp`, which never believes the
|
|
21
|
+
entries the client wrote (the recipe's base reads the number of proxies from
|
|
22
|
+
`PROXY_HOPS`):
|
|
23
|
+
|
|
24
|
+
```ts
|
|
25
|
+
import { alxia, forwardedIp } from '@alxia/core';
|
|
26
|
+
|
|
27
|
+
const base = alxia({ ip: forwardedIp({ trusted: 1 }) }); // one proxy in front
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
```ts no-check
|
|
31
|
+
// file: src/limits.ts
|
|
32
|
+
import { rateLimit } from '@alxia/rate-limit';
|
|
33
|
+
import type { UserRecord } from './store';
|
|
34
|
+
|
|
35
|
+
// What is counted: the viewer's id, else the client's address. `undefined`
|
|
36
|
+
// is not counted: with no address (a request made in process, with no
|
|
37
|
+
// socket) there is nothing to count.
|
|
38
|
+
export const keyOf = ({ viewer, ip }: { viewer: UserRecord | null; ip: string | undefined }) =>
|
|
39
|
+
viewer ? `user:${viewer.id}` : ip && `ip:${ip}`;
|
|
40
|
+
|
|
41
|
+
// `max` requests a minute for each key. Past it, a 429 with `Retry-After`.
|
|
42
|
+
export const limitTo = (max: number) =>
|
|
43
|
+
rateLimit<{ viewer: UserRecord | null }>({ limit: max, windowMs: 60_000, key: keyOf });
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
**One HTTP request is not one operation.** A client may send an array of
|
|
47
|
+
operations in a single `POST` when `batching` is on, and a document may ask
|
|
48
|
+
for a hundred fields, or the same expensive field a hundred times under
|
|
49
|
+
aliases. The limit counts the request: keep `batching` off, or give it a
|
|
50
|
+
small `limit`, and bound the cost of one operation with the next point.
|
|
51
|
+
|
|
52
|
+
## Limit depth and complexity
|
|
53
|
+
|
|
54
|
+
`useDepthLimit` from `@envelop/depth-limit` refuses a document nested deeper
|
|
55
|
+
than `maxDepth` before it executes
|
|
56
|
+
([Yoga's plugins](yoga.md#plugins) shows
|
|
57
|
+
it beside the others). Depth is one dimension: aliases, list sizes and
|
|
58
|
+
fragments multiply the work at a depth that is allowed, so give every list
|
|
59
|
+
argument a maximum in the schema, and add a cost plugin when a client
|
|
60
|
+
may write its own documents.
|
|
61
|
+
|
|
62
|
+
```ts
|
|
63
|
+
// file: src/depth.ts
|
|
64
|
+
import { useDepthLimit } from '@envelop/depth-limit';
|
|
65
|
+
|
|
66
|
+
// A document nested deeper than `maxDepth` is refused at validation, before
|
|
67
|
+
// a resolver runs: a 200 with `errors`, GraphQL's own format.
|
|
68
|
+
export const depthLimit = (maxDepth: number) => useDepthLimit({ maxDepth });
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
## Introspection off in production
|
|
72
|
+
|
|
73
|
+
Introspection hands anyone the whole schema, the fields you meant to keep
|
|
74
|
+
quiet included. GraphiQL needs it, so it follows the same switch: on in
|
|
75
|
+
development, off everywhere else. `isDev(context)` is the `ide`'s own test
|
|
76
|
+
(`alxia({ dev })`, else `NODE_ENV=development`), and the plugin adds
|
|
77
|
+
graphql-js's rule that refuses `__schema` and `__type` otherwise.
|
|
78
|
+
|
|
79
|
+
```ts
|
|
80
|
+
// file: src/introspection.ts
|
|
81
|
+
import { isDev } from '@alxia/core';
|
|
82
|
+
import { NoSchemaIntrospectionCustomRule } from 'graphql';
|
|
83
|
+
import type { Plugin } from 'graphql-yoga';
|
|
84
|
+
|
|
85
|
+
export const introspectionOnlyInDev: Plugin = {
|
|
86
|
+
onValidate({ addValidationRule, context }) {
|
|
87
|
+
if (!isDev(context)) addValidationRule(NoSchemaIntrospectionCustomRule);
|
|
88
|
+
},
|
|
89
|
+
};
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
This hides the schema from a client that asks, not from one that guesses
|
|
93
|
+
field names: it is not authorisation. Yoga's error suggestions ("Did you
|
|
94
|
+
mean…") also leak names; the plugin `@escape.tech/graphql-armor-block-field-suggestions`
|
|
95
|
+
removes them.
|
|
96
|
+
|
|
97
|
+
## Masked errors
|
|
98
|
+
|
|
99
|
+
Yoga masks errors by default (`maskedErrors: true`): an `Error` a resolver
|
|
100
|
+
throws reaches the client as `Unexpected error.`, with its message and stack
|
|
101
|
+
kept on the server. Leave it on. To tell the client something, throw a
|
|
102
|
+
`GraphQLError`, whose message is shown, with an `extensions.code` the client
|
|
103
|
+
can switch on; `extensions.http.status` puts the same refusal on the HTTP
|
|
104
|
+
status too (the [layers of an auth error](https://github.com/softistx/alxia/blob/develop/docs/recipes/graphql-api.md#auth-errors-in-three-layers)).
|
|
105
|
+
|
|
106
|
+
```ts
|
|
107
|
+
// file: src/errors.ts
|
|
108
|
+
import { GraphQLError } from 'graphql';
|
|
109
|
+
|
|
110
|
+
// What a client may read: a stable `code`, and a message meant for people.
|
|
111
|
+
export function invalid(message: string, field: string): GraphQLError {
|
|
112
|
+
return new GraphQLError(message, { extensions: { code: 'BAD_USER_INPUT', field } });
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export function notFound(what: string): GraphQLError {
|
|
116
|
+
return new GraphQLError(`No ${what}`, { extensions: { code: 'NOT_FOUND', http: { status: 404 } } });
|
|
117
|
+
}
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
## Cap the body
|
|
121
|
+
|
|
122
|
+
Yoga reads the whole body of a `POST` before it parses it, so a megabyte of
|
|
123
|
+
JSON costs a megabyte of memory. Core's `bodyLimit(bytes)` caps every route
|
|
124
|
+
declared after it: the bytes are counted as they arrive, and reading stops
|
|
125
|
+
at the limit. A query is a few kilobytes: 100 KiB is generous. A mutation
|
|
126
|
+
that takes a file by `multipart` needs a larger limit on a route of its own.
|
|
127
|
+
|
|
128
|
+
Put the call before `graphql(...)`, as in [Together](#together). Yoga reads
|
|
129
|
+
the body itself and would report a body it could not read as `400`, `POST
|
|
130
|
+
body sent invalid JSON.`; `@alxia/graphql` throws core's `ContentTooLargeError`
|
|
131
|
+
again instead, so a client gets the 413 a plain route answers, in the app's
|
|
132
|
+
error format (`application/problem+json` under `errors: 'problem'`), with a
|
|
133
|
+
`Content-Length` or without one (a chunked body). Whatever else Yoga cannot
|
|
134
|
+
parse is still its 400, and its parser's own error is never sent
|
|
135
|
+
(`extensions.originalError` is removed).
|
|
136
|
+
|
|
137
|
+
## CSRF for a cookie-authenticated API
|
|
138
|
+
|
|
139
|
+
A bearer token in a header cannot be sent by another site's form. A
|
|
140
|
+
**cookie** can: a page on another origin may make the browser `POST` the
|
|
141
|
+
cookie to `/graphql`. `SameSite=Lax` on the cookie is the first line (a
|
|
142
|
+
cross-site `POST` does not carry it); two more close the rest.
|
|
143
|
+
|
|
144
|
+
- Yoga's CSRF prevention plugin refuses a request without a custom header
|
|
145
|
+
(`x-graphql-yoga-csrf` by default): a browser cannot add one to a request
|
|
146
|
+
across origins without a CORS preflight, which `@alxia/cors` answers only
|
|
147
|
+
for the origins you named.
|
|
148
|
+
- Require `application/json` on a `POST`, which an HTML form cannot send. Yoga
|
|
149
|
+
also accepts a form-encoded `POST` and a `GET` query, the two a form or a
|
|
150
|
+
link can make, so this is a middleware before the endpoint.
|
|
151
|
+
|
|
152
|
+
```ts
|
|
153
|
+
// file: src/csrf.ts
|
|
154
|
+
import { defineMiddleware, HttpError } from '@alxia/core';
|
|
155
|
+
import { useCSRFPrevention } from '@graphql-yoga/plugin-csrf-prevention';
|
|
156
|
+
|
|
157
|
+
export const csrf = useCSRFPrevention({ requestHeaders: ['x-csrf'] });
|
|
158
|
+
|
|
159
|
+
// A POST that is not JSON is refused with a 415 before Yoga reads it.
|
|
160
|
+
export const jsonOnly = defineMiddleware(async ({ request }, next) => {
|
|
161
|
+
if (request.method === 'POST' && !request.headers.get('content-type')?.startsWith('application/json')) {
|
|
162
|
+
throw new HttpError(415, { error: 'unsupported_media_type' });
|
|
163
|
+
}
|
|
164
|
+
return next();
|
|
165
|
+
});
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
## Persisted operations, briefly
|
|
169
|
+
|
|
170
|
+
A client that sends only the hash of an operation it registered at build
|
|
171
|
+
time cannot send any other: the strongest limit on what it can ask. Yoga's
|
|
172
|
+
[persisted operations plugin](https://the-guild.dev/graphql/yoga-server/docs/features/persisted-operations)
|
|
173
|
+
works as it does elsewhere, since it is a Yoga plugin in the route:
|
|
174
|
+
|
|
175
|
+
```ts
|
|
176
|
+
// file: src/persisted.ts
|
|
177
|
+
import { usePersistedOperations } from '@graphql-yoga/plugin-persisted-operations';
|
|
178
|
+
import type { Plugin } from 'graphql-yoga';
|
|
179
|
+
|
|
180
|
+
// Hash to document: from a file the build wrote, here a literal.
|
|
181
|
+
export const operations = new Map([
|
|
182
|
+
['5f1bb2a0c2a0', '{ notes { text } }'],
|
|
183
|
+
]);
|
|
184
|
+
|
|
185
|
+
// `allowArbitraryOperations: false` refuses any document that was not
|
|
186
|
+
// registered, the point of it. Apollo's `extensions.persistedQuery.sha256Hash`
|
|
187
|
+
// names the operation.
|
|
188
|
+
export const persisted: Plugin = usePersistedOperations({
|
|
189
|
+
allowArbitraryOperations: false,
|
|
190
|
+
getPersistedOperation: (hash) => operations.get(hash) ?? null,
|
|
191
|
+
});
|
|
192
|
+
```
|
|
193
|
+
|
|
194
|
+
## Together
|
|
195
|
+
|
|
196
|
+
```ts no-check
|
|
197
|
+
// file: src/production.ts
|
|
198
|
+
import { logger } from '@alxia/logger';
|
|
199
|
+
import { base } from './context';
|
|
200
|
+
import { csrf, jsonOnly } from './csrf';
|
|
201
|
+
import { depthLimit } from './depth';
|
|
202
|
+
import { introspectionOnlyInDev } from './introspection';
|
|
203
|
+
import { limitTo } from './limits';
|
|
204
|
+
import { createLoaders } from './loaders';
|
|
205
|
+
import { schema } from './schema';
|
|
206
|
+
import { graphql } from '@alxia/graphql';
|
|
207
|
+
|
|
208
|
+
export const production = base.fork()
|
|
209
|
+
.use(logger())
|
|
210
|
+
.use(limitTo(120)) // the probes above it are not counted
|
|
211
|
+
.use(jsonOnly)
|
|
212
|
+
.bodyLimit(100 * 1024) // a body past 100 KiB is refused (a 413), for the routes below
|
|
213
|
+
.plugin((app) =>
|
|
214
|
+
graphql(app, {
|
|
215
|
+
schema,
|
|
216
|
+
context: () => ({ loaders: createLoaders() }),
|
|
217
|
+
logging: false,
|
|
218
|
+
plugins: [depthLimit(8), introspectionOnlyInDev, csrf],
|
|
219
|
+
}),
|
|
220
|
+
);
|
|
221
|
+
```
|
|
222
|
+
|
|
223
|
+
The recipe's spec runs each point against this app and a small schema, in
|
|
224
|
+
process: the 429 for a viewer and for an address (a batch of three counts
|
|
225
|
+
once), a document too deep, introspection refused outside development and
|
|
226
|
+
answering in it, a masked `Error` beside a `GraphQLError` with its
|
|
227
|
+
extensions, the body limit, the CSRF header, the `415`, and a persisted
|
|
228
|
+
hash running while an arbitrary document is refused
|
|
229
|
+
([the recipe](https://github.com/softistx/alxia/blob/develop/docs/recipes/graphql-api.md#7-harden-it-for-production)).
|
package/docs/guide/websockets.md
CHANGED
|
@@ -142,6 +142,48 @@ before you trust it. A header the upgrade's middlewares set with
|
|
|
142
142
|
`set.headers` is sent with the `101`; set during an operation, it goes
|
|
143
143
|
nowhere.
|
|
144
144
|
|
|
145
|
+
## Logging and tracing
|
|
146
|
+
|
|
147
|
+
The upgrade is answered before the first operation runs, so its request
|
|
148
|
+
cannot name one. Each operation on the socket is told to the observers
|
|
149
|
+
around the upgrade instead, from its `subscribe` message to its end — a
|
|
150
|
+
query's or a mutation's result sent, a subscription completed, stopped by
|
|
151
|
+
its client or cut by the socket's close — with its type, its name and
|
|
152
|
+
whether it was answered with errors. Give `logger()` and `telemetry()` to
|
|
153
|
+
`use` before `graphql()`, as over HTTP; nothing else to set:
|
|
154
|
+
|
|
155
|
+
```ts
|
|
156
|
+
const app = alxia()
|
|
157
|
+
.use(logger())
|
|
158
|
+
.use(telemetry({ service: 'notes' }))
|
|
159
|
+
.plugin((app) => graphql(app, { schema, ws: true }));
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
- `@alxia/logger` writes the upgrade's line, then one line per operation,
|
|
163
|
+
carrying the upgrade's `requestId`, its `duration` and `outcome`: `ok`,
|
|
164
|
+
or `errors` (a `warn`):
|
|
165
|
+
|
|
166
|
+
```json
|
|
167
|
+
{"level":"info","requestId":"7f3c…","message":"GET /graphql 200","status":200}
|
|
168
|
+
{"level":"info","requestId":"7f3c…","message":"query GetNotes","duration":2.4,"outcome":"ok","operationName":"GetNotes","operationType":"query"}
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
- `@alxia/telemetry` gives the upgrade a span that ends with its answer,
|
|
172
|
+
and each operation a span of its own, a child of the upgrade's:
|
|
173
|
+
`subscription OnNote`, with `graphql.operation.name` and
|
|
174
|
+
`graphql.operation.type`, an error when answered with errors. No span
|
|
175
|
+
lasts as long as the socket.
|
|
176
|
+
- An error is an operation answered with errors: a resolver that threw
|
|
177
|
+
(in `errors[]`), a document that does not validate, a subscription that
|
|
178
|
+
failed. A message that does not parse names no operation, and is not
|
|
179
|
+
told.
|
|
180
|
+
- Without either observer, nothing is told, and the operations run as
|
|
181
|
+
they do.
|
|
182
|
+
|
|
183
|
+
`graphql()` tells them with core's `startOperation`, and they subscribe
|
|
184
|
+
during the upgrade with `onOperation`: no package imports another
|
|
185
|
+
([core's plugin guide](https://github.com/softistx/alxia/blob/develop/packages/core/docs/guide/writing-a-plugin.md)).
|
|
186
|
+
|
|
145
187
|
## Errors
|
|
146
188
|
|
|
147
189
|
An error stays GraphQL's. A resolver's arrives in a `next` message with
|
package/docs/guide/yoga.md
CHANGED
|
@@ -141,6 +141,11 @@ POST [{"query":"{ admin }"},{"query":"{ __typename }"}]
|
|
|
141
141
|
200 [{"data":{"admin":"welcome"}},{"data":{"__typename":"Query"}}]
|
|
142
142
|
```
|
|
143
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
|
+
|
|
144
149
|
## Subscriptions
|
|
145
150
|
|
|
146
151
|
Subscriptions are served over server-sent events, Yoga's default: a
|
|
@@ -226,5 +231,6 @@ Passing Yoga's `cors` turns Yoga's on for this endpoint; do not use both.
|
|
|
226
231
|
|
|
227
232
|
- [Mounting the endpoint](endpoint.md): what the endpoint answers.
|
|
228
233
|
- [The typed context](context.md): the `context` option.
|
|
234
|
+
- [Harden it for production](production.md): depth limits, introspection off, a body limit, CSRF and persisted operations, run.
|
|
229
235
|
- [Troubleshooting](../troubleshooting.md): `Unexpected error.`, the `406`
|
|
230
236
|
and the `405`.
|
package/docs/roadmap.md
CHANGED
|
@@ -38,6 +38,11 @@ Nothing scheduled yet.
|
|
|
38
38
|
|
|
39
39
|
## Shipped
|
|
40
40
|
|
|
41
|
+
### Next release
|
|
42
|
+
|
|
43
|
+
- **Each operation over a socket.** Over `ws: true`, every query, mutation and subscription on a socket is told to the observers around its upgrade, from its `subscribe` message to its end, with whether it was answered with errors: `@alxia/logger` writes a line for each, `@alxia/telemetry` a span, a child of the upgrade's, named `subscription OnNote` ([WebSocket guide](guide/websockets.md#logging-and-tracing)).
|
|
44
|
+
- **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)).
|
|
45
|
+
|
|
41
46
|
### 0.1.0
|
|
42
47
|
|
|
43
48
|
- **GraphQL Yoga as a route.** `graphql(app, options)` serves a schema at
|
package/docs/troubleshooting.md
CHANGED
|
@@ -31,6 +31,7 @@ symptom.
|
|
|
31
31
|
- [`405 {"error":"method_not_allowed"}` on `OPTIONS /graphql`](#405-errormethod_not_allowed-on-options-graphql)
|
|
32
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)
|
|
33
33
|
- [`406` with an empty body](#406-with-an-empty-body)
|
|
34
|
+
- [`413 {"error":"content_too_large", …}`](#413-errorcontent_too_large--on-post-graphql)
|
|
34
35
|
- [`{"errors":[{"message":"Must provide query string."}]}`](#errorsmessagemust-provide-query-string)
|
|
35
36
|
- [`4406 Subprotocol not acceptable`](#4406-subprotocol-not-acceptable)
|
|
36
37
|
|
|
@@ -239,6 +240,20 @@ const app = alxia()
|
|
|
239
240
|
.plugin((app) => graphql(app, { schema: admin, path: '/admin/graphql' }));
|
|
240
241
|
```
|
|
241
242
|
|
|
243
|
+
For two variants on one base, build each on a fork of it
|
|
244
|
+
([Several apps on one base](../../core/docs/guide/groups-and-plugins.md#several-apps-on-one-base-fork)):
|
|
245
|
+
|
|
246
|
+
```ts
|
|
247
|
+
import { defineMiddleware } from '@alxia/core';
|
|
248
|
+
import { graphql } from '@alxia/graphql';
|
|
249
|
+
import { base } from './context';
|
|
250
|
+
import { schema } from './schema';
|
|
251
|
+
|
|
252
|
+
export const app = base.fork().plugin((app) => graphql(app, { schema }));
|
|
253
|
+
const fakeViewer = defineMiddleware((_ctx, next) => next({ viewer: { id: 'ada' } }));
|
|
254
|
+
const testApp = base.fork().use(fakeViewer).plugin((app) => graphql(app, { schema }));
|
|
255
|
+
```
|
|
256
|
+
|
|
242
257
|
### `TypeError: graphql(app, { ws: { keepAlive: 0 } }): keepAlive is the milliseconds between pings, a positive number, or false for none`
|
|
243
258
|
|
|
244
259
|
**When:** declaring `graphql(app, { ws: { keepAlive } })` with `0`, a
|
|
@@ -277,6 +292,23 @@ throw createGraphQLError('Admins only', {
|
|
|
277
292
|
|
|
278
293
|
`maskedErrors: false` shows every message, for development only.
|
|
279
294
|
|
|
295
|
+
### `413 {"error":"content_too_large", …}` on `POST /graphql`
|
|
296
|
+
|
|
297
|
+
**When:** the body of a `POST` is larger than the `bodyLimit` declared
|
|
298
|
+
before `graphql(...)`, with a `Content-Length` or chunked.
|
|
299
|
+
|
|
300
|
+
**Why:** core counts the bytes as they arrive and fails the read past the
|
|
301
|
+
limit; the endpoint answers it as any route does, in the app's error format
|
|
302
|
+
(`application/problem+json` under `errors: 'problem'`).
|
|
303
|
+
|
|
304
|
+
**Fix:** a client sends less, or the route takes a larger limit:
|
|
305
|
+
|
|
306
|
+
```ts
|
|
307
|
+
alxia()
|
|
308
|
+
.bodyLimit(512 * 1024) // before graphql(...)
|
|
309
|
+
.plugin((app) => graphql(app, { schema }));
|
|
310
|
+
```
|
|
311
|
+
|
|
280
312
|
### `405 {"error":"method_not_allowed"}` on `OPTIONS /graphql`
|
|
281
313
|
|
|
282
314
|
**When:** a browser on another origin calls the endpoint; its preflight
|
|
@@ -401,6 +433,26 @@ const base = alxia().use(bearer({ jwt }));
|
|
|
401
433
|
const app = base.plugin((app) => graphql(app, { schema }));
|
|
402
434
|
```
|
|
403
435
|
|
|
436
|
+
### Every log line and span is an anonymous `POST /graphql`
|
|
437
|
+
|
|
438
|
+
**When:** `@alxia/logger` writes `POST /graphql 200` with no
|
|
439
|
+
`operationName`, and the span of `@alxia/telemetry` is named
|
|
440
|
+
`POST /graphql`.
|
|
441
|
+
|
|
442
|
+
**Why:** an operation is reported only when Yoga executes it. A request
|
|
443
|
+
refused before that (a syntax error, a document that fails validation) names
|
|
444
|
+
none; an operation over `ws: true` is a line and a span of its own, not
|
|
445
|
+
the upgrade's ([the WebSocket guide](guide/websockets.md#logging-and-tracing));
|
|
446
|
+
and a logger or a
|
|
447
|
+
telemetry given to `use` *after* the endpoint, or a version of
|
|
448
|
+
`@alxia/core` older than the one that reports (`operationOf`), never reads
|
|
449
|
+
it.
|
|
450
|
+
|
|
451
|
+
**Fix:** give `logger()` and `telemetry()` to `use` before `graphql()`, and
|
|
452
|
+
update `@alxia/core`, `@alxia/graphql`, `@alxia/logger` and
|
|
453
|
+
`@alxia/telemetry` together. See
|
|
454
|
+
[the endpoint guide](guide/endpoint.md#the-operation-in-the-log-and-the-trace).
|
|
455
|
+
|
|
404
456
|
### The logger, CORS or secure headers miss the endpoint
|
|
405
457
|
|
|
406
458
|
**When:** `use(logger())`, `use(cors(…))` or `use(secureHeaders())` comes
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@alxia/graphql",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.0",
|
|
4
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",
|
|
@@ -41,7 +41,13 @@
|
|
|
41
41
|
]
|
|
42
42
|
},
|
|
43
43
|
"devDependencies": {
|
|
44
|
-
"@alxia/core": "^0.
|
|
44
|
+
"@alxia/core": "^0.8.0",
|
|
45
|
+
"@alxia/logger": "^0.6.0",
|
|
46
|
+
"@alxia/telemetry": "^0.6.0",
|
|
47
|
+
"@envelop/depth-limit": "^7.2.1",
|
|
48
|
+
"@graphql-yoga/plugin-csrf-prevention": "^3.24.2",
|
|
49
|
+
"@graphql-yoga/plugin-persisted-operations": "^3.24.2",
|
|
50
|
+
"@nxgt/telemetry": "^0.2.1",
|
|
45
51
|
"@types/bun": "^1.4.2",
|
|
46
52
|
"dataloader": "^2.2.3",
|
|
47
53
|
"graphql": "^16.11.0",
|
|
@@ -49,7 +55,7 @@
|
|
|
49
55
|
"graphql-yoga": "^5.16.0"
|
|
50
56
|
},
|
|
51
57
|
"peerDependencies": {
|
|
52
|
-
"@alxia/core": "^0.
|
|
58
|
+
"@alxia/core": "^0.8.0",
|
|
53
59
|
"graphql": "^16.11.0 || ^17.0.0",
|
|
54
60
|
"graphql-ws": "^6.1.0",
|
|
55
61
|
"graphql-yoga": "^5.16.0",
|