@simpleapps-com/augur-api 0.2.6 → 0.2.8

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,148 +1,421 @@
1
- # Augur API Client Library
1
+ # The Augur Platform: Code That Almost Writes Itself
2
2
 
3
- A comprehensive TypeScript client library for accessing Augur microservices with type safety, runtime validation, edge caching, and excellent developer experience.
3
+ Transform enterprise API chaos into developer flow with intelligent client generation, context-aware discovery, and AI-powered development acceleration.
4
+
5
+ ## Experience the Magic in 30 Seconds
6
+
7
+ ```typescript
8
+ // Before: 35+ lines of authentication boilerplate
9
+ const userJwt = await getToken({ req: request });
10
+ if (!userJwt?.jwtToken) throw new Error('Authentication failed');
11
+ const api = new AugurAPI({ siteId: context.siteId, bearerToken: userJwt.jwtToken });
12
+
13
+ // After: Pure business intent ✨
14
+ const api = AugurAPI.fromContext(context);
15
+
16
+ // Ask for anything and find it instantly
17
+ const userOps = await api.findEndpoint('user management');
18
+ const inventory = await api.findEndpoint('stock levels');
19
+ const pricing = await api.findEndpoint('product pricing');
20
+
21
+ // Code that understands your business domain
22
+ const users = await api.joomla.users.list({ limit: 10, edgeCache: 2 });
23
+ const availability = await api.vmi.inventory.checkAvailability(warehouse);
24
+ const price = await api.pricing.getPrice({ customerId, itemId, quantity });
25
+ ```
4
26
 
5
27
  ## Table of Contents
6
28
 
