@pothos/selection-mapper 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/README.md +16 -6
  3. package/dts/deep-equal.d.ts +4 -0
  4. package/dts/deep-equal.d.ts.map +1 -1
  5. package/dts/errors.d.ts +7 -0
  6. package/dts/errors.d.ts.map +1 -0
  7. package/dts/index.d.ts +3 -2
  8. package/dts/index.d.ts.map +1 -1
  9. package/dts/loader-map.d.ts +37 -16
  10. package/dts/loader-map.d.ts.map +1 -1
  11. package/dts/matches.d.ts +5 -0
  12. package/dts/matches.d.ts.map +1 -1
  13. package/dts/parent-types.d.ts +9 -0
  14. package/dts/parent-types.d.ts.map +1 -0
  15. package/dts/plan.d.ts +36 -20
  16. package/dts/plan.d.ts.map +1 -1
  17. package/dts/shape.d.ts +8 -0
  18. package/dts/shape.d.ts.map +1 -0
  19. package/dts/types.d.ts +21 -1
  20. package/dts/types.d.ts.map +1 -1
  21. package/dts/walk.d.ts +20 -2
  22. package/dts/walk.d.ts.map +1 -1
  23. package/esm/deep-equal.d.ts +4 -0
  24. package/esm/deep-equal.d.ts.map +1 -1
  25. package/esm/deep-equal.js +60 -28
  26. package/esm/deep-equal.js.map +1 -1
  27. package/esm/errors.d.ts +7 -0
  28. package/esm/errors.d.ts.map +1 -0
  29. package/esm/errors.js +11 -0
  30. package/esm/errors.js.map +1 -0
  31. package/esm/index.d.ts +3 -2
  32. package/esm/index.d.ts.map +1 -1
  33. package/esm/index.js +2 -1
  34. package/esm/index.js.map +1 -1
  35. package/esm/loader-map.d.ts +37 -16
  36. package/esm/loader-map.d.ts.map +1 -1
  37. package/esm/loader-map.js +165 -99
  38. package/esm/loader-map.js.map +1 -1
  39. package/esm/matches.d.ts +5 -0
  40. package/esm/matches.d.ts.map +1 -1
  41. package/esm/matches.js +11 -3
  42. package/esm/matches.js.map +1 -1
  43. package/esm/parent-types.d.ts +9 -0
  44. package/esm/parent-types.d.ts.map +1 -0
  45. package/esm/parent-types.js +24 -0
  46. package/esm/parent-types.js.map +1 -0
  47. package/esm/plan.d.ts +36 -20
  48. package/esm/plan.d.ts.map +1 -1
  49. package/esm/plan.js +107 -71
  50. package/esm/plan.js.map +1 -1
  51. package/esm/shape.d.ts +8 -0
  52. package/esm/shape.d.ts.map +1 -0
  53. package/esm/shape.js +94 -0
  54. package/esm/shape.js.map +1 -0
  55. package/esm/types.d.ts +21 -1
  56. package/esm/types.d.ts.map +1 -1
  57. package/esm/types.js.map +1 -1
  58. package/esm/walk.d.ts +20 -2
  59. package/esm/walk.d.ts.map +1 -1
  60. package/esm/walk.js +199 -71
  61. package/esm/walk.js.map +1 -1
  62. package/lib/deep-equal.js +60 -28
  63. package/lib/deep-equal.js.map +1 -1
  64. package/lib/errors.js +18 -0
  65. package/lib/errors.js.map +1 -0
  66. package/lib/index.js +13 -3
  67. package/lib/index.js.map +1 -1
  68. package/lib/loader-map.js +145 -90
  69. package/lib/loader-map.js.map +1 -1
  70. package/lib/matches.js +14 -3
  71. package/lib/matches.js.map +1 -1
  72. package/lib/parent-types.js +29 -0
  73. package/lib/parent-types.js.map +1 -0
  74. package/lib/plan.js +107 -71
  75. package/lib/plan.js.map +1 -1
  76. package/lib/shape.js +109 -0
  77. package/lib/shape.js.map +1 -0
  78. package/lib/walk.js +186 -68
  79. package/lib/walk.js.map +1 -1
  80. package/package.json +4 -3
  81. package/src/deep-equal.ts +77 -34
  82. package/src/errors.ts +12 -0
  83. package/src/index.ts +6 -1
  84. package/src/loader-map.ts +235 -125
  85. package/src/matches.ts +15 -3
  86. package/src/parent-types.ts +33 -0
  87. package/src/plan.ts +145 -78
  88. package/src/shape.ts +126 -0
  89. package/src/types.ts +25 -1
  90. package/src/walk.ts +250 -83
