@23blocks/sdk 5.0.0 → 6.0.0

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 ADDED
@@ -0,0 +1,473 @@
1
+ # @23blocks/sdk
2
+
3
+ The complete 23blocks SDK - all blocks in a single package with automatic token management.
4
+
5
+ [![npm version](https://img.shields.io/npm/v/@23blocks/sdk.svg)](https://www.npmjs.com/package/@23blocks/sdk)
6
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
7
+
8
+ ## Installation
9
+
10
+ ```bash
11
+ npm install @23blocks/sdk
12
+ ```
13
+
14
+ ## Overview
15
+
16
+ This is the recommended package for most users. It provides:
17
+
18
+ - **All blocks** - Every 23blocks feature in one package
19
+ - **Simple client** - Single factory function to create the client
20
+ - **Token management** - Automatic token storage and refresh
21
+ - **Type safety** - Full TypeScript support
22
+
23
+ ## Quick Start
24
+
25
+ ```typescript
26
+ import { create23BlocksClient } from '@23blocks/sdk';
27
+
28
+ // Create client with service URLs
29
+ const client = create23BlocksClient({
30
+ apiKey: 'your-api-key',
31
+ urls: {
32
+ authentication: 'https://auth.yourapp.com',
33
+ // Add other services as needed
34
+ // products: 'https://products.yourapp.com',
35
+ // crm: 'https://crm.yourapp.com',
36
+ },
37
+ });
38
+
39
+ // Sign in - tokens are stored automatically
40
+ const { user } = await client.auth.signIn({
41
+ email: 'user@example.com',
42
+ password: 'password',
43
+ });
44
+ console.log('Welcome', user.email);
45
+
46
+ // All subsequent requests include auth automatically
47
+ const currentUser = await client.auth.getCurrentUser();
48
+
49
+ // Sign out - tokens are cleared automatically
50
+ await client.auth.signOut();
51
+ ```
52
+
53
+ ## Configuration
54
+
55
+ ### ClientConfig Options
56
+
57
+ ```typescript
58
+ const client = create23BlocksClient({
59
+ // Required: Service URLs (only configure what you need)
60
+ urls: {
61
+ authentication: 'https://auth.yourapp.com',
62
+ products: 'https://products.yourapp.com',
63
+ crm: 'https://crm.yourapp.com',
64
+ // ... other services
65
+ },
66
+
67
+ // Required: Your API key
68
+ apiKey: 'your-api-key',
69
+
70
+ // Optional: Tenant ID for multi-tenant setups
71
+ tenantId: 'tenant-123',
72
+
73
+ // Optional: Authentication mode (default: 'token')
74
+ authMode: 'token', // 'token' | 'cookie'
75
+
76
+ // Optional: Token storage (default: 'localStorage' in browser, 'memory' in SSR)
77
+ storage: 'localStorage', // 'localStorage' | 'sessionStorage' | 'memory'
78
+
79
+ // Optional: Additional headers for every request
80
+ headers: { 'X-Custom-Header': 'value' },
81
+
82
+ // Optional: Request timeout in milliseconds (default: 30000)
83
+ timeout: 30000,
84
+ });
85
+ ```
86
+
87
+ ### Service URLs
88
+
89
+ Each microservice has its own URL. Only configure the services you need:
90
+
91
+ ```typescript
92
+ interface ServiceUrls {
93
+ authentication?: string; // Auth, users, roles
94
+ search?: string; // Search, favorites
95
+ products?: string; // Products, cart, catalog
96
+ crm?: string; // Contacts, leads, opportunities
97
+ content?: string; // CMS posts, comments
98
+ geolocation?: string; // Addresses, locations
99
+ conversations?: string; // Messages, notifications
100
+ files?: string; // File uploads
101
+ forms?: string; // Form builder
102
+ assets?: string; // Asset tracking
103
+ campaigns?: string; // Marketing campaigns
104
+ company?: string; // Company settings
105
+ rewards?: string; // Rewards, loyalty
106
+ sales?: string; // Orders, payments
107
+ wallet?: string; // Digital wallet
108
+ jarvis?: string; // AI assistant
109
+ onboarding?: string; // User onboarding
110
+ university?: string; // Learning management
111
+ }
112
+ ```
113
+
114
+ > **Note:** Accessing a service without a configured URL will throw an error with a helpful message.
115
+
116
+ ### Token Mode (Default)
117
+
118
+ Tokens are stored in browser storage and attached to requests automatically:
119
+
120
+ ```typescript
121
+ const client = create23BlocksClient({
122
+ apiKey: 'your-api-key',
123
+ urls: { authentication: 'https://auth.yourapp.com' },
124
+ authMode: 'token', // default
125
+ storage: 'localStorage', // default in browser
126
+ });
127
+ ```
128
+
129
+ ### Cookie Mode (Recommended for Security)
130
+
131
+ Backend manages authentication via httpOnly cookies:
132
+
133
+ ```typescript
134
+ const client = create23BlocksClient({
135
+ apiKey: 'your-api-key',
136
+ urls: { authentication: 'https://auth.yourapp.com' },
137
+ authMode: 'cookie',
138
+ });
139
+ ```
140
+
141
+ ### SSR / Server-Side Usage
142
+
143
+ For server-side rendering, use memory storage and pass tokens manually:
144
+
145
+ ```typescript
146
+ const client = create23BlocksClient({
147
+ apiKey: 'your-api-key',
148
+ urls: { authentication: 'https://auth.yourapp.com' },
149
+ storage: 'memory',
150
+ headers: {
151
+ Authorization: `Bearer ${tokenFromRequest}`,
152
+ },
153
+ });
154
+ ```
155
+
156
+ ### Multi-Tenant Setup
157
+
158
+ ```typescript
159
+ const client = create23BlocksClient({
160
+ apiKey: 'your-api-key',
161
+ urls: { authentication: 'https://auth.yourapp.com' },
162
+ tenantId: 'tenant-123',
163
+ });
164
+ ```
165
+
166
+ ## Authentication
167
+
168
+ ### Sign In
169
+
170
+ ```typescript
171
+ // Required: email, password
172
+ const { user, accessToken, refreshToken, expiresIn } = await client.auth.signIn({
173
+ email: 'user@example.com',
174
+ password: 'password',
175
+ });
176
+
177
+ // In token mode, tokens are automatically stored
178
+ // In cookie mode, backend sets httpOnly cookies
179
+ ```
180
+
181
+ ### Sign Up (Registration)
182
+
183
+ ```typescript
184
+ // Sign up with required fields only
185
+ const { user, accessToken, message } = await client.auth.signUp({
186
+ email: 'new@example.com', // Required
187
+ password: 'password', // Required
188
+ passwordConfirmation: 'password', // Required - must match password
189
+ });
190
+
191
+ // Sign up with optional fields
192
+ const { user, accessToken, message } = await client.auth.signUp({
193
+ // Required
194
+ email: 'new@example.com',
195
+ password: 'password',
196
+ passwordConfirmation: 'password',
197
+
198
+ // Optional
199
+ name: 'John Doe',
200
+ username: 'johndoe',
201
+ roleId: 'role-uuid',
202
+ confirmSuccessUrl: 'https://yourapp.com/confirmed', // Redirect after email confirmation
203
+ timeZone: 'America/New_York',
204
+ preferredLanguage: 'en',
205
+ payload: { referralCode: 'ABC123' }, // Custom data
206
+ subscription: 'premium-plan', // Subscription model ID
207
+ });
208
+ ```
209
+
210
+ > **Note:** If email confirmation is enabled, `accessToken` will be `undefined`. The user must confirm their email before signing in.
211
+
212
+ ### Sign Out
213
+
214
+ ```typescript
215
+ await client.auth.signOut();
216
+ // Tokens are automatically cleared (token mode) or cookies invalidated (cookie mode)
217
+ ```
218
+
219
+ ### Get Current User
220
+
221
+ ```typescript
222
+ const user = await client.auth.getCurrentUser();
223
+ // Returns user with role, avatar, and profile included
224
+ ```
225
+
226
+ ### Email Confirmation
227
+
228
+ ```typescript
229
+ // Confirm email with token from email link
230
+ const user = await client.auth.confirmEmail('confirmation-token');
231
+
232
+ // Resend confirmation email
233
+ await client.auth.resendConfirmation({
234
+ email: 'user@example.com',
235
+ confirmSuccessUrl: 'https://yourapp.com/confirmed', // Optional
236
+ });
237
+ ```
238
+
239
+ ### Password Reset
240
+
241
+ ```typescript
242
+ // Request password reset email
243
+ await client.auth.requestPasswordReset({
244
+ email: 'user@example.com',
245
+ redirectUrl: 'https://yourapp.com/reset', // Optional
246
+ });
247
+
248
+ // Update password with reset token
249
+ await client.auth.updatePassword({
250
+ password: 'newPassword',
251
+ passwordConfirmation: 'newPassword',
252
+ resetPasswordToken: 'token-from-email',
253
+ });
254
+ ```
255
+
256
+ ### Token Utilities
257
+
258
+ ```typescript
259
+ // Check if authenticated (token mode only, returns null in cookie mode)
260
+ const isLoggedIn = client.isAuthenticated();
261
+
262
+ // Get tokens manually (token mode only)
263
+ const accessToken = client.getAccessToken();
264
+ const refreshToken = client.getRefreshToken();
265
+
266
+ // Set tokens manually (useful for SSR hydration)
267
+ client.setTokens(accessToken, refreshToken);
268
+
269
+ // Clear session
270
+ client.clearSession();
271
+ ```
272
+
273
+ ## Available Blocks
274
+
275
+ The client provides access to all blocks:
276
+
277
+ | Block | Description |
278
+ |-------|-------------|
279
+ | `client.auth` | Authentication with managed tokens |
280
+ | `client.authentication` | Full authentication block |
281
+ | `client.search` | Search and favorites |
282
+ | `client.products` | Products, categories, cart |
283
+ | `client.crm` | CRM - contacts, accounts, leads |
284
+ | `client.content` | CMS - posts, comments |
285
+ | `client.geolocation` | Addresses, locations |
286
+ | `client.conversations` | Messages, notifications |
287
+ | `client.files` | File uploads |
288
+ | `client.forms` | Form builder |
289
+ | `client.assets` | Asset tracking |
290
+ | `client.campaigns` | Marketing campaigns |
291
+ | `client.company` | Company settings |
292
+ | `client.rewards` | Rewards and loyalty |
293
+ | `client.sales` | Orders and payments |
294
+ | `client.wallet` | Digital wallet |
295
+ | `client.jarvis` | AI assistant |
296
+ | `client.onboarding` | User onboarding |
297
+ | `client.university` | Learning management |
298
+
299
+ ## Usage Examples
300
+
301
+ ### Products
302
+
303
+ ```typescript
304
+ // Requires urls.products to be configured
305
+ const { data: products, meta } = await client.products.products.list({
306
+ limit: 20,
307
+ categoryId: 'category-123',
308
+ });
309
+
310
+ // Get product
311
+ const product = await client.products.products.get('product-id');
312
+
313
+ // Add to cart
314
+ const cart = await client.products.cart.addItem({
315
+ productId: 'product-id',
316
+ quantity: 2,
317
+ });
318
+
319
+ // Checkout
320
+ const order = await client.products.cart.checkout({
321
+ shippingAddressId: 'address-id',
322
+ paymentMethodId: 'payment-id',
323
+ });
324
+ ```
325
+
326
+ ### Search
327
+
328
+ ```typescript
329
+ // Requires urls.search to be configured
330
+ const { results, totalRecords } = await client.search.search.search({
331
+ query: 'laptop',
332
+ limit: 20,
333
+ });
334
+
335
+ // Suggestions
336
+ const suggestions = await client.search.search.suggest('lap', 5);
337
+
338
+ // Favorites
339
+ await client.search.favorites.add({
340
+ entityUniqueId: 'product-123',
341
+ entityType: 'Product',
342
+ });
343
+
344
+ const { data: favorites } = await client.search.favorites.list();
345
+ ```
346
+
347
+ ### CRM
348
+
349
+ ```typescript
350
+ // Requires urls.crm to be configured
351
+ const { data: contacts } = await client.crm.contacts.list({ limit: 20 });
352
+
353
+ // Create lead
354
+ const lead = await client.crm.leads.create({
355
+ firstName: 'John',
356
+ lastName: 'Doe',
357
+ email: 'john@example.com',
358
+ });
359
+
360
+ // Create opportunity
361
+ const opp = await client.crm.opportunities.create({
362
+ name: 'Enterprise Deal',
363
+ accountId: 'account-id',
364
+ value: 50000,
365
+ });
366
+ ```
367
+
368
+ ## Error Handling
369
+
370
+ ```typescript
371
+ import { isBlockErrorException, ErrorCodes } from '@23blocks/sdk';
372
+
373
+ try {
374
+ await client.auth.signIn({ email, password });
375
+ } catch (error) {
376
+ if (isBlockErrorException(error)) {
377
+ switch (error.code) {
378
+ case ErrorCodes.INVALID_CREDENTIALS:
379
+ console.log('Invalid email or password');
380
+ break;
381
+ case ErrorCodes.UNAUTHORIZED:
382
+ console.log('Session expired');
383
+ break;
384
+ case ErrorCodes.VALIDATION_ERROR:
385
+ console.log('Validation error:', error.message);
386
+ break;
387
+ case ErrorCodes.NETWORK_ERROR:
388
+ console.log('Network error');
389
+ break;
390
+ default:
391
+ console.log(error.message);
392
+ }
393
+ }
394
+ }
395
+ ```
396
+
397
+ ## Advanced: Custom Transport
398
+
399
+ For advanced users who need custom transport configuration:
400
+
401
+ ```typescript
402
+ import { createHttpTransport, createAuthenticationBlock } from '@23blocks/sdk';
403
+
404
+ const transport = createHttpTransport({
405
+ baseUrl: 'https://auth.yourapp.com',
406
+ headers: () => {
407
+ const token = localStorage.getItem('access_token');
408
+ return {
409
+ 'x-api-key': 'your-api-key',
410
+ ...(token ? { Authorization: `Bearer ${token}` } : {}),
411
+ };
412
+ },
413
+ timeout: 60000,
414
+ });
415
+
416
+ const auth = createAuthenticationBlock(transport, {
417
+ apiKey: 'your-api-key',
418
+ });
419
+
420
+ // Use the block directly
421
+ const { user } = await auth.auth.signIn({ email, password });
422
+ ```
423
+
424
+ ## TypeScript
425
+
426
+ All types are exported and can be used directly:
427
+
428
+ ```typescript
429
+ import type {
430
+ // Client types
431
+ Blocks23Client,
432
+ ClientConfig,
433
+ ServiceUrls,
434
+ AuthMode,
435
+ StorageType,
436
+
437
+ // Auth types
438
+ User,
439
+ SignInRequest,
440
+ SignInResponse,
441
+ SignUpRequest,
442
+ SignUpResponse,
443
+
444
+ // Product types
445
+ Product,
446
+ Cart,
447
+
448
+ // Core types
449
+ PageResult,
450
+ BlockError,
451
+ } from '@23blocks/sdk';
452
+ ```
453
+
454
+ ## Framework-Specific Packages
455
+
456
+ For framework-specific features:
457
+
458
+ - [`@23blocks/angular`](https://www.npmjs.com/package/@23blocks/angular) - Injectable services with RxJS
459
+ - [`@23blocks/react`](https://www.npmjs.com/package/@23blocks/react) - React hooks and context
460
+
461
+ ## Individual Blocks
462
+
463
+ If you only need specific functionality, install individual blocks:
464
+
465
+ ```bash
466
+ npm install @23blocks/transport-http @23blocks/block-authentication @23blocks/block-search
467
+ ```
468
+
469
+ See the [main README](https://github.com/23blocks-OS/frontend-sdk) for the complete list of available packages.
470
+
471
+ ## License
472
+
473
+ MIT - Copyright (c) 2024 23blocks
package/dist/index.esm.js CHANGED
@@ -253,7 +253,7 @@ export * from '@23blocks/jsonapi-codec';
253
253
  credentials: authMode === 'cookie' ? 'include' : undefined,
254
254
  headers: ()=>{
255
255
  const headers = _({}, staticHeaders, {
256
- 'api-key': apiKey
256
+ 'x-api-key': apiKey
257
257
  });
258
258
  if (tenantId) {
259
259
  headers['tenant-id'] = tenantId;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@23blocks/sdk",
3
- "version": "5.0.0",
3
+ "version": "6.0.0",
4
4
  "description": "23blocks SDK - unified meta-package re-exporting all blocks and utilities",
5
5
  "license": "MIT",
6
6
  "author": "23blocks <hello@23blocks.com>",