carrick 0.3.135 → 0.3.137

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.
@@ -39,7 +39,8 @@ import * as crypto from 'node:crypto';
39
39
  import * as fs from 'node:fs';
40
40
  import * as path from 'node:path';
41
41
  import { ts } from 'ts-morph';
42
- import { holdsResult, resultCandidatesOf } from './result-candidates.js';
42
+ import { holdsResult, resultCandidatesOf, resultCandidatesOfReturn } from './result-candidates.js';
43
+ import { RUNTIME_EMITTER_EVENTS, RUNTIME_TYPE_PACKAGES, isRuntimeEmitterMember } from './runtime-emitter.js';
43
44
  import { PathNames, declaringFileName } from './position-rows.js';
44
45
  import { memberDeclaration } from './declaration-attribution.js';
45
46
  /** The methods a `verb` claim may name, and a method key may accept. */
@@ -54,6 +55,44 @@ const HTTP_METHODS = new Set([
54
55
  ]);
55
56
  /** The methods a route may register: every request method, and `ALL` for a member that registers each. */
56
57
  const ROUTE_METHODS = new Set([...HTTP_METHODS, 'ALL']);
58
+ /**
59
+ * The method words of the protocols that are not HTTP (amendment 7, part 4,
60
+ * carrick#3048): the kind of an RPC procedure, the operation kind of a
61
+ * GraphQL request.
62
+ */
63
+ const RPC_WORDS = new Set(['QUERY', 'MUTATE', 'MUTATION', 'SUBSCRIBE', 'SUBSCRIPTION']);
64
+ const GRAPHQL_WORDS = new Set(['QUERY', 'MUTATION', 'SUBSCRIPTION']);
65
+ /** Every protocol value the grammar names; any other is `claim_invalid`. */
66
+ const PROTOCOLS = new Set(['http', 'graphql', 'rpc', 'socket', 'message']);
67
+ /**
68
+ * The protocols an op of each role may speak. An HTTP framework and an HTTP
69
+ * client carry RPC and GraphQL operations over HTTP, so they speak all three;
70
+ * the message roles speak only their own.
71
+ */
72
+ const ROLE_PROTOCOLS = {
73
+ http_client: new Set(['http', 'rpc', 'graphql']),
74
+ server_framework: new Set(['http', 'rpc', 'graphql']),
75
+ graphql_client: new Set(['graphql']),
76
+ socket: new Set(['socket']),
77
+ broker: new Set(['message']),
78
+ in_process_bus: new Set(['message']),
79
+ none: new Set(),
80
+ };
81
+ /** The type names a `document` name slot accepts; a string is accepted too. */
82
+ const DOCUMENT_TYPES = new Set([
83
+ 'DocumentNode',
84
+ 'TypedDocumentNode',
85
+ 'RequestDocument',
86
+ 'TypedDocumentString',
87
+ ]);
88
+ /** The method words an op reads under its protocol; absent, the role's own. */
89
+ function methodWords(claim, rules) {
90
+ if (claim.protocol === 'rpc')
91
+ return RPC_WORDS;
92
+ if (claim.protocol === 'graphql')
93
+ return GRAPHQL_WORDS;
94
+ return rules.methods;
95
+ }
57
96
  /**
58
97
  * Interfaces whose members every value of that kind inherits. A key found only
59
98
  * on one of these (`constructor`, `toString`, a string's `length`) is not a
@@ -72,19 +111,6 @@ const BUILTIN_INTERFACES = new Set([
72
111
  'Array',
73
112
  'ReadonlyArray',
74
113
  ]);
75
- /**
76
- * The runtime's own type packages. A type they declare (the runtime's event
77
- * emitter above all) is never part of another package's own declarations,
78
- * even when that package's maker returns it: a member only the runtime
79
- * declares is the runtime's, not the package's. When the named package is
80
- * one of these, it is its own.
81
- */
82
- const RUNTIME_TYPE_PACKAGES = new Set([
83
- '@types/node',
84
- '@types/bun',
85
- 'bun-types',
86
- '@types/deno',
87
- ]);
88
114
  /**
89
115
  * A runtime module's own specifier (`node:events`). Its declarations are the
90
116
  * runtime's types package's, which is therefore its home (contract
@@ -164,7 +190,25 @@ function hasV2Field(claim) {
164
190
  return claim.runs !== undefined;
165
191
  if (claim.kind !== 'op')
166
192
  return false;
167
- return claim.method_default !== undefined || claim.base !== undefined || claim.runs !== undefined || claim.yields !== undefined;
193
+ return (claim.method_default !== undefined ||
194
+ claim.base !== undefined ||
195
+ claim.runs !== undefined ||
196
+ claim.yields !== undefined ||
197
+ claim.form === 'new');
198
+ }
199
+ /**
200
+ * Whether an op uses a field amendment 7 of carrick#2434 adds to the claim
201
+ * grammar and that picks the v2 rules: a `protocol`, or a name that is bound,
202
+ * a literal, a document or a reference. A package with one such op reads
203
+ * every one of its `http_client` exports under the v2 rules (carrick#3048):
204
+ * the maker of an RPC client carries none of these fields itself.
205
+ */
206
+ function usesAmendment7(claim) {
207
+ if (claim.kind !== 'op')
208
+ return false;
209
+ const name = claim.name;
210
+ return (claim.protocol !== undefined ||
211
+ (name !== undefined && (!('arg' in name) || name.document !== undefined || name.ref !== undefined)));
168
212
  }
169
213
  const VERIFIED = { verdict: 'verified' };
170
214
  const failed = (reason) => ({ verdict: 'failed', reason });
@@ -311,6 +355,12 @@ export class LibraryClaimsVerifier {
311
355
  if (check.role === 'http_client' && hasV2Field(check.claim))
312
356
  v2Exports.add(exportKey(check));
313
357
  }
358
+ // A package whose labels use the new grammar reads all its http_client exports as v2.
359
+ const v2Packages = new Set(checks.filter(check => check.role === 'http_client' && usesAmendment7(check.claim)).map(check => check.package));
360
+ for (const check of checks) {
361
+ if (check.role === 'http_client' && v2Packages.has(check.package))
362
+ v2Exports.add(exportKey(check));
363
+ }
314
364
  const rulesFor = (check) => check.role === 'http_client' && v2Exports.has(exportKey(check))
315
365
  ? HTTP_V2_RULES
316
366
  : readReplies && check.role === 'server_framework'
@@ -360,6 +410,23 @@ export class LibraryClaimsVerifier {
360
410
  builtIndex.set(key, importLines.length + builtLines.length);
361
411
  builtLines.push(`${expression};`);
362
412
  }
413
+ // A check on a type receiver (carrick#2977) reads its type as declared
414
+ // after the export's import: the export itself, a type the export's
415
+ // namespace declares (`type:A.B`), or one another module declares
416
+ // (`type:<module>#A.B`, carrick#3046). A `lib:` global is named as itself.
417
+ for (const check of checks) {
418
+ const typed = parseReceiver(check.receiver);
419
+ if (!rulesFor(check)?.message || !typed?.type)
420
+ continue;
421
+ const key = builtKey(check, check.receiver);
422
+ if (builtIndex.has(key))
423
+ continue;
424
+ builtIndex.set(key, importLines.length + builtLines.length);
425
+ const local = DEFAULT_LIBRARY.test(check.package) ? check.export : `__carrick_e${importIndex.get(exportKey(check))}`;
426
+ builtLines.push(typeBuildLine(builtLines.length, typed.typeModule !== undefined
427
+ ? `import(${JSON.stringify(typed.typeModule)}).${typed.typePath.join('.')}`
428
+ : [local, ...(typed.typePath ?? [])].join('.')));
429
+ }
363
430
  // A `node:` key may name a file of the runtime's types, whose exports are
364
431
  // globals (`runtimeGlobalFile`): the probe reads each as `globalThis` holds
365
432
  // it, beside its import, and the reader takes the one the key resolves to.
@@ -483,9 +550,70 @@ export class LibraryClaimsVerifier {
483
550
  makerHolding,
484
551
  ...(keyBound === undefined ? {} : { keyBound }),
485
552
  madeBy: receiverPath.maker?.member === null && receiverPath.scope === undefined ? check.export : undefined,
553
+ exportName: check.export,
486
554
  })),
487
555
  };
488
556
  };
557
+ /**
558
+ * The one receiver of a check on `type` (carrick#2977): the export read
559
+ * as a type at its declared type-parameter defaults (a generic with no
560
+ * default is read at its declared type, its parameters read through
561
+ * their constraints, ruling R2), its home from the declaration the
562
+ * probe line names. A name bound under a maker or scope claim reads
563
+ * as the claim builds it (`boundByType`). `type_unresolved` when the
564
+ * name has no type meaning.
565
+ */
566
+ const readTypeReceiver = (check) => {
567
+ const index = builtIndex.get(builtKey(check, check.receiver));
568
+ const built = index === undefined ? undefined : builtTypeAt(checker, file.statements[index]);
569
+ if (built === undefined)
570
+ return { reason: 'type_unresolved' };
571
+ const bound = boundByType(check, built.type);
572
+ return {
573
+ value: [
574
+ {
575
+ type: built.type,
576
+ pkg: check.package,
577
+ home: withTypePackages(reader.homeOf(check.package, [built.symbol, ...typeSymbols(built.type)]), typePackages[check.package]),
578
+ makerBindsName: bound.maker,
579
+ scoped: bound.scope,
580
+ },
581
+ ],
582
+ };
583
+ };
584
+ /**
585
+ * On a receiver keyed by type, a name is bound by a verified maker or
586
+ * scope claim of the same package that returns a type with a
587
+ * declaration in common with the receiver's (`sameDeclared`, never the
588
+ * same name). Judged only for an op that reads a bound name.
589
+ */
590
+ const boundByType = (check, type) => {
591
+ const claim = check.claim;
592
+ const result = { maker: false, scope: false };
593
+ if (claim.kind !== 'op' || claim.name === undefined || !('bound' in claim.name))
594
+ return result;
595
+ if (claim.name.bound !== 'maker' && claim.name.bound !== 'scope')
596
+ return result;
597
+ checks.forEach((other, i) => {
598
+ if (other.package !== check.package || other === check)
599
+ return;
600
+ const made = other.claim;
601
+ if ((made.kind !== 'make' && made.kind !== 'scope') || made.name === undefined)
602
+ return;
603
+ const judgement = judge(i);
604
+ if (judgement.outcome.verdict !== 'verified' || !judgement.holding)
605
+ return;
606
+ const builtOther = builtReceiver(other);
607
+ const at = builtOther === undefined ? undefined : atDefaults(other, builtOther);
608
+ if (judgement.holding.some(sig => sameDeclared(checker, reader.returnOf(sig, at), type))) {
609
+ if (made.kind === 'make')
610
+ result.maker = true;
611
+ else
612
+ result.scope = true;
613
+ }
614
+ });
615
+ return result;
616
+ };
489
617
  /**
490
618
  * What a set of maker (or scope) judgements build: the distinct types
491
619
  * their common overloads return, each read at its declared
@@ -552,6 +680,14 @@ export class LibraryClaimsVerifier {
552
680
  return { outcome: unchecked('role_conflict') };
553
681
  if (placementInvalid(check.claim))
554
682
  return { outcome: unchecked('claim_invalid') };
683
+ if (check.claim.kind === 'op' && check.claim.protocol !== undefined) {
684
+ if (!PROTOCOLS.has(check.claim.protocol))
685
+ return { outcome: unchecked('claim_invalid') };
686
+ if (!ROLE_PROTOCOLS[check.role].has(check.claim.protocol))
687
+ return { outcome: unchecked('protocol_role') };
688
+ }
689
+ if (unbuiltPart(check.claim) !== undefined)
690
+ return { outcome: unchecked('part_unbuilt') };
555
691
  if (rules.http && !HTTP_RECEIVER.test(check.receiver))
556
692
  return { outcome: unchecked('receiver_invalid') };
557
693
  if (rules.message && !fitsReceiver(check))
@@ -563,10 +699,12 @@ export class LibraryClaimsVerifier {
563
699
  if (rules.message && LOCAL_RANGE.test(localRanges.get(packageNameOf(check.package)) ?? '')) {
564
700
  return { outcome: unchecked('module_workspace') };
565
701
  }
566
- const exportRead = readExport(check);
567
- if ('reason' in exportRead)
702
+ // A type export has no value to read (carrick#2977): `readTypeReceiver` reads it.
703
+ const typeReceiver = rules.message && parseReceiver(check.receiver)?.type === true;
704
+ const exportRead = typeReceiver ? undefined : readExport(check);
705
+ if (exportRead !== undefined && 'reason' in exportRead)
568
706
  return { outcome: unchecked(exportRead.reason) };
569
- if (rules.http) {
707
+ if (rules.http && exportRead !== undefined) {
570
708
  const key = exportKey(check);
571
709
  const receiverKey = `${key}\u0000${check.receiver}`;
572
710
  let receiverRead = httpReceivers.get(receiverKey);
@@ -582,7 +720,7 @@ export class LibraryClaimsVerifier {
582
720
  if (check.claim.kind === 'op' && !rules.ops.has(check.claim.op)) {
583
721
  return { outcome: unchecked('role_unsupported') };
584
722
  }
585
- const receivers = readMessageReceivers(index, exportRead.value);
723
+ const receivers = exportRead === undefined ? readTypeReceiver(check) : readMessageReceivers(index, exportRead.value);
586
724
  if ('reason' in receivers)
587
725
  return { outcome: unchecked(receivers.reason) };
588
726
  const built = builtReceiver(check);
@@ -609,6 +747,9 @@ export class LibraryClaimsVerifier {
609
747
  const verified = declarations.length > 0 ? { verdict: 'verified', declarations: sortedDeclarations(declarations) } : { ...VERIFIED };
610
748
  if (verified.verdict === 'verified' && members.length > 0)
611
749
  verified.members = members;
750
+ if (verified.verdict === 'verified' && exportRead === undefined) {
751
+ verified.receiverTypes = receivers.value.flatMap(r => [...declaredSymbols(checker, r.type)].flatMap(s => s.declarations ?? []));
752
+ }
612
753
  if (verified.verdict === 'verified' && requestDropped !== undefined)
613
754
  verified.requestDropped = requestDropped;
614
755
  else if (verified.verdict === 'verified' && bodyMembers.length > 0)
@@ -644,15 +785,19 @@ export class LibraryClaimsVerifier {
644
785
  */
