@venizia/dev-configs 0.5.0-1 → 0.5.0-10
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 +18 -13
- package/dist/checks/purity/manifest.js +11 -3
- package/dist/checks/purity/manifest.js.map +1 -1
- package/dist/checks/purity/probe.js +19 -2
- package/dist/checks/purity/probe.js.map +1 -1
- package/dist/checks/split-report.js +2 -1
- package/dist/checks/split-report.js.map +1 -1
- package/dist/checks/test-controls.d.ts +9 -1
- package/dist/checks/test-controls.js +9 -3
- package/dist/checks/test-controls.js.map +1 -1
- package/dist/checks/test-dead-code.d.ts +9 -1
- package/dist/checks/test-dead-code.js +13 -2
- package/dist/checks/test-dead-code.js.map +1 -1
- package/dist/checks/test-mutate.d.ts +9 -1
- package/dist/checks/test-mutate.js +12 -6
- package/dist/checks/test-mutate.js.map +1 -1
- package/dist/cli/check.js +42 -38
- package/dist/cli/check.js.map +1 -1
- package/dist/cli/clean.js +3 -2
- package/dist/cli/clean.js.map +1 -1
- package/dist/cli/codemod/any-aliases.d.ts +1 -1
- package/dist/cli/codemod/any-aliases.js +14 -13
- package/dist/cli/codemod/any-aliases.js.map +1 -1
- package/dist/cli/codemod/async-style.d.ts +1 -1
- package/dist/cli/codemod/async-style.js +18 -17
- package/dist/cli/codemod/async-style.js.map +1 -1
- package/dist/cli/codemod/binding-keys.d.ts +32 -1
- package/dist/cli/codemod/binding-keys.js +238 -58
- package/dist/cli/codemod/binding-keys.js.map +1 -1
- package/dist/cli/codemod/class-renames.d.ts +39 -0
- package/dist/cli/codemod/class-renames.js +297 -0
- package/dist/cli/codemod/class-renames.js.map +1 -0
- package/dist/cli/codemod/connector-imports.d.ts +1 -1
- package/dist/cli/codemod/connector-imports.js +13 -12
- package/dist/cli/codemod/connector-imports.js.map +1 -1
- package/dist/cli/codemod/const-class-sets.d.ts +55 -0
- package/dist/cli/codemod/const-class-sets.js +219 -0
- package/dist/cli/codemod/const-class-sets.js.map +1 -0
- package/dist/cli/codemod/const-classes.d.ts +21 -3
- package/dist/cli/codemod/const-classes.js +151 -36
- package/dist/cli/codemod/const-classes.js.map +1 -1
- package/dist/cli/codemod/drop-redundant-casts.d.ts +6 -1
- package/dist/cli/codemod/drop-redundant-casts.js +27 -19
- package/dist/cli/codemod/drop-redundant-casts.js.map +1 -1
- package/dist/cli/codemod/env-get.d.ts +3 -3
- package/dist/cli/codemod/env-get.js +19 -18
- package/dist/cli/codemod/env-get.js.map +1 -1
- package/dist/cli/codemod/files.d.ts +4 -2
- package/dist/cli/codemod/files.js +7 -8
- package/dist/cli/codemod/files.js.map +1 -1
- package/dist/cli/codemod/function-to-arrow.d.ts +76 -0
- package/dist/cli/codemod/function-to-arrow.js +357 -0
- package/dist/cli/codemod/function-to-arrow.js.map +1 -0
- package/dist/cli/codemod/index.js +25 -4
- package/dist/cli/codemod/index.js.map +1 -1
- package/dist/cli/codemod/namespace-functions/index.d.ts +1 -1
- package/dist/cli/codemod/namespace-functions/index.js +14 -13
- package/dist/cli/codemod/namespace-functions/index.js.map +1 -1
- package/dist/cli/codemod/namespace-functions/mappings/dev-configs.js +3 -3
- package/dist/cli/codemod/namespace-functions/mappings/dev-configs.js.map +1 -1
- package/dist/cli/codemod/namespace-functions/mappings/helpers.js +1 -1
- package/dist/cli/codemod/namespace-functions/mappings/helpers.js.map +1 -1
- package/dist/cli/codemod/typed-route-context.d.ts +58 -0
- package/dist/cli/codemod/typed-route-context.js +918 -0
- package/dist/cli/codemod/typed-route-context.js.map +1 -0
- package/dist/cli/index.js +5 -4
- package/dist/cli/index.js.map +1 -1
- package/dist/common/cli-output.d.ts +16 -0
- package/dist/common/cli-output.js +49 -0
- package/dist/common/cli-output.js.map +1 -0
- package/dist/compilers/bun.js +1 -1
- package/dist/compilers/bun.js.map +1 -1
- package/dist/linters/eslint.js +1 -1
- package/dist/linters/eslint.js.map +1 -1
- package/dist/linters/house/browser-api-patterns.d.ts +43 -0
- package/dist/linters/house/browser-api-patterns.js +87 -0
- package/dist/linters/house/browser-api-patterns.js.map +1 -0
- package/dist/linters/house/common.d.ts +17 -2
- package/dist/linters/house/common.js +18 -2
- package/dist/linters/house/common.js.map +1 -1
- package/dist/linters/house/configs.js +25 -0
- package/dist/linters/house/configs.js.map +1 -1
- package/dist/linters/house/const-class-values.rule.d.ts +2 -2
- package/dist/linters/house/const-class-values.rule.js +14 -5
- package/dist/linters/house/const-class-values.rule.js.map +1 -1
- package/dist/linters/house/effect-cleanup-consistency.rule.d.ts +2 -2
- package/dist/linters/house/effect-cleanup-consistency.rule.js +1 -1
- package/dist/linters/house/effect-cleanup-consistency.rule.js.map +1 -1
- package/dist/linters/house/framework-api-patterns.d.ts +54 -0
- package/dist/linters/house/framework-api-patterns.js +62 -0
- package/dist/linters/house/framework-api-patterns.js.map +1 -0
- package/dist/linters/house/framework-exports.d.ts +62 -0
- package/dist/linters/house/framework-exports.js +325 -0
- package/dist/linters/house/framework-exports.js.map +1 -0
- package/dist/linters/house/import-support.d.ts +56 -0
- package/dist/linters/house/import-support.js +179 -0
- package/dist/linters/house/import-support.js.map +1 -0
- package/dist/linters/house/index.d.ts +12 -0
- package/dist/linters/house/index.js +15 -1
- package/dist/linters/house/index.js.map +1 -1
- package/dist/linters/house/max-params-own.rule.d.ts +2 -2
- package/dist/linters/house/max-params-own.rule.js +1 -1
- package/dist/linters/house/max-params-own.rule.js.map +1 -1
- package/dist/linters/house/no-async-hook-callback.rule.d.ts +2 -2
- package/dist/linters/house/no-async-hook-callback.rule.js +1 -1
- package/dist/linters/house/no-async-hook-callback.rule.js.map +1 -1
- package/dist/linters/house/no-await-new-chain.rule.d.ts +2 -2
- package/dist/linters/house/no-await-new-chain.rule.js +1 -1
- package/dist/linters/house/no-await-new-chain.rule.js.map +1 -1
- package/dist/linters/house/no-await-promise-chain.rule.d.ts +2 -2
- package/dist/linters/house/no-await-promise-chain.rule.js +5 -5
- package/dist/linters/house/no-await-promise-chain.rule.js.map +1 -1
- package/dist/linters/house/no-inline-await.rule.d.ts +2 -2
- package/dist/linters/house/no-inline-await.rule.js +1 -1
- package/dist/linters/house/no-inline-await.rule.js.map +1 -1
- package/dist/linters/house/no-leaked-render.rule.d.ts +2 -2
- package/dist/linters/house/no-leaked-render.rule.js +1 -1
- package/dist/linters/house/no-leaked-render.rule.js.map +1 -1
- package/dist/linters/house/no-new-error.rule.d.ts +2 -2
- package/dist/linters/house/no-new-error.rule.js +2 -2
- package/dist/linters/house/no-new-error.rule.js.map +1 -1
- package/dist/linters/house/no-parent-import.rule.d.ts +45 -0
- package/dist/linters/house/no-parent-import.rule.js +176 -0
- package/dist/linters/house/no-parent-import.rule.js.map +1 -0
- package/dist/linters/house/no-return-await.rule.d.ts +2 -2
- package/dist/linters/house/no-return-await.rule.js +1 -1
- package/dist/linters/house/no-return-await.rule.js.map +1 -1
- package/dist/linters/house/no-shadow-framework-type.rule.d.ts +24 -0
- package/dist/linters/house/no-shadow-framework-type.rule.js +100 -0
- package/dist/linters/house/no-shadow-framework-type.rule.js.map +1 -0
- package/dist/linters/house/no-silent-catch.rule.d.ts +2 -2
- package/dist/linters/house/no-silent-catch.rule.js +3 -3
- package/dist/linters/house/no-silent-catch.rule.js.map +1 -1
- package/dist/linters/house/no-unbraced-case.rule.d.ts +2 -2
- package/dist/linters/house/no-unbraced-case.rule.js +1 -1
- package/dist/linters/house/no-unbraced-case.rule.js.map +1 -1
- package/dist/linters/house/plugin.d.ts +1 -1
- package/dist/linters/house/plugin.js +18 -2
- package/dist/linters/house/plugin.js.map +1 -1
- package/dist/linters/house/prefer-framework-api.rule.d.ts +83 -0
- package/dist/linters/house/prefer-framework-api.rule.js +562 -0
- package/dist/linters/house/prefer-framework-api.rule.js.map +1 -0
- package/dist/linters/house/prefer-http-method.rule.d.ts +22 -0
- package/dist/linters/house/prefer-http-method.rule.js +182 -0
- package/dist/linters/house/prefer-http-method.rule.js.map +1 -0
- package/dist/linters/house/prefer-promise-sleep.rule.d.ts +26 -0
- package/dist/linters/house/prefer-promise-sleep.rule.js +155 -0
- package/dist/linters/house/prefer-promise-sleep.rule.js.map +1 -0
- package/dist/linters/house/prefer-tnullable.rule.d.ts +25 -0
- package/dist/linters/house/prefer-tnullable.rule.js +124 -0
- package/dist/linters/house/prefer-tnullable.rule.js.map +1 -0
- package/dist/linters/house/typed-route-context.rule.d.ts +19 -0
- package/dist/linters/house/typed-route-context.rule.js +334 -0
- package/dist/linters/house/typed-route-context.rule.js.map +1 -0
- package/dist/linters/house/zod-schema-convention.rule.d.ts +82 -0
- package/dist/linters/house/zod-schema-convention.rule.js +477 -0
- package/dist/linters/house/zod-schema-convention.rule.js.map +1 -0
- package/dist/linters/oxlint.js +11 -1
- package/dist/linters/oxlint.js.map +1 -1
- package/dist/linters/react-eslint.js.map +1 -1
- package/dist/linters/rules/naming-convention.rule.d.ts +4 -1
- package/dist/linters/rules/naming-convention.rule.js +30 -1
- package/dist/linters/rules/naming-convention.rule.js.map +1 -1
- package/dist/linters/rules/no-restricted-properties.rule.js +1 -1
- package/dist/linters/rules/no-restricted-properties.rule.js.map +1 -1
- package/dist/testing/index.d.ts +2 -2
- package/dist/testing/index.js +2 -2
- package/dist/testing/index.js.map +1 -1
- package/dist/testing/{rejection.helper.d.ts → rejection.utility.d.ts} +4 -4
- package/dist/testing/{rejection.helper.js → rejection.utility.js} +7 -7
- package/dist/testing/rejection.utility.js.map +1 -0
- package/dist/testing/{spawn.helper.d.ts → spawn.utility.d.ts} +2 -2
- package/dist/testing/{spawn.helper.js → spawn.utility.js} +6 -6
- package/dist/testing/spawn.utility.js.map +1 -0
- package/package.json +7 -7
- package/dist/testing/rejection.helper.js.map +0 -1
- package/dist/testing/spawn.helper.js.map +0 -1
|
@@ -0,0 +1,357 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.FunctionToArrowCommand = exports.FunctionToArrow = exports.ArrowSkipReasons = exports.FunctionToArrowFlags = void 0;
|
|
4
|
+
const node_fs_1 = require("node:fs");
|
|
5
|
+
const node_path_1 = require("node:path");
|
|
6
|
+
const cli_output_1 = require("../../common/cli-output");
|
|
7
|
+
const files_1 = require("./files");
|
|
8
|
+
/** A usage error: nothing was read or written. */
|
|
9
|
+
const USAGE_ERROR_CODE = 2;
|
|
10
|
+
/** The options of the command. */
|
|
11
|
+
class FunctionToArrowFlags {
|
|
12
|
+
static { this.WRITE = '--write'; }
|
|
13
|
+
static { this.DRY_RUN = '--dry-run'; }
|
|
14
|
+
static { this.CHECK = '--check'; }
|
|
15
|
+
static { this.ALL = '--all'; }
|
|
16
|
+
static { this.HELP = '--help'; }
|
|
17
|
+
static { this.HELP_SHORT = '-h'; }
|
|
18
|
+
static isValid(flag) {
|
|
19
|
+
return Object.values(FunctionToArrowFlags).includes(flag);
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
exports.FunctionToArrowFlags = FunctionToArrowFlags;
|
|
23
|
+
/** Why a `function` declaration is left as it is: rewriting it could change what the program does or its types. */
|
|
24
|
+
class ArrowSkipReasons {
|
|
25
|
+
static { this.HOISTED = 'used-before-declaration'; }
|
|
26
|
+
static { this.OVERLOAD = 'overload-or-no-body'; }
|
|
27
|
+
static { this.GENERATOR = 'generator'; }
|
|
28
|
+
static { this.THIS = 'uses-this'; }
|
|
29
|
+
static { this.ARGUMENTS = 'uses-arguments'; }
|
|
30
|
+
static { this.NEW_TARGET = 'uses-new-target'; }
|
|
31
|
+
static { this.EXPORT_DEFAULT = 'export-default'; }
|
|
32
|
+
static { this.CONSTRUCTED = 'used-as-constructor'; }
|
|
33
|
+
static { this.ASSERTION = 'assertion-signature'; }
|
|
34
|
+
static { this.MERGED = 'merged-declaration'; }
|
|
35
|
+
static { this.HEADER_COMMENT = 'comment-before-the-name'; }
|
|
36
|
+
}
|
|
37
|
+
exports.ArrowSkipReasons = ArrowSkipReasons;
|
|
38
|
+
const USAGE = `devz codemod function-to-arrow [paths...] [--write [--all] | --check | --dry-run]
|
|
39
|
+
|
|
40
|
+
Rewrites a \`function\` declaration as \`const name = (...) => {...};\`, keeping export, async, type parameters,
|
|
41
|
+
the return type and comments. A declaration whose rewrite could change the program is listed with its reason and left
|
|
42
|
+
alone: used before it is declared, overloads, generators, this / arguments / new.target, export default, used with
|
|
43
|
+
new, assertion signatures and merged declarations. A function another module calls while an import cycle is still
|
|
44
|
+
loading is not detected: run your tests.
|
|
45
|
+
|
|
46
|
+
--dry-run the default: list the changes and the skips, write nothing
|
|
47
|
+
--write write the changed files (--write needs a path or --all)
|
|
48
|
+
--check dry run that exits 1 while a file would change
|
|
49
|
+
--help print this text and exit`;
|
|
50
|
+
/** The rewrite of one file's `function` declarations. */
|
|
51
|
+
class FunctionToArrow {
|
|
52
|
+
/** The reason the body cannot move into an arrow: it reads what only a `function` binds. */
|
|
53
|
+
static ownBinding(opts) {
|
|
54
|
+
const { typescript, declaration } = opts;
|
|
55
|
+
let found;
|
|
56
|
+
const first = declaration.parameters[0]?.name;
|
|
57
|
+
// A `this` parameter types the `this` an arrow does not have.
|
|
58
|
+
if (first && typescript.isIdentifier(first) && first.text === 'this') {
|
|
59
|
+
return ArrowSkipReasons.THIS;
|
|
60
|
+
}
|
|
61
|
+
const visit = (node) => {
|
|
62
|
+
// A nested `function` or class member binds its own; an arrow does not.
|
|
63
|
+
if (typescript.isFunctionDeclaration(node) ||
|
|
64
|
+
typescript.isFunctionExpression(node) ||
|
|
65
|
+
typescript.isClassLike(node) ||
|
|
66
|
+
typescript.isMethodDeclaration(node) ||
|
|
67
|
+
typescript.isGetAccessorDeclaration(node) ||
|
|
68
|
+
typescript.isSetAccessorDeclaration(node)) {
|
|
69
|
+
return;
|
|
70
|
+
}
|
|
71
|
+
if (node.kind === typescript.SyntaxKind.ThisKeyword) {
|
|
72
|
+
found = ArrowSkipReasons.THIS;
|
|
73
|
+
}
|
|
74
|
+
else if (typescript.isIdentifier(node) && node.text === 'arguments') {
|
|
75
|
+
found = ArrowSkipReasons.ARGUMENTS;
|
|
76
|
+
}
|
|
77
|
+
else if (typescript.isMetaProperty(node) &&
|
|
78
|
+
node.keywordToken === typescript.SyntaxKind.NewKeyword) {
|
|
79
|
+
found = ArrowSkipReasons.NEW_TARGET;
|
|
80
|
+
}
|
|
81
|
+
typescript.forEachChild(node, visit);
|
|
82
|
+
};
|
|
83
|
+
declaration.parameters.forEach(visit);
|
|
84
|
+
if (declaration.body) {
|
|
85
|
+
typescript.forEachChild(declaration.body, visit);
|
|
86
|
+
}
|
|
87
|
+
return found;
|
|
88
|
+
}
|
|
89
|
+
/** Every reference to each `function` declaration of the file, itself and its name excluded. */
|
|
90
|
+
static references(opts) {
|
|
91
|
+
const { typescript, sourceFile, checker } = opts;
|
|
92
|
+
const found = new Map();
|
|
93
|
+
const visit = (node) => {
|
|
94
|
+
if (typescript.isIdentifier(node)) {
|
|
95
|
+
const parent = node.parent;
|
|
96
|
+
// The name of an export specifier or of a shorthand property stands for the local declaration too.
|
|
97
|
+
const symbol = typescript.isExportSpecifier(parent)
|
|
98
|
+
? checker.getExportSpecifierLocalTargetSymbol(parent)
|
|
99
|
+
: typescript.isShorthandPropertyAssignment(parent) && parent.name === node
|
|
100
|
+
? checker.getShorthandAssignmentValueSymbol(parent)
|
|
101
|
+
: checker.getSymbolAtLocation(node);
|
|
102
|
+
const isOwnName = typescript.isFunctionDeclaration(parent) && parent.name === node;
|
|
103
|
+
if (symbol && !isOwnName) {
|
|
104
|
+
found.set(symbol, [...(found.get(symbol) ?? []), node]);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
typescript.forEachChild(node, visit);
|
|
108
|
+
};
|
|
109
|
+
visit(sourceFile);
|
|
110
|
+
return found;
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* The earliest position of the file from which `node` can run: where it is written, or earlier when it sits in a
|
|
114
|
+
* hoisted `function` that is itself used before that.
|
|
115
|
+
*/
|
|
116
|
+
static runsFrom(opts) {
|
|
117
|
+
const { typescript, sourceFile, checker, references, node, seen } = opts;
|
|
118
|
+
let earliest = node.getStart(sourceFile);
|
|
119
|
+
for (let parent = node.parent; parent; parent = parent.parent) {
|
|
120
|
+
if (!typescript.isFunctionDeclaration(parent) || !parent.name || seen.has(parent)) {
|
|
121
|
+
continue;
|
|
122
|
+
}
|
|
123
|
+
seen.add(parent);
|
|
124
|
+
const symbol = checker.getSymbolAtLocation(parent.name);
|
|
125
|
+
for (const use of (symbol && references.get(symbol)) ?? []) {
|
|
126
|
+
earliest = Math.min(earliest, FunctionToArrow.runsFrom({ ...opts, node: use, seen }));
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
return earliest;
|
|
130
|
+
}
|
|
131
|
+
/** What the other references to the function forbid. */
|
|
132
|
+
static usage(opts) {
|
|
133
|
+
const { typescript, sourceFile, references, declaration, symbol } = opts;
|
|
134
|
+
const uses = references.get(symbol) ?? [];
|
|
135
|
+
const isConstructed = uses.some(({ parent }) => (typescript.isNewExpression(parent) &&
|
|
136
|
+
parent.expression.getText(sourceFile) === declaration.name?.text) ||
|
|
137
|
+
(typescript.isPropertyAccessExpression(parent) && parent.name.text === 'prototype'));
|
|
138
|
+
if (isConstructed) {
|
|
139
|
+
return ArrowSkipReasons.CONSTRUCTED;
|
|
140
|
+
}
|
|
141
|
+
const start = declaration.getStart(sourceFile);
|
|
142
|
+
const isHoisted = uses.some((node) => FunctionToArrow.runsFrom({ ...opts, node, seen: new Set([declaration]) }) < start);
|
|
143
|
+
return isHoisted ? ArrowSkipReasons.HOISTED : undefined;
|
|
144
|
+
}
|
|
145
|
+
static skipReason(opts) {
|
|
146
|
+
const { typescript, sourceFile, checker, references, declaration, name } = opts;
|
|
147
|
+
const modifiers = typescript.getModifiers(declaration) ?? [];
|
|
148
|
+
if (modifiers.some((modifier) => modifier.kind === typescript.SyntaxKind.DefaultKeyword)) {
|
|
149
|
+
return ArrowSkipReasons.EXPORT_DEFAULT;
|
|
150
|
+
}
|
|
151
|
+
const symbol = checker.getSymbolAtLocation(name);
|
|
152
|
+
const declarations = symbol?.declarations ?? [];
|
|
153
|
+
if (!declaration.body || declarations.filter(typescript.isFunctionDeclaration).length > 1) {
|
|
154
|
+
return ArrowSkipReasons.OVERLOAD;
|
|
155
|
+
}
|
|
156
|
+
if (declarations.length > 1) {
|
|
157
|
+
return ArrowSkipReasons.MERGED;
|
|
158
|
+
}
|
|
159
|
+
if (declaration.asteriskToken) {
|
|
160
|
+
return ArrowSkipReasons.GENERATOR;
|
|
161
|
+
}
|
|
162
|
+
if (declaration.type &&
|
|
163
|
+
typescript.isTypePredicateNode(declaration.type) &&
|
|
164
|
+
declaration.type.assertsModifier) {
|
|
165
|
+
return ArrowSkipReasons.ASSERTION;
|
|
166
|
+
}
|
|
167
|
+
const header = sourceFile.text.slice(declaration.getStart(sourceFile), name.getStart(sourceFile));
|
|
168
|
+
if (header.includes('//') || header.includes('/*')) {
|
|
169
|
+
return ArrowSkipReasons.HEADER_COMMENT;
|
|
170
|
+
}
|
|
171
|
+
return (FunctionToArrow.ownBinding({ typescript, declaration }) ??
|
|
172
|
+
(symbol
|
|
173
|
+
? FunctionToArrow.usage({
|
|
174
|
+
typescript,
|
|
175
|
+
sourceFile,
|
|
176
|
+
checker,
|
|
177
|
+
references,
|
|
178
|
+
declaration,
|
|
179
|
+
symbol,
|
|
180
|
+
})
|
|
181
|
+
: undefined));
|
|
182
|
+
}
|
|
183
|
+
/** One pass over the file: the declarations that are safe, innermost ones included. */
|
|
184
|
+
static pass(opts) {
|
|
185
|
+
const { typescript, fileName, source } = opts;
|
|
186
|
+
const sourceFile = typescript.createSourceFile(fileName, source, typescript.ScriptTarget.Latest, true);
|
|
187
|
+
// One file, no library: enough to tell which names refer to which declaration.
|
|
188
|
+
const host = {
|
|
189
|
+
...typescript.createCompilerHost({}),
|
|
190
|
+
getSourceFile: (name) => (name === fileName ? sourceFile : undefined),
|
|
191
|
+
};
|
|
192
|
+
const checker = typescript
|
|
193
|
+
.createProgram([fileName], { noLib: true, noResolve: true, allowJs: false }, host)
|
|
194
|
+
.getTypeChecker();
|
|
195
|
+
const references = FunctionToArrow.references({ typescript, sourceFile, checker });
|
|
196
|
+
const isTsx = fileName.endsWith('.tsx');
|
|
197
|
+
const edits = [];
|
|
198
|
+
const skipped = [];
|
|
199
|
+
const visit = (node) => {
|
|
200
|
+
typescript.forEachChild(node, visit);
|
|
201
|
+
if (!typescript.isFunctionDeclaration(node) || !node.name) {
|
|
202
|
+
if (typescript.isFunctionDeclaration(node) &&
|
|
203
|
+
(typescript.getModifiers(node) ?? []).some((modifier) => modifier.kind === typescript.SyntaxKind.DefaultKeyword)) {
|
|
204
|
+
skipped.push({
|
|
205
|
+
name: 'default',
|
|
206
|
+
line: sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line + 1,
|
|
207
|
+
reason: ArrowSkipReasons.EXPORT_DEFAULT,
|
|
208
|
+
});
|
|
209
|
+
}
|
|
210
|
+
return;
|
|
211
|
+
}
|
|
212
|
+
const name = node.name;
|
|
213
|
+
const reason = FunctionToArrow.skipReason({
|
|
214
|
+
typescript,
|
|
215
|
+
sourceFile,
|
|
216
|
+
checker,
|
|
217
|
+
references,
|
|
218
|
+
declaration: node,
|
|
219
|
+
name,
|
|
220
|
+
});
|
|
221
|
+
if (reason || !node.body) {
|
|
222
|
+
skipped.push({
|
|
223
|
+
name: name.text,
|
|
224
|
+
line: sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line + 1,
|
|
225
|
+
reason: reason ?? ArrowSkipReasons.OVERLOAD,
|
|
226
|
+
});
|
|
227
|
+
return;
|
|
228
|
+
}
|
|
229
|
+
const modifiers = (typescript.getModifiers(node) ?? []).map((modifier) => modifier.kind);
|
|
230
|
+
const isExported = modifiers.includes(typescript.SyntaxKind.ExportKeyword);
|
|
231
|
+
const isAsync = modifiers.includes(typescript.SyntaxKind.AsyncKeyword);
|
|
232
|
+
let signature = source.slice(name.end, node.body.getStart(sourceFile)).trimEnd();
|
|
233
|
+
// In a .tsx file `<T>(` opens an element; the comma makes it a type parameter list.
|
|
234
|
+
if (isTsx && node.typeParameters?.length === 1 && !node.typeParameters.hasTrailingComma) {
|
|
235
|
+
signature = signature.replace(/>(\s*\()/, ',>$1');
|
|
236
|
+
}
|
|
237
|
+
const head = `${isExported ? 'export ' : ''}const ${name.text} = ${isAsync ? 'async ' : ''}${signature} => `;
|
|
238
|
+
const bodyStart = node.body.getStart(sourceFile);
|
|
239
|
+
edits.push({ start: node.getStart(sourceFile), end: bodyStart, text: head });
|
|
240
|
+
if (source[node.body.end] !== ';') {
|
|
241
|
+
edits.push({ start: node.body.end, end: node.body.end, text: ';' });
|
|
242
|
+
}
|
|
243
|
+
};
|
|
244
|
+
visit(sourceFile);
|
|
245
|
+
let output = source;
|
|
246
|
+
// From the end; where a header starts at the point a semicolon goes in, the header is replaced first.
|
|
247
|
+
for (const edit of edits.sort((a, b) => b.start - a.start || b.end - a.end)) {
|
|
248
|
+
output = output.slice(0, edit.start) + edit.text + output.slice(edit.end);
|
|
249
|
+
}
|
|
250
|
+
return {
|
|
251
|
+
output,
|
|
252
|
+
rewritten: edits.filter((edit) => edit.end !== edit.start).length,
|
|
253
|
+
skipped: skipped.sort((a, b) => a.line - b.line),
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
/** The file with every safe declaration rewritten, and the ones left alone with their reasons. */
|
|
257
|
+
static rewrite(opts) {
|
|
258
|
+
return FunctionToArrow.pass(opts);
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
exports.FunctionToArrow = FunctionToArrow;
|
|
262
|
+
/**
|
|
263
|
+
* `devz codemod function-to-arrow [paths...] [--write [--all] | --check | --dry-run]`: a dry run unless `--write`
|
|
264
|
+
* is given. `--check` is the same dry run, and exits 1 while a file would change.
|
|
265
|
+
*/
|
|
266
|
+
class FunctionToArrowCommand {
|
|
267
|
+
static { this.USAGE = USAGE; }
|
|
268
|
+
static async run(opts) {
|
|
269
|
+
const { root, args } = opts;
|
|
270
|
+
if (args.includes(FunctionToArrowFlags.HELP) ||
|
|
271
|
+
args.includes(FunctionToArrowFlags.HELP_SHORT)) {
|
|
272
|
+
cli_output_1.CliOutput.log(USAGE);
|
|
273
|
+
return 0;
|
|
274
|
+
}
|
|
275
|
+
const flags = args.filter((argument) => argument.startsWith('-'));
|
|
276
|
+
const paths = args.filter((argument) => !argument.startsWith('-'));
|
|
277
|
+
const unknown = flags.filter((flag) => !FunctionToArrowFlags.isValid(flag));
|
|
278
|
+
const isWrite = flags.includes(FunctionToArrowFlags.WRITE);
|
|
279
|
+
const isCheck = flags.includes(FunctionToArrowFlags.CHECK);
|
|
280
|
+
const isDryRun = flags.includes(FunctionToArrowFlags.DRY_RUN);
|
|
281
|
+
if (unknown.length > 0 || (isWrite && (isCheck || isDryRun))) {
|
|
282
|
+
const problem = unknown.length > 0
|
|
283
|
+
? `unknown option ${unknown.map((flag) => `"${flag}"`).join(', ')}`
|
|
284
|
+
: `${FunctionToArrowFlags.WRITE} contradicts a dry run`;
|
|
285
|
+
cli_output_1.CliOutput.error(`devz codemod: ${problem}\n${USAGE}`);
|
|
286
|
+
return USAGE_ERROR_CODE;
|
|
287
|
+
}
|
|
288
|
+
const refusal = files_1.CodemodFiles.refusal({
|
|
289
|
+
command: 'function-to-arrow',
|
|
290
|
+
isWrite,
|
|
291
|
+
isAll: flags.includes(FunctionToArrowFlags.ALL),
|
|
292
|
+
paths,
|
|
293
|
+
});
|
|
294
|
+
if (refusal) {
|
|
295
|
+
cli_output_1.CliOutput.error(`${refusal}\n${USAGE}`);
|
|
296
|
+
return USAGE_ERROR_CODE;
|
|
297
|
+
}
|
|
298
|
+
let typescript;
|
|
299
|
+
try {
|
|
300
|
+
const loaded = await import('typescript');
|
|
301
|
+
typescript = loaded.default;
|
|
302
|
+
}
|
|
303
|
+
catch {
|
|
304
|
+
cli_output_1.CliOutput.error('devz codemod: the "typescript" package is required to read your sources');
|
|
305
|
+
return 1;
|
|
306
|
+
}
|
|
307
|
+
const targets = (paths.length > 0 ? paths : ['.']).map((path) => (0, node_path_1.resolve)(root, path));
|
|
308
|
+
let changedCount = 0;
|
|
309
|
+
let rewrittenCount = 0;
|
|
310
|
+
let refusedCount = 0;
|
|
311
|
+
const skips = [];
|
|
312
|
+
for (const target of targets) {
|
|
313
|
+
const files = files_1.CodemodFiles.collect({ target });
|
|
314
|
+
const dirty = isWrite ? files_1.CodemodFiles.dirty({ target }) : undefined;
|
|
315
|
+
if (files.length === 0 && paths.length > 0) {
|
|
316
|
+
cli_output_1.CliOutput.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`);
|
|
317
|
+
}
|
|
318
|
+
for (const file of files) {
|
|
319
|
+
const source = (0, node_fs_1.readFileSync)(file, 'utf8');
|
|
320
|
+
if (!source.includes('function')) {
|
|
321
|
+
continue;
|
|
322
|
+
}
|
|
323
|
+
const result = FunctionToArrow.rewrite({ typescript, fileName: file, source });
|
|
324
|
+
const shown = (0, node_path_1.relative)(root, file).split('\\').join('/') || file;
|
|
325
|
+
skips.push(...result.skipped.map((skip) => ` ${shown}:${skip.line} ${skip.name} ${skip.reason}`));
|
|
326
|
+
if (result.rewritten === 0) {
|
|
327
|
+
continue;
|
|
328
|
+
}
|
|
329
|
+
if (dirty?.has(file)) {
|
|
330
|
+
refusedCount += 1;
|
|
331
|
+
cli_output_1.CliOutput.warn(`refused ${shown} has local changes (commit, stash or "git add" them, then run again)`);
|
|
332
|
+
continue;
|
|
333
|
+
}
|
|
334
|
+
changedCount += 1;
|
|
335
|
+
rewrittenCount += result.rewritten;
|
|
336
|
+
cli_output_1.CliOutput.log(`${isWrite ? 'changed' : 'would change'} ${shown} (${result.rewritten} function(s))`);
|
|
337
|
+
if (isWrite) {
|
|
338
|
+
(0, node_fs_1.writeFileSync)(file, result.output);
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
if (skips.length > 0) {
|
|
343
|
+
cli_output_1.CliOutput.log(`left as they are (${skips.length}):\n${skips.join('\n')}`);
|
|
344
|
+
}
|
|
345
|
+
cli_output_1.CliOutput.log(`devz codemod function-to-arrow: ${rewrittenCount} function(s) ${isWrite ? 'rewritten' : 'would be rewritten'} in ${changedCount} file(s), ${skips.length} left` +
|
|
346
|
+
(refusedCount > 0 ? `, ${refusedCount} file(s) refused` : ''));
|
|
347
|
+
if (!isWrite && changedCount > 0) {
|
|
348
|
+
cli_output_1.CliOutput.log(`Nothing was written. Run again with ${FunctionToArrowFlags.WRITE} to apply, then run your typecheck, formatter and tests.`);
|
|
349
|
+
}
|
|
350
|
+
if (isWrite && refusedCount > 0) {
|
|
351
|
+
return 1;
|
|
352
|
+
}
|
|
353
|
+
return isCheck && changedCount > 0 ? 1 : 0;
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
exports.FunctionToArrowCommand = FunctionToArrowCommand;
|
|
357
|
+
//# sourceMappingURL=function-to-arrow.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"function-to-arrow.js","sourceRoot":"","sources":["../../../src/cli/codemod/function-to-arrow.ts"],"names":[],"mappings":";;;AAAA,qCAAsD;AACtD,yCAA8C;AAE9C,wDAAoD;AAEpD,mCAAuC;AAIvC,kDAAkD;AAClD,MAAM,gBAAgB,GAAG,CAAC,CAAC;AAE3B,kCAAkC;AAClC,MAAa,oBAAoB;aACf,UAAK,GAAG,SAAS,CAAC;aAClB,YAAO,GAAG,WAAW,CAAC;aACtB,UAAK,GAAG,SAAS,CAAC;aAClB,QAAG,GAAG,OAAO,CAAC;aACd,SAAI,GAAG,QAAQ,CAAC;aAChB,eAAU,GAAG,IAAI,CAAC;IAElC,MAAM,CAAC,OAAO,CAAC,IAAY;QACzB,OAAO,MAAM,CAAC,MAAM,CAAC,oBAAoB,CAAC,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;IAC5D,CAAC;;AAVH,oDAWC;AAED,mHAAmH;AACnH,MAAa,gBAAgB;aACX,YAAO,GAAG,yBAAyB,CAAC;aAC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BAAkB,CAAC,CAAC,CAAC,EAAE,CAAC,CAChE,CAAC;QAEF,IAAI,CAAC,OAAO,IAAI,YAAY,GAAG,CAAC,EAAE,CAAC;YACjC,sBAAS,CAAC,GAAG,CACX,uCAAuC,oBAAoB,CAAC,KAAK,0DAA0D,CAC5H,CAAC;QACJ,CAAC;QAED,IAAI,OAAO,IAAI,YAAY,GAAG,CAAC,EAAE,CAAC;YAChC,OAAO,CAAC,CAAC;QACX,CAAC;QAED,OAAO,OAAO,IAAI,YAAY,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IAC7C,CAAC;;AAjIH,wDAkIC","sourcesContent":["import { readFileSync, writeFileSync } from 'node:fs';\nimport { relative, resolve } from 'node:path';\nimport type ts from 'typescript';\nimport { CliOutput } from '../../common/cli-output';\nimport type { TConstValue } from '../../linters/rules/common';\nimport { CodemodFiles } from './files';\n\ntype TTypeScript = typeof ts;\n\n/** A usage error: nothing was read or written. */\nconst USAGE_ERROR_CODE = 2;\n\n/** The options of the command. */\nexport class FunctionToArrowFlags {\n static readonly WRITE = '--write';\n static readonly DRY_RUN = '--dry-run';\n static readonly CHECK = '--check';\n static readonly ALL = '--all';\n static readonly HELP = '--help';\n static readonly HELP_SHORT = '-h';\n\n static isValid(flag: string): boolean {\n return Object.values(FunctionToArrowFlags).includes(flag);\n }\n}\n\n/** Why a `function` declaration is left as it is: rewriting it could change what the program does or its types. */\nexport class ArrowSkipReasons {\n static readonly HOISTED = 'used-before-declaration';\n static readonly OVERLOAD = 'overload-or-no-body';\n static readonly GENERATOR = 'generator';\n static readonly THIS = 'uses-this';\n static readonly ARGUMENTS = 'uses-arguments';\n static readonly NEW_TARGET = 'uses-new-target';\n static readonly EXPORT_DEFAULT = 'export-default';\n static readonly CONSTRUCTED = 'used-as-constructor';\n static readonly ASSERTION = 'assertion-signature';\n static readonly MERGED = 'merged-declaration';\n static readonly HEADER_COMMENT = 'comment-before-the-name';\n}\n\nexport type TArrowSkipReason = TConstValue<typeof ArrowSkipReasons>;\n\n/** A declaration the codemod listed and did not touch. */\nexport interface IArrowSkip {\n name: string;\n line: number;\n reason: TArrowSkipReason;\n}\n\n/** One file's rewrite. */\nexport interface IArrowRewrite {\n output: string;\n rewritten: number;\n skipped: Array<IArrowSkip>;\n}\n\nconst USAGE = `devz codemod function-to-arrow [paths...] [--write [--all] | --check | --dry-run]\n\nRewrites a \\`function\\` declaration as \\`const name = (...) => {...};\\`, keeping export, async, type parameters,\nthe return type and comments. A declaration whose rewrite could change the program is listed with its reason and left\nalone: used before it is declared, overloads, generators, this / arguments / new.target, export default, used with\nnew, assertion signatures and merged declarations. A function another module calls while an import cycle is still\nloading is not detected: run your tests.\n\n --dry-run the default: list the changes and the skips, write nothing\n --write write the changed files (--write needs a path or --all)\n --check dry run that exits 1 while a file would change\n --help print this text and exit`;\n\n/** The rewrite of one file's `function` declarations. */\nexport class FunctionToArrow {\n /** The reason the body cannot move into an arrow: it reads what only a `function` binds. */\n private static ownBinding(opts: {\n typescript: TTypeScript;\n declaration: ts.FunctionDeclaration;\n }): TArrowSkipReason | undefined {\n const { typescript, declaration } = opts;\n let found: TArrowSkipReason | undefined;\n const first = declaration.parameters[0]?.name;\n\n // A `this` parameter types the `this` an arrow does not have.\n if (first && typescript.isIdentifier(first) && first.text === 'this') {\n return ArrowSkipReasons.THIS;\n }\n\n const visit = (node: ts.Node): void => {\n // A nested `function` or class member binds its own; an arrow does not.\n if (\n typescript.isFunctionDeclaration(node) ||\n typescript.isFunctionExpression(node) ||\n typescript.isClassLike(node) ||\n typescript.isMethodDeclaration(node) ||\n typescript.isGetAccessorDeclaration(node) ||\n typescript.isSetAccessorDeclaration(node)\n ) {\n return;\n }\n\n if (node.kind === typescript.SyntaxKind.ThisKeyword) {\n found = ArrowSkipReasons.THIS;\n } else if (typescript.isIdentifier(node) && node.text === 'arguments') {\n found = ArrowSkipReasons.ARGUMENTS;\n } else if (\n typescript.isMetaProperty(node) &&\n node.keywordToken === typescript.SyntaxKind.NewKeyword\n ) {\n found = ArrowSkipReasons.NEW_TARGET;\n }\n\n typescript.forEachChild(node, visit);\n };\n\n declaration.parameters.forEach(visit);\n\n if (declaration.body) {\n typescript.forEachChild(declaration.body, visit);\n }\n\n return found;\n }\n\n /** Every reference to each `function` declaration of the file, itself and its name excluded. */\n private static references(opts: {\n typescript: TTypeScript;\n sourceFile: ts.SourceFile;\n checker: ts.TypeChecker;\n }): Map<ts.Symbol, Array<ts.Identifier>> {\n const { typescript, sourceFile, checker } = opts;\n const found = new Map<ts.Symbol, Array<ts.Identifier>>();\n\n const visit = (node: ts.Node): void => {\n if (typescript.isIdentifier(node)) {\n const parent = node.parent;\n // The name of an export specifier or of a shorthand property stands for the local declaration too.\n const symbol = typescript.isExportSpecifier(parent)\n ? checker.getExportSpecifierLocalTargetSymbol(parent)\n : typescript.isShorthandPropertyAssignment(parent) && parent.name === node\n ? checker.getShorthandAssignmentValueSymbol(parent)\n : checker.getSymbolAtLocation(node);\n const isOwnName = typescript.isFunctionDeclaration(parent) && parent.name === node;\n\n if (symbol && !isOwnName) {\n found.set(symbol, [...(found.get(symbol) ?? []), node]);\n }\n }\n\n typescript.forEachChild(node, visit);\n };\n\n visit(sourceFile);\n\n return found;\n }\n\n /**\n * The earliest position of the file from which `node` can run: where it is written, or earlier when it sits in a\n * hoisted `function` that is itself used before that.\n */\n private static runsFrom(opts: {\n typescript: TTypeScript;\n sourceFile: ts.SourceFile;\n checker: ts.TypeChecker;\n references: Map<ts.Symbol, Array<ts.Identifier>>;\n node: ts.Node;\n seen: Set<ts.Node>;\n }): number {\n const { typescript, sourceFile, checker, references, node, seen } = opts;\n let earliest = node.getStart(sourceFile);\n\n for (let parent: ts.Node | undefined = node.parent; parent; parent = parent.parent) {\n if (!typescript.isFunctionDeclaration(parent) || !parent.name || seen.has(parent)) {\n continue;\n }\n\n seen.add(parent);\n const symbol = checker.getSymbolAtLocation(parent.name);\n\n for (const use of (symbol && references.get(symbol)) ?? []) {\n earliest = Math.min(earliest, FunctionToArrow.runsFrom({ ...opts, node: use, seen }));\n }\n }\n\n return earliest;\n }\n\n /** What the other references to the function forbid. */\n private static usage(opts: {\n typescript: TTypeScript;\n sourceFile: ts.SourceFile;\n checker: ts.TypeChecker;\n references: Map<ts.Symbol, Array<ts.Identifier>>;\n declaration: ts.FunctionDeclaration;\n symbol: ts.Symbol;\n }): TArrowSkipReason | undefined {\n const { typescript, sourceFile, references, declaration, symbol } = opts;\n const uses = references.get(symbol) ?? [];\n const isConstructed = uses.some(\n ({ parent }) =>\n (typescript.isNewExpression(parent) &&\n parent.expression.getText(sourceFile) === declaration.name?.text) ||\n (typescript.isPropertyAccessExpression(parent) && parent.name.text === 'prototype'),\n );\n\n if (isConstructed) {\n return ArrowSkipReasons.CONSTRUCTED;\n }\n\n const start = declaration.getStart(sourceFile);\n const isHoisted = uses.some(\n (node) =>\n FunctionToArrow.runsFrom({ ...opts, node, seen: new Set<ts.Node>([declaration]) }) < start,\n );\n\n return isHoisted ? ArrowSkipReasons.HOISTED : undefined;\n }\n\n private static skipReason(opts: {\n typescript: TTypeScript;\n sourceFile: ts.SourceFile;\n checker: ts.TypeChecker;\n references: Map<ts.Symbol, Array<ts.Identifier>>;\n declaration: ts.FunctionDeclaration;\n name: ts.Identifier;\n }): TArrowSkipReason | undefined {\n const { typescript, sourceFile, checker, references, declaration, name } = opts;\n const modifiers = typescript.getModifiers(declaration) ?? [];\n\n if (modifiers.some((modifier) => modifier.kind === typescript.SyntaxKind.DefaultKeyword)) {\n return ArrowSkipReasons.EXPORT_DEFAULT;\n }\n\n const symbol = checker.getSymbolAtLocation(name);\n const declarations = symbol?.declarations ?? [];\n\n if (!declaration.body || declarations.filter(typescript.isFunctionDeclaration).length > 1) {\n return ArrowSkipReasons.OVERLOAD;\n }\n\n if (declarations.length > 1) {\n return ArrowSkipReasons.MERGED;\n }\n\n if (declaration.asteriskToken) {\n return ArrowSkipReasons.GENERATOR;\n }\n\n if (\n declaration.type &&\n typescript.isTypePredicateNode(declaration.type) &&\n declaration.type.assertsModifier\n ) {\n return ArrowSkipReasons.ASSERTION;\n }\n\n const header = sourceFile.text.slice(\n declaration.getStart(sourceFile),\n name.getStart(sourceFile),\n );\n\n if (header.includes('//') || header.includes('/*')) {\n return ArrowSkipReasons.HEADER_COMMENT;\n }\n\n return (\n FunctionToArrow.ownBinding({ typescript, declaration }) ??\n (symbol\n ? FunctionToArrow.usage({\n typescript,\n sourceFile,\n checker,\n references,\n declaration,\n symbol,\n })\n : undefined)\n );\n }\n\n /** One pass over the file: the declarations that are safe, innermost ones included. */\n private static pass(opts: {\n typescript: TTypeScript;\n fileName: string;\n source: string;\n }): IArrowRewrite {\n const { typescript, fileName, source } = opts;\n const sourceFile = typescript.createSourceFile(\n fileName,\n source,\n typescript.ScriptTarget.Latest,\n true,\n );\n // One file, no library: enough to tell which names refer to which declaration.\n const host: ts.CompilerHost = {\n ...typescript.createCompilerHost({}),\n getSourceFile: (name) => (name === fileName ? sourceFile : undefined),\n };\n const checker = typescript\n .createProgram([fileName], { noLib: true, noResolve: true, allowJs: false }, host)\n .getTypeChecker();\n const references = FunctionToArrow.references({ typescript, sourceFile, checker });\n const isTsx = fileName.endsWith('.tsx');\n const edits: Array<{ start: number; end: number; text: string }> = [];\n const skipped: Array<IArrowSkip> = [];\n\n const visit = (node: ts.Node): void => {\n typescript.forEachChild(node, visit);\n\n if (!typescript.isFunctionDeclaration(node) || !node.name) {\n if (\n typescript.isFunctionDeclaration(node) &&\n (typescript.getModifiers(node) ?? []).some(\n (modifier) => modifier.kind === typescript.SyntaxKind.DefaultKeyword,\n )\n ) {\n skipped.push({\n name: 'default',\n line: sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line + 1,\n reason: ArrowSkipReasons.EXPORT_DEFAULT,\n });\n }\n\n return;\n }\n\n const name = node.name;\n const reason = FunctionToArrow.skipReason({\n typescript,\n sourceFile,\n checker,\n references,\n declaration: node,\n name,\n });\n\n if (reason || !node.body) {\n skipped.push({\n name: name.text,\n line: sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line + 1,\n reason: reason ?? ArrowSkipReasons.OVERLOAD,\n });\n\n return;\n }\n\n const modifiers = (typescript.getModifiers(node) ?? []).map((modifier) => modifier.kind);\n const isExported = modifiers.includes(typescript.SyntaxKind.ExportKeyword);\n const isAsync = modifiers.includes(typescript.SyntaxKind.AsyncKeyword);\n let signature = source.slice(name.end, node.body.getStart(sourceFile)).trimEnd();\n\n // In a .tsx file `<T>(` opens an element; the comma makes it a type parameter list.\n if (isTsx && node.typeParameters?.length === 1 && !node.typeParameters.hasTrailingComma) {\n signature = signature.replace(/>(\\s*\\()/, ',>$1');\n }\n\n const head = `${isExported ? 'export ' : ''}const ${name.text} = ${isAsync ? 'async ' : ''}${signature} => `;\n const bodyStart = node.body.getStart(sourceFile);\n\n edits.push({ start: node.getStart(sourceFile), end: bodyStart, text: head });\n\n if (source[node.body.end] !== ';') {\n edits.push({ start: node.body.end, end: node.body.end, text: ';' });\n }\n };\n\n visit(sourceFile);\n\n let output = source;\n\n // From the end; where a header starts at the point a semicolon goes in, the header is replaced first.\n for (const edit of edits.sort((a, b) => b.start - a.start || b.end - a.end)) {\n output = output.slice(0, edit.start) + edit.text + output.slice(edit.end);\n }\n\n return {\n output,\n rewritten: edits.filter((edit) => edit.end !== edit.start).length,\n skipped: skipped.sort((a, b) => a.line - b.line),\n };\n }\n\n /** The file with every safe declaration rewritten, and the ones left alone with their reasons. */\n static rewrite(opts: {\n typescript: TTypeScript;\n fileName: string;\n source: string;\n }): IArrowRewrite {\n return FunctionToArrow.pass(opts);\n }\n}\n\n/**\n * `devz codemod function-to-arrow [paths...] [--write [--all] | --check | --dry-run]`: a dry run unless `--write`\n * is given. `--check` is the same dry run, and exits 1 while a file would change.\n */\nexport class FunctionToArrowCommand {\n static readonly USAGE = USAGE;\n\n static async run(opts: { root: string; args: string[] }): Promise<number> {\n const { root, args } = opts;\n\n if (\n args.includes(FunctionToArrowFlags.HELP) ||\n args.includes(FunctionToArrowFlags.HELP_SHORT)\n ) {\n CliOutput.log(USAGE);\n\n return 0;\n }\n\n const flags = args.filter((argument) => argument.startsWith('-'));\n const paths = args.filter((argument) => !argument.startsWith('-'));\n const unknown = flags.filter((flag) => !FunctionToArrowFlags.isValid(flag));\n const isWrite = flags.includes(FunctionToArrowFlags.WRITE);\n const isCheck = flags.includes(FunctionToArrowFlags.CHECK);\n const isDryRun = flags.includes(FunctionToArrowFlags.DRY_RUN);\n\n if (unknown.length > 0 || (isWrite && (isCheck || isDryRun))) {\n const problem =\n unknown.length > 0\n ? `unknown option ${unknown.map((flag) => `\"${flag}\"`).join(', ')}`\n : `${FunctionToArrowFlags.WRITE} contradicts a dry run`;\n CliOutput.error(`devz codemod: ${problem}\\n${USAGE}`);\n\n return USAGE_ERROR_CODE;\n }\n\n const refusal = CodemodFiles.refusal({\n command: 'function-to-arrow',\n isWrite,\n isAll: flags.includes(FunctionToArrowFlags.ALL),\n paths,\n });\n\n if (refusal) {\n CliOutput.error(`${refusal}\\n${USAGE}`);\n\n return USAGE_ERROR_CODE;\n }\n\n let typescript: TTypeScript;\n\n try {\n const loaded = await import('typescript');\n typescript = loaded.default;\n } catch {\n CliOutput.error('devz codemod: the \"typescript\" package is required to read your sources');\n\n return 1;\n }\n\n const targets = (paths.length > 0 ? paths : ['.']).map((path) => resolve(root, path));\n let changedCount = 0;\n let rewrittenCount = 0;\n let refusedCount = 0;\n const skips: Array<string> = [];\n\n for (const target of targets) {\n const files = CodemodFiles.collect({ target });\n const dirty = isWrite ? CodemodFiles.dirty({ target }) : undefined;\n\n if (files.length === 0 && paths.length > 0) {\n CliOutput.warn(\n `devz codemod: no source files under \"${relative(root, target) || target}\" (git ignores the path, or it holds none): nothing was read`,\n );\n }\n\n for (const file of files) {\n const source = readFileSync(file, 'utf8');\n\n if (!source.includes('function')) {\n continue;\n }\n\n const result = FunctionToArrow.rewrite({ typescript, fileName: file, source });\n const shown = relative(root, file).split('\\\\').join('/') || file;\n skips.push(\n ...result.skipped.map((skip) => ` ${shown}:${skip.line} ${skip.name} ${skip.reason}`),\n );\n\n if (result.rewritten === 0) {\n continue;\n }\n\n if (dirty?.has(file)) {\n refusedCount += 1;\n CliOutput.warn(\n `refused ${shown} has local changes (commit, stash or \"git add\" them, then run again)`,\n );\n continue;\n }\n\n changedCount += 1;\n rewrittenCount += result.rewritten;\n CliOutput.log(\n `${isWrite ? 'changed' : 'would change'} ${shown} (${result.rewritten} function(s))`,\n );\n\n if (isWrite) {\n writeFileSync(file, result.output);\n }\n }\n }\n\n if (skips.length > 0) {\n CliOutput.log(`left as they are (${skips.length}):\\n${skips.join('\\n')}`);\n }\n\n CliOutput.log(\n `devz codemod function-to-arrow: ${rewrittenCount} function(s) ${isWrite ? 'rewritten' : 'would be rewritten'} in ${changedCount} file(s), ${skips.length} left` +\n (refusedCount > 0 ? `, ${refusedCount} file(s) refused` : ''),\n );\n\n if (!isWrite && changedCount > 0) {\n CliOutput.log(\n `Nothing was written. Run again with ${FunctionToArrowFlags.WRITE} to apply, then run your typecheck, formatter and tests.`,\n );\n }\n\n if (isWrite && refusedCount > 0) {\n return 1;\n }\n\n return isCheck && changedCount > 0 ? 1 : 0;\n }\n}\n"]}
|
|
@@ -4,11 +4,15 @@ exports.CodemodCommand = void 0;
|
|
|
4
4
|
const any_aliases_1 = require("./any-aliases");
|
|
5
5
|
const async_style_1 = require("./async-style");
|
|
6
6
|
const binding_keys_1 = require("./binding-keys");
|
|
7
|
+
const class_renames_1 = require("./class-renames");
|
|
7
8
|
const connector_imports_1 = require("./connector-imports");
|
|
8
9
|
const const_classes_1 = require("./const-classes");
|
|
9
10
|
const env_get_1 = require("./env-get");
|
|
11
|
+
const function_to_arrow_1 = require("./function-to-arrow");
|
|
10
12
|
const drop_redundant_casts_1 = require("./drop-redundant-casts");
|
|
11
13
|
const namespace_functions_1 = require("./namespace-functions");
|
|
14
|
+
const typed_route_context_1 = require("./typed-route-context");
|
|
15
|
+
const cli_output_1 = require("../../common/cli-output");
|
|
12
16
|
const USAGE = [
|
|
13
17
|
drop_redundant_casts_1.DropRedundantCastsCommand.USAGE,
|
|
14
18
|
const_classes_1.ConstClassesCommand.USAGE,
|
|
@@ -18,6 +22,9 @@ const USAGE = [
|
|
|
18
22
|
env_get_1.EnvGetCommand.USAGE,
|
|
19
23
|
any_aliases_1.AnyAliasesCommand.USAGE,
|
|
20
24
|
binding_keys_1.BindingKeysCommand.USAGE,
|
|
25
|
+
class_renames_1.ClassRenamesCommand.USAGE,
|
|
26
|
+
function_to_arrow_1.FunctionToArrowCommand.USAGE,
|
|
27
|
+
typed_route_context_1.TypedRouteContextCommand.USAGE,
|
|
21
28
|
].join('\n\n');
|
|
22
29
|
/** The codemods `devz codemod <name>` runs. */
|
|
23
30
|
const NAME_LIST = [
|
|
@@ -29,6 +36,9 @@ const NAME_LIST = [
|
|
|
29
36
|
'env-get',
|
|
30
37
|
'any-aliases',
|
|
31
38
|
'binding-keys',
|
|
39
|
+
'class-renames',
|
|
40
|
+
'function-to-arrow',
|
|
41
|
+
'typed-route-context',
|
|
32
42
|
];
|
|
33
43
|
const NAMES = NAME_LIST.join(', ');
|
|
34
44
|
/** A usage error: nothing was read or written. */
|
|
@@ -41,6 +51,8 @@ const NOT_REVERSIBLE = new Set([
|
|
|
41
51
|
'env-get',
|
|
42
52
|
'any-aliases',
|
|
43
53
|
'binding-keys',
|
|
54
|
+
'function-to-arrow',
|
|
55
|
+
'typed-route-context',
|
|
44
56
|
]);
|
|
45
57
|
/** `devz codemod <name> [args]`: hands the arguments to the codemod called `name`. */
|
|
46
58
|
class CodemodCommand {
|
|
@@ -48,11 +60,11 @@ class CodemodCommand {
|
|
|
48
60
|
const { args } = opts;
|
|
49
61
|
const [name, ...rest] = args;
|
|
50
62
|
if (name === '--list') {
|
|
51
|
-
|
|
63
|
+
cli_output_1.CliOutput.log(NAME_LIST.join('\n'));
|
|
52
64
|
return 0;
|
|
53
65
|
}
|
|
54
66
|
if (name !== undefined && NOT_REVERSIBLE.has(name) && rest.includes('--reverse')) {
|
|
55
|
-
|
|
67
|
+
cli_output_1.CliOutput.error(`devz codemod ${name}: not reversible`);
|
|
56
68
|
return USAGE_ERROR_CODE;
|
|
57
69
|
}
|
|
58
70
|
if (name === 'drop-redundant-casts') {
|
|
@@ -79,11 +91,20 @@ class CodemodCommand {
|
|
|
79
91
|
if (name === 'binding-keys') {
|
|
80
92
|
return binding_keys_1.BindingKeysCommand.run({ root: opts.root, args: rest });
|
|
81
93
|
}
|
|
94
|
+
if (name === 'function-to-arrow') {
|
|
95
|
+
return function_to_arrow_1.FunctionToArrowCommand.run({ root: opts.root, args: rest });
|
|
96
|
+
}
|
|
97
|
+
if (name === 'typed-route-context') {
|
|
98
|
+
return typed_route_context_1.TypedRouteContextCommand.run({ root: opts.root, args: rest });
|
|
99
|
+
}
|
|
100
|
+
if (name === 'class-renames') {
|
|
101
|
+
return class_renames_1.ClassRenamesCommand.run({ root: opts.root, args: rest });
|
|
102
|
+
}
|
|
82
103
|
if (args.includes('--help') || args.includes('-h')) {
|
|
83
|
-
|
|
104
|
+
cli_output_1.CliOutput.log(USAGE);
|
|
84
105
|
return 0;
|
|
85
106
|
}
|
|
86
|
-
|
|
107
|
+
cli_output_1.CliOutput.error(`devz codemod: unknown codemod "${name ?? ''}" | the codemods are: ${NAMES}\n\n${USAGE}`);
|
|
87
108
|
return USAGE_ERROR_CODE;
|
|
88
109
|
}
|
|
89
110
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/cli/codemod/index.ts"],"names":[],"mappings":";;;AAAA,+CAAkD;AAClD,+CAAkD;AAClD,iDAAoD;AACpD,2DAA8D;AAC9D,mDAAsD;AACtD,uCAA0C;AAC1C,iEAAmE;AACnE,+DAAkE;
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/cli/codemod/index.ts"],"names":[],"mappings":";;;AAAA,+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KAAK,CACb,kCAAkC,IAAI,IAAI,EAAE,yBAAyB,KAAK,OAAO,KAAK,EAAE,CACzF,CAAC;QAEF,OAAO,gBAAgB,CAAC;IAC1B,CAAC;CACF;AAzED,wCAyEC","sourcesContent":["import { AnyAliasesCommand } from './any-aliases';\nimport { AsyncStyleCommand } from './async-style';\nimport { BindingKeysCommand } from './binding-keys';\nimport { ClassRenamesCommand } from './class-renames';\nimport { ConnectorImportsCommand } from './connector-imports';\nimport { ConstClassesCommand } from './const-classes';\nimport { EnvGetCommand } from './env-get';\nimport { FunctionToArrowCommand } from './function-to-arrow';\nimport { DropRedundantCastsCommand } from './drop-redundant-casts';\nimport { NamespaceFunctionsCommand } from './namespace-functions';\nimport { TypedRouteContextCommand } from './typed-route-context';\nimport { CliOutput } from '../../common/cli-output';\n\nconst USAGE = [\n DropRedundantCastsCommand.USAGE,\n ConstClassesCommand.USAGE,\n AsyncStyleCommand.USAGE,\n NamespaceFunctionsCommand.USAGE,\n ConnectorImportsCommand.USAGE,\n EnvGetCommand.USAGE,\n AnyAliasesCommand.USAGE,\n BindingKeysCommand.USAGE,\n ClassRenamesCommand.USAGE,\n FunctionToArrowCommand.USAGE,\n TypedRouteContextCommand.USAGE,\n].join('\\n\\n');\n\n/** The codemods `devz codemod <name>` runs. */\nconst NAME_LIST = [\n 'drop-redundant-casts',\n 'const-classes',\n 'async-style',\n 'namespace-functions',\n 'connector-imports',\n 'env-get',\n 'any-aliases',\n 'binding-keys',\n 'class-renames',\n 'function-to-arrow',\n 'typed-route-context',\n];\nconst NAMES = NAME_LIST.join(', ');\n\n/** A usage error: nothing was read or written. */\nconst USAGE_ERROR_CODE = 2;\n\n/** The codemods that are style rewrites, not migrations: there is no downgrade of them. */\nconst NOT_REVERSIBLE = new Set([\n 'drop-redundant-casts',\n 'const-classes',\n 'async-style',\n 'env-get',\n 'any-aliases',\n 'binding-keys',\n 'function-to-arrow',\n 'typed-route-context',\n]);\n\n/** `devz codemod <name> [args]`: hands the arguments to the codemod called `name`. */\nexport class CodemodCommand {\n static async run(opts: { root: string; args: string[] }): Promise<number> {\n const { args } = opts;\n const [name, ...rest] = args;\n\n if (name === '--list') {\n CliOutput.log(NAME_LIST.join('\\n'));\n\n return 0;\n }\n\n if (name !== undefined && NOT_REVERSIBLE.has(name) && rest.includes('--reverse')) {\n CliOutput.error(`devz codemod ${name}: not reversible`);\n\n return USAGE_ERROR_CODE;\n }\n\n if (name === 'drop-redundant-casts') {\n return DropRedundantCastsCommand.run({ root: opts.root, args: rest });\n }\n\n if (name === 'const-classes') {\n return ConstClassesCommand.run({ root: opts.root, args: rest });\n }\n\n if (name === 'async-style') {\n return AsyncStyleCommand.run({ root: opts.root, args: rest });\n }\n\n if (name === 'namespace-functions') {\n return NamespaceFunctionsCommand.run({ root: opts.root, args: rest });\n }\n\n if (name === 'connector-imports') {\n return ConnectorImportsCommand.run({ root: opts.root, args: rest });\n }\n\n if (name === 'env-get') {\n return EnvGetCommand.run({ root: opts.root, args: rest });\n }\n\n if (name === 'any-aliases') {\n return AnyAliasesCommand.run({ root: opts.root, args: rest });\n }\n\n if (name === 'binding-keys') {\n return BindingKeysCommand.run({ root: opts.root, args: rest });\n }\n\n if (name === 'function-to-arrow') {\n return FunctionToArrowCommand.run({ root: opts.root, args: rest });\n }\n\n if (name === 'typed-route-context') {\n return TypedRouteContextCommand.run({ root: opts.root, args: rest });\n }\n\n if (name === 'class-renames') {\n return ClassRenamesCommand.run({ root: opts.root, args: rest });\n }\n\n if (args.includes('--help') || args.includes('-h')) {\n CliOutput.log(USAGE);\n\n return 0;\n }\n\n CliOutput.error(\n `devz codemod: unknown codemod \"${name ?? ''}\" | the codemods are: ${NAMES}\\n\\n${USAGE}`,\n );\n\n return USAGE_ERROR_CODE;\n }\n}\n"]}
|
|
@@ -10,7 +10,7 @@ export * from './rewriter';
|
|
|
10
10
|
* `--check` is the same dry run, and exits 1 while a call can be rewritten or is left untouched.
|
|
11
11
|
*/
|
|
12
12
|
export declare class NamespaceFunctionsCommand {
|
|
13
|
-
static readonly USAGE = "Usage: devz codemod namespace-functions [paths...] [--write | --check] [--reverse]\n\nMoves calls of an IGNIS function that now lives in a class to the class form, with one options\nobject: `oldName(a, b)` becomes `ClassName.method({ first: a, second: b })`, and an argument named\nlike its key is written short (`{ first }`). The old names are removed from the packages, so run it\nonce after you upgrade. A table in @venizia/dev-configs names each moved function.\n\nIt follows a named import (aliased too) and a namespace import (`ns.oldName(...)`) from a module the\ntable lists, adds the class to that import, and drops the old name once nothing else uses it. It lists\nwith its file and line, and leaves for you: a call with a spread argument or the wrong number of\narguments, the old name used as a value (passed, stored, exported, in typeof), a re-export, a type-only\nimport, and a file that declares a name the rewrite would collide with.\n\nIt also moves the removed `ApplicationLogger`: `ApplicationLogger.get('scope')`, `.get(NAME)` and\n`.get({ scope: NAME })` become `LoggerFactory.getLogger(['scope'])`, `([NAME])`, and the import follows, when\n`ApplicationLogger` comes from `@venizia/ignis-helpers` or `@venizia/ignis`. `Logger.get` and\n`HfLogger.get` are not touched, and a call it cannot decide is listed, as is any other use of\n`ApplicationLogger` (a type, a re-export, a value). An identifier argument is taken for a scope: run your\ntypecheck afterwards.\n\n --write write the changed files (without it, nothing is written)\n --check dry run that exits 1 while a call can be rewritten or is left untouched (for CI)\n --reverse apply the table backward, for a downgrade: `ClassName.method({ first: a })` becomes\n `oldName(a)` and the import follows. The `ApplicationLogger` rule is not reversed.\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\nfiles git knows (tracked, or untracked and not ignored), and --write refuses a file with local changes\n(changed
|
|
13
|
+
static readonly USAGE = "Usage: devz codemod namespace-functions [paths...] [--write | --check] [--reverse]\n\nMoves calls of an IGNIS function that now lives in a class to the class form, with one options\nobject: `oldName(a, b)` becomes `ClassName.method({ first: a, second: b })`, and an argument named\nlike its key is written short (`{ first }`). The old names are removed from the packages, so run it\nonce after you upgrade. A table in @venizia/dev-configs names each moved function.\n\nIt follows a named import (aliased too) and a namespace import (`ns.oldName(...)`) from a module the\ntable lists, adds the class to that import, and drops the old name once nothing else uses it. It lists\nwith its file and line, and leaves for you: a call with a spread argument or the wrong number of\narguments, the old name used as a value (passed, stored, exported, in typeof), a re-export, a type-only\nimport, and a file that declares a name the rewrite would collide with.\n\nIt also moves the removed `ApplicationLogger`: `ApplicationLogger.get('scope')`, `.get(NAME)` and\n`.get({ scope: NAME })` become `LoggerFactory.getLogger(['scope'])`, `([NAME])`, and the import follows, when\n`ApplicationLogger` comes from `@venizia/ignis-helpers` or `@venizia/ignis`. `Logger.get` and\n`HfLogger.get` are not touched, and a call it cannot decide is listed, as is any other use of\n`ApplicationLogger` (a type, a re-export, a value). An identifier argument is taken for a scope: run your\ntypecheck afterwards.\n\n --write write the changed files (without it, nothing is written)\n --check dry run that exits 1 while a call can be rewritten or is left untouched (for CI)\n --reverse apply the table backward, for a downgrade: `ClassName.method({ first: a })` becomes\n `oldName(a)` and the import follows. The `ApplicationLogger` rule is not reversed.\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\nfiles git knows (tracked, or untracked and not ignored), and --write refuses a file with local changes\n(changed since staged, or untracked): commit, stash or \"git add\" it first, so git can undo the codemod.";
|
|
14
14
|
static run(opts: {
|
|
15
15
|
root: string;
|
|
16
16
|
args: string[];
|