@2bad/bitrix 3.0.0-beta.0 → 3.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.
Files changed (71) hide show
  1. package/README.md +93 -186
  2. package/build/bin.d.ts +1 -0
  3. package/build/bin.js +160 -0
  4. package/build/client-Bk76ySik.js +769 -0
  5. package/build/index.d.ts +2881 -0
  6. package/build/index.js +1 -0
  7. package/package.json +43 -64
  8. package/build/bitrix.d.ts +0 -65
  9. package/build/bitrix.js +0 -55
  10. package/build/client/hooks/addAccessToken.d.ts +0 -6
  11. package/build/client/hooks/addAccessToken.js +0 -9
  12. package/build/client/index.d.ts +0 -15
  13. package/build/client/index.js +0 -53
  14. package/build/client/methods/batch.d.ts +0 -40
  15. package/build/client/methods/batch.js +0 -75
  16. package/build/client/methods/call.d.ts +0 -17
  17. package/build/client/methods/call.js +0 -27
  18. package/build/client/methods/list.d.ts +0 -30
  19. package/build/client/methods/list.js +0 -58
  20. package/build/commands.d.ts +0 -10
  21. package/build/commands.js +0 -1
  22. package/build/methods.d.ts +0 -92
  23. package/build/methods.js +0 -38
  24. package/build/payloads.d.ts +0 -40
  25. package/build/payloads.js +0 -1
  26. package/build/services/common.d.ts +0 -22
  27. package/build/services/common.js +0 -2
  28. package/build/services/companies/entities.d.ts +0 -54
  29. package/build/services/companies/entities.js +0 -1
  30. package/build/services/companies/index.d.ts +0 -15
  31. package/build/services/companies/index.js +0 -17
  32. package/build/services/companies/methods.d.ts +0 -44
  33. package/build/services/companies/methods.js +0 -1
  34. package/build/services/contacts/entities.d.ts +0 -45
  35. package/build/services/contacts/entities.js +0 -1
  36. package/build/services/contacts/index.d.ts +0 -15
  37. package/build/services/contacts/index.js +0 -17
  38. package/build/services/contacts/methods.d.ts +0 -44
  39. package/build/services/contacts/methods.js +0 -1
  40. package/build/services/currencies/entities.d.ts +0 -15
  41. package/build/services/currencies/entities.js +0 -1
  42. package/build/services/deals/entities.d.ts +0 -43
  43. package/build/services/deals/entities.js +0 -1
  44. package/build/services/deals/index.d.ts +0 -15
  45. package/build/services/deals/index.js +0 -17
  46. package/build/services/deals/methods.d.ts +0 -44
  47. package/build/services/deals/methods.js +0 -1
  48. package/build/services/leads/entities.d.ts +0 -49
  49. package/build/services/leads/entities.js +0 -1
  50. package/build/services/leads/index.d.ts +0 -15
  51. package/build/services/leads/index.js +0 -17
  52. package/build/services/leads/methods.d.ts +0 -44
  53. package/build/services/leads/methods.js +0 -1
  54. package/build/services/statuses/entities.d.ts +0 -16
  55. package/build/services/statuses/entities.js +0 -1
  56. package/build/services/statuses/index.d.ts +0 -14
  57. package/build/services/statuses/index.js +0 -19
  58. package/build/services/statuses/methods.d.ts +0 -51
  59. package/build/services/statuses/methods.js +0 -1
  60. package/build/services/users/entities.d.ts +0 -40
  61. package/build/services/users/entities.js +0 -1
  62. package/build/services/users/index.d.ts +0 -9
  63. package/build/services/users/index.js +0 -7
  64. package/build/services/users/methods.d.ts +0 -17
  65. package/build/services/users/methods.js +0 -1
  66. package/build/utils/Diff.d.ts +0 -1
  67. package/build/utils/Diff.js +0 -7
  68. package/build/utils/ExtractValue.d.ts +0 -6
  69. package/build/utils/ExtractValue.js +0 -5
  70. package/build/utils/isArray.d.ts +0 -2
  71. package/build/utils/isArray.js +0 -2
package/build/index.js ADDED
@@ -0,0 +1 @@
1
+ export { n as BitrixError, t as createClient } from "./client-Bk76ySik.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@2bad/bitrix",
3
- "version": "3.0.0-beta.0",
3
+ "version": "3.0.0",
4
4
  "description": "Bitrix24 REST API client that doesn't suck",
