carrick 0.3.156 → 0.3.157

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/dist/facts/enabled.d.ts +6 -0
  2. package/dist/facts/enabled.js +8 -0
  3. package/dist/facts/enabled.js.map +1 -1
  4. package/dist/facts/fetch.js +2 -1
  5. package/dist/facts/fetch.js.map +1 -1
  6. package/dist/held/client.d.ts +34 -0
  7. package/dist/held/client.js +85 -0
  8. package/dist/held/client.js.map +1 -0
  9. package/dist/held/daemon.d.ts +106 -0
  10. package/dist/held/daemon.js +307 -0
  11. package/dist/held/daemon.js.map +1 -0
  12. package/dist/held/engine.d.ts +50 -0
  13. package/dist/held/engine.js +166 -0
  14. package/dist/held/engine.js.map +1 -0
  15. package/dist/held/paths.d.ts +9 -0
  16. package/dist/held/paths.js +27 -0
  17. package/dist/held/paths.js.map +1 -0
  18. package/dist/held/place.d.ts +84 -0
  19. package/dist/held/place.js +198 -0
  20. package/dist/held/place.js.map +1 -0
  21. package/dist/held/registry.d.ts +22 -0
  22. package/dist/held/registry.js +72 -0
  23. package/dist/held/registry.js.map +1 -0
  24. package/dist/held/run.d.ts +2 -0
  25. package/dist/held/run.js +60 -0
  26. package/dist/held/run.js.map +1 -0
  27. package/dist/hook/bash-targets.d.ts +7 -2
  28. package/dist/hook/bash-targets.js +82 -27
  29. package/dist/hook/bash-targets.js.map +1 -1
  30. package/dist/hook/lock.d.ts +26 -0
  31. package/dist/hook/lock.js +122 -0
  32. package/dist/hook/lock.js.map +1 -0
  33. package/dist/hook/post-bash.js +14 -5
  34. package/dist/hook/post-bash.js.map +1 -1
  35. package/dist/hook/rechecks.d.ts +1 -0
  36. package/dist/hook/rechecks.js +8 -121
  37. package/dist/hook/rechecks.js.map +1 -1
  38. package/dist/hook/timings.d.ts +2 -2
  39. package/dist/hook/timings.js +1 -1
  40. package/dist/hook/timings.js.map +1 -1
  41. package/dist/lsp-frame.d.ts +20 -0
  42. package/dist/lsp-frame.js +47 -0
  43. package/dist/lsp-frame.js.map +1 -0
  44. package/dist/server.js +4 -28
  45. package/dist/server.js.map +1 -1
  46. package/package.json +6 -6
  47. package/plugin/.claude-plugin/plugin.json +1 -1
  48. package/sidecar/dist/src/capture/api.d.ts +31 -1
  49. package/sidecar/dist/src/capture/check-probe.d.ts +15 -9
  50. package/sidecar/dist/src/capture/check-probe.js +36 -11
  51. package/sidecar/dist/src/capture/index.d.ts +9 -3
  52. package/sidecar/dist/src/capture/index.js +9 -2
  53. package/sidecar/dist/src/capture/result-label.js +3 -1
  54. package/sidecar/dist/src/capture/type-reasons.json +78 -0
  55. package/sidecar/dist/src/definition-resolver.d.ts +4 -4
  56. package/sidecar/dist/src/definition-resolver.js +8 -9
  57. package/sidecar/dist/src/engine-stamp.json +1 -0
  58. package/sidecar/dist/src/held-shadow.d.ts +60 -0
  59. package/sidecar/dist/src/held-shadow.js +222 -0
  60. package/sidecar/dist/src/index.js +47 -1
  61. package/sidecar/dist/src/library-claims.d.ts +3 -1
  62. package/sidecar/dist/src/library-claims.js +79 -3
  63. package/sidecar/dist/src/type-home.d.ts +12 -0
  64. package/sidecar/dist/src/type-home.js +41 -1
  65. package/sidecar/dist/src/type-inferrer.d.ts +8 -3
  66. package/sidecar/dist/src/type-inferrer.js +36 -18
  67. package/sidecar/dist/src/type-structural-expander.d.ts +1 -11
  68. package/sidecar/dist/src/types.d.ts +43 -5
  69. package/sidecar/dist/src/validators.d.ts +293 -246
  70. package/sidecar/dist/src/validators.js +8 -0
