@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.
- package/CHANGELOG.md +39 -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/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 +9 -3
- package/dist/code-generator.js +28 -55
- 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 +1 -1
- package/dist/operation-type-coder.d.ts +6 -0
- package/dist/operation-type-coder.js +17 -5
- 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 +15 -1
- package/dist/repository.js +184 -33
- package/dist/route-file-layout.d.ts +32 -0
- package/dist/route-file-layout.js +152 -0
- package/dist/scenario-file-generator.js +25 -5
- 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/package.json +4 -3
- package/src/README.md +2 -1
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { Requirement } from "./requirement.js";
|
|
2
|
+
const methods = new Set([
|
|
3
|
+
"get",
|
|
4
|
+
"put",
|
|
5
|
+
"post",
|
|
6
|
+
"delete",
|
|
7
|
+
"options",
|
|
8
|
+
"head",
|
|
9
|
+
"patch",
|
|
10
|
+
"trace",
|
|
11
|
+
]);
|
|
12
|
+
export function pathOperations(pathItem) {
|
|
13
|
+
let resolved = pathItem;
|
|
14
|
+
while (resolved.isReference)
|
|
15
|
+
resolved = resolved.reference();
|
|
16
|
+
const operations = resolved.flatMap((operation, name) => {
|
|
17
|
+
if (name === "additionalOperations") {
|
|
18
|
+
return operation.map((additional, method) => [
|
|
19
|
+
additional,
|
|
20
|
+
method.toLowerCase(),
|
|
21
|
+
]);
|
|
22
|
+
}
|
|
23
|
+
return methods.has(name) ? [[operation, name]] : [];
|
|
24
|
+
});
|
|
25
|
+
return operations.map(([operation, method]) => {
|
|
26
|
+
// A referenced operation still belongs to the endpoint and its path-item parameters.
|
|
27
|
+
const logical = new Requirement(operation.data, `${pathItem.url}/${method}`, pathItem.specification);
|
|
28
|
+
logical.parent = pathItem;
|
|
29
|
+
return [logical, method];
|
|
30
|
+
});
|
|
31
|
+
}
|
package/dist/prune.d.ts
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
* @param openApiPaths - Iterable of OpenAPI path strings (e.g. "/pet/{id}")
|
|
6
6
|
* @returns Number of files removed
|
|
7
7
|
*/
|
|
8
|
-
export declare function pruneRoutes(destination: string, openApiPaths: Iterable<string>): Promise<number>;
|
|
8
|
+
export declare function pruneRoutes(destination: string, openApiPaths: Iterable<string>, outputPaths?: Iterable<string>): Promise<number>;
|
|
9
9
|
/**
|
|
10
10
|
* Prunes obsolete files from the OpenAPI generator-owned namespaces below
|
|
11
11
|
* `types/`. Hidden files are included by the recursive directory walk.
|
package/dist/prune.js
CHANGED
|
@@ -81,11 +81,18 @@ function openApiPathToRouteFile(openApiPath) {
|
|
|
81
81
|
* @param openApiPaths - Iterable of OpenAPI path strings (e.g. "/pet/{id}")
|
|
82
82
|
* @returns Number of files removed
|
|
83
83
|
*/
|
|
84
|
-
export async function pruneRoutes(destination, openApiPaths) {
|
|
84
|
+
export async function pruneRoutes(destination, openApiPaths, outputPaths) {
|
|
85
85
|
const routesDir = nodePath.join(destination, "routes");
|
|
86
|
-
const expectedFiles = new Set(
|
|
86
|
+
const expectedFiles = new Set(outputPaths
|
|
87
|
+
? Array.from(outputPaths, (path) => path.slice("routes/".length))
|
|
88
|
+
: Array.from(openApiPaths).map(openApiPathToRouteFile));
|
|
87
89
|
debug("expected route files: %o", Array.from(expectedFiles));
|
|
88
|
-
const actualFiles = (await collectTypeScriptFiles(routesDir)).filter((file) =>
|
|
90
|
+
const actualFiles = (await collectTypeScriptFiles(routesDir)).filter((file) => {
|
|
91
|
+
const name = nodePath.basename(file);
|
|
92
|
+
return (name !== "_.context.ts" &&
|
|
93
|
+
name !== "_.middleware.ts" &&
|
|
94
|
+
!name.startsWith("_.counterfact-legacy-"));
|
|
95
|
+
});
|
|
89
96
|
debug("actual route files: %o", actualFiles);
|
|
90
97
|
let prunedCount = 0;
|
|
91
98
|
for (const file of actualFiles) {
|
package/dist/repository.d.ts
CHANGED
|
@@ -2,6 +2,8 @@ import { Script } from "./script.js";
|
|
|
2
2
|
interface WriteFilesOptions {
|
|
3
3
|
routes?: boolean;
|
|
4
4
|
types?: boolean;
|
|
5
|
+
prune?: boolean;
|
|
6
|
+
keepVersionsFile?: boolean;
|
|
5
7
|
}
|
|
6
8
|
/**
|
|
7
9
|
* Collection of {@link Script} objects keyed by their repository-relative
|
|
@@ -14,6 +16,14 @@ interface WriteFilesOptions {
|
|
|
14
16
|
*/
|
|
15
17
|
export declare class Repository {
|
|
16
18
|
scripts: Map<string, Script>;
|
|
19
|
+
private readonly routesByPath;
|
|
20
|
+
private readonly specRouteFiles;
|
|
21
|
+
private readonly typeLayout;
|
|
22
|
+
private readonly typeScripts;
|
|
23
|
+
private routeLayout;
|
|
24
|
+
recordRouteFile(logicalFile: string): void;
|
|
25
|
+
route(logicalFile: string, path: string): Script;
|
|
26
|
+
outputPath(logical: string): string;
|
|
17
27
|
constructor();
|
|
18
28
|
/**
|
|
19
29
|
* Returns the {@link Script} for `path`, creating it if it does not yet
|
|
@@ -46,7 +56,8 @@ export declare class Repository {
|
|
|
46
56
|
* @param destination - Absolute path to the output root directory.
|
|
47
57
|
* @param options - Controls which artefacts are written.
|
|
48
58
|
*/
|
|
49
|
-
writeFiles(destination: string, { routes, types }: WriteFilesOptions): Promise<void>;
|
|
59
|
+
writeFiles(destination: string, { routes, types, prune, keepVersionsFile }: WriteFilesOptions): Promise<void>;
|
|
60
|
+
private assertSafeRouteLayout;
|
|
50
61
|
/**
|
|
51
62
|
* Waits for all scripts to finish, then writes only the schemas for
|
|
52
63
|
* `version` directly under `destination`, without the
|
|
@@ -62,6 +73,9 @@ export declare class Repository {
|
|
|
62
73
|
* @returns The output paths written, relative to `destination`.
|
|
63
74
|
*/
|
|
64
75
|
writeSchemas(destination: string, version?: string): Promise<string[]>;
|
|
76
|
+
/** Write an isolated tree of generated scripts at their original paths. */
|
|
77
|
+
writeGeneratedScripts(destination: string, version: string, extra?: ReadonlyMap<string, string>): Promise<string[]>;
|
|
78
|
+
private writeOutputs;
|
|
65
79
|
/**
|
|
66
80
|
* Creates the default `routes/_.context.ts` file if it does not already
|
|
67
81
|
* exist.
|
package/dist/repository.js
CHANGED
|
@@ -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
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
|
-
|
|
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
|
|
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 (
|
|
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(
|
|
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
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
await
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
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
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
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,32 @@ 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
|
+
}
|
|
147
275
|
/**
|
|
148
276
|
* Waits for all scripts to finish, then writes only the schemas for
|
|
149
277
|
* `version` directly under `destination`, without the
|
|
@@ -173,13 +301,36 @@ export class Repository {
|
|
|
173
301
|
}
|
|
174
302
|
}
|
|
175
303
|
const outputs = schemaScripts.map(([path, script]) => ({
|
|
176
|
-
outputPath: outputPrefix + path.slice(schemaPrefix.length),
|
|
177
|
-
script,
|
|
304
|
+
outputPath: outputPrefix + this.outputPath(path).slice(schemaPrefix.length),
|
|
305
|
+
contents: () => script.contents(),
|
|
178
306
|
}));
|
|
179
|
-
|
|
180
|
-
|
|
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 }) => {
|
|
181
332
|
await ensureDirectoryExists(fullPath);
|
|
182
|
-
await fs.writeFile(fullPath,
|
|
333
|
+
await fs.writeFile(fullPath, contents);
|
|
183
334
|
}));
|
|
184
335
|
return outputs.map(({ outputPath }) => outputPath);
|
|
185
336
|
}
|
|
@@ -534,7 +685,7 @@ export class Repository {
|
|
|
534
685
|
? ["routes", ...parts.slice(pathsIndex + 1)].join("/")
|
|
535
686
|
: parts.join("/");
|
|
536
687
|
if (logicalPath !== undefined)
|
|
537
|
-
directory = ["routes", ...logicalPath.split("/").filter(Boolean)].join("/");
|
|
688
|
+
directory = this.routeLayout.file(["routes", ...logicalPath.split("/").filter(Boolean)].join("/"));
|
|
538
689
|
while (directory !== "." && directory !== "routes") {
|
|
539
690
|
const candidate = nodePath.join(destination, directory, "_.context.ts");
|
|
540
691
|
if (existsSync(candidate)) {
|
|
@@ -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");
|
|
@@ -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.
|
|
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.
|
|
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.
|
|
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;
|