@counterfact/generator 0.1.5 → 0.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/script.js CHANGED
@@ -1,45 +1,24 @@
1
1
  import createDebugger from "debug";
2
- import { format } from "prettier";
2
+ import ts from "typescript";
3
+ import { formatStatements, importDeclaration, objectExpression, typeAlias, typeLiteral, typeProperty, unknownType, withComment, } from "./ast.js";
3
4
  import { escapePathForWindows } from "./windows-escape.js";
4
5
  import { pathJoin, pathRelative, pathDirname } from "./forward-slash-path.js";
5
6
  const debug = createDebugger("counterfact:typescript-generator:script");
6
- /**
7
- * Represents a single TypeScript file being assembled by the code generator.
8
- *
9
- * A `Script` accumulates exports, imports, and external imports contributed by
10
- * {@link Coder} instances. Once all coders have resolved, {@link contents}
11
- * formats the result with Prettier and returns the final source text.
12
- *
13
- * Scripts are created and retrieved through a {@link Repository} so that the
14
- * same module path always maps to the same `Script` instance.
15
- */
7
+ /** One generated module: coders register nodes; printing occurs after resolution. */
16
8
  export class Script {
17
- repository;
18
- comments;
19
- exports;
20
- versions;
21
- versionFormatters;
22
- imports;
23
- externalImport;
24
- cache;
25
- typeCache;
26
9
  path;
10
+ repository;
11
+ comments = [];
12
+ exports = new Map();
13
+ versions = new Map();
14
+ versionBuilders = new Map();
15
+ imports = new Map();
16
+ externalImport = new Map();
17
+ cache = new Map();
27
18
  constructor(repository, path) {
28
- this.repository = repository;
29
- this.comments = [];
30
- this.exports = new Map();
31
- this.versions = new Map();
32
- this.versionFormatters = new Map();
33
- this.imports = new Map();
34
- this.externalImport = new Map();
35
- this.cache = new Map();
36
- this.typeCache = new Map();
37
19
  this.path = path;
20
+ this.repository = repository;
38
21
  }
39
- /**
40
- * A `"../"` path fragment that points from this script's directory back to
41
- * the repository root, used to resolve relative import paths.
42
- */
43
22
  get relativePathToBase() {
44
23
  return this.path
45
24
  .split("/")
@@ -47,100 +26,79 @@ export class Script {
47
26
  .map(() => "..")
48
27
  .join("/");
49
28
  }
50
- /**
51
- * Picks the first name from `coder.names()` that is not already used as an
52
- * import in this script, ensuring export/import name uniqueness.
53
- *
54
- * @param coder - The coder needing a name.
55
- * @throws When all 100 candidate names are already taken.
56
- */
57
- firstUniqueName(coder) {
29
+ firstUniqueName(coder, isType = false, isDefault = false) {
58
30
  for (const name of coder.names()) {
59
- if (!this.imports.has(name)) {
31
+ if ((!this.imports.has(name) ||
32
+ (this.imports.get(name).id === coder.exportId &&
33
+ this.imports.get(name).isType === isType &&
34
+ this.imports.get(name).isDefault === isDefault)) &&
35
+ (!this.exports.has(name) ||
36
+ (this.exports.get(name).id === coder.exportId &&
37
+ this.exports.get(name).isType === isType &&
38
+ this.exports.get(name).isDefault === isDefault)) &&
39
+ !this.externalImport.has(name))
60
40
  return name;
61
- }
62
41
  }
63
42
  throw new Error(`could not find a unique name for ${coder.id}`);
64
43
  }
65
- /**
66
- * Registers an export for `coder` in this script and returns the export name.
67
- *
68
- * If the same coder has already been exported (cache hit), the previously
69
- * assigned name is returned without creating a duplicate.
70
- *
71
- * @param coder - The coder to export.
72
- * @param isType - Emit `export type` instead of `export const`.
73
- * @param isDefault - Emit `export default` instead of a named export.
74
- * @returns The name under which the coder is exported.
75
- */
76
44
  export(coder, isType = false, isDefault = false) {
77
45
  const cacheKey = isDefault ? "default" : `${coder.id}:${isType}`;
78
- if (this.cache.has(cacheKey)) {
46
+ if (this.cache.has(cacheKey))
79
47
  return this.cache.get(cacheKey);
80
- }
81
- const name = this.firstUniqueName(coder);
48
+ const name = this.firstUniqueName(coder, isType, isDefault);
82
49
  this.cache.set(cacheKey, name);
83
- const exportStatement = {
84
- beforeExport: coder.beforeExport(this.path),
50
+ const entry = {
85
51
  done: false,
86
- id: coder.id,
52
+ id: coder.exportId,
87
53
  isDefault,
88
54
  isType,
55
+ name,
89
56
  jsdoc: "",
90
57
  typeDeclaration: coder.typeDeclaration(this.exports, this),
91
58
  };
92
- exportStatement.promise = coder
59
+ this.exports.set(name, entry);
60
+ entry.promise = coder
93
61
  .delegate()
94
- .then((availableCoder) => {
95
- exportStatement.name = name;
96
- exportStatement.code = availableCoder.write(this);
97
- exportStatement.jsdoc = availableCoder.jsdoc();
98
- return availableCoder;
62
+ .then((available) => {
63
+ entry.statements = available.exportDeclarations(this, name);
64
+ if (entry.statements === undefined)
65
+ entry.node = available.write(this);
66
+ entry.jsdoc = available.jsdoc();
67
+ return available;
99
68
  })
100
69
  .catch((error) => {
101
- exportStatement.code = `{/* error creating export "${name}" for ${this.path}: ${error.stack} */}`;
102
- exportStatement.error = error;
70
+ entry.node = isType ? unknownType() : objectExpression([]);
71
+ entry.jsdoc = `/** error creating export "${name}" for ${this.path}: ${error.stack} */`;
72
+ entry.error = error;
103
73
  return undefined;
104
74
  })
105
75
  .finally(() => {
106
- exportStatement.done = true;
76
+ entry.done = true;
107
77
  });
108
- this.exports.set(name, exportStatement);
109
78
  return name;
110
79
  }
111
80
  exportDefault(coder, isType = false) {
112
81
  this.export(coder, isType, true);
113
82
  }
114
- /**
115
- * Registers an import of `coder` from its owning module and returns the
116
- * local alias used in this script.
117
- *
118
- * The coder is also exported from its home module as a side effect.
119
- *
120
- * @param coder - The coder to import.
121
- * @param isType - Use a `import type` declaration.
122
- * @param isDefault - Import the default export rather than a named export.
123
- */
124
83
  import(coder, isType = false, isDefault = false) {
125
- debug("import coder: %s", coder.id);
126
84
  const modulePath = coder.modulePath();
127
- const cacheKey = `${coder.id}@${modulePath}:${isType}:${isDefault}`;
128
- debug("cache key: %s", cacheKey);
129
- if (this.cache.has(cacheKey)) {
130
- debug("cache hit: %s", cacheKey);
131
- return this.cache.get(cacheKey);
132
- }
133
- debug("cache miss: %s", cacheKey);
134
- const name = this.firstUniqueName(coder);
135
- this.cache.set(cacheKey, name);
136
- const scriptFromWhichToExport = this.repository.get(modulePath);
137
- const exportedName = scriptFromWhichToExport.export(coder, isType, isDefault);
85
+ const key = `${coder.id}@${modulePath}:${isType}:${isDefault}`;
86
+ if (this.cache.has(key))
87
+ return this.cache.get(key);
88
+ if (modulePath === this.path)
89
+ return this.export(coder, isType, isDefault);
90
+ const name = this.firstUniqueName(coder, isType, isDefault);
91
+ this.cache.set(key, name);
92
+ const script = this.repository.get(modulePath);
93
+ const exportedName = script.export(coder, isType, isDefault);
138
94
  this.imports.set(name, {
95
+ id: coder.exportId,
139
96
  isDefault,
140
97
  isType,
141
98
  name: exportedName,
142
- script: scriptFromWhichToExport,
99
+ script,
143
100
  });
101
+ debug("import %s as %s from %s", exportedName, name, modulePath);
144
102
  return name;
145
103
  }
146
104
  importType(coder) {
@@ -149,174 +107,141 @@ export class Script {
149
107
  importDefault(coder, isType = false) {
150
108
  return this.import(coder, isType, true);
151
109
  }
152
- /**
153
- * Registers an import from an external npm package or absolute module path
154
- * (not managed by the repository).
155
- *
156
- * @param name - The local binding name.
157
- * @param modulePath - The module specifier (e.g. `"counterfact-types/index"`).
158
- * @param isType - Use a `import type` declaration.
159
- * @returns `name` (for convenience in method chaining).
160
- */
161
110
  importExternal(name, modulePath, isType = false) {
162
111
  this.externalImport.set(name, { isType, modulePath });
163
112
  return name;
164
113
  }
165
- /**
166
- * Convenience wrapper that calls {@link importExternal} with `isType = true`.
167
- */
168
- importExternalType(name, modulePath) {
169
- return this.importExternal(name, modulePath, true);
114
+ importExternalType(name, path) {
115
+ return this.importExternal(name, path, true);
170
116
  }
171
- /**
172
- * Imports a type from the shared `counterfact-types/index.ts` module,
173
- * resolving the path relative to this script's location in the repository.
174
- *
175
- * @param name - The type name to import (e.g. `"WideOperationArgument"`).
176
- */
177
117
  importSharedType(name) {
178
- return this.importExternal(name, pathJoin(this.relativePathToBase, "counterfact-types/index.ts"), true);
118
+ return this.importExternalType(name, pathJoin(this.relativePathToBase, "counterfact-types/index.ts"));
179
119
  }
180
- /**
181
- * Imports a type from the generated `types/versions.ts` module,
182
- * resolving the path relative to this script's location in the repository.
183
- *
184
- * @param name - The type name to import (e.g. `"Versioned"`).
185
- */
186
120
  importVersionsType(name) {
187
- return this.importExternal(name, pathJoin(this.relativePathToBase, "types/versions.ts"), true);
121
+ return this.importExternalType(name, pathJoin(this.relativePathToBase, "types/versions.ts"));
188
122
  }
189
123
  exportType(coder) {
190
124
  return this.export(coder, true);
191
125
  }
192
- /**
193
- * Registers a formatter function for the merged versioned type emitted under
194
- * `name` by {@link versionsTypeStatements}.
195
- *
196
- * When a formatter is present for a name, `versionsTypeStatements` delegates
197
- * the entire type declaration to it instead of generating the default
198
- * `Versions` object type. The formatter receives a `Map<version, importAlias>`
199
- * and must return the complete TypeScript source for that operation type.
200
- */
201
- setVersionFormatter(name, formatter) {
202
- this.versionFormatters.set(name, formatter);
126
+ setVersionBuilder(name, builder) {
127
+ this.versionBuilders.set(name, builder);
203
128
  }
204
129
  declareVersion(coder, name) {
205
- const version = coder.version;
206
130
  const versions = this.versions.get(name) ?? new Map();
207
131
  this.versions.set(name, versions);
208
- if (versions.has(version)) {
132
+ if (versions.has(coder.version))
209
133
  return;
210
- }
211
- const versionStatement = {
212
- beforeExport: "",
134
+ const entry = {
213
135
  done: false,
214
- id: coder.id,
136
+ id: coder.exportId,
215
137
  isDefault: false,
216
138
  isType: true,
217
139
  jsdoc: "",
218
- typeDeclaration: "",
219
140
  };
220
- versionStatement.promise = coder
141
+ versions.set(coder.version, entry);
142
+ entry.promise = coder
221
143
  .delegate()
222
- .then((availableCoder) => {
223
- versionStatement.code = availableCoder.write(this);
224
- return availableCoder;
144
+ .then((available) => {
145
+ entry.node = available.write(this);
146
+ return available;
225
147
  })
226
148
  .catch((error) => {
227
- versionStatement.code = `unknown /* error declaring version "${name}" (${version}) for ${this.path}: ${error.message} */`;
228
- versionStatement.error = error;
149
+ entry.node = unknownType();
150
+ entry.error = error;
229
151
  return undefined;
230
152
  })
231
153
  .finally(() => {
232
- versionStatement.done = true;
154
+ entry.done = true;
233
155
  });
234
- versions.set(version, versionStatement);
235
156
  }
236
- /** `true` while at least one export promise is still pending. */
237
157
  isInProgress() {
238
- return (Array.from(this.exports.values()).some((exportStatement) => !exportStatement.done) ||
239
- Array.from(this.versions.values())
240
- .flatMap((versions) => Array.from(versions.values()))
241
- .some((versionStatement) => !versionStatement.done));
158
+ return [
159
+ ...this.exports.values(),
160
+ ...[...this.versions.values()].flatMap((versions) => [
161
+ ...versions.values(),
162
+ ]),
163
+ ].some((entry) => !entry.done);
242
164
  }
243
- /** Returns a promise that resolves when all pending export promises settle. */
244
165
  finished() {
245
166
  return Promise.all([
246
- ...Array.from(this.exports.values(), (value) => value.promise),
247
- ...Array.from(this.versions.values())
248
- .flatMap((versions) => Array.from(versions.values()))
249
- .map((value) => value.promise),
250
- ]);
251
- }
252
- externalImportStatements() {
253
- return Array.from(this.externalImport, ([name, { isDefault, isType, modulePath }]) => `import${isType ? " type" : ""} ${isDefault ? name : `{ ${name} }`} from "${modulePath}";`);
167
+ ...this.exports.values(),
168
+ ...[...this.versions.values()].flatMap((versions) => [
169
+ ...versions.values(),
170
+ ]),
171
+ ].map((entry) => entry.promise));
172
+ }
173
+ externalImportStatements(contextPath) {
174
+ return Array.from(this.externalImport, ([name, entry]) => {
175
+ const modulePath = typeof entry.modulePath === "string"
176
+ ? entry.modulePath
177
+ : (contextPath ??
178
+ pathRelative(pathDirname(this.path), "routes/_.context.ts"));
179
+ return importDeclaration(name, modulePath.startsWith(".") || typeof entry.modulePath === "string"
180
+ ? modulePath
181
+ : `./${modulePath}`, entry.isType, entry.isDefault);
182
+ });
254
183
  }
255
184
  importStatements() {
256
- return Array.from(this.imports, ([name, { isDefault, isType, script }]) => {
257
- const resolvedPath = escapePathForWindows(pathRelative(pathDirname(this.path), script.path.replace(/\.ts$/u, ".js")));
258
- return `import${isType ? " type" : ""} ${isDefault ? name : `{ ${name} }`} from "${resolvedPath.includes("../") ? "" : "./"}${resolvedPath}";`;
185
+ return Array.from(this.imports, ([name, entry]) => {
186
+ const path = escapePathForWindows(pathRelative(pathDirname(this.path), entry.script.path.replace(/\.ts$/u, ".js")));
187
+ return importDeclaration(name, path.includes("../") ? path : `./${path}`, entry.isType, entry.isDefault, entry.name);
259
188
  });
260
189
  }
261
190
  exportStatements() {
262
- return Array.from(this.exports.values(), ({ beforeExport, code, isDefault, isType, jsdoc, name, typeDeclaration, }) => {
263
- if (typeof code === "object" && code !== null && "raw" in code) {
264
- return code.raw;
191
+ return [...this.exports.values()].flatMap((entry) => {
192
+ if (entry.statements !== undefined)
193
+ return entry.statements;
194
+ const node = entry.node;
195
+ if (entry.isType) {
196
+ if (!ts.isTypeNode(node))
197
+ throw new Error(`Expected a type node for ${entry.name}`);
198
+ const declaration = withComment(typeAlias(entry.name, node), entry.jsdoc);
199
+ if (!entry.isDefault)
200
+ return [declaration];
201
+ return [
202
+ declaration,
203
+ ts.factory.createExportDeclaration(undefined, true, ts.factory.createNamedExports([
204
+ ts.factory.createExportSpecifier(false, entry.name, "default"),
205
+ ])),
206
+ ];
265
207
  }
266
- if (isDefault) {
267
- return `${jsdoc}${beforeExport}export default ${code};`;
268
- }
269
- const keyword = isType ? "type" : "const";
270
- const typeAnnotation = (typeDeclaration ?? "").length === 0
271
- ? ""
272
- : `:${typeDeclaration ?? ""}`;
273
- return `${jsdoc}${beforeExport}export ${keyword} ${name ?? ""}${typeAnnotation} = ${code};`;
208
+ if (ts.isTypeNode(node))
209
+ throw new Error(`Expected an expression for ${entry.name}`);
210
+ const statement = entry.isDefault
211
+ ? ts.factory.createExportAssignment(undefined, false, node)
212
+ : ts.factory.createVariableStatement([ts.factory.createModifier(ts.SyntaxKind.ExportKeyword)], ts.factory.createVariableDeclarationList([
213
+ ts.factory.createVariableDeclaration(entry.name, undefined, entry.typeDeclaration, node),
214
+ ], ts.NodeFlags.Const));
215
+ return [withComment(statement, entry.jsdoc)];
274
216
  });
275
217
  }
276
218
  versionsTypeStatements() {
277
- if (this.versions.size === 0) {
278
- return [];
279
- }
280
219
  const statements = [];
281
- const unformatted = [];
220
+ const unbuilt = [];
282
221
  for (const [name, versions] of this.versions) {
283
- const formatter = this.versionFormatters.get(name);
284
- if (formatter) {
285
- const versionCodes = new Map(Array.from(versions, ([version, stmt]) => [
286
- version,
287
- stmt.code,
288
- ]));
289
- statements.push(formatter(versionCodes));
222
+ const types = new Map();
223
+ for (const [version, entry] of versions) {
224
+ if (!entry.node || !ts.isTypeNode(entry.node))
225
+ throw new Error(`Expected a type for ${name} version ${version}`);
226
+ types.set(version, entry.node);
290
227
  }
291
- else {
292
- unformatted.push([name, versions]);
293
- }
294
- }
295
- if (unformatted.length > 0) {
296
- const names = unformatted.map(([name, versions]) => {
297
- const mappedVersions = Array.from(versions, ([version, versionStatement]) => `"${version}": ${versionStatement.code}`);
298
- return `"${name}": { ${mappedVersions.join(", ")} }`;
299
- });
300
- statements.push(`export type Versions = { ${names.join(", ")} };`);
228
+ const builder = this.versionBuilders.get(name);
229
+ if (builder)
230
+ statements.push(...builder(types));
231
+ else
232
+ unbuilt.push(typeProperty(name, typeLiteral([...types].map(([version, type]) => typeProperty(version, type)))));
301
233
  }
234
+ if (unbuilt.length > 0)
235
+ statements.push(typeAlias("Versions", typeLiteral(unbuilt)));
302
236
  return statements;
303
237
  }
304
- /**
305
- * Formats the fully assembled script source with Prettier and returns it.
306
- *
307
- * All pending export promises are awaited before formatting.
308
- */
309
- async contents() {
238
+ async contents(contextPath) {
310
239
  await this.finished();
311
- return format([
312
- this.comments.map((comment) => `// ${comment}`).join("\n"),
313
- this.comments.length > 0 ? "\n\n" : "",
314
- this.externalImportStatements().join("\n"),
315
- this.importStatements().join("\n"),
316
- "\n\n",
317
- this.versionsTypeStatements().join("\n"),
318
- this.versions.size > 0 ? "\n\n" : "",
319
- this.exportStatements().join("\n\n"),
320
- ].join(""), { parser: "typescript" });
240
+ return formatStatements([
241
+ ...this.externalImportStatements(contextPath),
242
+ ...this.importStatements(),
243
+ ...this.versionsTypeStatements(),
244
+ ...this.exportStatements(),
245
+ ], this.comments);
321
246
  }
322
247
  }
@@ -1,5 +1,7 @@
1
+ import type ts from "typescript";
1
2
  import { Coder } from "./coder.js";
2
3
  import type { Script } from "./script.js";
3
4
  export declare class TypeCoder extends Coder {
4
- write(script: Script): string;
5
+ write(script: Script): ts.TypeNode;
6
+ writeCode(_script: Script): ts.TypeNode;
5
7
  }
@@ -1,9 +1,13 @@
1
+ import { typeReference } from "./ast.js";
1
2
  import { Coder } from "./coder.js";
2
3
  export class TypeCoder extends Coder {
3
4
  write(script) {
4
5
  if (this.requirement?.isReference) {
5
- return script.importType(this);
6
+ return typeReference(script.importType(this));
6
7
  }
7
8
  return this.writeCode(script);
8
9
  }
10
+ writeCode(_script) {
11
+ throw new Error("TypeCoder.writeCode() must be implemented by a subclass");
12
+ }
9
13
  }
@@ -1,10 +1 @@
1
- /**
2
- * Generates the TypeScript source text for `types/versions.ts`.
3
- *
4
- * Returns an empty string when `versions` is empty.
5
- * The returned string is formatted with Prettier.
6
- *
7
- * @param versions - Ordered list of unique, non-empty version strings.
8
- * The first entry is the oldest version.
9
- */
10
1
  export declare function generateVersionsTsContent(versions: readonly string[]): Promise<string>;
@@ -1,82 +1,51 @@
1
- import { format } from "prettier";
2
- /**
3
- * Builds the `VersionsGTE` map: for each version V at index i,
4
- * maps V to all versions at indices >= i (i.e. V and all later-declared
5
- * versions, where "later" means "newer").
6
- */
1
+ import ts from "typescript";
2
+ import { formatStatements, literalType, parameter, typeAlias, typeLiteral, typeProperty, typeReference, unionType, withJsDoc, } from "./ast.js";
7
3
  function buildVersionsGTE(versions) {
8
- const result = new Map();
9
- versions.forEach((version, index) => {
10
- result.set(version, versions.slice(index));
11
- });
12
- return result;
4
+ return new Map(versions.map((version, index) => [version, versions.slice(index)]));
13
5
  }
14
- /**
15
- * Generates the TypeScript source text for `types/versions.ts`.
16
- *
17
- * Returns an empty string when `versions` is empty.
18
- * The returned string is formatted with Prettier.
19
- *
20
- * @param versions - Ordered list of unique, non-empty version strings.
21
- * The first entry is the oldest version.
22
- */
6
+ const VERSIONED_DESCRIPTION = `The type of the \u0060$\u0060 argument in a versioned route handler.
7
+
8
+ @typeParam T - A map from version string to the \u0060$\u0060-arg type for that version
9
+ (e.g. \u0060{ v1: $v1Type; v2: $v2Type }\u0060). Generated by Counterfact from the spec.
10
+ @typeParam V - The union of currently active version keys; defaults to all keys of \u0060T\u0060.
11
+
12
+ An instance of \u0060Versioned<T, V>\u0060 exposes:
13
+ - All properties of the intersection \u0060T[V]\u0060 (request data, response builders, etc.)
14
+ - \u0060version\u0060 — the version string for the current request (e.g. \u0060"v2"\u0060).
15
+ - \u0060minVersion(min)\u0060 — type predicate that returns \u0060true\u0060 when the current version
16
+ is at or after \u0060min\u0060 in the declared version order and narrows \u0060$\u0060 accordingly.`;
23
17
  export async function generateVersionsTsContent(versions) {
24
- if (versions.length === 0) {
18
+ if (versions.length === 0)
25
19
  return "";
26
- }
27
- const versionsUnion = versions.map((v) => `"${v}"`).join(" | ");
28
- const versionsGTE = buildVersionsGTE(versions);
29
- const versionsGTEBody = Array.from(versionsGTE, ([v, gte]) => ` "${v}": ${gte.map((g) => `"${g}"`).join(" | ")};`).join("\n");
30
- const source = [
31
- "// This file is auto-generated by Counterfact. Do not edit.",
32
- "",
33
- '/** Union of all version strings declared for this API group (e.g. `"v1" | "v2" | "v3"`). */',
34
- `export type Versions = ${versionsUnion};`,
35
- "",
36
- "/**",
37
- " * Maps each version to the set of versions that are greater than or equal to it.",
38
- " * Used by `Versioned.minVersion()` to narrow which versions a handler must support.",
39
- " */",
40
- "export type VersionsGTE = {",
41
- versionsGTEBody,
42
- "};",
43
- "",
44
- "type VersionMap = Partial<Record<Versions, object>>;",
45
- "",
46
- "/**",
47
- " * The type of the `$` argument in a versioned route handler.",
48
- " *",
49
- " * @typeParam T - A map from version string to the `$`-arg type for that version",
50
- " * (e.g. `{ v1: $v1Type; v2: $v2Type }`). Generated by Counterfact from the spec.",
51
- " * @typeParam V - The union of currently active version keys; defaults to all keys of `T`.",
52
- " *",
53
- " * An instance of `Versioned<T, V>` exposes:",
54
- " * - All properties of the intersection `T[V]` (request data, response builders, etc.)",
55
- ' * - `version` — the version string for the current request (e.g. `"v2"`).',
56
- " * - `minVersion(min)` — type predicate that returns `true` when the current version",
57
- " * is at or after `min` in the declared version order and narrows `$` accordingly.",
58
- " *",
59
- " * @example",
60
- " * ```ts",
61
- " * export const GET: HTTP_GET = ($) => {",
62
- ' * if ($.minVersion("v2")) {',
63
- " * // $ is now typed as the v2+ arg — v2-only fields are available",
64
- " * return $.response[200].json({ id: $.path.id, extra: $.body.extra });",
65
- " * }",
66
- " * return $.response[200].json({ id: $.path.id });",
67
- " * };",
68
- " * ```",
69
- " */",
70
- "export type Versioned<",
71
- " T extends VersionMap,",
72
- " V extends keyof T & Versions = keyof T & Versions,",
73
- "> = T[V] & {",
74
- " version: V;",
75
- " minVersion<M extends keyof T & Versions>(",
76
- " min: M,",
77
- " ): this is Versioned<T, Extract<V, VersionsGTE[M]>>;",
78
- "};",
79
- "",
80
- ].join("\n");
81
- return format(source, { parser: "typescript" });
20
+ const activeKeys = () => ts.factory.createIntersectionTypeNode([
21
+ ts.factory.createTypeOperatorNode(ts.SyntaxKind.KeyOfKeyword, typeReference("T")),
22
+ typeReference("Versions"),
23
+ ]);
24
+ const activeVersionMap = ts.factory.createIndexedAccessTypeNode(typeReference("VersionsGTE"), typeReference("M"));
25
+ const narrowing = ts.factory.createTypePredicateNode(undefined, ts.factory.createThisTypeNode(), typeReference("Versioned", [
26
+ typeReference("T"),
27
+ typeReference("Extract", [typeReference("V"), activeVersionMap]),
28
+ ]));
29
+ const minVersion = ts.factory.createMethodSignature(undefined, "minVersion", undefined, [ts.factory.createTypeParameterDeclaration(undefined, "M", activeKeys())], [parameter("min", typeReference("M"))], narrowing);
30
+ return formatStatements([
31
+ withJsDoc(typeAlias("Versions", unionType(versions.map(literalType))), {
32
+ description: 'Union of all version strings declared for this API group (e.g. \u0060"v1" | "v2" | "v3"\u0060).',
33
+ }),
34
+ withJsDoc(typeAlias("VersionsGTE", typeLiteral([...buildVersionsGTE(versions)].map(([version, newer]) => typeProperty(version, unionType(newer.map(literalType)))), true)), {
35
+ description: "Maps each version to the set of versions that are greater than or equal to it.\nUsed by \u0060Versioned.minVersion()\u0060 to narrow which versions a handler must support.",
36
+ }),
37
+ typeAlias("VersionMap", typeReference("Partial", [
38
+ typeReference("Record", [
39
+ typeReference("Versions"),
40
+ ts.factory.createKeywordTypeNode(ts.SyntaxKind.ObjectKeyword),
41
+ ]),
42
+ ]), false),
43
+ withJsDoc(typeAlias("Versioned", ts.factory.createIntersectionTypeNode([
44
+ ts.factory.createIndexedAccessTypeNode(typeReference("T"), typeReference("V")),
45
+ typeLiteral([typeProperty("version", typeReference("V")), minVersion], true),
46
+ ]), true, [
47
+ ts.factory.createTypeParameterDeclaration(undefined, "T", typeReference("VersionMap")),
48
+ ts.factory.createTypeParameterDeclaration(undefined, "V", activeKeys(), activeKeys()),
49
+ ]), { description: VERSIONED_DESCRIPTION }),
50
+ ], ["This file is auto-generated by Counterfact. Do not edit."]);
82
51
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@counterfact/generator",
3
- "version": "0.1.5",
3
+ "version": "0.1.6",
4
4
  "description": "Generate Counterfact route scaffolds and OpenAPI-derived TypeScript contracts.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -52,10 +52,11 @@
52
52
  "test:packed-consumer": "node test/package/generator-consumer-smoke.mjs"
53
53
  },
54
54
  "dependencies": {
55
- "@counterfact/openapi": "0.1.5",
55
+ "@counterfact/openapi": "0.1.6",
56
56
  "@counterfact/types": "0.1.0",
57
57
  "chokidar": "5.0.0",
58
58
  "debug": "4.4.3",
59
- "prettier": "3.9.10"
59
+ "prettier": "3.9.10",
60
+ "typescript": "6.0.3"
60
61
  }
61
62
  }