@@ -0,0 +1,222 @@
1
+ /**
2
+ * The shadow tree a held-open compiler reads: a copy of one service's program
3
+ * that lives outside the checkout and loads on TypeScript 7.
4
+ *
5
+ * The scan's loader builds the program on TypeScript 6 (repo tsconfig, Deno
6
+ * graph, workspace links). TypeScript 7's command line refuses options the
7
+ * repo may set (`baseUrl`, `moduleResolution: node`, `target: es5`,
8
+ * `esModuleInterop: false`), and a config outside the repo cannot govern files
9
+ * inside it, so the held compiler never reads the repo's own config or files.
10
+ * It reads this tree instead:
11
+ *
12
+ * - `w/<repo-relative path>`: byte copies of the service's own files;
13
+ * - `v/<absolute path>`: every other program file (installed packages,
14
+ * runtime types), with each import, export, import type, augmentation and
15
+ * `types` reference pinned to the copy of the file TypeScript 6 resolved it
16
+ * to, so one package name that resolves to two versions stays two files;
17
+ * - `w/tsconfig.json`: generated, `moduleResolution: bundler`, exact `paths`
18
+ * for the bare specifiers the own files use, every non-library program file
19
+ * named in `files` (so `@types` the loader included on its own are
20
+ * explicit), and the library files TypeScript 6 loaded named in `lib`.
21
+ *
22
+ * Own = under the scanned repo, not under a `node_modules` segment, not under
23
+ * `.carrick/`. A bare import added later is not in `paths` (it needs a new
24
+ * shadow).
25
+ */
26
+ import * as fs from 'node:fs';
27
+ import * as path from 'node:path';
28
+ import { ts } from 'ts-morph';
29
+ import { WriteGuard, judgeTscPath } from './capture/index.js';
30
+ /** The platform package's executable, `@typescript/typescript-<platform>-<arch>/lib/tsc`. */
31
+ const NATIVE_TSC = /[\\/]@typescript[\\/]typescript-[^\\/]+[\\/]lib[\\/]tsc(\.exe)?$/;
32
+ /** `judgeTscPath()` when it is the native executable, else null (no held compiler). */
33
+ export function nativeTscPath(tscPath = judgeTscPath()) {
34
+ return NATIVE_TSC.test(tscPath) ? tscPath : null;
35
+ }
36
+ const MISSING = (spec) => `__held_unresolved__/${spec.replace(/[^A-Za-z0-9@/._-]/g, '_')}`;
37
+ /** A `/// <reference types>` or import target written for a vendored file: relative, JS-spelled for declaration files. */
38
+ function relativeSpecifier(fromFile, toFile) {
39
+ let rel = path.relative(path.dirname(fromFile), toFile).split(path.sep).join('/');
40
+ if (!rel.startsWith('.'))
41
+ rel = `./${rel}`;
42
+ return rel.replace(/\.d\.ts$/, '.js').replace(/\.d\.mts$/, '.mjs').replace(/\.d\.cts$/, '.cjs');
43
+ }
44
+ function isLibraryFile(program, fileName) {
45
+ const sf = program.getSourceFile(fileName);
46
+ if (sf && program.isSourceFileDefaultLibrary(sf))
47
+ return true;
48
+ return (/[\\/]typescript[\\/]lib[\\/]lib\.[^/\\]*\.d\.ts$/.test(fileName) ||
49
+ /[\\/]@ts-morph[\\/]common[\\/].*lib\.[^/\\]*\.d\.ts$/.test(fileName));
50
+ }
51
+ /**
52
+ * Write the shadow tree of the loader's default program under `outDir` (which
53
+ * must be outside the scan root). Reads the program; changes nothing in the
54
+ * checkout.
55
+ */
56
+ export function writeShadow(loader, outDir) {
57
+ const scanRoot = loader.getScanRoot();
58
+ const program = loader.getProject().getProgram().compilerObject;
59
+ const internal = program;
60
+ const roots = [scanRoot, safeRealpath(scanRoot)].filter((r, i, all) => all.indexOf(r) === i);
61
+ const underRoot = (file) => roots.find((r) => file.startsWith(r + path.sep));
62
+ const isOwn = (file) => {
63
+ const root = underRoot(file);
64
+ if (root === undefined)
65
+ return false;
66
+ const segments = file.slice(root.length + 1).split(path.sep);
67
+ return !segments.includes('node_modules') && segments[0] !== '.carrick';
68
+ };
69
+ const ownRelative = (file) => path.relative(underRoot(file) ?? scanRoot, file);
70
+ const guard = WriteGuard.of({ dirs: [outDir], protect: [scanRoot, loader.getRepoRoot()] });
71
+ const own = path.join(outDir, 'w');
72
+ const vendoredRoot = path.join(outDir, 'v');
73
+ const shadowPath = (file) => isOwn(file) ? path.join(own, ownRelative(file)) : path.join(vendoredRoot, file);
74
+ const inProgram = new Set(program.getSourceFiles().map((sf) => sf.fileName));
75
+ const paths = {};
76
+ const pathConflicts = [];
77
+ const ownFiles = [];
78
+ let vendored = 0;
79
+ let rewritten = 0;
80
+ let unresolved = 0;
81
+ let hono = false;
82
+ for (const sf of program.getSourceFiles()) {
83
+ const file = sf.fileName;
84
+ if (isLibraryFile(program, file))
85
+ continue;
86
+ const literals = [];
87
+ const { imports = [], moduleAugmentations = [] } = sf;
88
+ for (const node of [...imports, ...moduleAugmentations]) {
89
+ if (!ts.isStringLiteralLike(node))
90
+ continue;
91
+ const augmentation = moduleAugmentations.includes(node);
92
+ if (augmentation && !ts.isExternalModule(sf))
93
+ continue; // an ambient declaration, not a resolution
94
+ const mode = program.getModeForUsageLocation(sf, node);
95
+ const resolved = internal.getResolvedModule(sf, node.text, mode)?.resolvedModule;
96
+ literals.push({
97
+ node,
98
+ text: node.text,
99
+ to: resolved?.resolvedFileName,
100
+ pkg: resolved?.packageId?.name,
101
+ augmentation,
102
+ synthesized: node.pos < 0 || node.end < 0 || !node.parent,
103
+ });
104
+ }
105
+ if (isOwn(file)) {
106
+ ownFiles.push(ownRelative(file));
107
+ const out = shadowPath(file);
108
+ guard.mkdir(path.dirname(out));
109
+ guard.copyFile(file, out);
110
+ for (const lit of literals) {
111
+ if (lit.text.startsWith('.') || path.isAbsolute(lit.text))
112
+ continue;
113
+ if (!lit.to || !inProgram.has(lit.to))
114
+ continue; // unresolved stays unresolved: no `paths` entry
115
+ if (isHonoFile(loader, lit.to, lit.pkg))
116
+ hono = true;
117
+ const target = shadowPath(lit.to);
118
+ const known = paths[lit.text];
119
+ if (known && known[0] !== target)
120
+ pathConflicts.push({ spec: lit.text, a: known[0], b: target, from: ownRelative(file) });
121
+ else
122
+ paths[lit.text] = [target];
123
+ }
124
+ continue;
125
+ }
126
+ // A vendored copy: every specifier pinned to the copy TypeScript 6 chose.
127
+ let text = sf.text;
128
+ const edits = [];
129
+ for (const lit of literals) {
130
+ if (lit.synthesized)
131
+ continue;
132
+ let spec;
133
+ if (lit.to && inProgram.has(lit.to))
134
+ spec = relativeSpecifier(shadowPath(file), shadowPath(lit.to));
135
+ else {
136
+ spec = MISSING(lit.text);
137
+ unresolved++;
138
+ }
139
+ edits.push({ start: lit.node.getStart(sf) + 1, end: lit.node.end - 1, text: spec });
140
+ }
141
+ for (const ref of sf.typeReferenceDirectives ?? []) {
142
+ const mode = ref.resolutionMode ?? internal.getDefaultResolutionModeForFile(sf);
143
+ const target = internal.getResolvedTypeReferenceDirective?.(sf, ref.fileName, mode)?.resolvedTypeReferenceDirective?.resolvedFileName;
144
+ // The whole `/// <reference types="..." />` line becomes a path reference to the copy.
145
+ const lineStart = text.lastIndexOf('\n', ref.pos) + 1;
146
+ const newline = text.indexOf('\n', ref.end);
147
+ const lineEnd = newline === -1 ? text.length : newline;
148
+ const replacement = target && inProgram.has(target)
149
+ ? `/// <reference path="${relativeSpecifier(shadowPath(file), shadowPath(target)).replace(/\.js$/, '.d.ts').replace(/\.mjs$/, '.d.mts').replace(/\.cjs$/, '.d.cts')}" />`
150
+ : `// held: unresolved types reference ${ref.fileName}`;
151
+ edits.push({ start: lineStart, end: lineEnd, text: replacement });
152
+ }
153
+ edits.sort((a, b) => b.start - a.start);
154
+ for (const edit of edits)
155
+ text = text.slice(0, edit.start) + edit.text + text.slice(edit.end);
156
+ rewritten += edits.length;
157
+ const out = shadowPath(file);
158
+ guard.mkdir(path.dirname(out));
159
+ guard.writeFile(out, text);
160
+ vendored++;
161
+ }
162
+ const options = program.getCompilerOptions();
163
+ // A repo that sets no `lib` gets the default library files for its target (DOM, es2022, ...). `lib: []`
164
+ // would leave only what `@types/node` references, so the files TypeScript 6 loaded are named. `*.full`
165
+ // is a file, not a `--lib` name, and TypeScript 7 refuses it; its parts are listed.
166
+ const libraryNames = program
167
+ .getSourceFiles()
168
+ .map((sf) => sf.fileName)
169
+ .filter((f) => isLibraryFile(program, f))
170
+ .map((f) => path.basename(f).replace(/^lib\./, '').replace(/\.d\.ts$/, ''))
171
+ .filter((name) => !name.endsWith('.full'));
172
+ const lib = options.lib ? options.lib.map((l) => l.replace(/^lib\./, '').replace(/\.d\.ts$/, '')) : libraryNames;
173
+ // Every non-library program file is a root, so `@types` the loader included on its own and the
174
+ // synthesised JSX runtime import's target stay in the program.
175
+ const files = program.getSourceFiles().filter((sf) => !isLibraryFile(program, sf.fileName)).map((sf) => shadowPath(sf.fileName));
176
+ const jsx = { 1: 'preserve', 2: 'react', 3: 'react-native', 4: 'react-jsx', 5: 'react-jsxdev' }[options.jsx ?? 0];
177
+ const passed = [
178
+ 'noImplicitAny', 'strictNullChecks', 'noUnusedLocals', 'noUnusedParameters', 'exactOptionalPropertyTypes',
179
+ 'noImplicitOverride', 'noImplicitReturns', 'noFallthroughCasesInSwitch', 'noUncheckedIndexedAccess',
180
+ 'useUnknownInCatchVariables', 'verbatimModuleSyntax', 'isolatedModules', 'experimentalDecorators',
181
+ 'emitDecoratorMetadata', 'useDefineForClassFields', 'noPropertyAccessFromIndexSignature',
182
+ ];
183
+ const compilerOptions = {
184
+ // Options TypeScript 7 removed (baseUrl, node10 resolution, es5, esModuleInterop: false) are never carried.
185
+ target: 'esnext', module: 'esnext', moduleResolution: 'bundler', strict: options.strict ?? false,
186
+ allowJs: !!options.allowJs, checkJs: !!options.checkJs, skipLibCheck: !!options.skipLibCheck,
187
+ resolveJsonModule: !!options.resolveJsonModule,
188
+ ...(jsx ? { jsx } : {}), ...(options.jsxImportSource ? { jsxImportSource: options.jsxImportSource } : {}),
189
+ lib, allowImportingTsExtensions: true, noEmit: true,
190
+ // `false` (the loader's reading of `esModuleInterop: false`) is refused by TypeScript 7 (TS5108); the default is true.
191
+ ...(options.allowSyntheticDefaultImports === false ? {} : { allowSyntheticDefaultImports: true }),
192
+ types: options.types ?? [], noUncheckedSideEffectImports: options.noUncheckedSideEffectImports ?? false,
193
+ ...Object.fromEntries(passed.filter((k) => options[k] !== undefined).map((k) => [k, options[k]])),
194
+ paths,
195
+ };
196
+ const tsconfig = path.join(own, 'tsconfig.json');
197
+ guard.mkdir(own);
198
+ guard.writeFile(tsconfig, JSON.stringify({ compilerOptions, files, include: [] }, null, 1));
199
+ return {
200
+ tsconfig,
201
+ own_files: ownFiles.sort(),
202
+ vendored,
203
+ rewritten,
204
+ unresolved,
205
+ path_conflicts: pathConflicts,
206
+ bare_specifiers: Object.keys(paths).sort(),
207
+ hono,
208
+ native_tsc: nativeTscPath(),
209
+ };
210
+ }
211
+ /** The resolved file belongs to a package named `hono`: by the resolver's package id, the Deno graph, or the install path. */
212
+ function isHonoFile(loader, file, packageId) {
213
+ return packageId === 'hono' || loader.packageDirectoryOf(file)?.name === 'hono' || /[\\/]node_modules[\\/]hono[\\/]/.test(file);
214
+ }
215
+ function safeRealpath(p) {
216
+ try {
217
+ return fs.realpathSync(p);
218
+ }
219
+ catch {
220
+ return p;
221
+ }
222
+ }
@@ -16,6 +16,7 @@
16
16
  * that goes silent past its deadline; a long handler stays alive by writing
