anl 1.7.3 → 1.7.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.ar.md +59 -15
- package/README.es.md +45 -1
- package/README.fr.md +59 -15
- package/README.jp.md +45 -1
- package/README.md +44 -0
- package/README.ru.md +59 -15
- package/README.zh.md +63 -37
- package/lib/data/openapi.json.js +1 -0
- package/lib/package.json.js +1 -1
- package/lib/src/build-type/core/components.js +1 -1
- package/lib/src/build-type/core/path.js +1 -1
- package/lib/src/build-type/index.js +1 -1
- package/lib/src/git-local-config/index.js +1 -1
- package/lib/src/git-local-config/utils.js +1 -1
- package/lib/src/index.js +1 -1
- package/package.json +1 -1
- package/lib/data/open-api.json.js +0 -1
package/README.ar.md
CHANGED
|
@@ -89,7 +89,7 @@ $ pnpm add -g anl
|
|
|
89
89
|
### طريقة الاستخدام
|
|
90
90
|
|
|
91
91
|
```bash
|
|
92
|
-
$ anl
|
|
92
|
+
$ anl type
|
|
93
93
|
```
|
|
94
94
|
|
|
95
95
|
### شرح ملف التكوين بالتفصيل
|
|
@@ -127,20 +127,21 @@ $ anl lint
|
|
|
127
127
|
|
|
128
128
|
#### شرح عناصر التكوين
|
|
129
129
|
|
|
130
|
-
| عنصر التكوين | النوع | مطلوب | الوصف
|
|
131
|
-
| ------------------------ | ------------------------------------- | ----- |
|
|
132
|
-
| saveTypeFolderPath | string | نعم | مسار حفظ ملفات تعريف الأنواع
|
|
133
|
-
| saveApiListFolderPath | string | نعم | مسار حفظ ملفات دوال طلبات API
|
|
134
|
-
| saveEnumFolderPath | string | نعم | مسار حفظ ملفات بيانات التعداد
|
|
135
|
-
| importEnumPath | string | نعم | مسار استيراد التعداد (مسار ملف enum المُشار إليه في apps/types/models/\*.ts)
|
|
136
|
-
| swaggerJsonUrl | string | نعم | عنوان مستند Swagger JSON
|
|
137
|
-
| requestMethodsImportPath | string | نعم | مسار استيراد طرق الطلب
|
|
138
|
-
| dataLevel | 'data' \| 'serve' \| 'axios' | نعم | مستوى بيانات استجابة الواجهة
|
|
139
|
-
| formatting | object | لا | تكوين تنسيق الكود
|
|
140
|
-
| headers | object | لا | تكوين رأس الطلب
|
|
141
|
-
| includeInterface | Array<{path: string, method: string}> | لا | الواجهات المضمنة: ملف قائمة الواجهات المحدد بـ `saveApiListFolderPath` سيتضمن فقط الواجهات في القائمة، متعارض مع حقل `excludeInterface`
|
|
142
|
-
| excludeInterface | Array<{path: string, method: string}> | لا | الواجهات المستبعدة: نص قائمة الواجهات المحدد بـ `saveApiListFolderPath` لن يتضمن الواجهات في هذه القائمة، متعارض مع `includeInterface`
|
|
143
|
-
| publicPrefix | string | لا | البادئة العامة على مسار url، على سبيل المثال: api/users، api/users/{id}، api هي البادئة العامة
|
|
130
|
+
| عنصر التكوين | النوع | مطلوب | الوصف |
|
|
131
|
+
| ------------------------ | ------------------------------------- | ----- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
132
|
+
| saveTypeFolderPath | string | نعم | مسار حفظ ملفات تعريف الأنواع |
|
|
133
|
+
| saveApiListFolderPath | string | نعم | مسار حفظ ملفات دوال طلبات API |
|
|
134
|
+
| saveEnumFolderPath | string | نعم | مسار حفظ ملفات بيانات التعداد |
|
|
135
|
+
| importEnumPath | string | نعم | مسار استيراد التعداد (مسار ملف enum المُشار إليه في apps/types/models/\*.ts) |
|
|
136
|
+
| swaggerJsonUrl | string | نعم | عنوان مستند Swagger JSON |
|
|
137
|
+
| requestMethodsImportPath | string | نعم | مسار استيراد طرق الطلب |
|
|
138
|
+
| dataLevel | 'data' \| 'serve' \| 'axios' | نعم | مستوى بيانات استجابة الواجهة |
|
|
139
|
+
| formatting | object | لا | تكوين تنسيق الكود |
|
|
140
|
+
| headers | object | لا | تكوين رأس الطلب |
|
|
141
|
+
| includeInterface | Array<{path: string, method: string}> | لا | الواجهات المضمنة: ملف قائمة الواجهات المحدد بـ `saveApiListFolderPath` سيتضمن فقط الواجهات في القائمة، متعارض مع حقل `excludeInterface` |
|
|
142
|
+
| excludeInterface | Array<{path: string, method: string}> | لا | الواجهات المستبعدة: نص قائمة الواجهات المحدد بـ `saveApiListFolderPath` لن يتضمن الواجهات في هذه القائمة، متعارض مع `includeInterface` |
|
|
143
|
+
| publicPrefix | string | لا | البادئة العامة على مسار url، على سبيل المثال: api/users، api/users/{id}، api هي البادئة العامة |
|
|
144
|
+
| erasableSyntaxOnly | boolean | نعم | يتوافق مع خيار `compilerOptions.erasableSyntaxOnly` في tsconfig.json. عندما يكون `true`، يتم إنشاء كائن const بدلاً من enum (صيغة النوع فقط). القيمة الافتراضية: `false` |
|
|
144
145
|
|
|
145
146
|
#### العلاقة بين عناصر التكوين والملفات المولدة
|
|
146
147
|
|
|
@@ -201,6 +202,49 @@ export const userDetailGet = (params: UserDetail_GET.Query) => GET<UserDetail_GE
|
|
|
201
202
|
- يدعم أنواع المصفوفات والكائنات والتعدادات وغيرها
|
|
202
203
|
- توليد تعليقات الواجهة تلقائيًا
|
|
203
204
|
|
|
205
|
+
#### توليد التعداد
|
|
206
|
+
|
|
207
|
+
تدعم الأداة وضعين لتوليد التعداد، يتم التحكم فيهما من خلال تكوين `erasableSyntaxOnly`:
|
|
208
|
+
|
|
209
|
+
**وضع التعداد التقليدي** (`erasableSyntaxOnly: false`، القيمة الافتراضية):
|
|
210
|
+
|
|
211
|
+
```typescript
|
|
212
|
+
export enum Status {
|
|
213
|
+
Success = 'Success',
|
|
214
|
+
Error = 'Error',
|
|
215
|
+
Pending = 'Pending',
|
|
216
|
+
}
|
|
217
|
+
```
|
|
218
|
+
|
|
219
|
+
**وضع الكائن الثابت** (`erasableSyntaxOnly: true`):
|
|
220
|
+
|
|
221
|
+
```typescript
|
|
222
|
+
export const Status = {
|
|
223
|
+
Success: 'Success',
|
|
224
|
+
Error: 'Error',
|
|
225
|
+
Pending: 'Pending',
|
|
226
|
+
} as const;
|
|
227
|
+
|
|
228
|
+
export type StatusType = (typeof Status)[keyof typeof Status];
|
|
229
|
+
```
|
|
230
|
+
|
|
231
|
+
> **لماذا نستخدم وضع الكائن الثابت؟**
|
|
232
|
+
> عندما يتم تعيين `compilerOptions.erasableSyntaxOnly` في TypeScript إلى `true`، يمكن للكود استخدام صيغة النوع القابلة للمسح فقط. يولد `enum` التقليدي كود وقت التشغيل، بينما الكائن الثابت هو نوع خالص ويتم مسحه بالكامل بعد الترجمة. هذا يضمن التوافق مع أدوات البناء التي تتطلب صيغة النوع فقط.
|
|
233
|
+
|
|
234
|
+
**الاستخدام في الأنواع:**
|
|
235
|
+
|
|
236
|
+
```typescript
|
|
237
|
+
// وضع التعداد التقليدي
|
|
238
|
+
interface User {
|
|
239
|
+
status: Status; // استخدام التعداد مباشرة كنوع
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
// وضع الكائن الثابت
|
|
243
|
+
interface User {
|
|
244
|
+
status: StatusType; // استخدام النوع المولد بلاحقة 'Type'
|
|
245
|
+
}
|
|
246
|
+
```
|
|
247
|
+
|
|
204
248
|
#### تحميل الملفات
|
|
205
249
|
|
|
206
250
|
عند اكتشاف نوع تحميل ملف، سيتم إضافة رأس الطلب المقابل تلقائيًا:
|
package/README.es.md
CHANGED
|
@@ -87,7 +87,7 @@ $ pnpm add -g anl
|
|
|
87
87
|
### Método de Uso
|
|
88
88
|
|
|
89
89
|
```bash
|
|
90
|
-
$ anl
|
|
90
|
+
$ anl type
|
|
91
91
|
```
|
|
92
92
|
|
|
93
93
|
### Explicación Detallada del Archivo de Configuración
|
|
@@ -139,6 +139,7 @@ $ anl lint
|
|
|
139
139
|
| includeInterface | Array<{path: string, method: string}> | No | Interfaces incluidas: el archivo de lista de interfaces especificado por `saveApiListFolderPath` solo incluirá las interfaces en la lista, es mutuamente excluyente con el campo `excludeInterface` |
|
|
140
140
|
| excludeInterface | Array<{path: string, method: string}> | No | Interfaces excluidas: el texto de lista de interfaces especificado por `saveApiListFolderPath` no incluirá las interfaces en esta lista, es mutuamente excluyente con `includeInterface` |
|
|
141
141
|
| publicPrefix | string | No | Prefijo público en la ruta URL, por ejemplo: api/users, api/users/{id}, api es el prefijo público |
|
|
142
|
+
| erasableSyntaxOnly | boolean | Sí | Alineado con la opción `compilerOptions.erasableSyntaxOnly` de tsconfig.json. Cuando es `true`, genera objetos const en lugar de enum (solo sintaxis de tipo). Valor predeterminado: `false` |
|
|
142
143
|
|
|
143
144
|
#### Relación entre Elementos de Configuración y Archivos Generados
|
|
144
145
|
|
|
@@ -199,6 +200,49 @@ export const userDetailGet = (params: UserDetail_GET.Query) => GET<UserDetail_GE
|
|
|
199
200
|
- Soporte para tipos como arrays, objetos, enums, etc.
|
|
200
201
|
- Generación automática de comentarios de interfaz
|
|
201
202
|
|
|
203
|
+
#### Generación de Enumeraciones
|
|
204
|
+
|
|
205
|
+
La herramienta admite dos modos de generación de enumeraciones, controlados mediante la configuración `erasableSyntaxOnly`:
|
|
206
|
+
|
|
207
|
+
**Modo de enumeración tradicional** (`erasableSyntaxOnly: false`, valor predeterminado):
|
|
208
|
+
|
|
209
|
+
```typescript
|
|
210
|
+
export enum Status {
|
|
211
|
+
Success = 'Success',
|
|
212
|
+
Error = 'Error',
|
|
213
|
+
Pending = 'Pending',
|
|
214
|
+
}
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
**Modo de objeto constante** (`erasableSyntaxOnly: true`):
|
|
218
|
+
|
|
219
|
+
```typescript
|
|
220
|
+
export const Status = {
|
|
221
|
+
Success: 'Success',
|
|
222
|
+
Error: 'Error',
|
|
223
|
+
Pending: 'Pending',
|
|
224
|
+
} as const;
|
|
225
|
+
|
|
226
|
+
export type StatusType = (typeof Status)[keyof typeof Status];
|
|
227
|
+
```
|
|
228
|
+
|
|
229
|
+
> **¿Por qué usar el modo de objeto constante?**
|
|
230
|
+
> Cuando la opción `compilerOptions.erasableSyntaxOnly` de TypeScript está configurada en `true`, el código solo puede usar sintaxis de tipo borrable. Los `enum` tradicionales generan código en tiempo de ejecución, mientras que los objetos constantes son puramente de tipo y se eliminan completamente después de la compilación. Esto garantiza la compatibilidad con herramientas de construcción que requieren sintaxis solo de tipo.
|
|
231
|
+
|
|
232
|
+
**Uso en tipos:**
|
|
233
|
+
|
|
234
|
+
```typescript
|
|
235
|
+
// Modo de enumeración tradicional
|
|
236
|
+
interface User {
|
|
237
|
+
status: Status; // Usar directamente la enumeración como tipo
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
// Modo de objeto constante
|
|
241
|
+
interface User {
|
|
242
|
+
status: StatusType; // Usar el tipo generado con sufijo 'Type'
|
|
243
|
+
}
|
|
244
|
+
```
|
|
245
|
+
|
|
202
246
|
#### Carga de Archivos
|
|
203
247
|
|
|
204
248
|
Cuando se detecta un tipo de carga de archivo, se añaden automáticamente los encabezados de solicitud correspondientes:
|
package/README.fr.md
CHANGED
|
@@ -89,7 +89,7 @@ $ pnpm add -g anl
|
|
|
89
89
|
### Méthode d'utilisation
|
|
90
90
|
|
|
91
91
|
```bash
|
|
92
|
-
$ anl
|
|
92
|
+
$ anl type
|
|
93
93
|
```
|
|
94
94
|
|
|
95
95
|
### Explication détaillée du fichier de configuration
|
|
@@ -127,20 +127,21 @@ $ anl lint
|
|
|
127
127
|
|
|
128
128
|
#### Explication des éléments de configuration
|
|
129
129
|
|
|
130
|
-
| Élément de configuration | Type | Obligatoire | Description
|
|
131
|
-
| ------------------------ | ------------------------------------- | ----------- |
|
|
132
|
-
| saveTypeFolderPath | string | Oui | Chemin de sauvegarde des fichiers de définition de types
|
|
133
|
-
| saveApiListFolderPath | string | Oui | Chemin de sauvegarde des fichiers de fonctions de requête API
|
|
134
|
-
| saveEnumFolderPath | string | Oui | Chemin de sauvegarde des fichiers de données enum
|
|
135
|
-
| importEnumPath | string | Oui | Chemin d'import enum (chemin des fichiers enum référencés dans apps/types/models/\*.ts)
|
|
136
|
-
| swaggerJsonUrl | string | Oui | Adresse du document Swagger JSON
|
|
137
|
-
| requestMethodsImportPath | string | Oui | Chemin d'import des méthodes de requête
|
|
138
|
-
| dataLevel | 'data' \| 'serve' \| 'axios' | Oui | Niveau de données retournées par l'interface
|
|
139
|
-
| formatting | object | Non | Configuration du formatage du code
|
|
140
|
-
| headers | object | Non | Configuration des en-têtes de requête
|
|
141
|
-
| includeInterface | Array<{path: string, method: string}> | Non | Interfaces à inclure : Le fichier de liste d'interfaces spécifié par `saveApiListFolderPath` ne contiendra que les interfaces de la liste, mutuellement exclusif avec `excludeInterface`
|
|
142
|
-
| excludeInterface | Array<{path: string, method: string}> | Non | Interfaces à exclure : Le fichier de liste d'interfaces spécifié par `saveApiListFolderPath` ne contiendra pas les interfaces de cette liste, mutuellement exclusif avec `includeInterface`
|
|
143
|
-
| publicPrefix | string | Non | Préfixe commun sur le chemin URL, par exemple : api/users, api/users/{id}, api est le préfixe commun
|
|
130
|
+
| Élément de configuration | Type | Obligatoire | Description |
|
|
131
|
+
| ------------------------ | ------------------------------------- | ----------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
132
|
+
| saveTypeFolderPath | string | Oui | Chemin de sauvegarde des fichiers de définition de types |
|
|
133
|
+
| saveApiListFolderPath | string | Oui | Chemin de sauvegarde des fichiers de fonctions de requête API |
|
|
134
|
+
| saveEnumFolderPath | string | Oui | Chemin de sauvegarde des fichiers de données enum |
|
|
135
|
+
| importEnumPath | string | Oui | Chemin d'import enum (chemin des fichiers enum référencés dans apps/types/models/\*.ts) |
|
|
136
|
+
| swaggerJsonUrl | string | Oui | Adresse du document Swagger JSON |
|
|
137
|
+
| requestMethodsImportPath | string | Oui | Chemin d'import des méthodes de requête |
|
|
138
|
+
| dataLevel | 'data' \| 'serve' \| 'axios' | Oui | Niveau de données retournées par l'interface |
|
|
139
|
+
| formatting | object | Non | Configuration du formatage du code |
|
|
140
|
+
| headers | object | Non | Configuration des en-têtes de requête |
|
|
141
|
+
| includeInterface | Array<{path: string, method: string}> | Non | Interfaces à inclure : Le fichier de liste d'interfaces spécifié par `saveApiListFolderPath` ne contiendra que les interfaces de la liste, mutuellement exclusif avec `excludeInterface` |
|
|
142
|
+
| excludeInterface | Array<{path: string, method: string}> | Non | Interfaces à exclure : Le fichier de liste d'interfaces spécifié par `saveApiListFolderPath` ne contiendra pas les interfaces de cette liste, mutuellement exclusif avec `includeInterface` |
|
|
143
|
+
| publicPrefix | string | Non | Préfixe commun sur le chemin URL, par exemple : api/users, api/users/{id}, api est le préfixe commun |
|
|
144
|
+
| erasableSyntaxOnly | boolean | Oui | Doit être cohérent avec l'option `compilerOptions.erasableSyntaxOnly` de tsconfig.json. Si `true`, génère un objet const au lieu d'un enum (syntaxe de type uniquement). Valeur par défaut : `false` |
|
|
144
145
|
|
|
145
146
|
#### Relation entre les éléments de configuration et les fichiers générés
|
|
146
147
|
|
|
@@ -201,6 +202,49 @@ export const userDetailGet = (params: UserDetail_GET.Query) => GET<UserDetail_GE
|
|
|
201
202
|
- Support des types array, object, enum, etc.
|
|
202
203
|
- Génération automatique de commentaires d'interface
|
|
203
204
|
|
|
205
|
+
#### Génération d'enum
|
|
206
|
+
|
|
207
|
+
L'outil prend en charge deux modes de génération d'enum, contrôlés par la configuration `erasableSyntaxOnly` :
|
|
208
|
+
|
|
209
|
+
**Mode enum traditionnel** (`erasableSyntaxOnly: false`, valeur par défaut) :
|
|
210
|
+
|
|
211
|
+
```typescript
|
|
212
|
+
export enum Status {
|
|
213
|
+
Success = 'Success',
|
|
214
|
+
Error = 'Error',
|
|
215
|
+
Pending = 'Pending',
|
|
216
|
+
}
|
|
217
|
+
```
|
|
218
|
+
|
|
219
|
+
**Mode objet constant** (`erasableSyntaxOnly: true`) :
|
|
220
|
+
|
|
221
|
+
```typescript
|
|
222
|
+
export const Status = {
|
|
223
|
+
Success: 'Success',
|
|
224
|
+
Error: 'Error',
|
|
225
|
+
Pending: 'Pending',
|
|
226
|
+
} as const;
|
|
227
|
+
|
|
228
|
+
export type StatusType = (typeof Status)[keyof typeof Status];
|
|
229
|
+
```
|
|
230
|
+
|
|
231
|
+
> **Pourquoi utiliser le mode objet constant ?**
|
|
232
|
+
> Lorsque `compilerOptions.erasableSyntaxOnly` de TypeScript est défini sur `true`, le code ne peut utiliser que la syntaxe de type effaçable. Les `enum` traditionnels génèrent du code d'exécution, tandis que les objets constants sont purement typés et sont complètement effacés après compilation. Cela garantit la compatibilité avec les outils de construction nécessitant une syntaxe de type uniquement.
|
|
233
|
+
|
|
234
|
+
**Utilisation dans les types :**
|
|
235
|
+
|
|
236
|
+
```typescript
|
|
237
|
+
// Mode enum traditionnel
|
|
238
|
+
interface User {
|
|
239
|
+
status: Status; // Utilise directement l'enum comme type
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
// Mode objet constant
|
|
243
|
+
interface User {
|
|
244
|
+
status: StatusType; // Utilise le type généré avec le suffixe 'Type'
|
|
245
|
+
}
|
|
246
|
+
```
|
|
247
|
+
|
|
204
248
|
#### Téléchargement de fichiers
|
|
205
249
|
|
|
206
250
|
Lorsqu'un type de téléchargement de fichier est détecté, les en-têtes de requête correspondants sont automatiquement ajoutés :
|
package/README.jp.md
CHANGED
|
@@ -89,7 +89,7 @@ $ pnpm add -g anl
|
|
|
89
89
|
### 使用方法
|
|
90
90
|
|
|
91
91
|
```bash
|
|
92
|
-
$ anl
|
|
92
|
+
$ anl type
|
|
93
93
|
```
|
|
94
94
|
|
|
95
95
|
### 設定ファイル詳細
|
|
@@ -141,6 +141,7 @@ $ anl lint
|
|
|
141
141
|
| includeInterface | Array<{path: string, method: string}> | いいえ | 含めるインターフェース:`saveApiListFolderPath` で指定されたインターフェースリストファイルには、このリストに含まれるインターフェースのみが含まれます。`excludeInterface` フィールドと相互排他的です |
|
|
142
142
|
| excludeInterface | Array<{path: string, method: string}> | いいえ | 除外するインターフェース:`saveApiListFolderPath` で指定されたインターフェースリストテキストには、このリストに含まれないインターフェースが含まれます。`includeInterface` と相互排他的です |
|
|
143
143
|
| publicPrefix | string | いいえ | URL パス上の共通プレフィックス、例:api/users、api/users/{id}、api が共通プレフィックスです |
|
|
144
|
+
| erasableSyntaxOnly | boolean | はい | tsconfig.json の `compilerOptions.erasableSyntaxOnly` オプションと一致させます。`true` の場合、enum ではなく const オブジェクトを生成します(型のみの構文)。デフォルト値:`false` |
|
|
144
145
|
|
|
145
146
|
#### 設定項目と生成ファイルの対応関係
|
|
146
147
|
|
|
@@ -201,6 +202,49 @@ export const userDetailGet = (params: UserDetail_GET.Query) => GET<UserDetail_GE
|
|
|
201
202
|
- 配列、オブジェクト、列挙型などの型をサポート
|
|
202
203
|
- インターフェースコメントの自動生成
|
|
203
204
|
|
|
205
|
+
#### 列挙型生成
|
|
206
|
+
|
|
207
|
+
ツールは 2 つの列挙型生成モードをサポートしており、`erasableSyntaxOnly` 設定で制御します:
|
|
208
|
+
|
|
209
|
+
**従来の列挙型モード** (`erasableSyntaxOnly: false`、デフォルト値):
|
|
210
|
+
|
|
211
|
+
```typescript
|
|
212
|
+
export enum Status {
|
|
213
|
+
Success = 'Success',
|
|
214
|
+
Error = 'Error',
|
|
215
|
+
Pending = 'Pending',
|
|
216
|
+
}
|
|
217
|
+
```
|
|
218
|
+
|
|
219
|
+
**定数オブジェクトモード** (`erasableSyntaxOnly: true`):
|
|
220
|
+
|
|
221
|
+
```typescript
|
|
222
|
+
export const Status = {
|
|
223
|
+
Success: 'Success',
|
|
224
|
+
Error: 'Error',
|
|
225
|
+
Pending: 'Pending',
|
|
226
|
+
} as const;
|
|
227
|
+
|
|
228
|
+
export type StatusType = (typeof Status)[keyof typeof Status];
|
|
229
|
+
```
|
|
230
|
+
|
|
231
|
+
> **なぜ定数オブジェクトモードを使用するのか?**
|
|
232
|
+
> TypeScript の `compilerOptions.erasableSyntaxOnly` が `true` に設定されている場合、コードは削除可能な型構文のみを使用できます。従来の `enum` は実行時コードを生成しますが、定数オブジェクトは純粋な型であり、コンパイル後に完全に削除されます。これにより、型のみの構文を要求するビルドツールとの互換性が保証されます。
|
|
233
|
+
|
|
234
|
+
**型での使用:**
|
|
235
|
+
|
|
236
|
+
```typescript
|
|
237
|
+
// 従来の列挙型モード
|
|
238
|
+
interface User {
|
|
239
|
+
status: Status; // 列挙型を直接型として使用
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
// 定数オブジェクトモード
|
|
243
|
+
interface User {
|
|
244
|
+
status: StatusType; // 生成された 'Type' サフィックス付きの型を使用
|
|
245
|
+
}
|
|
246
|
+
```
|
|
247
|
+
|
|
204
248
|
#### ファイルアップロード
|
|
205
249
|
|
|
206
250
|
ファイルアップロード型が検出されると、対応するリクエストヘッダーが自動的に追加されます:
|
package/README.md
CHANGED
|
@@ -139,6 +139,7 @@ $ anl type
|
|
|
139
139
|
| includeInterface | Array<{path: string, method: string}> | No | Included interfaces: The interface list file specified by `saveApiListFolderPath` will only include interfaces in the list, mutually exclusive with `excludeInterface` field |
|
|
140
140
|
| excludeInterface | Array<{path: string, method: string}> | No | Excluded interfaces: The interface list file specified by `saveApiListFolderPath` will not include interfaces in this list, mutually exclusive with `includeInterface` |
|
|
141
141
|
| publicPrefix | string | No | Common prefix on url path, e.g.: api/users, api/users/{id}, api is the common prefix |
|
|
142
|
+
| erasableSyntaxOnly | boolean | Yes | Align with tsconfig.json `compilerOptions.erasableSyntaxOnly`. When `true`, generates const objects instead of enums (type-only syntax). Default: `false` |
|
|
142
143
|
|
|
143
144
|
#### Configuration Items and Generated Files Correspondence
|
|
144
145
|
|
|
@@ -199,6 +200,49 @@ export const userDetailGet = (params: UserDetail_GET.Query) => GET<UserDetail_GE
|
|
|
199
200
|
- Supports arrays, objects, enums, and other types
|
|
200
201
|
- Automatically generates interface comments
|
|
201
202
|
|
|
203
|
+
#### Enum Generation
|
|
204
|
+
|
|
205
|
+
The tool supports two enum generation modes, controlled by the `erasableSyntaxOnly` configuration:
|
|
206
|
+
|
|
207
|
+
**Traditional Enum Mode** (`erasableSyntaxOnly: false`, default):
|
|
208
|
+
|
|
209
|
+
```typescript
|
|
210
|
+
export enum Status {
|
|
211
|
+
Success = 'Success',
|
|
212
|
+
Error = 'Error',
|
|
213
|
+
Pending = 'Pending',
|
|
214
|
+
}
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
**Const Object Mode** (`erasableSyntaxOnly: true`):
|
|
218
|
+
|
|
219
|
+
```typescript
|
|
220
|
+
export const Status = {
|
|
221
|
+
Success: 'Success',
|
|
222
|
+
Error: 'Error',
|
|
223
|
+
Pending: 'Pending',
|
|
224
|
+
} as const;
|
|
225
|
+
|
|
226
|
+
export type StatusType = (typeof Status)[keyof typeof Status];
|
|
227
|
+
```
|
|
228
|
+
|
|
229
|
+
> **Why use const object mode?**
|
|
230
|
+
> When TypeScript's `compilerOptions.erasableSyntaxOnly` is set to `true`, the code can only use type-erasable syntax. Traditional `enum` generates runtime code, while const objects are type-only and get completely erased during compilation. This ensures compatibility with build tools that require type-only syntax.
|
|
231
|
+
|
|
232
|
+
**Usage in types:**
|
|
233
|
+
|
|
234
|
+
```typescript
|
|
235
|
+
// Traditional enum mode
|
|
236
|
+
interface User {
|
|
237
|
+
status: Status; // Use enum as type directly
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
// Const object mode
|
|
241
|
+
interface User {
|
|
242
|
+
status: StatusType; // Use the generated type with 'Type' suffix
|
|
243
|
+
}
|
|
244
|
+
```
|
|
245
|
+
|
|
202
246
|
#### File Upload
|
|
203
247
|
|
|
204
248
|
When file upload types are detected, corresponding request headers are automatically added:
|
package/README.ru.md
CHANGED
|
@@ -89,7 +89,7 @@ $ pnpm add -g anl
|
|
|
89
89
|
### Способ использования
|
|
90
90
|
|
|
91
91
|
```bash
|
|
92
|
-
$ anl
|
|
92
|
+
$ anl type
|
|
93
93
|
```
|
|
94
94
|
|
|
95
95
|
### Подробное описание конфигурационного файла
|
|
@@ -127,20 +127,21 @@ $ anl lint
|
|
|
127
127
|
|
|
128
128
|
#### Описание элементов конфигурации
|
|
129
129
|
|
|
130
|
-
| Элемент конфигурации | Тип | Обязательный | Описание
|
|
131
|
-
| ------------------------ | ------------------------------------- | ------------ |
|
|
132
|
-
| saveTypeFolderPath | string | Да | Путь сохранения файлов определений типов
|
|
133
|
-
| saveApiListFolderPath | string | Да | Путь сохранения файлов функций API-запросов
|
|
134
|
-
| saveEnumFolderPath | string | Да | Путь сохранения файлов данных enum
|
|
135
|
-
| importEnumPath | string | Да | Путь импорта enum (путь ссылки на файлы enum в apps/types/models/\*.ts)
|
|
136
|
-
| swaggerJsonUrl | string | Да | Адрес документа Swagger JSON
|
|
137
|
-
| requestMethodsImportPath | string | Да | Путь импорта методов запросов
|
|
138
|
-
| dataLevel | 'data' \| 'serve' \| 'axios' | Да | Уровень данных возврата интерфейса
|
|
139
|
-
| formatting | object | Нет | Конфигурация форматирования кода
|
|
140
|
-
| headers | object | Нет | Конфигурация заголовков запроса
|
|
141
|
-
| includeInterface | Array<{path: string, method: string}> | Нет | Включаемые интерфейсы: файл списка интерфейсов, указанный `saveApiListFolderPath`, будет включать только интерфейсы из списка, взаимоисключающий с полем `excludeInterface`
|
|
142
|
-
| excludeInterface | Array<{path: string, method: string}> | Нет | Исключаемые интерфейсы: файл списка интерфейсов, указанный `saveApiListFolderPath`, не будет содержать интерфейсы из этого списка, взаимоисключающий с `includeInterface`
|
|
143
|
-
| publicPrefix | string | Нет | Общий префикс на url path, например: api/users、api/users/{id} ,api является общим префиксом
|
|
130
|
+
| Элемент конфигурации | Тип | Обязательный | Описание |
|
|
131
|
+
| ------------------------ | ------------------------------------- | ------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
132
|
+
| saveTypeFolderPath | string | Да | Путь сохранения файлов определений типов |
|
|
133
|
+
| saveApiListFolderPath | string | Да | Путь сохранения файлов функций API-запросов |
|
|
134
|
+
| saveEnumFolderPath | string | Да | Путь сохранения файлов данных enum |
|
|
135
|
+
| importEnumPath | string | Да | Путь импорта enum (путь ссылки на файлы enum в apps/types/models/\*.ts) |
|
|
136
|
+
| swaggerJsonUrl | string | Да | Адрес документа Swagger JSON |
|
|
137
|
+
| requestMethodsImportPath | string | Да | Путь импорта методов запросов |
|
|
138
|
+
| dataLevel | 'data' \| 'serve' \| 'axios' | Да | Уровень данных возврата интерфейса |
|
|
139
|
+
| formatting | object | Нет | Конфигурация форматирования кода |
|
|
140
|
+
| headers | object | Нет | Конфигурация заголовков запроса |
|
|
141
|
+
| includeInterface | Array<{path: string, method: string}> | Нет | Включаемые интерфейсы: файл списка интерфейсов, указанный `saveApiListFolderPath`, будет включать только интерфейсы из списка, взаимоисключающий с полем `excludeInterface` |
|
|
142
|
+
| excludeInterface | Array<{path: string, method: string}> | Нет | Исключаемые интерфейсы: файл списка интерфейсов, указанный `saveApiListFolderPath`, не будет содержать интерфейсы из этого списка, взаимоисключающий с `includeInterface` |
|
|
143
|
+
| publicPrefix | string | Нет | Общий префикс на url path, например: api/users、api/users/{id} ,api является общим префиксом |
|
|
144
|
+
| erasableSyntaxOnly | boolean | Да | Соответствует опции `compilerOptions.erasableSyntaxOnly` в tsconfig.json. При значении `true` генерируется const объект вместо enum (только типовый синтаксис). Значение по умолчанию: `false` |
|
|
144
145
|
|
|
145
146
|
#### Соответствие элементов конфигурации и генерируемых файлов
|
|
146
147
|
|
|
@@ -201,6 +202,49 @@ export const userDetailGet = (params: UserDetail_GET.Query) => GET<UserDetail_GE
|
|
|
201
202
|
- Поддержка массивов, объектов, enum и других типов
|
|
202
203
|
- Автоматическая генерация комментариев к интерфейсам
|
|
203
204
|
|
|
205
|
+
#### Генерация enum
|
|
206
|
+
|
|
207
|
+
Инструмент поддерживает два режима генерации enum, контролируемые через конфигурацию `erasableSyntaxOnly`:
|
|
208
|
+
|
|
209
|
+
**Традиционный режим enum** (`erasableSyntaxOnly: false`, значение по умолчанию):
|
|
210
|
+
|
|
211
|
+
```typescript
|
|
212
|
+
export enum Status {
|
|
213
|
+
Success = 'Success',
|
|
214
|
+
Error = 'Error',
|
|
215
|
+
Pending = 'Pending',
|
|
216
|
+
}
|
|
217
|
+
```
|
|
218
|
+
|
|
219
|
+
**Режим константного объекта** (`erasableSyntaxOnly: true`):
|
|
220
|
+
|
|
221
|
+
```typescript
|
|
222
|
+
export const Status = {
|
|
223
|
+
Success: 'Success',
|
|
224
|
+
Error: 'Error',
|
|
225
|
+
Pending: 'Pending',
|
|
226
|
+
} as const;
|
|
227
|
+
|
|
228
|
+
export type StatusType = (typeof Status)[keyof typeof Status];
|
|
229
|
+
```
|
|
230
|
+
|
|
231
|
+
> **Зачем использовать режим константного объекта?**
|
|
232
|
+
> Когда в TypeScript `compilerOptions.erasableSyntaxOnly` установлен в `true`, код может использовать только стираемый типовый синтаксис. Традиционный `enum` генерирует рантайм-код, в то время как константный объект является чисто типовым и полностью стирается после компиляции. Это обеспечивает совместимость с инструментами сборки, требующими только типовой синтаксис.
|
|
233
|
+
|
|
234
|
+
**Использование в типах:**
|
|
235
|
+
|
|
236
|
+
```typescript
|
|
237
|
+
// Традиционный режим enum
|
|
238
|
+
interface User {
|
|
239
|
+
status: Status; // Используйте enum напрямую как тип
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
// Режим константного объекта
|
|
243
|
+
interface User {
|
|
244
|
+
status: StatusType; // Используйте сгенерированный тип с суффиксом 'Type'
|
|
245
|
+
}
|
|
246
|
+
```
|
|
247
|
+
|
|
204
248
|
#### Загрузка файлов
|
|
205
249
|
|
|
206
250
|
При обнаружении типа загрузки файлов автоматически добавляются соответствующие заголовки запроса:
|
package/README.zh.md
CHANGED
|
@@ -7,17 +7,12 @@
|
|
|
7
7
|
> an-cli 是前端命令行工具,包含以下命令:
|
|
8
8
|
>
|
|
9
9
|
> - `anl type` 命令:基于 Swagger JSON 自动生成 TypeScript 类型定义和 API 请求函数的命令行工具。
|
|
10
|
-
>
|
|
11
10
|
> - `anl lint` 命令: 生成 react 或 vue 项目 eslint、stylelint、prettier、commitLint、VSCode相关配置
|
|
12
|
-
>
|
|
13
11
|
> - `anl git` 命令: 生成 git 本地配置,并设有可选功能: gitflow 标准分支创建、git commit messages 主题、git 自定义命令配置
|
|
14
12
|
|
|
15
|
-
|
|
16
|
-
|
|
17
13
|
# 功能特点
|
|
18
14
|
|
|
19
15
|
- `anl type`
|
|
20
|
-
|
|
21
16
|
- 🚀 自动解析 Swagger JSON 文档
|
|
22
17
|
- 📦 生成 TypeScript 类型定义文件
|
|
23
18
|
- 🔄 生成类型安全的 API 请求函数
|
|
@@ -26,23 +21,20 @@
|
|
|
26
21
|
- 🎨 支持代码格式化
|
|
27
22
|
- ⚡️ 支持文件上传
|
|
28
23
|
- 🛠 可配置的代码生成选项
|
|
29
|
-
|
|
24
|
+
|
|
30
25
|
- `anl lint`
|
|
31
|
-
|
|
32
26
|
- 🔍 一键配置各种 lint 工具
|
|
33
27
|
- 🎨 ESLint 配置自动化
|
|
34
28
|
- 🎯Prettier 格式化配置
|
|
35
29
|
- 🔄 CommitLint 提交规范
|
|
36
30
|
- 📦 VSCode 编辑器配置
|
|
37
|
-
|
|
31
|
+
|
|
38
32
|
- `anl git`
|
|
39
33
|
- 🔍 多种功能可选安装
|
|
40
34
|
- 🎨 标准 git flow 分支创建
|
|
41
35
|
- 🎯 符合 CommitLint 提交规范的主题自动设置
|
|
42
36
|
- 🔄 提供 git 自定义命令配置以及入口
|
|
43
37
|
- 📦 自动化生成 0 配置
|
|
44
|
-
|
|
45
|
-
|
|
46
38
|
|
|
47
39
|
# 安装
|
|
48
40
|
|
|
@@ -61,8 +53,6 @@ $ yarn global add anl
|
|
|
61
53
|
$ pnpm add -g anl
|
|
62
54
|
```
|
|
63
55
|
|
|
64
|
-
|
|
65
|
-
|
|
66
56
|
# 使用说明
|
|
67
57
|
|
|
68
58
|
> [!TIP]
|
|
@@ -71,8 +61,6 @@ $ pnpm add -g anl
|
|
|
71
61
|
> 2. 或者跟着下面步骤 一步一步做,就会有收获
|
|
72
62
|
> 3. 请在项目根目录执行 `anl type`、`anl lint`、 `anl git` 命令
|
|
73
63
|
|
|
74
|
-
|
|
75
|
-
|
|
76
64
|
## `anl type` 命令使用说明
|
|
77
65
|
|
|
78
66
|
- **首次**执行 `anl type`, 命令,会在*项目根目录下*, _自动创建_ 以 `an.config.json` 为名的配置文件(手动创建也可以)初始化配置模板。
|
|
@@ -92,22 +80,18 @@ $ pnpm add -g anl
|
|
|
92
80
|
|
|
93
81
|
- 如果 'config.ts', 'error-message.ts', 'fetch.ts', 'api-type.d.ts' 这些文件存在的话将不再重复生成
|
|
94
82
|
|
|
95
|
-
-
|
|
83
|
+
-
|
|
96
84
|
|
|
97
85
|
> [!NOTE]
|
|
98
86
|
>
|
|
99
87
|
> 如果不清楚这些配置,可以先执行 anl type 命令,将类型先生成,然后检查项目目录,结合配置项说明,调整配置项,再次生成,逐步验证配置项目作用,完成最终配置
|
|
100
88
|
|
|
101
|
-
|
|
102
|
-
|
|
103
89
|
### 使用方法
|
|
104
90
|
|
|
105
91
|
```bash
|
|
106
|
-
$ anl
|
|
92
|
+
$ anl type
|
|
107
93
|
```
|
|
108
94
|
|
|
109
|
-
|
|
110
|
-
|
|
111
95
|
### 配置文件详解
|
|
112
96
|
|
|
113
97
|
#### 配置文件示例
|
|
@@ -143,24 +127,25 @@ $ anl lint
|
|
|
143
127
|
|
|
144
128
|
#### 配置项说明
|
|
145
129
|
|
|
146
|
-
| 配置项 | 类型 | 必填 | 说明
|
|
147
|
-
| ------------------------ | ------------------------------------- | ---- |
|
|
148
|
-
| saveTypeFolderPath | string | 是 | 类型定义文件保存路径
|
|
149
|
-
| saveApiListFolderPath | string | 是 | API 请求函数文件保存路径
|
|
150
|
-
| saveEnumFolderPath | string | 是 | 枚举数据文件保存路径
|
|
151
|
-
| importEnumPath | string | 是 | 枚举导入路径(apps/types/models
|
|
152
|
-
| swaggerJsonUrl | string | 是 | Swagger JSON 文档地址
|
|
153
|
-
| requestMethodsImportPath | string | 是 | 请求方法导入路径
|
|
154
|
-
| dataLevel | 'data' \| 'serve' \| 'axios' | 是 | 接口返回数据层级
|
|
155
|
-
| formatting | object | 否 | 代码格式化配置
|
|
156
|
-
| headers | object | 否 | 请求头配置
|
|
157
|
-
| includeInterface | Array<{path: string, method: string}> | 否 | 包含的接口:`saveApiListFolderPath`指定的接口列表文件,只会包含列表中的接口,与 `excludeInterface` 字段互斥
|
|
158
|
-
| excludeInterface | Array<{path: string, method: string}> | 否 | 排除的接口: `saveApiListFolderPath` 指定的接口列表文本,不存在该列表中的接口,与 `includeInterface` 互斥
|
|
159
|
-
| publicPrefix | string | 否 | url path 上的公共前缀,例如:api/users、api/users/{id} ,api 就是公共前缀
|
|
130
|
+
| 配置项 | 类型 | 必填 | 说明 |
|
|
131
|
+
| ------------------------ | ------------------------------------- | ---- | -------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
132
|
+
| saveTypeFolderPath | string | 是 | 类型定义文件保存路径 |
|
|
133
|
+
| saveApiListFolderPath | string | 是 | API 请求函数文件保存路径 |
|
|
134
|
+
| saveEnumFolderPath | string | 是 | 枚举数据文件保存路径 |
|
|
135
|
+
| importEnumPath | string | 是 | 枚举导入路径(apps/types/models/\*.ts 中 enum 文件的引用的路径) |
|
|
136
|
+
| swaggerJsonUrl | string | 是 | Swagger JSON 文档地址 |
|
|
137
|
+
| requestMethodsImportPath | string | 是 | 请求方法导入路径 |
|
|
138
|
+
| dataLevel | 'data' \| 'serve' \| 'axios' | 是 | 接口返回数据层级 |
|
|
139
|
+
| formatting | object | 否 | 代码格式化配置 |
|
|
140
|
+
| headers | object | 否 | 请求头配置 |
|
|
141
|
+
| includeInterface | Array<{path: string, method: string}> | 否 | 包含的接口:`saveApiListFolderPath`指定的接口列表文件,只会包含列表中的接口,与 `excludeInterface` 字段互斥 |
|
|
142
|
+
| excludeInterface | Array<{path: string, method: string}> | 否 | 排除的接口: `saveApiListFolderPath` 指定的接口列表文本,不存在该列表中的接口,与 `includeInterface` 互斥 |
|
|
143
|
+
| publicPrefix | string | 否 | url path 上的公共前缀,例如:api/users、api/users/{id} ,api 就是公共前缀 |
|
|
144
|
+
| erasableSyntaxOnly | boolean | 是 | 与 tsconfig.json 的 `compilerOptions.erasableSyntaxOnly` 选项保持一致。为 `true` 时,生成 const 对象而非 enum(仅类型语法)。默认值:`false` |
|
|
160
145
|
|
|
161
146
|
#### 配置项与生成的文件对应关系
|
|
162
147
|
|
|
163
|
-
> 文件结构是依据配置文件产生的,标注 **不受控**
|
|
148
|
+
> 文件结构是依据配置文件产生的,标注 **不受控** 表示: 该文件夹及其文件为自动生成不受配置项控制
|
|
164
149
|
|
|
165
150
|
```
|
|
166
151
|
project/
|
|
@@ -217,6 +202,49 @@ export const userDetailGet = (params: UserDetail_GET.Query) => GET<UserDetail_GE
|
|
|
217
202
|
- 支持数组、对象、枚举等类型
|
|
218
203
|
- 自动生成接口注释
|
|
219
204
|
|
|
205
|
+
#### 枚举生成
|
|
206
|
+
|
|
207
|
+
工具支持两种枚举生成模式,通过 `erasableSyntaxOnly` 配置控制:
|
|
208
|
+
|
|
209
|
+
**传统枚举模式** (`erasableSyntaxOnly: false`,默认值):
|
|
210
|
+
|
|
211
|
+
```typescript
|
|
212
|
+
export enum Status {
|
|
213
|
+
Success = 'Success',
|
|
214
|
+
Error = 'Error',
|
|
215
|
+
Pending = 'Pending',
|
|
216
|
+
}
|
|
217
|
+
```
|
|
218
|
+
|
|
219
|
+
**常量对象模式** (`erasableSyntaxOnly: true`):
|
|
220
|
+
|
|
221
|
+
```typescript
|
|
222
|
+
export const Status = {
|
|
223
|
+
Success: 'Success',
|
|
224
|
+
Error: 'Error',
|
|
225
|
+
Pending: 'Pending',
|
|
226
|
+
} as const;
|
|
227
|
+
|
|
228
|
+
export type StatusType = (typeof Status)[keyof typeof Status];
|
|
229
|
+
```
|
|
230
|
+
|
|
231
|
+
> **为什么使用常量对象模式?**
|
|
232
|
+
> 当 TypeScript 的 `compilerOptions.erasableSyntaxOnly` 设置为 `true` 时,代码只能使用可擦除的类型语法。传统的 `enum` 会生成运行时代码,而常量对象是纯类型的,编译后会被完全擦除。这确保了与要求仅类型语法的构建工具的兼容性。
|
|
233
|
+
|
|
234
|
+
**在类型中使用:**
|
|
235
|
+
|
|
236
|
+
```typescript
|
|
237
|
+
// 传统枚举模式
|
|
238
|
+
interface User {
|
|
239
|
+
status: Status; // 直接使用枚举作为类型
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
// 常量对象模式
|
|
243
|
+
interface User {
|
|
244
|
+
status: StatusType; // 使用生成的带 'Type' 后缀的类型
|
|
245
|
+
}
|
|
246
|
+
```
|
|
247
|
+
|
|
220
248
|
#### 文件上传
|
|
221
249
|
|
|
222
250
|
当检测到文件上传类型时,会自动添加对应的请求头:
|
|
@@ -337,8 +365,6 @@ $ anl lint
|
|
|
337
365
|
- 设置默认格式化工具
|
|
338
366
|
- 支持已有配置文件更新
|
|
339
367
|
|
|
340
|
-
|
|
341
|
-
|
|
342
368
|
# `anl git` 命令
|
|
343
369
|
|
|
344
370
|
### 功能概述
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e="3.0.3",t={title:"Swagger Petstore - OpenAPI 3.0",description:"This is a sample Pet Store Server based on the OpenAPI 3.0 specification. You can find out more about\nSwagger at [https://swagger.io](https://swagger.io). In the third iteration of the pet store, we've switched to the design first approach!\nYou can now help us improve the API whether it's by making changes to the definition itself or to the code.\nThat way, with time, we can improve the API in general, and expose some of the new features in OAS3.\n\n_If you're looking for the Swagger 2.0/OAS 2.0 version of Petstore, then click [here](https://editor.swagger.io/?url=https://petstore.swagger.io/v2/swagger.yaml). Alternatively, you can load via the `Edit > Load Petstore OAS 2.0` menu option!_\n\nSome useful links:\n- [The Pet Store repository](https://github.com/swagger-api/swagger-petstore)\n- [The source API definition for the Pet Store](https://github.com/swagger-api/swagger-petstore/blob/master/src/main/resources/openapi.yaml)",termsOfService:"http://swagger.io/terms/",contact:{email:"apiteam@swagger.io"},license:{name:"Apache 2.0",url:"http://www.apache.org/licenses/LICENSE-2.0.html"},version:"1.0.11"},s={description:"Find out more about Swagger",url:"http://swagger.io"},r=[{url:"https://petstore3.swagger.io/api/v3"}],a=[{name:"pet",description:"Everything about your Pets",externalDocs:{description:"Find out more",url:"http://swagger.io"}},{name:"store",description:"Access to Petstore orders",externalDocs:{description:"Find out more about our store",url:"http://swagger.io"}},{name:"user",description:"Operations about user"}],o={"/pet":{put:{tags:["pet"],summary:"Update an existing pet",description:"Update an existing pet by Id",operationId:"updatePet",requestBody:{description:"Update an existent pet in the store",content:{"application/json":{schema:{$ref:"#/components/schemas/Pet"}},"application/xml":{schema:{$ref:"#/components/schemas/Pet"}},"application/x-www-form-urlencoded":{schema:{$ref:"#/components/schemas/Pet"}}},required:!0},responses:{200:{description:"Successful operation",content:{"application/json":{schema:{$ref:"#/components/schemas/Pet"}},"application/xml":{schema:{$ref:"#/components/schemas/Pet"}}}},400:{description:"Invalid ID supplied"},404:{description:"Pet not found"},422:{description:"Validation exception"}},security:[{petstore_auth:["write:pets","read:pets"]}]},post:{tags:["pet"],summary:"Add a new pet to the store",description:"Add a new pet to the store",operationId:"addPet",requestBody:{description:"Create a new pet in the store",content:{"application/json":{schema:{$ref:"#/components/schemas/Pet"}},"application/xml":{schema:{$ref:"#/components/schemas/Pet"}},"application/x-www-form-urlencoded":{schema:{$ref:"#/components/schemas/Pet"}}},required:!0},responses:{200:{description:"Successful operation",content:{"application/json":{schema:{$ref:"#/components/schemas/Pet"}},"application/xml":{schema:{$ref:"#/components/schemas/Pet"}}}},400:{description:"Invalid input"},422:{description:"Validation exception"}},security:[{petstore_auth:["write:pets","read:pets"]}]}},"/pet/findByStatus":{get:{tags:["pet"],summary:"Finds Pets by status",description:"Multiple status values can be provided with comma separated strings",operationId:"findPetsByStatus",parameters:[{name:"status",in:"query",description:"Status values that need to be considered for filter",required:!1,explode:!0,schema:{type:"string",default:"available",enum:["available","pending","sold"]}}],responses:{200:{description:"successful operation",content:{"application/json":{schema:{type:"array",items:{$ref:"#/components/schemas/Pet"}}},"application/xml":{schema:{type:"array",items:{$ref:"#/components/schemas/Pet"}}}}},400:{description:"Invalid status value"}},security:[{petstore_auth:["write:pets","read:pets"]}]}},"/pet/findByTags":{get:{tags:["pet"],summary:"Finds Pets by tags",description:"Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.",operationId:"findPetsByTags",parameters:[{name:"tags",in:"query",description:"Tags to filter by",required:!1,explode:!0,schema:{type:"array",items:{type:"string"}}}],responses:{200:{description:"successful operation",content:{"application/json":{schema:{type:"array",items:{$ref:"#/components/schemas/Pet"}}},"application/xml":{schema:{type:"array",items:{$ref:"#/components/schemas/Pet"}}}}},400:{description:"Invalid tag value"}},security:[{petstore_auth:["write:pets","read:pets"]}]}},"/pet/{petId}":{get:{tags:["pet"],summary:"Find pet by ID",description:"Returns a single pet",operationId:"getPetById",parameters:[{name:"petId",in:"path",description:"ID of pet to return",required:!0,schema:{type:"integer",format:"int64"}}],responses:{200:{description:"successful operation",content:{"application/json":{schema:{$ref:"#/components/schemas/Pet"}},"application/xml":{schema:{$ref:"#/components/schemas/Pet"}}}},400:{description:"Invalid ID supplied"},404:{description:"Pet not found"}},security:[{api_key:[]},{petstore_auth:["write:pets","read:pets"]}]},post:{tags:["pet"],summary:"Updates a pet in the store with form data",description:"",operationId:"updatePetWithForm",parameters:[{name:"petId",in:"path",description:"ID of pet that needs to be updated",required:!0,schema:{type:"integer",format:"int64"}},{name:"name",in:"query",description:"Name of pet that needs to be updated",schema:{type:"string"}},{name:"status",in:"query",description:"Status of pet that needs to be updated",schema:{type:"string"}}],responses:{400:{description:"Invalid input"}},security:[{petstore_auth:["write:pets","read:pets"]}]},delete:{tags:["pet"],summary:"Deletes a pet",description:"delete a pet",operationId:"deletePet",parameters:[{name:"api_key",in:"header",description:"",required:!1,schema:{type:"string"}},{name:"petId",in:"path",description:"Pet id to delete",required:!0,schema:{type:"integer",format:"int64"}}],responses:{400:{description:"Invalid pet value"}},security:[{petstore_auth:["write:pets","read:pets"]}]}},"/pet/{petId}/uploadImage":{post:{tags:["pet"],summary:"uploads an image",description:"",operationId:"uploadFile",parameters:[{name:"petId",in:"path",description:"ID of pet to update",required:!0,schema:{type:"integer",format:"int64"}},{name:"additionalMetadata",in:"query",description:"Additional Metadata",required:!1,schema:{type:"string"}}],requestBody:{content:{"application/octet-stream":{schema:{type:"string",format:"binary"}}}},responses:{200:{description:"successful operation",content:{"application/json":{schema:{$ref:"#/components/schemas/ApiResponse"}}}}},security:[{petstore_auth:["write:pets","read:pets"]}]}},"/store/inventory":{get:{tags:["store"],summary:"Returns pet inventories by status",description:"Returns a map of status codes to quantities",operationId:"getInventory",responses:{200:{description:"successful operation",content:{"application/json":{schema:{type:"object",additionalProperties:{type:"integer",format:"int32"}}}}}},security:[{api_key:[]}]}},"/store/order":{post:{tags:["store"],summary:"Place an order for a pet",description:"Place a new order in the store",operationId:"placeOrder",requestBody:{content:{"application/json":{schema:{$ref:"#/components/schemas/Order"}},"application/xml":{schema:{$ref:"#/components/schemas/Order"}},"application/x-www-form-urlencoded":{schema:{$ref:"#/components/schemas/Order"}}}},responses:{200:{description:"successful operation",content:{"application/json":{schema:{$ref:"#/components/schemas/Order"}}}},400:{description:"Invalid input"},422:{description:"Validation exception"}}}},"/store/order/{orderId}":{get:{tags:["store"],summary:"Find purchase order by ID",description:"For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions.",operationId:"getOrderById",parameters:[{name:"orderId",in:"path",description:"ID of order that needs to be fetched",required:!0,schema:{type:"integer",format:"int64"}}],responses:{200:{description:"successful operation",content:{"application/json":{schema:{$ref:"#/components/schemas/Order"}},"application/xml":{schema:{$ref:"#/components/schemas/Order"}}}},400:{description:"Invalid ID supplied"},404:{description:"Order not found"}}},delete:{tags:["store"],summary:"Delete purchase order by ID",description:"For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors",operationId:"deleteOrder",parameters:[{name:"orderId",in:"path",description:"ID of the order that needs to be deleted",required:!0,schema:{type:"integer",format:"int64"}}],responses:{400:{description:"Invalid ID supplied"},404:{description:"Order not found"}}}},"/user":{post:{tags:["user"],summary:"Create user",description:"This can only be done by the logged in user.",operationId:"createUser",requestBody:{description:"Created user object",content:{"application/json":{schema:{$ref:"#/components/schemas/User"}},"application/xml":{schema:{$ref:"#/components/schemas/User"}},"application/x-www-form-urlencoded":{schema:{$ref:"#/components/schemas/User"}}}},responses:{default:{description:"successful operation",content:{"application/json":{schema:{$ref:"#/components/schemas/User"}},"application/xml":{schema:{$ref:"#/components/schemas/User"}}}}}}},"/user/createWithList":{post:{tags:["user"],summary:"Creates list of users with given input array",description:"Creates list of users with given input array",operationId:"createUsersWithListInput",requestBody:{content:{"application/json":{schema:{type:"array",items:{$ref:"#/components/schemas/User"}}}}},responses:{200:{description:"Successful operation",content:{"application/json":{schema:{$ref:"#/components/schemas/User"}},"application/xml":{schema:{$ref:"#/components/schemas/User"}}}},default:{description:"successful operation"}}}},"/user/login":{get:{tags:["user"],summary:"Logs user into the system",description:"",operationId:"loginUser",parameters:[{name:"username",in:"query",description:"The user name for login",required:!1,schema:{type:"string"}},{name:"password",in:"query",description:"The password for login in clear text",required:!1,schema:{type:"string"}}],responses:{200:{description:"successful operation",headers:{"X-Rate-Limit":{description:"calls per hour allowed by the user",schema:{type:"integer",format:"int32"}},"X-Expires-After":{description:"date in UTC when token expires",schema:{type:"string",format:"date-time"}}},content:{"application/xml":{schema:{type:"string"}},"application/json":{schema:{type:"string"}}}},400:{description:"Invalid username/password supplied"}}}},"/user/logout":{get:{tags:["user"],summary:"Logs out current logged in user session",description:"",operationId:"logoutUser",parameters:[],responses:{default:{description:"successful operation"}}}},"/user/{username}":{get:{tags:["user"],summary:"Get user by user name",description:"",operationId:"getUserByName",parameters:[{name:"username",in:"path",description:"The name that needs to be fetched. Use user1 for testing. ",required:!0,schema:{type:"string"}}],responses:{200:{description:"successful operation",content:{"application/json":{schema:{$ref:"#/components/schemas/User"}},"application/xml":{schema:{$ref:"#/components/schemas/User"}}}},400:{description:"Invalid username supplied"},404:{description:"User not found"}}},put:{tags:["user"],summary:"Update user",description:"This can only be done by the logged in user.",operationId:"updateUser",parameters:[{name:"username",in:"path",description:"name that need to be deleted",required:!0,schema:{type:"string"}}],requestBody:{description:"Update an existent user in the store",content:{"application/json":{schema:{$ref:"#/components/schemas/User"}},"application/xml":{schema:{$ref:"#/components/schemas/User"}},"application/x-www-form-urlencoded":{schema:{$ref:"#/components/schemas/User"}}}},responses:{default:{description:"successful operation"}}},delete:{tags:["user"],summary:"Delete user",description:"This can only be done by the logged in user.",operationId:"deleteUser",parameters:[{name:"username",in:"path",description:"The name that needs to be deleted",required:!0,schema:{type:"string"}}],responses:{400:{description:"Invalid username supplied"},404:{description:"User not found"}}}}},n={schemas:{Order:{type:"object",properties:{id:{type:"integer",format:"int64",example:10},petId:{type:"integer",format:"int64",example:198772},quantity:{type:"integer",format:"int32",example:7},shipDate:{type:"string",format:"date-time"},status:{type:"string",description:"Order Status",example:"approved",enum:["placed","approved","delivered"]},complete:{type:"boolean"}},xml:{name:"order"}},Customer:{type:"object",properties:{id:{type:"integer",format:"int64",example:1e5},username:{type:"string",example:"fehguy"},address:{type:"array",xml:{name:"addresses",wrapped:!0},items:{$ref:"#/components/schemas/Address"}}},xml:{name:"customer"}},Address:{type:"object",properties:{street:{type:"string",example:"437 Lytton"},city:{type:"string",example:"Palo Alto"},state:{type:"string",example:"CA"},zip:{type:"string",example:"94301"}},xml:{name:"address"}},Category:{type:"object",properties:{id:{type:"integer",format:"int64",example:1},name:{type:"string",example:"Dogs"}},xml:{name:"category"}},User:{type:"object",properties:{id:{type:"integer",format:"int64",example:10},username:{type:"string",example:"theUser"},firstName:{type:"string",example:"John"},lastName:{type:"string",example:"James"},email:{type:"string",example:"john@email.com"},password:{type:"string",example:"12345"},phone:{type:"string",example:"12345"},userStatus:{type:"integer",description:"User Status",format:"int32",example:1}},xml:{name:"user"}},Tag:{type:"object",properties:{id:{type:"integer",format:"int64"},name:{type:"string"}},xml:{name:"tag"}},Pet:{required:["name","photoUrls"],type:"object",properties:{id:{type:"integer",format:"int64",example:10},name:{type:"string",example:"doggie"},category:{$ref:"#/components/schemas/Category"},photoUrls:{type:"array",xml:{wrapped:!0},items:{type:"string",xml:{name:"photoUrl"}}},tags:{type:"array",xml:{wrapped:!0},items:{$ref:"#/components/schemas/Tag"}},status:{type:"string",description:"pet status in the store",enum:["available","pending","sold"]}},xml:{name:"pet"}},ApiResponse:{type:"object",properties:{code:{type:"integer",format:"int32"},type:{type:"string"},message:{type:"string"}},xml:{name:"##default"}}},requestBodies:{Pet:{description:"Pet object that needs to be added to the store",content:{"application/json":{schema:{$ref:"#/components/schemas/Pet"}},"application/xml":{schema:{$ref:"#/components/schemas/Pet"}}}},UserArray:{description:"List of user object",content:{"application/json":{schema:{type:"array",items:{$ref:"#/components/schemas/User"}}}}}},securitySchemes:{petstore_auth:{type:"oauth2",flows:{implicit:{authorizationUrl:"https://petstore3.swagger.io/oauth/authorize",scopes:{"write:pets":"modify pets in your account","read:pets":"read your pets"}}}},api_key:{type:"apiKey",name:"api_key",in:"header"}}},i={openapi:e,info:t,externalDocs:s,servers:r,tags:a,paths:o,components:n};exports.components=n,exports.default=i,exports.externalDocs=s,exports.info=t,exports.openapi=e,exports.paths=o,exports.servers=r,exports.tags=a;
|
package/lib/package.json.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e="1.7.
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e="1.7.5",i="FE command line tool",s="bin/an-cli.js",p={dev:"rollup --config rollup.config.ts --configPlugin @rollup/plugin-typescript -w",build:"rimraf lib && rollup --config rollup.config.ts --configPlugin @rollup/plugin-typescript",pub:"bash publish.sh",ts:"tsc ./src/int.ts --noEmit --watch",blink:"npm run build && npm link","sync-docs":"node scripts/sync-docs.js"},l={anl:"bin/an-cli.js"},o="Gleason <bianliuzhu@gmail.com>",t={"@commitlint/cli":"^17.4.3","@commitlint/config-conventional":"^17.4.3","@rollup/plugin-commonjs":"^21.0.1","@rollup/plugin-json":"^4.1.0","@rollup/plugin-node-resolve":"^13.1.3","@rollup/plugin-typescript":"^8.3.0","@types/inquirer":"^9.0.7","@types/shelljs":"^0.8.11","@typescript-eslint/eslint-plugin":"^5.52.0","@typescript-eslint/parser":"^5.52.0","cross-env":"^7.0.3",eslint:"^8.7.0",husky:"^8.0.3","openapi-types":"^12.1.3",prettier:"^3.3.2",rimraf:"^5.0.7",rollup:"^2.64.0","rollup-plugin-cleandir":"^2.0.0","rollup-plugin-copy":"^3.5.0","rollup-plugin-terser":"^7.0.2",typescript:"^4.5.4"},r={"app-root-path":"^3.1.0",cac:"^6.7.12",chalk:"4.*","clear-console":"^1.1.0",commander:"14.0.1",figures:"^6.1.0",inquirer:"^10.1.8","log-symbols":"^5.1.0",ora:"5.*","progress-estimator":"^0.3.0",shelljs:"^0.8.5"},n=["typescript","cli","typescript 脚手架","ts 脚手架","ts-cli","脚手架"],c=["package.json","README.md","lib","template"],u={type:"git",url:"https://github.com/bianliuzhu/an-cli.git"},a="commonjs",m={name:"anl",version:e,description:i,main:s,scripts:p,bin:l,author:o,license:"ISC",devDependencies:t,dependencies:r,keywords:n,files:c,repository:u,type:a};exports.author=o,exports.bin=l,exports.default=m,exports.dependencies=r,exports.description=i,exports.devDependencies=t,exports.files=c,exports.keywords=n,exports.license="ISC",exports.main=s,exports.name="anl",exports.repository=u,exports.scripts=p,exports.type=a,exports.version=e;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("../../utils/index.js");const t="\t";exports.default=class{config;schemas={};enumsMap=new Map;schemasMap=new Map;defaultReturn={headerRef:"",renderStr:"",comment:"",typeName:""};requiredFieldS=[];constructor(e,t){this.schemas=e,this.config=t}nullable(e){return""+(e?" | null":"")}fieldComment(e){const{description:t}=e;if(t){return["\t","/**","\n",`\t * ${t}`,"\n","\t */"].join("")}return""}typeNameToFileName(e){return e.replace(/_/g,"-").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase().replace(/-+/g,"-")}nameTheHumpCenterStroke(e){const t=e.replace("#/components/schemas/",""),
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("../../utils/index.js");const t="\t";exports.default=class{config;schemas={};enumsMap=new Map;schemasMap=new Map;defaultReturn={headerRef:"",renderStr:"",comment:"",typeName:""};requiredFieldS=[];constructor(e,t){this.schemas=e,this.config=t}nullable(e){return""+(e?" | null":"")}getEnumTypeName(e){return this.config.erasableSyntaxOnly?`${e}Type`:e}fieldComment(e){const{description:t}=e;if(t){return["\t","/**","\n",`\t * ${t}`,"\n","\t */"].join("")}return""}typeNameToFileName(e){return e.replace(/_/g,"-").replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase().replace(/-+/g,"-")}nameTheHumpCenterStroke(e){const t=e.replace("#/components/schemas/",""),n={typeName:t,fileName:this.typeNameToFileName(t),dataType:""};if(this.schemas){const e=this.schemas[t];e.enum?n.dataType="enum":n.dataType=e.type}return n}parseRef(e){if(!e?.trim())return{headerRefStr:"",typeName:"",dataType:""};const{fileName:t,typeName:n,dataType:r=""}=this.nameTheHumpCenterStroke(e);let s;if("enum"===r){s=`import type { ${this.getEnumTypeName(n)} } from '${this.config.importEnumPath}';`}else s=`import type { ${n} } from './${t}';`;return{headerRefStr:s,typeName:n,dataType:r}}parseObject(e,n){let r="",s="";if("object"===e.type){const i=e;if("object"==typeof i.additionalProperties){const e=this.parseArray(i.additionalProperties,n)??this.defaultReturn;r=e?.headerRef??"",s=e?.renderStr??""}else s=`${t}${n}${this.requiredFieldS.includes(n)?"":"?"}: ${e.type}${this.nullable(e.nullable)};`}return{headerRef:r,renderStr:s}}parseArray(n,r){const s=n,{items:i={},nullable:a,example:o}=s,u=i?.$ref;if(u){const{headerRefStr:n,typeName:s,dataType:i}=this.parseRef(u);if("enum"===i&&e.isValidJSON(o)){const e=this.typeNameToFileName(s),t=this.convertJsonToEnumString(o,s);this.enumsMap.set(e,{fileName:e,content:t})}const l="enum"===i?this.getEnumTypeName(s):s;return{headerRef:n,renderStr:`${t}${r}${this.requiredFieldS.includes(r)?"":"?"}: Array<${l}>${this.nullable(a)};`,typeName:l}}const l=i?.type,p="integer"===l?"number":l;return{headerRef:"",renderStr:`${t}${r}${this.requiredFieldS.includes(r)?"":"?"}: Array<${p}>${this.nullable(a)};`,typeName:p}}parseBoolean(e,n){return"boolean"===e.type?`${t}${n}${this.requiredFieldS.includes(n)?"":"?"}: boolean${this.nullable(e.nullable)};`:""}parseEnum(e,n){if(!Array.isArray(e.enum))return null;if(this.config.erasableSyntaxOnly){if("integer"===e.type){return{headerRef:"",renderStr:[`export const ${n} = {`,...e.enum.map(e=>`${t}NUMBER_${e}: ${e},`),"} as const;","",`export type ${this.getEnumTypeName(n)} = typeof ${n}[keyof typeof ${n}];`].join("\n")}}if("string"===e.type){const r=e.enum.every(e=>!isNaN(Number(e)));return{headerRef:"",renderStr:[`export const ${n} = {`,...e.enum.map(e=>r?`${t}NUMBER_${e}: '${e}',`:`${t}${e.toUpperCase()}: '${e}',`),"} as const;","",`export type ${this.getEnumTypeName(n)} = typeof ${n}[keyof typeof ${n}];`].join("\n")}}}else{if("integer"===e.type){return{headerRef:"",renderStr:[`export enum ${n} {`,...e.enum.map(e=>`${t}NUMBER_${e} = ${e},`),"}"].join("\n")}}if("string"===e.type){const r=e.enum.every(e=>!isNaN(Number(e)));return{headerRef:"",renderStr:[`export enum ${n} {`,...e.enum.map(e=>r?`${t}NUMBER_${e} = '${e}',`:`${t}${e.toUpperCase()} = '${e}',`),"}"].join("\n")}}}return null}parseInteger(e,n){if(Array.isArray(e.enum)){const t=n.charAt(0).toUpperCase()+n.slice(1);return this.parseEnum(e,t)?.renderStr??""}return`${t}${n}${this.requiredFieldS.includes(n)?"":"?"}: number${this.nullable(e.nullable)};`}parseNumber(e,n){return"number"===e.type?`${t}${n}${this.requiredFieldS.includes(n)?"":"?"}: number${this.nullable(e.nullable)};`:""}convertJsonToEnumString(e,n){try{const r=JSON.parse(e);if(this.config.erasableSyntaxOnly){return`export const ${n} = {\n${Object.entries(r).map(([e,n])=>`${t}${e}: '${n}'`).join(",\n")}\n} as const;\n\nexport type ${this.getEnumTypeName(n)} = typeof ${n}[keyof typeof ${n}];`}return`export enum ${n} {\n${Object.entries(r).map(([e,n])=>`${t}${e} = '${n}'`).join(",\n")}\n}`}catch(e){return console.error("JSON 解析失败:",e),""}}parseString(n,r){if("string"===n.type){if(n.enum){const s=r.charAt(0).toUpperCase()+r.slice(1);if(e.isValidJSON(n.example)){const e=this.convertJsonToEnumString(n.example,s),i=this.getEnumTypeName(s);return{headerRef:"",renderStr:`${t}${r}${this.requiredFieldS.includes(r)?"":"?"}: ${i}${this.nullable(n.nullable)};`,comment:e}}{const e=this.typeNameToFileName(s),t=this.parseEnum(n,s);if(t&&!this.enumsMap.has(e))return this.enumsMap.set(e,{fileName:e,content:t.renderStr}),{headerRef:"",renderStr:""}}}return{headerRef:"",renderStr:`${t}${r}${this.requiredFieldS.includes(r)?"":"?"}: string${this.nullable(n.nullable)};`}}return null}parseProperties(n,r){const s=[],i=[];for(const a in n){const o=n[a];if(o?.$ref){const{headerRefStr:n,typeName:r,dataType:u}=this.parseRef(o.$ref);i.includes(n)||i.push(n);const l="enum"===u?this.getEnumTypeName(r):r;s.push(`${t}${a}${this.requiredFieldS.includes(a)?"":"?"}: ${l};`);const p=o.example;if("enum"===u&&p&&e.isValidJSON(p)){const e=this.typeNameToFileName(r),t=this.convertJsonToEnumString(p,r);this.enumsMap.set(e,{fileName:e,content:t})}continue}if("allOf"in o){const e=o.allOf?.[0];if(e?.$ref){const{headerRefStr:n,typeName:r}=this.parseRef(e.$ref);i.includes(n)||i.push(n),s.push(`${t}${a}${this.requiredFieldS.includes(a)?"":"?"}: ${r}${this.nullable(o.nullable)};`);continue}}const u=o,l=this.fieldComment(u);switch(""!==l&&s.push(l),u.type){case"array":{const e=this.parseArray(u,a)??this.defaultReturn;s.push(e?.renderStr??""),i.includes(e.headerRef)||r===e.typeName||i.push(e.headerRef)}break;case"boolean":s.push(this.parseBoolean(u,a));break;case"integer":s.push(this.parseInteger(u,a));break;case"number":s.push(this.parseNumber(u,a));break;case"string":if(u.enum){const n=a.charAt(0).toUpperCase()+a.slice(1);if(u.example&&e.isValidJSON(u.example)){const e=this.getEnumTypeName(n),r=`import type { ${e} } from '${this.config.importEnumPath}';`;i.includes(r)||i.push(r);const o=this.typeNameToFileName(n);if(!this.enumsMap.has(o)){const e=this.convertJsonToEnumString(u.example,n);this.enumsMap.set(o,{fileName:o,content:e})}s.push(`${t}${a}${this.requiredFieldS.includes(a)?"":"?"}: ${e}${this.nullable(u.nullable)};`)}else{const e=this.parseEnum(u,n);if(e?.renderStr){const r=this.getEnumTypeName(n),o=`import type { ${r} } from '${this.config.importEnumPath}';`;i.includes(o)||i.push(o);const l=this.typeNameToFileName(n);this.enumsMap.has(l)||this.enumsMap.set(l,{fileName:l,content:e.renderStr}),s.push(`${t}${a}${this.requiredFieldS.includes(a)?"":"?"}: ${r}${this.nullable(u.nullable)};`)}}}else s.push(this.parseString(u,a)?.renderStr??"");break;case"object":{const{headerRef:e,renderStr:t}=this.parseObject(u,a)??this.defaultReturn;s.push(t),i.includes(e)||i.push(e)}}}const a=[`export interface ${r} {`,...s,"}"];if(i.length>0){const e=i.filter(e=>""!==e);e.length>0&&e.push(""),a.unshift(...e)}const o=a.join("\n");return{headerRef:i.join("\n"),renderStr:o}}async generateContent(e,t){if("items"in e)return console.warn(`数组类型未处理: ${t}`,e.items),"";switch(e.type){case"boolean":return this.parseBoolean(e,t);case"integer":return this.parseInteger(e,t);case"number":return this.parseNumber(e,t);case"object":{const n=this.parseProperties(e.properties,t);return n?.renderStr??""}case"string":{const n=this.parseString(e,t);return n?.renderStr??""}default:return""}}async parseData(){try{if(!this.schemas)return void console.warn("schemas 为空");for(const[e,t]of Object.entries(this.schemas)){if("$ref"in t){console.warn(`跳过 ReferenceObject: ${e}`);continue}const n="type"in t?t:null;if(!n?.type){console.warn(`无效的 schema 对象: ${e}`);continue}this.requiredFieldS=t.required??[];const r=this.typeNameToFileName(e),s=await this.generateContent(n,e);if(s){(s.includes("export enum ")||s.includes("export const ")&&s.includes("as const"))&&!this.enumsMap.has(r)?this.enumsMap.set(r,{fileName:r,content:s}):this.schemasMap.set(e,{fileName:r,content:s})}}}catch(e){throw console.error("解析过程出错:",e),e}}async writeEnums(){const t=[],n=[];for(const[,r]of this.enumsMap){const s=async({fileName:t,content:r})=>{n.push(`export * from './${t}';`);const s=`${this.config.saveEnumFolderPath}/${t}.ts`;await e.writeFileRecursive(s,r),e.log.info(`${s.padEnd(80)} - Write done!`)};t.push(s(r))}await Promise.all(t),await e.writeFileRecursive(`${this.config.saveEnumFolderPath}/index.ts`,n.join("\n")),e.log.success("Enums write done!")}async writeFile(){const t=[],n=[],r=`${this.config.saveTypeFolderPath}/models/`;for(const[,s]of this.schemasMap){const i=async({fileName:t,content:s})=>{n.push(`export * from './${t}';`);const i=`${r}${t}.ts`;await e.writeFileRecursive(i,s),e.log.info(`${i.padEnd(80)} - Write done!`)};t.push(i(s))}await Promise.all(t),await e.writeFileRecursive(`${r}index.ts`,n.join("\n")),e.log.success("Component parse & write done!")}async handle(){await this.parseData(),await this.writeFile(),await this.writeEnums()}};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("../../utils/index.js");const t="\t";var n;!function(e){e.GET="get",e.PUT="put",e.POST="post",e.DELETE="delete",e.OPTIONS="options",e.HEAD="head",e.PATCH="patch",e.TRACE="trace"}(n||(n={}));const r={typeMapping:new Map([["integer","number"],["string","string"],["boolean","boolean"],["binary","File"]]),errorHandling:{throwOnError:!1,logErrors:!0}},s="#/components/schemas/",a="#/components/parameters/",i="#/definitions/",o=["application/json","text/json","text/plain","application/x-www-form-urlencoded","application/xml","text/xml","*/*","application/octet-stream","multipart/form-data"],c=["application/octet-stream","multipart/form-data"];class p{pathsObject={};nonArrayType=["boolean","object","number","string","integer"];pathKey="";contentBody={payload:{path:[],query:[],body:[]},response:"",_response:"",fileName:"",method:"",requestPath:"",summary:"",apiName:"",typeName:"",deprecated:!1,contentType:"application/json"};Map=new Map;config;errors=[];referenceCache=new Map;parameters={};templates={exportConst:e=>`export const ${e}`,typeDefinition:(e,t)=>`type ${e} = ${t}`,interfaceDefinition:e=>`interface ${e}`};constructor(e,t,n){this.pathsObject=e,this.parameters=t??{},this.config={...r,...n,typeMapping:new Map([...r.typeMapping||[],...n.typeMapping||[]])}}handleError(t){if(this.errors.push(t),this.config.errorHandling?.logErrors&&e.log.error(`${t.type}: ${t.message}${t.path?` at ${t.path}`:""}`),this.config.errorHandling?.throwOnError)throw new Error(`${t.type}: ${t.message}`)}getIndentation(){return this.config.formatting?.indentation||t}typeNameToFileName(e){return e=(e=(e=e.replace(/_/g,"-")).replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()).replace(/-+/g,"-")}handleComplexType(e){try{return e.oneOf?e.oneOf.map(e=>this.schemaParse(e)).join(" | "):e.allOf?e.allOf.map(e=>this.schemaParse(e)).join(" & "):e.anyOf?e.anyOf.map(e=>this.schemaParse(e)).join(" | "):e.enum?"number"===e.type||"integer"===e.type?e.enum.join(" | "):e.enum.map(e=>`'${e}'`).join(" | "):"unknown"}catch(e){return this.handleError({type:"SCHEMA",message:"Failed to handle complex type",details:e}),"unknown"}}propertiesParse(e){if(!e)return[];const n=[];for(const r in e){const s=e[r],a=this.schemaParse(s);let i="";i=Array.isArray(a)?`${t}${t}${r}: {${a.join("\n")}};`:`${t}${t}${r}: ${a};`,n.push(i)}return n}nonArraySchemaObjectParse(e){if(!e)return"unknown";if("binary"===e.format||"string"===e.type&&"binary"===e.format)return"File";switch(e.type){case"boolean":return"boolean";case"integer":case"number":return"number";case"object":return this.propertiesParse(e.properties);case"string":return"binary"===e.format?"File":"string";default:return"unknown"}}arraySchemaObjectParse(e){if("array"!==e.type)return"";const{items:t}=e,n="$ref"in t?t:null,r=t;if(n){return`Array<${this.referenceObjectParse(n)}>`}if(r){const e=this.schemaParse(t);return Array.isArray(e)?`Array<{${e.join("\n")}}>`:`Array<${e}>`}return""}referenceObjectParse(e){try{const t=e.$ref,n=this.referenceCache.get(t);if(n)return n;let r=t;t.startsWith(s)&&(r=t.replace(s,"")),t.startsWith(a)&&(r=t.replace(a,"")),t.startsWith(i)&&(r=t.replace(i,""));const o=this.typeNameToFileName(r),c=/enum/gi.test(r)?`import('${this.config.importEnumPath}/${o}').${r}`:`import('../models/${o}').${r}`;return this.referenceCache.set(t,c),c}catch(e){return this.handleError({type:"REFERENCE",message:"Failed to parse reference object",details:e}),"unknown"}}schemaParse(e){try{if(!e)return"unknown";if("oneOf"in e||"allOf"in e||"anyOf"in e||"enum"in e)return this.handleComplexType(e);if("$ref"in e)return this.referenceObjectParse(e);const t=e,n=t.type,r=!0===t.nullable?" | null":"";if(e.format&&this.config.typeMapping?.has(e.format))return this.config.typeMapping.get(e.format)+r;if(n&&this.config.typeMapping?.has(n))return this.config.typeMapping.get(n)+r;if("array"===n&&t.items){const e=this.schemaParse(t.items);if(Array.isArray(e)){const t=this.config.formatting?.lineEnding,n=this.config.formatting?.indentation;return`Array<{${t}${e.join("\n")}${t}${n}${n}}>`}return`Array<${e}>`}if("object"===n){if(t.properties){const e=this.propertiesParse(t.properties);return e.length?e:["unknown"]}if(!0===t.additionalProperties)return"Record<string, unknown>"+r;if("object"==typeof t.additionalProperties){return`Record<string, ${this.schemaParse(t.additionalProperties)}>`+r}}return"unknown"}catch(e){return this.handleError({type:"SCHEMA",message:"Failed to parse schema",details:e}),"unknown"}}responseObjectParse(e){try{const t=e.content;if(!t)return"";let n;for(const e of o)if(t[e]?.schema){n=t[e].schema;break}return n?this.schemaParse(n):""}catch(e){return this.handleError({type:"RESPONSE",message:"Failed to parse response object",details:e}),""}}responseHandle(e){const t=e[200];if(!t)return;const n="content"in t?t:null,r="$ref"in t?t:null;if(null===n&&null===r&&(this.contentBody.response="type Response = unknown",this.contentBody._response="unknown"),r){const e=this.referenceObjectParse(r);this.contentBody.response=`type Response = ${e}`,this.contentBody._response=e}if(n){const e=this.responseObjectParse(n);if(Array.isArray(e)){if(1===e.length&&"unknown"===e[0])this.contentBody.response=`type Response = ${e.join("\n")};`;else{const t=this.config.formatting?.lineEnding,n=this.config.formatting?.indentation;this.contentBody.response=`interface Response {${t}${e.join("\n")}${t}${n}};`}this.contentBody._response=`${e.join("\n")}`}else this.contentBody.response=`type Response = ${e}`,this.contentBody._response=`${e}`}}requestBodyObjectParse(e){const n=Object.values(e.content),{schema:r}=n[0]||{schema:null};if(r){const e=r?.type,n="$ref"in r?r:null,s="array"===e?r:null,a=e&&this.nonArrayType.includes(e)?r:null;if(n){const e=this.referenceObjectParse(n);return`${t}type Body = ${e}`}if(s){const e=this.arraySchemaObjectParse(s);return`${t}type Body = ${e}`}if(a){const e=this.nonArraySchemaObjectParse(a);return Array.isArray(e)?0===e.length?[`${t}type Body = ${a.type};`]:[`${t}interface Body {`,...e.map(e=>e.replace(/: string;/,": File;")),"}"]:[`${t}type Body = ${e}`]}}}requestBodyParse(e){if(!e)return"{}";const n="$ref"in e?e:null,r="content"in e?e:null;if(n){const e=this.referenceObjectParse(n);return`${t}type Body = ${e}`}return r&&"[object Object]"===String(e)&&0!==Reflect.ownKeys(e).length?this.requestBodyObjectParse(r):"{}"}parametersItemHandle(e,n,r){const s="$ref"in e?e:null,i="name"in e?e:null;if(s&&s.$ref&&s.$ref.startsWith(a)&&this.parameters){const e=s.$ref.replace(a,""),t=this.parameters[e];this.parametersItemHandle(t,n,r)}if(i){if("path"===i.in){const e=this.schemaParse(i.schema);n.push(`${t}${t}type ${i.name} = ${e};`),this.contentBody.payload._path?"string"==typeof e?this.contentBody.payload._path[i.name]=e:console.log("Unexpected v2value type:",e):"string"==typeof e?this.contentBody.payload._path={[i.name]:e}:console.log("Unexpected v2value type:",e)}if("query"===i.in){const e=this.schemaParse(i.schema);r.push(`${t}${t}${i.name}: ${e};`),this.contentBody.payload._query?"string"==typeof e?this.contentBody.payload._query[i.name]=e:console.log("Unexpected v2value type:",e):"string"==typeof e?this.contentBody.payload._query={[i.name]:e}:console.log("Unexpected v2value type:",e)}}}requestParametersParse(e){const n=[],r=[];e?.map(e=>this.parametersItemHandle(e,n,r)),0!==n.length&&(n.unshift(`${t}namespace Path {`),n.push(`${t}}`)),0!==r.length&&(r.unshift(`${t}interface Query {`),r.push(`${t}}`)),this.contentBody.payload.path=n,this.contentBody.payload.query=r}requestHandle(e){if(e.parameters&&this.requestParametersParse(e.parameters),e.requestBody){const t=this.requestBodyParse(e.requestBody);if(Array.isArray(t))this.contentBody.payload.body=t;else if(t){const e=t?.split("\n")||[];this.contentBody.payload.body=e}}}apiRequestItemHandle(e){const{payload:t,requestPath:n,_response:r,method:s,typeName:a,apiName:i,contentType:o}=e,{_path:p,_query:h,body:l}=t,y=(()=>{const e=[];for(const t in p)e.push(`${t}: ${a}.Path.${t}`);const t=e.join(e.length>1?",":"");return""===t?t:t+","})(),d=(()=>{const e=h?`query: ${a}.Query,`:"";return""===e?"":`${e}`})(),u=(()=>{const e=l.length>0?`body: ${a}.Body,`:"";return""===e?"":`${e}`})(),f=(y+d+u).replace(/,$/,"");return[`export const ${i} = `,"(",f,""===f?"params?: IRequestFnParams":", params?: IRequestFnParams",")"," => ",s,""+(r?`<${a}.Response>`:""),"(","`"+n+"`,",(()=>{const e=c.includes(o)?`headers: { 'Content-Type': '${o}' }`:void 0;return["{",e?`${e},`:"","...params, ",""===d?"":"query,",""===u?"":"body,","},"].join("")})(),`'${this.config.dataLevel}'`,");"].join("")}parsePathItemObject(e,t){if(e)for(const n in e){const r=e[n];if(r){if(this.config.includeInterface&&this.config.includeInterface.length>0){const e=this.config.includeInterface?.find(e=>t.includes(e.path)&&e.method===n);if(!e)return}else if(this.config.excludeInterface&&this.config.excludeInterface.length>0){const e=this.config.excludeInterface?.find(e=>t.includes(e.path)&&e.method===n);if(e)return}const e=n.toUpperCase(),s=t+"|"+e,{apiName:a,typeName:i,fileName:c,path:p}=this.convertEndpointString(s),h=r.requestBody&&"content"in r.requestBody&&r.requestBody.content,l="object"==typeof h?Object.keys(h)[0]:"application/json";this.contentBody={payload:{path:[],query:[],body:[]},response:"",_response:"",fileName:c,method:e,typeName:i,requestPath:p,apiName:a,summary:r.summary,deprecated:r.deprecated??!1,contentType:o.includes(l)?l:"application/json"},this.requestHandle(r),this.responseHandle(r.responses),this.Map.has(s)||this.Map.set(s,JSON.parse(JSON.stringify(this.contentBody)))}}}convertEndpointString(e){let t=e;e.startsWith("/")||(t="/"+e);const[n,r]=t.split("|");let s="";this.config.publicPrefix&&(s=this.config.publicPrefix.replace(/^\/+|\/+$/g,""));let a=n.replace(/^\/+/,"");if(s&&a.startsWith(s+"/"))a=a.slice(s.length+1);else if(s&&a===s)a="";else if(s&&a.startsWith(s)){const e=a.slice(s.length);(e.startsWith("/")||""===e)&&(a=e.replace(/^\/+/,""))}const i=a?a.split("/").filter(e=>e):[],o=i.map(e=>e.includes("{")?e.slice(1,-1):e).join("_"),c=i.map(e=>{if(e.includes("{")){const t=e.slice(1,-1);return t.charAt(0).toUpperCase()+t.slice(1)}return e.charAt(0).toUpperCase()+e.slice(1)}).join("_");let p="";i.length>0?(p=i.map(e=>e.replace(/[{}]/g,"")).join("-"),p=`${p}-${r}`.toLowerCase()):p=`${r}`.toLowerCase();let h="/"+a;a||(h="/"),h=h.replace(/\{(\w+)\}/g,(e,t)=>`\${${t}}`);return{apiName:o?`${o}_${r}`:r,fileName:p,typeName:c?`${c}_${r}`:r,path:h}}parseData(){return new Promise((e,t)=>{try{for(const e in this.pathsObject){const t=this.pathsObject[e];t&&this.parsePathItemObject(t,e)}e(this.Map)}catch(e){this.handleError({type:"SCHEMA",message:"Failed to parse schema",details:e}),t(e)}})}async writeFile(){const n=[],r=[],s=this.config.saveTypeFolderPath,a=[],i=(n,i)=>new Promise((o,c)=>{try{const{payload:p,response:h,fileName:l,summary:y,typeName:d,deprecated:u}=i,[,f]=n.split("|");!a.includes(f)&&a.push(f);const m=[`declare namespace ${d} {`,...p.path,...p.query,...p.body,`${t}${h}`,"}"];y&&r.push(["/**","\n",u?` * @deprecated ${y}`:` * ${y}`,"\n"," */"].join(""));const g=this.apiRequestItemHandle(i);r.push(g,"\n");const $=`${s}/connectors/${l}.d.ts`;e.writeFileRecursive($,m.join("\n")).then(()=>{e.log.info(`${$.padEnd(80)} - Write done!`),o(1)}).catch(e=>{this.handleError({type:"FILE_WRITE",message:"Failed to write type definition file",path:l,details:e}),c(e)})}catch(e){this.handleError({type:"PATH",message:"Failed to process path item",path:n,details:e}),c(e)}});for(const[e,t]of this.Map)n.push(i(e,t));try{await Promise.all(n),e.log.success("Path parse & write done!"),r.unshift(`import { ${a.join(", ")} } from '${this.config.requestMethodsImportPath||"./api"}';`,"\n"),await e.clearDir(this.config.saveApiListFolderPath+"/index.ts"),await e.writeFileRecursive(this.config.saveApiListFolderPath+"/index.ts",r.join("\n")),this.Map=new Map,this.errors.length>0&&e.log.warning(`Completed with ${this.errors.length} errors`)}catch(e){throw this.handleError({type:"FILE_WRITE",message:"Failed to write API list file",details:e}),e}}async handle(){try{await this.parseData(),await this.writeFile()}catch(e){if(this.handleError({type:"SCHEMA",message:"Failed to handle schema",details:e}),this.config.errorHandling?.throwOnError)throw e}}}exports.PathParse=p,exports.default=p;
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("../../utils/index.js");const t="\t";var n;!function(e){e.GET="get",e.PUT="put",e.POST="post",e.DELETE="delete",e.OPTIONS="options",e.HEAD="head",e.PATCH="patch",e.TRACE="trace"}(n||(n={}));const r={typeMapping:new Map([["integer","number"],["string","string"],["boolean","boolean"],["binary","File"]]),errorHandling:{throwOnError:!1,logErrors:!0}},s="#/components/schemas/",a="#/components/parameters/",i="#/definitions/",o=["application/json","text/json","text/plain","application/x-www-form-urlencoded","application/xml","text/xml","*/*","application/octet-stream","multipart/form-data"],c=["application/octet-stream","multipart/form-data"];class p{pathsObject={};nonArrayType=["boolean","object","number","string","integer"];pathKey="";contentBody={payload:{path:[],query:[],body:[]},response:"",_response:"",fileName:"",method:"",requestPath:"",summary:"",apiName:"",typeName:"",deprecated:!1,contentType:"application/json"};Map=new Map;config;errors=[];referenceCache=new Map;parameters={};schemas={};templates={exportConst:e=>`export const ${e}`,typeDefinition:(e,t)=>`type ${e} = ${t}`,interfaceDefinition:e=>`interface ${e}`};constructor(e,t,n,s){this.pathsObject=e,this.parameters=t??{},this.schemas=n??{},this.config={...r,...s,typeMapping:new Map([...r.typeMapping||[],...s.typeMapping||[]])}}handleError(t){if(this.errors.push(t),this.config.errorHandling?.logErrors&&e.log.error(`${t.type}: ${t.message}${t.path?` at ${t.path}`:""}`),this.config.errorHandling?.throwOnError)throw new Error(`${t.type}: ${t.message}`)}getIndentation(){return this.config.formatting?.indentation||t}getEnumTypeName(e){return this.config.erasableSyntaxOnly?`${e}Type`:e}typeNameToFileName(e){return e=(e=(e=e.replace(/_/g,"-")).replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()).replace(/-+/g,"-")}handleComplexType(e){try{return e.oneOf?e.oneOf.map(e=>this.schemaParse(e)).join(" | "):e.allOf?e.allOf.map(e=>this.schemaParse(e)).join(" & "):e.anyOf?e.anyOf.map(e=>this.schemaParse(e)).join(" | "):e.enum?"number"===e.type||"integer"===e.type?e.enum.join(" | "):e.enum.map(e=>`'${e}'`).join(" | "):"unknown"}catch(e){return this.handleError({type:"SCHEMA",message:"Failed to handle complex type",details:e}),"unknown"}}propertiesParse(e){if(!e)return[];const n=[];for(const r in e){const s=e[r],a=this.schemaParse(s);let i="";i=Array.isArray(a)?`${t}${t}${r}: {${a.join("\n")}};`:`${t}${t}${r}: ${a};`,n.push(i)}return n}nonArraySchemaObjectParse(e){if(!e)return"unknown";if("binary"===e.format||"string"===e.type&&"binary"===e.format)return"File";switch(e.type){case"boolean":return"boolean";case"integer":case"number":return"number";case"object":return this.propertiesParse(e.properties);case"string":return"binary"===e.format?"File":"string";default:return"unknown"}}arraySchemaObjectParse(e){if("array"!==e.type)return"";const{items:t}=e,n="$ref"in t?t:null,r=t;if(n){return`Array<${this.referenceObjectParse(n)}>`}if(r){const e=this.schemaParse(t);return Array.isArray(e)?`Array<{${e.join("\n")}}>`:`Array<${e}>`}return""}referenceObjectParse(e){try{const t=e.$ref,n=this.referenceCache.get(t);if(n)return n;let r=t;t.startsWith(s)&&(r=t.replace(s,"")),t.startsWith(a)&&(r=t.replace(a,"")),t.startsWith(i)&&(r=t.replace(i,""));const o=this.typeNameToFileName(r),c=/enum/gi.test(r),p=this.schemas?.[r],h=p&&"enum"in p&&Array.isArray(p.enum),l=c||h,y=l?this.getEnumTypeName(r):r,d=l?`import('${this.config.importEnumPath}/${o}').${y}`:`import('../models/${o}').${r}`;return this.referenceCache.set(t,d),d}catch(e){return this.handleError({type:"REFERENCE",message:"Failed to parse reference object",details:e}),"unknown"}}schemaParse(e){try{if(!e)return"unknown";if("oneOf"in e||"allOf"in e||"anyOf"in e||"enum"in e)return this.handleComplexType(e);if("$ref"in e)return this.referenceObjectParse(e);const t=e,n=t.type,r=!0===t.nullable?" | null":"";if(e.format&&this.config.typeMapping?.has(e.format))return this.config.typeMapping.get(e.format)+r;if(n&&this.config.typeMapping?.has(n))return this.config.typeMapping.get(n)+r;if("array"===n&&t.items){const e=this.schemaParse(t.items);if(Array.isArray(e)){const t=this.config.formatting?.lineEnding,n=this.config.formatting?.indentation;return`Array<{${t}${e.join("\n")}${t}${n}${n}}>`}return`Array<${e}>`}if("object"===n){if(t.properties){const e=this.propertiesParse(t.properties);return e.length?e:["unknown"]}if(!0===t.additionalProperties)return"Record<string, unknown>"+r;if("object"==typeof t.additionalProperties){return`Record<string, ${this.schemaParse(t.additionalProperties)}>`+r}}return"unknown"}catch(e){return this.handleError({type:"SCHEMA",message:"Failed to parse schema",details:e}),"unknown"}}responseObjectParse(e){try{const t=e.content;if(!t)return"";let n;for(const e of o)if(t[e]?.schema){n=t[e].schema;break}return n?this.schemaParse(n):""}catch(e){return this.handleError({type:"RESPONSE",message:"Failed to parse response object",details:e}),""}}responseHandle(e){const t=e[200];if(!t)return;const n="content"in t?t:null,r="$ref"in t?t:null;if(null===n&&null===r&&(this.contentBody.response="type Response = unknown",this.contentBody._response="unknown"),r){const e=this.referenceObjectParse(r);this.contentBody.response=`type Response = ${e}`,this.contentBody._response=e}if(n){const e=this.responseObjectParse(n);if(Array.isArray(e)){if(1===e.length&&"unknown"===e[0])this.contentBody.response=`type Response = ${e.join("\n")};`;else{const t=this.config.formatting?.lineEnding,n=this.config.formatting?.indentation;this.contentBody.response=`interface Response {${t}${e.join("\n")}${t}${n}};`}this.contentBody._response=`${e.join("\n")}`}else this.contentBody.response=`type Response = ${e}`,this.contentBody._response=`${e}`}}requestBodyObjectParse(e){const n=Object.values(e.content),{schema:r}=n[0]||{schema:null};if(r){const e=r?.type,n="$ref"in r?r:null,s="array"===e?r:null,a=e&&this.nonArrayType.includes(e)?r:null;if(n){const e=this.referenceObjectParse(n);return`${t}type Body = ${e}`}if(s){const e=this.arraySchemaObjectParse(s);return`${t}type Body = ${e}`}if(a){const e=this.nonArraySchemaObjectParse(a);return Array.isArray(e)?0===e.length?[`${t}type Body = ${a.type};`]:[`${t}interface Body {`,...e.map(e=>e.replace(/: string;/,": File;")),"}"]:[`${t}type Body = ${e}`]}}}requestBodyParse(e){if(!e)return"{}";const n="$ref"in e?e:null,r="content"in e?e:null;if(n){const e=this.referenceObjectParse(n);return`${t}type Body = ${e}`}return r&&"[object Object]"===String(e)&&0!==Reflect.ownKeys(e).length?this.requestBodyObjectParse(r):"{}"}parametersItemHandle(e,n,r){const s="$ref"in e?e:null,i="name"in e?e:null;if(s&&s.$ref&&s.$ref.startsWith(a)&&this.parameters){const e=s.$ref.replace(a,""),t=this.parameters[e];this.parametersItemHandle(t,n,r)}if(i){if("path"===i.in){const e=this.schemaParse(i.schema);n.push(`${t}${t}type ${i.name} = ${e};`),this.contentBody.payload._path?"string"==typeof e?this.contentBody.payload._path[i.name]=e:console.log("Unexpected v2value type:",e):"string"==typeof e?this.contentBody.payload._path={[i.name]:e}:console.log("Unexpected v2value type:",e)}if("query"===i.in){const e=this.schemaParse(i.schema);r.push(`${t}${t}${i.name}: ${e};`),this.contentBody.payload._query?"string"==typeof e?this.contentBody.payload._query[i.name]=e:console.log("Unexpected v2value type:",e):"string"==typeof e?this.contentBody.payload._query={[i.name]:e}:console.log("Unexpected v2value type:",e)}}}requestParametersParse(e){const n=[],r=[];e?.map(e=>this.parametersItemHandle(e,n,r)),0!==n.length&&(n.unshift(`${t}namespace Path {`),n.push(`${t}}`)),0!==r.length&&(r.unshift(`${t}interface Query {`),r.push(`${t}}`)),this.contentBody.payload.path=n,this.contentBody.payload.query=r}requestHandle(e){if(e.parameters&&this.requestParametersParse(e.parameters),e.requestBody){const t=this.requestBodyParse(e.requestBody);if(Array.isArray(t))this.contentBody.payload.body=t;else if(t){const e=t?.split("\n")||[];this.contentBody.payload.body=e}}}apiRequestItemHandle(e){const{payload:t,requestPath:n,_response:r,method:s,typeName:a,apiName:i,contentType:o}=e,{_path:p,_query:h,body:l}=t,y=(()=>{const e=[];for(const t in p)e.push(`${t}: ${a}.Path.${t}`);const t=e.join(e.length>1?",":"");return""===t?t:t+","})(),d=(()=>{const e=h?`query: ${a}.Query,`:"";return""===e?"":`${e}`})(),u=(()=>{const e=l.length>0?`body: ${a}.Body,`:"";return""===e?"":`${e}`})(),f=(y+d+u).replace(/,$/,"");return[`export const ${i} = `,"(",f,""===f?"params?: IRequestFnParams":", params?: IRequestFnParams",")"," => ",s,""+(r?`<${a}.Response>`:""),"(","`"+n+"`,",(()=>{const e=c.includes(o)?`headers: { 'Content-Type': '${o}' }`:void 0;return["{",e?`${e},`:"","...params, ",""===d?"":"query,",""===u?"":"body,","},"].join("")})(),`'${this.config.dataLevel}'`,");"].join("")}parsePathItemObject(e,t){if(e)for(const n in e){const r=e[n];if(r){if(this.config.includeInterface&&this.config.includeInterface.length>0){const e=this.config.includeInterface?.find(e=>t.includes(e.path)&&e.method===n);if(!e)return}else if(this.config.excludeInterface&&this.config.excludeInterface.length>0){const e=this.config.excludeInterface?.find(e=>t.includes(e.path)&&e.method===n);if(e)return}const e=n.toUpperCase(),s=t+"|"+e,{apiName:a,typeName:i,fileName:c,path:p}=this.convertEndpointString(s),h=r.requestBody&&"content"in r.requestBody&&r.requestBody.content,l="object"==typeof h?Object.keys(h)[0]:"application/json";this.contentBody={payload:{path:[],query:[],body:[]},response:"",_response:"",fileName:c,method:e,typeName:i,requestPath:p,apiName:a,summary:r.summary,deprecated:r.deprecated??!1,contentType:o.includes(l)?l:"application/json"},this.requestHandle(r),this.responseHandle(r.responses),this.Map.has(s)||this.Map.set(s,JSON.parse(JSON.stringify(this.contentBody)))}}}convertEndpointString(e){let t=e;e.startsWith("/")||(t="/"+e);const[n,r]=t.split("|");let s="";this.config.publicPrefix&&(s=this.config.publicPrefix.replace(/^\/+|\/+$/g,""));let a=n.replace(/^\/+/,"");if(s&&a.startsWith(s+"/"))a=a.slice(s.length+1);else if(s&&a===s)a="";else if(s&&a.startsWith(s)){const e=a.slice(s.length);(e.startsWith("/")||""===e)&&(a=e.replace(/^\/+/,""))}const i=a?a.split("/").filter(e=>e):[],o=i.map(e=>e.includes("{")?e.slice(1,-1).replace(/-/g,"_"):e.replace(/-/g,"_")).join("_"),c=i.map(e=>{if(e.includes("{")){return e.slice(1,-1).split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("_")}return e.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("_")}).join("_");let p="";i.length>0?(p=i.map(e=>e.replace(/[{}]/g,"")).join("-"),p=`${p}-${r}`.toLowerCase()):p=`${r}`.toLowerCase();let h="/"+a;a||(h="/"),h=h.replace(/\{(\w+)\}/g,(e,t)=>`\${${t}}`);return{apiName:o?`${o}_${r}`:r,fileName:p,typeName:c?`${c}_${r}`:r,path:h}}parseData(){return new Promise((e,t)=>{try{for(const e in this.pathsObject){const t=this.pathsObject[e];t&&this.parsePathItemObject(t,e)}e(this.Map)}catch(e){this.handleError({type:"SCHEMA",message:"Failed to parse schema",details:e}),t(e)}})}async writeFile(){const n=[],r=[],s=this.config.saveTypeFolderPath,a=[],i=(n,i)=>new Promise((o,c)=>{try{const{payload:p,response:h,fileName:l,summary:y,typeName:d,deprecated:u}=i,[,f]=n.split("|");!a.includes(f)&&a.push(f);const m=[`declare namespace ${d} {`,...p.path,...p.query,...p.body,`${t}${h}`,"}"];y&&r.push(["/**","\n",u?` * @deprecated ${y}`:` * ${y}`,"\n"," */"].join(""));const g=this.apiRequestItemHandle(i);r.push(g,"\n");const $=`${s}/connectors/${l}.d.ts`;e.writeFileRecursive($,m.join("\n")).then(()=>{e.log.info(`${$.padEnd(80)} - Write done!`),o(1)}).catch(e=>{this.handleError({type:"FILE_WRITE",message:"Failed to write type definition file",path:l,details:e}),c(e)})}catch(e){this.handleError({type:"PATH",message:"Failed to process path item",path:n,details:e}),c(e)}});for(const[e,t]of this.Map)n.push(i(e,t));try{await Promise.all(n),e.log.success("Path parse & write done!"),r.unshift(`import { ${a.join(", ")} } from '${this.config.requestMethodsImportPath||"./api"}';`,"\n"),await e.clearDir(this.config.saveApiListFolderPath+"/index.ts"),await e.writeFileRecursive(this.config.saveApiListFolderPath+"/index.ts",r.join("\n")),this.Map=new Map,this.errors.length>0&&e.log.warning(`Completed with ${this.errors.length} errors`)}catch(e){throw this.handleError({type:"FILE_WRITE",message:"Failed to write API list file",details:e}),e}}async handle(){try{await this.parseData(),await this.writeFile()}catch(e){if(this.handleError({type:"SCHEMA",message:"Failed to handle schema",details:e}),this.config.errorHandling?.throwOnError)throw e}}}exports.PathParse=p,exports.default=p;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("fs"),t=require("../utils/index.js"),a=require("./core/components.js"),s=require("./core/get-data.js"),
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("fs"),t=require("../utils/index.js"),a=require("./core/components.js"),s=require("./core/get-data.js"),r=require("./core/path.js"),o=require("shelljs"),i=require("chalk"),n=require("path");function l(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var c=l(e),d=l(i),u=l(n);let p;const f="development"===process.env.NODE_ENV,h={saveTypeFolderPath:f?"apps/types":"src/api/types",saveApiListFolderPath:f?"apps/types":"src/api",saveEnumFolderPath:f?"apps/types/enums":"src/enums",importEnumPath:"../../../enums",requestMethodsImportPath:"./fetch",publicPrefix:"/api",dataLevel:"serve",swaggerJsonUrl:"https://generator3.swagger.io/openapi.json",headers:{},formatting:{indentation:"\t",lineEnding:"\n"},includeInterface:[],excludeInterface:[],erasableSyntaxOnly:!1};class g{schemas={};paths={};async handle(e){try{let t;if(t=f?(await Promise.resolve().then(function(){return require("../../data/openapi.json.js")})).default:await s.getSwaggerJson(e),!t)throw new Error("无法获取 Swagger 数据");this.schemas=t.components?.schemas||{},this.paths=t.paths||{};const o=new a.default(this.schemas,e),i=new r.PathParse(this.paths,t.components?.parameters,this.schemas,e);return await o.handle(),await i.handle(),!0}catch(e){if(e instanceof Error)throw new Error(`Handle Swagger data failed: ${e.message}`);throw new Error("Handle Swagger data failed: unknown error")}}async formatGeneratedFiles(e){const a=`npx prettier --write "${e.saveTypeFolderPath}/**/*.{ts,d.ts}"`;try{await c.default.promises.access(e.saveTypeFolderPath);const{stderr:s}=await new Promise((e,t)=>{o.exec(a,(a,s,r)=>{a?t(a):e({stdout:s,stderr:r})})});s&&(console.log("\n"),console.log("$",d.default.yellow(a)),console.log("\n")),t.log.success("File formatting successful"),console.log("\n")}catch(e){console.log(""),console.log(e),t.log.error("Format failed, please manually execute the following command:"),console.log("$",d.default.yellow(a)),console.log("")}}async copyAjaxConfigFiles(e){try{const a=["config.ts","error-message.ts","fetch.ts","api-type.d.ts"],s=f?u.default.join(__dirname,"..","..","postbuild-assets","ajax-config"):u.default.join(__dirname,"..","..","ajax-config"),r=e;for(const e of a){const a=u.default.join(s,e),o=u.default.join(r,e);try{await c.default.promises.access(a);try{await c.default.promises.access(o),t.log.info(`${e} already exists, skipping generation.`)}catch{await c.default.promises.copyFile(a,o),t.log.success(`${e} create done.`)}}catch(e){t.log.error(`Source file ${a} does not exist`);continue}}}catch(e){return e}}async getConfig(e){try{const t=await c.default.promises.readFile(e,"utf8");return p=!0,JSON.parse(t)}catch(a){return p=!1,t.log.warning("Config file does not exist, will automatically create config file."),await t.writeFileRecursive(e,JSON.stringify(h,null,2)),t.log.success("Please check the an.config.json file in the project root directory"),h}}async initialize(){const e=process.cwd()+"/an.config.json";try{const a=await this.getConfig(e);if(!p)return;await c.default.promises.mkdir(a.saveApiListFolderPath,{recursive:!0}),await this.copyAjaxConfigFiles(a.saveApiListFolderPath),await t.clearDir(a.saveTypeFolderPath),await t.clearDir(a.saveEnumFolderPath),await this.handle(a),await this.formatGeneratedFiles(a),t.log.success("Successfully, all done, see you next time!"),console.log("\n")}catch(e){const a=e instanceof Error?e.message:"Unknown error";t.log.error(`Initialization failed: ${a}`)}}}if("development"===process.env.NODE_ENV){(new g).initialize()}exports.Main=g;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var o=require("path"),
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var o=require("path"),e=require("fs"),t=require("child_process"),i=require("../utils/index.js"),s=require("./utils.js");function c(o){return o&&"object"==typeof o&&"default"in o?o:{default:o}}var r=c(o),a=c(e);exports.gitHandle=(o=[])=>{o.includes("gitflow")&&(async()=>{const o=r.default.join(__dirname,"..","..","git-local-config"),e=process.cwd(),c=r.default.join(o,".gitscripts"),n=r.default.join(e,".gitscripts");await s.pathExists(c)?(await s.copyDirectoryRecursive(c,n),i.log.success(".gitscripts create done.")):i.log.error(`source directory ${c} does not exist`);const g=[".gitconfig",".commit-type.cjs"];for(const t of g){const c=r.default.join(o,t),a=r.default.join(e,t);await s.pathExists(c)?await s.copyFileIfMissing(c,a):i.log.error(`source file ${c} does not exist`)}try{a.default.chmodSync(r.default.join(n,"random-branch.sh"),493),i.log.success("random-branch.sh Raise power")}catch(o){i.log.error(`设置 .githooks/commit-msg 可执行权限失败: ${o instanceof Error?o.message:o}`)}try{t.execSync("git config --local include.path ../.gitconfig",{stdio:"ignore"}),i.log.success(".gitconfig git set")}catch(o){i.log.error("执行 git config --local include.path ../.gitconfig 失败,请手动执行该命令")}})(),o.includes("commitSubject")&&(async()=>{const o=r.default.join(__dirname,"..","..","git-local-config",".githooks"),e=process.cwd(),c=r.default.join(e,".githooks");if(await s.pathExists(o)){await s.copyDirectoryRecursive(o,c),i.log.success(".githooks create done.");try{a.default.chmodSync(r.default.join(c,"commit-msg"),493),i.log.success("commit-msg raise power done.")}catch(o){i.log.error(`设置 .githooks/commit-msg 可执行权限失败: ${o instanceof Error?o.message:o}`)}try{t.execSync("git config core.hooksPath .githooks",{stdio:"ignore"}),i.log.success("git set .githooks done.")}catch(o){i.log.error("Execute [git config core.hooksPath .githooks] failed, please execute the command manually")}}else i.log.error(`source directory ${o} does not exist`)})(),o.includes("customGitCommand")&&(async()=>{const o=r.default.join(__dirname,"..","..","git-local-config"),e=process.cwd(),t=r.default.join(o,".gitattributes"),c=r.default.join(e,".gitattributes");await s.pathExists(t)?await s.copyFileIfMissing(t,c):i.log.error(`source file ${t} does not exist`)})()};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("path"),t=require("fs"),a=require("../utils/index.js");function
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("path"),t=require("fs"),a=require("../utils/index.js");function i(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var r=i(e),s=i(t);const o=async e=>{await s.default.promises.mkdir(e,{recursive:!0})},n=async e=>{try{return await s.default.promises.access(e),!0}catch{return!1}},c=async(e,t)=>{await n(t)?a.log.info(`${r.default.basename(t)} Already exists, skip generation.`):(await o(r.default.dirname(t)),await s.default.promises.copyFile(e,t),a.log.success(`${r.default.basename(t)} create done.`))},u=async(e,t)=>{if(!(await s.default.promises.stat(e)).isDirectory())throw new Error(`${e} is not a directory`);await o(t);const a=await s.default.promises.readdir(e,{withFileTypes:!0});for(const i of a){const a=r.default.join(e,i.name),s=r.default.join(t,i.name);i.isDirectory()?await u(a,s):i.isFile()&&await c(a,s)}};exports.copyDirectoryRecursive=u,exports.copyFileIfMissing=c,exports.ensureDir=o,exports.pathExists=n;
|
package/lib/src/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("../node_modules/commander/esm.mjs.js"),i=require("../package.json.js"),t=require("./build-type/index.js"),a=require("./standard/lint-init.js"),
|
|
1
|
+
"use strict";var e=require("../node_modules/commander/esm.mjs.js"),i=require("../package.json.js"),t=require("./build-type/index.js"),a=require("./standard/lint-init.js"),n=require("./git-local-config/index.js"),o=require("../node_modules/inquirer/dist/esm/index.mjs.js");e.program.version(`${i.default.version}`,"-v --version").usage("<command> [options]"),e.program.command("type").description("auto interface").action(()=>{(new t.Main).initialize()}),e.program.command("lint").description("install eslint, prettier, commitlint").action(()=>a.lintHandle()),e.program.command("git").description("config git Local custom command").action(async()=>{const{features:e}=await o.default.prompt([{type:"checkbox",name:"features",message:"Select the required Git features (multi-select):",choices:[{name:"gitflow standard branch creation",value:"gitflow"},{name:"automatically set commit subject",value:"commitSubject"},{name:"custom git command",value:"customGitCommand"}],pageSize:10}]);n.gitHandle(e)}),e.program.parse(process.argv);
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e="3.0.1",t={title:"Swagger Generator",description:"This is an online swagger codegen server. You can find out more at https://github.com/swagger-api/swagger-codegen or on [irc.freenode.net, #swagger](http://swagger.io/irc/).",license:{name:"Apache 2.0",url:"http://www.apache.org/licenses/LICENSE-2.0.html"},version:"3.0.73"},r=[{url:"/api"}],n=[{name:"clients"},{name:"servers"},{name:"documentation"},{name:"config"}],o={"/generate":{get:{tags:["clients","servers","documentation","config"],summary:"Generates and download code. GenerationRequest input provided as JSON available at URL specified in parameter codegenOptionsURL.",operationId:"generateFromURL",parameters:[{name:"codegenOptionsURL",in:"query",required:!0,schema:{type:"string"}}],responses:{200:{description:"successful operation",content:{"application/octet-stream":{schema:{type:"string",format:"binary"}}}}},"x-swagger-router-controller":"io.swagger.v3.generator.online.GeneratorController"},post:{tags:["clients","servers","documentation","config"],summary:"Generates and download code. GenerationRequest input provided as request body.",operationId:"generate",requestBody:{content:{"application/json":{schema:{$ref:"#/components/schemas/GenerationRequest"}}}},responses:{200:{description:"successful operation",content:{"application/octet-stream":{schema:{type:"string",format:"binary"}}}}},"x-swagger-router-controller":"io.swagger.v3.generator.online.GeneratorController"}},"/clients":{get:{tags:["clients","documentation"],summary:"Deprecated, use '/{type}/{version}' instead. List generator languages of type 'client' or 'documentation' for given codegen version (defaults to V3)",operationId:"clientLanguages",parameters:[{$ref:"#/components/parameters/version"},{name:"clientOnly",in:"query",description:"flag to only return languages of type `client`",schema:{type:"boolean",default:!1}}],responses:{200:{description:"successful operation",content:{"application/json":{schema:{type:"array",items:{type:"string"}}}}}},deprecated:!0,"x-swagger-router-controller":"io.swagger.v3.generator.online.GeneratorController"}},"/servers":{get:{tags:["servers"],summary:"Deprecated, use '/{type}/{version}' instead. List generator languages of type 'server' for given codegen version (defaults to V3)",operationId:"serverLanguages",parameters:[{$ref:"#/components/parameters/version"}],responses:{200:{description:"successful operation",content:{"application/json":{schema:{type:"array",items:{type:"string"}}}}}},deprecated:!0,"x-swagger-router-controller":"io.swagger.v3.generator.online.GeneratorController"}},"/documentation":{get:{tags:["documentation"],summary:"Deprecated, use '/{type}/{version}' instead. List generator languages of type 'documentation' for given codegen version (defaults to V3)",operationId:"documentationLanguages",parameters:[{$ref:"#/components/parameters/version"}],responses:{200:{description:"successful operation",content:{"application/json":{schema:{type:"array",items:{type:"string"}}}}}},deprecated:!0,"x-swagger-router-controller":"io.swagger.v3.generator.online.GeneratorController"}},"/{type}/{version}":{get:{tags:["clients","servers","documentation","config"],summary:"List generator languages of the given type and version",operationId:"languages",parameters:[{$ref:"#/components/parameters/type"},{name:"version",in:"path",description:"generator version used by codegen engine",required:!0,schema:{type:"string",enum:["V2","V3"]}}],responses:{200:{description:"successful operation",content:{"application/json":{schema:{type:"array",items:{type:"string"}}}}}},"x-swagger-router-controller":"io.swagger.v3.generator.online.GeneratorController"}},"/types":{get:{tags:["clients","servers","documentation","config"],summary:"List generator languages of version defined in 'version parameter (defaults to V3) and type included in 'types' parameter; all languages",operationId:"languagesMulti",parameters:[{$ref:"#/components/parameters/types"},{$ref:"#/components/parameters/version"}],responses:{200:{description:"successful operation",content:{"application/json":{schema:{type:"array",items:{type:"string"}}}}}},"x-swagger-router-controller":"io.swagger.v3.generator.online.GeneratorController"}},"/options":{get:{tags:["clients","servers","documentation","config"],summary:"Returns options for a given language and version (defaults to V3)",operationId:"listOptions",parameters:[{name:"language",in:"query",description:"language",schema:{type:"string"}},{$ref:"#/components/parameters/version"}],responses:{200:{description:"successful operation",content:{"application/json":{schema:{type:"object",additionalProperties:{$ref:"#/components/schemas/CliOption"}}}}}},"x-swagger-router-controller":"io.swagger.v3.generator.online.GeneratorController"}},"/model":{post:{tags:["clients","servers","documentation","config"],summary:'Generates the intermediate model ("bundle") and returns it as a JSON. body.',operationId:"generateBundle",requestBody:{content:{"application/json":{schema:{$ref:"#/components/schemas/GenerationRequest"}}}},responses:{200:{description:"successful operation",content:{"application/json":{schema:{type:"object"}}}}},"x-swagger-router-controller":"io.swagger.v3.generator.online.GeneratorController"}},"/render":{post:{tags:["documentation"],summary:"render a template using the provided data",operationId:"renderTemplate",requestBody:{content:{"application/json":{schema:{$ref:"#/components/schemas/RenderRequest"}}}},responses:{200:{description:"successful operation"}},"x-swagger-router-controller":"io.swagger.v3.generator.online.GeneratorController"}}},i={schemas:{GenerationRequest:{required:["lang"],type:"object",properties:{lang:{title:"language",type:"string",description:"language to generate (required)",example:"java"},spec:{type:"object",description:"spec in json format. . Alternative to `specURL`"},specURL:{type:"string",description:"URL of the spec in json format. Alternative to `spec`"},type:{type:"string",description:"type of the spec",enum:["CLIENT","SERVER","DOCUMENTATION","CONFIG"]},codegenVersion:{type:"string",description:"codegen version to use",enum:["V2","V3"]},options:{$ref:"#/components/schemas/Options"}},"x-swagger-router-model":"io.swagger.codegen.v3.service.GenerationRequest"},AuthorizationValue:{title:"authorization",type:"object",properties:{value:{type:"string",description:"Authorization value"},keyName:{type:"string",description:"Authorization key"},type:{type:"string",description:"Authorization type",enum:["query","header"]}},description:"adds authorization headers when fetching the open api definitions remotely. Pass in an authorizationValue object","x-swagger-router-model":"io.swagger.v3.parser.core.models.AuthorizationValue"},Options:{type:"object",properties:{auth:{title:"authorization",type:"string",description:"adds authorization headers when fetching the open api definitions remotely. Pass in a URL-encoded string of name:header with a comma separating multiple values"},authorizationValue:{$ref:"#/components/schemas/AuthorizationValue"},apiPackage:{title:"api package",type:"string",description:"package for generated api classes"},templateVersion:{title:"Template Version",type:"string",description:"template version for generation"},modelPackage:{title:"model package",type:"string",description:"package for generated models"},modelNamePrefix:{title:"model name prefix",type:"string",description:"Prefix that will be prepended to all model names. Default is the empty string."},modelNameSuffix:{title:"model name suffix",type:"string",description:"PrefixSuffix that will be appended to all model names. Default is the empty string."},systemProperties:{title:"System Properties",type:"object",additionalProperties:{type:"string"},description:"sets specified system properties in key/value format"},instantiationTypes:{title:"instantiation types",type:"object",additionalProperties:{type:"string"},description:"sets instantiation type mappings in key/value format. For example (in Java): array=ArrayList,map=HashMap. In other words array types will get instantiated as ArrayList in generated code."},typeMappings:{title:"type mappings",type:"object",additionalProperties:{type:"string"},description:"sets mappings between swagger spec types and generated code types in key/value format. For example: array=List,map=Map,string=String."},additionalProperties:{title:"additional properties",type:"object",additionalProperties:{type:"object"},description:"sets additional properties that can be referenced by the mustache templates in key/value format."},languageSpecificPrimitives:{title:"language specific primitives",type:"array",description:"specifies additional language specific primitive types in the format of type1,type2,type3,type3. For example: String,boolean,Boolean,Double. You can also have multiple occurrences of this option.",items:{type:"string"}},importMappings:{title:"import mappings",type:"object",additionalProperties:{type:"string"},description:"specifies mappings between a given class and the import that should be used for that class in key/value format."},invokerPackage:{title:"invoker package",type:"string",description:"root package for generated code"},groupId:{title:"group id",type:"string",description:"groupId in generated pom.xml"},artifactId:{title:"artifact id",type:"string",description:"artifactId in generated pom.xml"},artifactVersion:{title:"artifact version",type:"string",description:"artifact version generated in pom.xml"},library:{title:"library",type:"string",description:"library template (sub-template)"},gitUserId:{title:"git user id",type:"string",description:"Git user ID, e.g. swagger-api."},gitRepoId:{title:"git repo id",type:"string",description:"Git repo ID, e.g. swagger-codegen."},releaseNote:{title:"release note",type:"string",description:"Release note, default to 'Minor update'."},httpUserAgent:{title:"http user agent",type:"string",description:"HTTP user agent, e.g. codegen_csharp_api_client, default to 'Swagger-Codegen/{packageVersion}}/{language}'"},reservedWordsMappings:{title:"reserved words mappings",type:"object",additionalProperties:{type:"string"},description:"pecifies how a reserved name should be escaped to. Otherwise, the default _<name> is used. For example id=identifier."},ignoreFileOverride:{title:"ignore file override location",type:"string",description:"Specifies an override location for the .swagger-codegen-ignore file. Most useful on initial generation."},removeOperationIdPrefix:{title:"remove prefix of the operationId",type:"boolean",description:"Remove prefix of operationId, e.g. config_getId => getId"},skipOverride:{type:"boolean"}},"x-swagger-router-model":"io.swagger.codegen.v3.service.Options"},CliOption:{type:"object",properties:{optionName:{type:"string"},description:{type:"string"},type:{type:"string",description:"Data type is based on the types supported by the JSON-Schema"},enum:{type:"object",additionalProperties:{type:"string"}},default:{type:"string"}}},RenderRequest:{required:["context","template"],type:"object",properties:{template:{title:"template",type:"string",description:"template as string",example:"{{!mustache}}"},context:{title:"context",type:"string",description:"context as string",example:"{}"}},"x-swagger-router-model":"io.swagger.codegen.v3.service.RenderRequest"},RenderResponse:{required:["value"],type:"object",properties:{value:{type:"string"}},"x-swagger-router-model":"io.swagger.codegen.v3.service.RenderResponse"}},parameters:{version:{name:"version",in:"query",description:"generator version used by codegen engine",schema:{type:"string",enum:["V2","V3"]}},type:{name:"type",in:"path",description:"generator type",required:!0,schema:{type:"string",enum:["client","server","documentation","config"]}},types:{name:"types",in:"query",description:"comma-separated list of generator types",required:!0,style:"form",explode:!1,schema:{type:"array",items:{type:"string",enum:["client","server","documentation","config"]}}}}},s={openapi:e,info:t,servers:r,tags:n,paths:o,components:i};exports.components=i,exports.default=s,exports.info=t,exports.openapi=e,exports.paths=o,exports.servers=r,exports.tags=n;
|