package/src/plan.ts CHANGED
@@ -1,27 +1,26 @@
1
- /**
2
- * One root being planned: the two entry points that build one from a resolver's `info`, the
3
- * merges a traversal collected for it, and the fold that turns those merges into a node.
4
- *
5
- * A plan holds no node — playing it builds one — so the same plan can be played more than once,
6
- * behind a different seed each time. Playing is where a merge is accepted or rejected and the
7
- * only place a mapping is recorded; the traversal decides nothing, so a field that lost to
8
- * another occurrence of itself is still on the list and a play whose seed makes it fit takes it.
9
- */
10
- import { PothosValidationError } from '@pothos/core';
11
1
  import { type GraphQLNamedType, type GraphQLResolveInfo, getNamedType } from 'graphql';
12
2
  import type { Adapter, NodeBase } from './adapter.js';
3
+ import { unexpectedError } from './errors.js';
13
4
  import { type Mapping, type Mappings, setLoaderMappings, unionMappings } from './loader-map.js';
14
5
  import {
15
6
  findMatches,
16
7
  type IndirectPathSegment,
17
8
  includeOf,
9
+ includePaths,
18
10
  matchesForModel,
19
11
  modelOf,
20
12
  type PathSegment,
21
13
  resolveType,
22
14
  } from './matches.js';
23
15
  import type { Node } from './node.js';
24
- import type { EntryOptions, MergeOptions, Position, WalkedType } from './types.js';
16
+ import type {
17
+ EntryOptions,
18
+ MergeOptions,
19
+ ParentRowOptions,
20
+ Position,
21
+ TypeLevelConflict,
22
+ WalkedType,
23
+ } from './types.js';
25
24
  import { type Branch, walkBranches, walkField } from './walk.js';
26
25
 
27
26
  // Shared, since neither carries anything per merge.
@@ -30,8 +29,8 @@ const LENIENT: MergeOptions = Object.freeze({ lenient: true });
30
29
 
31
30
  /**
32
31
  * One merge a traversal collected, in the order it happened: a type's selection, a same-model
33
- * variant's, a nested selection's relation query, or a field's. A play folds the list into a
34
- * node; nothing is merged, accepted or rejected before then.
32
+ * variant's, or a field's. A play folds the list into a node; nothing is merged, accepted or
33
+ * rejected before then.
35
34
  *
36
35
  * A record holds its query by reference, so a select function that mutates the query it returned
37
36
  * after returning it changes what a later play builds — a bug in the select function. Nothing
@@ -40,7 +39,6 @@ const LENIENT: MergeOptions = Object.freeze({ lenient: true });
40
39
  */
41
40
  export type RootMerge<Query> =
42
41
  | { kind: 'type'; query: Query }
43
- | { kind: 'query'; query: Query }
44
42
  | { kind: 'variant'; type: WalkedType; variant: WalkedType; query: Query }
45
43
  | { kind: 'field'; key: string; alias: string; query: Query; mapping: Mapping };
46
44
 
@@ -82,6 +80,21 @@ export class Plan<Model, Query, NodeType extends NodeBase<Model> = Node<Model>>
82
80
  /** The traversal's whole output: every merge it collected, in the order it collected them. */
83
81
  private readonly merges: RootMerge<Query>[] = [];
84
82
 
