@counterfact/generator 1.3.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.
Files changed (43) hide show
  1. package/CHANGELOG.md +39 -0
  2. package/dist/adopt-spellings.d.ts +15 -0
  3. package/dist/adopt-spellings.js +48 -0
  4. package/dist/case-safe-paths.d.ts +21 -0
  5. package/dist/case-safe-paths.js +57 -0
  6. package/dist/client-multipart-schema-type-coder.d.ts +16 -0
  7. package/dist/client-multipart-schema-type-coder.js +78 -0
  8. package/dist/client-response-schemas.d.ts +29 -0
  9. package/dist/client-response-schemas.js +120 -0
  10. package/dist/client-security.d.ts +10 -0
  11. package/dist/client-security.js +49 -0
  12. package/dist/code-generator.d.ts +9 -3
  13. package/dist/code-generator.js +28 -55
  14. package/dist/generate-client.d.ts +3 -0
  15. package/dist/generate-client.js +418 -0
  16. package/dist/generate-versioned-client.d.ts +12 -0
  17. package/dist/generate-versioned-client.js +103 -0
  18. package/dist/index.d.ts +1 -0
  19. package/dist/index.js +1 -0
  20. package/dist/migrate-route-layout.d.ts +8 -0
  21. package/dist/migrate-route-layout.js +448 -0
  22. package/dist/named-client-operations.d.ts +19 -0
  23. package/dist/named-client-operations.js +96 -0
  24. package/dist/operation-coder.js +1 -1
  25. package/dist/operation-type-coder.d.ts +6 -0
  26. package/dist/operation-type-coder.js +17 -5
  27. package/dist/path-operations.d.ts +2 -0
  28. package/dist/path-operations.js +31 -0
  29. package/dist/prune.d.ts +1 -1
  30. package/dist/prune.js +10 -3
  31. package/dist/repository.d.ts +15 -1
  32. package/dist/repository.js +184 -33
  33. package/dist/route-file-layout.d.ts +32 -0
  34. package/dist/route-file-layout.js +152 -0
  35. package/dist/scenario-file-generator.js +25 -5
  36. package/dist/script.d.ts +2 -0
  37. package/dist/script.js +16 -4
  38. package/dist/standalone-client-validators.d.ts +2 -0
  39. package/dist/standalone-client-validators.js +85 -0
  40. package/dist/swagger2-client.d.ts +31 -0
  41. package/dist/swagger2-client.js +92 -0
  42. package/package.json +4 -3
  43. package/src/README.md +2 -1
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 {};
@@ -0,0 +1,96 @@
1
+ import { RESERVED_WORDS } from "./reserved-words.js";
2
+ function words(value) {
3
+ return value
4
+ .replaceAll(/(?<lower>[a-z\d])(?<upper>[A-Z])/gu, "$<lower> $<upper>")
5
+ .split(/[^A-Za-z\d]+/u)
6
+ .filter(Boolean);
7
+ }
8
+ function capitalize(word) {
9
+ return word.charAt(0).toUpperCase() + word.slice(1);
10
+ }
11
+ function safeIdentifier(name, fallback) {
12
+ if (name === "")
13
+ return fallback;
14
+ if (/^\d/u.test(name))
15
+ return `_${name}`;
16
+ return RESERVED_WORDS.has(name) ? `${name}_` : name;
17
+ }
18
+ /** Converts arbitrary text such as `list_users` to `listUsers`. */
19
+ function camelCase(value, fallback = "_") {
20
+ const [first = "", ...rest] = words(value);
21
+ return safeIdentifier(first.charAt(0).toLowerCase() +
22
+ first.slice(1) +
23
+ rest.map(capitalize).join(""), fallback);
24
+ }
25
+ /** Converts arbitrary text such as `explodable-parameters` to `ExplodableParameters`. */
26
+ function pascalCase(value, fallback = "_") {
27
+ return safeIdentifier(words(value).map(capitalize).join(""), fallback);
28
+ }
29
+ /** Reserves `name`, appending a counter when it is already taken. */
30
+ function uniqueName(name, taken) {
31
+ let candidate = name;
32
+ for (let index = 2; taken.has(candidate.toLowerCase()); index += 1) {
33
+ candidate = `${name}${index}`;
34
+ }
35
+ taken.add(candidate.toLowerCase());
36
+ return candidate;
37
+ }
38
+ function isPathParameterSegment(segment) {
39
+ return /^\{[^}]+\}$/u.test(segment);
40
+ }
41
+ /**
42
+ * Names an operation that has no `operationId` from its path and method,
43
+ * for example `GET /pets` → `petsList` and `GET /pets/{id}` → `petsDetail`.
44
+ */
45
+ function fallbackOperationName(path, method) {
46
+ const segments = path.split("/").filter(Boolean);
47
+ const base = camelCase(segments.filter((segment) => !isPathParameterSegment(segment)).join(" "), "root");
48
+ const endsWithParameter = isPathParameterSegment(segments.at(-1) ?? "");
49
+ const suffixes = {
50
+ delete: "Delete",
51
+ get: endsWithParameter ? "Detail" : "List",
52
+ patch: "PartialUpdate",
53
+ post: "Create",
54
+ put: "Update",
55
+ };
56
+ // eslint-disable-next-line security/detect-object-injection -- method is an OpenAPI operation key; unknown methods fall back below.
57
+ return `${base}${suffixes[method] ?? pascalCase(method)}`;
58
+ }
59
+ function moduleNameFor(path, tags, options) {
60
+ const tag = tags[0];
61
+ if (options.moduleNameFirstTag && tag !== undefined) {
62
+ const name = pascalCase(tag, "");
63
+ if (name !== "")
64
+ return name;
65
+ }
66
+ const segment = path.split("/").filter(Boolean)[options.moduleNameIndex ?? 0];
67
+ return segment === undefined
68
+ ? "Root"
69
+ : pascalCase(segment.replaceAll(/[{}]/gu, ""), "Root");
70
+ }
71
+ export function namedOperations(paths, options) {
72
+ const groups = new Map();
73
+ for (const { path, operations } of paths) {
74
+ const pathParameters = Array.from(path.matchAll(/\{(?<name>[^}]+)\}/gu), (match) => match.groups["name"]);
75
+ for (const { method, operationId, tags } of operations) {
76
+ const name = camelCase(moduleNameFor(path, tags, options), "root");
77
+ const key = name.toLowerCase();
78
+ let group = groups.get(key);
79
+ if (!group) {
80
+ group = {
81
+ name,
82
+ used: new Set(["constructor", "http"]),
83
+ operations: new Map(),
84
+ };
85
+ groups.set(key, group);
86
+ }
87
+ const methodName = uniqueName((operationId && camelCase(operationId, "")) ||
88
+ fallbackOperationName(path, method), group.used);
89
+ group.operations.set(methodName, { path, method, pathParameters });
90
+ }
91
+ }
92
+ return Object.fromEntries(Array.from(groups.values(), ({ name, operations }) => [
93
+ name,
94
+ Object.fromEntries(operations),
95
+ ]));
96
+ }
@@ -79,7 +79,7 @@ export class OperationCoder extends Coder {
79
79
  // merged handler type after all versions have been declared.
80
80
  const versionedArgCoder = new VersionedArgTypeCoder(this.requirement, this.version, this.requestMethod, this.securitySchemes);
81
81
  const sharedScript = script.repository.get(operationTypeCoder.modulePath());
82
- sharedScript.declareVersion(versionedArgCoder, operationTypeCoder.getOperationBaseName());
82
+ sharedScript.declareVersion(versionedArgCoder, sharedScript.operationVersionKey(operationTypeCoder.getOperationBaseName(), operationTypeCoder.logicalRoute));
83
83
  }