17
17
  * `progress` frames as it finishes units of work (writeProgress).
18
18
  */
19
+ import * as fs from 'node:fs';
19
20
  import * as path from 'node:path';
20
21
  import * as readline from 'node:readline';
21
22
  import { parseRequest } from './validators.js';
@@ -30,6 +31,7 @@ import { readServerLabels } from './server-labels.js';
30
31
  import { PROGRESS_INTERVAL_MS, atMostEvery } from './progress.js';
31
32
  import { mergeInferTimings } from './infer-timing.js';
32
33
  import { addProgramFiles, listProgramFiles } from './program-files.js';
34
+ import { writeShadow } from './held-shadow.js';
33
35
  import { changedSource, inferCacheDir, keepable, programDifference, programRecord, readEntry, requestDigest, writeEntry, } from './infer-cache.js';
34
36
  import { writePositionRows } from './position-rows.js';
35
37
  import { findImplementations } from './implementations.js';
@@ -630,6 +632,25 @@ function handleVerifyClientSemantics(request) {
630
632
  return { request_id: request.request_id, status: 'error', errors: [error] };
631
633
  }
632
634
  }
635
+ /**
636
+ * A verifier over a program built from another service's tsconfig: its
637
+ * compiler options, none of its files (the `scripts` build kind), so the probe
638
+ * file is the only root. Nothing keeps the program; it is garbage once the
639
+ * request that asked for it has answered. Module resolution still goes through
640
+ * this process's loader, as the default program's does.
641
+ *
642
+ * @throws if the tsconfig cannot be read
643
+ */
644
+ function probeOnlyVerifier(tsconfigPath) {
645
+ const loader = initializedLoader();
646
+ const configPath = path.resolve(loader.getRepoRoot(), tsconfigPath);
647
+ if (!fs.existsSync(configPath))
648
+ throw new Error(`tsconfig_path ${configPath} does not exist`);
649
+ return new LibraryClaimsVerifier(loader.scriptProjectFor(configPath), {
650
+ packageDirectoryOf: (file) => loader.packageDirectoryOf(file),
651
+ resolveModule: (name, from, options) => loader.resolveThroughGraph(name, from, options),
652
+ });
653
+ }
633
654
  /**
634
655
  * Handle the 'verify_library_claims' action - check library claims of every
635
656
  * role against each package's own declarations (carrick#1616). One verdict
@@ -638,7 +659,10 @@ function handleVerifyClientSemantics(request) {
638
659
  function handleVerifyLibraryClaims(request) {
639
660
  const started = performance.now();
640
661
  try {
641
- const { claimsVerifier } = projectComponents();
662
+ // A named tsconfig is judged in a probe-only program of its own options,
663
+ // built for this request and dropped with it (carrick#4472); the service's
664
+ // own program is not built for it.
665
+ const claimsVerifier = request.tsconfig_path === undefined ? projectComponents().claimsVerifier : probeOnlyVerifier(request.tsconfig_path);
642
666
  // The verifier's budget starts now, and so does the scanner's wait.
643
667
  writeProgress(request.request_id, 'verify_library_claims', 'program ready');
644
668
  const fromDir = path.resolve(projectLoader.getRepoRoot(), request.from_dir);
@@ -730,6 +754,26 @@ function handleListProgramFiles(request) {
730
754
  return { request_id: request.request_id, status: 'error', errors: [error] };
731
755
  }
732
756
  }
757
+ /**
758
+ * Handle the 'write_shadow' action: write the service's program as the shadow
759
+ * tree a held-open compiler reads (held-shadow.ts). Builds the default
760
+ * project if the process has not, reads it, and changes nothing in the
761
+ * checkout.
762
+ */
763
+ function handleWriteShadow(request) {
764
+ try {
765
+ const loader = initializedLoader();
766
+ const startTime = performance.now();
767
+ const result = writeShadow(loader, request.out_dir);
768
+ log(`Wrote the shadow of ${result.own_files.length} own file(s) in ${Math.round(performance.now() - startTime)}ms`);
769
+ return { request_id: request.request_id, status: 'success', ...result };
770
+ }
771
+ catch (err) {
772
+ const error = err instanceof Error ? err.message : String(err);
773
+ logError(`Writing the shadow failed: ${error}`);
774
+ return { request_id: request.request_id, status: 'error', errors: [error] };
775
+ }
776
+ }
733
777
  /**
734
778
  * Handle the 'reach_graph' action - the import graph of every program the
735
779
  * process has built, the default one and each owning project's (carrick#3100).
@@ -913,6 +957,8 @@ function handleRequest(request) {
913
957
  return handleListLibrarySurface(request);
914
958
  case 'list_program_files':
915
959
  return handleListProgramFiles(request);
960
+ case 'write_shadow':
961
+ return handleWriteShadow(request);
916
962
  case 'reach_graph':
917
963
  return handleReachGraph(request);
918
964
  case 'reach':
@@ -31,7 +31,9 @@
31
31
  *
32
32
  * The export's type is read the way the service's own code would read it: a
33
33
  * probe file in `from_dir` imports it, inside the service's program, under the
34
- * service's compiler options. The declarations must be the installed
34
+ * service's compiler options. A request that names another service's tsconfig
35
+ * (`tsconfig_path`, carrick#4472) reads it in a probe-only program under that
36
+ * tsconfig's options instead. The declarations must be the installed
35
37
  * package's: a `paths` alias or a `declare module` block the service writes
36
38
  * for itself is not evidence about the library.
37
39
  */
