buildgql 0.1.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.
@@ -0,0 +1,85 @@
1
+ export { BuildGQLError, BuildGQLHttpError, BuildGQLResponseError, Client, ClientOptions, ExecuteOptions, GraphQLFormattedError, HeadersSource, SseTransportOptions, StreamChunk, SubscribePayload, SubscriptionTransport, WsTransportOptions, createClient, sseTransport, wsTransport } from './client/index.js';
2
+ import { N as NonNull, A as ArgSpec, F as FieldSelection, a as ArgsInput, b as VarsOf, S as SelectionNode, c as Selected, d as VarsIn, e as VarMarker, f as FragmentDefinition, R as RESULT, g as VARS, h as FragmentSpread, I as InlineFragment, i as Simplify, j as VarProxy } from './operation-DxbEION8.js';
3
+ export { k as AnyFieldSelection, l as Arg, D as Directive, K as KEY, O as Operation, U as UnionToIntersection, m as VarRef, n as makeMutation, o as makeQuery, p as makeSubscription } from './operation-DxbEION8.js';
4
+
5
+ type WrapTok = 'l' | '!';
6
+ /** Outer-to-inner wrapper tuple. `[]` means "nullable named type". */
7
+ type Wrap = readonly WrapTok[];
8
+ type Apply<W extends Wrap, T> = W extends readonly ['!', ...infer R] ? R extends Wrap ? NonNull<Apply<R, T>> : never : W extends readonly ['l', ...infer R] ? R extends Wrap ? Apply<R, T>[] | null : never : T | null;
9
+
10
+ /** Declares a field's argument types (compile time) and GraphQL types (runtime). */
11
+ declare function argSpec<T>(gql: Readonly<Record<string, string>>, enums?: readonly string[]): ArgSpec<T>;
12
+ /**
13
+ * PHANTOM CASTS IN THIS FILE
14
+ *
15
+ * Every `as unknown as` below is a phantom-type attachment. The value produced by
16
+ * `makeFieldNode(...)` (or by `make(alias)`) is already the complete runtime value;
17
+ * the cast exists only to stamp type parameters — `N`/`AL`, `Apply<W, T>`,
18
+ * `VarsOf<A, Spec>`, `VarsIn<S>` — that have no runtime representation at all.
19
+ * None of them can be derived structurally from the runtime value.
20
+ */
21
+ /** A scalar or enum field. `W` MUST be a `const` parameter or wrappers degrade. */
22
+ declare function leafField<N extends string, const W extends Wrap, T>(name: N, _wrap: W): FieldSelection<N, Apply<W, T>> & {
23
+ as<A extends string>(alias: A): FieldSelection<A, Apply<W, T>>;
24
+ };
25
+ /** A scalar or enum field that takes arguments. */
26
+ declare function leafFieldArgs<N extends string, const W extends Wrap, T, Spec>(name: N, _wrap: W, spec: ArgSpec<Spec>): (<A extends ArgsInput<Spec>>(argv: A) => FieldSelection<N, Apply<W, T>, VarsOf<A, Spec>>) & {
27
+ as<AL extends string>(alias: AL): <A extends ArgsInput<Spec>>(argv: A) => FieldSelection<AL, Apply<W, T>, VarsOf<A, Spec>>;
28
+ };
29
+ /** An object/interface/union field. `F` is the child field map from codegen. */
30
+ declare function objectField<N extends string, const W extends Wrap, F>(name: N, _wrap: W, fields: F): (<S extends readonly SelectionNode[]>(pick: (f: F) => readonly [...S]) => FieldSelection<N, Apply<W, Selected<S>>, VarsIn<S>>) & {
31
+ as<AL extends string>(alias: AL): <S extends readonly SelectionNode[]>(pick: (f: F) => readonly [...S]) => FieldSelection<AL, Apply<W, Selected<S>>, VarsIn<S>>;
32
+ };
33
+ /** An object field that takes arguments. */
34
+ declare function objectFieldArgs<N extends string, const W extends Wrap, F, Spec>(name: N, _wrap: W, fields: F, spec: ArgSpec<Spec>): (<A extends ArgsInput<Spec>, S extends readonly SelectionNode[]>(argv: A, pick: (f: F) => readonly [...S]) => FieldSelection<N, Apply<W, Selected<S>>, VarsIn<S> & VarsOf<A, Spec>>) & {
35
+ as<AL extends string>(alias: AL): <A extends ArgsInput<Spec>, S extends readonly SelectionNode[]>(argv: A, pick: (f: F) => readonly [...S]) => FieldSelection<AL, Apply<W, Selected<S>>, VarsIn<S> & VarsOf<A, Spec>>;
36
+ };
37
+
38
+ /**
39
+ * `include`/`skip` MUST be overloaded, not declared with a single
40
+ * `cond: boolean | VarMarker<Name>` parameter. With the union form, a literal
41
+ * `true` leaves `Name` unconstrained, so TypeScript falls back to its constraint
42
+ * and infers `Name = string`. `{ [P in string]: boolean }` is an *index
43
+ * signature*, which then intersects into the operation's variables type and makes
44
+ * the whole operation untypeable by its caller.
45
+ */
46
+ declare function include<N extends string, R, V>(sel: FieldSelection<N, R, V, boolean>, cond: boolean): FieldSelection<N, R, V, true>;
47
+ declare function include<N extends string, R, V, Name extends string>(sel: FieldSelection<N, R, V, boolean>, cond: VarMarker<Name>): FieldSelection<N, R, V & {
48
+ [P in Name]: boolean;
49
+ }, true>;
50
+ declare function skip<N extends string, R, V>(sel: FieldSelection<N, R, V, boolean>, cond: boolean): FieldSelection<N, R, V, true>;
51
+ declare function skip<N extends string, R, V, Name extends string>(sel: FieldSelection<N, R, V, boolean>, cond: VarMarker<Name>): FieldSelection<N, R, V & {
52
+ [P in Name]: boolean;
53
+ }, true>;
54
+
55
+ interface Fragment<R, V> extends FragmentDefinition {
56
+ readonly [RESULT]?: R;
57
+ readonly [VARS]?: V;
58
+ }
59
+ /** Codegen emits one of these per object type so the type condition is fixed. */
60
+ declare function makeFragment<F>(typeCondition: string, fields: F): <S extends readonly SelectionNode[]>(name: string, pick: (f: F) => readonly [...S]) => Fragment<Selected<S>, VarsIn<S>>;
61
+ declare function spread<R, V>(f: Fragment<R, V>): FragmentSpread<R, V>;
62
+
63
+ /**
64
+ * Narrow a union or interface field to a concrete type.
65
+ * `__typename` is injected into the result type of every branch so the union
66
+ * discriminates; the printer adds the matching field to the document.
67
+ */
68
+ declare function on<TN extends string, F, S extends readonly SelectionNode[]>(typename: TN, fields: F, pick: (f: F) => readonly [...S]): InlineFragment<TN, Simplify<Selected<S> & {
69
+ __typename: TN;
70
+ }>, VarsIn<S>>;
71
+
72
+ /**
73
+ * Placeholder proxy. The accessed key is deliberately ignored: a mapped type
74
+ * over `string` cannot preserve it, so the type system names the variable after
75
+ * the *argument key* instead. Recording `null` here keeps runtime and types in
76
+ * agreement — see `splitArgs` in builders.ts.
77
+ */
78
+ declare const $: VarProxy;
79
+ /** Explicitly name a variable — use when two fields would collide on an arg key. */
80
+ declare function v<N extends string>(name: N): VarMarker<N>;
81
+
82
+ /** Kept in step with package.json by `test/unit/public-api.test.ts`. */
83
+ declare const VERSION = "0.1.0";
84
+
85
+ export { $, type Apply, ArgSpec, ArgsInput, FieldSelection, type Fragment, FragmentDefinition, FragmentSpread, InlineFragment, NonNull, RESULT, Selected, SelectionNode, Simplify, VARS, VERSION, VarMarker, VarProxy, VarsIn, VarsOf, type Wrap, type WrapTok, argSpec, include, leafField, leafFieldArgs, makeFragment, objectField, objectFieldArgs, on, skip, spread, v };
package/dist/index.js ADDED
@@ -0,0 +1,313 @@
1
+ import {
2
+ BuildGQLError,
3
+ BuildGQLHttpError,
4
+ BuildGQLResponseError,
5
+ createClient,
6
+ sseTransport,
7
+ wsTransport
8
+ } from "./chunk-RSDTCILU.js";
9
+
10
+ // src/runtime/markers.ts
11
+ var VAR = /* @__PURE__ */ Symbol.for("buildgql.var");
12
+ var ENUM = /* @__PURE__ */ Symbol.for("buildgql.enum");
13
+ var VAR_REF = /* @__PURE__ */ Symbol.for("buildgql.varRef");
14
+ function makeVarMarker(name) {
15
+ return { [VAR]: true, __var: name };
16
+ }
17
+ function isVarMarker(x) {
18
+ return typeof x === "object" && x !== null && x[VAR] === true;
19
+ }
20
+ function markerName(m) {
21
+ return m.__var;
22
+ }
23
+ function enumValue(value) {
24
+ return { [ENUM]: value };
25
+ }
26
+ function isEnumValue(x) {
27
+ return typeof x === "object" && x !== null && typeof x[ENUM] === "string";
28
+ }
29
+ function varRefValue(name) {
30
+ return { [VAR_REF]: name };
31
+ }
32
+ function isVarRefValue(x) {
33
+ return typeof x === "object" && x !== null && typeof x[VAR_REF] === "string";
34
+ }
35
+
36
+ // src/runtime/builders.ts
37
+ function argSpec(gql, enums) {
38
+ return enums && enums.length > 0 ? { gql, enums } : { gql };
39
+ }
40
+ function markEnums(value) {
41
+ if (Array.isArray(value)) return value.map(markEnums);
42
+ return typeof value === "string" ? enumValue(value) : value;
43
+ }
44
+ function splitArgs(argv, spec) {
45
+ const literals = {};
46
+ const varRefs = [];
47
+ for (const [key, value] of Object.entries(argv)) {
48
+ if (isVarMarker(value)) {
49
+ const explicit = markerName(value);
50
+ const varName = explicit ?? key;
51
+ const gqlType = spec.gql[key];
52
+ if (gqlType === void 0) {
53
+ throw new Error(`buildgql: unknown argument "${key}" (no GraphQL type recorded for it)`);
54
+ }
55
+ varRefs.push({ varName, gqlType });
56
+ literals[key] = varRefValue(varName);
57
+ } else {
58
+ literals[key] = spec.enums?.includes(key) ? markEnums(value) : value;
59
+ }
60
+ }
61
+ return { literals, varRefs };
62
+ }
63
+ function makeFieldNode(name, alias, argv, sels, varRefs) {
64
+ return { kind: "field", name, alias, args: argv, sels, varRefs };
65
+ }
66
+ function leafField(name, _wrap) {
67
+ const base = makeFieldNode(name, void 0, void 0, void 0, []);
68
+ return Object.assign(base, {
69
+ as(alias) {
70
+ return makeFieldNode(name, alias, void 0, void 0, []);
71
+ }
72
+ });
73
+ }
74
+ function leafFieldArgs(name, _wrap, spec) {
75
+ const make = (alias) => (argv) => {
76
+ const { literals, varRefs } = splitArgs(argv, spec);
77
+ return makeFieldNode(name, alias, literals, void 0, varRefs);
78
+ };
79
+ return Object.assign(make(void 0), {
80
+ as(alias) {
81
+ return make(alias);
82
+ }
83
+ });
84
+ }
85
+ function objectField(name, _wrap, fields) {
86
+ const make = (alias) => (pick) => {
87
+ const sels = pick(fields);
88
+ return makeFieldNode(name, alias, void 0, sels, []);
89
+ };
90
+ return Object.assign(make(void 0), {
91
+ as(alias) {
92
+ return make(alias);
93
+ }
94
+ });
95
+ }
96
+ function objectFieldArgs(name, _wrap, fields, spec) {
97
+ const make = (alias) => (argv, pick) => {
98
+ const { literals, varRefs } = splitArgs(argv, spec);
99
+ const sels = pick(fields);
100
+ return makeFieldNode(name, alias, literals, sels, varRefs);
101
+ };
102
+ return Object.assign(make(void 0), {
103
+ as(alias) {
104
+ return make(alias);
105
+ }
106
+ });
107
+ }
108
+
109
+ // src/runtime/var.ts
110
+ var $ = new Proxy({}, {
111
+ get() {
112
+ return makeVarMarker(null);
113
+ }
114
+ });
115
+ function v(name) {
116
+ return makeVarMarker(name);
117
+ }
118
+
119
+ // src/runtime/directives.ts
120
+ function applyDirective(sel, name, cond) {
121
+ let directive;
122
+ if (typeof cond === "boolean") {
123
+ directive = { name, if: cond };
124
+ } else {
125
+ if (!isVarMarker(cond)) {
126
+ throw new Error(`buildgql: @${name} condition must be a boolean or a variable from v()`);
127
+ }
128
+ const varName = markerName(cond);
129
+ if (varName === null) {
130
+ throw new Error(
131
+ `buildgql: @${name} needs an explicitly named variable \u2014 use v('flagName'), not $.flagName. Directive conditions have no argument key to take their name from.`
132
+ );
133
+ }
134
+ directive = { name, if: { varName, gqlType: "Boolean!" } };
135
+ }
136
+ const next = { ...sel, directives: [...sel.directives ?? [], directive] };
137
+ return next;
138
+ }
139
+ function include(sel, cond) {
140
+ return applyDirective(sel, "include", cond);
141
+ }
142
+ function skip(sel, cond) {
143
+ return applyDirective(sel, "skip", cond);
144
+ }
145
+
146
+ // src/runtime/fragment.ts
147
+ function makeFragment(typeCondition, fields) {
148
+ return (name, pick) => ({ name, typeCondition, sels: pick(fields) });
149
+ }
150
+ function spread(f) {
151
+ return { kind: "spread", fragment: f };
152
+ }
153
+ function collectFragments(sels) {
154
+ const found = /* @__PURE__ */ new Map();
155
+ const walk = (nodes) => {
156
+ for (const n of nodes) {
157
+ if (n.kind === "spread") {
158
+ const seen = found.get(n.fragment.name);
159
+ if (seen && seen !== n.fragment) {
160
+ throw new Error(
161
+ `buildgql: two different fragments are both named "${n.fragment.name}". Fragment names must be unique \u2014 give one of them a different name.`
162
+ );
163
+ }
164
+ if (!seen) {
165
+ found.set(n.fragment.name, n.fragment);
166
+ walk(n.fragment.sels);
167
+ }
168
+ continue;
169
+ }
170
+ if (n.kind === "on") {
171
+ walk(n.sels);
172
+ continue;
173
+ }
174
+ const sel = n;
175
+ if (sel.sels) walk(sel.sels);
176
+ }
177
+ };
178
+ walk(sels);
179
+ return [...found.values()];
180
+ }
181
+
182
+ // src/runtime/on.ts
183
+ function on(typename, fields, pick) {
184
+ return { kind: "on", typename, sels: pick(fields) };
185
+ }
186
+
187
+ // src/runtime/print.ts
188
+ function printValue(value) {
189
+ if (isVarRefValue(value)) return `$${value[VAR_REF]}`;
190
+ if (value === null || value === void 0) return "null";
191
+ if (isEnumValue(value)) return value[ENUM];
192
+ if (typeof value === "string") return JSON.stringify(value);
193
+ if (typeof value === "number" || typeof value === "boolean") return String(value);
194
+ if (Array.isArray(value)) return `[${value.map(printValue).join(", ")}]`;
195
+ if (typeof value === "object") {
196
+ const entries = Object.entries(value).filter(([, v2]) => v2 !== void 0).map(([k, v2]) => `${k}: ${printValue(v2)}`);
197
+ return `{${entries.join(", ")}}`;
198
+ }
199
+ throw new Error(`buildgql: cannot serialise argument value of type ${typeof value}`);
200
+ }
201
+ function printArgs(argv) {
202
+ if (!argv) return "";
203
+ const entries = Object.entries(argv).filter(([, v2]) => v2 !== void 0);
204
+ if (entries.length === 0) return "";
205
+ return `(${entries.map(([k, v2]) => `${k}: ${printValue(v2)}`).join(", ")})`;
206
+ }
207
+ function printDirectives(ds) {
208
+ if (!ds || ds.length === 0) return "";
209
+ return ds.map((d) => {
210
+ const cond = typeof d.if === "boolean" ? String(d.if) : `$${d.if.varName}`;
211
+ return ` @${d.name}(if: ${cond})`;
212
+ }).join("");
213
+ }
214
+ function printNode(n) {
215
+ if (n.kind === "spread") return `...${n.fragment.name}`;
216
+ if (n.kind === "on") {
217
+ const o = n;
218
+ return `... on ${o.typename} ${printSels(o.sels)}`;
219
+ }
220
+ const s = n;
221
+ const head = s.alias ? `${s.alias}: ${s.name}` : s.name;
222
+ const body = s.sels && s.sels.length > 0 ? ` ${printSels(s.sels)}` : "";
223
+ return `${head}${printArgs(s.args)}${printDirectives(s.directives)}${body}`;
224
+ }
225
+ function printSels(sels) {
226
+ const hasInline = sels.some((n) => n.kind === "on");
227
+ const hasTypename = sels.some((n) => n.kind === "field" && n.name === "__typename");
228
+ const parts = sels.map(printNode);
229
+ if (hasInline && !hasTypename) parts.unshift("__typename");
230
+ return `{ ${parts.join(" ")} }`;
231
+ }
232
+ function collectVarRefs(sels) {
233
+ const out = [];
234
+ const walk = (nodes) => {
235
+ for (const n of nodes) {
236
+ if (n.kind === "on") {
237
+ walk(n.sels);
238
+ continue;
239
+ }
240
+ if (n.kind === "spread") {
241
+ walk(n.fragment.sels);
242
+ continue;
243
+ }
244
+ const s = n;
245
+ if (s.varRefs) out.push(...s.varRefs);
246
+ for (const d of s.directives ?? []) {
247
+ if (typeof d.if !== "boolean") out.push(d.if);
248
+ }
249
+ if (s.sels) walk(s.sels);
250
+ }
251
+ };
252
+ walk(sels);
253
+ return out;
254
+ }
255
+ function dedupeVarRefs(refs) {
256
+ const byName = /* @__PURE__ */ new Map();
257
+ for (const ref of refs) {
258
+ const seen = byName.get(ref.varName);
259
+ if (seen && seen.gqlType !== ref.gqlType) {
260
+ throw new Error(
261
+ `buildgql: variable $${ref.varName} is used with two different types (${seen.gqlType} and ${ref.gqlType}). Give one of them an explicit name with v('otherName').`
262
+ );
263
+ }
264
+ if (!seen) byName.set(ref.varName, ref);
265
+ }
266
+ return [...byName.values()];
267
+ }
268
+ function printOperation(kind, name, sels, fragments = []) {
269
+ const vars = dedupeVarRefs(collectVarRefs(sels));
270
+ const sig = vars.length > 0 ? `(${vars.map((v2) => `$${v2.varName}: ${v2.gqlType}`).join(", ")})` : "";
271
+ const op = `${kind} ${name}${sig} ${printSels(sels)}`;
272
+ const frags = fragments.map((f) => `fragment ${f.name} on ${f.typeCondition} ${printSels(f.sels)}`);
273
+ return [op, ...frags].join(" ");
274
+ }
275
+
276
+ // src/runtime/operation.ts
277
+ function makeOperation(kind) {
278
+ return (root) => (name, build) => {
279
+ const sels = build($, root);
280
+ const document = printOperation(kind, name, sels, collectFragments(sels));
281
+ return { kind, name, document, sels };
282
+ };
283
+ }
284
+ var makeQuery = makeOperation("query");
285
+ var makeMutation = makeOperation("mutation");
286
+ var makeSubscription = makeOperation("subscription");
287
+
288
+ // src/index.ts
289
+ var VERSION = "0.1.0";
290
+ export {
291
+ $,
292
+ BuildGQLError,
293
+ BuildGQLHttpError,
294
+ BuildGQLResponseError,
295
+ VERSION,
296
+ argSpec,
297
+ createClient,
298
+ include,
299
+ leafField,
300
+ leafFieldArgs,
301
+ makeFragment,
302
+ makeMutation,
303
+ makeQuery,
304
+ makeSubscription,
305
+ objectField,
306
+ objectFieldArgs,
307
+ on,
308
+ skip,
309
+ spread,
310
+ sseTransport,
311
+ v,
312
+ wsTransport
313
+ };
@@ -0,0 +1,200 @@
1
+ /** Phantom carrier for a selection's *result key* (field name or alias). */
2
+ declare const KEY: unique symbol;
3
+ /** Phantom carrier for a selection's inferred result type. */
4
+ declare const RESULT: unique symbol;
5
+ /** Phantom carrier for the variables a selection contributes. */
6
+ declare const VARS: unique symbol;
7
+
8
+ /** A variable reference recorded at build time, used to emit `$name: Type!`. */
9
+ interface VarRef {
10
+ readonly varName: string;
11
+ readonly gqlType: string;
12
+ }
13
+ /** An `@include`/`@skip` directive attached to a field selection. */
14
+ interface Directive {
15
+ readonly name: 'include' | 'skip';
16
+ /** Either a literal boolean or a variable reference. */
17
+ readonly if: boolean | VarRef;
18
+ }
19
+ /**
20
+ * A selected field.
21
+ * `N` is the key it lands under in the result. It is carried by the phantom
22
+ * `[KEY]` property — it MUST appear structurally, or `Extract`/`Exclude` cannot
23
+ * tell two selections apart and the whole remap collapses.
24
+ * `O` marks the field optional in the result (set by `@include`/`@skip`).
25
+ */
26
+ interface FieldSelection<N extends string, R, V = {}, O extends boolean = false> {
27
+ readonly kind: 'field';
28
+ readonly name: string;
29
+ readonly alias?: string;
30
+ readonly args?: Record<string, unknown>;
31
+ readonly sels?: readonly SelectionNode[];
32
+ readonly directives?: readonly Directive[];
33
+ readonly varRefs?: readonly VarRef[];
34
+ readonly [KEY]?: N;
35
+ readonly [RESULT]?: R;
36
+ readonly [VARS]?: V;
37
+ readonly __optional?: O;
38
+ }
39
+ /**
40
+ * The part of a fragment a spread needs to carry: enough to emit the definition
41
+ * and to walk into it for variables. Declared here rather than in
42
+ * `src/runtime/fragment.ts` so `print.ts` and `fragment.ts` share one contract
43
+ * instead of each re-declaring the shape behind a cast.
44
+ */
45
+ interface FragmentDefinition {
46
+ readonly name: string;
47
+ readonly typeCondition: string;
48
+ readonly sels: readonly SelectionNode[];
49
+ }
50
+ /** A fragment spread. Required `kind` discriminant makes Extract/Exclude work. */
51
+ interface FragmentSpread<R, V = {}> {
52
+ readonly kind: 'spread';
53
+ /**
54
+ * The fragment being spread. Consumed by `collectFragments` and the variable walk
55
+ * in `print.ts`. Its `name` is the single source of truth for the fragment's printed
56
+ * name — there is deliberately no separate `fragmentName` field to keep in sync.
57
+ */
58
+ readonly fragment: FragmentDefinition;
59
+ readonly [RESULT]?: R;
60
+ readonly [VARS]?: V;
61
+ }
62
+ /** An inline fragment (`... on Dog { ... }`). */
63
+ interface InlineFragment<TN extends string, R, V = {}> {
64
+ readonly kind: 'on';
65
+ readonly typename: string;
66
+ readonly sels: readonly SelectionNode[];
67
+ readonly [KEY]?: TN;
68
+ readonly [RESULT]?: R;
69
+ readonly [VARS]?: V;
70
+ }
71
+ type AnyFieldSelection = FieldSelection<string, unknown, unknown, boolean>;
72
+ type SelectionNode = AnyFieldSelection | FragmentSpread<unknown, unknown> | InlineFragment<string, unknown, unknown>;
73
+
74
+ /** Flattens intersections so hovers and errors show one object, not `A & B & C`. */
75
+ type Simplify<T> = {
76
+ [K in keyof T]: T[K];
77
+ } & {};
78
+ /**
79
+ * Intersects a union. The `[U] extends [never]` guard is load-bearing: the bare
80
+ * idiom maps `never` to `unknown`, which silently leaks into every derived type
81
+ * built on it (`VarsIn<[]>`, `VarsOf<{}, Spec>`, `SpreadFields<[]>`) and violates
82
+ * the "no derived type resolves to unknown" constraint. Empty union -> `{}`.
83
+ */
84
+ type UnionToIntersection<U> = [U] extends [never] ? {} : (U extends unknown ? (k: U) => void : never) extends (k: infer I) => void ? I : never;
85
+ /** Strips `null` from a union. Distributes, so `NonNull<A | null>` is `A`. */
86
+ type NonNull<T> = T extends null ? never : T;
87
+ /** Keys of `V` that are not optional. */
88
+ type RequiredKeys<V> = {
89
+ [K in keyof V]-?: {} extends Pick<V, K> ? never : K;
90
+ }[keyof V];
91
+
92
+ type KeyOf<E> = E extends FieldSelection<infer N, unknown, unknown, boolean> ? N : never;
93
+ type ResOf<E> = E extends FieldSelection<string, infer R, unknown, boolean> ? R : never;
94
+ type RequiredSels<S extends readonly SelectionNode[]> = Extract<S[number], FieldSelection<string, unknown, unknown, false>>;
95
+ type OptionalSels<S extends readonly SelectionNode[]> = Extract<S[number], FieldSelection<string, unknown, unknown, true>>;
96
+ type PlainFields<S extends readonly SelectionNode[]> = {
97
+ [E in RequiredSels<S> as KeyOf<E>]: ResOf<E>;
98
+ } & {
99
+ [E in OptionalSels<S> as KeyOf<E>]?: ResOf<E>;
100
+ };
101
+ /**
102
+ * Fragment spreads merge into the parent object.
103
+ * Written in the distributive `S[number] extends infer E` form on purpose:
104
+ * `Extract<S[number], FragmentSpread<unknown, unknown>> extends FragmentSpread<infer R, unknown>` is NOT a
105
+ * naked type parameter, so it collapses the union instead of mapping over it.
106
+ */
107
+ type SpreadFields<S extends readonly SelectionNode[]> = UnionToIntersection<S[number] extends infer E ? (E extends FragmentSpread<infer R, unknown> ? R : {}) : never>;
108
+ /** The union of inline-fragment branches, or `never` when there are none. */
109
+ type OnBranches<S extends readonly SelectionNode[]> = S[number] extends infer E ? E extends InlineFragment<string, infer R, unknown> ? R : never : never;
110
+ /**
111
+ * Assemble a selection tuple into its result type.
112
+ * With no inline fragments this is just the field map. With inline fragments the
113
+ * common fields are distributed across every branch, producing a discriminated
114
+ * union that narrows on `__typename`.
115
+ */
116
+ type Selected<S extends readonly SelectionNode[]> = [OnBranches<S>] extends [never] ? Simplify<PlainFields<S> & SpreadFields<S>> : Simplify<PlainFields<S> & SpreadFields<S>> extends infer Common ? OnBranches<S> extends infer B ? B extends unknown ? Simplify<Common & B> : never : never : never;
117
+ /**
118
+ * Union of every variable map contributed anywhere in a selection tuple.
119
+ */
120
+ type VarsIn<S extends readonly SelectionNode[]> = UnionToIntersection<{
121
+ [I in keyof S]: S[I] extends {
122
+ readonly [VARS]?: infer V;
123
+ } ? (V extends undefined ? {} : V) : {};
124
+ }[number]>;
125
+
126
+ /**
127
+ * A placeholder standing in for a GraphQL variable.
128
+ * `N` is only populated by the explicit `v('name')` helper; the `$` proxy
129
+ * produces `VarMarker<string>` because a mapped type over `string` cannot
130
+ * preserve the accessed key.
131
+ */
132
+ interface VarMarker<N extends string = string> {
133
+ readonly __var: N;
134
+ }
135
+ /** Any argument slot accepts a literal value or a variable placeholder. */
136
+ type Arg<T> = T | VarMarker;
137
+ type ArgsInput<Spec> = {
138
+ [K in keyof Spec]: Arg<Spec[K]>;
139
+ };
140
+ /**
141
+ * Carries a field's argument types at the type level and their GraphQL type
142
+ * strings at runtime (needed to print `$name: String!`).
143
+ */
144
+ interface ArgSpec<T> {
145
+ readonly gql: Readonly<Record<string, string>>;
146
+ /** Arg keys whose base type is an enum — their literals must print unquoted. */
147
+ readonly enums?: readonly string[];
148
+ readonly __t?: T;
149
+ }
150
+ type IsOpt<Spec, K> = K extends keyof Spec ? ({} extends Pick<Spec, K> ? true : false) : false;
151
+ type VarEntry<N extends string, T, O extends boolean> = O extends true ? {
152
+ [P in N]?: T;
153
+ } : {
154
+ [P in N]: T;
155
+ };
156
+ /**
157
+ * Derive the variable map from the args the user wrote.
158
+ * Name comes from the arg key (or the explicit `v()` name); type comes from the
159
+ * codegen-supplied `Spec`. Optional args yield optional variables.
160
+ */
161
+ type VarsOf<A, Spec> = UnionToIntersection<{
162
+ [K in keyof A]: A[K] extends VarMarker<infer N> ? string extends N ? VarEntry<K & string, K extends keyof Spec ? Spec[K] : never, IsOpt<Spec, K>> : VarEntry<N, K extends keyof Spec ? Spec[K] : never, IsOpt<Spec, K>> : {};
163
+ }[keyof A]>;
164
+ /**
165
+ * The `$` object handed to operation builders.
166
+ * Deliberately NOT callable: a callable type would resolve `$.name`, `$.length`,
167
+ * `$.call`, `$.apply` and `$.bind` to `Function`'s own members, silently turning
168
+ * those variables into plain strings. Explicit naming lives in `v()` instead.
169
+ */
170
+ type VarProxy = {
171
+ readonly [K in string]: VarMarker;
172
+ };
173
+ /**
174
+ * True when the operation declared at least one REQUIRED variable — an all-optional
175
+ * variable map (e.g. `{ after?: string }`) must not force a positional `vars` argument.
176
+ */
177
+ type HasVars<V> = RequiredKeys<V> extends never ? false : true;
178
+ /**
179
+ * The trailing parameter list carrying an operation's variables, and nothing else.
180
+ * `NoInfer` stops `V` being re-inferred from the argument, which would otherwise let a
181
+ * pre-declared object with missing keys through silently.
182
+ *
183
+ * `client.execute`/`client.subscribe` need a second `ExecuteOptions` slot as well, so they
184
+ * build their own tuple from `HasVars` rather than using this alias — see `create-client.ts`.
185
+ */
186
+ type VarsArg<V> = HasVars<V> extends true ? [vars: NoInfer<V>] : [vars?: NoInfer<V>];
187
+
188
+ interface Operation<R, V> {
189
+ readonly kind: 'query' | 'mutation' | 'subscription';
190
+ readonly name: string;
191
+ readonly document: string;
192
+ readonly sels: readonly SelectionNode[];
193
+ readonly [RESULT]?: R;
194
+ readonly [VARS]?: V;
195
+ }
196
+ declare const makeQuery: <Root>(root: Root) => <S extends readonly SelectionNode[]>(name: string, build: (v: VarProxy, r: Root) => readonly [...S]) => Operation<Selected<S>, Simplify<VarsIn<S>>>;
197
+ declare const makeMutation: <Root>(root: Root) => <S extends readonly SelectionNode[]>(name: string, build: (v: VarProxy, r: Root) => readonly [...S]) => Operation<Selected<S>, Simplify<VarsIn<S>>>;
198
+ declare const makeSubscription: <Root>(root: Root) => <S extends readonly SelectionNode[]>(name: string, build: (v: VarProxy, r: Root) => readonly [...S]) => Operation<Selected<S>, Simplify<VarsIn<S>>>;
199
+
200
+ export { type ArgSpec as A, type Directive as D, type FieldSelection as F, type HasVars as H, type InlineFragment as I, KEY as K, type NonNull as N, type Operation as O, RESULT as R, type SelectionNode as S, type UnionToIntersection as U, type VarsArg as V, type ArgsInput as a, type VarsOf as b, type Selected as c, type VarsIn as d, type VarMarker as e, type FragmentDefinition as f, VARS as g, type FragmentSpread as h, type Simplify as i, type VarProxy as j, type AnyFieldSelection as k, type Arg as l, type VarRef as m, makeMutation as n, makeQuery as o, makeSubscription as p };