@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.
Files changed (47) hide show
  1. package/CHANGELOG.md +55 -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/central-types.d.ts +2 -1
  7. package/dist/central-types.js +2 -2
  8. package/dist/client-multipart-schema-type-coder.d.ts +16 -0
  9. package/dist/client-multipart-schema-type-coder.js +78 -0
  10. package/dist/client-response-schemas.d.ts +29 -0
  11. package/dist/client-response-schemas.js +120 -0
  12. package/dist/client-security.d.ts +10 -0
  13. package/dist/client-security.js +49 -0
  14. package/dist/code-generator.d.ts +22 -4
  15. package/dist/code-generator.js +51 -57
  16. package/dist/generate-client.d.ts +3 -0
  17. package/dist/generate-client.js +418 -0
  18. package/dist/generate-versioned-client.d.ts +12 -0
  19. package/dist/generate-versioned-client.js +103 -0
  20. package/dist/index.d.ts +1 -0
  21. package/dist/index.js +1 -0
  22. package/dist/migrate-route-layout.d.ts +8 -0
  23. package/dist/migrate-route-layout.js +448 -0
  24. package/dist/named-client-operations.d.ts +19 -0
  25. package/dist/named-client-operations.js +96 -0
  26. package/dist/operation-coder.js +3 -3
  27. package/dist/operation-type-coder.d.ts +9 -3
  28. package/dist/operation-type-coder.js +43 -33
  29. package/dist/path-operations.d.ts +2 -0
  30. package/dist/path-operations.js +31 -0
  31. package/dist/prune.d.ts +1 -1
  32. package/dist/prune.js +10 -3
  33. package/dist/repository.d.ts +30 -1
  34. package/dist/repository.js +224 -34
  35. package/dist/requirement.js +3 -1
  36. package/dist/route-file-layout.d.ts +32 -0
  37. package/dist/route-file-layout.js +152 -0
  38. package/dist/scenario-file-generator.js +27 -7
  39. package/dist/script.d.ts +2 -0
  40. package/dist/script.js +16 -4
  41. package/dist/standalone-client-validators.d.ts +2 -0
  42. package/dist/standalone-client-validators.js +85 -0
  43. package/dist/swagger2-client.d.ts +31 -0
  44. package/dist/swagger2-client.js +92 -0
  45. package/examples/generate-routes.mjs +2 -0
  46. package/package.json +4 -3
  47. package/src/README.md +21 -20
@@ -6,10 +6,14 @@ import { fileURLToPath } from "node:url";
6
6
  import createDebug from "debug";
7
7
  import ts from "typescript";
8
8
  import { formatStatements, importDeclaration, parameter, stringType, typeAlias, typeReference, withJsDoc, withComment, } from "./ast.js";
9
+ import { adoptSpellings } from "./adopt-spellings.js";
9
10
  import { ensureDirectoryExists } from "./ensure-directory-exists.js";
10
- import { toForwardSlashPath, pathRelative, pathDirname, } from "./forward-slash-path.js";
11
+ import { toForwardSlashPath, pathJoin, pathRelative, pathDirname, } from "./forward-slash-path.js";
11
12
  import { writeHelperTypes } from "./scenario-file-generator.js";
12
13
  import { Script } from "./script.js";
14
+ import { collisionMethodContents, collisionRouteContents, CaseLayout, matchesRouteMapShape, missingRouteMapMethods, readRoutePaths, } from "./route-file-layout.js";
15
+ import { pruneRoutes, pruneTypes } from "./prune.js";
16
+ import { managedRouteSpellings, migrateLegacyRoutes, ROUTE_MIGRATION_RECORD, } from "./migrate-route-layout.js";
13
17
  import { escapePathForWindows } from "./windows-escape.js";
14
18
  const debug = createDebug("counterfact:server:repository");
15
19
  const __dirname = toForwardSlashPath(dirname(fileURLToPath(import.meta.url)));