@@ -31,7 +31,9 @@
31
31
  *
32
32
  * The export's type is read the way the service's own code would read it: a
33
33
  * probe file in `from_dir` imports it, inside the service's program, under the
34
- * service's compiler options. The declarations must be the installed
34
+ * service's compiler options. A request that names another service's tsconfig
35
+ * (`tsconfig_path`, carrick#4472) reads it in a probe-only program under that
36
+ * tsconfig's options instead. The declarations must be the installed
35
37
  * package's: a `paths` alias or a `declare module` block the service writes
36
38
  * for itself is not evidence about the library.
37
39
  */
@@ -627,6 +629,9 @@ export class LibraryClaimsVerifier {
627
629
  const made = other.claim;
628
630
  if ((made.kind !== 'make' && made.kind !== 'scope') || made.name === undefined)
629
631
  return;
632
+ // An `of`-make names the object its member returns, not an instance of this export (rule 7).
633
+ if (made.kind === 'make' && made.of !== undefined)
634
+ return;
630
635
  const judgement = judge(i);
631
636
  if (judgement.outcome.verdict !== 'verified' || !judgement.holding)
632
637
  return;
@@ -699,6 +704,8 @@ export class LibraryClaimsVerifier {
699
704
  };
700
705
  const judgeCheck = (index) => {
701
706
  const check = checks[index];
707
+ if (check.claim.kind === 'make' && ofMakeInvalid(check.claim))
708
+ return { outcome: unchecked('claim_invalid') };
702
709
  const makeProtocol = makeProtocolRefusal(check);
703
710
  if (makeProtocol !== undefined)
704
711
  return { outcome: unchecked(makeProtocol) };
@@ -718,6 +725,8 @@ export class LibraryClaimsVerifier {
718
725
  }
719
726
  if (unbuiltPart(check.claim) !== undefined)
720
727
  return { outcome: unchecked('part_unbuilt') };
728
+ if (rules.http && check.claim.kind === 'make' && check.claim.of !== undefined)
729
+ return { outcome: unchecked('role_unsupported') };
721
730
  if (rules.http && !HTTP_RECEIVER.test(check.receiver))
722
731
  return { outcome: unchecked('receiver_invalid') };
723
732
  if (rules.message && !fitsReceiver(check))
@@ -1283,13 +1292,33 @@ function unbuiltPart(claim) {
1283
1292
  * maker's instances" is two elements, not one.
1284
1293
  */
1285
1294
  function placementInvalid(claim) {
1286
- if (claim.kind === 'make' || claim.of === undefined)
1295
+ if (claim.kind === 'make')
1296
+ return ofMakeInvalid(claim);
1297
+ if (claim.of === undefined)
1287
1298
  return false;
1288
1299
  if (claim.on !== undefined)
1289
1300
  return true;
1290
1301
  const of = parseReceiver(claim.of);
1291
1302
  return of === undefined || (of.maker === undefined && of.scope === undefined && of.type === undefined);
1292
1303
  }
1304
+ /**
1305
+ * Rules 1-3 of amendment 12: a make's `of` is a maker receiver id (never the
1306
+ * export, a scope or a type), the make is a `call` on a named member, and it
1307
+ * takes a `name` at an argument with only `key_labels`, `name_scope` and
1308
+ * `picker` beside it. Rule 4 is read on the member's declared return.
1309
+ */
1310
+ function ofMakeInvalid(claim) {
1311
+ if (claim.of === undefined)
1312
+ return false;
1313
+ const of = parseReceiver(claim.of);
1314
+ if (of?.maker === undefined || of.scope !== undefined)
1315
+ return true;
1316
+ if (claim.form !== 'call' || claim.member === null)
1317
+ return true;
1318
+ if (claim.name === undefined || !('arg' in claim.name))
1319
+ return true;
1320
+ return [claim.base, claim.prefix, claim.handler, claim.runs, claim.protocol, claim.result].some(part => part !== undefined);
1321
+ }
1293
1322
  /** The slots a claim's name sits at: one slot, or each of its parts. */
1294
1323
  function nameSlots(claim) {
1295
1324
  const name = claim.name;
@@ -1376,7 +1405,7 @@ function fitsReceiver(check) {
1376
1405
  if (receiver.type)
1377
1406
  return claim.kind !== 'make' && claim.of === check.receiver;
1378
1407
  if (claim.kind === 'make')
1379
- return check.receiver === 'export';
1408
+ return claim.of === undefined ? check.receiver === 'export' : check.receiver === claim.of;
1380
1409
  if (claim.of !== undefined)
1381
1410
  return check.receiver === claim.of;
1382
1411
  if (claim.on === undefined)
@@ -1398,6 +1427,9 @@ function fitsReceiver(check) {
1398
1427
  function builtReceiver(check) {
1399
1428
  const claim = check.claim;
1400
1429
  if (claim.kind === 'make') {
1430
+ // An `of`-make opens no receiver id on its own export (amendment 12, rule 7).
1431
+ if (claim.of !== undefined)
1432
+ return undefined;
1401
1433
  if (claim.member === null)
1402
1434
  return claim.form === 'call' ? 'instance:()' : 'instance:new';
1403
1435
  return claim.form === 'call' ? `instance:${claim.member}` : `instance:new:${claim.member}`;
@@ -2264,6 +2296,8 @@ class DeclarationReader {
2264
2296
  * (`runsCollectionOutcome`). With no such scope this arm never runs.
2265
2297
  */
2266
2298
  judgeMake(receiver, claim, built, collections) {
2299
+ if (claim.of !== undefined)
2300
+ return this.judgeOfMake(receiver, claim);
2267
2301
  const layout = this.layout({
2268
2302
  base: claim.base,
2269
2303
  prefix: claim.prefix,
@@ -2302,6 +2336,48 @@ class DeclarationReader {
2302
2336
  return { outcome: VERIFIED, holding };
2303
2337
  return { outcome: best.outcome };
2304
2338
  }
2339
+ /**
2340
+ * An `of`-make (amendment 12): `member` is a home-declared call on the
2341
+ * receiver `of` names, whose name slot takes the name at `name`, and whose
2342
+ * declared return is an object type: not the receiver's own (a fluent
2343
+ * `this`), not a Promise (`claim_invalid`). It opens no receiver, so it
2344
+ * holds no overloads; its verdict carries the member's declarations.
2345
+ */
2346
+ judgeOfMake(receiver, claim) {
2347
+ const layout = this.layout({ name: claim.name });
2348
+ if ('failure' in layout)
2349
+ return { outcome: layout.failure };
2350
+ const callee = this.ownCallee(receiver, [], claim.member, 'call');
2351
+ if ('failure' in callee)
2352
+ return { outcome: callee.failure };
2353
+ const labels = claim.key_labels ?? {};
2354
+ const holding = [];
2355
+ let best;
2356
+ for (const signature of callee.signatures) {
2357
+ let result = this.messageSignatureOutcome(signature, layout.value, labels);
2358
+ if (result.rank === Infinity && !this.makesAnObject(this.checker.getReturnTypeOfSignature(signature), receiver.type)) {
2359
+ result = { rank: 6, outcome: unchecked('claim_invalid') };
2360
+ }
2361
+ if (result.rank === Infinity)
2362
+ holding.push(signature);
2363
+ else
2364
+ best = furthest(best, result.rank, result.outcome);
2365
+ }
2366
+ if (holding.length === 0)
2367
+ return { outcome: best.outcome };
2368
+ const declarations = this.declarationsOf({ signatures: holding, named: callee.named });
2369
+ return { outcome: declarations.length > 0 ? { verdict: 'verified', declarations } : VERIFIED };
2370
+ }
2371
+ /** An `of`-make's return (rule 4): an object type that is neither the receiver's own nor a thenable. */
2372
+ makesAnObject(returned, receiver) {
2373
+ if (returned.flags & ts.TypeFlags.TypeParameter && returned.isThisType)
2374
+ return false;
2375
+ if (returned === receiver || sameDeclared(this.checker, returned, receiver))
2376
+ return false;
2377
+ if (this.checker.getAwaitedType(returned) !== returned)
2378
+ return false;
2379
+ return this.isObjectType(returned);
2380
+ }
2305
2381
  /**
2306
2382
  * `member` (after `path`) is a home-declared callable member whose name
2307
2383
  * slot accepts a string, under the name-slot rules, and returns a type that
@@ -28,3 +28,15 @@ export declare function declaredTypeName(name: string, declaration: Node): strin
28
28
  * - a declaration with no name to point at (`export default class {}`).
29
29
  */
30
30
  export declare function homeOfTypeDeclaration(name: string, declaration: Node, program: ts.Program): TypeHome | undefined;
31
+ /**
32
+ * carrick#2148 H3: the home of a schema value a contract was read off, where
33
+ * the value is one name for a `const` the repository declares
34
+ * (`guard('json', NewTicket)`, `NewTicket.safeParse(body)`). The schema is
35
+ * where that contract is written, so the home is the const's name, marked
36
+ * `kind: "schema"`: it is a value, never a type a reader can import as one.
37
+ *
38
+ * None for a schema built at its use (`record({ … })`), a name that is not a
39
+ * `const` (it can be reassigned, so the declaration is not the contract), an
40
+ * ambient `declare const`, and a declaration in a package or a `.d.ts`.
41
+ */
42
+ export declare function homeOfSchemaValue(value: Node): TypeHome | undefined;
@@ -3,7 +3,7 @@
3
3
  * The compiler engine's answers (`type_home`, `stated_body.root_home`) and
4
4
  * the bundle's manifest (`home`) read it from here.
5
5
  */
6
- import { Node } from 'ts-morph';
6
+ import { Node, VariableDeclarationKind } from 'ts-morph';
7
7
  import { startLineOf } from './line-index.js';
8
8
  /** A declaration that names a type: an interface, a type alias, a class or an enum. */
9
9
  export function isTypeSpaceDeclaration(declaration) {
@@ -52,3 +52,43 @@ export function homeOfTypeDeclaration(name, declaration, program) {
52
52
  return undefined;
53
53
  return { symbol, file_path: sourceFile.getFilePath(), line: startLineOf(nameNode) };
54
54
  }
55
+ /**
56
+ * carrick#2148 H3: the home of a schema value a contract was read off, where
57
+ * the value is one name for a `const` the repository declares
58
+ * (`guard('json', NewTicket)`, `NewTicket.safeParse(body)`). The schema is
59
+ * where that contract is written, so the home is the const's name, marked
60
+ * `kind: "schema"`: it is a value, never a type a reader can import as one.
61
+ *
62
+ * None for a schema built at its use (`record({ … })`), a name that is not a
63
+ * `const` (it can be reassigned, so the declaration is not the contract), an
64
+ * ambient `declare const`, and a declaration in a package or a `.d.ts`.
65
+ */
66
+ export function homeOfSchemaValue(value) {
67
+ if (!Node.isIdentifier(value))
68
+ return undefined;
69
+ let symbol = value.getSymbol();
70
+ if (symbol?.isAlias())
71
+ symbol = symbol.getAliasedSymbol() ?? symbol;
72
+ const declarations = symbol?.getDeclarations() ?? [];
73
+ if (declarations.length !== 1)
74
+ return undefined;
75
+ const [declaration] = declarations;
76
+ if (!Node.isVariableDeclaration(declaration) || !declaration.hasInitializer())
77
+ return undefined;
78
+ const list = declaration.getParent();
79
+ if (!Node.isVariableDeclarationList(list) || list.getDeclarationKind() !== VariableDeclarationKind.Const) {
80
+ return undefined;
81
+ }
82
+ const sourceFile = declaration.getSourceFile();
83
+ if (sourceFile.isDeclarationFile() || sourceFile.isInNodeModules())
84
+ return undefined;
85
+ const nameNode = declaration.getNameNode();
86
+ if (!Node.isIdentifier(nameNode))
87
+ return undefined;
88
+ return {
89
+ symbol: nameNode.getText(),
90
+ file_path: sourceFile.getFilePath(),
91
+ line: startLineOf(nameNode),
92
+ kind: 'schema',
93
+ };
94
+ }
@@ -21,9 +21,10 @@ import { Project, SourceFile, type CallExpression } from 'ts-morph';
21
21
  import type { InferRequestItem, InferResult, ModelSymbol, ExtractionConfig } from './types.js';
22
22
  import { type LabelledMembers } from './library-claims.js';
23
23
  /**
24
- * The reasons an `unknown` answer is a decision, not a failure to read: the
25
- * list `DECIDED_ABSTAIN_REASONS` in `src/engine/type_compat_v2.rs` holds
26
- * final. A stated reply never replaces one (carrick#2674).
24
+ * The reasons an `unknown` answer is a decision, not a failure to read, on the
25
+ * response path that reads this set: the words `capture/type-reasons.json`
26
+ * marks `always` (carrick#4231). A stated reply never replaces one
27
+ * (carrick#2674).
27
28
  */
28
29
  export declare const DECIDED_ABSTAIN_REASONS: ReadonlySet<string>;
29
30
  /**
@@ -2749,6 +2750,10 @@ export declare class TypeInferrer {
2749
2750
  * `unknown`.
2750
2751
  */
2751
2752
  private schemaContract;
2753
+ /**
2754
+ * `schemaContract`'s text and provenance, read off the schema's types.
2755
+ */
2756
+ private schemaContractText;
2752
2757
  /**
2753
2758
  * Print a schema's input with each coerced position replaced by the output's
2754
2759
  * type at that position (carrick#1105). Null when any position cannot be