gqls-cli 0.11.0

Fuzzy and semantic search over a GraphQL schema (SDL, introspection JSON, or a live endpoint), plus a field-to-resolver jump.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
//! Draft a ready-to-paste example operation for a matched field.
//!
//! Everything here is mechanical — the schema already says what the arguments
//! are, what the field returns, and which of that type's fields are leaves. The
//! rules, and why each one:
//!
//! * **Arguments always become variables.** Never inline a literal into the
//!   query body; a pasted operation should be parameterized from the start.
//! * **One level of selection, leaves only.** A scalar or enum return needs no
//!   selection set at all. An object return gets its scalar/enum fields, and a
//!   `# add fields you need` marker for the object-valued ones — guessing how
//!   deep someone wants to go is worse than leaving a hole.
//! * **An `errors` block only when the schema has one.** The payload/errors
//!   convention is widespread but not universal, so it's expanded only when
//!   that field really exists.
//! * **A nested field is reached through a root.** `Company.employee` isn't
//!   callable on its own, so it's wrapped in a root field that returns
//!   `Company`. When several roots qualify, the caller is told, rather than the
//!   pick being passed off as obvious.

use std::collections::HashMap;

use anyhow::{bail, Result};
use serde_json::{Map, Value};

use crate::model::{Kind, SchemaRecord};

/// A drafted operation and the variables it expects.
#[derive(Debug)]
pub struct Example {
    /// The GraphQL document, ready to paste.
    pub operation: String,
    /// A JSON object of placeholder variable values.
    pub variables: Value,
    /// The root field a nested target was reached through, if it needed one.
    pub via: Option<String>,
    /// Other root fields that could have reached a nested target. Non-empty
    /// only when the choice was ambiguous.
    pub alternatives: Vec<String>,
}

/// Draft an operation that reaches `target`.
pub fn build(target: &SchemaRecord, records: &[SchemaRecord]) -> Result<Example> {
    let schema = Schema::index(records);

    // The chain of fields to nest, outermost first. A root operation field is
    // already reachable; anything else needs a root that returns its parent.
    let (chain, via, alternatives) = match target.kind {
        Kind::Query | Kind::Mutation | Kind::Subscription => (vec![target], None, Vec::new()),
        Kind::Field => {
            let parent = target
                .parent
                .as_deref()
                .ok_or_else(|| anyhow::anyhow!("{} has no enclosing type", target.path))?;
            let mut roots = schema.roots_returning(parent);
            if roots.is_empty() {
                bail!(
                    "{} isn't reachable in one hop — no root field returns {parent}. \
                     Try `gqls --returns {parent}` to see what's close.",
                    target.path
                );
            }
            let chosen = roots.remove(0);
            let via = Some(chosen.path.clone());
            let alternatives = roots.iter().map(|r| r.path.clone()).collect();
            (vec![chosen, target], via, alternatives)
        }
        other => bail!(
            "can't draft an operation for a {} — pick a field, query, or mutation",
            other.as_str()
        ),
    };

    let operation_kind = match chain[0].kind {
        Kind::Mutation => "mutation",
        Kind::Subscription => "subscription",
        _ => "query",
    };

    // Variables first: every argument along the chain, deduped so a repeated
    // name (two `id`s) doesn't collide in the signature.
    let vars = Variables::collect(&chain);

    // Then the selection, innermost outward.
    let leaf_type = chain
        .last()
        .and_then(|r| r.base_type())
        .unwrap_or_default()
        .to_string();
    let mut body = schema.selection(&leaf_type);

    for (depth, field) in chain.iter().enumerate().rev() {
        let args = vars.rendered_for(depth);
        body = if body.is_empty() {
            // A leaf-returning field takes no selection set at all.
            vec![format!("{}{}", field.name, args)]
        } else {
            let mut wrapped = vec![format!("{}{} {{", field.name, args)];
            wrapped.extend(body.into_iter().map(|l| format!("  {l}")));
            wrapped.push("}".to_string());
            wrapped
        };
    }

    let mut operation = String::new();
    operation.push_str(operation_kind);
    operation.push(' ');
    operation.push_str(&pascal_case(&chain.last().unwrap().name));
    operation.push_str(&vars.signature());
    operation.push_str(" {\n");
    for line in &body {
        operation.push_str("  ");
        operation.push_str(line);
        operation.push('\n');
    }
    operation.push_str("}\n");

    Ok(Example {
        operation,
        variables: vars.placeholders(&schema),
        via,
        alternatives,
    })
}

