@ioka-technologies/asyncapi-ts-client-template 0.0.10 → 0.0.12

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/package.json CHANGED
@@ -1,12 +1,13 @@
1
1
  {
2
2
  "name": "@ioka-technologies/asyncapi-ts-client-template",
3
- "version": "0.0.10",
3
+ "version": "0.0.12",
4
4
  "description": "TypeScript AsyncAPI client generator template compatible with rust-asyncapi patterns",
5
5
  "main": "template/index.js",
6
6
  "scripts": {
7
7
  "test": "npm run test:generate",
8
8
  "test:generate": "asyncapi generate fromTemplate examples/auth-retry/asyncapi.yaml . -o test-output-auth-retry --force-write -p enableAuth=true && cd test-output-auth-retry && npm install && npm run build",
9
9
  "test:realworld": "asyncapi generate fromTemplate ../examples/realworld/asyncapi.yaml . -o test-output-realworld --force-write -p enableAuth=true",
10
+ "test:simple": "asyncapi generate fromTemplate ../examples/simple/asyncapi.yaml . -o test-output-simple --force-write -p enableAuth=true",
10
11
  "clean": "rm -rf test-output-*"
11
12
  },
12
13
  "keywords": [
package/template/index.js CHANGED
@@ -38,70 +38,67 @@ module.exports = function ({ asyncapi, params }) {
38
38
  ? params.packageVersion
39
39
  : version;
40
40
 
41
- const transports = (params.transports || 'websocket,http').split(',').map(t => t.trim());
42
-
43
41
  // Generate all files from the main index.js
44
42
  return [
45
- React.createElement(File, { name: "package.json" },
43
+ React.createElement(File, { name: 'package.json' },
46
44
  JSON.stringify({
47
45
  name: packageName,
48
46
  version: packageVersion,
49
47
  description: `${description || title} - TypeScript AsyncAPI Client`,
50
- main: "dist/index.js",
51
- types: "dist/index.d.ts",
48
+ main: 'dist/index.js',
49
+ types: 'dist/index.d.ts',
52
50
  scripts: {
53
- build: "tsc",
54
- dev: "tsc --watch",
55
- test: "jest",
56
- lint: "eslint src/**/*.ts",
57
- prepare: "npm run build"
51
+ build: 'tsc',
52
+ dev: 'tsc --watch',
53
+ test: 'jest',
54
+ lint: 'eslint src/**/*.ts',
55
+ prepare: 'npm run build'
58
56
  },
59
57
  keywords: [
60
- "asyncapi",
61
- "websocket",
62
- "http",
63
- "client",
64
- "typescript",
58
+ 'asyncapi',
59
+ 'websocket',
60
+ 'http',
61
+ 'client',
62
+ 'typescript',
65
63
  title.toLowerCase().replace(/[^a-z0-9]/g, '-')
66
64
  ],
67
- author: params.author || "AsyncAPI Generator",
68
- license: params.license || "Apache-2.0",
65
+ author: params.author || 'AsyncAPI Generator',
66
+ license: params.license || 'Apache-2.0',
69
67
  dependencies: {
70
- uuid: "^9.0.0"
68
+ uuid: '^9.0.0'
71
69
  },
72
70
  optionalDependencies: {
73
- ws: "^8.14.0"
71
+ ws: '^8.14.0'
74
72
  },
75
73
  devDependencies: {
76
- "@types/ws": "^8.5.0",
77
- "@types/uuid": "^9.0.0",
78
- "@types/node": "^20.0.0",
79
- typescript: "^5.0.0",
80
- eslint: "^8.0.0",
81
- "@typescript-eslint/eslint-plugin": "^6.0.0",
82
- "@typescript-eslint/parser": "^6.0.0",
74
+ '@types/ws': '^8.5.0',
75
+ '@types/uuid': '^9.0.0',
76
+ '@types/node': '^20.0.0',
77
+ typescript: '^5.0.0',
78
+ eslint: '^8.0.0',
79
+ '@typescript-eslint/eslint-plugin': '^6.0.0',
80
+ '@typescript-eslint/parser': '^6.0.0',
83
81
  ...(params.generateTests && {
84
- jest: "^29.0.0",
85
- "@types/jest": "^29.0.0",
86
- "ts-jest": "^29.0.0"
82
+ jest: '^29.0.0',
83
+ '@types/jest': '^29.0.0',
84
+ 'ts-jest': '^29.0.0'
87
85
  })
88
86
  },
89
87
  files: [
90
- "dist/**/*",
91
- "README.md",
92
- "USAGE.md"
88
+ 'dist/**/*',
89
+ 'README.md'
93
90
  ]
94
91
  }, null, 2)
95
92
  ),
96
93
 
97
- React.createElement(File, { name: "tsconfig.json" },
94
+ React.createElement(File, { name: 'tsconfig.json' },
98
95
  JSON.stringify({
99
96
  compilerOptions: {
100
- target: "ES2020",
101
- module: "ES2020",
102
- lib: ["ES2020", "DOM"],
103
- outDir: "./dist",
104
- rootDir: "./src",
97
+ target: 'ES2020',
98
+ module: 'ES2020',
99
+ lib: ['ES2020', 'DOM'],
100
+ outDir: './dist',
101
+ rootDir: './src',
105
102
  strict: true,
106
103
  esModuleInterop: true,
107
104
  skipLibCheck: true,
@@ -109,75 +106,61 @@ module.exports = function ({ asyncapi, params }) {
109
106
  declaration: true,
110
107
  declarationMap: true,
111
108
  sourceMap: true,
112
- moduleResolution: "node",
109
+ moduleResolution: 'node',
113
110
  allowSyntheticDefaultImports: true,
114
111
  experimentalDecorators: true,
115
112
  emitDecoratorMetadata: true,
116
113
  resolveJsonModule: true,
117
- typeRoots: ["node_modules/@types"]
114
+ typeRoots: ['node_modules/@types']
118
115
  },
119
116
  include: [
120
- "src/**/*"
117
+ 'src/**/*'
121
118
  ],
122
119
  exclude: [
123
- "node_modules",
124
- "dist",
125
- "**/*.test.ts",
126
- "**/*.spec.ts"
120
+ 'node_modules',
121
+ 'dist',
122
+ '**/*.test.ts',
123
+ '**/*.spec.ts'
127
124
  ]
128
125
  }, null, 2)
129
126
  ),
130
127
 
131
- React.createElement(File, { name: "README.md" },
128
+ React.createElement(File, { name: 'README.md' },
132
129
  `# ${title}
133
130
 
134
131
  ${description || 'Generated TypeScript AsyncAPI client'}
135
132
 
136
- ## Installation
137
-
138
- \`\`\`bash
139
- npm install ${packageName}
140
- \`\`\`
141
-
142
- ## Quick Start
143
-
144
- See [USAGE.md](./USAGE.md) for detailed usage instructions.
133
+ ## Overview
145
134
 
146
- ## Generated from AsyncAPI
135
+ This TypeScript client provides type-safe access to your AsyncAPI service with automatic transport selection and built-in error handling. Generated from your AsyncAPI specification, it offers seamless integration with both WebSocket and HTTP protocols.
147
136
 
148
- This client was generated from an AsyncAPI specification using the TypeScript AsyncAPI Client Generator.
137
+ ## Technical Requirements
149
138
 
150
- - AsyncAPI Version: ${asyncapi.version()}
151
- - Generated: ${new Date().toISOString()}
152
- `
153
- ),
139
+ - Node.js 16+
140
+ - TypeScript 4.5+
154
141
 
155
- React.createElement(File, { name: "USAGE.md" },
156
- `# ${title} - Usage Guide
142
+ ## Supported Transports
157
143
 
158
- This document shows how to use the generated TypeScript AsyncAPI client.
144
+ - WebSocket (with auto-reconnection)
145
+ - HTTP (with retry logic)
159
146
 
160
147
  ## Installation
161
148
 
162
- ### Browser Usage
163
- For browser environments, install the package normally:
164
- \`\`\`bash
165
- npm install ${packageName}
166
- \`\`\`
149
+ ### For Node.js Projects
167
150
 
168
- ### Node.js Usage
169
- For Node.js environments, you'll also need the WebSocket library:
170
151
  \`\`\`bash
171
152
  npm install ${packageName} ws
172
153
  \`\`\`
173
154
 
174
- ## Environment Compatibility
155
+ ### For Browser Projects
156
+
157
+ \`\`\`bash
158
+ npm install ${packageName}
159
+ \`\`\`
175
160
 
176
- This client automatically detects the environment and uses the appropriate WebSocket implementation:
177
- - **Browser**: Uses the native \`WebSocket\` API
178
- - **Node.js**: Uses the \`ws\` library (must be installed separately)
161
+ ## Quick Start
179
162
 
180
- ## WebSocket Usage
163
+ ### WebSocket Client
181
164
 
182
165
  \`\`\`typescript
183
166
  import { ${clientName} } from '${packageName}';
@@ -190,25 +173,16 @@ const client = new ${clientName}({
190
173
  }
191
174
  });
192
175
 
193
- // Connect to the WebSocket
176
+ // Connect and send messages
194
177
  await client.connect();
195
-
196
- // Send a message and wait for response
197
- try {
198
- const response = await client.sendMessage({
199
- text: 'Hello, World!',
200
- userId: '123'
201
- });
202
- console.log('Response:', response);
203
- } catch (error) {
204
- console.error('Error:', error);
205
- }
206
-
207
- // Disconnect when done
208
- await client.disconnect();
178
+ const response = await client.sendMessage({
179
+ text: 'Hello, World!',
180
+ userId: '123'
181
+ });
182
+ console.log('Response:', response);
209
183
  \`\`\`
210
184
 
211
- ## HTTP Usage
185
+ ### HTTP Client
212
186
 
213
187
  \`\`\`typescript
214
188
  import { ${clientName} } from '${packageName}';
@@ -221,36 +195,24 @@ const client = new ${clientName}({
221
195
  }
222
196
  });
223
197
 
224
- // Send HTTP request
225
- try {
226
- const response = await client.sendMessage({
227
- text: 'Hello, World!',
228
- userId: '123'
229
- });
230
- console.log('Response:', response);
231
- } catch (error) {
232
- console.error('Error:', error);
233
- }
198
+ const response = await client.sendMessage({
199
+ text: 'Hello, World!',
200
+ userId: '123'
201
+ });
234
202
  \`\`\`
235
203
 
236
204
  ## Configuration Options
237
205
 
238
- \`\`\`typescript
239
- interface TransportConfig {
240
- type: 'websocket' | 'http';
241
- url: string;
242
- headers?: Record<string, string>;
243
- timeout?: number;
244
- }
245
- \`\`\`
206
+ | Option | Type | Description | Default |
207
+ |--------|------|-------------|---------|
208
+ | \`type\` | \`'websocket' \\| 'http'\` | Transport protocol | Required |
209
+ | \`url\` | \`string\` | Server URL | Required |
210
+ | \`headers\` | \`Record<string, string>\` | Request headers | \`{}\` |
211
+ | \`timeout\` | \`number\` | Request timeout (ms) | \`30000\` |
246
212
 
247
213
  ## Error Handling
248
214
 
249
- The client throws specific error types:
250
-
251
- - \`TransportError\`: General transport errors
252
- - \`ConnectionError\`: Connection-related errors
253
- - \`TimeoutError\`: Request timeout errors
215
+ The client provides specific error types for different scenarios:
254
216
 
255
217
  \`\`\`typescript
256
218
  import { TransportError, ConnectionError, TimeoutError } from '${packageName}';
@@ -261,23 +223,52 @@ try {
261
223
  if (error instanceof ConnectionError) {
262
224
  console.error('Connection failed:', error.message);
263
225
  } else if (error instanceof TimeoutError) {
264
- console.error('Request timed out:', error.message);
226
+ console.error('Request timed out');
265
227
  } else if (error instanceof TransportError) {
266
228
  console.error('Transport error:', error.message);
267
229
  }
268
230
  }
269
231
  \`\`\`
270
232
 
271
- ## Troubleshooting
233
+ ## Environment Compatibility
234
+
235
+ - **Browser**: Uses native WebSocket API (no additional dependencies)
236
+ - **Node.js**: Requires \`ws\` package for WebSocket support
237
+
238
+ ## Development
272
239
 
273
- ### WebSocket Issues in Node.js
274
- If you get an error like "WebSocket implementation not available", make sure you have installed the \`ws\` package:
275
240
  \`\`\`bash
276
- npm install ws
241
+ # Build the project
242
+ npm run build
243
+
244
+ # Watch for changes
245
+ npm run dev
246
+
247
+ # Run tests
248
+ npm test
249
+
250
+ # Lint code
251
+ npm run lint
277
252
  \`\`\`
278
253
 
279
- ### Browser Compatibility
280
- The client uses the native WebSocket API in browsers, which is supported in all modern browsers. No additional dependencies are required.
254
+ ## Generated from AsyncAPI
255
+
256
+ - **AsyncAPI Version**: ${asyncapi.version()}
257
+ - **Generated**: ${new Date().toISOString()}
258
+ - **Title**: ${title}
259
+ - **Version**: ${packageVersion}
260
+
261
+ ## Contributing
262
+
263
+ 1. Fork the repository
264
+ 2. Create a feature branch
265
+ 3. Make your changes and add tests
266
+ 4. Run the test suite: \`npm test\`
267
+ 5. Submit a pull request
268
+
269
+ ## License
270
+
271
+ ${params.license || 'Apache-2.0'}
281
272
  `
282
273
  )
283
274
  ];
@@ -311,9 +311,17 @@ function generateModels(asyncapi) {
311
311
  componentSchemas.forEach(schema => {
312
312
  const doc = schema.description ? `/** ${schema.description} */\n` : `/** ${schema.name} */\n`;
313
313
 
314
- content += `${doc}export interface ${schema.typeName} {\n`;
315
- content += generateMessageInterface(schema.schema, schema.typeName);
316
- content += '\n}\n\n';
314
+ // Check if this is a standalone enum schema
315
+ if (schema.schema.type === 'string' && schema.schema.enum && Array.isArray(schema.schema.enum)) {
316
+ // Generate union type for enum
317
+ const enumValues = schema.schema.enum.map(val => `'${val}'`).join(' | ');
318
+ content += `${doc}export type ${schema.typeName} = ${enumValues};\n\n`;
319
+ } else {
320
+ // Generate interface for object schema
321
+ content += `${doc}export interface ${schema.typeName} {\n`;
322
+ content += generateMessageInterface(schema.schema, schema.typeName);
323
+ content += '\n}\n\n';
324
+ }
317
325
 
318
326
  // Track generated types to avoid duplicates
319
327
  generatedTypes.add(schema.typeName);