@alxia/graphql 0.1.2 → 0.3.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 +35 -11
- package/dist/graphql.d.ts +10 -11
- package/dist/graphql.d.ts.map +1 -1
- package/dist/handler.d.ts +14 -3
- package/dist/handler.d.ts.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +64 -15
- package/dist/index.js.map +6 -6
- package/docs/README.md +12 -2
- package/docs/guide/context.md +10 -10
- package/docs/guide/endpoint.md +86 -36
- package/docs/guide/ide.md +33 -22
- package/docs/guide/yoga.md +8 -7
- package/docs/roadmap.md +14 -3
- package/docs/troubleshooting.md +88 -21
- package/package.json +3 -3
package/README.md
CHANGED
|
@@ -2,8 +2,8 @@
|
|
|
2
2
|
|
|
3
3
|
GraphQL for [alxia](https://www.npmjs.com/package/@alxia/core), served by
|
|
4
4
|
[GraphQL Yoga](https://the-guild.dev/graphql/yoga-server). The endpoint is a
|
|
5
|
-
route like any other: behind the app's
|
|
6
|
-
resolvers reading the context those
|
|
5
|
+
route like any other: behind the app's middlewares, guarded by its guards, its
|
|
6
|
+
resolvers reading the context those middlewares built — typed, and checked.
|
|
7
7
|
Yoga's plugin system is yours whole: Envelop's plugins and Yoga's own.
|
|
8
8
|
|
|
9
9
|
```sh
|
|
@@ -34,18 +34,18 @@ const schema = createSchema<GraphQLContext<typeof base>>({
|
|
|
34
34
|
},
|
|
35
35
|
});
|
|
36
36
|
|
|
37
|
-
const app = base.
|
|
37
|
+
const app = base.plugin((app) => graphql(app, { schema })); // POST and GET /graphql
|
|
38
38
|
app.listen(3000);
|
|
39
39
|
```
|
|
40
40
|
|
|
41
41
|
`graphql(app, options)` adds `GET` and `POST` routes at `path` —
|
|
42
42
|
`/graphql` by default, under the app's prefix — and returns the app. Given
|
|
43
|
-
to `
|
|
43
|
+
to `app.plugin` as a function, it stays in the chain and sees the app's type.
|
|
44
44
|
|
|
45
45
|
## The context
|
|
46
46
|
|
|
47
47
|
A resolver's context is Yoga's (`request`, `params`), the app's — every
|
|
48
|
-
`decorate`, every `derive`, every
|
|
48
|
+
`decorate`, every `derive`, every middleware's: `user`, `db`, `log`,
|
|
49
49
|
`requestId` — and `set`, through which it sets a header or a cookie:
|
|
50
50
|
|
|
51
51
|
```ts
|
|
@@ -75,7 +75,7 @@ graphql(app, {
|
|
|
75
75
|
schema,
|
|
76
76
|
plugins: [useDepthLimit({ maxDepth: 8 }), useResponseCache({ session: ({ request }) => ... })],
|
|
77
77
|
maskedErrors: true, // Yoga's default: an error's message never leaks
|
|
78
|
-
ide:
|
|
78
|
+
ide: Bun.env.NODE_ENV === 'development' && 'apollo-sandbox', // at runtime, never process.env: bun build inlines it
|
|
79
79
|
batching: true,
|
|
80
80
|
});
|
|
81
81
|
```
|
|
@@ -84,22 +84,45 @@ graphql(app, {
|
|
|
84
84
|
`async *subscribe` in a resolver, `Accept: text/event-stream` on the
|
|
85
85
|
request. `@alxia/compress` leaves an event stream alone by default.
|
|
86
86
|
- **An IDE** answers a `GET` from a browser at the endpoint, with a
|
|
87
|
-
`Content-Security-Policy` that lets it load —
|
|
88
|
-
|
|
87
|
+
`Content-Security-Policy` that lets it load — its pinned files on unpkg
|
|
88
|
+
alone, framed by no one — which `@alxia/secure-headers` keeps. By
|
|
89
|
+
default, GraphiQL in the serving app's dev alone (`NODE_ENV=development`,
|
|
90
|
+
or `alxia({ dev: true })`), none otherwise; `ide` chooses one everywhere:
|
|
89
91
|
|
|
90
92
|
```ts
|
|
93
|
+
graphql(app, { schema }); // GraphiQL in dev, nothing deployed
|
|
91
94
|
graphql(app, { schema, ide: 'apollo-sandbox', sandbox: { initialDocument: '{ me }' } });
|
|
92
|
-
graphql(app, { schema, ide: Bun.env.NODE_ENV === 'production' ? false : 'graphiql' });
|
|
93
95
|
```
|
|
94
96
|
|
|
95
97
|
| `ide` | |
|
|
96
98
|
| --- | --- |
|
|
97
|
-
|
|
|
99
|
+
| none (default) | Yoga's GraphiQL in dev (`isDev`), nothing otherwise |
|
|
100
|
+
| `'graphiql'` | Yoga's GraphiQL, everywhere; `graphiql` takes its options |
|
|
98
101
|
| `'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`, `pollForSchemaUpdates`, `includeCookies` |
|
|
99
102
|
| `false` | none |
|
|
100
103
|
- **CORS** is `@alxia/cors`'s for the whole app: Yoga's own is off unless
|
|
101
104
|
`cors` is given.
|
|
102
105
|
|
|
106
|
+
## Errors, health and shutdown
|
|
107
|
+
|
|
108
|
+
A GraphQL error stays GraphQL's — an entry of `errors[]`, inside a 200 —
|
|
109
|
+
while `@alxia/core`'s `alxia({ errors: 'problem' })` makes the HTTP layer
|
|
110
|
+
around the endpoint answer RFC 9457 problems: a guard's 401, a 413, a
|
|
111
|
+
500. `health()` mounts beside it, and on `SIGTERM` the queries in flight
|
|
112
|
+
are answered and the subscriptions ended before the process exits:
|
|
113
|
+
|
|
114
|
+
```ts
|
|
115
|
+
import { alxia, health } from '@alxia/core';
|
|
116
|
+
import { graphql } from '@alxia/graphql';
|
|
117
|
+
|
|
118
|
+
const app = alxia({ errors: 'problem' })
|
|
119
|
+
.plugin(health())
|
|
120
|
+
.plugin((app) => graphql(app, { schema }));
|
|
121
|
+
app.listen({ port: 4000 });
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
See [the endpoint guide](https://github.com/softistx/alxia/blob/develop/packages/graphql/docs/guide/endpoint.md#errors-health-and-shutdown).
|
|
125
|
+
|
|
103
126
|
## API
|
|
104
127
|
|
|
105
128
|
| export | |
|
|
@@ -108,10 +131,11 @@ graphql(app, {
|
|
|
108
131
|
| `renderSandbox(endpoint, options?)`, `SANDBOX_POLICY` | the Sandbox page, and the policy it loads under |
|
|
109
132
|
| `SandboxOptions` | its options: `title`, `initialDocument`, `initialHeaders`, `pollForSchemaUpdates`, `includeCookies` |
|
|
110
133
|
| `GraphQLContext<App, UserContext?>` | what a resolver reads |
|
|
111
|
-
| `ServerContext<Ctx>`, `GraphQLOptions
|
|
134
|
+
| `ServerContext<Ctx>`, `GraphQLOptions` | its types |
|
|
112
135
|
|
|
113
136
|
## Documentation
|
|
114
137
|
|
|
115
138
|
- [Guide](https://github.com/softistx/alxia/tree/develop/packages/graphql/docs): a page per area — mounting the endpoint, the typed context, Yoga's plugins and options, and GraphiQL and Apollo Sandbox.
|
|
116
139
|
- [Troubleshooting](https://github.com/softistx/alxia/blob/develop/packages/graphql/docs/troubleshooting.md): an error message, and what to do about it.
|
|
117
140
|
- [Roadmap](https://github.com/softistx/alxia/blob/develop/packages/graphql/docs/roadmap.md): what is coming, and what is not planned.
|
|
141
|
+
- [Recipes](https://github.com/softistx/alxia/blob/develop/docs/recipes/README.md): [A GraphQL API](https://github.com/softistx/alxia/blob/develop/docs/recipes/graphql-api.md), [Authenticate requests](https://github.com/softistx/alxia/blob/develop/docs/recipes/authentication.md), [Test an alxia app](https://github.com/softistx/alxia/blob/develop/docs/recipes/testing.md), [Health checks and graceful shutdown](https://github.com/softistx/alxia/blob/develop/docs/recipes/health-and-shutdown.md), and more.
|
package/dist/graphql.d.ts
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import type
|
|
1
|
+
import { type Alxia, type BaseContext, type Empty, type RoutePath } from '@alxia/core';
|
|
2
2
|
import type { GraphQLSchemaWithContext, YogaInitialContext, YogaServerOptions } from 'graphql-yoga';
|
|
3
3
|
import { type YogaContext } from './handler';
|
|
4
4
|
import type { SandboxOptions } from './sandbox';
|
|
5
5
|
/** The parts of a route's context Yoga owns, or that mean nothing to a resolver. */
|
|
6
6
|
type RouteOnly = 'params' | 'query' | 'headers' | 'cookies' | 'body' | 'reply' | 'redirect';
|
|
7
7
|
/**
|
|
8
|
-
* What alxia hands Yoga for each request: the context its
|
|
8
|
+
* What alxia hands Yoga for each request: the context its middlewares built —
|
|
9
9
|
* `user`, `db`, `log`… — with `request`, `url`, `ip` and `set`, through
|
|
10
10
|
* which a resolver sets a cookie or a header on the response.
|
|
11
11
|
*/
|
|
@@ -27,7 +27,9 @@ export type GraphQLContext<App, UserContext = Empty> = App extends {
|
|
|
27
27
|
export interface GraphQLOptions<ServerCtx extends YogaContext, UserCtx extends YogaContext, Path extends RoutePath, SchemaCtx = unknown> extends Omit<YogaServerOptions<ServerCtx, UserCtx>, 'graphqlEndpoint' | 'cors' | 'schema' | 'graphiql'> {
|
|
28
28
|
/**
|
|
29
29
|
* What a browser gets at the endpoint: Yoga's GraphiQL, Apollo Sandbox,
|
|
30
|
-
* or nothing. GraphiQL
|
|
30
|
+
* or nothing. By default, GraphiQL in the serving app's dev alone
|
|
31
|
+
* (`isDev`: `alxia({ dev })`, else `NODE_ENV=development`), nothing
|
|
32
|
+
* otherwise; `graphiql` or `apollo-sandbox` serves one everywhere.
|
|
31
33
|
*/
|
|
32
34
|
readonly ide?: 'graphiql' | 'apollo-sandbox' | false;
|
|
33
35
|
/** GraphiQL's options, Yoga's own, when `ide` is `graphiql`. */
|
|
@@ -37,7 +39,7 @@ export interface GraphQLOptions<ServerCtx extends YogaContext, UserCtx extends Y
|
|
|
37
39
|
/**
|
|
38
40
|
* The schema, from Yoga's `createSchema`, Pothos, or any tool that types
|
|
39
41
|
* its context. Its context must be one the app builds: a resolver that
|
|
40
|
-
* reads `user` behind no
|
|
42
|
+
* reads `user` behind no middleware that adds one is a compile error.
|
|
41
43
|
*/
|
|
42
44
|
readonly schema: GraphQLSchemaWithContext<SchemaCtx>;
|
|
43
45
|
/** Where the endpoint is, under the app's prefix. `/graphql` by default. */
|
|
@@ -56,13 +58,10 @@ export interface GraphQLOptions<ServerCtx extends YogaContext, UserCtx extends Y
|
|
|
56
58
|
type ProvidesContext<Provided, Required> = Provided extends Required ? unknown : {
|
|
57
59
|
readonly schema: `the schema's resolvers read a context the app does not build: missing ${Exclude<keyof Required, keyof Provided> & string}`;
|
|
58
60
|
};
|
|
59
|
-
/** What the endpoint answers, as alxia's client sees it: a body to read as GraphQL. */
|
|
60
|
-
type GraphQLReply = Reply<StatusCode, ReadableStream<Uint8Array> | undefined>;
|
|
61
|
-
export type GraphQLRoutes<Path extends string, Shortcuts extends AnyReply> = RouteEntryOf<'GET', Path, Empty, GraphQLReply, Shortcuts> & RouteEntryOf<'POST', Path, Empty, GraphQLReply, Shortcuts>;
|
|
62
61
|
/**
|
|
63
62
|
* A GraphQL endpoint on `app`, served by [GraphQL Yoga](https://the-guild.dev/graphql/yoga-server):
|
|
64
|
-
* `GET` and `POST` at `path`, behind every
|
|
65
|
-
* A guard before it guards it; what the
|
|
63
|
+
* `GET` and `POST` at `path`, behind every middleware given to `use` on `app`
|
|
64
|
+
* before it. A guard before it guards it; what the middlewares added is in each
|
|
66
65
|
* resolver's context, typed. Yoga's options pass through — `plugins`
|
|
67
66
|
* (Envelop's and Yoga's), `graphiql`, `maskedErrors`, `batching`… —
|
|
68
67
|
* and subscriptions are served over server-sent events.
|
|
@@ -70,9 +69,9 @@ export type GraphQLRoutes<Path extends string, Shortcuts extends AnyReply> = Rou
|
|
|
70
69
|
* ```ts
|
|
71
70
|
* const app = alxia()
|
|
72
71
|
* .use(bearer({ jwt }))
|
|
73
|
-
* .
|
|
72
|
+
* .plugin((app) => graphql(app, { schema, plugins: [useDepthLimit()] }));
|
|
74
73
|
* ```
|
|
75
74
|
*/
|
|
76
|
-
export declare function graphql<Ctx extends object,
|
|
75
|
+
export declare function graphql<Ctx extends object, Prefix extends string, SchemaCtx, UserCtx extends YogaContext = Empty, const Path extends RoutePath = '/graphql'>(app: Alxia<Ctx, Prefix>, options: GraphQLOptions<ServerContext<Ctx>, UserCtx, Path, SchemaCtx> & ProvidesContext<YogaInitialContext & ServerContext<Ctx> & UserCtx, SchemaCtx>): Alxia<Ctx, Prefix>;
|
|
77
76
|
export {};
|
|
78
77
|
//# sourceMappingURL=graphql.d.ts.map
|
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,KAAK,
|
|
1
|
+
{"version":3,"file":"graphql.d.ts","sourceRoot":"","sources":["../src/graphql.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,KAAK,KAAK,EACV,KAAK,WAAW,EAChB,KAAK,KAAK,EAEV,KAAK,SAAS,EACd,MAAM,aAAa,CAAC;AACrB,OAAO,KAAK,EACX,wBAAwB,EACxB,kBAAkB,EAClB,iBAAiB,EACjB,MAAM,cAAc,CAAC;AACtB,OAAO,EAAkB,KAAK,WAAW,EAAe,MAAM,WAAW,CAAC;AAC1E,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAEhD,oFAAoF;AACpF,KAAK,SAAS,GACX,QAAQ,GACR,OAAO,GACP,SAAS,GACT,SAAS,GACT,MAAM,GACN,OAAO,GACP,UAAU,CAAC;AAEd;;;;GAIG;AACH,MAAM,MAAM,aAAa,CAAC,GAAG,IAAI,IAAI,CAAC,WAAW,GAAG,GAAG,EAAE,SAAS,CAAC,CAAC;AAEpE;;;;;;;;GAQG;AACH,MAAM,MAAM,cAAc,CAAC,GAAG,EAAE,WAAW,GAAG,KAAK,IAAI,GAAG,SAAS;IAClE,QAAQ,CAAC,UAAU,EAAE,MAAM,GAAG,CAAC;CAC/B,GACE,kBAAkB,GAAG,aAAa,CAAC,GAAG,CAAC,GAAG,WAAW,GAGtD;IACC,QAAQ,CAAC,QAAQ,EAAE,qEAAqE,CAAC;CACzF,CAAC;AAEJ,MAAM,WAAW,cAAc,CAC9B,SAAS,SAAS,WAAW,EAC7B,OAAO,SAAS,WAAW,EAC3B,IAAI,SAAS,SAAS,EACtB,SAAS,GAAG,OAAO,CAClB,SAAQ,IAAI,CACZ,iBAAiB,CAAC,SAAS,EAAE,OAAO,CAAC,EACrC,iBAAiB,GAAG,MAAM,GAAG,QAAQ,GAAG,UAAU,CAClD;IACD;;;;;OAKG;IACH,QAAQ,CAAC,GAAG,CAAC,EAAE,UAAU,GAAG,gBAAgB,GAAG,KAAK,CAAC;IACrD,gEAAgE;IAChE,QAAQ,CAAC,QAAQ,CAAC,EAAE,OAAO,CAC1B,iBAAiB,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC,UAAU,CAAC,EACjD,OAAO,CACP,CAAC;IACF,gEAAgE;IAChE,QAAQ,CAAC,OAAO,CAAC,EAAE,cAAc,CAAC;IAClC;;;;OAIG;IACH,QAAQ,CAAC,MAAM,EAAE,wBAAwB,CAAC,SAAS,CAAC,CAAC;IACrD,4EAA4E;IAC5E,QAAQ,CAAC,IAAI,CAAC,EAAE,IAAI,CAAC;IACrB;;;OAGG;IACH,QAAQ,CAAC,IAAI,CAAC,EAAE,iBAAiB,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC,MAAM,CAAC,CAAC;CAC9D;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;;;;;;;;;;;;;GAaG;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,CA+BpB"}
|
package/dist/handler.d.ts
CHANGED
|
@@ -2,10 +2,19 @@
|
|
|
2
2
|
* The endpoint behind `graphql()`: one Yoga per path it is served at, and
|
|
3
3
|
* the route handler that hands each request to it.
|
|
4
4
|
*/
|
|
5
|
-
import type
|
|
5
|
+
import { type BaseContext, type StatusCode } from '@alxia/core';
|
|
6
6
|
import { type YogaServerInstance, type YogaServerOptions } from 'graphql-yoga';
|
|
7
7
|
import { type SandboxOptions } from './sandbox';
|
|
8
8
|
export type YogaContext = Record<string, any>;
|
|
9
|
+
/**
|
|
10
|
+
* What GraphiQL's page may load: its scripts, styles and Monaco's
|
|
11
|
+
* workers from the exact version of `@graphql-yoga/graphiql` the page
|
|
12
|
+
* names, fetched and run as blobs; queries to this server alone; framed
|
|
13
|
+
* by no one. A page that names none (a `renderGraphiQL` of the app's own)
|
|
14
|
+
* gets this server alone. `@alxia/secure-headers` keeps a policy a
|
|
15
|
+
* response already has.
|
|
16
|
+
*/
|
|
17
|
+
export declare function graphiqlPolicy(html: string): string;
|
|
9
18
|
/**
|
|
10
19
|
* The Yoga serving `endpoint`, created on first use. One per path: a plugin
|
|
11
20
|
* mounted under a prefix serves the same routes at a longer path, and
|
|
@@ -15,8 +24,10 @@ export declare function yogaServers<UserCtx extends YogaContext>(options: Omit<Y
|
|
|
15
24
|
/**
|
|
16
25
|
* The handler of the endpoint's `GET` and `POST`: Apollo Sandbox's page to
|
|
17
26
|
* a browser when `sandbox` is not `false`, else the request to Yoga, with
|
|
18
|
-
* the route's context — the
|
|
27
|
+
* the route's context — the middlewares' work, minus what a resolver has no use
|
|
19
28
|
* for — as Yoga's server context.
|
|
20
29
|
*/
|
|
21
|
-
export declare function graphqlHandler<UserCtx extends YogaContext>(yogaAt: (endpoint: string) => YogaServerInstance<YogaContext, UserCtx>, sandbox: SandboxOptions | false): (ctx: Record<string, unknown> & BaseContext
|
|
30
|
+
export declare function graphqlHandler<UserCtx extends YogaContext>(yogaAt: (endpoint: string) => YogaServerInstance<YogaContext, UserCtx>, sandbox: SandboxOptions | false): (ctx: Record<string, unknown> & BaseContext & {
|
|
31
|
+
readonly route: string;
|
|
32
|
+
}) => Promise<import("@alxia/core").Reply<StatusCode, string> | import("@alxia/core").Reply<StatusCode, ReadableStream<Uint8Array<ArrayBufferLike>>>>;
|
|
22
33
|
//# sourceMappingURL=handler.d.ts.map
|
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,KAAK,
|
|
1
|
+
{"version":3,"file":"handler.d.ts","sourceRoot":"","sources":["../src/handler.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAE,KAAK,WAAW,EAAE,KAAK,UAAU,EAAkB,MAAM,aAAa,CAAC;AAChF,OAAO,EAEN,KAAK,kBAAkB,EACvB,KAAK,iBAAiB,EACtB,MAAM,cAAc,CAAC;AACtB,OAAO,EAAiC,KAAK,cAAc,EAAE,MAAM,WAAW,CAAC;AAE/E,MAAM,MAAM,WAAW,GAAG,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;AAM9C;;;;;;;GAOG;AACH,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAanD;AAED;;;;GAIG;AACH,wBAAgB,WAAW,CAAC,OAAO,SAAS,WAAW,EACtD,OAAO,EAAE,IAAI,CAAC,iBAAiB,CAAC,WAAW,EAAE,OAAO,CAAC,EAAE,iBAAiB,CAAC,GACvE,CAAC,QAAQ,EAAE,MAAM,KAAK,kBAAkB,CAAC,WAAW,EAAE,OAAO,CAAC,CAahE;AAED;;;;;GAKG;AACH,wBAAgB,cAAc,CAAC,OAAO,SAAS,WAAW,EACzD,MAAM,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,kBAAkB,CAAC,WAAW,EAAE,OAAO,CAAC,EACtE,OAAO,EAAE,cAAc,GAAG,KAAK,IAK9B,KAAK,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,WAAW,GAAG;IAAE,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAA;CAAE,qJA2CxE"}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
export { type GraphQLContext, type GraphQLOptions,
|
|
1
|
+
export { type GraphQLContext, type GraphQLOptions, graphql, type ServerContext, } from './graphql';
|
|
2
2
|
export { renderSandbox, SANDBOX_POLICY, type SandboxOptions } from './sandbox';
|
|
3
3
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,KAAK,cAAc,EACnB,KAAK,cAAc,EACnB,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,KAAK,cAAc,EACnB,KAAK,cAAc,EACnB,OAAO,EACP,KAAK,aAAa,GAClB,MAAM,WAAW,CAAC;AACnB,OAAO,EAAE,aAAa,EAAE,cAAc,EAAE,KAAK,cAAc,EAAE,MAAM,WAAW,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,10 @@
|
|
|
1
|
+
// src/graphql.ts
|
|
2
|
+
import {
|
|
3
|
+
isDev
|
|
4
|
+
} from "@alxia/core";
|
|
5
|
+
|
|
1
6
|
// src/handler.ts
|
|
7
|
+
import { shutdownSignal } from "@alxia/core";
|
|
2
8
|
import {
|
|
3
9
|
createYoga
|
|
4
10
|
} from "graphql-yoga";
|
|
@@ -54,15 +60,21 @@ function script(value) {
|
|
|
54
60
|
}
|
|
55
61
|
|
|
56
62
|
// src/handler.ts
|
|
57
|
-
var
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
"
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
63
|
+
var GRAPHIQL_FILES = /https:\/\/unpkg\.com\/@graphql-yoga\/graphiql@[\w.-]+\//;
|
|
64
|
+
function graphiqlPolicy(html) {
|
|
65
|
+
const files = html.match(GRAPHIQL_FILES)?.[0] ?? "";
|
|
66
|
+
const from = files === "" ? "" : ` ${files}`;
|
|
67
|
+
return [
|
|
68
|
+
"default-src 'self'",
|
|
69
|
+
`script-src 'self' 'unsafe-inline'${from}`,
|
|
70
|
+
`style-src 'self' 'unsafe-inline'${from}`,
|
|
71
|
+
"img-src 'self' data: https:",
|
|
72
|
+
`font-src 'self' data:${from}`,
|
|
73
|
+
"worker-src 'self' blob:",
|
|
74
|
+
`connect-src 'self'${from}`,
|
|
75
|
+
"frame-ancestors 'none'"
|
|
76
|
+
].join("; ");
|
|
77
|
+
}
|
|
66
78
|
function yogaServers(options) {
|
|
67
79
|
const servers = new Map;
|
|
68
80
|
return (endpoint) => {
|
|
@@ -78,7 +90,7 @@ function yogaServers(options) {
|
|
|
78
90
|
};
|
|
79
91
|
}
|
|
80
92
|
function graphqlHandler(yogaAt, sandbox) {
|
|
81
|
-
return async (ctx)
|
|
93
|
+
return async function graphql(ctx) {
|
|
82
94
|
const {
|
|
83
95
|
params: _params,
|
|
84
96
|
query: _query,
|
|
@@ -100,28 +112,65 @@ function graphqlHandler(yogaAt, sandbox) {
|
|
|
100
112
|
const response = await yogaAt(ctx.route).fetch(ctx.request, server);
|
|
101
113
|
const headers = new Headers(response.headers);
|
|
102
114
|
if (headers.get("content-type")?.startsWith("text/html") && !headers.has("content-security-policy")) {
|
|
103
|
-
|
|
115
|
+
const html = await response.text();
|
|
116
|
+
headers.set("content-security-policy", graphiqlPolicy(html));
|
|
117
|
+
return reply(response.status, html, { headers });
|
|
104
118
|
}
|
|
105
|
-
|
|
119
|
+
const body = endedOnShutdown(response, shutdownSignal(ctx));
|
|
120
|
+
return reply(response.status, body ?? undefined, {
|
|
106
121
|
headers
|
|
107
122
|
});
|
|
108
123
|
};
|
|
109
124
|
}
|
|
125
|
+
function endedOnShutdown(response, signal) {
|
|
126
|
+
const body = response.body;
|
|
127
|
+
const type = response.headers.get("content-type") ?? "";
|
|
128
|
+
if (body === null || !/text\/event-stream|multipart\/mixed/.test(type)) {
|
|
129
|
+
return body;
|
|
130
|
+
}
|
|
131
|
+
const reader = body.getReader();
|
|
132
|
+
return new ReadableStream({
|
|
133
|
+
start(controller) {
|
|
134
|
+
const end = () => {
|
|
135
|
+
reader.cancel();
|
|
136
|
+
try {
|
|
137
|
+
controller.close();
|
|
138
|
+
} catch {}
|
|
139
|
+
};
|
|
140
|
+
if (signal.aborted)
|
|
141
|
+
end();
|
|
142
|
+
else
|
|
143
|
+
signal.addEventListener("abort", end, { once: true });
|
|
144
|
+
},
|
|
145
|
+
async pull(controller) {
|
|
146
|
+
const { value, done } = await reader.read();
|
|
147
|
+
if (done) {
|
|
148
|
+
try {
|
|
149
|
+
controller.close();
|
|
150
|
+
} catch {}
|
|
151
|
+
return;
|
|
152
|
+
}
|
|
153
|
+
controller.enqueue(value);
|
|
154
|
+
},
|
|
155
|
+
cancel: (reason) => reader.cancel(reason)
|
|
156
|
+
});
|
|
157
|
+
}
|
|
110
158
|
|
|
111
159
|
// src/graphql.ts
|
|
112
160
|
function graphql(app, options) {
|
|
113
161
|
const {
|
|
114
162
|
path = "/graphql",
|
|
115
163
|
cors = false,
|
|
116
|
-
ide
|
|
164
|
+
ide,
|
|
117
165
|
graphiql,
|
|
118
166
|
sandbox,
|
|
119
167
|
...yogaOptions
|
|
120
168
|
} = options;
|
|
169
|
+
const page = graphiql ?? true;
|
|
121
170
|
const yogaAt = yogaServers({
|
|
122
171
|
...yogaOptions,
|
|
123
172
|
cors,
|
|
124
|
-
graphiql: ide === "graphiql" ?
|
|
173
|
+
graphiql: ide === undefined ? (_request, context) => isDev(context) && page : ide === "graphiql" ? page : false
|
|
125
174
|
});
|
|
126
175
|
const handler = graphqlHandler(yogaAt, ide === "apollo-sandbox" ? sandbox ?? {} : false);
|
|
127
176
|
const route = app;
|
|
@@ -135,5 +184,5 @@ export {
|
|
|
135
184
|
renderSandbox
|
|
136
185
|
};
|
|
137
186
|
|
|
138
|
-
//# debugId=
|
|
187
|
+
//# debugId=36F374D7B3E2E7EE64756E2164756E21
|
|
139
188
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../src/
|
|
3
|
+
"sources": ["../src/graphql.ts", "../src/handler.ts", "../src/sandbox.ts"],
|
|
4
4
|
"sourcesContent": [
|
|
5
|
-
"
|
|
6
|
-
"/**\n *
|
|
7
|
-
"
|
|
5
|
+
"import {\n\ttype Alxia,\n\ttype BaseContext,\n\ttype Empty,\n\tisDev,\n\ttype RoutePath,\n} from '@alxia/core';\nimport type {\n\tGraphQLSchemaWithContext,\n\tYogaInitialContext,\n\tYogaServerOptions,\n} from 'graphql-yoga';\nimport { graphqlHandler, type YogaContext, yogaServers } from './handler';\nimport type { SandboxOptions } from './sandbox';\n\n/** The parts of a route's context Yoga owns, or that mean nothing to a resolver. */\ntype RouteOnly =\n\t| 'params'\n\t| 'query'\n\t| 'headers'\n\t| 'cookies'\n\t| 'body'\n\t| 'reply'\n\t| 'redirect';\n\n/**\n * What alxia hands Yoga for each request: the context its middlewares built —\n * `user`, `db`, `log`… — with `request`, `url`, `ip` and `set`, through\n * which a resolver sets a cookie or a header on the response.\n */\nexport type ServerContext<Ctx> = Omit<BaseContext & Ctx, RouteOnly>;\n\n/**\n * What a resolver reads as its context: Yoga's own, the app's, and what\n * the `context` option adds. Type a schema with it:\n *\n * ```ts\n * const base = alxia().use(bearer({ jwt }));\n * const schema = createSchema<GraphQLContext<typeof base>>({ ... });\n * ```\n */\nexport type GraphQLContext<App, UserContext = Empty> = App extends {\n\treadonly '~context': infer Ctx;\n}\n\t? YogaInitialContext & ServerContext<Ctx> & UserContext\n\t: // Not `never`: a schema typed with `never` would let every resolver\n\t\t// read anything until `graphql()` refused it.\n\t\t{\n\t\t\treadonly '~error': 'GraphQLContext needs the type of an app: GraphQLContext<typeof app>';\n\t\t};\n\nexport interface GraphQLOptions<\n\tServerCtx extends YogaContext,\n\tUserCtx extends YogaContext,\n\tPath extends RoutePath,\n\tSchemaCtx = unknown,\n> extends Omit<\n\t\tYogaServerOptions<ServerCtx, UserCtx>,\n\t\t'graphqlEndpoint' | 'cors' | 'schema' | 'graphiql'\n\t> {\n\t/**\n\t * What a browser gets at the endpoint: Yoga's GraphiQL, Apollo Sandbox,\n\t * or nothing. By default, GraphiQL in the serving app's dev alone\n\t * (`isDev`: `alxia({ dev })`, else `NODE_ENV=development`), nothing\n\t * otherwise; `graphiql` or `apollo-sandbox` serves one everywhere.\n\t */\n\treadonly ide?: 'graphiql' | 'apollo-sandbox' | false;\n\t/** GraphiQL's options, Yoga's own, when `ide` is `graphiql`. */\n\treadonly graphiql?: Exclude<\n\t\tYogaServerOptions<ServerCtx, UserCtx>['graphiql'],\n\t\tboolean\n\t>;\n\t/** Apollo Sandbox's options, when `ide` is `apollo-sandbox`. */\n\treadonly sandbox?: SandboxOptions;\n\t/**\n\t * The schema, from Yoga's `createSchema`, Pothos, or any tool that types\n\t * its context. Its context must be one the app builds: a resolver that\n\t * reads `user` behind no middleware that adds one is a compile error.\n\t */\n\treadonly schema: GraphQLSchemaWithContext<SchemaCtx>;\n\t/** Where the endpoint is, under the app's prefix. `/graphql` by default. */\n\treadonly path?: Path;\n\t/**\n\t * Yoga's own CORS. Off by default: `@alxia/cors` answers for the whole\n\t * app, this endpoint included.\n\t */\n\treadonly cors?: YogaServerOptions<ServerCtx, UserCtx>['cors'];\n}\n\n/**\n * The check Yoga's types leave out: the context the app builds must hold\n * what the schema's resolvers read. A mistake comes back as a `schema`\n * whose type is the message.\n */\ntype ProvidesContext<Provided, Required> = Provided extends Required\n\t? unknown\n\t: {\n\t\t\treadonly schema: `the schema's resolvers read a context the app does not build: missing ${Exclude<\n\t\t\t\tkeyof Required,\n\t\t\t\tkeyof Provided\n\t\t\t> &\n\t\t\t\tstring}`;\n\t\t};\n\n/**\n * A GraphQL endpoint on `app`, served by [GraphQL Yoga](https://the-guild.dev/graphql/yoga-server):\n * `GET` and `POST` at `path`, behind every middleware given to `use` on `app`\n * before it. A guard before it guards it; what the middlewares added is in each\n * resolver's context, typed. Yoga's options pass through — `plugins`\n * (Envelop's and Yoga's), `graphiql`, `maskedErrors`, `batching`… —\n * and subscriptions are served over server-sent events.\n *\n * ```ts\n * const app = alxia()\n * .use(bearer({ jwt }))\n * .plugin((app) => graphql(app, { schema, plugins: [useDepthLimit()] }));\n * ```\n */\nexport function graphql<\n\tCtx extends object,\n\tPrefix extends string,\n\tSchemaCtx,\n\tUserCtx extends YogaContext = Empty,\n\tconst Path extends RoutePath = '/graphql',\n>(\n\tapp: Alxia<Ctx, Prefix>,\n\toptions: GraphQLOptions<ServerContext<Ctx>, UserCtx, Path, SchemaCtx> &\n\t\tProvidesContext<\n\t\t\tYogaInitialContext & ServerContext<Ctx> & UserCtx,\n\t\t\tSchemaCtx\n\t\t>,\n): Alxia<Ctx, Prefix> {\n\tconst {\n\t\tpath = '/graphql' as Path,\n\t\tcors = false,\n\t\tide,\n\t\tgraphiql,\n\t\tsandbox,\n\t\t...yogaOptions\n\t} = options;\n\tconst page = graphiql ?? true;\n\tconst yogaAt = yogaServers<UserCtx>({\n\t\t...(yogaOptions as YogaServerOptions<YogaContext, UserCtx>),\n\t\tcors,\n\t\tgraphiql: (ide === undefined\n\t\t\t? (_request: Request, context: object) => isDev(context) && page\n\t\t\t: ide === 'graphiql'\n\t\t\t\t? page\n\t\t\t\t: false) as YogaServerOptions<YogaContext, UserCtx>['graphiql'],\n\t});\n\tconst handler = graphqlHandler(\n\t\tyogaAt,\n\t\tide === 'apollo-sandbox' ? (sandbox ?? {}) : false,\n\t);\n\n\tconst route = app as unknown as {\n\t\tget(path: string, handler: unknown): unknown;\n\t\tpost(path: string, handler: unknown): unknown;\n\t};\n\troute.get(path, handler);\n\troute.post(path, handler);\n\treturn app as never;\n}\n",
|
|
6
|
+
"/**\n * The endpoint behind `graphql()`: one Yoga per path it is served at, and\n * the route handler that hands each request to it.\n */\nimport { type BaseContext, type StatusCode, shutdownSignal } from '@alxia/core';\nimport {\n\tcreateYoga,\n\ttype YogaServerInstance,\n\ttype YogaServerOptions,\n} from 'graphql-yoga';\nimport { renderSandbox, SANDBOX_POLICY, type SandboxOptions } from './sandbox';\n\nexport type YogaContext = Record<string, any>;\n\n/** Where Yoga's GraphiQL page loads its files from: one pinned version on unpkg. */\nconst GRAPHIQL_FILES =\n\t/https:\\/\\/unpkg\\.com\\/@graphql-yoga\\/graphiql@[\\w.-]+\\//;\n\n/**\n * What GraphiQL's page may load: its scripts, styles and Monaco's\n * workers from the exact version of `@graphql-yoga/graphiql` the page\n * names, fetched and run as blobs; queries to this server alone; framed\n * by no one. A page that names none (a `renderGraphiQL` of the app's own)\n * gets this server alone. `@alxia/secure-headers` keeps a policy a\n * response already has.\n */\nexport function graphiqlPolicy(html: string): string {\n\tconst files = html.match(GRAPHIQL_FILES)?.[0] ?? '';\n\tconst from = files === '' ? '' : ` ${files}`;\n\treturn [\n\t\t\"default-src 'self'\",\n\t\t`script-src 'self' 'unsafe-inline'${from}`,\n\t\t`style-src 'self' 'unsafe-inline'${from}`,\n\t\t\"img-src 'self' data: https:\",\n\t\t`font-src 'self' data:${from}`,\n\t\t\"worker-src 'self' blob:\",\n\t\t`connect-src 'self'${from}`,\n\t\t\"frame-ancestors 'none'\",\n\t].join('; ');\n}\n\n/**\n * The Yoga serving `endpoint`, created on first use. One per path: a plugin\n * mounted under a prefix serves the same routes at a longer path, and\n * GraphiQL must ask that one.\n */\nexport function yogaServers<UserCtx extends YogaContext>(\n\toptions: Omit<YogaServerOptions<YogaContext, UserCtx>, 'graphqlEndpoint'>,\n): (endpoint: string) => YogaServerInstance<YogaContext, UserCtx> {\n\tconst servers = new Map<string, YogaServerInstance<YogaContext, UserCtx>>();\n\treturn (endpoint) => {\n\t\tlet yoga = servers.get(endpoint);\n\t\tif (yoga === undefined) {\n\t\t\tyoga = createYoga<YogaContext, UserCtx>({\n\t\t\t\t...options,\n\t\t\t\tgraphqlEndpoint: endpoint,\n\t\t\t});\n\t\t\tservers.set(endpoint, yoga);\n\t\t}\n\t\treturn yoga;\n\t};\n}\n\n/**\n * The handler of the endpoint's `GET` and `POST`: Apollo Sandbox's page to\n * a browser when `sandbox` is not `false`, else the request to Yoga, with\n * the route's context — the middlewares' work, minus what a resolver has no use\n * for — as Yoga's server context.\n */\nexport function graphqlHandler<UserCtx extends YogaContext>(\n\tyogaAt: (endpoint: string) => YogaServerInstance<YogaContext, UserCtx>,\n\tsandbox: SandboxOptions | false,\n) {\n\t// A handler's context: its route is the one it was declared at. Named\n\t// `graphql`, the name the route table `listen` prints in dev shows.\n\treturn async function graphql(\n\t\tctx: Record<string, unknown> & BaseContext & { readonly route: string },\n\t) {\n\t\tconst {\n\t\t\tparams: _params,\n\t\t\tquery: _query,\n\t\t\theaders: _headers,\n\t\t\tcookies: _cookies,\n\t\t\tbody: _body,\n\t\t\treply,\n\t\t\tredirect: _redirect,\n\t\t\t...server\n\t\t} = ctx;\n\t\tif (\n\t\t\tsandbox !== false &&\n\t\t\tctx.request.method === 'GET' &&\n\t\t\tctx.request.headers.get('accept')?.includes('text/html') &&\n\t\t\t!ctx.url.searchParams.has('query')\n\t\t) {\n\t\t\t// A path: the page resolves it against its own address, so behind\n\t\t\t// a TLS proxy the Sandbox asks over https, as the browser did.\n\t\t\treturn reply(200, renderSandbox(ctx.route, sandbox), {\n\t\t\t\theaders: {\n\t\t\t\t\t'content-type': 'text/html;charset=utf-8',\n\t\t\t\t\t'content-security-policy': SANDBOX_POLICY,\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\t\tconst response = await yogaAt(ctx.route).fetch(ctx.request, server);\n\t\tconst headers = new Headers(response.headers);\n\t\tif (\n\t\t\theaders.get('content-type')?.startsWith('text/html') &&\n\t\t\t!headers.has('content-security-policy')\n\t\t) {\n\t\t\t// GraphiQL's page: its policy names the files it loads.\n\t\t\tconst html = await response.text();\n\t\t\theaders.set('content-security-policy', graphiqlPolicy(html));\n\t\t\treturn reply(response.status as StatusCode, html, { headers });\n\t\t}\n\t\tconst body = endedOnShutdown(response, shutdownSignal(ctx));\n\t\treturn reply(response.status as StatusCode, body ?? undefined, {\n\t\t\theaders,\n\t\t});\n\t};\n}\n\n/**\n * A subscription's or an incremental delivery's body, which streams until\n * its reader stops: ended when the app starts shutting down — Yoga's\n * stream cancelled, as when the client leaves, and the client reading its\n * end — so the drain does not wait for it. Any other body finishes within\n * the drain as it is.\n */\nfunction endedOnShutdown(\n\tresponse: Response,\n\tsignal: AbortSignal,\n): ReadableStream<Uint8Array> | null {\n\tconst body = response.body;\n\tconst type = response.headers.get('content-type') ?? '';\n\tif (body === null || !/text\\/event-stream|multipart\\/mixed/.test(type)) {\n\t\treturn body;\n\t}\n\tconst reader = body.getReader();\n\treturn new ReadableStream<Uint8Array>({\n\t\tstart(controller) {\n\t\t\tconst end = () => {\n\t\t\t\tvoid reader.cancel();\n\t\t\t\ttry {\n\t\t\t\t\tcontroller.close();\n\t\t\t\t} catch {\n\t\t\t\t\t// Closed already: the stream had ended.\n\t\t\t\t}\n\t\t\t};\n\t\t\tif (signal.aborted) end();\n\t\t\telse signal.addEventListener('abort', end, { once: true });\n\t\t},\n\t\tasync pull(controller) {\n\t\t\tconst { value, done } = await reader.read();\n\t\t\tif (done) {\n\t\t\t\ttry {\n\t\t\t\t\tcontroller.close();\n\t\t\t\t} catch {\n\t\t\t\t\t// Closed already: the shutdown ended it.\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcontroller.enqueue(value);\n\t\t},\n\t\tcancel: (reason) => reader.cancel(reason),\n\t});\n}\n",
|
|
7
|
+
"/**\n * [Apollo Sandbox](https://www.apollographql.com/docs/graphos/platform/sandbox),\n * embedded: the page a browser gets at the endpoint when the IDE is\n * `apollo-sandbox`. `@nxgt/shared-graphql`'s `renderSandbox`, kept twice: the\n * Sandbox asks the address the page was opened at, as there since\n * nxgt-core#171, but here the page resolves the path itself, so a TLS proxy\n * in front changes nothing.\n */\n\nexport interface SandboxOptions {\n\t/** The page's title. `Sandbox Explorer` by default. */\n\treadonly title?: string;\n\t/** The operation the Sandbox opens with. */\n\treadonly initialDocument?: string;\n\t/** Headers every operation sends, shown and editable in the Sandbox. */\n\treadonly initialHeaders?: Readonly<Record<string, string>>;\n\t/** Whether the Sandbox polls the schema as it changes. On by default. */\n\treadonly pollForSchemaUpdates?: boolean;\n\t/** Whether operations send the browser's cookies: a session cookie. On by default. */\n\treadonly includeCookies?: boolean;\n}\n\n/** What the page loads: the Sandbox's script, its frame, and operations to this server. */\nexport const SANDBOX_POLICY = [\n\t\"default-src 'self'\",\n\t\"script-src 'self' 'unsafe-inline' https://embeddable-sandbox.cdn.apollographql.com\",\n\t\"style-src 'self' 'unsafe-inline'\",\n\t'frame-src https://sandbox.embed.apollographql.com',\n\t\"img-src 'self' data: https:\",\n\t\"connect-src 'self'\",\n].join('; ');\n\n/**\n * The page, its endpoint `endpoint`: a URL, or a path the page resolves\n * against its own address. Every value is escaped into its JavaScript and\n * HTML.\n */\nexport function renderSandbox(\n\tendpoint: string,\n\toptions: SandboxOptions = {},\n): string {\n\tconst config = {\n\t\ttarget: '#sandbox',\n\t\tinitialEndpoint: endpoint,\n\t\tinitialState: {\n\t\t\tincludeCookies: options.includeCookies ?? true,\n\t\t\tpollForSchemaUpdates: options.pollForSchemaUpdates ?? true,\n\t\t\t...(options.initialDocument === undefined\n\t\t\t\t? {}\n\t\t\t\t: { document: options.initialDocument }),\n\t\t\t...(options.initialHeaders === undefined\n\t\t\t\t? {}\n\t\t\t\t: { headers: options.initialHeaders }),\n\t\t},\n\t\thideCookieToggle: false,\n\t\tendpointIsEditable: false,\n\t};\n\treturn `<!doctype html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\" />\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n<title>${html(options.title ?? 'Sandbox Explorer')}</title>\n<style>html, body { margin: 0; height: 100%; } #sandbox { position: absolute; inset: 0; }</style>\n</head>\n<body>\n<div id=\"sandbox\"></div>\n<script src=\"https://embeddable-sandbox.cdn.apollographql.com/_latest/embeddable-sandbox.umd.production.min.js\"></script>\n<script>\n{\nconst config = ${script(config)};\nconfig.initialEndpoint = new URL(config.initialEndpoint, location.href).href;\nnew window.EmbeddedSandbox(config);\n}\n</script>\n</body>\n</html>`;\n}\n\nfunction html(text: string): string {\n\treturn text.replace(/[&<>\"']/g, (char) => `&#${char.charCodeAt(0)};`);\n}\n\n/** JSON that cannot close the `<script>` it is written in. */\nfunction script(value: unknown): string {\n\treturn JSON.stringify(value)\n\t\t.replace(/</g, '\\\\u003c')\n\t\t.replace(/>/g, '\\\\u003e')\n\t\t.replace(/\\u2028/g, '\\\\u2028')\n\t\t.replace(/\\u2029/g, '\\\\u2029');\n}\n"
|
|
8
8
|
],
|
|
9
|
-
"mappings": ";
|
|
10
|
-
"debugId": "
|
|
9
|
+
"mappings": "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",
|
|
10
|
+
"debugId": "36F374D7B3E2E7EE64756E2164756E21",
|
|
11
11
|
"names": []
|
|
12
12
|
}
|
package/docs/README.md
CHANGED
|
@@ -8,9 +8,19 @@ a realistic example for each.
|
|
|
8
8
|
|
|
9
9
|
| Page | Read it when |
|
|
10
10
|
| --- | --- |
|
|
11
|
-
| [Mounting the endpoint](guide/endpoint.md) | adding GraphQL to an app, choosing its path under a prefix, putting it behind a guard, reading what it answers, or testing it without a server |
|
|
11
|
+
| [Mounting the endpoint](guide/endpoint.md) | adding GraphQL to an app, choosing its path under a prefix, putting it behind a guard, reading what it answers, telling GraphQL errors from the problem details of the HTTP layer around it, adding `health()` probes and draining it on `SIGTERM`, or testing it without a server |
|
|
12
12
|
| [The typed context](guide/context.md) | typing a schema with the app's context, reading `user` or a database handle in a resolver, setting a cookie, adding per-request loaders, or reading the `missing …` compile error |
|
|
13
13
|
| [Yoga's plugins and options](guide/yoga.md) | adding Yoga or Envelop plugins, exposing or masking errors, batching, serving subscriptions, or calling the endpoint from another origin |
|
|
14
|
-
| [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
|
|
14
|
+
| [GraphiQL and Apollo Sandbox](guide/ide.md) | choosing the IDE a browser gets, configuring it, keeping it working under a strict `Content-Security-Policy`, or serving it outside dev with `ide: 'graphiql'` |
|
|
15
15
|
| [Troubleshooting](troubleshooting.md) | something went wrong and you have the message |
|
|
16
16
|
| [Roadmap](roadmap.md) | wondering what is coming, and what is not planned |
|
|
17
|
+
|
|
18
|
+
## Recipes
|
|
19
|
+
|
|
20
|
+
A task that crosses packages, in [the repository's recipes](https://github.com/softistx/alxia/blob/develop/docs/recipes/README.md), each with a complete example:
|
|
21
|
+
|
|
22
|
+
- [A GraphQL API](https://github.com/softistx/alxia/blob/develop/docs/recipes/graphql-api.md): typed resolvers, a viewer, subscriptions, GraphiQL, auth errors and the drain
|
|
23
|
+
- [Authenticate requests](https://github.com/softistx/alxia/blob/develop/docs/recipes/authentication.md): a bearer token or a cookie session, a role check, the user typed in every handler
|
|
24
|
+
- [Test an alxia app](https://github.com/softistx/alxia/blob/develop/docs/recipes/testing.md): `app.request`, a middleware alone, the typed client, sockets, Redis
|
|
25
|
+
- [Health checks and graceful shutdown](https://github.com/softistx/alxia/blob/develop/docs/recipes/health-and-shutdown.md): probes, the drain, Docker and Kubernetes
|
|
26
|
+
- [Deploy with Docker](https://github.com/softistx/alxia/blob/develop/docs/recipes/deploying.md): the build stage, the final image, `NODE_ENV=production`
|
package/docs/guide/context.md
CHANGED
|
@@ -28,10 +28,10 @@ const schema = createSchema<GraphQLContext<typeof base>>({
|
|
|
28
28
|
},
|
|
29
29
|
});
|
|
30
30
|
|
|
31
|
-
const app = base.
|
|
31
|
+
const app = base.plugin((app) => graphql(app, { schema }));
|
|
32
32
|
```
|
|
33
33
|
|
|
34
|
-
Declare the
|
|
34
|
+
Declare the middlewares on a `base` app, type the schema with
|
|
35
35
|
`GraphQLContext<typeof base>`, then mount the endpoint on it. The schema
|
|
36
36
|
cannot be typed from `app` itself: `app` is built from the schema.
|
|
37
37
|
|
|
@@ -65,7 +65,7 @@ A resolver's context holds:
|
|
|
65
65
|
| From | Fields |
|
|
66
66
|
| --- | --- |
|
|
67
67
|
| Yoga (`YogaInitialContext`) | `request`, and `params`: the GraphQL request's `query`, `variables`, `operationName`, `extensions` |
|
|
68
|
-
| the app's
|
|
68
|
+
| the app's middlewares | everything `decorate` and `derive` added before the endpoint, and what middlewares such as `@alxia/jwt`'s `bearer` add (`user`) |
|
|
69
69
|
| the route (`BaseContext`) | `url`, `ip`, `server`, `route`, `pathParams`, `error`, and `set` |
|
|
70
70
|
| the `context` option | what it returns, as `UserContext` ([below](#the-context-option)) |
|
|
71
71
|
|
|
@@ -117,7 +117,7 @@ typed with a context the app does not build is refused, and the error names
|
|
|
117
117
|
the missing field:
|
|
118
118
|
|
|
119
119
|
```ts
|
|
120
|
-
const app = alxia().
|
|
120
|
+
const app = alxia().plugin((app) => graphql(app, { schema })); // no middleware derives `viewer` or `users`
|
|
121
121
|
```
|
|
122
122
|
|
|
123
123
|
```text
|
|
@@ -128,7 +128,7 @@ error TS2322: Type 'GraphQLSchemaWithContext<…>' is not assignable to type 'Gr
|
|
|
128
128
|
|
|
129
129
|
With `exactOptionalPropertyTypes` on, the code is `TS2375`; the message
|
|
130
130
|
ends the same way. The fix is to mount the endpoint on the
|
|
131
|
-
app the schema was typed from, after its
|
|
131
|
+
app the schema was typed from, after its middlewares:
|
|
132
132
|
[Troubleshooting](../troubleshooting.md#the-schemas-resolvers-read-a-context-the-app-does-not-build-missing-).
|
|
133
133
|
|
|
134
134
|
An untyped schema — `createSchema({ … })` with no type argument — passes
|
|
@@ -138,7 +138,7 @@ app's context.
|
|
|
138
138
|
|
|
139
139
|
## With a token: `@alxia/jwt`
|
|
140
140
|
|
|
141
|
-
A guard
|
|
141
|
+
A guard is a middleware like any other, given to `use` before the endpoint. With `@alxia/jwt`'s `bearer`, the
|
|
142
142
|
endpoint requires a token and `user` is the token's claims, typed by the
|
|
143
143
|
schema you give it:
|
|
144
144
|
|
|
@@ -164,7 +164,7 @@ const schema = createSchema<GraphQLContext<typeof base>>({
|
|
|
164
164
|
},
|
|
165
165
|
});
|
|
166
166
|
|
|
167
|
-
const app = base.
|
|
167
|
+
const app = base.plugin((app) => graphql(app, { schema }));
|
|
168
168
|
```
|
|
169
169
|
|
|
170
170
|
The guard's `401` and its body are `@alxia/jwt`'s, described in its
|
|
@@ -186,7 +186,7 @@ const schema = createSchema<GraphQLContext<typeof base, Loaders>>({
|
|
|
186
186
|
},
|
|
187
187
|
});
|
|
188
188
|
|
|
189
|
-
const app = base.
|
|
189
|
+
const app = base.plugin((app) =>
|
|
190
190
|
graphql(app, {
|
|
191
191
|
schema,
|
|
192
192
|
// annotate the argument: see below
|
|
@@ -219,6 +219,6 @@ as per-request data loaders.
|
|
|
219
219
|
|
|
220
220
|
## See also
|
|
221
221
|
|
|
222
|
-
- [Mounting the endpoint](endpoint.md): which
|
|
223
|
-
- [
|
|
222
|
+
- [Mounting the endpoint](endpoint.md): which middlewares run before it.
|
|
223
|
+
- [Middlewares](https://github.com/softistx/alxia/blob/develop/packages/core/docs/guide/middleware.md),
|
|
224
224
|
in `@alxia/core`'s guide: `decorate` and `derive`.
|
package/docs/guide/endpoint.md
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
# Mounting the endpoint
|
|
2
2
|
|
|
3
3
|
This page covers `graphql(app, options)`: where the endpoint is served, what
|
|
4
|
-
it answers, which
|
|
4
|
+
it answers, which middlewares run before it, and how to test it.
|
|
5
5
|
|
|
6
6
|
```ts
|
|
7
7
|
import { alxia } from '@alxia/core';
|
|
@@ -15,7 +15,7 @@ const schema = createSchema({
|
|
|
15
15
|
|
|
16
16
|
const app = alxia()
|
|
17
17
|
.get('/health', ({ reply }) => reply(200, 'ok'))
|
|
18
|
-
.
|
|
18
|
+
.plugin((app) => graphql(app, { schema })); // GET and POST /graphql
|
|
19
19
|
|
|
20
20
|
app.listen(3000);
|
|
21
21
|
```
|
|
@@ -28,18 +28,18 @@ curl localhost:3000/graphql -H 'content-type: application/json' -d '{"query":"{
|
|
|
28
28
|
## `graphql`
|
|
29
29
|
|
|
30
30
|
```ts
|
|
31
|
-
function graphql<Ctx,
|
|
32
|
-
app: Alxia<Ctx,
|
|
31
|
+
function graphql<Ctx, Prefix, SchemaCtx, UserCtx = Empty, const Path = '/graphql'>(
|
|
32
|
+
app: Alxia<Ctx, Prefix>,
|
|
33
33
|
options: GraphQLOptions<ServerContext<Ctx>, UserCtx, Path, SchemaCtx>,
|
|
34
|
-
): Alxia<Ctx,
|
|
34
|
+
): Alxia<Ctx, Prefix>;
|
|
35
35
|
```
|
|
36
36
|
|
|
37
37
|
`graphql` declares a `GET` and a `POST` route at `path` on `app`, and returns
|
|
38
|
-
`app
|
|
38
|
+
`app`, its type unchanged. Hand it to `app.plugin` as a function, so
|
|
39
39
|
it stays in the chain and sees the app as typed so far:
|
|
40
40
|
|
|
41
41
|
```ts
|
|
42
|
-
const app = base.
|
|
42
|
+
const app = base.plugin((app) => graphql(app, { schema }));
|
|
43
43
|
```
|
|
44
44
|
|
|
45
45
|
Calling it directly does the same: `graphql(base, { schema })` declares the
|
|
@@ -62,17 +62,17 @@ routes on `base` and returns it.
|
|
|
62
62
|
## Where it is served
|
|
63
63
|
|
|
64
64
|
`path` is joined to the app's prefix, and to the prefix of every app it is
|
|
65
|
-
mounted into
|
|
65
|
+
mounted into:
|
|
66
66
|
|
|
67
67
|
```ts
|
|
68
|
-
import { alxia
|
|
68
|
+
import { alxia } from '@alxia/core';
|
|
69
69
|
|
|
70
70
|
const api = alxia({ prefix: '/api' })
|
|
71
|
-
.
|
|
71
|
+
.plugin((app) => graphql(app, { schema, path: '/gql' })); // /api/gql
|
|
72
72
|
|
|
73
|
-
const root = alxia({ prefix: '/v1' }).
|
|
73
|
+
const root = alxia({ prefix: '/v1' }).plugin(api); // /v1/api/gql
|
|
74
74
|
|
|
75
|
-
|
|
75
|
+
root.routes.map((route) => `${route.method} ${route.path}`); // ['GET /v1/api/gql', 'POST /v1/api/gql']
|
|
76
76
|
```
|
|
77
77
|
|
|
78
78
|
Two endpoints on one app need two paths: declaring the default path twice
|
|
@@ -81,34 +81,55 @@ own path:
|
|
|
81
81
|
|
|
82
82
|
```ts
|
|
83
83
|
const app = alxia()
|
|
84
|
-
.
|
|
85
|
-
.
|
|
84
|
+
.plugin((app) => graphql(app, { schema }))
|
|
85
|
+
.plugin((app) => graphql(app, { schema: admin, path: '/admin/graphql' }));
|
|
86
86
|
```
|
|
87
87
|
|
|
88
|
-
## Behind the app's
|
|
88
|
+
## Behind the app's middlewares
|
|
89
89
|
|
|
90
|
-
The endpoint is a route like any other: every
|
|
91
|
-
it runs first, and one that replies ends the request there. A
|
|
92
|
-
it guards it
|
|
90
|
+
The endpoint is a route like any other: every middleware given to `use`
|
|
91
|
+
**before** it runs first, and one that replies ends the request there. A
|
|
92
|
+
guard before it guards it — a plain `(ctx, next)` function, what it passes
|
|
93
|
+
`next` typed into each resolver's context:
|
|
93
94
|
|
|
94
95
|
```ts
|
|
95
96
|
const app = alxia()
|
|
96
|
-
.
|
|
97
|
+
.use(({ request, reply }, next) =>
|
|
97
98
|
request.headers.get('authorization') === `Bearer ${Bun.env['API_TOKEN']}`
|
|
98
|
-
? { viewer: 'service' }
|
|
99
|
+
? next({ viewer: 'service' })
|
|
99
100
|
: reply(401, { error: 'unauthorized' as const }),
|
|
100
101
|
)
|
|
101
|
-
.
|
|
102
|
+
.plugin((app) => graphql(app, { schema })); // 401 without the token
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
`@alxia/jwt`'s `bearer()` is that guard for a JWT: `.use(bearer({ jwt }))`
|
|
106
|
+
([The typed context](context.md#with-a-token-alxiajwt)).
|
|
107
|
+
|
|
108
|
+
A middleware declared **after** `app.plugin` does not run for the endpoint: it
|
|
109
|
+
answers without it. Give the observers (`@alxia/logger`, `@alxia/cors`,
|
|
110
|
+
`@alxia/secure-headers`, `@alxia/compress`) to `use` first, so they wrap the
|
|
111
|
+
endpoint, and every other request, the 404s included:
|
|
112
|
+
|
|
113
|
+
```ts
|
|
114
|
+
import { alxia } from '@alxia/core';
|
|
115
|
+
import { cors } from '@alxia/cors';
|
|
116
|
+
import { graphql } from '@alxia/graphql';
|
|
117
|
+
import { logger } from '@alxia/logger';
|
|
118
|
+
import { secureHeaders } from '@alxia/secure-headers';
|
|
119
|
+
|
|
120
|
+
const app = alxia()
|
|
121
|
+
.use(logger())
|
|
122
|
+
.use(secureHeaders())
|
|
123
|
+
.use(cors({ origin: 'https://app.example.com' }))
|
|
124
|
+
.plugin((app) => graphql(app, { schema }));
|
|
102
125
|
```
|
|
103
126
|
|
|
104
|
-
A
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
them, such as `@alxia/cors` or `@alxia/secure-headers` — apply wherever they
|
|
109
|
-
are declared.
|
|
127
|
+
A guard given to the app's `use` (`bearer`, a required session) also runs on
|
|
128
|
+
a request no route matches: an anonymous request to a missing path is a 401,
|
|
129
|
+
not a 404. The order is core's, explained in
|
|
130
|
+
[Middlewares](https://github.com/softistx/alxia/blob/develop/packages/core/docs/guide/middleware.md).
|
|
110
131
|
|
|
111
|
-
What the
|
|
132
|
+
What the middlewares added is in each resolver's context: that is the next page,
|
|
112
133
|
[The typed context](context.md).
|
|
113
134
|
|
|
114
135
|
## What it answers
|
|
@@ -123,7 +144,7 @@ IDE page ([GraphiQL and Apollo Sandbox](ide.md)).
|
|
|
123
144
|
| `GET ?query=…` | the same, for a query; a mutation is a `405` |
|
|
124
145
|
| `POST` a subscription with `Accept: text/event-stream` | `200`, a `text/event-stream` of results ([subscriptions](yoga.md#subscriptions)) |
|
|
125
146
|
| `GET` from a browser (`Accept: text/html`), no `query` | the IDE page; with `ide: false`, a GraphQL answer (`Must provide query string.`) |
|
|
126
|
-
| a
|
|
147
|
+
| a middleware replied first | that middleware's reply, such as a `401` |
|
|
127
148
|
|
|
128
149
|
```text
|
|
129
150
|
POST {"query":"{ nope }"} → 200 {"errors":[{"message":"Cannot query field \"nope\" on type \"Query\".", … "extensions":{"code":"GRAPHQL_VALIDATION_FAILED"}}]}
|
|
@@ -131,14 +152,43 @@ GET ?query=mutation { m } → 405 {"errors":[{"message":"Can only pe
|
|
|
131
152
|
POST {} → 200 {"errors":[{"message":"Must provide query string.","extensions":{"code":"BAD_REQUEST"}}]}
|
|
132
153
|
```
|
|
133
154
|
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
155
|
+
Both methods answer a body to read as GraphQL, whatever its status, and
|
|
156
|
+
the replies of the middlewares before them — a guard's `401`, say.
|
|
157
|
+
|
|
158
|
+
## Errors, health and shutdown
|
|
159
|
+
|
|
160
|
+
**GraphQL errors stay GraphQL's.** A resolver that throws, a query that
|
|
161
|
+
does not validate, is an entry of `errors[]` in Yoga's answer — inside a
|
|
162
|
+
`200`, as the GraphQL over HTTP specification has it — whatever
|
|
163
|
+
`@alxia/core`'s `errors` option says. `alxia({ errors: 'problem' })`
|
|
164
|
+
applies to the HTTP layer around the endpoint: `@alxia/jwt`'s 401 before
|
|
165
|
+
it, a body past its `bodyLimit` (413), a middleware's 500, a `PUT` at its
|
|
166
|
+
path (405) — each an `application/problem+json` problem
|
|
167
|
+
([core's errors guide](https://github.com/softistx/alxia/blob/develop/packages/core/docs/guide/errors.md#graphql)).
|
|
168
|
+
|
|
169
|
+
```text
|
|
170
|
+
POST {"query":"{ boom }"} → 200 {"data":{"boom":null},"errors":[{"message":"Unexpected error.", …}]}
|
|
171
|
+
POST without a token → 401 application/problem+json {"type":"about:blank","title":"Unauthorized", …}
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
**Probes and the drain.** `@alxia/core`'s `health()` mounts beside the
|
|
175
|
+
endpoint, and `listen`'s graceful shutdown covers it: on `SIGTERM` a
|
|
176
|
+
query or a mutation in flight is answered, and a subscription over
|
|
177
|
+
server-sent events ends — its stream cancelled as when the client leaves,
|
|
178
|
+
the client reading the end and reconnecting elsewhere — so the drain does
|
|
179
|
+
not wait for it until `shutdownTimeout`.
|
|
137
180
|
|
|
138
181
|
```ts
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
182
|
+
import { alxia, health } from '@alxia/core';
|
|
183
|
+
import { bearer } from '@alxia/jwt';
|
|
184
|
+
import { graphql } from '@alxia/graphql';
|
|
185
|
+
|
|
186
|
+
const app = alxia({ errors: 'problem' })
|
|
187
|
+
.plugin(health({ checks: { db: () => sql`select 1` } }))
|
|
188
|
+
.use(bearer({ jwt }))
|
|
189
|
+
.plugin((app) => graphql(app, { schema }));
|
|
190
|
+
|
|
191
|
+
app.listen({ port: 4000 }); // SIGTERM: /ready 503, queries answered, subscriptions ended, exit 0
|
|
142
192
|
```
|
|
143
193
|
|
|
144
194
|
## Testing it
|
|
@@ -158,7 +208,7 @@ const schema = createSchema({
|
|
|
158
208
|
resolvers: { Query: { hello: (_, { name }: { name: string }) => `hello ${name}` } },
|
|
159
209
|
});
|
|
160
210
|
|
|
161
|
-
const app = alxia().
|
|
211
|
+
const app = alxia().plugin((app) => graphql(app, { schema, logging: false }));
|
|
162
212
|
|
|
163
213
|
const execute = (query: string, variables?: Record<string, unknown>) =>
|
|
164
214
|
app.request('/graphql', {
|
package/docs/guide/ide.md
CHANGED
|
@@ -15,10 +15,10 @@ const schema = createSchema({
|
|
|
15
15
|
resolvers: { Query: { hello: () => 'world' } },
|
|
16
16
|
});
|
|
17
17
|
|
|
18
|
-
const app = alxia().
|
|
18
|
+
const app = alxia().plugin((app) =>
|
|
19
19
|
graphql(app, {
|
|
20
20
|
schema,
|
|
21
|
-
ide: Bun.env['NODE_ENV'] === '
|
|
21
|
+
ide: Bun.env['NODE_ENV'] === 'development' && 'apollo-sandbox', // read at runtime
|
|
22
22
|
sandbox: { title: 'Hello API', initialDocument: '{ hello }' },
|
|
23
23
|
}),
|
|
24
24
|
);
|
|
@@ -29,7 +29,8 @@ const app = alxia().use((app) =>
|
|
|
29
29
|
|
|
30
30
|
| `ide` | A browser's `GET` at the endpoint gets | Options |
|
|
31
31
|
| --- | --- | --- |
|
|
32
|
-
|
|
|
32
|
+
| not given (default) | Yoga's GraphiQL in the serving app's dev — `alxia({ dev })`, else `NODE_ENV=development` — and no page elsewhere | `graphiql` |
|
|
33
|
+
| `'graphiql'` | Yoga's GraphiQL, in every mode | `graphiql` |
|
|
33
34
|
| `'apollo-sandbox'` | [Apollo Sandbox](https://www.apollographql.com/docs/graphos/platform/sandbox), embedded | `sandbox` |
|
|
34
35
|
| `false` | no page: the request is answered as a GraphQL request | — |
|
|
35
36
|
|
|
@@ -43,14 +44,15 @@ only `text/html` gets a [`406` with an empty
|
|
|
43
44
|
body](../troubleshooting.md#406-with-an-empty-body) instead.
|
|
44
45
|
|
|
45
46
|
Both IDEs run the schema's introspection and any operation against the
|
|
46
|
-
endpoint, behind the same
|
|
47
|
+
endpoint, behind the same middlewares as every other request: a guard before
|
|
47
48
|
the endpoint guards the page too, and a browser without a token gets the
|
|
48
|
-
guard's reply.
|
|
49
|
-
it.
|
|
49
|
+
guard's reply. By default the IDE is off outside dev; give `ide:
|
|
50
|
+
'graphiql'` only where you mean to publish it. Before 0.5, GraphiQL was
|
|
51
|
+
on in every mode.
|
|
50
52
|
|
|
51
53
|
## GraphiQL
|
|
52
54
|
|
|
53
|
-
The default. `graphiql` takes Yoga's `GraphiQLOptions` — not `true` or
|
|
55
|
+
The default, in dev. `graphiql` takes Yoga's `GraphiQLOptions` — not `true` or
|
|
54
56
|
`false`, which `ide` decides:
|
|
55
57
|
|
|
56
58
|
```ts
|
|
@@ -68,13 +70,20 @@ Its other options — `subscriptionsProtocol`, `credentials`,
|
|
|
68
70
|
`additionalHeaders`… — are listed in
|
|
69
71
|
[Yoga's GraphiQL documentation](https://the-guild.dev/graphql/yoga-server/docs/features/graphiql).
|
|
70
72
|
|
|
71
|
-
The page loads GraphiQL from `unpkg.com
|
|
72
|
-
`
|
|
73
|
+
The page loads GraphiQL from one pinned folder on `unpkg.com`,
|
|
74
|
+
`https://unpkg.com/@graphql-yoga/graphiql@<version>/`, the version the
|
|
75
|
+
installed Yoga names. Yoga's response has no `Content-Security-Policy`, so
|
|
76
|
+
the package adds one that lets that folder alone load — its scripts,
|
|
77
|
+
styles and fonts, and the Monaco workers the page fetches — and no one
|
|
78
|
+
frame the page:
|
|
73
79
|
|
|
74
80
|
```text
|
|
75
|
-
default-src 'self'; script-src 'self' 'unsafe-inline' https://unpkg.com
|
|
81
|
+
default-src 'self'; script-src 'self' 'unsafe-inline' https://unpkg.com/@graphql-yoga/graphiql@<version>/; style-src 'self' 'unsafe-inline' https://unpkg.com/@graphql-yoga/graphiql@<version>/; img-src 'self' data: https:; font-src 'self' data: https://unpkg.com/@graphql-yoga/graphiql@<version>/; worker-src 'self' blob:; connect-src 'self' https://unpkg.com/@graphql-yoga/graphiql@<version>/; frame-ancestors 'none'
|
|
76
82
|
```
|
|
77
83
|
|
|
84
|
+
A page of your own (`renderGraphiQL`) that names no such folder gets
|
|
85
|
+
`'self'` alone.
|
|
86
|
+
|
|
78
87
|
## Apollo Sandbox
|
|
79
88
|
|
|
80
89
|
`ide: 'apollo-sandbox'` serves a page embedding Apollo Sandbox, pointed at
|
|
@@ -128,27 +137,29 @@ default-src 'self'; script-src 'self' 'unsafe-inline' https://embeddable-sandbox
|
|
|
128
137
|
## With `@alxia/secure-headers`
|
|
129
138
|
|
|
130
139
|
`@alxia/secure-headers` keeps a header a response already has, so the
|
|
131
|
-
IDE's policy survives it and every other route keeps the strict one. A
|
|
140
|
+
IDE's policy survives it and every other route keeps the strict one. A middleware
|
|
132
141
|
of your own that **overwrites** `Content-Security-Policy` on every
|
|
133
142
|
response blocks the IDE's scripts, and the page stays blank: set it only
|
|
134
143
|
when the response has none.
|
|
135
144
|
|
|
136
145
|
```ts
|
|
137
|
-
import { alxia, withHeaders } from '@alxia/core';
|
|
146
|
+
import { alxia, defineMiddleware, settle, withHeaders } from '@alxia/core';
|
|
147
|
+
|
|
148
|
+
const defaultPolicy = defineMiddleware(async (ctx, next) =>
|
|
149
|
+
withHeaders(await settle(ctx, next()), (headers) => {
|
|
150
|
+
if (!headers.has('content-security-policy'))
|
|
151
|
+
headers.set('content-security-policy', "default-src 'self'");
|
|
152
|
+
}),
|
|
153
|
+
);
|
|
138
154
|
|
|
139
155
|
const app = alxia()
|
|
140
|
-
.
|
|
141
|
-
|
|
142
|
-
if (!headers.has('content-security-policy'))
|
|
143
|
-
headers.set('content-security-policy', "default-src 'self'");
|
|
144
|
-
}),
|
|
145
|
-
)
|
|
146
|
-
.use((app) => graphql(app, { schema }));
|
|
156
|
+
.use(defaultPolicy)
|
|
157
|
+
.plugin((app) => graphql(app, { schema }));
|
|
147
158
|
```
|
|
148
159
|
|
|
149
160
|
## `renderSandbox`
|
|
150
161
|
|
|
151
|
-
```ts
|
|
162
|
+
```ts no-check
|
|
152
163
|
function renderSandbox(endpoint: string, options?: SandboxOptions): string;
|
|
153
164
|
const SANDBOX_POLICY: string;
|
|
154
165
|
```
|
|
@@ -165,7 +176,7 @@ import { alxia } from '@alxia/core';
|
|
|
165
176
|
import { graphql, renderSandbox, SANDBOX_POLICY } from '@alxia/graphql';
|
|
166
177
|
|
|
167
178
|
const app = alxia()
|
|
168
|
-
.
|
|
179
|
+
.plugin((app) => graphql(app, { schema, ide: false }))
|
|
169
180
|
.get('/explorer', ({ reply }) =>
|
|
170
181
|
reply(200, renderSandbox('/graphql', { title: 'Users API' }), {
|
|
171
182
|
headers: {
|
|
@@ -182,5 +193,5 @@ another server: `renderSandbox('https://api.example.com/graphql')`.
|
|
|
182
193
|
|
|
183
194
|
## See also
|
|
184
195
|
|
|
185
|
-
- [Mounting the endpoint](endpoint.md): which
|
|
196
|
+
- [Mounting the endpoint](endpoint.md): which middlewares run before the page.
|
|
186
197
|
- [Troubleshooting](../troubleshooting.md#the-ide-page-is-blank): a blank IDE page.
|
package/docs/guide/yoga.md
CHANGED
|
@@ -14,7 +14,7 @@ const schema = createSchema({
|
|
|
14
14
|
resolvers: { Query: { hello: () => 'world' } },
|
|
15
15
|
});
|
|
16
16
|
|
|
17
|
-
const app = alxia().
|
|
17
|
+
const app = alxia().plugin((app) =>
|
|
18
18
|
graphql(app, {
|
|
19
19
|
schema,
|
|
20
20
|
plugins: [useExecutionCancellation()], // stop resolvers when the client goes away
|
|
@@ -84,9 +84,9 @@ const slowOperations: Plugin = {
|
|
|
84
84
|
graphql(app, { schema, plugins: [slowOperations] });
|
|
85
85
|
```
|
|
86
86
|
|
|
87
|
-
Yoga's plugins run inside the route, after the app's
|
|
88
|
-
sees only requests the
|
|
89
|
-
added.
|
|
87
|
+
Yoga's plugins run inside the route, after the app's middlewares: a plugin
|
|
88
|
+
sees only requests the middlewares let through, and its context holds what
|
|
89
|
+
they added.
|
|
90
90
|
|
|
91
91
|
## Errors
|
|
92
92
|
|
|
@@ -122,8 +122,9 @@ const resolvers = {
|
|
|
122
122
|
```
|
|
123
123
|
|
|
124
124
|
`maskedErrors: false` sends every message as it is: for development only.
|
|
125
|
-
A resolver's error is Yoga's to answer; it
|
|
126
|
-
|
|
125
|
+
A resolver's error is Yoga's to answer; it never reaches a try/catch
|
|
126
|
+
middleware before the endpoint, which sees only what fails around it — a
|
|
127
|
+
middleware that throws, say.
|
|
127
128
|
|
|
128
129
|
## Batching
|
|
129
130
|
|
|
@@ -210,7 +211,7 @@ import { graphql } from '@alxia/graphql';
|
|
|
210
211
|
|
|
211
212
|
const app = alxia()
|
|
212
213
|
.use(cors({ origin: 'https://app.example.com', credentials: true }))
|
|
213
|
-
.
|
|
214
|
+
.plugin((app) => graphql(app, { schema }));
|
|
214
215
|
// OPTIONS /graphql → 204, Access-Control-Allow-Origin: https://app.example.com
|
|
215
216
|
```
|
|
216
217
|
|
package/docs/roadmap.md
CHANGED
|
@@ -7,7 +7,18 @@ number on it. Every release, with each change it made, is in
|
|
|
7
7
|
|
|
8
8
|
## Now
|
|
9
9
|
|
|
10
|
-
|
|
10
|
+
- **GraphiQL in dev alone, under a pinned policy.** Without `ide`, a
|
|
11
|
+
browser gets GraphiQL only while the serving app is in dev
|
|
12
|
+
(`NODE_ENV=development`, or `alxia({ dev: true })`); `ide: 'graphiql'`
|
|
13
|
+
serves it everywhere. Its `Content-Security-Policy` allows the one
|
|
14
|
+
pinned `@graphql-yoga/graphiql` folder it loads from, the Monaco workers
|
|
15
|
+
included, and no frame ([IDE guide](guide/ide.md)).
|
|
16
|
+
- **Subscriptions drained on shutdown.** When the app starts shutting
|
|
17
|
+
down — `SIGTERM`, `SIGINT`, `stop()` — a subscription over server-sent
|
|
18
|
+
events ends, so `@alxia/core`'s drain answers the queries in flight and
|
|
19
|
+
exits without waiting for it; `health()` probes mount beside the
|
|
20
|
+
endpoint, and GraphQL errors stay in `errors[]` under core's problem
|
|
21
|
+
details ([endpoint guide](guide/endpoint.md#errors-health-and-shutdown)).
|
|
11
22
|
|
|
12
23
|
## Next
|
|
13
24
|
|
|
@@ -24,11 +35,11 @@ Nothing scheduled yet.
|
|
|
24
35
|
- **GraphQL Yoga as a route.** `graphql(app, options)` serves a schema at
|
|
25
36
|
`GET` and `POST` `/graphql`, or any `path`, under the app's prefix and
|
|
26
37
|
the prefix of every app it is mounted into. The endpoint runs behind the
|
|
27
|
-
app's
|
|
38
|
+
app's middlewares like any route: a guard given to `use` before it guards it, and its
|
|
28
39
|
reply is part of the endpoint's type.
|
|
29
40
|
- **The app's context in every resolver, typed and checked.**
|
|
30
41
|
`GraphQLContext<typeof app>` types a schema with Yoga's context and
|
|
31
|
-
everything the app's
|
|
42
|
+
everything the app's middlewares add — a user, a database handle — plus `set`,
|
|
32
43
|
through which a resolver sets a header or a cookie. A schema whose
|
|
33
44
|
resolvers read what the app does not build is a compile error naming the
|
|
34
45
|
missing field, and `GraphQLContext` of anything but an app is a message
|
package/docs/troubleshooting.md
CHANGED
|
@@ -34,9 +34,12 @@ symptom.
|
|
|
34
34
|
**Traps**
|
|
35
35
|
|
|
36
36
|
- [The endpoint answers without a guard declared after it](#the-endpoint-answers-without-a-guard-declared-after-it)
|
|
37
|
+
- [The logger, CORS or secure headers miss the endpoint](#the-logger-cors-or-secure-headers-miss-the-endpoint)
|
|
38
|
+
- [An anonymous request to a missing path is a 401](#an-anonymous-request-to-a-missing-path-is-a-401)
|
|
37
39
|
- [A WebSocket client cannot connect: `Expected 101 status code`](#a-websocket-client-cannot-connect-expected-101-status-code)
|
|
38
40
|
- [The IDE page is blank](#the-ide-page-is-blank)
|
|
39
41
|
- [GraphiQL is served in production](#graphiql-is-served-in-production)
|
|
42
|
+
- [GraphiQL does not open in development, or in a test](#graphiql-does-not-open-in-development-or-in-a-test)
|
|
40
43
|
|
|
41
44
|
## Install
|
|
42
45
|
|
|
@@ -75,17 +78,17 @@ error TS2322: Type 'GraphQLSchemaWithContext<…>' is not assignable to type 'Gr
|
|
|
75
78
|
```
|
|
76
79
|
|
|
77
80
|
**Why:** the schema was typed with `GraphQLContext<typeof base>`, and its
|
|
78
|
-
resolvers read what `base`'s
|
|
79
|
-
does not run those
|
|
81
|
+
resolvers read what `base`'s middlewares add, but `graphql` was given an app that
|
|
82
|
+
does not run those middlewares: another app, or the endpoint declared before the
|
|
80
83
|
`derive` or the guard.
|
|
81
84
|
|
|
82
85
|
**Fix:** mount the endpoint on the app the schema was typed from, after its
|
|
83
|
-
|
|
86
|
+
middlewares ([The typed context](guide/context.md)):
|
|
84
87
|
|
|
85
88
|
```ts
|
|
86
89
|
const base = alxia().use(bearer({ jwt })); // adds user
|
|
87
90
|
const schema = createSchema<GraphQLContext<typeof base>>({ … });
|
|
88
|
-
const app = base.
|
|
91
|
+
const app = base.plugin((app) => graphql(app, { schema })); // not alxia().plugin(…)
|
|
89
92
|
```
|
|
90
93
|
|
|
91
94
|
**When the missing field comes from the `context` option** — `missing
|
|
@@ -121,7 +124,7 @@ createSchema<GraphQLContext<typeof base>>({ … }); // not GraphQLContext<type
|
|
|
121
124
|
### `Property 'viewer' does not exist on type 'YogaInitialContext'`
|
|
122
125
|
|
|
123
126
|
**When:** a resolver of a schema created with `createSchema({ … })`, no type
|
|
124
|
-
argument, reads what the app's
|
|
127
|
+
argument, reads what the app's middlewares add.
|
|
125
128
|
|
|
126
129
|
**Why:** an untyped schema's context is Yoga's alone. The field is there at
|
|
127
130
|
runtime; its type is not.
|
|
@@ -205,7 +208,7 @@ graphql(app, { schema, path: '/gql' });
|
|
|
205
208
|
`get('/graphql', …)` beside the endpoint.
|
|
206
209
|
|
|
207
210
|
**Why:** each `graphql` call declares `GET` and `POST` at its `path`, and
|
|
208
|
-
two endpoints with the default path collide. `
|
|
211
|
+
two endpoints with the default path collide. `plugin((app) => graphql(app, …))`
|
|
209
212
|
declares the routes on the app it is called on, so calling it twice on the
|
|
210
213
|
same `base` — for two variants of an app — declares them twice there.
|
|
211
214
|
|
|
@@ -213,8 +216,8 @@ same `base` — for two variants of an app — declares them twice there.
|
|
|
213
216
|
|
|
214
217
|
```ts
|
|
215
218
|
const app = alxia()
|
|
216
|
-
.
|
|
217
|
-
.
|
|
219
|
+
.plugin((app) => graphql(app, { schema }))
|
|
220
|
+
.plugin((app) => graphql(app, { schema: admin, path: '/admin/graphql' }));
|
|
218
221
|
```
|
|
219
222
|
|
|
220
223
|
## Responses
|
|
@@ -247,16 +250,17 @@ throw createGraphQLError('Admins only', {
|
|
|
247
250
|
fails and the console reports a CORS error.
|
|
248
251
|
|
|
249
252
|
**Why:** Yoga's CORS is off, and the app answers no `OPTIONS` without a
|
|
250
|
-
CORS
|
|
253
|
+
CORS middleware.
|
|
251
254
|
|
|
252
|
-
**Fix:** `@alxia/cors`, for the whole app
|
|
255
|
+
**Fix:** `@alxia/cors`, given to `use` first, for the whole app: it answers a
|
|
256
|
+
preflight itself, before the router's 404 or 405 ([CORS](guide/yoga.md#cors)):
|
|
253
257
|
|
|
254
258
|
```ts
|
|
255
259
|
import { cors } from '@alxia/cors';
|
|
256
260
|
|
|
257
261
|
const app = alxia()
|
|
258
262
|
.use(cors({ origin: 'https://app.example.com', credentials: true }))
|
|
259
|
-
.
|
|
263
|
+
.plugin((app) => graphql(app, { schema }));
|
|
260
264
|
```
|
|
261
265
|
|
|
262
266
|
### `405 {"errors":[{"message":"Can only perform a mutation operation from a POST request."}]}`
|
|
@@ -328,19 +332,61 @@ await app.request(`/graphql?query=${encodeURIComponent('{ me }')}`, {
|
|
|
328
332
|
|
|
329
333
|
### The endpoint answers without a guard declared after it
|
|
330
334
|
|
|
331
|
-
**When:** `.
|
|
335
|
+
**When:** `.plugin((app) => graphql(app, { schema }))` comes before
|
|
332
336
|
`.use(bearer(…))` or a guarding `derive`: the endpoint answers anonymous
|
|
333
337
|
requests, and its resolvers read no `user`.
|
|
334
338
|
|
|
335
|
-
**Why:** a
|
|
336
|
-
is a route, declared where `graphql` is called
|
|
339
|
+
**Why:** a middleware applies to the routes declared after it. The endpoint
|
|
340
|
+
is a route, declared where `graphql` is called, so a middleware given to `use`
|
|
341
|
+
after it never runs for it. A schema typed from the
|
|
337
342
|
guarded app is refused (`missing user`); an untyped one is not.
|
|
338
343
|
|
|
339
344
|
**Fix:** declare the guard first:
|
|
340
345
|
|
|
341
346
|
```ts
|
|
342
347
|
const base = alxia().use(bearer({ jwt }));
|
|
343
|
-
const app = base.
|
|
348
|
+
const app = base.plugin((app) => graphql(app, { schema }));
|
|
349
|
+
```
|
|
350
|
+
|
|
351
|
+
### The logger, CORS or secure headers miss the endpoint
|
|
352
|
+
|
|
353
|
+
**When:** `use(logger())`, `use(cors(…))` or `use(secureHeaders())` comes
|
|
354
|
+
after `.plugin((app) => graphql(app, { schema }))`: the endpoint is not
|
|
355
|
+
logged, its responses carry no CORS or security headers.
|
|
356
|
+
|
|
357
|
+
**Why:** a `use` middleware runs on the routes declared after it, and on a
|
|
358
|
+
request no route matches. The endpoint is declared before it.
|
|
359
|
+
|
|
360
|
+
**Fix:** give the observers to `use` first:
|
|
361
|
+
|
|
362
|
+
```ts
|
|
363
|
+
const app = alxia()
|
|
364
|
+
.use(logger())
|
|
365
|
+
.use(cors({ origin: 'https://app.example.com' }))
|
|
366
|
+
.plugin((app) => graphql(app, { schema }));
|
|
367
|
+
```
|
|
368
|
+
|
|
369
|
+
### An anonymous request to a missing path is a 401
|
|
370
|
+
|
|
371
|
+
**When:** `use(bearer(…))` is on the app, and `GET /nope` answers
|
|
372
|
+
`401` rather than `404`.
|
|
373
|
+
|
|
374
|
+
**Why:** a guard given to the app's `use` runs on every request, a request
|
|
375
|
+
no route matches included, and answers before the 404.
|
|
376
|
+
|
|
377
|
+
**Fix:** scope the guard to what it guards, with a `group`. A path-scoped
|
|
378
|
+
`use('/graphql', bearer(…))` does not compile: a middleware given a path may
|
|
379
|
+
add nothing to the context, and `bearer` adds `user`.
|
|
380
|
+
|
|
381
|
+
```ts
|
|
382
|
+
const app = alxia()
|
|
383
|
+
.get('/health', ({ reply }) => reply(200, 'ok'))
|
|
384
|
+
.group('/api', (api) =>
|
|
385
|
+
api
|
|
386
|
+
.use(bearer({ jwt }))
|
|
387
|
+
.plugin((app) => graphql(app, { schema })), // /api/graphql: a 401 without a token
|
|
388
|
+
);
|
|
389
|
+
// GET /nope → 404, GET /api/nope → 404
|
|
344
390
|
```
|
|
345
391
|
|
|
346
392
|
### A WebSocket client cannot connect: `Expected 101 status code`
|
|
@@ -367,7 +413,7 @@ graphql(app, { schema, graphiql: { subscriptionsProtocol: 'SSE' } });
|
|
|
367
413
|
console reports scripts refused by the `Content-Security-Policy`.
|
|
368
414
|
|
|
369
415
|
**Why:** the endpoint sends the IDE with a policy that lets it load its
|
|
370
|
-
scripts from `unpkg.com` or Apollo's CDN. A
|
|
416
|
+
scripts from `unpkg.com` or Apollo's CDN. A middleware of the app that sets its
|
|
371
417
|
own `Content-Security-Policy` on every response replaces it.
|
|
372
418
|
`@alxia/secure-headers` does not: it keeps a policy a response already has.
|
|
373
419
|
|
|
@@ -375,22 +421,43 @@ own `Content-Security-Policy` on every response replaces it.
|
|
|
375
421
|
([With `@alxia/secure-headers`](guide/ide.md#with-alxiasecure-headers)):
|
|
376
422
|
|
|
377
423
|
```ts
|
|
378
|
-
|
|
379
|
-
withHeaders(
|
|
424
|
+
const defaultPolicy = defineMiddleware(async (ctx, next) =>
|
|
425
|
+
withHeaders(await settle(ctx, next()), (headers) => {
|
|
380
426
|
if (!headers.has('content-security-policy'))
|
|
381
427
|
headers.set('content-security-policy', "default-src 'self'");
|
|
382
428
|
}),
|
|
383
429
|
);
|
|
430
|
+
|
|
431
|
+
app.use(defaultPolicy); // before the endpoint, so it wraps it
|
|
384
432
|
```
|
|
385
433
|
|
|
386
434
|
### GraphiQL is served in production
|
|
387
435
|
|
|
388
436
|
**When:** a browser opening the production endpoint gets GraphiQL.
|
|
389
437
|
|
|
390
|
-
**Why:** `ide
|
|
438
|
+
**Why:** the app gives `ide: 'graphiql'`, which serves it in every mode, or
|
|
439
|
+
the serving app is in dev there (`NODE_ENV=development`, or
|
|
440
|
+
`alxia({ dev: true })`). Without `ide`, GraphiQL follows the dev switch
|
|
441
|
+
since 0.5; before, it was on everywhere.
|
|
391
442
|
|
|
392
|
-
**Fix:**
|
|
443
|
+
**Fix:** leave `ide` out, and keep `NODE_ENV=development` out of the
|
|
444
|
+
deployed environment, or turn it off:
|
|
445
|
+
|
|
446
|
+
```ts
|
|
447
|
+
graphql(app, { schema, ide: false });
|
|
448
|
+
```
|
|
449
|
+
|
|
450
|
+
### GraphiQL does not open in development, or in a test
|
|
451
|
+
|
|
452
|
+
**When:** a browser's `GET` at the endpoint gets a JSON result, or
|
|
453
|
+
`Must provide query string.`, where GraphiQL used to open.
|
|
454
|
+
|
|
455
|
+
**Why:** without `ide`, GraphiQL is served in the serving app's dev alone,
|
|
456
|
+
on only under `NODE_ENV=development`; `bun test` sets `NODE_ENV=test`.
|
|
457
|
+
|
|
458
|
+
**Fix:** run the `dev` script with `NODE_ENV=development`, or give the IDE
|
|
459
|
+
explicitly where it must open:
|
|
393
460
|
|
|
394
461
|
```ts
|
|
395
|
-
graphql(app, { schema, ide:
|
|
462
|
+
graphql(app, { schema, ide: 'graphiql' });
|
|
396
463
|
```
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@alxia/graphql",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "GraphQL for alxia with GraphQL Yoga: its plugins, subscriptions over SSE and GraphiQL, behind the app's hooks, its resolvers reading the app's typed context",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -41,13 +41,13 @@
|
|
|
41
41
|
]
|
|
42
42
|
},
|
|
43
43
|
"devDependencies": {
|
|
44
|
-
"@alxia/core": "^0.
|
|
44
|
+
"@alxia/core": "^0.5.0",
|
|
45
45
|
"@types/bun": "^1.4.2",
|
|
46
46
|
"graphql": "^16.11.0",
|
|
47
47
|
"graphql-yoga": "^5.16.0"
|
|
48
48
|
},
|
|
49
49
|
"peerDependencies": {
|
|
50
|
-
"@alxia/core": "^0.
|
|
50
|
+
"@alxia/core": "^0.5.0",
|
|
51
51
|
"graphql": "^16.11.0 || ^17.0.0",
|
|
52
52
|
"graphql-yoga": "^5.16.0",
|
|
53
53
|
"typescript": "^6.0.3 || ^7.0.0"
|