/// Records indexed the two ways drafting needs: what kind a type name is, and
/// what fields a type has.
struct Schema<'a> {
    kinds: HashMap<&'a str, Kind>,
    fields: HashMap<&'a str, Vec<&'a SchemaRecord>>,
    roots: Vec<&'a SchemaRecord>,
}

impl<'a> Schema<'a> {
    fn index(records: &'a [SchemaRecord]) -> Self {
        let mut kinds = HashMap::new();
        let mut fields: HashMap<&str, Vec<&SchemaRecord>> = HashMap::new();
        let mut roots = Vec::new();
        for r in records {
            match r.kind {
                Kind::Query | Kind::Mutation | Kind::Subscription => {
                    roots.push(r);
                    if let Some(p) = r.parent.as_deref() {
                        fields.entry(p).or_default().push(r);
                    }
                }
                Kind::Field | Kind::InputField | Kind::EnumValue => {
                    if let Some(p) = r.parent.as_deref() {
                        fields.entry(p).or_default().push(r);
                    }
                }
                _ => {
                    kinds.insert(r.name.as_str(), r.kind);
                }
            }
        }
        Self {
            kinds,
            fields,
            roots,
        }
    }

    /// Root operation fields returning `type_name`, best first. Fewest required
    /// arguments wins: `viewer` is a friendlier entry point than `node(id:)`,
    /// which needs one you may not have yet.
    fn roots_returning(&self, type_name: &str) -> Vec<&'a SchemaRecord> {
        let mut hits: Vec<&SchemaRecord> = self
            .roots
            .iter()
            .copied()
            .filter(|r| {
                r.base_type()
                    .is_some_and(|t| t.eq_ignore_ascii_case(type_name))
            })
            .collect();
        hits.sort_by_key(|r| (required_args(r), r.path.len(), r.path.clone()));
        hits
    }

    /// Whether a type needs no selection set — a scalar, an enum, or a name
    /// the schema never defines (the built-in scalars, which SDL omits).
    fn is_leaf(&self, type_name: &str) -> bool {
        !matches!(
            self.kinds.get(type_name),
            Some(Kind::Object | Kind::Interface | Kind::Union | Kind::InputObject)
        )
    }

    /// The selection set for `type_name`: its leaf fields, plus a marker for
    /// each object-valued field so the hole is visible. Empty for a leaf type.
    fn selection(&self, type_name: &str) -> Vec<String> {
        if type_name.is_empty() || self.is_leaf(type_name) {
            return Vec::new();
        }
        let mut lines = Vec::new();
        let mut deferred = Vec::new();
        for f in self.fields.get(type_name).into_iter().flatten() {
            if f.kind != Kind::Field {
                continue;
            }
            let Some(base) = f.base_type() else { continue };
            if self.is_leaf(base) {
                // A field with required arguments can't be selected bare.
                if f.args.iter().any(|a| a.trim_end().ends_with('!')) {
                    deferred.push(format!("# {}: {} — needs arguments", f.name, base));
                } else {
                    lines.push(f.name.clone());
                }
            } else if f.name.eq_ignore_ascii_case("errors") {
                // The payload/errors convention, expanded only because this
                // schema really has the field.
                let inner = self.selection(base);
                lines.push(format!("{} {{", f.name));
                lines.extend(inner.into_iter().map(|l| format!("  {l}")));
                lines.push("}".to_string());
            } else {
                deferred.push(format!("# {}: {} — add fields you need", f.name, base));
            }
        }
        lines.extend(deferred);
        if lines.is_empty() {
            // A union (no fields of its own), or a type this schema doesn't
            // detail. `__typename` is always valid and keeps the query runnable.
            lines.push("__typename".to_string());
            lines.push("# add inline fragments: ... on ConcreteType { … }".to_string());
        }
        lines
    }

    /// A JSON placeholder for a variable of this type.
    fn placeholder(&self, type_ref: &str) -> Value {
        let type_ref = type_ref.trim();
        // An optional argument stays null — present so the knob is visible,
        // unset because a made-up default would be a silent decision.
        if !type_ref.ends_with('!') {
            return Value::Null;
        }
        if type_ref.starts_with('[') {
            return Value::Array(Vec::new());
        }
        let base = type_ref.trim_matches(|c| matches!(c, '[' | ']' | '!' | ' '));
        match base {
            "ID" | "String" => Value::String(String::new()),
            "Int" => Value::Number(0.into()),
            "Float" => serde_json::json!(0.0),
            "Boolean" => Value::Bool(false),
            _ => match self.kinds.get(base) {
                // An enum's first value is a real, valid choice.
                Some(Kind::Enum) => self
                    .fields
                    .get(base)
                    .and_then(|vs| vs.first())
                    .map(|v| Value::String(v.name.clone()))
                    .unwrap_or(Value::Null),
                Some(Kind::InputObject) => Value::Object(Map::new()),
                _ => Value::Null,
            },
        }
    }
}