645
786
  labelledMembers(fromDir, checks, budgetMs, scanRoot, typePackages = {}) {
646
787
  const sends = new Map();
788
+ const sets = new Map();
789
+ const returns = new Map();
647
790
  const bodies = new Set();
648
791
  const wanted = checks.filter(check => check.role === 'server_framework' &&
649
792
  check.claim.kind === 'op' &&
650
793
  ((check.claim.op === 'send' && check.claim.payload !== undefined) ||
651
- (check.claim.op === 'receive' && check.claim.request?.body !== undefined)));
794
+ (check.claim.op === 'receive' &&
795
+ (check.claim.request?.body !== undefined ||
796
+ (check.claim.returns !== undefined && check.claim.handler !== undefined)))));
652
797
  // A receiver an op is read on can need the maker or scope claims beside it.
653
798
  const context = checks.filter(check => check.role === 'server_framework' && (check.claim.kind === 'make' || check.claim.kind === 'scope'));
654
799
  if (wanted.length === 0)
655
- return { sends, bodies };
800
+ return { sends, sets, returns, bodies };
656
801
  const outcomes = {};
657
802
  const observe = (check, outcome) => {
658
803
  if (check.claim.kind !== 'op')
@@ -666,14 +811,20 @@ export class LibraryClaimsVerifier {
666
811
  if (outcome.verdict !== 'verified')
667
812
  return;
668
813
  if (check.claim.op === 'send' && check.claim.payload !== undefined) {
814
+ const into = check.claim.form === 'set' ? sets : sends;
669
815
  for (const member of outcome.members ?? [])
670
- sends.set(declarationKey(member), check.claim.payload);
816
+ into.set(declarationKey(member), check.claim.payload);
817
+ }
818
+ if (check.claim.op === 'receive' && check.claim.returns !== undefined && check.claim.handler !== undefined) {
819
+ const read = { handler: check.claim.handler, ...(check.claim.returns.result ? { result: check.claim.returns.result } : {}) };
820
+ for (const member of outcome.members ?? [])
821
+ returns.set(declarationKey(member), read);
671
822
  }
672
823
  for (const member of outcome.bodyMembers ?? [])
673
824
  bodies.add(declarationKey(member));
674
825
  };
675
826
  this.run(fromDir, [...context, ...wanted], budgetMs, scanRoot, { observe, readReplies: true, typePackages });
676
- return { sends, bodies, outcomes };
827
+ return { sends, sets, returns, bodies, outcomes };
677
828
  }
678
829
  /**
679
830
  * Each specifier's declared surface, read with the verifier's predicates
@@ -731,12 +882,28 @@ export class LibraryClaimsVerifier {
731
882
  defaultImport: file.statements[at + 1],
732
883
  };
733
884
  };
734
- const makers = this.readProbe(fromDir, imports, (_checker, reader, file) => packages.map((pkg, i) => reader.makersOf(pkg, probeOf(file, i), only[pkg])));
885
+ const read = this.readProbe(fromDir, imports, (_checker, reader, file) => packages.map((pkg, i) => reader.makersOf(pkg, probeOf(file, i), only[pkg])));
735
886
  const importLines = [];
736
887
  const buildLines = [];
737
888
  const builtIndex = new Map();
889
+ // The type-only exports a handler's parameter may be (carrick#2977): each
890
+ // imported and declared at its defaults (`typeBuildLine`), as the verifier
891
+ // reads a `type` receiver. Only with handlers: the table names them.
892
+ const typeImports = new Map();
893
+ packages.forEach((pkg, i) => {
894
+ if (options.handlers !== true && options.types !== true)
895
+ return;
896
+ for (const name of typeNamesOf(read[i], options)) {
897
+ const local = `__carrick_e${importLines.length}`;
898
+ const key = builtKey({ package: pkg, export: name }, TYPE_RECEIVER);
899
+ typeImports.set(key, importLines.length);
900
+ importLines.push(probeLine(pkg, name, local));
901
+ builtIndex.set(key, buildLines.length);
902
+ buildLines.push(typeBuildLine(buildLines.length, local));
903
+ }
904
+ });
738
905
  packages.forEach((pkg, i) => {
739
- for (const { export: name, receivers, scopes } of makers[i]) {
906
+ for (const { export: name, receivers, scopes } of read[i].makers) {
740
907
  const local = `__carrick_e${importLines.length}`;
741
908
  importLines.push(probeLine(pkg, name, local));
742
909
  // The scope receivers a maker's members may return (carrick#2774) are
@@ -751,10 +918,25 @@ export class LibraryClaimsVerifier {
751
918
  }
752
919
  });
753
920
  const firstBuild = imports.length + importLines.length;
754
- const surfaces = this.readProbe(fromDir, [...imports, ...importLines, ...buildLines], (checker, reader, file) => packages.map((pkg, i) => reader.listPackage(pkg, probeOf(file, i), maxEntries, only[pkg], options, (name, receiver) => {
755
- const index = builtIndex.get(builtKey({ package: pkg, export: name }, receiver));
756
- return index === undefined ? undefined : resolvedBuild(checker, file.statements[firstBuild + index]);
757
- })));
921
+ const surfaces = this.readProbe(fromDir, [...imports, ...importLines, ...buildLines], (checker, reader, file) => {
922
+ // One budget for the whole call, spent across its specifiers: the answer is one line.
923
+ reader.startListing(options.maxHandlerMembers ?? HANDLER_LISTING_BUDGET);
924
+ return packages.map((pkg, i) => {
925
+ const typeExports = [];
926
+ if (options.handlers === true || options.types === true) {
927
+ for (const name of typeNamesOf(read[i], options)) {
928
+ const key = builtKey({ package: pkg, export: name }, TYPE_RECEIVER);
929
+ const built = builtType(checker, file.statements[imports.length + typeImports.get(key)], file.statements[firstBuild + builtIndex.get(key)]);
930
+ if (built)
931
+ typeExports.push({ ...built, name });
932
+ }
933
+ }
934
+ return reader.listPackage(pkg, probeOf(file, i), maxEntries, only[pkg], options, typeExports, (name, receiver) => {
935
+ const index = builtIndex.get(builtKey({ package: pkg, export: name }, receiver));
936
+ return index === undefined ? undefined : resolvedBuild(checker, file.statements[firstBuild + index]);
937
+ });
938
+ });
939
+ });
758
940
  return { surfaces, surface_sha256: fullSurfaceSha256(surfaces) };
759
941
  }
760
942
  /** `read` over a probe file holding `lines` in `fromDir`, removed again afterwards. */
@@ -787,6 +969,129 @@ function resolvedBuild(checker, statement) {
787
969
  return undefined;
788
970
  return checker.getResolvedSignature(expression);
789
971
  }
972
+ /** How many `extends` links `receiver_types` follows from a receiver's type. */
973
+ const RECEIVER_BASE_DEPTH = 8;
974
+ /** The receiver id a type export is read on (carrick#2977): the type itself, at its defaults. */
975
+ const TYPE_RECEIVER = 'type';
976
+ /** The probe line that builds a type export bound to `local` at its declared type-parameter defaults. */
977
+ function typeBuildLine(index, local) {
978
+ return `declare const __carrick_t${index}: ${local};`;
979
+ }
980
+ /**
981
+ * What a type export's probe lines read (carrick#2977): the declaration its
982
+ * import names (`importStatement`, one named import) and the type
983
+ * `typeBuildLine` declares. Undefined when the name has no type meaning
984
+ * (a `const`) or the line does not resolve to a type (a generic whose type
985
+ * parameter has no default): the checker reads either as `any`.
986
+ */
987
+ function builtType(checker, importStatement, buildStatement) {
988
+ if (!importStatement || !ts.isImportDeclaration(importStatement))
989
+ return undefined;
990
+ const bindings = importStatement.importClause?.namedBindings;
991
+ const element = bindings && ts.isNamedImports(bindings) ? bindings.elements[0] : undefined;
992
+ if (!element || !buildStatement || !ts.isVariableStatement(buildStatement))
993
+ return undefined;
994
+ const local = checker.getSymbolAtLocation(element.name);
995
+ if (!local)
996
+ return undefined;
997
+ const symbol = local.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(local) : local;
998
+ if (checker.isUnknownSymbol(symbol) || (symbol.flags & ts.SymbolFlags.Type) === 0)
999
+ return undefined;
1000
+ const declaration = buildStatement.declarationList.declarations[0];
1001
+ if (!declaration)
1002
+ return undefined;
1003
+ const type = checker.getTypeAtLocation(declaration.name);
1004
+ if (type.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown))
1005
+ return undefined;
1006
+ return { symbol, type };
1007
+ }
1008
+ /**
1009
+ * The type a type receiver's probe line declares (carrick#3046), read from
1010
+ * the line's own type reference, so a default import, a namespace path, an
1011
+ * `import("module")` path and a `lib:` global all resolve. A generic with no
1012
+ * default is read at its declared type: its type parameters stay, and every
1013
+ * predicate reads them through their constraints (ruling R2). Undefined when
1014
+ * the name has no type meaning (a `const`). The lister reads `builtType`.
1015
+ */
1016
+ function builtTypeAt(checker, buildStatement) {
1017
+ if (!buildStatement || !ts.isVariableStatement(buildStatement))
1018
+ return undefined;
1019
+ const declaration = buildStatement.declarationList.declarations[0];
1020
+ const node = declaration?.type;
1021
+ if (!declaration || !node)
1022
+ return undefined;
1023
+ let name;
1024
+ if (ts.isTypeReferenceNode(node))
1025
+ name = ts.isQualifiedName(node.typeName) ? node.typeName.right : node.typeName;
1026
+ else if (ts.isImportTypeNode(node) && node.qualifier)
1027
+ name = ts.isQualifiedName(node.qualifier) ? node.qualifier.right : node.qualifier;
1028
+ else
1029
+ return undefined;
1030
+ const local = checker.getSymbolAtLocation(name);
1031
+ if (!local)
1032
+ return undefined;
1033
+ const symbol = local.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(local) : local;
1034
+ if (checker.isUnknownSymbol(symbol) || (symbol.flags & ts.SymbolFlags.Type) === 0)
1035
+ return undefined;
1036
+ let type = checker.getTypeAtLocation(declaration.name);
1037
+ if (type.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown))
1038
+ type = checker.getDeclaredTypeOfSymbol(symbol);
1039
+ if (type.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown))
1040
+ return undefined;
1041
+ return { symbol, type };
1042
+ }
1043
+ /** How many levels of base types `declaredSymbols` follows. */
1044
+ const BASE_DEPTH = 8;
1045
+ /**
1046
+ * A type's key (carrick#3046): the class, interface and alias symbols the
1047
+ * type stands on. They are the type's own, those of its union and
1048
+ * intersection parts, of its awaited type, of its reference target, and of
1049
+ * its base types, to a bounded depth. A `this` type is the symbol of its class or
1050
+ * interface, which the checker already hands over instantiated.
1051
+ */
1052
+ function declaredSymbols(checker, type, bases = true) {
1053
+ const out = new Set();
1054
+ const wanted = ts.SymbolFlags.Class | ts.SymbolFlags.Interface | ts.SymbolFlags.TypeAlias;
1055
+ const seen = new Set();
1056
+ const visit = (t, depth) => {
1057
+ if (seen.has(t) || depth > BASE_DEPTH)
1058
+ return;
1059
+ seen.add(t);
1060
+ const awaited = checker.getAwaitedType(t) ?? t;
1061
+ if (awaited !== t)
1062
+ return visit(awaited, depth);
1063
+ if (t.isUnionOrIntersection()) {
1064
+ for (const part of t.types)
1065
+ visit(part, depth);
1066
+ return;
1067
+ }
1068
+ const reference = t;
1069
+ const target = t.objectFlags & ts.ObjectFlags.Reference ? reference.target : undefined;
1070
+ for (const symbol of [t.getSymbol(), t.aliasSymbol, target?.getSymbol()]) {
1071
+ if (symbol && symbol.flags & wanted)
1072
+ out.add(symbol);
1073
+ }
1074
+ const own = target ?? t;
1075
+ if (bases && own.isClassOrInterface())
1076
+ for (const base of checker.getBaseTypes(own))
1077
+ visit(base, depth + 1);
1078
+ };
1079
+ visit(type, 0);
1080
+ return out;
1081
+ }
1082
+ /**
1083
+ * `built` is a `wanted` type: some declaration `wanted` stands on is one
1084
+ * `built` stands on, bases included (an interface that extends the wanted
1085
+ * one builds it too). Never the reverse, and never through a shared base
1086
+ * alone: the same symbol, never the same name.
1087
+ */
1088
+ function sameDeclared(checker, built, wanted) {
1089
+ const left = declaredSymbols(checker, built);
1090
+ for (const symbol of declaredSymbols(checker, wanted, false))
1091
+ if (left.has(symbol))
1092
+ return true;
1093
+ return false;
1094
+ }
790
1095
  /**
791
1096
  * The full-surface hash the shared library store keys on: sha256 of the JSON
792
1097
  * array of `[package, exports]` for every surface that listed at least one
@@ -803,9 +1108,12 @@ export function fullSurfaceSha256(surfaces) {
803
1108
  .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
804
1109
  // A member's `handlers` (carrick#2674), a signature's `result_candidates`
805
1110
  // (carrick#2817) and a member's `scope_receiver` (carrick#2774) are out of
806
- // the hash at every depth, so a package's key does not change when the
807
- // lister learns to list them.
808
- const text = JSON.stringify(listed, (key, value) => key === 'handlers' || key === 'result_candidates' || key === 'scope_receiver' ? undefined : value);
1111
+ // the hash at every depth, and so is a member's `runtime_events`
1112
+ // (carrick#3032), so a package's key does not change when the lister
1113
+ // learns to list them.
1114
+ const text = JSON.stringify(listed, (key, value) => key === 'handlers' || key === 'result_candidates' || key === 'scope_receiver' || key === 'runtime_events'
1115
+ ? undefined
1116
+ : value);
809
1117
  return crypto.createHash('sha256').update(text).digest('hex');
810
1118
  }
811
1119
  function exportKey(check) {
@@ -816,7 +1124,9 @@ function factoryKey(exportKeyText, member) {
816
1124
  }
817
1125
  /**
818
1126
  * `export`, `instance:()`, `instance:new`, `instance:new:<member>` or
819
- * `instance:<member>`, optionally followed by `>scope:<path.member>`.
1127
+ * `instance:<member>`, optionally followed by `>scope:<path.member>`; or
1128
+ * `type` (carrick#2977), `type:<A.B>` or `type:<module>#<A.B>` (carrick#3046),
1129
+ * followed by nothing.
820
1130
  */