@@ -48,6 +52,33 @@ function resolveDestinationPath(destination, path) {
48
52
  */
49
53
  export class Repository {
50
54
  scripts;
55
+ routesByPath = new Map();
56
+ specRouteFiles = new Set();
57
+ typeLayout = new CaseLayout();
58
+ // Type scripts are found by case-folded path, because the spelling chosen
59
+ // for a type file can change until every type has been registered.
60
+ typeScripts = new Map();
61
+ routeLayout = new CaseLayout();
62
+ recordRouteFile(logicalFile) {
63
+ this.specRouteFiles.add(logicalFile);
64
+ }
65
+ route(logicalFile, path) {
66
+ const existing = this.routesByPath.get(path);
67
+ if (existing)
68
+ return existing;
69
+ // The root and literal /index share the historic filename, but their
70
+ // logical modules must remain distinct until the physical layout is built.
71
+ const script = [...this.routesByPath.values()].some((entry) => entry.path === logicalFile)
72
+ ? new Script(this, logicalFile)
73
+ : this.get(logicalFile);
74
+ this.routesByPath.set(path, script);
75
+ return script;
76
+ }
77
+ outputPath(logical) {
78
+ return logical.startsWith("types/")
79
+ ? this.typeLayout.file(logical)
80
+ : logical;
81
+ }
51
82
  constructor() {
52
83
  this.scripts = new Map();
53
84
  }
@@ -60,20 +91,31 @@ export class Repository {
60
91
  get(path) {
61
92
  debug("getting script at %s", path);
62
93
  assertSafeRepositoryPath(path);
63
- if (this.scripts.has(path)) {
94
+ const typeKey = path.startsWith("types/") ? path.toLowerCase() : undefined;
95
+ const existing = typeKey === undefined
96
+ ? this.scripts.get(path)
97
+ : this.typeScripts.get(typeKey);
98
+ path = this.outputPath(path);
99
+ if (existing) {
64
100
  debug("already have script %s, returning it", path);
65
- return this.scripts.get(path);
101
+ return existing;
66
102
  }
67
103
  debug("don't have %s, creating it", path);
68
104
  const script = new Script(this, path);
69
105
  this.scripts.set(path, script);
106
+ if (typeKey !== undefined)
107
+ this.typeScripts.set(typeKey, script);
70
108
  return script;
71
109
  }
72
110
  /** Waits until all scripts have resolved all of their pending export promises. */
73
111
  async finished() {
74
- while (Array.from(this.scripts.values()).some((script) => script.isInProgress())) {
112
+ while ([
113
+ ...new Set([...this.scripts.values(), ...this.routesByPath.values()]),
114
+ ].some((script) => script.isInProgress())) {
75
115
  debug("waiting for %i scripts to finish", this.scripts.size);
76
- await Promise.all(Array.from(this.scripts.values(), (script) => script.finished()));
116
+ await Promise.all([
117
+ ...new Set([...this.scripts.values(), ...this.routesByPath.values()]),
118
+ ].map((script) => script.finished()));
77
119
  }
78
120
  }
79
121
  /**
@@ -109,34 +151,94 @@ export class Repository {
109
151
  * @param destination - Absolute path to the output root directory.
110
152
  * @param options - Controls which artefacts are written.
111
153
  */
112
- async writeFiles(destination, { routes, types }) {
154
+ async writeFiles(destination, { routes, types, prune, keepVersionsFile }) {
113
155
  debug("waiting for %i or more scripts to finish before writing files", this.scripts.size);
114
156
  await this.finished();
115
157
  debug("all %i scripts are finished", this.scripts.size);
116
- const writeFiles = Array.from(this.scripts.entries(), async ([path, script]) => {
117
- const fullPath = resolveDestinationPath(destination, path);
118
- const contents = await script.contents(this.findContextPath(destination, path, script.contextRoutePath));
119
- await ensureDirectoryExists(fullPath);
120
- const shouldWriteRoutes = routes && path.startsWith("routes");
121
- const shouldWriteTypes = types && !path.startsWith("routes");
122
- if (shouldWriteRoutes) {
123
- const fileExists = await fs
124
- .stat(fullPath)
125
- .then((stat) => stat.isFile())
126
- .catch(() => false);
127
- if (fileExists) {
128
- debug(`route file exists, checking for new handlers: ${fullPath}`);
129
- await this.appendNewHandlers(fullPath, script);
158
+ const layout = new CaseLayout();
159
+ this.routeLayout = layout;
160
+ if (routes) {
161
+ for (const managed of await managedRouteSpellings(destination, this.specRouteFiles))
162
+ layout.pin(managed);
163
+ }
164
+ for (const script of this.routesByPath.values())
165
+ layout.file(script.path);
166
+ for (const path of this.specRouteFiles)
167
+ layout.file(path);
168
+ const routeGroups = new Map();
169
+ for (const [path, script] of [...this.routesByPath].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)) {
170
+ const target = layout.file(script.path);
171
+ const group = routeGroups.get(target) ?? [];
172
+ group.push([path, script]);
173
+ routeGroups.set(target, group);
174
+ }
175
+ if (routes) {
176
+ await migrateLegacyRoutes(destination, routeGroups);
177
+ await this.assertSafeRouteLayout(destination, routeGroups);
178
+ }
179
+ if (types)
180
+ await adoptSpellings(destination, Array.from(this.scripts.keys())
181
+ .filter((path) => path.startsWith("types/"))
182
+ .map((path) => this.outputPath(path)));
183
+ await Promise.all([
184
+ ...Array.from(this.scripts, async ([logical, script]) => {
185
+ const routeScript = logical.startsWith("routes/");
186
+ if ((routeScript && (!routes || routeGroups.has(layout.file(logical)))) ||
187
+ (!routeScript && !types))
130
188
  return;
189
+ const output = this.outputPath(logical);
190
+ const fullPath = resolveDestinationPath(destination, output);
191
+ const contents = await script.contents(this.findContextPath(destination, output, script.contextRoutePath));
192
+ await ensureDirectoryExists(fullPath);
193
+ if (routeScript && existsSync(fullPath)) {
194
+ await this.appendNewHandlers(fullPath, script);
131
195
  }
132
- }
133
- if (shouldWriteRoutes || shouldWriteTypes) {
134
- debug("about to write", fullPath);
135
- await fs.writeFile(fullPath, contents);
136
- debug("did write", fullPath);
137
- }
138
- });
139
- await Promise.all(writeFiles);
196
+ else {
197
+ await fs.writeFile(fullPath, contents);
198
+ }
199
+ }),
200
+ ...(routes
201
+ ? Array.from(routeGroups, async ([target, group]) => {
202
+ const fullPath = resolveDestinationPath(destination, target);
203
+ const first = group[0];
204
+ const [, script] = first;
205
+ // Colliding files are shape-checked and never rewritten; methods the
206
+ // file lacks are appended. A singleton can continue using the
207
+ // existing AST-based method append pipeline.
208
+ if (existsSync(fullPath)) {
209
+ if (group.length === 1) {
210
+ await this.appendNewHandlers(fullPath, script);
211
+ return;
212
+ }
213
+ const existing = await fs.readFile(fullPath, "utf8");
214
+ const missing = missingRouteMapMethods(ts.createSourceFile(fullPath, existing, ts.ScriptTarget.Latest, true), group);
215
+ if (missing && missing.length > 0)
216
+ await fs.writeFile(fullPath, `${existing.trimEnd()}\n${await collisionMethodContents(group, new Set(missing))}`);
217
+ return;
218
+ }
219
+ await ensureDirectoryExists(fullPath);
220
+ if (group.length > 1) {
221
+ await fs.writeFile(fullPath, await collisionRouteContents(group));
222
+ return;
223
+ }
224
+ const contents = await script.contents(this.findContextPath(destination, target, script.contextRoutePath));
225
+ // Only routes that share a file declare their paths. Every other
226
+ // route keeps the historic layout and case-insensitive matching.
227
+ await fs.writeFile(fullPath, contents);
228
+ })
229
+ : []),
230
+ ]);
231
+ if (prune &&
232
+ routes &&
233
+ !existsSync(nodePath.join(destination, "routes", ROUTE_MIGRATION_RECORD))) {
234
+ await pruneRoutes(destination, this.routesByPath.keys(), [...this.specRouteFiles].map((path) => layout.file(path)));
235
+ }
236
+ if (prune && types) {
237
+ await pruneTypes(destination, [
238
+ ...Array.from(this.scripts.keys(), (path) => this.outputPath(path)),
239
+ ...(keepVersionsFile ? ["types/versions.ts"] : []),
240
+ ]);
241
+ }
140
242
  await this.copyCoreFiles(destination);
141
243
  if (routes) {
142
244
  await this.createDefaultContextFile(destination);
@@ -144,6 +246,94 @@ export class Repository {
144
246
  if (types)
145
247
  await writeHelperTypes(destination, destination, true);
146
248
  }
249
+ async assertSafeRouteLayout(destination, groups) {
250
+ for (const [target, group] of groups) {
251
+ const paths = group.map(([path]) => path).sort();
252
+ const fail = (reason) => {
253
+ throw new Error(`Cannot generate ${target} for ${paths.join(", ")}: ${reason}. ` +
254
+ "Move or combine the existing handlers into the canonical file and " +
255
+ "declare __counterfactPaths and case-keyed method exports where required. " +
256
+ "Existing route files were left unchanged.");
257
+ };
258
+ const fullPath = resolveDestinationPath(destination, target);
259
+ if (!existsSync(fullPath))
260
+ continue;
261
+ const existing = await fs.readFile(fullPath, "utf8");
262
+ const source = ts.createSourceFile(fullPath, existing, ts.ScriptTarget.Latest, true);
263
+ const declared = readRoutePaths(source);
264
+ const needsMetadata = group.length > 1;
265
+ if (declared === undefined && !needsMetadata)
266
+ continue;
267
+ if (JSON.stringify(declared?.sort()) !== JSON.stringify(paths))
268
+ fail("existing route path metadata does not match");
269
+ if (group.length > 1 && !missingRouteMapMethods(source, group))
270
+ fail("existing handler map does not match the OpenAPI methods and paths");
271
+ if (group.length === 1 && matchesRouteMapShape(source, group))
272
+ fail("existing handler map must be converted back to functions");
273
+ }
274
+ }
275
+ /**
276
+ * Waits for all scripts to finish, then writes only the schemas for
277
+ * `version` directly under `destination`, without the
278
+ * `types/<version>/components/schemas/` prefix. Versioned schemas are written
279
+ * to `<destination>/<version>/`.
280
+ *
281
+ * Every other script in the repository is left unwritten. Fails, naming the
282
+ * schema, when a schema imports anything that would not be written, because
283
+ * the flattened file would then contain a broken import.
284
+ *
285
+ * @param destination - Absolute path to the output directory.
286
+ * @param version - Version label of the schemas to write (`""` when unversioned).
287
+ * @returns The output paths written, relative to `destination`.
288
+ */
289
+ async writeSchemas(destination, version = "") {
290
+ await this.finished();
291
+ const schemaPrefix = `${pathJoin("types", version, "components", "schemas")}/`;
292
+ const outputPrefix = version === "" ? "" : `${version}/`;
293
+ const schemaScripts = Array.from(this.scripts).filter(([path]) => path.startsWith(schemaPrefix));
294
+ for (const [path, script] of schemaScripts) {
295
+ const unsupportedImport = [...script.externalImport.values()].map((entry) => typeof entry.modulePath === "string" ? entry.modulePath : "context")[0] ??
296
+ [...script.imports.values()]
297
+ .map((entry) => entry.script.path)
298
+ .find((importedPath) => !importedPath.startsWith(schemaPrefix));
299
+ if (unsupportedImport !== undefined) {
300
+ throw new Error(`Cannot generate schema ${JSON.stringify(path.slice(schemaPrefix.length).replace(/\.ts$/u, ""))} on its own: it depends on ${JSON.stringify(unsupportedImport)}, which is not a schema.`);
301
+ }
302
+ }
303
+ const outputs = schemaScripts.map(([path, script]) => ({
304
+ outputPath: outputPrefix + this.outputPath(path).slice(schemaPrefix.length),
305
+ contents: () => script.contents(),
306
+ }));
307
+ return this.writeOutputs(destination, outputs);
308
+ }
309
+ /** Write an isolated tree of generated scripts at their original paths. */
310
+ async writeGeneratedScripts(destination, version, extra = new Map()) {
311
+ await this.finished();
312
+ const outputPrefix = version === "" ? "" : `${version}/`;
313
+ const outputs = [
314
+ ...[...this.scripts].map(([path, script]) => ({
315
+ outputPath: outputPrefix + this.outputPath(path),
316
+ contents: () => script.contents(),
317
+ })),
318
+ ...[...extra].map(([path, contents]) => ({
319
+ outputPath: outputPrefix + path,
320
+ contents: () => contents,
321
+ })),
322
+ ];
323
+ return this.writeOutputs(destination, outputs);
324
+ }
325
+ async writeOutputs(destination, outputs) {
326
+ const files = await Promise.all(outputs.map(async ({ outputPath, contents }) => ({
327
+ fullPath: resolveDestinationPath(destination, outputPath),
328
+ contents: await contents(),
329
+ })));
330
+ await adoptSpellings(destination, outputs.map(({ outputPath }) => outputPath));
331
+ await Promise.all(files.map(async ({ fullPath, contents }) => {
332
+ await ensureDirectoryExists(fullPath);
333
+ await fs.writeFile(fullPath, contents);
334
+ }));
335
+ return outputs.map(({ outputPath }) => outputPath);
336
+ }
147
337
  /**
148
338
  * Creates the default `routes/_.context.ts` file if it does not already
149
339
  * exist.
@@ -418,12 +608,12 @@ export class Repository {
418
608
  const scanner = ts.createScanner(ts.ScriptTarget.Latest, false, ts.LanguageVariant.Standard, existing);
419
609
  scanner.setTextPos(position);
420
610
  let end = position;
421
- for (let token = scanner.scan(); token !== ts.SyntaxKind.EndOfFileToken; token = scanner.scan()) {
422
- if (token === ts.SyntaxKind.NewLineTrivia)
611
+ for (let syntaxKind = scanner.scan(); syntaxKind !== ts.SyntaxKind.EndOfFileToken; syntaxKind = scanner.scan()) {
612
+ if (syntaxKind === ts.SyntaxKind.NewLineTrivia)
423
613
  return scanner.getTextPos();
424
- if (token !== ts.SyntaxKind.WhitespaceTrivia &&
425
- token !== ts.SyntaxKind.SingleLineCommentTrivia &&
426
- token !== ts.SyntaxKind.MultiLineCommentTrivia)
614
+ if (syntaxKind !== ts.SyntaxKind.WhitespaceTrivia &&
615
+ syntaxKind !== ts.SyntaxKind.SingleLineCommentTrivia &&
616
+ syntaxKind !== ts.SyntaxKind.MultiLineCommentTrivia)
427
617
  break;
428
618
  end = scanner.getTextPos();
429
619
  }
@@ -495,7 +685,7 @@ export class Repository {
495
685
  ? ["routes", ...parts.slice(pathsIndex + 1)].join("/")
496
686
  : parts.join("/");
497
687
  if (logicalPath !== undefined)
498
- directory = ["routes", ...logicalPath.split("/").filter(Boolean)].join("/");
688
+ directory = this.routeLayout.file(["routes", ...logicalPath.split("/").filter(Boolean)].join("/"));
499
689
  while (directory !== "." && directory !== "routes") {
500
690
  const candidate = nodePath.join(destination, directory, "_.context.ts");
501
691
  if (existsSync(candidate)) {
@@ -81,7 +81,9 @@ export class Requirement {
81
81
  return undefined;
82
82
  }
83
83
  const objectData = this.data;
84
- const child = new Requirement(objectData[key], `${this.url}/${this.escapeJsonPointer(key)}`, this.specification);
84
+ const child = new Requirement(
85
+ // eslint-disable-next-line security/detect-object-injection -- Requirement traversal intentionally resolves dynamic OpenAPI property/index names after has(key) checks.
86
+ objectData[key], `${this.url}/${this.escapeJsonPointer(key)}`, this.specification);
85
87
  child.parent = this;
86
88
  return child;
87
89
  }
@@ -0,0 +1,32 @@
1
+ import ts from "typescript";
2
+ import type { Script } from "./script.js";
3
+ export declare const ROUTE_PATHS_EXPORT = "__counterfactPaths";
4
+ /**
5
+ * Chooses one spelling for paths that differ only by case, segment by segment.
6
+ *
7
+ * The smallest spelling in code-unit order wins, so the result does not
8
+ * depend on the order in which paths are observed. A pinned spelling (one that
9
+ * already exists on disk) always wins. Spellings can change until every path
10
+ * has been observed, so resolve output paths only after that.
11
+ */
12
+ export declare class CaseLayout {
13
+ private readonly spellings;
14
+ private readonly pinned;
15
+ pin(logicalFile: string): void;
16
+ file(logicalFile: string): string;
17
+ private observe;
18
+ }
19
+ export declare function routePathsStatement(paths: readonly string[]): ts.Statement;
20
+ export declare function collisionRouteContents(entries: ReadonlyArray<readonly [string, Script]>, imports?: ReadonlyMap<string, string>, overrides?: ReadonlyMap<string, ts.Expression>): Promise<string>;
21
+ /** Generates handler exports for `methods` only, to append to a route file. */
22
+ export declare function collisionMethodContents(entries: ReadonlyArray<readonly [string, Script]>, methods: ReadonlySet<string>): Promise<string>;
23
+ export declare function readRoutePaths(source: ts.SourceFile): string[] | undefined;
24
+ /** Refuse shape transitions that would drop or misattribute authored code. */
25
+ export declare function matchesRouteMapShape(source: ts.SourceFile, entries: ReadonlyArray<readonly [string, Script]>): boolean;
26
+ /**
27
+ * Returns the methods that `entries` declare but the handler maps in `source`
28
+ * do not, or `undefined` when an existing handler map does not match the
29
+ * expected paths, so new methods can be appended without touching authored
30
+ * handlers.
31
+ */
32
+ export declare function missingRouteMapMethods(source: ts.SourceFile, entries: ReadonlyArray<readonly [string, Script]>): string[] | undefined;
@@ -0,0 +1,152 @@
1
+ import ts from "typescript";
2
+ import { formatStatements, importDeclaration, literalType } from "./ast.js";
3
+ export const ROUTE_PATHS_EXPORT = "__counterfactPaths";
4
+ /**
5
+ * Chooses one spelling for paths that differ only by case, segment by segment.
6
+ *
7
+ * The smallest spelling in code-unit order wins, so the result does not
8
+ * depend on the order in which paths are observed. A pinned spelling (one that
9
+ * already exists on disk) always wins. Spellings can change until every path
10
+ * has been observed, so resolve output paths only after that.
11
+ */
12
+ export class CaseLayout {
13
+ spellings = new Map();
14
+ pinned = new Set();
15
+ pin(logicalFile) {
16
+ this.observe(logicalFile, true);
17
+ }
18
+ file(logicalFile) {
19
+ return this.observe(logicalFile, false);
20
+ }
21
+ observe(logicalFile, pin) {
22
+ const physical = [];
23
+ let key = "";
24
+ for (const segment of logicalFile.split("/")) {
25
+ key = key ? `${key}/${segment.toLowerCase()}` : segment.toLowerCase();
26
+ const known = this.spellings.get(key);
27
+ if (known === undefined ||
28
+ (!this.pinned.has(key) && (pin || segment < known)))
29
+ this.spellings.set(key, segment);
30
+ if (pin)
31
+ this.pinned.add(key);
32
+ physical.push(this.spellings.get(key));
33
+ }
34
+ return physical.join("/");
35
+ }
36
+ }
37
+ function exportedConstant(name, value, type) {
38
+ return ts.factory.createVariableStatement([ts.factory.createModifier(ts.SyntaxKind.ExportKeyword)], ts.factory.createVariableDeclarationList([ts.factory.createVariableDeclaration(name, undefined, type, value)], ts.NodeFlags.Const));
39
+ }
40
+ export function routePathsStatement(paths) {
41
+ return exportedConstant(ROUTE_PATHS_EXPORT, ts.factory.createArrayLiteralExpression(paths.map((path) => ts.factory.createStringLiteral(path))));
42
+ }
43
+ export async function collisionRouteContents(entries, imports = new Map(), overrides = new Map()) {
44
+ const first = entries[0];
45
+ if (!first)
46
+ throw new Error("Cannot generate an empty route.");
47
+ return formatStatements([
48
+ importDeclaration("Routes", `${first[1].relativePathToBase}/types/index.js`, true),
49
+ ...[...imports].map(([local, module]) => ts.factory.createImportDeclaration(undefined, ts.factory.createImportClause(false, undefined, ts.factory.createNamespaceImport(ts.factory.createIdentifier(local))), ts.factory.createStringLiteral(module))),
50
+ routePathsStatement(entries.map(([path]) => path)),
51
+ ...methodStatements(entries, overrides),
52
+ ]);
53
+ }
54
+ /** Generates handler exports for `methods` only, to append to a route file. */
55
+ export async function collisionMethodContents(entries, methods) {
56
+ return formatStatements(methodStatements(entries, new Map(), methods));
57
+ }
58
+ function methodStatements(entries, overrides, only) {
59
+ const methods = new Map();
60
+ for (const [path, script] of entries) {
61
+ for (const [method, entry] of script.exports) {
62
+ if (only && !only.has(method))
63
+ continue;
64
+ const route = script.localTypes.get("Route");
65
+ if (!entry.node || !ts.isExpression(entry.node) || !route)
66
+ throw new Error(`Missing handler for ${method} ${path}.`);
67
+ const handlers = methods.get(method) ?? [];
68
+ handlers.push([
69
+ path,
70
+ overrides.get(JSON.stringify([path, method])) ?? entry.node,
71
+ route,
72
+ ]);
73
+ methods.set(method, handlers);
74
+ }
75
+ }
76
+ return [...methods].map(([method, handlers]) => {
77
+ if (entries.length === 1) {
78
+ const [, implementation, route] = handlers[0];
79
+ return exportedConstant(method, implementation, ts.factory.createIndexedAccessTypeNode(route, literalType(method)));
80
+ }
81
+ return exportedConstant(method, ts.factory.createObjectLiteralExpression(handlers.map(([path, expression]) => ts.factory.createPropertyAssignment(ts.factory.createStringLiteral(path), expression)), true), ts.factory.createTypeLiteralNode(handlers.map(([path, , route]) => ts.factory.createPropertySignature(undefined, ts.factory.createStringLiteral(path), undefined, ts.factory.createIndexedAccessTypeNode(route, literalType(method))))));
82
+ });
83
+ }
84
+ export function readRoutePaths(source) {
85
+ for (const statement of source.statements) {
86
+ if (!ts.isVariableStatement(statement))
87
+ continue;
88
+ for (const declaration of statement.declarationList.declarations) {
89
+ if (!ts.isIdentifier(declaration.name) ||
90
+ declaration.name.text !== ROUTE_PATHS_EXPORT)
91
+ continue;
92
+ const value = declaration.initializer;
93
+ if (!value ||
94
+ !ts.isArrayLiteralExpression(value) ||
95
+ !value.elements.every(ts.isStringLiteral))
96
+ return [];
97
+ return value.elements
98
+ .filter(ts.isStringLiteral)
99
+ .map((element) => element.text);
100
+ }
101
+ }
102
+ return undefined;
103
+ }
104
+ /** Refuse shape transitions that would drop or misattribute authored code. */
105
+ export function matchesRouteMapShape(source, entries) {
106
+ return missingRouteMapMethods(source, entries)?.length === 0;
107
+ }
108
+ /**
109
+ * Returns the methods that `entries` declare but the handler maps in `source`
110
+ * do not, or `undefined` when an existing handler map does not match the
111
+ * expected paths, so new methods can be appended without touching authored
112
+ * handlers.
113
+ */
114
+ export function missingRouteMapMethods(source, entries) {
115
+ const methods = new Map();
116
+ for (const [path, script] of entries) {
117
+ for (const name of script.exports.keys()) {
118
+ const paths = methods.get(name) ?? new Set();
119
+ paths.add(path);
120
+ methods.set(name, paths);
121
+ }
122
+ }
123
+ for (const statement of source.statements) {
124
+ if (!ts.isVariableStatement(statement) ||
125
+ !ts
126
+ .getModifiers(statement)
127
+ ?.some((mod) => mod.kind === ts.SyntaxKind.ExportKeyword))
128
+ continue;
129
+ for (const decl of statement.declarationList.declarations) {
130
+ if (!ts.isIdentifier(decl.name))
131
+ continue;
132
+ const expected = methods.get(decl.name.text);
133
+ if (!expected)
134
+ continue;
135
+ if (!decl.initializer || !ts.isObjectLiteralExpression(decl.initializer))
136
+ return undefined;
137
+ const actual = new Set();
138
+ for (const property of decl.initializer.properties) {
139
+ if ((!ts.isPropertyAssignment(property) &&
140
+ !ts.isMethodDeclaration(property)) ||
141
+ !ts.isStringLiteral(property.name))
142
+ return undefined;
143
+ actual.add(property.name.text);
144
+ }
145
+ if (expected.size !== actual.size ||
146
+ [...expected].some((key) => !actual.has(key)))
147
+ return undefined;
148
+ methods.delete(decl.name.text);
149
+ }
150
+ }
151
+ return [...methods.keys()];
152
+ }
@@ -5,9 +5,26 @@ import nodePath from "node:path";
5
5
  import { watch } from "chokidar";
6
6
  import ts from "typescript";
7
7
  import { exportedConst, formatStatements, functionType, importDeclaration, literalType, parameter, readonlyProperty, stringType, typeAlias, typeLiteral, typeProperty, typeReference, unionType, unknownType, valueExpression, withJsDoc, } from "./ast.js";
8
+ import { adoptSpellings } from "./adopt-spellings.js";
9
+ import { caseSafeOutputPaths } from "./case-safe-paths.js";
8
10
  import { pathRelative } from "./forward-slash-path.js";
9
11
  import { waitForEvent } from "./wait-for-event.js";
10
12
  import { CHOKIDAR_OPTIONS } from "./watch-options.js";
13
+ /**
14
+ * Route directories that differ only by case are distinct on case-sensitive
15
+ * file systems, so their mirrored middleware types need distinct directories
16
+ * (`companies_2/`) to stay apart elsewhere. `Middleware` map keys keep the
17
+ * route directory paths.
18
+ */
19
+ function withMiddlewareTypePaths(routeDirectories) {
20
+ const typePaths = caseSafeOutputPaths(routeDirectories
21
+ .map(({ relativePath }) => relativePath)
22
+ .filter((relativePath) => relativePath !== ""));
23
+ return routeDirectories.map((routeDirectory) => ({
24
+ ...routeDirectory,
25
+ typePath: typePaths.get(routeDirectory.relativePath) ?? routeDirectory.relativePath,
26
+ }));
27
+ }
11
28
  const GENERATED_FILE_COMMENT = "// This file is generated by Counterfact. Do not edit manually.";
12
29
  async function collectContextFiles(destination) {
13
30
  const routesDir = nodePath.join(destination, "routes");
@@ -91,8 +108,8 @@ function routePathToAlias(routePath) {
91
108
  .split("/")
92
109
  .filter(Boolean)
93
110
  .map((seg) => seg
94
- .replace(/\{(.+?)\}/g, (_match, name) => name.replace(/[^a-z0-9]/gi, " "))
95
- .replace(/[-_\s]([a-z])/g, (_match, c) => c.toUpperCase())
111
+ .replace(/\{(?<name>.+?)\}/g, (_match, name) => name.replace(/[^a-z0-9]/gi, " "))
112
+ .replace(/[-_\s](?<letter>[a-z])/g, (_match, c) => c.toUpperCase())
96
113
  .replace(/^[a-z]/, (c) => c.toUpperCase())
97
114
  .replace(/[^a-z0-9]/gi, ""))
98
115
  .join("") + "Context");
@@ -173,7 +190,7 @@ function ensureRelativeImportPath(path) {
173
190
  return path.startsWith(".") ? path : "./" + path;
174
191
  }
175
192
  async function buildMiddlewareTypeContent(destination, routeDirectory) {
176
- const directory = nodePath.join(destination, "types", routeDirectory.relativePath);
193
+ const directory = nodePath.join(destination, "types", routeDirectory.typePath);
177
194
  const sharedPath = ensureRelativeImportPath(pathRelative(directory, nodePath.join(destination, "counterfact-types", "index.js")));
178
195
  const statements = [
179
196
  importDeclaration("MiddlewareFunction", sharedPath, true, false, "Middleware"),
@@ -233,8 +250,11 @@ async function writeGeneratedType(filePath, content) {
233
250
  }
234
251
  async function writeMiddlewareTypes(destination, routeDirectories) {
235
252
  const expectedFiles = new Set();
253
+ // Keep the stale-file sweep below from deleting a file just written under an
254
+ // older spelling of its directory.
255
+ await adoptSpellings(nodePath.join(destination, "types"), routeDirectories.map(({ typePath }) => nodePath.posix.join(typePath, "_.middleware.ts")));
236
256
  for (const routeDirectory of routeDirectories) {
237
- const filePath = nodePath.join(destination, "types", routeDirectory.relativePath, "_.middleware.ts");
257
+ const filePath = nodePath.join(destination, "types", routeDirectory.typePath, "_.middleware.ts");
238
258
  expectedFiles.add(nodePath.resolve(filePath));
239
259
  await fs.mkdir(nodePath.dirname(filePath), { recursive: true });
240
260
  await writeGeneratedType(filePath, await buildMiddlewareTypeContent(destination, routeDirectory));
@@ -312,18 +332,18 @@ export async function writeHelperTypes(destination, rootDestination = destinatio
312
332
  const pending = (async () => {
313
333
  await previous.catch(() => undefined);
314
334
  await writeScenarioContextType(destination, rootDestination, preserveStore);
315
- const directories = (await collectRouteDirectories(destination)).sort((a, b) => a.relativePath < b.relativePath
335
+ const directories = withMiddlewareTypePaths((await collectRouteDirectories(destination)).sort((a, b) => a.relativePath < b.relativePath
316
336
  ? -1
317
337
  : a.relativePath > b.relativePath
318
338
  ? 1
319
- : 0);
339
+ : 0));
320
340
  await writeMiddlewareTypes(destination, directories);
321
341
  const declarations = [
322
342
  ts.factory.createExportDeclaration(undefined, true, ts.factory.createNamedExports(["Context$", "Scenario", "Scenario$"].map((name) => ts.factory.createExportSpecifier(false, undefined, name))), ts.factory.createStringLiteral("./_.context.js")),
323
343
  ];
324
344
  const properties = directories.map((directory, index) => {
325
345
  const alias = `Middleware${index}`;
326
- const modulePath = ensureRelativeImportPath(nodePath.posix.join(directory.relativePath, "_.middleware.js"));
346
+ const modulePath = ensureRelativeImportPath(nodePath.posix.join(directory.typePath, "_.middleware.js"));
327
347
  declarations.push(importDeclaration(alias, modulePath, true, false, "Middleware"));
328
348
  return typeProperty(directory.relativePath === "" ? "/" : `/${directory.relativePath}`, typeReference(alias));
329
349
  });
package/dist/script.d.ts CHANGED
@@ -32,6 +32,8 @@ export declare class Script {
32
32
  reservedNames: Set<string>;
33
33
  localTypes: Map<string, ts.TypeNode>;
34
34
  statementBuilders: Map<string, () => ts.Statement[]>;
35
+ private readonly primaryVersionPaths;
36
+ operationVersionKey(name: string, logicalPath: string): string;
35
37
  constructor(repository: Repository, path: string);
36
38
  get relativePathToBase(): string;
37
39
  firstUniqueName(coder: Coder, isType?: boolean, isDefault?: boolean): string;