83
+ /** The plan whose merges a play folds: this one, or a walk shared with other invocations. */
84
+ private walk: Plan<Model, Query, NodeType> = this;
85
+
86
+ /** The relation query of the nested selection this plan was made for, merged ahead of `walk`. */
87
+ private relationQuery?: Query;
88
+
89
+ /** Whether a select function in this walk read the position above its own field. */
90
+ positionRead = false;
91
+
92
+ /**
93
+ * The walks beneath every field of the plans hanging from one root, by `nested`'s `key`. Shared
94
+ * with the plan this one was created from, so the root creates it and every nested plan reads it.
95
+ */
96
+ private readonly walks: Map<string, Plan<Model, Query, NodeType>>;
97
+
85
98
  /**
86
99
  * The play `settle` ran, which a later play takes whole when the seed conflicts with none of
87
100
  * it. Never handed out: a play that reuses it copies it into a node of its own.
@@ -108,11 +121,13 @@ export class Plan<Model, Query, NodeType extends NodeBase<Model> = Node<Model>>
108
121
  let rootType = target;
109
122
  let branches: Branch[];
110
123
 
111
- if (paths?.length || path?.length) {
112
- const includePaths = normalizePaths(paths?.length ? paths : [path!]);
124
+ const entryPaths = includePaths({ path, paths });
125
+
126
+ if (entryPaths) {
127
+ const normalized = normalizePaths(entryPaths);
113
128
  const prefix = includeOf(returnType)?.path;
114
129
  const found = info.fieldNodes.flatMap((fieldNode) =>
115
- findMatches(info, returnType, fieldNode, includePaths, { prefix }),
130
+ findMatches(info, returnType, fieldNode, normalized, { prefix }),
116
131
  );
117
132
 
118
133
  if (found.length === 0) {
@@ -162,15 +177,15 @@ export class Plan<Model, Query, NodeType extends NodeBase<Model> = Node<Model>>
162
177
  * replaces the parent the field resolver sees, so besides the field's own selection it
163
178
  * carries the parent type's type-level selection. The field is what the row is loaded for, so
164
179
  * it is merged first and a type-level relation whose arguments conflict with it is left out.
180
+ * `initial` is merged before anything else.
165
181
  */
