@ioka-technologies/asyncapi-ts-client-template 0.0.8 → 0.0.11

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.md CHANGED
@@ -1,304 +1,152 @@
1
- # TypeScript AsyncAPI Client Generator Template
1
+ # AsyncAPI TypeScript Client Template
2
2
 
3
- A production-ready AsyncAPI code generator template for TypeScript clients. This template generates fully-typed TypeScript clients from AsyncAPI specifications with support for WebSocket and HTTP transports, compatible with the rust-asyncapi patterns.
3
+ ⚠️ **Experimental**: This template is still a work in progress and until we reach a 0.1.0 version, assume this is experimental and is not production ready.
4
4
 
5
- ## 🎯 Key Features
5
+ Generate type-safe TypeScript clients from your AsyncAPI specifications with automatic transport selection and built-in error handling.
6
6
 
7
- - 🦀 **Rust-AsyncAPI Compatible**: Generated clients are type-compatible with rust-asyncapi servers
8
- - 🔄 **Multiple Transports**: WebSocket and HTTP support with automatic transport selection
9
- - 🛡️ **Type Safe**: Full TypeScript support with generated interfaces from AsyncAPI schemas
10
- - 🔧 **Smart Method Names**: Automatic sanitization of operation names to valid JavaScript identifiers
11
- - 🔌 **Auto Reconnection**: WebSocket reconnection with configurable retry logic
12
- - 🔐 **Authentication**: JWT, API Key, and custom authentication support
13
- - ⚡ **Promise Based**: Modern async/await API
14
- - 📦 **Zero Config**: Works out of the box with sensible defaults
15
- - 🧪 **Well Tested**: Comprehensive examples and documentation
7
+ ## Overview
16
8
 
17
- ## 🚀 Quick Start
9
+ This template generates TypeScript clients that provide full type safety across the network boundary. The generated clients work seamlessly with AsyncAPI servers and automatically handle transport protocols, reconnection logic, and error recovery.
18
10
 
19
- ### Prerequisites
11
+ **Key Benefits:**
20
12
 
