@23blocks/sdk 6.5.15 → 6.6.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.
Files changed (2) hide show
  1. package/llms.txt +466 -0
  2. package/package.json +2 -1
package/llms.txt ADDED
@@ -0,0 +1,466 @@
1
+ # 23blocks SDK
2
+
3
+ > LLM-friendly reference for the 23blocks TypeScript SDK.
4
+ > Source: https://github.com/23blocks-OS/frontend-sdk
5
+
6
+ ## Overview
7
+
8
+ 23blocks SDK is a modular, framework-agnostic TypeScript SDK for building applications with 23blocks backends. It uses JSON:API v1.0 and provides native bindings for Angular (RxJS) and React (hooks/context).
9
+
10
+ ## Quick Start
11
+
12
+ ```typescript
13
+ import { create23BlocksClient } from '@23blocks/sdk';
14
+
15
+ const client = create23BlocksClient({
16
+ apiKey: 'your-api-key',
17
+ urls: {
18
+ authentication: 'https://gateway.example.com',
19
+ crm: 'https://crm.example.com',
20
+ },
21
+ });
22
+
23
+ // Sign in (tokens stored automatically)
24
+ const { user, accessToken } = await client.auth.signIn({
25
+ email: 'user@example.com',
26
+ password: 'password',
27
+ });
28
+
29
+ // Access sub-services
30
+ const contacts = await client.crm.contacts.list({ page: 1, perPage: 20 });
31
+ ```
32
+
33
+ ## Architecture
34
+
35
+ The SDK is organized as independent npm packages:
36
+
37
+ ```
38
+ @23blocks/sdk Meta-package re-exporting all blocks + client factory
39
+ @23blocks/contracts Core types: Transport, BlockConfig, IdentityCore, PageResult, ListParams
40
+ @23blocks/jsonapi-codec JSON:API v1.0 encoder/decoder
41
+ @23blocks/transport-http HTTP transport implementation (fetch-based)
42
+ @23blocks/block-* 18 feature blocks (Promise-based, framework-agnostic)
43
+ @23blocks/angular Angular services wrapping blocks (delegation pattern)
44
+ @23blocks/react React context + hooks wrapping blocks
45
+ ```
46
+
47
+ ### Block Pattern
48
+
49
+ Each block follows this pattern:
50
+
51
+ ```typescript
52
+ import { createXxxBlock } from '@23blocks/block-xxx';
53
+ const block = createXxxBlock(transport, { apiKey: 'xxx' });
54
+ // block.subService.method(params) => Promise<T>
55
+ ```
56
+
57
+ ## Core Types
58
+
59
+ ### IdentityCore
60
+
61
+ All entities extend this base interface:
62
+
63
+ ```typescript
64
+ interface IdentityCore {
65
+ id: string; // Database ID
66
+ uniqueId: string; // UUID - use this for API calls
67
+ createdAt: Date;
68
+ updatedAt: Date;
69
+ }
70
+ ```
71
+
72
+ ### PageResult<T>
73
+
74
+ List operations return paginated results:
75
+
76
+ ```typescript
77
+ interface PageResult<T> {
78
+ data: T[];
79
+ meta: {
80
+ currentPage: number; // 1-indexed
81
+ totalPages: number;
82
+ totalCount: number;
83
+ perPage: number;
84
+ };
85
+ }
86
+ ```
87
+
88
+ ### ListParams
89
+
90
+ Common parameters for list operations:
91
+
92
+ ```typescript
93
+ interface ListParams {
94
+ page?: number;
95
+ perPage?: number;
96
+ sort?: SortParam | SortParam[]; // { field: string, direction: 'asc' | 'desc' }
97
+ filter?: Record<string, string | number | boolean | string[]>;
98
+ include?: string[]; // Related resources to include
99
+ }
100
+ ```
101
+
102
+ ### EntityStatus
103
+
104
+ ```typescript
105
+ type EntityStatus = 'active' | 'inactive' | 'pending' | 'archived' | 'deleted';
106
+ ```
107
+
108
+ ## The User Object
109
+
110
+ The User type has optional relationships that are only populated when included:
111
+
112
+ ```typescript
113
+ interface User extends IdentityCore {
114
+ email: string;
115
+ username: string | null;
116
+ name: string | null;
117
+ nickname: string | null;
118
+ bio: string | null;
119
+ provider: string;
120
+ uid: string;
121
+ roleId: string | null;
122
+ status: EntityStatus;
123
+ // ... other fields
124
+
125
+ // Relationships - only populated when included via `include` param
126
+ role?: Role | null;
127
+ avatar?: UserAvatar | null;
128
+ profile?: UserProfile | null;
129
+ }
130
+ ```
131
+
132
+ ### Accessing User Profile Data
133
+
134
+ The profile is a separate relationship. To access profile fields:
135
+
136
+ ```typescript
137
+ // getCurrentUser() includes role, avatar, profile by default
138
+ const user = await client.auth.getCurrentUser();
139
+ console.log(user.profile?.firstName); // Profile data
140
+ console.log(user.profile?.lastName);
141
+ console.log(user.profile?.payload); // Custom JSON payload (object, not string)
142
+ console.log(user.role?.name); // Role name
143
+ console.log(user.avatar?.url); // Avatar URL
144
+ ```
145
+
146
+ ### Updating a Profile
147
+
148
+ `updateProfile()` returns a **User** object, not a profile. The updated profile is nested in `user.profile`:
149
+
150
+ ```typescript
151
+ const user = await client.users.updateProfile(userUniqueId, {
152
+ firstName: 'Jane',
153
+ lastName: 'Doe',
154
+ payload: { customField: 'value' }, // Must be an object, not a string
155
+ });
156
+ // Access updated profile: user.profile?.firstName === 'Jane'
157
+ ```
158
+
159
+ ## Common Gotchas
160
+
161
+ 1. **No PATCH method.** The 23blocks API only supports PUT for updates. Never use PATCH.
162
+ 2. **`payload` is an object, not a string.** Pass `Record<string, unknown>`, not `JSON.stringify()`.
163
+ 3. **`updateProfile()` returns User, not UserProfile.** Profile data is in `user.profile?.fieldName`.
164
+ 4. **`uniqueId` vs `id`.** Always use `uniqueId` (UUID) for API calls, not `id` (database ID).
165
+ 5. **Relationships are optional.** `user.role`, `user.avatar`, `user.profile` are only populated when explicitly included via the `include` parameter or when using `getCurrentUser()` / `users.get()`.
166
+ 6. **`create()` on ApiKeysService returns `ApiKeyWithSecret`.** The secret is only available once at creation time.
167
+ 7. **Service URLs are per-microservice.** Each block connects to its own backend URL.
168
+ 8. **Accessing unconfigured services throws.** If you didn't provide `urls.crm`, accessing `client.crm` throws an error.
169
+
170
+ ## Error Handling
171
+
172
+ All service methods throw on HTTP errors. The SDK uses a standard error hierarchy:
173
+
174
+ ```typescript
175
+ import { ApiError, NotFoundError, ValidationError, UnauthorizedError } from '@23blocks/contracts';
176
+
177
+ try {
178
+ const user = await client.users.get('nonexistent-id');
179
+ } catch (error) {
180
+ if (error instanceof NotFoundError) { /* 404 */ }
181
+ if (error instanceof ValidationError) { /* 422 - check error.errors for field-level details */ }
182
+ if (error instanceof UnauthorizedError) { /* 401 - token expired or invalid */ }
183
+ if (error instanceof ApiError) { /* any HTTP error - check error.status, error.message */ }
184
+ }
185
+ ```
186
+
187
+ ## Client Factory (Recommended)
188
+
189
+ ```typescript
190
+ import { create23BlocksClient } from '@23blocks/sdk';
191
+
192
+ const client = create23BlocksClient({
193
+ apiKey: 'your-api-key',
194
+ urls: { authentication: '...', crm: '...', /* only what you need */ },
195
+ authMode: 'token', // 'token' (default) or 'cookie'
196
+ storage: 'localStorage', // 'localStorage' | 'sessionStorage' | 'memory'
197
+ timeout: 30000, // Request timeout in ms
198
+ });
199
+ ```
200
+
201
+ The client provides:
202
+ - `client.auth` - Managed auth with automatic token storage
203
+ - `client.users`, `client.roles`, `client.apiKeys` - Auth sub-services (shorthand)
204
+ - `client.authentication` - Full authentication block
205
+ - `client.{blockName}` - All other blocks
206
+ - `client.getAccessToken()`, `client.setTokens()`, `client.clearSession()` - Token utilities
207
+
208
+ ## All 18 Blocks and Their Sub-Services
209
+
210
+ ### authentication (block-authentication)
211
+ - `auth` - Sign in, sign up, sign out, password reset, magic links, invitations, email confirmation
212
+ - `users` - List, get, update, delete, activate/deactivate, change role, search, profile, devices, companies
213
+ - `roles` - CRUD roles, manage permissions per role
214
+ - `permissions` - CRUD standalone permissions
215
+ - `apiKeys` - CRUD API keys with scopes, rate limits, usage stats
216
+ - `mfa` - Setup, enable, disable, verify TOTP codes, check status
217
+ - `oauth` - Facebook/Google login, tenant login, token introspection, revocation, tenant context switching
218
+ - `avatars` - CRUD avatars with presigned upload and multipart upload support
219
+ - `tenants` - List child tenants, validate codes, search, create tenant users
220
+ - `apps` - CRUD apps with webhook management
221
+ - `blocks` - List/add/remove feature blocks for companies
222
+ - `services` - Service registry with health checks
223
+ - `subscriptionModels` - List subscription plans, get by code
224
+ - `userSubscriptions` - Subscribe/cancel/reactivate user plans
225
+ - `companySubscriptions` - Subscribe/cancel/reactivate company plans
226
+ - `countries`, `states`, `counties`, `cities`, `currencies` - Geography lookups
227
+ - `guests` - Track anonymous visitors, convert to users
228
+ - `magicLinks` - Create, validate, expire magic links
229
+ - `refreshTokens` - List, revoke, revoke all/others
230
+ - `userDevices` - Register, update, unregister devices
231
+ - `tenantUsers` - Current tenant user, list tenant users
232
+ - `mailTemplates` - CRUD email templates by event
233
+ - `jwks` - Get JWKS public keys
234
+ - `adminRsaKeys` - CRUD RSA keys, rotate, deactivate
235
+ - `oidc` - OpenID Connect discovery, authorize, token exchange, userinfo
236
+
237
+ ### search (block-search)
238
+ - `search` - Full-text search across entities
239
+ - `history` - Search history tracking
240
+ - `favorites` - User favorites management
241
+ - `entities` - Entity search operations
242
+ - `identities` - Identity search operations
243
+ - `jarvis` - AI-powered search
244
+
245
+ ### products (block-products)
246
+ - `products` - CRUD products with filtering
247
+ - `cart`, `cartDetails` - Shopping cart management
248
+ - `categories`, `brands`, `vendors`, `warehouses` - Catalog taxonomy
249
+ - `channels`, `collections`, `productSets` - Product organization
250
+ - `shoppingLists` - Saved shopping lists
251
+ - `promotions`, `prices` - Pricing and promotions
252
+ - `filters` - Dynamic product filters
253
+ - `images` - Product image management
254
+ - `variations`, `reviews`, `variationReviews` - Product variants and reviews
255
+ - `stock` - Inventory management
256
+ - `suggestions`, `addons` - Recommendations and add-ons
257
+ - `myCarts`, `remarketing`, `visitors` - User cart history and remarketing
258
+ - `productVendors` - Product-vendor relationships
259
+
260
+ ### crm (block-crm)
261
+ - `accounts` - Company/organization accounts
262
+ - `contacts`, `contactEvents` - Contact management with event tracking
263
+ - `leads`, `leadFollows` - Lead management with follow-up tracking
264
+ - `opportunities` - Sales pipeline opportunities
265
+ - `meetings`, `meetingParticipants`, `meetingBillings` - Meeting scheduling and billing
266
+ - `quotes` - Sales quotes
267
+ - `subscribers`, `referrals` - Subscriber and referral tracking
268
+ - `touches` - Customer touchpoint logging
269
+ - `categories` - CRM categories
270
+ - `calendarAccounts`, `busyBlocks`, `icsTokens`, `calendarSync` - Calendar integration
271
+ - `zoomMeetings`, `zoomHosts` - Zoom integration
272
+ - `mailTemplates` - CRM email templates
273
+ - `communications` - Communication logging
274
+ - `users` - CRM user management
275
+ - `billingReports` - Billing reports
276
+
277
+ ### content (block-content)
278
+ - `posts`, `postVersions`, `postTemplates` - Content with versioning
279
+ - `comments` - Comment system
280
+ - `categories`, `tags` - Content taxonomy
281
+ - `users` - Content user identities
282
+ - `moderation` - Content moderation
283
+ - `activity` - Activity feed
284
+ - `series` - Content series/collections
285
+
286
+ ### conversations (block-conversations)
287
+ - `messages`, `draftMessages` - Messaging
288
+ - `groups`, `groupInvites` - Group management
289
+ - `notifications`, `webNotifications`, `notificationSettings` - Notification system
290
+ - `conversations` - Conversation threads
291
+ - `websocketTokens` - Real-time connection tokens
292
+ - `contexts`, `sources` - Conversation context
293
+ - `availabilities` - User availability
294
+ - `messageFiles` - File attachments
295
+ - `users` - Conversation participants
296
+ - `meetings` - Meeting scheduling
297
+
298
+ ### files (block-files)
299
+ - `storageFiles` - Company-level file storage
300
+ - `entityFiles` - Entity-associated files
301
+ - `fileSchemas` - File metadata schemas
302
+ - `userFiles` - User file uploads with presigned URLs
303
+ - `fileCategories`, `fileTags` - File organization
304
+ - `delegations` - File access delegation
305
+ - `fileAccess`, `fileAccessRequests` - Access control
306
+
307
+ ### forms (block-forms)
308
+ - `forms` - Form definitions
309
+ - `schemas`, `schemaVersions` - Form schema management
310
+ - `instances` - Form submissions/instances
311
+ - `sets` - Form grouping
312
+ - `landings` - Landing page forms
313
+ - `subscriptions` - Newsletter subscriptions
314
+ - `appointments` - Appointment scheduling
315
+ - `surveys` - Survey management
316
+ - `referrals` - Referral tracking
317
+ - `mailTemplates` - Form email templates
318
+ - `applicationForms` - Application form processing
319
+ - `crmSync` - CRM synchronization
320
+
321
+ ### geolocation (block-geolocation)
322
+ - `locations`, `locationHours`, `locationImages`, `locationSlots` - Location management
323
+ - `addresses` - Address management
324
+ - `areas`, `regions` - Geographic areas
325
+ - `routes`, `routeTracker` - Travel routes
326
+ - `bookings` - Premise bookings
327
+ - `premises`, `premiseEvents` - Premise management
328
+ - `locationTaxes`, `locationGroups` - Location config
329
+ - `identities`, `locationIdentities` - User location associations
330
+ - `geoCountries`, `geoStates`, `geoCities` - Geography lookups
331
+
332
+ ### assets (block-assets)
333
+ - `assets`, `events`, `audits` - Asset lifecycle management
334
+ - `categories`, `tags` - Asset taxonomy
335
+ - `vendors`, `warehouses` - Supply chain
336
+ - `entities` - Asset-entity relationships
337
+ - `operations` - Asset operations
338
+ - `alerts` - Asset alerts
339
+ - `users` - Asset user management
340
+ - `images` - Asset images
341
+
342
+ ### campaigns (block-campaigns)
343
+ - `campaigns`, `campaignMedia` - Campaign management
344
+ - `landingPages`, `landingTemplates` - Landing pages
345
+ - `audiences` - Audience targeting
346
+ - `targets`, `results`, `mediaResults` - Campaign targeting and analytics
347
+ - `markets`, `locations` - Market segmentation
348
+ - `templates` - Campaign templates
349
+ - `media` - Media management
350
+
351
+ ### company (block-company)
352
+ - `companies` - Company settings
353
+ - `departments`, `teams`, `teamMembers` - Org structure
354
+ - `quarters` - Quarterly planning
355
+ - `positions`, `employeeAssignments` - HR/positions
356
+
357
+ ### rewards (block-rewards)
358
+ - `rewards` - Reward definitions
359
+ - `coupons`, `couponConfigurations`, `offerCodes` - Coupon system
360
+ - `loyalty` - Loyalty program
361
+ - `badges`, `badgeCategories` - Achievement badges
362
+ - `expirationRules` - Reward expiration
363
+ - `customers` - Reward customer profiles
364
+ - `moneyRules`, `productRules`, `eventRules` - Reward trigger rules
365
+
366
+ ### sales (block-sales)
367
+ - `orders`, `orderDetails`, `orderTaxes` - Order management
368
+ - `payments` - Payment processing
369
+ - `subscriptions`, `subscriptionModels` - Recurring billing
370
+ - `entities`, `users`, `customers` - Sales entities
371
+ - `flexibleOrders` - Custom order workflows
372
+ - `stripe`, `mercadopago` - Payment gateway integrations
373
+ - `vendorPayments` - Vendor payment management
374
+
375
+ ### wallet (block-wallet)
376
+ - `wallets` - Digital wallet management
377
+ - `transactions` - Transaction history
378
+ - `authorizationCodes` - Payment authorization
379
+ - `webhooks` - Wallet webhooks
380
+
381
+ ### jarvis (block-jarvis)
382
+ - `agents`, `agentRuntime` - AI agent management and execution
383
+ - `prompts`, `promptComments` - Prompt management
384
+ - `workflows`, `workflowSteps`, `workflowParticipants`, `workflowInstances` - AI workflows
385
+ - `executions`, `executionComments` - Execution tracking
386
+ - `conversations` - AI conversations
387
+ - `aiModels` - Model configuration
388
+ - `entities`, `clusters` - Knowledge management
389
+ - `users` - Jarvis user management
390
+ - `mailTemplates` - AI email templates
391
+ - `marvinChat` - Chat interface
392
+
393
+ ### onboarding (block-onboarding)
394
+ - `onboardings`, `flows` - Onboarding flow definitions
395
+ - `userJourneys` - User journey tracking
396
+ - `userIdentities` - Identity management
397
+ - `onboard` - Onboarding execution
398
+ - `mailTemplates` - Onboarding emails
399
+ - `remarketing` - Re-engagement
400
+
401
+ ### university (block-university)
402
+ - `courses`, `courseGroups` - Course management
403
+ - `lessons` - Lesson content
404
+ - `enrollments` - Student enrollment
405
+ - `assignments`, `submissions` - Assignments and grading
406
+ - `subjects` - Subject areas
407
+ - `teachers`, `students` - User roles
408
+ - `coachingSessions` - 1:1 coaching
409
+ - `tests`, `placements` - Testing and placement
410
+ - `calendars` - Academic calendar
411
+ - `matches` - Student-teacher matching
412
+ - `attendance` - Attendance tracking
413
+ - `notes` - Student notes
414
+ - `registrationTokens` - Registration management
415
+
416
+ ## React Integration
417
+
418
+ ```typescript
419
+ import { Blocks23Provider, useAuth, useSearch } from '@23blocks/react';
420
+
421
+ function App() {
422
+ return (
423
+ <Blocks23Provider config={{
424
+ apiKey: 'your-api-key',
425
+ urls: { authentication: '...', search: '...' },
426
+ }}>
427
+ <MyComponent />
428
+ </Blocks23Provider>
429
+ );
430
+ }
431
+
432
+ function MyComponent() {
433
+ const auth = useAuth(); // AuthenticationBlock
434
+ const search = useSearch(); // SearchBlock
435
+ // Blocks are memoized - stable references across re-renders
436
+ }
437
+ ```
438
+
439
+ ## Angular Integration
440
+
441
+ ```typescript
442
+ // app.config.ts
443
+ import { provideBlocks23 } from '@23blocks/angular';
444
+
445
+ export const appConfig = {
446
+ providers: [
447
+ provideBlocks23({
448
+ apiKey: 'your-api-key',
449
+ urls: { authentication: '...', crm: '...' },
450
+ }),
451
+ ],
452
+ };
453
+
454
+ // component.ts
455
+ import { AuthenticationService, CrmService } from '@23blocks/angular';
456
+
457
+ @Component({ ... })
458
+ export class MyComponent {
459
+ private auth = inject(AuthenticationService);
460
+ private crm = inject(CrmService);
461
+
462
+ // Angular services delegate to block sub-services via typed getters
463
+ // auth.users.list() returns Promise<PageResult<User>>
464
+ // auth.auth.signIn() wraps in Observable with token management
465
+ }
466
+ ```
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@23blocks/sdk",
3
- "version": "6.5.15",
3
+ "version": "6.6.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>",
@@ -51,6 +51,7 @@
51
51
  },
52
52
  "files": [
53
53
  "dist",
54
+ "llms.txt",
54
55
  "!**/*.tsbuildinfo"
55
56
  ],
56
57
  "nx": {