prisma-swagger-autogen 1.0.7 → 1.0.10

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/bin.cjs CHANGED
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- require('./cli.cjs');
2
+ require("./cli.cjs");
package/dist/cli.cjs CHANGED
@@ -1,9 +1,221 @@
1
+ #!/usr/bin/env node
1
2
  "use strict";
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
18
+ // If the importer is in node compatibility mode or this is not an ESM
19
+ // file that has been converted to a CommonJS file using a Babel-
20
+ // compatible transform (i.e. "__esModule" has not been set), then set
21
+ // "default" to the CommonJS "module.exports" for node compatibility.
22
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
23
+ mod
24
+ ));
2
25
 
3
- var _chunkD67FQWAIcjs = require('./chunk-D67FQWAI.cjs');
26
+ // src/index.ts
27
+ var import_node_fs = __toESM(require("fs"), 1);
28
+ var import_node_path = __toESM(require("path"), 1);
29
+ var import_node_module = require("module");
30
+ var import_glob = require("glob");
31
+ var CONFIG = {
32
+ projectRoot: process.cwd(),
33
+ controllersGlob: "./src/web/api/controllers/**/*.ts",
34
+ outFile: "./swagger.config.js",
35
+ openapiOut: "./src/web/api/openapi.json",
36
+ serviceTitle: "Prescription Service",
37
+ serverUrl: "http://localhost:3008",
38
+ securitySchemeName: "keycloakOAuth",
39
+ oauth: {
40
+ tokenUrl: "http://auth.localhost/realms/haemo/protocol/openid-connect/token",
41
+ refreshUrl: "http://auth.localhost/realms/haemo/protocol/openid-connect/refresh",
42
+ scopes: { openid: "openid scope" }
43
+ },
44
+ omitFieldsInWriteDtos: /* @__PURE__ */ new Set(["id", "createdAt", "updatedAt", "v"])
45
+ };
46
+ function ensurePosix(p) {
47
+ return p.split(import_node_path.default.sep).join(import_node_path.default.posix.sep);
48
+ }
49
+ function pluralize(name) {
50
+ if (name.endsWith("s")) return `${name}es`;
51
+ return `${name}s`;
52
+ }
53
+ function getRequire() {
54
+ return (0, import_node_module.createRequire)(typeof __filename !== "undefined" ? __filename : process.cwd() + "/");
55
+ }
56
+ async function loadDmmfFromProject(schemaPath) {
57
+ const resolvedSchemaPath = schemaPath ? import_node_path.default.resolve(process.cwd(), schemaPath) : import_node_path.default.resolve(process.cwd(), "prisma/schema.prisma");
58
+ if (!import_node_fs.default.existsSync(resolvedSchemaPath)) {
59
+ throw new Error(`Prisma schema not found at ${resolvedSchemaPath}`);
60
+ }
61
+ const datamodel = import_node_fs.default.readFileSync(resolvedSchemaPath, "utf8");
62
+ const require2 = getRequire();
63
+ const internals = require2("@prisma/internals");
64
+ if (typeof internals.getDMMF !== "function") {
65
+ throw new Error(`@prisma/internals.getDMMF not available`);
66
+ }
67
+ const dmmf = await internals.getDMMF({ datamodel });
68
+ if (!dmmf || !dmmf.datamodel || !Array.isArray(dmmf.datamodel.models) || !Array.isArray(dmmf.datamodel.enums)) {
69
+ throw new Error(`Unexpected DMMF shape returned by @prisma/internals.getDMMF`);
70
+ }
71
+ return dmmf;
72
+ }
73
+ function scalarToSchema(scalar) {
74
+ switch (scalar) {
75
+ case "String":
76
+ return { type: "string" };
77
+ case "Boolean":
78
+ return { type: "boolean" };
79
+ case "Int":
80
+ return { type: "integer" };
81
+ case "BigInt":
82
+ return { type: "integer", format: "int64" };
83
+ case "Float":
84
+ return { type: "number" };
85
+ case "Decimal":
86
+ return { type: "number" };
87
+ case "DateTime":
88
+ return { type: "string", format: "date-time" };
89
+ case "Json":
90
+ return { type: "object" };
91
+ case "Bytes":
92
+ return { type: "string", format: "byte" };
93
+ default:
94
+ return { type: "string" };
95
+ }
96
+ }
97
+ function fieldSchema(field, getRefName) {
98
+ if (field.kind === "scalar") {
99
+ const base = scalarToSchema(field.type);
100
+ if (field.isList) return { type: "array", items: base };
101
+ return base;
102
+ }
103
+ if (field.kind === "enum") {
104
+ const base = { $ref: `#/components/schemas/${field.type}` };
105
+ if (field.isList) return { type: "array", items: base };
106
+ return base;
107
+ }
108
+ if (field.kind === "object") {
109
+ const ref = { $ref: `#/components/schemas/${getRefName(String(field.type))}` };
110
+ if (field.isList) return { type: "array", items: ref };
111
+ return ref;
112
+ }
113
+ return { type: "object" };
114
+ }
115
+ function modelToGetSchema(model, getRefName) {
116
+ const properties = {};
117
+ const required = [];
118
+ for (const f of model.fields) {
119
+ properties[f.name] = fieldSchema(f, getRefName);
120
+ if (f.isRequired) required.push(f.name);
121
+ }
122
+ const schema = { type: "object", properties };
123
+ if (required.length) schema.required = required;
124
+ return schema;
125
+ }
126
+ function stripWriteFields(model, getSchema, omit) {
127
+ const schema = JSON.parse(JSON.stringify(getSchema));
128
+ if (!schema.properties) return schema;
129
+ const relationFieldNames = new Set(model.fields.filter((f) => f.kind === "object").map((f) => f.name));
130
+ for (const key of Object.keys(schema.properties)) {
131
+ if (omit.has(key) || relationFieldNames.has(key)) delete schema.properties[key];
132
+ }
133
+ if (Array.isArray(schema.required)) {
134
+ schema.required = schema.required.filter((k) => !omit.has(k) && !relationFieldNames.has(k));
135
+ if (schema.required.length === 0) delete schema.required;
136
+ }
137
+ return schema;
138
+ }
139
+ function makeAllOptional(schema) {
140
+ const s = JSON.parse(JSON.stringify(schema));
141
+ delete s.required;
142
+ return s;
143
+ }
144
+ function listResponseSchema(itemRef) {
145
+ return {
146
+ type: "object",
147
+ properties: {
148
+ count: { type: "number" },
149
+ hasPreviousPage: { type: "boolean" },
150
+ hasNextPage: { type: "boolean" },
151
+ pageNumber: { type: "number" },
152
+ pageSize: { type: "number" },
153
+ totalPages: { type: "number" },
154
+ items: { type: "array", items: { $ref: itemRef } }
155
+ },
156
+ required: ["count", "hasPreviousPage", "hasNextPage", "pageNumber", "pageSize", "totalPages", "items"]
157
+ };
158
+ }
159
+ async function buildSchemasFromPrismaDmmf(schemaPath) {
160
+ const dmmf = await loadDmmfFromProject(schemaPath);
161
+ const schemas = {};
162
+ const getRefName = (modelName) => `Get${modelName}Response`;
163
+ for (const e of dmmf.datamodel.enums) {
164
+ schemas[e.name] = { type: "string", enum: e.values.map((v) => v.name) };
165
+ }
166
+ for (const model of dmmf.datamodel.models) {
167
+ const getName = `Get${model.name}Response`;
168
+ const postName = `Post${model.name}Request`;
169
+ const putName = `Put${model.name}Request`;
170
+ const listName = `List${pluralize(model.name)}Response`;
171
+ const getSchema = modelToGetSchema(model, getRefName);
172
+ const postSchema = stripWriteFields(model, getSchema, CONFIG.omitFieldsInWriteDtos);
173
+ const putSchema = makeAllOptional(postSchema);
174
+ schemas[getName] = getSchema;
175
+ schemas[postName] = postSchema;
176
+ schemas[putName] = putSchema;
177
+ schemas[listName] = listResponseSchema(`#/components/schemas/${getName}`);
178
+ }
179
+ return schemas;
180
+ }
181
+ function generateSwaggerConfigJs(schemas) {
182
+ const routes = (0, import_glob.globSync)(CONFIG.controllersGlob, { nodir: true }).map((p) => ensurePosix(p));
183
+ const docs = {
184
+ info: { title: CONFIG.serviceTitle },
185
+ servers: [{ url: CONFIG.serverUrl }],
186
+ components: {
187
+ schemas,
188
+ securitySchemes: {
189
+ [CONFIG.securitySchemeName]: {
190
+ type: "oauth2",
191
+ description: "This API uses OAuth2 with the password flow.",
192
+ flows: {
193
+ password: {
194
+ tokenUrl: CONFIG.oauth.tokenUrl,
195
+ refreshUrl: CONFIG.oauth.refreshUrl,
196
+ scopes: CONFIG.oauth.scopes
197
+ }
198
+ }
199
+ }
200
+ }
201
+ },
202
+ security: [{ [CONFIG.securitySchemeName]: ["openid"] }]
203
+ };
204
+ const fileContent = `const swaggerAutogen = require('swagger-autogen')();
205
+ const docs = ${JSON.stringify(docs, null, 2)};
206
+ const routes = ${JSON.stringify(routes, null, 2)};
207
+ swaggerAutogen('${ensurePosix(CONFIG.openapiOut)}', routes, docs);`;
208
+ import_node_fs.default.writeFileSync(import_node_path.default.resolve(CONFIG.projectRoot, CONFIG.outFile), fileContent, "utf8");
209
+ }
210
+ async function run(args = []) {
211
+ const schemaFlagIndex = args.findIndex((a) => a === "--schema");
212
+ const schemaPath = schemaFlagIndex >= 0 ? args[schemaFlagIndex + 1] : void 0;
213
+ const schemas = await buildSchemasFromPrismaDmmf(schemaPath);
214
+ generateSwaggerConfigJs(schemas);
215
+ }
4
216
 
