@simpleapps-com/augur-api 0.2.6 → 0.2.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,132 @@
1
+ # API Discovery Guide
2
+
3
+ Find any functionality across 13 microservices using natural language search.
4
+
5
+ ## Quick Reference
6
+
7
+ ```typescript
8
+ import { AugurAPI } from '@simpleapps-com/augur-api';
9
+
10
+ const api = new AugurAPI({ siteId: 'your-site', bearerToken: 'token' });
11
+
12
+ // Discover all services
13
+ const services = await api.discover();
14
+
15
+ // Find specific functionality
16
+ const results = await api.findEndpoint('user management');
17
+ const inventory = await api.findEndpoint('stock levels');
18
+ const pricing = await api.findEndpoint('product pricing');
19
+ ```
20
+
21
+ ## Core Methods
22
+
23
+ ### `api.discover()`
24
+ Returns complete service map with all available endpoints.
25
+
26
+ ```typescript
27
+ const services = await api.discover();
28
+ services.forEach(service => {
29
+ console.log(`${service.serviceName}: ${service.endpointCount} endpoints`);
30
+ });
31
+ ```
32
+
33
+ ### `api.findEndpoint(searchTerm, options?)`
34
+ Search across all services for matching functionality.
35
+
36
+ ```typescript
37
+ // Basic search
38
+ const results = await api.findEndpoint('users');
39
+
40
+ // Advanced search with filters
41
+ const results = await api.findEndpoint('settings', {
42
+ service: 'agrSite', // Filter by service
43
+ domain: 'content-management', // Filter by domain
44
+ readOnly: true, // Only GET endpoints
45
+ maxResults: 5 // Limit results
46
+ });
47
+ ```
48
+
49
+ ## Common Searches
50
+
51
+ | Search Term | Returns |
52
+ |-------------|---------|
53
+ | `'user management'` | User CRUD, authentication, groups |
54
+ | `'inventory'` | Stock levels, warehouse operations |
55
+ | `'product search'` | OpenSearch, product catalogs |
56
+ | `'site settings'` | Configuration, notifications |
57
+ | `'pricing'` | Price engine, job pricing |
58
+ | `'orders'` | Order management, invoicing |
59
+
60
+ ## Search Filters
61
+
62
+ ```typescript
63
+ interface SearchOptions {
64
+ service?: string; // 'joomla', 'vmi', 'commerce', etc.
65
+ domain?: string; // 'user-management', 'inventory-management'
66
+ readOnly?: boolean; // true = GET only, false = all methods
67
+ minScore?: number; // 0.0 to 1.0 relevance threshold
68
+ maxResults?: number; // Limit number of results
69
+ }
70
+ ```
71
+
72
+ ## Business Domains
73
+
74
+ - **user-management** - Users, authentication, permissions
75
+ - **content-management** - Articles, site settings, notifications
76
+ - **e-commerce** - Shopping carts, checkout, recommendations
77
+ - **inventory-management** - Warehouses, stock levels, transfers
78
+ - **product-catalog** - Products, categories, search
79
+ - **customer-data** - Customer profiles, orders, addresses
80
+ - **order-processing** - Orders, invoicing, payments
81
+
82
+ ## AI Assistant Integration
83
+
84
+ Every method includes semantic tags for AI assistants:
85
+
86
+ ```typescript
87
+ /**
88
+ * @searchTerms ["users", "user management", "authentication"]
89
+ * @relatedEndpoints ["api.joomla.users.get", "api.joomla.users.create"]
90
+ * @commonPatterns ["List all users", "Get user directory"]
91
+ */
92
+ ```
93
+
94
+ When you ask an AI assistant "help me manage users", it can:
95
+ 1. Find `api.joomla.users.list()` through searchTerms
96
+ 2. Suggest related operations from relatedEndpoints
97
+ 3. Provide examples using commonPatterns
98
+ 4. Show complete workflows across services
99
+
100
+ ## Example Workflows
101
+
102
+ ### User Management
103
+ ```typescript
104
+ const userOps = await api.findEndpoint('user management');
105
+ // Returns: api.joomla.users.list, api.joomla.users.get, api.joomla.users.create
106
+
107
+ const users = await api.joomla.users.list({ limit: 10 });
108
+ const user = await api.joomla.users.get('123');
109
+ ```
110
+
111
+ ### Inventory Operations
112
+ ```typescript
113
+ const inventory = await api.findEndpoint('inventory levels');
114
+ // Returns: api.vmi.inventory.checkAvailability, api.vmi.warehouses.list
115
+
116
+ const availability = await api.vmi.inventory.checkAvailability(warehouseId);
117
+ const warehouses = await api.vmi.warehouses.list({ customerId: 12345 });
118
+ ```
119
+
120
+ ### Product Search
121
+ ```typescript
122
+ const search = await api.findEndpoint('product search');
123
+ // Returns: api.opensearch.itemSearch.search, api.items.products.list
124
+
125
+ const results = await api.opensearch.itemSearch.search({
126
+ q: 'electrical wire',
127
+ searchType: 'query',
128
+ size: 20
129
+ });
130
+ ```
131
+
132
+ The discovery system eliminates the need to memorize 13 different microservice APIs. Just describe what you want to accomplish, and find the right endpoints instantly.
@@ -0,0 +1,371 @@
1
+ # Authentication Guide
2
+
3
+ Complete guide to authentication patterns in the Augur API Client.
4
+
5
+ ## Standard Authentication (Most Common)
6
+
7
+ The standard authentication pattern works for 95% of use cases.
8
+
9
+ ### Dual Authentication System
10
+
11
+ Every API request requires two pieces of authentication:
12
+
13
+ 1. **Site ID** (`x-site-id` header) - Identifies which site/tenant you're working with
14
+ 2. **Bearer Token** (JWT) - Proves you're authorized to access that site
15
+
16
+ ```typescript
17
+ const api = new AugurAPI({
18
+ siteId: 'your-site-id', // Always required
19
+ bearerToken: 'your-jwt-token', // Required except for health checks
20
+ });
21
+ ```
22
+
23
+ ### How to Get Your Credentials
24
+
25
+ **Site ID**: Usually provided by your system administrator or found in your project configuration.
26
+
27
+ **Bearer Token**: Obtained through your application's login process. This is typically a JWT token that looks like:
28
+ `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...`
29
+
30
+ ### Health Checks (No Authentication Required)
31
+
32
+ Health checks are the only endpoints that don't require a bearer token:
33
+
34
+ ```typescript
35
+ // Health checks work without bearer token
36
+ const api = new AugurAPI({
37
+ siteId: 'your-site-id',
38
+ // No bearerToken needed
39
+ });
40
+
41
+ const health = await api.joomla.getHealthCheck();
42
+ const pricingHealth = await api.pricing.getHealthCheck();
43
+ const vmiPing = await api.vmi.health.ping();
44
+ ```
45
+
46
+ ### Dynamic Authentication Updates
47
+
48
+ Update credentials at runtime when needed:
49
+
50
+ ```typescript
51
+ // Update token after login/refresh
52
+ api.setAuthToken('new-jwt-token');
53
+
54
+ // Switch to different site
55
+ api.setSiteId('different-site-id');
56
+
57
+ // Example: Token refresh scenario
58
+ async function refreshTokenIfNeeded() {
59
+ try {
60
+ await api.joomla.users.list({ limit: 1 });
61
+ } catch (error) {
62
+ if (error instanceof AuthenticationError) {
63
+ const newToken = await refreshJWTToken();
64
+ api.setAuthToken(newToken);
65
+ }
66
+ }
67
+ }
68
+ ```
69
+
70
+ ### Environment Variables Setup
71
+
72
+ Store credentials securely in environment variables:
73
+
74
+ ```bash
75
+ # .env file
76
+ AUGUR_SITE_ID=your-site-id
77
+ AUGUR_JWT_TOKEN=your-jwt-token
78
+ ```
79
+
80
+ ```typescript
81
+ const api = new AugurAPI({
82
+ siteId: process.env.AUGUR_SITE_ID!,
83
+ bearerToken: process.env.AUGUR_JWT_TOKEN!,
84
+ });
85
+ ```
86
+
87
+ ### Security Best Practices
88
+
89
+ 1. **Environment Variables**: Never hardcode credentials
90
+ 2. **Token Rotation**: Implement regular token rotation in production
91
+ 3. **HTTPS Only**: All API requests use HTTPS in production
92
+ 4. **Secure Storage**: Never store tokens in localStorage for web apps
93
+ 5. **Minimal Permissions**: Use tokens with minimal required permissions
94
+
95
+ ```typescript
96
+ // ✅ Good: Environment-based configuration
97
+ const api = new AugurAPI({
98
+ siteId: process.env.AUGUR_SITE_ID!,
99
+ bearerToken: getSecurelyStoredToken(), // From secure storage
100
+ });
101
+
102
+ // ❌ Bad: Hardcoded credentials
103
+ const api = new AugurAPI({
104
+ siteId: 'hardcoded-site-id',
105
+ bearerToken: 'hardcoded-token', // Never do this!
106
+ });
107
+ ```
108
+
109
+ ---
110
+
111
+ ## Advanced: Cross-Site Authentication
112
+
113
+ **⚠️ Advanced Feature**: Only needed for multi-tenant applications where you need to authenticate users across different sites.
114
+
115
+ ### When You Need Cross-Site Auth
116
+
117
+ Cross-site authentication is needed when:
118
+ - You're building a multi-tenant application
119
+ - You need to authenticate a user from one site against a different site
120
+ - You're managing multiple client sites from a central application
121
+
122
+ ### Prerequisites
123
+
124
+ - Access to the special `augur_info` site
125
+ - Admin-level JWT token with `augur_info` privileges
126
+ - Target site ID where you want to authenticate the user
127
+
128
+ ### Option 1: Streamlined Utility Function (Recommended)
129
+
130
+ ```typescript
131
+ import { authenticateUserForSite } from '@simpleapps-com/augur-api';
132
+
133
+ const result = await authenticateUserForSite({
134
+ targetSiteId: 'tenant_site_1',
135
+ username: 'user@tenant.com',
136
+ password: 'user-password',
137
+ augurInfoToken: 'admin-jwt-token' // JWT with augur_info admin privileges
138
+ });
139
+
140
+ if (result.success) {
141
+ // Ready-to-use API client for the target site
142
+ const userData = await result.targetSiteAPI!.joomla.users.get(result.userId!);
143
+ console.log('User authenticated:', result.username);
144
+ console.log('User data:', userData);
145
+ } else {
146
+ console.error('Authentication failed:', result.error);
147
+ }
148
+ ```
149
+
150
+ ### Option 2: Reusable Authenticator
151
+
152
+ ```typescript
153
+ import { createCrossSiteAuthenticator } from '@simpleapps-com/augur-api';
154
+
155
+ // Create reusable authenticator
156
+ const crossSiteAuth = createCrossSiteAuthenticator('admin-jwt-token');
157
+
158
+ // Use for multiple sites
159
+ const result1 = await crossSiteAuth('tenant_site_1', 'user1@tenant.com', 'pass1');
160
+ const result2 = await crossSiteAuth('tenant_site_2', 'user2@tenant.com', 'pass2');
161
+
162
+ if (result1.success) {
163
+ const tenantData = await result1.targetSiteAPI!.joomla.content.list({ limit: 10 });
164
+ }
165
+ ```
166
+
167
+ ### Option 3: Manual Approach
168
+
169
+ ```typescript
170
+ // Manual approach using the API client directly
171
+ const crossSiteAPI = new AugurAPI({
172
+ siteId: 'augur_info', // Special site for cross-site operations
173
+ bearerToken: 'admin-jwt-token', // JWT token with augur_info admin privileges
174
+ });
175
+
176
+ // Authenticate user against a different site
177
+ const authResult = await crossSiteAPI.joomla.users.verifyPassword({
178
+ username: 'user@tenant.com',
179
+ password: 'user-password',
180
+ siteId: 'tenant_site_1' // Target site for authentication
181
+ });
182
+
183
+ if (authResult.data.isVerified) {
184
+ // Create API instance for the target site
185
+ const tenantAPI = new AugurAPI({
186
+ siteId: 'tenant_site_1',
187
+ bearerToken: authResult.data.token, // Token scoped to tenant site
188
+ });
189
+
190
+ const userData = await tenantAPI.joomla.users.get(authResult.data.id);
191
+ }
192
+ ```
193
+
194
+ ### Cross-Site Auth Flow Diagram
195
+
196
+ ```
197
+ [Your App] → [augur_info API] → [Target Site] → [User Validated] → [Target Site API Client]
198
+ ↓ ↓ ↓ ↓ ↓
199
+ Admin Token → Verify User → Check Password → Return User Token → Ready for API calls
200
+ ```
201
+
202
+ ### Common Cross-Site Patterns
203
+
204
+ #### Multi-Tenant Dashboard
205
+ ```typescript
206
+ // Authenticate users across multiple tenant sites
207
+ const authenticator = createCrossSiteAuthenticator(adminToken);
208
+
209
+ const tenants = ['site1', 'site2', 'site3'];
210
+ const userCredentials = { username: 'user@example.com', password: 'pass' };
211
+
212
+ const results = await Promise.all(
213
+ tenants.map(siteId =>
214
+ authenticator(siteId, userCredentials.username, userCredentials.password)
215
+ )
216
+ );
217
+
218
+ // Process results for each tenant
219
+ results.forEach((result, index) => {
220
+ if (result.success) {
221
+ console.log(`${tenants[index]}: User authenticated as ${result.username}`);
222
+ } else {
223
+ console.log(`${tenants[index]}: Authentication failed - ${result.error}`);
224
+ }
225
+ });
226
+ ```
227
+
228
+ #### Site Switching
229
+ ```typescript
230
+ // Allow users to switch between sites they have access to
231
+ async function switchUserToSite(username: string, password: string, targetSiteId: string) {
232
+ const result = await authenticateUserForSite({
233
+ targetSiteId,
234
+ username,
235
+ password,
236
+ augurInfoToken: process.env.AUGUR_INFO_ADMIN_TOKEN!
237
+ });
238
+
239
+ if (result.success) {
240
+ // Store the new site's API client
241
+ global.userAPI = result.targetSiteAPI;
242
+ global.currentSiteId = targetSiteId;
243
+ return { success: true, siteId: targetSiteId };
244
+ }
245
+
246
+ return { success: false, error: result.error };
247
+ }
248
+ ```
249
+
250
+ ### Cross-Site Error Handling
251
+
252
+ ```typescript
253
+ try {
254
+ const result = await authenticateUserForSite({
255
+ targetSiteId: 'tenant-site',
256
+ username: 'user@tenant.com',
257
+ password: 'user-pass',
258
+ augurInfoToken: adminToken
259
+ });
260
+
261
+ if (!result.success) {
262
+ switch (result.error) {
263
+ case 'Invalid username or password':
264
+ // Handle wrong username/password
265
+ break;
266
+ case 'Site not found':
267
+ // Handle invalid target site (from API error)
268
+ break;
269
+ case 'Authentication failed':
270
+ // Handle general auth failures or network issues
271
+ break;
272
+ default:
273
+ // Handle other errors
274
+ break;
275
+ }
276
+ }
277
+ } catch (error) {
278
+ console.error('Cross-site auth failed:', error.message);
279
+ }
280
+ ```
281
+
282
+ ### Security Considerations for Cross-Site Auth
283
+
284
+ 1. **Admin Token Security**: The `augur_info` admin token is very powerful - store it extremely securely
285
+ 2. **Audit Logging**: Log all cross-site authentication attempts for security monitoring
286
+ 3. **Rate Limiting**: Implement rate limiting to prevent brute force attacks
287
+ 4. **Token Scoping**: Returned tokens are scoped to the target site only
288
+ 5. **Session Management**: Properly manage and clean up cross-site sessions
289
+
290
+ ### When NOT to Use Cross-Site Auth
291
+
292
+ Don't use cross-site authentication if:
293
+ - You're working with a single site (use standard auth)
294
+ - You don't have admin-level access to `augur_info`
295
+ - You're building a simple application without multi-tenancy
296
+ - Security requirements prohibit cross-site token exchange
297
+
298
+ ---
299
+
300
+ ## Troubleshooting Authentication
301
+
302
+ ### Common Issues
303
+
304
+ **"Authentication failed" (401 Error)**
305
+ - Check your `bearerToken` is correct and not expired
306
+ - Verify your `siteId` matches your environment
307
+ - For cross-site auth, ensure your admin token has `augur_info` privileges
308
+
309
+ **"Forbidden" (403 Error)**
310
+ - Your token is valid but doesn't have permission for this operation
311
+ - Check if you need admin-level permissions
312
+ - Verify the site ID matches the token's scope
313
+
314
+ **"Site not found" (Cross-site auth)**
315
+ - Verify the target site ID exists and is accessible
316
+ - Check that the target site is properly configured
317
+ - Ensure your admin token has access to the target site
318
+
319
+ **Token Expiration**
320
+ - Implement token refresh logic
321
+ - Monitor token expiration times
322
+ - Have fallback authentication flow
323
+
324
+ ### Authentication Testing
325
+
326
+ ```typescript
327
+ // Test standard authentication
328
+ async function testAuth() {
329
+ try {
330
+ const api = new AugurAPI({
331
+ siteId: 'your-site-id',
332
+ bearerToken: 'your-token'
333
+ });
334
+
335
+ // Simple test call
336
+ const health = await api.joomla.getHealthCheck();
337
+ console.log('✅ Authentication working:', health.data.status);
338
+
339
+ // Test authenticated call
340
+ const users = await api.joomla.users.list({ limit: 1 });
341
+ console.log('✅ Authenticated API calls working');
342
+
343
+ } catch (error) {
344
+ console.error('❌ Authentication failed:', error.message);
345
+ }
346
+ }
347
+
348
+ // Test cross-site authentication
349
+ async function testCrossSiteAuth() {
350
+ try {
351
+ const result = await authenticateUserForSite({
352
+ targetSiteId: 'test-site',
353
+ username: 'test-user',
354
+ password: 'test-pass',
355
+ augurInfoToken: 'admin-token'
356
+ });
357
+
358
+ if (result.success) {
359
+ console.log('✅ Cross-site auth working');
360
+ const testCall = await result.targetSiteAPI!.joomla.getHealthCheck();
361
+ console.log('✅ Target site API working:', testCall.data.status);
362
+ } else {
363
+ console.error('❌ Cross-site auth failed:', result.error);
364
+ }
365
+ } catch (error) {
366
+ console.error('❌ Cross-site auth error:', error.message);
367
+ }
368
+ }
369
+ ```
370
+
371
+ For most applications, stick with standard authentication. Only implement cross-site authentication if you specifically need multi-tenant capabilities.
package/QUICKSTART.md ADDED
@@ -0,0 +1,255 @@
1
+ # Quick Start Guide
2
+
3
+ Get up and running with the Augur API Client in under 5 minutes.
4
+
5
+ ## What is This?
6
+
7
+ The Augur API Client connects your application to 13 different business services (like user management, inventory, pricing) through a single, easy-to-use interface. Instead of learning 13 different APIs, you learn one.
8
+
9
+ ## Installation
10
+
11
+ ```bash
12
+ npm install @simpleapps-com/augur-api
13
+ ```
14
+
15
+ ## Your First API Call
16
+
17
+ ### Step 1: Get Your Credentials
18
+
19
+ You need two pieces of information:
20
+ - **Site ID**: Identifies which site/tenant you're working with (e.g., `my-company-site`)
21
+ - **Bearer Token**: Your authentication JWT token (looks like `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...`)
22
+
23
+ Ask your system administrator or check your project's environment variables.
24
+
25
+ ### Step 2: Make Your First Call
26
+
27
+ ```typescript
28
+ import { AugurAPI } from '@simpleapps-com/augur-api';
29
+
30
+ // Create the API client
31
+ const api = new AugurAPI({
32
+ siteId: 'your-site-id', // Replace with your actual site ID
33
+ bearerToken: 'your-jwt-token' // Replace with your actual token
34
+ });
35
+
36
+ // Make your first API call - list users
37
+ try {
38
+ const users = await api.joomla.users.list({ limit: 5 });
39
+ console.log('Success! Found users:', users.data.length);
40
+ console.log('First user:', users.data[0]?.name);
41
+ } catch (error) {
42
+ console.error('Something went wrong:', error.message);
43
+ }
44
+ ```
45
+
46
+ ### Step 3: Verify It Works
47
+
48
+ If you see output like this, you're ready to go:
49
+ ```
50
+ Success! Found users: 5
51
+ First user: John Smith
52
+ ```
53
+
54
+ ## Common First Steps
55
+
56
+ ### Health Check (No Authentication Required)
57
+ Test your connection without needing authentication:
58
+
59
+ ```typescript
60
+ const api = new AugurAPI({
61
+ siteId: 'your-site-id'
62
+ // No bearerToken needed for health checks
63
+ });
64
+
65
+ const health = await api.joomla.getHealthCheck();
66
+ console.log('Service is:', health.data.status); // Should show "OK"
67
+ ```
68
+
69
+ ### Environment Variables Setup
70
+ Create a `.env` file in your project:
71
+
72
+ ```bash
73
+ # .env file
74
+ AUGUR_SITE_ID=your-site-id-here
75
+ AUGUR_JWT_TOKEN=your-jwt-token-here
76
+ ```
77
+
78
+ Then use them in your code:
79
+
80
+ ```typescript
81
+ const api = new AugurAPI({
82
+ siteId: process.env.AUGUR_SITE_ID!,
83
+ bearerToken: process.env.AUGUR_JWT_TOKEN!
84
+ });
85
+ ```
86
+
87
+ ## Understanding the Response Format
88
+
89
+ All API calls return data in the same format:
90
+
91
+ ```typescript
92
+ const response = await api.joomla.users.list();
93
+
94
+ // Response structure:
95
+ // {
96
+ // status: 200, // HTTP status code
97
+ // message: "Ok", // Status message
98
+ // data: [...], // The actual data you want
99
+ // totalResults: 150 // Total count (for lists)
100
+ // }
101
+
102
+ // Access the actual data:
103
+ const users = response.data; // Array of users
104
+ const totalCount = response.totalResults; // Total number of users
105
+ ```
106
+
107
+ ## Two Ways to Get Data
108
+
109
+ Every API call has two versions:
110
+
111
+ ```typescript
112
+ // 1. Full response (includes metadata)
113
+ const response = await api.joomla.users.list();
114
+ console.log('Users:', response.data);
115
+ console.log('Total:', response.totalResults);
116
+
117
+ // 2. Data only (just the data you want)
118
+ const users = await api.joomla.users.listData();
119
+ console.log('Users:', users); // Direct array access
120
+ ```
121
+
122
+ ## What Can You Do?
123
+
124
+ The API gives you access to:
125
+
126
+ | Service | What It Does | Example |
127
+ |---------|--------------|---------|
128
+ | **joomla** | Users, content, site management | `api.joomla.users.list()` |
129
+ | **commerce** | Shopping carts, checkout | `api.commerce.cartHeaders.list()` |
130
+ | **pricing** | Product pricing, calculations | `api.pricing.getPrice()` |
131
+ | **vmi** | Inventory, warehouses | `api.vmi.warehouses.list()` |
132
+ | **opensearch** | Product search | `api.opensearch.itemSearch.search()` |
133
+ | **items** | Product catalog | `api.items.categories.list()` |
134
+ | **customers** | Customer data | `api.customers.customer.list()` |
135
+
136
+ ## Common Patterns
137
+
138
+ ### List Things with Limits
139
+ ```typescript
140
+ // Get first 10 users
141
+ const users = await api.joomla.users.list({ limit: 10 });
142
+
143
+ // Get first 20 products
144
+ const products = await api.items.products.list({ limit: 20 });
145
+ ```
146
+
147
+ ### Get Single Items
148
+ ```typescript
149
+ // Get specific user by ID
150
+ const user = await api.joomla.users.get('123');
151
+
152
+ // Get specific product by ID
153
+ const product = await api.items.products.get(456);
154
+ ```
155
+
156
+ ### Search for Things
157
+ ```typescript
158
+ // Search for products
159
+ const results = await api.opensearch.itemSearch.search({
160
+ q: 'wire', // Search term
161
+ size: 10 // Number of results
162
+ });
163
+ ```
164
+
165
+ ## Performance Tip: Caching
166
+
167
+ Add caching to make your app faster:
168
+
169
+ ```typescript
170
+ // Cache user list for 2 hours
171
+ const users = await api.joomla.users.list({
172
+ limit: 10,
173
+ edgeCache: 2 // Cache for 2 hours
174
+ });
175
+
176
+ // Cache product search for 4 hours
177
+ const products = await api.opensearch.itemSearch.search({
178
+ q: 'electrical',
179
+ size: 20,
180
+ edgeCache: 4 // Cache for 4 hours
181
+ });
182
+ ```
183
+
184
+ **Cache Options:** 1, 2, 3, 4, 5, or 8 hours only.
185
+
186
+ ## Don't Know What's Available?
187
+
188
+ Use the discovery system to explore:
189
+
190
+ ```typescript
191
+ // See all available services
192
+ const services = await api.discover();
193
+ services.forEach(service => {
194
+ console.log(`${service.serviceName}: ${service.description}`);
195
+ });
196
+
197
+ // Find specific functionality
198
+ const userStuff = await api.findEndpoint('user management');
199
+ const inventoryStuff = await api.findEndpoint('inventory');
200
+ ```
201
+
202
+ Learn more in the [API Discovery Guide](./API-DISCOVERY.md).
203
+
204
+ ## Error Handling
205
+
206
+ Wrap your API calls in try/catch:
207
+
208
+ ```typescript
209
+ try {
210
+ const users = await api.joomla.users.list();
211
+ console.log('Got users:', users.data.length);
212
+ } catch (error) {
213
+ if (error.message.includes('401')) {
214
+ console.error('Authentication failed - check your token');
215
+ } else if (error.message.includes('404')) {
216
+ console.error('Endpoint not found - check your URL');
217
+ } else {
218
+ console.error('Something else went wrong:', error.message);
219
+ }
220
+ }
221
+ ```
222
+
223
+ ## Troubleshooting
224
+
225
+ **"Authentication failed"**
226
+ - Check your `bearerToken` is correct and not expired
227
+ - Verify your `siteId` matches your environment
228
+
229
+ **"Cannot find endpoint"**
230
+ - Try a health check first: `api.joomla.getHealthCheck()`
231
+ - Verify you're using the right service name
232
+
233
+ **"Network error"**
234
+ - Check your internet connection
235
+ - Verify the API endpoints are accessible from your network
236
+
237
+ **"Validation error"**
238
+ - Check the parameter names and types match the examples
239
+ - Look at the error message for specific field issues
240
+
241
+ ## Next Steps
242
+
243
+ 1. **Read the main [README](./README.md)** for comprehensive documentation
244
+ 2. **Explore the [API Discovery Guide](./API-DISCOVERY.md)** to find functionality
245
+ 3. **Check the Integration Guides** in the README for React, Node.js, etc.
246
+ 4. **Look at Error Handling** section for production-ready error management
247
+
248
+ ## Need Help?
249
+
250
+ - Check the comprehensive [README](./README.md) for detailed examples
251
+ - Use `api.discover()` to explore available functionality
252
+ - Look at the error messages - they usually tell you what's wrong
253
+ - Ask your team lead or system administrator for credentials
254
+
255
+ You're ready to build! Start with simple calls like listing users or checking health, then gradually explore more functionality as you need it.
package/README.md CHANGED
@@ -4,12 +4,14 @@ A comprehensive TypeScript client library for accessing Augur microservices with
4
4
 