7
- - [Overview](#overview)
8
- - [🎯 AI-Powered Discovery System - Where Code Writes Itself](#-ai-powered-discovery-system---where-code-writes-itself)
9
- - [Features](#features)
10
- - [Installation](#installation)
11
- - [Getting Started](#getting-started)
12
- - [Authentication & Security](#authentication--security)
13
- - [API Documentation](#api-documentation)
14
- - [Advanced Features](#advanced-features)
15
- - [Integration Guides](#integration-guides)
16
- - [Error Handling](#error-handling)
17
- - [Configuration](#configuration)
18
- - [Performance Optimization](#performance-optimization)
19
- - [Development](#development)
20
- - [Contributing](#contributing)
29
+ - [🚀 Quick Start Guide](./QUICKSTART.md) - **Experience the magic in under 5 minutes**
30
+ - [The Five Ideals in Action](#the-five-ideals-in-action)
31
+ - [🎯 AI-Powered Discovery System](#-ai-powered-discovery-system)
32
+ - [📖 API Discovery Guide](./API-DISCOVERY.md) - Natural language API navigation
33
+ - [Developer Experience Revolution](#developer-experience-revolution)
34
+ - [Context-Aware Architecture](#context-aware-architecture)
35
+ - [Installation & First Steps](#installation--first-steps)
36
+ - [Intelligent Discovery Examples](#intelligent-discovery-examples)
37
+ - [Cross-Service Intelligence](#cross-service-intelligence)
38
+ - [Advanced Capabilities](#advanced-capabilities)
39
+ - [Platform Integration](#platform-integration)
40
+ - [Performance & Caching](#performance--caching)
41
+ - [Troubleshooting & Support](#troubleshooting--support)
21
42
 
22
- ## Overview
43
+ ## The Five Ideals in Action
23
44
 
24
- The Augur API Client Library provides a unified TypeScript SDK for accessing Augur's microservices ecosystem. Built with modern web development in mind, it offers seamless integration with React, React Native, Next.js, and Node.js applications.
45
+ This platform embodies the Five Ideals from The Unicorn Project, transforming how developers interact with enterprise APIs:
25
46
 
26
- ### Key Capabilities
47
+ ### Locality and Simplicity ✨
48
+ **No more coordination across 13 different APIs.** One unified interface eliminates architectural complexity.
27
49
 
28
- - **13 Microservice Clients**: Comprehensive coverage of Joomla, Commerce, Pricing, VMI, OpenSearch, Items, Legacy, Nexus, AGR Site, Customers, Orders, P21 PIM, and Payments services
29
- - **Type-Safe Operations**: Full TypeScript support with auto-generated types from Zod schemas
30
- - **Edge Caching**: Built-in Cloudflare integration for optimal performance
31
- - **Cross-Site Authentication**: Support for multi-tenant applications
32
- - **Runtime Validation**: Zod schemas validate all requests and responses
33
- - **Developer Experience**: Rich JSDoc documentation and IntelliSense support
50
+ ```typescript
51
+ // Instead of learning 13 different authentication patterns
52
+ await joomlaAPI.authenticate(token);
53
+ await commerceAPI.setAuth(bearer);
54
+ await pricingAPI.login(credentials);
34
55
 
35
- ## IDE Support & AI Assistant Integration
56
+ // One pattern rules them all
57
+ const api = AugurAPI.fromContext(context);
58
+ ```
36
59
 
37
- This client library is designed to work seamlessly with modern IDEs and AI coding assistants through comprehensive semantic documentation.
60
+ ### Focus, Flow, and Joy 🎯
61
+ **Zero context switching.** Intelligent discovery means never leaving your flow state.
38
62
 
39
- ### IntelliSense & Auto-completion
63
+ ```typescript
64
+ // No documentation hunting, no API reference browsing
65
+ const results = await api.findEndpoint('inventory management');
66
+ // Instantly find: api.vmi.warehouses.list, api.vmi.inventory.checkAvailability
67
+
68
+ // Your IDE becomes clairvoyant with comprehensive semantic JSDoc
69
+ api.vmi.inventory. // ← Auto-complete shows exactly what you need
70
+ ```
71
+
72
+ ### Improvement of Daily Work 🔄
73
+ **The platform learns your patterns** and suggests related operations across services.
74
+
75
+ ```typescript
76
+ // When you work with users, it suggests related customer operations
77
+ const user = await api.joomla.users.get('123');
78
+ // Related suggestions: api.customers.customer.get, api.orders.salesRep.getOrders
79
+ ```
80
+
81
+ ### Psychological Safety 🛡️
82
+ **Fail fast with clear, actionable errors.** No more guessing what went wrong.
83
+
84
+ ```typescript
85
+ try {
86
+ const api = AugurAPI.fromContext(context);
87
+ } catch (error) {
88
+ // Clear guidance: "Context missing siteId - check your context.siteId property"
89
+ // No blame, just solutions
90
+ }
91
+ ```
40
92
 
41
- Every method includes detailed JSDoc with:
42
- - **Parameter descriptions** and types
43
- - **Usage examples** with real code
44
- - **Related methods** and cross-service connections
45
- - **Business context** and workflow information
93
+ ### Customer Focus 📊
94
+ **Business context embedded** in every endpoint. Search by business intent, not technical implementation.
46
95
 
47
96
  ```typescript
48
- client.agrSite.settings. // IDE shows all available methods with descriptions
97
+ // Search by what you're trying to accomplish
98
+ await api.findEndpoint('customer order history');
99
+ await api.findEndpoint('product recommendations');
100
+ await api.findEndpoint('inventory replenishment');
49
101
  ```
50
102
 
51
- ### AI Assistant Features
103
+ ## AI-Powered Discovery System
104
+
105
+ **Never memorize API endpoints again.** The discovery system understands business context and finds functionality through natural language.
106
+
107
+ ### Semantic Intelligence
52
108
 
53
- The semantic JSDoc tags help AI assistants understand:
109
+ Every endpoint includes AI-readable metadata:
54
110
 
55
111
  ```typescript
56
112
  /**
57
- * @searchTerms ["settings", "configuration", "site config"]
58
- * @relatedEndpoints ["api.agrSite.settings.get", "api.agrSite.settings.update"]
59
- * @workflow ["settings-management", "site-configuration"]
60
- * @commonPatterns ["Get all settings", "List site configuration"]
113
+ * @searchTerms ["users", "authentication", "user management", "login"]
114
+ * @relatedEndpoints ["api.customers.customer.get", "api.joomla.userGroups.list"]
115
+ * @workflow ["user-onboarding", "authentication-flow", "user-administration"]
116
+ * @commonPatterns ["Get user profile", "List active users", "Create new account"]
61
117
  */
62
118
  ```
63
119
 
64
- This means when you ask an AI assistant to "help me manage site settings", it can:
65
- 1. Find the right service (`agrSite.settings`)
66
- 2. Suggest the correct method (`list`, `get`, `create`, etc.)
67
- 3. Show related operations you might need
68
- 4. Provide complete workflow examples
120
+ ### Cross-Service Awareness
121
+
122
+ The system maps relationships between all 13 microservices:
123
+
124
+ ```typescript
125
+ // Working with users? It knows you might need customers too
126
+ const userEndpoints = await api.findEndpoint('user management');
127
+ // Suggests: joomla.users.list, customers.customer.get, orders.salesRep.getOrders
128
+
129
+ // Working with inventory? It connects you to pricing
130
+ const inventoryOps = await api.findEndpoint('stock management');
131
+ // Suggests: vmi.warehouses.list, pricing.getPrice, items.products.get
132
+ ```
69
133
 
70
- ### Dual API Pattern
134
+ ## Developer Experience Revolution
71
135
 
72
- Each service provides two ways to call methods:
136
+ ### Context-Aware Creation
137
+ Eliminate 70% of setup boilerplate with intelligent context extraction:
73
138
 
74
139
  ```typescript
75
- // Standard method - returns full response with metadata
76
- const response = await client.agrSite.settings.list();
77
- console.log(response.data, response.total, response.message);
140
+ // Traditional enterprise pattern (35+ lines)
141
+ const authentication = await authenticateUser(request);
142
+ if (!authentication.success) {
143
+ return handleAuthFailure(authentication.error);
144
+ }
145
+ const siteContext = await resolveSiteContext(authentication.user);
146
+ const apiConfig = {
147
+ siteId: siteContext.siteId,
148
+ bearerToken: authentication.jwtToken,
149
+ timeout: getConfiguredTimeout(),
150
+ retries: getRetryPolicy()
151
+ };
152
+ const api = new AugurAPI(apiConfig);
78
153
 
79
- // Data method - returns only the data portion
80
- const settings = await client.agrSite.settings.listData();
81
- console.log(settings); // Direct array access
154
+ // Context-aware magic (1 line)
155
+ const api = AugurAPI.fromContext(context);
82
156
  ```
83
157
 
84
- ### API Discovery Functions
158
+ ### Intelligent Method Discovery
159
+ Every method includes rich semantic metadata for AI assistants:
160
+
161
+ ```typescript
162
+ // Ask your AI assistant: "Help me manage warehouse inventory"
163
+ // It instantly finds and suggests:
164
+ await api.vmi.warehouses.list({ customerId: 12345 });
165
+ await api.vmi.inventory.checkAvailability(warehouseId);
166
+ await api.vmi.inventory.replenish(warehouseId, { items });
167
+ ```
168
+
169
+ ### Factory Pattern Excellence
170
+ Sophisticated factory patterns create consistent, discoverable APIs:
171
+
172
+ ```typescript
173
+ // Auto-generated from OpenAPI specs with semantic enhancement
174
+ export class VMIClient extends BaseServiceClient {
175
+ get warehouses() { return this.createWarehouseOperations(); }
176
+ get inventory() { return this.createInventoryOperations(); }
177
+ get distributors() { return this.createDistributorOperations(); }
178
+ }
179
+ ```
85
180
 
86
- The client provides discovery functions for exploring available services and endpoints:
181
+ ## Installation & First Steps
87
182
 
88
- #### `discover()` - Service Map
183
+ ```bash
184
+ npm install @simpleapps-com/augur-api
185
+ ```
89
186
 
90
- Get an overview of available services and their discoverable endpoints:
187
+ ### Immediate Value Demo
91
188
 
92
189
  ```typescript
93
- const api = new AugurAPI({ siteId: 'my-site', bearerToken: 'token' });
190
+ import { AugurAPI } from '@simpleapps-com/augur-api';
191
+
192
+ // Create from context (eliminates boilerplate)
193
+ const api = AugurAPI.fromContext(context);
194
+
195
+ // Discover capabilities (no documentation needed)
94
196
  const services = await api.discover();
197
+ console.log(`Connected to ${services.length} business services`);
198
+
199
+ // Find what you need (natural language)
200
+ const userStuff = await api.findEndpoint('user management');
201
+ const inventoryStuff = await api.findEndpoint('stock levels');
202
+
203
+ // Work with intelligent caching (sub-100ms responses)
204
+ const users = await api.joomla.users.list({
205
+ limit: 10,
206
+ edgeCache: 2 // Cloudflare edge caching
207
+ });
208
+ ```
209
+
210
+ ## Intelligent Discovery Examples
211
+
212
+ ### Business Context Understanding
213
+
214
+ The platform knows your business domain and connects related operations:
215
+
216
+ ```typescript
217
+ // Search by business intent, not technical endpoints
218
+ const userOps = await api.findEndpoint('customer account management');
219
+ // Returns:
220
+ // - api.joomla.users.list (user authentication)
221
+ // - api.customers.customer.get (customer profiles)
222
+ // - api.orders.salesRep.getOrders (order history)
223
+
224
+ const inventoryOps = await api.findEndpoint('stock replenishment');
225
+ // Returns:
226
+ // - api.vmi.inventory.checkAvailability (current levels)
227
+ // - api.vmi.inventory.replenish (automated ordering)
228
+ // - api.pricing.getPrice (cost calculations)
229
+ ```
230
+
231
+ ### Workflow-Aware Suggestions
232
+
233
+ Working on one task? The system suggests the next logical steps:
234
+
235
+ ```typescript
236
+ // Create a user account
237
+ const newUser = await api.joomla.users.create({
238
+ username: 'john.doe',
239
+ email: 'john@company.com'
240
+ });
241
+
242
+ // System knows you might need to:
243
+ // 1. Set up customer profile: api.customers.customer.create()
244
+ // 2. Assign user groups: api.joomla.userGroups.createMapping()
245
+ // 3. Check permissions: api.joomla.users.groups.list()
246
+ ```
247
+
248
+ ### Cross-Service Intelligence
249
+
250
+ The discovery system maps business workflows across all 13 microservices:
251
+
252
+ ```typescript
253
+ // E-commerce workflow discovery
254
+ const ecommerceFlow = await api.findEndpoint('online shopping');
255
+ // Suggests complete customer journey:
256
+ // - Product search: api.opensearch.itemSearch.search()
257
+ // - Pricing: api.pricing.getPrice()
258
+ // - Cart management: api.commerce.cartHeaders.lookup()
259
+ // - Checkout: api.commerce.checkout.get()
260
+ // - Payment: api.payments.unified.transactionSetup()
261
+ ```
262
+
263
+ ## Context-Aware Architecture
264
+
265
+ ### Intelligent Context Extraction
266
+
267
+ The `fromContext()` method understands various context patterns:
268
+
269
+ ```typescript
270
+ // Middleware context
271
+ const api = AugurAPI.fromContext({
272
+ siteId: req.headers['x-site-id'],
273
+ jwt: req.headers.authorization?.replace('Bearer ', ''),
274
+ userId: req.user.id
275
+ });
276
+
277
+ // Tool handler context
278
+ const api = AugurAPI.fromContext({
279
+ siteId: context.siteId,
280
+ bearerToken: context.authentication.token,
281
+ parameters: context.requestParams
282
+ });
283
+
284
+ // Next.js context
285
+ const api = AugurAPI.fromContext({
286
+ siteId: process.env.NEXT_PUBLIC_SITE_ID,
287
+ jwt: session.accessToken
288
+ });
289
+ ```
290
+
291
+ ### Factory Pattern Excellence
292
+
293
+ Each service client is lazily instantiated with sophisticated caching:
294
+
295
+ ```typescript
296
+ // Clients are created on-demand and cached
297
+ const joomla1 = api.joomla; // Creates new instance
298
+ const joomla2 = api.joomla; // Returns cached instance
299
+ console.log(joomla1 === joomla2); // true
300
+
301
+ // Token changes invalidate all clients automatically
302
+ api.setAuthToken('new-token');
303
+ const joomla3 = api.joomla; // Creates fresh instance with new token
304
+ console.log(joomla1 === joomla3); // false
305
+ ```
306
+
307
+ ### Semantic Method Generation
308
+
309
+ Every endpoint includes rich semantic metadata for AI discovery:
310
+
311
+ ```typescript
312
+ /**
313
+ * List site settings with intelligent filtering and caching
314
+ * @fullPath api.agrSite.settings.list
315
+ * @service agr-site
316
+ * @domain site-content-management
317
+ * @searchTerms ["settings", "configuration", "site management", "admin"]
318
+ * @relatedEndpoints ["api.agrSite.settings.get", "api.agrSite.settings.update"]
319
+ * @workflow ["site-administration", "configuration-management"]
320
+ * @commonPatterns ["Get all settings", "Filter by service", "Cache configuration"]
321
+ * @discoverable true
322
+ */
323
+ async list(params?: SettingListParams): Promise<SettingListResponse> {
324
+ // Implementation uses sophisticated base class patterns
325
+ }
326
+ ```
327
+
328
+ ## Advanced Capabilities
329
+
330
+ ### Intelligent Service Discovery
95
331
 
96
- // Returns ServiceMap[] with:
97
- // - serviceName: string
98
- // - description: string
99
- // - baseUrl: string
100
- // - endpointCount: number
101
- // - endpoints: DiscoveryEndpoint[]
332
+ The discovery system provides both exploration and targeted search:
102
333
 
334
+ ```typescript
335
+ // Comprehensive service topology
336
+ const services = await api.discover();
337
+ console.log(`Platform connected to ${services.length} business services`);
338
+
339
+ // Each service reveals its capabilities
103
340
  services.forEach(service => {
104
- console.log(`${service.serviceName}: ${service.endpointCount} endpoints`);
341
+ console.log(`${service.serviceName}: ${service.endpointCount} operations available`);
342
+ console.log(`Business domain: ${service.description}`);
105
343
  });
344
+
345
+ // Targeted functionality search with intelligent scoring
346
+ const results = await api.findEndpoint('inventory management', {
347
+ minScore: 0.1, // Relevance threshold
348
+ maxResults: 10, // Limit results
349
+ service: 'vmi', // Optional service filter
350
+ domain: 'inventory-management', // Business domain filter
351
+ readOnly: true // Only read operations
352
+ });
353
+
354
+ // Results include relevance scores and match reasoning
355
+ results.forEach(result => {
356
+ console.log(`${result.endpoint.fullPath} (score: ${result.score})`);
357
+ console.log(`Match reason: ${result.matchReason}`);
358
+ });
359
+ ```
360
+
361
+ ### Multi-Method Pattern Innovation
362
+
363
+ Every endpoint offers dual access patterns for maximum flexibility:
364
+
365
+ ```typescript
366
+ // Full response with metadata (standard pattern)
367
+ const response = await api.joomla.users.list({ limit: 10 });
368
+ console.log(`Found ${response.data.length} users`);
369
+ console.log(`Total available: ${response.totalResults}`);
370
+ console.log(`Status: ${response.message}`);
371
+
372
+ // Data-only access (streamlined pattern)
373
+ const users = await api.joomla.users.listData({ limit: 10 });
374
+ console.log(users); // Direct array access, no wrapper
106
375
  ```
107
376
 
108
- #### `findEndpoint()` - Endpoint Search
377
+ ### Sophisticated Caching Architecture
109
378
 
110
- Search across services for endpoints matching a search term:
379
+ Intelligent edge caching with business-aware TTL policies:
111
380
 
112
381
  ```typescript
113
- // Basic search
114
- const results = await api.findEndpoint('users');
382
+ // Cache strategy varies by data volatility
383
+ const categories = await api.items.categories.list({
384
+ edgeCache: 8 // Static reference data - 8 hours
385
+ });
386
+
387
+ const pricing = await api.pricing.getPrice({
388
+ customerId: 12345,
389
+ itemId: 'STANDARD-ITEM',
390
+ quantity: 10,
391
+ edgeCache: 3 // Standard pricing - 3 hours
392
+ });
115
393
 
116
- // With options
117
- const results = await api.findEndpoint('settings', {
118
- minScore: 0.1, // Minimum relevance score (default: 0.1)
119
- maxResults: 10, // Max results (default: 10)
120
- service: 'agrSite', // Filter by service
121
- domain: 'site-content-management', // Filter by domain
122
- readOnly: true // Only GET endpoints
394
+ const cart = await api.commerce.cartHeaders.list({
395
+ userId: 123,
396
+ edgeCache: 1 // Volatile user data - 1 hour only
123
397
  });
124
398
 
125
- // Returns EndpointSearchResult[] with:
126
- // - endpoint: DiscoveryEndpoint (with fullPath, service, domain, etc.)
127
- // - score: number (0-1 relevance)
128
- // - matchReason: string
399
+ // Real-time operations never cached
400
+ const auth = await api.joomla.users.verifyPassword({
401
+ username: 'user',
402
+ password: 'pass'
403
+ // No edgeCache - authentication must be real-time
404
+ });
129
405
  ```
130
406
 
131
- ## Features
407
+ ## Platform Capabilities Matrix
132
408
 
133
- **Context-Aware Magic** - Eliminate 70% of setup boilerplate with `fromContext()` ⭐ NEW!
134
- ✅ **AI-Powered Discovery** - Natural language search finds any functionality instantly
135
- **Semantic Intelligence** - Understands business context and suggests workflows
136
- **Cross-Service Awareness** - Maps relationships between all microservices
137
- **Simple API** - Intuitive method names following REST conventions
138
- **Type Safe** - Full TypeScript support with auto-completion
139
- **Runtime Validation** - Zod schemas validate all requests and responses
140
- **Automatic Retries** - Built-in retry logic for failed requests
141
- **Smart Authentication** - Handles JWT tokens and site IDs automatically
142
- **Edge Caching** - Cloudflare integration for sub-100ms response times
143
- ✅ **Multi-Platform** - Works in React Native, React, Next.js, Node.js, and Electron
144
- ✅ **Great DX** - Helpful error messages and comprehensive JSDoc documentation
145
- ✅ **Cross-Site Auth** - Multi-tenant authentication support
409
+ | Capability | Impact | Technical Implementation |
410
+ |------------|--------|-------------------------|
411
+ | **Context-Aware Creation** | 70% boilerplate reduction | `AugurAPI.fromContext()` with intelligent field extraction |
412
+ | **Natural Language Discovery** | Zero API documentation hunting | Semantic JSDoc parsing with cross-service mapping |
413
+ | **Intelligent Caching** | Sub-100ms response times | Cloudflare edge integration with business-aware TTL |
414
+ | **Factory Pattern Excellence** | Consistent developer experience | Lazy instantiation with automatic cache invalidation |
415
+ | **Cross-Service Intelligence** | Business workflow awareness | Relationship mapping across 13 microservices |
416
+ | **AI Assistant Integration** | Code that almost writes itself | Rich semantic metadata in every endpoint |
417
+ | **Type Safety** | Runtime validation guarantee | Zod schema validation on all requests/responses |
418
+ | **Multi-Platform Support** | Universal JavaScript compatibility | React, React Native, Next.js, Node.js, Electron |
146
419
 
147
420
  ## Installation
148
421
 
@@ -303,7 +576,9 @@ const searchResults = await api.opensearch.itemSearch.search({
303
576
 
304
577
  ## Authentication & Security
305
578
 
306
- ### Dual Authentication System
579
+ > 📋 **[Complete Authentication Guide](./AUTHENTICATION.md)** - Comprehensive guide including cross-site authentication for multi-tenant applications.
580
+
581
+ ### Standard Authentication (Most Common)
307
582
 
308
583
  The Augur API uses a dual authentication system:
309
584
 
@@ -331,75 +606,18 @@ const pricing = await api.pricing.getHealthCheck();
331
606
  const vmiPing = await api.vmi.health.ping();
332
607
  ```
333
608
 
334
- ### Cross-Site Authentication
335
-
336
- Enable multi-tenant authentication using the special `augur_info` site:
337
-
338
- #### Option 1: Streamlined Utility Function (Recommended)
339
-
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
609
+ ### Environment Variables Setup
362
610
 
363
611
  ```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
- });
612
+ // .env file
613
+ AUGUR_SITE_ID=your-site-id
614
+ AUGUR_JWT_TOKEN=your-jwt-token
386
615
 
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
616
+ // app.ts
617
+ const api = new AugurAPI({
618
+ siteId: process.env.AUGUR_SITE_ID!,
619
+ bearerToken: process.env.AUGUR_JWT_TOKEN!,
392
620
  });
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
621
  ```
404
622
 
405
623
  ### Dynamic Authentication Updates
@@ -422,28 +640,27 @@ async function refreshTokenIfNeeded() {
422
640
  }
423
641
  ```
424
642
 
425
- ### Security Best Practices
643
+ ### Advanced: Cross-Site Authentication
426
644
 
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
645
+ For multi-tenant applications that need to authenticate users across different sites:
432
646
 
433
647
  ```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
- });
648
+ import { authenticateUserForSite } from '@simpleapps-com/augur-api';
439
649
 
440
- // Bad: Hardcoded credentials
441
- const api = new AugurAPI({
442
- siteId: 'hardcoded-site-id',
443
- bearerToken: 'hardcoded-token', // Never do this!
650
+ const result = await authenticateUserForSite({
651
+ targetSiteId: 'tenant_site_1',
652
+ username: 'user@tenant.com',
653
+ password: 'user-password',
654
+ augurInfoToken: 'admin-jwt-token'
444
655
  });
656
+
657
+ if (result.success) {
658
+ const userData = await result.targetSiteAPI!.joomla.users.get(result.userId!);
659
+ }
445
660
  ```
446
661
 
662
+ > ⚠️ **Cross-site authentication is an advanced feature.** See the [Complete Authentication Guide](./AUTHENTICATION.md) for detailed implementation patterns, security considerations, and troubleshooting.
663
+
447
664
  ## API Documentation
448
665
 
449
666
  ### Service Overview
@@ -1,4 +1,4 @@
1
- export declare const VERSION = "0.2.6";
1
+ export declare const VERSION = "0.2.8";
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';