166
182
  static forParentRow<Model, Query, NodeType extends NodeBase<Model> = Node<Model>>(
167
183
  adapter: Adapter<Model, Query, NodeType>,
168
- context: object,
169
- info: GraphQLResolveInfo,
170
- skipDeferredFragments?: boolean,
184
+ options: ParentRowOptions<Query>,
171
185
  ): PlayedPlan<Model, Query, NodeType> {
186
+ const { info } = options;
172
187
  const type = info.parentType;
173
- const plan = new Plan(adapter, { context, info, skipDeferredFragments }, type);
188
+ const plan = new Plan(adapter, options, type, undefined, options.initial);
174
189
 
175
190
  try {
176
191
  // Every node selecting the field (one per fragment it appears under) plans into the same
@@ -203,11 +218,12 @@ export class Plan<Model, Query, NodeType extends NodeBase<Model> = Node<Model>>
203
218
  this.context = source.context;
204
219
  this.info = source.info;
205
220
  this.skipDeferredFragments = source.skipDeferredFragments ?? adapter.skipDeferredFragments;
221
+ this.walks = source instanceof Plan ? source.walks : new Map();
206
222
 
207
223
  const model = modelOf(adapter, source.info.schema, type);
208
224
 
209
225
  if (!model) {
210
- throw new PothosValidationError(
226
+ throw unexpectedError(
211
227
  `Expected ${resolveType(source.info.schema, type).name} to have a model`,
212
228
  );
213
229
  }
@@ -218,10 +234,55 @@ export class Plan<Model, Query, NodeType extends NodeBase<Model> = Node<Model>>
218
234
 
219
235
  /**
220
236
  * The plan beneath one nested selection: this plan's adapter, context, info and deferred
221
- * setting, with merges of its own. It hangs beneath the field whose select function made it.
237
+ * setting. It holds the invocation's relation query and plays over a walk of the selection
238
+ * beneath the field, which `walk` collects the first time this plan needs it.
239
+ *
240
+ * One field node is invoked once per type it is reached on in a walk (see `walkField`). A named
241
+ * fragment spread at every level reaches the same selection set beneath several field nodes,
242
+ * which may hang beneath different plans, so a walk per invocation is exponential in the
243
+ * document's depth.
244
+ *
245
+ * What a walk collects depends only on `key`, which names the selection set by its shape (see
246
+ * shape.ts) and holds everything else the walk reads, unless a select function reads the
247
+ * position above it: `positionRead` says it did. Every other invocation with the same key, under
248
+ * any plan from the same root, shares a walk that did not. A walk that is still pending may yet
249
+ * read it, so it is not shared. A walk that throws is not kept, so a select function that catches
250
+ * the failure can retry it.
222
251
  */
223
- nested(type: GraphQLNamedType, position: Position): Plan<Model, Query, NodeType> {
224
- return new Plan(this.adapter, this, type, position);
252
+ nested(
253
+ type: GraphQLNamedType,
254
+ position: Position,
255
+ key: string,
256
+ walk: (plan: Plan<Model, Query, NodeType>) => void,
257
+ ): Plan<Model, Query, NodeType> {
258
+ let walked = this.walks.get(key);
259
+
260
+ if (!walked) {
261
+ const created = new Plan(this.adapter, this, type, position);
262
+
263
+ try {
264
+ walk(created);
265
+ } catch (error) {
266
+ created.abandon();
267
+ throw error;
268
+ }
269
+
270
+ if (!(created.positionRead || created.pending)) {
271
+ this.walks.set(key, created);
272
+ }
273
+
274
+ walked = created;
275
+ }
276
+
277
+ const plan = new Plan(this.adapter, this, type, position);
278
+
279
+ plan.walk = walked;
280
+
281
+ if (walked.pending) {
282
+ plan.chain(walked.pending, noop);
283
+ }
284
+
285
+ return plan;
225
286
  }
226
287
 
227
288
  /** Appends one merge to the list a play folds. The traversal's only way to add to a plan. */
@@ -230,12 +291,12 @@ export class Plan<Model, Query, NodeType extends NodeBase<Model> = Node<Model>>
230
291
  }
231
292
 
232
293
  /**
233
- * The relation query of the nested selection this plan was made for. It takes the head of the
234
- * list, so it is merged before the fields walked beneath it whether the callback that produced
235
- * it answered at once or resolved after the walk. A nested plan has at most one.
294
+ * The relation query of the nested selection this plan was made for. It is merged ahead of the
295
+ * walk, whether the callback that produced it answered at once or resolved after the walk. A
296
+ * nested plan has at most one.
236
297
  */
237
298
  collectQuery(query: Query) {
238
- this.merges.unshift({ kind: 'query', query });
299
+ this.relationQuery = query;
239
300
  }
240
301
 
241
302
  /**
@@ -283,39 +344,52 @@ export class Plan<Model, Query, NodeType extends NodeBase<Model> = Node<Model>>
283
344
  * of a synchronous one.
284
345
  */
285
346
  play(seed?: Query): PlayedPlan<Model, Query, NodeType> {
286
- const { adapter } = this;
287
- const root = adapter.createNode(this.model);
288
347
  const settled = this.reusable(seed);
289
- // Merged before anything else, so on a conflict it wins. A settled play already holds the
290
- // plan's own `initial`, so reusing one merges the seed and nothing else: `mergeQuery` is not
291
- // required to be idempotent.
292
- const first = settled ? seed : (seed ?? this.initial);
293
-
294
- if (first) {
295
- adapter.mergeQuery(root, first);
296
- }
297
348
 
298
349
  if (settled) {
299
- // Every merge that play took still fits and every merge it left out still does not, so
300
- // the node it built is taken whole.
301
- adapter.mergeNode(root, settled.root);
350
+ const root = this.adapter.createNode(this.model);
351
+
352
+ // A settled play already holds the plan's own `initial`, so only the seed is merged here.
353
+ // `mergeQuery` is not required to be idempotent. Every merge that play took still fits and
354
+ // every merge it left out still does not, so its node is taken whole.
355
+ if (seed) {
356
+ this.adapter.mergeQuery(root, seed);
357
+ }
358
+
359
+ this.adapter.mergeNode(root, settled.root);
302
360
 
303
361
  return { plan: this, root, mappings: settled.mappings };
304
362
  }
305
363
 
364
+ const { adapter } = this;
365
+ const root = adapter.createNode(this.model);
306
366
  const mappings: Mappings = {};
367
+ // Merged before anything else, so on a conflict it wins.
368
+ const first = seed ?? this.initial;
369
+
370
+ if (first) {
371
+ adapter.mergeQuery(root, first);
372
+ }
373
+
374
+ if (this.relationQuery) {
375
+ adapter.mergeQuery(root, this.relationQuery, AS_QUERY);
376
+ }
307
377
 
308
- for (const merge of this.merges) {
378
+ for (const merge of this.walk.merges) {
309
379
  switch (merge.kind) {
310
380
  case 'type':
311
381
  adapter.mergeQuery(root, merge.query);
312
382
  break;
313
- case 'query':
314
- adapter.mergeQuery(root, merge.query, AS_QUERY);
315
- break;
316
- case 'variant':
317
- this.mergeVariant(root, merge.type, merge.variant, merge.query);
383
+ case 'variant': {
384
+ const conflict = adapter.firstConflict(root, merge.query);
385
+
386
+ if (conflict) {
387
+ throw variantConflict(merge.type, merge.variant, conflict);
388
+ }
389
+
390
+ adapter.mergeQuery(root, merge.query);
318
391
  break;
392
+ }
319
393
  case 'field': {
320
394
  // One options object for the pair: `mergeQuery` reads only the alias, and
321
395
  // `canMergeQuery` only the `ignoreArgs` beside it.
@@ -333,9 +407,7 @@ export class Plan<Model, Query, NodeType extends NodeBase<Model> = Node<Model>>
333
407
  default: {
334
408
  const unknown: never = merge;
335
409
 
336
- throw new PothosValidationError(
337
- `Unknown root merge ${String((unknown as RootMerge<Query>).kind)}`,
338
- );
410
+ throw unexpectedError(`Unknown root merge ${String((unknown as RootMerge<Query>).kind)}`);
339
411
  }
340
412
  }
341
413
  }
@@ -346,7 +418,7 @@ export class Plan<Model, Query, NodeType extends NodeBase<Model> = Node<Model>>
346
418
  /**
347
419
  * The plan played behind `seed`, its mappings recorded for the resolvers beneath it, and its
348
420
  * node serialized. A cached plan accepts the current resolver info to scope each execution.
349
- * Every play records its mappings on the request context; an adapter whose
421
+ * Every play records its mappings for the execution on the request context; an adapter whose
350
422
  * resolvers read a loaded row another way simply never looks them up.
351
423
  */
352
424
  query(seed?: Query, info = this.info): Query {
@@ -402,34 +474,29 @@ export class Plan<Model, Query, NodeType extends NodeBase<Model> = Node<Model>>
402
474
  ? this.played
403
475
  : undefined;
404
476
  }
477
+ }
405
478
 
406
- /**
407
- * Unlike a field-level select, a type-level selection has no per-field fallback, so a relation
408
- * argument or a computed value that conflicts with what is already in the node is an error
409
- * rather than a rejection.
410
- */
411
- private mergeVariant(node: NodeType, type: WalkedType, variant: WalkedType, selection: Query) {
412
- const conflict = this.adapter.firstConflict(node, selection);
413
-
414
- if (conflict) {
415
- switch (conflict.kind) {
416
- case 'relation':
417
- throw new PothosValidationError(
418
- `Type-level selections of ${type.name} and ${variant.name} conflict on relation "${conflict.name}". Move the relation arguments to a field-level select on one of the types.`,
419
- );
420
- case 'extra':
421
- throw new PothosValidationError(
422
- `Type-level selections of ${type.name} and ${variant.name} conflict on extra "${conflict.name}". Define the extra with the same function on both types, or move it to a field-level select on one of the types.`,
423
- );
424
- default: {
425
- const unknown: never = conflict.kind;
479
+ /**
480
+ * Unlike a field-level select, a type-level selection has no per-field fallback, so a relation
481
+ * argument or a computed value that conflicts with what is already in the node is an error rather
482
+ * than a rejection. It surfaces while a request runs, so the client sees a generic message and the
483
+ * detail is its `cause`, which responses leave out.
484
+ */
485
+ function variantConflict(type: WalkedType, variant: WalkedType, conflict: TypeLevelConflict) {
486
+ switch (conflict.kind) {
487
+ case 'relation':
488
+ return unexpectedError(
489
+ `Type-level selections of ${type.name} and ${variant.name} conflict on relation "${conflict.name}". Move the relation arguments to a field-level select on one of the types.`,
490
+ );
491
+ case 'extra':
492
+ return unexpectedError(
493
+ `Type-level selections of ${type.name} and ${variant.name} conflict on extra "${conflict.name}". Define the extra with the same function on both types, or move it to a field-level select on one of the types.`,
494
+ );
495
+ default: {
496
+ const unknown: never = conflict.kind;
426
497
 
427
- throw new PothosValidationError(`Unknown type-level conflict ${unknown as string}`);
428
- }
429
- }
498
+ return unexpectedError(`Unknown type-level conflict ${unknown as string}`);
430
499
  }
431
-
432
- this.adapter.mergeQuery(node, selection);
433
500
  }
434
501
  }
435
502
 
@@ -442,7 +509,7 @@ function positionForResolvedField(info: GraphQLResolveInfo): Position | undefine
442
509
  const node = info.fieldNodes[0];
443
510
  const field = info.parentType?.getFields()[node.name.value];
444
511
 
445
- return field && { parent: undefined, type: info.parentType, field, node };
512
+ return field && { parent: undefined, walkParent: undefined, type: info.parentType, field, node };
446
513
  }
447
514
 
448
515
  function normalizePaths(paths: PathSegment[][]): IndirectPathSegment[][] {
package/src/shape.ts ADDED
@@ -0,0 +1,126 @@
1
+ /**
2
+ * The shape of a selection set: a number that two selection sets of one document share exactly
3
+ * when they select the same thing, written the same way. A walk beneath a field reads its
4
+ * selection set and nothing else of the node, so walks are shared by shape rather than by node.
5
+ */
6
+ import { PothosValidationError } from '@pothos/core';
7
+ import {
8
+ type ASTNode,
9
+ type FieldNode,
10
+ type GraphQLResolveInfo,
11
+ Kind,
12
+ print,
13
+ type SelectionNode,
14
+ type SelectionSetNode,
15
+ } from 'graphql';
16
+
17
+ /** One document's shapes: the id interned for each selection's text, and each set's and field's id. */
18
+ interface Shapes {
19
+ ids: Map<string, number>;
20
+ sets: WeakMap<SelectionSetNode, number>;
21
+ fields: WeakMap<FieldNode, number>;
22
+ }
23
+
24
+ /**
25
+ * Per operation: a fragment spread is shaped by its name, which means the same definition only
26
+ * within one document. An operation's node belongs to one document and, unlike `info.fragments`,
27
+ * is the same in every execution of a cached document, so each set is shaped once per document.
28
+ */
29
+ const shapesByOperation = new WeakMap<object, Shapes>();
30
+
31
+ export function selectionShape(
32
+ info: GraphQLResolveInfo,
33
+ selectionSet: SelectionSetNode | undefined,
34
+ ): number {
35
+ return selectionSet ? shapeOfSet(shapesOf(info), selectionSet) : 0;
36
+ }
37
+
38
+ /**
39
+ * The shape of a field selection: its alias, name, arguments, directives and the shape of its
40
+ * selection set. Two field nodes with one shape select the same thing under the same response key.
41
+ */
42
+ export function fieldShape(info: GraphQLResolveInfo, field: FieldNode): number {
43
+ const shapes = shapesOf(info);
44
+ let id = shapes.fields.get(field);
45
+
46
+ if (id === undefined) {
47
+ id = shapeOfSelection(shapes, field);
48
+ shapes.fields.set(field, id);
49
+ }
50
+
51
+ return id;
52
+ }
53
+
54
+ function shapesOf(info: GraphQLResolveInfo): Shapes {
55
+ let shapes = shapesByOperation.get(info.operation);
56
+
57
+ if (!shapes) {
58
+ shapes = { ids: new Map(), sets: new WeakMap(), fields: new WeakMap() };
59
+ shapesByOperation.set(info.operation, shapes);
60
+ }
61
+
62
+ return shapes;
63
+ }
64
+
65
+ function shapeOfSet(shapes: Shapes, selectionSet: SelectionSetNode): number {
66
+ let id = shapes.sets.get(selectionSet);
67
+
68
+ if (id === undefined) {
69
+ id = intern(
70
+ shapes,
71
+ selectionSet.selections.map((selection) => shapeOfSelection(shapes, selection)),
72
+ );
73
+ shapes.sets.set(selectionSet, id);
74
+ }
75
+
76
+ return id;
77
+ }
78
+
79
+ /**
80
+ * A selection's text with every selection set beneath it replaced by its id. A spread stops at its
81
+ * name, so nothing is shaped twice however often a fragment is spread.
82
+ */
83
+ function shapeOfSelection(shapes: Shapes, selection: SelectionNode): number {
84
+ switch (selection.kind) {
85
+ case Kind.FIELD:
86
+ return intern(shapes, [
87
+ 'field',
88
+ selection.alias?.value ?? '',
89
+ selection.name.value,
90
+ printAll(selection.arguments),
91
+ printAll(selection.directives),
92
+ selection.selectionSet ? shapeOfSet(shapes, selection.selectionSet) : 0,
93
+ ]);
94
+ case Kind.FRAGMENT_SPREAD:
95
+ return intern(shapes, ['spread', selection.name.value, printAll(selection.directives)]);
96
+ case Kind.INLINE_FRAGMENT:
97
+ return intern(shapes, [
98
+ 'inline',
99
+ selection.typeCondition?.name.value ?? '',
100
+ printAll(selection.directives),
101
+ shapeOfSet(shapes, selection.selectionSet),
102
+ ]);
103
+ default: {
104
+ const unknown: never = selection;
105
+
106
+ throw new PothosValidationError(`Unknown selection kind ${(unknown as SelectionNode).kind}`);
107
+ }
108
+ }
109
+ }
110
+
111
+ function printAll(nodes: readonly ASTNode[] | undefined) {
112
+ return nodes?.length ? nodes.map((node) => print(node)) : [];
113
+ }
114
+
115
+ /** The id of `parts`, assigned the first time they are seen. Ids start at 1; 0 means no set. */
116
+ function intern(shapes: Shapes, parts: unknown[]): number {
117
+ const text = JSON.stringify(parts);
118
+ let id = shapes.ids.get(text);
119
+
120
+ if (id === undefined) {
121
+ id = shapes.ids.size + 1;
122
+ shapes.ids.set(text, id);
123
+ }
124
+
125
+ return id;
126
+ }
package/src/types.ts CHANGED
@@ -24,8 +24,26 @@ export type WalkedType = GraphQLInterfaceType | GraphQLObjectType;
24
24
  * about costs one link per select function and no arrays at all.
25
25
  */
26
26
  export interface Position {
27
- /** The field this one is selected beneath, or undefined at the field the plan started from. */
27
+ /**
28
+ * The field this one is selected beneath, or undefined at the field the plan started from.
29
+ * Reading it during planning has a cost. Invocations of a field at different places normally
30
+ * share the walk beneath it; a read keeps every walk it reads through from being shared, so
31
+ * each invocation is walked with its own path, which a document whose fragments branch at every
32
+ * level makes exponential in its depth. A fragment expanding to the implementations of a model
33
+ * interface walks its fields as each implementation, which adds an invocation, and a path, per
34
+ * implementation, except for a field the implementation inherits unchanged from that interface
35
+ * and no fragment narrows to the implementation: it is invoked once, on the interface, and its
36
+ * path names the interface. Read after planning, it is the first invocation's.
37
+ */
28
38
  readonly parent: Position | undefined;
39
+ /**
40
+ * The same link as `parent`, read without keeping the walk beneath from being shared. Its chain
41
+ * is the one the shared walk holds, the first invocation's, and not always the true path, so it
42
+ * is only for a name that needs to agree with itself: one a plan writes into its query and a
43
+ * resolver beneath the same walk reads back through its mapping. Anything that depends on where
44
+ * a field really is reads `parent`.
45
+ */
46
+ readonly walkParent: Position | undefined;
29
47
  /** The type the field was walked on: its parent type, or a same-model type the plan moved to. */
30
48
  readonly type: WalkedType;
31
49
  readonly field: GraphQLField<unknown, unknown>;
@@ -87,6 +105,12 @@ export interface EntryOptions<Query> {
87
105
  skipDeferredFragments?: boolean;
88
106
  }
89
107
 
108
+ /** The options of `Plan.forParentRow`, which plans the field `info` resolves on its own. */
109
+ export type ParentRowOptions<Query> = Pick<
110
+ EntryOptions<Query>,
111
+ 'context' | 'info' | 'initial' | 'skipDeferredFragments'
112
+ >;
113
+
90
114
  /** How one merge into an adapter's node differs from a plain one. */
91
115
  export interface MergeOptions {
92
116
  /**