@softistx/alxia-graphql 0.0.0-stage → 0.20.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.
Files changed (49) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +445 -2
  3. package/dist/bounded-stream.d.ts +37 -0
  4. package/dist/bounded-stream.d.ts.map +1 -0
  5. package/dist/endpoint.d.ts +17 -0
  6. package/dist/endpoint.d.ts.map +1 -0
  7. package/dist/executor.d.ts +49 -0
  8. package/dist/executor.d.ts.map +1 -0
  9. package/dist/explorer.d.ts +24 -0
  10. package/dist/explorer.d.ts.map +1 -0
  11. package/dist/graphql.d.ts +63 -0
  12. package/dist/graphql.d.ts.map +1 -0
  13. package/dist/handler.d.ts +11 -0
  14. package/dist/handler.d.ts.map +1 -0
  15. package/dist/index.d.ts +8 -0
  16. package/dist/index.d.ts.map +1 -0
  17. package/dist/index.js +621 -0
  18. package/dist/index.js.map +21 -0
  19. package/dist/once-per-request.d.ts +28 -0
  20. package/dist/once-per-request.d.ts.map +1 -0
  21. package/dist/operation.d.ts +3 -0
  22. package/dist/operation.d.ts.map +1 -0
  23. package/dist/options.d.ts +38 -0
  24. package/dist/options.d.ts.map +1 -0
  25. package/dist/removed.d.ts +14 -0
  26. package/dist/removed.d.ts.map +1 -0
  27. package/dist/sandbox.d.ts +15 -0
  28. package/dist/sandbox.d.ts.map +1 -0
  29. package/dist/testing/client.d.ts +95 -0
  30. package/dist/testing/client.d.ts.map +1 -0
  31. package/dist/testing/index.d.ts +2 -0
  32. package/dist/testing/index.d.ts.map +1 -0
  33. package/dist/testing/index.js +73 -0
  34. package/dist/testing/index.js.map +10 -0
  35. package/dist/ws.d.ts +30 -0
  36. package/dist/ws.d.ts.map +1 -0
  37. package/docs/README.md +31 -0
  38. package/docs/guide/context.md +351 -0
  39. package/docs/guide/endpoint.md +293 -0
  40. package/docs/guide/executor.md +75 -0
  41. package/docs/guide/ide.md +160 -0
  42. package/docs/guide/plugins.md +316 -0
  43. package/docs/guide/production.md +374 -0
  44. package/docs/guide/testing.md +171 -0
  45. package/docs/guide/websockets.md +329 -0
  46. package/docs/migrating-to-graxia.md +408 -0
  47. package/docs/roadmap.md +122 -0
  48. package/docs/troubleshooting.md +963 -0
  49. package/package.json +69 -5
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Steve Tsala
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,446 @@
1
- # Temporary Holding Version
1
+ # @softistx/alxia-graphql
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ > Moved from `@alxia/graphql`: see the [migration guide](https://github.com/softistx/alxia/blob/develop/packages/core/docs/guide/migrating-from-alxia-scope.md).
4
+
5
+ GraphQL for [alxia](https://www.npmjs.com/package/@softistx/alxia), served by
6
+ [`@softistx/graxia`](https://www.npmjs.com/package/@softistx/graxia). The endpoint is a
7
+ route like any other: behind the app's middlewares, guarded by its guards, its
8
+ resolvers reading the context those middlewares built — typed, and checked.
9
+ Graxia's plugin system is yours whole: `plugins` takes its hooks, and
10
+ `@softistx/graxia-envelop` (install it yourself) adapts an Envelop plugin.
11
+
12
+ ```sh
13
+ bun add @softistx/alxia-graphql @softistx/graxia @softistx/graxia-graphiql graphql @softistx/alxia
14
+ bun add -d typescript
15
+ bun add @softistx/graxia-envelop @envelop/depth-limit # install yourself to use Envelop plugins
16
+ ```
17
+
18
+ `@softistx/graxia` (`^0.16.0`), `@softistx/graxia-graphiql` (`^0.4.0`) and `graphql` (17.1 or later) are peers:
19
+ the package declares no dependency. `@softistx/graxia-graphiql` serves the IDE and is
20
+ required. CSRF protection is graxia's default (on): a `GET` needs one of the
21
+ `x-graphql-csrf`, `graphql-require-preflight`, `apollo-require-preflight` or
22
+ `x-apollo-operation-name` headers.
23
+
24
+ `@softistx/graxia-graphiql` peers on exactly one core minor, so install the one that matches:
25
+
26
+ | `@softistx/graxia` | `@softistx/graxia-graphiql` |
27
+ | --- | --- |
28
+ | 0.15 | 0.3.0 |
29
+
30
+ Before the move to the `@softistx` scope, the packages were `@graxia/core` and `@graxia/graphiql`:
31
+ core 0.10 to 0.14 paired with graphiql 0.2.4 to 0.2.8 (one graphiql patch per core minor).
32
+
33
+ ## Usage
34
+
35
+ ```ts
36
+ import { alxia } from '@softistx/alxia';
37
+ import { graphql, type GraphQLContext } from '@softistx/alxia-graphql';
38
+ import { bearer } from '@softistx/alxia-jwt';
39
+ import { createSchema } from '@softistx/graxia';
40
+
41
+ const base = alxia()
42
+ .decorate({ db })
43
+ .use(bearer({ jwt, schema: Claims })); // every route after it needs a token
44
+
45
+ const schema = createSchema<GraphQLContext<typeof base>>()({
46
+ typeDefs: /* GraphQL */ `type Query { me: String! }`,
47
+ resolvers: {
48
+ Query: { me: (_, __, { user, db }) => db.name(user.sub) }, // user and db typed
49
+ },
50
+ });
51
+
52
+ const app = base.plugin((app) => graphql(app, { schema })); // POST and GET /graphql
53
+ app.listen(3000);
54
+ ```
55
+
56
+ `graphql(app, options)` adds `GET` and `POST` routes at `path` —
57
+ `/graphql` by default, under the app's prefix — and returns the app. Given
58
+ to `app.plugin` as a function, it stays in the chain and sees the app's type.
59
+
60
+ ## The context
61
+
62
+ A resolver's context is graxia's (`request`, `params`), the app's — every
63
+ `decorate`, every `derive`, every middleware's: `user`, `db`, `log`,
64
+ `requestId` — and `set`, through which it sets a header or a cookie:
65
+
66
+ ```ts
67
+ login: async (_, { name }, { set }) => {
68
+ set.cookies.set('session', await sign(name), { httpOnly: true });
69
+ return true;
70
+ },
71
+ ```
72
+
73
+ `GraphQLContext<typeof app>` is that type. A schema whose resolvers read
74
+ what the app does not build is a compile error:
75
+
76
+ ```
77
+ the schema's resolvers read a context the app does not build: missing user
78
+ ```
79
+
80
+ ## Batching (N+1)
81
+
82
+ A field that loads a record per parent — `Note.author` over 50 notes — is
83
+ 51 queries. Build [DataLoaders](https://github.com/graphql/dataloader) in
84
+ the `context` option and type them through `GraphQLContext`'s second
85
+ argument. (The `batching` option, below, is another thing: several
86
+ operations in one HTTP request.)
87
+
88
+ ```sh
89
+ bun add dataloader
90
+ ```
91
+
92
+ ```ts
93
+ import DataLoader from 'dataloader';
94
+
95
+ const createLoaders = () => ({
96
+ user: new DataLoader(async (ids: readonly string[]) => findUsers(ids)), // one query for all ids
97
+ });
98
+ type Loaders = ReturnType<typeof createLoaders>;
99
+
100
+ const schema = createSchema<GraphQLContext<typeof base, { loaders: Loaders }>>()({
101
+ typeDefs,
102
+ resolvers: { Note: { author: (note: { authorId: string }, _, { loaders }) => loaders.user.load(note.authorId) } },
103
+ });
104
+
105
+ const app = base.plugin((app) => graphql(app, { schema, context: () => ({ loaders: createLoaders() }) }));
106
+ ```
107
+
108
+ Per request, never once for the process: a DataLoader caches what it
109
+ loads, so a shared one would serve stale records and hand one user's data
110
+ to the next. Over WebSocket, `context` runs for each operation. See
111
+ [Batching with DataLoader](https://github.com/softistx/alxia/blob/develop/packages/graphql/docs/guide/context.md#batching-with-dataloader-n1).
112
+
113
+ ## One value per request
114
+
115
+ A field that resolves the same value for many parents (the category of
116
+ twenty items) should load it once. `oncePerRequest(context, key, load)`
117
+ runs `load` the first time a request asks for `key` and returns that value
118
+ to every later call of the same request. The cache is released with the
119
+ context object, and a `load` that throws or rejects is not kept.
120
+
121
+ ```ts
122
+ import DataLoader from 'dataloader';
123
+ import { oncePerRequest } from '@softistx/alxia-graphql';
124
+
125
+ const categories = (context: object) =>
126
+ oncePerRequest(context, 'categories', () => new DataLoader(loadCategories)); // one DataLoader per request and key
127
+
128
+ const category = (item: { categoryId: string }, _args: unknown, context: object) =>
129
+ categories(context).load(item.categoryId);
130
+ ```
131
+
132
+ A mutation runs its root fields one after another, and one may change what a
133
+ later one reads. Wrap the resolvers with `freshPerMutation` so each root
134
+ mutation field starts with an empty cache (its sub-fields share it); a query
135
+ keeps one cache:
136
+
137
+ ```ts
138
+ import { freshPerMutation } from '@softistx/alxia-graphql';
139
+
140
+ const resolvers = freshPerMutation({ Query, Mutation, Ward });
141
+ ```
142
+
143
+ It takes no dependency: `dataloader` stays yours. See
144
+ [One value per request](https://github.com/softistx/alxia/blob/develop/packages/graphql/docs/guide/context.md#one-value-per-request).
145
+
146
+ ## Graxia's plugins
147
+
148
+ Every `createGraxia` option passes through, but the endpoint path, which `path`
149
+ sets, and the IDE, which `ide` decides:
150
+
151
+ ```ts
152
+ import { useDepthLimit } from '@envelop/depth-limit';
153
+ import { fromEnvelop } from '@softistx/graxia-envelop';
154
+
155
+ graphql(app, {
156
+ schema,
157
+ plugins: [fromEnvelop(useDepthLimit({ maxDepth: 8 }))],
158
+ maskedErrors: true, // the default: an error's message never leaks
159
+ ide: Bun.env.NODE_ENV === 'development' && 'apollo-sandbox', // at runtime, never process.env: bun build inlines it
160
+ batching: true,
161
+ });
162
+ ```
163
+
164
+ - **Subscriptions** are served over server-sent events:
165
+ `async *subscribe` in a resolver, `Accept: text/event-stream` on the
166
+ request; over WebSocket too with [`ws: true`](#websocket). `@softistx/alxia-compress` leaves an event stream alone by default.
167
+ - **An IDE** answers a `GET` from a browser at the endpoint, with a
168
+ `Content-Security-Policy` that lets it load — its pinned files on unpkg
169
+ alone, framed by no one — which `@softistx/alxia-secure-headers` keeps. By
170
+ default, GraphiQL in the serving app's dev alone (`NODE_ENV=development`,
171
+ or `alxia({ dev: true })`), none otherwise; `ide` chooses one everywhere:
172
+
173
+ ```ts
174
+ graphql(app, { schema }); // GraphiQL in dev, nothing deployed
175
+ graphql(app, { schema, ide: 'apollo-sandbox', sandbox: { initialDocument: '{ me }' } });
176
+ ```
177
+
178
+ | `ide` | |
179
+ | --- | --- |
180
+ | none (default) | GraphiQL in dev (`isDev`), nothing otherwise |
181
+ | `'graphiql'` | GraphiQL (`@softistx/graxia-graphiql`), everywhere; `graphiql` takes its options |
182
+ | `'apollo-sandbox'` | [Apollo Sandbox](https://www.apollographql.com/docs/graphos/platform/sandbox), embedded, pointed at the address the page was opened at, prefix included — `https` behind a proxy that terminates TLS ([IDE guide](https://github.com/softistx/alxia/blob/develop/packages/graphql/docs/guide/ide.md#apollo-sandbox)). `sandbox` takes `title`, `initialDocument`, `initialHeaders`, `includeCookies` |
183
+ | `false` | none |
184
+ - **CORS** is `@softistx/alxia-cors`'s for the whole app; `cors` is not an option of
185
+ `graphql()`.
186
+
187
+ ## Which operation ran
188
+
189
+ Every call is a `POST /graphql`; `graphql()` tells the observers around it
190
+ which operation it executes. Behind `use(logger())` the request's line
191
+ carries `operationName` and `operationType`, and behind
192
+ `use(telemetry({ … }))` its span is named `query GetNotes`, with
193
+ OpenTelemetry's `graphql.operation.name` and `graphql.operation.type`. A
194
+ batched body is one line and one span, `batch`, with every name. graxia's
195
+ own operation span is off by default (`telemetry: { operationSpans: false }`), so an operation is one span, with graxia's parse, validate and execute spans under it; see
196
+ [graxia's own spans](https://github.com/softistx/alxia/blob/develop/packages/graphql/docs/guide/endpoint.md#graxias-own-spans).
197
+
198
+ ```ts
199
+ const app = alxia()
200
+ .use(logger())
201
+ .use(telemetry({ service: 'notes' }))
202
+ .plugin((app) => graphql(app, { schema }));
203
+ ```
204
+
205
+ A request
206
+ refused before it executes names none. Over `ws: true`, each operation on
207
+ the socket is a line and a span of its own, from its `subscribe` message
208
+ to its end, marked when answered with errors.
209
+ 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)
210
+ and [the WebSocket guide](https://github.com/softistx/alxia/blob/develop/packages/graphql/docs/guide/websockets.md#logging-and-tracing).
211
+
212
+ ## WebSocket
213
+
214
+ `ws: true` serves the endpoint over WebSocket too, with the
215
+ `graphql-transport-ws` protocol, spoken by graxia itself (no extra
216
+ install), the default of Apollo Client's `GraphQLWsLink` and urql's
217
+ `subscriptionExchange`. Server-sent events stay served at the same path.
218
+
219
+ ```ts
220
+ const app = base.plugin((app) => graphql(app, { schema, ws: true })); // ws://…/graphql too
221
+ ```
222
+
223
+ ```ts
224
+ import { createClient } from 'graphql-ws';
225
+
226
+ const client = createClient({ url: 'wss://api.example.com/graphql', connectionParams: { device: 'web' } });
227
+ ```
228
+
229
+ The upgrade runs the app's middlewares — a guard's `401` refuses the
230
+ socket, what they add is in the context, beside the `connectionParams`
231
+ the client sent — each operation runs through
232
+ graxia's plugins, and a shutdown closes the sockets with `1001`, completing
233
+ their subscriptions. `ws: { path, keepAlive }` moves the socket or spaces
234
+ its pings. See [the WebSocket guide](https://github.com/softistx/alxia/blob/develop/packages/graphql/docs/guide/websockets.md),
235
+ Apollo Client's and urql's setup included.
236
+
237
+ ## Bound a subscription
238
+
239
+ ```ts
240
+ import { boundedStream } from '@softistx/alxia-graphql';
241
+
242
+ // Your pub/sub reader and your session check.
243
+ declare function subscribeToTopic(topicId: string): AsyncIterable<unknown>;
244
+
245
+ const subscribe = (
246
+ _: unknown,
247
+ args: { topicId: string },
248
+ ctx: { assertSession(): Promise<void> },
249
+ ) =>
250
+ boundedStream(subscribeToTopic(args.topicId), {
251
+ idleMs: 90_000,
252
+ totalMs: 10 * 60_000,
253
+ checkEveryMs: 30_000,
254
+ check: () => ctx.assertSession(),
255
+ });
256
+ ```
257
+
258
+ The stream ends cleanly when idle or old, throws when `check` throws, and
259
+ releases the source as soon as the client leaves. See
260
+ [the plugins and options guide](https://github.com/softistx/alxia/blob/develop/packages/graphql/docs/guide/plugins.md#bound-a-subscription).
261
+
262
+ ## Limits
263
+
264
+ Four limits bound what a request costs before any resolver runs. A document
265
+ may hold at most **15 000 tokens** (`limits.tokens`, or the deprecated `maxTokens`; `false` for no cap): a longer
266
+ one is refused by the parser as `GRAPHQL_PARSE_FAILED`, 400 under
267
+ `application/graphql-response+json`, and never reaches the schema. It may
268
+ nest at most **1 000 levels** of `{`, `(` and `[` (`limits.nesting`, or the deprecated
269
+ `maxNesting`; `false` for no limit): graphql-js parses by recursion and overflows the stack a few
270
+ thousand levels down, so a deeper document is refused the same way before the
271
+ parser recurses into it, never a 500. It counts `{`, `(` and `[` together,
272
+ arguments and lists included, so it is not a selection-depth rule; use a
273
+ validation rule for that. The
274
+ documents graxia parses are kept in a cache (`caches.parse`, or the
275
+ deprecated `parseCache`; `caches: false` for none). A `POST` body may hold **1 MiB** (`bodyLimit`, graxia's `limits.bodyBytes`) unless the
276
+ app declared its own `bodyLimit()` before `graphql()`, which graxia then
277
+ enforces; a body past it is a `413` with `extensions.code: 'BODY_TOO_LARGE'`,
278
+ declared by `Content-Length` or counted as it arrives. Every refusal graxia
279
+ builds before execution has a stable code (`UNSUPPORTED_MEDIA_TYPE` 415,
280
+ `BODY_NOT_JSON` 400, `PARAMS_INVALID` 400, `NOT_ACCEPTABLE` 406…): match
281
+ `errors[0].extensions.code`, never the message
282
+ ([the table](https://github.com/softistx/graxia/blob/develop/packages/core/docs/guide/http.md#refusal-codes);
283
+ `GraxiaErrorCode` is re-exported as a type). Under `Accept: application/json` (the default) a 400 refusal is a `200`; `413`, `415`, `404`, `405` and `406` never change. `bodyLimit` bounds a `POST`
284
+ alone: a WebSocket `subscribe` message is bounded by Bun's `maxPayloadLength`
285
+ (16 MiB by default):
286
+
287
+ ```ts
288
+ graphql(app, {
289
+ schema,
290
+ limits: { tokens: 20_000, nesting: 2_000 }, // false: no cap
291
+ caches: { parse: { max: 512, ttlMs: 30 * 60_000 } }, // false: no cache
292
+ bodyLimit: 5 * 1024 * 1024, // 1 MiB by default; a multipart upload needs more
293
+ });
294
+ ```
295
+
296
+ A refused document is a 200 with `errors` under `application/json` (400 under
297
+ `application/graphql-response+json`). A bad option value throws a `TypeError`
298
+ where `graphql()` is declared.
299
+
300
+ A client query is a few thousand tokens; the introspection query is 163. See
301
+ [Cap what a request costs](https://github.com/softistx/alxia/blob/develop/packages/graphql/docs/guide/production.md#cap-what-a-request-costs).
302
+
303
+ ## Count a field, not a request
304
+
305
+ A limit on HTTP requests counts one request however many times it selects
306
+ `signIn` under aliases (`a: signIn(...) b: signIn(...) …`). `fieldRateLimit`
307
+ is a graxia plugin that walks the operation about to run, aliases, inline
308
+ fragments and fragment spreads expanded, and consumes the number of
309
+ selections of each chosen field on a limit keyed by the client. Past the
310
+ limit nothing executes: a 429 `RATE_LIMITED` (the `code` option names it
311
+ otherwise, `TOO_MANY_ATTEMPTS` say) with `extensions.retryAfter` (seconds) and
312
+ a `Retry-After` header. List it first in `plugins`.
313
+
314
+ ```ts
315
+ import { alxia } from '@softistx/alxia';
316
+ import { MemoryStore } from '@softistx/alxia-rate-limit';
317
+ import { fieldRateLimit, graphql, limitFromStore } from '@softistx/alxia-graphql';
318
+ import { schema } from './schema';
319
+
320
+ const store = new MemoryStore();
321
+
322
+ graphql(alxia(), {
323
+ schema,
324
+ plugins: [
325
+ fieldRateLimit({
326
+ // Optional: who is counted. The client's address by default, and
327
+ // ipv6Prefix: 64 counts an IPv6 client by its network.
328
+ // key: ({ ip }) => ip,
329
+ fields: {
330
+ signIn: { limit: limitFromStore(store, { limit: 5, windowMs: 60_000 }), single: true },
331
+ },
332
+ }),
333
+ ],
334
+ });
335
+ ```
336
+
337
+ A limit is anything with `consume(key, cost)` answering `{ allowed,
338
+ retryAfter }` (milliseconds): `limitFromStore` makes one of an
339
+ `@softistx/alxia-rate-limit` store, one store call per unit of cost (up to `limit + 1`
340
+ round trips), and a `@softistx/redis` bound limit, which takes the cost in
341
+ one call and suits a large limit, fits as
342
+ `{ consume: async (key, cost) => limit.consume({ ip: key }, cost) }` (`limit`
343
+ is the entry of your wired Redis handle). Units spent before a refusal stay
344
+ spent, and so do the fields charged before a refused one. `single: true`
345
+ refuses the field written more than once in the document (400
346
+ `FIELD_SELECTED_ONCE`), counting a selection written the same way twice as
347
+ one. Counting is per selection in the document: a list parent costs 1,
348
+ `@skip` and `@include` are not evaluated, and a field matches by name on any
349
+ type. Under `batching` a refused element is an error in a 200 array, with no
350
+ `Retry-After`. See
351
+ [Count a field, not a request](https://github.com/softistx/alxia/blob/develop/packages/graphql/docs/guide/production.md#count-a-field-not-a-request).
352
+
353
+ ## Errors, health and shutdown
354
+
355
+ A GraphQL error stays GraphQL's — an entry of `errors[]`, inside a 200 —
356
+ while `@softistx/alxia`'s `alxia({ errors: 'problem' })` makes the HTTP layer
357
+ around the endpoint answer RFC 9457 problems: a guard's 401, a 413, a
358
+ 500. `health()` mounts beside it, and on `SIGTERM` the queries in flight
359
+ are answered and the subscriptions ended before the process exits:
360
+
361
+ ```ts
362
+ import { alxia, health } from '@softistx/alxia';
363
+ import { graphql } from '@softistx/alxia-graphql';
364
+
365
+ const app = alxia({ errors: 'problem' })
366
+ .plugin(health())
367
+ .plugin((app) => graphql(app, { schema }));
368
+ app.listen({ port: 4000 });
369
+ ```
370
+
371
+ See [the endpoint guide](https://github.com/softistx/alxia/blob/develop/packages/graphql/docs/guide/endpoint.md#errors-health-and-shutdown).
372
+
373
+ ## In process
374
+
375
+ `graphqlExecutor(options)` runs a query or a mutation in the process, with the
376
+ same plugins, limits, parse cache and error masking as `graphql()`, and a
377
+ server context you pass: for an MCP tool or a job, not a browser.
378
+
379
+ ```ts
380
+ import { graphqlExecutor } from '@softistx/alxia-graphql';
381
+
382
+ const execute = graphqlExecutor({ schema, plugins: [useAuth()] });
383
+ const { data, errors } = await execute({ query: '{ me { id } }' }, { viewer });
384
+ ```
385
+
386
+ See [the guide](https://github.com/softistx/alxia/blob/develop/packages/graphql/docs/guide/executor.md).
387
+
388
+ ## Testing
389
+
390
+ `graphqlClient` from `@softistx/alxia-graphql/testing` sends operations to the app
391
+ in process, through `app.fetch`: no port. It is a subpath, so the main entry
392
+ and a production bundle never carry it.
393
+
394
+ ```ts
395
+ import { graphqlClient } from '@softistx/alxia-graphql/testing';
396
+
397
+ const client = graphqlClient(app, { headers: { authorization: `Bearer ${token}` } });
398
+ const { status, data, errors } = await client.query(
399
+ 'query ($name: String!) { hello(name: $name) }',
400
+ { variables: { name: 'Ada' } },
401
+ );
402
+ ```
403
+
404
+ A `TypedDocumentNode` types `data` and the variables. `method: 'GET'` sends
405
+ the operation in the URL; `persisted` sends the hash of a persisted operation,
406
+ alone when the app allows nothing else (you name `TData`); the client adds no
407
+ CSRF header, put yours in `headers`:
408
+
409
+ ```ts
410
+ const result = await client.query<{ hello: string }>({ persisted: hash, method: 'GET' });
411
+ ```
412
+
413
+ See
414
+ [the testing guide](https://github.com/softistx/alxia/blob/develop/packages/graphql/docs/guide/testing.md).
415
+
416
+ ## API
417
+
418
+ | export | |
419
+ | --- | --- |
420
+ | `graphql(app, options)` | the endpoint: `schema`, `path`, `ide`, `sandbox`, `ws`, `limits`, `caches`, `csrf`, `maskErrors`, `bodyLimit`, and every `createGraxia` option (the older `maxTokens`, `maxNesting`, `parseCache` and `maskedErrors` still map, deprecated) |
421
+ | `graphqlExecutor(options)` | `(request: { query, operationName?, variables? }, context, { signal? }?) => Promise<{ data?, errors? }>` with a `dispose()`: a query or mutation in process, through the options of `graphql()` without the route's (`path`, `ide`, `ws`, `bodyLimit`) |
422
+ | `ExecutorRequest`, `ExecutorResult`, `ExecutorError`, `ExecutorCall`, `GraphQLExecutor`, `GraphQLExecutorOptions` | its types |
423
+ | `GraphQLWsOptions` | `ws`'s options: `path`, `keepAlive` |
424
+ | `GraphQLWsContext` | what an operation over WebSocket adds to the context: `connectionParams` |
425
+ | `SandboxOptions` | its options: `title`, `initialDocument`, `initialHeaders`, `includeCookies` |
426
+ | `GraphQLContext<App, UserContext?>` | what a resolver reads |
427
+ | `oncePerRequest(request, key, load)` | `load()`'s value, computed at most once per request object and `key` (a `string`); returns `T`, a promise kept as the same promise, a throw or rejection not kept |
428
+ | `clearRequestCache(request)` | empties what `oncePerRequest` kept for that request object; the next call loads again; returns `void` |
429
+ | `freshPerMutation(resolvers)` | the same resolvers (same type; an array of maps gives an array) with each function of `Mutation` wrapped to call `clearRequestCache(context)` first: each root mutation field starts empty, its sub-fields share, a query is untouched |
430
+ | `fieldRateLimit({ fields, key?, ipv6Prefix?, code? })` | re-exported from `@softistx/graxia`, a plugin, listed first: consumes the number of selections (aliases and fragments expanded) of each chosen field on its limit, keyed by `key(context)` (the client address by default, its IPv6 network under `ipv6Prefix`); 429 `RATE_LIMITED` (`code`) with `retryAfter`, or 400 `FIELD_SELECTED_ONCE` for a `single` field; units spent before a refusal stay spent |
431
+ | `limitFromStore(store, policy?)` | an `@softistx/alxia-rate-limit` store as a `FieldLimit`: one consume per unit of cost, stopped at the first refusal (up to `limit + 1` round trips); `policy` may come from `store.policy` and must not differ from it |
432
+ | `FieldLimit`, `FieldDecision`, `FieldRule`, `FieldRateLimitOptions`, `CostlessStore` | their types |
433
+ | `boundedStream(source, options)` | `source` (an `AsyncIterable` or `AsyncIterator`) as an `AsyncIterableIterator<T>` for a subscription's `subscribe`: ends cleanly after `idleMs` without an event and `totalMs` in all, runs `check` every `checkEveryMs` and before an event when the last check is `checkDebounceMs` old, throws `mapError(error)` when `check` fails or the source itself throws, and calls the source's `return()` on disconnect or any end |
434
+ | `BoundedStreamOptions` | its options: `idleMs`, `totalMs`, `checkEveryMs`, `checkDebounceMs?`, `check`, `mapError?`, `signal?` |
435
+ | `GraphQLContextInit<App>` | the parameter of a `context` factory that reads `serverContext`, typed from the app: `({ serverContext }: GraphQLContextInit<typeof app>) => …` |
436
+ | `ServerContext<Ctx>`, `GraphQLOptions` | its types |
437
+ | `GraxiaErrorCode` | graxia's union of refusal codes (`BODY_TOO_LARGE`, `CSRF_HEADER_REQUIRED`, …), re-exported as a type |
438
+ | `graphqlClient(app, { path?, headers?, method?, csrfHeader? })` (`@softistx/alxia-graphql/testing`) | `query(document, { variables?, operationName?, headers?, method?, extensions?, persisted? })`, or `query({ persisted })` with no document, in process: `{ status, data?, errors?, response }` |
439
+ | `GraphQLClient`, `GraphQLResult`, `QueryDocument`, `QueryOptions`, `PersistedQueryOptions`, `HttpMethod`, `GraphQLClientOptions`, `ResponseError` (`@softistx/alxia-graphql/testing`) | its types |
440
+
441
+ ## Documentation
442
+
443
+ - [Guide](https://github.com/softistx/alxia/tree/develop/packages/graphql/docs): a page per area — mounting the endpoint, the typed context, graxia's plugins and options, GraphQL over WebSocket, running operations in process, 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).
444
+ - [Troubleshooting](https://github.com/softistx/alxia/blob/develop/packages/graphql/docs/troubleshooting.md): an error message, and what to do about it.
445
+ - [Roadmap](https://github.com/softistx/alxia/blob/develop/packages/graphql/docs/roadmap.md): what is coming, and what is not planned.
446
+ - [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,37 @@
1
+ /** What bounds a stream, and what keeps it authorized. All durations in ms. */
2
+ export interface BoundedStreamOptions {
3
+ /** The stream ends, cleanly, after this long without an event. */
4
+ idleMs: number;
5
+ /** The stream ends, cleanly, this long after it began, however chatty. */
6
+ totalMs: number;
7
+ /** `check` runs at least this often, also while no event comes. */
8
+ checkEveryMs: number;
9
+ /**
10
+ * Before an event is yielded, `check` runs when the last check is at least
11
+ * this old. Default `0`: every event is checked. Raise it when events come
12
+ * in bursts and one check per event would cost more than the delay of a
13
+ * revocation it saves.
14
+ */
15
+ checkDebounceMs?: number;
16
+ /** Throws to refuse (a session that ended, a role that was lost). */
17
+ check: () => Promise<void> | void;
18
+ /** Turns what `check` (or the source) threw into the error the stream throws. Default: rethrown as is. */
19
+ mapError?: (error: unknown) => unknown;
20
+ /** Aborted when the client leaves: the stream ends and releases the source. */
21
+ signal?: AbortSignal;
22
+ }
23
+ /**
24
+ * `source` bounded by an idle and a total lifetime and re-checked while it
25
+ * lives, to return as a subscription's `subscribe` result.
26
+ *
27
+ * It ends, without an error, when the source ends, on the idle bound, on the
28
+ * total bound and on `signal`'s abort. It throws `mapError(error)` (the
29
+ * error itself by default) when `check` fails, or when the source does. The
30
+ * source's `return()` is called at once on the consumer's `return()` (a
31
+ * client that disconnected) and on any end, even while a read is pending: the
32
+ * iterator is written by hand because a generator's `return()` waits behind a
33
+ * pending `next()`. Read it one `next()` at a time, as `for await` does. No
34
+ * timer outlives a step.
35
+ */
36
+ export declare function boundedStream<T>(source: AsyncIterable<T> | AsyncIterator<T>, options: BoundedStreamOptions): AsyncIterableIterator<T>;
37
+ //# sourceMappingURL=bounded-stream.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bounded-stream.d.ts","sourceRoot":"","sources":["../src/bounded-stream.ts"],"names":[],"mappings":"AAAA,+EAA+E;AAC/E,MAAM,WAAW,oBAAoB;IACpC,kEAAkE;IAClE,MAAM,EAAE,MAAM,CAAC;IACf,0EAA0E;IAC1E,OAAO,EAAE,MAAM,CAAC;IAChB,mEAAmE;IACnE,YAAY,EAAE,MAAM,CAAC;IACrB;;;;;OAKG;IACH,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,qEAAqE;IACrE,KAAK,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;IAClC,0GAA0G;IAC1G,QAAQ,CAAC,EAAE,CAAC,KAAK,EAAE,OAAO,KAAK,OAAO,CAAC;IACvC,+EAA+E;IAC/E,MAAM,CAAC,EAAE,WAAW,CAAC;CACrB;AAUD;;;;;;;;;;;;GAYG;AACH,wBAAgB,aAAa,CAAC,CAAC,EAC9B,MAAM,EAAE,aAAa,CAAC,CAAC,CAAC,GAAG,aAAa,CAAC,CAAC,CAAC,EAC3C,OAAO,EAAE,oBAAoB,GAC3B,qBAAqB,CAAC,CAAC,CAAC,CA+G1B"}
@@ -0,0 +1,17 @@
1
+ import type { Alxia } from '@softistx/alxia';
2
+ import type { graphqlSocket } from './ws';
3
+ /** What `declareEndpoint` asks its caller to build once the body limit is known. */
4
+ export interface Mounted {
5
+ readonly handler: (ctx: never) => unknown;
6
+ readonly socket: ReturnType<typeof graphqlSocket> | undefined;
7
+ }
8
+ /**
9
+ * `GET` and `POST` at `path` on `app`, and the WebSocket when `ws` is on.
10
+ * `mount` receives the bytes graxia's `limits.bodyBytes` must hold: the
11
+ * option, else the `bodyLimit()` the app declared before, else 1 MiB.
12
+ * A bad limit, the option or an inherited `bodyLimit(0)` (core accepts 0,
13
+ * graxia does not), throws before any route is declared, so the app stays
14
+ * as it was.
15
+ */
16
+ export declare function declareEndpoint(app: Alxia<never, string>, path: string, bodyLimit: number | undefined, mount: (bodyBytes: number) => Mounted): void;
17
+ //# sourceMappingURL=endpoint.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"endpoint.d.ts","sourceRoot":"","sources":["../src/endpoint.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,iBAAiB,CAAC;AAE7C,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,MAAM,CAAC;AAY1C,oFAAoF;AACpF,MAAM,WAAW,OAAO;IACvB,QAAQ,CAAC,OAAO,EAAE,CAAC,GAAG,EAAE,KAAK,KAAK,OAAO,CAAC;IAC1C,QAAQ,CAAC,MAAM,EAAE,UAAU,CAAC,OAAO,aAAa,CAAC,GAAG,SAAS,CAAC;CAC9D;AAED;;;;;;;GAOG;AACH,wBAAgB,eAAe,CAC9B,GAAG,EAAE,KAAK,CAAC,KAAK,EAAE,MAAM,CAAC,EACzB,IAAI,EAAE,MAAM,EACZ,SAAS,EAAE,MAAM,GAAG,SAAS,EAC7B,KAAK,EAAE,CAAC,SAAS,EAAE,MAAM,KAAK,OAAO,GACnC,IAAI,CA0BN"}
@@ -0,0 +1,49 @@
1
+ import type { Empty } from '@softistx/alxia';
2
+ import { type GraxiaOptions } from '@softistx/graxia';
3
+ import type { GraphQLSchema } from 'graphql';
4
+ import { type LegacyOptions } from './options';
5
+ /** What an in-process call asks for: a GraphQL-over-HTTP request's parameters. */
6
+ export interface ExecutorRequest {
7
+ readonly query: string;
8
+ readonly operationName?: string | undefined;
9
+ readonly variables?: Readonly<Record<string, unknown>> | undefined;
10
+ }
11
+ /** A plain, JSON-shaped error, as the route answers it. */
12
+ export interface ExecutorError {
13
+ readonly message: string;
14
+ readonly path?: readonly (string | number)[];
15
+ readonly locations?: readonly {
16
+ line: number;
17
+ column: number;
18
+ }[];
19
+ readonly extensions?: Readonly<Record<string, unknown>>;
20
+ }
21
+ /** The answer: `data` and `errors`, as the endpoint's JSON body. */
22
+ export interface ExecutorResult {
23
+ readonly data?: unknown;
24
+ readonly errors?: readonly ExecutorError[];
25
+ }
26
+ /** Per call: the signal that stops the operation, as a client leaving does. */
27
+ export interface ExecutorCall {
28
+ /**
29
+ * An aborted signal, before the call or while it runs, resolves to
30
+ * `{ errors: [{ extensions: { code: 'OPERATION_ABORTED' } }] }`: it never rejects.
31
+ */
32
+ readonly signal?: AbortSignal;
33
+ }
34
+ export interface GraphQLExecutorOptions<SchemaCtx = unknown> extends Omit<GraxiaOptions<any, GraphQLSchema, any, any>, 'path' | 'schema' | 'subscriptions' | 'context' | 'plugins'>, LegacyOptions {
35
+ readonly schema: GraphQLSchema & {
36
+ readonly '~context'?: SchemaCtx;
37
+ };
38
+ readonly context?: GraxiaOptions['context'];
39
+ readonly plugins?: GraxiaOptions['plugins'];
40
+ }
41
+ /** Runs one operation in process. */
42
+ export type GraphQLExecutor<ServerCtx> = ((request: ExecutorRequest, context: ServerCtx, call?: ExecutorCall) => Promise<ExecutorResult>) & {
43
+ /** Releases what the instance holds (plugins' `onDispose`, in-flight operations). A call after it rejects. */
44
+ dispose(): Promise<void>;
45
+ };
46
+ /** Runs a GraphQL operation in the process, through `graxia.execute`. Queries and mutations only (graxia refuses a subscription). */
47
+ export declare function graphqlExecutor<SchemaCtx, ServerCtx = Omit<SchemaCtx, 'signal'>>(options: GraphQLExecutorOptions<SchemaCtx>): GraphQLExecutor<ServerCtx>;
48
+ export type { Empty };
49
+ //# sourceMappingURL=executor.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"executor.d.ts","sourceRoot":"","sources":["../src/executor.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,iBAAiB,CAAC;AAC7C,OAAO,EAAgB,KAAK,aAAa,EAAE,MAAM,kBAAkB,CAAC;AACpE,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAC7C,OAAO,EAAiB,KAAK,aAAa,EAAE,MAAM,WAAW,CAAC;AAE9D,kFAAkF;AAClF,MAAM,WAAW,eAAe;IAC/B,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,aAAa,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAC5C,QAAQ,CAAC,SAAS,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,GAAG,SAAS,CAAC;CACnE;AAED,2DAA2D;AAC3D,MAAM,WAAW,aAAa;IAC7B,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,IAAI,CAAC,EAAE,SAAS,CAAC,MAAM,GAAG,MAAM,CAAC,EAAE,CAAC;IAC7C,QAAQ,CAAC,SAAS,CAAC,EAAE,SAAS;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE,EAAE,CAAC;IACjE,QAAQ,CAAC,UAAU,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC;CACxD;AAED,oEAAoE;AACpE,MAAM,WAAW,cAAc;IAC9B,QAAQ,CAAC,IAAI,CAAC,EAAE,OAAO,CAAC;IACxB,QAAQ,CAAC,MAAM,CAAC,EAAE,SAAS,aAAa,EAAE,CAAC;CAC3C;AAED,+EAA+E;AAC/E,MAAM,WAAW,YAAY;IAC5B;;;OAGG;IACH,QAAQ,CAAC,MAAM,CAAC,EAAE,WAAW,CAAC;CAC9B;AAED,MAAM,WAAW,sBAAsB,CAAC,SAAS,GAAG,OAAO,CAC1D,SAAQ,IAAI,CACV,aAAa,CAAC,GAAG,EAAE,aAAa,EAAE,GAAG,EAAE,GAAG,CAAC,EAC3C,MAAM,GAAG,QAAQ,GAAG,eAAe,GAAG,SAAS,GAAG,SAAS,CAC3D,EACD,aAAa;IACd,QAAQ,CAAC,MAAM,EAAE,aAAa,GAAG;QAAE,QAAQ,CAAC,UAAU,CAAC,EAAE,SAAS,CAAA;KAAE,CAAC;IACrE,QAAQ,CAAC,OAAO,CAAC,EAAE,aAAa,CAAC,SAAS,CAAC,CAAC;IAC5C,QAAQ,CAAC,OAAO,CAAC,EAAE,aAAa,CAAC,SAAS,CAAC,CAAC;CAC5C;AAED,qCAAqC;AACrC,MAAM,MAAM,eAAe,CAAC,SAAS,IAAI,CAAC,CACzC,OAAO,EAAE,eAAe,EACxB,OAAO,EAAE,SAAS,EAClB,IAAI,CAAC,EAAE,YAAY,KACf,OAAO,CAAC,cAAc,CAAC,CAAC,GAAG;IAC/B,8GAA8G;IAC9G,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CACzB,CAAC;AASF,qIAAqI;AACrI,wBAAgB,eAAe,CAC9B,SAAS,EACT,SAAS,GAAG,IAAI,CAAC,SAAS,EAAE,QAAQ,CAAC,EACpC,OAAO,EAAE,sBAAsB,CAAC,SAAS,CAAC,GAAG,eAAe,CAAC,SAAS,CAAC,CAiCxE;AACD,YAAY,EAAE,KAAK,EAAE,CAAC"}
@@ -0,0 +1,24 @@
1
+ /** The IDE of `graphql()`: graxia's GraphiQL or Apollo Sandbox plugin, from alxia's `ide` options. */
2
+ import type { GraxiaPlugin } from '@softistx/graxia';
3
+ import { type GraphiQLOptions } from '@softistx/graxia-graphiql';
4
+ import type { SandboxOptions } from './sandbox';
5
+ /**
6
+ * The requests the endpoint handler has seen, with the app's dev flag at the
7
+ * moment of each: what the IDE's `enabled` function reads, since graxia hands
8
+ * it the `Request` alone.
9
+ */
10
+ export type DevOfRequest = WeakMap<Request, boolean>;
11
+ export interface ExplorerOptions {
12
+ readonly ide?: 'graphiql' | 'apollo-sandbox' | false | undefined;
13
+ readonly graphiql?: GraphiQLOptions | false | undefined;
14
+ readonly sandbox?: SandboxOptions | undefined;
15
+ }
16
+ /**
17
+ * The IDE plugins: Sandbox for `ide: 'apollo-sandbox'`, nothing for
18
+ * `ide: false` or `graphiql: false`, GraphiQL otherwise. By default GraphiQL
19
+ * answers while the serving app is in dev (`alxia({ dev })`, else
20
+ * `NODE_ENV=development`, read per request from `devs`, which the endpoint
21
+ * handler fills), and everywhere under `ide: 'graphiql'`.
22
+ */
23
+ export declare function explorerPlugins(options: ExplorerOptions, devs: DevOfRequest): GraxiaPlugin<any, any>[];
24
+ //# sourceMappingURL=explorer.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"explorer.d.ts","sourceRoot":"","sources":["../src/explorer.ts"],"names":[],"mappings":"AAAA,sGAAsG;AAEtG,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AACrD,OAAO,EAGN,KAAK,eAAe,EAGpB,MAAM,2BAA2B,CAAC;AACnC,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAEhD;;;;GAIG;AACH,MAAM,MAAM,YAAY,GAAG,OAAO,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;AAErD,MAAM,WAAW,eAAe;IAC/B,QAAQ,CAAC,GAAG,CAAC,EAAE,UAAU,GAAG,gBAAgB,GAAG,KAAK,GAAG,SAAS,CAAC;IACjE,QAAQ,CAAC,QAAQ,CAAC,EAAE,eAAe,GAAG,KAAK,GAAG,SAAS,CAAC;IACxD,QAAQ,CAAC,OAAO,CAAC,EAAE,cAAc,GAAG,SAAS,CAAC;CAC9C;AA0BD;;;;;;GAMG;AACH,wBAAgB,eAAe,CAC9B,OAAO,EAAE,eAAe,EACxB,IAAI,EAAE,YAAY,GAChB,YAAY,CAAC,GAAG,EAAE,GAAG,CAAC,EAAE,CAW1B"}