@alxia/graphql 0.16.5 → 0.18.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 (74) hide show
  1. package/README.md +60 -62
  2. package/dist/endpoint.d.ts +14 -2
  3. package/dist/endpoint.d.ts.map +1 -1
  4. package/dist/executor.d.ts +20 -37
  5. package/dist/executor.d.ts.map +1 -1
  6. package/dist/explorer.d.ts +24 -0
  7. package/dist/explorer.d.ts.map +1 -0
  8. package/dist/graphql.d.ts +32 -95
  9. package/dist/graphql.d.ts.map +1 -1
  10. package/dist/handler.d.ts +7 -34
  11. package/dist/handler.d.ts.map +1 -1
  12. package/dist/index.d.ts +3 -4
  13. package/dist/index.d.ts.map +1 -1
  14. package/dist/index.js +301 -1011
  15. package/dist/index.js.map +14 -23
  16. package/dist/once-per-request.d.ts +5 -0
  17. package/dist/once-per-request.d.ts.map +1 -1
  18. package/dist/operation.d.ts +2 -7
  19. package/dist/operation.d.ts.map +1 -1
  20. package/dist/options.d.ts +38 -0
  21. package/dist/options.d.ts.map +1 -0
  22. package/dist/removed.d.ts +14 -0
  23. package/dist/removed.d.ts.map +1 -0
  24. package/dist/sandbox.d.ts +3 -17
  25. package/dist/sandbox.d.ts.map +1 -1
  26. package/dist/testing/client.d.ts +9 -7
  27. package/dist/testing/client.d.ts.map +1 -1
  28. package/dist/testing/index.js +5 -1
  29. package/dist/testing/index.js.map +3 -3
  30. package/dist/ws.d.ts +18 -30
  31. package/dist/ws.d.ts.map +1 -1
  32. package/docs/README.md +3 -2
  33. package/docs/guide/context.md +40 -32
  34. package/docs/guide/endpoint.md +42 -27
  35. package/docs/guide/executor.md +23 -8
  36. package/docs/guide/ide.md +27 -64
  37. package/docs/guide/{yoga.md → plugins.md} +87 -72
  38. package/docs/guide/production.md +115 -196
  39. package/docs/guide/testing.md +24 -24
  40. package/docs/guide/websockets.md +21 -14
  41. package/docs/migrating-to-graxia.md +283 -0
  42. package/docs/roadmap.md +7 -11
  43. package/docs/troubleshooting.md +231 -248
  44. package/package.json +15 -22
  45. package/dist/body-refusal.d.ts +0 -25
  46. package/dist/body-refusal.d.ts.map +0 -1
  47. package/dist/document-cache.d.ts +0 -39
  48. package/dist/document-cache.d.ts.map +0 -1
  49. package/dist/field-rate-limit/count.d.ts +0 -28
  50. package/dist/field-rate-limit/count.d.ts.map +0 -1
  51. package/dist/field-rate-limit/from-store.d.ts +0 -21
  52. package/dist/field-rate-limit/from-store.d.ts.map +0 -1
  53. package/dist/field-rate-limit/index.d.ts +0 -5
  54. package/dist/field-rate-limit/index.d.ts.map +0 -1
  55. package/dist/field-rate-limit/ipv6-network.d.ts +0 -8
  56. package/dist/field-rate-limit/ipv6-network.d.ts.map +0 -1
  57. package/dist/field-rate-limit/plugin.d.ts +0 -28
  58. package/dist/field-rate-limit/plugin.d.ts.map +0 -1
  59. package/dist/field-rate-limit/types.d.ts +0 -60
  60. package/dist/field-rate-limit/types.d.ts.map +0 -1
  61. package/dist/nesting.d.ts +0 -18
  62. package/dist/nesting.d.ts.map +0 -1
  63. package/dist/parse-limits.d.ts +0 -50
  64. package/dist/parse-limits.d.ts.map +0 -1
  65. package/dist/same-origin/index.d.ts +0 -2
  66. package/dist/same-origin/index.d.ts.map +0 -1
  67. package/dist/same-origin/same-origin.d.ts +0 -30
  68. package/dist/same-origin/same-origin.d.ts.map +0 -1
  69. package/dist/ws-operations.d.ts +0 -31
  70. package/dist/ws-operations.d.ts.map +0 -1
  71. package/dist/ws-server.d.ts +0 -32
  72. package/dist/ws-server.d.ts.map +0 -1
  73. package/dist/yoga.d.ts +0 -12
  74. package/dist/yoga.d.ts.map +0 -1
@@ -18,6 +18,11 @@ export declare function clearRequestCache(request: object): void;
18
18
  * `clearRequestCache(context)` before it runs: each root mutation field starts
19
19
  * with an empty cache, its own sub-fields share it, and a query (no wrapped
20
20
  * field) keeps one cache for the whole request. Other types are untouched.
21
+ *
22
+ * It returns the same type it was given: an array of maps (what
23
+ * `createSchema` takes for `resolvers`) stays an array, each map wrapped on its
24
+ * own, so graxia still merges them (a field defined twice throws there) and
25
+ * each map stays checked.
21
26
  */
22
27
  export declare function freshPerMutation<R extends object>(resolvers: R): R;
23
28
  //# sourceMappingURL=once-per-request.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"once-per-request.d.ts","sourceRoot":"","sources":["../src/once-per-request.ts"],"names":[],"mappings":"AAEA;;;;;GAKG;AACH,wBAAgB,cAAc,CAAC,CAAC,EAC/B,OAAO,EAAE,MAAM,EACf,GAAG,EAAE,MAAM,EACX,IAAI,EAAE,MAAM,CAAC,GACX,CAAC,CAgBH;AAED;;;;GAIG;AACH,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAEvD;AAED;;;;;;;GAOG;AACH,wBAAgB,gBAAgB,CAAC,CAAC,SAAS,MAAM,EAAE,SAAS,EAAE,CAAC,GAAG,CAAC,CAyBlE"}
1
+ {"version":3,"file":"once-per-request.d.ts","sourceRoot":"","sources":["../src/once-per-request.ts"],"names":[],"mappings":"AAEA;;;;;GAKG;AACH,wBAAgB,cAAc,CAAC,CAAC,EAC/B,OAAO,EAAE,MAAM,EACf,GAAG,EAAE,MAAM,EACX,IAAI,EAAE,MAAM,CAAC,GACX,CAAC,CAgBH;AAED;;;;GAIG;AACH,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAEvD;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,gBAAgB,CAAC,CAAC,SAAS,MAAM,EAAE,SAAS,EAAE,CAAC,GAAG,CAAC,CAAC"}
@@ -1,8 +1,3 @@
1
- import type { Plugin } from 'graphql-yoga';
2
- /**
3
- * A Yoga plugin reporting each operation Yoga executes or subscribes to,
4
- * through core's `reportOperation`: a batched body reports each of its
5
- * operations, a request refused before it executes none.
6
- */
7
- export declare function reportsOperations(): Plugin;
1
+ /** A graxia plugin reporting each operation graxia executes or subscribes to. */
2
+ export declare function reportsOperations(): import("@graxia/core").GraxiaPlugin<import("@graxia/core").Empty, import("@graxia/core").Empty>;
8
3
  //# sourceMappingURL=operation.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"operation.d.ts","sourceRoot":"","sources":["../src/operation.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAkB3C;;;;GAIG;AACH,wBAAgB,iBAAiB,IAAI,MAAM,CAK1C"}
