@counterfact/generator 0.1.4 → 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.
@@ -1,6 +1,15 @@
1
- import { printObjectWithoutQuotes } from "./printers.js";
2
- import { ResponseTypeCoder } from "./response-type-coder.js";
1
+ import ts from "typescript";
2
+ import { typeLiteral, typeReference, unionType } from "./ast.js";
3
3
  import { TypeCoder } from "./type-coder.js";
4
+ import { ResponseTypeCoder } from "./response-type-coder.js";
5
+ function statusName(status) {
6
+ return /^\d+$/u.test(status)
7
+ ? ts.factory.createNumericLiteral(status)
8
+ : ts.factory.createStringLiteral(status);
9
+ }
10
+ function statusLiteral(status) {
11
+ return ts.factory.createLiteralTypeNode(statusName(status));
12
+ }
4
13
  export class ResponsesTypeCoder extends TypeCoder {
5
14
  openApi2MediaTypes;
6
15
  constructor(requirement, version = "", openApi2MediaTypes = []) {
@@ -8,36 +17,40 @@ export class ResponsesTypeCoder extends TypeCoder {
8
17
  this.openApi2MediaTypes = openApi2MediaTypes;
9
18
  }
10
19
  typeForDefaultStatusCode(listedStatusCodes) {
11
- const definedStatusCodes = listedStatusCodes.filter((key) => key !== "default");
12
- if (definedStatusCodes.length === 0) {
13
- return "[statusCode in HttpStatusCode]";
14
- }
15
- return `[statusCode in Exclude<HttpStatusCode, ${definedStatusCodes.join(" | ")}>]`;
16
- }
17
- normalizeStatusCode(statusCode) {
18
- if (statusCode === "default") {
19
- return this.typeForDefaultStatusCode(Object.keys(this.requirement.data));
20
- }
21
- return statusCode;
20
+ const defined = listedStatusCodes.filter((key) => key !== "default");
21
+ const status = typeReference("HttpStatusCode");
22
+ return defined.length === 0
23
+ ? status
24
+ : typeReference("Exclude", [
25
+ status,
26
+ unionType(defined.map(statusLiteral)),
27
+ ]);
22
28
  }
23
29
  buildResponseObjectType(script) {
24
- const entries = this.requirement.map((response, responseCode) => [
25
- this.normalizeStatusCode(responseCode),
26
- new ResponseTypeCoder(response, this.version, this.openApi2MediaTypes).write(script),
27
- ]);
28
- const explicitEntries = entries.filter(([key]) => !key.startsWith("["));
29
- const mappedEntries = entries.filter(([key]) => key.startsWith("["));
30
- if (explicitEntries.length > 0 && mappedEntries.length > 0) {
31
- return `${printObjectWithoutQuotes(explicitEntries)} & ${printObjectWithoutQuotes(mappedEntries)}`;
32
- }
33
- return printObjectWithoutQuotes(entries);
30
+ const members = [];
31
+ let fallback;
32
+ this.requirement.forEach((response, code) => {
33
+ const type = new ResponseTypeCoder(response, this.version, this.openApi2MediaTypes).write(script);
34
+ if (code === "default") {
35
+ fallback = ts.factory.createMappedTypeNode(undefined, ts.factory.createTypeParameterDeclaration(undefined, "statusCode", this.typeForDefaultStatusCode(Object.keys(this.requirement.data))), undefined, undefined, type, undefined);
36
+ }
37
+ else {
38
+ members.push(ts.factory.createPropertySignature(undefined, statusName(code), undefined, type));
39
+ }
40
+ });
41
+ const explicit = typeLiteral(members, true);
42
+ return fallback
43
+ ? members.length > 0
44
+ ? ts.factory.createIntersectionTypeNode([explicit, fallback])
45
+ : fallback
46
+ : explicit;
34
47
  }
35
48
  writeCode(script) {
36
49
  script.importSharedType("ResponseBuilderFactory");
37
- const text = `ResponseBuilderFactory<${this.buildResponseObjectType(script)}>`;
38
- if (text.includes("HttpStatusCode")) {
50
+ const type = this.buildResponseObjectType(script);
51
+ if (this.requirement.has("default")) {
39
52
  script.importSharedType("HttpStatusCode");
40
53
  }
41
- return text;
54
+ return typeReference("ResponseBuilderFactory", [type]);
42
55
  }
43
56
  }
@@ -3,6 +3,8 @@ import fs from "node:fs/promises";
3
3
  import nodePath from "node:path";
4
4
  /* eslint-disable security/detect-non-literal-fs-filename -- scenario files are discovered and generated under the configured destination tree. */
5
5
  import { watch } from "chokidar";
6
+ import ts from "typescript";
7
+ import { exportedConst, formatStatements, functionType, importDeclaration, literalType, parameter, readonlyProperty, stringType, typeAlias, typeReference, unionType, unknownType, valueExpression, withJsDoc, } from "./ast.js";
6
8
  import { pathRelative } from "./forward-slash-path.js";
7
9
  import { waitForEvent } from "./wait-for-event.js";
8
10
  import { CHOKIDAR_OPTIONS } from "./watch-options.js";
@@ -15,6 +17,18 @@ async function collectContextFiles(destination) {
15
17
  }
16
18
  await walkForContextFiles(routesDir, routesDir, results);
17
19
  results.sort((a, b) => b.depth - a.depth);
20
+ const names = new Set();
21
+ for (const context of results) {
22
+ const base = /^\d/u.test(context.alias)
23
+ ? "_" + context.alias
24
+ : context.alias;
25
+ let name = base;
26
+ let suffix = 2;
27
+ while (names.has(name))
28
+ name = base + suffix++;
29
+ context.alias = name;
30
+ names.add(name);
31
+ }
18
32
  return results;
19
33
  }
20
34
  async function walkForContextFiles(routesDir, currentDir, results) {
@@ -84,90 +98,94 @@ function routePathToAlias(routePath) {
84
98
  .join("") + "Context");
85
99
  }
86
100
  const PARAM_SEGMENT_REGEX = /^\{.+\}$/u;
87
- function buildLoadContextOverload(routePath, alias) {
88
- if (routePath === "/") {
89
- return ' loadContext(path: "/" | `/${string}`): ' + alias + ";";
90
- }
91
- const segments = routePath.split("/").filter(Boolean);
92
- const hasParam = segments.some((seg) => PARAM_SEGMENT_REGEX.test(seg));
93
- if (!hasParam) {
94
- return ` loadContext(path: "${routePath}" | \`${routePath}/\${string}\`): ${alias};`;
101
+ function pathTemplate(parts) {
102
+ const fragments = [""];
103
+ const placeholders = [];
104
+ for (const part of parts) {
105
+ fragments[fragments.length - 1] += "/";
106
+ if (PARAM_SEGMENT_REGEX.test(part)) {
107
+ placeholders.push(stringType());
108
+ fragments.push("");
109
+ }
110
+ else {
111
+ fragments[fragments.length - 1] += part;
112
+ }
95
113
  }
96
- const templatePath = `/${segments
97
- .map((seg) => (PARAM_SEGMENT_REGEX.test(seg) ? "${string}" : seg))
98
- .join("/")}`;
99
- return ` loadContext(path: \`${templatePath}\`): ${alias};`;
114
+ return ts.factory.createTemplateLiteralType(ts.factory.createTemplateHead(fragments[0]), placeholders.map((type, index) => ts.factory.createTemplateLiteralTypeSpan(type, index === placeholders.length - 1
115
+ ? ts.factory.createTemplateTail(fragments[index + 1])
116
+ : ts.factory.createTemplateMiddle(fragments[index + 1]))));
100
117
  }
101
- function buildScenarioContextContent(contextFiles, storeImportPath) {
102
- const rootContext = contextFiles.find((f) => f.routePath === "/");
103
- const contextType = rootContext
104
- ? rootContext.alias
105
- : "Record<string, unknown>";
106
- const importLines = contextFiles.map(({ importPath, alias }) => alias === "Context"
107
- ? `import type { Context } from "${importPath}";`
108
- : `import type { Context as ${alias} } from "${importPath}";`);
109
- if (storeImportPath !== undefined) {
110
- importLines.push(`import type { Store } from "${storeImportPath}";`);
111
- }
112
- const overloadLines = contextFiles.map(({ alias, routePath }) => buildLoadContextOverload(routePath, alias));
113
- const parts = [
114
- GENERATED_FILE_COMMENT,
115
- ...importLines,
116
- "",
117
- "interface LoadContextDefinitions {",
118
- " /* code generator adds additional signatures here */",
119
- ...overloadLines,
120
- " loadContext(path: string): Record<string, unknown>;",
121
- "}",
122
- "",
123
- "export interface Scenario$ {",
124
- ' /** Root context, same as loadContext("/") */',
125
- ` readonly context: ${contextType};`,
126
- ' readonly loadContext: LoadContextDefinitions["loadContext"];',
127
- " /** Named route builders stored in the REPL execution context */",
128
- " readonly routes: Record<string, unknown>;",
129
- " /** Create a new route builder for a given path */",
130
- " readonly route: (path: string) => unknown;",
131
- "}",
132
- "",
133
- "/** A scenario function that receives the live REPL environment */",
134
- "export type Scenario = ($: Scenario$) => Promise<void> | void;",
135
- "",
136
- "/** Interface for Context objects defined in _.context.ts files */",
137
- "export interface Context$ {",
138
- ...(storeImportPath === undefined
139
- ? []
140
- : [
141
- " /** Application-level store shared by every API group */",
142
- " readonly store: Store;",
118
+ function buildLoadContextOverload(routePath, alias) {
119
+ const segments = routePath.split("/").filter(Boolean);
120
+ const path = segments.some((segment) => PARAM_SEGMENT_REGEX.test(segment))
121
+ ? pathTemplate(segments)
122
+ : unionType([
123
+ literalType(routePath),
124
+ ts.factory.createTemplateLiteralType(ts.factory.createTemplateHead(routePath === "/" ? "/" : routePath + "/"), [
125
+ ts.factory.createTemplateLiteralTypeSpan(stringType(), ts.factory.createTemplateTail("")),
143
126
  ]),
144
- " /** Load a context object for a specific path */",
145
- ' readonly loadContext: LoadContextDefinitions["loadContext"];',
146
- " /** Load a JSON file relative to this file's path */",
147
- " readonly readJson: (relativePath: string) => Promise<unknown>;",
148
- "}",
149
- "",
150
- ];
151
- return parts.join("\n");
127
+ ]);
128
+ return ts.factory.createMethodSignature(undefined, "loadContext", undefined, undefined, [parameter("path", path)], typeReference(alias));
129
+ }
130
+ function recordType() {
131
+ return typeReference("Record", [stringType(), unknownType()]);
132
+ }
133
+ function interfaceDeclaration(name, members, exported) {
134
+ return ts.factory.createInterfaceDeclaration(exported
135
+ ? [ts.factory.createModifier(ts.SyntaxKind.ExportKeyword)]
136
+ : undefined, name, undefined, undefined, members);
137
+ }
138
+ async function buildScenarioContextContent(contextFiles, storeImportPath) {
139
+ const rootContext = contextFiles.find((file) => file.routePath === "/");
140
+ const imports = contextFiles.map(({ importPath, alias }) => importDeclaration(alias, importPath, true, false, "Context"));
141
+ if (storeImportPath !== undefined)
142
+ imports.push(importDeclaration("Store", storeImportPath, true));
143
+ const loadContext = () => ts.factory.createIndexedAccessTypeNode(typeReference("LoadContextDefinitions"), literalType("loadContext"));
144
+ const voidType = () => ts.factory.createKeywordTypeNode(ts.SyntaxKind.VoidKeyword);
145
+ const overloads = contextFiles.map(({ alias, routePath }) => buildLoadContextOverload(routePath, alias));
146
+ const fallback = ts.factory.createMethodSignature(undefined, "loadContext", undefined, undefined, [parameter("path", stringType())], recordType());
147
+ return formatStatements([
148
+ ...imports,
149
+ interfaceDeclaration("LoadContextDefinitions", [...overloads, fallback], false),
150
+ interfaceDeclaration("Scenario$", [
151
+ readonlyProperty("context", rootContext ? typeReference(rootContext.alias) : recordType(), 'Root context, same as loadContext("/")'),
152
+ readonlyProperty("loadContext", loadContext(), "Load a context object for a specific path"),
153
+ readonlyProperty("routes", recordType(), "Named route builders stored in the REPL execution context"),
154
+ readonlyProperty("route", functionType([parameter("path", stringType())], unknownType()), "Create a new route builder for a given path"),
155
+ ], true),
156
+ withJsDoc(typeAlias("Scenario", functionType([parameter("$", typeReference("Scenario$"))], unionType([typeReference("Promise", [voidType()]), voidType()]))), {
157
+ description: "A scenario function that receives the live REPL environment",
158
+ }),
159
+ withJsDoc(interfaceDeclaration("Context$", [
160
+ ...(storeImportPath === undefined
161
+ ? []
162
+ : [
163
+ readonlyProperty("store", typeReference("Store"), "Application-level store shared by every API group"),
164
+ ]),
165
+ readonlyProperty("loadContext", loadContext(), "Load a context object for a specific path"),
166
+ readonlyProperty("readJson", functionType([parameter("relativePath", stringType())], typeReference("Promise", [unknownType()])), "Load a JSON file relative to this file's path"),
167
+ ], true), {
168
+ description: "Interface for Context objects defined in _.context.ts files",
169
+ }),
170
+ ], [GENERATED_FILE_COMMENT.slice(3)]);
152
171
  }
153
172
  function ensureRelativeImportPath(path) {
154
- return path.startsWith(".") ? path : `./${path}`;
173
+ return path.startsWith(".") ? path : "./" + path;
155
174
  }
156
- function buildMiddlewareTypeContent(destination, routeDirectory) {
157
- const typesDirectory = nodePath.join(destination, "types", routeDirectory.relativePath);
158
- const sharedTypePath = ensureRelativeImportPath(pathRelative(typesDirectory, nodePath.join(destination, "counterfact-types", "index.js")));
159
- const lines = [
160
- GENERATED_FILE_COMMENT,
161
- `import type { Middleware as MiddlewareFunction } from "${sharedTypePath}";`,
175
+ async function buildMiddlewareTypeContent(destination, routeDirectory) {
176
+ const directory = nodePath.join(destination, "types", routeDirectory.relativePath);
177
+ const sharedPath = ensureRelativeImportPath(pathRelative(directory, nodePath.join(destination, "counterfact-types", "index.js")));
178
+ const statements = [
179
+ importDeclaration("MiddlewareFunction", sharedPath, true, false, "Middleware"),
162
180
  ];
163
- if (routeDirectory.contextFile === undefined) {
164
- lines.push("", "export type Middleware = MiddlewareFunction;");
181
+ const arguments_ = [];
182
+ if (routeDirectory.contextFile !== undefined) {
183
+ const contextPath = ensureRelativeImportPath(pathRelative(directory, routeDirectory.contextFile).replace(/\.ts$/u, ".js"));
184
+ statements.push(importDeclaration("Context", contextPath, true));
185
+ arguments_.push(typeReference("Context"));
165
186
  }
166
- else {
167
- const contextImportPath = ensureRelativeImportPath(pathRelative(typesDirectory, routeDirectory.contextFile).replace(/\.ts$/u, ".js"));
168
- lines.push(`import type { Context } from "${contextImportPath}";`, "", "export type Middleware = MiddlewareFunction<Context>;");
169
- }
170
- return `${lines.join("\n")}\n`;
187
+ statements.push(typeAlias("Middleware", typeReference("MiddlewareFunction", arguments_)));
188
+ return formatStatements(statements, [GENERATED_FILE_COMMENT.slice(3)]);
171
189
  }
172
190
  async function collectGeneratedMiddlewareTypeFiles(directory) {
173
191
  let entries;
@@ -199,7 +217,7 @@ async function writeMiddlewareTypes(destination) {
199
217
  const filePath = nodePath.join(destination, "types", routeDirectory.relativePath, "_.middleware.ts");
200
218
  expectedFiles.add(nodePath.resolve(filePath));
201
219
  await fs.mkdir(nodePath.dirname(filePath), { recursive: true });
202
- await fs.writeFile(filePath, buildMiddlewareTypeContent(destination, routeDirectory), "utf8");
220
+ await fs.writeFile(filePath, await buildMiddlewareTypeContent(destination, routeDirectory), "utf8");
203
221
  }
204
222
  const generatedFiles = await collectGeneratedMiddlewareTypeFiles(nodePath.join(destination, "types"));
205
223
  await Promise.all(generatedFiles
@@ -226,65 +244,50 @@ async function writeScenarioContextType(destination, rootDestination) {
226
244
  const storeImportPath = existsSync(storePath)
227
245
  ? `${relativeStorePath.startsWith(".") ? "" : "./"}${relativeStorePath.replace(/\.ts$/u, ".js")}`
228
246
  : undefined;
229
- const content = buildScenarioContextContent(contextFiles, storeImportPath);
247
+ const content = await buildScenarioContextContent(contextFiles, storeImportPath);
230
248
  await fs.mkdir(typesDir, { recursive: true });
231
249
  await fs.writeFile(filePath, content, "utf8");
232
250
  }
233
- const DEFAULT_SCENARIOS_INDEX = `import type { Scenario } from "../types/_.context.js";
234
-
235
- /**
236
- * Scenario scripts are plain TypeScript functions that receive the live REPL
237
- * environment and can read or mutate server state. Run them from the REPL with:
238
- * .scenario <functionName>
239
- */
240
-
241
- /**
242
- * Read or mutate the root context (same object routes see as $.context):
243
- * $.context.<property> = <value>;
244
- *
245
- * Load a context for a specific path:
246
- * const petsCtx = $.loadContext("/pets");
247
- *
248
- * Store a pre-configured route builder for later use in the REPL:
249
- * $.routes.myRequest = $.route("/pets").method("get");
250
- */
251
-
252
- /**
253
- * startup() runs automatically when the server initializes, right before the
254
- * REPL starts. Use it to seed dummy data so the server is ready to use
255
- * immediately. It receives the same $ argument as all other scenario functions.
256
- *
257
- * Tip: delegate to other scenario functions and pass $ along so each function
258
- * stays focused on a single concern. You can also pass additional arguments to
259
- * configure them, e.g. addPets($, 20, "dog").
260
- *
261
- * If you don't need a startup scenario, delete this function or leave it empty.
262
- */
263
- export const startup: Scenario = ($) => {
264
- void $;
265
- };
266
-
267
- /**
268
- * An example scenario. To use it in the REPL, type:
269
- * .scenario help
270
- */
271
- export const help: Scenario = ($) => {
272
- void $;
273
-
274
- console.log(
275
- [
276
- "Scenarios are functions that populate the context object",
277
- "and / or the REPL environment. They are intended to",
278
- "populate your environment with specific data and",
279
- "configurations for testing purposes.",
280
- ].join("\\n"),
281
- );
282
-
283
- console.log(
284
- "\\nScenarios (including this one) are defined in the ./scenarios directory.",
285
- );
286
- };
287
- `;
251
+ async function defaultScenariosContent() {
252
+ const arrow = (statements) => ts.factory.createArrowFunction(undefined, undefined, [parameter("$")], undefined, ts.factory.createToken(ts.SyntaxKind.EqualsGreaterThanToken), ts.factory.createBlock(statements, true));
253
+ const ignoreArgument = () => ts.factory.createExpressionStatement(ts.factory.createVoidExpression(ts.factory.createIdentifier("$")));
254
+ const log = (expression) => ts.factory.createExpressionStatement(ts.factory.createCallExpression(ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier("console"), "log"), undefined, [expression]));
255
+ const lines = valueExpression([
256
+ "Scenarios are functions that populate the context object",
257
+ "and / or the REPL environment. They are intended to",
258
+ "populate your environment with specific data and",
259
+ "configurations for testing purposes.",
260
+ ]);
261
+ const joinedLines = ts.factory.createCallExpression(ts.factory.createPropertyAccessExpression(lines, "join"), undefined, [valueExpression("\n")]);
262
+ return formatStatements([
263
+ importDeclaration("Scenario", "../types/_.context.js", true),
264
+ withJsDoc(exportedConst("startup", arrow([ignoreArgument()]), typeReference("Scenario")), {
265
+ description: "Scenario scripts are plain TypeScript functions that receive the live REPL\n" +
266
+ "environment and can read or mutate server state. Run them from the REPL with:\n" +
267
+ " .scenario <functionName>\n\n" +
268
+ "Read or mutate the root context (same object routes see as $.context):\n" +
269
+ " $.context.<property> = <value>;\n\n" +
270
+ "Load a context for a specific path:\n" +
271
+ ' const petsCtx = $.loadContext("/pets");\n\n' +
272
+ "Store a pre-configured route builder for later use in the REPL:\n" +
273
+ ' $.routes.myRequest = $.route("/pets").method("get");\n\n' +
274
+ "startup() runs automatically when the server initializes, right before the\n" +
275
+ "REPL starts. Use it to seed dummy data so the server is ready to use\n" +
276
+ "immediately. It receives the same $ argument as all other scenario functions.\n\n" +
277
+ "Tip: delegate to other scenario functions and pass $ along so each function\n" +
278
+ "stays focused on a single concern. You can also pass additional arguments to\n" +
279
+ 'configure them, e.g. addPets($, 20, "dog").\n\n' +
280
+ "If you don't need a startup scenario, delete this function or leave it empty.",
281
+ }),
282
+ withJsDoc(exportedConst("help", arrow([
283
+ ignoreArgument(),
284
+ log(joinedLines),
285
+ log(valueExpression("\nScenarios (including this one) are defined in the ./scenarios directory.")),
286
+ ]), typeReference("Scenario")), {
287
+ description: "An example scenario. To use it in the REPL, type:\n .scenario help",
288
+ }),
289
+ ]);
290
+ }
288
291
  async function writeDefaultScenariosIndex(destination) {
289
292
  const scenariosDir = nodePath.join(destination, "scenarios");
290
293
  const filePath = nodePath.join(scenariosDir, "index.ts");
@@ -292,7 +295,7 @@ async function writeDefaultScenariosIndex(destination) {
292
295
  return;
293
296
  }
294
297
  await fs.mkdir(scenariosDir, { recursive: true });
295
- await fs.writeFile(filePath, DEFAULT_SCENARIOS_INDEX, "utf8");
298
+ await fs.writeFile(filePath, await defaultScenariosContent(), "utf8");
296
299
  }
297
300
  /**
298
301
  * Encapsulates the generation of scenario-related files:
@@ -1,10 +1,12 @@
1
+ import ts from "typescript";
1
2
  import { Coder } from "./coder.js";
2
3
  import type { Script } from "./script.js";
3
4
  export declare class SchemaCoder extends Coder {
4
5
  names(): Generator<string>;
5
- objectSchema(script: Script): string;
6
- arraySchema(script: Script): string;
7
- typeDeclaration(_namespace: Map<string, unknown> | undefined, script: Script): string;
6
+ objectSchema(script: Script): ts.Expression;
7
+ arraySchema(script: Script): ts.Expression;
8
+ typeDeclaration(_namespace: Map<string, unknown> | undefined, script: Script): ts.TypeNode;
8
9
  modulePath(): string;
9
- writeCode(script: Script): string;
10
+ write(script: Script): ts.Expression;
11
+ writeCode(script: Script): ts.Expression;
10
12
  }
@@ -1,6 +1,7 @@
1
+ import ts from "typescript";
2
+ import { objectExpression, typeReference, valueExpression } from "./ast.js";
1
3
  import { Coder } from "./coder.js";
2
4
  function scrubSchema(schema) {
3
- // remove properties that are not valid in JSON Schema 6 and not useful anyway
4
5
  const cleaned = { ...schema };
5
6
  delete cleaned["example"];
6
7
  delete cleaned["xml"];
@@ -12,38 +13,46 @@ export class SchemaCoder extends Coder {
12
13
  }
13
14
  objectSchema(script) {
14
15
  const { properties, required } = this.requirement.data;
15
- const propertyLines = Object.keys(properties ?? {}).map((name) => {
16
- const schemaCoder = new SchemaCoder(this.requirement.select(`properties/${name}`), this.version);
17
- return `"${name}": ${schemaCoder.write(script)}`;
18
- });
19
- return `
20
- {
21
- type: "object",
22
- required: ${JSON.stringify(required ?? [])},
23
- properties: { ${propertyLines.join(", ")} }
24
- }
25
- `;
16
+ return objectExpression([
17
+ ["type", valueExpression("object")],
18
+ ["required", valueExpression(required ?? [])],
19
+ [
20
+ "properties",
21
+ objectExpression(Object.keys(properties ?? {}).map((name) => [
22
+ name,
23
+ new SchemaCoder(this.requirement.get("properties").get(name), this.version).write(script),
24
+ ])),
25
+ ],
26
+ ], true);
26
27
  }
27
28
  arraySchema(script) {
28
- return `{
29
- type: "array",
30
- items: ${new SchemaCoder(this.requirement.get("items"), this.version).write(script)}
31
- }`;
29
+ return objectExpression([
30
+ ["type", valueExpression("array")],
31
+ [
32
+ "items",
33
+ new SchemaCoder(this.requirement.get("items"), this.version).write(script),
34
+ ],
35
+ ], true);
32
36
  }
33
37
  typeDeclaration(_namespace, script) {
34
- return script.importExternalType("JSONSchema6", "json-schema");
38
+ return typeReference(script.importExternalType("JSONSchema6", "json-schema"));
35
39
  }
36
40
  modulePath() {
37
41
  return `types/${this.requirement.refUrl}.ts`;
38
42
  }
43
+ write(script) {
44
+ if (this.requirement.isReference) {
45
+ // Runtime schemas refer to value exports, rather than type imports.
46
+ return ts.factory.createIdentifier(script.import(this));
47
+ }
48
+ return this.writeCode(script);
49
+ }
39
50
  writeCode(script) {
40
51
  const { type } = this.requirement.data;
41
- if (type === "object") {
52
+ if (type === "object")
42
53
  return this.objectSchema(script);
43
- }
44
- if (type === "array") {
54
+ if (type === "array")
45
55
  return this.arraySchema(script);
46
- }
47
- return JSON.stringify(scrubSchema(this.requirement.data));
56
+ return valueExpression(scrubSchema(this.requirement.data));
48
57
  }
49
58
  }
@@ -1,20 +1,21 @@
1
+ import ts from "typescript";
1
2
  import { TypeCoder } from "./type-coder.js";
2
3
  import { Requirement } from "./requirement.js";
3
4
  import type { Script } from "./script.js";
4
5
  export declare class SchemaTypeCoder extends TypeCoder {
5
6
  names(): Generator<string>;
6
7
  jsdoc(): string;
7
- additionalPropertiesType(script: Script): string;
8
- objectSchema(script: Script): string;
9
- arraySchema(script: Script): string;
10
- writePrimitive(value: unknown): string;
11
- writeType(script: Script, type: unknown): string;
8
+ additionalPropertiesType(script: Script): ts.TypeNode;
9
+ objectSchema(script: Script): ts.TypeNode;
10
+ arraySchema(script: Script): ts.TypeNode;
11
+ writePrimitive(value: unknown): ts.TypeNode;
12
+ writeType(script: Script, type: unknown): ts.TypeNode;
12
13
  writeGroup(script: Script, { allOf, anyOf, oneOf, }: {
13
14
  allOf?: unknown[];
14
15
  anyOf?: unknown[];
15
16
  oneOf?: unknown[];
16
- }): string;
17
- writeEnum(_script: Script, requirement: Requirement): string;
17
+ }): ts.TypeNode;
18
+ writeEnum(requirement: Requirement): ts.TypeNode;
18
19
  modulePath(): string;
19
- writeCode(script: Script): string;
20
+ writeCode(script: Script): ts.TypeNode;
20
21
  }