carrick 0.3.157 → 0.3.159

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 (144) hide show
  1. package/dist/cli.d.ts +7 -0
  2. package/dist/cli.js +4 -0
  3. package/dist/cli.js.map +1 -1
  4. package/dist/contract.d.ts +8 -1
  5. package/dist/contract.js.map +1 -1
  6. package/dist/engine-ask.d.ts +21 -0
  7. package/dist/engine-ask.js +50 -0
  8. package/dist/engine-ask.js.map +1 -0
  9. package/dist/facts/diff.d.ts +14 -1
  10. package/dist/facts/diff.js +21 -8
  11. package/dist/facts/diff.js.map +1 -1
  12. package/dist/facts/fetch.d.ts +7 -0
  13. package/dist/facts/fetch.js +22 -1
  14. package/dist/facts/fetch.js.map +1 -1
  15. package/dist/facts/lines.d.ts +24 -4
  16. package/dist/facts/lines.js +55 -19
  17. package/dist/facts/lines.js.map +1 -1
  18. package/dist/facts/peers.d.ts +13 -4
  19. package/dist/facts/peers.js +17 -15
  20. package/dist/facts/peers.js.map +1 -1
  21. package/dist/facts/rules/packages.js +3 -1
  22. package/dist/facts/rules/packages.js.map +1 -1
  23. package/dist/facts/rules/same-name.js +1 -1
  24. package/dist/facts/rules/same-name.js.map +1 -1
  25. package/dist/facts/store.d.ts +15 -0
  26. package/dist/facts/store.js +30 -0
  27. package/dist/facts/store.js.map +1 -1
  28. package/dist/held/backoff.d.ts +8 -0
  29. package/dist/held/backoff.js +43 -0
  30. package/dist/held/backoff.js.map +1 -0
  31. package/dist/held/build.d.ts +17 -0
  32. package/dist/held/build.js +62 -0
  33. package/dist/held/build.js.map +1 -0
  34. package/dist/held/client.d.ts +12 -3
  35. package/dist/held/client.js +123 -8
  36. package/dist/held/client.js.map +1 -1
  37. package/dist/held/daemon.d.ts +47 -2
  38. package/dist/held/daemon.js +115 -23
  39. package/dist/held/daemon.js.map +1 -1
  40. package/dist/held/early.d.ts +28 -0
  41. package/dist/held/early.js +115 -0
  42. package/dist/held/early.js.map +1 -0
  43. package/dist/held/paths.d.ts +6 -0
  44. package/dist/held/paths.js +17 -0
  45. package/dist/held/paths.js.map +1 -1
  46. package/dist/held/place.d.ts +78 -30
  47. package/dist/held/place.js +123 -83
  48. package/dist/held/place.js.map +1 -1
  49. package/dist/held/run.js +24 -6
  50. package/dist/held/run.js.map +1 -1
  51. package/dist/held/runtime.d.ts +22 -0
  52. package/dist/held/runtime.js +620 -0
  53. package/dist/held/runtime.js.map +1 -0
  54. package/dist/held/shadow.d.ts +44 -0
  55. package/dist/held/shadow.js +68 -0
  56. package/dist/held/shadow.js.map +1 -0
  57. package/dist/held/steps.d.ts +11 -0
  58. package/dist/held/steps.js +29 -0
  59. package/dist/held/steps.js.map +1 -0
  60. package/dist/hook/confirm.d.ts +79 -0
  61. package/dist/hook/confirm.js +220 -0
  62. package/dist/hook/confirm.js.map +1 -0
  63. package/dist/hook/edit-flow.d.ts +14 -3
  64. package/dist/hook/edit-flow.js +113 -33
  65. package/dist/hook/edit-flow.js.map +1 -1
  66. package/dist/hook/generation.d.ts +19 -0
  67. package/dist/hook/generation.js +75 -0
  68. package/dist/hook/generation.js.map +1 -0
  69. package/dist/hook/late.d.ts +50 -9
  70. package/dist/hook/late.js +104 -24
  71. package/dist/hook/late.js.map +1 -1
  72. package/dist/hook/post-bash.js +3 -3
  73. package/dist/hook/post-bash.js.map +1 -1
  74. package/dist/hook/post-edit.js +2 -2
  75. package/dist/hook/post-edit.js.map +1 -1
  76. package/dist/hook/post-read.js +25 -3
  77. package/dist/hook/post-read.js.map +1 -1
  78. package/dist/hook/post-search.js +1 -1
  79. package/dist/hook/post-search.js.map +1 -1
  80. package/dist/hook/probe.js +1 -0
  81. package/dist/hook/probe.js.map +1 -1
  82. package/dist/hook/read-answer.d.ts +5 -0
  83. package/dist/hook/read-answer.js +8 -4
  84. package/dist/hook/read-answer.js.map +1 -1
  85. package/dist/hook/rechecks.d.ts +58 -2
  86. package/dist/hook/rechecks.js +132 -9
  87. package/dist/hook/rechecks.js.map +1 -1
  88. package/dist/hook/session-start.d.ts +1 -1
  89. package/dist/hook/session-start.js +19 -5
  90. package/dist/hook/session-start.js.map +1 -1
  91. package/dist/hook/similar.d.ts +1 -1
  92. package/dist/hook/similar.js +21 -8
  93. package/dist/hook/similar.js.map +1 -1
  94. package/dist/hook/stop-wait.js +35 -16
  95. package/dist/hook/stop-wait.js.map +1 -1
  96. package/dist/hook/timings.d.ts +29 -1
  97. package/dist/hook/timings.js +7 -1
  98. package/dist/hook/timings.js.map +1 -1
  99. package/dist/hook/user-prompt.js +2 -2
  100. package/dist/hook/user-prompt.js.map +1 -1
  101. package/dist/hosted-snapshot.d.ts +27 -0
  102. package/dist/hosted-snapshot.js +32 -0
  103. package/dist/hosted-snapshot.js.map +1 -1
  104. package/dist/init/hosted.js +2 -9
  105. package/dist/init/hosted.js.map +1 -1
  106. package/dist/render.d.ts +15 -1
  107. package/dist/render.js +50 -4
  108. package/dist/render.js.map +1 -1
  109. package/dist/server.js +1 -1
  110. package/dist/server.js.map +1 -1
  111. package/package.json +6 -6
  112. package/plugin/.claude-plugin/plugin.json +1 -1
  113. package/sidecar/dist/src/capture/anchors.d.ts +8 -0
  114. package/sidecar/dist/src/capture/anchors.js +3 -2
  115. package/sidecar/dist/src/capture/api.d.ts +70 -3
  116. package/sidecar/dist/src/capture/check-classify.d.ts +7 -0
  117. package/sidecar/dist/src/capture/check-classify.js +24 -0
  118. package/sidecar/dist/src/capture/check-probe.d.ts +76 -7
  119. package/sidecar/dist/src/capture/check-probe.js +147 -19
  120. package/sidecar/dist/src/capture/check-workspace.d.ts +21 -0
  121. package/sidecar/dist/src/capture/check-workspace.js +13 -0
  122. package/sidecar/dist/src/capture/check.js +13 -1
  123. package/sidecar/dist/src/capture/graphql-leaves.d.ts +46 -0
  124. package/sidecar/dist/src/capture/graphql-leaves.js +142 -0
  125. package/sidecar/dist/src/capture/index.d.ts +5 -1
  126. package/sidecar/dist/src/capture/index.js +4 -1
  127. package/sidecar/dist/src/definition-resolver.d.ts +2 -1
  128. package/sidecar/dist/src/definition-resolver.js +15 -9
  129. package/sidecar/dist/src/engine-stamp.json +1 -1
  130. package/sidecar/dist/src/held-shadow.d.ts +17 -2
  131. package/sidecar/dist/src/held-shadow.js +11 -10
  132. package/sidecar/dist/src/index.js +18 -1
  133. package/sidecar/dist/src/library-claims.js +26 -3
  134. package/sidecar/dist/src/retype.d.ts +47 -0
  135. package/sidecar/dist/src/retype.js +274 -18
  136. package/sidecar/dist/src/site-find.d.ts +27 -0
  137. package/sidecar/dist/src/site-find.js +109 -0
  138. package/sidecar/dist/src/type-inferrer.d.ts +5 -0
  139. package/sidecar/dist/src/type-inferrer.js +8 -4
  140. package/sidecar/dist/src/type-structural-expander.d.ts +10 -0
  141. package/sidecar/dist/src/type-structural-expander.js +73 -4
  142. package/sidecar/dist/src/types.d.ts +50 -2
  143. package/sidecar/dist/src/validators.d.ts +424 -104
  144. package/sidecar/dist/src/validators.js +29 -0
