@venizia/dev-configs 0.5.0-2 → 0.5.0-4

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.
package/README.md CHANGED
@@ -104,7 +104,7 @@ Every IGNIS package and example does.
104
104
  | :--- | :--- |
105
105
  | `@venizia/dev-configs` | `/compilers` and `/linters`, re-exported. Not `/checks` or `/testing` |
106
106
  | `@venizia/dev-configs/compilers` | `BunCompiler` |
107
- | `@venizia/dev-configs/testing` | `RejectionHelper` (`rejectionOf`, `expectRejection`), `SpawnHelper` (`spawnSyncBounded`), `RepoTmp` (`findRoot`, `apply`) - test helpers (imports `bun:test`; tests only) |
107
+ | `@venizia/dev-configs/testing` | `RejectionUtility` (`rejectionOf`, `expectRejection`), `SpawnUtility` (`spawnSyncBounded`), `RepoTmp` (`findRoot`, `apply`) - test helpers (imports `bun:test`; tests only) |
108
108
  | `@venizia/dev-configs/testing/tmpdir-preload` | A bunfig test preload: a bare `bun test` keeps its temp folders in the repository (calls `RepoTmp.apply()`) |
109
109
  | `@venizia/dev-configs/checks` | The engines behind `devz check <name>`: catalog, module cycles, purity, split report and the test-trimming checks. Bun-only tooling, never import it from browser code |
110
110
  | `@venizia/dev-configs/linters` | `oxlintConfigs`, `OxlintConfigs`, `BrowserOxlintConfigs`, `ReactOxlintConfigs`, `LintIgnore`, `namingConventionConfigs`, `reactNamingConventionConfigs`, `houseConfigs`, `reactHouseConfigs`, `eslintConfigs`, `paddingConfigs`, the rule classes and their types |
