prisma-swagger-autogen 1.0.5 → 1.0.7

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