@@ -93,6 +93,8 @@ export class Retyper {
93
93
  // comment over the rest of the call.
94
94
  return abstain(item, "the producer's response type carries a comment");
95
95
  }
96
+ if (item.procedure_path)
97
+ return this.runProcedure(item, producer, before);
96
98
  const found = this.beforeRewrite(item);
97
99
  if (typeof found === 'string')
98
100
  return abstain(item, found);
@@ -339,14 +341,7 @@ export class Retyper {
339
341
  // Appended only when the rewrite names them: an alias nothing references
340
342
  // is a TS6196 under `noUnusedLocals`, which would read as the producer's
341
343
  // type failing to resolve.
342
- const appendix = rewrite.wire
343
- ? '\n' +
344
- [
345
- ...this.jsonWire(PREFIX),
346
- `type ${WIRE}<P> = ${PREFIX}JsonWireSame<${PREFIX}JsonWire<P>, P> extends true ? P : ${PREFIX}JsonWire<P>;`,
347
- ].join('\n') +
348
- '\n'
349
- : '';
344
+ const appendix = rewrite.wire ? '\n' + this.wireDeclarations().join('\n') + '\n' : '';
350
345
  const rewritten = applyEdits(original, rewrite.edits) + appendix;
351
346
  const bodyEnd = rewritten.length - appendix.length;
352
347
  const originOf = (pos) => pos >= bodyEnd ? { kind: 'inserted' } : mapBack(pos, rewrite.edits);
@@ -455,10 +450,223 @@ export class Retyper {
455
450
  const deciding = unknowns.length > 0 ? unknowns : diagnosed ? [] : anys;
456
451
  if (deciding.length === 0)
457
452
  return undefined;
458
- const members = deciding
459
- .map(({ kind, path }) => (path === '' ? `'${kind}'` : `'${kind}' at '${path}'`))
460
- .join(', ');
461
- return `the producer's response reads as ${members} in the consumer's program, so it was not compared`;
453
+ return `the producer's response reads as ${membersText(deciding)} in the consumer's program, so it was not compared`;
454
+ }
455
+ /**
456
+ * The JSON wire transform's declarations and the `${WIRE}<P>` alias that
457
+ * states a type in its wire form, as appended to a file that names them.
458
+ */
459
+ wireDeclarations() {
460
+ return [
461
+ ...this.jsonWire(PREFIX),
462
+ `type ${WIRE}<P> = ${PREFIX}JsonWireSame<${PREFIX}JsonWire<P>, P> extends true ? P : ${PREFIX}JsonWire<P>;`,
463
+ ];
464
+ }
465
+ /**
466
+ * The procedure form (carrick#937): judge a procedure call by the
467
+ * consumer's own code against the call's own type.
468
+ *
469
+ * A procedure call's type IS the producer's router type, read by the
470
+ * consumer's compiler, so stating the producer's output at the call would
471
+ * compare one type with itself. What breaks is the consumer's use of it.
472
+ * The file is type-checked as it is and again with only the call's result
473
+ * erased (`(<call> as any)`): a diagnostic present as-is and gone when
474
+ * erased is a place the consumer uses what the procedure does not return.
475
+ *
476
+ * A guard runs first: the call's result (or one member of it, for a hook's
477
+ * envelope such as `{ data }`) must be the producer's published output, as
478
+ * declared or in its JSON wire form. A call whose result is something else
479
+ * (an options builder's `{ key }`), or a router on disk that no longer
480
+ * returns what the producer published, is not compared: erasing it would
481
+ * agree about nothing.
482
+ */
483
+ runProcedure(item, producer, before) {
484
+ const located = this.locateProcedureCall(item, item.procedure_path);
485
+ if (typeof located === 'string')
486
+ return abstain(item, located);
487
+ const { sourceFile, call } = located;
488
+ if (resultIsDiscarded(call))
489
+ return abstain(item, 'the consumer never reads the response');
490
+ const escape = resultEscapes(call);
491
+ if (escape)
492
+ return abstain(item, escape);
493
+ // Read now: every text replacement makes ts-morph forget the file's
494
+ // nodes, `call` included.
495
+ const start = call.getStart();
496
+ const end = call.getEnd();
497
+ const original = sourceFile.getFullText();
498
+ let pre = before.get(sourceFile);
499
+ if (!pre) {
500
+ pre = fileDiagnostics(sourceFile);
501
+ before.set(sourceFile, pre);
502
+ }
503
+ const top = this.procedureTopTypes(call);
504
+ if (typeof top === 'string')
505
+ return abstain(item, top);
506
+ const carried = this.carriesProducerOutput(sourceFile, original, producer, start, end);
507
+ if (typeof carried === 'string')
508
+ return abstain(item, carried);
509
+ // Erase only what carries the output. A result that IS the output is
510
+ // erased to `any`. A result that carries it in one member (a hook's
511
+ // `{ data: O | undefined }`) keeps its envelope, and that member keeps its
512
+ // `null`/`undefined`: an error the client's own envelope raises
513
+ // (`result.data` possibly undefined) is the same with any output, so it
514
+ // must stay when the output is erased, not read as a break.
515
+ const edits = carried.member === undefined
516
+ ? [
517
+ { start, end: start, text: '(' },
518
+ { start: end, end, text: ' as any)' },
519
+ ]
520
+ : [
521
+ { start, end: start, text: `${ERASE_MEMBER}(` },
522
+ { start: end, end, text: `, ${JSON.stringify(carried.member)})` },
523
+ ];
524
+ const appendix = carried.member === undefined ? '' : '\n' + eraseMemberDeclarations().join('\n') + '\n';
525
+ const body = applyEdits(original, edits);
526
+ let erased;
527
+ replaceFileText(sourceFile, body + appendix);
528
+ try {
529
+ erased = fileDiagnostics(sourceFile).flatMap((d) => {
530
+ if (d.start >= body.length)
531
+ return [];
532
+ const origin = mapBack(d.start, edits);
533
+ return origin.kind === 'inserted' ? [] : [{ ...d, start: origin.pos }];
534
+ });
535
+ }
536
+ finally {
537
+ replaceFileText(sourceFile, original);
538
+ }
539
+ // Present as-is and gone once the result is erased: the reverse of
540
+ // `check`, which counts what a stated type adds.
541
+ const remaining = new Map();
542
+ for (const d of erased)
543
+ remaining.set(key(d), (remaining.get(key(d)) ?? 0) + 1);
544
+ const added = [];
545
+ for (const d of pre) {
546
+ if (UNUSED_DECLARATION_CODES.has(d.code))
547
+ continue;
548
+ const left = remaining.get(key(d)) ?? 0;
549
+ if (left > 0) {
550
+ remaining.set(key(d), left - 1);
551
+ continue;
552
+ }
553
+ added.push(d);
554
+ }
555
+ added.sort((a, b) => a.start - b.start || a.code - b.code);
556
+ if (added.length === 0) {
557
+ if (top.length > 0) {
558
+ return abstain(item, `the procedure call's result reads as ${membersText(top)} in the consumer's program, so it was not compared`);
559
+ }
560
+ return { item_id: item.item_id, outcome: 'agrees', diagnostics: [] };
561
+ }
562
+ const lineOf = lineIndex(original);
563
+ return {
564
+ item_id: item.item_id,
565
+ outcome: 'mismatch',
566
+ diagnostics: added.map((d) => ({ line: lineOf(d.start), code: d.code, message: d.message })),
567
+ };
568
+ }
569
+ /**
570
+ * The one call to the procedure `procedurePath` names that starts on the
571
+ * item's line: a call whose callee is `R.s1.….sk.m`, with `s1..sk` the key
572
+ * path's segments, `m` any name (the client's operation) and `R` any
573
+ * expression (the client). Or why there is not exactly one.
574
+ */
575
+ locateProcedureCall(item, procedurePath) {
576
+ const sourceFile = this.inferrer.sourceFileOf(item.file_path);
577
+ if (!sourceFile)
578
+ return 'the procedure call could not be located on its line';
579
+ const segments = procedurePath.split('.');
580
+ const calls = sourceFile
581
+ .getDescendantsOfKind(SyntaxKind.CallExpression)
582
+ .filter((c) => c.getStartLineNumber() === item.line_number && namesProcedure(c, segments));
583
+ if (calls.length === 0)
584
+ return 'the procedure call could not be located on its line';
585
+ if (calls.length > 1) {
586
+ return 'two calls to the procedure start on one line, so the call cannot be told apart';
587
+ }
588
+ return { sourceFile, call: calls[0] };
589
+ }
590
+ /**
591
+ * The `any` members of the call's awaited result, which can only hide a
592
+ * diagnostic and so decide only an empty diff, or why the result cannot be
593
+ * compared at all (`any`/`unknown` as a whole, `unknown` at a member). The
594
+ * walk's budget sentinel is dropped, as {@link unresolvedMembers} drops it.
595
+ */
596
+ procedureTopTypes(call) {
597
+ const program = this.project.getProgram().compilerObject;
598
+ const checker = program.getTypeChecker();
599
+ const own = awaitedResult(checker, call.compilerNode);
600
+ for (const [flag, kind] of [
601
+ [ts.TypeFlags.Any, 'any'],
602
+ [ts.TypeFlags.Unknown, 'unknown'],
603
+ ]) {
604
+ if (own.flags & flag) {
605
+ return `the procedure call's result reads as '${kind}' in the consumer's program, so it was not compared`;
606
+ }
607
+ }
608
+ const found = this.topTypes(own, program, checker, call.compilerNode);
609
+ const unknowns = found.filter((finding) => finding.kind === 'unknown');
610
+ if (unknowns.length > 0) {
611
+ return `the procedure call's result reads as ${membersText(unknowns)} in the consumer's program, so it was not compared`;
612
+ }
613
+ return found.filter((finding) => finding.kind === 'any');
614
+ }
615
+ /**
616
+ * Guard (carrick#937): what carries the producer's published output,
617
+ * declared or in its JSON wire form (each way assignable to the other),
618
+ * read in the consumer's own program: the call's awaited result as a whole
619
+ * (`member` unset), or for an object result the string-named member that
620
+ * does once `null`/`undefined` are removed. Else why the call is not
621
+ * compared.
622
+ */
623
+ carriesProducerOutput(sourceFile, original, producer, start, end) {
624
+ const out = `${PREFIX}ProcOut`;
625
+ const wire = `${PREFIX}ProcWire`;
626
+ const appendix = '\n' +
627
+ [
628
+ ...this.wireDeclarations(),
629
+ `type ${out} = (${producer});`,
630
+ `type ${wire} = ${WIRE}<(${producer})>;`,
631
+ ].join('\n') +
632
+ '\n';
633
+ replaceFileText(sourceFile, original + appendix);
634
+ try {
635
+ const unresolved = fileDiagnostics(sourceFile).find((d) => d.start >= original.length && !UNUSED_DECLARATION_CODES.has(d.code));
636
+ if (unresolved) {
637
+ return ("the producer's output does not resolve in the consumer's program: " +
638
+ `TS${unresolved.code}: ${unresolved.message}`);
639
+ }
640
+ const call = callAt(sourceFile, start, end);
641
+ if (!call)
642
+ return 'the procedure call could not be found again after the rewrite';
643
+ const checker = this.project.getProgram().compilerObject.getTypeChecker();
644
+ const stated = [out, wire].flatMap((name) => {
645
+ const alias = sourceFile.getTypeAlias(name);
646
+ return alias ? [checker.getTypeAtLocation(alias.getNameNode().compilerNode)] : [];
647
+ });
648
+ const own = awaitedResult(checker, call.compilerNode);
649
+ const candidates = [{ type: own }];
650
+ if (own.flags & ts.TypeFlags.Object && !checker.isArrayType(own) && !checker.isTupleType(own)) {
651
+ for (const property of checker.getPropertiesOfType(own)) {
652
+ // A symbol-keyed member has no name the erase can write.
653
+ if (property.escapedName.toString().startsWith('__@'))
654
+ continue;
655
+ candidates.push({
656
+ type: checker.getNonNullableType(checker.getTypeOfSymbol(property)),
657
+ member: property.getName(),
658
+ });
659
+ }
660
+ }
661
+ const same = (a, b) => checker.isTypeAssignableTo(a, b) && checker.isTypeAssignableTo(b, a);
662
+ const carrier = candidates.find((c) => stated.some((t) => same(t, c.type)));
663
+ if (carrier)
664
+ return { member: carrier.member };
665
+ return "the call's result does not carry the procedure's output as the producer publishes it";
666
+ }
667
+ finally {
668
+ replaceFileText(sourceFile, original);
669
+ }
462
670
  }
463
671
  /**
464
672
  * The stated type argument must be what the call RETURNS (or a type
@@ -468,9 +676,7 @@ export class Retyper {
468
676
  * consumer against the wrong thing, so the item abstains.
469
677
  */
470
678
  typeArgumentReachesResult(sourceFile, at) {
471
- const call = sourceFile
472
- .getDescendantsOfKind(SyntaxKind.CallExpression)
473
- .find((c) => c.getStart() === at.start && c.getEnd() === at.end);
679
+ const call = callAt(sourceFile, at.start, at.end);
474
680
  if (!call)
475
681
  return 'the retyped call could not be found again after the rewrite';
476
682
  const stated = call.getTypeArguments()[0]?.getType();
@@ -499,9 +705,7 @@ export class Retyper {
499
705
  }
500
706
  /** What the call yields once awaited: the type the reach test compares. */
501
707
  resultOf(call) {
502
- const checker = this.project.getTypeChecker().compilerObject;
503
- const returned = call.getType().compilerType;
504
- return checker.getAwaitedType(returned) ?? returned;
708
+ return awaitedResult(this.project.getTypeChecker().compilerObject, call.compilerNode);
505
709
  }
506
710
  /**
507
711
  * The abstention for a call whose type argument is not in its result. The
@@ -515,6 +719,58 @@ export class Retyper {
515
719
  `('${checker.typeToString(this.resultOf(call))}'), so it does not state the response`);
516
720
  }
517
721
  }
722
+ const ERASE_MEMBER = `${PREFIX}eraseMember`;
723
+ /**
724
+ * `${ERASE_MEMBER}(value, key)` types as `value` (awaited or not) with member
725
+ * `key` erased: any read of it passes, but the `null`/`undefined` it held
726
+ * stays, so a read the envelope itself rejects is still rejected. The
727
+ * erased part is an object that answers every property and index read with
728
+ * `any`, since `any | undefined` would collapse to `any`.
729
+ */
730
+ function eraseMemberDeclarations() {
731
+ const loose = `${PREFIX}Loose`;
732
+ const erasedIn = `${PREFIX}EraseIn`;
733
+ return [
734
+ `type ${loose} = { [key: string]: any; [index: number]: any };`,
735
+ `type ${erasedIn}<T, K extends PropertyKey> = Omit<T, K> & { [P in K & keyof T]: ${loose} | Exclude<T[P], NonNullable<T[P]>> };`,
736
+ `declare function ${ERASE_MEMBER}<T, K extends PropertyKey>(value: T, key: K): T extends PromiseLike<infer U> ? Promise<${erasedIn}<U, K>> : ${erasedIn}<T, K>;`,
737
+ ];
738
+ }
739
+ /** Top-type findings as a reason names them: `'any'`, `'unknown' at 'a.b'`. */
740
+ function membersText(findings) {
741
+ return findings
742
+ .map(({ kind, path }) => (path === '' ? `'${kind}'` : `'${kind}' at '${path}'`))
743
+ .join(', ');
744
+ }
745
+ /** What a call yields once awaited, read with `checker`. */
746
+ function awaitedResult(checker, call) {
747
+ const returned = checker.getTypeAtLocation(call);
748
+ return checker.getAwaitedType(returned) ?? returned;
749
+ }
750
+ /**
751
+ * `call`'s callee is `R.s1.….sk.m` with `[s1..sk]` equal to `segments`
752
+ * (`m` any name, `R` any expression).
753
+ */
754
+ function namesProcedure(call, segments) {
755
+ const callee = call.getExpression();
756
+ if (!Node.isPropertyAccessExpression(callee))
757
+ return false;
758
+ let at = callee.getExpression();
759
+ for (let i = segments.length - 1; i >= 0; i--) {
760
+ if (!Node.isPropertyAccessExpression(at) || at.getName() !== segments[i])
761
+ return false;
762
+ at = at.getExpression();
763
+ }
764
+ return true;
765
+ }
766
+ /** The call expression that spans exactly `start`..`end` in `sourceFile` now. */
767
+ function callAt(sourceFile, start, end) {
768
+ for (let at = sourceFile.getDescendantAtStartWithWidth(start, end - start); at && at.getStart() === start && at.getEnd() === end; at = at.getParent()) {
769
+ if (Node.isCallExpression(at))
770
+ return at;
771
+ }
772
+ return undefined;
773
+ }
518
774
  function abstain(item, reason) {
519
775
  return { item_id: item.item_id, outcome: 'abstain', diagnostics: [], reason };
520
776
  }
@@ -0,0 +1,27 @@
1
+ /**
2
+ * `find_site`: the capture's own site finder, asked by a caller that held a
3
+ * value's span in one text and needs its node in another (a held check whose
4
+ * bounds an edit crossed). The value is found by its parent slot, never by its
5
+ * text: the node of the old span sits in a slot of its parent (the n-th child
6
+ * of a call, a `return`'s expression, an arrow's body), and the answer is the
7
+ * node in that slot of the new text nearest the old position carried through
8
+ * the edit, so an edit to the value's own text, or the same text elsewhere
9
+ * (another handler's send, a binding of the same name), cannot move it. A call's
10
+ * slot also needs the callee to read as before unless the edit reaches the call.
11
+ * A node must be one the capture reads a value type at (`isPreferredTarget`).
12
+ * No program is loaded and nothing is read from disk: both texts are the
13
+ * caller's.
14
+ */
15
+ export type SiteAnswer = {
16
+ start: number;
17
+ end: number;
18
+ } | {
19
+ reason: 'value_not_a_node' | 'not_wrappable';
20
+ };
21
+ export declare function findSite(request: {
22
+ file: string;
23
+ oldText: string;
24
+ newText: string;
25
+ start: number;
26
+ end: number;
27
+ }): SiteAnswer;
@@ -0,0 +1,109 @@
1
+ /**
2
+ * `find_site`: the capture's own site finder, asked by a caller that held a
3
+ * value's span in one text and needs its node in another (a held check whose
4
+ * bounds an edit crossed). The value is found by its parent slot, never by its
5
+ * text: the node of the old span sits in a slot of its parent (the n-th child
6
+ * of a call, a `return`'s expression, an arrow's body), and the answer is the
7
+ * node in that slot of the new text nearest the old position carried through
8
+ * the edit, so an edit to the value's own text, or the same text elsewhere
9
+ * (another handler's send, a binding of the same name), cannot move it. A call's
10
+ * slot also needs the callee to read as before unless the edit reaches the call.
11
+ * A node must be one the capture reads a value type at (`isPreferredTarget`).
12
+ * No program is loaded and nothing is read from disk: both texts are the
13
+ * caller's.
14
+ */
15
+ import { ts } from 'ts-morph';
16
+ import { isPreferredTarget } from './capture/index.js';
17
+ /** The text a call's callee reads as, without whitespace. */
18
+ function headOf(parent, sourceFile) {
19
+ if (ts.isCallExpression(parent) || ts.isNewExpression(parent))
20
+ return parent.expression.getText(sourceFile).replace(/\s+/g, '');
21
+ return undefined;
22
+ }
23
+ function slotOf(node, sourceFile) {
24
+ const parent = node.parent;
25
+ if (!parent)
26
+ return undefined;
27
+ let index = -1;
28
+ let at = 0;
29
+ parent.forEachChild((child) => {
30
+ if (child === node)
31
+ index = at;
32
+ at += 1;
33
+ });
34
+ return index < 0 ? undefined : { parentKind: parent.kind, index, head: headOf(parent, sourceFile) };
35
+ }
36
+ /** The outermost value-space node whose span is exactly `[start, end)`. */
37
+ function nodeAtSpan(sourceFile, start, end) {
38
+ let found;
39
+ const visit = (node) => {
40
+ if (found || node.getEnd() < end || node.getStart(sourceFile) > start)
41
+ return;
42
+ if (node.getStart(sourceFile) === start && node.getEnd() === end && ts.isExpression(node)) {
43
+ found = node;
44
+ return;
45
+ }
46
+ node.forEachChild(visit);
47
+ };
48
+ visit(sourceFile);
49
+ return found;
50
+ }
51
+ /** The one region the edit changed, the common prefix and suffix cut off (the caller's `regionOfEdit`). */
52
+ function editRegion(oldText, newText) {
53
+ const limit = Math.min(oldText.length, newText.length);
54
+ let prefix = 0;
55
+ while (prefix < limit && oldText.charCodeAt(prefix) === newText.charCodeAt(prefix))
56
+ prefix += 1;
57
+ let suffix = 0;
58
+ while (suffix < limit - prefix && oldText.charCodeAt(oldText.length - 1 - suffix) === newText.charCodeAt(newText.length - 1 - suffix))
59
+ suffix += 1;
60
+ return { oldStart: prefix, oldEnd: oldText.length - suffix, newStart: prefix, newEnd: newText.length - suffix };
61
+ }
62
+ /** Where `position` of the old text lands in the new: shifted past the edit, kept before it, scaled inside it. */
63
+ function carried(position, region) {
64
+ if (position <= region.oldStart)
65
+ return position;
66
+ if (position >= region.oldEnd)
67
+ return position + (region.newEnd - region.newStart) - (region.oldEnd - region.oldStart);
68
+ return Math.min(region.newEnd, region.newStart + (position - region.oldStart));
69
+ }
70
+ export function findSite(request) {
71
+ const oldFile = ts.createSourceFile(request.file, request.oldText, ts.ScriptTarget.Latest, true);
72
+ const sourceFile = ts.createSourceFile(request.file, request.newText, ts.ScriptTarget.Latest, true);
73
+ const held = nodeAtSpan(oldFile, request.start, request.end);
74
+ const slot = held && slotOf(held, oldFile);
75
+ if (!slot)
76
+ return { reason: 'value_not_a_node' };
77
+ const region = editRegion(request.oldText, request.newText);
78
+ const target = carried(request.start, region);
79
+ let best;
80
+ let bestDistance = Infinity;
81
+ const visit = (node) => {
82
+ const parent = node.parent;
83
+ if (parent && parent.kind === slot.parentKind && isPreferredTarget(node) && ts.isExpression(node)) {
84
+ const at = slotOf(node, sourceFile);
85
+ if (at && at.index === slot.index) {
86
+ const start = node.getStart(sourceFile);
87
+ // The callee is how the slot is told from its namesakes; an edit that reaches the call may have changed it.
88
+ const reached = parent.getEnd() > region.newStart && parent.getStart(sourceFile) < region.newEnd;
89
+ if (at.head === slot.head || reached) {
90
+ const distance = Math.abs(start - target);
91
+ if (distance < bestDistance) {
92
+ best = node;
93
+ bestDistance = distance;
94
+ }
95
+ }
96
+ }
97
+ }
98
+ node.forEachChild(visit);
99
+ };
100
+ visit(sourceFile);
101
+ const node = best;
102
+ if (!node)
103
+ return { reason: 'value_not_a_node' };
104
+ // A call cannot wrap a spread, or the name a shorthand property is also the value of.
105
+ if (ts.isSpreadElement(node) || (ts.isIdentifier(node) && node.parent && ts.isShorthandPropertyAssignment(node.parent))) {
106
+ return { reason: 'not_wrappable' };
107
+ }
108
+ return { start: node.getStart(sourceFile), end: node.getEnd() };
109
+ }
@@ -264,6 +264,11 @@ export declare class TypeInferrer {
264
264
  sourceFile: SourceFile;
265
265
  call: CallExpression;
266
266
  } | undefined;
267
+ /**
268
+ * The source file a locator's `file_path` names (absolute, or relative to
269
+ * the repo root), added to the project when it is not loaded yet.
270
+ */
271
+ sourceFileOf(filePath: string): SourceFile | undefined;
267
272
  /**
268
273
  * Get or add a source file to the project
269
274
  */
@@ -1066,15 +1066,19 @@ export class TypeInferrer {
1066
1066
  * published type came from, not a guess at the line.
1067
1067
  */
1068
1068
  locateCall(request) {
1069
- const filePath = path.isAbsolute(request.file_path)
1070
- ? request.file_path
1071
- : path.join(this.repoRoot, request.file_path);
1072
- const sourceFile = this.getSourceFile(filePath);
1069
+ const sourceFile = this.sourceFileOf(request.file_path);
1073
1070
  if (!sourceFile)
1074
1071
  return undefined;
1075
1072
  const call = this.resolveTargetCallExpression(sourceFile, request);
1076
1073
  return call ? { sourceFile, call } : undefined;
1077
1074
  }
1075
+ /**
1076
+ * The source file a locator's `file_path` names (absolute, or relative to
1077
+ * the repo root), added to the project when it is not loaded yet.
1078
+ */
1079
+ sourceFileOf(filePath) {
1080
+ return this.getSourceFile(path.isAbsolute(filePath) ? filePath : path.join(this.repoRoot, filePath));
1081
+ }
1078
1082
  /**
1079
1083
  * Get or add a source file to the project
1080
1084
  */
@@ -31,6 +31,7 @@
31
31
  import { type Node, type Type, ts } from 'ts-morph';
32
32
  import { type ExternalImports } from './origin.js';
33
33
  import type { WireFormat } from './types.js';
34
+ import type { GraphqlRoot, GraphqlTypes } from './capture/index.js';
34
35
  /**
35
36
  * Bound on the structural-expansion recursion. Deep enough for every realistic
36
37
  * request/response shape; a backstop against pathological/recursive types the
@@ -89,6 +90,15 @@ export interface ExpandOptions {
89
90
  readonly overrides?: MemberOverrides;
90
91
  /** Which representation to print; see `WireFormat`. */
91
92
  readonly wire?: WireFormat;
93
+ /**
94
+ * For `'graphql_scalars'`: the producer service's SDL types and the root
95
+ * field the response answers (carrick#4403). Without a leaf for the root
96
+ * the print is the JSON form.
97
+ */
98
+ readonly graphql?: {
99
+ types: GraphqlTypes;
100
+ root: GraphqlRoot;
101
+ };
92
102
  /**
93
103
  * Where in the recursion the walk starts. Production callers never set it —
94
104
  * depth is walk state — but the `MAX_EXPANSION_DEPTH` backstop is reachable
@@ -32,6 +32,7 @@ import { ts } from 'ts-morph';
32
32
  import { canonicalizeUnionsInText, foldBooleanLiterals, } from './type-text-canonicalizer.js';
33
33
  import { isExternalOrigin } from './origin.js';
34
34
  import { notePrintedType } from './printed-names.js';
35
+ import { graphqlDeclaresType, graphqlFieldLeaf, graphqlRootLeaf, graphqlScalarSent, withoutNonNull, } from './capture/index.js';
35
36
  /**
36
37
  * Bound on the structural-expansion recursion. Deep enough for every realistic
37
38
  * request/response shape; a backstop against pathological/recursive types the
@@ -72,8 +73,67 @@ function childCursor(cursor, segment) {
72
73
  * representation (`WireFormat`).
73
74
  */
74
75
  export function expandTypeStructural(type, origin, options = {}) {
75
- const { overrides, wire = 'declared', depth = 0 } = options;
76
- return expandAt(type, new Set(), depth, overrides ? { overrides, position: '' } : undefined, wire, origin);
76
+ const { overrides, wire = 'declared', depth = 0, graphql } = options;
77
+ return expandAt(type, new Set(), depth, overrides ? { overrides, position: '' } : undefined, wire === 'graphql_scalars'
78
+ ? graphqlWalkFrom(graphql)
79
+ : wire === 'unknown'
80
+ ? 'declared' // an unknown form prints as declared (carrick#4402)
81
+ : wire, origin);
82
+ }
83
+ /** The walk's start for a GraphQL producer response: its root leaf, or JSON. */
84
+ function graphqlWalkFrom(graphql) {
85
+ const leaf = graphql && graphqlRootLeaf(graphql.types, graphql.root);
86
+ return leaf ? { leaf, types: graphql.types } : 'json';
87
+ }
88
+ /**
89
+ * The walk below the member `name` of a value at `wire`: the field's own
90
+ * leaf under a GraphQL object type, JSON for a field the SDL does not name,
91
+ * and `wire` itself everywhere else.
92
+ */
93
+ function memberWalk(wire, name) {
94
+ if (typeof wire !== 'object')
95
+ return wire;
96
+ const leaf = withoutNonNull(wire.leaf);
97
+ if (!('type' in leaf))
98
+ return 'json';
99
+ const field = graphqlFieldLeaf(wire.types, leaf.type, name);
100
+ return field ? { leaf: field, types: wire.types } : 'json';
101
+ }
102
+ /**
103
+ * A value at a GraphQL leaf, printed as the server sends it (carrick#4403),
104
+ * mirroring the probe's `GqlLeafSent`: `null`, `undefined`, `any` and
105
+ * `unknown` stay; a union maps each member; a list maps its elements; a
106
+ * built-in scalar is the type it sends; any other scalar, an enum, a type
107
+ * reference the table does not hold, and a shape the leaf does not describe
108
+ * print in the JSON form. `undefined` means an object type over an object
109
+ * value: the caller walks its members.
110
+ */
111
+ function graphqlLeafText(type, seen, depth, cursor, wire, origin) {
112
+ const leaf = withoutNonNull(wire.leaf);
113
+ const here = { leaf, types: wire.types };
114
+ if (type.isNull() || type.isUndefined() || type.isAny() || type.isUnknown()) {
115
+ return namedText(type);
116
+ }
117
+ if (type.isUnion()) {
118
+ return canonicalMembers(type.getUnionTypes(), seen, depth, cursor, here, origin).join(' | ');
119
+ }
120
+ const json = () => expandAt(type, seen, depth, cursor, 'json', origin);
121
+ if ('list' in leaf) {
122
+ const element = type.isArray() ? type.getArrayElementType() : undefined;
123
+ if (!element)
124
+ return json();
125
+ const inner = expandAt(element, seen, depth + 1, childCursor(cursor, '<0>'), { leaf: leaf.list, types: wire.types }, origin);
126
+ return element.isUnion() || element.isIntersection() ? `(${inner})[]` : `${inner}[]`;
127
+ }
128
+ if ('scalar' in leaf)
129
+ return graphqlScalarSent(leaf.scalar) ?? json();
130
+ if (!('type' in leaf) || !graphqlDeclaresType(wire.types, leaf.type))
131
+ return json();
132
+ if (type.isArray() || isTuple(type))
133
+ return json();
134
+ if (type.getCallSignatures().length > 0)
135
+ return namedText(type);
136
+ return undefined;
77
137
  }
78
138
  /**
79
139
  * The type `JSON.stringify` serialises in place of a value of `type`: the
@@ -120,6 +180,11 @@ function expandAt(type, seen, depth, at, wire, origin) {
120
180
  if (!hasOverrideBelow(cursor))
121
181
  cursor = undefined;
122
182
  }
183
+ if (typeof wire === 'object') {
184
+ const text = graphqlLeafText(type, seen, depth, cursor, wire, origin);
185
+ if (text !== undefined)
186
+ return text;
187
+ }
123
188
  // Primitives & literals: nothing to inline.
124
189
  if (type.isString() ||
125
190
  type.isNumber() ||
@@ -247,7 +312,10 @@ function backstopText(type) {
247
312
  * case the joined output is the same whichever way round they go.
248
313
  */
249
314
  function canonicalMembers(members, seen, depth, cursor, wire, origin) {
250
- return orderMembers(members, (member) => expandAt(member, seen, depth + 1, cursor, wire, origin));
315
+ const texts = orderMembers(members, (member) => expandAt(member, seen, depth + 1, cursor, wire, origin));
316
+ // Under a GraphQL leaf several members can send one type (`bigint |
317
+ // string` under `String`): print it once (carrick#4403).
318
+ return typeof wire === 'object' ? [...new Set(texts)] : texts;
251
319
  }
252
320
  /**
253
321
  * The canonical order itself, over whatever text `render` gives each member.
@@ -268,7 +336,8 @@ function orderMembers(members, render) {
268
336
  return rendered.map((entry) => entry.text);
269
337
  }
270
338
  /** Render a single property as `name[?]: <expanded>`. */
271
- function expandProperty(prop, owner, seen, depth, at, wire, origin) {
339
+ function expandProperty(prop, owner, seen, depth, at, parentWire, origin) {
340
+ const wire = memberWalk(parentWire, prop.getName());
272
341
  const optional = (prop.getFlags() & ts.SymbolFlags.Optional) !== 0;
273
342
  const propDecl = prop.getDeclarations()[0];
274
343
  // Render the key from the declaration's name node so quoted/computed keys