/// The operation's variables: one per argument along the field chain.
struct Variables {
    /// `(depth, arg name, variable name, type)`
    entries: Vec<(usize, String, String, String)>,
}

impl Variables {
    fn collect(chain: &[&SchemaRecord]) -> Self {
        let mut entries: Vec<(usize, String, String, String)> = Vec::new();
        for (depth, field) in chain.iter().enumerate() {
            for arg in &field.args {
                let (name, type_ref) = split_arg(arg);
                // Disambiguate a name already taken by an outer field's arg.
                let taken = entries.iter().any(|(_, _, var, _)| var == name);
                let var = if taken {
                    format!("{}{}", field.name, pascal_case(name))
                } else {
                    name.to_string()
                };
                entries.push((depth, name.to_string(), var, type_ref.to_string()));
            }
        }
        Self { entries }
    }

    /// `($id: ID!, $first: Int)`, or empty when there are no arguments.
    fn signature(&self) -> String {
        if self.entries.is_empty() {
            return String::new();
        }
        let inner: Vec<String> = self
            .entries
            .iter()
            .map(|(_, _, var, ty)| format!("${var}: {ty}"))
            .collect();
        format!("({})", inner.join(", "))
    }

    /// `(id: $id, first: $first)` for the field at `depth`, or empty.
    fn rendered_for(&self, depth: usize) -> String {
        let inner: Vec<String> = self
            .entries
            .iter()
            .filter(|(d, _, _, _)| *d == depth)
            .map(|(_, name, var, _)| format!("{name}: ${var}"))
            .collect();
        if inner.is_empty() {
            String::new()
        } else {
            format!("({})", inner.join(", "))
        }
    }

    fn placeholders(&self, schema: &Schema) -> Value {
        let mut map = Map::new();
        for (_, _, var, ty) in &self.entries {
            map.insert(var.clone(), schema.placeholder(ty));
        }
        Value::Object(map)
    }
}

/// How many of a field's arguments are non-null, and so must be supplied.
fn required_args(r: &SchemaRecord) -> usize {
    r.args
        .iter()
        .filter(|a| split_arg(a).1.ends_with('!'))
        .count()
}

/// `"first: Int = 10"` → `("first", "Int")`. gqls renders args as `name: Type`;
/// a default value, if one ever survives parsing, isn't part of the type.
fn split_arg(arg: &str) -> (&str, &str) {
    let (name, rest) = arg.split_once(':').unwrap_or((arg, ""));
    let type_ref = rest.split('=').next().unwrap_or(rest);
    (name.trim(), type_ref.trim())
}

