@drzl/cli 4.16.0 → 4.17.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.
@@ -0,0 +1,603 @@
1
+ // ../generator-json-schema/dist/index.js
2
+ import {
3
+ formatCode,
4
+ moduleFileName,
5
+ moduleSpecifier,
6
+ resolveAffix,
7
+ schemaName,
8
+ typeName
9
+ } from "@drzl/validation-core";
10
+ import {
11
+ COLUMN_FORMATS,
12
+ insertColumns,
13
+ isIntegerColumn,
14
+ parseCheck,
15
+ selectColumns,
16
+ updateColumns
17
+ } from "@drzl/validation-core";
18
+ var DRAFT = "https://json-schema.org/draft/2020-12/schema";
19
+ var UUID_FORMAT = "uuid";
20
+ var base64 = (target) => target === "openapi-3.0" ? { type: "string", format: "byte" } : { type: "string", contentEncoding: "base64" };
21
+ function baseSchema(c, mode, target, checks, sets, lengths) {
22
+ const s = c.shape;
23
+ if (s) {
24
+ switch (s.kind) {
25
+ case "json":
26
+ return {};
27
+ case "custom":
28
+ return {};
29
+ case "buffer":
30
+ return base64(target);
31
+ case "tuple":
32
+ return target === "openapi-3.0" ? { type: "array", items: { type: "number" }, minItems: s.length, maxItems: s.length } : {
33
+ type: "array",
34
+ prefixItems: Array.from({ length: s.length }, () => ({ type: "number" })),
35
+ minItems: s.length,
36
+ maxItems: s.length
37
+ };
38
+ case "numberObject":
39
+ return {
40
+ type: "object",
41
+ properties: Object.fromEntries(s.fields.map((f) => [f, { type: "number" }])),
42
+ required: [...s.fields]
43
+ };
44
+ case "numberVector":
45
+ return {
46
+ type: "array",
47
+ items: { type: "number" },
48
+ ...s.length ? { minItems: s.length, maxItems: s.length } : {}
49
+ };
50
+ case "bitstring":
51
+ return {
52
+ type: "string",
53
+ pattern: "^[01]*$",
54
+ ...s.length ? s.exact ? { minLength: s.length, maxLength: s.length } : { maxLength: s.length } : {}
55
+ };
56
+ case "byteString":
57
+ return { type: "string", ...s.length ? { maxLength: s.length } : {} };
58
+ }
59
+ }
60
+ const set = sets.find((x) => x.column === c.name);
61
+ if (set) return { enum: set.values.map((v) => set.kind === "string" ? v : Number(v)) };
62
+ if (c.enumValues && c.enumValues.length) return { enum: [...c.enumValues] };
63
+ const mine = c.arrayDimensions ? [] : checks.filter((k) => k.column === c.name);
64
+ const eq = mine.find((k) => k.operator === "=");
65
+ if (eq) {
66
+ const only = eq.kind === "string" ? eq.value : Number(eq.value);
67
+ return target === "openapi-3.0" ? { enum: [only] } : { const: only };
68
+ }
69
+ switch (c.tsType) {
70
+ case "string": {
71
+ const out = { type: "string" };
72
+ if (c.format === "uuid") out.format = UUID_FORMAT;
73
+ else if (c.format && COLUMN_FORMATS[c.format]) out.pattern = COLUMN_FORMATS[c.format];
74
+ if (c.maxLength !== void 0) out.maxLength = c.maxLength;
75
+ applyByteCap(out, c);
76
+ applyLengths(out, c, lengths);
77
+ return out;
78
+ }
79
+ case "number": {
80
+ const out = { type: isIntegerColumn(c) ? "integer" : "number" };
81
+ if (!c.arrayDimensions) applyNumericBounds(out, c, checks, target);
82
+ return out;
83
+ }
84
+ case "bigint":
85
+ return { type: "string", pattern: "^-?\\d+$" };
86
+ case "boolean":
87
+ return { type: "boolean" };
88
+ case "Date":
89
+ return { type: "string", format: "date-time" };
90
+ case "Uint8Array":
91
+ return base64(target);
92
+ default:
93
+ return {};
94
+ }
95
+ }
96
+ function applyByteCap(out, c) {
97
+ if (!c.maxBytes) return;
98
+ out.maxLength = Math.min(Number(out.maxLength ?? Infinity), c.maxBytes);
99
+ out.description = `At most ${c.maxBytes} bytes of UTF-8, which JSON Schema has no keyword for. maxLength counts characters: it refuses nothing the column accepts, and a string of multi-byte characters can satisfy it and still be too long for the column.`;
100
+ }
101
+ function applyLengths(out, c, lengths) {
102
+ for (const k of lengths.filter((x) => x.column === c.name)) {
103
+ const n = Number(k.value);
104
+ if (k.operator === ">=") out.minLength = Math.max(Number(out.minLength ?? 0), n);
105
+ else if (k.operator === ">") out.minLength = Math.max(Number(out.minLength ?? 0), n + 1);
106
+ else if (k.operator === "<=") out.maxLength = Math.min(Number(out.maxLength ?? Infinity), n);
107
+ else if (k.operator === "<") out.maxLength = Math.min(Number(out.maxLength ?? Infinity), n - 1);
108
+ else if (k.operator === "=") {
109
+ out.minLength = n;
110
+ out.maxLength = n;
111
+ }
112
+ }
113
+ }
114
+ function applyNumericBounds(out, c, checks, target) {
115
+ let min = c.min !== void 0 ? { value: Number(c.min), exclusive: false } : void 0;
116
+ let max = c.max !== void 0 ? { value: Number(c.max), exclusive: false } : void 0;
117
+ for (const k of checks.filter((x) => x.column === c.name && x.kind === "number")) {
118
+ if (k.operator === ">=") min = { value: Number(k.value), exclusive: false };
119
+ else if (k.operator === ">") min = { value: Number(k.value), exclusive: true };
120
+ else if (k.operator === "<=") max = { value: Number(k.value), exclusive: false };
121
+ else if (k.operator === "<") max = { value: Number(k.value), exclusive: true };
122
+ }
123
+ const old = target === "openapi-3.0";
124
+ if (min) {
125
+ if (min.exclusive && !old) out.exclusiveMinimum = min.value;
126
+ else {
127
+ out.minimum = min.value;
128
+ if (min.exclusive) out.exclusiveMinimum = true;
129
+ }
130
+ }
131
+ if (max) {
132
+ if (max.exclusive && !old) out.exclusiveMaximum = max.value;
133
+ else {
134
+ out.maximum = max.value;
135
+ if (max.exclusive) out.exclusiveMaximum = true;
136
+ }
137
+ }
138
+ }
139
+ function cardinalityBounds(c, cardinalities) {
140
+ if (!c.arrayDimensions) return {};
141
+ const out = {};
142
+ for (const k of cardinalities.filter((x) => x.column === c.name)) {
143
+ const n = Number(k.value);
144
+ if (k.operator === ">=") out.minItems = n;
145
+ else if (k.operator === ">") out.minItems = n + 1;
146
+ else if (k.operator === "<=") out.maxItems = n;
147
+ else if (k.operator === "<") out.maxItems = n - 1;
148
+ else if (k.operator === "=") {
149
+ out.minItems = n;
150
+ out.maxItems = n;
151
+ }
152
+ }
153
+ return out;
154
+ }
155
+ function makeNullable(s, target) {
156
+ if (target === "openapi-3.0") return { ...s, nullable: true };
157
+ if (s.type === void 0) {
158
+ if (Array.isArray(s.enum)) return { ...s, enum: [...s.enum, null] };
159
+ if ("const" in s) {
160
+ const { const: k, ...rest } = s;
161
+ return { ...rest, enum: [k, null] };
162
+ }
163
+ return s;
164
+ }
165
+ return { ...s, type: [s.type, "null"] };
166
+ }
167
+ function columnSchema(c, mode, target, checks, sets, lengths, cardinalities, applyDefault) {
168
+ let s = baseSchema(c, mode, target, checks, sets, lengths);
169
+ const dims = c.arrayDimensions ?? 0;
170
+ for (let i = 0; i < dims; i++) {
171
+ s = { type: "array", items: s, ...i === dims - 1 ? cardinalityBounds(c, cardinalities) : {} };
172
+ }
173
+ if (c.nullable) s = makeNullable(s, target);
174
+ if (mode === "insert" && applyDefault && c.defaultValue !== void 0) {
175
+ s = { ...s, default: c.defaultValue };
176
+ }
177
+ return s;
178
+ }
179
+ function rowDescription(rows, cols) {
180
+ const present = new Set(cols.map((c) => c.name));
181
+ const applicable = rows.filter((r) => present.has(r.left) && present.has(r.right));
182
+ if (!applicable.length) return void 0;
183
+ const list = applicable.map((r) => `${r.name ? `${r.name}: ` : ""}${r.left} ${r.operator} ${r.right}`).join("; ");
184
+ return `Row constraints not expressible in JSON Schema: ${list}`;
185
+ }
186
+ function tableSchema(table, cols, mode, target, applyDefaults, parsed) {
187
+ const properties = {};
188
+ const required = [];
189
+ for (const c of cols) {
190
+ properties[c.name] = columnSchema(
191
+ c,
192
+ mode,
193
+ target,
194
+ parsed.checks,
195
+ parsed.sets,
196
+ parsed.lengths,
197
+ parsed.cardinalities,
198
+ applyDefaults
199
+ );
200
+ const suppliedOnInsert = c.hasDefault || applyDefaults && c.defaultValue !== void 0 || c.isGenerated;
201
+ const optional = mode === "update" || mode === "insert" && suppliedOnInsert;
202
+ if (!optional) required.push(c.name);
203
+ }
204
+ const desc = rowDescription(parsed.rows, cols);
205
+ return {
206
+ ...target === "draft-2020-12" ? { $schema: DRAFT } : {},
207
+ $id: `${table.tsName}.${mode}`,
208
+ title: `${mode} ${table.tsName}`,
209
+ ...desc ? { description: desc } : {},
210
+ type: "object",
211
+ properties,
212
+ ...required.length ? { required } : {},
213
+ additionalProperties: false
214
+ };
215
+ }
216
+ function collect(table) {
217
+ const parsed = (table.checks ?? []).map((k) => parseCheck(k.expression, k.name));
218
+ return {
219
+ checks: parsed.flatMap((p) => p.ok ? p.checks : []),
220
+ sets: parsed.flatMap((p) => p.ok ? p.sets ?? [] : []),
221
+ rows: parsed.flatMap((p) => p.ok ? p.rows ?? [] : []),
222
+ lengths: parsed.flatMap((p) => p.ok ? p.lengths ?? [] : []),
223
+ cardinalities: parsed.flatMap((p) => p.ok ? p.cardinalities ?? [] : [])
224
+ };
225
+ }
226
+ function tableSchemas(table, opts = {}) {
227
+ const target = opts.target ?? "draft-2020-12";
228
+ const parsed = collect(table);
229
+ const build2 = (cols, mode) => tableSchema(table, cols, mode, target, !!opts.applyDefaults, parsed);
230
+ return {
231
+ insert: build2(insertColumns(table), "insert"),
232
+ update: build2(updateColumns(table), "update"),
233
+ select: build2(selectColumns(table), "select")
234
+ };
235
+ }
236
+ function componentsDocument(tables, opts = {}) {
237
+ const schemas = {};
238
+ for (const table of tables) {
239
+ const built = tableSchemas(table, opts);
240
+ for (const mode of ["insert", "update", "select"]) {
241
+ const name = `${table.tsName}${mode[0].toUpperCase()}${mode.slice(1)}`;
242
+ const { $schema: _dialect, $id: _id, ...rest } = built[mode];
243
+ schemas[name] = rest;
244
+ }
245
+ }
246
+ return { schemas };
247
+ }
248
+ var ERROR_SCHEMA = "Error";
249
+ var componentName = (table, mode) => `${table.tsName}${mode[0].toUpperCase()}${mode.slice(1)}`;
250
+ var ref = (name) => ({ $ref: `#/components/schemas/${name}` });
251
+ var pascal = (s) => s.charAt(0).toUpperCase() + s.slice(1);
252
+ function keyColumns(table) {
253
+ const names = table.primaryKey?.columns ?? [];
254
+ if (!names.length) return null;
255
+ const cols = names.map((n) => table.columns.find((c) => c.name === n));
256
+ if (cols.some((c) => !c)) return null;
257
+ return cols;
258
+ }
259
+ var modesFor = (table, key) => [
260
+ ...table.readOnly ? [] : ["insert"],
261
+ ...table.readOnly || !key ? [] : ["update"],
262
+ "select"
263
+ ];
264
+ var resourceSegment = (table) => encodeURIComponent(table.name);
265
+ function foreignKeysOf(table) {
266
+ if (table.foreignKeys?.length) return table.foreignKeys;
267
+ return table.columns.filter((c) => c.references).map((c) => ({
268
+ columns: [c.name],
269
+ foreignTable: c.references.table,
270
+ foreignColumns: [c.references.column]
271
+ }));
272
+ }
273
+ var jsonBody = (schema) => ({ content: { "application/json": { schema } } });
274
+ function build(tables, opts) {
275
+ const target = opts.target ?? "draft-2020-12";
276
+ const schemaTarget = target === "openapi-3.0" ? "openapi-3.0" : "openapi-3.1";
277
+ const failure = String(opts.validationStatus ?? 400);
278
+ const paths = {};
279
+ const schemas = {};
280
+ const tags = [];
281
+ const operationIds = /* @__PURE__ */ new Map();
282
+ const owner = /* @__PURE__ */ new Map();
283
+ const claim = (path, by, label) => {
284
+ const taken = owner.get(path);
285
+ if (taken !== void 0 && taken.by !== by) {
286
+ throw new Error(
287
+ `@drzl/generator-json-schema: the OpenAPI path "${path}" is claimed twice: by table "${taken.label}" (exported as ${taken.by}) and by table "${label}" (exported as ${by}). A path names one resource, so one of the two has to be left out of this generator with the config's "exclude" list.`
288
+ );
289
+ }
290
+ owner.set(path, { by, label });
291
+ };
292
+ const operation = (id, table, rest) => {
293
+ const clash = operationIds.get(id);
294
+ if (clash !== void 0) {
295
+ throw new Error(
296
+ `@drzl/generator-json-schema: the operationId "${id}" would be emitted for both "${clash}" and "${table.name}". An operationId is the method name a client generator derives, and the specification requires it to be unique across the document.`
297
+ );
298
+ }
299
+ operationIds.set(id, table.name);
300
+ return { operationId: id, tags: [table.name], ...rest };
301
+ };
302
+ const built = tables.map((table) => ({
303
+ table,
304
+ key: keyColumns(table),
305
+ segment: resourceSegment(table),
306
+ schemas: tableSchemas(table, { target: schemaTarget, applyDefaults: opts.applyDefaults })
307
+ }));
308
+ for (const { table, key, segment, schemas: built3 } of built) {
309
+ for (const mode of modesFor(table, key)) {
310
+ const { $schema: _dialect, $id: _id, ...rest } = built3[mode];
311
+ schemas[componentName(table, mode)] = rest;
312
+ }
313
+ const notes = [];
314
+ if (!key) notes.push("It has no primary key, so no path addresses a single row.");
315
+ if (table.readOnly) {
316
+ notes.push("It refuses every write, so only reads are described.");
317
+ }
318
+ tags.push({ name: table.name, description: [`Table "${table.name}".`, ...notes].join(" ") });
319
+ const T = pascal(table.tsName);
320
+ const select = ref(componentName(table, "select"));
321
+ const validationFailed = {
322
+ description: "The request does not match the schema for this operation.",
323
+ ...jsonBody(ref(ERROR_SCHEMA))
324
+ };
325
+ const collidable = [
326
+ ...table.primaryKey ? [`primary key (${table.primaryKey.columns.join(", ")})`] : [],
327
+ ...table.unique.map((u) => `${u.name ? `${u.name} ` : ""}(${u.columns.join(", ")})`)
328
+ ];
329
+ const conflict = (constraints) => ({
330
+ description: `The row collides with an existing one on ${constraints.join("; ")}.`,
331
+ ...jsonBody(ref(ERROR_SCHEMA))
332
+ });
333
+ const collection = `/${segment}`;
334
+ claim(collection, table.tsName, table.name);
335
+ const item = {
336
+ get: operation(`list${T}`, table, {
337
+ summary: `List every ${table.name} row.`,
338
+ // No pagination parameters. Whether the server implements a limit, an offset or a cursor is
339
+ // not something a Drizzle schema states, and a declared parameter nothing honours is worse
340
+ // than an undeclared one.
341
+ responses: {
342
+ "200": {
343
+ description: `Every ${table.name} row.`,
344
+ ...jsonBody({ type: "array", items: select })
345
+ }
346
+ }
347
+ })
348
+ };
349
+ if (!table.readOnly) {
350
+ item.post = operation(`create${T}`, table, {
351
+ summary: `Create a ${table.name} row.`,
352
+ requestBody: { required: true, ...jsonBody(ref(componentName(table, "insert"))) },
353
+ responses: {
354
+ "201": { description: `The ${table.name} row that was created.`, ...jsonBody(select) },
355
+ [failure]: validationFailed,
356
+ ...collidable.length ? { "409": conflict(collidable) } : {}
357
+ }
358
+ });
359
+ }
360
+ paths[collection] = item;
361
+ if (!key) continue;
362
+ const itemPath = `${collection}/${key.map((c) => `{${c.name}}`).join("/")}`;
363
+ claim(itemPath, table.tsName, table.name);
364
+ const parameters = key.map((c) => ({
365
+ name: c.name,
366
+ in: "path",
367
+ required: true,
368
+ description: `${c.name}, from the primary key of ${table.name}.`,
369
+ // The column's own schema rather than a string, so an integer key is declared as one and a
370
+ // uuid key carries its format. This is the whole point of reading the real key.
371
+ schema: built3.select.properties[c.name] ?? {}
372
+ }));
373
+ const missing = {
374
+ description: `No ${table.name} row has that ${key.map((c) => c.name).join(" and ")}.`,
375
+ ...jsonBody(ref(ERROR_SCHEMA))
376
+ };
377
+ const byId = {
378
+ parameters,
379
+ get: operation(`get${T}`, table, {
380
+ summary: `Read one ${table.name} row.`,
381
+ responses: {
382
+ "200": { description: `The requested ${table.name} row.`, ...jsonBody(select) },
383
+ [failure]: validationFailed,
384
+ "404": missing
385
+ }
386
+ })
387
+ };
388
+ if (!table.readOnly) {
389
+ byId.patch = operation(`update${T}`, table, {
390
+ summary: `Patch one ${table.name} row.`,
391
+ requestBody: { required: true, ...jsonBody(ref(componentName(table, "update"))) },
392
+ responses: {
393
+ "200": { description: `The ${table.name} row after the patch.`, ...jsonBody(select) },
394
+ [failure]: validationFailed,
395
+ "404": missing,
396
+ // The primary key is not in the update schema, so a patch cannot collide on it. Only a
397
+ // unique constraint over other columns can.
398
+ ...table.unique.length ? {
399
+ "409": conflict(
400
+ table.unique.map((u) => `${u.name ? `${u.name} ` : ""}(${u.columns.join(", ")})`)
401
+ )
402
+ } : {}
403
+ }
404
+ });
405
+ byId.delete = operation(`delete${T}`, table, {
406
+ summary: `Delete one ${table.name} row.`,
407
+ responses: {
408
+ // No body. Handing back the deleted row is the alternative and it is not a true statement
409
+ // on every dialect DRZL supports: RETURNING is Postgres and SQLite, and MySQL has no such
410
+ // clause, so an implementation there has nothing to send.
411
+ "204": { description: `The ${table.name} row was deleted. No content is returned.` },
412
+ [failure]: validationFailed,
413
+ "404": missing
414
+ }
415
+ });
416
+ }
417
+ paths[itemPath] = byId;
418
+ if (!opts.includeRelations) continue;
419
+ for (const child of built) {
420
+ if (child.table === table) continue;
421
+ const matching = foreignKeysOf(child.table).filter(
422
+ (fk) => fk.foreignTable === table.name && fk.foreignColumns.length === key.length && fk.foreignColumns.every((c, i) => c === key[i].name)
423
+ );
424
+ if (matching.length !== 1) continue;
425
+ const subPath = `${itemPath}/${child.segment}`;
426
+ claim(
427
+ subPath,
428
+ `${table.tsName} -> ${child.table.tsName}`,
429
+ `${table.name} -> ${child.table.name}`
430
+ );
431
+ paths[subPath] = {
432
+ parameters,
433
+ get: operation(`list${T}${pascal(child.table.tsName)}`, child.table, {
434
+ summary: `List the ${child.table.name} rows belonging to one ${table.name} row.`,
435
+ responses: {
436
+ "200": {
437
+ description: `The ${child.table.name} rows whose ${matching[0].columns.join(", ")} names this ${table.name} row.`,
438
+ ...jsonBody({ type: "array", items: ref(componentName(child.table, "select")) })
439
+ },
440
+ [failure]: validationFailed,
441
+ "404": missing
442
+ }
443
+ })
444
+ };
445
+ }
446
+ }
447
+ return { paths, schemas, tags };
448
+ }
449
+ var errorSchema = () => ({
450
+ title: "error",
451
+ description: "What an operation returns when it does not return the row.",
452
+ type: "object",
453
+ properties: {
454
+ message: { type: "string" },
455
+ code: { type: "string" }
456
+ },
457
+ required: ["message"],
458
+ additionalProperties: true
459
+ });
460
+ function openApiDocument(tables, opts = {}) {
461
+ const target = opts.target ?? "draft-2020-12";
462
+ const { paths, schemas, tags } = build(tables, opts);
463
+ if (ERROR_SCHEMA in schemas) {
464
+ throw new Error(
465
+ `@drzl/generator-json-schema: a table produced the component schema name "${ERROR_SCHEMA}", which the document already uses for its error responses.`
466
+ );
467
+ }
468
+ return {
469
+ openapi: target === "openapi-3.0" ? "3.0.3" : "3.1.1",
470
+ info: {
471
+ title: opts.info?.title ?? "API",
472
+ version: opts.info?.version ?? "0.0.0",
473
+ description: opts.info?.description ?? "Generated by DRZL from a Drizzle schema. Paths, request bodies and response bodies are derived from the schema alone; nothing here has been checked against a running server."
474
+ },
475
+ ...opts.servers?.length ? { servers: opts.servers } : {},
476
+ paths,
477
+ components: { schemas: { ...schemas, [ERROR_SCHEMA]: errorSchema() } },
478
+ tags
479
+ };
480
+ }
481
+ var DEFAULT_FILE_SUFFIX = ".schema.ts";
482
+ function renderTableModule(table, affix, target, applyDefaults) {
483
+ const T = table.tsName;
484
+ const schemas = tableSchemas(table, { target, applyDefaults });
485
+ const decl = (mode) => `export const ${schemaName(mode, T, affix)} = ${JSON.stringify(schemas[mode], null, 2)} as const;
486
+
487
+ export type ${typeName(mode, T, affix)} = typeof ${schemaName(mode, T, affix)};`;
488
+ return [decl("insert"), decl("update"), decl("select")].join("\n\n") + "\n";
489
+ }
490
+ function resolveDocument(opt) {
491
+ if (!opt) return null;
492
+ const o = opt === true ? {} : opt;
493
+ if (o.enabled === false) return null;
494
+ return { ...o, format: o.format ?? "ts" };
495
+ }
496
+ var JsonSchemaGenerator = class {
497
+ constructor(analysis) {
498
+ this.analysis = analysis;
499
+ this.library = "json-schema";
500
+ }
501
+ async generate(opts) {
502
+ const fs = await import("fs/promises");
503
+ const path = await import("path");
504
+ const out = path.resolve(process.cwd(), opts.outDir);
505
+ const files = [];
506
+ await fs.mkdir(out, { recursive: true });
507
+ const affix = resolveAffix(opts);
508
+ const fileSuffix = opts.fileSuffix ?? DEFAULT_FILE_SUFFIX;
509
+ const target = opts.target ?? "draft-2020-12";
510
+ const document = resolveDocument(opts.document);
511
+ for (const table of this.analysis.tables) {
512
+ const filePath = path.join(out, moduleFileName(table.tsName, fileSuffix));
513
+ const code = renderTableModule(table, affix, target, !!opts.applyDefaults);
514
+ const formatted = await formatCode(
515
+ buildHeader(opts.outputHeader) + code,
516
+ filePath,
517
+ opts.format
518
+ );
519
+ await fs.writeFile(filePath, formatted, "utf8");
520
+ files.push(filePath);
521
+ }
522
+ if (opts.components) {
523
+ const doc = componentsDocument(this.analysis.tables, {
524
+ target,
525
+ applyDefaults: !!opts.applyDefaults
526
+ });
527
+ const componentsPath = path.join(out, "components.ts");
528
+ const code = `export const components = ${JSON.stringify(doc, null, 2)} as const;
529
+ `;
530
+ await fs.writeFile(
531
+ componentsPath,
532
+ await formatCode(buildHeader(opts.outputHeader) + code, componentsPath, opts.format),
533
+ "utf8"
534
+ );
535
+ files.push(componentsPath);
536
+ }
537
+ if (document) {
538
+ const built = openApiDocument(this.analysis.tables, {
539
+ target,
540
+ applyDefaults: !!opts.applyDefaults,
541
+ includeRelations: !!opts.includeRelations,
542
+ info: document.info,
543
+ servers: document.servers,
544
+ validationStatus: document.validationStatus
545
+ });
546
+ const body = JSON.stringify(built, null, 2);
547
+ if (document.format !== "json") {
548
+ const tsPath = path.join(out, "openapi.ts");
549
+ const code = `export const openapi = ${body} as const;
550
+ `;
551
+ await fs.writeFile(
552
+ tsPath,
553
+ await formatCode(buildHeader(opts.outputHeader) + code, tsPath, opts.format),
554
+ "utf8"
555
+ );
556
+ files.push(tsPath);
557
+ }
558
+ if (document.format !== "ts") {
559
+ const jsonPath = path.join(out, "openapi.json");
560
+ await fs.writeFile(jsonPath, body + "\n", "utf8");
561
+ files.push(jsonPath);
562
+ }
563
+ }
564
+ const ext = opts.importExtension === "none" ? "" : ".js";
565
+ const indexPath = path.join(out, "index.ts");
566
+ const index = this.analysis.tables.map(
567
+ (t) => `export * from '${moduleSpecifier(t.tsName, fileSuffix, opts.importExtension)}';`
568
+ ).concat(opts.components ? [`export * from './components${ext}';`] : []).concat(document && document.format !== "json" ? [`export * from './openapi${ext}';`] : []).join("\n") + "\n";
569
+ const indexFormatted = await formatCode(
570
+ buildHeader(opts.outputHeader) + index,
571
+ indexPath,
572
+ opts.format
573
+ );
574
+ await fs.writeFile(indexPath, indexFormatted, "utf8");
575
+ files.push(indexPath);
576
+ return files;
577
+ }
578
+ renderTable(table, opts) {
579
+ return renderTableModule(
580
+ table,
581
+ resolveAffix(opts),
582
+ opts?.target ?? "draft-2020-12",
583
+ !!opts?.applyDefaults
584
+ );
585
+ }
586
+ };
587
+ var index_default = JsonSchemaGenerator;
588
+ function buildHeader(h) {
589
+ if (h?.enabled === false) return "";
590
+ const text = h?.text ?? "// Generated by DRZL. Do not edit by hand.";
591
+ return `${text}
592
+
593
+ `;
594
+ }
595
+ export {
596
+ DRAFT,
597
+ JsonSchemaGenerator,
598
+ componentsDocument,
599
+ index_default as default,
600
+ openApiDocument,
601
+ tableSchemas
602
+ };
603
+ //# sourceMappingURL=dist-TRJLPIWT.js.map