5
5
  "keywords": [
6
6
  "api",
@@ -19,79 +19,58 @@
19
19
  },
20
20
  "repository": {
21
21
  "type": "git",
22
- "url": "https://github.com/2BAD/bitrix.git"
22
+ "url": "git+https://github.com/2BAD/bitrix.git"
23
23
  },
24
24
  "license": "MIT",
25
25
  "author": "2BAD (https://github.com/2BAD)",
26
26
  "type": "module",
27
- "exports": "./build/bitrix.js",
28
- "typings": "./build/bitrix.d.ts",
27
+ "exports": {
28
+ ".": {
29
+ "import": {
30
+ "types": "./build/index.d.ts",
31
+ "default": "./build/index.js"
32
+ }
33
+ }
34
+ },
35
+ "bin": {
36
+ "bitrix-types": "./build/bin.js"
37
+ },
29
38
  "files": [
30
39
  "build"
31
40
  ],
32
- "scripts": {
33
- "prebuild": "rimraf build",
34
- "build": "run-p build:*",
35
- "postbuild": "run-s fix:alias",
36
- "build:swc": "swc ./source -d ./build --strip-leading-paths",
37
- "build:types": "tsc --project tsconfig.build.json",
38
- "check": "run-p check:*",
39
- "check:code": "eslint . --ext .ts --report-unused-disable-directives --max-warnings 0",
40
- "fix:alias": "tsc-alias -p tsconfig.build.json",
41
- "fix:code": "run-s 'check:code -- --fix'",
42
- "prepublishOnly": "run-s build",
43
- "preversion": "run-s check test:unit build",
44
- "test": "vitest run",
45
- "test:integration": "vitest run integration --coverage",
46
- "test:unit": "vitest run unit --coverage"
47
- },
48
- "prettier": {
49
- "printWidth": 100,
50
- "semi": false,
51
- "singleQuote": true,
52
- "trailingComma": "none"
53
- },
54
- "dependencies": {
55
- "@types/lodash.chunk": "4.2.9",
56
- "@types/lodash.frompairs": "4.0.9",
57
- "@types/lodash.range": "3.2.9",
58
- "@types/qs": "6.9.15",
59
- "got": "14.4.1",
60
- "lodash.chunk": "4.2.0",
61
- "lodash.frompairs": "4.0.1",
62
- "lodash.range": "3.2.0",
63
- "p-queue": "8.0.1",
64
- "qs": "6.12.3"
41
+ "volta": {
42
+ "node": "26.13.0",
43
+ "pnpm": "12.16.1"
65
44
  },
66
45
  "devDependencies": {
67
- "@2bad/tsconfig": "3.0.1",
68
- "@swc/cli": "0.4.0",
69
- "@swc/core": "1.7.0",
70
- "@types/node": "20.14.11",
71
- "@typescript-eslint/eslint-plugin": "4.22.0",
72
- "@vitest/coverage-v8": "2.0.3",
73
- "codecov": "3.8.2",
74
- "dotenv": "16.4.5",
75
- "eslint": "7.25.0",
76
- "eslint-config-standard-with-typescript": "20.0.0",
77
- "eslint-plugin-import": "2.22.1",
78
- "eslint-plugin-node": "11.1.0",
79
- "eslint-plugin-promise": "4.2.1",
80
- "eslint-plugin-standard": "4.1.0",
81
- "nock": "13.5.4",
82
- "npm-run-all": "4.1.5",
83
- "rimraf": "6.0.1",
84
- "tsc-alias": "1.8.10",
85
- "typescript": "5.5.3",
86
- "vite-tsconfig-paths": "4.3.2",
87
- "vitest": "2.0.3"
46
+ "@2bad/axiom": "2.1.0",
47
+ "@2bad/tsconfig": "4.0.0",
48
+ "@arethetypeswrong/cli": "0.18.5",
49
+ "@types/node": "26.6.6",
50
+ "@vitest/coverage-v8": "5.0.5",
51
+ "npm-run-all2": "9.0.4",
52
+ "oxfmt": "0.75.0",
53
+ "oxlint": "1.90.0",
54
+ "publint": "0.3.25",
55
+ "tsdown": "0.23.4",
56
+ "typescript": "7.0.2",
57
+ "vitest": "5.0.5"
88
58
  },
89
- "packageManager": "npm@10.8.2",
90
59
  "engines": {
91
- "node": ">=20"
60
+ "node": ">=26"
92
61
  },
93
- "volta": {
94
- "node": "22.5.0",
95
- "npm": "10.8.2"
62
+ "scripts": {
63
+ "build": "tsdown",
64
+ "check": "run-p check:**",
65
+ "check:code": "oxlint ./source",
66
+ "check:format": "oxfmt --check ./source",
67
+ "check:types": "tsc --noEmit",
68
+ "fix": "run-p fix:**",
69
+ "fix:code": "oxlint --fix ./source",
70
+ "fix:format": "oxfmt ./source",
71
+ "preversion": "run-s check test:unit build",
72
+ "test": "vitest run",
73
+ "test:integration": "vitest run integration --coverage",
74
+ "test:unit": "vitest run unit --coverage"
96
75
  }
97
- }
76
+ }
package/build/bitrix.d.ts DELETED
@@ -1,65 +0,0 @@
1
- import { ExtendOptions } from 'got';
2
- /**
3
- * Construct a Bitrix client with generic methods
4
- * @param restURI REST endpoint, like a `https://hello.bitrix24.ua/rest` or an inbound webhook endpoint,
5
- * like a `https://hello.bitrix24.ua/rest/1/WEBHOOK_TOKEN`.
6
- * @param accessToken Bitrix application Access Token. Do not specify in case inbound webhook endpoint used.
7
- * @param clientOptions an object that will overwrite underlying configuration for HTTP client,
8
- * see `https://github.com/sindresorhus/got/blob/main/documentation/2-options.md`.
9
- */
10
- export declare const Bitrix: (restURI: string, accessToken?: string, clientOptions?: ExtendOptions) => {
11
- call: import("./client/methods/call.ts").Call;
12
- batch: import("./client/methods/batch.ts").Batch;
13
- list: import("./client/methods/list.ts").List;
14
- companies: {
15
- fields: () => Promise<import("./payloads.ts").GetPayload<import("./services/common.js").Fields>>;
16
- create: <D extends import("./methods.js").MethodParams<import("./methods.js").Method.CRM_COMPANY_ADD>>(fields: D["fields"], params?: D["params"]) => Promise<import("./payloads.ts").GetPayload<number>>;
17
- get: (id: string) => Promise<import("./payloads.ts").GetPayload<import("./services/companies/entities.js").Company>>;
18
- list: (params?: import("./methods.js").MethodParams<import("./methods.js").Method.CRM_COMPANY_LIST>) => Promise<import("./payloads.ts").ListPayload<import("./services/companies/entities.js").Company>>;
19
- update: <D extends import("./methods.js").MethodParams<import("./methods.js").Method.CRM_COMPANY_UPDATE>>(id: string, fields: D["fields"], params?: D["params"]) => Promise<import("./payloads.ts").GetPayload<boolean>>;
20
- };
21
- contacts: {
22
- fields: () => Promise<import("./payloads.ts").GetPayload<import("./services/common.js").Fields>>;
23
- create: <D extends import("./methods.js").MethodParams<import("./methods.js").Method.CRM_CONTACT_ADD>>(fields: D["fields"], params?: D["params"]) => Promise<import("./payloads.ts").GetPayload<number>>;
24
- get: (id: string) => Promise<import("./payloads.ts").GetPayload<import("./services/contacts/entities.js").Contact>>;
25
- list: (params?: import("./methods.js").MethodParams<import("./methods.js").Method.CRM_CONTACT_LIST>) => Promise<import("./payloads.ts").ListPayload<import("./services/contacts/entities.js").Contact>>;
26
- update: <D extends import("./methods.js").MethodParams<import("./methods.js").Method.CRM_CONTACT_UPDATE>>(id: string, fields: D["fields"], params?: D["params"]) => Promise<import("./payloads.ts").GetPayload<boolean>>;
27
- };
28
- deals: {
29
- fields: () => Promise<import("./payloads.ts").GetPayload<import("./services/common.js").Fields>>;
30
- create: <D extends import("./methods.js").MethodParams<import("./methods.js").Method.CRM_DEAL_ADD>>(fields: D["fields"], params?: D["params"]) => Promise<import("./payloads.ts").GetPayload<number>>;
31
- get: (id: string) => Promise<import("./payloads.ts").GetPayload<import("./services/deals/entities.js").Deal>>;
32
- list: (params?: import("./methods.js").MethodParams<import("./methods.js").Method.CRM_DEAL_LIST>) => Promise<import("./payloads.ts").ListPayload<import("./services/deals/entities.js").Deal>>;
33
- update: <D extends import("./methods.js").MethodParams<import("./methods.js").Method.CRM_DEAL_UPDATE>>(id: string, fields: D["fields"], params?: D["params"]) => Promise<import("./payloads.ts").GetPayload<boolean>>;
34
- };
35
- leads: {
36
- fields: () => Promise<import("./payloads.ts").GetPayload<import("./services/common.js").Fields>>;
37
- create: <D extends import("./methods.js").MethodParams<import("./methods.js").Method.CRM_LEAD_ADD>>(fields: D["fields"], params?: D["params"]) => Promise<import("./payloads.ts").GetPayload<number>>;
38
- get: (id: string) => Promise<import("./payloads.ts").GetPayload<import("./services/leads/entities.js").Lead>>;
39
- list: (params?: import("./methods.js").MethodParams<import("./methods.js").Method.CRM_LEAD_LIST>) => Promise<import("./payloads.ts").ListPayload<import("./services/leads/entities.js").Lead>>;
40
- update: <D extends import("./methods.js").MethodParams<import("./methods.js").Method.CRM_LEAD_UPDATE>>(id: string, fields: D["fields"], params?: D["params"]) => Promise<import("./payloads.ts").GetPayload<boolean>>;
41
- };
42
- statuses: {
43
- fields: () => Promise<import("./payloads.ts").GetPayload<import("./services/common.js").Fields>>;
44
- create: (fields: import("./methods.js").MethodParams<import("./methods.js").Method.CRM_STATUS_ADD>["fields"]) => Promise<import("./payloads.ts").GetPayload<number>>;
45
- delete: (id: string | number, params?: import("./methods.js").MethodParams<import("./methods.js").Method.CRM_STATUS_DELETE>["params"]) => Promise<import("./payloads.ts").GetPayload<boolean>>;
46
- get: (id: string | number) => Promise<import("./payloads.ts").GetPayload<import("./services/statuses/entities.js").Status>>;
47
- list: (params?: import("./methods.js").MethodParams<import("./methods.js").Method.CRM_STATUS_LIST>) => Promise<import("./payloads.ts").ListPayload<import("./services/statuses/entities.js").Status>>;
48
- update: (id: string | number, fields: import("./methods.js").MethodParams<import("./methods.js").Method.CRM_STATUS_UPDATE>["fields"]) => Promise<import("./payloads.ts").GetPayload<boolean>>;
49
- };
50
- users: {
51
- fields: () => Promise<import("./payloads.ts").GetPayload<import("./services/users/entities.js").User>>;
52
- get: (id?: string) => Promise<import("./payloads.ts").GetPayload<readonly import("./services/users/entities.js").User[]>>;
53
- };
54
- };
55
- export default Bitrix;
56
- export * from './methods.js';
57
- export * from './commands.js';
58
- export * from './services/common.js';
59
- export * from './services/companies/entities.js';
60
- export * from './services/contacts/entities.js';
61
- export * from './services/currencies/entities.js';
62
- export * from './services/deals/entities.js';
63
- export * from './services/leads/entities.js';
64
- export * from './services/statuses/entities.js';
65
- export * from './services/users/entities.js';
package/build/bitrix.js DELETED
@@ -1,55 +0,0 @@
1
- import Client from "./client/index.js";
2
- import CompaniesService from "./services/companies/index.js";
3
- import ContactsService from "./services/contacts/index.js";
4
- import DealsService from "./services/deals/index.js";
5
- import LeadsService from "./services/leads/index.js";
6
- import StatusesService from "./services/statuses/index.js";
7
- import UsersService from "./services/users/index.js";
8
- /**
9
- * Construct a Bitrix client with generic methods
10
- * @param restURI REST endpoint, like a `https://hello.bitrix24.ua/rest` or an inbound webhook endpoint,
11
- * like a `https://hello.bitrix24.ua/rest/1/WEBHOOK_TOKEN`.
12
- * @param accessToken Bitrix application Access Token. Do not specify in case inbound webhook endpoint used.
13
- * @param clientOptions an object that will overwrite underlying configuration for HTTP client,
14
- * see `https://github.com/sindresorhus/got/blob/main/documentation/2-options.md`.
15
- */ export const Bitrix = (restURI, accessToken, clientOptions)=>{
16
- const { call, batch, list } = Client(restURI, accessToken, clientOptions);
17
- return {
18
- call,
19
- batch,
20
- list,
21
- companies: CompaniesService({
22
- call,
23
- list
24
- }),
25
- contacts: ContactsService({
26
- call,
27
- list
28
- }),
29
- deals: DealsService({
30
- call,
31
- list
32
- }),
33
- leads: LeadsService({
34
- call,
35
- list
36
- }),
37
- statuses: StatusesService({
38
- call
39
- }),
40
- users: UsersService({
41
- call
42
- })
43
- };
44
- };
45
- export default Bitrix;
46
- export * from "./methods.js";
47
- export * from "./commands.js";
48
- export * from "./services/common.js";
49
- export * from "./services/companies/entities.js";
50
- export * from "./services/contacts/entities.js";
51
- export * from "./services/currencies/entities.js";
52
- export * from "./services/deals/entities.js";
53
- export * from "./services/leads/entities.js";
54
- export * from "./services/statuses/entities.js";
55
- export * from "./services/users/entities.js";
@@ -1,6 +0,0 @@
1
- import { BeforeRequestHook } from 'got';
2
- /**
3
- * Got can't merge `query` option with other queries if they are string. But that hook can.
4
- */
5
- declare const _default: (accessToken?: string) => BeforeRequestHook;
6
- export default _default;
@@ -1,9 +0,0 @@
1
- /**
2
- * Got can't merge `query` option with other queries if they are string. But that hook can.
3
- */ export default ((accessToken)=>(options)=>{
4
- if (!accessToken) return;
5
- if (!options.url) return;
6
- if (typeof options.url.search === 'string') {
7
- options.url.search = `${options.url.search}${options.url.search ? '&' : '?'}access_token=${accessToken}`;
8
- }
9
- });
@@ -1,15 +0,0 @@
1
- import { ExtendOptions } from 'got';
2
- /**
3
- * Construct a Bitrix client with generic methods
4
- * @param restURI REST endpoint, like a `https://hello.bitrix24.ru/rest` or an inbound webhook endpoint,
5
- * like a `https://hello.bitrix24.ru/rest/1/WEBHOOK_TOKEN`.
6
- * @param accessToken Bitrix application Access Token. Do not specify in case inbound webhook endpoint used.
7
- * @param options an object that will overwrite underlying configuration for HTTP client,
8
- * see `https://github.com/sindresorhus/got/blob/main/documentation/2-options.md`.
9
- */
10
- declare const _default: (restURI: string, accessToken?: string, options?: ExtendOptions) => {
11
- call: import("./methods/call.js").Call;
12
- batch: import("./methods/batch.js").Batch;
13
- list: import("./methods/list.js").List;
14
- };
15
- export default _default;
@@ -1,53 +0,0 @@
1
- import got from "got";
2
- import Queue from "p-queue";
3
- import addAccessToken from "./hooks/addAccessToken.js";
4
- import Batch from "./methods/batch.js";
5
- import Call from "./methods/call.js";
6
- import List from "./methods/list.js";
7
- const BITRIX_API_RATE_LIMIT = 2;
8
- const BITRIX_API_RATE_INTERVAL = 1000 // 1 second
9
- ;
10
- /**
11
- * Construct a Bitrix client with generic methods
12
- * @param restURI REST endpoint, like a `https://hello.bitrix24.ru/rest` or an inbound webhook endpoint,
13
- * like a `https://hello.bitrix24.ru/rest/1/WEBHOOK_TOKEN`.
14
- * @param accessToken Bitrix application Access Token. Do not specify in case inbound webhook endpoint used.
15
- * @param options an object that will overwrite underlying configuration for HTTP client,
16
- * see `https://github.com/sindresorhus/got/blob/main/documentation/2-options.md`.
17
- */ export default ((restURI, accessToken, options)=>{
18
- const client = got.extend({
19
- prefixUrl: restURI,
20
- headers: {
21
- 'user-agent': '@2bad/bitrix'
22
- },
23
- responseType: 'json',
24
- hooks: {
25
- beforeRequest: [
26
- addAccessToken(accessToken)
27
- ]
28
- },
29
- ...options ?? {}
30
- });
31
- const queue = new Queue({
32
- intervalCap: BITRIX_API_RATE_LIMIT,
33
- interval: BITRIX_API_RATE_INTERVAL
34
- });
35
- const queuedGet = (...args)=>queue.add(()=>client.get(...args));
36
- // @ts-expect-error @todo remove after issue is resolved (https://github.com/sindresorhus/got/issues/954)
37
- const call = Call({
38
- get: queuedGet
39
- });
40
- // @ts-expect-error @todo remove after issue is resolved (https://github.com/sindresorhus/got/issues/954)
41
- const batch = Batch({
42
- get: queuedGet
43
- });
44
- const list = List({
45
- call,
46
- batch
47
- });
48
- return {
49
- call,
50
- batch,
51
- list
52
- };
53
- });
@@ -1,40 +0,0 @@
1
- import got from 'got';
2
- import { Commands } from '../../commands.js';
3
- import { Method, MethodPayloadType } from '../../methods.js';
4
- import { BatchPayload } from '../../payloads.js';
5
- export declare const MAX_COMMANDS_PER_BATCH = 50;
6
- /**
7
- * Split any number of commands into the chunks with max commands per batch in each chunk
8
- */
9
- export declare const chunkCommands: <C extends Commands>(commands: C, size?: number) => readonly C[];
10
- /**
11
- * Prepares list of commands to be used in requests to the Bitrix
12
- * @note We could avoid that function... if only Bitrix API would support posting of the batch commands as
13
- * plain objects, like it does with other methods. Instead, it should be a dict or array of string queries
14
- */
15
- export declare const prepareCommandsQueries: <C extends Commands, R = { [K in keyof C]: string; }>(commands: C) => R;
16
- /**
17
- * Merges list of batch responses into a single batch
18
- * @todo Generics inference is complicated here and might be not super accurate
19
- */
20
- export declare const mergeBatchPayloads: <B extends BatchPayload<unknown>, P = B extends BatchPayload<infer U> ? U : never>(payloads: readonly B[]) => BatchPayload<P>;
21
- export type CommandsPayloads<C extends Commands, CM = {
22
- [K in keyof C]: C[K] extends {
23
- readonly method: infer M;
24
- } ? M : never;
25
- }> = {
26
- [K in keyof CM]: MethodPayloadType<CM[K] extends Method ? CM[K] : never>;
27
- };
28
- export type Batch = <C extends Commands, P = CommandsPayloads<C>>(commands: C, commandsPerRequest?: number) => Promise<BatchPayload<P>>;
29
- type Dependencies = {
30
- readonly get: typeof got.get;
31
- };
32
- /**
33
- * Dispatches a batch request with specified commands. Will fill figure out payload type based on the Methods.
34
- * Supports unlimited number of commands. If they do exceed max amount of commands per batch, will dispatch
35
- * multiple request and merge result into single batch payload
36
- * @todo For now due to issues with types it won't check `params` of command, so any Method can be used
37
- * with any (even wrong) params
38
- */
39
- declare const _default: ({ get }: Dependencies) => Batch;
40
- export default _default;
@@ -1,75 +0,0 @@
1
- import chunk from "lodash.chunk";
2
- import fromPairs from "lodash.frompairs";
3
- import { stringify as toQuery } from "qs";
4
- import { Method } from "../../methods.js";
5
- import isArray from "../../utils/isArray.js";
6
- import { handlePayload } from "./call.js";
7
- export const MAX_COMMANDS_PER_BATCH = 50;
8
- /**
9
- * Split any number of commands into the chunks with max commands per batch in each chunk
10
- */ export const chunkCommands = (commands, size = MAX_COMMANDS_PER_BATCH)=>{
11
- const commandsIsArray = isArray(commands);
12
- const chunks = chunk(Object.entries(commands), size);
13
- // @todo Generated return type isn't very accurate since it says that it will make array of <C>, while
14
- // in fact <C> will be distributed among chunks. That gives wrong hints with named commands and arrays as const.
15
- return chunks.map((c)=>commandsIsArray ? c.map(([_key, command])=>command) : fromPairs(c));
16
- };
17
- /**
18
- * Prepares list of commands to be used in requests to the Bitrix
19
- * @note We could avoid that function... if only Bitrix API would support posting of the batch commands as
20
- * plain objects, like it does with other methods. Instead, it should be a dict or array of string queries
21
- */ export const prepareCommandsQueries = (commands)=>Object.entries(commands).reduce((calls, [name, { method, params }])=>{
22
- const stringifiedParams = params ? `?${toQuery(params)}` : '';
23
- return {
24
- ...calls,
25
- [`cmd[${name}]`]: `${method}${stringifiedParams}`
26
- };
27
- // eslint-disable-next-line @typescript-eslint/prefer-reduce-type-parameter
28
- }, {});
29
- /**
30
- * Merges list of batch responses into a single batch
31
- * @todo Generics inference is complicated here and might be not super accurate
32
- */ export const mergeBatchPayloads = (payloads)=>{
33
- const merge = (a, b)=>isArray(a) && isArray(b) ? [
34
- ...a,
35
- ...b
36
- ] : {
37
- ...a,
38
- ...b
39
- };
40
- return payloads.reduce((merged, payload)=>({
41
- result: {
42
- result: merge(merged.result.result || [], payload.result.result),
43
- result_error: merge(merged.result.result_error || [], payload.result.result_error),
44
- result_next: merge(merged.result.result_next || [], payload.result.result_next),
45
- result_time: merge(merged.result.result_time || [], payload.result.result_time),
46
- result_total: merge(merged.result.result_total || [], payload.result.result_total)
47
- },
48
- time: {
49
- ...merged.time,
50
- ...payload.time
51
- }
52
- }), {
53
- result: {},
54
- time: {}
55
- });
56
- };
57
- /**
58
- * Dispatches a batch request with specified commands. Will fill figure out payload type based on the Methods.
59
- * Supports unlimited number of commands. If they do exceed max amount of commands per batch, will dispatch
60
- * multiple request and merge result into single batch payload
61
- * @todo For now due to issues with types it won't check `params` of command, so any Method can be used
62
- * with any (even wrong) params
63
- */ export default (({ get })=>{
64
- const batch = async (commands, commandsPerRequest = MAX_COMMANDS_PER_BATCH)=>{
65
- const call = (c)=>get(Method.BATCH, {
66
- searchParams: prepareCommandsQueries(c)
67
- }).then(({ body })=>body);
68
- const calls = chunkCommands(commands, commandsPerRequest).map(call);
69
- return await Promise.all(calls).then((chunkedPayloads)=>{
70
- const payloads = mergeBatchPayloads(chunkedPayloads);
71
- return handlePayload(payloads);
72
- });
73
- };
74
- return batch;
75
- });
@@ -1,17 +0,0 @@
1
- import got from 'got';
2
- import { Method, MethodParams, MethodPayload } from '../../methods.js';
3
- import { Payload } from '../../payloads.js';
4
- /**
5
- * Checks wether payload have any errors and if it does — throws them
6
- * Bitrix payload types do not provide discriminators, so we're forced to type cast them
7
- */
8
- export declare const handlePayload: <P extends Payload<unknown>>(payload: P) => P;
9
- export type Call = <M extends Method>(method: M, params: MethodParams<M>) => Promise<MethodPayload<M>>;
10
- type Dependencies = {
11
- readonly get: typeof got.get;
12
- };
13
- /**
14
- * Dispatches a request with specified method and params. Will fill figure out payload type based on the Method
15
- */
16
- declare const _default: ({ get }: Dependencies) => Call;
17
- export default _default;
@@ -1,27 +0,0 @@
1
- import { stringify as toQuery } from "qs";
2
- import isArray from "../../utils/isArray.js";
3
- /**
4
- * Checks wether payload have any errors and if it does — throws them
5
- * Bitrix payload types do not provide discriminators, so we're forced to type cast them
6
- */ export const handlePayload = (payload)=>{
7
- if (payload.error) {
8
- throw new Error(`[call] failed to get the resource: ${payload.error ?? ''}.`);
9
- }
10
- if (payload.result && payload.result.result_error) {
11
- const resultErrors = payload.result.result_error;
12
- const errors = isArray(resultErrors) ? resultErrors : Object.values(resultErrors);
13
- if (errors.length > 0) {
14
- // @todo We can give better formatting to display errored commands. But it's not important for now
15
- throw new Error(`[batch] failed to process. Received errors in ${errors.length} commands:\n${errors.join('\n')}`);
16
- }
17
- }
18
- return payload;
19
- };
20
- /**
21
- * Dispatches a request with specified method and params. Will fill figure out payload type based on the Method
22
- */ export default (({ get })=>{
23
- const call = (method, params)=>get(method, {
24
- searchParams: toQuery(params)
25
- }).then(({ body })=>handlePayload(body));
26
- return call;
27
- });
@@ -1,30 +0,0 @@
1
- import { Command } from '../../commands.js';
2
- import { ListableMethod, MethodParams, MethodPayloadType } from '../../methods.js';
3
- import { BatchPayload, ListPayload } from '../../payloads.js';
4
- import { Batch } from './batch.js';
5
- import { Call } from './call.js';
6
- /**
7
- * Generates required amount of commands to process specified amount of entries
8
- */
9
- export declare const fillWithCommands: <C extends Command>({ method, params }: C, start: number, toProcess: number, entriesPerCommand: number) => ReadonlyArray<{
10
- readonly method: C["method"];
11
- readonly params?: C["params"];
12
- }>;
13
- /**
14
- * Get the highest value from object or an array if there's any
15
- */
16
- export declare const highest: (input: ReadonlyArray<number | undefined> | Record<string, number | undefined>) => number | undefined;
17
- /**
18
- * Converts batch payload to a list payload
19
- */
20
- export declare const batchToListPayload: <P>(payload: BatchPayload<Record<string, P> | readonly P[]>) => ListPayload<P>;
21
- type Dependencies = {
22
- readonly call: Call;
23
- readonly batch: Batch;
24
- };
25
- export type List = <M extends ListableMethod>(method: M, params: MethodParams<M>) => Promise<ListPayload<MethodPayloadType<M>>>;
26
- /**
27
- * Gets all entries by dispatching required amount of requests. Will fill figure out payload type based on the Method.
28
- */
29
- declare const _default: ({ call, batch }: Dependencies) => List;
30
- export default _default;
@@ -1,58 +0,0 @@
1
- import range from "lodash.range";
2
- const MAX_ENTRIES_PER_COMMAND = 50;
3
- /**
4
- * Generates required amount of commands to process specified amount of entries
5
- */ export const fillWithCommands = ({ method, params }, start, toProcess, entriesPerCommand)=>{
6
- const requiresCommands = Math.ceil((toProcess - start) / entriesPerCommand);
7
- return range(0, requiresCommands).map((i)=>({
8
- method,
9
- params: {
10
- ...params,
11
- start: start + entriesPerCommand * i
12
- }
13
- }));
14
- };
15
- /**
16
- * Get the highest value from object or an array if there's any
17
- */ export const highest = (input)=>Object.values(input).reduce((a, b)=>a !== undefined && b !== undefined ? a > b ? a : b : a !== undefined && b === undefined ? a : a === undefined && b !== undefined ? b : undefined, undefined);
18
- /**
19
- * Converts batch payload to a list payload
20
- */ export const batchToListPayload = (payload)=>{
21
- // eslint-disable-next-line @typescript-eslint/naming-convention
22
- const { result: { result, result_total, result_error, result_next }, time } = payload;
23
- const flattenResult = Object.entries(result).reduce(// @ts-expect-error ignore this for now
24
- (flatten, [_key, r])=>!r ? flatten : [
25
- ...flatten,
26
- ...r
27
- ], []);
28
- return {
29
- error: Object.values(result_error).join('\n'),
30
- next: highest(result_next),
31
- result: flattenResult,
32
- // @todo Not accurate, we do not care
33
- time,
34
- total: highest(result_total) ?? 0
35
- };
36
- };
37
- /**
38
- * Gets all entries by dispatching required amount of requests. Will fill figure out payload type based on the Method.
39
- */ export default (({ call, batch })=>{
40
- const list = async (method, params)=>{
41
- const start = params.start ?? 0;
42
- const listAll = async ()=>{
43
- const batchCommands = fillWithCommands({
44
- method,
45
- params
46
- }, start, firstCall.total, MAX_ENTRIES_PER_COMMAND);
47
- const payload = await batch(batchCommands);
48
- // @ts-expect-error ignore this for now
49
- return batchToListPayload(payload);
50
- };
51
- const firstCall = await call(method, {
52
- ...params,
53
- start
54
- });
55
- return !firstCall.next ? firstCall : await listAll();
56
- };
57
- return list;
58
- });
@@ -1,10 +0,0 @@
1
- import { Method } from './methods.js';
2
- export type Command = {
3
- readonly method: Method;
4
- readonly params?: Record<string, any>;
5
- };
6
- export type Commands = {
7
- readonly [key: string]: Command;
8
- } | {
9
- readonly [index: number]: Command;
10
- };
package/build/commands.js DELETED
@@ -1 +0,0 @@
1
- export { };