84
84
  const path = this.requirement.parent?.url.split("/").at(-1) ??
85
85
  this.requirement.url.split("/").at(-2);
@@ -28,6 +28,12 @@ export declare class OperationTypeCoder extends TypeCoder {
28
28
  /** Returns the stable HTTP-method identifier, independent of operationId. */
29
29
  getOperationBaseName(): string;
30
30
  jsdoc(): string;
31
+ /**
32
+ * The OpenAPI path (e.g. `/Pet`). It tells apart case-variant paths that
33
+ * share a module, and stays the same across API versions, unlike the
34
+ * requirement URL, which includes the specification's location.
35
+ */
36
+ get logicalRoute(): string;
31
37
  get exportId(): string;
32
38
  names(): Generator<string>;
33
39
  /**
@@ -44,10 +44,20 @@ export class OperationTypeCoder extends TypeCoder {
44
44
  jsdoc() {
45
45
  return buildJsDoc(this.requirement.data);
46
46
  }
47
+ /**
48
+ * The OpenAPI path (e.g. `/Pet`). It tells apart case-variant paths that
49
+ * share a module, and stays the same across API versions, unlike the
50
+ * requirement URL, which includes the specification's location.
51
+ */
52
+ get logicalRoute() {
53
+ const pointer = this.requirement.parent?.url.split("/").at(-1) ??
54
+ this.requirement.url.split("/").at(-2);
55
+ return pointer.replaceAll("~1", "/").replaceAll("~0", "~");
56
+ }
47
57
  get exportId() {
48
58
  return this.version === ""
49
59
  ? this.id
50
- : `${this.constructor.name}@${this.modulePath()}:${this.requestMethod.toLowerCase()}`;
60
+ : `${this.constructor.name}@${this.logicalRoute}:${this.requestMethod.toLowerCase()}`;
51
61
  }
52
62
  names() {
53
63
  return super.names(this.getOperationBaseName());
@@ -274,8 +284,10 @@ export class OperationTypeCoder extends TypeCoder {
274
284
  // OpenAPI 3.2 querystring parameter: the entire query string treated as a
275
285
  // single typed object (similar to requestBody for query strings).
276
286
  const querystringParam = parameters?.find((parameter) => parameter.get("in")?.data === "querystring");
277
- const querystringType = querystringParam?.has("schema") === true
278
- ? new SchemaTypeCoder(querystringParam.get("schema"), this.version).write(script)
287
+ const [querystringMedia] = querystringParam?.get("content")?.map((media) => media) ?? [];
288
+ const querystringSchema = querystringMedia?.get("schema") ?? querystringParam?.get("schema");
289
+ const querystringType = querystringSchema
290
+ ? new SchemaTypeCoder(querystringSchema, this.version).write(script)
279
291
  : neverType();
280
292
  const querystringTypeName = this.exportParameterType(script, "querystring", querystringType, baseName, modulePath);
281
293
  const versionLiteralType = this.version !== "" ? literalType(this.version) : neverType();
@@ -303,7 +315,7 @@ export class OperationTypeCoder extends TypeCoder {
303
315
  const versioned = script.importVersionsType("Versioned");
304
316
  const promise = script.importSharedType("MaybePromise");
305
317
  const response = script.importSharedType("COUNTERFACT_RESPONSE");
306
- script.setVersionBuilder(this.getOperationBaseName(), (versions) => {
318
+ script.setVersionBuilder(script.operationVersionKey(this.getOperationBaseName(), this.logicalRoute), (versions) => {
307
319
  const mapName = `${name}_$_Versions`;
308
320
  return [
309
321
  typeAlias(mapName, typeLiteral([...versions].map(([version, type]) => typeProperty(version, type))), false),
@@ -381,7 +393,7 @@ export class VersionedArgTypeCoder extends OperationTypeCoder {
381
393
  return undefined;
382
394
  }
383
395
  write(script) {
384
- if (script.path === this.modulePath()) {
396
+ if (script === script.repository.get(this.modulePath())) {
385
397
  return this.writeCode(script);
386
398
  }
387
399
  return typeReference(script.importType(this));
@@ -0,0 +1,2 @@
1
+ import { Requirement } from "./requirement.js";
2
+ export declare function pathOperations(pathItem: Requirement): [Requirement, string][];