@venizia/dev-configs 0.4.8-9 → 0.5.0-0

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.
@@ -0,0 +1,716 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.BindingKeysCommand = exports.BindingKeysCodemod = void 0;
4
+ const node_fs_1 = require("node:fs");
5
+ const node_path_1 = require("node:path");
6
+ const files_1 = require("./files");
7
+ const USAGE = `Usage: devz codemod binding-keys [paths...] [--write [--all] | --check] [--import-from <module>]
8
+
9
+ Rewrites the raw binding keys of the @venizia/ignis-inversion release where a key is made by BindingKeys.build<T>:
10
+
11
+ container.get<Mailer>({ key: 'services.Mailer' }) becomes container.get({ key: BindingKeys.build<Mailer>({ key: 'services.Mailer' }) })
12
+ container.bind({ key: 'services.Mailer' }) becomes container.bind({ key: BindingKeys.build<unknown>({ key: 'services.Mailer' }) })
13
+ @inject({ key: 'services.Mailer' }) becomes @inject({ key: BindingKeys.build<unknown>({ key: 'services.Mailer' }) })
14
+ container.get({ key: { namespace, key } }) becomes container.get({ key: BindingKeys.build<unknown>({ namespace, key }) })
15
+ container.get({ key: \`\${namespace}.Name\` }) becomes container.get({ key: BindingKeys.build<unknown>({ namespace, key: 'Name' }) })
16
+ BindingKeys.build({ key }) becomes BindingKeys.build<unknown>({ key })
17
+
18
+ The key string is never changed.
19
+
20
+ A call is rewritten only when the TypeScript checker resolves it to the framework's container (Container, IContainer,
21
+ Binding) or to its inject and provide, under any local name. A redis.get<T>({ key }), a worker pool or a class of your own
22
+ is left alone, type argument included. The checker reads your project through the nearest tsconfig.json, so run the codemod
23
+ from 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
24
+ claimed; without one the codemod writes build<unknown> and lists the site ("type"): name the real type there.
25
+
26
+ It rewrites a call named get, gets, getBinding, bind, isBound or unbind whose argument is an object literal with a
27
+ \`key\` (and, for get, \`isOptional\`), and a call of inject or provide. A container cannot be told from syntax, so the shape is the
28
+ test. A string key, a substitution-free template literal, a { namespace, key } literal and a template written
29
+ \${namespace}.Name or \${namespace}.\${name} are rewritten. These are listed
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.
34
+
35
+ BindingKeys is imported from the module the file already takes inject from, else from the first @venizia/ignis import,
36
+ or from --import-from <module>; a file with none of them is listed as manual and not rewritten. An existing import of
37
+ BindingKeys is reused. A second run changes nothing.
38
+
39
+ It reads TypeScript files (.ts, .tsx, .mts, .cts). A .js, .cjs or .mjs file is not read: edit it by hand.
40
+
41
+ --write write the changed files (without it, nothing is written); it needs a path, or --all
42
+ --all with --write and no path: rewrite every source file under the working directory
43
+ --check dry run that exits 1 while a file would change or a manual site remains (for CI)
44
+ --import-from the module BindingKeys is imported from when the file gives no better one
45
+ --help print this text and exit
46
+
47
+ With no flag it lists what would change and writes nothing. Inside a git repository it reads the files git knows, and
48
+ --write refuses a file with local changes: commit or stash it first, so git can undo it.
49
+ There is no --reverse: a downgrade restores the files from git.`;
50
+ /** A usage error: nothing was read or written. */
51
+ const USAGE_ERROR_CODE = 2;
52
+ /** The methods whose options object carries a container key. */
53
+ const KEY_METHODS = new Set(['get', 'gets', 'getBinding', 'bind', 'isBound', 'unbind']);
54
+ /** The other properties a key options object may carry and still be one. */
55
+ const OPTION_NAMES = new Set(['key', 'isOptional', 'scope']);
56
+ /** The decorators that take a key options object. */
57
+ const KEY_DECORATORS = new Set(['inject', 'provide']);
58
+ /** Where a file already imports the container API from. */
59
+ const IGNIS_MODULE = /^@venizia\/ignis(?:-kernel|-inversion)?$/;
60
+ const BUILDER = 'BindingKeys';
61
+ /** The classes and interfaces whose key methods are the container's. */
62
+ const CONTAINER_TYPES = new Set([
63
+ 'IContainer',
64
+ 'AbstractContainer',
65
+ 'BaseContainer',
66
+ 'Container',
67
+ 'Binding',
68
+ ]);
69
+ /** The packages that declare the container: the framework is identified by name, wherever it is installed or checked out. */
70
+ const FRAMEWORK_PACKAGES = new Set([
71
+ '@venizia/ignis',
72
+ '@venizia/ignis-inversion',
73
+ '@venizia/ignis-kernel',
74
+ ]);
75
+ /** A module of the framework: a file's own barrel is not a place to take `BindingKeys` from. */
76
+ const VENIZIA_MODULE = /^@venizia\//;
77
+ class BindingKeysFlags {
78
+ static { this.WRITE = '--write'; }
79
+ static { this.ALL = '--all'; }
80
+ static { this.CHECK = '--check'; }
81
+ static { this.IMPORT_FROM = '--import-from'; }
82
+ static { this.HELP = '--help'; }
83
+ static { this.HELP_SHORT = '-h'; }
84
+ static { this.SCHEME_SET = new Set([
85
+ this.WRITE,
86
+ this.ALL,
87
+ this.CHECK,
88
+ this.IMPORT_FROM,
89
+ this.HELP,
90
+ this.HELP_SHORT,
91
+ ]); }
92
+ static isValid(value) {
93
+ return this.SCHEME_SET.has(value);
94
+ }
95
+ }
96
+ /** Rewrites raw binding keys to `BindingKeys.build<T>({ key })`. */
97
+ class BindingKeysCodemod {
98
+ /** The module `BindingKeys` comes from in this file: an existing import, the module of `inject`, a @venizia/ignis import, or `fallback`. */
99
+ static readIdentifierSource(opts) {
100
+ const { typescript: ts, file, fallback } = opts;
101
+ let injectModule;
102
+ let ignisModule;
103
+ let named;
104
+ let declared = false;
105
+ for (const statement of file.statements) {
106
+ if (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier)) {
107
+ continue;
108
+ }
109
+ const module = statement.moduleSpecifier.text;
110
+ const bindings = statement.importClause?.namedBindings;
111
+ const isTypeOnly = statement.importClause?.isTypeOnly === true;
112
+ if (bindings === undefined || !ts.isNamedImports(bindings)) {
113
+ continue;
114
+ }
115
+ for (const element of bindings.elements) {
116
+ const imported = (element.propertyName ?? element.name).text;
117
+ if (imported === BUILDER && !isTypeOnly && !element.isTypeOnly) {
118
+ declared = true;
119
+ }
120
+ if (imported === 'inject' && injectModule === undefined && VENIZIA_MODULE.test(module)) {
121
+ injectModule = module;
122
+ }
123
+ }
124
+ if (IGNIS_MODULE.test(module) && !isTypeOnly) {
125
+ ignisModule ??= module;
126
+ named ??= bindings;
127
+ }
128
+ }
129
+ return { module: injectModule ?? ignisModule ?? fallback, declared, named };
130
+ }
131
+ /** The local name `BindingKeys` is imported under (an alias included), or `BindingKeys` when the file does not import it. */
132
+ static readBuilderName(opts) {
133
+ const { typescript: ts, file } = opts;
134
+ for (const statement of file.statements) {
135
+ const bindings = ts.isImportDeclaration(statement)
136
+ ? statement.importClause?.namedBindings
137
+ : undefined;
138
+ if (bindings === undefined || !ts.isNamedImports(bindings)) {
139
+ continue;
140
+ }
141
+ for (const element of bindings.elements) {
142
+ if ((element.propertyName ?? element.name).text === BUILDER) {
143
+ return element.name.text;
144
+ }
145
+ }
146
+ }
147
+ return BUILDER;
148
+ }
149
+ static rewrite(opts) {
150
+ const { typescript: ts, fileName, importFrom, program, readFile = (path) => ts.sys.readFile(path), } = opts;
151
+ const language = fileName.endsWith('.tsx') ? ts.ScriptKind.TSX : ts.ScriptKind.TS;
152
+ const file = program?.sourceFile ??
153
+ ts.createSourceFile(fileName, opts.source, ts.ScriptTarget.Latest, true, language);
154
+ const source = file.text;
155
+ const checker = program?.checker;
156
+ const builder = BindingKeysCodemod.readBuilderName({ typescript: ts, file });
157
+ const edits = [];
158
+ const manual = [];
159
+ const unnamed = [];
160
+ 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
+ let rewritten = 0;
165
+ const lineOf = (node) => file.getLineAndCharacterOfPosition(node.getStart(file)).line + 1;
166
+ const propertyOf = (node, name) => {
167
+ for (const property of node.properties) {
168
+ if (ts.isPropertyAssignment(property) &&
169
+ (ts.isIdentifier(property.name) || ts.isStringLiteral(property.name)) &&
170
+ property.name.text === name) {
171
+ return property;
172
+ }
173
+ }
174
+ return undefined;
175
+ };
176
+ /** An object literal whose properties are all in `names` and that has a `key`: the shape of a key options object. */
177
+ const isKeyOptions = (node) => {
178
+ if (node === undefined || !ts.isObjectLiteralExpression(node)) {
179
+ return false;
180
+ }
181
+ return (propertyOf(node, 'key') !== undefined &&
182
+ node.properties.every((property) => ts.isPropertyAssignment(property) &&
183
+ (ts.isIdentifier(property.name) || ts.isStringLiteral(property.name)) &&
184
+ OPTION_NAMES.has(property.name.text)));
185
+ };
186
+ const isBuilderCall = (node) => ts.isCallExpression(node) &&
187
+ ts.isPropertyAccessExpression(node.expression) &&
188
+ ts.isIdentifier(node.expression.expression) &&
189
+ node.expression.expression.text === builder &&
190
+ node.expression.name.text === 'build';
191
+ const isSymbolExpression = (node) => (ts.isCallExpression(node) &&
192
+ ((ts.isIdentifier(node.expression) && node.expression.text === 'Symbol') ||
193
+ (ts.isPropertyAccessExpression(node.expression) &&
194
+ ts.isIdentifier(node.expression.expression) &&
195
+ node.expression.expression.text === 'Symbol'))) ||
196
+ (ts.isPropertyAccessExpression(node) &&
197
+ ts.isIdentifier(node.expression) &&
198
+ node.expression.text === 'Symbol');
199
+ /**
200
+ * The `{ namespace, key }` text of a template written as `${namespace}.Name` or `${namespace}.${name}` (the two
201
+ * shapes the framework's own keys take), or `undefined` for any other template.
202
+ */
203
+ const namespaceKeyOf = (node) => {
204
+ const { head, templateSpans } = node;
205
+ if (head.text !== '') {
206
+ return undefined;
207
+ }
208
+ if (templateSpans.length === 1 && templateSpans[0].literal.text.startsWith('.')) {
209
+ const tail = templateSpans[0].literal.text.slice(1);
210
+ return tail === ''
211
+ ? undefined
212
+ : `{ namespace: ${templateSpans[0].expression.getText(file)}, key: '${tail.replace(/'/g, "\\'")}' }`;
213
+ }
214
+ if (templateSpans.length === 2 &&
215
+ templateSpans[0].literal.text === '.' &&
216
+ templateSpans[1].literal.text === '') {
217
+ return `{ namespace: ${templateSpans[0].expression.getText(file)}, key: ${templateSpans[1].expression.getText(file)} }`;
218
+ }
219
+ return undefined;
220
+ };
221
+ /**
222
+ * Wraps the key of one options object. `typeText` is the value type the call already claimed, or `undefined` for
223
+ * `unknown`. Answers whether the key was rewritten.
224
+ */
225
+ const rewriteKey = (options, typeText) => {
226
+ const property = propertyOf(options, 'key');
227
+ if (property === undefined) {
228
+ return false;
229
+ }
230
+ const value = property.initializer;
231
+ const text = typeText ?? 'unknown';
232
+ if (ts.isStringLiteral(value) || ts.isNoSubstitutionTemplateLiteral(value)) {
233
+ edits.push({
234
+ start: value.getStart(file),
235
+ end: value.getEnd(),
236
+ text: `${builder}.build<${text}>({ key: ${value.getText(file)} })`,
237
+ });
238
+ }
239
+ else if (ts.isObjectLiteralExpression(value) &&
240
+ propertyOf(value, 'key') !== undefined &&
241
+ value.properties.every((item) => ts.isPropertyAssignment(item) &&
242
+ ts.isIdentifier(item.name) &&
243
+ (item.name.text === 'key' || item.name.text === 'namespace'))) {
244
+ edits.push({
245
+ start: value.getStart(file),
246
+ end: value.getEnd(),
247
+ text: `${builder}.build<${text}>(${value.getText(file)})`,
248
+ });
249
+ }
250
+ else if (ts.isTemplateExpression(value) && namespaceKeyOf(value) !== undefined) {
251
+ edits.push({
252
+ start: value.getStart(file),
253
+ end: value.getEnd(),
254
+ text: `${builder}.build<${text}>(${namespaceKeyOf(value)})`,
255
+ });
256
+ }
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)} })`,
269
+ });
270
+ if (typeText === undefined) {
271
+ unnamed.push(lineOf(declaration));
272
+ }
273
+ rewritten += 1;
274
+ return true;
275
+ }
276
+ else if (isBuilderCall(value)) {
277
+ if (value.typeArguments !== undefined) {
278
+ return false;
279
+ }
280
+ handled.add(value);
281
+ // `BindingKeys.build(` then the argument: the type argument goes between the name and the parenthesis.
282
+ edits.push({
283
+ start: value.expression.getEnd(),
284
+ end: value.expression.getEnd(),
285
+ text: `<${text}>`,
286
+ });
287
+ }
288
+ else if (isSymbolExpression(value)) {
289
+ manual.push({
290
+ line: lineOf(value),
291
+ reason: 'a Symbol key: symbols are no longer binding keys, use BindingKeys.build<T>({ key: "..." })',
292
+ });
293
+ return false;
294
+ }
295
+ else {
296
+ // A name or a property (`MAILER`, `Keys.MAILER`) may already be a built key, and the typecheck names a raw
297
+ // one: only an expression that makes a string at run time is listed.
298
+ const isReference = ts.isIdentifier(value) ||
299
+ ts.isPropertyAccessExpression(value) ||
300
+ ts.isElementAccessExpression(value);
301
+ if (isReference && checker !== undefined) {
302
+ const type = checker.getTypeAtLocation(value);
303
+ if (type.flags & ts.TypeFlags.StringLike && type.getProperty('valueType') === undefined) {
304
+ manual.push({
305
+ line: lineOf(value),
306
+ reason: 'a string held in a name: build it with BindingKeys.build<T>({ key }) where it is defined (a key of a package you do not own is built by that package)',
307
+ });
308
+ }
309
+ }
310
+ if (!isReference) {
311
+ manual.push({
312
+ line: lineOf(value),
313
+ reason: 'a key made at run time (a template with substitutions, a call): build it with BindingKeys.build<T>({ key }) where it is made',
314
+ });
315
+ }
316
+ return false;
317
+ }
318
+ rewritten += 1;
319
+ if (typeText === undefined) {
320
+ unnamed.push(lineOf(value));
321
+ }
322
+ return true;
323
+ };
324
+ /** The declaration the checker resolves a call to, or `undefined` when it cannot (an unresolved receiver). */
325
+ const declarationOf = (node) => checker?.getResolvedSignature(node)?.declaration;
326
+ const packageNames = new Map();
327
+ /** The name in the nearest package.json above `directory`, or `undefined` when there is none. */
328
+ const packageNameAbove = (directory) => {
329
+ if (packageNames.has(directory)) {
330
+ return packageNames.get(directory);
331
+ }
332
+ const text = readFile((0, node_path_1.join)(directory, 'package.json'));
333
+ const parent = (0, node_path_1.dirname)(directory);
334
+ let name;
335
+ if (text !== undefined) {
336
+ const parsed = JSON.parse(text);
337
+ name =
338
+ typeof parsed === 'object' &&
339
+ parsed !== null &&
340
+ 'name' in parsed &&
341
+ typeof parsed.name === 'string'
342
+ ? parsed.name
343
+ : '';
344
+ }
345
+ else if (parent !== directory) {
346
+ name = packageNameAbove(parent);
347
+ }
348
+ packageNames.set(directory, name);
349
+ return name;
350
+ };
351
+ /** A declaration of the framework: the nearest package.json above its file names one of the framework's packages. */
352
+ const isFrameworkFile = (declaration) => {
353
+ const name = packageNameAbove((0, node_path_1.dirname)(declaration.getSourceFile().fileName));
354
+ return name !== undefined && FRAMEWORK_PACKAGES.has(name);
355
+ };
356
+ /** `container.get(...)`: the checker resolves the method to the container's (or `Binding`'s), declared by the framework. */
357
+ const isContainerMethod = (declaration) => {
358
+ if (declaration === undefined || !isFrameworkFile(declaration)) {
359
+ return false;
360
+ }
361
+ const owner = declaration.parent;
362
+ return ((ts.isClassLike(owner) || ts.isInterfaceDeclaration(owner)) &&
363
+ owner.name !== undefined &&
364
+ CONTAINER_TYPES.has(owner.name.text));
365
+ };
366
+ /** `inject(...)` or `provide(...)` under any local name: the checker follows the import to the framework's. */
367
+ const isFrameworkDecorator = (callee) => {
368
+ if (checker === undefined || !ts.isIdentifier(callee)) {
369
+ return false;
370
+ }
371
+ const symbol = checker.getSymbolAtLocation(callee);
372
+ const target = symbol !== undefined && symbol.flags & ts.SymbolFlags.Alias
373
+ ? checker.getAliasedSymbol(symbol)
374
+ : symbol;
375
+ const declaration = target?.declarations?.[0];
376
+ return (declaration !== undefined &&
377
+ KEY_DECORATORS.has(target?.name ?? '') &&
378
+ isFrameworkFile(declaration));
379
+ };
380
+ /** Whether a type mentions a type parameter of a function or class that encloses `from`. */
381
+ const mentionsScopedTypeParameter = (type, from) => {
382
+ const scoped = new Set();
383
+ for (let scope = from; scope !== undefined; scope = scope.parent) {
384
+ const parameters = ts.isFunctionLike(scope) || ts.isClassLike(scope) ? scope.typeParameters : undefined;
385
+ for (const parameter of parameters ?? []) {
386
+ scoped.add(parameter.name.text);
387
+ }
388
+ }
389
+ const search = (node) => (ts.isTypeReferenceNode(node) &&
390
+ ts.isIdentifier(node.typeName) &&
391
+ scoped.has(node.typeName.text)) ||
392
+ ts.forEachChild(node, (child) => (search(child) ? true : undefined)) === true;
393
+ return search(type);
394
+ };
395
+ /** The text of a decorated parameter's type with `undefined` left out: the key names what is injected, not its absence. */
396
+ const liftedTypeText = (type) => {
397
+ if (!ts.isUnionTypeNode(type)) {
398
+ return type.getText(file);
399
+ }
400
+ const kept = type.types.filter((member) => member.kind !== ts.SyntaxKind.UndefinedKeyword);
401
+ return kept.map((member) => member.getText(file)).join(' | ');
402
+ };
403
+ const visit = (node) => {
404
+ if (ts.isCallExpression(node)) {
405
+ const callee = node.expression;
406
+ const first = node.arguments[0];
407
+ const methodName = ts.isPropertyAccessExpression(callee) && KEY_METHODS.has(callee.name.text)
408
+ ? callee.name.text
409
+ : undefined;
410
+ if (isBuilderCall(node) &&
411
+ node.typeArguments === undefined &&
412
+ node.arguments.length === 1) {
413
+ if (handled.has(node)) {
414
+ ts.forEachChild(node, visit);
415
+ return;
416
+ }
417
+ const argument = node.arguments[0];
418
+ if (ts.isObjectLiteralExpression(argument) && propertyOf(argument, 'key') !== undefined) {
419
+ edits.push({
420
+ start: node.expression.getEnd(),
421
+ end: node.expression.getEnd(),
422
+ text: '<unknown>',
423
+ });
424
+ rewritten += 1;
425
+ unnamed.push(lineOf(node));
426
+ }
427
+ }
428
+ else if (methodName !== undefined || ts.isIdentifier(callee)) {
429
+ const isGets = methodName === 'gets' && first !== undefined && ts.isObjectLiteralExpression(first);
430
+ const hasShape = isGets || isKeyOptions(first);
431
+ const declaration = methodName === undefined ? undefined : declarationOf(node);
432
+ const isContainer = methodName === undefined
433
+ ? hasShape && isFrameworkDecorator(callee)
434
+ : hasShape && isContainerMethod(declaration);
435
+ if (hasShape && methodName !== undefined && !isContainer && declaration === undefined) {
436
+ manual.push({
437
+ line: lineOf(node),
438
+ reason: `${methodName}(...) with a key: the receiver's type is not resolved (no tsconfig reaches this file, or it is any), so it is not known to be the container: change it by hand if it is`,
439
+ });
440
+ }
441
+ if (isContainer && isGets && ts.isObjectLiteralExpression(first)) {
442
+ const list = propertyOf(first, 'bindings')?.initializer;
443
+ if (list !== undefined && ts.isArrayLiteralExpression(list)) {
444
+ for (const element of list.elements) {
445
+ if (isKeyOptions(element)) {
446
+ rewriteKey(element, undefined);
447
+ }
448
+ }
449
+ }
450
+ }
451
+ else if (isContainer && isKeyOptions(first)) {
452
+ // `@inject({ key }) service: Mailer`: the type the parameter or property already claims is the key's type.
453
+ const decorated = methodName === undefined &&
454
+ ts.isDecorator(node.parent) &&
455
+ (ts.isParameter(node.parent.parent) || ts.isPropertyDeclaration(node.parent.parent))
456
+ ? node.parent.parent.type
457
+ : undefined;
458
+ const callArgument = methodName !== undefined && node.typeArguments?.length === 1
459
+ ? node.typeArguments[0]
460
+ : undefined;
461
+ const claimed = callArgument ?? decorated;
462
+ // A type that names a type parameter of the enclosing code cannot go into `build<T>`: the check on the type
463
+ // argument is made while it is still unresolved.
464
+ if (claimed !== undefined && mentionsScopedTypeParameter(claimed, node)) {
465
+ manual.push({
466
+ line: lineOf(node),
467
+ reason: 'a key whose type names a type parameter of the enclosing code: a generic key factory builds BindingKeys.build<unknown> and returns it typed as TBindingKey<T>',
468
+ });
469
+ }
470
+ else {
471
+ const isKeyBuilt = (() => {
472
+ const value = propertyOf(first, 'key')?.initializer;
473
+ return (value !== undefined && isBuilderCall(value) && value.typeArguments !== undefined);
474
+ })();
475
+ if (!isKeyBuilt) {
476
+ const typeText = callArgument !== undefined
477
+ ? callArgument.getText(file)
478
+ : decorated === undefined
479
+ ? undefined
480
+ : liftedTypeText(decorated);
481
+ const done = rewriteKey(first, typeText);
482
+ // The type argument moved into `build<T>`; the call no longer needs it. Comments inside it stay.
483
+ if (done && callArgument !== undefined) {
484
+ const open = node.expression.getEnd();
485
+ const close = source.indexOf('(', callArgument.getEnd());
486
+ const comments = source
487
+ .slice(open, close)
488
+ .match(/\/\*[\s\S]*?\*\/|\/\/[^\n]*\n?/g);
489
+ edits.push({ start: open, end: close, text: comments ? comments.join(' ') : '' });
490
+ }
491
+ }
492
+ }
493
+ }
494
+ }
495
+ }
496
+ ts.forEachChild(node, visit);
497
+ };
498
+ const collect = (node) => {
499
+ if (ts.isVariableDeclaration(node) &&
500
+ ts.isIdentifier(node.name) &&
501
+ node.initializer !== undefined &&
502
+ (ts.isStringLiteral(node.initializer) ||
503
+ ts.isNoSubstitutionTemplateLiteral(node.initializer)) &&
504
+ (ts.getCombinedNodeFlags(node) & ts.NodeFlags.Const) !== 0) {
505
+ if (constants.has(node.name.text)) {
506
+ duplicates.add(node.name.text);
507
+ }
508
+ constants.set(node.name.text, node);
509
+ }
510
+ ts.forEachChild(node, collect);
511
+ };
512
+ collect(file);
513
+ visit(file);
514
+ if (edits.length === 0) {
515
+ return { output: source, changed: false, rewritten, unnamed, manual };
516
+ }
517
+ const { module, declared, named } = BindingKeysCodemod.readIdentifierSource({
518
+ typescript: ts,
519
+ file,
520
+ fallback: importFrom,
521
+ });
522
+ if (!declared && module === undefined) {
523
+ return {
524
+ output: source,
525
+ changed: false,
526
+ rewritten: 0,
527
+ unnamed: [],
528
+ manual: [
529
+ ...manual,
530
+ {
531
+ line: 1,
532
+ reason: `${rewritten} key(s) could be rewritten but the file imports nothing from @venizia/ignis to take BindingKeys from: pass --import-from <module>`,
533
+ },
534
+ ],
535
+ };
536
+ }
537
+ if (!declared) {
538
+ if (named !== undefined && named.elements.length > 0) {
539
+ const last = named.elements[named.elements.length - 1];
540
+ edits.push({ start: last.getEnd(), end: last.getEnd(), text: `, ${BUILDER}` });
541
+ }
542
+ else {
543
+ const lastImport = [...file.statements]
544
+ .reverse()
545
+ .find((statement) => ts.isImportDeclaration(statement));
546
+ const position = lastImport === undefined ? 0 : lastImport.getEnd();
547
+ const text = `${lastImport === undefined ? '' : '\n'}import { ${builder} } from '${module}';${lastImport === undefined ? '\n' : ''}`;
548
+ edits.push({ start: position, end: position, text });
549
+ }
550
+ }
551
+ let output = source;
552
+ for (const edit of [...edits].sort((left, right) => right.start - left.start || right.end - left.end)) {
553
+ output = `${output.slice(0, edit.start)}${edit.text}${output.slice(edit.end)}`;
554
+ }
555
+ return { output, changed: output !== source, rewritten, unnamed, manual };
556
+ }
557
+ }
558
+ exports.BindingKeysCodemod = BindingKeysCodemod;
559
+ /** `devz codemod binding-keys [paths...] [--write | --check]`: rewrites raw binding keys to `BindingKeys.build<T>`. */
560
+ class BindingKeysCommand {
561
+ static { this.USAGE = USAGE; }
562
+ /**
563
+ * The program the checker answers from: the project's own tsconfig (the nearest one above `root`) with the files the
564
+ * codemod reads added, so a receiver resolves the way the project's typecheck resolves it.
565
+ */
566
+ static createProgram(opts) {
567
+ const { typescript: ts, root, files } = opts;
568
+ const configPath = ts.findConfigFile(root, (path) => ts.sys.fileExists(path), 'tsconfig.json');
569
+ const read = configPath === undefined
570
+ ? undefined
571
+ : ts.readConfigFile(configPath, (path) => ts.sys.readFile(path));
572
+ const parsed = configPath === undefined || read === undefined || read.error !== undefined
573
+ ? undefined
574
+ : ts.parseJsonConfigFileContent(read.config, ts.sys, (0, node_path_1.resolve)(configPath, '..'));
575
+ const options = {
576
+ target: ts.ScriptTarget.ESNext,
577
+ module: ts.ModuleKind.ESNext,
578
+ moduleResolution: ts.ModuleResolutionKind.Bundler,
579
+ experimentalDecorators: true,
580
+ ...parsed?.options,
581
+ noEmit: true,
582
+ skipLibCheck: true,
583
+ incremental: false,
584
+ composite: false,
585
+ allowJs: false,
586
+ };
587
+ return ts.createProgram({ rootNames: files, options });
588
+ }
589
+ static async run(opts) {
590
+ const { root, args } = opts;
591
+ if (args.includes(BindingKeysFlags.HELP) || args.includes(BindingKeysFlags.HELP_SHORT)) {
592
+ console.log(USAGE);
593
+ return 0;
594
+ }
595
+ const flags = [];
596
+ const paths = [];
597
+ let importFrom;
598
+ let hasImportFlag = false;
599
+ for (let index = 0; index < args.length; index += 1) {
600
+ const argument = args[index];
601
+ if (argument === BindingKeysFlags.IMPORT_FROM) {
602
+ hasImportFlag = true;
603
+ importFrom = args[index + 1];
604
+ index += 1;
605
+ }
606
+ else if (argument.startsWith('-')) {
607
+ flags.push(argument);
608
+ }
609
+ else {
610
+ paths.push(argument);
611
+ }
612
+ }
613
+ const unknown = flags.filter((flag) => !BindingKeysFlags.isValid(flag));
614
+ if (hasImportFlag && (importFrom === undefined || importFrom.startsWith('-'))) {
615
+ console.error(`devz codemod: ${BindingKeysFlags.IMPORT_FROM} needs a module\n${USAGE}`);
616
+ return USAGE_ERROR_CODE;
617
+ }
618
+ if (unknown.length > 0) {
619
+ console.error(`devz codemod: unknown option ${unknown.map((flag) => `"${flag}"`).join(', ')}\n${USAGE}`);
620
+ return USAGE_ERROR_CODE;
621
+ }
622
+ const isWrite = flags.includes(BindingKeysFlags.WRITE);
623
+ const isCheck = flags.includes(BindingKeysFlags.CHECK);
624
+ if (isWrite && isCheck) {
625
+ console.error(`devz codemod: ${BindingKeysFlags.WRITE} and ${BindingKeysFlags.CHECK} contradict each other\n${USAGE}`);
626
+ return USAGE_ERROR_CODE;
627
+ }
628
+ const refusal = files_1.CodemodFiles.refusal({
629
+ command: 'binding-keys',
630
+ isWrite,
631
+ isAll: flags.includes(BindingKeysFlags.ALL),
632
+ paths,
633
+ });
634
+ if (refusal) {
635
+ console.error(`${refusal}\n${USAGE}`);
636
+ return USAGE_ERROR_CODE;
637
+ }
638
+ let typescript;
639
+ try {
640
+ const loaded = await import('typescript');
641
+ typescript = loaded.default;
642
+ }
643
+ catch {
644
+ console.error('devz codemod: the "typescript" package is required to read your sources');
645
+ return 1;
646
+ }
647
+ const targets = (paths.length > 0 ? paths : ['.']).map((path) => (0, node_path_1.resolve)(root, path));
648
+ let changedCount = 0;
649
+ let rewrittenCount = 0;
650
+ let manualCount = 0;
651
+ let unnamedCount = 0;
652
+ let refusedCount = 0;
653
+ const collected = targets.map((target) => files_1.CodemodFiles.collect({ target }));
654
+ const program = BindingKeysCommand.createProgram({
655
+ typescript,
656
+ root,
657
+ files: collected.flat(),
658
+ });
659
+ const checker = program.getTypeChecker();
660
+ for (const [index, target] of targets.entries()) {
661
+ const files = collected[index];
662
+ const dirty = isWrite ? files_1.CodemodFiles.dirty({ target }) : undefined;
663
+ if (files.length === 0 && paths.length > 0) {
664
+ console.warn(`devz codemod: no source files under "${(0, node_path_1.relative)(root, target) || target}" (git ignores the path, or it holds none): nothing was read`);
665
+ }
666
+ for (const file of files) {
667
+ const source = (0, node_fs_1.readFileSync)(file, 'utf8');
668
+ if (!/\b(?:get|gets|getBinding|bind|isBound|unbind|inject|provide|build)\b/.test(source)) {
669
+ continue;
670
+ }
671
+ const sourceFile = program.getSourceFile(file);
672
+ const result = BindingKeysCodemod.rewrite({
673
+ typescript,
674
+ fileName: file,
675
+ source,
676
+ importFrom,
677
+ program: sourceFile === undefined ? undefined : { sourceFile, checker },
678
+ });
679
+ const shown = (0, node_path_1.relative)(root, file).split('\\').join('/') || file;
680
+ for (const item of result.manual) {
681
+ manualCount += 1;
682
+ console.warn(`manual ${shown}:${item.line} ${item.reason}`);
683
+ }
684
+ for (const line of result.unnamed) {
685
+ unnamedCount += 1;
686
+ console.warn(`type ${shown}:${line} BindingKeys.build<unknown>: name the type of the value bound under this key`);
687
+ }
688
+ if (!result.changed) {
689
+ continue;
690
+ }
691
+ if (dirty?.has(file)) {
692
+ refusedCount += 1;
693
+ console.warn(`refused ${shown} has local changes (commit or stash them, then run again)`);
694
+ continue;
695
+ }
696
+ changedCount += 1;
697
+ rewrittenCount += result.rewritten;
698
+ console.log(`${isWrite ? 'changed' : 'would change'} ${shown} (${result.rewritten} key(s))`);
699
+ if (isWrite) {
700
+ (0, node_fs_1.writeFileSync)(file, result.output);
701
+ }
702
+ }
703
+ }
704
+ console.log(`devz codemod binding-keys: ${changedCount} file(s) ${isWrite ? 'changed' : 'would change'}, ${rewrittenCount} key(s) ${isWrite ? 'rewritten' : 'would be rewritten'}, ${unnamedCount} to type, ${manualCount} manual` +
705
+ (refusedCount > 0 ? `, ${refusedCount} refused` : ''));
706
+ if (!isWrite && changedCount > 0) {
707
+ console.log(`Nothing was written. Run again with ${BindingKeysFlags.WRITE} to apply, then name each "type" site and run your typecheck.`);
708
+ }
709
+ if (isWrite && refusedCount > 0) {
710
+ return 1;
711
+ }
712
+ return isCheck && (changedCount > 0 || manualCount > 0) ? 1 : 0;
713
+ }
714
+ }
715
+ exports.BindingKeysCommand = BindingKeysCommand;
716
+ //# sourceMappingURL=binding-keys.js.map