1
+ {"version":3,"file":"operation.d.ts","sourceRoot":"","sources":["../src/operation.ts"],"names":[],"mappings":"AAoDA,iFAAiF;AACjF,wBAAgB,iBAAiB,oGAgDhC"}
@@ -0,0 +1,38 @@
1
+ /**
2
+ * What `graphql()` and `graphqlExecutor()` share: alxia's options mapped
3
+ * onto `createGraxia`'s, the legacy names (`maxTokens`, `maxNesting`,
4
+ * `parseCache`, `maskedErrors`) kept, and the operation reporter.
5
+ */
6
+ import type { GraxiaOptions } from '@graxia/core';
7
+ import { type DevOfRequest } from './explorer';
8
+ export type { RemovedOptions } from './removed';
9
+ /** The cache sizes of the parse cache: graxia's `caches.parse`. */
10
+ export interface ParseCacheOptions {
11
+ /** graxia's `caches.parse.maxBytes`: the estimated bytes of sources kept (64 MiB by default). */
12
+ readonly maxBytes?: number;
13
+ readonly max?: number;
14
+ /** Milliseconds. */
15
+ readonly ttl?: number;
16
+ }
17
+ export interface LegacyOptions {
18
+ /** @deprecated Use `limits: { tokens }`. Works until the next minor. */
19
+ readonly maxTokens?: number | false;
20
+ /** @deprecated Use `limits: { nesting }`. Works until the next minor. */
21
+ readonly maxNesting?: number | false;
22
+ /** @deprecated Use `caches: { parse }`, or `caches: false`. Works until the next minor. */
23
+ readonly parseCache?: false | ParseCacheOptions;
24
+ /** `false` is graxia's `maskErrors: false`. */
25
+ readonly maskedErrors?: boolean;
26
+ }
27
+ interface Wiring {
28
+ /** Filled by the endpoint handler; the executor serves no page and gives none. */
29
+ readonly devs?: DevOfRequest | undefined;
30
+ readonly ws: false | {
31
+ keepAlive?: number | false | undefined;
32
+ };
33
+ readonly bodyLimit?: number | undefined;
34
+ /** Whose name an error carries. */
35
+ readonly caller?: 'graphqlExecutor(' | undefined;
36
+ }
37
+ export declare function graxiaOptions(options: object, wiring: Wiring): GraxiaOptions;
38
+ //# sourceMappingURL=options.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"options.d.ts","sourceRoot":"","sources":["../src/options.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAClD,OAAO,EACN,KAAK,YAAY,EAGjB,MAAM,YAAY,CAAC;AAIpB,YAAY,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAEhD,mEAAmE;AACnE,MAAM,WAAW,iBAAiB;IACjC,iGAAiG;IACjG,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,GAAG,CAAC,EAAE,MAAM,CAAC;IACtB,oBAAoB;IACpB,QAAQ,CAAC,GAAG,CAAC,EAAE,MAAM,CAAC;CACtB;AAED,MAAM,WAAW,aAAa;IAC7B,wEAAwE;IACxE,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,GAAG,KAAK,CAAC;IACpC,yEAAyE;IACzE,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM,GAAG,KAAK,CAAC;IACrC,2FAA2F;IAC3F,QAAQ,CAAC,UAAU,CAAC,EAAE,KAAK,GAAG,iBAAiB,CAAC;IAChD,+CAA+C;IAC/C,QAAQ,CAAC,YAAY,CAAC,EAAE,OAAO,CAAC;CAChC;AAED,UAAU,MAAM;IACf,kFAAkF;IAClF,QAAQ,CAAC,IAAI,CAAC,EAAE,YAAY,GAAG,SAAS,CAAC;IACzC,QAAQ,CAAC,EAAE,EAAE,KAAK,GAAG;QAAE,SAAS,CAAC,EAAE,MAAM,GAAG,KAAK,GAAG,SAAS,CAAA;KAAE,CAAC;IAChE,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IACxC,mCAAmC;IACnC,QAAQ,CAAC,MAAM,CAAC,EAAE,kBAAkB,GAAG,SAAS,CAAC;CACjD;AA+DD,wBAAgB,aAAa,CAAC,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,aAAa,CA0C5E"}
@@ -0,0 +1,14 @@
1
+ /** The options of the Yoga endpoint that no longer exist, refused with the fix. */
2
+ export interface RemovedOptions {
3
+ /** Removed: unexpected failures go to graxia's `onUnexpected` (`console.error`, off in production); log requests with `@alxia/logger`. */
4
+ readonly logging?: never;
5
+ /** Removed: graxia generates its own `x-request-id` and never echoes the client's; the app's own id is `@alxia/core`'s. */
6
+ readonly requestId?: never;
7
+ /** Removed: mount `@alxia/cors` on the app before `graphql()`. */
8
+ readonly cors?: never;
9
+ /** Removed with `sameOrigin()`: use `csrf: { sameOrigin: true }` (off by default; the CSRF header check is on). */
10
+ readonly sameOrigin?: never;
11
+ }
12
+ /** Throws, where `graphql()` is declared, for an option that was removed. */
13
+ export declare function rejectRemoved(options: object, caller?: 'graphql(app' | 'graphqlExecutor('): void;
14
+ //# sourceMappingURL=removed.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"removed.d.ts","sourceRoot":"","sources":["../src/removed.ts"],"names":[],"mappings":"AAAA,mFAAmF;AACnF,MAAM,WAAW,cAAc;IAC9B,0IAA0I;IAC1I,QAAQ,CAAC,OAAO,CAAC,EAAE,KAAK,CAAC;IACzB,2HAA2H;IAC3H,QAAQ,CAAC,SAAS,CAAC,EAAE,KAAK,CAAC;IAC3B,kEAAkE;IAClE,QAAQ,CAAC,IAAI,CAAC,EAAE,KAAK,CAAC;IACtB,mHAAmH;IACnH,QAAQ,CAAC,UAAU,CAAC,EAAE,KAAK,CAAC;CAC5B;AAYD,6EAA6E;AAC7E,wBAAgB,aAAa,CAC5B,OAAO,EAAE,MAAM,EACf,MAAM,GAAE,aAAa,GAAG,kBAAkC,GACxD,IAAI,CAaN"}
package/dist/sandbox.d.ts CHANGED
@@ -1,29 +1,15 @@
1
1
  /**
2
- * [Apollo Sandbox](https://www.apollographql.com/docs/graphos/platform/sandbox),
3
- * embedded: the page a browser gets at the endpoint when the IDE is
4
- * `apollo-sandbox`. `@softistx/shared-graphql`'s `renderSandbox`, kept twice: the
5
- * Sandbox asks the address the page was opened at, as there since
6
- * nxgt-core#171, but here the page resolves the path itself, so a TLS proxy
7
- * in front changes nothing.
2
+ * What `ide: 'apollo-sandbox'` gives `@graxia/graphiql`'s `apolloSandbox()`:
3
+ * the page's title and the state the Sandbox opens with.
8
4
  */
9
5
  export interface SandboxOptions {
10
- /** The page's title. `Sandbox Explorer` by default. */
6
+ /** The page's title. `Apollo Sandbox` by default. */
11
7
  readonly title?: string;
12
8
  /** The operation the Sandbox opens with. */
13
9
  readonly initialDocument?: string;
14
10
  /** Headers every operation sends, shown and editable in the Sandbox. */
15
11
  readonly initialHeaders?: Readonly<Record<string, string>>;
16
- /** Whether the Sandbox polls the schema as it changes. On by default. */
17
- readonly pollForSchemaUpdates?: boolean;
18
12
  /** Whether operations send the browser's cookies: a session cookie. On by default. */
19
13
  readonly includeCookies?: boolean;
20
14
  }
21
- /** What the page loads: the Sandbox's script, its frame, and operations to this server. */
22
- export declare const SANDBOX_POLICY: string;
23
- /**
24
- * The page, its endpoint `endpoint`: a URL, or a path the page resolves
25
- * against its own address. Every value is escaped into its JavaScript and
26
- * HTML.
27
- */
28
- export declare function renderSandbox(endpoint: string, options?: SandboxOptions): string;
29
15
  //# sourceMappingURL=sandbox.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"sandbox.d.ts","sourceRoot":"","sources":["../src/sandbox.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,MAAM,WAAW,cAAc;IAC9B,uDAAuD;IACvD,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,CAAC;IACxB,4CAA4C;IAC5C,QAAQ,CAAC,eAAe,CAAC,EAAE,MAAM,CAAC;IAClC,wEAAwE;IACxE,QAAQ,CAAC,cAAc,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;IAC3D,yEAAyE;IACzE,QAAQ,CAAC,oBAAoB,CAAC,EAAE,OAAO,CAAC;IACxC,sFAAsF;IACtF,QAAQ,CAAC,cAAc,CAAC,EAAE,OAAO,CAAC;CAClC;AAED,2FAA2F;AAC3F,eAAO,MAAM,cAAc,QAOf,CAAC;AAEb;;;;GAIG;AACH,wBAAgB,aAAa,CAC5B,QAAQ,EAAE,MAAM,EAChB,OAAO,GAAE,cAAmB,GAC1B,MAAM,CAqCR"}
