@counterfact/generator 1.2.0 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +55 -0
- package/dist/adopt-spellings.d.ts +15 -0
- package/dist/adopt-spellings.js +48 -0
- package/dist/case-safe-paths.d.ts +21 -0
- package/dist/case-safe-paths.js +57 -0
- package/dist/central-types.d.ts +2 -1
- package/dist/central-types.js +2 -2
- package/dist/client-multipart-schema-type-coder.d.ts +16 -0
- package/dist/client-multipart-schema-type-coder.js +78 -0
- package/dist/client-response-schemas.d.ts +29 -0
- package/dist/client-response-schemas.js +120 -0
- package/dist/client-security.d.ts +10 -0
- package/dist/client-security.js +49 -0
- package/dist/code-generator.d.ts +22 -4
- package/dist/code-generator.js +51 -57
- package/dist/generate-client.d.ts +3 -0
- package/dist/generate-client.js +418 -0
- package/dist/generate-versioned-client.d.ts +12 -0
- package/dist/generate-versioned-client.js +103 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/migrate-route-layout.d.ts +8 -0
- package/dist/migrate-route-layout.js +448 -0
- package/dist/named-client-operations.d.ts +19 -0
- package/dist/named-client-operations.js +96 -0
- package/dist/operation-coder.js +3 -3
- package/dist/operation-type-coder.d.ts +9 -3
- package/dist/operation-type-coder.js +43 -33
- package/dist/path-operations.d.ts +2 -0
- package/dist/path-operations.js +31 -0
- package/dist/prune.d.ts +1 -1
- package/dist/prune.js +10 -3
- package/dist/repository.d.ts +30 -1
- package/dist/repository.js +224 -34
- package/dist/requirement.js +3 -1
- package/dist/route-file-layout.d.ts +32 -0
- package/dist/route-file-layout.js +152 -0
- package/dist/scenario-file-generator.js +27 -7
- package/dist/script.d.ts +2 -0
- package/dist/script.js +16 -4
- package/dist/standalone-client-validators.d.ts +2 -0
- package/dist/standalone-client-validators.js +85 -0
- package/dist/swagger2-client.d.ts +31 -0
- package/dist/swagger2-client.js +92 -0
- package/examples/generate-routes.mjs +2 -0
- package/package.json +4 -3
- package/src/README.md +21 -20
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import ts from "typescript";
|
|
2
|
+
import { exportedConst, literalType, objectExpression, parameter, typeLiteral, typeProperty, typeReference, } from "./ast.js";
|
|
3
|
+
import { pathJoin, pathRelative } from "./forward-slash-path.js";
|
|
4
|
+
import { Repository } from "./repository.js";
|
|
5
|
+
function prefixedRouteSource(prefix, sdk, options) {
|
|
6
|
+
return objectExpression([
|
|
7
|
+
["prefix", ts.factory.createStringLiteral(prefix)],
|
|
8
|
+
[
|
|
9
|
+
"definition",
|
|
10
|
+
ts.factory.createPropertyAccessExpression(sdk, "routeDefinition"),
|
|
11
|
+
],
|
|
12
|
+
["options", options],
|
|
13
|
+
]);
|
|
14
|
+
}
|
|
15
|
+
function exportFactory(name, optionsType, factory, bindings) {
|
|
16
|
+
return exportedConst(name, ts.factory.createArrowFunction(undefined, undefined, [parameter("options", optionsType)], undefined, undefined, ts.factory.createCallExpression(ts.factory.createIdentifier(factory), undefined, [bindings])));
|
|
17
|
+
}
|
|
18
|
+
function versionedFactory(script, name, versions) {
|
|
19
|
+
const tsf = ts.factory;
|
|
20
|
+
const runtime = "@counterfact/client/fetch";
|
|
21
|
+
const fluent = name === "createClient";
|
|
22
|
+
const factoryName = script.importExternal(fluent ? "createPrefixedFetchRoute" : "versionedFetchClient", runtime);
|
|
23
|
+
const fetchOptions = script.importExternal("fetchOptionsForVersion", runtime);
|
|
24
|
+
const commonOptions = script.importExternalType("FetchClientOptions", runtime);
|
|
25
|
+
const options = tsf.createIdentifier("options");
|
|
26
|
+
const versionFactories = versions.map(({ version, prefix }) => {
|
|
27
|
+
const path = `./${pathJoin(version, "index.js")}`;
|
|
28
|
+
return {
|
|
29
|
+
version,
|
|
30
|
+
prefix,
|
|
31
|
+
factory: tsf.createIdentifier(script.importExternal(name, path, fluent)),
|
|
32
|
+
sdk: tsf.createIdentifier(script.importExternal("createSdk", path)),
|
|
33
|
+
};
|
|
34
|
+
});
|
|
35
|
+
const overrides = typeLiteral(versionFactories.map(({ version, factory }) => {
|
|
36
|
+
const factoryOptions = tsf.createIndexedAccessTypeNode(typeReference("Parameters", [tsf.createTypeQueryNode(factory)]), literalType(0));
|
|
37
|
+
return typeProperty(version, typeReference("Partial", [
|
|
38
|
+
typeReference("NonNullable", [factoryOptions]),
|
|
39
|
+
]), true);
|
|
40
|
+
}));
|
|
41
|
+
const optionsType = tsf.createIntersectionTypeNode([
|
|
42
|
+
typeReference("Omit", [typeReference(commonOptions), literalType("auth")]),
|
|
43
|
+
typeLiteral([typeProperty("versions", overrides, true)]),
|
|
44
|
+
]);
|
|
45
|
+
const entries = versionFactories.map(({ version, prefix, factory, sdk }) => {
|
|
46
|
+
const configuredOptions = tsf.createCallExpression(tsf.createIdentifier(fetchOptions), undefined, [
|
|
47
|
+
options,
|
|
48
|
+
tsf.createStringLiteral(fluent ? "" : prefix),
|
|
49
|
+
tsf.createElementAccessChain(tsf.createPropertyAccessExpression(options, "versions"), tsf.createToken(ts.SyntaxKind.QuestionDotToken), tsf.createStringLiteral(version)),
|
|
50
|
+
]);
|
|
51
|
+
return [
|
|
52
|
+
version,
|
|
53
|
+
fluent
|
|
54
|
+
? prefixedRouteSource(prefix, sdk, configuredOptions)
|
|
55
|
+
: tsf.createArrowFunction(undefined, undefined, [], undefined, undefined, tsf.createCallExpression(factory, undefined, [configuredOptions])),
|
|
56
|
+
];
|
|
57
|
+
});
|
|
58
|
+
const bindings = fluent
|
|
59
|
+
? tsf.createArrayLiteralExpression(entries.map(([, entry]) => entry), true)
|
|
60
|
+
: objectExpression(entries, true);
|
|
61
|
+
return exportFactory(name, optionsType, factoryName, bindings);
|
|
62
|
+
}
|
|
63
|
+
/** Write the group entry point after all version-specific clients are generated. */
|
|
64
|
+
export async function generateVersionedClient(destination, versions) {
|
|
65
|
+
if (versions.length === 0 || versions.some(({ version }) => version === "")) {
|
|
66
|
+
return [];
|
|
67
|
+
}
|
|
68
|
+
const repository = new Repository();
|
|
69
|
+
const script = repository.get("index.ts");
|
|
70
|
+
script.reservedNames.add("createClient");
|
|
71
|
+
script.reservedNames.add("createSdk");
|
|
72
|
+
script.comments.push("Generated by Counterfact. Do not edit.");
|
|
73
|
+
const statements = [
|
|
74
|
+
versionedFactory(script, "createClient", versions),
|
|
75
|
+
versionedFactory(script, "createSdk", versions),
|
|
76
|
+
];
|
|
77
|
+
script.statementBuilders.set("versioned-client", () => statements);
|
|
78
|
+
return repository.writeGeneratedScripts(destination, "");
|
|
79
|
+
}
|
|
80
|
+
/** Generate a fluent client across named APIs in configuration order. */
|
|
81
|
+
export async function generateConsolidatedClient(destination, sources, clientDirectory = "client") {
|
|
82
|
+
const root = pathJoin(destination, clientDirectory);
|
|
83
|
+
if (sources.length === 0 ||
|
|
84
|
+
sources.some(({ group }) => pathJoin(destination, group, clientDirectory) === root)) {
|
|
85
|
+
// The unnamed API already generates its entry point here.
|
|
86
|
+
return [];
|
|
87
|
+
}
|
|
88
|
+
const repository = new Repository();
|
|
89
|
+
const script = repository.get("index.ts");
|
|
90
|
+
script.comments.push("Generated by Counterfact. Do not edit.");
|
|
91
|
+
const runtime = "@counterfact/client/fetch";
|
|
92
|
+
const factory = script.importExternal("createPrefixedFetchRoute", runtime);
|
|
93
|
+
const options = script.importExternalType("FetchClientOptions", runtime);
|
|
94
|
+
const entries = sources.map(({ group, version, prefix }) => {
|
|
95
|
+
const file = pathRelative(root, pathJoin(destination, group, clientDirectory, version, "index.js"));
|
|
96
|
+
const module = file.startsWith("../") ? file : `./${file}`;
|
|
97
|
+
const sdk = script.importExternal("createSdk", module);
|
|
98
|
+
return prefixedRouteSource(prefix, ts.factory.createIdentifier(sdk), ts.factory.createIdentifier("options"));
|
|
99
|
+
});
|
|
100
|
+
const createClient = exportFactory("createClient", typeReference(options), factory, ts.factory.createArrayLiteralExpression(entries, true));
|
|
101
|
+
script.statementBuilders.set("consolidated-client", () => [createClient]);
|
|
102
|
+
return repository.writeGeneratedScripts(root, "");
|
|
103
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -2,4 +2,5 @@ export { CodeGenerator } from "./code-generator.js";
|
|
|
2
2
|
export { buildOperationTypeNameMapping, type OperationTypeNameMapping, } from "./operation-type-name-mapping.js";
|
|
3
3
|
export { Repository } from "./repository.js";
|
|
4
4
|
export { ScenarioFileGenerator } from "./scenario-file-generator.js";
|
|
5
|
+
export { generateConsolidatedClient, generateVersionedClient, type ClientVersion, } from "./generate-versioned-client.js";
|
|
5
6
|
export { generateVersionsTsContent } from "./versions-ts-generator.js";
|
package/dist/index.js
CHANGED
|
@@ -2,4 +2,5 @@ export { CodeGenerator } from "./code-generator.js";
|
|
|
2
2
|
export { buildOperationTypeNameMapping, } from "./operation-type-name-mapping.js";
|
|
3
3
|
export { Repository } from "./repository.js";
|
|
4
4
|
export { ScenarioFileGenerator } from "./scenario-file-generator.js";
|
|
5
|
+
export { generateConsolidatedClient, generateVersionedClient, } from "./generate-versioned-client.js";
|
|
5
6
|
export { generateVersionsTsContent } from "./versions-ts-generator.js";
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { Script } from "./script.js";
|
|
2
|
+
type Group = ReadonlyArray<readonly [string, Script]>;
|
|
3
|
+
export declare const ROUTE_MIGRATION_RECORD = ".counterfact-migrated-routes.json";
|
|
4
|
+
/** Keep an existing canonical wrapper stable across OpenAPI declaration reordering. */
|
|
5
|
+
export declare function managedRouteSpellings(destination: string, logicalFiles: Iterable<string>): Promise<string[]>;
|
|
6
|
+
/** Plan entirely in memory, then swap in a staged tree and retain the original. */
|
|
7
|
+
export declare function migrateLegacyRoutes(destination: string, groups: ReadonlyMap<string, Group>): Promise<void>;
|
|
8
|
+
export {};
|
|
@@ -0,0 +1,448 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import fs from "node:fs/promises";
|
|
3
|
+
import { METHODS } from "node:http";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import ts from "typescript";
|
|
6
|
+
/* eslint-disable security/detect-non-literal-fs-filename -- The migration enumerates and stages only validated paths inside the caller's routes tree. */
|
|
7
|
+
import { formatStatements } from "./ast.js";
|
|
8
|
+
import { CaseLayout, collisionRouteContents, missingRouteMapMethods, readRoutePaths, } from "./route-file-layout.js";
|
|
9
|
+
export const ROUTE_MIGRATION_RECORD = ".counterfact-migrated-routes.json";
|
|
10
|
+
const PRIVATE_PREFIX = "_.counterfact-legacy-";
|
|
11
|
+
const SOURCE = /\.[cm]?[jt]s$/u;
|
|
12
|
+
const httpMethods = new Set(METHODS);
|
|
13
|
+
const tsSource = (file) => ts.createSourceFile(file.name, file.bytes.toString("utf8"), ts.ScriptTarget.Latest, true);
|
|
14
|
+
const slash = (name) => name.split(path.sep).join("/");
|
|
15
|
+
async function inventory(root, relative = "", special = []) {
|
|
16
|
+
let names;
|
|
17
|
+
try {
|
|
18
|
+
names = await fs.readdir(path.join(root, relative));
|
|
19
|
+
}
|
|
20
|
+
catch (error) {
|
|
21
|
+
if (relative === "" && error.code === "ENOENT")
|
|
22
|
+
return [];
|
|
23
|
+
throw error;
|
|
24
|
+
}
|
|
25
|
+
const found = [];
|
|
26
|
+
for (const name of names.sort()) {
|
|
27
|
+
const key = path.posix.join(relative, name);
|
|
28
|
+
const full = path.join(root, key);
|
|
29
|
+
const stat = await fs.lstat(full);
|
|
30
|
+
if (stat.isDirectory())
|
|
31
|
+
found.push(...(await inventory(root, key, special)));
|
|
32
|
+
else if (stat.isFile())
|
|
33
|
+
found.push({
|
|
34
|
+
name: key,
|
|
35
|
+
bytes: await fs.readFile(full),
|
|
36
|
+
mode: stat.mode,
|
|
37
|
+
});
|
|
38
|
+
else
|
|
39
|
+
special.push(key);
|
|
40
|
+
}
|
|
41
|
+
return found;
|
|
42
|
+
}
|
|
43
|
+
function pathMatches(files, expected) {
|
|
44
|
+
return (JSON.stringify([...files].sort()) === JSON.stringify([...expected].sort()));
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Finds the route a legacy module was generated for. The generated `Route`
|
|
48
|
+
* type names it exactly; the file name can be spelled like a case variant,
|
|
49
|
+
* because a case-insensitive file system keeps the first spelling written.
|
|
50
|
+
*/
|
|
51
|
+
function originalPath(file, source, group) {
|
|
52
|
+
const routes = group.map(([route]) => route);
|
|
53
|
+
const typed = routeTypePath(source);
|
|
54
|
+
if (typed !== undefined && routes.includes(typed))
|
|
55
|
+
return typed;
|
|
56
|
+
const name = "/" + file.replace(SOURCE, "");
|
|
57
|
+
if (name === "/index") {
|
|
58
|
+
const root = routes.includes("/");
|
|
59
|
+
if (root && routes.includes("/index"))
|
|
60
|
+
throw new Error("Legacy routes/index.ts is ambiguous between / and /index");
|
|
61
|
+
return root ? "/" : name;
|
|
62
|
+
}
|
|
63
|
+
if (routes.includes(name))
|
|
64
|
+
return name;
|
|
65
|
+
const variants = routes.filter((route) => route.toLowerCase() === name.toLowerCase());
|
|
66
|
+
return variants.length === 1 ? variants[0] : name;
|
|
67
|
+
}
|
|
68
|
+
/** Reads the path from `type Route = Routes["/a"]["/{b}"]`. */
|
|
69
|
+
function routeTypePath(source) {
|
|
70
|
+
for (const statement of source.statements) {
|
|
71
|
+
if (!ts.isTypeAliasDeclaration(statement) ||
|
|
72
|
+
statement.name.text !== "Route")
|
|
73
|
+
continue;
|
|
74
|
+
const segments = [];
|
|
75
|
+
let type = statement.type;
|
|
76
|
+
while (ts.isIndexedAccessTypeNode(type)) {
|
|
77
|
+
const index = type.indexType;
|
|
78
|
+
if (!ts.isLiteralTypeNode(index) || !ts.isStringLiteral(index.literal))
|
|
79
|
+
return undefined;
|
|
80
|
+
segments.unshift(index.literal.text);
|
|
81
|
+
type = type.objectType;
|
|
82
|
+
}
|
|
83
|
+
if (!ts.isTypeReferenceNode(type) ||
|
|
84
|
+
!ts.isIdentifier(type.typeName) ||
|
|
85
|
+
type.typeName.text !== "Routes" ||
|
|
86
|
+
segments.length === 0)
|
|
87
|
+
return undefined;
|
|
88
|
+
return segments.join("") || "/";
|
|
89
|
+
}
|
|
90
|
+
return undefined;
|
|
91
|
+
}
|
|
92
|
+
/** Moves `file` to `target` (a `.ts` path) while keeping its own extension. */
|
|
93
|
+
function retarget(file, target) {
|
|
94
|
+
return target
|
|
95
|
+
.replace(/^routes\//u, "")
|
|
96
|
+
.replace(SOURCE, path.posix.extname(file));
|
|
97
|
+
}
|
|
98
|
+
function archive(file, destination) {
|
|
99
|
+
const hash = createHash("sha256")
|
|
100
|
+
.update(file.name)
|
|
101
|
+
.digest("hex")
|
|
102
|
+
.slice(0, 16);
|
|
103
|
+
return slash(path.posix.join(path.posix.dirname(destination), PRIVATE_PREFIX + hash + path.posix.extname(file.name)));
|
|
104
|
+
}
|
|
105
|
+
function modulePath(from, to, asset = false) {
|
|
106
|
+
const physical = path.posix.relative(path.posix.dirname(from), to);
|
|
107
|
+
const relative = asset ? physical : physical.replace(/\.ts$/u, ".js");
|
|
108
|
+
return relative.startsWith(".") ? relative : "./" + relative;
|
|
109
|
+
}
|
|
110
|
+
function preservedHandlers(file, group, imports, wrapper) {
|
|
111
|
+
if (!file.name.endsWith(".ts"))
|
|
112
|
+
throw new Error(`Move ${file.name} manually: automatic handler migration supports TypeScript route modules`);
|
|
113
|
+
const source = tsSource(file);
|
|
114
|
+
const declared = readRoutePaths(source);
|
|
115
|
+
const physical = originalPath(file.name, source, group);
|
|
116
|
+
const alias = `legacy${imports.size + 1}`;
|
|
117
|
+
imports.set(alias, modulePath(wrapper, archive(file, wrapper)));
|
|
118
|
+
const result = [];
|
|
119
|
+
function preserve(bindingName, pathName, keyed) {
|
|
120
|
+
const method = bindingName.toUpperCase();
|
|
121
|
+
if (result.some(([route, name]) => route === pathName && name === method))
|
|
122
|
+
throw new Error(`Move ambiguous authored handler ${method} ${pathName} from ${file.name} manually`);
|
|
123
|
+
if (!group.some(([route, script]) => route === pathName && script.exports.has(method))) {
|
|
124
|
+
throw new Error(`Move unmatched authored handler ${method} ${pathName} from ${file.name} manually`);
|
|
125
|
+
}
|
|
126
|
+
const binding = ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier(alias), bindingName);
|
|
127
|
+
result.push([
|
|
128
|
+
pathName,
|
|
129
|
+
method,
|
|
130
|
+
keyed
|
|
131
|
+
? ts.factory.createElementAccessExpression(binding, ts.factory.createStringLiteral(pathName))
|
|
132
|
+
: binding,
|
|
133
|
+
]);
|
|
134
|
+
}
|
|
135
|
+
for (const statement of source.statements) {
|
|
136
|
+
if (ts.isExportDeclaration(statement) && !statement.isTypeOnly) {
|
|
137
|
+
throw new Error(`Move re-exported handlers in ${file.name} manually`);
|
|
138
|
+
}
|
|
139
|
+
const modifiers = ts.canHaveModifiers(statement)
|
|
140
|
+
? ts.getModifiers(statement)
|
|
141
|
+
: undefined;
|
|
142
|
+
if (!modifiers?.some((mod) => mod.kind === ts.SyntaxKind.ExportKeyword) ||
|
|
143
|
+
modifiers.some((mod) => mod.kind === ts.SyntaxKind.DefaultKeyword))
|
|
144
|
+
continue;
|
|
145
|
+
if (ts.isFunctionDeclaration(statement) &&
|
|
146
|
+
statement.name &&
|
|
147
|
+
httpMethods.has(statement.name.text.toUpperCase())) {
|
|
148
|
+
const routeName = declared?.length === 1 ? declared[0] : physical;
|
|
149
|
+
if (declared && declared.length !== 1)
|
|
150
|
+
throw new Error(`Ambiguous handler in ${file.name}`);
|
|
151
|
+
preserve(statement.name.text, routeName, false);
|
|
152
|
+
}
|
|
153
|
+
if (!ts.isVariableStatement(statement))
|
|
154
|
+
continue;
|
|
155
|
+
for (const declaration of statement.declarationList.declarations) {
|
|
156
|
+
if (!ts.isIdentifier(declaration.name) ||
|
|
157
|
+
!httpMethods.has(declaration.name.text.toUpperCase()))
|
|
158
|
+
continue;
|
|
159
|
+
const initializer = declaration.initializer;
|
|
160
|
+
if (initializer && ts.isObjectLiteralExpression(initializer)) {
|
|
161
|
+
if (!declared || declared.length === 0)
|
|
162
|
+
throw new Error(`Add exact path metadata in ${file.name}`);
|
|
163
|
+
for (const property of initializer.properties) {
|
|
164
|
+
if ((!ts.isPropertyAssignment(property) &&
|
|
165
|
+
!ts.isMethodDeclaration(property)) ||
|
|
166
|
+
!ts.isStringLiteral(property.name) ||
|
|
167
|
+
!declared.includes(property.name.text))
|
|
168
|
+
throw new Error(`Move computed handler maps in ${file.name} manually`);
|
|
169
|
+
preserve(declaration.name.text, property.name.text, true);
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
else {
|
|
173
|
+
const routeName = declared?.length === 1 ? declared[0] : physical;
|
|
174
|
+
if (declared && declared.length !== 1)
|
|
175
|
+
throw new Error(`Ambiguous handler in ${file.name}`);
|
|
176
|
+
preserve(declaration.name.text, routeName, false);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
if (result.length === 0)
|
|
181
|
+
throw new Error(`No static HTTP handler exports found in ${file.name}`);
|
|
182
|
+
return result;
|
|
183
|
+
}
|
|
184
|
+
/** Rewrite only moved static relative references, preserving every other source byte. */
|
|
185
|
+
function relocate(file, target, outputs) {
|
|
186
|
+
if (!SOURCE.test(file.name))
|
|
187
|
+
return file.bytes;
|
|
188
|
+
const source = tsSource(file);
|
|
189
|
+
const edits = new Map();
|
|
190
|
+
const remap = (value, asset = false) => {
|
|
191
|
+
if (!value || !ts.isStringLiteralLike(value) || !value.text.startsWith("."))
|
|
192
|
+
return;
|
|
193
|
+
const oldPath = path.posix.normalize(path.posix.join(path.posix.dirname(file.name), value.text));
|
|
194
|
+
const withoutExtension = oldPath.replace(/\.[cm]?[jt]s$/u, "");
|
|
195
|
+
const candidates = [
|
|
196
|
+
oldPath,
|
|
197
|
+
withoutExtension + ".ts",
|
|
198
|
+
withoutExtension + ".mts",
|
|
199
|
+
withoutExtension + ".cts",
|
|
200
|
+
oldPath + ".ts",
|
|
201
|
+
oldPath + ".js",
|
|
202
|
+
path.posix.join(oldPath, "index.ts"),
|
|
203
|
+
];
|
|
204
|
+
const mapped = (asset ? [oldPath] : candidates)
|
|
205
|
+
.map((candidate) => outputs.get(candidate))
|
|
206
|
+
.find(Boolean);
|
|
207
|
+
if (!mapped)
|
|
208
|
+
return; // external to the route tree or unresolved in the original
|
|
209
|
+
const next = modulePath(target, mapped, asset);
|
|
210
|
+
if (next !== value.text)
|
|
211
|
+
edits.set(value.getStart(source), {
|
|
212
|
+
end: value.end,
|
|
213
|
+
value: JSON.stringify(next),
|
|
214
|
+
});
|
|
215
|
+
};
|
|
216
|
+
const visit = (node) => {
|
|
217
|
+
if (ts.isImportDeclaration(node) || ts.isExportDeclaration(node))
|
|
218
|
+
remap(node.moduleSpecifier);
|
|
219
|
+
if (ts.isCallExpression(node) &&
|
|
220
|
+
(node.expression.kind === ts.SyntaxKind.ImportKeyword ||
|
|
221
|
+
(ts.isIdentifier(node.expression) &&
|
|
222
|
+
node.expression.text === "require"))) {
|
|
223
|
+
const reference = node.arguments[0];
|
|
224
|
+
if (reference &&
|
|
225
|
+
!ts.isStringLiteralLike(reference) &&
|
|
226
|
+
target !== file.name)
|
|
227
|
+
throw new Error(`Move dynamic imports in ${file.name} manually before changing the route layout`);
|
|
228
|
+
remap(reference);
|
|
229
|
+
}
|
|
230
|
+
if (ts.isNewExpression(node) &&
|
|
231
|
+
ts.isIdentifier(node.expression) &&
|
|
232
|
+
node.expression.text === "URL")
|
|
233
|
+
remap(node.arguments?.[0], true);
|
|
234
|
+
ts.forEachChild(node, visit);
|
|
235
|
+
};
|
|
236
|
+
visit(source);
|
|
237
|
+
if (edits.size === 0)
|
|
238
|
+
return file.bytes;
|
|
239
|
+
let text = source.text;
|
|
240
|
+
for (const [start, edit] of [...edits].sort(([a], [b]) => b - a))
|
|
241
|
+
text = text.slice(0, start) + edit.value + text.slice(edit.end);
|
|
242
|
+
return Buffer.from(text);
|
|
243
|
+
}
|
|
244
|
+
async function middlewareWrapper(target, files) {
|
|
245
|
+
const entries = [];
|
|
246
|
+
const imports = [];
|
|
247
|
+
for (const file of files) {
|
|
248
|
+
if (!file.name.endsWith(".ts"))
|
|
249
|
+
throw new Error(`Move middleware ${file.name} manually before changing the route layout`);
|
|
250
|
+
const source = tsSource(file);
|
|
251
|
+
const declarations = source.statements.flatMap((statement) => ts.isVariableStatement(statement)
|
|
252
|
+
? [...statement.declarationList.declarations]
|
|
253
|
+
: []);
|
|
254
|
+
if (declarations.some((entry) => ts.isIdentifier(entry.name) &&
|
|
255
|
+
entry.name.text === "middleware" &&
|
|
256
|
+
entry.initializer &&
|
|
257
|
+
ts.isObjectLiteralExpression(entry.initializer)))
|
|
258
|
+
throw new Error(`Combine already case-keyed middleware in ${file.name} manually`);
|
|
259
|
+
const alias = `legacy${imports.length + 1}`;
|
|
260
|
+
imports.push(ts.factory.createImportDeclaration(undefined, ts.factory.createImportClause(false, undefined, ts.factory.createNamespaceImport(ts.factory.createIdentifier(alias))), ts.factory.createStringLiteral(modulePath(target, archive(file, target)))));
|
|
261
|
+
const directory = path.posix.dirname(file.name);
|
|
262
|
+
entries.push(ts.factory.createPropertyAssignment(ts.factory.createStringLiteral(directory === "." ? "/" : "/" + directory), ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier(alias), "middleware")));
|
|
263
|
+
}
|
|
264
|
+
return formatStatements([
|
|
265
|
+
...imports,
|
|
266
|
+
ts.factory.createVariableStatement([ts.factory.createModifier(ts.SyntaxKind.ExportKeyword)], ts.factory.createVariableDeclarationList([
|
|
267
|
+
ts.factory.createVariableDeclaration("middleware", undefined, undefined, ts.factory.createObjectLiteralExpression(entries, true)),
|
|
268
|
+
], ts.NodeFlags.Const)),
|
|
269
|
+
]);
|
|
270
|
+
}
|
|
271
|
+
/** Keep an existing canonical wrapper stable across OpenAPI declaration reordering. */
|
|
272
|
+
export async function managedRouteSpellings(destination, logicalFiles) {
|
|
273
|
+
const folded = new Set([...logicalFiles].map((file) => file.toLowerCase()));
|
|
274
|
+
const result = [];
|
|
275
|
+
const visit = async (dir) => {
|
|
276
|
+
let entries;
|
|
277
|
+
try {
|
|
278
|
+
entries = await fs.readdir(path.join(destination, dir), {
|
|
279
|
+
withFileTypes: true,
|
|
280
|
+
});
|
|
281
|
+
}
|
|
282
|
+
catch (error) {
|
|
283
|
+
if (error.code === "ENOENT")
|
|
284
|
+
return;
|
|
285
|
+
throw error;
|
|
286
|
+
}
|
|
287
|
+
for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
|
|
288
|
+
const name = dir + "/" + entry.name;
|
|
289
|
+
if (entry.isDirectory())
|
|
290
|
+
await visit(name);
|
|
291
|
+
else if (entry.isFile() && folded.has(name.toLowerCase())) {
|
|
292
|
+
const bytes = await fs.readFile(path.join(destination, name));
|
|
293
|
+
if (bytes.includes("__counterfactPaths") &&
|
|
294
|
+
readRoutePaths(tsSource({ name, bytes, mode: 0 }))?.length)
|
|
295
|
+
result.push(name);
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
};
|
|
299
|
+
await visit("routes");
|
|
300
|
+
return result;
|
|
301
|
+
}
|
|
302
|
+
/** Plan entirely in memory, then swap in a staged tree and retain the original. */
|
|
303
|
+
export async function migrateLegacyRoutes(destination, groups) {
|
|
304
|
+
const root = path.join(destination, "routes");
|
|
305
|
+
if (groups.size === 0)
|
|
306
|
+
return;
|
|
307
|
+
const special = [];
|
|
308
|
+
const files = await inventory(root, "", special);
|
|
309
|
+
if (files.length === 0)
|
|
310
|
+
return;
|
|
311
|
+
const caseFiles = new Map();
|
|
312
|
+
const groupTargets = new Map([...groups.keys()].map((name) => [name.toLowerCase(), name]));
|
|
313
|
+
for (const file of files) {
|
|
314
|
+
const key = "routes/" + file.name.replace(SOURCE, ".ts").toLowerCase();
|
|
315
|
+
const canonical = groupTargets.get(key);
|
|
316
|
+
if (!canonical)
|
|
317
|
+
continue;
|
|
318
|
+
const peers = caseFiles.get(canonical) ?? [];
|
|
319
|
+
peers.push(file);
|
|
320
|
+
caseFiles.set(canonical, peers);
|
|
321
|
+
}
|
|
322
|
+
const layout = new CaseLayout();
|
|
323
|
+
for (const target of groups.keys())
|
|
324
|
+
layout.file(target.slice("routes/".length));
|
|
325
|
+
const canonicalDirectory = (name) => {
|
|
326
|
+
const parent = path.posix.dirname(name);
|
|
327
|
+
return path.posix.join(parent === "." ? "" : layout.file(parent), path.posix.basename(name));
|
|
328
|
+
};
|
|
329
|
+
const outputs = new Map(files.map((file) => [file.name, canonicalDirectory(file.name)]));
|
|
330
|
+
const wrappers = new Map();
|
|
331
|
+
const migrateGroups = [...groups].filter(([target, group]) => {
|
|
332
|
+
const candidates = caseFiles.get(target) ?? [];
|
|
333
|
+
if (candidates.length === 0)
|
|
334
|
+
return false;
|
|
335
|
+
const candidate = candidates.find((file) => file.name.endsWith(".ts")) ?? candidates[0];
|
|
336
|
+
const source = tsSource(candidate);
|
|
337
|
+
const declared = readRoutePaths(source);
|
|
338
|
+
const expected = group.map(([route]) => route);
|
|
339
|
+
// A route without a collision keeps its module as-is. When the module is
|
|
340
|
+
// spelled differently (it sits in a directory a case variant created), it
|
|
341
|
+
// only moves to the chosen spelling.
|
|
342
|
+
if (!declared && group.length === 1 && candidates.length === 1) {
|
|
343
|
+
outputs.set(candidate.name, retarget(candidate.name, target));
|
|
344
|
+
return false;
|
|
345
|
+
}
|
|
346
|
+
// Files that differ only by extension (pet.js beside pet.ts) are not case
|
|
347
|
+
// variants and stay where they are.
|
|
348
|
+
if (candidates.some((file) => "routes/" + file.name.replace(SOURCE, ".ts") !== target))
|
|
349
|
+
return true;
|
|
350
|
+
if (!declared && group.length === 1)
|
|
351
|
+
return false;
|
|
352
|
+
return (!declared ||
|
|
353
|
+
!pathMatches(declared, expected) ||
|
|
354
|
+
(group.length > 1 && !missingRouteMapMethods(source, group)));
|
|
355
|
+
});
|
|
356
|
+
const shouldMoveDirectories = files.some((file) => outputs.get(file.name) !== file.name);
|
|
357
|
+
if (migrateGroups.length === 0 && !shouldMoveDirectories)
|
|
358
|
+
return;
|
|
359
|
+
if (special.length > 0) {
|
|
360
|
+
throw new Error(`Cannot migrate routes containing a symlink or special file: ${special.join(", ")}`);
|
|
361
|
+
}
|
|
362
|
+
for (const [target, group] of migrateGroups) {
|
|
363
|
+
const wrapper = target.slice("routes/".length);
|
|
364
|
+
const imported = new Map();
|
|
365
|
+
const handlers = new Map();
|
|
366
|
+
for (const file of caseFiles.get(target) ?? []) {
|
|
367
|
+
for (const [route, method, implementation] of preservedHandlers(file, group, imported, wrapper)) {
|
|
368
|
+
const key = JSON.stringify([route, method]);
|
|
369
|
+
if (handlers.has(key))
|
|
370
|
+
throw new Error(`Multiple authored handlers for ${method} ${route}`);
|
|
371
|
+
handlers.set(key, implementation);
|
|
372
|
+
}
|
|
373
|
+
outputs.set(file.name, archive(file, wrapper));
|
|
374
|
+
}
|
|
375
|
+
wrappers.set(wrapper, await collisionRouteContents(group, imported, handlers));
|
|
376
|
+
}
|
|
377
|
+
const middleware = new Map();
|
|
378
|
+
for (const file of files) {
|
|
379
|
+
if (!/^_\.middleware\.[cm]?[jt]s$/u.test(path.posix.basename(file.name)))
|
|
380
|
+
continue;
|
|
381
|
+
const target = canonicalDirectory(file.name).replace(SOURCE, ".ts");
|
|
382
|
+
const peers = middleware.get(target) ?? [];
|
|
383
|
+
peers.push(file);
|
|
384
|
+
middleware.set(target, peers);
|
|
385
|
+
}
|
|
386
|
+
for (const [target, candidates] of middleware) {
|
|
387
|
+
if (candidates.every((file) => file.name.replace(SOURCE, ".ts") === target))
|
|
388
|
+
continue;
|
|
389
|
+
if (candidates.length === 1) {
|
|
390
|
+
outputs.set(candidates[0].name, retarget(candidates[0].name, target));
|
|
391
|
+
continue;
|
|
392
|
+
}
|
|
393
|
+
for (const file of candidates)
|
|
394
|
+
outputs.set(file.name, archive(file, target));
|
|
395
|
+
wrappers.set(target, await middlewareWrapper(target, candidates));
|
|
396
|
+
}
|
|
397
|
+
const taken = new Set([...wrappers.keys()].map((name) => name.toLowerCase()));
|
|
398
|
+
const staged = files.map((file) => {
|
|
399
|
+
const target = outputs.get(file.name);
|
|
400
|
+
const key = target.toLowerCase();
|
|
401
|
+
if (taken.has(key))
|
|
402
|
+
throw new Error(`Route layout migration would overwrite ${target}; resolve aliases manually`);
|
|
403
|
+
taken.add(key);
|
|
404
|
+
return { ...file, name: target, bytes: relocate(file, target, outputs) };
|
|
405
|
+
});
|
|
406
|
+
const stage = await fs.mkdtemp(path.join(destination, ".counterfact-route-migration-"));
|
|
407
|
+
const backup = stage + "-original";
|
|
408
|
+
try {
|
|
409
|
+
for (const [name, content] of wrappers) {
|
|
410
|
+
const full = path.join(stage, name);
|
|
411
|
+
await fs.mkdir(path.dirname(full), { recursive: true });
|
|
412
|
+
await fs.writeFile(full, content, { flag: "wx" });
|
|
413
|
+
}
|
|
414
|
+
for (const file of staged) {
|
|
415
|
+
const full = path.join(stage, file.name);
|
|
416
|
+
await fs.mkdir(path.dirname(full), { recursive: true });
|
|
417
|
+
await fs.writeFile(full, file.bytes, { mode: file.mode, flag: "wx" });
|
|
418
|
+
}
|
|
419
|
+
await fs.writeFile(path.join(stage, ROUTE_MIGRATION_RECORD), JSON.stringify({
|
|
420
|
+
backup: path.basename(backup),
|
|
421
|
+
message: "Retain authored dependencies until the migrated tree has been reviewed.",
|
|
422
|
+
}) + "\n");
|
|
423
|
+
const latestSpecial = [];
|
|
424
|
+
const latest = await inventory(root, "", latestSpecial);
|
|
425
|
+
const prior = new Map(files.map((file) => [file.name, file.bytes]));
|
|
426
|
+
if (latestSpecial.length > 0 ||
|
|
427
|
+
latest.length !== files.length ||
|
|
428
|
+
latest.some((file) => !prior.get(file.name)?.equals(file.bytes)))
|
|
429
|
+
throw new Error("Route files changed concurrently; migration stopped without replacing the original tree");
|
|
430
|
+
await fs.rename(root, backup);
|
|
431
|
+
try {
|
|
432
|
+
await fs.rename(stage, root);
|
|
433
|
+
}
|
|
434
|
+
catch (error) {
|
|
435
|
+
try {
|
|
436
|
+
await fs.rename(backup, root);
|
|
437
|
+
}
|
|
438
|
+
catch (rollbackError) {
|
|
439
|
+
throw new AggregateError([error, rollbackError], `Could not install or restore the migrated routes. Original files remain in ${backup}.`, { cause: rollbackError });
|
|
440
|
+
}
|
|
441
|
+
throw error;
|
|
442
|
+
}
|
|
443
|
+
process.stdout.write(`Migrated route layout. Original route files are backed up in ${backup}.\n`);
|
|
444
|
+
}
|
|
445
|
+
finally {
|
|
446
|
+
await fs.rm(stage, { recursive: true, force: true });
|
|
447
|
+
}
|
|
448
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
export interface ClientGroupingOptions {
|
|
2
|
+
moduleNameFirstTag?: boolean | undefined;
|
|
3
|
+
moduleNameIndex?: number | undefined;
|
|
4
|
+
}
|
|
5
|
+
interface NamedOperation {
|
|
6
|
+
path: string;
|
|
7
|
+
method: string;
|
|
8
|
+
pathParameters: string[];
|
|
9
|
+
}
|
|
10
|
+
type ClientPaths = readonly {
|
|
11
|
+
path: string;
|
|
12
|
+
operations: readonly {
|
|
13
|
+
method: string;
|
|
14
|
+
operationId: string | undefined;
|
|
15
|
+
tags: string[];
|
|
16
|
+
}[];
|
|
17
|
+
}[];
|
|
18
|
+
export declare function namedOperations(paths: ClientPaths, options: ClientGroupingOptions): Record<string, Record<string, NamedOperation>>;
|
|
19
|
+
export {};
|