@distilled.cloud/core 1.0.0-rc.2 → 1.0.0-rc.20
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/LICENSE +201 -0
- package/lib/_bundle/aws.js +2 -0
- package/lib/_bundle/aws.js.map +1 -0
- package/lib/_bundle/base.js +5 -0
- package/lib/_bundle/base.js.map +1 -0
- package/lib/_bundle/graphql.js +3 -0
- package/lib/_bundle/graphql.js.map +1 -0
- package/lib/_bundle/grpc.js +2 -0
- package/lib/_bundle/grpc.js.map +1 -0
- package/lib/_bundle/rest.js +2 -0
- package/lib/_bundle/rest.js.map +1 -0
- package/lib/_bundle/xml.js +4 -0
- package/lib/_bundle/xml.js.map +1 -0
- package/lib/annotations.d.ts +17 -0
- package/lib/annotations.d.ts.map +1 -0
- package/lib/annotations.js +2 -0
- package/lib/annotations.js.map +1 -0
- package/lib/api.d.ts +174 -18
- package/lib/api.d.ts.map +1 -1
- package/lib/api.js +1 -178
- package/lib/category.d.ts +4 -4
- package/lib/category.d.ts.map +1 -1
- package/lib/category.js +1 -280
- package/lib/chunks.d.ts +3 -0
- package/lib/chunks.d.ts.map +1 -0
- package/lib/chunks.js +1 -0
- package/lib/config.d.ts +68 -0
- package/lib/config.d.ts.map +1 -0
- package/lib/config.js +1 -0
- package/lib/crypto.d.ts +76 -0
- package/lib/crypto.d.ts.map +1 -0
- package/lib/crypto.js +1 -0
- package/lib/error-category.d.ts +1 -1
- package/lib/error-category.d.ts.map +1 -1
- package/lib/error-category.js +1 -46
- package/lib/errors.d.ts +64 -72
- package/lib/errors.d.ts.map +1 -1
- package/lib/errors.js +1 -186
- package/lib/graphql.d.ts +403 -0
- package/lib/graphql.d.ts.map +1 -0
- package/lib/graphql.js +1 -0
- package/lib/graphql.types.d.ts +12 -0
- package/lib/graphql.types.d.ts.map +1 -0
- package/lib/graphql.types.js +1 -0
- package/lib/grpc-transport-cloudflare-http2.d.ts +7 -0
- package/lib/grpc-transport-cloudflare-http2.d.ts.map +1 -0
- package/lib/grpc-transport-cloudflare-http2.js +6 -0
- package/lib/grpc-transport-cloudflare-http2.js.map +1 -0
- package/lib/grpc-transport-cloudflare-sockets.d.ts +7 -0
- package/lib/grpc-transport-cloudflare-sockets.d.ts.map +1 -0
- package/lib/grpc-transport-cloudflare-sockets.js +5 -0
- package/lib/grpc-transport-cloudflare-sockets.js.map +1 -0
- package/lib/grpc-transport-node-http2.d.ts +19 -0
- package/lib/grpc-transport-node-http2.d.ts.map +1 -0
- package/lib/grpc-transport-node-http2.js +2 -0
- package/lib/grpc-transport-node-http2.js.map +1 -0
- package/lib/grpc-transport.d.ts +76 -0
- package/lib/grpc-transport.d.ts.map +1 -0
- package/lib/grpc-transport.js +1 -0
- package/lib/hpack.d.ts +34 -0
- package/lib/hpack.d.ts.map +1 -0
- package/lib/hpack.js +2 -0
- package/lib/hpack.js.map +1 -0
- package/lib/index.d.ts +32 -0
- package/lib/index.d.ts.map +1 -0
- package/lib/index.js +17 -0
- package/lib/pagination.d.ts +101 -24
- package/lib/pagination.d.ts.map +1 -1
- package/lib/pagination.js +1 -182
- package/lib/plain-values.d.ts +10 -0
- package/lib/plain-values.d.ts.map +1 -0
- package/lib/plain-values.js +2 -0
- package/lib/plain-values.js.map +1 -0
- package/lib/protobuf.d.ts +92 -0
- package/lib/protobuf.d.ts.map +1 -0
- package/lib/protobuf.js +1 -0
- package/lib/protocol-grpc.d.ts +86 -0
- package/lib/protocol-grpc.d.ts.map +1 -0
- package/lib/protocol-grpc.js +1 -0
- package/lib/protocol-http.d.ts +102 -23
- package/lib/protocol-http.d.ts.map +1 -1
- package/lib/protocol-http.js +1 -554
- package/lib/protocol-rest.d.ts +120 -50
- package/lib/protocol-rest.d.ts.map +1 -1
- package/lib/protocol-rest.js +1 -242
- package/lib/query.d.ts +29 -0
- package/lib/query.d.ts.map +1 -0
- package/lib/query.js +1 -0
- package/lib/response-validation-strict.d.ts +48 -0
- package/lib/response-validation-strict.d.ts.map +1 -0
- package/lib/response-validation-strict.js +1 -0
- package/lib/response-validation.d.ts +86 -0
- package/lib/response-validation.d.ts.map +1 -0
- package/lib/response-validation.js +1 -0
- package/lib/retry-after.d.ts +3 -3
- package/lib/retry-after.d.ts.map +1 -1
- package/lib/retry-after.js +1 -112
- package/lib/retry.d.ts +48 -29
- package/lib/retry.d.ts.map +1 -1
- package/lib/retry.js +1 -210
- package/lib/schema-lite-impl.d.ts +158 -0
- package/lib/schema-lite-impl.d.ts.map +1 -0
- package/lib/schema-lite-impl.js +1 -0
- package/lib/schema-lite-typed.d.ts +41 -0
- package/lib/schema-lite-typed.d.ts.map +1 -0
- package/lib/schema-lite-typed.js +1 -0
- package/lib/schema-lite.d.ts +40 -0
- package/lib/schema-lite.d.ts.map +1 -0
- package/lib/schema-lite.js +1 -0
- package/lib/schema.d.ts +21 -7
- package/lib/schema.d.ts.map +1 -1
- package/lib/schema.js +1 -48
- package/lib/sdk-error.d.ts +27 -0
- package/lib/sdk-error.d.ts.map +1 -0
- package/lib/sdk-error.js +1 -0
- package/lib/sensitive.d.ts +28 -0
- package/lib/sensitive.d.ts.map +1 -0
- package/lib/sensitive.js +2 -0
- package/lib/sensitive.js.map +1 -0
- package/lib/telemetry-debug.d.ts +6 -0
- package/lib/telemetry-debug.d.ts.map +1 -0
- package/lib/telemetry-debug.js +2 -0
- package/lib/telemetry-debug.js.map +1 -0
- package/lib/telemetry-hooks.d.ts +32 -0
- package/lib/telemetry-hooks.d.ts.map +1 -0
- package/lib/telemetry-hooks.js +2 -0
- package/lib/telemetry-hooks.js.map +1 -0
- package/lib/telemetry-host-rules.d.ts +23 -0
- package/lib/telemetry-host-rules.d.ts.map +1 -0
- package/lib/telemetry-host-rules.js +2 -0
- package/lib/telemetry-host-rules.js.map +1 -0
- package/lib/telemetry-lambda-context.d.ts +17 -0
- package/lib/telemetry-lambda-context.d.ts.map +1 -0
- package/lib/telemetry-lambda-context.js +2 -0
- package/lib/telemetry-lambda-context.js.map +1 -0
- package/lib/telemetry-message-context.d.ts +52 -0
- package/lib/telemetry-message-context.d.ts.map +1 -0
- package/lib/telemetry-message-context.js +2 -0
- package/lib/telemetry-message-context.js.map +1 -0
- package/lib/telemetry-metrics.d.ts +6 -0
- package/lib/telemetry-metrics.d.ts.map +1 -0
- package/lib/telemetry-metrics.js +2 -0
- package/lib/telemetry-metrics.js.map +1 -0
- package/lib/telemetry-name-template.d.ts +13 -0
- package/lib/telemetry-name-template.d.ts.map +1 -0
- package/lib/telemetry-name-template.js +2 -0
- package/lib/telemetry-name-template.js.map +1 -0
- package/lib/telemetry-stream.d.ts +11 -0
- package/lib/telemetry-stream.d.ts.map +1 -0
- package/lib/telemetry-stream.js +2 -0
- package/lib/telemetry-stream.js.map +1 -0
- package/lib/telemetry-xray.d.ts +28 -0
- package/lib/telemetry-xray.d.ts.map +1 -0
- package/lib/telemetry-xray.js +2 -0
- package/lib/telemetry-xray.js.map +1 -0
- package/lib/telemetry.d.ts +288 -0
- package/lib/telemetry.d.ts.map +1 -0
- package/lib/telemetry.js +3 -0
- package/lib/telemetry.js.map +1 -0
- package/lib/trait.d.ts +71 -20
- package/lib/trait.d.ts.map +1 -1
- package/lib/trait.js +1 -107
- package/lib/unknown-error.d.ts +18 -0
- package/lib/unknown-error.d.ts.map +1 -0
- package/lib/unknown-error.js +1 -0
- package/lib/xml.d.ts +44 -0
- package/lib/xml.d.ts.map +1 -0
- package/lib/xml.js +1 -0
- package/package.json +13 -13
- package/src/annotations.ts +53 -0
- package/src/api.ts +1370 -200
- package/src/category.ts +76 -106
- package/src/chunks.ts +30 -0
- package/src/config.ts +245 -0
- package/src/crypto.ts +202 -0
- package/src/error-category.ts +16 -29
- package/src/errors.ts +75 -75
- package/src/graphql.ts +1778 -0
- package/src/graphql.types.ts +105 -0
- package/src/grpc-transport-cloudflare-http2.ts +494 -0
- package/src/grpc-transport-cloudflare-sockets.ts +299 -0
- package/src/grpc-transport-node-http2.ts +234 -0
- package/src/grpc-transport.ts +118 -0
- package/src/hpack.ts +331 -0
- package/src/index.ts +31 -0
- package/src/pagination.ts +368 -94
- package/src/plain-values.ts +41 -0
- package/src/protobuf.ts +1332 -0
- package/src/protocol-grpc.ts +641 -0
- package/src/protocol-http.ts +622 -322
- package/src/protocol-rest.ts +440 -227
- package/src/query.ts +39 -0
- package/src/response-validation-strict.ts +327 -0
- package/src/response-validation.ts +161 -0
- package/src/retry-after.ts +7 -13
- package/src/retry.ts +96 -110
- package/src/schema-lite-impl.ts +550 -0
- package/src/schema-lite-typed.ts +44 -0
- package/src/schema-lite.ts +44 -0
- package/src/schema.ts +259 -15
- package/src/sdk-error.ts +33 -0
- package/src/sensitive.ts +154 -0
- package/src/telemetry-debug.ts +179 -0
- package/src/telemetry-hooks.ts +33 -0
- package/src/telemetry-host-rules.ts +39 -0
- package/src/telemetry-lambda-context.ts +46 -0
- package/src/telemetry-message-context.ts +170 -0
- package/src/telemetry-metrics.ts +69 -0
- package/src/telemetry-name-template.ts +26 -0
- package/src/telemetry-stream.ts +100 -0
- package/src/telemetry-xray.ts +66 -0
- package/src/telemetry.ts +832 -0
- package/src/trait.ts +106 -67
- package/src/unknown-error.ts +38 -0
- package/src/xml.ts +346 -0
- package/lib/api.js.map +0 -1
- package/lib/category.js.map +0 -1
- package/lib/codegen/cli.d.ts +0 -29
- package/lib/codegen/cli.d.ts.map +0 -1
- package/lib/codegen/cli.js +0 -165
- package/lib/codegen/cli.js.map +0 -1
- package/lib/codegen/emit.d.ts +0 -129
- package/lib/codegen/emit.d.ts.map +0 -1
- package/lib/codegen/emit.js +0 -105
- package/lib/codegen/emit.js.map +0 -1
- package/lib/codegen/format.d.ts +0 -23
- package/lib/codegen/format.d.ts.map +0 -1
- package/lib/codegen/format.js +0 -28
- package/lib/codegen/format.js.map +0 -1
- package/lib/codegen/generator.d.ts +0 -334
- package/lib/codegen/generator.d.ts.map +0 -1
- package/lib/codegen/generator.js +0 -691
- package/lib/codegen/generator.js.map +0 -1
- package/lib/codegen/graph.d.ts +0 -36
- package/lib/codegen/graph.d.ts.map +0 -1
- package/lib/codegen/graph.js +0 -136
- package/lib/codegen/graph.js.map +0 -1
- package/lib/codegen/members.d.ts +0 -25
- package/lib/codegen/members.d.ts.map +0 -1
- package/lib/codegen/members.js +0 -55
- package/lib/codegen/members.js.map +0 -1
- package/lib/codegen/naming.d.ts +0 -29
- package/lib/codegen/naming.d.ts.map +0 -1
- package/lib/codegen/naming.js +0 -74
- package/lib/codegen/naming.js.map +0 -1
- package/lib/codegen/openapi-cli.d.ts +0 -38
- package/lib/codegen/openapi-cli.d.ts.map +0 -1
- package/lib/codegen/openapi-cli.js +0 -107
- package/lib/codegen/openapi-cli.js.map +0 -1
- package/lib/codegen/openapi.d.ts +0 -115
- package/lib/codegen/openapi.d.ts.map +0 -1
- package/lib/codegen/openapi.js +0 -1220
- package/lib/codegen/openapi.js.map +0 -1
- package/lib/codegen/operations.d.ts +0 -24
- package/lib/codegen/operations.d.ts.map +0 -1
- package/lib/codegen/operations.js +0 -56
- package/lib/codegen/operations.js.map +0 -1
- package/lib/codegen/pagination.d.ts +0 -39
- package/lib/codegen/pagination.d.ts.map +0 -1
- package/lib/codegen/pagination.js +0 -33
- package/lib/codegen/pagination.js.map +0 -1
- package/lib/codegen/prelude.d.ts +0 -15
- package/lib/codegen/prelude.d.ts.map +0 -1
- package/lib/codegen/prelude.js +0 -60
- package/lib/codegen/prelude.js.map +0 -1
- package/lib/error-category.js.map +0 -1
- package/lib/errors.js.map +0 -1
- package/lib/json-patch.d.ts +0 -44
- package/lib/json-patch.d.ts.map +0 -1
- package/lib/json-patch.js +0 -174
- package/lib/json-patch.js.map +0 -1
- package/lib/pagination.js.map +0 -1
- package/lib/protocol-http.js.map +0 -1
- package/lib/protocol-rest.js.map +0 -1
- package/lib/retry-after.js.map +0 -1
- package/lib/retry.js.map +0 -1
- package/lib/schema.js.map +0 -1
- package/lib/trait.js.map +0 -1
- package/src/codegen/cli.ts +0 -268
- package/src/codegen/emit.ts +0 -207
- package/src/codegen/format.ts +0 -47
- package/src/codegen/generator.ts +0 -1153
- package/src/codegen/graph.ts +0 -151
- package/src/codegen/members.ts +0 -71
- package/src/codegen/naming.ts +0 -86
- package/src/codegen/openapi-cli.ts +0 -166
- package/src/codegen/openapi.ts +0 -1450
- package/src/codegen/operations.ts +0 -76
- package/src/codegen/pagination.ts +0 -71
- package/src/codegen/prelude.ts +0 -70
- package/src/json-patch.ts +0 -222
package/src/graphql.ts
ADDED
|
@@ -0,0 +1,1778 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* GraphQL Query algebra -- the runtime generated GraphQL SDKs target.
|
|
3
|
+
*
|
|
4
|
+
* U+2500U+2500 Why this exists U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500
|
|
5
|
+
* A GraphQL document is a *selection*, not an RPC. Distilled used to bake a
|
|
6
|
+
* max-depth selection into every operation (`Railway.me({})` downloaded the
|
|
7
|
+
* world). This module instead treats every field as a lazy `Query<Value>`:
|
|
8
|
+
* reading `user.email` records that field, and nothing is posted until
|
|
9
|
+
* `Query.fn` evaluates the plan you returned.
|
|
10
|
+
*
|
|
11
|
+
* U+2500U+2500 The two phases U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500
|
|
12
|
+
* 1. Build (your function). `Railway.me()` / `user.email` / `Query.map` do
|
|
13
|
+
* not talk to the network. They construct an expression tree:
|
|
14
|
+
* Of | Map | Filter | FlatMap | Prop | Root
|
|
15
|
+
* The inner function of `Query.fn` is therefore a *builder*, not an
|
|
16
|
+
* Effect generator. No `yield*` inside it.
|
|
17
|
+
*
|
|
18
|
+
* 2. Evaluate (`Query.fn`). Walk the returned plan, paint every GraphQL
|
|
19
|
+
* field that appears onto one selection forest, POST that document
|
|
20
|
+
* once through {@link GqlTransport}, then interpret Map/Filter/FlatMap
|
|
21
|
+
* against the JSON. Effects reached via FlatMap (e.g.
|
|
22
|
+
* `usernameIsAvailable(name)`) run *after* the POST, with real values.
|
|
23
|
+
*
|
|
24
|
+
* U+2500U+2500 Combinators U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500
|
|
25
|
+
* - `Query.of(x)` -- a literal; never selected.
|
|
26
|
+
* - `Query.map` on a list -- callback receives `Query<Item>` so `p.name` is
|
|
27
|
+
* still a Query (selected). On a scalar, callback receives the value
|
|
28
|
+
* after extract (`stars => stars > 5`). Relay connections (`edges { node }`)
|
|
29
|
+
* are lists of the node type, so `projects({ first: 20 }).pipe(Query.map)`
|
|
30
|
+
* maps projects, not edges.
|
|
31
|
+
* - `Query.filter` -- predicate is `Query<Item> => Query<boolean>`; the
|
|
32
|
+
* boolean Query is walked for fields, then run per row after the POST.
|
|
33
|
+
* - `Query.flatMap` -- after extract, run `(value) => Effect | Query`.
|
|
34
|
+
* - `Query.pages` / `Query.items` -- a Stream over every page / node of a
|
|
35
|
+
* Relay connection, one POST per page (see "Pagination").
|
|
36
|
+
*
|
|
37
|
+
* U+2500U+2500 Types U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500
|
|
38
|
+
* `Query<Value>` is `QueryNode<Value>` plus the GraphQL fields of `Value`,
|
|
39
|
+
* so `user.name` type-checks. That copy is a circular type alias
|
|
40
|
+
* (`Query<User>` contains `Query<Project[]>` which contains `Query<User>`
|
|
41
|
+
* again). TypeScript leaves the cycle lazy; there is no depth cap.
|
|
42
|
+
*
|
|
43
|
+
* U+2500U+2500 Transport U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500
|
|
44
|
+
* {@link GqlTransport.execute} posts `{ query, variables, operationName }`.
|
|
45
|
+
* The Effect it returns may require Credentials / HttpClient; those leak
|
|
46
|
+
* into `Query.fn`'s requirements. It returns the parsed `data` and raw
|
|
47
|
+
* `errors`; `Query.fn` classifies the errors (see "Errors" below). A plan
|
|
48
|
+
* that can't be compiled fails with {@link GqlError}.
|
|
49
|
+
*
|
|
50
|
+
* Generated SDKs export *roots* (`Railway.me`, `Railway.project`).
|
|
51
|
+
* Combinators live in `@distilled.cloud/core/query`.
|
|
52
|
+
*/
|
|
53
|
+
import * as Context from "effect/Context";
|
|
54
|
+
import * as Data from "effect/Data";
|
|
55
|
+
import * as Effect from "effect/Effect";
|
|
56
|
+
import * as Option from "effect/Option";
|
|
57
|
+
import * as Redacted from "effect/Redacted";
|
|
58
|
+
import * as Schedule from "effect/Schedule";
|
|
59
|
+
import * as S from "effect/Schema";
|
|
60
|
+
import * as Stream from "effect/Stream";
|
|
61
|
+
import { unwrapRedactedDeep } from "./plain-values.ts";
|
|
62
|
+
import * as Telemetry from "./telemetry.ts";
|
|
63
|
+
|
|
64
|
+
export const QuerySymbol = /*@__PURE__*/ Symbol.for("@distilled.cloud/graphql/Query");
|
|
65
|
+
const inspect = /*@__PURE__*/ Symbol.for("nodejs.util.inspect.custom");
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* A plan that cannot be compiled (a programming error in the query). The
|
|
69
|
+
* compiler throws it; `Query.fn`, `Query.pages` and `Query.items` fail with
|
|
70
|
+
* it (see {@link compiling}).
|
|
71
|
+
*/
|
|
72
|
+
export class GqlError
|
|
73
|
+
extends /*@__PURE__*/ Data.TaggedError("GqlError")<{
|
|
74
|
+
readonly message: string;
|
|
75
|
+
}>
|
|
76
|
+
{
|
|
77
|
+
constructor(message: string) {
|
|
78
|
+
super({ message });
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** `f()`, with what the compiler throws failed as a {@link GqlError}. */
|
|
83
|
+
const compiling = <A>(f: () => A): Effect.Effect<A, GqlError> =>
|
|
84
|
+
Effect.try({
|
|
85
|
+
try: f,
|
|
86
|
+
catch: (e) =>
|
|
87
|
+
e instanceof GqlError ? e : new GqlError(e instanceof Error ? e.message : String(e)),
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
// U+2500U+2500 Errors U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500
|
|
91
|
+
//
|
|
92
|
+
// Every entry of a GraphQL `errors` array becomes one typed issue. Generated
|
|
93
|
+
// SDKs declare tagged error classes plus the matchers that recognize them,
|
|
94
|
+
// scoped to the root fields that can return them (or global). `Query.fn`
|
|
95
|
+
// classifies each entry against the roots its path points at, so the error
|
|
96
|
+
// channel is the union of the errors declared by the roots the plan reads.
|
|
97
|
+
|
|
98
|
+
/** Fields every classified GraphQL error carries. */
|
|
99
|
+
export const errorFields = {
|
|
100
|
+
message: S.String,
|
|
101
|
+
code: /*@__PURE__*/ S.optional(S.String),
|
|
102
|
+
path: /*@__PURE__*/ S.optional(
|
|
103
|
+
/*@__PURE__*/ S.Array(/*@__PURE__*/ S.Union([S.String, S.Number])),
|
|
104
|
+
),
|
|
105
|
+
locations: /*@__PURE__*/ S.optional(
|
|
106
|
+
/*@__PURE__*/ S.Array(/*@__PURE__*/ S.Struct({ line: S.Number, column: S.Number })),
|
|
107
|
+
),
|
|
108
|
+
extensions: /*@__PURE__*/ S.optional(S.Unknown),
|
|
109
|
+
traceId: /*@__PURE__*/ S.optional(S.String),
|
|
110
|
+
status: /*@__PURE__*/ S.optional(S.Number),
|
|
111
|
+
/** Server retry hint in seconds. */
|
|
112
|
+
retryAfter: /*@__PURE__*/ S.optional(S.Number),
|
|
113
|
+
};
|
|
114
|
+
|
|
115
|
+
/** The shape shared by every classified GraphQL error. */
|
|
116
|
+
export interface GraphQLIssue {
|
|
117
|
+
readonly _tag: string;
|
|
118
|
+
readonly message: string;
|
|
119
|
+
readonly code?: string;
|
|
120
|
+
readonly path?: ReadonlyArray<string | number>;
|
|
121
|
+
readonly locations?: ReadonlyArray<{
|
|
122
|
+
readonly line: number;
|
|
123
|
+
readonly column: number;
|
|
124
|
+
}>;
|
|
125
|
+
readonly extensions?: unknown;
|
|
126
|
+
readonly traceId?: string;
|
|
127
|
+
readonly status?: number;
|
|
128
|
+
readonly retryAfter?: number;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
export type GraphQLIssueProps = Omit<GraphQLIssue, "_tag">;
|
|
132
|
+
|
|
133
|
+
/** A GraphQL error no declared matcher recognizes. */
|
|
134
|
+
export class UnknownGraphQLError
|
|
135
|
+
extends /*@__PURE__*/ S.TaggedError<UnknownGraphQLError>()("UnknownGraphQLError", {
|
|
136
|
+
...errorFields,
|
|
137
|
+
/** Root field the error path points at, when the path is known. */
|
|
138
|
+
coordinate: /*@__PURE__*/ S.optional(S.String),
|
|
139
|
+
}) {}
|
|
140
|
+
|
|
141
|
+
/** One response carried errors with different tags; none is hidden. */
|
|
142
|
+
export class GraphQLFailure<E extends GraphQLIssue = GraphQLIssue>
|
|
143
|
+
extends /*@__PURE__*/ Data.TaggedError("GraphQLFailure")<{
|
|
144
|
+
readonly errors: readonly [E, ...E[]];
|
|
145
|
+
/** The partial response data, with sensitive fields wrapped in `Redacted`. */
|
|
146
|
+
readonly data: unknown;
|
|
147
|
+
readonly status?: number;
|
|
148
|
+
}>
|
|
149
|
+
{
|
|
150
|
+
get message(): string {
|
|
151
|
+
return this.errors
|
|
152
|
+
.map((e) => `${e._tag}${e.path?.length ? ` at ${e.path.join(".")}` : ""}: ${e.message}`)
|
|
153
|
+
.join("; ");
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** The request never produced a GraphQL response (network, HTTP, non-JSON). */
|
|
158
|
+
export class GraphQLTransportError
|
|
159
|
+
extends /*@__PURE__*/ Data.TaggedError("GraphQLTransportError")<{
|
|
160
|
+
readonly message: string;
|
|
161
|
+
readonly status?: number;
|
|
162
|
+
/** Server retry hint in seconds. */
|
|
163
|
+
readonly retryAfter?: number;
|
|
164
|
+
readonly cause?: unknown;
|
|
165
|
+
}> {}
|
|
166
|
+
|
|
167
|
+
/** A paginated connection reported more pages without a new cursor. */
|
|
168
|
+
export class GraphQLPaginationError
|
|
169
|
+
extends /*@__PURE__*/ Data.TaggedError("GraphQLPaginationError")<{
|
|
170
|
+
readonly message: string;
|
|
171
|
+
readonly cursor: string | null;
|
|
172
|
+
}> {}
|
|
173
|
+
|
|
174
|
+
/** Recognizes a raw GraphQL error. Every present property must match. */
|
|
175
|
+
export interface ErrorMatcher {
|
|
176
|
+
readonly code?: string;
|
|
177
|
+
readonly message?: string;
|
|
178
|
+
readonly messageIncludes?: string;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** Runtime description of one generated error class. */
|
|
182
|
+
export interface ErrorSpec<E extends GraphQLIssue = GraphQLIssue> {
|
|
183
|
+
readonly tag: E["_tag"];
|
|
184
|
+
readonly make: (props: GraphQLIssueProps) => E;
|
|
185
|
+
readonly matchers: ReadonlyArray<ErrorMatcher>;
|
|
186
|
+
/** Queries failing only with retryable errors are retried. */
|
|
187
|
+
readonly retryable: boolean;
|
|
188
|
+
/** Applies to every root, including errors that carry no path. */
|
|
189
|
+
readonly global: boolean;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
export const errorSpec = <E extends GraphQLIssue>(
|
|
193
|
+
make: new (props: GraphQLIssueProps) => E,
|
|
194
|
+
tag: E["_tag"],
|
|
195
|
+
matchers: ReadonlyArray<ErrorMatcher>,
|
|
196
|
+
options: { readonly retryable?: boolean; readonly global?: boolean } = {},
|
|
197
|
+
): ErrorSpec<E> => ({
|
|
198
|
+
tag,
|
|
199
|
+
make: (props) => new make(props),
|
|
200
|
+
matchers,
|
|
201
|
+
retryable: options.retryable ?? false,
|
|
202
|
+
global: options.global ?? false,
|
|
203
|
+
});
|
|
204
|
+
|
|
205
|
+
/** An entry of a GraphQL response's `errors` array, as sent on the wire. */
|
|
206
|
+
export interface RawGraphQLError {
|
|
207
|
+
readonly message: string;
|
|
208
|
+
readonly path?: ReadonlyArray<string | number>;
|
|
209
|
+
readonly locations?: ReadonlyArray<{
|
|
210
|
+
readonly line: number;
|
|
211
|
+
readonly column: number;
|
|
212
|
+
}>;
|
|
213
|
+
readonly extensions?: Record<string, unknown>;
|
|
214
|
+
readonly [key: string]: unknown;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/** What a transport returns once it has a GraphQL response body. */
|
|
218
|
+
export interface GraphQLResponse {
|
|
219
|
+
readonly data?: unknown;
|
|
220
|
+
readonly errors?: ReadonlyArray<RawGraphQLError>;
|
|
221
|
+
readonly status?: number;
|
|
222
|
+
readonly headers?: Readonly<Record<string, string | undefined>>;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
export type ArgMeta = Record<string, string>;
|
|
226
|
+
|
|
227
|
+
export type FieldMeta = {
|
|
228
|
+
readonly name: string;
|
|
229
|
+
readonly kind: "scalar" | "object" | "list" | "connection";
|
|
230
|
+
readonly of?: TypeMeta;
|
|
231
|
+
readonly argTypes?: ArgMeta;
|
|
232
|
+
/** The value is a secret: extracted strings are wrapped in `Redacted`. */
|
|
233
|
+
readonly sensitive?: boolean;
|
|
234
|
+
};
|
|
235
|
+
|
|
236
|
+
export type TypeMeta = {
|
|
237
|
+
readonly name: string;
|
|
238
|
+
readonly fields: Record<string, FieldMeta>;
|
|
239
|
+
};
|
|
240
|
+
|
|
241
|
+
export const scalarField = (
|
|
242
|
+
name: string,
|
|
243
|
+
options: { readonly sensitive?: boolean } = {},
|
|
244
|
+
): FieldMeta => ({
|
|
245
|
+
name,
|
|
246
|
+
kind: "scalar",
|
|
247
|
+
...(options.sensitive ? { sensitive: true } : {}),
|
|
248
|
+
});
|
|
249
|
+
export const objectField = (name: string, objectType: TypeMeta): FieldMeta => ({
|
|
250
|
+
name,
|
|
251
|
+
kind: "object",
|
|
252
|
+
of: objectType,
|
|
253
|
+
});
|
|
254
|
+
export const listField = (name: string, itemType: TypeMeta, argTypes?: ArgMeta): FieldMeta => ({
|
|
255
|
+
name,
|
|
256
|
+
kind: "list",
|
|
257
|
+
of: itemType,
|
|
258
|
+
argTypes,
|
|
259
|
+
});
|
|
260
|
+
/** Relay connection: GraphQL `edges { node }` presented as `Query<Item[]>`. */
|
|
261
|
+
export const connectionField = (
|
|
262
|
+
name: string,
|
|
263
|
+
nodeType: TypeMeta,
|
|
264
|
+
argTypes?: ArgMeta,
|
|
265
|
+
): FieldMeta => ({
|
|
266
|
+
name,
|
|
267
|
+
kind: "connection",
|
|
268
|
+
of: nodeType,
|
|
269
|
+
argTypes,
|
|
270
|
+
});
|
|
271
|
+
|
|
272
|
+
export type TypeRef =
|
|
273
|
+
| { readonly tag: "scalar" }
|
|
274
|
+
| { readonly tag: "object"; readonly meta: TypeMeta }
|
|
275
|
+
| { readonly tag: "list"; readonly of: TypeRef };
|
|
276
|
+
|
|
277
|
+
const objectRef = (meta: TypeMeta): TypeRef => ({ tag: "object", meta });
|
|
278
|
+
const listRef = (itemType: TypeRef): TypeRef => ({
|
|
279
|
+
tag: "list",
|
|
280
|
+
of: itemType,
|
|
281
|
+
});
|
|
282
|
+
|
|
283
|
+
const fieldResult = (parent: TypeRef, field: FieldMeta): TypeRef => {
|
|
284
|
+
const inner = (): TypeRef => {
|
|
285
|
+
if (field.kind === "scalar") return { tag: "scalar" };
|
|
286
|
+
if (field.kind === "object") return objectRef(field.of!);
|
|
287
|
+
return listRef(objectRef(field.of!)); // list | connection
|
|
288
|
+
};
|
|
289
|
+
return parent.tag === "list" ? listRef(fieldResult(parent.of, field)) : inner();
|
|
290
|
+
};
|
|
291
|
+
|
|
292
|
+
const unwrapList = (typeRef: TypeRef): TypeRef => {
|
|
293
|
+
if (typeRef.tag !== "list") throw new GqlError("expected a list Query");
|
|
294
|
+
return typeRef.of;
|
|
295
|
+
};
|
|
296
|
+
|
|
297
|
+
const fieldsOf = (typeRef: TypeRef): Record<string, FieldMeta> => {
|
|
298
|
+
if (typeRef.tag === "object") return typeRef.meta.fields;
|
|
299
|
+
if (typeRef.tag === "list") return fieldsOf(typeRef.of);
|
|
300
|
+
return {};
|
|
301
|
+
};
|
|
302
|
+
|
|
303
|
+
export interface SelNode {
|
|
304
|
+
field: string;
|
|
305
|
+
alias: string | undefined;
|
|
306
|
+
args: Record<string, string> | undefined;
|
|
307
|
+
children: Map<string, SelNode>;
|
|
308
|
+
isScalar: boolean;
|
|
309
|
+
isList: boolean;
|
|
310
|
+
/** The value is a secret: its strings are wrapped in `Redacted`. */
|
|
311
|
+
sensitive?: boolean;
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
export interface CompiledOperation {
|
|
315
|
+
readonly document: string;
|
|
316
|
+
readonly operationName: string;
|
|
317
|
+
readonly variables: Record<string, unknown>;
|
|
318
|
+
readonly kind: "query" | "mutation";
|
|
319
|
+
readonly tree: SelNode;
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
/**
|
|
323
|
+
* What a GraphQL SDK's document spans carry, generated from its GraphQL
|
|
324
|
+
* model's `telemetry` entry (see `packages/dev/src/codegen/telemetry-traits.md`).
|
|
325
|
+
* One span per document: `<prefix>.<rootField>`, or `<prefix>.<kind>` when
|
|
326
|
+
* the document selects several root fields.
|
|
327
|
+
*/
|
|
328
|
+
export interface GraphQLTelemetry extends Telemetry.ServiceTelemetry {
|
|
329
|
+
readonly prefix: string;
|
|
330
|
+
/** `<kind>.<rootField>`, then argument name, then the attributes read from its value. */
|
|
331
|
+
readonly fields?: Readonly<
|
|
332
|
+
Record<string, Readonly<Record<string, ReadonlyArray<Telemetry.AttributeRule>>>>
|
|
333
|
+
>;
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
export class GqlTransport
|
|
337
|
+
extends /*@__PURE__*/ Context.Service<
|
|
338
|
+
GqlTransport,
|
|
339
|
+
{
|
|
340
|
+
readonly execute: (
|
|
341
|
+
req: CompiledOperation,
|
|
342
|
+
) => Effect.Effect<GraphQLResponse, GraphQLTransportError, any>;
|
|
343
|
+
/** The SDK's span facts; no spans without it. */
|
|
344
|
+
readonly telemetry?: GraphQLTelemetry;
|
|
345
|
+
}
|
|
346
|
+
>()("@distilled.cloud/graphql/Transport") {}
|
|
347
|
+
|
|
348
|
+
const log = (..._args: Array<unknown>): void => {};
|
|
349
|
+
|
|
350
|
+
/**
|
|
351
|
+
* GraphQL fields copied onto a Query so `user.name` type-checks.
|
|
352
|
+
* `Query<User>` contains `projects: Query<Project[]>`, which contains
|
|
353
|
+
* `owner: Query<User>` again -- TypeScript leaves the cycle lazy. Fields
|
|
354
|
+
* inherit the errors of the root they were read from.
|
|
355
|
+
*/
|
|
356
|
+
type QueryFields<Value, Error> = [NonNullable<Value>] extends [ReadonlyArray<infer Item>]
|
|
357
|
+
? {
|
|
358
|
+
readonly [Field in keyof NonNullable<Item>]: Query<
|
|
359
|
+
NonNullable<Item>[Field] | Nullish<Item>,
|
|
360
|
+
Error
|
|
361
|
+
>;
|
|
362
|
+
} & {
|
|
363
|
+
(args: Record<string, unknown>): Query<Value, Error>;
|
|
364
|
+
}
|
|
365
|
+
: [NonNullable<Value>] extends [object]
|
|
366
|
+
? {
|
|
367
|
+
readonly [Field in keyof NonNullable<Value>]: Query<
|
|
368
|
+
NonNullable<Value>[Field] | Nullish<Value>,
|
|
369
|
+
Error
|
|
370
|
+
>;
|
|
371
|
+
}
|
|
372
|
+
: {};
|
|
373
|
+
|
|
374
|
+
/** A field read through a `null` parent is `null`. */
|
|
375
|
+
type Nullish<Value> = Extract<Value, null | undefined>;
|
|
376
|
+
|
|
377
|
+
/**
|
|
378
|
+
* A lazy GraphQL selection. `Value` is the plain data after `Query.fn` runs;
|
|
379
|
+
* `Error` is the union of typed errors the roots it reads can return.
|
|
380
|
+
*/
|
|
381
|
+
export type Query<Value, Error = never> = QueryNode<Value, Error> & QueryFields<Value, Error>;
|
|
382
|
+
|
|
383
|
+
/** Strip Query/Effect wrappers from a returned plan down to plain data. */
|
|
384
|
+
export type UnwrapPlan<Plan> =
|
|
385
|
+
Plan extends QueryNode<infer Value, any>
|
|
386
|
+
? Value
|
|
387
|
+
: Plan extends Effect.Effect<infer Success, any, any>
|
|
388
|
+
? Success
|
|
389
|
+
: Plan extends ReadonlyArray<infer Element>
|
|
390
|
+
? ReadonlyArray<UnwrapPlan<Element>>
|
|
391
|
+
: Plan extends object
|
|
392
|
+
? { readonly [Key in keyof Plan]: UnwrapPlan<Plan[Key]> }
|
|
393
|
+
: Plan;
|
|
394
|
+
|
|
395
|
+
/** Typed errors of every Query and Effect in a returned plan. */
|
|
396
|
+
export type PlanError<Plan> =
|
|
397
|
+
Plan extends QueryNode<any, infer Error>
|
|
398
|
+
? Error
|
|
399
|
+
: Plan extends Effect.Effect<any, infer Error, any>
|
|
400
|
+
? Error
|
|
401
|
+
: Plan extends ReadonlyArray<infer Element>
|
|
402
|
+
? PlanError<Element>
|
|
403
|
+
: Plan extends object
|
|
404
|
+
? { readonly [Key in keyof Plan]: PlanError<Plan[Key]> }[keyof Plan]
|
|
405
|
+
: never;
|
|
406
|
+
|
|
407
|
+
/** Failures of evaluating a plan whose roots declare `Error`. */
|
|
408
|
+
export type QueryError<Error> =
|
|
409
|
+
| Error
|
|
410
|
+
| GraphQLFailure<Extract<Error, GraphQLIssue> | UnknownGraphQLError>
|
|
411
|
+
| UnknownGraphQLError
|
|
412
|
+
| GraphQLTransportError
|
|
413
|
+
| GqlError;
|
|
414
|
+
|
|
415
|
+
type Expr =
|
|
416
|
+
| RootExpr
|
|
417
|
+
| PropExpr
|
|
418
|
+
| ItemExpr
|
|
419
|
+
| MapValueExpr
|
|
420
|
+
| MapItemsExpr
|
|
421
|
+
| FilterExpr
|
|
422
|
+
| FlatMapExpr
|
|
423
|
+
| LiteralExpr;
|
|
424
|
+
|
|
425
|
+
type RootExpr = {
|
|
426
|
+
readonly _tag: "Root";
|
|
427
|
+
readonly op: "query" | "mutation";
|
|
428
|
+
readonly field: string;
|
|
429
|
+
readonly args: Record<string, unknown> | undefined;
|
|
430
|
+
readonly argTypes: ArgMeta | undefined;
|
|
431
|
+
readonly type: TypeRef;
|
|
432
|
+
/** Relay connection: paint `edges { node }`, extract an array of nodes. */
|
|
433
|
+
readonly connection?: boolean;
|
|
434
|
+
/** Errors this root field can return, including global errors. */
|
|
435
|
+
readonly errors: ReadonlyArray<ErrorSpec>;
|
|
436
|
+
/** Leaf root whose value is a secret: extracted strings are wrapped in `Redacted`. */
|
|
437
|
+
readonly sensitive?: boolean;
|
|
438
|
+
};
|
|
439
|
+
|
|
440
|
+
type PropExpr = {
|
|
441
|
+
readonly _tag: "Prop";
|
|
442
|
+
readonly parent: Expr;
|
|
443
|
+
readonly field: FieldMeta;
|
|
444
|
+
readonly type: TypeRef;
|
|
445
|
+
readonly args?: Record<string, unknown>;
|
|
446
|
+
};
|
|
447
|
+
|
|
448
|
+
type ItemExpr = {
|
|
449
|
+
readonly _tag: "Item";
|
|
450
|
+
readonly list: Expr;
|
|
451
|
+
readonly type: TypeRef;
|
|
452
|
+
};
|
|
453
|
+
|
|
454
|
+
type MapValueExpr = {
|
|
455
|
+
readonly _tag: "MapValue";
|
|
456
|
+
readonly parent: Expr;
|
|
457
|
+
readonly mapFn: (value: unknown) => unknown;
|
|
458
|
+
readonly type: TypeRef;
|
|
459
|
+
};
|
|
460
|
+
|
|
461
|
+
type MapItemsExpr = {
|
|
462
|
+
readonly _tag: "MapItems";
|
|
463
|
+
readonly parent: Expr;
|
|
464
|
+
readonly mapped: unknown;
|
|
465
|
+
/** Map one object (`null` stays `null`) instead of every list item. */
|
|
466
|
+
readonly single?: boolean;
|
|
467
|
+
readonly type: TypeRef;
|
|
468
|
+
};
|
|
469
|
+
|
|
470
|
+
type FilterExpr = {
|
|
471
|
+
readonly _tag: "Filter";
|
|
472
|
+
readonly parent: Expr;
|
|
473
|
+
readonly predicate: Expr;
|
|
474
|
+
readonly type: TypeRef;
|
|
475
|
+
};
|
|
476
|
+
|
|
477
|
+
type FlatMapExpr = {
|
|
478
|
+
readonly _tag: "FlatMap";
|
|
479
|
+
readonly parent: Expr;
|
|
480
|
+
readonly flatMapFn: (value: unknown) => unknown;
|
|
481
|
+
readonly type: TypeRef;
|
|
482
|
+
};
|
|
483
|
+
|
|
484
|
+
type LiteralExpr = {
|
|
485
|
+
readonly _tag: "Literal";
|
|
486
|
+
readonly value: unknown;
|
|
487
|
+
readonly type: TypeRef;
|
|
488
|
+
};
|
|
489
|
+
|
|
490
|
+
export class QueryNode<out Value = unknown, out Error = never> {
|
|
491
|
+
readonly [QuerySymbol] = QuerySymbol;
|
|
492
|
+
declare readonly valueType: Value;
|
|
493
|
+
declare readonly errorType: Error;
|
|
494
|
+
readonly expr: Expr;
|
|
495
|
+
constructor(expr: Expr) {
|
|
496
|
+
this.expr = expr;
|
|
497
|
+
return proxy(this) as QueryNode<Value, Error>;
|
|
498
|
+
}
|
|
499
|
+
pipe<Self>(this: Self): Self;
|
|
500
|
+
pipe<Self, Out1>(this: Self, step1: (_: Self) => Out1): Out1;
|
|
501
|
+
pipe<Self, Out1, Out2>(this: Self, step1: (_: Self) => Out1, step2: (_: Out1) => Out2): Out2;
|
|
502
|
+
pipe<Self, Out1, Out2, Out3>(
|
|
503
|
+
this: Self,
|
|
504
|
+
step1: (_: Self) => Out1,
|
|
505
|
+
step2: (_: Out1) => Out2,
|
|
506
|
+
step3: (_: Out2) => Out3,
|
|
507
|
+
): Out3;
|
|
508
|
+
pipe<Self, Out1, Out2, Out3, Out4>(
|
|
509
|
+
this: Self,
|
|
510
|
+
step1: (_: Self) => Out1,
|
|
511
|
+
step2: (_: Out1) => Out2,
|
|
512
|
+
step3: (_: Out2) => Out3,
|
|
513
|
+
step4: (_: Out3) => Out4,
|
|
514
|
+
): Out4;
|
|
515
|
+
pipe<Self, Out1, Out2, Out3, Out4, Out5>(
|
|
516
|
+
this: Self,
|
|
517
|
+
step1: (_: Self) => Out1,
|
|
518
|
+
step2: (_: Out1) => Out2,
|
|
519
|
+
step3: (_: Out2) => Out3,
|
|
520
|
+
step4: (_: Out3) => Out4,
|
|
521
|
+
step5: (_: Out4) => Out5,
|
|
522
|
+
): Out5;
|
|
523
|
+
pipe<Self, Out1, Out2, Out3, Out4, Out5, Out6>(
|
|
524
|
+
this: Self,
|
|
525
|
+
step1: (_: Self) => Out1,
|
|
526
|
+
step2: (_: Out1) => Out2,
|
|
527
|
+
step3: (_: Out2) => Out3,
|
|
528
|
+
step4: (_: Out3) => Out4,
|
|
529
|
+
step5: (_: Out4) => Out5,
|
|
530
|
+
step6: (_: Out5) => Out6,
|
|
531
|
+
): Out6;
|
|
532
|
+
pipe<Self, Out1, Out2, Out3, Out4, Out5, Out6, Out7>(
|
|
533
|
+
this: Self,
|
|
534
|
+
step1: (_: Self) => Out1,
|
|
535
|
+
step2: (_: Out1) => Out2,
|
|
536
|
+
step3: (_: Out2) => Out3,
|
|
537
|
+
step4: (_: Out3) => Out4,
|
|
538
|
+
step5: (_: Out4) => Out5,
|
|
539
|
+
step6: (_: Out5) => Out6,
|
|
540
|
+
step7: (_: Out6) => Out7,
|
|
541
|
+
): Out7;
|
|
542
|
+
pipe<Self, Out1, Out2, Out3, Out4, Out5, Out6, Out7, Out8>(
|
|
543
|
+
this: Self,
|
|
544
|
+
step1: (_: Self) => Out1,
|
|
545
|
+
step2: (_: Out1) => Out2,
|
|
546
|
+
step3: (_: Out2) => Out3,
|
|
547
|
+
step4: (_: Out3) => Out4,
|
|
548
|
+
step5: (_: Out4) => Out5,
|
|
549
|
+
step6: (_: Out5) => Out6,
|
|
550
|
+
step7: (_: Out6) => Out7,
|
|
551
|
+
step8: (_: Out7) => Out8,
|
|
552
|
+
): Out8;
|
|
553
|
+
pipe(...steps: Array<(_: any) => any>): unknown {
|
|
554
|
+
return steps.reduce((current, step) => step(current), this as never);
|
|
555
|
+
}
|
|
556
|
+
[inspect](): string {
|
|
557
|
+
return printExpr(this.expr);
|
|
558
|
+
}
|
|
559
|
+
toString(): string {
|
|
560
|
+
return this[inspect]();
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
export const isQuery = (value: unknown): value is Query<unknown> =>
|
|
565
|
+
(typeof value === "object" || typeof value === "function") &&
|
|
566
|
+
value !== null &&
|
|
567
|
+
QuerySymbol in value;
|
|
568
|
+
|
|
569
|
+
const make = <Value, Error = never>(expr: Expr): Query<Value, Error> =>
|
|
570
|
+
new QueryNode<Value, Error>(expr) as unknown as Query<Value, Error>;
|
|
571
|
+
|
|
572
|
+
const itemQuery = (list: QueryNode): QueryNode =>
|
|
573
|
+
new QueryNode({
|
|
574
|
+
_tag: "Item",
|
|
575
|
+
list: list.expr,
|
|
576
|
+
type: unwrapList(list.expr.type),
|
|
577
|
+
});
|
|
578
|
+
|
|
579
|
+
function proxy(self: QueryNode<unknown, unknown>): Query<unknown> {
|
|
580
|
+
const callable = Object.assign(function (bag?: Record<string, unknown>) {
|
|
581
|
+
return bag == null ? self : applyBag(self, bag);
|
|
582
|
+
}, self);
|
|
583
|
+
return new Proxy(callable, {
|
|
584
|
+
has: (_, prop) =>
|
|
585
|
+
prop === QuerySymbol ||
|
|
586
|
+
prop === inspect ||
|
|
587
|
+
prop in self ||
|
|
588
|
+
(typeof prop === "string" && prop in fieldsOf(self.expr.type)),
|
|
589
|
+
get: (_target, prop) => {
|
|
590
|
+
if (prop === QuerySymbol) return QuerySymbol;
|
|
591
|
+
if (prop === inspect) return self[inspect].bind(self);
|
|
592
|
+
if (prop === "pipe") return self.pipe.bind(self);
|
|
593
|
+
if (typeof prop === "string" && prop in self) {
|
|
594
|
+
const member = (self as unknown as Record<string, unknown>)[prop];
|
|
595
|
+
return typeof member === "function" ? member.bind(self) : member;
|
|
596
|
+
}
|
|
597
|
+
if (typeof prop !== "string") return undefined;
|
|
598
|
+
const field = fieldsOf(self.expr.type)[prop];
|
|
599
|
+
if (!field) return undefined;
|
|
600
|
+
return make({
|
|
601
|
+
_tag: "Prop",
|
|
602
|
+
parent: self.expr,
|
|
603
|
+
field,
|
|
604
|
+
type: fieldResult(self.expr.type, field),
|
|
605
|
+
});
|
|
606
|
+
},
|
|
607
|
+
apply: (_target, _thisArg, args) => applyBag(self, args[0] ?? {}),
|
|
608
|
+
}) as unknown as Query<unknown>;
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
const applyBag = <Value, Error>(
|
|
612
|
+
self: QueryNode<Value, Error>,
|
|
613
|
+
bag: Record<string, unknown>,
|
|
614
|
+
): Query<Value, Error> => {
|
|
615
|
+
const argTypes =
|
|
616
|
+
self.expr._tag === "Prop"
|
|
617
|
+
? self.expr.field.argTypes
|
|
618
|
+
: self.expr._tag === "Root"
|
|
619
|
+
? self.expr.argTypes
|
|
620
|
+
: undefined;
|
|
621
|
+
const args: Record<string, unknown> = {};
|
|
622
|
+
for (const [argName, argValue] of Object.entries(bag)) {
|
|
623
|
+
if (argTypes && argName in argTypes) args[argName] = argValue;
|
|
624
|
+
}
|
|
625
|
+
if (self.expr._tag === "Prop") {
|
|
626
|
+
return make<Value, Error>({
|
|
627
|
+
...self.expr,
|
|
628
|
+
args: { ...self.expr.args, ...args },
|
|
629
|
+
});
|
|
630
|
+
}
|
|
631
|
+
if (self.expr._tag === "Root") {
|
|
632
|
+
return make<Value, Error>({
|
|
633
|
+
...self.expr,
|
|
634
|
+
args: { ...self.expr.args, ...args },
|
|
635
|
+
});
|
|
636
|
+
}
|
|
637
|
+
return self as unknown as Query<Value, Error>;
|
|
638
|
+
};
|
|
639
|
+
|
|
640
|
+
export const root = <Value, Error = never>(
|
|
641
|
+
op: "query" | "mutation",
|
|
642
|
+
field: string,
|
|
643
|
+
meta: TypeMeta,
|
|
644
|
+
args?: Record<string, unknown>,
|
|
645
|
+
argTypes?: ArgMeta,
|
|
646
|
+
errors: ReadonlyArray<ErrorSpec> = [],
|
|
647
|
+
): Query<Value, Error> =>
|
|
648
|
+
make({
|
|
649
|
+
_tag: "Root",
|
|
650
|
+
op,
|
|
651
|
+
field,
|
|
652
|
+
args,
|
|
653
|
+
argTypes,
|
|
654
|
+
type: objectRef(meta),
|
|
655
|
+
errors,
|
|
656
|
+
});
|
|
657
|
+
|
|
658
|
+
export const rootList = <Item, Error = never>(
|
|
659
|
+
op: "query" | "mutation",
|
|
660
|
+
field: string,
|
|
661
|
+
meta: TypeMeta,
|
|
662
|
+
args?: Record<string, unknown>,
|
|
663
|
+
argTypes?: ArgMeta,
|
|
664
|
+
errors: ReadonlyArray<ErrorSpec> = [],
|
|
665
|
+
): Query<ReadonlyArray<Item>, Error> =>
|
|
666
|
+
make({
|
|
667
|
+
_tag: "Root",
|
|
668
|
+
op,
|
|
669
|
+
field,
|
|
670
|
+
args,
|
|
671
|
+
argTypes,
|
|
672
|
+
type: listRef(objectRef(meta)),
|
|
673
|
+
errors,
|
|
674
|
+
});
|
|
675
|
+
|
|
676
|
+
/** Root Relay connection: typed as `Query<Item[]>`, document uses `edges { node }`. */
|
|
677
|
+
export const rootConnection = <Item, Error = never>(
|
|
678
|
+
op: "query" | "mutation",
|
|
679
|
+
field: string,
|
|
680
|
+
meta: TypeMeta,
|
|
681
|
+
args?: Record<string, unknown>,
|
|
682
|
+
argTypes?: ArgMeta,
|
|
683
|
+
errors: ReadonlyArray<ErrorSpec> = [],
|
|
684
|
+
): Query<ReadonlyArray<Item>, Error> =>
|
|
685
|
+
make({
|
|
686
|
+
_tag: "Root",
|
|
687
|
+
op,
|
|
688
|
+
field,
|
|
689
|
+
args,
|
|
690
|
+
argTypes,
|
|
691
|
+
type: listRef(objectRef(meta)),
|
|
692
|
+
connection: true,
|
|
693
|
+
errors,
|
|
694
|
+
});
|
|
695
|
+
|
|
696
|
+
/** Root field whose GraphQL type is a scalar, enum, or list of those. */
|
|
697
|
+
export const rootLeaf = <Value, Error = never>(
|
|
698
|
+
op: "query" | "mutation",
|
|
699
|
+
field: string,
|
|
700
|
+
list: boolean,
|
|
701
|
+
args?: Record<string, unknown>,
|
|
702
|
+
argTypes?: ArgMeta,
|
|
703
|
+
errors: ReadonlyArray<ErrorSpec> = [],
|
|
704
|
+
options: { readonly sensitive?: boolean } = {},
|
|
705
|
+
): Query<Value, Error> =>
|
|
706
|
+
make({
|
|
707
|
+
_tag: "Root",
|
|
708
|
+
op,
|
|
709
|
+
field,
|
|
710
|
+
args,
|
|
711
|
+
argTypes,
|
|
712
|
+
type: list ? listRef({ tag: "scalar" }) : { tag: "scalar" },
|
|
713
|
+
errors,
|
|
714
|
+
...(options.sensitive ? { sensitive: true } : {}),
|
|
715
|
+
});
|
|
716
|
+
|
|
717
|
+
const printExpr = (expr: Expr): string => {
|
|
718
|
+
switch (expr._tag) {
|
|
719
|
+
case "Root":
|
|
720
|
+
return expr.args ? `${expr.field}(${JSON.stringify(expr.args)})` : expr.field;
|
|
721
|
+
case "Prop":
|
|
722
|
+
return `${printExpr(expr.parent)}.${expr.field.name}`;
|
|
723
|
+
case "Item":
|
|
724
|
+
return "$item";
|
|
725
|
+
case "MapValue":
|
|
726
|
+
return `map(${printExpr(expr.parent)})`;
|
|
727
|
+
case "MapItems":
|
|
728
|
+
return `mapItems(${printExpr(expr.parent)})`;
|
|
729
|
+
case "Filter":
|
|
730
|
+
return `filter(${printExpr(expr.parent)})`;
|
|
731
|
+
case "FlatMap":
|
|
732
|
+
return `flatMap(${printExpr(expr.parent)})`;
|
|
733
|
+
case "Literal":
|
|
734
|
+
return `of(${String(expr.value)})`;
|
|
735
|
+
}
|
|
736
|
+
};
|
|
737
|
+
|
|
738
|
+
const emptySel = (field: string): SelNode => ({
|
|
739
|
+
field,
|
|
740
|
+
alias: undefined,
|
|
741
|
+
args: undefined,
|
|
742
|
+
children: new Map(),
|
|
743
|
+
isScalar: false,
|
|
744
|
+
isList: false,
|
|
745
|
+
});
|
|
746
|
+
|
|
747
|
+
const stableStringify = (value: unknown): string => {
|
|
748
|
+
if (value === null || typeof value !== "object") return JSON.stringify(value);
|
|
749
|
+
if (Array.isArray(value)) return `[${value.map(stableStringify).join(",")}]`;
|
|
750
|
+
const keys = Object.keys(value as object).sort();
|
|
751
|
+
return `{${keys.map((key) => `${JSON.stringify(key)}:${stableStringify((value as Record<string, unknown>)[key])}`).join(",")}}`;
|
|
752
|
+
};
|
|
753
|
+
|
|
754
|
+
type Forest = {
|
|
755
|
+
kind: "query" | "mutation" | undefined;
|
|
756
|
+
roots: SelNode;
|
|
757
|
+
vars: Map<string, { type: string; value: unknown }>;
|
|
758
|
+
varI: number;
|
|
759
|
+
aliasI: number;
|
|
760
|
+
rootAlias: WeakMap<object, string>;
|
|
761
|
+
/** Response key of each root -> the root field and its declared errors. */
|
|
762
|
+
rootErrors: Map<string, RootErrors>;
|
|
763
|
+
};
|
|
764
|
+
|
|
765
|
+
interface RootErrors {
|
|
766
|
+
readonly field: string;
|
|
767
|
+
readonly errors: ReadonlyArray<ErrorSpec>;
|
|
768
|
+
}
|
|
769
|
+
|
|
770
|
+
const bindArgs = (
|
|
771
|
+
forest: Forest,
|
|
772
|
+
args: Record<string, unknown> | undefined,
|
|
773
|
+
argTypes: ArgMeta | undefined,
|
|
774
|
+
): Record<string, string> | undefined => {
|
|
775
|
+
if (args === undefined) return undefined;
|
|
776
|
+
const bound: Record<string, string> = {};
|
|
777
|
+
let hasArgs = false;
|
|
778
|
+
for (const [name, value] of Object.entries(args)) {
|
|
779
|
+
if (value === undefined) continue;
|
|
780
|
+
forest.vars.set(`v${forest.varI}`, {
|
|
781
|
+
type: argTypes?.[name] ?? "String",
|
|
782
|
+
value,
|
|
783
|
+
});
|
|
784
|
+
bound[name] = `v${forest.varI++}`;
|
|
785
|
+
hasArgs = true;
|
|
786
|
+
}
|
|
787
|
+
return hasArgs ? bound : undefined;
|
|
788
|
+
};
|
|
789
|
+
|
|
790
|
+
const ensureChild = (
|
|
791
|
+
forest: Forest,
|
|
792
|
+
parent: SelNode,
|
|
793
|
+
field: string,
|
|
794
|
+
options: {
|
|
795
|
+
args?: Record<string, unknown>;
|
|
796
|
+
argTypes?: ArgMeta;
|
|
797
|
+
isScalar?: boolean;
|
|
798
|
+
isList?: boolean;
|
|
799
|
+
sensitive?: boolean;
|
|
800
|
+
},
|
|
801
|
+
): SelNode => {
|
|
802
|
+
const args = unwrapRedactedDeep(options.args) as Record<string, unknown> | undefined;
|
|
803
|
+
const key = args === undefined ? field : `${field}:${stableStringify(args)}`;
|
|
804
|
+
const existing = parent.children.get(key);
|
|
805
|
+
if (existing) return existing;
|
|
806
|
+
const taken = new Set([...parent.children.values()].map((c) => c.alias ?? c.field));
|
|
807
|
+
let alias: string | undefined;
|
|
808
|
+
if (taken.has(field)) {
|
|
809
|
+
do {
|
|
810
|
+
alias = `${field}_${forest.aliasI++}`;
|
|
811
|
+
} while (taken.has(alias));
|
|
812
|
+
}
|
|
813
|
+
const sel: SelNode = {
|
|
814
|
+
field,
|
|
815
|
+
alias,
|
|
816
|
+
args: bindArgs(forest, args, options.argTypes),
|
|
817
|
+
children: new Map(),
|
|
818
|
+
isScalar: options.isScalar ?? false,
|
|
819
|
+
isList: options.isList ?? false,
|
|
820
|
+
...(options.sensitive ? { sensitive: true } : {}),
|
|
821
|
+
};
|
|
822
|
+
parent.children.set(key, sel);
|
|
823
|
+
return sel;
|
|
824
|
+
};
|
|
825
|
+
|
|
826
|
+
type Path = Array<string | "*">;
|
|
827
|
+
|
|
828
|
+
const paintConnection = (forest: Forest, connection: SelNode): Path => {
|
|
829
|
+
const edges = ensureChild(forest, connection, "edges", { isList: true });
|
|
830
|
+
ensureChild(forest, edges, "node", {});
|
|
831
|
+
return ["edges", "node"];
|
|
832
|
+
};
|
|
833
|
+
|
|
834
|
+
const paintAbs = (forest: Forest, expr: Expr): Path => {
|
|
835
|
+
switch (expr._tag) {
|
|
836
|
+
case "Root": {
|
|
837
|
+
if (forest.kind !== undefined && forest.kind !== expr.op) {
|
|
838
|
+
throw new GqlError(`cannot mix ${forest.kind} and ${expr.op} in one document`);
|
|
839
|
+
}
|
|
840
|
+
forest.kind = expr.op;
|
|
841
|
+
const node = ensureChild(forest, forest.roots, expr.field, {
|
|
842
|
+
args: expr.args,
|
|
843
|
+
argTypes: expr.argTypes,
|
|
844
|
+
// Leaf roots (`projectDelete: Boolean!`) take no sub-selection.
|
|
845
|
+
isScalar:
|
|
846
|
+
expr.type.tag === "scalar" || (expr.type.tag === "list" && expr.type.of.tag === "scalar"),
|
|
847
|
+
isList: expr.type.tag === "list" && !expr.connection,
|
|
848
|
+
sensitive: expr.sensitive,
|
|
849
|
+
});
|
|
850
|
+
const key = node.alias ?? node.field;
|
|
851
|
+
forest.rootAlias.set(expr, key);
|
|
852
|
+
forest.rootErrors.set(key, { field: expr.field, errors: expr.errors });
|
|
853
|
+
return expr.connection ? [key, ...paintConnection(forest, node)] : [key];
|
|
854
|
+
}
|
|
855
|
+
case "Prop": {
|
|
856
|
+
const parentPath = paintAbs(forest, expr.parent);
|
|
857
|
+
const parentSel = selAt(forest.roots, parentPath);
|
|
858
|
+
const node = ensureChild(forest, parentSel, expr.field.name, {
|
|
859
|
+
args: expr.args,
|
|
860
|
+
argTypes: expr.field.argTypes,
|
|
861
|
+
isScalar: expr.field.kind === "scalar",
|
|
862
|
+
isList: expr.field.kind === "list",
|
|
863
|
+
sensitive: expr.field.sensitive,
|
|
864
|
+
});
|
|
865
|
+
const path = [...parentPath, node.alias ?? node.field];
|
|
866
|
+
return expr.field.kind === "connection" ? [...path, ...paintConnection(forest, node)] : path;
|
|
867
|
+
}
|
|
868
|
+
default:
|
|
869
|
+
throw new GqlError(`paintAbs: ${expr._tag}`);
|
|
870
|
+
}
|
|
871
|
+
};
|
|
872
|
+
|
|
873
|
+
const selAt = (roots: SelNode, path: Path): SelNode => {
|
|
874
|
+
let current = roots;
|
|
875
|
+
for (const segment of path) {
|
|
876
|
+
if (segment === "*") continue;
|
|
877
|
+
const child = [...current.children.values()].find(
|
|
878
|
+
(candidate) => (candidate.alias ?? candidate.field) === segment,
|
|
879
|
+
);
|
|
880
|
+
if (!child) {
|
|
881
|
+
throw new GqlError(`internal: missing ${String(segment)}`);
|
|
882
|
+
}
|
|
883
|
+
current = child;
|
|
884
|
+
}
|
|
885
|
+
return current;
|
|
886
|
+
};
|
|
887
|
+
|
|
888
|
+
const connectionNodeSel = (connection: SelNode): SelNode => {
|
|
889
|
+
const edges = [...connection.children.values()].find((c) => c.field === "edges");
|
|
890
|
+
const node = edges ? [...edges.children.values()].find((c) => c.field === "node") : undefined;
|
|
891
|
+
if (!node) throw new GqlError("internal: connection missing edges.node");
|
|
892
|
+
return node;
|
|
893
|
+
};
|
|
894
|
+
|
|
895
|
+
const relSel = (expr: Expr, listSel: SelNode): SelNode => {
|
|
896
|
+
switch (expr._tag) {
|
|
897
|
+
case "Item":
|
|
898
|
+
return listSel;
|
|
899
|
+
case "Prop": {
|
|
900
|
+
const parent = relSel(expr.parent, listSel);
|
|
901
|
+
const child = [...parent.children.values()].find((c) => c.field === expr.field.name);
|
|
902
|
+
if (!child) {
|
|
903
|
+
throw new GqlError(`missing ${expr.field.name} in list selection`);
|
|
904
|
+
}
|
|
905
|
+
return expr.field.kind === "connection" ? connectionNodeSel(child) : child;
|
|
906
|
+
}
|
|
907
|
+
default:
|
|
908
|
+
return listSel;
|
|
909
|
+
}
|
|
910
|
+
};
|
|
911
|
+
|
|
912
|
+
const paintRel = (forest: Forest, expr: Expr, listSel: SelNode): void => {
|
|
913
|
+
switch (expr._tag) {
|
|
914
|
+
case "Item":
|
|
915
|
+
case "Literal":
|
|
916
|
+
return;
|
|
917
|
+
case "Prop": {
|
|
918
|
+
paintRel(forest, expr.parent, listSel);
|
|
919
|
+
const child = ensureChild(forest, relSel(expr.parent, listSel), expr.field.name, {
|
|
920
|
+
args: expr.args,
|
|
921
|
+
argTypes: expr.field.argTypes,
|
|
922
|
+
isScalar: expr.field.kind === "scalar",
|
|
923
|
+
isList: expr.field.kind === "list",
|
|
924
|
+
sensitive: expr.field.sensitive,
|
|
925
|
+
});
|
|
926
|
+
if (expr.field.kind === "connection") paintConnection(forest, child);
|
|
927
|
+
return;
|
|
928
|
+
}
|
|
929
|
+
case "MapValue":
|
|
930
|
+
case "FlatMap":
|
|
931
|
+
paintRel(forest, expr.parent, listSel);
|
|
932
|
+
return;
|
|
933
|
+
case "MapItems":
|
|
934
|
+
paintRel(forest, expr.parent, listSel);
|
|
935
|
+
visitRel(expr.mapped, forest, relSel(expr.parent, listSel));
|
|
936
|
+
return;
|
|
937
|
+
case "Filter":
|
|
938
|
+
paintRel(forest, expr.parent, listSel);
|
|
939
|
+
paintRel(forest, expr.predicate, relSel(expr.parent, listSel));
|
|
940
|
+
return;
|
|
941
|
+
case "Root":
|
|
942
|
+
throw new GqlError("root inside list item");
|
|
943
|
+
}
|
|
944
|
+
};
|
|
945
|
+
|
|
946
|
+
const visitExpr = (forest: Forest, expr: Expr): void => {
|
|
947
|
+
switch (expr._tag) {
|
|
948
|
+
case "Root":
|
|
949
|
+
case "Prop":
|
|
950
|
+
paintAbs(forest, expr);
|
|
951
|
+
return;
|
|
952
|
+
case "Item":
|
|
953
|
+
return;
|
|
954
|
+
case "Literal":
|
|
955
|
+
return;
|
|
956
|
+
case "MapValue":
|
|
957
|
+
case "FlatMap":
|
|
958
|
+
visitExpr(forest, expr.parent);
|
|
959
|
+
return;
|
|
960
|
+
case "MapItems": {
|
|
961
|
+
visitExpr(forest, expr.parent);
|
|
962
|
+
const path = paintAbs(forest, graphqlBase(expr.parent));
|
|
963
|
+
visitRel(expr.mapped, forest, selAt(forest.roots, path));
|
|
964
|
+
return;
|
|
965
|
+
}
|
|
966
|
+
case "Filter": {
|
|
967
|
+
visitExpr(forest, expr.parent);
|
|
968
|
+
const path = paintAbs(forest, graphqlBase(expr.parent));
|
|
969
|
+
paintRel(forest, expr.predicate, selAt(forest.roots, path));
|
|
970
|
+
return;
|
|
971
|
+
}
|
|
972
|
+
}
|
|
973
|
+
};
|
|
974
|
+
|
|
975
|
+
const graphqlBase = (expr: Expr): Expr => {
|
|
976
|
+
switch (expr._tag) {
|
|
977
|
+
case "Root":
|
|
978
|
+
case "Prop":
|
|
979
|
+
case "Item":
|
|
980
|
+
return expr;
|
|
981
|
+
case "MapValue":
|
|
982
|
+
case "MapItems":
|
|
983
|
+
case "Filter":
|
|
984
|
+
case "FlatMap":
|
|
985
|
+
return graphqlBase(expr.parent);
|
|
986
|
+
case "Literal":
|
|
987
|
+
throw new GqlError("literal has no graphql base");
|
|
988
|
+
}
|
|
989
|
+
};
|
|
990
|
+
|
|
991
|
+
const visitRel = (plan: unknown, forest: Forest, listSel: SelNode): void => {
|
|
992
|
+
if (isQuery(plan)) {
|
|
993
|
+
paintRel(forest, (plan as QueryNode).expr, listSel);
|
|
994
|
+
return;
|
|
995
|
+
}
|
|
996
|
+
if (plan !== null && typeof plan === "object" && !Effect.isEffect(plan)) {
|
|
997
|
+
for (const nested of Object.values(plan as Record<string, unknown>)) {
|
|
998
|
+
visitRel(nested, forest, listSel);
|
|
999
|
+
}
|
|
1000
|
+
}
|
|
1001
|
+
};
|
|
1002
|
+
|
|
1003
|
+
/**
|
|
1004
|
+
* Recurse through a builder return value. Query nodes contribute GraphQL
|
|
1005
|
+
* fields to `forest`; Effects are ignored until interpret (FlatMap).
|
|
1006
|
+
*/
|
|
1007
|
+
const visitPlan = (plan: unknown, forest: Forest): void => {
|
|
1008
|
+
if (isQuery(plan)) {
|
|
1009
|
+
log("visit", printExpr((plan as QueryNode).expr));
|
|
1010
|
+
visitExpr(forest, (plan as QueryNode).expr);
|
|
1011
|
+
return;
|
|
1012
|
+
}
|
|
1013
|
+
if (Effect.isEffect(plan)) return;
|
|
1014
|
+
if (plan !== null && typeof plan === "object" && !Array.isArray(plan)) {
|
|
1015
|
+
for (const nested of Object.values(plan as Record<string, unknown>)) {
|
|
1016
|
+
visitPlan(nested, forest);
|
|
1017
|
+
}
|
|
1018
|
+
}
|
|
1019
|
+
};
|
|
1020
|
+
|
|
1021
|
+
const validate = (node: SelNode): string | undefined => {
|
|
1022
|
+
for (const child of node.children.values()) {
|
|
1023
|
+
if (!child.isScalar && child.children.size === 0) {
|
|
1024
|
+
return `field "${child.field}" has no sub-selection`;
|
|
1025
|
+
}
|
|
1026
|
+
const inner = validate(child);
|
|
1027
|
+
if (inner) return inner;
|
|
1028
|
+
}
|
|
1029
|
+
return undefined;
|
|
1030
|
+
};
|
|
1031
|
+
|
|
1032
|
+
const printChildren = (node: SelNode, indent: number): string => {
|
|
1033
|
+
const pad = " ".repeat(indent);
|
|
1034
|
+
const lines: Array<string> = [];
|
|
1035
|
+
for (const child of node.children.values()) {
|
|
1036
|
+
let head = child.alias ? `${child.alias}: ${child.field}` : child.field;
|
|
1037
|
+
if (child.args && Object.keys(child.args).length > 0) {
|
|
1038
|
+
const printed = Object.entries(child.args)
|
|
1039
|
+
.map(([argName, varName]) => `${argName}: $${varName}`)
|
|
1040
|
+
.join(", ");
|
|
1041
|
+
head += `(${printed})`;
|
|
1042
|
+
}
|
|
1043
|
+
if (child.isScalar) lines.push(`${pad}${head}`);
|
|
1044
|
+
else {
|
|
1045
|
+
lines.push(`${pad}${head} {`);
|
|
1046
|
+
lines.push(printChildren(child, indent + 1));
|
|
1047
|
+
lines.push(`${pad}}`);
|
|
1048
|
+
}
|
|
1049
|
+
}
|
|
1050
|
+
return lines.join("\n");
|
|
1051
|
+
};
|
|
1052
|
+
|
|
1053
|
+
const emptyForest = (): Forest => ({
|
|
1054
|
+
kind: undefined,
|
|
1055
|
+
roots: emptySel(""),
|
|
1056
|
+
vars: new Map(),
|
|
1057
|
+
varI: 0,
|
|
1058
|
+
aliasI: 0,
|
|
1059
|
+
rootAlias: new WeakMap(),
|
|
1060
|
+
rootErrors: new Map(),
|
|
1061
|
+
});
|
|
1062
|
+
|
|
1063
|
+
const emit = (forest: Forest): Compiled => {
|
|
1064
|
+
const err = validate(forest.roots);
|
|
1065
|
+
if (err) throw new GqlError(err);
|
|
1066
|
+
const kind = forest.kind ?? "query";
|
|
1067
|
+
const varDefs = [...forest.vars.entries()]
|
|
1068
|
+
.map(([name, binding]) => `$${name}: ${binding.type}`)
|
|
1069
|
+
.join(", ");
|
|
1070
|
+
const header = varDefs.length > 0 ? `${kind} Gql(${varDefs})` : `${kind} Gql`;
|
|
1071
|
+
const variables: Record<string, unknown> = {};
|
|
1072
|
+
for (const [name, binding] of forest.vars) variables[name] = binding.value;
|
|
1073
|
+
return {
|
|
1074
|
+
document: `${header} {\n${printChildren(forest.roots, 1)}\n}`,
|
|
1075
|
+
operationName: "Gql",
|
|
1076
|
+
variables,
|
|
1077
|
+
kind,
|
|
1078
|
+
tree: forest.roots,
|
|
1079
|
+
rootAlias: forest.rootAlias,
|
|
1080
|
+
rootErrors: forest.rootErrors,
|
|
1081
|
+
};
|
|
1082
|
+
};
|
|
1083
|
+
|
|
1084
|
+
type Compiled = CompiledOperation & {
|
|
1085
|
+
readonly rootAlias: WeakMap<object, string>;
|
|
1086
|
+
readonly rootErrors: ReadonlyMap<string, RootErrors>;
|
|
1087
|
+
};
|
|
1088
|
+
|
|
1089
|
+
const nodesFromConnection = (value: unknown): unknown => {
|
|
1090
|
+
if (value == null) return value;
|
|
1091
|
+
if (Array.isArray(value)) return value.map(nodesFromConnection);
|
|
1092
|
+
const edges = (value as Record<string, unknown>).edges;
|
|
1093
|
+
if (!Array.isArray(edges)) return [];
|
|
1094
|
+
return edges.map((edge) => (edge == null ? edge : (edge as Record<string, unknown>).node));
|
|
1095
|
+
};
|
|
1096
|
+
|
|
1097
|
+
const readField = (parent: unknown, name: string): unknown => {
|
|
1098
|
+
if (parent == null) return parent;
|
|
1099
|
+
if (Array.isArray(parent)) {
|
|
1100
|
+
return parent.map((item) => (item == null ? item : (item as Record<string, unknown>)[name]));
|
|
1101
|
+
}
|
|
1102
|
+
return (parent as Record<string, unknown>)[name];
|
|
1103
|
+
};
|
|
1104
|
+
|
|
1105
|
+
/** Wrap every string of a sensitive scalar (or list of them) in `Redacted`. */
|
|
1106
|
+
const redactStrings = (value: unknown): unknown =>
|
|
1107
|
+
typeof value === "string"
|
|
1108
|
+
? Redacted.make(value)
|
|
1109
|
+
: Array.isArray(value)
|
|
1110
|
+
? value.map(redactStrings)
|
|
1111
|
+
: value;
|
|
1112
|
+
|
|
1113
|
+
/** Copy `data` with the strings of every sensitive field `sel` selects wrapped in `Redacted`. */
|
|
1114
|
+
const redactSelected = (sel: SelNode, data: unknown): unknown => {
|
|
1115
|
+
if (sel.children.size === 0 || data === null || typeof data !== "object") return data;
|
|
1116
|
+
if (Array.isArray(data)) return data.map((item) => redactSelected(sel, item));
|
|
1117
|
+
const out: Record<string, unknown> = { ...data };
|
|
1118
|
+
for (const child of sel.children.values()) {
|
|
1119
|
+
const key = child.alias ?? child.field;
|
|
1120
|
+
out[key] = child.sensitive ? redactStrings(out[key]) : redactSelected(child, out[key]);
|
|
1121
|
+
}
|
|
1122
|
+
return out;
|
|
1123
|
+
};
|
|
1124
|
+
|
|
1125
|
+
const extractAbs = (expr: Expr, data: unknown, rootAlias: WeakMap<object, string>): unknown => {
|
|
1126
|
+
switch (expr._tag) {
|
|
1127
|
+
case "Root": {
|
|
1128
|
+
const raw = (data as Record<string, unknown>)[rootAlias.get(expr) ?? expr.field];
|
|
1129
|
+
return expr.connection ? nodesFromConnection(raw) : raw;
|
|
1130
|
+
}
|
|
1131
|
+
case "Prop": {
|
|
1132
|
+
const value = readField(extractAbs(expr.parent, data, rootAlias), expr.field.name);
|
|
1133
|
+
return expr.field.kind === "connection" ? nodesFromConnection(value) : value;
|
|
1134
|
+
}
|
|
1135
|
+
default:
|
|
1136
|
+
throw new GqlError(`extractAbs: ${expr._tag}`);
|
|
1137
|
+
}
|
|
1138
|
+
};
|
|
1139
|
+
|
|
1140
|
+
const extractRel = (expr: Expr, item: unknown): unknown => {
|
|
1141
|
+
switch (expr._tag) {
|
|
1142
|
+
case "Item":
|
|
1143
|
+
return item;
|
|
1144
|
+
case "Prop": {
|
|
1145
|
+
const value = readField(extractRel(expr.parent, item), expr.field.name);
|
|
1146
|
+
return expr.field.kind === "connection" ? nodesFromConnection(value) : value;
|
|
1147
|
+
}
|
|
1148
|
+
default:
|
|
1149
|
+
throw new GqlError(`extractRel: ${expr._tag}`);
|
|
1150
|
+
}
|
|
1151
|
+
};
|
|
1152
|
+
|
|
1153
|
+
const inItem = (expr: Expr): boolean => {
|
|
1154
|
+
switch (expr._tag) {
|
|
1155
|
+
case "Item":
|
|
1156
|
+
return true;
|
|
1157
|
+
case "Prop":
|
|
1158
|
+
case "MapValue":
|
|
1159
|
+
case "MapItems":
|
|
1160
|
+
case "Filter":
|
|
1161
|
+
case "FlatMap":
|
|
1162
|
+
return inItem(expr.parent);
|
|
1163
|
+
default:
|
|
1164
|
+
return false;
|
|
1165
|
+
}
|
|
1166
|
+
};
|
|
1167
|
+
|
|
1168
|
+
const interpretExpr = (
|
|
1169
|
+
expr: Expr,
|
|
1170
|
+
data: unknown,
|
|
1171
|
+
rootAlias: WeakMap<object, string>,
|
|
1172
|
+
item: unknown,
|
|
1173
|
+
): unknown => {
|
|
1174
|
+
switch (expr._tag) {
|
|
1175
|
+
case "Literal":
|
|
1176
|
+
return expr.value;
|
|
1177
|
+
case "Item":
|
|
1178
|
+
return item;
|
|
1179
|
+
case "Root":
|
|
1180
|
+
case "Prop":
|
|
1181
|
+
return inItem(expr) ? extractRel(expr, item) : extractAbs(expr, data, rootAlias);
|
|
1182
|
+
case "MapValue":
|
|
1183
|
+
return expr.mapFn(interpretExpr(expr.parent, data, rootAlias, item));
|
|
1184
|
+
case "Filter": {
|
|
1185
|
+
const list = interpretExpr(expr.parent, data, rootAlias, item);
|
|
1186
|
+
const arr = Array.isArray(list) ? list : [];
|
|
1187
|
+
return arr.filter((row) => Boolean(interpretExpr(expr.predicate, data, rootAlias, row)));
|
|
1188
|
+
}
|
|
1189
|
+
case "MapItems": {
|
|
1190
|
+
const list = interpretExpr(expr.parent, data, rootAlias, item);
|
|
1191
|
+
if (expr.single) {
|
|
1192
|
+
return list == null ? null : interpretValueSync(expr.mapped, data, rootAlias, list);
|
|
1193
|
+
}
|
|
1194
|
+
const arr = Array.isArray(list) ? list : [];
|
|
1195
|
+
return arr.map((row) => interpretValueSync(expr.mapped, data, rootAlias, row));
|
|
1196
|
+
}
|
|
1197
|
+
case "FlatMap":
|
|
1198
|
+
throw new GqlError("FlatMap must be interpreted as Effect");
|
|
1199
|
+
}
|
|
1200
|
+
};
|
|
1201
|
+
|
|
1202
|
+
const interpretValueSync = (
|
|
1203
|
+
plan: unknown,
|
|
1204
|
+
data: unknown,
|
|
1205
|
+
rootAlias: WeakMap<object, string>,
|
|
1206
|
+
item: unknown,
|
|
1207
|
+
): unknown => {
|
|
1208
|
+
if (isQuery(plan)) {
|
|
1209
|
+
return interpretExpr((plan as QueryNode).expr, data, rootAlias, item);
|
|
1210
|
+
}
|
|
1211
|
+
if (plan !== null && typeof plan === "object" && !Effect.isEffect(plan)) {
|
|
1212
|
+
const out: Record<string, unknown> = {};
|
|
1213
|
+
for (const [key, nested] of Object.entries(plan as Record<string, unknown>)) {
|
|
1214
|
+
out[key] = interpretValueSync(nested, data, rootAlias, item);
|
|
1215
|
+
}
|
|
1216
|
+
return out;
|
|
1217
|
+
}
|
|
1218
|
+
return plan;
|
|
1219
|
+
};
|
|
1220
|
+
|
|
1221
|
+
const interpretPlan = (
|
|
1222
|
+
plan: unknown,
|
|
1223
|
+
data: unknown,
|
|
1224
|
+
rootAlias: WeakMap<object, string>,
|
|
1225
|
+
): Effect.Effect<unknown, unknown, GqlTransport> =>
|
|
1226
|
+
Effect.gen(function* () {
|
|
1227
|
+
if (isQuery(plan)) {
|
|
1228
|
+
const expr = (plan as QueryNode).expr;
|
|
1229
|
+
if (expr._tag === "FlatMap") {
|
|
1230
|
+
const resolved = yield* compiling(() =>
|
|
1231
|
+
interpretExpr(expr.parent, data, rootAlias, undefined),
|
|
1232
|
+
);
|
|
1233
|
+
const next = expr.flatMapFn(resolved);
|
|
1234
|
+
if (Effect.isEffect(next)) return yield* next;
|
|
1235
|
+
if (isQuery(next)) return yield* interpretPlan(next, data, rootAlias);
|
|
1236
|
+
return next;
|
|
1237
|
+
}
|
|
1238
|
+
return yield* compiling(() => interpretExpr(expr, data, rootAlias, undefined));
|
|
1239
|
+
}
|
|
1240
|
+
if (Effect.isEffect(plan)) return yield* plan;
|
|
1241
|
+
if (plan !== null && typeof plan === "object" && !Array.isArray(plan)) {
|
|
1242
|
+
const out: Record<string, unknown> = {};
|
|
1243
|
+
for (const [key, nested] of Object.entries(plan as Record<string, unknown>)) {
|
|
1244
|
+
out[key] = yield* interpretPlan(nested, data, rootAlias);
|
|
1245
|
+
}
|
|
1246
|
+
return out;
|
|
1247
|
+
}
|
|
1248
|
+
return plan;
|
|
1249
|
+
}) as Effect.Effect<unknown, unknown, GqlTransport>;
|
|
1250
|
+
|
|
1251
|
+
/**
|
|
1252
|
+
* Compile every Query in `plan` into one document, POST it, then replace
|
|
1253
|
+
* Query/Effect leaves with plain data (`UnwrapPlan`).
|
|
1254
|
+
*/
|
|
1255
|
+
const evaluatePlan = <Plan>(
|
|
1256
|
+
plan: Plan,
|
|
1257
|
+
): Effect.Effect<UnwrapPlan<Plan>, QueryError<PlanError<Plan>>, GqlTransport> =>
|
|
1258
|
+
Effect.gen(function* () {
|
|
1259
|
+
const forest = emptyForest();
|
|
1260
|
+
const compiled = yield* compiling(() => {
|
|
1261
|
+
visitPlan(plan, forest);
|
|
1262
|
+
return forest.roots.children.size > 0 ? emit(forest) : undefined;
|
|
1263
|
+
});
|
|
1264
|
+
let data: unknown = {};
|
|
1265
|
+
let rootAlias: WeakMap<object, string> = new WeakMap();
|
|
1266
|
+
if (compiled !== undefined) {
|
|
1267
|
+
log("document\n" + compiled.document);
|
|
1268
|
+
data = yield* execute(compiled);
|
|
1269
|
+
rootAlias = compiled.rootAlias;
|
|
1270
|
+
}
|
|
1271
|
+
return (yield* interpretPlan(plan, data, rootAlias)) as UnwrapPlan<Plan>;
|
|
1272
|
+
}) as Effect.Effect<UnwrapPlan<Plan>, QueryError<PlanError<Plan>>, GqlTransport>;
|
|
1273
|
+
|
|
1274
|
+
/**
|
|
1275
|
+
* POST one compiled document and fail with its classified errors. Queries
|
|
1276
|
+
* are retried (bounded) while every failure is retryable; mutations never
|
|
1277
|
+
* are, since an error can follow a side effect that already happened.
|
|
1278
|
+
*/
|
|
1279
|
+
const execute = (compiled: Compiled): Effect.Effect<unknown, ExecuteError, GqlTransport> => {
|
|
1280
|
+
const once = Effect.gen(function* () {
|
|
1281
|
+
const transport = yield* GqlTransport;
|
|
1282
|
+
const response = yield* transport.execute(compiled);
|
|
1283
|
+
const data = redactSelected(compiled.tree, response.data);
|
|
1284
|
+
const raw = response.errors ?? [];
|
|
1285
|
+
if (raw.length === 0) {
|
|
1286
|
+
// Without errors, a GraphQL response must carry a `data` object.
|
|
1287
|
+
if (!isRecord(response.data)) {
|
|
1288
|
+
return yield* Effect.fail(
|
|
1289
|
+
new GraphQLTransportError({
|
|
1290
|
+
message: "GraphQL response has no data object and no errors",
|
|
1291
|
+
status: response.status,
|
|
1292
|
+
}),
|
|
1293
|
+
);
|
|
1294
|
+
}
|
|
1295
|
+
return data;
|
|
1296
|
+
}
|
|
1297
|
+
const issues = raw.map((error) => classify(compiled, error, response));
|
|
1298
|
+
const [first, ...rest] = issues as [GraphQLIssue, ...GraphQLIssue[]];
|
|
1299
|
+
return yield* Effect.fail(
|
|
1300
|
+
rest.every((issue) => issue._tag === first._tag)
|
|
1301
|
+
? first
|
|
1302
|
+
: new GraphQLFailure({
|
|
1303
|
+
errors: [first, ...rest],
|
|
1304
|
+
data,
|
|
1305
|
+
status: response.status,
|
|
1306
|
+
}),
|
|
1307
|
+
);
|
|
1308
|
+
});
|
|
1309
|
+
const attempts = Effect.withFiber((fiber) => {
|
|
1310
|
+
if (compiled.kind !== "query") return once;
|
|
1311
|
+
const context = fiber.context as Context.Context<any>;
|
|
1312
|
+
let retries = 0;
|
|
1313
|
+
return once.pipe(
|
|
1314
|
+
Effect.retry({
|
|
1315
|
+
while: (error) => {
|
|
1316
|
+
const retry = isRetryable(compiled, error) && retries < 5;
|
|
1317
|
+
// Schedule.exponential("200 millis"): 200 ms, then doubling.
|
|
1318
|
+
if (retry) Telemetry.retried(context, ++retries, error, 200 * 2 ** (retries - 1));
|
|
1319
|
+
return retry;
|
|
1320
|
+
},
|
|
1321
|
+
times: 5,
|
|
1322
|
+
schedule: Schedule.exponential("200 millis"),
|
|
1323
|
+
}),
|
|
1324
|
+
);
|
|
1325
|
+
});
|
|
1326
|
+
return Effect.withFiber((fiber) => {
|
|
1327
|
+
const debug = fiber.getRef(Telemetry.Debug);
|
|
1328
|
+
const telemetry = Context.getOrUndefined(fiber.context, GqlTransport)?.telemetry;
|
|
1329
|
+
if (telemetry === undefined) return attempts;
|
|
1330
|
+
const [info, input] = documentInfo(telemetry, compiled);
|
|
1331
|
+
return Telemetry.operationSpan(fiber, debug, info, undefined, input, () => attempts);
|
|
1332
|
+
}) as Effect.Effect<unknown, ExecuteError, GqlTransport>;
|
|
1333
|
+
};
|
|
1334
|
+
|
|
1335
|
+
/**
|
|
1336
|
+
* One document's span facts: its root fields name it, and their arguments
|
|
1337
|
+
* fill the attributes the SDK's `fields` rules name (an input object keyed
|
|
1338
|
+
* `<kind>.<field>.<argument>`).
|
|
1339
|
+
*/
|
|
1340
|
+
const documentInfo = (
|
|
1341
|
+
telemetry: GraphQLTelemetry,
|
|
1342
|
+
compiled: Compiled,
|
|
1343
|
+
): readonly [Telemetry.OperationInfo, Record<string, unknown>] => {
|
|
1344
|
+
const roots = [...new Set([...compiled.tree.children.values()].map((node) => node.field))];
|
|
1345
|
+
const single = roots.length === 1 ? roots[0] : undefined;
|
|
1346
|
+
const target = single ?? compiled.kind;
|
|
1347
|
+
const input: Record<string, unknown> = {};
|
|
1348
|
+
const rules: Record<string, ReadonlyArray<Telemetry.AttributeRule>> = {};
|
|
1349
|
+
for (const node of compiled.tree.children.values()) {
|
|
1350
|
+
const fieldRules = telemetry.fields?.[`${compiled.kind}.${node.field}`];
|
|
1351
|
+
if (fieldRules === undefined || node.args === undefined) continue;
|
|
1352
|
+
for (const arg in node.args) {
|
|
1353
|
+
const argRules = fieldRules[arg];
|
|
1354
|
+
if (argRules === undefined) continue;
|
|
1355
|
+
const key = `${compiled.kind}.${node.field}.${arg}`;
|
|
1356
|
+
input[key] = compiled.variables[node.args[arg]!];
|
|
1357
|
+
rules[key] = argRules;
|
|
1358
|
+
}
|
|
1359
|
+
}
|
|
1360
|
+
const info = Telemetry.operationInfo(
|
|
1361
|
+
telemetry,
|
|
1362
|
+
{
|
|
1363
|
+
name: `${telemetry.prefix}.${target}`,
|
|
1364
|
+
method: `${telemetry.prefix}/${target}`,
|
|
1365
|
+
attributes: {
|
|
1366
|
+
"graphql.operation.type": compiled.kind,
|
|
1367
|
+
...(single !== undefined ? { "graphql.operation.name": single } : {}),
|
|
1368
|
+
},
|
|
1369
|
+
input: rules,
|
|
1370
|
+
},
|
|
1371
|
+
undefined,
|
|
1372
|
+
);
|
|
1373
|
+
return [info, input];
|
|
1374
|
+
};
|
|
1375
|
+
|
|
1376
|
+
type ExecuteError = GraphQLIssue | GraphQLFailure | GraphQLTransportError;
|
|
1377
|
+
|
|
1378
|
+
const isRetryable = (compiled: Compiled, error: ExecuteError): boolean => {
|
|
1379
|
+
if (error instanceof GraphQLTransportError) {
|
|
1380
|
+
return error.status === undefined || error.status === 429 || error.status >= 500;
|
|
1381
|
+
}
|
|
1382
|
+
const retryable = new Set(
|
|
1383
|
+
[...compiled.rootErrors.values()].flatMap((root) =>
|
|
1384
|
+
root.errors.filter((spec) => spec.retryable).map((spec) => spec.tag),
|
|
1385
|
+
),
|
|
1386
|
+
);
|
|
1387
|
+
return error instanceof GraphQLFailure
|
|
1388
|
+
? error.errors.every((issue) => retryable.has(issue._tag))
|
|
1389
|
+
: retryable.has(error._tag);
|
|
1390
|
+
};
|
|
1391
|
+
|
|
1392
|
+
const isRecord = (value: unknown): value is Record<string, unknown> =>
|
|
1393
|
+
typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1394
|
+
|
|
1395
|
+
/**
|
|
1396
|
+
* Pick the most specific matcher among the errors the root at `path[0]`
|
|
1397
|
+
* declares (or the global errors for a path-less error). A tie between
|
|
1398
|
+
* different tags is ambiguous and stays {@link UnknownGraphQLError}.
|
|
1399
|
+
*/
|
|
1400
|
+
const classify = (compiled: Compiled, entry: unknown, response: GraphQLResponse): GraphQLIssue => {
|
|
1401
|
+
// The entry comes from the wire: anything that is not an object (`null`,
|
|
1402
|
+
// a bare string) is read as an error with only a message.
|
|
1403
|
+
const raw: Partial<RawGraphQLError> = isRecord(entry)
|
|
1404
|
+
? (entry as Partial<RawGraphQLError>)
|
|
1405
|
+
: {
|
|
1406
|
+
message:
|
|
1407
|
+
typeof entry === "string"
|
|
1408
|
+
? entry
|
|
1409
|
+
: `malformed GraphQL error entry (${entry === null ? "null" : typeof entry})`,
|
|
1410
|
+
};
|
|
1411
|
+
const rawPath = Array.isArray(raw.path) ? (raw.path as ReadonlyArray<unknown>) : undefined;
|
|
1412
|
+
const root = typeof rawPath?.[0] === "string" ? compiled.rootErrors.get(rawPath[0]) : undefined;
|
|
1413
|
+
// The error classes validate `path` and `locations`, so a malformed value
|
|
1414
|
+
// is left out instead of making the constructor throw.
|
|
1415
|
+
const path = rawPath?.every((key) => typeof key === "string" || typeof key === "number")
|
|
1416
|
+
? (rawPath as ReadonlyArray<string | number>)
|
|
1417
|
+
: undefined;
|
|
1418
|
+
const locations =
|
|
1419
|
+
Array.isArray(raw.locations) &&
|
|
1420
|
+
raw.locations.every(
|
|
1421
|
+
(location: unknown) =>
|
|
1422
|
+
isRecord(location) &&
|
|
1423
|
+
typeof location.line === "number" &&
|
|
1424
|
+
typeof location.column === "number",
|
|
1425
|
+
)
|
|
1426
|
+
? raw.locations
|
|
1427
|
+
: undefined;
|
|
1428
|
+
const candidates = root
|
|
1429
|
+
? root.errors
|
|
1430
|
+
: uniqueByTag(
|
|
1431
|
+
[...compiled.rootErrors.values()].flatMap((entry) =>
|
|
1432
|
+
entry.errors.filter((spec) => spec.global),
|
|
1433
|
+
),
|
|
1434
|
+
);
|
|
1435
|
+
const extensions = isRecord(raw.extensions) ? raw.extensions : {};
|
|
1436
|
+
const code =
|
|
1437
|
+
typeof extensions.code === "string"
|
|
1438
|
+
? extensions.code
|
|
1439
|
+
: typeof extensions.errorCode === "string"
|
|
1440
|
+
? extensions.errorCode
|
|
1441
|
+
: undefined;
|
|
1442
|
+
const message = typeof raw.message === "string" ? raw.message : "";
|
|
1443
|
+
const retryHeader = response.headers?.["retry-after"];
|
|
1444
|
+
const props: GraphQLIssueProps = {
|
|
1445
|
+
message,
|
|
1446
|
+
code,
|
|
1447
|
+
path,
|
|
1448
|
+
locations,
|
|
1449
|
+
extensions: raw.extensions,
|
|
1450
|
+
traceId:
|
|
1451
|
+
typeof extensions.traceId === "string"
|
|
1452
|
+
? extensions.traceId
|
|
1453
|
+
: typeof raw.traceId === "string"
|
|
1454
|
+
? raw.traceId
|
|
1455
|
+
: undefined,
|
|
1456
|
+
status: response.status,
|
|
1457
|
+
retryAfter: retryHeader && /^\d+(\.\d+)?$/.test(retryHeader) ? Number(retryHeader) : undefined,
|
|
1458
|
+
};
|
|
1459
|
+
const matches = candidates.flatMap((spec) =>
|
|
1460
|
+
spec.matchers
|
|
1461
|
+
.filter(
|
|
1462
|
+
(matcher) =>
|
|
1463
|
+
(matcher.code === undefined || matcher.code === code) &&
|
|
1464
|
+
(matcher.message === undefined || matcher.message === message) &&
|
|
1465
|
+
(matcher.messageIncludes === undefined || message.includes(matcher.messageIncludes)),
|
|
1466
|
+
)
|
|
1467
|
+
.map((matcher) => ({
|
|
1468
|
+
spec,
|
|
1469
|
+
score:
|
|
1470
|
+
(matcher.code ? 1 : 0) + (matcher.message ? 4 : 0) + (matcher.messageIncludes ? 2 : 0),
|
|
1471
|
+
})),
|
|
1472
|
+
);
|
|
1473
|
+
matches.sort((a, b) => b.score - a.score);
|
|
1474
|
+
const best = matches[0];
|
|
1475
|
+
if (
|
|
1476
|
+
best &&
|
|
1477
|
+
!matches.some((match) => match.score === best.score && match.spec.tag !== best.spec.tag)
|
|
1478
|
+
) {
|
|
1479
|
+
return best.spec.make(props);
|
|
1480
|
+
}
|
|
1481
|
+
return new UnknownGraphQLError({
|
|
1482
|
+
...props,
|
|
1483
|
+
coordinate: root?.field,
|
|
1484
|
+
});
|
|
1485
|
+
};
|
|
1486
|
+
|
|
1487
|
+
const uniqueByTag = (specs: ReadonlyArray<ErrorSpec>): ErrorSpec[] => [
|
|
1488
|
+
...new Map(specs.map((spec) => [spec.tag, spec])).values(),
|
|
1489
|
+
];
|
|
1490
|
+
|
|
1491
|
+
/** `Query.of` / pure. */
|
|
1492
|
+
export const ofQuery = <Value>(value: Value): Query<Value> =>
|
|
1493
|
+
make({ _tag: "Literal", value, type: { tag: "scalar" } });
|
|
1494
|
+
|
|
1495
|
+
const filterImpl = (
|
|
1496
|
+
source: QueryNode,
|
|
1497
|
+
predicate: (item: QueryNode) => QueryNode,
|
|
1498
|
+
): Query<unknown> => {
|
|
1499
|
+
const proto = itemQuery(source);
|
|
1500
|
+
const predicateQuery = predicate(proto);
|
|
1501
|
+
log("filter pred", printExpr(predicateQuery.expr));
|
|
1502
|
+
return make({
|
|
1503
|
+
_tag: "Filter",
|
|
1504
|
+
parent: source.expr,
|
|
1505
|
+
predicate: predicateQuery.expr,
|
|
1506
|
+
type: source.expr.type,
|
|
1507
|
+
});
|
|
1508
|
+
};
|
|
1509
|
+
|
|
1510
|
+
export function filterQuery<Item, Error = never>(
|
|
1511
|
+
predicate: (item: Query<Item>) => QueryNode<boolean, any>,
|
|
1512
|
+
): (source: QueryNode<readonly Item[] | null, Error>) => Query<readonly Item[], Error>;
|
|
1513
|
+
export function filterQuery<Item, Error = never>(
|
|
1514
|
+
source: QueryNode<readonly Item[] | null, Error>,
|
|
1515
|
+
predicate: (item: Query<Item>) => QueryNode<boolean, any>,
|
|
1516
|
+
): Query<readonly Item[], Error>;
|
|
1517
|
+
export function filterQuery(sourceOrPredicate: any, predicate?: any): any {
|
|
1518
|
+
if (predicate === undefined) {
|
|
1519
|
+
return (source: QueryNode) => filterImpl(source, sourceOrPredicate);
|
|
1520
|
+
}
|
|
1521
|
+
return filterImpl(sourceOrPredicate, predicate);
|
|
1522
|
+
}
|
|
1523
|
+
|
|
1524
|
+
/**
|
|
1525
|
+
* What `Query.map`'s callback receives: a Query per item for lists, a Query
|
|
1526
|
+
* for an object (so its fields get selected), the plain value for scalars.
|
|
1527
|
+
*/
|
|
1528
|
+
type MapInput<Value> = [NonNullable<Value>] extends [ReadonlyArray<infer Item>]
|
|
1529
|
+
? Query<Item>
|
|
1530
|
+
: [NonNullable<Value>] extends [object]
|
|
1531
|
+
? Query<NonNullable<Value>>
|
|
1532
|
+
: Value;
|
|
1533
|
+
|
|
1534
|
+
/** An object mapped through a `null` value stays `null`. */
|
|
1535
|
+
type MapOutput<Value, Mapped> = [NonNullable<Value>] extends [ReadonlyArray<unknown>]
|
|
1536
|
+
? ReadonlyArray<UnwrapPlan<Mapped>>
|
|
1537
|
+
: [NonNullable<Value>] extends [object]
|
|
1538
|
+
? UnwrapPlan<Mapped> | Nullish<Value>
|
|
1539
|
+
: Mapped;
|
|
1540
|
+
|
|
1541
|
+
const mapImpl = (source: QueryNode, mapFn: (value: any) => unknown): Query<unknown> => {
|
|
1542
|
+
if (source.expr.type.tag === "object") {
|
|
1543
|
+
const mapped = mapFn(
|
|
1544
|
+
new QueryNode({
|
|
1545
|
+
_tag: "Item",
|
|
1546
|
+
list: source.expr,
|
|
1547
|
+
type: source.expr.type,
|
|
1548
|
+
}),
|
|
1549
|
+
);
|
|
1550
|
+
log("map object", printExpr(source.expr));
|
|
1551
|
+
return make({
|
|
1552
|
+
_tag: "MapItems",
|
|
1553
|
+
parent: source.expr,
|
|
1554
|
+
mapped,
|
|
1555
|
+
single: true,
|
|
1556
|
+
type: { tag: "scalar" },
|
|
1557
|
+
});
|
|
1558
|
+
}
|
|
1559
|
+
if (source.expr.type.tag === "list") {
|
|
1560
|
+
const proto = itemQuery(source);
|
|
1561
|
+
const mapped = mapFn(proto);
|
|
1562
|
+
log("map items", printExpr(source.expr));
|
|
1563
|
+
return make({
|
|
1564
|
+
_tag: "MapItems",
|
|
1565
|
+
parent: source.expr,
|
|
1566
|
+
mapped,
|
|
1567
|
+
type: source.expr.type,
|
|
1568
|
+
});
|
|
1569
|
+
}
|
|
1570
|
+
log("map value", printExpr(source.expr));
|
|
1571
|
+
return make({
|
|
1572
|
+
_tag: "MapValue",
|
|
1573
|
+
parent: source.expr,
|
|
1574
|
+
mapFn,
|
|
1575
|
+
type: { tag: "scalar" },
|
|
1576
|
+
});
|
|
1577
|
+
};
|
|
1578
|
+
|
|
1579
|
+
export function mapQuery<Value, Mapped, Error = never>(
|
|
1580
|
+
mapFn: (value: NoInfer<MapInput<Value>>) => Mapped,
|
|
1581
|
+
): (source: QueryNode<Value, Error>) => Query<MapOutput<Value, Mapped>, Error>;
|
|
1582
|
+
export function mapQuery<Value, Mapped, Error = never>(
|
|
1583
|
+
source: QueryNode<Value, Error>,
|
|
1584
|
+
mapFn: (value: NoInfer<MapInput<Value>>) => Mapped,
|
|
1585
|
+
): Query<MapOutput<Value, Mapped>, Error>;
|
|
1586
|
+
export function mapQuery(sourceOrMapFn: any, mapFn?: any): any {
|
|
1587
|
+
if (mapFn === undefined) {
|
|
1588
|
+
return (source: QueryNode) => mapImpl(source, sourceOrMapFn);
|
|
1589
|
+
}
|
|
1590
|
+
return mapImpl(sourceOrMapFn, mapFn);
|
|
1591
|
+
}
|
|
1592
|
+
|
|
1593
|
+
const flatMapImpl = (source: QueryNode, flatMapFn: (value: unknown) => unknown): Query<unknown> => {
|
|
1594
|
+
log("flatMap", printExpr(source.expr));
|
|
1595
|
+
return make({
|
|
1596
|
+
_tag: "FlatMap",
|
|
1597
|
+
parent: source.expr,
|
|
1598
|
+
flatMapFn,
|
|
1599
|
+
type: { tag: "scalar" },
|
|
1600
|
+
});
|
|
1601
|
+
};
|
|
1602
|
+
|
|
1603
|
+
export function flatMapQuery<Value, Result, Error, Requirements, SourceError = never>(
|
|
1604
|
+
flatMapFn: (
|
|
1605
|
+
value: Value,
|
|
1606
|
+
) => Effect.Effect<Result, Error, Requirements> | QueryNode<Result, Error>,
|
|
1607
|
+
): (source: QueryNode<Value, SourceError>) => Query<Result, SourceError | Error>;
|
|
1608
|
+
export function flatMapQuery<Value, Result, Error, Requirements, SourceError = never>(
|
|
1609
|
+
source: QueryNode<Value, SourceError>,
|
|
1610
|
+
flatMapFn: (
|
|
1611
|
+
value: Value,
|
|
1612
|
+
) => Effect.Effect<Result, Error, Requirements> | QueryNode<Result, Error>,
|
|
1613
|
+
): Query<Result, SourceError | Error>;
|
|
1614
|
+
export function flatMapQuery(sourceOrFlatMapFn: any, flatMapFn?: any): any {
|
|
1615
|
+
if (flatMapFn === undefined) {
|
|
1616
|
+
return (source: QueryNode) => flatMapImpl(source, sourceOrFlatMapFn);
|
|
1617
|
+
}
|
|
1618
|
+
return flatMapImpl(sourceOrFlatMapFn, flatMapFn);
|
|
1619
|
+
}
|
|
1620
|
+
|
|
1621
|
+
/**
|
|
1622
|
+
* Builder -> Effect. The inner function is *not* a generator; it returns a
|
|
1623
|
+
* plan of Query/Effect values. Query.fn visits the plan, POSTs one document,
|
|
1624
|
+
* then interprets Map/Filter/FlatMap/Of.
|
|
1625
|
+
*/
|
|
1626
|
+
export const queryFn =
|
|
1627
|
+
<Arguments extends Array<unknown>, Plan>(
|
|
1628
|
+
build: (...args: Arguments) => Plan,
|
|
1629
|
+
): ((
|
|
1630
|
+
...args: Arguments
|
|
1631
|
+
) => Effect.Effect<UnwrapPlan<Plan>, QueryError<PlanError<Plan>>, GqlTransport>) =>
|
|
1632
|
+
(...args) => {
|
|
1633
|
+
const plan = build(...args);
|
|
1634
|
+
return evaluatePlan(plan);
|
|
1635
|
+
};
|
|
1636
|
+
|
|
1637
|
+
// U+2500U+2500 Pagination U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500
|
|
1638
|
+
//
|
|
1639
|
+
// A connection lens hides `edges`/`pageInfo`. `Query.pages` re-evaluates the
|
|
1640
|
+
// query once per page: it sets the connection's `after` argument, paints
|
|
1641
|
+
// `pageInfo { hasNextPage endCursor }` next to `edges`, and stops when
|
|
1642
|
+
// `hasNextPage` is false.
|
|
1643
|
+
|
|
1644
|
+
/** The connection a paged query reads, below any list-level Map/Filter. */
|
|
1645
|
+
const connectionOf = (expr: Expr): RootExpr | PropExpr => {
|
|
1646
|
+
const base = graphqlBase(expr);
|
|
1647
|
+
const isConnection =
|
|
1648
|
+
(base._tag === "Root" && base.connection === true) ||
|
|
1649
|
+
(base._tag === "Prop" && base.field.kind === "connection");
|
|
1650
|
+
if (!isConnection || inItem(base)) {
|
|
1651
|
+
throw new GqlError(`Query.pages needs a Relay connection, got ${printExpr(base)}`);
|
|
1652
|
+
}
|
|
1653
|
+
const argTypes = base._tag === "Root" ? base.argTypes : base.field.argTypes;
|
|
1654
|
+
if (!argTypes || !("after" in argTypes)) {
|
|
1655
|
+
throw new GqlError(`${printExpr(base)} takes no "after" cursor`);
|
|
1656
|
+
}
|
|
1657
|
+
return base as RootExpr | PropExpr;
|
|
1658
|
+
};
|
|
1659
|
+
|
|
1660
|
+
/** Rebuild `expr` with the connection's `after` argument set. */
|
|
1661
|
+
const withCursor = (expr: Expr, connection: Expr, after: string | undefined): Expr => {
|
|
1662
|
+
if (expr === connection) {
|
|
1663
|
+
const current = expr as RootExpr | PropExpr;
|
|
1664
|
+
return { ...current, args: { ...current.args, after } } as Expr;
|
|
1665
|
+
}
|
|
1666
|
+
switch (expr._tag) {
|
|
1667
|
+
case "MapItems":
|
|
1668
|
+
case "Filter":
|
|
1669
|
+
case "MapValue":
|
|
1670
|
+
case "FlatMap":
|
|
1671
|
+
return { ...expr, parent: withCursor(expr.parent, connection, after) };
|
|
1672
|
+
default:
|
|
1673
|
+
throw new GqlError(`withCursor: ${expr._tag}`);
|
|
1674
|
+
}
|
|
1675
|
+
};
|
|
1676
|
+
|
|
1677
|
+
const readPath = (data: unknown, path: Path): unknown => {
|
|
1678
|
+
let current = data;
|
|
1679
|
+
for (const segment of path) {
|
|
1680
|
+
if (current == null) return undefined;
|
|
1681
|
+
if (Array.isArray(current)) {
|
|
1682
|
+
throw new GqlError("Query.pages cannot page a connection inside a list");
|
|
1683
|
+
}
|
|
1684
|
+
current = (current as Record<string, unknown>)[segment];
|
|
1685
|
+
}
|
|
1686
|
+
return current;
|
|
1687
|
+
};
|
|
1688
|
+
|
|
1689
|
+
interface PageState {
|
|
1690
|
+
readonly after: string | undefined;
|
|
1691
|
+
readonly seen: ReadonlySet<string>;
|
|
1692
|
+
}
|
|
1693
|
+
|
|
1694
|
+
const fetchPage = <Item>(
|
|
1695
|
+
query: QueryNode<ReadonlyArray<Item> | null, unknown>,
|
|
1696
|
+
connection: RootExpr | PropExpr,
|
|
1697
|
+
state: PageState,
|
|
1698
|
+
) =>
|
|
1699
|
+
Effect.gen(function* () {
|
|
1700
|
+
const { pageExpr, connectionPath, compiled } = yield* compiling(() => {
|
|
1701
|
+
const pageExpr = withCursor(query.expr, connection, state.after);
|
|
1702
|
+
const forest = emptyForest();
|
|
1703
|
+
visitExpr(forest, pageExpr);
|
|
1704
|
+
const nodePath = paintAbs(forest, withCursor(connection, connection, state.after));
|
|
1705
|
+
const connectionPath = nodePath.slice(0, -2);
|
|
1706
|
+
const pageInfo = ensureChild(forest, selAt(forest.roots, connectionPath), "pageInfo", {});
|
|
1707
|
+
ensureChild(forest, pageInfo, "hasNextPage", { isScalar: true });
|
|
1708
|
+
ensureChild(forest, pageInfo, "endCursor", { isScalar: true });
|
|
1709
|
+
return { pageExpr, connectionPath, compiled: emit(forest) };
|
|
1710
|
+
});
|
|
1711
|
+
log("page\n" + compiled.document);
|
|
1712
|
+
const data = yield* execute(compiled);
|
|
1713
|
+
const items = (yield* interpretPlan(make(pageExpr), data, compiled.rootAlias)) as
|
|
1714
|
+
| ReadonlyArray<Item>
|
|
1715
|
+
| null
|
|
1716
|
+
| undefined;
|
|
1717
|
+
const info = readPath(data, [...connectionPath, "pageInfo"]) as
|
|
1718
|
+
| { hasNextPage?: boolean; endCursor?: string | null }
|
|
1719
|
+
| null
|
|
1720
|
+
| undefined;
|
|
1721
|
+
const cursor = info?.endCursor ?? null;
|
|
1722
|
+
if (info?.hasNextPage !== true) {
|
|
1723
|
+
return [items ?? [], Option.none<PageState>()] as const;
|
|
1724
|
+
}
|
|
1725
|
+
if (cursor === null || cursor === state.after || state.seen.has(cursor)) {
|
|
1726
|
+
return yield* new GraphQLPaginationError({
|
|
1727
|
+
message: `${printExpr(connection)} returned a non-advancing cursor`,
|
|
1728
|
+
cursor,
|
|
1729
|
+
});
|
|
1730
|
+
}
|
|
1731
|
+
return [
|
|
1732
|
+
items ?? [],
|
|
1733
|
+
Option.some({ after: cursor, seen: new Set([...state.seen, cursor]) }),
|
|
1734
|
+
] as const;
|
|
1735
|
+
});
|
|
1736
|
+
|
|
1737
|
+
/**
|
|
1738
|
+
* Every page of a Relay connection, one request per page. `query` is a
|
|
1739
|
+
* connection lens (root or nested under objects), optionally mapped or
|
|
1740
|
+
* filtered: `Query.pages(Railway.project({ id }).services({ first: 50 }))`.
|
|
1741
|
+
* Starts from the query's own `after` argument, if any.
|
|
1742
|
+
*/
|
|
1743
|
+
export const pagesQuery = <Item, Error>(
|
|
1744
|
+
query: QueryNode<ReadonlyArray<Item> | null, Error>,
|
|
1745
|
+
): Stream.Stream<ReadonlyArray<Item>, QueryError<Error> | GraphQLPaginationError, GqlTransport> =>
|
|
1746
|
+
Stream.unwrap(
|
|
1747
|
+
Effect.map(
|
|
1748
|
+
compiling(() => connectionOf(query.expr)),
|
|
1749
|
+
(connection) => {
|
|
1750
|
+
const after = connection.args?.after;
|
|
1751
|
+
return Stream.paginate<
|
|
1752
|
+
PageState,
|
|
1753
|
+
ReadonlyArray<Item>,
|
|
1754
|
+
QueryError<Error> | GraphQLPaginationError,
|
|
1755
|
+
GqlTransport
|
|
1756
|
+
>(
|
|
1757
|
+
{
|
|
1758
|
+
after: typeof after === "string" ? after : undefined,
|
|
1759
|
+
seen: new Set(),
|
|
1760
|
+
},
|
|
1761
|
+
(state) =>
|
|
1762
|
+
fetchPage(query, connection, state).pipe(
|
|
1763
|
+
Effect.map(([items, next]) => [[items], next] as const),
|
|
1764
|
+
) as Effect.Effect<
|
|
1765
|
+
readonly [ReadonlyArray<ReadonlyArray<Item>>, Option.Option<PageState>],
|
|
1766
|
+
QueryError<Error> | GraphQLPaginationError,
|
|
1767
|
+
GqlTransport
|
|
1768
|
+
>,
|
|
1769
|
+
);
|
|
1770
|
+
},
|
|
1771
|
+
),
|
|
1772
|
+
);
|
|
1773
|
+
|
|
1774
|
+
/** Every node of a Relay connection, across all pages. */
|
|
1775
|
+
export const itemsQuery = <Item, Error>(
|
|
1776
|
+
query: QueryNode<ReadonlyArray<Item> | null, Error>,
|
|
1777
|
+
): Stream.Stream<Item, QueryError<Error> | GraphQLPaginationError, GqlTransport> =>
|
|
1778
|
+
pagesQuery(query).pipe(Stream.flatMap(Stream.fromIterable));
|