/// `updateEmployee` → `UpdateEmployee`, for the operation name.
fn pascal_case(name: &str) -> String {
    let mut chars = name.chars();
    match chars.next() {
        Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
        None => String::new(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn rec(
        path: &str,
        name: &str,
        kind: Kind,
        parent: Option<&str>,
        type_ref: Option<&str>,
        args: &[&str],
    ) -> SchemaRecord {
        SchemaRecord {
            path: path.into(),
            name: name.into(),
            kind,
            parent: parent.map(Into::into),
            type_ref: type_ref.map(Into::into),
            args: args.iter().map(|a| a.to_string()).collect(),
            description: None,
            deprecated: None,
            directives: vec![],
        }
    }

    /// Query.user(id) -> User { id name role posts(Post) }, plus a mutation
    /// whose payload carries an errors block.
    fn schema() -> Vec<SchemaRecord> {
        vec![
            rec("Query", "Query", Kind::Object, None, None, &[]),
            rec("User", "User", Kind::Object, None, None, &[]),
            rec("Post", "Post", Kind::Object, None, None, &[]),
            rec("Role", "Role", Kind::Enum, None, None, &[]),
            rec("Payload", "Payload", Kind::Object, None, None, &[]),
            rec("UserError", "UserError", Kind::Object, None, None, &[]),
            rec("Input", "Input", Kind::InputObject, None, None, &[]),
            rec(
                "Query.user",
                "user",
                Kind::Query,
                Some("Query"),
                Some("User"),
                &["id: ID!"],
            ),
            rec(
                "Query.count",
                "count",
                Kind::Query,
                Some("Query"),
                Some("Int!"),
                &[],
            ),
            rec("User.id", "id", Kind::Field, Some("User"), Some("ID!"), &[]),
            rec(
                "User.name",
                "name",
                Kind::Field,
                Some("User"),
                Some("String"),
                &[],
            ),
            rec(
                "User.role",
                "role",
                Kind::Field,
                Some("User"),
                Some("Role!"),
                &[],
            ),
            rec(
                "User.posts",
                "posts",
                Kind::Field,
                Some("User"),
                Some("[Post!]!"),
                &[],
            ),
            rec(
                "User.avatar",
                "avatar",
                Kind::Field,
                Some("User"),
                Some("String"),
                &["size: Int!"],
            ),
            rec(
                "Mutation.save",
                "save",
                Kind::Mutation,
                Some("Mutation"),
                Some("Payload!"),
                &["input: Input!", "dryRun: Boolean"],
            ),
            rec(
                "Payload.ok",
                "ok",
                Kind::Field,
                Some("Payload"),
                Some("Boolean!"),
                &[],
            ),
            rec(
                "Payload.errors",
                "errors",
                Kind::Field,
                Some("Payload"),
                Some("[UserError!]!"),
                &[],
            ),
            rec(
                "UserError.message",
                "message",
                Kind::Field,
                Some("UserError"),
                Some("String!"),
                &[],
            ),
            rec(
                "Role.ADMIN",
                "ADMIN",
                Kind::EnumValue,
                Some("Role"),
                None,
                &[],
            ),
        ]
    }

    fn build_for(path: &str) -> Example {
        let records = schema();
        let target = records.iter().find(|r| r.path == path).unwrap();
        build(target, &records).unwrap()
    }

    #[test]
    fn root_field_becomes_a_parameterized_query() {
        let ex = build_for("Query.user");
        assert_eq!(
            ex.operation,
            "query User($id: ID!) {\n  \
               user(id: $id) {\n    \
                 id\n    \
                 name\n    \
                 role\n    \
                 # posts: Post — add fields you need\n    \
                 # avatar: String — needs arguments\n  \
               }\n\
             }\n"
        );
        assert_eq!(ex.variables, serde_json::json!({ "id": "" }));
    }

    #[test]
    fn a_scalar_return_gets_no_selection_set() {
        let ex = build_for("Query.count");
        assert_eq!(ex.operation, "query Count {\n  count\n}\n");
        assert_eq!(ex.variables, serde_json::json!({}));
    }

    #[test]
    fn mutation_expands_a_real_errors_block() {
        let ex = build_for("Mutation.save");
        assert!(ex.operation.starts_with(
            "mutation Save($input: Input!, $dryRun: Boolean) {\n  save(input: $input, dryRun: $dryRun) {"
        ), "{}", ex.operation);
        assert!(
            ex.operation.contains("errors {\n      message\n    }"),
            "{}",
            ex.operation
        );
        // an optional arg is null; a required input object is an empty object
        assert_eq!(
            ex.variables,
            serde_json::json!({ "input": {}, "dryRun": null })
        );
    }

    #[test]
    fn nested_field_is_wrapped_in_a_root_that_returns_its_type() {
        let ex = build_for("User.posts");
        // User.posts isn't callable directly; Query.user returns a User
        assert_eq!(
            ex.operation,
            "query Posts($id: ID!) {\n  \
               user(id: $id) {\n    \
                 posts {\n      \
                   __typename\n      \
                   # add inline fragments: ... on ConcreteType { … }\n    \
                 }\n  \
               }\n\
             }\n"
        );
    }

    #[test]
    fn an_unreachable_field_is_an_error_not_a_guess() {
        let mut records = schema();
        // nothing returns UserError, so UserError.message can't be reached
        let target = records
            .iter()
            .position(|r| r.path == "UserError.message")
            .unwrap();
        let target = records.remove(target);
        let err = build(&target, &records).unwrap_err().to_string();
        assert!(err.contains("no root field returns UserError"), "{err}");
    }

    #[test]
    fn ambiguous_roots_are_reported_rather_than_hidden() {
        let mut records = schema();
        records.push(rec(
            "Query.viewer",
            "viewer",
            Kind::Query,
            Some("Query"),
            Some("User"),
            &[],
        ));
        let target = records.iter().find(|r| r.path == "User.name").unwrap();
        let ex = build(target, &records).unwrap();
        // both Query.user and Query.viewer return User
        assert_eq!(ex.alternatives.len(), 1);
    }

    /// The point of the whole module: what it prints must parse as GraphQL.
    #[test]
    fn every_drafted_operation_is_valid_graphql() {
        for path in [
            "Query.user",
            "Query.count",
            "Mutation.save",
            "User.posts",
            "User.name",
        ] {
            let ex = build_for(path);
            graphql_parser::parse_query::<String>(&ex.operation).unwrap_or_else(|e| {
                panic!("{path} drafted invalid GraphQL: {e}\n{}", ex.operation)
            });
        }
    }

    #[test]
    fn enum_placeholder_uses_a_real_value_and_args_disambiguate() {
        let records = vec![
            rec("Query", "Query", Kind::Object, None, None, &[]),
            rec("Role", "Role", Kind::Enum, None, None, &[]),
            rec(
                "Role.ADMIN",
                "ADMIN",
                Kind::EnumValue,
                Some("Role"),
                None,
                &[],
            ),
            rec("Thing", "Thing", Kind::Object, None, None, &[]),
            rec(
                "Query.thing",
                "thing",
                Kind::Query,
                Some("Query"),
                Some("Thing"),
                &["id: ID!"],
            ),
            rec(
                "Thing.child",
                "child",
                Kind::Field,
                Some("Thing"),
                Some("String"),
                &["id: ID!", "role: Role!"],
            ),
        ];
        let target = records.iter().find(|r| r.path == "Thing.child").unwrap();
        let ex = build(target, &records).unwrap();
        // the inner `id` collides with the root's, so it's prefixed
        assert!(
            ex.operation.contains("child(id: $childId, role: $role)"),
            "{}",
            ex.operation
        );
        assert_eq!(
            ex.variables,
            serde_json::json!({ "id": "", "childId": "", "role": "ADMIN" })
        );
    }
}