api-core-lib 12.0.36 → 12.0.37
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/cli.cjs +101 -27
- package/package.json +1 -1
package/dist/cli.cjs
CHANGED
|
@@ -33,8 +33,14 @@ var import_path = __toESM(require("path"), 1);
|
|
|
33
33
|
var import_axios = __toESM(require("axios"), 1);
|
|
34
34
|
var import_chalk = __toESM(require("chalk"), 1);
|
|
35
35
|
var import_dotenv = __toESM(require("dotenv"), 1);
|
|
36
|
+
var import_child_process = require("child_process");
|
|
36
37
|
|
|
37
38
|
// src/generator/module-parser.ts
|
|
39
|
+
function refToTypeName(ref) {
|
|
40
|
+
if (!ref) return "unknown";
|
|
41
|
+
const parts = ref.replace(/^#\/components\//, "").split("/");
|
|
42
|
+
return `components["${parts.join('"]["')}"]`;
|
|
43
|
+
}
|
|
38
44
|
function parseSpecToModules(spec) {
|
|
39
45
|
const modules = {};
|
|
40
46
|
for (const apiPath in spec.paths) {
|
|
@@ -44,22 +50,23 @@ function parseSpecToModules(spec) {
|
|
|
44
50
|
const tagName = endpoint.tags[0];
|
|
45
51
|
const moduleName = tagName.replace(/[^a-zA-Z0-9]/g, "").replace(/Central|Tenant/g, "") + "Api";
|
|
46
52
|
if (!modules[moduleName]) {
|
|
47
|
-
modules[moduleName] = {
|
|
48
|
-
baseEndpoint: "",
|
|
49
|
-
// سيتم ملء المسار الكامل في path
|
|
50
|
-
actions: {}
|
|
51
|
-
};
|
|
53
|
+
modules[moduleName] = { actions: {} };
|
|
52
54
|
}
|
|
53
|
-
const
|
|
55
|
+
const requestBodyRef = endpoint.requestBody?.content["application/json"]?.schema?.$ref;
|
|
56
|
+
const successResponse = endpoint.responses["200"] || endpoint.responses["201"];
|
|
57
|
+
const responseRef = successResponse?.content?.["application/json"]?.schema?.$ref;
|
|
58
|
+
const actionName = endpoint.operationId || `${method}${apiPath.replace(/[\/{}]+/g, "_")}`;
|
|
54
59
|
modules[moduleName].actions[actionName] = {
|
|
55
60
|
method: method.toUpperCase(),
|
|
56
61
|
path: apiPath,
|
|
57
62
|
description: endpoint.summary || "No description available.",
|
|
58
63
|
hasQuery: (endpoint.parameters || []).some((p) => p.in === "query"),
|
|
59
64
|
autoFetch: method.toUpperCase() === "GET" && !apiPath.includes("{"),
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
//
|
|
65
|
+
invalidates: [],
|
|
66
|
+
// [ميزة جديدة] إضافة الأنواع المستخرجة إلى الكائن
|
|
67
|
+
// سنستخدمها لاحقًا لتوليد الكود الصحيح
|
|
68
|
+
_inputType: refToTypeName(requestBodyRef),
|
|
69
|
+
_outputType: refToTypeName(responseRef)
|
|
63
70
|
};
|
|
64
71
|
}
|
|
65
72
|
}
|
|
@@ -67,44 +74,111 @@ function parseSpecToModules(spec) {
|
|
|
67
74
|
}
|
|
68
75
|
|
|
69
76
|
// src/generator/index.ts
|
|
70
|
-
var import_child_process = require("child_process");
|
|
71
77
|
async function runGenerator(options) {
|
|
72
|
-
console.log(import_chalk.default.cyan(
|
|
78
|
+
console.log(import_chalk.default.cyan.bold("\u{1F680} Starting API Core Lib Code Generator..."));
|
|
73
79
|
console.log(import_chalk.default.gray(`Output directory: ${options.output}`));
|
|
74
80
|
console.log(import_chalk.default.gray(`.env path: ${options.envPath}`));
|
|
81
|
+
console.log("\n" + import_chalk.default.blue("Step 1: Loading environment variables..."));
|
|
75
82
|
import_dotenv.default.config({ path: options.envPath });
|
|
76
|
-
const
|
|
77
|
-
if (!
|
|
78
|
-
console.error(import_chalk.default.red("Error:
|
|
83
|
+
const specUrl = process.env.OPENAPI_SPEC_URL || (process.env.API_URL ? `${process.env.API_URL}/docs-json` : null) || (process.env.NEXT_PUBLIC_API_URL ? `${process.env.NEXT_PUBLIC_API_URL}/docs-json` : null);
|
|
84
|
+
if (!specUrl) {
|
|
85
|
+
console.error(import_chalk.default.red.bold("\n\u274C Error: API specification URL not found."));
|
|
86
|
+
console.error(import_chalk.default.red("Please define either OPENAPI_SPEC_URL (recommended) or API_URL/NEXT_PUBLIC_API_URL in your .env file."));
|
|
79
87
|
process.exit(1);
|
|
80
88
|
}
|
|
89
|
+
console.log(import_chalk.default.green("\u2713 Environment variables loaded."));
|
|
90
|
+
const tempSpecPath = import_path.default.join(process.cwd(), `swagger-${Date.now()}.json`);
|
|
81
91
|
try {
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
const response = await import_axios.default.get(specUrl);
|
|
92
|
+
console.log("\n" + import_chalk.default.blue(`Step 2: Fetching OpenAPI spec from ${specUrl}...`));
|
|
93
|
+
const response = await import_axios.default.get(specUrl, { timeout: 15e3 });
|
|
85
94
|
const spec = response.data;
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
95
|
+
if (!spec.openapi || !spec.paths) {
|
|
96
|
+
throw new Error('Invalid OpenAPI specification file. "openapi" or "paths" property is missing.');
|
|
97
|
+
}
|
|
98
|
+
import_fs.default.writeFileSync(tempSpecPath, JSON.stringify(spec, null, 2));
|
|
99
|
+
console.log(import_chalk.default.green(`\u2713 OpenAPI spec saved temporarily to ${tempSpecPath}`));
|
|
100
|
+
console.log("\n" + import_chalk.default.blue("Step 3: Generating organized TypeScript types..."));
|
|
90
101
|
const typesOutputPath = import_path.default.join(options.output, "types");
|
|
91
|
-
const generatorCommand =
|
|
102
|
+
const generatorCommand = [
|
|
103
|
+
"npx",
|
|
104
|
+
"@openapitools/openapi-generator-cli",
|
|
105
|
+
"generate",
|
|
106
|
+
"-i",
|
|
107
|
+
`"${tempSpecPath}"`,
|
|
108
|
+
"-g",
|
|
109
|
+
"typescript-axios",
|
|
110
|
+
"-o",
|
|
111
|
+
`"${typesOutputPath}"`,
|
|
112
|
+
"--additional-properties=supportsES6=true,useSingleRequestParameter=true,withInterfaces=true,modelPropertyNaming=original"
|
|
113
|
+
].join(" ");
|
|
114
|
+
console.log(import_chalk.default.gray(`Executing: ${generatorCommand}`));
|
|
92
115
|
(0, import_child_process.execSync)(generatorCommand, { stdio: "inherit" });
|
|
93
116
|
console.log(import_chalk.default.green(`\u2713 Types generated successfully at ${typesOutputPath}`));
|
|
94
|
-
console.log("Generating API modules
|
|
117
|
+
console.log("\n" + import_chalk.default.blue("Step 4: Generating custom API modules..."));
|
|
95
118
|
const modules = parseSpecToModules(spec);
|
|
96
119
|
const modulesOutputPath = import_path.default.join(options.output, "modules");
|
|
97
120
|
if (!import_fs.default.existsSync(modulesOutputPath)) {
|
|
98
121
|
import_fs.default.mkdirSync(modulesOutputPath, { recursive: true });
|
|
99
122
|
}
|
|
100
123
|
for (const moduleName in modules) {
|
|
124
|
+
const moduleData = modules[moduleName];
|
|
125
|
+
const fileName = `${moduleName}.module.ts`;
|
|
126
|
+
const filePath = import_path.default.join(modulesOutputPath, fileName);
|
|
127
|
+
const actionsTypeParts = Object.entries(moduleData.actions).map(([actionName, actionData]) => {
|
|
128
|
+
const inputType = actionData._inputType !== "unknown" ? actionData._inputType : actionData.hasQuery ? "QueryOptions" : "undefined";
|
|
129
|
+
const outputType = actionData._outputType;
|
|
130
|
+
return ` ${actionName}: ActionConfigModule<${inputType}, ${outputType}>;`;
|
|
131
|
+
});
|
|
132
|
+
const actionsTypeDefinition = `{
|
|
133
|
+
${actionsTypeParts.join("\n")}
|
|
134
|
+
}`;
|
|
135
|
+
const actionsValueParts = Object.entries(moduleData.actions).map(([actionName, actionData]) => {
|
|
136
|
+
const { _inputType, _outputType, ...config } = actionData;
|
|
137
|
+
return ` ${actionName}: ${JSON.stringify(config, null, 2).replace(/\n/g, "\n ")}`;
|
|
138
|
+
});
|
|
139
|
+
const actionsValueDefinition = `{
|
|
140
|
+
${actionsValueParts.join(",\n")}
|
|
141
|
+
}`;
|
|
142
|
+
const fileContent = `/**
|
|
143
|
+
* This file is auto-generated by api-core-lib.
|
|
144
|
+
* Do not edit this file directly.
|
|
145
|
+
* @module ${moduleName}
|
|
146
|
+
*/
|
|
147
|
+
|
|
148
|
+
import type { ApiModuleConfig, ActionConfigModule, QueryOptions } from 'api-core-lib';
|
|
149
|
+
import type { components } from '../types/api-types.generated';
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* Defines the configuration for the ${moduleName} API module.
|
|
153
|
+
* This is a strongly-typed configuration object that ensures type safety.
|
|
154
|
+
*/
|
|
155
|
+
export const ${moduleName}Module: ApiModuleCodeConfig<${actionsTypeDefinition}> = {
|
|
156
|
+
baseEndpoint: '/api/v1', // \u064A\u0645\u0643\u0646\u0643 \u062C\u0639\u0644\u0647 \u062F\u064A\u0646\u0627\u0645\u064A\u0643\u064A\u064B\u0627
|
|
157
|
+
actions: ${actionsValueDefinition},
|
|
158
|
+
};
|
|
159
|
+
`;
|
|
160
|
+
import_fs.default.writeFileSync(filePath, fileContent);
|
|
161
|
+
console.log(import_chalk.default.green(`\u2713 Module generated: ${fileName}`));
|
|
101
162
|
}
|
|
102
|
-
|
|
103
|
-
console.log(import_chalk.default.bold.green("\n\u{1F389} API generation complete!"));
|
|
163
|
+
console.log(import_chalk.default.green("\u2713 All custom modules generated."));
|
|
164
|
+
console.log(import_chalk.default.bold.green("\n\u{1F389} API generation complete! All files are located in:"));
|
|
165
|
+
console.log(import_chalk.default.bold.cyan(options.output));
|
|
104
166
|
} catch (error) {
|
|
105
|
-
console.error(import_chalk.default.red("\
|
|
106
|
-
|
|
167
|
+
console.error(import_chalk.default.red.bold("\n\u274C An error occurred during generation:"));
|
|
168
|
+
if (error.response) {
|
|
169
|
+
console.error(import_chalk.default.red(`Network Error: ${error.message} (Status: ${error.response.status})`));
|
|
170
|
+
} else if (error.stderr) {
|
|
171
|
+
console.error(import_chalk.default.red(`Command Execution Error: ${error.message}`));
|
|
172
|
+
console.error(import_chalk.default.gray(error.stderr.toString()));
|
|
173
|
+
} else {
|
|
174
|
+
console.error(import_chalk.default.red(error.message));
|
|
175
|
+
}
|
|
107
176
|
process.exit(1);
|
|
177
|
+
} finally {
|
|
178
|
+
if (import_fs.default.existsSync(tempSpecPath)) {
|
|
179
|
+
import_fs.default.unlinkSync(tempSpecPath);
|
|
180
|
+
console.log(import_chalk.default.gray("\nTemporary spec file cleaned up."));
|
|
181
|
+
}
|
|
108
182
|
}
|
|
109
183
|
}
|
|
110
184
|
|