carrick 0.3.134 → 0.3.136

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.
@@ -259,6 +259,12 @@ function sortedDeclarations(declarations) {
259
259
  }
260
260
  let probeSequence = 0;
261
261
  const NO_MODULE_GRAPH = { packageDirectoryOf: () => undefined, resolveModule: () => undefined };
262
+ /**
263
+ * Test instrumentation, never on the wire: how many times the lister built a
264
+ * handler parameter's members and printed a type, since the caller last
265
+ * reset them (carrick#2977).
266
+ */
267
+ export const surfaceReadCounts = { handlerMemberBuilds: 0, typePrints: 0 };
262
268
  export class LibraryClaimsVerifier {
263
269
  project;
264
270
  graph;
@@ -281,6 +287,7 @@ export class LibraryClaimsVerifier {
281
287
  receiver: check.receiver,
282
288
  verdict: 'verified',
283
289
  ...(outcome.declarations?.length ? { declarations: outcome.declarations } : {}),
290
+ ...(outcome.requestDropped === undefined ? {} : { request_dropped: outcome.requestDropped }),
284
291
  }
285
292
  : {
286
293
  claim_id: check.claim_id,
@@ -587,6 +594,8 @@ export class LibraryClaimsVerifier {
587
594
  const declarations = [];
588
595
  const members = [];
589
596
  const bodyMembers = [];
597
+ // A request one receiver does not hold is dropped for the op (carrick#2968).
598
+ let requestDropped;
590
599
  for (const receiver of receivers.value) {
591
600
  const result = reader.judgeMessage(receiver, check.claim, rules, builtAtDefaults, collectionsOf);
592
601
  if (result.outcome.verdict !== 'verified')
@@ -595,11 +604,14 @@ export class LibraryClaimsVerifier {
595
604
  declarations.push(...(result.outcome.declarations ?? []));
596
605
  members.push(...(result.outcome.members ?? []));
597
606
  bodyMembers.push(...(result.outcome.bodyMembers ?? []));
607
+ requestDropped ??= result.outcome.requestDropped;
598
608
  }
599
609
  const verified = declarations.length > 0 ? { verdict: 'verified', declarations: sortedDeclarations(declarations) } : { ...VERIFIED };
600
610
  if (verified.verdict === 'verified' && members.length > 0)
601
611
  verified.members = members;
602
- if (verified.verdict === 'verified' && bodyMembers.length > 0)
612
+ if (verified.verdict === 'verified' && requestDropped !== undefined)
613
+ verified.requestDropped = requestDropped;
614
+ else if (verified.verdict === 'verified' && bodyMembers.length > 0)
603
615
  verified.bodyMembers = bodyMembers;
604
616
  return { outcome: verified, holding };
605
617
  };
@@ -645,7 +657,11 @@ export class LibraryClaimsVerifier {
645
657
  const observe = (check, outcome) => {
646
658
  if (check.claim.kind !== 'op')
647
659
  return;
648
- const read = outcome.verdict === 'verified' ? 'verified' : `${outcome.verdict} ${outcome.reason}`;
660
+ const read = outcome.verdict !== 'verified'
661
+ ? `${outcome.verdict} ${outcome.reason}`
662
+ : outcome.requestDropped === undefined
663
+ ? 'verified'
664
+ : `verified request_dropped ${outcome.requestDropped}`;
649
665
  outcomes[read] = (outcomes[read] ?? 0) + 1;
650
666
  if (outcome.verdict !== 'verified')
651
667
  return;
@@ -678,9 +694,20 @@ export class LibraryClaimsVerifier {
678
694
  * (`receiverExpression` on the export's `importLine`, read through
679
695
  * `DeclarationReader.returnOf`) and lists from it.
680
696
  *
697
+ * A member of an `instance:` receiver whose call returns another object
698
+ * that routes are registered on lists that object as its `scope_receiver`
699
+ * (carrick#2774), built as the verifier builds a scope step, under a cap of
700
+ * its own and left out of the hash.
701
+ *
702
+ * Each member's handler-parameter members (carrick#2674 S3) are listed
703
+ * only when `options.handlers` is set, and each signature's result
704
+ * candidates (carrick#2817) only when `options.resultCandidates` is
705
+ * (carrick#2966): on a large package either costs more than the rest of the
706
+ * listing.
707
+ *
681
708
  * `surface_sha256` is the full-surface hash (see `fullSurfaceSha256`).
682
709
  */
683
- listSurface(fromDir, packages, maxEntries, only = {}) {
710
+ listSurface(fromDir, packages, maxEntries, only = {}, options = {}) {
684
711
  if (packages.length === 0)
685
712
  return { surfaces: [], surface_sha256: fullSurfaceSha256([]) };
686
713
  // Each specifier twice: as a namespace, which holds its named exports, and
@@ -709,10 +736,12 @@ export class LibraryClaimsVerifier {
709
736
  const buildLines = [];
710
737
  const builtIndex = new Map();
711
738
  packages.forEach((pkg, i) => {
712
- for (const { export: name, receivers } of makers[i]) {
739
+ for (const { export: name, receivers, scopes } of makers[i]) {
713
740
  const local = `__carrick_e${importLines.length}`;
714
741
  importLines.push(probeLine(pkg, name, local));
715
- for (const receiver of receivers) {
742
+ // The scope receivers a maker's members may return (carrick#2774) are
743
+ // built beside the makers, so `listPackage` reads them as it reads those.
744
+ for (const receiver of [...receivers, ...scopes]) {
716
745
  const expression = receiverExpression(local, receiver);
717
746
  if (expression === undefined)
718
747
  continue;
@@ -722,10 +751,14 @@ export class LibraryClaimsVerifier {
722
751
  }
723
752
  });
724
753
  const firstBuild = imports.length + importLines.length;
725
- const surfaces = this.readProbe(fromDir, [...imports, ...importLines, ...buildLines], (checker, reader, file) => packages.map((pkg, i) => reader.listPackage(pkg, probeOf(file, i), maxEntries, only[pkg], (name, receiver) => {
726
- const index = builtIndex.get(builtKey({ package: pkg, export: name }, receiver));
727
- return index === undefined ? undefined : resolvedBuild(checker, file.statements[firstBuild + index]);
728
- })));
754
+ const surfaces = this.readProbe(fromDir, [...imports, ...importLines, ...buildLines], (checker, reader, file) => {
755
+ // One budget for the whole call, spent across its specifiers: the answer is one line.
756
+ reader.startListing(options.maxHandlerMembers ?? HANDLER_LISTING_BUDGET);
757
+ return packages.map((pkg, i) => reader.listPackage(pkg, probeOf(file, i), maxEntries, only[pkg], options, (name, receiver) => {
758
+ const index = builtIndex.get(builtKey({ package: pkg, export: name }, receiver));
759
+ return index === undefined ? undefined : resolvedBuild(checker, file.statements[firstBuild + index]);
760
+ }));
761
+ });
729
762
  return { surfaces, surface_sha256: fullSurfaceSha256(surfaces) };
730
763
  }
731
764
  /** `read` over a probe file holding `lines` in `fromDir`, removed again afterwards. */
@@ -763,8 +796,8 @@ function resolvedBuild(checker, statement) {
763
796
  * array of `[package, exports]` for every surface that listed at least one
764
797
  * export, sorted by `package` (code unit order). A specifier that lists
765
798
  * nothing (unresolved, local, no value exports) is left out, so asking for a
766
- * subpath a version does not have changes nothing. Handler members are not
767
- * hashed. Type text already names
799
+ * subpath a version does not have changes nothing. Handler members, result
800
+ * candidates and scope receivers are not hashed. Type text already names
768
801
  * the request's directory as `<root>`.
769
802
  */
770
803
  export function fullSurfaceSha256(surfaces) {
@@ -772,10 +805,11 @@ export function fullSurfaceSha256(surfaces) {
772
805
  .filter(surface => surface.reason === undefined && surface.exports.length > 0)
773
806
  .map(surface => [surface.package, surface.exports])
774
807
  .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
775
- // A member's `handlers` (carrick#2674) and a signature's `result_candidates`
776
- // (carrick#2817) are out of the hash at every depth, so a package's key does
777
- // not change when the lister learns to list them.
778
- const text = JSON.stringify(listed, (key, value) => key === 'handlers' || key === 'result_candidates' ? undefined : value);
808
+ // A member's `handlers` (carrick#2674), a signature's `result_candidates`
809
+ // (carrick#2817) and a member's `scope_receiver` (carrick#2774) are out of
810
+ // the hash at every depth, so a package's key does not change when the
811
+ // lister learns to list them.
812
+ const text = JSON.stringify(listed, (key, value) => key === 'handlers' || key === 'result_candidates' || key === 'scope_receiver' ? undefined : value);
779
813
  return crypto.createHash('sha256').update(text).digest('hex');
780
814
  }
781
815
  function exportKey(check) {
@@ -928,6 +962,18 @@ function receiverExpression(local, receiver) {
928
962
  text = `${text}${parsed.scope.split('.').map(access).join('')}()`;
929
963
  return text;
930
964
  }
965
+ /**
966
+ * The id of the receiver `member` of the receiver `receiver` returns when
967
+ * called with a path (carrick#2774): `receiver>scope:member`. Undefined for a
968
+ * receiver that is not an instance, or a member name the verifier's grammar
969
+ * does not read back as one scope step.
970
+ */
971
+ function scopeReceiverId(receiver, member) {
972
+ if (!receiver.startsWith('instance:') || receiver.includes('>') || /[>.\s]/.test(member))
973
+ return undefined;
974
+ const id = `${receiver}>scope:${member}`;
975
+ return parseReceiver(id)?.scope === member ? id : undefined;
976
+ }
931
977
  /** The symbols that say who declared a type: its own, its alias's, its parts'. */
932
978
  function typeSymbols(type) {
933
979
  const symbols = [type.getSymbol(), type.aliasSymbol];
@@ -1020,8 +1066,30 @@ class DeclarationReader {
1020
1066
  currentPackage = '';
1021
1067
  /** `declaredProperties` per type, for `currentPackage` (its augmentations decide them). */
1022
1068
  declared = new Map();
1069
+ /**
1070
+ * A handler parameter's listed members per type (`handlerMembersOf`), kept
1071
+ * across every specifier of one package and cleared with `declared` when
1072
+ * the package changes: a member's listing reads that package's
1073
+ * augmentations (carrick#2977).
1074
+ */
1075
+ handlerMembers = new Map();
1076
+ /** `takesString` per signature, and `scopeMembers` per type and home: the same types recur across receivers. */
1077
+ takesStringRead = new Map();
1078
+ scopeMembersRead = new Map();
1079
+ /** Handler-parameter members `HANDLER_MEMBER_CAP` and the listing's budget dropped in the package being listed. */
1080
+ handlersDropped = 0;
1081
+ /** Handler-parameter members the rest of this `listSurface` call may still list (carrick#3016). */
1082
+ handlerBudget = HANDLER_LISTING_BUDGET;
1083
+ /** Begin one `listSurface` call: its specifiers share `handlerBudget` handler-parameter members. */
1084
+ startListing(handlerBudget) {
1085
+ this.handlerBudget = handlerBudget;
1086
+ }
1087
+ /** Whether the package being listed lists each signature's `result_candidates`. */
1088
+ listResultCandidates = false;
1023
1089
  /** The service root as given and as a realpath, longest first: what a listing prints as `<root>`. */
1024
1090
  printedRoots;
1091
+ /** `printed` per type: its text reads nothing but the type and `printedRoots` (carrick#2977). */
1092
+ printedTexts = new Map();
1025
1093
  constructor(program, probe, host, serviceRoot, scanRoot, graph) {
1026
1094
  this.program = program;
1027
1095
  this.probe = probe;
@@ -2045,6 +2113,10 @@ class DeclarationReader {
2045
2113
  const labels = claim.key_labels ?? {};
2046
2114
  let best;
2047
2115
  let held = false;
2116
+ // An overload that holds but for a request member the declarations lack
2117
+ // (carrick#2968): the op stands without its request, unless another
2118
+ // overload holds the request too. Every other request fault fails the op.
2119
+ let requestDropped;
2048
2120
  const bodyMembers = [];
2049
2121
  for (const signature of callee.signatures) {
2050
2122
  let result = this.messageSignatureOutcome(signature, layout.value, labels);
@@ -2055,19 +2127,26 @@ class DeclarationReader {
2055
2127
  }
2056
2128
  if (result.rank === Infinity && claim.request !== undefined) {
2057
2129
  const read = this.requestOutcome(signature, claim.handler, claim.request, bodyMembers);
2130
+ if (read?.verdict === 'failed' && read.reason === 'request_member_missing') {
2131
+ requestDropped = read.reason;
2132
+ continue;
2133
+ }
2058
2134
  if (read)
2059
2135
  result = { rank: 5, outcome: read };
2060
2136
  }
2061
2137
  if (result.rank === Infinity) {
2062
2138
  held = true;
2139
+ requestDropped = undefined;
2063
2140
  break;
2064
2141
  }
2065
2142
  best = furthest(best, result.rank, result.outcome);
2066
2143
  }
2067
- if (!held)
2144
+ if (!held && requestDropped === undefined)
2068
2145
  return best.outcome;
2069
- if (boundRuns)
2070
- return this.boundRunsOutcome(receiver.makerHolding, boundRuns);
2146
+ if (boundRuns) {
2147
+ const ran = this.boundRunsOutcome(receiver.makerHolding, boundRuns);
2148
+ return ran.verdict === 'verified' && requestDropped !== undefined ? { ...ran, requestDropped } : ran;
2149
+ }
2071
2150
  const declarations = this.declarationsOf(callee);
2072
2151
  const members = callee.named
2073
2152
  ? (callee.named.property.declarations ?? [])
@@ -2077,6 +2156,7 @@ class DeclarationReader {
2077
2156
  ...(declarations.length > 0 ? { declarations } : {}),
2078
2157
  ...(members.length > 0 ? { members } : {}),
2079
2158
  ...(bodyMembers.length > 0 ? { bodyMembers } : {}),
2159
+ ...(requestDropped === undefined ? {} : { requestDropped }),
2080
2160
  };
2081
2161
  }
2082
2162
  /**
@@ -3011,7 +3091,7 @@ class DeclarationReader {
3011
3091
  * `built` answers the probe's no-argument build of a receiver an export
3012
3092
  * makes, resolved, when the probe holds one.
3013
3093
  */
3014
- listPackage(pkg, probe, maxEntries, only, built) {
3094
+ listPackage(pkg, probe, maxEntries, only, options, built) {
3015
3095
  this.setPackage(pkg);
3016
3096
  // Runtime modules on: a `node:` specifier is listed from the runtime's
3017
3097
  // types package, as the message roles read it.
@@ -3036,24 +3116,24 @@ class DeclarationReader {
3036
3116
  dropped += 1;
3037
3117
  return false;
3038
3118
  };
3039
- // Handler-parameter members (carrick#2674) have a cap of their own, so they
3040
- // take nothing from the main one: the listing, `truncated` and the hash are
3041
- // the ones the lister gave before handlers were listed.
3042
- let handlerBudget = maxEntries;
3043
- const takeHandler = () => {
3044
- if (handlerBudget <= 0)
3045
- return false;
3046
- handlerBudget -= 1;
3047
- return true;
3048
- };
3119
+ // Handler-parameter members (carrick#2674) take nothing from the main cap,
3120
+ // so the listing, `truncated` and the hash are the ones the lister gave
3121
+ // before handlers were listed; each parameter has a cap of its own
3122
+ // (`HANDLER_MEMBER_CAP`, carrick#2966).
3123
+ this.handlersDropped = 0;
3124
+ this.listResultCandidates = options.resultCandidates === true;
3125
+ const withHandlers = options.handlers === true;
3049
3126
  // Four passes: every export and receiver, then every member name, then the
3050
- // members of each handler's parameters (carrick#2674), then signatures.
3127
+ // members of each handler's parameters (carrick#2674; only when asked,
3128
+ // carrick#2966), then signatures.
3051
3129
  const names = [];
3052
3130
  const handlers = [];
3053
3131
  const fills = [];
3054
3132
  // What the package's default export names: a maker also exported by name
3055
3133
  // under this declaration is imported the same way, so it is read the same.
3056
3134
  const defaultTarget = exported.find(each => each.name === 'default')?.target;
3135
+ // The instance receivers listed, for the scope pass (carrick#2774).
3136
+ const instances = [];
3057
3137
  for (const { name, target, type } of exported) {
3058
3138
  if (!take())
3059
3139
  continue;
@@ -3065,7 +3145,11 @@ class DeclarationReader {
3065
3145
  if (!take())
3066
3146
  return;
3067
3147
  const home = this.homeOf(pkg, [target, ...typeSymbols(receiverType)]);
3068
- entry.receivers.push(this.outlineReceiver(pkg, receiverName, receiverType, home, take, takeHandler, names, handlers, fills));
3148
+ const receiver = this.outlineReceiver(pkg, receiverName, receiverType, home, take, names, handlers, fills);
3149
+ entry.receivers.push(receiver);
3150
+ if (receiverName.startsWith('instance:')) {
3151
+ instances.push({ export: name, target, type: receiverType, home, receiver });
3152
+ }
3069
3153
  };
3070
3154
  receiverOf('export', type);
3071
3155
  for (const maker of this.makers(pkg, target, type)) {
@@ -3082,13 +3166,57 @@ class DeclarationReader {
3082
3166
  }
3083
3167
  for (const run of names)
3084
3168
  run();
3085
- for (const run of handlers)
3086
- run();
3169
+ if (withHandlers)
3170
+ for (const run of handlers)
3171
+ run();
3087
3172
  for (const fill of fills)
3088
3173
  fill();
3174
+ this.listScopeReceivers(pkg, instances, maxEntries, withHandlers, built);
3089
3175
  surface.truncated = dropped;
3176
+ if (withHandlers)
3177
+ surface.handlers_truncated = this.handlersDropped;
3090
3178
  return surface;
3091
3179
  }
3180
+ /**
3181
+ * The fifth pass (carrick#2774): each own member of an instance receiver
3182
+ * whose call returns the object routes are registered on lists it as
3183
+ * `scope_receiver`, outlined as any receiver is. Everything it lists draws
3184
+ * on one budget of its own, spent after every other pass, so the listing
3185
+ * without it, `truncated` and the hash are the ones the lister gave before.
3186
+ * One level: a scope receiver lists no scope receiver of its own.
3187
+ */
3188
+ listScopeReceivers(pkg, sources, maxEntries, withHandlers, built) {
3189
+ let budget = maxEntries;
3190
+ const take = () => budget > 0 && (budget--, true);
3191
+ const names = [];
3192
+ const handlers = [];
3193
+ const fills = [];
3194
+ for (const source of sources) {
3195
+ const holder = this.surfaceHolder(pkg, source.type, source.home);
3196
+ for (const member of source.receiver.members) {
3197
+ const id = member.own ? scopeReceiverId(source.receiver.receiver, member.name) : undefined;
3198
+ if (id === undefined)
3199
+ continue;
3200
+ const callee = this.ownCallee(holder, [], member.name, 'call');
3201
+ if (!('signatures' in callee))
3202
+ continue;
3203
+ if (!callee.signatures.some(signature => this.takesString(signature)))
3204
+ continue;
3205
+ const type = this.scopeTypeOf(callee.signatures, built(source.export, id), source.type, source.home);
3206
+ if (type === undefined || !take())
3207
+ continue;
3208
+ const home = this.homeOf(pkg, [source.target, ...typeSymbols(type)]);
3209
+ member.scope_receiver = this.outlineReceiver(pkg, id, type, home, take, names, handlers, fills);
3210
+ }
3211
+ }
3212
+ for (const run of names)
3213
+ run();
3214
+ if (withHandlers)
3215
+ for (const run of handlers)
3216
+ run();
3217
+ for (const fill of fills)
3218
+ fill();
3219
+ }
3092
3220
  /**
3093
3221
  * The receivers each export of a specifier can make, by receiver id, for
3094
3222
  * the probe statements that build them (see `LibraryClaimsVerifier.listSurface`).
@@ -3100,12 +3228,157 @@ class DeclarationReader {
3100
3228
  return [];
3101
3229
  return (this.listedExports(probe, only, moduleRead?.globalFile) ?? [])
3102
3230
  .filter(({ type }) => !this.isOpenTop(type))
3103
- .map(({ name, target, type }) => ({
3104
- export: name,
3105
- receivers: this.makers(pkg, target, type).map(maker => maker.receiver),
3106
- }))
3231
+ .map(({ name, target, type }) => {
3232
+ const makers = this.makers(pkg, target, type);
3233
+ return {
3234
+ export: name,
3235
+ receivers: makers.map(maker => maker.receiver),
3236
+ scopes: this.scopeCandidates(pkg, target, makers),
3237
+ };
3238
+ })
3107
3239
  .filter(({ receivers }) => receivers.length > 0);
3108
3240
  }
3241
+ /**
3242
+ * The `R>scope:m` receivers an export's `instance:` makers may have
3243
+ * (carrick#2774): for each object type a maker's overloads declare as their
3244
+ * return, each own member that `scopeTypeOf` lists at its declared return.
3245
+ * A superset of the listing, which reads each at the type the probe's build
3246
+ * resolves; the second program builds these so `listPackage` can.
3247
+ */
3248
+ scopeCandidates(pkg, target, makers) {
3249
+ const found = new Set();
3250
+ for (const maker of makers) {
3251
+ if (!maker.receiver.startsWith('instance:'))
3252
+ continue;
3253
+ const types = new Set(maker.signatures.map(sig => this.checker.getReturnTypeOfSignature(sig)));
3254
+ for (const type of types) {
3255
+ if (this.returnSaysNothing(type) || !this.isObjectType(type))
3256
+ continue;
3257
+ const home = this.homeOf(pkg, [target, ...typeSymbols(type)]);
3258
+ for (const name of this.scopeMembers(pkg, type, home)) {
3259
+ const id = scopeReceiverId(maker.receiver, name);
3260
+ if (id !== undefined)
3261
+ found.add(id);
3262
+ }
3263
+ }
3264
+ }
3265
+ return [...found];
3266
+ }
3267
+ /** The members of `type` that list a scope receiver at their declared return, read once per type and home. */
3268
+ scopeMembers(pkg, type, home) {
3269
+ const key = [...home].sort().join('\u0000');
3270
+ let byHome = this.scopeMembersRead.get(type);
3271
+ if (byHome === undefined)
3272
+ this.scopeMembersRead.set(type, (byHome = new Map()));
3273
+ const read = byHome.get(key);
3274
+ if (read !== undefined)
3275
+ return read;
3276
+ const names = [];
3277
+ const holder = this.surfaceHolder(pkg, type, home);
3278
+ for (const property of sortedByName(this.namedProperties(type))) {
3279
+ if (!this.mayScope(property))
3280
+ continue;
3281
+ const callee = this.ownCallee(holder, [], property.getName(), 'call');
3282
+ if ('signatures' in callee && this.scopeTypeOf(callee.signatures, undefined, type, home) !== undefined) {
3283
+ names.push(property.getName());
3284
+ }
3285
+ }
3286
+ byHome.set(key, names);
3287
+ return names;
3288
+ }
3289
+ /** Some library signature of the member takes a string: the cheap superset of what `scopeTypeOf` asks first. */
3290
+ mayScope(property) {
3291
+ return this.librarySignatures(this.checker.getTypeOfSymbol(property), 'call').some(signature => this.takesString(signature));
3292
+ }
3293
+ /**
3294
+ * The object a scope member returns, as the verifier reads a scope step
3295
+ * (carrick#2774): what a route is registered on when the member is called
3296
+ * with a path. Undefined unless:
3297
+ * - some own signature takes a string, positionally or at a key of an
3298
+ * object parameter;
3299
+ * - the returns (at `built`'s defaults, less those that say nothing) are
3300
+ * all object types, none thenable, sharing one declared symbol that is
3301
+ * declared in the receiver's home and has a callable member of its own;
3302
+ * - that symbol and the receiver's share no declaration in the home
3303
+ * (`family`): the receiver itself (`basePath(): this`), a sibling or a
3304
+ * wrapper of one base is a builder's next link, not an object routes
3305
+ * are registered on.
3306
+ * The type is the return of the overload `built` resolves, when that is
3307
+ * one of the signatures that take a string, else the first of them.
3308
+ */
3309
+ scopeTypeOf(signatures, built, receiver, home) {
3310
+ const takers = signatures.filter(signature => this.takesString(signature));
3311
+ const returns = takers
3312
+ .map(signature => ({ signature, type: this.returnOf(signature, built) }))
3313
+ .filter(({ type }) => !this.returnSaysNothing(type));
3314
+ if (returns.length === 0)
3315
+ return undefined;
3316
+ const symbolOf = (type) => type.getSymbol() ?? type.aliasSymbol;
3317
+ const symbol = symbolOf(returns[0].type);
3318
+ if (symbol === undefined)
3319
+ return undefined;
3320
+ // The receiver itself, a sibling of it, or a wrapper built from the same
3321
+ // base (a fluent builder's `.default(x)`) is the same kind of thing, not
3322
+ // an object routes are registered on: abstain.
3323
+ const mine = this.family(receiver, home);
3324
+ if ([...this.family(returns[0].type, home)].some(each => mine.has(each)))
3325
+ return undefined;
3326
+ for (const { type } of returns) {
3327
+ if (!this.isObjectType(type) || symbolOf(type) !== symbol || this.isThenable(type))
3328
+ return undefined;
3329
+ }
3330
+ if (!(symbol.declarations ?? []).some(declaration => this.isOwnFile(declaration.getSourceFile(), home)))
3331
+ return undefined;
3332
+ const chosen = returns.find(({ signature }) => built !== undefined && this.instantiates(built, signature)) ?? returns[0];
3333
+ const callable = this.namedProperties(chosen.type).some(member => this.librarySignatures(this.checker.getTypeOfSymbol(member), 'call').length > 0);
3334
+ return callable ? chosen.type : undefined;
3335
+ }
3336
+ /** The type's own declaration and every base it extends or implements that its home declares. */
3337
+ family(type, home) {
3338
+ const found = new Set();
3339
+ const visit = (each, depth) => {
3340
+ const target = (each.objectFlags ?? 0) & ts.ObjectFlags.Reference ? each.target : each;
3341
+ const symbol = target.getSymbol();
3342
+ if (symbol === undefined || found.has(symbol) || depth > 12)
3343
+ return;
3344
+ if (!(symbol.declarations ?? []).some(declaration => this.isOwnFile(declaration.getSourceFile(), home)))
3345
+ return;
3346
+ found.add(symbol);
3347
+ if ((target.objectFlags ?? 0) & ts.ObjectFlags.ClassOrInterface) {
3348
+ for (const base of this.checker.getBaseTypes(target))
3349
+ visit(base, depth + 1);
3350
+ }
3351
+ };
3352
+ visit(type, 0);
3353
+ return found;
3354
+ }
3355
+ /** A parameter of the signature accepts a string, positionally or at a key of its object. */
3356
+ takesString(signature) {
3357
+ let read = this.takesStringRead.get(signature);
3358
+ if (read === undefined)
3359
+ this.takesStringRead.set(signature, (read = this.readTakesString(signature)));
3360
+ return read;
3361
+ }
3362
+ readTakesString(signature) {
3363
+ const count = signature.getParameters().length;
3364
+ for (let index = 0; index < count; index++) {
3365
+ const slot = this.keyParameterAt(signature, index);
3366
+ if (slot === undefined || slot === VARIADIC)
3367
+ continue;
3368
+ if (this.acceptsString(this.throughConditional(slot)))
3369
+ return true;
3370
+ if (this.isObjectType(slot) && this.handlerFailure(slot) !== undefined) {
3371
+ if (this.listKeys(slot, () => true).some(key => key.accepts_string))
3372
+ return true;
3373
+ }
3374
+ }
3375
+ return false;
3376
+ }
3377
+ /** The type has a callable `then`: awaiting it gives something else. */
3378
+ isThenable(type) {
3379
+ const then = this.checker.getPropertyOfType(type, 'then');
3380
+ return then !== undefined && this.checker.getNonNullableType(this.checker.getTypeOfSymbol(then)).getCallSignatures().length > 0;
3381
+ }
3109
3382
  /**
3110
3383
  * The value exports a specifier lists (every one, or only those `only`
3111
3384
  * names), sorted by name: what its namespace holds, and `default` for a
@@ -3232,7 +3505,7 @@ class DeclarationReader {
3232
3505
  * parameters next (`handlers`), once every name is; its call, construct and
3233
3506
  * member signatures last (`fills`), once every handler is.
3234
3507
  */
3235
- outlineReceiver(pkg, receiverName, type, home, take, takeHandler, names, handlers, fills) {
3508
+ outlineReceiver(pkg, receiverName, type, home, take, names, handlers, fills) {
3236
3509
  const receiver = { receiver: receiverName, members: [] };
3237
3510
  const holder = this.surfaceHolder(pkg, type, home);
3238
3511
  // The receiver's own call and construct signatures, as a claim with a
@@ -3260,7 +3533,7 @@ class DeclarationReader {
3260
3533
  const member = { name: property.getName(), own, signatures: [] };
3261
3534
  receiver.members.push(member);
3262
3535
  handlers.push(() => {
3263
- const listed = this.listHandlers(own ? callee.signatures : library, takeHandler);
3536
+ const listed = this.listHandlers(own ? callee.signatures : library);
3264
3537
  if (listed.length > 0)
3265
3538
  member.handlers = listed;
3266
3539
  });
@@ -3276,14 +3549,14 @@ class DeclarationReader {
3276
3549
  * A parameter that declares no member lists nothing, and so does a handler
3277
3550
  * none of whose parameters do.
3278
3551
  */
3279
- listHandlers(signatures, take) {
3552
+ listHandlers(signatures) {
3280
3553
  const listed = [];
3281
3554
  const seen = new Set();
3282
3555
  const add = (arg, key, slot) => {
3283
3556
  const place = JSON.stringify([arg, key ?? null]);
3284
3557
  if (seen.has(place))
3285
3558
  return;
3286
- const params = this.listHandlerParams(slot, take);
3559
+ const params = this.listHandlerParams(slot);
3287
3560
  if (params.length === 0)
3288
3561
  return;
3289
3562
  seen.add(place);
@@ -3315,8 +3588,8 @@ class DeclarationReader {
3315
3588
  }
3316
3589
  return listed;
3317
3590
  }
3318
- /** The parameters of a function type's first signature that declare members, each member counting against the cap. */
3319
- listHandlerParams(handler, take) {
3591
+ /** The parameters of a function type's first signature that declare members, each with its members (`handlerMembersOf`). */
3592
+ listHandlerParams(handler) {
3320
3593
  const slot = this.throughConditional(this.throughConstraint(handler));
3321
3594
  if (slot === VARIADIC)
3322
3595
  return [];
@@ -3328,32 +3601,79 @@ class DeclarationReader {
3328
3601
  const listed = [];
3329
3602
  signature.getParameters().forEach((parameter, index) => {
3330
3603
  const type = this.checker.getTypeOfSymbol(parameter);
3331
- if (this.namedProperties(type).length === 0 || !take())
3604
+ if (this.namedProperties(type).length === 0)
3605
+ return;
3606
+ const { members, dropped } = this.handlerMembersOf(type);
3607
+ this.handlersDropped += dropped;
3608
+ // Past the listing's budget a parameter is left out whole and counted (carrick#3016).
3609
+ if (members.length > this.handlerBudget) {
3610
+ this.handlersDropped += members.length;
3332
3611
  return;
3333
- const members = [];
3334
- this.listMembers(type, [], members, take);
3612
+ }
3613
+ this.handlerBudget -= members.length;
3335
3614
  listed.push({ param: index, name: parameter.getName(), type: this.printed(type), members });
3336
3615
  });
3337
3616
  return listed;
3338
3617
  }
3339
- /** A type's declared members by path, parents before children, each level sorted by name, down to `HANDLER_MEMBER_DEPTH`. */
3340
- listMembers(type, prefix, into, take) {
3341
- for (const property of sortedByName(this.namedProperties(type))) {
3342
- if (!take())
3343
- continue;
3344
- const memberType = this.checker.getTypeOfSymbol(property);
3345
- const path = [...prefix, property.getName()];
3346
- const callable = this.librarySignatures(memberType, 'call').length > 0;
3347
- into.push({
3348
- path,
3349
- type: this.printed(memberType),
3350
- optional: (property.flags & ts.SymbolFlags.Optional) !== 0,
3351
- function: callable,
3352
- });
3353
- if (!callable && path.length < HANDLER_MEMBER_DEPTH && this.isObjectType(memberType)) {
3354
- this.listMembers(memberType, path, into, take);
3618
+ /**
3619
+ * A handler parameter's declared members by path, down to
3620
+ * `HANDLER_MEMBER_DEPTH`, at most `HANDLER_MEMBER_CAP` of them (carrick#2966).
3621
+ * The cap keeps every top-level member before any nested one, so a wide
3622
+ * parameter loses its deepest members, never a top-level one a later member
3623
+ * name sorts after. Kept members come back parents before children, each
3624
+ * level sorted by name. Read once per type in a package, across its
3625
+ * specifiers: a type many handlers share is listed once.
3626
+ */
3627
+ handlerMembersOf(type) {
3628
+ const known = this.handlerMembers.get(type);
3629
+ if (known)
3630
+ return known;
3631
+ surfaceReadCounts.handlerMemberBuilds += 1;
3632
+ const roots = [];
3633
+ let kept = 0;
3634
+ let dropped = 0;
3635
+ // Breadth first: a level is kept whole, in name order, before the next.
3636
+ let level = [{ type, prefix: [], into: roots }];
3637
+ while (level.length > 0) {
3638
+ const next = [];
3639
+ for (const { type: holder, prefix, into } of level) {
3640
+ for (const property of sortedByName(this.namedProperties(holder))) {
3641
+ if (kept >= HANDLER_MEMBER_CAP) {
3642
+ dropped += 1;
3643
+ continue;
3644
+ }
3645
+ kept += 1;
3646
+ const memberType = this.checker.getTypeOfSymbol(property);
3647
+ const path = [...prefix, property.getName()];
3648
+ const callable = this.librarySignatures(memberType, 'call').length > 0;
3649
+ const node = {
3650
+ member: {
3651
+ path,
3652
+ type: this.printed(memberType),
3653
+ optional: (property.flags & ts.SymbolFlags.Optional) !== 0,
3654
+ function: callable,
3655
+ },
3656
+ children: [],
3657
+ };
3658
+ into.push(node);
3659
+ if (!callable && path.length < HANDLER_MEMBER_DEPTH && this.isObjectType(memberType)) {
3660
+ next.push({ type: memberType, prefix: path, into: node.children });
3661
+ }
3662
+ }
3355
3663
  }
3664
+ level = next;
3356
3665
  }
3666
+ const members = [];
3667
+ const emit = (nodes) => {
3668
+ for (const node of nodes) {
3669
+ members.push(node.member);
3670
+ emit(node.children);
3671
+ }
3672
+ };
3673
+ emit(roots);
3674
+ const listed = { members, dropped };
3675
+ this.handlerMembers.set(type, listed);
3676
+ return listed;
3357
3677
  }
3358
3678
  listSignatures(signatures, holder, take) {
3359
3679
  const listed = [];
@@ -3391,7 +3711,7 @@ class DeclarationReader {
3391
3711
  params.push(param);
3392
3712
  }
3393
3713
  const entry = { params, returns: this.printed(this.checker.getReturnTypeOfSignature(signature)) };
3394
- const candidates = resultCandidatesOf(this.checker, signature);
3714
+ const candidates = this.listResultCandidates ? resultCandidatesOf(this.checker, signature) : undefined;
3395
3715
  if (candidates !== undefined)
3396
3716
  entry.result_candidates = candidates;
3397
3717
  listed.push(entry);
@@ -3441,9 +3761,15 @@ class DeclarationReader {
3441
3761
  * so where the cut falls does not depend on where the package is installed.
3442
3762
  */
3443
3763
  printed(type) {
3764
+ const known = this.printedTexts.get(type);
3765
+ if (known !== undefined)
3766
+ return known;
3767
+ surfaceReadCounts.typePrints += 1;
3444
3768
  const node = this.checker.typeToTypeNode(type, undefined, PRINT_FLAGS);
3445
3769
  const text = node === undefined ? this.checker.typeToString(type) : printTypeNode(this.orderUnions(node));
3446
- return truncate(this.scrubbed(text));
3770
+ const listed = truncate(this.scrubbed(text));
3771
+ this.printedTexts.set(type, listed);
3772
+ return listed;
3447
3773
  }
3448
3774
  /** `text` with the service root written as `<root>`. */
3449
3775
  scrubbed(text) {
@@ -3617,8 +3943,10 @@ class DeclarationReader {
3617
3943
  /** Judge the next check as a claim about `pkg`. */
3618
3944
  setPackage(pkg) {
3619
3945
  const named = packageNameOf(pkg);
3620
- if (named !== this.currentPackage)
3946
+ if (named !== this.currentPackage) {
3621
3947
  this.declared.clear();
3948
+ this.handlerMembers.clear();
3949
+ }
3622
3950
  this.currentPackage = named;
3623
3951
  }
3624
3952
  /**
@@ -3911,6 +4239,21 @@ class DeclarationReader {
3911
4239
  */
3912
4240
  /** The longest member path a handler parameter's members are listed to (`['raw', 'url']`). */
3913
4241
  const HANDLER_MEMBER_DEPTH = 2;
4242
+ /**
4243
+ * The most members one handler parameter lists (carrick#2966), top-level
4244
+ * first. The store's server question shows at most 300 of them in the same
4245
+ * order, so this must stay at least that.
4246
+ */
4247
+ const HANDLER_MEMBER_CAP = 500;
4248
+ /**
4249
+ * The most handler-parameter members one `listSurface` call lists, across all
4250
+ * its specifiers (carrick#3016). The answer is one JSON line and a string
4251
+ * passes V8's limit at about 512 MiB; a member costs about 150 bytes, so this
4252
+ * keeps the handlers near 75 MB beside an export listing of tens of MB. A
4253
+ * server framework handing 50 distinct request types to thousands of members
4254
+ * listed 8.99 million of them (1.3 GB) before it.
4255
+ */
4256
+ const HANDLER_LISTING_BUDGET = 500_000;
3914
4257
  const PRINT_FLAGS = ts.NodeBuilderFlags.AllowUniqueESSymbolType |
3915
4258
  ts.NodeBuilderFlags.UseAliasDefinedOutsideCurrentScope |
3916
4259
  ts.NodeBuilderFlags.IgnoreErrors |