oas-truth 0.6.1 → 0.7.1

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/README.md CHANGED
@@ -13,7 +13,8 @@ npm install oas-truth
13
13
  ```ts
14
14
  import { parseOpenAPI } from 'oas-truth'
15
15
 
16
- const result = await parseOpenAPI('openapi.yaml') // supports .json / .yaml / .tsp
16
+ // a .yaml / .yml / .json / .tsp file, or an http(s) URL
17
+ const result = await parseOpenAPI('openapi.yaml')
17
18
 
18
19
  if (result.ok) {
19
20
  result.value // resolved, typed OpenAPI document
@@ -24,9 +25,25 @@ if (result.ok) {
24
25
 
25
26
  `parseOpenAPI` does the following:
26
27
 
27
- - OpenAPI files (`.json` / `.yaml`) are bundled with `@apidevtools/swagger-parser` to resolve `$ref`
28
- - TypeSpec files (`.tsp`) are compiled with `@typespec/compiler` and then bundled
29
- - Returns `{ ok: true, value } | { ok: false, error }` (never throws)
28
+ - OpenAPI documents (`.json` / `.yaml` / `.yml` files and `http://` / `https://` URLs) are bundled
29
+ with `@apidevtools/swagger-parser` to resolve external `$ref`s
30
+ - TypeSpec files (`.tsp`) are compiled with `@typespec/compiler` and then bundled; the compiler is
31
+ loaded only for a `.tsp` input
32
+ - Returns a `Result<OpenAPI>`, `{ ok: true, value } | { ok: false, error }`, and never throws: an
33
+ unsupported input, a missing file, an unreachable URL and a TypeSpec diagnostic all come back as
34
+ `error`
35
+
36
+ The input is typed as `OpenAPIInput`. `isOpenAPIInput` narrows a CLI argument or a config value
37
+ to it:
38
+
39
+ ```ts
40
+ import { isOpenAPIInput, parseOpenAPI } from 'oas-truth'
41
+
42
+ const input = process.argv[2]
43
+ if (isOpenAPIInput(input)) {
44
+ const result = await parseOpenAPI(input)
45
+ }
46
+ ```
30
47
 
31
48
  ## Component schemas
32
49
 
@@ -35,12 +52,17 @@ dependency order. `makeSchemaDeclarations` returns the same declarations one by
35
52
  `varName`, `fileName`, `importLine`, `code`) so a host can split a file per schema.
36
53
 
37
54
  Recursive `$ref` cycles keep a helper type so the const can be annotated (`z.ZodType<NodeType>`,
38
- `v.GenericSchema<NodeType>`, `Schema.Codec<NodeType>`). That helper matches what the library
55
+ `v.GenericSchema<NodeType>`, `Schema.Codec<NodeType, unknown>`). The Effect annotation leaves the
56
+ encoded side free and the services `never`, so the declaration still decodes and passes to
57
+ `Schema.toStandardSchemaV1`. That helper matches what the library
39
58
  infers — `| undefined` on Valibot optionals, `readonly` arrays on Effect — so it
40
59
  type-checks under `exactOptionalPropertyTypes`. ArkType cycles become
41
60
  `scope({...}).export().Member`; that declaration's `importLine` is then
42
- `import { type, scope } from 'arktype'`. `schemaImportLine` is the same function
43
- `makeSchemasCode` uses when the declarations stay in one file.
61
+ `import { type, scope } from 'arktype'`. An Effect declaration's `importLine` names every
62
+ `effect` module its code uses (`Effect` for a decoding default, `SchemaTransformation` for an
63
+ int64 decode). A comment schema-truth puts above a declaration, such as TypeBox's marker for a
64
+ `not` it cannot enforce, is written above `export const`. `schemaImportLine` is the same
65
+ function `makeSchemasCode` uses when the declarations stay in one file.
44
66
 
45
67
  Every other component kind has the same split: `make<Kind>Declarations` returns `{ name,
46
68
  varName, fileName, code }` with no import line, and `make<Kind>Code` joins those bodies.