1
+ {"version":3,"file":"sandbox.d.ts","sourceRoot":"","sources":["../src/sandbox.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,MAAM,WAAW,cAAc;IAC9B,qDAAqD;IACrD,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,CAAC;IACxB,4CAA4C;IAC5C,QAAQ,CAAC,eAAe,CAAC,EAAE,MAAM,CAAC;IAClC,wEAAwE;IACxE,QAAQ,CAAC,cAAc,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;IAC3D,sFAAsF;IACtF,QAAQ,CAAC,cAAc,CAAC,EAAE,OAAO,CAAC;CAClC"}
@@ -30,12 +30,14 @@ export type HttpMethod = 'GET' | 'POST';
30
30
  export interface GraphQLClientOptions {
31
31
  /** The endpoint's path. Default `/graphql`. */
32
32
  readonly path?: string;
33
+ /** Sent with every query: an `authorization` header, say. */
34
+ readonly headers?: HeadersInit;
33
35
  /**
34
- * Sent with every query: an `authorization` header, and the CSRF one the
35
- * app's `useCSRFPrevention` asks of a `GET` (the client sends none of its
36
- * own: its name is the app's).
36
+ * The CSRF header a `GET` carries, graxia's `x-graphql-csrf` by default.
37
+ * Name the one the app's `csrf.requireHeader` lists instead, or `false` to
38
+ * send none (to test the refusal). A `POST` never needs it.
37
39
  */
38
- readonly headers?: HeadersInit;
40
+ readonly csrfHeader?: string | false;
39
41
  /** How a call is sent unless it says. Default `'POST'`. */
40
42
  readonly method?: HttpMethod;
41
43
  }
@@ -55,7 +57,7 @@ export interface QueryOptions<TVars = Record<string, unknown>> {
55
57
  /**
56
58
  * The hash of a persisted operation, sent as Apollo's
57
59
  * `extensions.persistedQuery: { version: 1, sha256Hash }`, the shape of
58
- * `@graphql-yoga/plugin-persisted-operations` by default. With a
60
+ * graxia's persisted operations by default. With a
59
61
  * document it is sent too; alone, only it is.
60
62
  */
61
63
  readonly persisted?: string;
@@ -81,10 +83,10 @@ export interface Servable {
81
83
  /**
82
84
  * Sends operations to an app's GraphQL endpoint in process, through
83
85
  * `app.fetch`: no port, no server, the whole chain (middlewares, body limit,
84
- * Yoga's plugins) in play. Meant for specs; import it from
86
+ * graxia's plugins) in play. Meant for specs; import it from
85
87
  * `@alxia/graphql/testing`, never from the app.
86
88
  *
87
- * It POSTs JSON, or with `method: 'GET'` puts `query`, `variables`,
89
+ * It POSTs JSON, or with `method: 'GET'` (sending the CSRF header) puts `query`, `variables`,
88
90
  * `operationName` and `extensions` in the URL. A body that is not JSON (a 413
89
91
  * from a body limit, a 404) leaves `data` and `errors` unset: read `status`,
90
92
  * or `response`'s headers.
@@ -1 +1 @@
1
- {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../../src/testing/client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,YAAY,EAAS,KAAK,sBAAsB,EAAE,MAAM,SAAS,CAAC;AAEhF;;;;;GAKG;AACH,MAAM,MAAM,aAAa,CAAC,KAAK,GAAG,OAAO,EAAE,KAAK,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,IACvE,MAAM,GACN,sBAAsB,CAAC,KAAK,SAAS,MAAM,GAAG,KAAK,GAAG,KAAK,EAAE,KAAK,CAAC,GACnE,CAAC,YAAY,GAAG;IAAE,SAAS,CAAC,EAAE,CAAC,SAAS,EAAE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,CAAC,KAAK,CAAC,CAAC,CAAC;IACjC,6EAA6E;IAC7E,KAAK,CAAC,KAAK,GAAG,OAAO,EAAE,KAAK,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EACrD,OAAO,EAAE,qBAAqB,CAAC,KAAK,CAAC,GACnC,OAAO,CAAC,aAAa,CAAC,KAAK,CAAC,CAAC,CAAC;CACjC;AAID,wEAAwE;AACxE,MAAM,WAAW,QAAQ;IACxB,KAAK,CAAC,OAAO,EAAE,OAAO,GAAG,QAAQ,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC;CACtD;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,aAAa,CAC5B,GAAG,EAAE,QAAQ,EACb,OAAO,GAAE,oBAAyB,GAChC,aAAa,CAiBf"}
@@ -1,5 +1,6 @@
1
1
  // src/testing/client.ts
2
2
  import { print } from "graphql";
3
+ var DEFAULT_CSRF_HEADER = "x-graphql-csrf";
3
4
  function graphqlClient(app, options = {}) {
4
5
  const { path = "/graphql" } = options;
5
6
  return {
@@ -32,8 +33,11 @@ function buildRequest(path, document, call, client) {
32
33
  headers.set(name, value);
33
34
  }
34
35
  const url = new URL(path, "http://localhost");
36
+ const csrf = client.csrfHeader ?? DEFAULT_CSRF_HEADER;
35
37
  const parts = payload(document, call);
36
38
  if ((call.method ?? client.method ?? "POST") === "GET") {
39
+ if (csrf !== false && !headers.has(csrf))
40
+ headers.set(csrf, "1");
37
41
  for (const [name, value] of Object.entries(parts)) {
38
42
  url.searchParams.set(name, typeof value === "string" ? value : JSON.stringify(value));
39
43
  }
@@ -65,5 +69,5 @@ export {
65
69
  graphqlClient
66
70
  };
67
71
 
68
- //# debugId=7C558AD3A041624964756E2164756E21
72
+ //# debugId=2783394E46FFEAF364756E2164756E21
69
73
  //# sourceMappingURL=index.js.map
@@ -2,9 +2,9 @@
2
2
  "version": 3,
3
3
  "sources": ["../src/testing/client.ts"],
4
4
  "sourcesContent": [
5
- "import { type DocumentNode, print, type TypedQueryDocumentNode } from 'graphql';\n\n/**\n * A document that carries its types: `graphql`'s own `TypedQueryDocumentNode`,\n * or the `TypedDocumentNode` of `@graphql-typed-document-node/core` that\n * GraphQL Code Generator writes, read by its `__apiType` marker. Both are a\n * `DocumentNode` with an optional function, so neither package is imported.\n */\nexport type QueryDocument<TData = unknown, TVars = Record<string, unknown>> =\n\t| string\n\t| TypedQueryDocumentNode<TData extends object ? TData : never, TVars>\n\t| (DocumentNode & { __apiType?: (variables: TVars) => TData });\n\n/** One entry of a response's `errors`. */\nexport interface ResponseError {\n\treadonly message: string;\n\treadonly path?: readonly (string | number)[];\n\treadonly extensions?: {\n\t\treadonly code?: string;\n\t\treadonly [key: string]: unknown;\n\t};\n}\n\n/** What `query` resolves to: the HTTP status, the parsed body, the response. */\nexport interface GraphQLResult<TData = unknown> {\n\treadonly status: number;\n\treadonly data?: TData | null;\n\treadonly errors?: readonly ResponseError[];\n\t/** The response, its body still unread: `headers`, `ok`. */\n\treadonly response: Response;\n}\n\n/** How the operation travels: a JSON body, or the URL's query string. */\nexport type HttpMethod = 'GET' | 'POST';\n\nexport interface GraphQLClientOptions {\n\t/** The endpoint's path. Default `/graphql`. */\n\treadonly path?: string;\n\t/**\n\t * Sent with every query: an `authorization` header, and the CSRF one the\n\t * app's `useCSRFPrevention` asks of a `GET` (the client sends none of its\n\t * own: its name is the app's).\n\t */\n\treadonly headers?: HeadersInit;\n\t/** How a call is sent unless it says. Default `'POST'`. */\n\treadonly method?: HttpMethod;\n}\n\nexport interface QueryOptions<TVars = Record<string, unknown>> {\n\treadonly variables?: TVars;\n\treadonly operationName?: string;\n\t/** Added to the client's, and replacing one of the same name. */\n\treadonly headers?: HeadersInit;\n\t/** This call's method, over the client's. */\n\treadonly method?: HttpMethod;\n\t/**\n\t * Sent as `extensions`, beside the `persistedQuery` that `persisted`\n\t * adds: what an app that reads an operation's id from its own extension\n\t * (`extractPersistedOperationId`) is sent.\n\t */\n\treadonly extensions?: Record<string, unknown>;\n\t/**\n\t * The hash of a persisted operation, sent as Apollo's\n\t * `extensions.persistedQuery: { version: 1, sha256Hash }`, the shape of\n\t * `@graphql-yoga/plugin-persisted-operations` by default. With a\n\t * document it is sent too; alone, only it is.\n\t */\n\treadonly persisted?: string;\n}\n\n/**\n * A call with no document: the operation is the one `persisted` names, or\n * the one an app reads from the `extensions` it is sent (an id).\n */\nexport type PersistedQueryOptions<TVars = Record<string, unknown>> =\n\tQueryOptions<TVars> &\n\t\t(\n\t\t\t| { readonly persisted: string }\n\t\t\t| { readonly extensions: Record<string, unknown> }\n\t\t);\n\nexport interface GraphQLClient {\n\tquery<TData = unknown, TVars = Record<string, unknown>>(\n\t\tdocument: QueryDocument<TData, TVars>,\n\t\toptions?: QueryOptions<TVars>,\n\t): Promise<GraphQLResult<TData>>;\n\t/** A persisted operation, by its hash or id alone: name `TData` yourself. */\n\tquery<TData = unknown, TVars = Record<string, unknown>>(\n\t\toptions: PersistedQueryOptions<TVars>,\n\t): Promise<GraphQLResult<TData>>;\n}\n\n/** What it calls: an alxia app, or anything with a `fetch(Request)`. */\nexport interface Servable {\n\tfetch(request: Request): Response | Promise<Response>;\n}\n\n/**\n * Sends operations to an app's GraphQL endpoint in process, through\n * `app.fetch`: no port, no server, the whole chain (middlewares, body limit,\n * Yoga's plugins) in play. Meant for specs; import it from\n * `@alxia/graphql/testing`, never from the app.\n *\n * It POSTs JSON, or with `method: 'GET'` puts `query`, `variables`,\n * `operationName` and `extensions` in the URL. A body that is not JSON (a 413\n * from a body limit, a 404) leaves `data` and `errors` unset: read `status`,\n * or `response`'s headers.\n */\nexport function graphqlClient(\n\tapp: Servable,\n\toptions: GraphQLClientOptions = {},\n): GraphQLClient {\n\tconst { path = '/graphql' } = options;\n\treturn {\n\t\tasync query(\n\t\t\tfirst: QueryDocument | PersistedQueryOptions,\n\t\t\tsecond: QueryOptions = {},\n\t\t) {\n\t\t\tconst [document, call] = isCall(first)\n\t\t\t\t? [undefined, first]\n\t\t\t\t: [first, second];\n\t\t\tconst response = await app.fetch(\n\t\t\t\tbuildRequest(path, document, call, options),\n\t\t\t);\n\t\t\tconst text = await response.clone().text();\n\t\t\treturn { status: response.status, ...parse(text), response };\n\t\t},\n\t} as GraphQLClient;\n}\n\n/** A call's options, not a document: a `DocumentNode` has a `kind`. */\nfunction isCall(\n\tvalue: QueryDocument | PersistedQueryOptions,\n): value is PersistedQueryOptions {\n\treturn typeof value === 'object' && !('kind' in value);\n}\n\n/** The operation's parts, each only when the call has it. */\nfunction payload(\n\tdocument: QueryDocument | undefined,\n\tcall: QueryOptions,\n): Record<string, unknown> {\n\tconst extensions = {\n\t\t...call.extensions,\n\t\t...(call.persisted === undefined\n\t\t\t? {}\n\t\t\t: { persistedQuery: { version: 1, sha256Hash: call.persisted } }),\n\t};\n\treturn {\n\t\t...(document === undefined\n\t\t\t? {}\n\t\t\t: { query: typeof document === 'string' ? document : print(document) }),\n\t\t...(call.variables === undefined ? {} : { variables: call.variables }),\n\t\t...(call.operationName === undefined\n\t\t\t? {}\n\t\t\t: { operationName: call.operationName }),\n\t\t...(Object.keys(extensions).length === 0 ? {} : { extensions }),\n\t};\n}\n\nfunction buildRequest(\n\tpath: string,\n\tdocument: QueryDocument | undefined,\n\tcall: QueryOptions,\n\tclient: GraphQLClientOptions,\n): Request {\n\tconst headers = new Headers(client.headers);\n\tfor (const [name, value] of new Headers(call.headers)) {\n\t\theaders.set(name, value);\n\t}\n\tconst url = new URL(path, 'http://localhost');\n\tconst parts = payload(document, call);\n\tif ((call.method ?? client.method ?? 'POST') === 'GET') {\n\t\t// `variables` and `extensions` are JSON in the URL, as Yoga reads them.\n\t\tfor (const [name, value] of Object.entries(parts)) {\n\t\t\turl.searchParams.set(\n\t\t\t\tname,\n\t\t\t\ttypeof value === 'string' ? value : JSON.stringify(value),\n\t\t\t);\n\t\t}\n\t\treturn new Request(url, { method: 'GET', headers });\n\t}\n\theaders.set('content-type', 'application/json');\n\treturn new Request(url, {\n\t\tmethod: 'POST',\n\t\theaders,\n\t\tbody: JSON.stringify(parts),\n\t});\n}\n\n/** `data` and `errors` of a JSON object body, each only when it has one. */\nfunction parse<TData>(text: string): {\n\tdata?: TData | null;\n\terrors?: readonly ResponseError[];\n} {\n\ttry {\n\t\tconst body: unknown = JSON.parse(text);\n\t\tif (typeof body !== 'object' || body === null || Array.isArray(body)) {\n\t\t\treturn {};\n\t\t}\n\t\tconst { data, errors } = body as Record<string, unknown>;\n\t\treturn {\n\t\t\t...(data === undefined ? {} : { data: data as TData | null }),\n\t\t\t...(errors === undefined\n\t\t\t\t? {}\n\t\t\t\t: { errors: errors as readonly ResponseError[] }),\n\t\t};\n\t} catch {\n\t\treturn {};\n\t}\n}\n"
5
+ "import { type DocumentNode, print, type TypedQueryDocumentNode } from 'graphql';\n\n/**\n * A document that carries its types: `graphql`'s own `TypedQueryDocumentNode`,\n * or the `TypedDocumentNode` of `@graphql-typed-document-node/core` that\n * GraphQL Code Generator writes, read by its `__apiType` marker. Both are a\n * `DocumentNode` with an optional function, so neither package is imported.\n */\nexport type QueryDocument<TData = unknown, TVars = Record<string, unknown>> =\n\t| string\n\t| TypedQueryDocumentNode<TData extends object ? TData : never, TVars>\n\t| (DocumentNode & { __apiType?: (variables: TVars) => TData });\n\n/** One entry of a response's `errors`. */\nexport interface ResponseError {\n\treadonly message: string;\n\treadonly path?: readonly (string | number)[];\n\treadonly extensions?: {\n\t\treadonly code?: string;\n\t\treadonly [key: string]: unknown;\n\t};\n}\n\n/** What `query` resolves to: the HTTP status, the parsed body, the response. */\nexport interface GraphQLResult<TData = unknown> {\n\treadonly status: number;\n\treadonly data?: TData | null;\n\treadonly errors?: readonly ResponseError[];\n\t/** The response, its body still unread: `headers`, `ok`. */\n\treadonly response: Response;\n}\n\n/** How the operation travels: a JSON body, or the URL's query string. */\nexport type HttpMethod = 'GET' | 'POST';\n\nexport interface GraphQLClientOptions {\n\t/** The endpoint's path. Default `/graphql`. */\n\treadonly path?: string;\n\t/** Sent with every query: an `authorization` header, say. */\n\treadonly headers?: HeadersInit;\n\t/**\n\t * The CSRF header a `GET` carries, graxia's `x-graphql-csrf` by default.\n\t * Name the one the app's `csrf.requireHeader` lists instead, or `false` to\n\t * send none (to test the refusal). A `POST` never needs it.\n\t */\n\treadonly csrfHeader?: string | false;\n\t/** How a call is sent unless it says. Default `'POST'`. */\n\treadonly method?: HttpMethod;\n}\n\nexport interface QueryOptions<TVars = Record<string, unknown>> {\n\treadonly variables?: TVars;\n\treadonly operationName?: string;\n\t/** Added to the client's, and replacing one of the same name. */\n\treadonly headers?: HeadersInit;\n\t/** This call's method, over the client's. */\n\treadonly method?: HttpMethod;\n\t/**\n\t * Sent as `extensions`, beside the `persistedQuery` that `persisted`\n\t * adds: what an app that reads an operation's id from its own extension\n\t * (`extractPersistedOperationId`) is sent.\n\t */\n\treadonly extensions?: Record<string, unknown>;\n\t/**\n\t * The hash of a persisted operation, sent as Apollo's\n\t * `extensions.persistedQuery: { version: 1, sha256Hash }`, the shape of\n\t * graxia's persisted operations by default. With a\n\t * document it is sent too; alone, only it is.\n\t */\n\treadonly persisted?: string;\n}\n\n/**\n * A call with no document: the operation is the one `persisted` names, or\n * the one an app reads from the `extensions` it is sent (an id).\n */\nexport type PersistedQueryOptions<TVars = Record<string, unknown>> =\n\tQueryOptions<TVars> &\n\t\t(\n\t\t\t| { readonly persisted: string }\n\t\t\t| { readonly extensions: Record<string, unknown> }\n\t\t);\n\nexport interface GraphQLClient {\n\tquery<TData = unknown, TVars = Record<string, unknown>>(\n\t\tdocument: QueryDocument<TData, TVars>,\n\t\toptions?: QueryOptions<TVars>,\n\t): Promise<GraphQLResult<TData>>;\n\t/** A persisted operation, by its hash or id alone: name `TData` yourself. */\n\tquery<TData = unknown, TVars = Record<string, unknown>>(\n\t\toptions: PersistedQueryOptions<TVars>,\n\t): Promise<GraphQLResult<TData>>;\n}\n\nconst DEFAULT_CSRF_HEADER = 'x-graphql-csrf';\n\n/** What it calls: an alxia app, or anything with a `fetch(Request)`. */\nexport interface Servable {\n\tfetch(request: Request): Response | Promise<Response>;\n}\n\n/**\n * Sends operations to an app's GraphQL endpoint in process, through\n * `app.fetch`: no port, no server, the whole chain (middlewares, body limit,\n * graxia's plugins) in play. Meant for specs; import it from\n * `@alxia/graphql/testing`, never from the app.\n *\n * It POSTs JSON, or with `method: 'GET'` (sending the CSRF header) puts `query`, `variables`,\n * `operationName` and `extensions` in the URL. A body that is not JSON (a 413\n * from a body limit, a 404) leaves `data` and `errors` unset: read `status`,\n * or `response`'s headers.\n */\nexport function graphqlClient(\n\tapp: Servable,\n\toptions: GraphQLClientOptions = {},\n): GraphQLClient {\n\tconst { path = '/graphql' } = options;\n\treturn {\n\t\tasync query(\n\t\t\tfirst: QueryDocument | PersistedQueryOptions,\n\t\t\tsecond: QueryOptions = {},\n\t\t) {\n\t\t\tconst [document, call] = isCall(first)\n\t\t\t\t? [undefined, first]\n\t\t\t\t: [first, second];\n\t\t\tconst response = await app.fetch(\n\t\t\t\tbuildRequest(path, document, call, options),\n\t\t\t);\n\t\t\tconst text = await response.clone().text();\n\t\t\treturn { status: response.status, ...parse(text), response };\n\t\t},\n\t} as GraphQLClient;\n}\n\n/** A call's options, not a document: a `DocumentNode` has a `kind`. */\nfunction isCall(\n\tvalue: QueryDocument | PersistedQueryOptions,\n): value is PersistedQueryOptions {\n\treturn typeof value === 'object' && !('kind' in value);\n}\n\n/** The operation's parts, each only when the call has it. */\nfunction payload(\n\tdocument: QueryDocument | undefined,\n\tcall: QueryOptions,\n): Record<string, unknown> {\n\tconst extensions = {\n\t\t...call.extensions,\n\t\t...(call.persisted === undefined\n\t\t\t? {}\n\t\t\t: { persistedQuery: { version: 1, sha256Hash: call.persisted } }),\n\t};\n\treturn {\n\t\t...(document === undefined\n\t\t\t? {}\n\t\t\t: { query: typeof document === 'string' ? document : print(document) }),\n\t\t...(call.variables === undefined ? {} : { variables: call.variables }),\n\t\t...(call.operationName === undefined\n\t\t\t? {}\n\t\t\t: { operationName: call.operationName }),\n\t\t...(Object.keys(extensions).length === 0 ? {} : { extensions }),\n\t};\n}\n\nfunction buildRequest(\n\tpath: string,\n\tdocument: QueryDocument | undefined,\n\tcall: QueryOptions,\n\tclient: GraphQLClientOptions,\n): Request {\n\tconst headers = new Headers(client.headers);\n\tfor (const [name, value] of new Headers(call.headers)) {\n\t\theaders.set(name, value);\n\t}\n\tconst url = new URL(path, 'http://localhost');\n\tconst csrf = client.csrfHeader ?? DEFAULT_CSRF_HEADER;\n\tconst parts = payload(document, call);\n\tif ((call.method ?? client.method ?? 'POST') === 'GET') {\n\t\tif (csrf !== false && !headers.has(csrf)) headers.set(csrf, '1');\n\t\t// `variables` and `extensions` are JSON in the URL.\n\t\tfor (const [name, value] of Object.entries(parts)) {\n\t\t\turl.searchParams.set(\n\t\t\t\tname,\n\t\t\t\ttypeof value === 'string' ? value : JSON.stringify(value),\n\t\t\t);\n\t\t}\n\t\treturn new Request(url, { method: 'GET', headers });\n\t}\n\theaders.set('content-type', 'application/json');\n\treturn new Request(url, {\n\t\tmethod: 'POST',\n\t\theaders,\n\t\tbody: JSON.stringify(parts),\n\t});\n}\n\n/** `data` and `errors` of a JSON object body, each only when it has one. */\nfunction parse<TData>(text: string): {\n\tdata?: TData | null;\n\terrors?: readonly ResponseError[];\n} {\n\ttry {\n\t\tconst body: unknown = JSON.parse(text);\n\t\tif (typeof body !== 'object' || body === null || Array.isArray(body)) {\n\t\t\treturn {};\n\t\t}\n\t\tconst { data, errors } = body as Record<string, unknown>;\n\t\treturn {\n\t\t\t...(data === undefined ? {} : { data: data as TData | null }),\n\t\t\t...(errors === undefined\n\t\t\t\t? {}\n\t\t\t\t: { errors: errors as readonly ResponseError[] }),\n\t\t};\n\t} catch {\n\t\treturn {};\n\t}\n}\n"
6
6
  ],
7
- "mappings": ";AAAA;AA4GO,SAAS,aAAa,CAC5B,KACA,UAAgC,CAAC,GACjB;AAAA,EAChB,QAAQ,OAAO,eAAe;AAAA,EAC9B,OAAO;AAAA,UACA,KAAK,CACV,OACA,S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Q,IAAI,MAAM,GAAG;AAAA,IAE/D,YAAY,MAAM,UAAU,OAAO,QAAQ,KAAK,GAAG;AAAA,MAClD,IAAI,aAAa,IAChB,MACA,OAAO,UAAU,WAAW,QAAQ,KAAK,UAAU,KAAK,CACzD;AAAA,IACD;AAAA,IACA,OAAO,IAAI,QAAQ,KAAK,EAAE,QAAQ,OAAO,QAAQ,CAAC;AAAA,EACnD;AAAA,EACA,QAAQ,IAAI,gBAAgB,kBAAkB;AAAA,EAC9C,OAAO,IAAI,QAAQ,KAAK;AAAA,IACvB,QAAQ;AAAA,IACR;AAAA,IACA,MAAM,KAAK,UAAU,KAAK;AAAA,EAC3B,CAAC;AAAA;AAIF,SAAS,KAAY,CAAC,MAGpB;AAAA,EACD,IAAI;AAAA,IACH,MAAM,OAAgB,KAAK,MAAM,IAAI;AAAA,IACrC,IAAI,OAAO,SAAS,YAAY,SAAS,QAAQ,MAAM,QAAQ,IAAI,GAAG;AAAA,MACrE,OAAO,CAAC;AAAA,IACT;AAAA,IACA,QAAQ,MAAM,WAAW;AAAA,IACzB,OAAO;AAAA,SACF,SAAS,YAAY,CAAC,IAAI,EAAE,KAA2B;AAAA,SACvD,WAAW,YACZ,CAAC,IACD,EAAE,OAA2C;AAAA,IACjD;AAAA,IACC,MAAM;AAAA,IACP,OAAO,CAAC;AAAA;AAAA;",
8
+ "debugId": "2783394E46FFEAF364756E2164756E21",
9
9
  "names": []
10
10
  }
package/dist/ws.d.ts CHANGED
@@ -1,42 +1,30 @@
1
1
  /**
2
- * GraphQL over WebSocket, the `graphql-transport-ws` protocol of
3
- * `graphql-ws`, on a socket route of the app: the upgrade runs the app's
4
- * middlewares, each operation runs through Yoga's envelop — its plugins,
5
- * its `context` — and is told to the observers around the upgrade
6
- * (`ws-operations.ts`, through `ws-server.ts`'s options), and the app's shutdown closes the sockets with 1001.
2
+ * GraphQL over WebSocket: the `graphql-transport-ws` protocol is graxia's.
3
+ * alxia owns `Bun.serve`'s websocket handler, so the route's middleware asks
4
+ * `graxia.upgrade` for the socket's data through a stand-in server that only
5
+ * captures it, and each socket's events are handed to `graxia.websocket`.
6
+ * graxia's `maxPayloadBytes` (1 MiB) is applied by `graxia.serve`, which
7
+ * alxia does not use: a message is bounded by Bun's `maxPayloadLength` (16 MiB
8
+ * by default), as the WebSocket guide says.
7
9
  */
8
10
  import type { BaseContext, NextFunction, RoutePath, Socket } from '@alxia/core';
9
- import type { YogaServerInstance } from 'graphql-yoga';
10
- import type { YogaContext } from './handler';
11
- /** `graphql(app, { ws })`: GraphQL over WebSocket beside the HTTP endpoint. */
11
+ import type { Graxia } from '@graxia/core';
12
12
  export interface GraphQLWsOptions {
13
- /**
14
- * Where a client opens its socket, under the app's prefix. The
15
- * endpoint's own path by default: one URL, `http(s)://` for queries and
16
- * server-sent events, `ws(s)://` for the socket.
17
- */
13
+ /** Where a client opens its socket. The endpoint's own path by default. */
18
14
  readonly path?: RoutePath;
19
- /**
20
- * Milliseconds between the WebSocket pings the server sends each open
21
- * socket, so a proxy does not close an idle subscription. `12_000` by
22
- * default, as `graphql-ws`'s own server for Node; `false` for none.
23
- */
15
+ /** Milliseconds between pings, or `false` for none. */
24
16
  readonly keepAlive?: number | false;
25
17
  }
26
- /** What the missing optional peer is answered with: the package to add. */
27
- export declare const MISSING_PEER = "@alxia/graphql: graphql(app, { ws }) serves GraphQL over WebSocket with the optional peer graphql-ws, which is not installed: bun add graphql-ws";
28
- /**
29
- * The socket route's middleware and handlers: the upgrade loads
30
- * `graphql-ws` and names the subprotocol it serves in the `101`; each
31
- * open socket is a `graphql-ws` client, ended when it closes.
32
- */
33
- export declare function graphqlSocket<UserCtx extends YogaContext>(yogaAt: (endpoint: string) => YogaServerInstance<YogaContext, UserCtx>, endpoint: string, options: GraphQLWsOptions): {
18
+ /** Refuses, where `graphql()` is declared, a `keepAlive` that would ping in a loop. */
19
+ export declare function checkKeepAlive(options: GraphQLWsOptions): void;
20
+ export declare function graphqlSocket(graxia: Graxia<any>, endpoint: string, options: GraphQLWsOptions): {
34
21
  path: string;
35
- middleware: (ctx: BaseContext, next: NextFunction) => Promise<import("@alxia/core").Next<import("@alxia/core").Empty, import("@alxia/core").Empty>>;
22
+ middleware: (ctx: BaseContext, next: NextFunction) => Promise<any>;
36
23
  handlers: {
37
- open(socket: Socket<Record<string, unknown> & BaseContext, unknown>): void;
38
- message(socket: Socket<Record<string, unknown> & BaseContext, unknown>, message: unknown): Promise<void>;
39
- close(socket: Socket<Record<string, unknown> & BaseContext, unknown>, code: number, reason: string): Promise<void>;
24
+ open(socket: Socket<Record<string, any> & BaseContext, unknown>): void;
25
+ message(socket: Socket<Record<string, any> & BaseContext, unknown>, message: unknown): Promise<void>;
26
+ close(socket: Socket<Record<string, any> & BaseContext, unknown>, code: number, reason: string): Promise<void>;
27
+ drain(socket: Socket<Record<string, any> & BaseContext, unknown>): void;
40
28
  };
41
29
  };
42
30
  //# sourceMappingURL=ws.d.ts.map
package/dist/ws.d.ts.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"ws.d.ts","sourceRoot":"","sources":["../src/ws.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,KAAK,EAAE,WAAW,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAEhF,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AACvD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,WAAW,CAAC;AAI7C,+EAA+E;AAC/E,MAAM,WAAW,gBAAgB;IAChC;;;;OAIG;IACH,QAAQ,CAAC,IAAI,CAAC,EAAE,SAAS,CAAC;IAC1B;;;;OAIG;IACH,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,GAAG,KAAK,CAAC;CACpC;AAID,2EAA2E;AAC3E,eAAO,MAAM,YAAY,qJAC0H,CAAC;AAoDpJ;;;;GAIG;AACH,wBAAgB,aAAa,CAAC,OAAO,SAAS,WAAW,EACxD,MAAM,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,kBAAkB,CAAC,WAAW,EAAE,OAAO,CAAC,EACtE,QAAQ,EAAE,MAAM,EAChB,OAAO,EAAE,gBAAgB;;sBAUK,WAAW,QAAQ,YAAY;;;yFA0Cd,OAAO;oFAOZ,MAAM,UAAU,MAAM;;EAWhE"}
1
+ {"version":3,"file":"ws.d.ts","sourceRoot":"","sources":["../src/ws.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,OAAO,KAAK,EAAE,WAAW,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAChF,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAG3C,MAAM,WAAW,gBAAgB;IAChC,2EAA2E;IAC3E,QAAQ,CAAC,IAAI,CAAC,EAAE,SAAS,CAAC;IAC1B,uDAAuD;IACvD,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,GAAG,KAAK,CAAC;CACpC;AAID,uFAAuF;AACvF,wBAAgB,cAAc,CAAC,OAAO,EAAE,gBAAgB,GAAG,IAAI,CAa9D;AAED,wBAAgB,aAAa,CAC5B,MAAM,EAAE,MAAM,CAAC,GAAG,CAAC,EACnB,QAAQ,EAAE,MAAM,EAChB,OAAO,EAAE,gBAAgB;;sBAEK,WAAW,QAAQ,YAAY;;;qFAyBd,OAAO;gFAGZ,MAAM,UAAU,MAAM;;;EAQhE"}
package/docs/README.md CHANGED
@@ -10,10 +10,11 @@ a realistic example for each.
10
10
  | --- | --- |
11
11
  | [Mounting the endpoint](guide/endpoint.md) | adding GraphQL to an app, choosing its path under a prefix, putting it behind a guard, reading what it answers, telling GraphQL errors from the problem details of the HTTP layer around it, adding `health()` probes and draining it on `SIGTERM`, or its first spec |
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 a value loaded once per request (`oncePerRequest`, emptied per root mutation field by `freshPerMutation`), or reading the `missing …` compile error |
13
- | [Yoga's plugins and options](guide/yoga.md) | adding Yoga or Envelop plugins, exposing or masking errors, batching, serving subscriptions, bounding them with `boundedStream`, or calling the endpoint from another origin |
13
+ | [Plugins and options](guide/plugins.md) | adding graxia or Envelop plugins, exposing or masking errors, batching, serving subscriptions, bounding them with `boundedStream`, or calling the endpoint from another origin |
14
+ | [Migrating to graxia](migrating-to-graxia.md) | moving an app from the Yoga-based `@alxia/graphql` to graxia: peers, the curried `createSchema`, plugins, options, CSRF headers and refusal codes |
14
15
  | [GraphQL over WebSocket](guide/websockets.md) | serving Apollo Client's, urql's or `graphql-ws`'s WebSocket clients with `ws: true`, guarding the upgrade, reading `connectionParams`, the subprotocol, closing the sockets on shutdown, or testing a subscription over a socket |
15
16
  | [Running operations in process](guide/executor.md) | calling the schema from an MCP tool, a job or a script with `graphqlExecutor`: the same plugins, limits and error masking as the route, a server context you pass, a signal, what it leaves out |
16
- | [Harden it for production](guide/production.md) | putting a GraphQL API on the internet: rate limiting the endpoint, counting a field selected under aliases (`fieldRateLimit`), depth limits, the token cap, the nesting cap, the parse cache and the body limit, introspection off outside development, masked errors and the errors a client may read, a body limit, CSRF for a cookie session (`sameOrigin`), persisted operations |
17
+ | [Harden it for production](guide/production.md) | putting a GraphQL API on the internet: rate limiting the endpoint, counting a field selected under aliases (`fieldRateLimit`), depth limits, the token cap, the nesting cap, the parse cache and the body limit, introspection off outside development, masked errors and the errors a client may read, a body limit, CSRF for a cookie session (`csrf`), persisted operations |
17
18
  | [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'` |
18
19
  | [Testing the endpoint](guide/testing.md) | testing a GraphQL app without a server: `graphqlClient`, an auth header, a custom path, `GET`, persisted operations, the CSRF header, a typed document, the HTTP status of a 400 or a 413 |
19
20
  | [Troubleshooting](troubleshooting.md) | something went wrong and you have the message |
@@ -1,13 +1,13 @@
1
1
  # The typed context
2
2
 
3
- This page covers what a resolver reads as its context — Yoga's, the app's,
3
+ This page covers what a resolver reads as its context — graxia's, the app's,
4
4
  and what the `context` option adds — how to type a schema with it, and the
5
5
  compile error when the schema reads what the app does not build.
6
6
 
7
7
  ```ts
8
8
  import { alxia } from '@alxia/core';
9
9
  import { graphql, type GraphQLContext } from '@alxia/graphql';
10
- import { createSchema } from 'graphql-yoga';
10
+ import { createSchema } from '@graxia/core';
11
11
 
12
12
  const users = new Map([['1', { id: '1', name: 'Ada' }]]);
13
13
 
@@ -15,7 +15,7 @@ const base = alxia()
15
15
  .decorate({ users })
16
16
  .derive(({ request }) => ({ viewer: request.headers.get('x-user') }));
17
17
 
18
- const schema = createSchema<GraphQLContext<typeof base>>({
18
+ const schema = createSchema<GraphQLContext<typeof base>>()({
19
19
  typeDefs: /* GraphQL */ `
20
20
  type User { id: ID!, name: String! }
21
21
  type Query { me: String, user(id: ID!): User }
@@ -39,7 +39,7 @@ cannot be typed from `app` itself: `app` is built from the schema.
39
39
 
40
40
  ```ts
41
41
  type GraphQLContext<App, UserContext = Empty> =
42
- YogaInitialContext & ServerContext<ContextOf<App>> & UserContext;
42
+ CoreContext & ServerContext<ContextOf<App>> & GraphQLWsContext & UserContext;
43
43
  // when App is not an alxia app — a function returning one, a schema, a route:
44
44
  // { readonly '~error': 'GraphQLContext needs the type of an app: GraphQLContext<typeof app>' }
45
45
 
@@ -53,30 +53,31 @@ Given anything but an app's type, the context holds only that message, so
53
53
  the first resolver that reads a field is a compile error naming it:
54
54
 
55
55
  ```text
56
- error TS2339: Property 'viewer' does not exist on type '{ readonly '~error': "GraphQLContext needs the type of an app: GraphQLContext<typeof app>"; } & YogaInitialContext'.
56
+ error TS2339: Property 'viewer' does not exist on type '{ readonly '~error': "GraphQLContext needs the type of an app: GraphQLContext<typeof app>"; } & GraphQLWsContext'.
57
57
  ```
58
58
 
59
59
  Give it the app's type, `typeof base` — not that of a function that builds
60
60
  the app, nor of a schema
61
- ([Troubleshooting](../troubleshooting.md#property-viewer-does-not-exist-on-type--readonly-error-graphqlcontext-needs-the-type-of-an-app-graphqlcontexttypeof-app---yogainitialcontext)).
61
+ ([Troubleshooting](../troubleshooting.md#property-viewer-does-not-exist-on-type--readonly-error-graphqlcontext-needs-the-type-of-an-app-graphqlcontexttypeof-app---graphqlwscontext)).
62
62
 
63
63
  A resolver's context holds:
64
64
 
65
65
  | From | Fields |
66
66
  | --- | --- |
67
- | Yoga (`YogaInitialContext`) | `request`, and `params`: the GraphQL request's `query`, `variables`, `operationName`, `extensions` |
67
+ | graxia (`CoreContext`) | `signal`: the operation's `AbortSignal`, aborted when the client leaves, the stream ends or the server shuts down |
68
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
- | the route (`BaseContext`) | `url`, `ip`, `server`, `route`, `pathParams`, `error`, and `set` |
69
+ | the route (`BaseContext`) | `request`, `url`, `ip`, `server`, `route`, `pathParams`, `error`, and `set` |
70
+ | a WebSocket operation (`GraphQLWsContext`) | `connectionParams`, the client's, when the operation came over `ws` |
70
71
  | the `context` option | what it returns, as `UserContext` ([below](#the-context-option)) |
71
72
 
72
- What a route handler reads but a resolver does not: `query`, `headers`,
73
- `cookies` and `body` are the GraphQL request's, read through `request` and
74
- `params`; `reply` and `redirect` answer a route, not a field. `params` is
75
- Yoga's, not the route's path parameters. A resolver that reads one is a
76
- compile error:
73
+ What a route handler reads but a resolver does not: `params`, `query`,
74
+ `headers`, `cookies` and `body` are the route's, read through `request`;
75
+ `reply` and `redirect` answer a route, not a field. The request, params,
76
+ headers and cookies are not spread into the context any more. A resolver
77
+ that reads one is a compile error:
77
78
 
78
79
  ```text
79
- error TS2339: Property 'query' does not exist on type 'YogaInitialContext & ServerContext<…> & Empty'.
80
+ error TS2339: Property 'query' does not exist on type 'CoreContext & ServerContext<…> & GraphQLWsContext & Empty'.
80
81
  ```
81
82
 
82
83
  Read a header or a cookie from `request`:
@@ -89,10 +90,12 @@ const locale = (_: unknown, __: unknown, { request }: GraphQLContext<typeof base
89
90
  ## Setting a header or a cookie
90
91
 
91
92
  `set` is the route's: what a resolver sets on it is on the response, beside
92
- Yoga's own headers.
93
+ graxia's own headers. A header a resolver sets is lost on a server-sent
94
+ events or multipart response, whose headers left before the resolver ran, and
95
+ `set` is ignored over a WebSocket.
93
96
 
94
97
  ```ts
95
- const schema = createSchema<GraphQLContext<typeof base>>({
98
+ const schema = createSchema<GraphQLContext<typeof base>>()({
96
99
  typeDefs: /* GraphQL */ `type Query { ok: Boolean } type Mutation { login(name: String!): Boolean! }`,
97
100
  resolvers: {
98
101
  Mutation: {
@@ -111,7 +114,7 @@ const schema = createSchema<GraphQLContext<typeof base>>({
111
114
 
112
115
  ## The compile check
113
116
 
114
- Yoga's types alone accept any schema. `graphql` also checks that the
117
+ graxia's types alone accept any schema. `graphql` also checks that the
115
118
  context the app builds holds what the schema's resolvers read. A schema
116
119
  typed with a context the app does not build is refused, and the error names
117
120
  the missing field:
@@ -132,7 +135,7 @@ app the schema was typed from, after its middlewares:
132
135
  [Troubleshooting](../troubleshooting.md#the-schemas-resolvers-read-a-context-the-app-does-not-build-missing-).
133
136
 
134
137
  An untyped schema — `createSchema({ … })` with no type argument — passes
135
- on any app, but its resolvers see Yoga's context only: reading `viewer`
138
+ on any app, but its resolvers see graxia's context only: reading `viewer`
136
139
  there is `Property 'viewer' does not exist`. Type the schema to read the
137
140
  app's context.
138
141
 
@@ -144,9 +147,9 @@ schema you give it:
144
147
 
145
148
  ```ts
146
149
  import { alxia } from '@alxia/core';
147
- import { graphql, type GraphQLContext } from '@alxia/graphql';
150
+ import { graphql, type GraphQLContext, type GraphQLContextInit } from '@alxia/graphql';
148
151
  import { bearer, createJwt } from '@alxia/jwt';
149
- import { createSchema } from 'graphql-yoga';
152
+ import { createSchema } from '@graxia/core';
150
153
  import { z } from 'zod';
151
154
 
152
155
  const jwt = createJwt({ secret: Bun.env['JWT_SECRET']! });
@@ -154,7 +157,7 @@ const Claims = z.object({ sub: z.string(), role: z.enum(['admin', 'user']) });
154
157
 
155
158
  const base = alxia().use(bearer({ jwt, schema: Claims })); // 401 without a valid token
156
159
 
157
- const schema = createSchema<GraphQLContext<typeof base>>({
160
+ const schema = createSchema<GraphQLContext<typeof base>>()({
158
161
  typeDefs: /* GraphQL */ `type Query { me: String!, isAdmin: Boolean! }`,
159
162
  resolvers: {
160
163
  Query: {
@@ -172,14 +175,16 @@ The guard's `401` and its body are `@alxia/jwt`'s, described in its
172
175
 
173
176
  ## The `context` option
174
177
 
175
- Yoga's `context` option adds to the context per request. Its argument is
176
- the context so far — Yoga's and the app's — and what it returns is merged
177
- in. Give its type to `GraphQLContext` as the second argument:
178
+ The `context` option adds to the context per request. Its argument is
179
+ graxia's `ContextInit`: the `request`, the `signal` and the `serverContext`,
180
+ which is what the app's middlewares built. What it returns is merged in
181
+ (graxia's `onContext` hook, which a plugin implements, does the same).
182
+ Give the type of what it returns to `GraphQLContext` as the second argument:
178
183
 
179
184
  ```ts
180
185
  type Loaders = { loaders: { user: (id: string) => Promise<User | null> } };
181
186
 
182
- const schema = createSchema<GraphQLContext<typeof base, Loaders>>({
187
+ const schema = createSchema<GraphQLContext<typeof base, Loaders>>()({
183
188
  typeDefs: /* GraphQL */ `type User { id: ID!, name: String! } type Query { user(id: ID!): User }`,
184
189
  resolvers: {
185
190
  Query: { user: (_, { id }: { id: string }, { loaders }) => loaders.user(id) },
@@ -190,8 +195,8 @@ const app = base.plugin((app) =>
190
195
  graphql(app, {
191
196
  schema,
192
197
  // annotate the argument: see below
193
- context: ({ users }: GraphQLContext<typeof base>) => ({
194
- loaders: { user: async (id: string) => users.get(id) ?? null },
198
+ context: ({ serverContext }: GraphQLContextInit<typeof base>) => ({
199
+ loaders: { user: async (id: string) => serverContext.users.get(id) ?? null },
195
200
  }),
196
201
  }),
197
202
  );
@@ -200,17 +205,17 @@ const app = base.plugin((app) =>
200
205
  Without the `context` option, the same schema is refused: the error ends in
201
206
  `missing loaders`.
202
207
 
203
- **Annotate the argument when the function reads it.** TypeScript infers
208
+ **Annotate the argument when the function reads it** with `GraphQLContextInit<typeof base>` (the `ContextInit` of the app's `serverContext`, no `['~context']` to write). TypeScript infers
204
209
  `UserContext` from what the function returns only when the function does
205
- not depend on its parameter's contextual type. `({ users }) => …`
210
+ not depend on its parameter's contextual type. `({ serverContext }) => …`
206
211
  unannotated leaves `UserContext` as `Empty`, and the schema is refused
207
212
  with `missing loaders` although the function returns them. A function that
208
213
  takes no argument, or annotates it, is inferred:
209
214
 
210
215
  ```ts
211
216
  context: () => ({ loaders: createLoaders() }), // inferred
212
- context: ({ users }: GraphQLContext<typeof base>) => ({ loaders: …(users) }), // inferred
213
- context: ({ users }) => ({ loaders: …(users) }), // `missing loaders`
217
+ context: ({ serverContext }: GraphQLContextInit<typeof base>) => ({ loaders: …(serverContext.users) }), // inferred
218
+ context: ({ serverContext }) => ({ loaders: …(serverContext.users) }), // `missing loaders`
214
219
  ```
215
220
 
216
221
  Prefer a `derive` on the app for what every route needs — the user, a
@@ -241,7 +246,7 @@ const createLoaders = () => ({
241
246
  type Loaders = ReturnType<typeof createLoaders>;
242
247
  type Context = GraphQLContext<typeof base, { loaders: Loaders }>;
243
248
 
244
- const schema = createSchema<Context>({
249
+ const schema = createSchema<Context>()({
245
250
  typeDefs: /* GraphQL */ `type User { id: ID!, name: String! } type Note { author: User! } type Query { notes: [Note!]! }`,
246
251
  resolvers: { Note: { author: (note: { authorId: string }, _, { loaders }) => loaders.user.load(note.authorId) } },
247
252
  });
@@ -328,6 +333,9 @@ const resolvers = freshPerMutation({
328
333
  });
329
334
  ```
330
335
 
336
+ Given an array of maps (what `createSchema`'s `resolvers` accepts), it returns
337
+ an array: each map is wrapped on its own and graxia merges them afterwards.
338
+
331
339
  - Each root mutation field starts with an empty cache; its sub-fields share
332
340
  it. A query has no wrapped field, so it keeps one cache.
333
341
  - Only functions of `Mutation` are wrapped; other types and non-function