5
217
  // src/cli.ts
6
- void _chunkD67FQWAIcjs.run.call(void 0, process.argv.slice(2)).catch((e) => {
218
+ void run(process.argv.slice(2)).catch((e) => {
7
219
  console.error(e);
8
220
  process.exitCode = 1;
9
221
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "prisma-swagger-autogen",
3
- "version": "1.0.7",
3
+ "version": "1.0.10",
4
4
  "description": "Generate swagger-autogen config + Prisma DMMF schemas and fix swagger-autogen output.",
5
5
  "license": "MIT",
6
6
  "author": "Joyce Marvin Rafflenbeul",
@@ -35,11 +35,12 @@
35
35
  },
36
36
  "files": [
37
37
  "dist",
38
+ "scripts/make-bin.cjs",
38
39
  "README.md",
39
40
  "LICENSE"
40
41
  ],
41
42
  "scripts": {
42
- "build": "tsup src/index.ts src/cli.ts --format esm,cjs --dts --out-dir dist --tsconfig tsconfig.json && node scripts/make-bin.cjs && chmod +x dist/bin.cjs",
43
+ "build": "tsup src/index.ts --format esm,cjs --dts --out-dir dist --tsconfig tsconfig.json && tsup src/cli.ts --format cjs --out-dir dist --no-dts --tsconfig tsconfig.json && node scripts/make-bin.cjs",
43
44
  "prepublishOnly": "npm run build"
44
45
  },
45
46
  "dependencies": {
@@ -0,0 +1,14 @@
1
+ const fs = require("fs");
2
+ const path = require("path");
3
+
4
+ const distDir = path.resolve(__dirname, "../dist");
5
+ fs.mkdirSync(distDir, { recursive: true });
6
+
7
+ const out = path.join(distDir, "bin.cjs");
8
+
9
+ const content = `#!/usr/bin/env node
10
+ require("./cli.cjs");
11
+ `;
12
+
13
+ fs.writeFileSync(out, content, "utf8");
14
+ try { fs.chmodSync(out, 0o755); } catch {}
@@ -1,197 +0,0 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }// src/index.ts
2
- var _fs = require('fs'); var _fs2 = _interopRequireDefault(_fs);
3
- var _path = require('path'); var _path2 = _interopRequireDefault(_path);
4
- var _module = require('module');
5
- var _glob = require('glob');
6
- var CONFIG = {
7
- projectRoot: process.cwd(),
8
- controllersGlob: "./src/web/api/controllers/**/*.ts",
9
- outFile: "./swagger.config.js",
10
- openapiOut: "./src/web/api/openapi.json",
11
- serviceTitle: "Prescription Service",
12
- serverUrl: "http://localhost:3008",
13
- securitySchemeName: "keycloakOAuth",
14
- oauth: {
15
- tokenUrl: "http://auth.localhost/realms/haemo/protocol/openid-connect/token",
16
- refreshUrl: "http://auth.localhost/realms/haemo/protocol/openid-connect/refresh",
17
- scopes: { openid: "openid scope" }
18
- },
19
- omitFieldsInWriteDtos: /* @__PURE__ */ new Set(["id", "createdAt", "updatedAt", "v"])
20
- };
21
- function ensurePosix(p) {
22
- return p.split(_path2.default.sep).join(_path2.default.posix.sep);
23
- }
24
- function pluralize(name) {
25
- if (name.endsWith("s")) return `${name}es`;
26
- return `${name}s`;
27
- }
28
- function getRequire() {
29
- const base = typeof __filename !== "undefined" ? __filename : import.meta.url;
30
- return _module.createRequire.call(void 0, base);
31
- }
32
- async function loadDmmfFromProject(schemaPath) {
33
- const resolvedSchemaPath = schemaPath ? _path2.default.resolve(process.cwd(), schemaPath) : _path2.default.resolve(process.cwd(), "prisma/schema.prisma");
34
- if (!_fs2.default.existsSync(resolvedSchemaPath)) {
35
- throw new Error(`Prisma schema not found at ${resolvedSchemaPath}`);
36
- }
37
- const datamodel = _fs2.default.readFileSync(resolvedSchemaPath, "utf8");
38
- const require2 = getRequire();
39
- const internals = require2("@prisma/internals");
40
- if (typeof internals.getDMMF !== "function") {
41
- throw new Error(`@prisma/internals.getDMMF not available`);
42
- }
43
- const dmmf = await internals.getDMMF({ datamodel });
44
- if (!dmmf || !dmmf.datamodel || !Array.isArray(dmmf.datamodel.models) || !Array.isArray(dmmf.datamodel.enums)) {
45
- throw new Error(`Unexpected DMMF shape returned by @prisma/internals.getDMMF`);
46
- }
47
- return dmmf;
48
- }
49
- function scalarToSchema(scalar) {
50
- switch (scalar) {
51
- case "String":
52
- return { type: "string" };
53
- case "Boolean":
54
- return { type: "boolean" };
55
- case "Int":
56
- return { type: "integer" };
57
- case "BigInt":
58
- return { type: "integer", format: "int64" };
59
- case "Float":
60
- return { type: "number" };
61
- case "Decimal":
62
- return { type: "number" };
63
- case "DateTime":
64
- return { type: "string", format: "date-time" };
65
- case "Json":
66
- return { type: "object" };
67
- case "Bytes":
68
- return { type: "string", format: "byte" };
69
- default:
70
- return { type: "string" };
71
- }
72
- }
73
- function fieldSchema(field, getRefName) {
74
- if (field.kind === "scalar") {
75
- const base = scalarToSchema(field.type);
76
- if (field.isList) return { type: "array", items: base };
77
- return base;
78
- }
79
- if (field.kind === "enum") {
80
- const base = { $ref: `#/components/schemas/${field.type}` };
81
- if (field.isList) return { type: "array", items: base };
82
- return base;
83
- }
84
- if (field.kind === "object") {
85
- const ref = { $ref: `#/components/schemas/${getRefName(String(field.type))}` };
86
- if (field.isList) return { type: "array", items: ref };
87
- return ref;
88
- }
89
- return { type: "object" };
90
- }
91
- function modelToGetSchema(model, getRefName) {
92
- const properties = {};
93
- const required = [];
94
- for (const f of model.fields) {
95
- properties[f.name] = fieldSchema(f, getRefName);
96
- if (f.isRequired) required.push(f.name);
97
- }
98
- const schema = { type: "object", properties };
99
- if (required.length) schema.required = required;
100
- return schema;
101
- }
102
- function stripWriteFields(model, getSchema, omit) {
103
- const schema = JSON.parse(JSON.stringify(getSchema));
104
- if (!schema.properties) return schema;
105
- const relationFieldNames = new Set(model.fields.filter((f) => f.kind === "object").map((f) => f.name));
106
- for (const key of Object.keys(schema.properties)) {
107
- if (omit.has(key) || relationFieldNames.has(key)) {
108
- delete schema.properties[key];
109
- }
110
- }
111
- if (Array.isArray(schema.required)) {
112
- schema.required = schema.required.filter((k) => !omit.has(k) && !relationFieldNames.has(k));
113
- if (schema.required.length === 0) delete schema.required;
114
- }
115
- return schema;
116
- }
117
- function makeAllOptional(schema) {
118
- const s = JSON.parse(JSON.stringify(schema));
119
- delete s.required;
120
- return s;
121
- }
122
- function listResponseSchema(itemRef) {
123
- return {
124
- type: "object",
125
- properties: {
126
- count: { type: "number" },
127
- hasPreviousPage: { type: "boolean" },
128
- hasNextPage: { type: "boolean" },
129
- pageNumber: { type: "number" },
130
- pageSize: { type: "number" },
131
- totalPages: { type: "number" },
132
- items: { type: "array", items: { $ref: itemRef } }
133
- },
134
- required: ["count", "hasPreviousPage", "hasNextPage", "pageNumber", "pageSize", "totalPages", "items"]
135
- };
136
- }
137
- async function buildSchemasFromPrismaDmmf(schemaPath) {
138
- const dmmf = await loadDmmfFromProject(schemaPath);
139
- const schemas = {};
140
- const getRefName = (modelName) => `Get${modelName}Response`;
141
- for (const e of dmmf.datamodel.enums) {
142
- schemas[e.name] = { type: "string", enum: e.values.map((v) => v.name) };
143
- }
144
- for (const model of dmmf.datamodel.models) {
145
- const getName = `Get${model.name}Response`;
146
- const postName = `Post${model.name}Request`;
147
- const putName = `Put${model.name}Request`;
148
- const listName = `List${pluralize(model.name)}Response`;
149
- const getSchema = modelToGetSchema(model, getRefName);
150
- const postSchema = stripWriteFields(model, getSchema, CONFIG.omitFieldsInWriteDtos);
151
- const putSchema = makeAllOptional(postSchema);
152
- schemas[getName] = getSchema;
153
- schemas[postName] = postSchema;
154
- schemas[putName] = putSchema;
155
- schemas[listName] = listResponseSchema(`#/components/schemas/${getName}`);
156
- }
157
- return schemas;
158
- }
159
- function generateSwaggerConfigJs(schemas) {
160
- const routes = _glob.globSync.call(void 0, CONFIG.controllersGlob, { nodir: true }).map((p) => ensurePosix(p));
161
- const docs = {
162
- info: { title: CONFIG.serviceTitle },
163
- servers: [{ url: CONFIG.serverUrl }],
164
- components: {
165
- schemas,
166
- securitySchemes: {
167
- [CONFIG.securitySchemeName]: {
168
- type: "oauth2",
169
- description: "This API uses OAuth2 with the password flow.",
170
- flows: {
171
- password: {
172
- tokenUrl: CONFIG.oauth.tokenUrl,
173
- refreshUrl: CONFIG.oauth.refreshUrl,
174
- scopes: CONFIG.oauth.scopes
175
- }
176
- }
177
- }
178
- }
179
- },
180
- security: [{ [CONFIG.securitySchemeName]: ["openid"] }]
181
- };
182
- const fileContent = `const swaggerAutogen = require('swagger-autogen')();
183
- const docs = ${JSON.stringify(docs, null, 2)};
184
- const routes = ${JSON.stringify(routes, null, 2)};
185
- swaggerAutogen('${ensurePosix(CONFIG.openapiOut)}', routes, docs);`;
186
- _fs2.default.writeFileSync(_path2.default.resolve(CONFIG.projectRoot, CONFIG.outFile), fileContent, "utf8");
187
- }
188
- async function run(args = []) {
189
- const schemaFlagIndex = args.findIndex((a) => a === "--schema");
190
- const schemaPath = schemaFlagIndex >= 0 ? args[schemaFlagIndex + 1] : void 0;
191
- const schemas = await buildSchemasFromPrismaDmmf(schemaPath);
192
- generateSwaggerConfigJs(schemas);
193
- }
194
-
195
-
196
-
197
- exports.run = run;
@@ -1,197 +0,0 @@
1
- // src/index.ts
2
- import fs from "fs";
3
- import path from "path";
4
- import { createRequire } from "module";
5
- import { globSync } from "glob";
6
- var CONFIG = {
7
- projectRoot: process.cwd(),
8
- controllersGlob: "./src/web/api/controllers/**/*.ts",
9
- outFile: "./swagger.config.js",
10
- openapiOut: "./src/web/api/openapi.json",
11
- serviceTitle: "Prescription Service",
12
- serverUrl: "http://localhost:3008",
13
- securitySchemeName: "keycloakOAuth",
14
- oauth: {
15
- tokenUrl: "http://auth.localhost/realms/haemo/protocol/openid-connect/token",
16
- refreshUrl: "http://auth.localhost/realms/haemo/protocol/openid-connect/refresh",
17
- scopes: { openid: "openid scope" }
18
- },
19
- omitFieldsInWriteDtos: /* @__PURE__ */ new Set(["id", "createdAt", "updatedAt", "v"])
20
- };
21
- function ensurePosix(p) {
22
- return p.split(path.sep).join(path.posix.sep);
23
- }
24
- function pluralize(name) {
25
- if (name.endsWith("s")) return `${name}es`;
26
- return `${name}s`;
27
- }
28
- function getRequire() {
29
- const base = typeof __filename !== "undefined" ? __filename : import.meta.url;
30
- return createRequire(base);
31
- }
32
- async function loadDmmfFromProject(schemaPath) {
33
- const resolvedSchemaPath = schemaPath ? path.resolve(process.cwd(), schemaPath) : path.resolve(process.cwd(), "prisma/schema.prisma");
34
- if (!fs.existsSync(resolvedSchemaPath)) {
35
- throw new Error(`Prisma schema not found at ${resolvedSchemaPath}`);
36
- }
37
- const datamodel = fs.readFileSync(resolvedSchemaPath, "utf8");
38
- const require2 = getRequire();
39
- const internals = require2("@prisma/internals");
40
- if (typeof internals.getDMMF !== "function") {
41
- throw new Error(`@prisma/internals.getDMMF not available`);
42
- }
43
- const dmmf = await internals.getDMMF({ datamodel });
44
- if (!dmmf || !dmmf.datamodel || !Array.isArray(dmmf.datamodel.models) || !Array.isArray(dmmf.datamodel.enums)) {
45
- throw new Error(`Unexpected DMMF shape returned by @prisma/internals.getDMMF`);
46
- }
47
- return dmmf;
48
- }
49
- function scalarToSchema(scalar) {
50
- switch (scalar) {
51
- case "String":
52
- return { type: "string" };
53
- case "Boolean":
54
- return { type: "boolean" };
55
- case "Int":
56
- return { type: "integer" };
57
- case "BigInt":
58
- return { type: "integer", format: "int64" };
59
- case "Float":
60
- return { type: "number" };
61
- case "Decimal":
62
- return { type: "number" };
63
- case "DateTime":
64
- return { type: "string", format: "date-time" };
65
- case "Json":
66
- return { type: "object" };
67
- case "Bytes":
68
- return { type: "string", format: "byte" };
69
- default:
70
- return { type: "string" };
71
- }
72
- }
73
- function fieldSchema(field, getRefName) {
74
- if (field.kind === "scalar") {
75
- const base = scalarToSchema(field.type);
76
- if (field.isList) return { type: "array", items: base };
77
- return base;
78
- }
79
- if (field.kind === "enum") {
80
- const base = { $ref: `#/components/schemas/${field.type}` };
81
- if (field.isList) return { type: "array", items: base };
82
- return base;
83
- }
84
- if (field.kind === "object") {
85
- const ref = { $ref: `#/components/schemas/${getRefName(String(field.type))}` };
86
- if (field.isList) return { type: "array", items: ref };
87
- return ref;
88
- }
89
- return { type: "object" };
90
- }
91
- function modelToGetSchema(model, getRefName) {
92
- const properties = {};
93
- const required = [];
94
- for (const f of model.fields) {
95
- properties[f.name] = fieldSchema(f, getRefName);
96
- if (f.isRequired) required.push(f.name);
97
- }
98
- const schema = { type: "object", properties };
99
- if (required.length) schema.required = required;
100
- return schema;
101
- }
102
- function stripWriteFields(model, getSchema, omit) {
103
- const schema = JSON.parse(JSON.stringify(getSchema));
104
- if (!schema.properties) return schema;
105
- const relationFieldNames = new Set(model.fields.filter((f) => f.kind === "object").map((f) => f.name));
106
- for (const key of Object.keys(schema.properties)) {
107
- if (omit.has(key) || relationFieldNames.has(key)) {
108
- delete schema.properties[key];
109
- }
110
- }
111
- if (Array.isArray(schema.required)) {
112
- schema.required = schema.required.filter((k) => !omit.has(k) && !relationFieldNames.has(k));
113
- if (schema.required.length === 0) delete schema.required;
114
- }
115
- return schema;
116
- }
117
- function makeAllOptional(schema) {
118
- const s = JSON.parse(JSON.stringify(schema));
119
- delete s.required;
120
- return s;
121
- }
122
- function listResponseSchema(itemRef) {
123
- return {
124
- type: "object",
125
- properties: {
126
- count: { type: "number" },
127
- hasPreviousPage: { type: "boolean" },
128
- hasNextPage: { type: "boolean" },
129
- pageNumber: { type: "number" },
130
- pageSize: { type: "number" },
131
- totalPages: { type: "number" },
132
- items: { type: "array", items: { $ref: itemRef } }
133
- },
134
- required: ["count", "hasPreviousPage", "hasNextPage", "pageNumber", "pageSize", "totalPages", "items"]
135
- };
136
- }
137
- async function buildSchemasFromPrismaDmmf(schemaPath) {
138
- const dmmf = await loadDmmfFromProject(schemaPath);
139
- const schemas = {};
140
- const getRefName = (modelName) => `Get${modelName}Response`;
141
- for (const e of dmmf.datamodel.enums) {
142
- schemas[e.name] = { type: "string", enum: e.values.map((v) => v.name) };
143
- }
144
- for (const model of dmmf.datamodel.models) {
145
- const getName = `Get${model.name}Response`;
146
- const postName = `Post${model.name}Request`;
147
- const putName = `Put${model.name}Request`;
148
- const listName = `List${pluralize(model.name)}Response`;
149
- const getSchema = modelToGetSchema(model, getRefName);
150
- const postSchema = stripWriteFields(model, getSchema, CONFIG.omitFieldsInWriteDtos);
151
- const putSchema = makeAllOptional(postSchema);
152
- schemas[getName] = getSchema;
153
- schemas[postName] = postSchema;
154
- schemas[putName] = putSchema;
155
- schemas[listName] = listResponseSchema(`#/components/schemas/${getName}`);
156
- }
157
- return schemas;
158
- }
159
- function generateSwaggerConfigJs(schemas) {
160
- const routes = globSync(CONFIG.controllersGlob, { nodir: true }).map((p) => ensurePosix(p));
161
- const docs = {
162
- info: { title: CONFIG.serviceTitle },
163
- servers: [{ url: CONFIG.serverUrl }],
164
- components: {
165
- schemas,
166
- securitySchemes: {
167
- [CONFIG.securitySchemeName]: {
168
- type: "oauth2",
169
- description: "This API uses OAuth2 with the password flow.",
170
- flows: {
171
- password: {
172
- tokenUrl: CONFIG.oauth.tokenUrl,
173
- refreshUrl: CONFIG.oauth.refreshUrl,
174
- scopes: CONFIG.oauth.scopes
175
- }
176
- }
177
- }
178
- }
179
- },
180
- security: [{ [CONFIG.securitySchemeName]: ["openid"] }]
181
- };
182
- const fileContent = `const swaggerAutogen = require('swagger-autogen')();
183
- const docs = ${JSON.stringify(docs, null, 2)};
184
- const routes = ${JSON.stringify(routes, null, 2)};
185
- swaggerAutogen('${ensurePosix(CONFIG.openapiOut)}', routes, docs);`;
186
- fs.writeFileSync(path.resolve(CONFIG.projectRoot, CONFIG.outFile), fileContent, "utf8");
187
- }
188
- async function run(args = []) {
189
- const schemaFlagIndex = args.findIndex((a) => a === "--schema");
190
- const schemaPath = schemaFlagIndex >= 0 ? args[schemaFlagIndex + 1] : void 0;
191
- const schemas = await buildSchemasFromPrismaDmmf(schemaPath);
192
- generateSwaggerConfigJs(schemas);
193
- }
194
-
195
- export {
196
- run
197
- };
package/dist/cli.d.cts DELETED
@@ -1,2 +0,0 @@
1
-
2
- export { }
package/dist/cli.d.ts DELETED
@@ -1,2 +0,0 @@
1
-
2
- export { }
package/dist/cli.js DELETED
@@ -1,9 +0,0 @@
1
- import {
2
- run
3
- } from "./chunk-HDG7TBSN.js";
4
-
5
- // src/cli.ts
6
- void run(process.argv.slice(2)).catch((e) => {
7
- console.error(e);
8
- process.exitCode = 1;
9
- });
package/dist/index.cjs DELETED
@@ -1,6 +0,0 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true});
2
-
3
- var _chunkD67FQWAIcjs = require('./chunk-D67FQWAI.cjs');
4
-
5
-
6
- exports.run = _chunkD67FQWAIcjs.run;
package/dist/index.d.cts DELETED
@@ -1,3 +0,0 @@
1
- declare function run(args?: string[]): Promise<void>;
2
-
3
- export { run };
package/dist/index.d.ts DELETED
@@ -1,3 +0,0 @@
1
- declare function run(args?: string[]): Promise<void>;
2
-
3
- export { run };
package/dist/index.js DELETED
@@ -1,6 +0,0 @@
1
- import {
2
- run
3
- } from "./chunk-HDG7TBSN.js";
4
- export {
5
- run
6
- };