package/dist/index.d.ts CHANGED
@@ -1,12 +1,32 @@
1
- export declare function parseOpenAPI(input: string): Promise<{
1
+ /**
2
+ * The outcome of an operation that can fail: the value, or the reason it failed. The public
3
+ * API never throws; every failure is folded into `{ ok: false, error }`.
4
+ */
5
+ export type Result<T, E = string> = {
2
6
  readonly ok: true;
3
- readonly value: OpenAPI;
4
- readonly error?: never;
7
+ readonly value: T;
5
8
  } | {
6
- readonly value?: never;
7
9
  readonly ok: false;
8
- readonly error: string;
9
- }>;
10
+ readonly error: E;
11
+ };
12
+ /**
13
+ * A document `parseOpenAPI` reads: an OpenAPI file by its extension, a TypeSpec file, or an
14
+ * `http(s)` URL whatever its path (a document served without an extension is OpenAPI by
15
+ * content).
16
+ */
17
+ export type OpenAPIInput = `${string}.yaml` | `${string}.yml` | `${string}.json` | `${string}.tsp` | `http://${string}` | `https://${string}`;
18
+ /** Whether a value names a document `parseOpenAPI` reads, for narrowing a CLI or config value. */
19
+ export declare function isOpenAPIInput(value: unknown): value is OpenAPIInput;
20
+ /**
21
+ * Read an OpenAPI or TypeSpec document into a typed OpenAPI document.
22
+ *
23
+ * OpenAPI (a local `.yaml` / `.yml` / `.json` file or an `http(s)` URL) goes through
24
+ * swagger-parser's `bundle()`, which resolves external `$ref`s and keeps internal ones, so
25
+ * the code builders can emit schema variables instead of inline copies. A local `.tsp` file
26
+ * is compiled with `@typespec/compiler` and emitted with `@typespec/openapi3`, both loaded
27
+ * only for TypeSpec, then bundled the same way.
28
+ */
29
+ export declare function parseOpenAPI(input: OpenAPIInput): Promise<Result<OpenAPI>>;
10
30
  export type OpenAPI = {
11
31
  readonly openapi?: string;
12
32
  readonly $self?: string;
@@ -535,6 +555,21 @@ export type ToExpressionOptions = {
535
555
  export type RenderImportOptions = {
536
556
  readonly cyclic?: boolean;
537
557
  readonly exportTypes?: boolean;
558
+ /**
559
+ * The code the import line serves. Effect spreads its schema API over several modules
560
+ * (`Effect.succeed` for a decoding default, `SchemaTransformation` for an int64 decode),
561
+ * so its adapter imports each module this code names; the other libraries ignore it.
562
+ */
563
+ readonly code?: string;
564
+ };
565
+ /**
566
+ * An expression and the comment lines schema-truth wrote above its declaration, such as
567
+ * TypeBox's marker for a `not` it cannot enforce. A declaration builder writes them above
568
+ * `export const`; an inline `schema:` slot has nowhere to put them.
569
+ */
570
+ export type ExpressionParts = {
571
+ readonly expression: string;
572
+ readonly comments: readonly string[];
538
573
  };
539
574
  /**
540
575
  * How this library's inferred object type differs from a Zod-shaped
@@ -572,6 +607,11 @@ export type CyclicTypeStyle = {
572
607
  export type ComponentAdapter = {
573
608
  readonly renderImport: (options?: RenderImportOptions) => string;
574
609
  readonly toExpression: (schema: Schema, paramIn?: ParamIn, options?: ToExpressionOptions) => string;
610
+ /**
611
+ * `toExpression` with the comment lines schema-truth emits above the declaration. Every
612
+ * adapter `makeAdapter` returns has it; a host adapter without it gets no comments.
613
+ */
614
+ readonly toExpressionParts?: (schema: Schema, paramIn?: ParamIn, options?: ToExpressionOptions) => ExpressionParts;
575
615
  readonly renderTypeInfer: (constName: string) => string;
576
616
  readonly wrapSchema?: (expr: string, slot?: SchemaSlot) => string;
577
617
  readonly withRef?: (expr: string, ref: string) => string;
@@ -669,7 +709,7 @@ type SchemasOptions = {
669
709
  readonly typeAlias?: 'const' | 'key';
670
710
  /**
671
711
  * Shape of the TS7022 helper type. `'library'` (default) matches what the
672
- * validator infers, so `v.GenericSchema<Helper>` / `Schema.Codec<Helper>`
712
+ * validator infers, so `v.GenericSchema<Helper>` / `Schema.Codec<Helper, unknown>`
673
713
  * type-check under `exactOptionalPropertyTypes`. `'literal'` is the
674
714
  * Zod-shaped `prop?: T` form for every library.
675
715
  */
@@ -703,9 +743,10 @@ type SchemaDeclaration = {
703
743
  * The import line a schemas file needs. `cyclic` is true when this file (or
704
744
  * the bundled document) contains an Arktype `scope` / TypeBox container
705
745
  * cycle — split files that are only `scope({...}).export().Member` still
706
- * have to import `scope`.
746
+ * have to import `scope`. `code` is the code the line serves, so an Effect
747
+ * file imports every module it names.
707
748
  */
708
- export declare function schemaImportLine(adapter: ComponentAdapter, options?: SchemasOptions, cyclic?: boolean): string;
749
+ export declare function schemaImportLine(adapter: ComponentAdapter, options?: SchemasOptions, cyclic?: boolean, code?: string): string;
709
750
  /**
710
751
  * One `export const <X>Schema=...` declaration per `components.schemas` entry,
711
752
  * in dependency-first order. Only references inside a `$ref` cycle are lazy
package/dist/index.js CHANGED
@@ -1,28 +1,40 @@
1
1
  import path from "node:path";
2
2
  import SwaggerParser from "@apidevtools/swagger-parser";
3
- import { NodeHost, compile } from "@typespec/compiler";
4
- import { getOpenAPI3 } from "@typespec/openapi3";
5
3
  import { schemaToArktype } from "schema-truth/arktype";
6
4
  import { schemaToEffect } from "schema-truth/effect";
7
5
  import { schemaToTypebox } from "schema-truth/typebox";
8
6
  import { schemaToValibot } from "schema-truth/valibot";
9
7
  import { schemaToZod } from "schema-truth/zod";
10
8
  // src/openapi/index.ts
9
+ const INPUT_EXTENSIONS = [
10
+ ".yaml",
11
+ ".yml",
12
+ ".json",
13
+ ".tsp"
14
+ ];
15
+ /** Whether a value names a document `parseOpenAPI` reads, for narrowing a CLI or config value. */
16
+ function isOpenAPIInput(value) {
17
+ return typeof value === "string" && (isURL(value) || INPUT_EXTENSIONS.some((extension) => value.endsWith(extension)));
18
+ }
19
+ function isURL(value) {
20
+ return /^https?:\/\//iu.test(value);
21
+ }
22
+ /**
23
+ * Read an OpenAPI or TypeSpec document into a typed OpenAPI document.
24
+ *
25
+ * OpenAPI (a local `.yaml` / `.yml` / `.json` file or an `http(s)` URL) goes through
26
+ * swagger-parser's `bundle()`, which resolves external `$ref`s and keeps internal ones, so
27
+ * the code builders can emit schema variables instead of inline copies. A local `.tsp` file
28
+ * is compiled with `@typespec/compiler` and emitted with `@typespec/openapi3`, both loaded
29
+ * only for TypeSpec, then bundled the same way.
30
+ */
11
31
  async function parseOpenAPI(input) {
32
+ if (typeof input === "string" && !isOpenAPIInput(input)) return {
33
+ ok: false,
34
+ error: `Unsupported input: ${String(input)} (expected a .yaml, .yml, .json or .tsp file, or an http(s) URL)`
35
+ };
12
36
  try {
13
- if (typeof input === "string" && input.endsWith(".tsp")) {
14
- const program = await compile(NodeHost, path.resolve(input), { noEmit: true });
15
- if (program.diagnostics.length > 0) return {
16
- ok: false,
17
- error: `TypeSpec compile failed:\n${program.diagnostics.map((d) => d.message).join("\n")}`
18
- };
19
- const [record] = await getOpenAPI3(program);
20
- const tsp = "document" in record ? record.document : record.versions[0].document;
21
- return {
22
- ok: true,
23
- value: await SwaggerParser.bundle(tsp)
24
- };
25
- }
37
+ if (typeof input === "string" && input.endsWith(".tsp") && !isURL(input)) return await parseTypeSpec(input);
26
38
  return {
27
39
  ok: true,
28
40
  value: await SwaggerParser.bundle(input)
@@ -30,10 +42,38 @@ async function parseOpenAPI(input) {
30
42
  } catch (error) {
31
43
  return {
32
44
  ok: false,
33
- error: error instanceof Error ? error.message : String(error)
45
+ error: errorMessage(error)
34
46
  };
35
47
  }
36
48
  }
49
+ async function parseTypeSpec(input) {
50
+ const [{ compile, NodeHost }, { getOpenAPI3 }] = await Promise.all([import("@typespec/compiler"), import("@typespec/openapi3")]);
51
+ const program = await compile(NodeHost, path.resolve(input), { noEmit: true });
52
+ if (program.diagnostics.length > 0) return {
53
+ ok: false,
54
+ error: `TypeSpec compile failed:\n${program.diagnostics.map((d) => d.message).join("\n")}`
55
+ };
56
+ const [record] = await getOpenAPI3(program);
57
+ const document = record === void 0 ? void 0 : "document" in record ? record.document : record.versions[0]?.document;
58
+ if (document === void 0) return {
59
+ ok: false,
60
+ error: `TypeSpec emitted no OpenAPI document: ${input}`
61
+ };
62
+ return {
63
+ ok: true,
64
+ value: await SwaggerParser.bundle(document)
65
+ };
66
+ }
67
+ /**
68
+ * The message of a thrown value. swagger-parser reports some I/O failures (a URL that does
69
+ * not resolve, a missing file) with a message that ends before the reason and the reason in
70
+ * `ioErrorCode`; it is appended so the message says what went wrong.
71
+ */
72
+ function errorMessage(error) {
73
+ if (!(error instanceof Error)) return String(error);
74
+ const code = "ioErrorCode" in error ? error.ioErrorCode : void 0;
75
+ return (error.message.trim() === "" || error.message.trimEnd().endsWith(":")) && typeof code === "string" && code !== "" ? `${error.message.trimEnd()} ${code}`.trim() : error.message;
76
+ }
37
77
  // src/adapter/index.ts
38
78
  const PARAM_STYLES = [
39
79
  "matrix",
@@ -69,12 +109,42 @@ function wireOptions(paramIn, options) {
69
109
  ...options?.allowEmptyValue !== void 0 && { allowEmptyValue: options.allowEmptyValue }
70
110
  };
71
111
  }
72
- /** Pull the bare expression out of a `export const X = <expr>` wrapper, then strip cross-schema refs. */
73
- function extractExpr(code, stripRefs = (s) => s) {
74
- const joined = code.split("\n").filter((line) => !line.startsWith("import ")).join("\n").trim();
112
+ /**
113
+ * Pull the bare expression out of a `export const X = <expr>` wrapper, then strip
114
+ * cross-schema refs. The `//` comment lines above the declaration are returned apart, so a
115
+ * marker never lands between `=` and the expression.
116
+ */
117
+ function extractParts(code, stripRefs = (s) => s) {
118
+ const lines = code.split("\n").filter((line) => !line.startsWith("import "));
119
+ const firstCode = lines.findIndex((line) => line.trim() !== "" && !line.startsWith("//"));
120
+ const comments = (firstCode === -1 ? lines : lines.slice(0, firstCode)).filter((line) => line.startsWith("//"));
121
+ const joined = (firstCode === -1 ? [] : lines.slice(firstCode)).join("\n").trim();
75
122
  const expr = joined.match(/^export const \w+ = (.+)$/su)?.[1];
76
- if (expr !== void 0) return stripRefs(expr.replace(/;?\s*$/u, ""));
77
- return stripRefs(joined);
123
+ return {
124
+ expression: stripRefs(expr === void 0 ? joined : expr.replace(/;?\s*$/u, "")),
125
+ comments
126
+ };
127
+ }
128
+ /** An adapter's `toExpression` and `toExpressionParts` over one schema-truth call. */
129
+ function expressionMethods(generate, stripRefs) {
130
+ const toExpressionParts = (schema, paramIn, options) => extractParts(generate(schema, paramIn, options), stripRefs);
131
+ return {
132
+ toExpressionParts,
133
+ toExpression: (schema, paramIn, options) => toExpressionParts(schema, paramIn, options).expression
134
+ };
135
+ }
136
+ /**
137
+ * The `effect` modules `code` names, `Schema` always among them: the rule schema-truth's
138
+ * Effect CLI writes its import line by.
139
+ */
140
+ function effectModules(code) {
141
+ return [
142
+ .../(?<![\w.])Effect\./u.test(code) ? ["Effect"] : [],
143
+ "Schema",
144
+ .../(?<![\w.])SchemaGetter\./u.test(code) ? ["SchemaGetter"] : [],
145
+ .../(?<![\w.])SchemaIssue\./u.test(code) ? ["SchemaIssue"] : [],
146
+ .../(?<![\w.])SchemaTransformation\./u.test(code) ? ["SchemaTransformation"] : []
147
+ ];
78
148
  }
79
149
  /** One factory per library; the mapped type makes a missing library a compile error. */
80
150
  const ADAPTERS = {
@@ -111,14 +181,12 @@ function renderArktypeCyclic(varName, containerExpr, externals) {
111
181
  }
112
182
  function makeZodAdapter() {
113
183
  return {
114
- toExpression(schema, paramIn, options) {
115
- return extractExpr(schemaToZod(toJsonSchema(schema), {
116
- exportType: false,
117
- openapi: true,
118
- readonly: false,
119
- ...wireOptions(paramIn, options)
120
- }), stripZodLazy);
121
- },
184
+ ...expressionMethods((schema, paramIn, options) => schemaToZod(toJsonSchema(schema), {
185
+ exportType: false,
186
+ openapi: true,
187
+ readonly: false,
188
+ ...wireOptions(paramIn, options)
189
+ }), stripZodLazy),
122
190
  renderImport() {
123
191
  return "import * as z from 'zod'";
124
192
  },
@@ -138,14 +206,12 @@ function makeZodAdapter() {
138
206
  }
139
207
  function makeValibotAdapter() {
140
208
  return {
141
- toExpression(schema, paramIn, options) {
142
- return extractExpr(schemaToValibot(toJsonSchema(schema), {
143
- exportType: false,
144
- openapi: true,
145
- readonly: false,
146
- ...wireOptions(paramIn, options)
147
- }), stripValibotLazy);
148
- },
209
+ ...expressionMethods((schema, paramIn, options) => schemaToValibot(toJsonSchema(schema), {
210
+ exportType: false,
211
+ openapi: true,
212
+ readonly: false,
213
+ ...wireOptions(paramIn, options)
214
+ }), stripValibotLazy),
149
215
  renderImport() {
150
216
  return "import * as v from 'valibot'";
151
217
  },
@@ -166,14 +232,12 @@ function makeValibotAdapter() {
166
232
  }
167
233
  function makeArktypeAdapter() {
168
234
  return {
169
- toExpression(schema, paramIn, options) {
170
- return extractExpr(schemaToArktype(toJsonSchema(schema), {
171
- exportType: false,
172
- openapi: true,
173
- readonly: false,
174
- ...wireOptions(paramIn, options)
175
- }));
176
- },
235
+ ...expressionMethods((schema, paramIn, options) => schemaToArktype(toJsonSchema(schema), {
236
+ exportType: false,
237
+ openapi: true,
238
+ readonly: false,
239
+ ...wireOptions(paramIn, options)
240
+ })),
177
241
  renderImport(options) {
178
242
  return options?.cyclic === true ? "import { type, scope } from 'arktype'" : "import { type } from 'arktype'";
179
243
  },
@@ -189,15 +253,13 @@ function makeArktypeAdapter() {
189
253
  }
190
254
  function makeTypeboxAdapter() {
191
255
  return {
192
- toExpression(schema, paramIn, options) {
193
- return extractExpr(schemaToTypebox(toJsonSchema(schema), {
194
- exportType: false,
195
- openapi: true,
196
- readonly: false,
197
- ...wireOptions(paramIn, options),
198
- ...options?.ref !== void 0 && { ref: options.ref }
199
- }));
200
- },
256
+ ...expressionMethods((schema, paramIn, options) => schemaToTypebox(toJsonSchema(schema), {
257
+ exportType: false,
258
+ openapi: true,
259
+ readonly: false,
260
+ ...wireOptions(paramIn, options),
261
+ ...options?.ref !== void 0 && { ref: options.ref }
262
+ })),
201
263
  renderImport(options) {
202
264
  return options?.exportTypes === true ? "import { Type, type Static } from 'typebox'" : "import { Type } from 'typebox'";
203
265
  },
@@ -214,16 +276,14 @@ function makeTypeboxAdapter() {
214
276
  }
215
277
  function makeEffectAdapter() {
216
278
  return {
217
- toExpression(schema, paramIn, options) {
218
- return extractExpr(schemaToEffect(toJsonSchema(schema), {
219
- exportType: false,
220
- openapi: true,
221
- readonly: false,
222
- ...wireOptions(paramIn, options)
223
- }), stripEffectSuspend);
224
- },
225
- renderImport() {
226
- return "import { Schema } from 'effect'";
279
+ ...expressionMethods((schema, paramIn, options) => schemaToEffect(toJsonSchema(schema), {
280
+ exportType: false,
281
+ openapi: true,
282
+ readonly: false,
283
+ ...wireOptions(paramIn, options)
284
+ }), stripEffectSuspend),
285
+ renderImport(options) {
286
+ return `import { ${effectModules(options?.code ?? "").join(", ")} } from 'effect'`;
227
287
  },
228
288
  renderTypeInfer(constName) {
229
289
  return `export type ${constName}=Schema.Schema.Type<typeof ${constName}>`;
@@ -232,7 +292,7 @@ function makeEffectAdapter() {
232
292
  return `Schema.suspend(() => ${varName})`;
233
293
  },
234
294
  cyclicAnnotation(typeName) {
235
- return `Schema.Codec<${typeName}>`;
295
+ return `Schema.Codec<${typeName}, unknown>`;
236
296
  },
237
297
  cyclicTypeStyle: { readonlyArrays: true },
238
298
  reservedTypeNames: ["Schema", "Effect"],
@@ -402,13 +462,15 @@ function makeEntries(v, adapter, seen, path, options) {
402
462
  /**
403
463
  * Join declaration bodies the way `make<Kind>Code` already does: `;` between
404
464
  * entries, no `import ` line. `trailingNewline` matches examples / links /
405
- * security-schemes / parameters / headers.
465
+ * security-schemes / parameters / headers. `importLine` is the line itself, or
466
+ * built from the joined code, so it imports what the declarations name.
406
467
  */
407
468
  function joinDeclarations(declarations, options) {
408
469
  if (declarations.length === 0) return "";
409
470
  const body = declarations.map((d) => d.code).join(";");
410
471
  const text = options?.trailingNewline === true ? `${body}\n` : body;
411
- return options?.importLine === void 0 ? text : `${options.importLine}\n\n${text}`;
472
+ const importLine = typeof options?.importLine === "function" ? options.importLine(body) : options?.importLine;
473
+ return importLine === void 0 ? text : `${importLine}\n\n${text}`;
412
474
  }
413
475
  // src/generator/components/callbacks.ts
414
476
  function makeCallbacksDeclarations(components, adapter, options) {
@@ -475,7 +537,7 @@ function makeHeadersDeclarations(components, adapter, options) {
475
537
  function makeHeadersCode(components, adapter, exportTypes) {
476
538
  return joinDeclarations(makeHeadersDeclarations(components, adapter, exportTypes === true ? { exportTypes: true } : void 0), {
477
539
  trailingNewline: true,
478
- importLine: adapter.renderImport()
540
+ importLine: (code) => adapter.renderImport({ code })
479
541
  });
480
542
  }
481
543
  // src/generator/components/links.ts
@@ -520,7 +582,7 @@ function makeMediaTypesDeclarations(components, adapter, options) {
520
582
  function makeMediaTypesCode(components, adapter, exportTypes) {
521
583
  return joinDeclarations(makeMediaTypesDeclarations(components, adapter, exportTypes === true ? { exportTypes: true } : void 0), {
522
584
  trailingNewline: true,
523
- importLine: adapter.renderImport()
585
+ importLine: (code) => adapter.renderImport({ code })
524
586
  });
525
587
  }
526
588
  // src/generator/components/parameters.ts
@@ -549,7 +611,7 @@ function makeParametersDeclarations(components, adapter, options) {
549
611
  function makeParametersCode(components, adapter, exportTypes) {
550
612
  return joinDeclarations(makeParametersDeclarations(components, adapter, exportTypes === true ? { exportTypes: true } : void 0), {
551
613
  trailingNewline: true,
552
- importLine: adapter.renderImport()
614
+ importLine: (code) => adapter.renderImport({ code })
553
615
  });
554
616
  }
555
617
  // src/generator/components/path-items.ts
@@ -854,24 +916,32 @@ function makeCyclicContainer(varName, group, schemas, identifiers, adapter, ref)
854
916
  }
855
917
  return rewriteCollisionRef(node, identifiers);
856
918
  };
857
- const $defs = Object.fromEntries(group.map((name) => [`${groupIdentifiers.get(name)}Schema`, mapSchema(schemas[name] ?? {}, localize)]));
858
- return adapter.toExpression({
919
+ return expressionParts(adapter, {
859
920
  title: varName,
860
- $defs
861
- }, void 0, ref === void 0 ? void 0 : { ref });
921
+ $defs: Object.fromEntries(group.map((name) => [`${groupIdentifiers.get(name)}Schema`, mapSchema(schemas[name] ?? {}, localize)]))
922
+ }, ref === void 0 ? void 0 : { ref });
923
+ }
924
+ /** The adapter's expression for a declaration, with the comments to write above it. */
925
+ function expressionParts(adapter, schema, options) {
926
+ return adapter.toExpressionParts?.(schema, void 0, options) ?? {
927
+ expression: adapter.toExpression(schema, void 0, options),
928
+ comments: []
929
+ };
862
930
  }
863
931
  /**
864
932
  * The import line a schemas file needs. `cyclic` is true when this file (or
865
933
  * the bundled document) contains an Arktype `scope` / TypeBox container
866
934
  * cycle — split files that are only `scope({...}).export().Member` still
867
- * have to import `scope`.
935
+ * have to import `scope`. `code` is the code the line serves, so an Effect
936
+ * file imports every module it names.
868
937
  */
869
- function schemaImportLine(adapter, options, cyclic = false) {
938
+ function schemaImportLine(adapter, options, cyclic = false, code) {
870
939
  const exportTypes = options?.exportTypes === true;
871
- if (!cyclic && !exportTypes) return adapter.renderImport();
940
+ if (!cyclic && !exportTypes && code === void 0) return adapter.renderImport();
872
941
  return adapter.renderImport({
873
942
  ...cyclic && { cyclic: true },
874
- ...exportTypes && { exportTypes: true }
943
+ ...exportTypes && { exportTypes: true },
944
+ ...code !== void 0 && { code }
875
945
  });
876
946
  }
877
947
  function exportedTypeName(ident, varName, adapter, options) {
@@ -905,11 +975,15 @@ function makeSchemaDeclarations(schemas, adapter, options) {
905
975
  const hostRef = declarationRef ? name : void 0;
906
976
  const container = group && adapter.wrapLazy === void 0 ? makeCyclicContainer(varName, group, arktypeReadonly ? schemas : prepared, identifiers, adapter, adapter.withRef === void 0 ? hostRef : void 0) : void 0;
907
977
  const peers = group ?? [];
908
- const rendered = container === void 0 ? void 0 : adapter.renderCyclic?.(varName, container, [...new Set(peers.flatMap((peer) => collectSchemaRefs(schemas[peer])))].flatMap((ref) => peers.includes(ref) || !identifiers.has(ref) ? [] : [`${identifiers.get(ref)}Schema`])) ?? container;
909
- const expression = (rendered && arktypeReadonly ? `${rendered}.readonly()` : rendered) ?? adapter.toExpression({
978
+ const rendered = container === void 0 ? void 0 : adapter.renderCyclic?.(varName, container.expression, [...new Set(peers.flatMap((peer) => collectSchemaRefs(schemas[peer])))].flatMap((ref) => peers.includes(ref) || !identifiers.has(ref) ? [] : [`${identifiers.get(ref)}Schema`])) ?? container.expression;
979
+ const member = rendered && arktypeReadonly ? `${rendered}.readonly()` : rendered;
980
+ const parts = container === void 0 ? expressionParts(adapter, {
910
981
  ...schema,
911
982
  title: varName
912
- }, void 0, adapter.withRef === void 0 && hostRef !== void 0 ? { ref: hostRef } : void 0);
983
+ }, adapter.withRef === void 0 && hostRef !== void 0 ? { ref: hostRef } : void 0) : void 0;
984
+ const expression = member ?? parts?.expression ?? "";
985
+ const comments = container?.comments ?? parts?.comments;
986
+ const leading = comments && comments.length > 0 ? `${comments.join("\n")}\n` : "";
913
987
  const body = adapter.wrapLazy ? wrapReferences(expression, new Set((group ?? []).map((peer) => `${identifiers.get(peer)}Schema`)), adapter.wrapLazy) : expression;
914
988
  const value = options?.wrapDeclaration ? options.wrapDeclaration(body, name) : hostRef !== void 0 && adapter.withRef ? adapter.withRef(body, name) : body;
915
989
  const helper = group && adapter.cyclicAnnotation ? claimName(`${ident}Type`, taken) : void 0;
@@ -920,12 +994,13 @@ function makeSchemaDeclarations(schemas, adapter, options) {
920
994
  const annotation = annotationText === void 0 ? "" : `:${annotationText}`;
921
995
  const typeExport = options?.exportTypes === true ? `\n\nexport type ${exportedTypeName(ident, varName, adapter, options)}=${infer(varName)}` : "";
922
996
  const containerCycle = group !== void 0 && adapter.wrapLazy === void 0;
997
+ const code = `${typeDef}${leading}export const ${varName}${annotation}=${value}${typeExport}`;
923
998
  return {
924
999
  name,
925
1000
  varName,
926
1001
  fileName: declarationFileName(ident),
927
- importLine: schemaImportLine(adapter, options, containerCycle),
928
- code: `${typeDef}export const ${varName}${annotation}=${value}${typeExport}`
1002
+ importLine: schemaImportLine(adapter, options, containerCycle, code),
1003
+ code
929
1004
  };
930
1005
  });
931
1006
  }
@@ -938,7 +1013,9 @@ function makeSchemasCode(components, adapter, options) {
938
1013
  if (!schemas) return "";
939
1014
  const declarations = makeSchemaDeclarations(schemas, adapter, options);
940
1015
  if (declarations.length === 0) return "";
941
- return `${schemaImportLine(adapter, options, declarations.some((d) => d.importLine !== schemaImportLine(adapter, options)))}\n\n${declarations.map((d) => d.code).join(";")}\n`;
1016
+ const cyclic = declarations.some((d) => d.importLine !== schemaImportLine(adapter, options, false, d.code));
1017
+ const code = declarations.map((d) => d.code).join(";");
1018
+ return `${schemaImportLine(adapter, options, cyclic, code)}\n\n${code}\n`;
942
1019
  }
943
1020
  // src/generator/components/security-schemes.ts
944
1021
  function makeSecuritySchemesDeclarations(components, options) {
@@ -959,4 +1036,4 @@ function makeSecuritySchemesDeclarations(components, options) {
959
1036
  function makeSecuritySchemesCode(components, readonly) {
960
1037
  return joinDeclarations(makeSecuritySchemesDeclarations(components, { readonly }), { trailingNewline: true });
961
1038
  }
962
- export { declarationFileName, isParamStyle, isRecord, makeAdapter, makeCallbacksCode, makeCallbacksDeclarations, makeExamplesCode, makeExamplesDeclarations, makeHeadersCode, makeHeadersDeclarations, makeLinksCode, makeLinksDeclarations, makeMediaTypesCode, makeMediaTypesDeclarations, makeParametersCode, makeParametersDeclarations, makePathItemsCode, makePathItemsDeclarations, makeRequestBodiesCode, makeRequestBodiesDeclarations, makeResponsesCode, makeResponsesDeclarations, makeSafeKey, makeSchemaDeclarations, makeSchemaIdentifiers, makeSchemaReplacements, makeSchemaVarName, makeSchemasCode, makeSecuritySchemesCode, makeSecuritySchemesDeclarations, parseOpenAPI, schemaImportLine, schemaRefToName, toIdentifierPascalCase, toPascalCase, valueToCode };
1039
+ export { declarationFileName, isOpenAPIInput, isParamStyle, isRecord, makeAdapter, makeCallbacksCode, makeCallbacksDeclarations, makeExamplesCode, makeExamplesDeclarations, makeHeadersCode, makeHeadersDeclarations, makeLinksCode, makeLinksDeclarations, makeMediaTypesCode, makeMediaTypesDeclarations, makeParametersCode, makeParametersDeclarations, makePathItemsCode, makePathItemsDeclarations, makeRequestBodiesCode, makeRequestBodiesDeclarations, makeResponsesCode, makeResponsesDeclarations, makeSafeKey, makeSchemaDeclarations, makeSchemaIdentifiers, makeSchemaReplacements, makeSchemaVarName, makeSchemasCode, makeSecuritySchemesCode, makeSecuritySchemesDeclarations, parseOpenAPI, schemaImportLine, schemaRefToName, toIdentifierPascalCase, toPascalCase, valueToCode };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "oas-truth",
3
- "version": "0.6.1",
3
+ "version": "0.7.1",
4
4
  "description": "oas-truth is a parser from OpenAPI and TypeSpec to a typed OpenAPI document",
5
5
  "keywords": [
6
6
  "openapi",
@@ -32,7 +32,7 @@
32
32
  "provenance": true
33
33
  },
34
34
  "dependencies": {
35
- "schema-truth": "^0.8.4"
35
+ "schema-truth": "^0.8.5"
36
36
  },
37
37
  "devDependencies": {
38
38
  "@apidevtools/swagger-parser": "^13.1.0",