821
1131
  function parseReceiver(text) {
822
1132
  const steps = text.split('>');
@@ -832,6 +1142,14 @@ function parseReceiver(text) {
832
1142
  }
833
1143
  if (base === 'export')
834
1144
  return { base, scope };
1145
+ if (base === TYPE_RECEIVER)
1146
+ return scope === undefined ? { base, type: true } : undefined;
1147
+ const typed = /^type:(?:([^#\s]+)#)?([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*)$/.exec(base);
1148
+ if (typed) {
1149
+ return scope === undefined
1150
+ ? { base, type: true, typePath: typed[2].split('.'), ...(typed[1] ? { typeModule: typed[1] } : {}) }
1151
+ : undefined;
1152
+ }
835
1153
  if (base === 'instance:()')
836
1154
  return { base, scope, maker: { form: 'call', member: null } };
837
1155
  if (base === 'instance:new')
@@ -848,11 +1166,74 @@ function parseReceiver(text) {
848
1166
  function scopeStep(claim) {
849
1167
  return [...(claim.path ?? []), claim.member].join('.');
850
1168
  }
1169
+ /**
1170
+ * A form no judge reads on this op yet (carrick#3047): `override`, and `set`
1171
+ * on anything but a send (a socket's handler by assignment is a later
1172
+ * slice). A form on an op kind it never belongs to (`new` on a receive,
1173
+ * `decorate` on a send) is `claim_invalid`, read by `judgeOp`.
1174
+ */
1175
+ function formUnbuilt(claim) {
1176
+ return claim.form === 'override' || (claim.form === 'set' && claim.op !== 'send');
1177
+ }
1178
+ /**
1179
+ * The first part of a claim that amendment 7 of carrick#2434 adds and no
1180
+ * judge reads yet, or undefined (carrick#3045). The schema takes the whole
1181
+ * grammar so one request never fails on a part; an element that uses one
1182
+ * answers `unchecked part_unbuilt` until the judge for it lands. Each slice
1183
+ * removes the parts it judges from here.
1184
+ */
1185
+ function unbuiltPart(claim) {
1186
+ const slots = [];
1187
+ if (claim.kind === 'make')
1188
+ slots.push(claim.base, claim.prefix, claim.name, claim.handler);
1189
+ if (claim.kind === 'scope')
1190
+ slots.push(claim.name, claim.mounts);
1191
+ if (claim.kind === 'op') {
1192
+ const name = claim.name;
1193
+ slots.push(claim.payload, claim.handler, claim.ack, claim.options, claim.method_key, claim.base);
1194
+ if (name !== undefined) {
1195
+ if ('bound' in name) {
1196
+ if (name.bound === 'subscribed')
1197
+ return `name.bound.${name.bound}`;
1198
+ // A path joins its property names; no other bound name has a join, a param or an `at`.
1199
+ const joins = name.bound === 'path' ? undefined : name.join;
1200
+ if (joins !== undefined || name.param !== undefined || name.at !== undefined)
1201
+ return 'name.bound';
1202
+ }
1203
+ else if ('parts' in name) {
1204
+ return 'name.parts';
1205
+ }
1206
+ else if (!('literal' in name)) {
1207
+ // A literal is judged in `judgeOp`, a document or reference slot too; a make's or scope's still is not.
1208
+ slots.push({ ...name, document: undefined, ref: undefined });
1209
+ }
1210
+ }
1211
+ if (formUnbuilt(claim))
1212
+ return `form.${claim.form}`;
1213
+ if (claim.when !== undefined)
1214
+ return 'when';
1215
+ }
1216
+ for (const slot of slots) {
1217
+ if (slot === undefined)
1218
+ continue;
1219
+ const named = slot;
1220
+ if (named.at !== undefined)
1221
+ return 'slot.at';
1222
+ if (named.each !== undefined)
1223
+ return 'slot.each';
1224
+ if (named.document !== undefined)
1225
+ return 'slot.document';
1226
+ if (named.ref !== undefined)
1227
+ return 'slot.ref';
1228
+ }
1229
+ return undefined;
1230
+ }
851
1231
  /**
852
1232
  * An op, scope or reserved name carries `on` or `of`, never both, and `of` is
853
- * a receiver a maker or a scope builds, by its receiver id: never the export
854
- * itself, which `on: 'export'` names (contract amendment 2, B3). "Both the
855
- * export and one maker's instances" is two elements, not one.
1233
+ * a receiver a maker or a scope builds, by its receiver id, or `type`, the
1234
+ * export read as a type (carrick#2977): never the export itself, which
1235
+ * `on: 'export'` names (contract amendment 2, B3). "Both the export and one
1236
+ * maker's instances" is two elements, not one.
856
1237
  */
857
1238
  function placementInvalid(claim) {
858
1239
  if (claim.kind === 'make' || claim.of === undefined)
@@ -860,7 +1241,7 @@ function placementInvalid(claim) {
860
1241
  if (claim.on !== undefined)
861
1242
  return true;
862
1243
  const of = parseReceiver(claim.of);
863
- return of === undefined || (of.maker === undefined && of.scope === undefined);
1244
+ return of === undefined || (of.maker === undefined && of.scope === undefined && of.type === undefined);
864
1245
  }
865
1246
  /**
866
1247
  * Where a handler's request holds its path, method and body (#2474 R0,
@@ -895,7 +1276,8 @@ export function declarationKey(declaration) {
895
1276
  * `of` is read on exactly that receiver. One with `on` is read on the export
896
1277
  * (`export`), on an instance of a maker (`instance`) or on either (`both`),
897
1278
  * and never on a receiver a scope returns, which only `of` names. One with
898
- * neither names no receiver of its own. A claim read on a receiver it was
1279
+ * neither names no receiver of its own. A type receiver (`type`, `type:A.B`,
1280
+ * `type:<module>#A.B`) is read only by the `of` that names it (carrick#2977). A claim read on a receiver it was
899
1281
  * not claimed for could verify a member of the same name with another shape
900
1282
  * (`client.write(name, value)` against `instance.write(value)`).
901
1283
  */
@@ -904,6 +1286,9 @@ function fitsReceiver(check) {
904
1286
  if (!receiver)
905
1287
  return false;
906
1288
  const claim = check.claim;
1289
+ // A type is read only by a claim placed on it, by the same id (carrick#2977, #3046).
1290
+ if (receiver.type)
1291
+ return claim.kind !== 'make' && claim.of === check.receiver;
907
1292
  if (claim.kind === 'make')
908
1293
  return check.receiver === 'export';
909
1294
  if (claim.of !== undefined)
@@ -1072,8 +1457,42 @@ class DeclarationReader {
1072
1457
  /** `takesString` per signature, and `scopeMembers` per type and home: the same types recur across receivers. */
1073
1458
  takesStringRead = new Map();
1074
1459
  scopeMembersRead = new Map();
1075
- /** Handler-parameter members `HANDLER_MEMBER_CAP` dropped in the package being listed. */
1076
- handlersDropped = 0;
1460
+ /**
1461
+ * The surface being listed's `handler_types` (carrick#2977): its entries in
1462
+ * id order; per type object and export name, the id it was given (0: the
1463
+ * budget left it out); per content key, the id. Reset per surface.
1464
+ */
1465
+ handlerTypes = [];
1466
+ handlerTypeIds = new Map();
1467
+ handlerTypeByContent = new Map();
1468
+ /** The handler parameters the listing's budget left out of the surface being listed (carrick#3016). */
1469
+ handlerParamsLeftOut = 0;
1470
+ /** The surface being listed's nameable type exports, by the symbol each names (carrick#2977). */
1471
+ typeExportNames = new Map();
1472
+ /** Handler-parameter members the rest of this `listSurface` call may still list (carrick#3016). */
1473
+ handlerBudget = HANDLER_LISTING_BUDGET;
1474
+ /** The surface being listed lists `types[]` widened (`types: true`, carrick#3050). */
1475
+ listTypes = false;
1476
+ /** The receivers being outlined are the surface's own: the types they return are candidates for `types[]`. */
1477
+ collectTypes = false;
1478
+ /** The types `types[]` may list, by declaring symbol, in discovery order. */
1479
+ typeCandidates = new Map();
1480
+ /** `idOfSymbol` per symbol, for the surface being listed. */
1481
+ typeIds = new Map();
1482
+ /** The surface's listed value exports, by target symbol: what a namespace-declared type's export is. */
1483
+ exportTargets = new Map();
1484
+ /** The packages the specifier names (itself and its types package): a type declared there is the specifier's own. */
1485
+ specifierHome = new Set();
1486
+ /** The export whose receivers are being outlined: the export a module-declared type is listed under. */
1487
+ typeContext = '';
1488
+ /** `types[]` entries the budget left out of the surface being listed. */
1489
+ typesLeftOut = 0;
1490
+ /** The receivers the surface lists, with the type each is built at: what `receiver_types` maps (carrick#3051). */
1491
+ receiverSources = [];
1492
+ /** Begin one `listSurface` call: its specifiers share `handlerBudget` handler-parameter members. */
1493
+ startListing(handlerBudget) {
1494
+ this.handlerBudget = handlerBudget;
1495
+ }
1077
1496
  /** Whether the package being listed lists each signature's `result_candidates`. */
1078
1497
  listResultCandidates = false;
1079
1498
  /** The service root as given and as a realpath, longest first: what a listing prints as `<root>`. */
@@ -1445,7 +1864,7 @@ class DeclarationReader {
1445
1864
  return unchecked('claim_invalid');
1446
1865
  }
1447
1866
  const name = claim.name;
1448
- if (name !== undefined && 'bound' in name)
1867
+ if (name !== undefined && !('arg' in name))
1449
1868
  return unchecked('claim_invalid');
1450
1869
  if (claim.method_key) {
1451
1870
  const at = claim.method_key.arg;
@@ -1795,6 +2214,8 @@ class DeclarationReader {
1795
2214
  * its return, the collection, is read as a plain scope's is.
1796
2215
  */
1797
2216
  judgeScope(receiver, claim, built) {
2217
+ if (claim.form === 'decorate')
2218
+ return { outcome: this.decorateScopeOutcome(receiver, claim) };
1798
2219
  if ((claim.runs === undefined) !== (claim.yields === undefined))
1799
2220
  return { outcome: unchecked('claim_invalid') };
1800
2221
  if (claim.mounts !== undefined && claim.runs !== undefined)
@@ -2050,9 +2471,28 @@ class DeclarationReader {
2050
2471
  * scope.
2051
2472
  */
2052
2473
  judgeOp(receiver, claim, rules) {
2053
- const method = this.methodOutcome(claim, rules);
2474
+ // Amendment 7, part 3 (carrick#3047): the form says how the service
2475
+ // writes the op, and the op kinds a form belongs to.
2476
+ const form = claim.form ?? 'call';
2477
+ if (form === 'new' && claim.op !== 'send' && claim.op !== 'request')
2478
+ return unchecked('claim_invalid');
2479
+ if (form === 'decorate' && claim.op !== 'receive')
2480
+ return unchecked('claim_invalid');
2481
+ // `returns` judges the handler a receive op registers.
2482
+ if (claim.returns !== undefined && (claim.op !== 'receive' || claim.handler === undefined)) {
2483
+ return unchecked('claim_invalid');
2484
+ }
2485
+ if (form === 'set') {
2486
+ // Only the server's reply is read by assignment so far.
2487
+ return rules.namelessSends === true ? this.setOutcome(receiver, claim) : unchecked('part_unbuilt');
2488
+ }
2489
+ const method = this.methodOutcome(claim, rules, receiver);
2054
2490
  if (method)
2055
2491
  return method;
2492
+ // The routing name is the property path walked on a proxy (carrick#3048).
2493
+ if (claim.name !== undefined && 'bound' in claim.name && claim.name.bound === 'path') {
2494
+ return this.pathOutcome(receiver, claim);
2495
+ }
2056
2496
  // What a handler is handed is read on a receive op's handler only.
2057
2497
  if (claim.yields !== undefined && (claim.op !== 'receive' || claim.handler === undefined)) {
2058
2498
  return unchecked('claim_invalid');
@@ -2071,16 +2511,53 @@ class DeclarationReader {
2071
2511
  return unchecked('claim_invalid');
2072
2512
  }
2073
2513
  let nameSlot;
2514
+ let documentSlot;
2515
+ let refSlot;
2074
2516
  if (name === undefined) {
2075
2517
  nameSlot = undefined;
2076
2518
  }
2519
+ else if ('literal' in name) {
2520
+ // A name the library fixes: nothing on the call to read.
2521
+ if (typeof name.literal !== 'string' || name.literal.length === 0)
2522
+ return unchecked('claim_invalid');
2523
+ }
2077
2524
  else if ('bound' in name) {
2078
- const bound = name.bound === 'maker' ? receiver.makerBindsName : name.bound === 'scope' ? receiver.scoped : receiver.keyBound === true;
2079
- if (!bound)
2080
- return failed('name_unbound');
2525
+ if (name.bound === 'export') {
2526
+ // The export is the name (a decorator, a handler class): a receive op with a handler.
2527
+ if (claim.op !== 'receive' || claim.handler === undefined)
2528
+ return unchecked('claim_invalid');
2529
+ }
2530
+ else if (name.bound === 'maker' || name.bound === 'scope' || name.bound === 'key') {
2531
+ const bound = name.bound === 'maker' ? receiver.makerBindsName : name.bound === 'scope' ? receiver.scoped : receiver.keyBound === true;
2532
+ if (!bound)
2533
+ return failed('name_unbound');
2534
+ }
2535
+ else {
2536
+ // `unbuiltPart` answers before this is reached.
2537
+ return unchecked('part_unbuilt');
2538
+ }
2539
+ }
2540
+ else if ('arg' in name) {
2541
+ const slot = { arg: name.arg, ...(name.key === undefined ? {} : { key: name.key }) };
2542
+ if (name.document !== undefined && name.ref !== undefined)
2543
+ return unchecked('claim_invalid');
2544
+ if (name.document !== undefined) {
2545
+ if (name.document !== 'graphql')
2546
+ return unchecked('claim_invalid');
2547
+ documentSlot = slot;
2548
+ }
2549
+ else if (name.ref !== undefined) {
2550
+ if (name.ref !== 'function' && name.ref !== 'class')
2551
+ return unchecked('claim_invalid');
2552
+ refSlot = slot;
2553
+ }
2554
+ else {
2555
+ nameSlot = name;
2556
+ }
2081
2557
  }
2082
2558
  else {
2083
- nameSlot = name;
2559
+ // `unbuiltPart` answers before this is reached.
2560
+ return unchecked('part_unbuilt');
2084
2561
  }
2085
2562
  const runs = claim.runs;
2086
2563
  const boundRuns = runs?.bound === 'maker' ? runs : undefined;
@@ -2088,6 +2565,8 @@ class DeclarationReader {
2088
2565
  return failed('runs_unbound');
2089
2566
  const layout = this.layout({
2090
2567
  name: nameSlot,
2568
+ document: documentSlot,
2569
+ ref: refSlot,
2091
2570
  payload: claim.payload,
2092
2571
  handler: claim.handler,
2093
2572
  ack: claim.ack,
@@ -2097,7 +2576,7 @@ class DeclarationReader {
2097
2576
  });
2098
2577
  if ('failure' in layout)
2099
2578
  return layout.failure;
2100
- const callee = this.ownCallee(receiver, claim.path ?? [], claim.member, 'call');
2579
+ const callee = this.ownCallee(receiver, claim.path ?? [], claim.member, form === 'new' ? 'new' : 'call');
2101
2580
  if ('failure' in callee)
2102
2581
  return callee.failure;
2103
2582
  const labels = claim.key_labels ?? {};
@@ -2109,12 +2588,25 @@ class DeclarationReader {
2109
2588
  let requestDropped;
2110
2589
  const bodyMembers = [];
2111
2590
  for (const signature of callee.signatures) {
2591
+ // A decorator is read before the slots: it takes the path, and has no handler.
2592
+ if (form === 'decorate') {
2593
+ const given = this.decoratorOutcome(signature, 'method');
2594
+ if (given) {
2595
+ best = furthest(best, 1, given);
2596
+ continue;
2597
+ }
2598
+ }
2112
2599
  let result = this.messageSignatureOutcome(signature, layout.value, labels);
2113
2600
  if (result.rank === Infinity && claim.yields !== undefined) {
2114
2601
  const given = this.yieldsOutcome(signature, claim.handler, claim.yields, receiver);
2115
2602
  if (given)
2116
2603
  result = { rank: 5, outcome: given };
2117
2604
  }
2605
+ if (result.rank === Infinity && claim.returns !== undefined) {
2606
+ const given = this.returnsOutcome(signature, claim.handler, claim.returns);
2607
+ if (given)
2608
+ result = { rank: 5, outcome: given };
2609
+ }
2118
2610
  if (result.rank === Infinity && claim.request !== undefined) {
2119
2611
  const read = this.requestOutcome(signature, claim.handler, claim.request, bodyMembers);
2120
2612
  if (read?.verdict === 'failed' && read.reason === 'request_member_missing') {
@@ -2149,6 +2641,203 @@ class DeclarationReader {
2149
2641
  ...(requestDropped === undefined ? {} : { requestDropped }),
2150
2642
  };
2151
2643
  }
2644
+ /**
2645
+ * `form: set` on a send (amendment 7 part 3, carrick#3047): the service
2646
+ * assigns the reply (`ctx.body = x`). `member` is a property that `path`
2647
+ * reaches, settable by {@link settable}, and the assigned value is the
2648
+ * call's only argument, `{ arg: 0 }`. It names nothing on the wire and takes
2649
+ * no other part. Verified, it carries the property's declarations as the
2650
+ * members `labelledMembers` keys its `sets` by.
2651
+ */
2652
+ setOutcome(receiver, claim) {
2653
+ const alone = claim.name === undefined &&
2654
+ claim.handler === undefined &&
2655
+ claim.ack === undefined &&
2656
+ claim.runs === undefined &&
2657
+ claim.yields === undefined &&
2658
+ claim.request === undefined &&
2659
+ claim.returns === undefined &&
2660
+ claim.options === undefined &&
2661
+ claim.method === undefined &&
2662
+ claim.method_key === undefined &&
2663
+ claim.method_default === undefined &&
2664
+ claim.base === undefined;
2665
+ const payload = claim.payload;
2666
+ if (!alone || claim.member === null || payload?.arg !== 0 || payload.key !== undefined) {
2667
+ return unchecked('claim_invalid');
2668
+ }
2669
+ const walked = this.walkHops(receiver, claim.path ?? []);
2670
+ if ('failure' in walked)
2671
+ return walked.failure;
2672
+ const step = this.ownMember(walked.holder, claim.member);
2673
+ if ('failure' in step)
2674
+ return step.failure;
2675
+ const reason = this.settable(walked.holder, step.property);
2676
+ if (reason !== 'ok')
2677
+ return failed(reason);
2678
+ const declarations = this.declarationsOf({
2679
+ signatures: [],
2680
+ named: { property: step.property, holder: walked.holder.type },
2681
+ });
2682
+ const members = step.property.declarations ?? [];
2683
+ return { verdict: 'verified', ...(declarations.length > 0 ? { declarations } : {}), members };
2684
+ }
2685
+ /**
2686
+ * `form: decorate` (amendment 7 part 3): the call returns a decorator of
2687
+ * the kind the claim needs, else `decorate_not_decorator`. A route's is a
2688
+ * method decorator, a type that is called with the target, the key and a
2689
+ * descriptor (`MethodDecorator`); a class decorator, which a scope's is,
2690
+ * takes the class alone (`ClassDecorator`). A parameter or property
2691
+ * decorator is neither: it takes a third argument that is not a
2692
+ * descriptor, or none.
2693
+ */
2694
+ decoratorOutcome(signature, kind) {
2695
+ const returned = this.checker.getReturnTypeOfSignature(signature);
2696
+ const parts = this.parts(returned);
2697
+ if (parts.some(part => this.isOpenTop(part)))
2698
+ return unchecked('decorate_untyped');
2699
+ const decorates = (handed) => {
2700
+ const parameters = handed.getParameters();
2701
+ if (kind === 'class') {
2702
+ const required = parameters.filter(parameter => (parameter.flags & ts.SymbolFlags.Optional) === 0 &&
2703
+ !(parameter.valueDeclaration !== undefined &&
2704
+ ts.isParameter(parameter.valueDeclaration) &&
2705
+ parameter.valueDeclaration.dotDotDotToken !== undefined));
2706
+ return parameters.length >= 1 && required.length <= 1;
2707
+ }
2708
+ if (parameters.length < 3)
2709
+ return false;
2710
+ const descriptor = this.checker.getTypeOfSymbol(parameters[2]);
2711
+ return (descriptor.flags & (ts.TypeFlags.Object | ts.TypeFlags.Intersection | ts.TypeFlags.Any)) !== 0;
2712
+ };
2713
+ return parts.some(part => part.getCallSignatures().some(decorates)) ? undefined : failed('decorate_not_decorator');
2714
+ }
2715
+ /**
2716
+ * A scope with `form: decorate`: a class decorator whose `name` slot takes
2717
+ * a string and whose call returns a class decorator; the names it is given
2718
+ * prefix the ops of the class's methods. The call is the export's own when
2719
+ * `member` is the export's name (a decorator is imported, not read off an
2720
+ * object), else `member` of what `path` reaches. It builds no receiver, so
2721
+ * the claim holds no overloads, as a scope that binds through a
2722
+ * parameter does not.
2723
+ */
2724
+ decorateScopeOutcome(receiver, claim) {
2725
+ if (claim.name === undefined ||
2726
+ claim.collects !== undefined ||
2727
+ claim.runs !== undefined ||
2728
+ claim.yields !== undefined ||
2729
+ claim.mounts !== undefined) {
2730
+ return unchecked('claim_invalid');
2731
+ }
2732
+ const layout = this.layout({ name: claim.name });
2733
+ if ('failure' in layout)
2734
+ return layout.failure;
2735
+ const own = (claim.path?.length ?? 0) === 0 && claim.member === receiver.exportName;
2736
+ const callee = this.ownCallee(receiver, claim.path ?? [], own ? null : claim.member, 'call');
2737
+ if ('failure' in callee)
2738
+ return callee.failure;
2739
+ let best;
2740
+ for (const signature of callee.signatures) {
2741
+ const given = this.decoratorOutcome(signature, 'class');
2742
+ if (given) {
2743
+ best = furthest(best, 1, given);
2744
+ continue;
2745
+ }
2746
+ const result = this.messageSignatureOutcome(signature, layout.value, claim.key_labels ?? {});
2747
+ if (result.rank === Infinity) {
2748
+ const declarations = this.declarationsOf(callee);
2749
+ return declarations.length > 0 ? { verdict: 'verified', declarations } : VERIFIED;
2750
+ }
2751
+ best = furthest(best, result.rank, result.outcome);
2752
+ }
2753
+ return best.outcome;
2754
+ }
2755
+ /**
2756
+ * `returns` on a receive op (amendment 7 part 3): what the handler at the
2757
+ * `handler` slot returns is the reply. The function the signature takes
2758
+ * there declares a return, awaited, with a part that is not `void`,
2759
+ * `undefined` or `never` (`replyReturn`). Only void is `returns_void`
2760
+ * (the framework drops it); `any` or `unknown` says nothing
2761
+ * (`returns_untyped`). With `result`, the return holds that part of the
2762
+ * reply as a `result` claim reads a call's return (`result_not_candidate`).
2763
+ * Undefined when it holds.
2764
+ */
2765
+ returnsOutcome(signature, handler, returns) {
2766
+ let declared = this.keyParameterAt(signature, handler.arg);
2767
+ if (declared !== undefined && handler.key !== undefined) {
2768
+ const property = this.declaredProperty(declared, handler.key);
2769
+ declared = property ? this.checker.getTypeOfSymbol(property) : undefined;
2770
+ }
2771
+ if (declared === undefined)
2772
+ return failed('param_missing');
2773
+ const slot = this.throughConditional(this.throughConstraint(declared));
2774
+ if (slot === VARIADIC)
2775
+ return unchecked('returns_untyped');
2776
+ const own = signature.typeParameters ?? [];
2777
+ let open = false;
2778
+ let missed = false;
2779
+ for (const part of this.parts(slot)) {
2780
+ for (const handed of part.getCallSignatures()) {
2781
+ const read = this.replyReturn(this.checker.getReturnTypeOfSignature(handed), own);
2782
+ if (read === 'typed') {
2783
+ if (returns.result === undefined)
2784
+ return undefined;
2785
+ const candidates = resultCandidatesOfReturn(this.checker, this.checker.getReturnTypeOfSignature(handed), [
2786
+ ...own,
2787
+ ...(handed.getTypeParameters() ?? []),
2788
+ ]);
2789
+ if (candidates !== undefined && holdsResult(candidates, returns.result))
2790
+ return undefined;
2791
+ missed = true;
2792
+ }
2793
+ else if (read === 'open') {
2794
+ open = true;
2795
+ }
2796
+ }
2797
+ }
2798
+ if (missed)
2799
+ return failed('result_not_candidate');
2800
+ return open ? unchecked('returns_untyped') : failed('returns_void');
2801
+ }
2802
+ /**
2803
+ * What a handler's declared return says about the reply: `typed` when a part
2804
+ * is not `void`, `undefined`, `null` or `never` (a concrete type, or one the
2805
+ * route's own type parameters decide), `open` when the best part is `any`
2806
+ * or `unknown`, `void` when none is. A promise is read through to what it
2807
+ * resolves to.
2808
+ */
2809
+ replyReturn(type, own, depth = 0) {
2810
+ if (depth > 4)
2811
+ return 'open';
2812
+ const NOTHING = ts.TypeFlags.Void | ts.TypeFlags.Undefined | ts.TypeFlags.Never | ts.TypeFlags.Null;
2813
+ let open = false;
2814
+ for (const part of type.isUnion() ? type.types : [type]) {
2815
+ if (part.flags & NOTHING)
2816
+ continue;
2817
+ if (part.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown)) {
2818
+ open = true;
2819
+ continue;
2820
+ }
2821
+ const resolved = this.checker.getAwaitedType(part);
2822
+ if (resolved !== undefined && resolved !== part) {
2823
+ const read = this.replyReturn(resolved, own, depth + 1);
2824
+ if (read === 'typed')
2825
+ return 'typed';
2826
+ if (read === 'open')
2827
+ open = true;
2828
+ continue;
2829
+ }
2830
+ // A return the route's own type parameters decide (`R`, `Reply[K]`) is typed per route.
2831
+ if (part.flags & (ts.TypeFlags.Conditional | ts.TypeFlags.IndexedAccess | ts.TypeFlags.TypeParameter)) {
2832
+ if (own.some(parameter => this.mentions(part, parameter)))
2833
+ return 'typed';
2834
+ open = true;
2835
+ continue;
2836
+ }
2837
+ return 'typed';
2838
+ }
2839
+ return open ? 'open' : 'void';
2840
+ }
2152
2841
  /**
2153
2842
  * Where a verified op or scope's member is declared, as position rows spell
2154
2843
  * it (`decl_file`, `decl_line`): the declaration the call row names for the
@@ -2181,7 +2870,9 @@ class DeclarationReader {
2181
2870
  * carrying `method`, `method_key`, `options`, `method_default` or `base` is
2182
2871
  * `claim_invalid`, as before. With them:
2183
2872
  * - `method` is the member's own name, upper-cased (ASCII only), and a
2184
- * method word: `get` registers or sends GET (`method_not_member_verb`);
2873
+ * method word: `get` registers or sends GET (`method_not_member_verb`).
2874
+ * A `decorate` op whose member is null (the export's own call) takes the
2875
+ * export's name: `Get` registers GET;
2185
2876
  * - `method_key` is where the method sits, a slot that accepts a string or
2186
2877
  * a method literal (read with the call's other parts);
2187
2878
  * - `method_default` is a method word (`method_not_word`): beside
@@ -2192,18 +2883,28 @@ class DeclarationReader {
2192
2883
  * Undefined when the fields hold so far; their slots are read with the
2193
2884
  * call's other parts.
2194
2885
  */
2195
- methodOutcome(claim, rules) {
2196
- const words = rules.methods;
2197
- // A procedure named by its key (#2474 R6a): a receive op with a handler
2198
- // whose label states its method, a route word. The member names the
2199
- // procedure kind (`query`), not a verb, so it need not equal the method.
2886
+ methodOutcome(claim, rules, receiver) {
2887
+ const words = methodWords(claim, rules);
2888
+ // A procedure named by its key (#2474 R6a): a receive op with a handler.
2889
+ // On http the label states its method, a route word, and the member names
2890
+ // the procedure kind (`query`), not a verb, so it need not equal the
2891
+ // method. On rpc and graphql the kind is the method, so the label may
2892
+ // leave it out, and states it as the member's own name (carrick#3048).
2200
2893
  if (claim.name !== undefined && 'bound' in claim.name && claim.name.bound === 'key') {
2201
- if (!words || claim.op !== 'receive' || claim.handler === undefined || claim.method === undefined) {
2894
+ if (!words || claim.op !== 'receive' || claim.handler === undefined)
2202
2895
  return unchecked('claim_invalid');
2203
- }
2204
2896
  if (claim.method_key !== undefined || claim.method_default !== undefined || claim.options !== undefined) {
2205
2897
  return unchecked('claim_invalid');
2206
2898
  }
2899
+ if (claim.protocol === 'rpc' || claim.protocol === 'graphql') {
2900
+ if (claim.method === undefined)
2901
+ return undefined;
2902
+ return claim.member !== null && claim.method === asciiUpperCase(claim.member) && words.has(claim.method)
2903
+ ? undefined
2904
+ : failed('method_not_member_verb');
2905
+ }
2906
+ if (claim.method === undefined)
2907
+ return unchecked('claim_invalid');
2207
2908
  return words.has(claim.method) ? undefined : failed('method_not_word');
2208
2909
  }
2209
2910
  if (!words) {
@@ -2220,7 +2921,9 @@ class DeclarationReader {
2220
2921
  return unchecked('claim_invalid');
2221
2922
  }
2222
2923
  if (claim.method !== undefined) {
2223
- if (claim.member === null || claim.method !== asciiUpperCase(claim.member) || !words.has(claim.method)) {
2924
+ // A decorator export is its own verb (`@Get`): the export, when the call is the export's.
2925
+ const verb = claim.member ?? (claim.form === 'decorate' ? (receiver.exportName ?? null) : null);
2926
+ if (verb === null || claim.method !== asciiUpperCase(verb) || !words.has(claim.method)) {
2224
2927
  return failed('method_not_member_verb');
2225
2928
  }
2226
2929
  }
@@ -2228,6 +2931,87 @@ class DeclarationReader {
2228
2931
  return failed('method_not_word');
2229
2932
  return undefined;
2230
2933
  }
2934
+ /**
2935
+ * `name: { bound: 'path' }` (amendment 7, carrick#3048): the routing name is
2936
+ * the property path the service walks on the receiver (`client.a.b.query(x)`),
2937
+ * joined by the name's `join`. That is a recursive proxy of procedures, a
2938
+ * mapped type or an index signature whose members the caller's type argument
2939
+ * names, and not a plain object, whose members are all there is
2940
+ * (`path_not_proxy`). The op's `member` is a callable property the home
2941
+ * packages declare at a leaf (`member_missing`), and a `payload` slot is a
2942
+ * parameter of one of its signatures. The op takes no handler, ack or other
2943
+ * name part.
2944
+ */
2945
+ pathOutcome(receiver, claim) {
2946
+ if (claim.member === null ||
2947
+ (claim.path?.length ?? 0) > 0 ||
2948
+ claim.handler !== undefined ||
2949
+ claim.ack !== undefined ||
2950
+ claim.runs !== undefined ||
2951
+ claim.yields !== undefined) {
2952
+ return unchecked('claim_invalid');
2953
+ }
2954
+ const apparent = this.checker.getApparentType(this.checker.getNonNullableType(receiver.type));
2955
+ const proxied = this.parts(apparent).some(part => ((part.objectFlags ?? 0) & ts.ObjectFlags.Mapped) !== 0 ||
2956
+ this.checker.getIndexInfosOfType(part).length > 0);
2957
+ if (!proxied)
2958
+ return failed('path_not_proxy');
2959
+ const found = [];
2960
+ for (const file of this.program.getSourceFiles()) {
2961
+ if (!this.isOwnFile(file, receiver.home))
2962
+ continue;
2963
+ const visit = (node) => {
2964
+ if ((ts.isPropertySignature(node) || ts.isMethodSignature(node)) &&
2965
+ ts.isIdentifier(node.name) &&
2966
+ node.name.text === claim.member &&
2967
+ this.checker.getTypeAtLocation(node).getCallSignatures().length > 0) {
2968
+ found.push(node);
2969
+ }
2970
+ ts.forEachChild(node, visit);
2971
+ };
2972
+ visit(file);
2973
+ }
2974
+ if (found.length === 0)
2975
+ return failed('member_missing');
2976
+ const payload = claim.payload;
2977
+ if (payload !== undefined &&
2978
+ !found.some(declaration => this.checker
2979
+ .getTypeAtLocation(declaration)
2980
+ .getCallSignatures()
2981
+ .some(signature => this.parameterAt(signature, payload.arg) !== undefined))) {
2982
+ return failed('payload_missing');
2983
+ }
2984
+ return { verdict: 'verified', members: found };
2985
+ }
2986
+ /**
2987
+ * A `document: 'graphql'` name slot: it accepts a string, or a document type
2988
+ * by its name (`DOCUMENT_TYPES`), on some part of the declared type.
2989
+ */
2990
+ documentFailure(declared) {
2991
+ const slot = this.throughConditional(this.throughConstraint(declared));
2992
+ if (this.acceptsString(slot))
2993
+ return undefined;
2994
+ if (slot !== VARIADIC) {
2995
+ const parts = this.parts(slot).flatMap(part => (part.isIntersection() ? part.types : [part]));
2996
+ const named = parts.some(part => typeSymbols(part).some(symbol => symbol !== undefined && DOCUMENT_TYPES.has(symbol.getName())));
2997
+ if (named)
2998
+ return undefined;
2999
+ }
3000
+ return this.slotFailure(slot, 'name_not_document');
3001
+ }
3002
+ /** A `ref` name slot: a function or a class, so every part has a call or a construct signature. */
3003
+ refFailure(declared) {
3004
+ const slot = this.throughConditional(this.throughConstraint(declared));
3005
+ if (slot === VARIADIC)
3006
+ return unchecked('member_untyped');
3007
+ const parts = this.parts(slot);
3008
+ if (parts.length === 0 || parts.some(part => this.isOpenTop(part) || this.isUnconstrained(part))) {
3009
+ return unchecked('member_untyped');
3010
+ }
3011
+ return parts.every(part => part.getCallSignatures().length > 0 || part.getConstructSignatures().length > 0)
3012
+ ? undefined
3013
+ : failed('ref_not_callable');
3014
+ }
2231
3015
  /**
2232
3016
  * `runs: { bound: 'maker', arg, key }`: some overload the instance's maker
2233
3017
  * holds on takes a function with a declared signature there (the function
@@ -2261,11 +3045,12 @@ class DeclarationReader {
2261
3045
  return failure.verdict === 'failed' ? failed(reason) : unchecked(reason);
2262
3046
  }
2263
3047
  /**
2264
- * `yields: { param, export, side }` on a receive op or a scope: some
3048
+ * `yields: { param, export, side, package? }` on a receive op or a scope: some
2265
3049
  * signature of the function this overload takes declares a parameter at
2266
3050
  * `param` whose type is either
2267
- * - the package's own export named `export` (a class, or the interface an
2268
- * instance has), declared in the receiver's home packages; or
3051
+ * - the export named `export` (a class, or the interface an instance has),
3052
+ * declared in the receiver's home packages, or in `package` (and its
3053
+ * `@types` package) when the claim names one (carrick#3046); or
2269
3054
  * - when `export` is the maker whose own call made the instance the claim
2270
3055
  * is read on (`madeBy`, carrick#2663): that instance, compared by
2271
3056
  * declaration (`handsInstance`), since a factory's result has no export
@@ -2276,6 +3061,10 @@ class DeclarationReader {
2276
3061
  yieldsOutcome(signature, handler, yields, receiver) {
2277
3062
  if (yields.side !== 'client' && yields.side !== 'server')
2278
3063
  return failed('yields_side_invalid');
3064
+ // The handed type is declared in `yields.package` (and its `@types` package) when it names one.
3065
+ const yieldsHome = yields.package === undefined
3066
+ ? receiver.home
3067
+ : new Set([packageNameOf(yields.package), typesPackageOf(packageNameOf(yields.package))]);
2279
3068
  let declared = this.keyParameterAt(signature, handler.arg);
2280
3069
  if (declared !== undefined && handler.key !== undefined) {
2281
3070
  const property = this.declaredProperty(declared, handler.key);
@@ -2292,7 +3081,7 @@ class DeclarationReader {
2292
3081
  if (given === undefined || given === VARIADIC)
2293
3082
  continue;
2294
3083
  const named = typeSymbols(given).some(symbol => symbol?.getName() === yields.export &&
2295
- (symbol.declarations ?? []).some(declaration => this.isOwnFile(declaration.getSourceFile(), receiver.home)));
3084
+ (symbol.declarations ?? []).some(declaration => this.isOwnFile(declaration.getSourceFile(), yieldsHome)));
2296
3085
  if (named)
2297
3086
  return undefined;
2298
3087
  if (yields.export === receiver.madeBy && this.handsInstance(given, receiver, signature.typeParameters ?? [])) {
@@ -2389,7 +3178,9 @@ class DeclarationReader {
2389
3178
  * overload whose parameter there is that literal, or a key of the map a
2390
3179
  * `keyof` constraint reads. The claim carries no slot, so every parameter
2391
3180
  * is read. A name the library emits itself only ever removes rows, so this
2392
- * verdict is for the record.
3181
+ * verdict is for the record. The runtime's own emitter members also
3182
+ * reserve the names the runtime gives every emitter, which no declaration
3183
+ * states (`RUNTIME_EMITTER_EVENTS`, carrick#3032).
2393
3184
  */
2394
3185
  judgeReserved(receiver, claim) {
2395
3186
  const callee = this.ownCallee(receiver, claim.path ?? [], claim.member, 'call');
@@ -2402,8 +3193,14 @@ class DeclarationReader {
2402
3193
  return VERIFIED;
2403
3194
  }
2404
3195
  }
3196
+ if (RUNTIME_EMITTER_EVENTS.includes(claim.name) && this.isRuntimeEmitterProperty(callee.named?.property))
3197
+ return VERIFIED;
2405
3198
  return failed('reserved_not_declared');
2406
3199
  }
3200
+ /** The property is a member of the runtime's own emitter (`isRuntimeEmitterMember`). */
3201
+ isRuntimeEmitterProperty(property) {
3202
+ return property !== undefined && isRuntimeEmitterMember(property, file => this.packageOf(file));
3203
+ }
2407
3204
  /**
2408
3205
  * Where a claim's parts sit. Two parts at one position (`send(data)` read
2409
3206
  * as both the name and the payload), or a part at a position another part
@@ -2458,6 +3255,15 @@ class DeclarationReader {
2458
3255
  return { rank: 1, outcome: this.slotFailure(declared, 'method_not_string') };
2459
3256
  continue;
2460
3257
  }
3258
+ if (part === 'document' || part === 'ref') {
3259
+ const declared = this.keyParameterAt(signature, arg);
3260
+ if (declared === undefined)
3261
+ return { rank: 1, outcome: failed('param_missing') };
3262
+ const bad = part === 'document' ? this.documentFailure(declared) : this.refFailure(declared);
3263
+ if (bad)
3264
+ return { rank: 1, outcome: bad };
3265
+ continue;
3266
+ }
2461
3267
  if (part !== 'name' && part !== 'base' && part !== 'prefix')
2462
3268
  continue;
2463
3269
  const declared = this.keyParameterAt(signature, arg);
@@ -2526,6 +3332,14 @@ class DeclarationReader {
2526
3332
  break;
2527
3333
  }
2528
3334
  const type = this.checker.getTypeOfSymbol(property);
3335
+ if (part === 'document' || part === 'ref') {
3336
+ const bad = part === 'document' ? this.documentFailure(type) : this.refFailure(type);
3337
+ if (bad) {
3338
+ failure = { rank: 3, outcome: bad };
3339
+ break;
3340
+ }
3341
+ continue;
3342
+ }
2529
3343
  if ((part === 'name' || part === 'base' || part === 'prefix') && !this.acceptsString(this.throughConditional(type))) {
2530
3344
  failure = { rank: 3, outcome: this.slotFailure(this.throughConditional(type), 'key_not_string') };
2531
3345
  break;
@@ -2930,21 +3744,12 @@ class DeclarationReader {
2930
3744
  return bound;
2931
3745
  }
2932
3746
  /**
2933
- * The callee of a message claim: the claim's member `path` walked from the
2934
- * receiver hop by hop (`client.tasks.trigger`), then `member` of the object
2935
- * reached (or that object itself, when null), called (`call`) or
2936
- * constructed (`new`), through the signatures its home packages declare.
2937
- * A member, or every signature, that only another package declares (the
2938
- * runtime's event emitter a library class extends, a base class from a
2939
- * dependency) is `member_inherited`. Each hop must be a home member too;
2940
- * the object it reaches adds the packages that declare its type to the
2941
- * home, never the runtime's, and a hop whose type says nothing has no
2942
- * members to read (`member_untyped`).
3747
+ * The object a claim's member `path` reaches from the receiver, hop by hop,
3748
+ * each a home member whose type says something; `named` is the last member
3749
+ * the path reaches, with the type it is read on (carrick#2654).
2943
3750
  */
2944
- ownCallee(receiver, hops, member, form) {
3751
+ walkHops(receiver, hops) {
2945
3752
  let holder = receiver;
2946
- // The last member the path reaches, with the type it is read on: the
2947
- // symbol the call row names (carrick#2654).
2948
3753
  let named;
2949
3754
  for (const hop of hops) {
2950
3755
  const step = this.ownMember(holder, hop);
@@ -2956,6 +3761,26 @@ class DeclarationReader {
2956
3761
  named = { property: step.property, holder: holder.type };
2957
3762
  holder = { type, home: this.homeOf(receiver.pkg, typeSymbols(type), holder.home) };
2958
3763
  }
3764
+ return { holder, named };
3765
+ }
3766
+ /**
3767
+ * The callee of a message claim: the claim's member `path` walked from the
3768
+ * receiver hop by hop (`client.tasks.trigger`), then `member` of the object
3769
+ * reached (or that object itself, when null), called (`call`) or
3770
+ * constructed (`new`), through the signatures its home packages declare.
3771
+ * A member, or every signature, that only another package declares (the
3772
+ * runtime's event emitter a library class extends, a base class from a
3773
+ * dependency) is `member_inherited`. Each hop must be a home member too;
3774
+ * the object it reaches adds the packages that declare its type to the
3775
+ * home, never the runtime's, and a hop whose type says nothing has no
3776
+ * members to read (`member_untyped`).
3777
+ */
3778
+ ownCallee(receiver, hops, member, form) {
3779
+ const walked = this.walkHops(receiver, hops);
3780
+ if ('failure' in walked)
3781
+ return walked;
3782
+ const holder = walked.holder;
3783
+ let named = walked.named;
2959
3784
  let type = holder.type;
2960
3785
  // A member of a base the holder binds with its own type (see `isBoundByOwnType`).
2961
3786
  let boundBase = false;
@@ -3081,7 +3906,7 @@ class DeclarationReader {
3081
3906
  * `built` answers the probe's no-argument build of a receiver an export
3082
3907
  * makes, resolved, when the probe holds one.
3083
3908
  */
3084
- listPackage(pkg, probe, maxEntries, only, options, built) {
3909
+ listPackage(pkg, probe, maxEntries, only, options, typeExports, built) {
3085
3910
  this.setPackage(pkg);
3086
3911
  // Runtime modules on: a `node:` specifier is listed from the runtime's
3087
3912
  // types package, as the message roles read it.
@@ -3108,11 +3933,31 @@ class DeclarationReader {
3108
3933
  };
3109
3934
  // Handler-parameter members (carrick#2674) take nothing from the main cap,
3110
3935
  // so the listing, `truncated` and the hash are the ones the lister gave
3111
- // before handlers were listed; each parameter has a cap of its own
3112
- // (`HANDLER_MEMBER_CAP`, carrick#2966).
3113
- this.handlersDropped = 0;
3936
+ // before handlers were listed; each parameter type has a cap of its own
3937
+ // (`HANDLER_MEMBER_CAP`, carrick#2966), and is listed once per surface in
3938
+ // `handler_types` (carrick#2977).
3114
3939
  this.listResultCandidates = options.resultCandidates === true;
3115
3940
  const withHandlers = options.handlers === true;
3941
+ this.listTypes = options.types === true;
3942
+ this.collectTypes = this.listTypes;
3943
+ this.typeCandidates.clear();
3944
+ this.typeIds.clear();
3945
+ this.typesLeftOut = 0;
3946
+ this.receiverSources = [];
3947
+ this.typeContext = '';
3948
+ this.specifierHome = this.homeOf(pkg, []);
3949
+ this.exportTargets = new Map(exported.map(each => [each.target, each.name]).reverse());
3950
+ if (withHandlers || this.listTypes) {
3951
+ this.handlerTypes = [];
3952
+ this.handlerTypeIds.clear();
3953
+ this.handlerTypeByContent.clear();
3954
+ this.handlerParamsLeftOut = 0;
3955
+ this.typeExportNames = new Map();
3956
+ for (const each of [...typeExports].sort((a, b) => byName(a.name, b.name))) {
3957
+ if (!this.typeExportNames.has(each.symbol))
3958
+ this.typeExportNames.set(each.symbol, each.name);
3959
+ }
3960
+ }
3116
3961
  // Four passes: every export and receiver, then every member name, then the
3117
3962
  // members of each handler's parameters (carrick#2674; only when asked,
3118
3963
  // carrick#2966), then signatures.
@@ -3135,6 +3980,10 @@ class DeclarationReader {
3135
3980
  if (!take())
3136
3981
  return;
3137
3982
  const home = this.homeOf(pkg, [target, ...typeSymbols(receiverType)]);
3983
+ this.typeContext = name;
3984
+ if (receiverName.startsWith('instance:'))
3985
+ this.noteType(receiverType);
3986
+ this.receiverSources.push({ export: name, receiver: receiverName, type: receiverType });
3138
3987
  const receiver = this.outlineReceiver(pkg, receiverName, receiverType, home, take, names, handlers, fills);
3139
3988
  entry.receivers.push(receiver);
3140
3989
  if (receiverName.startsWith('instance:')) {
@@ -3163,10 +4012,283 @@ class DeclarationReader {
3163
4012
  fill();
3164
4013
  this.listScopeReceivers(pkg, instances, maxEntries, withHandlers, built);
3165
4014
  surface.truncated = dropped;
4015
+ this.collectTypes = false;
4016
+ if (withHandlers)
4017
+ surface.handler_types = this.handlerTypes;
4018
+ if (withHandlers || this.listTypes)
4019
+ surface.types = this.listTypeReceivers(pkg, typeExports, maxEntries);
3166
4020
  if (withHandlers)
3167
- surface.handlers_truncated = this.handlersDropped;
4021
+ surface.handler_params_left_out = this.handlerParamsLeftOut;
4022
+ if (this.listTypes) {
4023
+ surface.types_left_out = this.typesLeftOut;
4024
+ surface.receiver_types = this.receiverTypes(surface.types ?? []);
4025
+ }
3168
4026
  return surface;
3169
4027
  }
4028
+ /**
4029
+ * The sixth pass (carrick#2977): each type export a `handler_types` entry
4030
+ * names, sorted by name, as the one receiver `type`, built at its declared
4031
+ * type-parameter defaults as the verifier builds it (`typeBuildLine`), and
4032
+ * outlined as any receiver is, without handlers. Everything it lists draws
4033
+ * on one budget of its own, so `truncated` and the hash are unchanged.
4034
+ */
4035
+ listTypeReceivers(pkg, typeExports, maxEntries) {
4036
+ if (this.listTypes)
4037
+ return this.listWidenedTypes(pkg, typeExports, maxEntries);
4038
+ const named = [...new Set(this.handlerTypes.flatMap(entry => (entry.export === undefined ? [] : [entry.export])))].sort(byName);
4039
+ let budget = maxEntries;
4040
+ const take = () => budget > 0 && (budget--, true);
4041
+ const names = [];
4042
+ const fills = [];
4043
+ const listed = [];
4044
+ for (const name of named) {
4045
+ const built = typeExports.find(each => each.name === name);
4046
+ if (built === undefined || !take())
4047
+ continue;
4048
+ const home = this.homeOf(pkg, [built.symbol, ...typeSymbols(built.type)]);
4049
+ listed.push({
4050
+ export: name,
4051
+ receivers: [this.outlineReceiver(pkg, TYPE_RECEIVER, built.type, home, take, names, [], fills)],
4052
+ });
4053
+ }
4054
+ for (const run of names)
4055
+ run();
4056
+ for (const fill of fills)
4057
+ fill();
4058
+ return listed;
4059
+ }
4060
+ /**
4061
+ * `types[]` under `types: true` (carrick#3050): every exported class, and
4062
+ * every type the surface's makers, members and handlers reach that has a
4063
+ * receiver id (`idOfSymbol`), sorted by id, each outlined as any receiver
4064
+ * is, with the properties a service may assign. A `type` id reads the type
4065
+ * the probe built at its defaults; any other, the type as reached when
4066
+ * that is its defaults (`atDefaults`). One budget of its own: an entry it
4067
+ * leaves out is counted in `types_left_out`.
4068
+ */
4069
+ listWidenedTypes(pkg, typeExports, maxEntries) {
4070
+ const builtBySymbol = new Map(typeExports.map(each => [each.symbol, each]).reverse());
4071
+ const entries = new Map();
4072
+ for (const built of typeExports) {
4073
+ if ((built.symbol.flags & ts.SymbolFlags.Class) === 0 || entries.has(built.symbol))
4074
+ continue;
4075
+ entries.set(built.symbol, { id: TYPE_RECEIVER, export: built.name, symbol: built.symbol, type: built.type });
4076
+ }
4077
+ for (const candidate of this.typeCandidates.values()) {
4078
+ if (entries.has(candidate.symbol))
4079
+ continue;
4080
+ if (candidate.id !== TYPE_RECEIVER) {
4081
+ entries.set(candidate.symbol, candidate);
4082
+ continue;
4083
+ }
4084
+ const built = builtBySymbol.get(candidate.symbol);
4085
+ if (built !== undefined)
4086
+ entries.set(candidate.symbol, { ...candidate, type: built.type });
4087
+ }
4088
+ const ordered = [...entries.values()].sort((a, b) => byName(a.id, b.id) || byName(a.export, b.export));
4089
+ let budget = maxEntries;
4090
+ const take = () => budget > 0 && (budget--, true);
4091
+ const names = [];
4092
+ const fills = [];
4093
+ const listed = [];
4094
+ for (const entry of ordered) {
4095
+ if (!take()) {
4096
+ this.typesLeftOut += 1;
4097
+ continue;
4098
+ }
4099
+ const home = this.homeOf(pkg, [entry.symbol, ...typeSymbols(entry.type)]);
4100
+ const receiver = this.outlineReceiver(pkg, entry.id, entry.type, home, take, names, [], fills);
4101
+ const settable = this.settableOf(pkg, entry.type, home);
4102
+ if (settable.length > 0)
4103
+ receiver.settable = settable;
4104
+ listed.push({ export: entry.export, receivers: [receiver] });
4105
+ }
4106
+ for (const run of names)
4107
+ run();
4108
+ for (const fill of fills)
4109
+ fill();
4110
+ return listed;
4111
+ }
4112
+ /**
4113
+ * `receiver_types` (carrick#3051): per export, per receiver the surface
4114
+ * lists, the receiver ids of `types[]` that the receiver's built type and
4115
+ * its base types are declared by, sorted. A receiver whose type has no
4116
+ * listed id is left out, and so is one whose type is a class constructor
4117
+ * (an export's own `export` receiver is the constructor, not an instance).
4118
+ * `type` and `type:<Path>` are relative to an export: they are told of a
4119
+ * receiver only on that export; a `type:<module>#<Path>` is the same on any.
4120
+ */
4121
+ receiverTypes(types) {
4122
+ const keyOf = (id, exportName) => (id.includes('#') ? id : `${exportName}\0${id}`);
4123
+ const listed = new Set(types.flatMap(entry => entry.receivers.map(each => keyOf(each.receiver, entry.export))));
4124
+ const map = {};
4125
+ for (const source of this.receiverSources) {
4126
+ const found = new Set();
4127
+ const visit = (type, depth) => {
4128
+ const symbol = type.aliasSymbol ?? type.getSymbol();
4129
+ if (symbol !== undefined && (symbol.flags & ts.SymbolFlags.Class) !== 0 && type.getConstructSignatures().length > 0)
4130
+ return;
4131
+ const id = symbol === undefined || type.isUnion() ? undefined : this.idOfSymbol(symbol);
4132
+ if (id !== undefined && listed.has(keyOf(id.id, id.export ?? source.export)) && (id.id.includes('#') || id.export === source.export)) {
4133
+ found.add(id.id);
4134
+ }
4135
+ const target = (type.objectFlags ?? 0) & ts.ObjectFlags.Reference ? type.target : type;
4136
+ if (depth >= RECEIVER_BASE_DEPTH || !((target.objectFlags ?? 0) & ts.ObjectFlags.ClassOrInterface))
4137
+ return;
4138
+ for (const base of this.checker.getBaseTypes(target))
4139
+ visit(base, depth + 1);
4140
+ };
4141
+ visit(source.type, 0);
4142
+ if (found.size === 0)
4143
+ continue;
4144
+ (map[source.export] ??= {})[source.receiver] = [...found].sort(byName);
4145
+ }
4146
+ return map;
4147
+ }
4148
+ /** The properties of a type a service may assign, depth 1, by name (`settable`). */
4149
+ settableOf(pkg, type, home) {
4150
+ const holder = this.surfaceHolder(pkg, type, home);
4151
+ const listed = [];
4152
+ for (const property of sortedByName(this.namedProperties(type))) {
4153
+ if (this.settable(holder, property) !== 'ok')
4154
+ continue;
4155
+ listed.push({
4156
+ name: property.getName(),
4157
+ type: this.printed(this.checker.getTypeOfSymbol(property)),
4158
+ own: !('failure' in this.ownMember(holder, property.getName())),
4159
+ });
4160
+ }
4161
+ return listed;
4162
+ }
4163
+ /**
4164
+ * Whether a service may assign `property` of `holder`, as a reply body is
4165
+ * set (`ctx.body = x`): a property, not a method or a function-typed one
4166
+ * (`set_not_property`); not readonly and not get-only (`set_readonly`); its
4167
+ * declared type open, `unknown` or an unconstrained type parameter
4168
+ * (`set_not_open`), which is what tells a body from a setter such as a
4169
+ * status. No member name is read.
4170
+ */
4171
+ settable(holder, property) {
4172
+ const read = this.declaredProperty(holder.type, property.getName()) ?? property;
4173
+ const type = this.checker.getTypeOfSymbol(read);
4174
+ if ((read.flags & ts.SymbolFlags.Method) !== 0 ||
4175
+ this.parts(type).some(part => part.getCallSignatures().length > 0 || part.getConstructSignatures().length > 0)) {
4176
+ return 'set_not_property';
4177
+ }
4178
+ const declarations = read.declarations ?? [];
4179
+ const getOnly = (read.flags & ts.SymbolFlags.GetAccessor) !== 0 && (read.flags & ts.SymbolFlags.SetAccessor) === 0;
4180
+ if (getOnly ||
4181
+ (declarations.length > 0 &&
4182
+ declarations.every(declaration => (ts.getCombinedModifierFlags(declaration) & ts.ModifierFlags.Readonly) !== 0))) {
4183
+ return 'set_readonly';
4184
+ }
4185
+ return this.isOpenBody(type) ? 'ok' : 'set_not_open';
4186
+ }
4187
+ /**
4188
+ * Note a type for `types[]` when it has a receiver id (carrick#3050), under
4189
+ * the export being read. A type seen at other than its type-parameter
4190
+ * defaults is not noted, unless its id says the probe builds it (`type`).
4191
+ */
4192
+ noteType(type) {
4193
+ if (!this.listTypes || type.isUnion() || (type.flags & ts.TypeFlags.TypeParameter) !== 0)
4194
+ return;
4195
+ const symbol = type.aliasSymbol ?? type.getSymbol();
4196
+ if (symbol === undefined || this.typeCandidates.has(symbol))
4197
+ return;
4198
+ const id = this.idOfSymbol(symbol);
4199
+ if (id === undefined || (id.id !== TYPE_RECEIVER && !this.atDefaults(type, symbol)))
4200
+ return;
4201
+ this.typeCandidates.set(symbol, { id: id.id, export: id.export ?? this.typeContext, symbol, type });
4202
+ }
4203
+ /** A type a signature returns, awaited and without null, noted for `types[]`. */
4204
+ noteReturn(signature) {
4205
+ const returned = this.checker.getNonNullableType(this.checker.getReturnTypeOfSignature(signature));
4206
+ this.noteType(this.checker.getNonNullableType(this.checker.getAwaitedType(returned) ?? returned));
4207
+ }
4208
+ /** `type` is `symbol` read at its declared type-parameter defaults: it has none, or its arguments are exactly the defaults. */
4209
+ atDefaults(type, symbol) {
4210
+ const declaration = (symbol.declarations ?? []).find((each) => (ts.isInterfaceDeclaration(each) || ts.isTypeAliasDeclaration(each) || ts.isClassDeclaration(each)) &&
4211
+ (each.typeParameters?.length ?? 0) > 0);
4212
+ if (declaration === undefined)
4213
+ return true;
4214
+ const args = type.aliasSymbol === symbol
4215
+ ? type.aliasTypeArguments ?? []
4216
+ : (type.objectFlags ?? 0) & ts.ObjectFlags.Reference
4217
+ ? this.checker.getTypeArguments(type)
4218
+ : [];
4219
+ return declaration.typeParameters.every((node, index) => {
4220
+ const parameter = this.checker.getTypeAtLocation(node);
4221
+ const fallback = this.checker.getDefaultFromTypeParameter(parameter);
4222
+ return fallback !== undefined && fallback === args[index];
4223
+ });
4224
+ }
4225
+ /**
4226
+ * The receiver id of a class, interface or alias (amendment 7), or
4227
+ * undefined when it has none. Declared in the specifier's own packages:
4228
+ * `type` when the specifier exports it (the export), `type:<Path>` when an
4229
+ * export's namespace declares it (that export). Declared in another
4230
+ * installed package: `type:<module>#<Path>`, the module as a service
4231
+ * imports it (`@types/x` is `x`; an ambient `declare module 'm'` is `m`),
4232
+ * whichever specifier re-exports it. Anonymous types, the default
4233
+ * library's and the runtime's types have none.
4234
+ */
4235
+ idOfSymbol(symbol) {
4236
+ const known = this.typeIds.get(symbol);
4237
+ if (known !== undefined)
4238
+ return known ?? undefined;
4239
+ const found = this.readIdOfSymbol(symbol);
4240
+ this.typeIds.set(symbol, found ?? null);
4241
+ return found;
4242
+ }
4243
+ readIdOfSymbol(symbol) {
4244
+ if ((symbol.flags & (ts.SymbolFlags.Class | ts.SymbolFlags.Interface | ts.SymbolFlags.TypeAlias)) === 0)
4245
+ return undefined;
4246
+ const declarations = symbol.declarations ?? [];
4247
+ if (declarations.length === 0 || !IDENTIFIER.test(symbol.getName()))
4248
+ return undefined;
4249
+ if (declarations.some(declaration => this.program.isSourceFileDefaultLibrary(declaration.getSourceFile())))
4250
+ return undefined;
4251
+ const first = declarations[0];
4252
+ // The namespaces around the declaration, outermost first.
4253
+ const containers = [];
4254
+ for (let node = first.parent; node !== undefined; node = node.parent) {
4255
+ if (ts.isModuleDeclaration(node))
4256
+ containers.unshift(node);
4257
+ }
4258
+ if (declarations.some(declaration => this.isOwnFile(declaration.getSourceFile(), this.specifierHome))) {
4259
+ const exported = this.typeExportNames.get(symbol);
4260
+ if (exported !== undefined)
4261
+ return { id: TYPE_RECEIVER, export: exported };
4262
+ const outer = containers[0] === undefined ? undefined : this.checker.getSymbolAtLocation(containers[0].name);
4263
+ const owner = outer === undefined ? undefined : this.exportTargets.get(outer);
4264
+ if (owner === undefined || !containers.every(each => ts.isIdentifier(each.name)))
4265
+ return undefined;
4266
+ const names = [...containers.slice(1).map(each => each.name.text), symbol.getName()];
4267
+ return { id: `type:${names.join('.')}`, export: owner };
4268
+ }
4269
+ const owner = this.packageOf(first.getSourceFile());
4270
+ if (owner === undefined || RUNTIME_TYPE_PACKAGES.has(owner))
4271
+ return undefined;
4272
+ let module = importedNameOf(owner);
4273
+ let names = containers.filter(each => ts.isIdentifier(each.name)).map(each => each.name.text);
4274
+ const ambient = containers.findIndex(each => ts.isStringLiteral(each.name));
4275
+ if (ambient >= 0) {
4276
+ module = containers[ambient].name.text;
4277
+ names = containers.slice(ambient + 1).map(each => each.name.text);
4278
+ }
4279
+ else if (names.length > 0 && this.isExportEqualsTarget(first.getSourceFile(), names[0])) {
4280
+ // The namespace a module exports whole is the module itself.
4281
+ names = names.slice(1);
4282
+ }
4283
+ return { id: `type:${module}#${[...names, symbol.getName()].join('.')}` };
4284
+ }
4285
+ /** The file says `export = name`. */
4286
+ isExportEqualsTarget(file, name) {
4287
+ return file.statements.some(statement => ts.isExportAssignment(statement) &&
4288
+ statement.isExportEquals === true &&
4289
+ ts.isIdentifier(statement.expression) &&
4290
+ statement.expression.text === name);
4291
+ }
3170
4292
  /**
3171
4293
  * The fifth pass (carrick#2774): each own member of an instance receiver
3172
4294
  * whose call returns the object routes are registered on lists it as
@@ -3196,6 +4318,9 @@ class DeclarationReader {
3196
4318
  if (type === undefined || !take())
3197
4319
  continue;
3198
4320
  const home = this.homeOf(pkg, [source.target, ...typeSymbols(type)]);
4321
+ this.typeContext = source.export;
4322
+ this.noteType(type);
4323
+ this.receiverSources.push({ export: source.export, receiver: id, type });
3199
4324
  member.scope_receiver = this.outlineReceiver(pkg, id, type, home, take, names, handlers, fills);
3200
4325
  }
3201
4326
  }
@@ -3215,8 +4340,11 @@ class DeclarationReader {
3215
4340
  this.setPackage(pkg);
3216
4341
  const moduleRead = 'namespace' in probe ? this.readModule(pkg, probe.namespace, true) : undefined;
3217
4342
  if (moduleRead?.reason)
3218
- return [];
3219
- return (this.listedExports(probe, only, moduleRead?.globalFile) ?? [])
4343
+ return { makers: [], types: [], classes: [] };
4344
+ const readable = 'namespace' in probe && !moduleRead?.globalFile;
4345
+ const types = readable ? this.typeExportCandidates(probe.namespace, false) : [];
4346
+ const classes = readable ? this.typeExportCandidates(probe.namespace, true) : [];
4347
+ const makers = (this.listedExports(probe, only, moduleRead?.globalFile) ?? [])
3220
4348
  .filter(({ type }) => !this.isOpenTop(type))
3221
4349
  .map(({ name, target, type }) => {
3222
4350
  const makers = this.makers(pkg, target, type);
@@ -3227,6 +4355,33 @@ class DeclarationReader {
3227
4355
  };
3228
4356
  })
3229
4357
  .filter(({ receivers }) => receivers.length > 0);
4358
+ return { makers, types, classes };
4359
+ }
4360
+ /**
4361
+ * The type-only exports of a specifier a handler's parameter may be
4362
+ * (carrick#2977 decision 7), sorted by name: an interface or a type alias
4363
+ * with no value meaning, every type parameter defaulted, so the probe can
4364
+ * build it with no type argument. Every one, whatever `only` names: the
4365
+ * value exports a caller wants hand these types to their handlers. A
4366
+ * superset: the listing names one only when a parameter is that
4367
+ * declaration and it is declared in the handing receiver's home.
4368
+ */
4369
+ typeExportCandidates(namespace, classes) {
4370
+ const moduleSymbol = this.checker.getSymbolAtLocation(namespace.moduleSpecifier);
4371
+ if (!moduleSymbol)
4372
+ return [];
4373
+ const names = [];
4374
+ for (const symbol of this.checker.getExportsOfModule(moduleSymbol)) {
4375
+ const target = symbol.flags & ts.SymbolFlags.Alias ? this.checker.getAliasedSymbol(symbol) : symbol;
4376
+ const wanted = classes
4377
+ ? (target.flags & ts.SymbolFlags.Class) !== 0 && symbol.getName() !== 'default'
4378
+ : (target.flags & ts.SymbolFlags.Value) === 0 &&
4379
+ (target.flags & (ts.SymbolFlags.Interface | ts.SymbolFlags.TypeAlias)) !== 0;
4380
+ if (IDENTIFIER.test(symbol.getName()) && !this.checker.isUnknownSymbol(target) && wanted && typeParametersDefaulted(target)) {
4381
+ names.push(symbol.getName());
4382
+ }
4383
+ }
4384
+ return names.sort(byName);
3230
4385
  }
3231
4386
  /**
3232
4387
  * The `R>scope:m` receivers an export's `instance:` makers may have
@@ -3498,6 +4653,7 @@ class DeclarationReader {
3498
4653
  outlineReceiver(pkg, receiverName, type, home, take, names, handlers, fills) {
3499
4654
  const receiver = { receiver: receiverName, members: [] };
3500
4655
  const holder = this.surfaceHolder(pkg, type, home);
4656
+ const context = this.typeContext;
3501
4657
  // The receiver's own call and construct signatures, as a claim with a
3502
4658
  // null member reads them.
3503
4659
  const call = this.ownCallee(holder, [], null, 'call');
@@ -3522,12 +4678,28 @@ class DeclarationReader {
3522
4678
  const own = 'signatures' in callee;
3523
4679
  const member = { name: property.getName(), own, signatures: [] };
3524
4680
  receiver.members.push(member);
4681
+ if (this.collectTypes) {
4682
+ this.typeContext = context;
4683
+ for (const signature of own ? callee.signatures : library)
4684
+ this.noteReturn(signature);
4685
+ }
3525
4686
  handlers.push(() => {
3526
- const listed = this.listHandlers(own ? callee.signatures : library);
4687
+ this.typeContext = context;
4688
+ const listed = this.listHandlers(own ? callee.signatures : library, home);
3527
4689
  if (listed.length > 0)
3528
4690
  member.handlers = listed;
3529
4691
  });
3530
- fills.push(() => (member.signatures = this.listSignatures(own ? callee.signatures : library, holder.type, take)));
4692
+ fills.push(() => {
4693
+ member.signatures = this.listSignatures(own ? callee.signatures : library, holder.type, take);
4694
+ // The runtime's own emitter members take the names the runtime
4695
+ // gives every emitter, besides the ones a signature spells.
4696
+ if (!RUNTIME_MODULE.test(pkg) || !this.isRuntimeEmitterProperty(property))
4697
+ return;
4698
+ const spelled = new Set(member.signatures.flatMap(s => s.params.flatMap(p => p.literals ?? [])));
4699
+ const events = RUNTIME_EMITTER_EVENTS.filter(name => !spelled.has(name));
4700
+ if (events.length > 0)
4701
+ member.runtime_events = events;
4702
+ });
3531
4703
  }
3532
4704
  });
3533
4705
  return receiver;
@@ -3539,14 +4711,14 @@ class DeclarationReader {
3539
4711
  * A parameter that declares no member lists nothing, and so does a handler
3540
4712
  * none of whose parameters do.
3541
4713
  */
3542
- listHandlers(signatures) {
4714
+ listHandlers(signatures, home) {
3543
4715
  const listed = [];
3544
4716
  const seen = new Set();
3545
4717
  const add = (arg, key, slot) => {
3546
4718
  const place = JSON.stringify([arg, key ?? null]);
3547
4719
  if (seen.has(place))
3548
4720
  return;
3549
- const params = this.listHandlerParams(slot);
4721
+ const params = this.listHandlerParams(slot, home);
3550
4722
  if (params.length === 0)
3551
4723
  return;
3552
4724
  seen.add(place);
@@ -3578,8 +4750,13 @@ class DeclarationReader {
3578
4750
  }
3579
4751
  return listed;
3580
4752
  }
3581
- /** The parameters of a function type's first signature that declare members, each with its members (`handlerMembersOf`). */
3582
- listHandlerParams(handler) {
4753
+ /**
4754
+ * The parameters of a function type's first signature that declare
4755
+ * members, each by the id of its type's entry (`handlerTypeId`). A
4756
+ * parameter whose new entry would pass the listing's budget is left out
4757
+ * and counted (carrick#3016).
4758
+ */
4759
+ listHandlerParams(handler, home) {
3583
4760
  const slot = this.throughConditional(this.throughConstraint(handler));
3584
4761
  if (slot === VARIADIC)
3585
4762
  return [];
@@ -3593,12 +4770,81 @@ class DeclarationReader {
3593
4770
  const type = this.checker.getTypeOfSymbol(parameter);
3594
4771
  if (this.namedProperties(type).length === 0)
3595
4772
  return;
3596
- const { members, dropped } = this.handlerMembersOf(type);
3597
- this.handlersDropped += dropped;
3598
- listed.push({ param: index, name: parameter.getName(), type: this.printed(type), members });
4773
+ const id = this.handlerTypeId(type, home);
4774
+ if (id === 0) {
4775
+ this.handlerParamsLeftOut += 1;
4776
+ return;
4777
+ }
4778
+ listed.push({ param: index, name: parameter.getName(), type_id: id });
3599
4779
  });
3600
4780
  return listed;
3601
4781
  }
4782
+ /**
4783
+ * The id of a handler parameter's entry in the surface's `handler_types`
4784
+ * (carrick#2977), 0 when the listing's budget leaves it out. One lookup per
4785
+ * parameter by type object and export name; a type object seen for the
4786
+ * first time is keyed by content (its printed type, members and export
4787
+ * name), so equal contents share one entry and a resolved reference is
4788
+ * byte for byte the inline parameter the lister wrote before. Only a new
4789
+ * entry spends the budget: its members are written once.
4790
+ */
4791
+ handlerTypeId(type, home) {
4792
+ let exportName = this.nameableExport(type, home);
4793
+ if (this.listTypes) {
4794
+ // A handed type declared in another package carries its receiver id as
4795
+ // its `export` (carrick#3050); the ones declared in the home are as
4796
+ // they were.
4797
+ this.noteType(type);
4798
+ const symbol = type.aliasSymbol ?? type.getSymbol();
4799
+ const id = symbol === undefined || type.isUnion() ? undefined : this.idOfSymbol(symbol);
4800
+ if (id !== undefined && id.id.includes('#'))
4801
+ exportName = id.id;
4802
+ }
4803
+ let byExport = this.handlerTypeIds.get(type);
4804
+ if (byExport === undefined)
4805
+ this.handlerTypeIds.set(type, (byExport = new Map()));
4806
+ const known = byExport.get(exportName);
4807
+ if (known !== undefined)
4808
+ return known;
4809
+ const { members, dropped } = this.handlerMembersOf(type);
4810
+ const printed = this.printed(type);
4811
+ const content = JSON.stringify([printed, members, exportName]);
4812
+ let id = this.handlerTypeByContent.get(content);
4813
+ if (id === undefined) {
4814
+ if (members.length > this.handlerBudget) {
4815
+ id = 0;
4816
+ }
4817
+ else {
4818
+ this.handlerBudget -= members.length;
4819
+ id = this.handlerTypes.length + 1;
4820
+ const entry = { id, type: printed, members, dropped };
4821
+ if (exportName !== null)
4822
+ entry.export = exportName;
4823
+ this.handlerTypes.push(entry);
4824
+ }
4825
+ this.handlerTypeByContent.set(content, id);
4826
+ }
4827
+ byExport.set(exportName, id);
4828
+ return id;
4829
+ }
4830
+ /**
4831
+ * The type export of the surface being listed that a handler parameter's
4832
+ * type is (carrick#2977 decision 7): the same symbol (its alias's, then its
4833
+ * own), never the same name, with a declaration in `home`, the packages of
4834
+ * the receiver whose member hands it, as `yieldsOutcome` reads a `yields`.
4835
+ */
4836
+ nameableExport(type, home) {
4837
+ if (this.typeExportNames.size === 0)
4838
+ return null;
4839
+ for (const symbol of [type.aliasSymbol, type.getSymbol()]) {
4840
+ const name = symbol === undefined ? undefined : this.typeExportNames.get(symbol);
4841
+ if (name !== undefined &&
4842
+ (symbol.declarations ?? []).some(declaration => this.isOwnFile(declaration.getSourceFile(), home))) {
4843
+ return name;
4844
+ }
4845
+ }
4846
+ return null;
4847
+ }
3602
4848
  /**
3603
4849
  * A handler parameter's declared members by path, down to
3604
4850
  * `HANDLER_MEMBER_DEPTH`, at most `HANDLER_MEMBER_CAP` of them (carrick#2966).
@@ -4229,6 +5475,15 @@ const HANDLER_MEMBER_DEPTH = 2;
4229
5475
  * order, so this must stay at least that.
4230
5476
  */
4231
5477
  const HANDLER_MEMBER_CAP = 500;
5478
+ /**
5479
+ * The most handler-parameter members one `listSurface` call lists, across all
5480
+ * its specifiers (carrick#3016). The answer is one JSON line and a string
5481
+ * passes V8's limit at about 512 MiB; a member costs about 150 bytes, so this
5482
+ * keeps the handlers near 75 MB beside an export listing of tens of MB. A
5483
+ * server framework handing 50 distinct request types to thousands of members
5484
+ * listed 8.99 million of them (1.3 GB) before it.
5485
+ */
5486
+ const HANDLER_LISTING_BUDGET = 500_000;
4232
5487
  const PRINT_FLAGS = ts.NodeBuilderFlags.AllowUniqueESSymbolType |
4233
5488
  ts.NodeBuilderFlags.UseAliasDefinedOutsideCurrentScope |
4234
5489
  ts.NodeBuilderFlags.IgnoreErrors |
@@ -4242,7 +5497,23 @@ const TYPE_PRINTER = ts.createPrinter({ removeComments: true });
4242
5497
  function printTypeNode(node) {
4243
5498
  return TYPE_PRINTER.printNode(ts.EmitHint.Unspecified, node, undefined);
4244
5499
  }
5500
+ /** The type exports a listing builds with the probe: the type-only ones, and with `types: true` the exported classes (carrick#3050). */
5501
+ function typeNamesOf(read, options) {
5502
+ return options.types === true ? [...read.types, ...read.classes].sort(byName) : [...read.types];
5503
+ }
4245
5504
  /** Code-unit order on names. */
5505
+ /** Every type parameter of an interface, type alias or class has a default, in some declaration of it (carrick#2977). */
5506
+ function typeParametersDefaulted(symbol) {
5507
+ const declarations = (symbol.declarations ?? []).filter((declaration) => ts.isInterfaceDeclaration(declaration) || ts.isTypeAliasDeclaration(declaration) || ts.isClassDeclaration(declaration));
5508
+ if (declarations.length === 0)
5509
+ return false;
5510
+ const count = Math.max(...declarations.map(declaration => declaration.typeParameters?.length ?? 0));
5511
+ for (let index = 0; index < count; index++) {
5512
+ if (!declarations.some(declaration => declaration.typeParameters?.[index]?.default !== undefined))
5513
+ return false;
5514
+ }
5515
+ return true;
5516
+ }
4246
5517
  function byName(a, b) {
4247
5518
  return a < b ? -1 : a > b ? 1 : 0;
4248
5519
  }
@@ -4268,6 +5539,14 @@ function isNamedPackage(specifier, packageName) {
4268
5539
  const named = packageNameOf(specifier);
4269
5540
  return packageName === named || packageName === typesPackageOf(named);
4270
5541
  }
5542
+ /** The name a service imports a package by: `@types/scope__name` is `@scope/name`, `@types/name` is `name`. */
5543
+ function importedNameOf(installed) {
5544
+ if (!installed.startsWith('@types/'))
5545
+ return installed;
5546
+ const bare = installed.slice('@types/'.length);
5547
+ const scoped = /^([^_]+)__(.+)$/.exec(bare);
5548
+ return scoped ? `@${scoped[1]}/${scoped[2]}` : bare;
5549
+ }
4271
5550
  /** The `@types` package of a package name (`@types/scope__name` for a scoped one). */
4272
5551
  function typesPackageOf(named) {
4273
5552
  return `@types/${named.startsWith('@') ? named.slice(1).replace('/', '__') : named}`;