@venizia/dev-configs 0.4.8-9 → 0.4.8

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,599 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.EnvGetCommand = exports.EnvGet = 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 env-get [paths...] [--write [--all] | --check]
8
+
9
+ Rewrites the type arguments of applicationEnvironment.get() (and its alias AppEnvs.get()) for the
10
+ @venizia/ignis-helpers release where get() reads strings:
11
+
12
+ get<string>(key) becomes get(key)
13
+ get<string | undefined>(key) becomes get(key)
14
+ get<string>(key, { defaultValue }) becomes get(key, { defaultValue })
15
+ get<R, B>(key, { transform }) becomes get<R>(key, { transform })
16
+
17
+ Any other type argument (get<number>(key), get<boolean>(key)) was a cast the new get() no longer allows:
18
+ the codemod lists it as "manual" and leaves it. Move the conversion into a transform, or read the
19
+ string and convert it where you use it: get(key, { transform: Number }).
20
+
21
+ A call already in the new form (one type argument and an options literal with a transform) is left alone
22
+ and not listed, and a second run changes nothing.
23
+
24
+ It reads TypeScript files (.ts, .tsx, .mts, .cts) and rewrites only calls whose receiver resolves, from the
25
+ scope of the call, to the store: a name imported as applicationEnvironment or AppEnvs from @venizia/ignis,
26
+ @venizia/ignis-helpers (or a sub-path), under any local name (import { AppEnvs as Envs } ...), or a const
27
+ initialised from such a name in the same or an enclosing scope. A parameter, a local variable, an import from
28
+ anywhere else (a barrel of your own included) and a name nothing declares are not the store. Every other
29
+ get<...>(key) call (a property, an optional chain, those names) is printed as skipped with its file and line,
30
+ and a call with a type argument it cannot place as manual, so run your typecheck after it. A call with one type argument and options
31
+ that are not a literal (a variable) is left alone and not listed; one with two type arguments and such options is listed as manual, and so is a number read with such options under --numbers (the codemod cannot see what the options hold). A var declared in a nested block counts as block-scoped (a hoisted one is not followed). A comment between the method name and the parenthesis is dropped. A .js, .cjs or .mjs file
32
+ is not read: edit it by hand.
33
+
34
+ --write write the changed files (without it, nothing is written); it needs a path, or --all
35
+ --all with --write and no path: rewrite every source file under the working directory
36
+ --numbers also rewrite the number reads: get<number>(key) and get<number>(key, { defaultValue }) become
37
+ get(key, { transform: (raw) => ParseUtility.toNumber({ input: raw }), defaultValue }) and
38
+ ParseUtility joins the import of the store. Every rewrite is listed ("numbers"). The old call returned
39
+ the environment STRING typed as a number: after the rewrite the read converts it to a number, an unset
40
+ variable still answers undefined (or the default), and a non-numeric value throws at the read
41
+ instead of flowing on as a string. A boolean (the "false" string is truthy) stays manual. So does a number
42
+ read the rewrite would not compile: a defaultValue that is a literal but not a number ('10'), options that
43
+ are a variable, a ParseUtility name the file already declares for something else (an import from another
44
+ module, a type-only import, a local), and a parameter or local named ParseUtility at the call.
45
+ --check dry run that exits 1 while a file would change or a manual call remains (for CI)
46
+ --help print this text and exit
47
+
48
+ With no flag it lists what would change and writes nothing. Inside a git repository it reads the files
49
+ git knows, and --write refuses a file with local changes: commit or stash it first, so git can undo it.
50
+ There is no --reverse: a downgrade restores the files from git.`;
51
+ /** A usage error: nothing was read or written. */
52
+ const USAGE_ERROR_CODE = 2;
53
+ /** The names the environment store is exported under, and so the receivers `get()` is called on. */
54
+ const RECEIVERS = new Set(['applicationEnvironment', 'AppEnvs']);
55
+ /** A module that exports the store: the root package and the helpers package, with or without a subpath. */
56
+ const STORE_MODULE = /^@venizia\/ignis(?:-helpers)?(?:\/.*)?$/;
57
+ class EnvGetFlags {
58
+ static { this.WRITE = '--write'; }
59
+ static { this.ALL = '--all'; }
60
+ static { this.NUMBERS = '--numbers'; }
61
+ static { this.CHECK = '--check'; }
62
+ static { this.HELP = '--help'; }
63
+ static { this.HELP_SHORT = '-h'; }
64
+ static { this.SCHEME_SET = new Set([
65
+ this.WRITE,
66
+ this.ALL,
67
+ this.NUMBERS,
68
+ this.CHECK,
69
+ this.HELP,
70
+ this.HELP_SHORT,
71
+ ]); }
72
+ static isValid(value) {
73
+ return this.SCHEME_SET.has(value);
74
+ }
75
+ }
76
+ /** Rewrites the type arguments of `applicationEnvironment.get()` calls. */
77
+ class EnvGet {
78
+ /** The names a declaration in `node` binds, for `node` a scope: a block or file, a function, a loop or a catch clause. */
79
+ static declarationIn(opts) {
80
+ const { typescript: ts, scope, name } = opts;
81
+ const bindingNames = (node) => {
82
+ if (ts.isIdentifier(node)) {
83
+ return [node.text];
84
+ }
85
+ return node.elements.flatMap((element) => ts.isBindingElement(element) ? bindingNames(element.name) : []);
86
+ };
87
+ const inDeclarations = (declarations) => declarations.find((declaration) => bindingNames(declaration.name).includes(name));
88
+ if (ts.isSourceFile(scope) ||
89
+ ts.isBlock(scope) ||
90
+ ts.isModuleBlock(scope) ||
91
+ ts.isCaseClause(scope) ||
92
+ ts.isDefaultClause(scope)) {
93
+ for (const statement of scope.statements) {
94
+ if (ts.isVariableStatement(statement)) {
95
+ const found = inDeclarations(statement.declarationList.declarations);
96
+ if (found !== undefined) {
97
+ return found;
98
+ }
99
+ }
100
+ else if ((ts.isFunctionDeclaration(statement) ||
101
+ ts.isClassDeclaration(statement) ||
102
+ ts.isEnumDeclaration(statement)) &&
103
+ statement.name?.text === name) {
104
+ return statement;
105
+ }
106
+ else if (ts.isImportDeclaration(statement) && statement.importClause !== undefined) {
107
+ const clause = statement.importClause;
108
+ if (clause.name?.text === name) {
109
+ return clause;
110
+ }
111
+ const bindings = clause.namedBindings;
112
+ if (bindings !== undefined &&
113
+ ts.isNamespaceImport(bindings) &&
114
+ bindings.name.text === name) {
115
+ return bindings;
116
+ }
117
+ if (bindings !== undefined && ts.isNamedImports(bindings)) {
118
+ const element = bindings.elements.find((candidate) => candidate.name.text === name);
119
+ if (element !== undefined) {
120
+ return element;
121
+ }
122
+ }
123
+ }
124
+ }
125
+ return undefined;
126
+ }
127
+ if (ts.isFunctionLike(scope)) {
128
+ const parameter = scope.parameters.find((candidate) => bindingNames(candidate.name).includes(name));
129
+ if (parameter !== undefined) {
130
+ return parameter;
131
+ }
132
+ return ts.isFunctionExpression(scope) && scope.name?.text === name ? scope : undefined;
133
+ }
134
+ if ((ts.isForStatement(scope) || ts.isForOfStatement(scope) || ts.isForInStatement(scope)) &&
135
+ scope.initializer !== undefined &&
136
+ ts.isVariableDeclarationList(scope.initializer)) {
137
+ return inDeclarations(scope.initializer.declarations);
138
+ }
139
+ if (ts.isCatchClause(scope) && scope.variableDeclaration !== undefined) {
140
+ return inDeclarations([scope.variableDeclaration]);
141
+ }
142
+ return undefined;
143
+ }
144
+ /**
145
+ * Whether `identifier` refers to the environment store: the binding the name resolves to, from the
146
+ * innermost scope outwards, is an import of `applicationEnvironment` or `AppEnvs` from the store module
147
+ * (aliased or not), or a `const` that is initialised from such a name. A parameter, a local, an import
148
+ * from anywhere else and a name nothing declares are not the store.
149
+ */
150
+ static isStore(opts) {
151
+ return EnvGet.storeImport(opts) !== undefined;
152
+ }
153
+ /** The import specifier of the store that `identifier` resolves to (through const aliases), or `undefined` when it is not the store. */
154
+ static storeImport(opts) {
155
+ const { typescript: ts, identifier } = opts;
156
+ const seen = opts.seen ?? new Set();
157
+ if (seen.has(identifier)) {
158
+ return undefined;
159
+ }
160
+ seen.add(identifier);
161
+ for (let scope = identifier.parent; scope !== undefined; scope = scope.parent) {
162
+ const declaration = EnvGet.declarationIn({ typescript: ts, scope, name: identifier.text });
163
+ if (declaration === undefined) {
164
+ continue;
165
+ }
166
+ if (ts.isImportSpecifier(declaration)) {
167
+ const importDeclaration = declaration.parent.parent.parent;
168
+ return ts.isStringLiteral(importDeclaration.moduleSpecifier) &&
169
+ STORE_MODULE.test(importDeclaration.moduleSpecifier.text) &&
170
+ RECEIVERS.has((declaration.propertyName ?? declaration.name).text)
171
+ ? declaration
172
+ : undefined;
173
+ }
174
+ if (ts.isVariableDeclaration(declaration) &&
175
+ (ts.getCombinedNodeFlags(declaration) & ts.NodeFlags.Const) !== 0 &&
176
+ ts.isIdentifier(declaration.name) &&
177
+ declaration.initializer !== undefined &&
178
+ ts.isIdentifier(declaration.initializer)) {
179
+ return EnvGet.storeImport({ typescript: ts, identifier: declaration.initializer, seen });
180
+ }
181
+ return undefined;
182
+ }
183
+ return undefined;
184
+ }
185
+ static rewrite(opts) {
186
+ const { typescript: ts, fileName, source, numbers = false } = opts;
187
+ const language = fileName.endsWith('.tsx') ? ts.ScriptKind.TSX : ts.ScriptKind.TS;
188
+ const file = ts.createSourceFile(fileName, source, ts.ScriptTarget.Latest, true, language);
189
+ const edits = [];
190
+ const manual = [];
191
+ const skipped = [];
192
+ const numbered = [];
193
+ let rewrittenCalls = 0;
194
+ let isParseUtilityImported = false;
195
+ const lineOf = (node) => file.getLineAndCharacterOfPosition(node.getStart(file)).line + 1;
196
+ /** `string`, or `string | undefined` (the type `get(key)` already answers): the type argument can go. */
197
+ const isStringType = (node) => {
198
+ if (node.kind === ts.SyntaxKind.StringKeyword) {
199
+ return true;
200
+ }
201
+ if (ts.isParenthesizedTypeNode(node)) {
202
+ return isStringType(node.type);
203
+ }
204
+ if (ts.isUnionTypeNode(node) && node.types.length === 2) {
205
+ const parts = node.types.map((part) => part.kind);
206
+ return (parts.includes(ts.SyntaxKind.StringKeyword) &&
207
+ parts.includes(ts.SyntaxKind.UndefinedKeyword));
208
+ }
209
+ return false;
210
+ };
211
+ /** An options literal that already carries a `transform`: the call is in the new form. */
212
+ const hasTransform = (node) => node !== undefined &&
213
+ ts.isObjectLiteralExpression(node) &&
214
+ node.properties.some((property) => property.name !== undefined &&
215
+ ts.isIdentifier(property.name) &&
216
+ property.name.text === 'transform');
217
+ /** `number`, or `number | undefined`: the types `--numbers` rewrites. */
218
+ const isNumberType = (node) => {
219
+ if (node.kind === ts.SyntaxKind.NumberKeyword) {
220
+ return true;
221
+ }
222
+ if (ts.isParenthesizedTypeNode(node)) {
223
+ return isNumberType(node.type);
224
+ }
225
+ if (ts.isUnionTypeNode(node) && node.types.length === 2) {
226
+ const parts = node.types.map((part) => part.kind);
227
+ return (parts.includes(ts.SyntaxKind.NumberKeyword) &&
228
+ parts.includes(ts.SyntaxKind.UndefinedKeyword));
229
+ }
230
+ return false;
231
+ };
232
+ /** A literal that is not a number: a `defaultValue` of this kind matches no overload of the rewritten call. */
233
+ const isNonNumericLiteral = (node) => ts.isStringLiteral(node) ||
234
+ ts.isNoSubstitutionTemplateLiteral(node) ||
235
+ ts.isTemplateExpression(node) ||
236
+ ts.isRegularExpressionLiteral(node) ||
237
+ ts.isArrayLiteralExpression(node) ||
238
+ ts.isObjectLiteralExpression(node) ||
239
+ node.kind === ts.SyntaxKind.TrueKeyword ||
240
+ node.kind === ts.SyntaxKind.FalseKeyword ||
241
+ node.kind === ts.SyntaxKind.NullKeyword;
242
+ /** An options literal whose `defaultValue` is a literal that is not a number (`{ defaultValue: '10' }`). */
243
+ const hasNonNumericDefault = (node) => node !== undefined &&
244
+ ts.isObjectLiteralExpression(node) &&
245
+ node.properties.some((property) => ts.isPropertyAssignment(property) &&
246
+ (ts.isIdentifier(property.name) || ts.isStringLiteral(property.name)) &&
247
+ property.name.text === 'defaultValue' &&
248
+ isNonNumericLiteral(property.initializer));
249
+ /** The import specifier the file already has for `ParseUtility`: a value import from the store module, under any local name. */
250
+ const findParseUtilityImport = () => {
251
+ for (const statement of file.statements) {
252
+ if (ts.isImportDeclaration(statement) &&
253
+ ts.isStringLiteral(statement.moduleSpecifier) &&
254
+ STORE_MODULE.test(statement.moduleSpecifier.text) &&
255
+ statement.importClause?.namedBindings !== undefined &&
256
+ ts.isNamedImports(statement.importClause.namedBindings)) {
257
+ const element = statement.importClause.namedBindings.elements.find((candidate) => (candidate.propertyName ?? candidate.name).text === 'ParseUtility' &&
258
+ !candidate.isTypeOnly &&
259
+ !statement.importClause?.isTypeOnly);
260
+ if (element !== undefined) {
261
+ return element;
262
+ }
263
+ }
264
+ }
265
+ return undefined;
266
+ };
267
+ /**
268
+ * The local name `call` can use for `ParseUtility`, or the reason it cannot. The name resolves from the
269
+ * scope of the call, the way the store receiver does: the file's own import of `ParseUtility` from the store
270
+ * module (under any local name) when it is the binding the call sees, a new `ParseUtility` import when
271
+ * nothing in the file or in a scope around the call declares that name. Another module's `ParseUtility`, a
272
+ * type-only import of it, a local declaration of it and a parameter that shadows it all leave the call manual,
273
+ * because the rewrite would not compile (TS2300, TS2339).
274
+ */
275
+ const resolveParseUtility = (call) => {
276
+ const existing = findParseUtilityImport();
277
+ const name = existing?.name.text ?? 'ParseUtility';
278
+ let found;
279
+ let isFileLevel = false;
280
+ for (let scope = call.parent; scope !== undefined && found === undefined; scope = scope.parent) {
281
+ found = EnvGet.declarationIn({ typescript: ts, scope, name });
282
+ isFileLevel = ts.isSourceFile(scope);
283
+ }
284
+ if (found === existing) {
285
+ return { name };
286
+ }
287
+ return {
288
+ reason: isFileLevel
289
+ ? `${name} is already declared in this file by something other than a value import from @venizia/ignis-helpers (an import from another module, a type-only import or a local declaration): the rewrite would not compile, so import ParseUtility from @venizia/ignis-helpers under a free name and write the transform by hand`
290
+ : `a parameter or local declaration named ${name} hides the ParseUtility import at this call: the rewrite would not compile, so write the transform by hand or rename the local`,
291
+ };
292
+ };
293
+ /** Adds `ParseUtility` to the import of the store, once per file: on its own line inside a multi-line import, after the last name in a one-line one, in a new import beside a type-only one. */
294
+ const addParseUtilityImport = (storeImport) => {
295
+ if (isParseUtilityImported || findParseUtilityImport() !== undefined) {
296
+ return;
297
+ }
298
+ isParseUtilityImported = true;
299
+ const declaration = storeImport.parent.parent.parent;
300
+ const named = storeImport.parent;
301
+ if (declaration.importClause?.isTypeOnly) {
302
+ edits.push({
303
+ start: declaration.getEnd(),
304
+ end: declaration.getEnd(),
305
+ text: `\nimport { ParseUtility } from ${declaration.moduleSpecifier.getText(file)};`,
306
+ });
307
+ return;
308
+ }
309
+ const last = named.elements[named.elements.length - 1];
310
+ const lastLine = file.getLineAndCharacterOfPosition(last.getStart(file)).line;
311
+ const isMultiLine = file.getLineAndCharacterOfPosition(named.getStart(file)).line < lastLine;
312
+ if (!isMultiLine) {
313
+ edits.push({ start: last.getEnd(), end: last.getEnd(), text: ', ParseUtility' });
314
+ return;
315
+ }
316
+ const lineStart = file.getLineStarts()[lastLine];
317
+ const indent = source.slice(lineStart, last.getStart(file)).match(/^\s*/)?.[0] ?? '';
318
+ const lineBreak = source.includes('\r\n') ? '\r\n' : '\n';
319
+ edits.push({
320
+ start: last.getEnd(),
321
+ end: last.getEnd(),
322
+ text: `,${lineBreak}${indent}ParseUtility`,
323
+ });
324
+ };
325
+ /** Puts `transform` first in the options literal, keeping its layout: `{}` becomes `{ transform }`, a multi-line literal gets the property on its own line. */
326
+ const insertTransform = (options, transform) => {
327
+ const open = options.getStart(file) + 1;
328
+ const [first] = options.properties;
329
+ if (first === undefined) {
330
+ const inner = source.slice(open, options.getEnd() - 1);
331
+ edits.push(inner.trim() === ''
332
+ ? { start: open, end: options.getEnd() - 1, text: ` ${transform} ` }
333
+ : { start: open, end: open, text: ` ${transform}` });
334
+ return;
335
+ }
336
+ const between = source.slice(open, first.getStart(file));
337
+ if (between.includes('\n')) {
338
+ const firstLineStart = file.getLineStarts()[file.getLineAndCharacterOfPosition(first.getStart(file)).line];
339
+ const indent = source.slice(firstLineStart, first.getStart(file)).match(/^\s*/)?.[0] ?? '';
340
+ const lineBreak = between.includes('\r\n') ? '\r\n' : '\n';
341
+ edits.push({ start: open, end: open, text: `${lineBreak}${indent}${transform},` });
342
+ return;
343
+ }
344
+ edits.push({
345
+ start: open,
346
+ end: open,
347
+ text: ` ${transform},${/^\s/.test(between) ? '' : ' '}`,
348
+ });
349
+ };
350
+ const visit = (node) => {
351
+ if (ts.isCallExpression(node) &&
352
+ node.typeArguments !== undefined &&
353
+ ts.isPropertyAccessExpression(node.expression) &&
354
+ node.expression.name.text === 'get') {
355
+ const callee = node.expression;
356
+ const isOptional = node.questionDotToken !== undefined || callee.questionDotToken !== undefined;
357
+ const storeImport = !isOptional && ts.isIdentifier(callee.expression)
358
+ ? EnvGet.storeImport({ typescript: ts, identifier: callee.expression })
359
+ : undefined;
360
+ if (storeImport !== undefined) {
361
+ const [first] = node.typeArguments;
362
+ const start = callee.name.getEnd();
363
+ const end = node.arguments.pos - 1;
364
+ const options = node.arguments[1];
365
+ const isTwo = node.typeArguments.length === 2;
366
+ const isPlainLiteral = options !== undefined &&
367
+ ts.isObjectLiteralExpression(options) &&
368
+ !hasTransform(options);
369
+ // `get<number>(key)`, `get<number>(key, { defaultValue })` and `get<number, B>(key, { defaultValue })` are one read.
370
+ const isNumberRead = numbers &&
371
+ isNumberType(first) &&
372
+ ((!isTwo &&
373
+ !hasTransform(options) &&
374
+ (options === undefined || ts.isObjectLiteralExpression(options))) ||
375
+ (isTwo && isPlainLiteral));
376
+ // `--numbers`: a number read (one type argument or two) with options the codemod cannot read. It cannot see
377
+ // whether they hold a transform, so the call is listed, not left silently.
378
+ const isNumberReadWithVariableOptions = numbers &&
379
+ isNumberType(first) &&
380
+ options !== undefined &&
381
+ !ts.isObjectLiteralExpression(options);
382
+ if (isNumberReadWithVariableOptions) {
383
+ manual.push({
384
+ line: lineOf(node),
385
+ type: first.getText(file),
386
+ reason: 'the options are not an object literal, so the codemod cannot see whether they hold a transform: put the number transform in them by hand, for example { ...options, transform: (raw) => ParseUtility.toNumber({ input: raw }) }',
387
+ });
388
+ }
389
+ else if (isNumberRead) {
390
+ const parseUtility = resolveParseUtility(node);
391
+ if ('reason' in parseUtility) {
392
+ manual.push({
393
+ line: lineOf(node),
394
+ type: first.getText(file),
395
+ reason: parseUtility.reason,
396
+ });
397
+ }
398
+ else if (hasNonNumericDefault(options)) {
399
+ manual.push({
400
+ line: lineOf(node),
401
+ type: first.getText(file),
402
+ reason: 'the defaultValue is a literal that is not a number: the rewritten call matches no overload (and would return that value as it is), so give it a number or convert it where you use it',
403
+ });
404
+ }
405
+ else {
406
+ addParseUtilityImport(storeImport);
407
+ const transform = `transform: (raw) => ${parseUtility.name}.toNumber({ input: raw })`;
408
+ edits.push({ start, end, text: '' });
409
+ if (options !== undefined && ts.isObjectLiteralExpression(options)) {
410
+ insertTransform(options, transform);
411
+ }
412
+ else {
413
+ const insertAt = node.arguments[0].getEnd();
414
+ edits.push({ start: insertAt, end: insertAt, text: `, { ${transform} }` });
415
+ }
416
+ numbered.push(lineOf(node));
417
+ rewrittenCalls += 1;
418
+ }
419
+ }
420
+ else if (isTwo && options !== undefined && !ts.isObjectLiteralExpression(options)) {
421
+ // `get<R, B>(key, options)` with options in a variable: the codemod cannot see whether they hold a
422
+ // transform or a default of the right type, and `get<R>(key, options)` may not compile with them.
423
+ manual.push({
424
+ line: lineOf(node),
425
+ type: first.getText(file),
426
+ reason: 'two type arguments and options that are not an object literal, so the codemod cannot see what they hold: drop the second type argument by hand once the options carry a transform',
427
+ });
428
+ }
429
+ else if (isTwo && hasTransform(options)) {
430
+ // `get<R, B>(key, { transform })` keeps R, even when R is `string`: a second run leaves
431
+ // `get<string>(key, { transform })` alone.
432
+ edits.push({ start, end, text: `<${first.getText(file)}>` });
433
+ rewrittenCalls += 1;
434
+ }
435
+ else if (!isTwo &&
436
+ options !== undefined &&
437
+ (hasTransform(options) || !ts.isObjectLiteralExpression(options))) {
438
+ // One type argument and a transform: the new form. One type argument and options that are not a
439
+ // literal (a variable): the codemod cannot see what they hold, and what it just left in
440
+ // `get<R, B>(key, options)` would otherwise be listed on the next run; the typecheck names a bad one.
441
+ // Nothing to do and nothing to list.
442
+ }
443
+ else if (isStringType(first) && (!isTwo || isPlainLiteral)) {
444
+ // `string` is what get() returns without a transform, so the type arguments carry nothing: a literal
445
+ // without a transform reads the same with one type argument or two.
446
+ edits.push({ start, end, text: '' });
447
+ rewrittenCalls += 1;
448
+ }
449
+ else {
450
+ manual.push({ line: lineOf(node), type: first.getText(file) });
451
+ }
452
+ }
453
+ else if (node.arguments.length > 0 && !ts.isObjectLiteralExpression(node.arguments[0])) {
454
+ // Every other `x.get<T>(key)` is listed, never hidden: a name the file does not bind to the store, a
455
+ // property, a parameter or an optional chain. A container lookup shares the shape (its first
456
+ // argument is an object literal, so it is not listed).
457
+ skipped.push({ line: lineOf(node), receiver: callee.expression.getText(file) });
458
+ }
459
+ }
460
+ ts.forEachChild(node, visit);
461
+ };
462
+ visit(file);
463
+ if (edits.length === 0) {
464
+ return { output: source, changed: false, rewritten: 0, manual, numbered, skipped };
465
+ }
466
+ let output = source;
467
+ for (const edit of [...edits].sort((left, right) => right.start - left.start)) {
468
+ output = output.slice(0, edit.start) + edit.text + output.slice(edit.end);
469
+ }
470
+ return {
471
+ output,
472
+ changed: output !== source,
473
+ rewritten: rewrittenCalls,
474
+ manual,
475
+ numbered,
476
+ skipped,
477
+ };
478
+ }
479
+ }
480
+ exports.EnvGet = EnvGet;
481
+ /** `devz codemod env-get [paths...] [--write | --check]`: rewrites the type arguments of `applicationEnvironment.get()`. */
482
+ class EnvGetCommand {
483
+ static { this.USAGE = USAGE; }
484
+ static async run(opts) {
485
+ const { root, args } = opts;
486
+ if (args.includes(EnvGetFlags.HELP) || args.includes(EnvGetFlags.HELP_SHORT)) {
487
+ console.log(USAGE);
488
+ return 0;
489
+ }
490
+ const flags = args.filter((argument) => argument.startsWith('-'));
491
+ const paths = args.filter((argument) => !argument.startsWith('-'));
492
+ const unknown = flags.filter((flag) => !EnvGetFlags.isValid(flag));
493
+ if (unknown.length > 0) {
494
+ console.error(`devz codemod: unknown option ${unknown.map((flag) => `"${flag}"`).join(', ')}\n${USAGE}`);
495
+ return USAGE_ERROR_CODE;
496
+ }
497
+ const isWrite = flags.includes(EnvGetFlags.WRITE);
498
+ const isCheck = flags.includes(EnvGetFlags.CHECK);
499
+ const isNumbers = flags.includes(EnvGetFlags.NUMBERS);
500
+ if (isWrite && isCheck) {
501
+ console.error(`devz codemod: ${EnvGetFlags.WRITE} and ${EnvGetFlags.CHECK} contradict each other\n${USAGE}`);
502
+ return USAGE_ERROR_CODE;
503
+ }
504
+ const refusal = files_1.CodemodFiles.refusal({
505
+ command: 'env-get',
506
+ isWrite,
507
+ isAll: flags.includes(EnvGetFlags.ALL),
508
+ paths,
509
+ });
510
+ if (refusal) {
511
+ console.error(`${refusal}\n${USAGE}`);
512
+ return USAGE_ERROR_CODE;
513
+ }
514
+ let typescript;
515
+ try {
516
+ const loaded = await import('typescript');
517
+ typescript = loaded.default;
518
+ }
519
+ catch {
520
+ console.error('devz codemod: the "typescript" package is required to read your sources');
521
+ return 1;
522
+ }
523
+ const targets = (paths.length > 0 ? paths : ['.']).map((path) => (0, node_path_1.resolve)(root, path));
524
+ let changedCount = 0;
525
+ let callCount = 0;
526
+ let manualCount = 0;
527
+ let skippedCount = 0;
528
+ let numberedCount = 0;
529
+ const manualByType = new Map();
530
+ let refusedCount = 0;
531
+ for (const target of targets) {
532
+ const files = files_1.CodemodFiles.collect({ target });
533
+ const dirty = isWrite ? files_1.CodemodFiles.dirty({ target }) : undefined;
534
+ if (files.length === 0 && paths.length > 0) {
535
+ 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`);
536
+ }
537
+ for (const file of files) {
538
+ const source = (0, node_fs_1.readFileSync)(file, 'utf8');
539
+ if (!/\.\s*get\b/.test(source)) {
540
+ continue;
541
+ }
542
+ const result = EnvGet.rewrite({
543
+ typescript,
544
+ fileName: file,
545
+ source,
546
+ numbers: isNumbers,
547
+ });
548
+ const shown = (0, node_path_1.relative)(root, file).split('\\').join('/') || file;
549
+ for (const item of result.manual) {
550
+ manualCount += 1;
551
+ manualByType.set(item.type, (manualByType.get(item.type) ?? 0) + 1);
552
+ console.warn(`manual ${shown}:${item.line} get<${item.type}>: ${item.reason ??
553
+ 'a type argument the rewrite cannot place (not string or string | undefined, or two type arguments without an options argument): a number or other conversion goes in a transform, for example get(key, { transform: Number })'}`);
554
+ }
555
+ for (const line of result.numbered) {
556
+ numberedCount += 1;
557
+ console.log(`numbers ${shown}:${line} get<number> rewritten to a transform: the value is now a real number and a non-numeric value throws at the read`);
558
+ }
559
+ for (const call of result.skipped) {
560
+ skippedCount += 1;
561
+ console.warn(`skipped ${shown}:${call.line} ${call.receiver}.get<...>(): the receiver is not bound to applicationEnvironment or AppEnvs in this file (a property, a parameter, an optional chain or another object): check it by hand if it is the environment store`);
562
+ }
563
+ if (!result.changed) {
564
+ continue;
565
+ }
566
+ if (dirty?.has(file)) {
567
+ refusedCount += 1;
568
+ console.warn(`refused ${shown} has local changes (commit or stash them, then run again)`);
569
+ continue;
570
+ }
571
+ changedCount += 1;
572
+ callCount += result.rewritten;
573
+ console.log(`${isWrite ? 'changed' : 'would change'} ${shown} (${result.rewritten} call(s))`);
574
+ if (isWrite) {
575
+ (0, node_fs_1.writeFileSync)(file, result.output);
576
+ }
577
+ }
578
+ }
579
+ console.log(`devz codemod env-get: ${changedCount} file(s) ${isWrite ? 'changed' : 'would change'}, ${callCount} call(s) ${isWrite ? 'rewritten' : 'would be rewritten'}, ${manualCount} manual, ${skippedCount} skipped` +
580
+ (isNumbers ? `, ${numberedCount} number read(s) rewritten` : '') +
581
+ (refusedCount > 0 ? `, ${refusedCount} refused` : ''));
582
+ if (manualByType.size > 0) {
583
+ const counts = [...manualByType.entries()]
584
+ .sort((left, right) => right[1] - left[1])
585
+ .map(([typeText, count]) => `${typeText} x${count}`)
586
+ .join(', ');
587
+ console.log(`manual by type argument: ${counts}`);
588
+ }
589
+ if (!isWrite && changedCount > 0) {
590
+ console.log(`Nothing was written. Run again with ${EnvGetFlags.WRITE} to apply, then run your typecheck.`);
591
+ }
592
+ if (isWrite && refusedCount > 0) {
593
+ return 1;
594
+ }
595
+ return isCheck && (changedCount > 0 || manualCount > 0) ? 1 : 0;
596
+ }
597
+ }
598
+ exports.EnvGetCommand = EnvGetCommand;
599
+ //# sourceMappingURL=env-get.js.map