### Install Dependencies and Setup Environment Source: https://github.com/bitrix24/b24jssdk/blob/main/playgrounds/nuxt/README.md Install project dependencies and copy the environment configuration file. Remember to fill in your Bitrix24 credentials in the .env file. ```bash pnpm install cp .env.example .env # Fill in your Bitrix24 credentials in .env ``` -------------------------------- ### Install and Setup Telegram Bot Source: https://github.com/bitrix24/b24jssdk/blob/main/docs/content/docs/2.working-with-the-rest-api/66.logger-telegram.md Instructions for setting up a Telegram bot via @BotFather to obtain the necessary token and chat ID. ```bash # Create a bot via @BotFather # Get the token and chat_id ``` -------------------------------- ### Start Documentation Development Server Source: https://github.com/bitrix24/b24jssdk/blob/main/AGENTS.md Starts a local development server for the project's documentation site. Allows for live preview of documentation changes. ```bash pnpm run docs:dev ``` -------------------------------- ### Example Script Execution Source: https://github.com/bitrix24/b24jssdk/blob/main/scripts/b24-self-task/README.md An example of how to activate the virtual environment and run the self-task automation script with a specific task ID. ```bash source venv/bin/activate python scripts/b24-self-task/make.py 2026 ``` -------------------------------- ### Install and Prepare Packages Source: https://github.com/bitrix24/b24jssdk/blob/main/CLAUDE.md Bootstrap the monorepo and prepare all packages for development by building and stubbing them. ```bash pnpm install # bootstrap pnpm run dev:prepare # build/stub all packages so workspaces resolve ``` -------------------------------- ### Example: Getting all companies with filtering Source: https://github.com/bitrix24/b24jssdk/blob/main/docs/content/docs/2.working-with-the-rest-api/2.call-list-rest-api-ver2.md An example demonstrating how to fetch a list of companies using the `crm.item.list` method with specific filters for title and creation time. It includes comprehensive error handling and logging. ```APIDOC ## Example: Getting all companies with filtering ### Description This example showcases how to retrieve a list of companies from Bitrix24 CRM using the `crm.item.list` method. It demonstrates applying filters to narrow down the results based on the company title and creation date, along with robust error handling and logging. ### Method `$b24.actions.v2.callList.make` ### Endpoint `crm.item.list` (This is the method called, not a direct HTTP endpoint) ### Parameters - **method**: `'crm.item.list'` - **params**: - **entityTypeId**: `EnumCrmEntityTypeId.company` - **filter**: - `'=%title'`: `'Prime%'` (Filter for titles starting with 'Prime') - `'>=createdTime'`: `Text.toB24Format(sixMonthAgo)` (Filter for creation time at least 6 months ago) - **select**: `['id', 'title']` (Fields to retrieve) - **idKey**: `'id'` - **customKeyForResult**: `'items'` - **requestId**: `string` (A unique identifier for the request) ### Request Example ```ts import { B24Hook, EnumCrmEntityTypeId, LoggerFactory, Text, SdkError, AjaxError } from '@bitrix24/b24jssdk' type Company = { id: number title: string } const devMode = typeof import.meta !== 'undefined' && (import.meta.dev || import.meta.env?.DEV) const $logger = LoggerFactory.createForBrowser('Example:AllCrmItems', devMode) const $b24 = B24Hook.fromWebhookUrl('https://your_domain.bitrix24.com/rest/1/webhook_code/') async function getCrmItemList(requestId: string): Promise { const sixMonthAgo = new Date() sixMonthAgo.setMonth((new Date()).getMonth() - 6) sixMonthAgo.setHours(0, 0, 0) const response = await $b24.actions.v2.callList.make({ method: 'crm.item.list', params: { entityTypeId: EnumCrmEntityTypeId.company, filter: { // use some filter by title '=%title': 'Prime%', '>=createdTime': Text.toB24Format(sixMonthAgo) // created at least 6 months ago }, select: ['id', 'title'] }, idKey: 'id', customKeyForResult: 'items', requestId }) if (!response.isSuccess) { throw new SdkError({ code: 'MY_APP_GET_PROBLEM', description: `Problem ${response.getErrorMessages().join('; ')}`, status: 404 }) } return response.getData() } // Usage const requestId = 'some-crm-item-list' try { const list = await getCrmItemList(requestId) $logger.info(`List [${list?.length}]`, { requestId, list }) } catch (error) { if (error instanceof AjaxError) { $logger.critical(error.message, { requestId, code: error.code }) } else { $logger.alert('Problem', { requestId, error }) } } ``` ### Response - **Company[]**: An array of company objects, where each object has at least an `id` and `title` property. ``` -------------------------------- ### Install b24pysdk Source: https://github.com/bitrix24/b24jssdk/blob/main/scripts/b24-self-task/README.md If you encounter a 'b24pysdk not installed' error, run this command to install the library. ```bash pip install b24pysdk ``` -------------------------------- ### Manage Application and User Options (UI Integration) Source: https://github.com/bitrix24/b24jssdk/blob/main/packages/jssdk/README-AI.md Allows setting and getting application-level flags (e.g., installation status) and user-level preferences like theme settings. ```typescript // App-level await $b24.options.appSet('installComplete', true) const appFlag = $b24.options.appGet('installComplete') // User-level await $b24.options.userSet('theme', 'dark') const theme = $b24.options.userGet('theme') ``` -------------------------------- ### Install BxAssistant Dependencies Source: https://github.com/bitrix24/b24jssdk/blob/main/docs/modules/bx-assistant/README.md Install the necessary dependencies for the BxAssistant module using pnpm. ```bash pnpm add @ai-sdk/mcp @ai-sdk/vue @ai-sdk/deepseek ai motion-v shiki shiki-stream @shikijs/core @shikijs/engine-javascript @shikijs/langs @shikijs/themes ``` -------------------------------- ### Example: Getting all Event Log Items with filtering Source: https://github.com/bitrix24/b24jssdk/blob/main/docs/content/docs/2.working-with-the-rest-api/2.call-list-rest-api-ver3.md An example demonstrating how to fetch a list of event log items using the callList.make method, including filtering by date and selecting specific fields. It also shows comprehensive error handling. ```APIDOC ## Example: Getting all Event Log Items with filtering ### Description This example shows how to retrieve a list of `main.eventlog.list` items from the past six months, filtering by timestamp and selecting only the 'id' and 'userId' fields. It includes robust error handling using `isSuccess` and custom error throwing. ### Method POST (implied by SDK usage) ### Endpoint Not directly exposed as an HTTP endpoint; invoked via SDK. ### Parameters - **method**: 'main.eventlog.list' - **params**: { filter: [['timestampX', '>=', 'YYYY-MM-DDTHH:MI:SS+ZZ:ZZ']], // Filter for items created at least 6 months ago select: ['id', 'userId'] // Select only id and userId fields } - **idKey**: 'id' - **customKeyForResult**: 'items' - **requestId**: (string) A unique identifier for the request. - **limit**: (number) Maximum number of records per request (e.g., 60). ### Request Example ```ts import { B24Hook, LoggerFactory, Text, SdkError, AjaxError } from '@bitrix24/b24jssdk' type MainEventLogItem = { id: number userId: number } const devMode = typeof import.meta !== 'undefined' && (import.meta.dev || import.meta.env?.DEV) const $logger = LoggerFactory.createForBrowser('Example:AllMainEventLogItems', devMode) const $b24 = B24Hook.fromWebhookUrl('https://your_domain.bitrix24.com/rest/1/webhook_code/') async function getMainEventLogItemList(requestId: string): Promise { const sixMonthAgo = new Date() sixMonthAgo.setMonth((new Date()).getMonth() - 6) sixMonthAgo.setHours(0, 0, 0) const response = await $b24.actions.v3.callList.make({ method: 'main.eventlog.list', params: { filter: [ ['timestampX', '>=', Text.toB24Format(sixMonthAgo)] // created at least 6 months ago ], select: ['id', 'userId'] }, idKey: 'id', customKeyForResult: 'items', requestId, limit: 60 }) if (!response.isSuccess) { throw new SdkError({ code: 'MY_APP_GET_PROBLEM', description: `Problem ${response.getErrorMessages().join('; ')}`, status: 404 }) } return response.getData() } // Usage const requestId = 'some-main-event-log-item-list' try { const list = await getMainEventLogItemList(requestId) $logger.info(`List [${list?.length}]`, { requestId, list }) } catch (error) { if (error instanceof AjaxError) { $logger.critical(error.message, { requestId, code: error.code }) } else { $logger.alert('Problem', { requestId, error }) } } ``` ### Response #### Success Response Returns an array of `MainEventLogItem` objects, each containing 'id' and 'userId'. #### Response Example ```json [ { "id": 123, "userId": 45 }, { "id": 124, "userId": 46 } ] ``` ``` -------------------------------- ### Bulk CRM Deal Creation using BatchByChunk Source: https://github.com/bitrix24/b24jssdk/blob/main/docs/content/docs/2.working-with-the-rest-api/4.batch-by-chunk-rest-api-ver2.md This example shows how to create multiple CRM deals in bulk using the `batchByChunk.make` method. It includes detailed error handling and extracts successful item IDs from the response. Ensure proper setup of `$b24` and logging. ```typescript import type { AjaxResult } from '@bitrix24/b24jssdk' import { B24Hook, EnumCrmEntityTypeId, LoggerFactory } from '@bitrix24/b24jssdk' type Deal = { id: number title: string stageId: string opportunity: number } const devMode = typeof import.meta !== 'undefined' && (import.meta.dev || import.meta.env?.DEV) const $logger = LoggerFactory.createForBrowser('Example:batchByChunkCrmItems', devMode) const $b24 = B24Hook.fromWebhookUrl('https://your_domain.bitrix24.com/rest/1/webhook_code/') async function addMultipleItems(needAdd: number, requestId: string): Promise { const calls = Array.from({ length: needAdd }, (_, i) => [ 'crm.item.add', { entityTypeId: EnumCrmEntityTypeId.deal, fields: { title: `Automatic deal #${i + 1}`, stageId: 'NEW', opportunity: Math.floor(Math.random() * 10000) + 1000 } } ]) const response = await $b24.actions.v2.batchByChunk.make<{ item: Deal }>({ calls, options: { isHaltOnError: true, requestId } }) if (!response.isSuccess) { throw new Error(`Problem: ${response.getErrorMessages().join('; ')}`) } const resultData = (response as Result[]>).getData()! const results: number[] = [] resultData.forEach((resultRow, index) => { if (resultRow.isSuccess) { results.push(resultRow.item.id) } }) return results } // Usage const requestId = 'batch/crm.item.add' try { const needAdd = 120 const items = await addMultipleItems(needAdd, requestId) $logger.info(`Retrieved ${items.length} items`, { expected: needAdd, retrieved: items.length, items }) } catch (error) { if (error instanceof AjaxError) { $logger.critical(error.message, { requestId, code: error.code }) } else { $logger.alert('Problem', { requestId, error }) } } ``` -------------------------------- ### Install Dependencies Source: https://github.com/bitrix24/b24jssdk/blob/main/AGENTS.md Installs all project dependencies across all workspaces using pnpm. This is typically the first step after cloning the repository. ```bash pnpm install ``` -------------------------------- ### Advanced Logger Configuration Example Source: https://github.com/bitrix24/b24jssdk/blob/main/docs/content/docs/2.working-with-the-rest-api/66.logger.md An advanced example showing how to configure a logger with a custom handler, formatter, and processors. ```APIDOC ```ts import { Logger, ConsoleV2Handler, LineFormatter } from '@bitrix24/b24jssdk' const $logger = new Logger('app') const handler = new ConsoleV2Handler(LogLevel.DEBUG) handler.setFormatter(new LineFormatter('[{levelName}] {message}')) $logger .pushHandler(handler) .pushProcessor(memoryUsageProcessor) .pushProcessor(pidProcessor) $logger.warning('Low memory', { freeMemory: '10MB' }) ``` ``` -------------------------------- ### Develop Documentation and Playgrounds Source: https://github.com/bitrix24/b24jssdk/blob/main/CLAUDE.md Commands to start the development server for the Nuxt-based documentation site and the Nuxt playground. ```bash pnpm run docs:dev # docs site dev server pnpm run playground-nuxt:dev # Nuxt playground (live SDK) ``` -------------------------------- ### Basic Logger Usage Example Source: https://github.com/bitrix24/b24jssdk/blob/main/docs/content/docs/2.working-with-the-rest-api/66.logger.md A basic example demonstrating how to create a logger for the browser and log an informational message with context. ```APIDOC ```ts import { LoggerFactory } from '@bitrix24/b24jssdk' const devMode = typeof import.meta !== 'undefined' && (import.meta.dev || import.meta.env?.DEV) const $logger = LoggerFactory.createForBrowser('Example:getCrmItem', devMode) $logger.info('User logged in', { userId: 123 }) ``` ``` -------------------------------- ### Getting Multiple Tasks Example Source: https://github.com/bitrix24/b24jssdk/blob/main/docs/content/docs/2.working-with-the-rest-api/3.batch-rest-api-ver3.md This TypeScript example shows how to use the batch API to retrieve details for multiple tasks simultaneously. It includes input validation, constructing the calls array, executing the batch request, and processing the results, handling potential errors for each individual task retrieval. ```APIDOC ## Getting Multiple Tasks This TypeScript example shows how to use the batch API to retrieve details for multiple tasks simultaneously. It includes input validation, constructing the calls array, executing the batch request, and processing the results, handling potential errors for each individual task retrieval. ### Method POST ### Endpoint /api/v3/batch/ ### Parameters #### Request Body - **calls** (array) - Required - An array of calls to be executed. Each call is an array containing the method name and its parameters. - **options** (object) - Optional - Configuration options for the batch request. - **isHaltOnError** (boolean) - Optional - If true, the batch request will stop executing further calls if any call fails. - **returnAjaxResult** (boolean) - Optional - If true, the response will include detailed results for each individual call. - **requestId** (string) - Optional - A unique identifier for the request. ### Request Example ```ts import type { AjaxResult } from '@bitrix24/b24jssdk' import { B24Hook, EnumCrmEntityTypeId, LoggerFactory, SdkError } from '@bitrix24/b24jssdk' type TaskItem = { id: number title: string } const devMode = typeof import.meta !== 'undefined' && (import.meta.dev || import.meta.env?.DEV) const $logger = LoggerFactory.createForBrowser('Example:batchTasks', devMode) const $b24 = B24Hook.fromWebhookUrl('https://your_domain.bitrix24.com/rest/1/webhook_code/') async function getMultipleItems(itemIds: number[], requestId: string): Promise { if (itemIds.length < 1 || itemIds.length > 50) { throw new SdkError({ code: 'MY_APP_GET_PROBLEM', description: `The number of elements must be between 1 and 50`, status: 404 }) } const calls = itemIds.map(id => [ 'tasks.task.get', { id, select: ['id', 'title'] } ]) const response = await $b24.actions.v3.batch.make<{ item: TaskItem }>({ calls, options: { isHaltOnError: true, returnAjaxResult: true, requestId } }) if (!response.isSuccess) { throw new Error(`Problem: ${response.getErrorMessages().join('; ')}`) } const resultData = (response as any).getData() // Type assertion for demonstration const results: TaskItem[] = [] resultData.forEach((resultRow: any, index: number) => { if (resultRow.isSuccess) { results.push(resultRow.getData()!.result.item) } }) return results } // Usage const requestId = 'batch/tasks.task.get' try { const itemIds = [1, 2, 3] const items = await getMultipleItems(itemIds, requestId) $logger.info(`Retrieved ${items.length} items`, { expected: itemIds.length, retrieved: items.length, items: items.map(c => ({ id: c.id, title: c.title })) }) } catch (error) { if (error instanceof Error) { // Simplified error handling for example $logger.critical(error.message, { requestId, code: (error as any).code }) } else { $logger.alert('Problem', { requestId, error }) } } ``` ### Response #### Success Response (200) - **result** (object) - Contains the results of the batch request. - **calls** (array) - An array of results, one for each call in the request. - **isSuccess** (boolean) - Indicates if the individual call was successful. - **error** (object) - If `isSuccess` is false, this contains error details. - **result** (any) - If `isSuccess` is true, this contains the result of the individual call. #### Response Example ```json { "result": { "calls": [ { "isSuccess": true, "result": { "task": { "id": 1, "title": "Example Task 1" } } }, { "isSuccess": true, "result": { "task": { "id": 2, "title": "Example Task 2" } } }, { "isSuccess": true, "result": { "task": { "id": 3, "title": "Example Task 3" } } } ] } } ``` ``` -------------------------------- ### Configure Bitrix24 Webhook Source: https://github.com/bitrix24/b24jssdk/blob/main/scripts/b24-self-task/README.md Set up your Bitrix24 webhook by copying the example environment file and adding your webhook URL. ```bash B24_WEBHOOK=https://yourdomain.bitrix24.com/rest/1/xxxx/ ``` -------------------------------- ### Signal Application Installation Completion Source: https://github.com/bitrix24/b24jssdk/blob/main/docs/content/docs/2.working-with-the-rest-api/30.frame.md Call `installFinish` to signal that the application installation process has been successfully completed. This method returns a Promise. ```typescript async installFinish(): Promise ``` -------------------------------- ### Install Nuxt Package with Package Managers Source: https://github.com/bitrix24/b24jssdk/blob/main/docs/content/docs/1.getting-started/2.installation/2.nuxt.md Install the `@bitrix24/b24jssdk-nuxt` package using your preferred package manager. ```bash pnpm add @bitrix24/b24jssdk-nuxt ``` ```bash yarn add @bitrix24/b24jssdk-nuxt ``` ```bash npm install @bitrix24/b24jssdk-nuxt ``` ```bash bun add @bitrix24/b24jssdk-nuxt ``` -------------------------------- ### Configure Environment Variables Source: https://github.com/bitrix24/b24jssdk/blob/main/playgrounds/cli/README.md Navigate to the CLI playground directory, copy the example environment file, and edit it to set your Bitrix24 webhook URL. ```bash cd playgrounds/cli cp .env.example .env ``` ```bash B24_HOOK=https://your-domain.bitrix24.com/rest/your-user-id/your-webhook-code/ ``` -------------------------------- ### Custom Handler Example Source: https://github.com/bitrix24/b24jssdk/blob/main/docs/content/docs/2.working-with-the-rest-api/66.logger.md An example demonstrating how to create a custom handler by extending the AbstractHandler class. ```APIDOC ```ts import { AbstractHandler, LogRecord } from '@bitrix24/b24jssdk' class CustomHandler extends AbstractHandler { async handle(record: LogRecord): Promise { // Send to server, write to file, etc. return true // Returns true if record was processed } } ``` ``` -------------------------------- ### Run the Nuxt Development Server Source: https://github.com/bitrix24/b24jssdk/blob/main/playgrounds/nuxt/README.md Start the Nuxt development server to run the playground app. The app will be accessible at http://localhost:3001. ```bash pnpm dev ``` -------------------------------- ### Retrieving Small Datasets with callListMethod Source: https://github.com/bitrix24/b24jssdk/blob/main/packages/jssdk/README-AI.md Example demonstrating how to use `callListMethod` to fetch all items from a list, suitable for smaller datasets that can be loaded entirely into memory. ```APIDOC ## Retrieving Small Datasets (all-in-memory) Use `callListMethod` for datasets smaller than 1000 items. ```ts import { EnumCrmEntityTypeId, Result } from '@bitrix24/b24jssdk' async function loadAllCompaniesSmall($b24: any) { const response: Result = await $b24.callListMethod( 'crm.item.list', { entityTypeId: EnumCrmEntityTypeId.company, order: { id: 'asc' }, select: ['id', 'title'] }, (progress: number) => { // Optional progress callback (0..100) // console.log('progress', progress) } ) const items = response.getData() as any[] // Process all items (already fully loaded in memory) for (const row of items) { // ...process row } return items } ``` ``` -------------------------------- ### Auth and Environment Source: https://github.com/bitrix24/b24jssdk/blob/main/packages/jssdk/README-AI.md Retrieve authentication data, refresh tokens, and get portal language and app SID. ```APIDOC ## Auth and Environment ### Description Provides access to authentication details and environment information. ### Methods - `auth.getAuthData()`: Retrieves current authentication data. - `auth.refreshAuth()`: Refreshes the authentication token. - `getLang()`: Gets the current portal UI language. - `getAppSid()`: Gets the application's SID in the current session. ### Example ```ts const auth = $b24.auth.getAuthData() // { access_token, refresh_token, expires_in, domain, member_id } | false if (!auth) { await $b24.auth.refreshAuth() } const lang = $b24.getLang() // portal UI language const sid = $b24.getAppSid() // app SID in current session ``` ``` -------------------------------- ### B24Frame Usage (REST API v2) Source: https://github.com/bitrix24/b24jssdk/blob/main/docs/content/docs/2.working-with-the-rest-api/0.index.md Example of initializing B24Frame and making a call to the REST API v2 from an application embedded within Bitrix24. ```APIDOC ## B24Frame Usage (REST API v2) ### Description Example of initializing B24Frame and making a call to the REST API v2 from an application embedded within Bitrix24. ### Method ```ts async () => { $b24 = await initializeB24Frame() const response = await B24Frame.actions.v2.call.make({ method: 'crm.contact.get', params: { id: 123 } }) } ``` ``` -------------------------------- ### Retrieving Large Datasets with fetchListMethod Source: https://github.com/bitrix24/b24jssdk/blob/main/packages/jssdk/README-AI.md Example showing how to use `fetchListMethod` to stream data in chunks, which is recommended for large datasets to manage memory usage efficiently. ```APIDOC ## Retrieving Large Datasets (streaming by chunks) Use `fetchListMethod` for large datasets to keep memory usage low. For `crm.item.list`, use `idKey: 'id'` for reliable iteration. ```ts import { EnumCrmEntityTypeId } from '@bitrix24/b24jssdk' async function loadAllDealsStreaming($b24: any) { const all: any[] = [] for await (const chunk of $b24.fetchListMethod( 'crm.item.list', { entityTypeId: EnumCrmEntityTypeId.deal, select: ['id', 'title'] }, 'id' // idKey for crm.item.list payloads )) { // Process current chunk for (const row of chunk) { // ...process row } all.push(...chunk) } return all } ``` ``` -------------------------------- ### B24Frame Usage (REST API v3) Source: https://github.com/bitrix24/b24jssdk/blob/main/docs/content/docs/2.working-with-the-rest-api/0.index.md Example of initializing B24Frame and making a call to the REST API v3 from an application embedded within Bitrix24. ```APIDOC ## B24Frame Usage (REST API v3) ### Description Example of initializing B24Frame and making a call to the REST API v3 from an application embedded within Bitrix24. ### Method ```ts async () => { $b24 = await initializeB24Frame() const response = await B24Frame.actions.v3.call.make({ method: 'tasks.task.get', params: { id: 123 } }) } ``` ``` -------------------------------- ### Bitrix24 API: Get Entire List Example Source: https://github.com/bitrix24/b24jssdk/blob/main/docs/content/docs/1.getting-started/1.index.md Retrieves all companies that match the filter criteria using `callList`. Suitable for smaller datasets where fetching all records at once is acceptable. ```typescript // 2. Get entire list (CallList) const allItems = await $b24.actions.v2.callList.make({ method: 'crm.company.list', params: { filter: { '>ID': 0 }, select: ['ID', 'TITLE'] }, idKey: 'ID', requestId: 'get-all-companies' }) ``` -------------------------------- ### Get Contacts List with B24Frame Source: https://github.com/bitrix24/b24jssdk/blob/main/docs/content/docs/1.getting-started/1.index.md This example demonstrates how to retrieve a list of contacts using the B24Frame class for applications embedded in Bitrix24. It selects specific fields and filters contacts by ID. ```typescript async function getContacts() { if (!$b24) { return } const response = await B24Frame.actions.v2.callList.make({ method: 'crm.contact.list', params: { filter: { '>ID': 0 }, select: ['ID', 'NAME', 'LAST_NAME', 'EMAIL'] }, idKey: 'ID', requestId: 'get-all-contacts' }) if (response.isSuccess) { return response.getData() } return [] } ``` -------------------------------- ### Get Requisites Fields with Personal Key (JavaScript) Source: https://github.com/bitrix24/b24jssdk/blob/main/docs/llms-full.txt Fetch requisite fields using JavaScript with a personal API key. This example logs the total number of fields returned. Ensure 'YOUR_API_KEY' is replaced. ```javascript const res = await fetch('https://vibecode.bitrix24.tech/v1/requisites/fields', { headers: { 'X-Api-Key': 'YOUR_API_KEY' }, }) const { success, data } = await res.json() console.log('Всего полей:', Object.keys(data.fields).length) ``` -------------------------------- ### B24 Helper Initialization and Usage Source: https://github.com/bitrix24/b24jssdk/blob/main/packages/jssdk/README-AI.md Demonstrates how to initialize the B24 helper, load necessary data types, and access helper data and managers. It also shows how to enable and subscribe to the Pull client for real-time notifications. ```APIDOC ## Initialization Pattern Initialize the B24 helper after `B24Frame` is initialized. ```ts import { useB24Helper, LoadDataType, type TypePullMessage } from '@bitrix24/b24jssdk' const { initB24Helper, destroyB24Helper, getB24Helper, usePullClient, useSubscribePullClient, startPullClient } = useB24Helper() const $b24 = await initializeB24Frame() await initB24Helper($b24, [ LoadDataType.Profile, LoadDataType.App, LoadDataType.Currency, LoadDataType.AppOptions, LoadDataType.UserOptions, ]) // Enable Pull usePullClient('prefix') // optionally pass userId useSubscribePullClient((m: TypePullMessage) => { // handle Pull messages }, 'application') startPullClient() // Access helper data and extra managers const helper = getB24Helper() const userId = helper.profileInfo.data.id const uniq = $b24.auth.getUniq('prefix') // unique per member ``` **Helper Managers:** profile, app, payment, license, currency, options. **Note:** Currency and options managers internally use `callBatch`/`callBatchByChunk`. ``` -------------------------------- ### UMD Initialization and Usage Source: https://github.com/bitrix24/b24jssdk/blob/main/packages/jssdk/README-AI.md Shows how to load and use the Bitrix24 SDK via a UMD bundle from a CDN, including initialization and making batch API calls. ```APIDOC ## Global B24Js Object (UMD) ### Description When using the UMD bundle loaded from a CDN, the Bitrix24 SDK is exposed globally as the `B24Js` object. This allows access to initialization functions and utility modules without a build step. ### Initialization Example ```html ``` ### Exposed Globals - `B24Js.initializeB24Frame`: Function to initialize the SDK. - `B24Js.B24Frame`: The main SDK frame class. - Managers accessible via properties of `B24Frame` (e.g., `B24Js.B24Frame.auth`, `B24Js.B24Frame.parent`). - Utilities: `B24Js.LoggerBrowser`, `B24Js.Text`, `B24Js.Type`, enums (e.g., `B24Js.EnumCrmEntityTypeId`), `B24Js.Result`, `B24Js.AjaxError`, `B24Js.AjaxResult`, etc. ``` -------------------------------- ### Making a Batch Request Source: https://github.com/bitrix24/b24jssdk/blob/main/docs/content/docs/2.working-with-the-rest-api/3.batch-rest-api-ver3.md This example demonstrates how to construct and execute a batch request using the `$b24.actions.v3.batch.make` method. It includes setting up multiple calls, configuring options like `isHaltOnError`, and handling the response, including error checking. ```APIDOC ## Making a Batch Request This example demonstrates how to construct and execute a batch request using the `$b24.actions.v3.batch.make` method. It includes setting up multiple calls, configuring options like `isHaltOnError`, and handling the response, including error checking. ### Method POST ### Endpoint /api/v3/batch/ ### Parameters #### Request Body - **calls** (array) - Required - An array of calls to be executed. Each call is an array containing the method name and its parameters. - **options** (object) - Optional - Configuration options for the batch request. - **isHaltOnError** (boolean) - Optional - If true, the batch request will stop executing further calls if any call fails. - **returnAjaxResult** (boolean) - Optional - If true, the response will include detailed results for each individual call. - **requestId** (string) - Optional - A unique identifier for the request. ### Request Example ```json { "calls": [ ["tasks.task.get", {"id": 1}], ["tasks.task.get", {"id": 2}] ], "options": { "isHaltOnError": true, "returnAjaxResult": true, "requestId": "unique-request-id" } } ``` ### Response #### Success Response (200) - **result** (object) - Contains the results of the batch request. - **calls** (array) - An array of results, one for each call in the request. - **isSuccess** (boolean) - Indicates if the individual call was successful. - **error** (object) - If `isSuccess` is false, this contains error details. - **result** (any) - If `isSuccess` is true, this contains the result of the individual call. #### Response Example ```json { "result": { "calls": [ { "isSuccess": true, "result": { "task": { "id": 1, "title": "Example Task 1" } } }, { "isSuccess": false, "error": { "code": 500, "message": "Internal Server Error" } } ] } } ``` ``` -------------------------------- ### Initialize, Call REST, and Cleanup (TypeScript/ESM) Source: https://github.com/bitrix24/b24jssdk/blob/main/packages/jssdk/README-AI.md Demonstrates initializing the SDK, making single and batched REST calls, and cleaning up resources. Ensure `initializeB24Frame()` is awaited before any SDK calls. Use `$b24.destroy()` on unmount. ```typescript import { initializeB24Frame, B24Frame, EnumCrmEntityTypeId, Text, LoggerBrowser, Result, type ISODate } from '@bitrix24/b24jssdk' const logger = LoggerBrowser.build('MyApp', import.meta.env?.DEV === true) let $b24: B24Frame async function boot() { $b24 = await initializeB24Frame() // Single method const companies = await $b24.callMethod('crm.item.list', { entityTypeId: EnumCrmEntityTypeId.company, order: { id: 'desc' }, select: ['id', 'title', 'createdTime'] }) logger.info('items:', companies.getData().result) // Batch (object syntax, with keys) const batch: Result = await $b24.callBatch({ CompanyList: { method: 'crm.item.list', params: { entityTypeId: EnumCrmEntityTypeId.company, order: { id: 'desc' }, select: ['id', 'title', 'createdTime'] } } }, true) const data = batch.getData() const list = (data.CompanyList.items || []).map((it: any) => ({ id: Number(it.id), title: it.title, createdTime: Text.toDateTime(it.createdTime as ISODate) })) logger.info('batch list:', list) } function teardown() { $b24?.destroy() } ``` -------------------------------- ### Get Multiple Tasks Using Batch API v3 Source: https://github.com/bitrix24/b24jssdk/blob/main/docs/content/docs/2.working-with-the-rest-api/3.batch-rest-api-ver3.md This example demonstrates how to fetch multiple tasks by their IDs using the Batch REST API v3. It includes input validation for the number of item IDs and detailed error handling for both the batch request and individual call results. Ensure the `B24Hook` is initialized with your domain and webhook code. ```typescript import type { AjaxResult } from '@bitrix24/b24jssdk' import { B24Hook, EnumCrmEntityTypeId, LoggerFactory, SdkError } from '@bitrix24/b24jssdk' type TaskItem = { id: number title: string } const devMode = typeof import.meta !== 'undefined' && (import.meta.dev || import.meta.env?.DEV) const $logger = LoggerFactory.createForBrowser('Example:batchTasks', devMode) const $b24 = B24Hook.fromWebhookUrl('https://your_domain.bitrix24.com/rest/1/webhook_code/') async function getMultipleItems(itemIds: number[], requestId: string): Promise { if (itemId.length < 1 || itemId.length > 50) { throw new SdkError({ code: 'MY_APP_GET_PROBLEM' description: `The number of elements must be between 1 and 50`, status: 404 }) } const calls = itemIds.map(id => [ 'tasks.task.get', { id, select: ['id', 'title'] } ]) const response = await $b24.actions.v3.batch.make<{ item: TaskItem }> ({ calls, options: { isHaltOnError: true, returnAjaxResult: true, requestId } }) if (!response.isSuccess) { throw new Error(`Problem: ${response.getErrorMessages().join('; ')}`) } const resultData = (response as Result[]>).getData() const results: TaskItem[] = [] resultData.forEach((resultRow, index) => { if (resultRow.isSuccess) { results.push(resultRow.getData()!.result.item) } }) return results } // Usage const requestId = 'batch/tasks.task.get' try { const itemIds = [1, 2, 3] const items = await getMultipleItems(itemIds, requestId) $logger.info(`Retrieved ${items.length} items`, { expected: itemIds.length, retrieved: items.length, items: items.map(c => ({ id: c.id, title: c.title })) }) } catch (error) { if (error instanceof AjaxError) { $logger.critical(error.message, { requestId, code: error.code }) } else { $logger.alert('Problem', { requestId, error }) } } ``` -------------------------------- ### Check Claude CLI Installation Source: https://github.com/bitrix24/b24jssdk/blob/main/scripts/b24-self-task/README.md Verify that the Claude Code CLI is installed and accessible in your system's PATH. Test its installation with this command. ```bash claude --version ``` -------------------------------- ### Install Python Dependencies Source: https://github.com/bitrix24/b24jssdk/blob/main/scripts/b24-self-task/README.md Install Python dependencies using pip within a virtual environment. Ensure you activate the virtual environment before installing. ```bash python -m venv venv source venv/bin/activate pip install -r scripts/b24-self-task/requirements.txt ``` -------------------------------- ### Check if Application is in Installation Mode Source: https://github.com/bitrix24/b24jssdk/blob/main/docs/content/docs/2.working-with-the-rest-api/30.frame.md Use the `isInstallMode` getter to check if the application is currently in its installation phase. ```typescript get isInstallMode(): boolean ``` -------------------------------- ### Create Industrial-Themed Products Source: https://github.com/bitrix24/b24jssdk/blob/main/playgrounds/cli/README.md Creates 10 industrial-themed products with default settings for SKUs, VAT, and currency. ```bash pnpm run dev make products-sku --total=10 ``` -------------------------------- ### Basic Usage of BatchByChunkV3.make Source: https://github.com/bitrix24/b24jssdk/blob/main/docs/content/docs/2.working-with-the-rest-api/4.batch-by-chunk-rest-api-ver3.md Demonstrates how to use BatchByChunkV3.make to execute a large number of commands. The commands are automatically divided into chunks of 50. Ensure you import necessary types like B24Hook and EnumCrmEntityTypeId. ```typescript import { B24Hook, EnumCrmEntityTypeId } from '@bitrix24/b24jssdk' // We create 150 tasks (they will be divided into 3 chunks of 50 tasks each) const commands = Array.from({ length: 150 }, (_, i) => [ 'tasks.task.get', { id: i + 1, select: ['id', 'title'] } ]) const response = await $b24.actions.v3.batchByChunk.make({ calls: commands, options: { isHaltOnError: true, requestId: 'unique-request-id' } }) ``` -------------------------------- ### Initialize and Use B24Frame SDK Source: https://github.com/bitrix24/b24jssdk/blob/main/packages/jssdk/README-AI.md Demonstrates the minimal contract for initializing the B24Frame SDK, making single API calls, performing batch requests, and cleaning up resources. ```APIDOC ## initializeB24Frame() ### Description Initializes the B24Frame SDK by establishing communication with the parent Bitrix24 window. This method must be awaited before making any other SDK calls. ### Method `initializeB24Frame(): Promise` ### Parameters None ### Returns A Promise that resolves to a `B24Frame` instance, which provides access to various SDK functionalities. ## B24Frame.callMethod(method, params) ### Description Executes a single Bitrix24 REST API method. ### Method `callMethod(method: string, params?: object): Promise` ### Parameters - **method** (string) - Required - The name of the REST API method to call (e.g., 'crm.item.list'). - **params** (object) - Optional - Parameters for the REST API method. ### Returns A Promise that resolves to a `Result` object containing the API response. ## B24Frame.callBatch(batch, atomic) ### Description Executes multiple Bitrix24 REST API methods in a single batch request. ### Method `callBatch(batch: object, atomic: boolean): Promise` ### Parameters - **batch** (object) - Required - An object where keys are batch item names and values are objects containing `method` and `params` for each call. - **atomic** (boolean) - Required - If true, the entire batch fails if any single call fails. ### Returns A Promise that resolves to a `Result` object containing the batch response. ## B24Frame.destroy() ### Description Cleans up resources and disconnects from the parent Bitrix24 window. Should be called when the component or page unmounts. ### Method `destroy(): void` ### Parameters None ``` -------------------------------- ### Install @bitrix24/b24jssdk-nuxt Module Source: https://github.com/bitrix24/b24jssdk/blob/main/packages/jssdk-nuxt/README.md Install the module to your Nuxt application using nuxi. This is the primary step to integrate the Bitrix24 JS SDK. ```bash npx nuxi module add @bitrix24/b24jssdk-nuxt ``` -------------------------------- ### Create Catalog Product Source: https://github.com/bitrix24/b24jssdk/blob/main/docs/llms-full.txt Create a new catalog product. The request body must be JSON and include required fields like name, active status, and iblockId. ```bash curl -X POST '/v1/catalog-products' \ -H 'X-Api-Key: YOUR_KEY' \ -H 'Content-Type: application/json' \ -d '{"name":"value","active":"true","iblockId":1}' ``` -------------------------------- ### Bulk Create Deals with B24Hook Source: https://github.com/bitrix24/b24jssdk/blob/main/docs/content/docs/1.getting-started/1.index.md This example demonstrates how to create multiple deals efficiently using the `batchByChunk` method with the B24Hook class. It's suitable for server applications using webhooks. ```typescript async function createMultipleDeals(dealsData: Array<{title: string, opportunity: number}>) { const calls = dealsData.map((deal, index) => [ 'crm.deal.add', { fields: { TITLE: deal.title, OPPORTUNITY: deal.opportunity, CATEGORY_ID: 0 } } ]) const response = await $b24.actions.v2.batchByChunk.make({ calls, options: { requestId: 'bulk-create-deals' } }) return response } ``` -------------------------------- ### Format Currency and Get Currency Details with JSSDK Source: https://github.com/bitrix24/b24jssdk/blob/main/packages/jssdk/README-AI.md Use the CurrencyManager to get the full name, literal representation (symbol/wording), or formatted price for a given currency and language. ```typescript const name = helper.currency.getCurrencyFullName('USD', 'en') const literal = helper.currency.getCurrencyLiteral('USD', 'en') // currency symbol/wording const price = helper.currency.format(1234.56, 'USD', 'en') ``` -------------------------------- ### Get Department by ID Source: https://github.com/bitrix24/b24jssdk/blob/main/docs/llms-full.txt Retrieve a specific department by its unique identifier. ```bash curl -X GET '/v1/departments/123' \ -H 'X-Api-Key: YOUR_KEY' ``` -------------------------------- ### Initialize and Call REST via UMD (CDN) Source: https://github.com/bitrix24/b24jssdk/blob/main/packages/jssdk/README-AI.md Loads the SDK globally from a CDN and initializes it within an iframe app. This approach is useful when bundling ESM is not possible. Ensure the DOM is fully loaded before executing the script. ```html ``` -------------------------------- ### Get Booking by ID Source: https://github.com/bitrix24/b24jssdk/blob/main/docs/llms-full.txt Retrieves a specific booking by its unique identifier. ```APIDOC ## GET /v1/bookings/:id ### Description Retrieves a specific booking by its unique identifier. ### Method GET ### Endpoint /v1/bookings/:id #### Path Parameters - **id** (number) - Required - The ID of the booking to retrieve. ``` -------------------------------- ### Create Fashion Products with VAT Source: https://github.com/bitrix24/b24jssdk/blob/main/playgrounds/cli/README.md Generates a specified number of fashion products with VAT included in their prices and a custom currency. ```bash pnpm run dev make products-sku --total=20 --theme=fashion --vatIncluded=Y --currency=EUR ``` -------------------------------- ### Initialize and Use B24 Helper with Pull Client Source: https://github.com/bitrix24/b24jssdk/blob/main/packages/jssdk/README-AI.md Demonstrates the initialization pattern for the B24 helper, including preloading various data types and enabling the Pull client for real-time updates. Accesses helper data and managers after initialization. ```typescript import { useB24Helper, LoadDataType, type TypePullMessage } from '@bitrix24/b24jssdk' const { initB24Helper, destroyB24Helper, getB24Helper, usePullClient, useSubscribePullClient, startPullClient } = useB24Helper() const $b24 = await initializeB24Frame() await initB24Helper($b24, [ LoadDataType.Profile, LoadDataType.App, LoadDataType.Currency, LoadDataType.AppOptions, LoadDataType.UserOptions, ]) // Enable Pull usePullClient('prefix') // optionally pass userId useSubscribePullClient((m: TypePullMessage) => { // handle Pull messages }, 'application') startPullClient() // Access helper data and extra managers const helper = getB24Helper() const userId = helper.profileInfo.data.id const uniq = $b24.auth.getUniq('prefix') // unique per member ``` -------------------------------- ### Create Order Source: https://github.com/bitrix24/b24jssdk/blob/main/docs/llms-full.txt Create a new order with required fields like 'accountNumber', 'price', and 'currency'. ```bash curl -X POST '/v1/orders' \ -H 'X-Api-Key: YOUR_KEY' \ -H 'Content-Type: application/json' \ -d '{"accountNumber":"value","price":1,"currency":"value"}' ```