5
5
  ## Table of Contents
6
6
 
7
+ - [🚀 Quick Start Guide](./QUICKSTART.md) - **New to Augur API? Start here!**
7
8
  - [Overview](#overview)
8
9
  - [🎯 AI-Powered Discovery System - Where Code Writes Itself](#-ai-powered-discovery-system---where-code-writes-itself)
10
+ - [📖 API Discovery Guide](./API-DISCOVERY.md) - Complete discovery system reference
9
11
  - [Features](#features)
10
12
  - [Installation](#installation)
11
13
  - [Getting Started](#getting-started)
12
- - [Authentication & Security](#authentication--security)
14
+ - [Authentication & Security](#authentication--security) | [📋 Complete Auth Guide](./AUTHENTICATION.md)
13
15
  - [API Documentation](#api-documentation)
14
16
  - [Advanced Features](#advanced-features)
15
17
  - [Integration Guides](#integration-guides)
@@ -303,7 +305,9 @@ const searchResults = await api.opensearch.itemSearch.search({
303
305
 
304
306
  ## Authentication & Security
305
307
 
306
- ### Dual Authentication System
308
+ > 📋 **[Complete Authentication Guide](./AUTHENTICATION.md)** - Comprehensive guide including cross-site authentication for multi-tenant applications.
309
+
310
+ ### Standard Authentication (Most Common)
307
311
 
308
312
  The Augur API uses a dual authentication system:
309
313
 
@@ -331,75 +335,18 @@ const pricing = await api.pricing.getHealthCheck();
331
335
  const vmiPing = await api.vmi.health.ping();
332
336
  ```
333
337
 
334
- ### Cross-Site Authentication
335
-
336
- Enable multi-tenant authentication using the special `augur_info` site:
337
-
338
- #### Option 1: Streamlined Utility Function (Recommended)
338
+ ### Environment Variables Setup
339
339
 
340
340
  ```typescript
341
- import { authenticateUserForSite } from '@simpleapps-com/augur-api';
342
-
343
- // Simple one-function approach
344
- const result = await authenticateUserForSite({
345
- targetSiteId: 'tenant_site_1',
346
- username: 'user@tenant.com',
347
- password: 'userpassword',
348
- augurInfoToken: 'admin-jwt-token' // JWT with augur_info admin privileges
349
- });
350
-
351
- if (result.success) {
352
- // Ready-to-use API client for the target site
353
- const userData = await result.targetSiteAPI!.joomla.users.get(result.userId!);
354
- console.log('User authenticated:', result.username);
355
- console.log('User data:', userData);
356
- } else {
357
- console.error('Authentication failed:', result.error);
358
- }
359
- ```
360
-
361
- #### Option 2: Reusable Authenticator
362
-
363
- ```typescript
364
- import { createCrossSiteAuthenticator } from '@simpleapps-com/augur-api';
365
-
366
- // Create reusable authenticator
367
- const crossSiteAuth = createCrossSiteAuthenticator('admin-jwt-token');
368
-
369
- // Use for multiple sites
370
- const result1 = await crossSiteAuth('tenant_site_1', 'user1@tenant.com', 'pass1');
371
- const result2 = await crossSiteAuth('tenant_site_2', 'user2@tenant.com', 'pass2');
372
-
373
- if (result1.success) {
374
- const tenantData = await result1.targetSiteAPI!.joomla.content.list({ limit: 10 });
375
- }
376
- ```
377
-
378
- #### Option 3: Manual Approach
379
-
380
- ```typescript
381
- // Manual approach using the API client directly
382
- const crossSiteAPI = new AugurAPI({
383
- siteId: 'augur_info', // Special site for cross-site operations
384
- bearerToken: 'admin-jwt-token', // JWT token with augur_info admin privileges
385
- });
341
+ // .env file
342
+ AUGUR_SITE_ID=your-site-id
343
+ AUGUR_JWT_TOKEN=your-jwt-token
386
344
 
387
- // Authenticate user against a different site
388
- const authResult = await crossSiteAPI.joomla.users.verifyPassword({
389
- username: 'user@tenant.com',
390
- password: 'userpassword',
391
- siteId: 'tenant_site_1' // Target site for authentication
345
+ // app.ts
346
+ const api = new AugurAPI({
347
+ siteId: process.env.AUGUR_SITE_ID!,
348
+ bearerToken: process.env.AUGUR_JWT_TOKEN!,
392
349
  });
393
-
394
- if (authResult.data.isVerified) {
395
- // Create API instance for the target site
396
- const tenantAPI = new AugurAPI({
397
- siteId: 'tenant_site_1',
398
- bearerToken: authResult.data.token, // Token scoped to tenant site
399
- });
400
-
401
- const userData = await tenantAPI.joomla.users.get(authResult.data.id);
402
- }
403
350
  ```
404
351
 
405
352
  ### Dynamic Authentication Updates
@@ -422,28 +369,27 @@ async function refreshTokenIfNeeded() {
422
369
  }
423
370
  ```
424
371
 
425
- ### Security Best Practices
372
+ ### Advanced: Cross-Site Authentication
426
373
 
427
- 1. **Environment Variables**: Store credentials in environment variables
428
- 2. **Token Rotation**: Implement regular token rotation in production
429
- 3. **HTTPS Only**: All API requests use HTTPS in production
430
- 4. **Secure Storage**: Never store tokens in localStorage for web apps
431
- 5. **Minimal Permissions**: Use tokens with minimal required permissions
374
+ For multi-tenant applications that need to authenticate users across different sites:
432
375
 
433
376
  ```typescript
434
- // Good: Environment-based configuration
435
- const api = new AugurAPI({
436
- siteId: process.env.AUGUR_SITE_ID!,
437
- bearerToken: getSecurelyStoredToken(), // From secure storage
438
- });
377
+ import { authenticateUserForSite } from '@simpleapps-com/augur-api';
439
378
 
440
- // Bad: Hardcoded credentials
441
- const api = new AugurAPI({
442
- siteId: 'hardcoded-site-id',
443
- bearerToken: 'hardcoded-token', // Never do this!
379
+ const result = await authenticateUserForSite({
380
+ targetSiteId: 'tenant_site_1',
381
+ username: 'user@tenant.com',
382
+ password: 'user-password',
383
+ augurInfoToken: 'admin-jwt-token'
444
384
  });
385
+
386
+ if (result.success) {
387
+ const userData = await result.targetSiteAPI!.joomla.users.get(result.userId!);
388
+ }
445
389
  ```
446
390
 
391
+ > ⚠️ **Cross-site authentication is an advanced feature.** See the [Complete Authentication Guide](./AUTHENTICATION.md) for detailed implementation patterns, security considerations, and troubleshooting.
392
+
447
393
  ## API Documentation
448
394
 
449
395
  ### Service Overview
@@ -1,4 +1,4 @@
1
- export declare const VERSION = "0.2.6";
1
+ export declare const VERSION = "0.2.7";
2
2
  export { AugurAPI } from './client';
3
3
  export { authenticateUserForSite, createCrossSiteAuthenticator, type CrossSiteAuthParams, type CrossSiteAuthResult, } from './utils/cross-site-auth';
4
4
  export { AugurAPIConfig, RequestConfig, type AugurContext, ContextCreationError, } from './core/config';
package/dist/cjs/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.PaymentsClient = exports.P21PimClient = exports.OrdersClient = exports.CustomersClient = exports.AgrSiteClient = exports.LegacyClient = exports.NexusClient = exports.ItemsClient = exports.OpenSearchClient = exports.VMIClient = exports.PricingClient = exports.CommerceClient = exports.JoomlaClient = exports.PaginationParamsSchema = exports.HealthCheckDataSchema = exports.BaseResponseSchema = exports.RateLimitError = exports.NotFoundError = exports.AuthenticationError = exports.ValidationError = exports.AugurError = exports.ContextCreationError = exports.createCrossSiteAuthenticator = exports.authenticateUserForSite = exports.AugurAPI = exports.VERSION = void 0;
4
- exports.VERSION = '0.2.6';
4
+ exports.VERSION = '0.2.7';
5
5
  // Main client
6
6
  var client_1 = require("./client");
7
7
  Object.defineProperty(exports, "AugurAPI", { enumerable: true, get: function () { return client_1.AugurAPI; } });
@@ -1,4 +1,4 @@
1
- export declare const VERSION = "0.2.6";
1
+ export declare const VERSION = "0.2.7";
2
2
  export { AugurAPI } from './client';
3
3
  export { authenticateUserForSite, createCrossSiteAuthenticator, type CrossSiteAuthParams, type CrossSiteAuthResult, } from './utils/cross-site-auth';
4
4
  export { AugurAPIConfig, RequestConfig, type AugurContext, ContextCreationError, } from './core/config';
package/dist/esm/index.js CHANGED
@@ -1,4 +1,4 @@
1
- export const VERSION = '0.2.6';
1
+ export const VERSION = '0.2.7';
2
2
  // Main client
3
3
  export { AugurAPI } from './client';
4
4
  // Utilities
@@ -1,4 +1,4 @@
1
- export declare const VERSION = "0.2.6";
1
+ export declare const VERSION = "0.2.7";
2
2
  export { AugurAPI } from './client';
3
3
  export { authenticateUserForSite, createCrossSiteAuthenticator, type CrossSiteAuthParams, type CrossSiteAuthResult, } from './utils/cross-site-auth';
4
4
  export { AugurAPIConfig, RequestConfig, type AugurContext, ContextCreationError, } from './core/config';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@simpleapps-com/augur-api",
3
- "version": "0.2.6",
3
+ "version": "0.2.7",
4
4
  "description": "TypeScript client library for Augur microservices API endpoints",
5
5
  "keywords": [
6
6
  "augur",
@@ -26,7 +26,10 @@
26
26
  },
27
27
  "files": [
28
28
  "dist",
29
- "README.md"
29
+ "README.md",
30
+ "QUICKSTART.md",
31
+ "API-DISCOVERY.md",
32
+ "AUTHENTICATION.md"
30
33
  ],
31
34
  "scripts": {
32
35
  "build": "npm run build:cjs && npm run build:esm && npm run build:types && npm run build:package-json",