@@ -406,7 +406,7 @@ The codemods are `drop-redundant-casts` (removes `as X` casts the compiler no lo
406
406
  `const-classes` (turns a string-literal union into a const class), `async-style` (applies the async style
407
407
  fixers and lists the rest), `namespace-functions` (moves calls of a function that moved into a class to the
408
408
  class form), `connector-imports` (moves `@venizia/ignis/<connector sub-path>` imports to
409
- `@venizia/ignis-connectors`) and `env-get` (strips the type arguments of `applicationEnvironment.get()`
409
+ `@venizia/ignis-connectors`), `class-renames` (renames the classes IGNIS renamed, such as `RejectionHelper` to `RejectionUtility`, at the import and every use) and `env-get` (strips the type arguments of `applicationEnvironment.get()`
410
410
  for the string-reading `get()`; the receiver is a name the call's scope resolves to an import of `applicationEnvironment` or `AppEnvs` from the store module, or a const initialised from one; every other `get<...>(key)` call is listed as skipped, and a call it cannot place as manual, with its file and line) and `any-aliases` (replaces the removed `AnyType` and `AnyObject` aliases by what they stood for, `any` and `Record<string | symbol | number, any>`, so no type changes, and drops them from the imports; `--strict` writes `unknown` and `Record<string, unknown>` instead; it reads imports from `@venizia/ignis`, `-helpers`, `-inversion`, and from `@venizia/ardor` and `-kernel`, which re-exported them).
411
411
 
412
412
  ## Where it sits
@@ -10,12 +10,33 @@ export interface IBindingKeysResult {
10
10
  reason: string;
11
11
  }>;
12
12
  }
13
+ /** What the use sites of one key constant claim: each claim is the type's text and the symbols its names resolve to at the use site. */
14
+ export interface IKeyClaims {
15
+ declaration: import('typescript').Node;
16
+ claims: Array<{
17
+ text: string | undefined;
18
+ names: Array<{
19
+ name: string;
20
+ symbol: import('typescript').Symbol | undefined;
21
+ }>;
22
+ }>;
23
+ }
13
24
  /** Rewrites raw binding keys to `BindingKeys.build<T>({ key })`. */
14
25
  export declare class BindingKeysCodemod {
15
26
  /** The module `BindingKeys` comes from in this file: an existing import, the module of `inject`, a @venizia/ignis import, or `fallback`. */
16
27
  private static readIdentifierSource;
17
28
  /** The local name `BindingKeys` is imported under (an alias included), or `BindingKeys` when the file does not import it. */
18
29
  private static readBuilderName;
30
+ /**
31
+ * The type a key constant is built with: the one type its use sites claim, else `undefined` (`unknown`). A type is copied as
32
+ * text into the declaration's file, so it counts only when every name in it means the same symbol at each use site and
33
+ * at the declaration (a type of another file, not imported there, would not compile); no import is added.
34
+ */
35
+ static agreedType(opts: {
36
+ typescript: typeof import('typescript');
37
+ checker: import('typescript').TypeChecker;
38
+ entry: IKeyClaims;
39
+ }): string | undefined;
19
40
  static rewrite(opts: {
20
41
  typescript: typeof import('typescript');
21
42
  fileName: string;
@@ -29,11 +50,17 @@ export declare class BindingKeysCodemod {
29
50
  };
30
51
  /** Reads a file for the package.json lookup; defaults to the file system. */
31
52
  readFile?: (path: string) => string | undefined;
53
+ /** Out: the value type each use site claims for a key constant, by declaration (`<file>:<initializer start>`). */
54
+ claims?: Map<string, IKeyClaims>;
55
+ /** In: the type to build each key constant of THIS file with (`undefined` is `unknown`); a constant of this file not named here gets the type its own use sites agree on. */
56
+ declare?: Map<string, string | undefined>;
57
+ /** Whether a declaration in `fileName` may be edited: the files the run reads. Defaults to this file only. */
58
+ isEditable?: (fileName: string) => boolean;
32
59
  }): IBindingKeysResult;
33
60
  }
34
61
  /** `devz codemod binding-keys [paths...] [--write | --check]`: rewrites raw binding keys to `BindingKeys.build<T>`. */
35
62
  export declare class BindingKeysCommand {
36
- static readonly USAGE = "Usage: devz codemod binding-keys [paths...] [--write [--all] | --check] [--import-from <module>]\n\nRewrites the raw binding keys of the @venizia/ignis-inversion release where a key is made by BindingKeys.build<T>:\n\n container.get<Mailer>({ key: 'services.Mailer' }) becomes container.get({ key: BindingKeys.build<Mailer>({ key: 'services.Mailer' }) })\n container.bind({ key: 'services.Mailer' }) becomes container.bind({ key: BindingKeys.build<unknown>({ key: 'services.Mailer' }) })\n @inject({ key: 'services.Mailer' }) becomes @inject({ key: BindingKeys.build<unknown>({ key: 'services.Mailer' }) })\n container.get({ key: { namespace, key } }) becomes container.get({ key: BindingKeys.build<unknown>({ namespace, key }) })\n container.get({ key: `${namespace}.Name` }) becomes container.get({ key: BindingKeys.build<unknown>({ namespace, key: 'Name' }) })\n BindingKeys.build({ key }) becomes BindingKeys.build<unknown>({ key })\n\nThe key string is never changed.\n\nA call is rewritten only when the TypeScript checker resolves it to the framework's container (Container, IContainer,\nBinding) or to its inject and provide, under any local name. A redis.get<T>({ key }), a worker pool or a class of your own\nis left alone, type argument included. The checker reads your project through the nearest tsconfig.json, so run the codemod\nfrom the project root with the dependencies installed; a receiver it cannot resolve is listed as \"manual\". The call's own type argument moves into build<T>, so the caller keeps the type it\nclaimed; without one the codemod writes build<unknown> and lists the site (\"type\"): name the real type there.\n\nIt rewrites a call named get, gets, getBinding, bind, isBound or unbind whose argument is an object literal with a\n`key` (and, for get, `isOptional`), and a call of inject or provide. A container cannot be told from syntax, so the shape is the\ntest. A string key, a substitution-free template literal, a { namespace, key } literal and a template written\n${namespace}.Name or ${namespace}.${name} are rewritten. These are listed\nas \"manual\" and left alone: a key made at run time (a template with substitutions, a call) and a Symbol key (symbols are no\nlonger keys). A key that is a const of the file (const MAILER = 'services.Mailer') is rewritten where it is declared. Any\nother name or property (Keys.MAILER) is left alone without a line: it may already be a built key, and your typecheck\nnames a raw one.\n\nBindingKeys is imported from the module the file already takes inject from, else from the first @venizia/ignis import,\nor from --import-from <module>; a file with none of them is listed as manual and not rewritten. An existing import of\nBindingKeys is reused. A second run changes nothing.\n\nIt reads TypeScript files (.ts, .tsx, .mts, .cts). A .js, .cjs or .mjs file is not read: edit it by hand.\n\n --write write the changed files (without it, nothing is written); it needs a path, or --all\n --all with --write and no path: rewrite every source file under the working directory\n --check dry run that exits 1 while a file would change or a manual site remains (for CI)\n --import-from the module BindingKeys is imported from when the file gives no better one\n --help print this text and exit\n\nWith no flag it lists what would change and writes nothing. Inside a git repository it reads the files git knows, and\n--write refuses a file with local changes: commit or stash it first, so git can undo it.\nThere is no --reverse: a downgrade restores the files from git.";
63
+ static readonly USAGE = "Usage: devz codemod binding-keys [paths...] [--write [--all] | --check] [--import-from <module>]\n\nRewrites the raw binding keys of the @venizia/ignis-inversion release where a key is made by BindingKeys.build<T>:\n\n container.get<Mailer>({ key: 'services.Mailer' }) becomes container.get({ key: BindingKeys.build<Mailer>({ key: 'services.Mailer' }) })\n container.bind({ key: 'services.Mailer' }) becomes container.bind({ key: BindingKeys.build<unknown>({ key: 'services.Mailer' }) })\n @inject({ key: 'services.Mailer' }) becomes @inject({ key: BindingKeys.build<unknown>({ key: 'services.Mailer' }) })\n container.get({ key: { namespace, key } }) becomes container.get({ key: BindingKeys.build<unknown>({ namespace, key }) })\n container.get({ key: `${namespace}.Name` }) becomes container.get({ key: BindingKeys.build<unknown>({ namespace, key: 'Name' }) })\n BindingKeys.build({ key }) becomes BindingKeys.build<unknown>({ key })\n\nThe key string is never changed.\n\nA call is rewritten only when the TypeScript checker resolves it to the framework's container (Container, IContainer,\nBinding) or to its inject and provide, under any local name. A redis.get<T>({ key }), a worker pool or a class of your own\nis left alone, type argument included. The checker reads your project through the nearest tsconfig.json, so run the codemod\nfrom the project root with the dependencies installed; a receiver it cannot resolve is listed as \"manual\". The call's own type argument moves into build<T>, so the caller keeps the type it\nclaimed; without one the codemod writes build<unknown> and lists the site (\"type\"): name the real type there.\n\nIt rewrites a call named get, gets, getBinding, bind, isBound or unbind whose argument is an object literal with a\n`key` (and, for get, `isOptional`), and a call of inject or provide. A container cannot be told from syntax, so the shape is the\ntest. A string key, a substitution-free template literal, a { namespace, key } literal and a template written\n${namespace}.Name or ${namespace}.${name} are rewritten. These are listed\nas \"manual\" and left alone: a key made at run time (a template with substitutions, a call) and a Symbol key (symbols are no\nlonger keys). A key held in a name (MAILER, Keys.MAILER) is built where it is declared, in any file of the run: a const, a\nreadonly property or a property of an object literal, with a string initializer and no type annotation. Its type is the\none type its use sites claim (get<Mailer>, the type of a decorated parameter), else unknown (listed as \"type\"); the use\nsites are not edited. A name declared another way (a let, an annotation, a parameter, a call, a package you do not own)\nis listed as \"manual\". build throws on an empty key, so a computed constant that comes out '' now throws when its class loads.\n\nBindingKeys is imported from the module the file already takes inject from, else from the first @venizia/ignis import,\nor from --import-from <module>; a file with none of them is listed as manual and not rewritten. An existing import of\nBindingKeys is reused. A second run changes nothing.\n\nIt reads TypeScript files (.ts, .tsx, .mts, .cts). A .js, .cjs or .mjs file is not read: edit it by hand.\n\n --write write the changed files (without it, nothing is written); it needs a path, or --all\n --all with --write and no path: rewrite every source file under the working directory\n --check dry run that exits 1 while a file would change or a manual site remains (for CI)\n --import-from the module BindingKeys is imported from when the file gives no better one\n --help print this text and exit\n\nWith no flag it lists what would change and writes nothing. Inside a git repository it reads the files git knows, and\n--write refuses a file with local changes: commit or stash it first, so git can undo it.\nThere is no --reverse: a downgrade restores the files from git.";
37
64
  /**
38
65
  * The program the checker answers from: the project's own tsconfig (the nearest one above `root`) with the files the
39
66
  * codemod reads added, so a receiver resolves the way the project's typecheck resolves it.
@@ -28,9 +28,11 @@ It rewrites a call named get, gets, getBinding, bind, isBound or unbind whose ar
28
28
  test. A string key, a substitution-free template literal, a { namespace, key } literal and a template written
29
29
  \${namespace}.Name or \${namespace}.\${name} are rewritten. These are listed
30
30
  as "manual" and left alone: a key made at run time (a template with substitutions, a call) and a Symbol key (symbols are no
31
- longer keys). A key that is a const of the file (const MAILER = 'services.Mailer') is rewritten where it is declared. Any
32
- other name or property (Keys.MAILER) is left alone without a line: it may already be a built key, and your typecheck
33
- names a raw one.
31
+ longer keys). A key held in a name (MAILER, Keys.MAILER) is built where it is declared, in any file of the run: a const, a
32
+ readonly property or a property of an object literal, with a string initializer and no type annotation. Its type is the
33
+ one type its use sites claim (get<Mailer>, the type of a decorated parameter), else unknown (listed as "type"); the use
34
+ sites are not edited. A name declared another way (a let, an annotation, a parameter, a call, a package you do not own)
35
+ is listed as "manual". build throws on an empty key, so a computed constant that comes out '' now throws when its class loads.
34
36
 
35
37
  BindingKeys is imported from the module the file already takes inject from, else from the first @venizia/ignis import,
36
38
  or from --import-from <module>; a file with none of them is listed as manual and not rewritten. An existing import of
@@ -146,8 +148,35 @@ class BindingKeysCodemod {
146
148
  }
147
149
  return BUILDER;
148
150
  }
151
+ /**
152
+ * The type a key constant is built with: the one type its use sites claim, else `undefined` (`unknown`). A type is copied as
153
+ * text into the declaration's file, so it counts only when every name in it means the same symbol at each use site and
154
+ * at the declaration (a type of another file, not imported there, would not compile); no import is added.
155
+ */
156
+ static agreedType(opts) {
157
+ const { typescript: ts, checker, entry } = opts;
158
+ const named = entry.claims.filter((claim) => claim.text !== undefined);
159
+ const texts = new Set(named.map((claim) => claim.text));
160
+ if (texts.size !== 1) {
161
+ return undefined;
162
+ }
163
+ // An exported declaration has a local symbol and an export symbol; an import resolves to the export one.
164
+ const dealias = (symbol) => symbol === undefined
165
+ ? undefined
166
+ : checker.getExportSymbolOfSymbol(symbol.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(symbol) : symbol);
167
+ const flags = ts.SymbolFlags.Type | ts.SymbolFlags.Value | ts.SymbolFlags.Namespace | ts.SymbolFlags.Alias;
168
+ const inScope = checker.getSymbolsInScope(entry.declaration, flags);
169
+ for (const { name } of named[0].names) {
170
+ const here = dealias(inScope.find((candidate) => candidate.name === name));
171
+ if (here === undefined ||
172
+ named.some((claim) => claim.names.some((other) => other.name === name && dealias(other.symbol) !== here))) {
173
+ return undefined;
174
+ }
175
+ }
176
+ return named[0].text;
177
+ }
149
178
  static rewrite(opts) {
150
- const { typescript: ts, fileName, importFrom, program, readFile = (path) => ts.sys.readFile(path), } = opts;
179
+ const { typescript: ts, fileName, importFrom, program, readFile = (path) => ts.sys.readFile(path), claims = new Map(), } = opts;
151
180
  const language = fileName.endsWith('.tsx') ? ts.ScriptKind.TSX : ts.ScriptKind.TS;
152
181
  const file = program?.sourceFile ??
153
182
  ts.createSourceFile(fileName, opts.source, ts.ScriptTarget.Latest, true, language);
@@ -158,11 +187,9 @@ class BindingKeysCodemod {
158
187
  const manual = [];
159
188
  const unnamed = [];
160
189
  const handled = new Set();
161
- /** `const NAME = 'literal'` declared once in the file: a key held in a constant is rewritten where it is declared. */
162
- const constants = new Map();
163
- const duplicates = new Set();
164
190
  let rewritten = 0;
165
191
  const lineOf = (node) => file.getLineAndCharacterOfPosition(node.getStart(file)).line + 1;
192
+ const isEditable = opts.isEditable ?? ((name) => name === file.fileName);
166
193
  const propertyOf = (node, name) => {
167
194
  for (const property of node.properties) {
168
195
  if (ts.isPropertyAssignment(property) &&
@@ -218,17 +245,102 @@ class BindingKeysCodemod {
218
245
  }
219
246
  return undefined;
220
247
  };
248
+ /** An object literal under `as const`: its properties are readonly, as a `readonly` class property is. */
249
+ const isConstObject = (node) => ts.isObjectLiteralExpression(node) &&
250
+ ts.isAsExpression(node.parent) &&
251
+ ts.isTypeReferenceNode(node.parent.type) &&
252
+ ts.isIdentifier(node.parent.type.typeName) &&
253
+ node.parent.type.typeName.text === 'const';
254
+ /**
255
+ * The declaration of a key held in a name (`MAILER`, `Keys.MAILER`) that the codemod may build where it is made: a const, a
256
+ * readonly property or a property of an object literal, with a string initializer, no type annotation, in a file of the
257
+ * run (not a declaration file, not node_modules). `undefined` when the name is anything else.
258
+ */
259
+ const heldDeclaration = (value) => {
260
+ if (checker === undefined) {
261
+ return undefined;
262
+ }
263
+ const name = ts.isPropertyAccessExpression(value) ? value.name : value;
264
+ let symbol = checker.getSymbolAtLocation(name);
265
+ if (symbol !== undefined && symbol.flags & ts.SymbolFlags.Alias) {
266
+ symbol = checker.getAliasedSymbol(symbol);
267
+ }
268
+ const declaration = symbol?.valueDeclaration;
269
+ const initializer = declaration !== undefined &&
270
+ (ts.isVariableDeclaration(declaration) ||
271
+ ts.isPropertyDeclaration(declaration) ||
272
+ ts.isPropertyAssignment(declaration))
273
+ ? declaration.initializer
274
+ : undefined;
275
+ if (declaration === undefined || initializer === undefined) {
276
+ return undefined;
277
+ }
278
+ const isHeld = ts.isVariableDeclaration(declaration)
279
+ ? ts.isIdentifier(declaration.name) &&
280
+ (ts.getCombinedNodeFlags(declaration) & ts.NodeFlags.Const) !== 0 &&
281
+ declaration.type === undefined
282
+ : ts.isPropertyDeclaration(declaration)
283
+ ? (ts.getCombinedModifierFlags(declaration) & ts.ModifierFlags.Readonly) !== 0 &&
284
+ declaration.type === undefined
285
+ : isConstObject(declaration.parent);
286
+ const declared = declaration.getSourceFile();
287
+ const type = checker.getTypeAtLocation(initializer);
288
+ if (!isHeld ||
289
+ declared.isDeclarationFile ||
290
+ declared.fileName.includes('/node_modules/') ||
291
+ !isEditable(declared.fileName) ||
292
+ !(type.flags & ts.TypeFlags.StringLike) ||
293
+ type.getProperty('valueType') !== undefined) {
294
+ return undefined;
295
+ }
296
+ return {
297
+ initializer,
298
+ key: `${declared.fileName}:${initializer.getStart(declared)}`,
299
+ declaration,
300
+ };
301
+ };
302
+ /** The names a type mentions (`Mailer`, the head of `ns.Mailer`, `typeof X`) with what each means at the use site. */
303
+ const namesOf = (type) => {
304
+ const found = new Map();
305
+ const flags = ts.SymbolFlags.Type |
306
+ ts.SymbolFlags.Value |
307
+ ts.SymbolFlags.Namespace |
308
+ ts.SymbolFlags.Alias;
309
+ const inScope = checker?.getSymbolsInScope(type, flags) ?? [];
310
+ const head = (name) => ts.isIdentifier(name) ? name.text : head(name.left);
311
+ const search = (node) => {
312
+ // `import('../mailer').Mailer` names a path that means something only from the file that wrote it.
313
+ if (ts.isImportTypeNode(node)) {
314
+ found.set(`import(${node.argument.getText()})`, undefined);
315
+ }
316
+ const name = ts.isTypeReferenceNode(node)
317
+ ? node.typeName
318
+ : ts.isTypeQueryNode(node)
319
+ ? node.exprName
320
+ : undefined;
321
+ if (name !== undefined) {
322
+ const text = head(name);
323
+ found.set(text, inScope.find((candidate) => candidate.name === text));
324
+ }
325
+ ts.forEachChild(node, search);
326
+ };
327
+ search(type);
328
+ return [...found].map(([name, symbol]) => ({ name, symbol }));
329
+ };
221
330
  /**
222
331
  * Wraps the key of one options object. `typeText` is the value type the call already claimed, or `undefined` for
223
332
  * `unknown`. Answers whether the key was rewritten.
224
333
  */
225
- const rewriteKey = (options, typeText) => {
334
+ const rewriteKey = (options, typeText, typeNode) => {
226
335
  const property = propertyOf(options, 'key');
227
336
  if (property === undefined) {
228
337
  return false;
229
338
  }
230
339
  const value = property.initializer;
231
340
  const text = typeText ?? 'unknown';
341
+ const held = ts.isIdentifier(value) || ts.isPropertyAccessExpression(value)
342
+ ? heldDeclaration(value)
343
+ : undefined;
232
344
  if (ts.isStringLiteral(value) || ts.isNoSubstitutionTemplateLiteral(value)) {
233
345
  edits.push({
234
346
  start: value.getStart(file),
@@ -254,24 +366,15 @@ class BindingKeysCodemod {
254
366
  text: `${builder}.build<${text}>(${namespaceKeyOf(value)})`,
255
367
  });
256
368
  }
257
- else if (ts.isIdentifier(value) &&
258
- constants.has(value.text) &&
259
- !duplicates.has(value.text)) {
260
- const declaration = constants.get(value.text);
261
- if (declaration?.initializer === undefined || handled.has(declaration)) {
262
- return false;
263
- }
264
- handled.add(declaration);
265
- edits.push({
266
- start: declaration.initializer.getStart(file),
267
- end: declaration.initializer.getEnd(),
268
- text: `${builder}.build<${text}>({ key: ${declaration.initializer.getText(file)} })`,
369
+ else if (held !== undefined) {
370
+ // The key is built where it is declared (the claim is answered once every file is read); this site needs no edit.
371
+ const entry = claims.get(held.key) ?? { declaration: held.declaration, claims: [] };
372
+ entry.claims.push({
373
+ text: typeText,
374
+ names: typeNode === undefined ? [] : namesOf(typeNode),
269
375
  });
270
- if (typeText === undefined) {
271
- unnamed.push(lineOf(declaration));
272
- }
273
- rewritten += 1;
274
- return true;
376
+ claims.set(held.key, entry);
377
+ return false;
275
378
  }
276
379
  else if (isBuilderCall(value)) {
277
380
  if (value.typeArguments !== undefined) {
@@ -481,7 +584,7 @@ class BindingKeysCodemod {
481
584
  : decorated === undefined
482
585
  ? undefined
483
586
  : liftedTypeText(decorated);
484
- const done = rewriteKey(first, typeText);
587
+ const done = rewriteKey(first, typeText, callArgument ?? decorated);
485
588
  // The type argument moved into `build<T>`; the call no longer needs it. Comments inside it stay.
486
589
  if (done && callArgument !== undefined) {
487
590
  const open = node.expression.getEnd();
@@ -498,22 +601,36 @@ class BindingKeysCodemod {
498
601
  }
499
602
  ts.forEachChild(node, visit);
500
603
  };
501
- const collect = (node) => {
502
- if (ts.isVariableDeclaration(node) &&
503
- ts.isIdentifier(node.name) &&
504
- node.initializer !== undefined &&
505
- (ts.isStringLiteral(node.initializer) ||
506
- ts.isNoSubstitutionTemplateLiteral(node.initializer)) &&
507
- (ts.getCombinedNodeFlags(node) & ts.NodeFlags.Const) !== 0) {
508
- if (constants.has(node.name.text)) {
509
- duplicates.add(node.name.text);
510
- }
511
- constants.set(node.name.text, node);
512
- }
513
- ts.forEachChild(node, collect);
514
- };
515
- collect(file);
516
604
  visit(file);
605
+ // A key constant of this file: build it with the type its use sites agree on, or the one the run settled.
606
+ const build = new Map(opts.declare);
607
+ for (const [key, entry] of claims) {
608
+ if (key.startsWith(`${file.fileName}:`) && !build.has(key) && checker !== undefined) {
609
+ build.set(key, BindingKeysCodemod.agreedType({ typescript: ts, checker, entry }));
610
+ }
611
+ }
612
+ if (build.size > 0) {
613
+ const declare = (node) => {
614
+ if ((ts.isVariableDeclaration(node) ||
615
+ ts.isPropertyDeclaration(node) ||
616
+ ts.isPropertyAssignment(node)) &&
617
+ node.initializer !== undefined &&
618
+ build.has(`${file.fileName}:${node.initializer.getStart(file)}`)) {
619
+ const type = build.get(`${file.fileName}:${node.initializer.getStart(file)}`);
620
+ edits.push({
621
+ start: node.initializer.getStart(file),
622
+ end: node.initializer.getEnd(),
623
+ text: `${builder}.build<${type ?? 'unknown'}>({ key: ${node.initializer.getText(file)} })`,
624
+ });
625
+ rewritten += 1;
626
+ if (type === undefined) {
627
+ unnamed.push(lineOf(node.initializer));
628
+ }
629
+ }
630
+ ts.forEachChild(node, declare);
631
+ };
632
+ declare(file);
633
+ }
517
634
  if (edits.length === 0) {
518
635
  return { output: source, changed: false, rewritten, unnamed, manual };
519
636
  }
@@ -660,6 +777,33 @@ class BindingKeysCommand {
660
777
  files: collected.flat(),
661
778
  });
662
779
  const checker = program.getTypeChecker();
780
+ const prefilter = /\b(?:get|gets|getBinding|bind|isBound|unbind|inject|provide|build)\b/;
781
+ const editable = new Set(collected.flat().map((file) => (0, node_path_1.resolve)(file)));
782
+ const isEditable = (fileName) => editable.has((0, node_path_1.resolve)(fileName));
783
+ // First pass: every use site of a key held in a constant claims a type for the constant's declaration, which can be in
784
+ // another file. The answer is one type per declaration, so the second pass edits each declaration once.
785
+ const claims = new Map();
786
+ for (const file of collected.flat()) {
787
+ const source = (0, node_fs_1.readFileSync)(file, 'utf8');
788
+ const sourceFile = program.getSourceFile(file);
789
+ if (sourceFile !== undefined && prefilter.test(source)) {
790
+ BindingKeysCodemod.rewrite({
791
+ typescript,
792
+ fileName: file,
793
+ source,
794
+ importFrom,
795
+ program: { sourceFile, checker },
796
+ claims,
797
+ isEditable,
798
+ });
799
+ }
800
+ }
801
+ const declare = new Map();
802
+ const declareFiles = new Set();
803
+ for (const [key, entry] of claims) {
804
+ declare.set(key, BindingKeysCodemod.agreedType({ typescript, checker, entry }));
805
+ declareFiles.add(entry.declaration.getSourceFile().fileName);
806
+ }
663
807
  for (const [index, target] of targets.entries()) {
664
808
  const files = collected[index];
665
809
  const dirty = isWrite ? files_1.CodemodFiles.dirty({ target }) : undefined;
@@ -668,16 +812,18 @@ class BindingKeysCommand {
668
812
  }
669
813
  for (const file of files) {
670
814
  const source = (0, node_fs_1.readFileSync)(file, 'utf8');
671
- if (!/\b(?:get|gets|getBinding|bind|isBound|unbind|inject|provide|build)\b/.test(source)) {
815
+ const sourceFile = program.getSourceFile(file);
816
+ if (!prefilter.test(source) && !declareFiles.has(sourceFile?.fileName ?? file)) {
672
817
  continue;
673
818
  }
674
- const sourceFile = program.getSourceFile(file);
675
819
  const result = BindingKeysCodemod.rewrite({
676
820
  typescript,
677
821
  fileName: file,
678
822
  source,
679
823
  importFrom,
680
824
  program: sourceFile === undefined ? undefined : { sourceFile, checker },
825
+ declare,
826
+ isEditable,
681
827
  });
682
828
  const shown = (0, node_path_1.relative)(root, file).split('\\').join('/') || file;
683
829
  for (const item of result.manual) {