21
- - [AsyncAPI CLI](https://github.com/asyncapi/cli) installed
22
- - [Node.js](https://nodejs.org/) 16+ installed
13
+ - **Type Safety**: Full TypeScript types generated from your AsyncAPI spec
14
+ - **Transport Agnostic**: Same API works over WebSocket or HTTP
15
+ - **Auto Reconnection**: Built-in resilience for production environments
16
+ - **Zero Configuration**: Works out of the box with sensible defaults
23
17
 
24
- ### Generate Your Client
18
+ ## Technical Requirements
25
19
 
26
- ```bash
27
- # Install AsyncAPI CLI
28
- npm install -g @asyncapi/cli
20
+ - Node.js 16+
21
+ - TypeScript 4.5+
22
+ - AsyncAPI CLI 1.0+
29
23
 
30
- # Generate TypeScript client from your AsyncAPI specification
31
- asyncapi generate fromTemplate asyncapi.yaml ./template -o ./my-client
24
+ ## Supported Transports
32
25
 
33
- # Install dependencies and build
34
- cd my-client
35
- npm install
36
- npm run build
37
- ```
26
+ - WebSocket (with auto-reconnection)
27
+ - HTTP (with retry logic)
38
28
 
39
- ## 📁 Project Structure
29
+ ## Quick Start
40
30
 
41
- ```
42
- ts-asyncapi/
43
- ├── README.md # This file
44
- ├── USAGE.md # Comprehensive usage guide
45
- ├── PROJECT_SUMMARY.md # Project summary and achievements
46
- ├── example-api.yaml # Example AsyncAPI specification
47
- ├── package.json # Project dependencies
48
- └── template/ # AsyncAPI Generator Template
49
- ├── package.json # Template dependencies
50
- ├── index.jsx # Template entry point
51
- ├── README.md # Template documentation
52
- ├── test.js # Template testing script
53
- └── components/ # Template components
54
- ├── PackageJson.js # Package.json generator
55
- ├── IndexFile.js # Main index.ts generator
56
- ├── ClientFile.js # Client class generator
57
- ├── ModelsFile.js # Type definitions generator
58
- ├── TransportsFile.js # Transport exports
59
- ├── TsConfigFile.js # TypeScript config generator
60
- ├── ReadmeFile.js # Generated README
61
- ├── UsageFile.js # Generated usage docs
62
- ├── examples/ # Example generators
63
- │ ├── WebSocketExample.js # WebSocket example generator
64
- │ └── HttpExample.js # HTTP example generator
65
- └── runtime/ # Runtime implementation generators
66
- ├── RuntimeTypes.js # Core type definitions
67
- ├── RuntimeErrors.js # Error classes
68
- ├── TransportFactory.js # Transport factory
69
- ├── WebSocketTransport.js # WebSocket implementation
70
- └── HttpTransport.js # HTTP implementation
71
- ```
72
-
73
- ## 🔧 Template Parameters
74
-
75
- | Parameter | Type | Default | Description |
76
- |-----------|------|---------|-------------|
77
- | `clientName` | string | `"{{info.title}}Client"` | Name of the generated client class |
78
- | `packageName` | string | `"{{info.title | kebabCase}}-client"` | Name of the generated npm package |
79
- | `packageVersion` | string | `"{{info.version}}"` | Version of the generated package |
80
- | `author` | string | `"AsyncAPI Generator"` | Package author |
81
- | `license` | string | `"Apache-2.0"` | Package license |
82
- | `generateTests` | boolean | `true` | Generate unit tests |
83
- | `includeExamples` | boolean | `true` | Include usage examples |
84
- | `transports` | string | `"websocket,http"` | Comma-separated list of transports |
85
-
86
- ### Example with Parameters
31
+ ### Installation
87
32
 
88
33
  ```bash
89
- asyncapi generate fromTemplate asyncapi.yaml ./template \
90
- -o ./my-client \
91
- -p clientName=MyAwesomeClient \
92
- -p packageName=my-awesome-client \
93
- -p packageVersion=1.0.0 \
94
- -p author="Your Name" \
95
- -p transports=websocket
96
- ```
97
-
98
- ## 📨 Message Envelope Standard
99
-
100
- This template implements a standardized message envelope format for all AsyncAPI communications, enabling operation-based routing and consistent message handling across transports.
101
-
102
- ### Message Envelope Structure
103
-
104
- ```typescript
105
- interface MessageEnvelope {
106
- operation: string; // AsyncAPI operation ID
107
- id?: string; // Correlation ID for request/response
108
- channel?: string; // Optional channel context
109
- payload: any; // Message payload
110
- timestamp?: number; // Message timestamp
111
- error?: { // Error information
112
- code: string;
113
- message: string;
114
- };
115
- }
116
- ```
117
-
118
- ### Message Flow Examples
119
-
120
- #### Request/Response Pattern
121
- ```typescript
122
- // Client sends:
123
- {
124
- "operation": "getUserProfile",
125
- "id": "uuid-1234",
126
- "channel": "user/profile",
127
- "payload": { "userId": "123" },
128
- "timestamp": 1234567890
129
- }
130
-
131
- // Server responds:
132
- {
133
- "operation": "getUserProfile",
134
- "id": "uuid-1234",
135
- "payload": { "id": "123", "name": "John" },
136
- "timestamp": 1234567891
137
- }
138
- ```
34
+ # Install AsyncAPI CLI
35
+ npm install -g @asyncapi/cli
139
36
 
140
- #### Subscription Pattern
141
- ```typescript
142
- // Server publishes:
143
- {
144
- "operation": "onMessageReceived",
145
- "channel": "chat/receive",
146
- "payload": { "text": "Hello", "from": "Alice" },
147
- "timestamp": 1234567892
148
- }
149
- ```
37
+ # Generate your TypeScript client
38
+ asyncapi generate fromTemplate asyncapi.yaml @ioka-technologies/asyncapi-ts-client-template -o my-client
150
39
 
151
- #### Error Response
152
- ```typescript
153
- {
154
- "operation": "getUserProfile",
155
- "id": "uuid-1234",
156
- "error": {
157
- "code": "USER_NOT_FOUND",
158
- "message": "User with ID 123 not found"
159
- },
160
- "timestamp": 1234567893
161
- }
40
+ cd my-client
41
+ npm install
42
+ npm run build
162
43
  ```
163
44
 
164
- ### Transport-Specific Handling
165
-
166
- #### WebSocket Transport
167
- - **Sending**: All messages wrapped in MessageEnvelope
168
- - **Receiving**: Automatic envelope parsing and operation-based routing
169
- - **Subscriptions**: Client-side filtering by operation field
170
- - **Correlation**: Built-in request/response correlation via `id` field
171
-
172
- #### HTTP Transport
173
- - **Sending**: Complete envelope in POST body
174
- - **Headers**: Operation and correlation ID in HTTP headers
175
- - **Error Handling**: Envelope-level errors parsed from response body
176
- - **Subscriptions**: Warning logged (HTTP doesn't support real-time subscriptions)
177
-
178
- ### Server Implementation Guide
179
-
180
- To implement a compatible server, ensure your server:
181
-
182
- 1. **Parses MessageEnvelope**: All incoming messages should be parsed as MessageEnvelope
183
- 2. **Routes by Operation**: Use the `operation` field to route messages to appropriate handlers
184
- 3. **Preserves Correlation**: Include the same `id` in response messages for request/response patterns
185
- 4. **Uses Error Format**: Return errors in the envelope `error` field with `code` and `message`
186
- 5. **Includes Timestamps**: Add `timestamp` field for message timing information
187
-
188
- ## 🔄 Rust-AsyncAPI Compatibility
189
-
190
- This template generates clients that work with AsyncAPI-compliant servers. The message envelope format provides a standard way to handle operation routing and correlation across different server implementations.
191
-
192
- ### Key Compatibility Features
193
-
194
- - **Operation-Based Routing**: Servers can route messages based on the `operation` field
195
- - **Request/Response Correlation**: Built-in correlation ID support for async request/response patterns
196
- - **Standardized Error Format**: Consistent error structure across all operations
197
- - **Transport Agnostic**: Same envelope format works across WebSocket and HTTP transports
198
- - **Channel Context**: Optional channel information for debugging and routing
199
-
200
- ## 📚 Usage Examples
201
-
202
- ### WebSocket Client
45
+ ### Basic Usage
203
46
 
204
47
  ```typescript
205
- import { MyServiceClient } from './my-client';
48
+ import { MyApiClient } from './my-client';
206
49
 
207
- const client = new MyServiceClient({
50
+ // WebSocket client with auto-reconnection
51
+ const client = new MyApiClient({
208
52
  transport: 'websocket',
209
53
  websocket: {
210
- url: 'ws://localhost:8080',
211
- reconnect: true,
212
- auth: {
213
- token: 'your-jwt-token'
214
- }
54
+ url: 'wss://api.example.com',
55
+ reconnect: true
215
56
  }
216
57
  });
217
58
 
59
+ // Type-safe API calls
218
60
  await client.connect();
219
- const response = await client.getUserProfile({ userId: '123' });
220
- console.log(response);
61
+
62
+ // All methods are fully typed
63
+ const user = await client.createUser({
64
+ name: "John Doe", // TypeScript knows this is required
65
+ email: "john@example.com",
66
+ age: 30 // TypeScript knows this is optional
67
+ });
68
+
69
+ // Response is fully typed
70
+ console.log(user.id); // TypeScript provides autocomplete
71
+ console.log(user.createdAt); // TypeScript knows this is a Date
72
+
73
+ // Real-time subscriptions
74
+ client.onUserCreated((user) => {
75
+ console.log('New user:', user);
76
+ });
221
77
  ```
222
78
 
223
- ### HTTP Client
79
+ ### HTTP Transport
224
80
 
225
81
  ```typescript
226
- import { MyServiceClient } from './my-client';
227
-
228
- const client = new MyServiceClient({
82
+ // HTTP client with retry logic
83
+ const client = new MyApiClient({
229
84
  transport: 'http',
230
85
  http: {
231
- baseUrl: 'http://localhost:8080',
86
+ baseUrl: 'https://api.example.com',
232
87
  retry: {
233
88
  attempts: 3,
234
- delay: 1000,
235
89
  backoff: 'exponential'
236
90
  }
237
91
  }
238
92
  });
239
93
 
240
- await client.connect();
241
- const response = await client.createUser({ name: 'John', email: 'john@example.com' });
242
- console.log(response);
94
+ const response = await client.getUser({ userId: '123' });
243
95
  ```
244
96
 
245
- ## 🛡️ Type Safety
246
-
247
- The generated client provides full TypeScript type safety:
97
+ ### Authentication
248
98
 
249
99
  ```typescript
250
- // All request/response types are generated from your AsyncAPI spec
251
- const response = await client.getUserProfile({
252
- userId: '123' // TypeScript knows this is required
253
- });
254
-
255
- // Response is fully typed
256
- console.log(response.user.name); // TypeScript provides autocomplete
257
- ```
258
-
259
- ## 🔐 Authentication Support
260
-
261
- ### JWT Tokens
262
-
263
- ```typescript
264
- {
100
+ // JWT Authentication
101
+ const client = new MyApiClient({
102
+ transport: 'websocket',
103
+ websocket: { url: 'wss://api.example.com' },
265
104
  auth: {
266
- token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...'
105
+ jwt: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...'
267
106
  }
268
- }
269
- ```
270
-
271
- ### API Keys
107
+ });
272
108
 
273
- ```typescript
274
- {
109
+ // API Key Authentication
110
+ const client = new MyApiClient({
111
+ transport: 'http',
112
+ http: { baseUrl: 'https://api.example.com' },
275
113
  auth: {
276
- apiKey: 'your-api-key'
114
+ apiKey: {
115
+ key: 'my-api-key-123',
116
+ location: 'header',
117
+ name: 'X-API-Key'
118
+ }
277
119
  }
278
- }
120
+ });
279
121
  ```
280
122
 
281
- ### Custom Headers
123
+ ## Template Configuration
282
124
 
283
- ```typescript
284
- {
285
- auth: {
286
- headers: {
287
- 'X-Custom-Auth': 'custom-value'
288
- }
289
- }
290
- }
125
+ Configure the template with parameters:
126
+
127
+ ```bash
128
+ asyncapi generate fromTemplate asyncapi.yaml @ioka-technologies/asyncapi-ts-client-template \
129
+ -o my-client \
130
+ -p clientName=MyApiClient \
131
+ -p packageName=my-api-client \
132
+ -p packageVersion=1.0.0
291
133
  ```
292
134
 
293
- ## 🔄 Error Handling
135
+ | Parameter | Default | Description |
136
+ |-----------|---------|-------------|
137
+ | `clientName` | `"{{info.title}}Client"` | Main client class name |
138
+ | `packageName` | `"{{info.title | kebabCase}}-client"` | NPM package name |
139
+ | `packageVersion` | `"{{info.version}}"` | Package version |
140
+ | `author` | `"AsyncAPI Generator"` | Package author |
141
+ | `transports` | `"websocket,http"` | Supported transport protocols |
294
142
 
295
- Comprehensive error types for robust error handling:
143
+ ## Error Handling
296
144
 
297
145
  ```typescript
298
146
  import { ConnectionError, MessageTimeoutError, HttpError } from './my-client';
299
147
 
300
148
  try {
301
- await client.someOperation(data);
149
+ await client.createUser(userData);
302
150
  } catch (error) {
303
151
  if (error instanceof ConnectionError) {
304
152
  console.error('Connection failed:', error.message);
@@ -310,73 +158,49 @@ try {
310
158
  }
311
159
  ```
312
160
 
313
- ## 🧪 Testing the Template
314
-
315
- ```bash
316
- # Test the template with the example API
317
- cd template
318
- npm install
319
- node test.js
320
- ```
321
-
322
- ## 🏗️ Generated Project Structure
323
-
324
- When you generate a client, you'll get a complete TypeScript project:
161
+ ## Generated Project Structure
325
162
 
326
163
  ```
327
164
  my-client/
328
165
  ├── package.json # NPM package configuration
329
166
  ├── tsconfig.json # TypeScript configuration
330
- ├── README.md # Generated documentation
331
- ├── USAGE.md # Detailed usage instructions
332
167
  ├── src/
333
168
  │ ├── index.ts # Main exports
334
169
  │ ├── client.ts # Generated client class
335
- │ ├── models.ts # Generated TypeScript interfaces
336
- ├── transports.ts # Transport exports
337
- │ └── runtime/ # Runtime implementation
338
- │ ├── types.ts # Core type definitions
339
- │ ├── errors.ts # Error classes
340
- │ └── transports/ # Transport implementations
341
- │ ├── factory.ts # Transport factory
342
- │ ├── websocket.ts # WebSocket transport
343
- │ └── http.ts # HTTP transport
170
+ │ ├── models.ts # TypeScript interfaces
171
+ └── runtime/ # Transport implementations
344
172
  └── examples/ # Usage examples
345
- ├── websocket-example.ts # WebSocket example
346
- └── http-example.ts # HTTP example
347
173
  ```
348
174
 
349
- ## 📖 Documentation
175
+ ## Examples
350
176
 
351
- - **[USAGE.md](./USAGE.md)** - Comprehensive usage guide with examples
352
- - **[PROJECT_SUMMARY.md](./PROJECT_SUMMARY.md)** - Complete project summary
353
- - **[template/README.md](./template/README.md)** - Template-specific documentation
177
+ See the [examples directory](../examples/) for sample AsyncAPI specifications and generated clients.
354
178
 
355
- ## 🤝 Contributing
179
+ ## Development
356
180
 
357
- 1. Fork the repository
358
- 2. Create your feature branch (`git checkout -b feature/amazing-feature`)
359
- 3. Commit your changes (`git commit -m 'Add some amazing feature'`)
360
- 4. Push to the branch (`git push origin feature/amazing-feature`)
361
- 5. Submit a pull request
181
+ ```bash
182
+ # Clone and test locally
183
+ git clone https://github.com/Ioka-Technologies/asyncapi-template.git
184
+ cd asyncapi-template/ts-client
362
185
 
363
- ## 📋 Requirements
186
+ # Run tests
187
+ npm test
188
+ ```
189
+
190
+ ## Contributing
364
191
 
365
- - **Node.js**: >= 16.0.0
366
- - **TypeScript**: >= 4.5.0
367
- - **AsyncAPI CLI**: Latest version
192
+ 1. Fork the repository
193
+ 2. Create a feature branch
194
+ 3. Make your changes and add tests
195
+ 4. Run the test suite: `npm test`
196
+ 5. Submit a pull request
368
197
 
369
- ## 📄 License
198
+ ## License
370
199
 
371
- This project is licensed under the Apache License 2.0 - see the [LICENSE](LICENSE) file for details.
200
+ Apache-2.0
372
201
 
373
- ## 🔗 Related Projects
202
+ ## Related Projects
374
203
 
375
204
  - [AsyncAPI Generator](https://github.com/asyncapi/generator)
376
205
  - [AsyncAPI CLI](https://github.com/asyncapi/cli)
377
- - [Rust AsyncAPI Template](https://github.com/asyncapi/rust-template)
378
- - [AsyncAPI Specification](https://github.com/asyncapi/spec)
379
-
380
- ---
381
-
382
- Generated with ❤️ by [AsyncAPI Generator](https://github.com/asyncapi/generator)
206
+ - [Rust Server Template](../rust-server/)