@cosmicdrift/kumiko-feature-ast 0.413.1 → 0.415.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.
- package/dist/extractors/handlers.js +2 -1
- package/dist/extractors/projections-screens.js +12 -0
- package/dist/patch.js +2 -2
- package/dist/pattern-id-matchers.d.ts +1 -5
- package/dist/pattern-id-matchers.js +4 -2
- package/dist/patterns.d.ts +2 -1
- package/dist/render.js +3 -0
- package/package.json +3 -3
- package/src/changes.json +12 -0
- package/src/scripts/codemod/codemod-support.ts +22 -4
- package/src/scripts/codemod/collect-source-files.ts +28 -3
- package/src/scripts/codemod/ctx-namespaces-annotations.ts +12 -5
- package/src/scripts/codemod/ctx-namespaces-structural-types.ts +161 -36
- package/src/scripts/codemod/feature-ast-package-manifest.ts +11 -5
- package/src/scripts/codemod/feature-ast-package.ts +68 -6
- package/src/scripts/codemod/lint-ignore-to-biome.ts +218 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { ENTITY_CONVENTION_QUERY_BRAND } from "@cosmicdrift/kumiko-types/handlers";
|
|
1
|
+
import { ENTITY_CONVENTION_QUERY_BRAND, ENTITY_CONVENTION_WRITE_BRAND, } from "@cosmicdrift/kumiko-types/handlers";
|
|
2
2
|
import { SyntaxKind } from "ts-morph";
|
|
3
3
|
import { sourceLocationFromNode } from "../source-location.js";
|
|
4
4
|
import { readHeaderValueOrRaw, readOptionalAccessRule, readOptionalAdditionalRateLimits, readOptionalEscapeHatch, readOptionalRateLimit, } from "./hooks.js";
|
|
@@ -26,6 +26,7 @@ const WRITE_HANDLER_KEY_KINDS = {
|
|
|
26
26
|
name: "modeled",
|
|
27
27
|
schema: "modeled",
|
|
28
28
|
handler: "modeled",
|
|
29
|
+
[ENTITY_CONVENTION_WRITE_BRAND]: "opaque",
|
|
29
30
|
access: "modeled",
|
|
30
31
|
description: "modeled",
|
|
31
32
|
agent: "modeled",
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { IRREVERSIBLE_WITHOUT_ENTRY_HANDLER_CASES, } from "@cosmicdrift/kumiko-types/config";
|
|
2
|
+
import { isOneOf } from "@cosmicdrift/kumiko-types/type-guards";
|
|
1
3
|
import { SyntaxKind } from "ts-morph";
|
|
2
4
|
import { SCREEN_OPAQUE_MARKER } from "../patterns.js";
|
|
3
5
|
import { sourceLocationFromNode } from "../source-location.js";
|
|
@@ -102,6 +104,15 @@ export function extractMultiStreamProjection(call, sourceFile) {
|
|
|
102
104
|
const delivery = deliveryLit
|
|
103
105
|
? deliveryLit.getLiteralValue()
|
|
104
106
|
: undefined;
|
|
107
|
+
const irreversibleLit = arg
|
|
108
|
+
.getProperty("irreversibleWithoutEntryHandler")
|
|
109
|
+
?.asKind(SyntaxKind.PropertyAssignment)
|
|
110
|
+
?.getInitializer()
|
|
111
|
+
?.asKind(SyntaxKind.StringLiteral);
|
|
112
|
+
const irreversibleValue = irreversibleLit?.getLiteralValue();
|
|
113
|
+
const irreversibleWithoutEntryHandler = isOneOf(IRREVERSIBLE_WITHOUT_ENTRY_HANDLER_CASES, irreversibleValue)
|
|
114
|
+
? irreversibleValue
|
|
115
|
+
: undefined;
|
|
105
116
|
return ok({
|
|
106
117
|
kind: "multiStreamProjection",
|
|
107
118
|
source: sourceLocationFromNode(call, sourceFile),
|
|
@@ -110,6 +121,7 @@ export function extractMultiStreamProjection(call, sourceFile) {
|
|
|
110
121
|
...(isPlainObject(errorMode) && { errorMode: errorMode }),
|
|
111
122
|
...(runIn !== undefined && { runIn }),
|
|
112
123
|
...(delivery !== undefined && { delivery }),
|
|
124
|
+
...(irreversibleWithoutEntryHandler !== undefined && { irreversibleWithoutEntryHandler }),
|
|
113
125
|
});
|
|
114
126
|
}
|
|
115
127
|
export function collectScreenOpaqueProps(node, path, sourceFile, out) {
|
package/dist/patch.js
CHANGED
|
@@ -525,7 +525,7 @@ function findCallForId(sourceFile, id) {
|
|
|
525
525
|
continue;
|
|
526
526
|
if (propAccess.getName() !== id.kind)
|
|
527
527
|
continue;
|
|
528
|
-
if (callMatchesId(call, id
|
|
528
|
+
if (callMatchesId(call, id))
|
|
529
529
|
matches.push(call);
|
|
530
530
|
}
|
|
531
531
|
if (SINGLETON_KINDS.has(id.kind) && matches.length > 1) {
|
|
@@ -546,7 +546,7 @@ function findAiStepCall(sourceFile, id) {
|
|
|
546
546
|
for (const call of sourceFile.getDescendantsOfKind(SyntaxKind.CallExpression)) {
|
|
547
547
|
if (call.getExpression().getText() !== factory)
|
|
548
548
|
continue;
|
|
549
|
-
if (callMatchesId(call, id
|
|
549
|
+
if (callMatchesId(call, id))
|
|
550
550
|
matches.push(call);
|
|
551
551
|
}
|
|
552
552
|
if (matches.length > 1) {
|
|
@@ -1,7 +1,3 @@
|
|
|
1
1
|
import { type CallExpression } from "ts-morph";
|
|
2
2
|
import type { PatternId } from "./patch.ts";
|
|
3
|
-
|
|
4
|
-
type PatternIdKind = PatternId["kind"];
|
|
5
|
-
type PatternIdOfKind = MembersByKind<PatternId>;
|
|
6
|
-
export declare function callMatchesId<K extends PatternIdKind>(call: CallExpression, kind: K, id: PatternIdOfKind[K]): boolean;
|
|
7
|
-
export {};
|
|
3
|
+
export declare function callMatchesId(call: CallExpression, id: PatternId): boolean;
|
|
@@ -39,7 +39,10 @@ const PATTERN_ID_MATCHERS = {
|
|
|
39
39
|
"ai.extract": matchAiStepCall,
|
|
40
40
|
"ai.classify": matchAiStepCall,
|
|
41
41
|
};
|
|
42
|
-
export function callMatchesId(call,
|
|
42
|
+
export function callMatchesId(call, id) {
|
|
43
|
+
return dispatchMatcher(call, id.kind, id);
|
|
44
|
+
}
|
|
45
|
+
function dispatchMatcher(call, kind, id) {
|
|
43
46
|
return PATTERN_ID_MATCHERS[kind](call, id);
|
|
44
47
|
}
|
|
45
48
|
// Singletons: kind alone identifies the call.
|
|
@@ -161,7 +164,6 @@ function matchArgString(call, index, expected) {
|
|
|
161
164
|
return false;
|
|
162
165
|
return readNameLiteral(arg) === expected;
|
|
163
166
|
}
|
|
164
|
-
// @wrapper-known semantic-alias
|
|
165
167
|
function matchFirstArgString(call, expected) {
|
|
166
168
|
return matchArgString(call, 0, expected);
|
|
167
169
|
}
|
package/dist/patterns.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { AccessRule, AgentHandlerHints, ClaimKeyType, ConfigKeyDefinition, ConfigKeyType, EntityDefinition, EscapeHatchDeclaration, JobDefinition, LifecycleHookType, MspErrorMode, NavDefinition, ReferenceDataDef, RelationDefinition, ScreenDefinition, SecretNamespaceOptions, TranslationKeys, TreeActionDef, WorkspaceDefinition } from "@cosmicdrift/kumiko-framework/engine";
|
|
2
|
-
import type { RunIn } from "@cosmicdrift/kumiko-types/config";
|
|
2
|
+
import type { IrreversibleWithoutEntryHandler, RunIn } from "@cosmicdrift/kumiko-types/config";
|
|
3
3
|
import type { MetricOptions, SecretOptions } from "@cosmicdrift/kumiko-types/feature";
|
|
4
4
|
import type { PayloadRateLimitOption, RateLimitDeclaration } from "@cosmicdrift/kumiko-types/handlers";
|
|
5
5
|
import type { HookPhase } from "@cosmicdrift/kumiko-types/hook-phase";
|
|
@@ -223,6 +223,7 @@ export type MultiStreamProjectionPattern = {
|
|
|
223
223
|
readonly errorMode?: MspErrorMode;
|
|
224
224
|
readonly runIn?: RunIn;
|
|
225
225
|
readonly delivery?: "shared" | "per-instance";
|
|
226
|
+
readonly irreversibleWithoutEntryHandler?: IrreversibleWithoutEntryHandler;
|
|
226
227
|
};
|
|
227
228
|
export type DefineEventPattern = {
|
|
228
229
|
readonly kind: "defineEvent";
|
package/dist/render.js
CHANGED
|
@@ -527,6 +527,9 @@ function renderMultiStreamProjection(p) {
|
|
|
527
527
|
lines.push(` runIn: ${renderValue(p.runIn)},`);
|
|
528
528
|
if (p.delivery !== undefined)
|
|
529
529
|
lines.push(` delivery: ${JSON.stringify(p.delivery)},`);
|
|
530
|
+
if (p.irreversibleWithoutEntryHandler !== undefined) {
|
|
531
|
+
lines.push(` irreversibleWithoutEntryHandler: ${JSON.stringify(p.irreversibleWithoutEntryHandler)},`);
|
|
532
|
+
}
|
|
530
533
|
lines.push("});");
|
|
531
534
|
return lines.join("\n");
|
|
532
535
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cosmicdrift/kumiko-feature-ast",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.415.0",
|
|
4
4
|
"description": "Feature-file AST for Kumiko: parse, patch and render feature definitions, the pattern library, and the codemods kumiko-upgrade runs.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Marc Frost <marc@cosmicdriftgamestudio.com>",
|
|
@@ -22,8 +22,8 @@
|
|
|
22
22
|
}
|
|
23
23
|
},
|
|
24
24
|
"dependencies": {
|
|
25
|
-
"@cosmicdrift/kumiko-framework": "0.
|
|
26
|
-
"@cosmicdrift/kumiko-types": "0.
|
|
25
|
+
"@cosmicdrift/kumiko-framework": "0.415.0",
|
|
26
|
+
"@cosmicdrift/kumiko-types": "0.415.0",
|
|
27
27
|
"ts-morph": "^28.0.0",
|
|
28
28
|
"zod": "^4.6.7"
|
|
29
29
|
},
|
package/src/changes.json
CHANGED
|
@@ -1,4 +1,16 @@
|
|
|
1
1
|
[
|
|
2
|
+
{
|
|
3
|
+
"version": "0.415.0",
|
|
4
|
+
"type": "fix",
|
|
5
|
+
"title": "lint-ignore-to-biome skips no-raw-hooks markers outside the plugin scope",
|
|
6
|
+
"detail": "The no-raw-hooks Biome plugin only scans .tsx files under web/ and public/, without tests, renderer, document-designer and samples. Converting a marker elsewhere produced a `biome-ignore` that suppresses nothing. The codemod now keeps such markers as they are."
|
|
7
|
+
},
|
|
8
|
+
{
|
|
9
|
+
"version": "0.414.0",
|
|
10
|
+
"type": "fix",
|
|
11
|
+
"title": "ctx-namespaces codemod reads the context kind a structural parameter receives",
|
|
12
|
+
"detail": "A structural context type that only a job context reaches kept being rewritten with the handler namespaces, for example `tracer` into `obs.tracer`, which `JobContext` does not carry. The codemod now collects the context kinds that reach the parameter: members that move the same way for all kinds are rewritten, members that move for one kind only are reported as manual. The type-aware project also forwards the redirected project reference and the module mode of the importing file to module resolution."
|
|
13
|
+
},
|
|
2
14
|
{
|
|
3
15
|
"version": "0.404.0",
|
|
4
16
|
"type": "improvement",
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { existsSync, readFileSync, writeFileSync } from "node:fs";
|
|
1
|
+
import { existsSync, readFileSync, statSync, writeFileSync } from "node:fs";
|
|
2
2
|
import { dirname, join, relative, resolve } from "node:path";
|
|
3
3
|
import {
|
|
4
4
|
type ImportDeclaration,
|
|
@@ -278,7 +278,8 @@ function displayPath(file: string): string {
|
|
|
278
278
|
|
|
279
279
|
export interface CodemodCliConfig {
|
|
280
280
|
readonly name: string;
|
|
281
|
-
|
|
281
|
+
// projectRoot: nearest ancestor of the target with a Biome config, else the target itself.
|
|
282
|
+
readonly transform: (source: string, filePath: string, projectRoot: string) => CodemodResult;
|
|
282
283
|
readonly isSkippedPath: (file: string) => boolean;
|
|
283
284
|
// Exact file names (e.g. package.json) handed to transform next to the .ts/.tsx sources.
|
|
284
285
|
readonly extraFileNames?: readonly string[];
|
|
@@ -301,17 +302,29 @@ function parseArgsOrUsageError(
|
|
|
301
302
|
}
|
|
302
303
|
}
|
|
303
304
|
|
|
305
|
+
function findProjectRoot(target: string): string {
|
|
306
|
+
const start = resolve(target);
|
|
307
|
+
let dir = statSync(start).isDirectory() ? start : dirname(start);
|
|
308
|
+
for (;;) {
|
|
309
|
+
if (existsSync(join(dir, "biome.json")) || existsSync(join(dir, "biome.jsonc"))) return dir;
|
|
310
|
+
const parent = dirname(dir);
|
|
311
|
+
if (parent === dir) return statSync(start).isDirectory() ? start : dirname(start);
|
|
312
|
+
dir = parent;
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
|
|
304
316
|
function transformFiles(
|
|
305
317
|
config: CodemodCliConfig,
|
|
306
318
|
files: readonly string[],
|
|
307
319
|
mode: Mode,
|
|
320
|
+
projectRoot: string,
|
|
308
321
|
): { rewrites: CodemodSite[]; manual: CodemodSite[]; changedFiles: string[] } {
|
|
309
322
|
const rewrites: CodemodSite[] = [];
|
|
310
323
|
const manual: CodemodSite[] = [];
|
|
311
324
|
const changedFiles: string[] = [];
|
|
312
325
|
for (const file of files) {
|
|
313
326
|
const before = readFileSync(file, "utf8");
|
|
314
|
-
const result = config.transform(before, file);
|
|
327
|
+
const result = config.transform(before, file, projectRoot);
|
|
315
328
|
const shown = displayPath(file);
|
|
316
329
|
for (const site of result.rewrites)
|
|
317
330
|
console.log(`${shown}:${site.line} rewritten ${site.description}`);
|
|
@@ -349,7 +362,12 @@ export async function runCodemod(
|
|
|
349
362
|
(config.extraFileNames?.includes(name) ?? false) ||
|
|
350
363
|
(config.extraExtensions?.some((extension) => name.endsWith(extension)) ?? false),
|
|
351
364
|
}).filter((file) => !(file.includes("/__tests__/fixtures/") || config.isSkippedPath(file)));
|
|
352
|
-
const { rewrites, manual, changedFiles } = transformFiles(
|
|
365
|
+
const { rewrites, manual, changedFiles } = transformFiles(
|
|
366
|
+
config,
|
|
367
|
+
files,
|
|
368
|
+
options.mode,
|
|
369
|
+
findProjectRoot(options.paths[0] ?? "."),
|
|
370
|
+
);
|
|
353
371
|
console.log(
|
|
354
372
|
`\n[${config.name}] ${options.mode === "write" ? "rewritten" : "rewritable"}: ${rewrites.length} site(s) in ${new Set(rewrites.map((site) => site.file)).size} file(s); manual: ${manual.length}`,
|
|
355
373
|
);
|
|
@@ -51,9 +51,10 @@ export function collectSourceFiles(
|
|
|
51
51
|
return files;
|
|
52
52
|
}
|
|
53
53
|
|
|
54
|
-
// git check-ignore exits 0 when it printed ignored paths
|
|
55
|
-
// repository
|
|
54
|
+
// git check-ignore exits 0 when it printed ignored paths and 1 when none is ignored. Any other code
|
|
55
|
+
// (128: outside a repository, or one path in a submodule fails the whole batch) cannot filter the batch.
|
|
56
56
|
const GIT_CHECK_IGNORE_SOME_IGNORED = 0;
|
|
57
|
+
const GIT_CHECK_IGNORE_NONE_IGNORED = 1;
|
|
57
58
|
|
|
58
59
|
// A git hook exports GIT_DIR and friends, and git prefers them over cwd: inherited, check-ignore
|
|
59
60
|
// would ask the hook's repository about paths outside it.
|
|
@@ -70,11 +71,35 @@ export function envWithoutGitRepositoryOverrides(): Record<string, string> {
|
|
|
70
71
|
function withoutGitIgnored(cwd: string, files: readonly string[]): readonly string[] {
|
|
71
72
|
if (files.length === 0) return files;
|
|
72
73
|
const result = runGitCheckIgnore(cwd, files);
|
|
73
|
-
if (result === undefined || result.exitCode
|
|
74
|
+
if (result === undefined || result.exitCode === GIT_CHECK_IGNORE_NONE_IGNORED) return files;
|
|
75
|
+
if (result.exitCode !== GIT_CHECK_IGNORE_SOME_IGNORED) {
|
|
76
|
+
if (!isInsideWorkTree(cwd)) return files;
|
|
77
|
+
return files.filter((file) => !isIgnoredByOwnRepository(file));
|
|
78
|
+
}
|
|
74
79
|
const ignored = new Set(result.stdout.toString().split("\0"));
|
|
75
80
|
return files.filter((file) => !ignored.has(file));
|
|
76
81
|
}
|
|
77
82
|
|
|
83
|
+
function isInsideWorkTree(cwd: string): boolean {
|
|
84
|
+
return (
|
|
85
|
+
Bun.spawnSync({
|
|
86
|
+
cmd: ["git", "rev-parse", "--is-inside-work-tree"],
|
|
87
|
+
cwd,
|
|
88
|
+
env: envWithoutGitRepositoryOverrides(),
|
|
89
|
+
stdout: "ignore",
|
|
90
|
+
stderr: "ignore",
|
|
91
|
+
}).exitCode === 0
|
|
92
|
+
);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// The batch failed inside a repository, so each file is asked from its own directory: a file inside a submodule or
|
|
96
|
+
// embedded checkout then answers from that repository's .gitignore instead of dropping the filter
|
|
97
|
+
// for every file under the root.
|
|
98
|
+
function isIgnoredByOwnRepository(file: string): boolean {
|
|
99
|
+
const result = runGitCheckIgnore(dirname(file), [file]);
|
|
100
|
+
return result?.exitCode === GIT_CHECK_IGNORE_SOME_IGNORED;
|
|
101
|
+
}
|
|
102
|
+
|
|
78
103
|
function runGitCheckIgnore(cwd: string, files: readonly string[]) {
|
|
79
104
|
try {
|
|
80
105
|
return Bun.spawnSync({
|
|
@@ -2,6 +2,7 @@ import { Node, Project, type SourceFile, SyntaxKind, type Type } from "ts-morph"
|
|
|
2
2
|
import { ensureNamedImport, removeNamedImport } from "./codemod-support.ts";
|
|
3
3
|
import type { EditPlan } from "./ctx-namespaces-edits.ts";
|
|
4
4
|
import type { ContextKind } from "./ctx-namespaces-mapping.ts";
|
|
5
|
+
import type { StructuralContextParameter } from "./ctx-namespaces-structural-types.ts";
|
|
5
6
|
|
|
6
7
|
export interface NamedImportNeed {
|
|
7
8
|
readonly specifier: string;
|
|
@@ -15,17 +16,23 @@ export class Counters {
|
|
|
15
16
|
readonly droppedImports = new Set<string>();
|
|
16
17
|
// Hook parameters annotated AppContext whose annotation is rewritten in this run: their body is
|
|
17
18
|
// already read as a handler context.
|
|
18
|
-
readonly pinnedParameters = new
|
|
19
|
+
readonly pinnedParameters = new Map<Node, ContextKind>();
|
|
19
20
|
// Structural context type members moved in this run, so a type shared by several parameters is
|
|
20
21
|
// rewritten once.
|
|
21
22
|
readonly rewrittenMembers = new Set<Node>();
|
|
23
|
+
// Finding the kinds a parameter receives walks references recursively; every call site and the
|
|
24
|
+
// annotation visit ask for the same parameter.
|
|
25
|
+
readonly structuralParameters = new Map<Node, StructuralContextParameter | undefined>();
|
|
26
|
+
readonly typeSharedWithOthers = new Map<Node, boolean>();
|
|
22
27
|
|
|
23
28
|
pinnedKindOf(expression: Node): ContextKind | undefined {
|
|
24
29
|
if (!Node.isIdentifier(expression)) return undefined;
|
|
25
30
|
const declarations = expression.getSymbol()?.getDeclarations() ?? [];
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
31
|
+
for (const declaration of declarations) {
|
|
32
|
+
const kind = this.pinnedParameters.get(declaration);
|
|
33
|
+
if (kind !== undefined) return kind;
|
|
34
|
+
}
|
|
35
|
+
return undefined;
|
|
29
36
|
}
|
|
30
37
|
}
|
|
31
38
|
|
|
@@ -143,7 +150,7 @@ export function planHookAnnotation(plan: EditPlan, counters: Counters, parameter
|
|
|
143
150
|
}
|
|
144
151
|
counters.imports.push({ ...imported, name: "HandlerContext" });
|
|
145
152
|
counters.droppedImports.add("AppContext");
|
|
146
|
-
counters.pinnedParameters.
|
|
153
|
+
counters.pinnedParameters.set(parameter, "handler");
|
|
147
154
|
plan.replaceNode(reference.getTypeName(), "HandlerContext");
|
|
148
155
|
plan.recordRewrite(reference, "AppContext -> HandlerContext (hook parameter)");
|
|
149
156
|
return true;
|
|
@@ -5,13 +5,21 @@ import {
|
|
|
5
5
|
Node,
|
|
6
6
|
type ParameterDeclaration,
|
|
7
7
|
type PropertySignature,
|
|
8
|
+
SyntaxKind,
|
|
8
9
|
type TypeLiteralNode,
|
|
9
10
|
} from "ts-morph";
|
|
10
11
|
import { appContextReference, type Counters } from "./ctx-namespaces-annotations.ts";
|
|
11
12
|
import { contextReceiver } from "./ctx-namespaces-contracts.ts";
|
|
12
13
|
import { isContextNamedReceiver, isKumikoTypesFile, receiverOf } from "./ctx-namespaces-detect.ts";
|
|
13
14
|
import type { EditPlan } from "./ctx-namespaces-edits.ts";
|
|
14
|
-
import {
|
|
15
|
+
import {
|
|
16
|
+
type ContextKind,
|
|
17
|
+
describePath,
|
|
18
|
+
isMovedMemberName,
|
|
19
|
+
moveOf,
|
|
20
|
+
type NamespacePath,
|
|
21
|
+
samePath,
|
|
22
|
+
} from "./ctx-namespaces-mapping.ts";
|
|
15
23
|
|
|
16
24
|
type MemberOwner = TypeLiteralNode | InterfaceDeclaration;
|
|
17
25
|
type MovedSignature = PropertySignature | MethodSignature;
|
|
@@ -73,6 +81,24 @@ function movedSignatures(owner: MemberOwner): MovedSignature[] {
|
|
|
73
81
|
);
|
|
74
82
|
}
|
|
75
83
|
|
|
84
|
+
// A member that moves for one receiving kind but not (or elsewhere) for another cannot be rewritten
|
|
85
|
+
// for both; it is reported instead.
|
|
86
|
+
function pathAcrossKinds(
|
|
87
|
+
kinds: readonly ContextKind[],
|
|
88
|
+
memberName: string,
|
|
89
|
+
): { readonly path: NamespacePath | undefined; readonly agrees: boolean } {
|
|
90
|
+
const [first, ...rest] = kinds;
|
|
91
|
+
const path = first === undefined ? undefined : moveOf(first, memberName);
|
|
92
|
+
return { path, agrees: rest.every((kind) => samePath(moveOf(kind, memberName), path)) };
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function movedSignaturesFor(owner: MemberOwner, kinds: readonly ContextKind[]): MovedSignature[] {
|
|
96
|
+
return movedSignatures(owner).filter((member) => {
|
|
97
|
+
const { path, agrees } = pathAcrossKinds(kinds, member.getName());
|
|
98
|
+
return !agrees || path !== undefined;
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
|
|
76
102
|
function referenceTarget(parameter: ParameterDeclaration): Node | undefined {
|
|
77
103
|
const fn = parameter.getParent();
|
|
78
104
|
if (Node.isFunctionDeclaration(fn) || Node.isMethodDeclaration(fn)) return fn.getNameNode();
|
|
@@ -89,35 +115,41 @@ function callOf(reference: Node): CallExpression | undefined {
|
|
|
89
115
|
|
|
90
116
|
// Only a parameter a Kumiko context is passed to is a context; a ctx-named parameter of a foreign
|
|
91
117
|
// structural type (an MSP apply context) must stay as it is. A context handed on through another
|
|
92
|
-
// structural parameter counts too.
|
|
93
|
-
function
|
|
118
|
+
// structural parameter counts too. The kinds say which context shape the parameter really receives.
|
|
119
|
+
function receivingKinds(
|
|
94
120
|
counters: Counters,
|
|
95
121
|
parameter: ParameterDeclaration,
|
|
96
122
|
seen: Set<Node>,
|
|
97
|
-
):
|
|
98
|
-
|
|
123
|
+
): Set<ContextKind> {
|
|
124
|
+
const kinds = new Set<ContextKind>();
|
|
125
|
+
if (seen.has(parameter)) return kinds;
|
|
99
126
|
seen.add(parameter);
|
|
100
127
|
const target = referenceTarget(parameter);
|
|
101
|
-
if (target === undefined || !Node.isReferenceFindable(target)) return
|
|
128
|
+
if (target === undefined || !Node.isReferenceFindable(target)) return kinds;
|
|
102
129
|
const fn = parameter.getParent();
|
|
103
130
|
const index = Node.isParametered(fn) ? fn.getParameters().indexOf(parameter) : -1;
|
|
104
|
-
if (index < 0) return
|
|
105
|
-
|
|
131
|
+
if (index < 0) return kinds;
|
|
132
|
+
for (const reference of target.findReferencesAsNodes()) {
|
|
106
133
|
const argument = callOf(reference)?.getArguments()[index];
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
134
|
+
if (argument === undefined) continue;
|
|
135
|
+
const receiver = contextReceiver(counters, argument);
|
|
136
|
+
if (receiver.kind === "context") {
|
|
137
|
+
for (const kind of receiver.contexts) kinds.add(kind);
|
|
138
|
+
} else {
|
|
139
|
+
for (const kind of passedOnKinds(counters, argument, seen)) kinds.add(kind);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
return kinds;
|
|
113
143
|
}
|
|
114
144
|
|
|
115
|
-
function
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
145
|
+
function passedOnKinds(counters: Counters, argument: Node, seen: Set<Node>): Set<ContextKind> {
|
|
146
|
+
const kinds = new Set<ContextKind>();
|
|
147
|
+
if (!Node.isIdentifier(argument)) return kinds;
|
|
148
|
+
for (const declaration of argument.getSymbol()?.getDeclarations() ?? []) {
|
|
149
|
+
if (!Node.isParameterDeclaration(declaration)) continue;
|
|
150
|
+
for (const kind of receivingKinds(counters, declaration, seen)) kinds.add(kind);
|
|
151
|
+
}
|
|
152
|
+
return kinds;
|
|
121
153
|
}
|
|
122
154
|
|
|
123
155
|
function entryText(plan: EditPlan, member: MovedSignature, leaf: string): string {
|
|
@@ -142,6 +174,7 @@ function planNamespaceGroup(
|
|
|
142
174
|
owner: MemberOwner,
|
|
143
175
|
namespace: string,
|
|
144
176
|
members: readonly MovedSignature[],
|
|
177
|
+
kind: ContextKind,
|
|
145
178
|
): void {
|
|
146
179
|
const [first, ...rest] = members;
|
|
147
180
|
// skip: a group is never empty, this narrows the destructured head
|
|
@@ -152,7 +185,7 @@ function planNamespaceGroup(
|
|
|
152
185
|
return;
|
|
153
186
|
}
|
|
154
187
|
const entries = members.map((member) =>
|
|
155
|
-
entryText(plan, member, moveOf(
|
|
188
|
+
entryText(plan, member, moveOf(kind, member.getName())?.leaf ?? member.getName()),
|
|
156
189
|
);
|
|
157
190
|
const separator = /[;,]$/.exec(first.getText())?.[0] ?? "";
|
|
158
191
|
const modifier = members.every(isReadonlySignature) ? "readonly " : "";
|
|
@@ -161,22 +194,39 @@ function planNamespaceGroup(
|
|
|
161
194
|
plan.add({ start: member.getFullStart(), end: member.getEnd(), text: "" });
|
|
162
195
|
}
|
|
163
196
|
for (const member of members) {
|
|
164
|
-
const path = moveOf(
|
|
197
|
+
const path = moveOf(kind, member.getName());
|
|
165
198
|
if (path !== undefined) {
|
|
166
199
|
plan.recordRewrite(member, `${member.getName()} -> ${describePath(path)} (structural type)`);
|
|
167
200
|
}
|
|
168
201
|
}
|
|
169
202
|
}
|
|
170
203
|
|
|
171
|
-
function planOwner(
|
|
204
|
+
function planOwner(
|
|
205
|
+
plan: EditPlan,
|
|
206
|
+
counters: Counters,
|
|
207
|
+
owner: MemberOwner,
|
|
208
|
+
kinds: readonly ContextKind[],
|
|
209
|
+
): void {
|
|
210
|
+
const [kind] = kinds;
|
|
211
|
+
// skip: a receiving parameter always has at least one kind
|
|
212
|
+
if (kind === undefined) return;
|
|
172
213
|
const groups = new Map<string, MovedSignature[]>();
|
|
173
|
-
for (const member of
|
|
214
|
+
for (const member of movedSignaturesFor(owner, kinds)) {
|
|
174
215
|
if (counters.rewrittenMembers.has(member)) continue;
|
|
175
216
|
counters.rewrittenMembers.add(member);
|
|
176
|
-
|
|
217
|
+
if (!pathAcrossKinds(kinds, member.getName()).agrees) {
|
|
218
|
+
plan.flagManual(
|
|
219
|
+
member,
|
|
220
|
+
`${member.getName()}: moves differently for ${kinds.join(" and ")} contexts, which both reach this type`,
|
|
221
|
+
);
|
|
222
|
+
continue;
|
|
223
|
+
}
|
|
224
|
+
const namespace = moveOf(kind, member.getName())?.namespace ?? "";
|
|
177
225
|
groups.set(namespace, [...(groups.get(namespace) ?? []), member]);
|
|
178
226
|
}
|
|
179
|
-
for (const [namespace, members] of groups)
|
|
227
|
+
for (const [namespace, members] of groups) {
|
|
228
|
+
planNamespaceGroup(plan, owner, namespace, members, kind);
|
|
229
|
+
}
|
|
180
230
|
}
|
|
181
231
|
|
|
182
232
|
function foreignMovedNames(declarations: readonly Node[]): string[] {
|
|
@@ -191,15 +241,29 @@ function foreignMovedNames(declarations: readonly Node[]): string[] {
|
|
|
191
241
|
);
|
|
192
242
|
}
|
|
193
243
|
|
|
194
|
-
interface StructuralContextParameter {
|
|
244
|
+
export interface StructuralContextParameter {
|
|
195
245
|
readonly annotation: Node;
|
|
196
246
|
readonly collected: Collected;
|
|
197
247
|
readonly foreign: string[];
|
|
248
|
+
readonly kinds: readonly ContextKind[];
|
|
249
|
+
readonly conflicts: boolean;
|
|
198
250
|
}
|
|
199
251
|
|
|
200
252
|
function structuralContextParameter(
|
|
201
253
|
counters: Counters,
|
|
202
254
|
parameter: Node,
|
|
255
|
+
): StructuralContextParameter | undefined {
|
|
256
|
+
if (counters.structuralParameters.has(parameter)) {
|
|
257
|
+
return counters.structuralParameters.get(parameter);
|
|
258
|
+
}
|
|
259
|
+
const found = findStructuralContextParameter(counters, parameter);
|
|
260
|
+
counters.structuralParameters.set(parameter, found);
|
|
261
|
+
return found;
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
function findStructuralContextParameter(
|
|
265
|
+
counters: Counters,
|
|
266
|
+
parameter: Node,
|
|
203
267
|
): StructuralContextParameter | undefined {
|
|
204
268
|
if (!Node.isParameterDeclaration(parameter)) return undefined;
|
|
205
269
|
const annotation = parameter.getTypeNode();
|
|
@@ -211,17 +275,68 @@ function structuralContextParameter(
|
|
|
211
275
|
const collected: Collected = { owners: [], foreignDeclarations: [] };
|
|
212
276
|
collect(annotation, new Set(), collected);
|
|
213
277
|
const foreign = foreignMovedNames(collected.foreignDeclarations);
|
|
214
|
-
const
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
278
|
+
const kinds = [...receivingKinds(counters, parameter, new Set())];
|
|
279
|
+
const hasLocal = collected.owners.some((owner) => movedSignaturesFor(owner, kinds).length > 0);
|
|
280
|
+
if ((!hasLocal && foreign.length === 0) || kinds.length === 0) return undefined;
|
|
281
|
+
const conflicts = collected.owners.some((owner) =>
|
|
282
|
+
movedSignatures(owner).some((member) => !pathAcrossKinds(kinds, member.getName()).agrees),
|
|
283
|
+
);
|
|
284
|
+
return { annotation, collected, foreign, kinds, conflicts };
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
function isRewritableAlone(found: StructuralContextParameter | undefined): boolean {
|
|
288
|
+
return found !== undefined && found.foreign.length === 0 && !found.conflicts;
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
function typeDeclarationOf(owner: MemberOwner): Node | undefined {
|
|
292
|
+
return Node.isInterfaceDeclaration(owner)
|
|
293
|
+
? owner
|
|
294
|
+
: owner.getFirstAncestorByKind(SyntaxKind.TypeAliasDeclaration);
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
function isInsideTypeAnnotation(reference: Node, parameter: Node): boolean {
|
|
298
|
+
const annotation = Node.isParameterDeclaration(parameter) ? parameter.getTypeNode() : undefined;
|
|
299
|
+
return (
|
|
300
|
+
annotation !== undefined &&
|
|
301
|
+
reference.getStart() >= annotation.getStart() &&
|
|
302
|
+
reference.getEnd() <= annotation.getEnd()
|
|
303
|
+
);
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
// A shared alias or interface is rewritten for every user at once. A user the rewrite does not
|
|
307
|
+
// reach (another parameter name, a non-parameter reference, a mock typed by it) would keep the flat
|
|
308
|
+
// shape and stop type-checking, so the type is reported instead.
|
|
309
|
+
function isTypeSharedWithOthers(
|
|
310
|
+
counters: Counters,
|
|
311
|
+
parameter: Node,
|
|
312
|
+
found: StructuralContextParameter,
|
|
313
|
+
): boolean {
|
|
314
|
+
const cached = counters.typeSharedWithOthers.get(parameter);
|
|
315
|
+
if (cached !== undefined) return cached;
|
|
316
|
+
const shared = found.collected.owners.some((owner) => {
|
|
317
|
+
const declaration = typeDeclarationOf(owner);
|
|
318
|
+
if (declaration === undefined || !Node.isNamed(declaration)) return false;
|
|
319
|
+
return declaration
|
|
320
|
+
.getNameNode()
|
|
321
|
+
.findReferencesAsNodes()
|
|
322
|
+
.some((reference) => {
|
|
323
|
+
const user = reference.getFirstAncestorByKind(SyntaxKind.Parameter);
|
|
324
|
+
if (user === undefined || !isInsideTypeAnnotation(reference, user)) return true;
|
|
325
|
+
return user !== parameter && !isRewritableAlone(structuralContextParameter(counters, user));
|
|
326
|
+
});
|
|
327
|
+
});
|
|
328
|
+
counters.typeSharedWithOthers.set(parameter, shared);
|
|
329
|
+
return shared;
|
|
219
330
|
}
|
|
220
331
|
|
|
221
332
|
// The structural-params report would repeat what the rewrite of this parameter already fixes.
|
|
222
333
|
export function isRewrittenStructuralParameter(counters: Counters, parameter: Node): boolean {
|
|
223
334
|
const found = structuralContextParameter(counters, parameter);
|
|
224
|
-
return
|
|
335
|
+
return (
|
|
336
|
+
found !== undefined &&
|
|
337
|
+
isRewritableAlone(found) &&
|
|
338
|
+
!isTypeSharedWithOthers(counters, parameter, found)
|
|
339
|
+
);
|
|
225
340
|
}
|
|
226
341
|
|
|
227
342
|
// A hand-written structural type (alias, interface, intersection or inline literal) that declares
|
|
@@ -233,7 +348,7 @@ export function planStructuralContextParameter(
|
|
|
233
348
|
): boolean {
|
|
234
349
|
const found = structuralContextParameter(counters, parameter);
|
|
235
350
|
if (found === undefined) return false;
|
|
236
|
-
const { annotation, collected, foreign } = found;
|
|
351
|
+
const { annotation, collected, foreign, kinds, conflicts } = found;
|
|
237
352
|
if (foreign.length > 0) {
|
|
238
353
|
plan.flagManual(
|
|
239
354
|
annotation,
|
|
@@ -241,7 +356,17 @@ export function planStructuralContextParameter(
|
|
|
241
356
|
);
|
|
242
357
|
return false;
|
|
243
358
|
}
|
|
244
|
-
|
|
245
|
-
|
|
359
|
+
if (isTypeSharedWithOthers(counters, parameter, found)) {
|
|
360
|
+
plan.flagManual(
|
|
361
|
+
annotation,
|
|
362
|
+
"a structural context type is also used where the rewrite does not reach it (other parameter names, mocks or type references); move its flat members by hand",
|
|
363
|
+
);
|
|
364
|
+
return false;
|
|
365
|
+
}
|
|
366
|
+
for (const owner of collected.owners) planOwner(plan, counters, owner, kinds);
|
|
367
|
+
// A conflicting member stays flat and reported, so the body must not be rewritten either.
|
|
368
|
+
if (conflicts) return false;
|
|
369
|
+
const [kind] = kinds;
|
|
370
|
+
if (kind !== undefined) counters.pinnedParameters.set(parameter, kind);
|
|
246
371
|
return true;
|
|
247
372
|
}
|
|
@@ -48,14 +48,16 @@ function mirrorOptionalPeer(record: Record<string, unknown>): void {
|
|
|
48
48
|
}
|
|
49
49
|
}
|
|
50
50
|
|
|
51
|
+
function declaresInAnyBlock(record: Record<string, unknown>, packageName: string): boolean {
|
|
52
|
+
return DEPENDENCY_BLOCKS.some((name) => {
|
|
53
|
+
const block = record[name];
|
|
54
|
+
return isStringRecord(block) && packageName in block;
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
|
|
51
58
|
// Every block that declares framework needs the entry: a devDependencies-only add would leave
|
|
52
59
|
// the published package (peerDependencies) without it.
|
|
53
60
|
function addFeatureAstDependency(record: Record<string, unknown>): string[] {
|
|
54
|
-
const alreadyDeclared = DEPENDENCY_BLOCKS.some((name) => {
|
|
55
|
-
const block = record[name];
|
|
56
|
-
return isStringRecord(block) && NEW_PACKAGE in block;
|
|
57
|
-
});
|
|
58
|
-
if (alreadyDeclared) return [];
|
|
59
61
|
const touched: string[] = [];
|
|
60
62
|
for (const name of DEPENDENCY_BLOCKS) {
|
|
61
63
|
const block = record[name];
|
|
@@ -83,6 +85,10 @@ export function transformPackageJson(
|
|
|
83
85
|
}
|
|
84
86
|
if (typeof manifest !== "object" || manifest === null || Array.isArray(manifest)) return source;
|
|
85
87
|
const record: Record<string, unknown> = { ...manifest };
|
|
88
|
+
// Cheap manifest checks first: the source walk below parses every matching file.
|
|
89
|
+
if (declaresInAnyBlock(record, NEW_PACKAGE) || !declaresInAnyBlock(record, FRAMEWORK_PACKAGE)) {
|
|
90
|
+
return source;
|
|
91
|
+
}
|
|
86
92
|
if (!packageUsesFeatureAst(dirname(filePath), probe)) return source;
|
|
87
93
|
const touched = addFeatureAstDependency(record);
|
|
88
94
|
if (touched.length === 0) return source;
|
|
@@ -81,17 +81,78 @@ function namedSpecifiers(declaration: Declaration) {
|
|
|
81
81
|
const isMovedSpecifier = (specifier: { getName(): string }): boolean =>
|
|
82
82
|
MOVED_NAMES.has(specifier.getName());
|
|
83
83
|
|
|
84
|
+
function readsMovedMember(node: Node, namespace: string): boolean {
|
|
85
|
+
if (Node.isPropertyAccessExpression(node)) {
|
|
86
|
+
return node.getExpression().getText() === namespace && MOVED_NAMES.has(node.getName());
|
|
87
|
+
}
|
|
88
|
+
if (Node.isElementAccessExpression(node)) {
|
|
89
|
+
const key = node.getArgumentExpression();
|
|
90
|
+
return (
|
|
91
|
+
node.getExpression().getText() === namespace &&
|
|
92
|
+
key !== undefined &&
|
|
93
|
+
Node.isStringLiteral(key) &&
|
|
94
|
+
MOVED_NAMES.has(key.getLiteralValue())
|
|
95
|
+
);
|
|
96
|
+
}
|
|
97
|
+
if (Node.isVariableDeclaration(node)) {
|
|
98
|
+
const pattern = node.getNameNode();
|
|
99
|
+
return (
|
|
100
|
+
Node.isObjectBindingPattern(pattern) &&
|
|
101
|
+
node.getInitializer()?.getText() === namespace &&
|
|
102
|
+
pattern
|
|
103
|
+
.getElements()
|
|
104
|
+
.some((element) =>
|
|
105
|
+
MOVED_NAMES.has(element.getPropertyNameNode()?.getText() ?? element.getName()),
|
|
106
|
+
)
|
|
107
|
+
);
|
|
108
|
+
}
|
|
109
|
+
return false;
|
|
110
|
+
}
|
|
111
|
+
|
|
84
112
|
function readsMovedNamespaceMember(sourceFile: SourceFile, namespace: string): number | undefined {
|
|
85
|
-
|
|
113
|
+
return sourceFile
|
|
114
|
+
.getDescendants()
|
|
115
|
+
.find((node) => readsMovedMember(node, namespace))
|
|
116
|
+
?.getStartLineNumber();
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// Forms whose moved names cannot be rewritten mechanically: the old module is still read, so
|
|
120
|
+
// the run must not look finished.
|
|
121
|
+
function reportUnrewritableEngineUses(
|
|
122
|
+
sourceFile: SourceFile,
|
|
123
|
+
filePath: string,
|
|
124
|
+
result: SiteLists,
|
|
125
|
+
): void {
|
|
126
|
+
for (const declaration of sourceFile.getExportDeclarations()) {
|
|
127
|
+
const isBareReExportOfEngine =
|
|
128
|
+
declaration.getModuleSpecifierValue() === OLD_ENGINE_MODULE &&
|
|
129
|
+
!declaration.hasNamedExports() &&
|
|
130
|
+
declaration.getNamespaceExport() === undefined;
|
|
131
|
+
if (isBareReExportOfEngine) {
|
|
132
|
+
result.manual.push({
|
|
133
|
+
file: filePath,
|
|
134
|
+
line: declaration.getStartLineNumber(),
|
|
135
|
+
description: `export * from ${OLD_ENGINE_MODULE} no longer re-exports the moved names; re-export them from ${NEW_PACKAGE}`,
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
for (const literal of moduleSpecifierLiterals(sourceFile)) {
|
|
140
|
+
const isDeclarationSpecifier =
|
|
141
|
+
Node.isImportDeclaration(literal.getParent()) ||
|
|
142
|
+
Node.isExportDeclaration(literal.getParent());
|
|
86
143
|
if (
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
144
|
+
isDeclarationSpecifier ||
|
|
145
|
+
!Node.isStringLiteral(literal) ||
|
|
146
|
+
literal.getLiteralValue() !== OLD_ENGINE_MODULE
|
|
90
147
|
) {
|
|
91
|
-
|
|
148
|
+
continue;
|
|
92
149
|
}
|
|
150
|
+
result.manual.push({
|
|
151
|
+
file: filePath,
|
|
152
|
+
line: literal.getStartLineNumber(),
|
|
153
|
+
description: `dynamic import or import type of ${OLD_ENGINE_MODULE}: moved names must come from ${NEW_PACKAGE}`,
|
|
154
|
+
});
|
|
93
155
|
}
|
|
94
|
-
return undefined;
|
|
95
156
|
}
|
|
96
157
|
|
|
97
158
|
function splitDeclaration(sourceFile: SourceFile, declaration: Declaration): void {
|
|
@@ -190,6 +251,7 @@ function transformTypeScriptSource(source: string, filePath: string, result: Sit
|
|
|
190
251
|
for (const declaration of declarations.reverse()) {
|
|
191
252
|
rewriteDeclaration(sourceFile, declaration, filePath, result);
|
|
192
253
|
}
|
|
254
|
+
reportUnrewritableEngineUses(sourceFile, filePath, result);
|
|
193
255
|
rewriteCodemodSubpath(sourceFile, filePath, result);
|
|
194
256
|
return sourceFile.getFullText();
|
|
195
257
|
}
|
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
// The single-file guards moved to Biome (preset `@cosmicdrift/kumiko-framework/biome-rules`), so
|
|
3
|
+
// their `kumiko-lint-ignore <slug> <reason>` markers turn into `biome-ignore <rule>: <reason>`.
|
|
4
|
+
// Only slugs of deleted guards are touched; slugs of surviving guards (complexity-budget,
|
|
5
|
+
// cross-feature-import, ...) stay as they are. The comment form (`//`, `/* */`, `{/* */}`) and the
|
|
6
|
+
// reason are kept verbatim; a marker without a reason of at least three words is listed, never
|
|
7
|
+
// converted, because a reason is not invented here.
|
|
8
|
+
//
|
|
9
|
+
// Usage: bun scripts/codemod/lint-ignore-to-biome.ts <targetDir> [--check | --dry-run]
|
|
10
|
+
|
|
11
|
+
import { relative } from "node:path";
|
|
12
|
+
import preset from "@cosmicdrift/kumiko-framework/biome-rules" with { type: "json" };
|
|
13
|
+
import { ts } from "ts-morph";
|
|
14
|
+
import * as z from "zod";
|
|
15
|
+
import {
|
|
16
|
+
type CodemodCliConfig,
|
|
17
|
+
type CodemodResult,
|
|
18
|
+
type CodemodSite,
|
|
19
|
+
runCodemod,
|
|
20
|
+
} from "./codemod-support.ts";
|
|
21
|
+
|
|
22
|
+
const MIN_REASON_WORDS = 3;
|
|
23
|
+
|
|
24
|
+
const PLUGIN_RULE = "lint/plugin";
|
|
25
|
+
const INLINE_STYLES_RULE = "lint/style/noInlineStyles";
|
|
26
|
+
const PROCESS_ENV_RULE = "lint/style/noProcessEnv";
|
|
27
|
+
const RESTRICTED_IMPORTS_RULE = "lint/style/noRestrictedImports";
|
|
28
|
+
|
|
29
|
+
// Slugs of the guards deleted in the guards-to-biome move; each maps to the rule that replaces it.
|
|
30
|
+
const DELETED_GUARD_SLUG_RULES: ReadonlyMap<string, string> = new Map([
|
|
31
|
+
["admin-api", PLUGIN_RULE],
|
|
32
|
+
["direct-fetch", PLUGIN_RULE],
|
|
33
|
+
["direct-fs", PLUGIN_RULE],
|
|
34
|
+
["error-reasons", PLUGIN_RULE],
|
|
35
|
+
["es-literal-writes", PLUGIN_RULE],
|
|
36
|
+
["event-store-writes", PLUGIN_RULE],
|
|
37
|
+
["i18n-locale-terminology", PLUGIN_RULE],
|
|
38
|
+
["no-custom-primitives", PLUGIN_RULE],
|
|
39
|
+
["no-date-api", PLUGIN_RULE],
|
|
40
|
+
["no-direct-process-env", PROCESS_ENV_RULE],
|
|
41
|
+
["no-inline-styles", INLINE_STYLES_RULE],
|
|
42
|
+
["no-raw-hooks", PLUGIN_RULE],
|
|
43
|
+
["no-temporal-polyfill-import", RESTRICTED_IMPORTS_RULE],
|
|
44
|
+
["primitives-discipline", PLUGIN_RULE],
|
|
45
|
+
["raw-classname", PLUGIN_RULE],
|
|
46
|
+
["raw-interactive-elements", PLUGIN_RULE],
|
|
47
|
+
["restricted-symbols", PLUGIN_RULE],
|
|
48
|
+
["test-es-fixtures", PLUGIN_RULE],
|
|
49
|
+
["test-title", PLUGIN_RULE],
|
|
50
|
+
["unsafe-json-parse", PLUGIN_RULE],
|
|
51
|
+
]);
|
|
52
|
+
|
|
53
|
+
const presetPluginsSchema = z.object({
|
|
54
|
+
plugins: z.array(z.object({ path: z.string(), includes: z.array(z.string()).optional() })),
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
// Outside the plugin's includes a converted marker would be a `biome-ignore` that suppresses
|
|
58
|
+
// nothing, which Biome reports as unused. The includes come from the preset itself.
|
|
59
|
+
function noRawHooksIncludes(): { positive: Bun.Glob[]; negative: Bun.Glob[] } {
|
|
60
|
+
const plugin = presetPluginsSchema
|
|
61
|
+
.parse(preset)
|
|
62
|
+
.plugins.find((candidate) => candidate.path.endsWith("/no-raw-hooks.grit"));
|
|
63
|
+
const includes = plugin?.includes ?? [];
|
|
64
|
+
const toGlobs = (patterns: string[]): Bun.Glob[] =>
|
|
65
|
+
patterns.map((pattern) => new Bun.Glob(pattern));
|
|
66
|
+
return {
|
|
67
|
+
positive: toGlobs(includes.filter((pattern) => !pattern.startsWith("!"))),
|
|
68
|
+
negative: toGlobs(includes.filter((pattern) => pattern.startsWith("!")).map((p) => p.slice(1))),
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const NO_RAW_HOOKS_INCLUDES = noRawHooksIncludes();
|
|
73
|
+
|
|
74
|
+
function isPluginScopeOfSlug(slug: string, relativePath: string): boolean {
|
|
75
|
+
if (slug !== "no-raw-hooks") return true;
|
|
76
|
+
return (
|
|
77
|
+
NO_RAW_HOOKS_INCLUDES.positive.some((glob) => glob.match(relativePath)) &&
|
|
78
|
+
!NO_RAW_HOOKS_INCLUDES.negative.some((glob) => glob.match(relativePath))
|
|
79
|
+
);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
const MARKER_RE = /^\s*\**\s*kumiko-lint-ignore\s+([\w-]+(?:,[\w-]+)*)(?:\s+([\s\S]*))?$/;
|
|
83
|
+
|
|
84
|
+
type CommentRange = { readonly pos: number; readonly end: number; readonly line: number };
|
|
85
|
+
|
|
86
|
+
function scriptKindFor(file: string): ts.ScriptKind {
|
|
87
|
+
return file.endsWith(".tsx") ? ts.ScriptKind.TSX : ts.ScriptKind.TS;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** Real comments only: JSX text and string literals that merely look like comments are skipped. */
|
|
91
|
+
function collectComments(sourceFile: ts.SourceFile): CommentRange[] {
|
|
92
|
+
const text = sourceFile.text;
|
|
93
|
+
const seen = new Map<number, CommentRange>();
|
|
94
|
+
const addRanges = (ranges: readonly ts.CommentRange[] | undefined): void => {
|
|
95
|
+
for (const range of ranges ?? []) {
|
|
96
|
+
const line = sourceFile.getLineAndCharacterOfPosition(range.pos).line + 1;
|
|
97
|
+
seen.set(range.pos, { pos: range.pos, end: range.end, line });
|
|
98
|
+
}
|
|
99
|
+
};
|
|
100
|
+
const visit = (node: ts.Node): void => {
|
|
101
|
+
addRanges(ts.getLeadingCommentRanges(text, node.getFullStart()));
|
|
102
|
+
addRanges(ts.getTrailingCommentRanges(text, node.getEnd()));
|
|
103
|
+
for (const child of node.getChildren(sourceFile)) visit(child);
|
|
104
|
+
};
|
|
105
|
+
visit(sourceFile);
|
|
106
|
+
return [...seen.values()].sort((a, b) => a.pos - b.pos);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function reasonWordCount(reason: string): number {
|
|
110
|
+
return reason.split(/\s+/).filter((word) => word.length > 0).length;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
type Rewrite =
|
|
114
|
+
| { readonly kind: "converted"; readonly replacement: string }
|
|
115
|
+
| { readonly kind: "unconverted"; readonly note: string }
|
|
116
|
+
| { readonly kind: "untouched" };
|
|
117
|
+
|
|
118
|
+
function rewriteComment(commentText: string, relativePath: string): Rewrite {
|
|
119
|
+
const isBlock = commentText.startsWith("/*");
|
|
120
|
+
const body = isBlock ? commentText.slice(2, -2) : commentText.slice(2);
|
|
121
|
+
const match = MARKER_RE.exec(body);
|
|
122
|
+
if (!match) {
|
|
123
|
+
return /kumiko-lint-ignore\s+[\w-]/.test(body) && mentionsDeletedSlug(body)
|
|
124
|
+
? {
|
|
125
|
+
kind: "unconverted",
|
|
126
|
+
note: "marker does not start the comment, convert it by hand",
|
|
127
|
+
}
|
|
128
|
+
: { kind: "untouched" };
|
|
129
|
+
}
|
|
130
|
+
const slugs = (match[1] ?? "").split(",");
|
|
131
|
+
const deleted = slugs.filter(
|
|
132
|
+
(slug) => DELETED_GUARD_SLUG_RULES.has(slug) && isPluginScopeOfSlug(slug, relativePath),
|
|
133
|
+
);
|
|
134
|
+
if (deleted.length === 0) return { kind: "untouched" };
|
|
135
|
+
|
|
136
|
+
const rules = new Set(deleted.map((slug) => DELETED_GUARD_SLUG_RULES.get(slug)));
|
|
137
|
+
if (deleted.length !== slugs.length || rules.size !== 1) {
|
|
138
|
+
return {
|
|
139
|
+
kind: "unconverted",
|
|
140
|
+
note: `slug list "${slugs.join(",")}" mixes surviving guards or several Biome rules, split it by hand`,
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
const reason = (match[2] ?? "").replace(/\s+/g, " ").trim();
|
|
144
|
+
if (reasonWordCount(reason) < MIN_REASON_WORDS) {
|
|
145
|
+
return {
|
|
146
|
+
kind: "unconverted",
|
|
147
|
+
note: `reason "${reason}" has fewer than ${MIN_REASON_WORDS} words, add a real reason by hand`,
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
const [rule] = rules;
|
|
151
|
+
const suppression = `biome-ignore ${rule}: ${reason}`;
|
|
152
|
+
return {
|
|
153
|
+
kind: "converted",
|
|
154
|
+
replacement: isBlock ? `/* ${suppression} */` : `// ${suppression}`,
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function mentionsDeletedSlug(body: string): boolean {
|
|
159
|
+
return [...DELETED_GUARD_SLUG_RULES.keys()].some((slug) => body.includes(slug));
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// Biome does not honour a trailing suppression; only a lone `{` (JSX comment container) may precede.
|
|
163
|
+
function isTrailingComment(text: string, commentPos: number): boolean {
|
|
164
|
+
const lineStart = text.lastIndexOf("\n", commentPos - 1) + 1;
|
|
165
|
+
const before = text.slice(lineStart, commentPos).trim();
|
|
166
|
+
return before !== "" && before !== "{";
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
function migrateLintIgnoreMarkers(text: string, file: string, projectRoot: string): CodemodResult {
|
|
170
|
+
const relativePath = relative(projectRoot, file).split("\\").join("/");
|
|
171
|
+
const rewrites: CodemodSite[] = [];
|
|
172
|
+
const manual: CodemodSite[] = [];
|
|
173
|
+
if (!text.includes("kumiko-lint-ignore")) return { output: text, rewrites, manual };
|
|
174
|
+
const sourceFile = ts.createSourceFile(
|
|
175
|
+
file,
|
|
176
|
+
text,
|
|
177
|
+
ts.ScriptTarget.Latest,
|
|
178
|
+
true,
|
|
179
|
+
scriptKindFor(file),
|
|
180
|
+
);
|
|
181
|
+
let output = text;
|
|
182
|
+
for (const comment of collectComments(sourceFile).reverse()) {
|
|
183
|
+
const rewrite = rewriteComment(text.slice(comment.pos, comment.end), relativePath);
|
|
184
|
+
if (rewrite.kind === "untouched") continue;
|
|
185
|
+
if (rewrite.kind === "converted" && isTrailingComment(text, comment.pos)) {
|
|
186
|
+
manual.push({
|
|
187
|
+
file,
|
|
188
|
+
line: comment.line,
|
|
189
|
+
description: "trailing marker, move it above the hit as `// biome-ignore ...`",
|
|
190
|
+
});
|
|
191
|
+
continue;
|
|
192
|
+
}
|
|
193
|
+
if (rewrite.kind === "unconverted") {
|
|
194
|
+
manual.push({ file, line: comment.line, description: rewrite.note });
|
|
195
|
+
continue;
|
|
196
|
+
}
|
|
197
|
+
output = output.slice(0, comment.pos) + rewrite.replacement + output.slice(comment.end);
|
|
198
|
+
rewrites.push({ file, line: comment.line, description: rewrite.replacement });
|
|
199
|
+
}
|
|
200
|
+
return { output, rewrites: rewrites.reverse(), manual: manual.reverse() };
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
export const lintIgnoreToBiomeCodemod: CodemodCliConfig = {
|
|
204
|
+
name: "lint-ignore-to-biome",
|
|
205
|
+
transform: migrateLintIgnoreMarkers,
|
|
206
|
+
isSkippedPath: () => false,
|
|
207
|
+
extraExtensions: [".mts", ".cts"],
|
|
208
|
+
};
|
|
209
|
+
|
|
210
|
+
if (import.meta.main) {
|
|
211
|
+
const exitCode = await runCodemod(lintIgnoreToBiomeCodemod, process.argv.slice(2));
|
|
212
|
+
console.log(
|
|
213
|
+
"\nNote: each marker was converted where it stood. Biome applies a suppression only to the next line or node, " +
|
|
214
|
+
"while the old marker could sit several lines above its hit (and a trailing comment is not honoured at all). " +
|
|
215
|
+
"Run `biome lint` afterwards and move the remaining ones by hand.\n",
|
|
216
|
+
);
|
|
217
|
+
process.exit(exitCode);
|
|
218
|
+
}
|