@webitel/api-services 26.12.20 → 26.12.22

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 (85) hide show
  1. package/package.json +1 -1
  2. package/src/api/clients/_shared/appUrls.ts +11 -0
  3. package/src/api/clients/chatGateways/__tests__/chatGatewayChannels.spec.ts +84 -0
  4. package/src/api/clients/chatGateways/__tests__/chatGateways.spec.ts +115 -0
  5. package/src/api/clients/chatGateways/chatGatewayChannels.ts +162 -0
  6. package/src/api/clients/chatGateways/chatGateways.ts +66 -25
  7. package/src/api/clients/chatGateways/defaults/chatGatewayProviderDefaults.ts +91 -0
  8. package/src/api/clients/chatGateways/defaults/defaultChatGateway.ts +3 -1
  9. package/src/api/clients/chatGateways/defaults/webChatGateway.ts +8 -5
  10. package/src/api/clients/chatplans/__tests__/chatplans.spec.ts +129 -0
  11. package/src/api/clients/chatplans/chatplans.ts +35 -45
  12. package/src/api/clients/cognitiveProfiles/cognitiveProfiles.ts +8 -32
  13. package/src/api/clients/cognitiveProfiles/defaults/cognitiveProfileDefaults.ts +39 -0
  14. package/src/api/clients/gateways/__tests__/gateways.spec.ts +138 -0
  15. package/src/api/clients/gateways/gateways.ts +60 -52
  16. package/src/api/clients/index.ts +2 -0
  17. package/src/enums/ChatGatewayChannelSetup/ChatGatewayChannelSetup.ts +10 -0
  18. package/src/enums/GatewayIpAclProtocol/GatewayIpAclProtocol.ts +8 -0
  19. package/src/enums/GatewayRegisterState/GatewayRegisterState.ts +17 -0
  20. package/src/enums/StorageType/StorageType.ts +10 -0
  21. package/src/enums/WebchatAlternativeChannel/WebchatAlternativeChannel.ts +15 -0
  22. package/src/enums/index.ts +10 -0
  23. package/src/locale/en/en.ts +8 -0
  24. package/src/locale/es/es.ts +8 -0
  25. package/src/locale/kz/kz.ts +8 -0
  26. package/src/locale/pl/pl.ts +8 -0
  27. package/src/locale/ro/ro.ts +8 -0
  28. package/src/locale/ru/ru.ts +8 -0
  29. package/src/locale/uk/uk.ts +8 -0
  30. package/src/locale/uz/uz.ts +8 -0
  31. package/src/locale/vi/vi.ts +8 -0
  32. package/src/validations/_shared/ip.validations.ts +10 -0
  33. package/src/validations/backendProfile/__tests__/backendProfile.validations.spec.ts +104 -0
  34. package/src/validations/backendProfile/backendProfile.validations.ts +79 -0
  35. package/src/validations/chatGateway/__tests__/chatGateway.validations.spec.ts +189 -0
  36. package/src/validations/chatGateway/chatGateway.validations.ts +452 -0
  37. package/src/validations/chatplan/__tests__/chatplan.validations.spec.ts +43 -0
  38. package/src/validations/chatplan/chatplan.validations.ts +17 -0
  39. package/src/validations/cognitiveProfile/__tests__/cognitiveProfile.validations.spec.ts +83 -0
  40. package/src/validations/cognitiveProfile/cognitiveProfile.validations.ts +74 -0
  41. package/src/validations/device/device.validations.ts +2 -8
  42. package/src/validations/gateway/__tests__/gateway.validations.spec.ts +168 -0
  43. package/src/validations/gateway/gateway.validations.ts +138 -0
  44. package/src/validations/index.ts +5 -0
  45. package/types/.tsbuildinfo +1 -1
  46. package/types/api/clients/_shared/appUrls.d.ts +11 -0
  47. package/types/api/clients/chatGateways/chatGatewayChannels.d.ts +62 -0
  48. package/types/api/clients/chatGateways/chatGateways.d.ts +4 -4
  49. package/types/api/clients/chatGateways/defaults/chatGatewayProviderDefaults.d.ts +21 -0
  50. package/types/api/clients/chatGateways/defaults/defaultChatGateway.d.ts +3 -1
  51. package/types/api/clients/chatGateways/defaults/webChatGateway.d.ts +5 -4
  52. package/types/api/clients/cognitiveProfiles/cognitiveProfiles.d.ts +1 -1
  53. package/types/api/clients/cognitiveProfiles/defaults/cognitiveProfileDefaults.d.ts +13 -0
  54. package/types/api/clients/index.d.ts +2 -0
  55. package/types/enums/ChatGatewayChannelSetup/ChatGatewayChannelSetup.d.ts +8 -0
  56. package/types/enums/GatewayIpAclProtocol/GatewayIpAclProtocol.d.ts +6 -0
  57. package/types/enums/GatewayRegisterState/GatewayRegisterState.d.ts +15 -0
  58. package/types/enums/StorageType/StorageType.d.ts +9 -0
  59. package/types/enums/WebchatAlternativeChannel/WebchatAlternativeChannel.d.ts +13 -0
  60. package/types/enums/index.d.ts +6 -1
  61. package/types/locale/en/en.d.ts +7 -0
  62. package/types/locale/es/es.d.ts +7 -0
  63. package/types/locale/index.d.ts +63 -0
  64. package/types/locale/kz/kz.d.ts +7 -0
  65. package/types/locale/pl/pl.d.ts +7 -0
  66. package/types/locale/ro/ro.d.ts +7 -0
  67. package/types/locale/ru/ru.d.ts +7 -0
  68. package/types/locale/uk/uk.d.ts +7 -0
  69. package/types/locale/uz/uz.d.ts +7 -0
  70. package/types/locale/vi/vi.d.ts +7 -0
  71. package/types/validations/_shared/ip.validations.d.ts +4 -0
  72. package/types/validations/backendProfile/backendProfile.validations.d.ts +24 -0
  73. package/types/validations/chatGateway/chatGateway.validations.d.ts +165 -0
  74. package/types/validations/chatplan/chatplan.validations.d.ts +14 -0
  75. package/types/validations/cognitiveProfile/cognitiveProfile.validations.d.ts +28 -0
  76. package/types/validations/gateway/gateway.validations.d.ts +48 -0
  77. package/types/validations/index.d.ts +5 -0
  78. package/src/api/clients/chatGateways/enums/WebchatAlternativeChannel.enum.ts +0 -12
  79. package/src/api/clients/gateways/defaults/defaultGateway.ts +0 -9
  80. package/src/api/clients/gateways/defaults/registerGateway.ts +0 -12
  81. package/src/api/clients/gateways/defaults/trunkingGateway.ts +0 -16
  82. package/types/api/clients/chatGateways/enums/WebchatAlternativeChannel.enum.d.ts +0 -12
  83. package/types/api/clients/gateways/defaults/defaultGateway.d.ts +0 -8
  84. package/types/api/clients/gateways/defaults/registerGateway.d.ts +0 -13
  85. package/types/api/clients/gateways/defaults/trunkingGateway.d.ts +0 -16
@@ -1,3 +1,4 @@
1
+ export * from './_shared/appUrls';
1
2
  export * from './_shared/generatePermissionsApi';
2
3
  export * from './activeCalls/activeCalls';
3
4
  export * from './agentCalls/agentCalls';
@@ -32,6 +33,7 @@ export * from './cases/cases';
32
33
  export * from './catalog/catalog';
33
34
  export * from './changelogs/changelogs';
34
35
  export * from './chatDialogs/chatDialogs';
36
+ export * from './chatGateways/chatGatewayChannels';
35
37
  export * from './chatGateways/chatGateways';
36
38
  export * from './chatMessagesHistory/chatMessagesHistory';
37
39
  export * from './chatplans/chatplans';
@@ -0,0 +1,10 @@
1
+ /** [Claude] the chat service page where a channel is set up, opened in a popup */
2
+ export const ChatGatewayChannelSetup = {
3
+ Facebook: 'pages=setup',
4
+ Instagram: 'instagram=setup',
5
+ Whatsapp: 'whatsapp=setup',
6
+ TelegramApp: 'auth',
7
+ } as const;
8
+
9
+ export type ChatGatewayChannelSetup =
10
+ (typeof ChatGatewayChannelSetup)[keyof typeof ChatGatewayChannelSetup];
@@ -0,0 +1,8 @@
1
+ export const GatewayIpAclProtocol = {
2
+ Any: 'any',
3
+ Udp: 'udp',
4
+ Tcp: 'tcp',
5
+ } as const;
6
+
7
+ export type GatewayIpAclProtocol =
8
+ (typeof GatewayIpAclProtocol)[keyof typeof GatewayIpAclProtocol];
@@ -0,0 +1,17 @@
1
+ /** [Claude] gateway `rState`: FreeSWITCH sofia registration states, in their numeric order */
2
+ export const GatewayRegisterState = {
3
+ Unregistered: 0,
4
+ Trying: 1,
5
+ Register: 2,
6
+ Registered: 3,
7
+ Unregister: 4,
8
+ Failed: 5,
9
+ FailWait: 6,
10
+ Expired: 7,
11
+ NoReg: 8,
12
+ Down: 9,
13
+ Timeout: 10,
14
+ } as const;
15
+
16
+ export type GatewayRegisterState =
17
+ (typeof GatewayRegisterState)[keyof typeof GatewayRegisterState];
@@ -0,0 +1,10 @@
1
+ /** [Claude] the `type` of a file storage backend ("storage" in the admin ui) */
2
+ export const StorageType = {
3
+ Local: 'local',
4
+ S3: 's3',
5
+ Backblaze: 'backblaze',
6
+ Dropbox: 'dropbox',
7
+ Drive: 'drive',
8
+ } as const;
9
+
10
+ export type StorageType = (typeof StorageType)[keyof typeof StorageType];
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Difference between MessangerType enum and WebchatAlternativeChannel:
3
+ * MessangerType - backend fields naming, provider
4
+ * WebchatAlternativeChannel - front-end only "simple" channel naming
5
+ */
6
+ export const WebchatAlternativeChannel = {
7
+ Viber: 'viber',
8
+ Whatsapp: 'whatsapp',
9
+ Telegram: 'telegram',
10
+ Messenger: 'messenger',
11
+ Email: 'email',
12
+ } as const;
13
+
14
+ export type WebchatAlternativeChannel =
15
+ (typeof WebchatAlternativeChannel)[keyof typeof WebchatAlternativeChannel];
@@ -2,8 +2,11 @@ import { AgentStatus } from './AgentStatus/AgentStatus';
2
2
  import { CallReportingStatus } from './CallReportingStatus/CallReportingStatus';
3
3
  import { ChannelState } from './ChannelState/ChannelState';
4
4
  import { ChannelType } from './ChannelType/ChannelType';
5
+ import { ChatGatewayChannelSetup } from './ChatGatewayChannelSetup/ChatGatewayChannelSetup';
5
6
  import { ChatGatewayProvider } from './ChatGatewayProvider/ChatGatewayPrivider';
6
7
  import { FormatDateMode } from './FormatDateMode/FormatDateMode';
8
+ import { GatewayIpAclProtocol } from './GatewayIpAclProtocol/GatewayIpAclProtocol';
9
+ import { GatewayRegisterState } from './GatewayRegisterState/GatewayRegisterState';
7
10
  import { MemberStopCause } from './MemberStopCause/MemberStopCause';
8
11
  import { QueuePeriod } from './QueuePeriod/QueuePeriod';
9
12
  import {
@@ -14,6 +17,7 @@ import { QueueType, QueueTypeName } from './QueueType/QueueType';
14
17
  import { RelativeDatetimeValue } from './RelativeDatetimeValue/RelativeDatetimeValue';
15
18
  import { ResourceCidType } from './ResourceCidType/ResourceCidType';
16
19
  import { ResourceIgnoreEarlyMedia } from './ResourceIgnoreEarlyMedia/ResourceIgnoreEarlyMedia';
20
+ import { StorageType } from './StorageType/StorageType';
17
21
  import { TimeBaseScore } from './TimeBaseScore/TimeBaseScore';
18
22
  import { TtsGoogleVoiceList } from './TtsGoogleVoice/TtsGoogleVoice';
19
23
  import { TtsMicrosoftVoice } from './TtsMicrosoftVoice/TtsMicrosoftVoice';
@@ -21,6 +25,7 @@ import { TtsTextType } from './TtsTextType/TtsTextType';
21
25
  import { TypesResourceStrategy } from './TypesResourceStrategy/TypesResourceStrategy';
22
26
  import { UrlProtocol } from './UrlProtocol/UrlProtocol';
23
27
  import { UserPresenceStatus } from './UserPresenceStatus/UserPresenceStatus';
28
+ import { WebchatAlternativeChannel } from './WebchatAlternativeChannel/WebchatAlternativeChannel';
24
29
 
25
30
  export type { TtsGoogleVoice } from './TtsGoogleVoice/TtsGoogleVoice';
26
31
  export {
@@ -28,8 +33,11 @@ export {
28
33
  CallReportingStatus,
29
34
  ChannelState,
30
35
  ChannelType,
36
+ ChatGatewayChannelSetup,
31
37
  ChatGatewayProvider,
32
38
  FormatDateMode,
39
+ GatewayIpAclProtocol,
40
+ GatewayRegisterState,
33
41
  MemberStopCause,
34
42
  QueuePeriod,
35
43
  QueueStrategy,
@@ -39,6 +47,7 @@ export {
39
47
  RelativeDatetimeValue,
40
48
  ResourceCidType,
41
49
  ResourceIgnoreEarlyMedia,
50
+ StorageType,
42
51
  TimeBaseScore,
43
52
  TtsGoogleVoiceList,
44
53
  TtsMicrosoftVoice,
@@ -46,4 +55,5 @@ export {
46
55
  TypesResourceStrategy,
47
56
  UrlProtocol,
48
57
  UserPresenceStatus,
58
+ WebchatAlternativeChannel,
49
59
  };
@@ -2,6 +2,14 @@ import type { MessageContext } from 'vue-i18n';
2
2
 
3
3
  export default {
4
4
  backendErrors: {
5
+ sip: {
6
+ gateway: {
7
+ password: {
8
+ invalid:
9
+ "Password contains forbidden characters. Reserved URI symbols, whitespace, and special characters like (! * ' ( ) & $) are not allowed.",
10
+ },
11
+ },
12
+ },
5
13
  ccOutboundResource: {
6
14
  validatePhoneNumber: ({ linked }: MessageContext) =>
7
15
  `File contains invalid numbers. ${linked('validation.phoneNumberSymbolsValidator')}`,
@@ -2,6 +2,14 @@ import type { MessageContext } from 'vue-i18n';
2
2
 
3
3
  export default {
4
4
  backendErrors: {
5
+ sip: {
6
+ gateway: {
7
+ password: {
8
+ invalid:
9
+ "La contraseña contiene caracteres no permitidos. No se permiten símbolos reservados de URI, espacios en blanco ni caracteres especiales como (! * ' ( ) & $).",
10
+ },
11
+ },
12
+ },
5
13
  ccOutboundResource: {
6
14
  validatePhoneNumber: ({ linked }: MessageContext) =>
7
15
  `El archivo contiene números incorrectos. ${linked('validation.phoneNumberSymbolsValidator')}`,
@@ -2,6 +2,14 @@ import type { MessageContext } from 'vue-i18n';
2
2
 
3
3
  export default {
4
4
  backendErrors: {
5
+ sip: {
6
+ gateway: {
7
+ password: {
8
+ invalid:
9
+ "Құпия сөзде рұқсат етілмеген таңбалар бар. Резервтелген URI таңбалары, бос орындар және (! * ' ( ) & $) сияқты арнайы таңбаларды пайдалануға болмайды.",
10
+ },
11
+ },
12
+ },
5
13
  ccOutboundResource: {
6
14
  validatePhoneNumber: ({ linked }: MessageContext) =>
7
15
  `Файлда қате нөмірлер бар. ${linked('validation.phoneNumberSymbolsValidator')}`,
@@ -2,6 +2,14 @@ import type { MessageContext } from 'vue-i18n';
2
2
 
3
3
  export default {
4
4
  backendErrors: {
5
+ sip: {
6
+ gateway: {
7
+ password: {
8
+ invalid:
9
+ "Hasło zawiera niedozwolone znaki. Zarezerwowane symbole URI, spacje oraz znaki specjalne takie jak (! * ' ( ) & $) są niedozwolone.",
10
+ },
11
+ },
12
+ },
5
13
  ccOutboundResource: {
6
14
  validatePhoneNumber: ({ linked }: MessageContext) =>
7
15
  `Plik zawiera nieprawidłowe numery. ${linked('validation.phoneNumberSymbolsValidator')}`,
@@ -2,6 +2,14 @@ import type { MessageContext } from 'vue-i18n';
2
2
 
3
3
  export default {
4
4
  backendErrors: {
5
+ sip: {
6
+ gateway: {
7
+ password: {
8
+ invalid:
9
+ "Parola conține caractere interzise. Simbolurile URI rezervate, spațiile și caracterele speciale precum (! * ' ( ) & $) nu sunt permise.",
10
+ },
11
+ },
12
+ },
5
13
  ccOutboundResource: {
6
14
  validatePhoneNumber: ({ linked }: MessageContext) =>
7
15
  `Fișierul conține numere incorecte. ${linked('validation.phoneNumberSymbolsValidator')}`,
@@ -2,6 +2,14 @@ import type { MessageContext } from 'vue-i18n';
2
2
 
3
3
  export default {
4
4
  backendErrors: {
5
+ sip: {
6
+ gateway: {
7
+ password: {
8
+ invalid:
9
+ "Пароль содержит запрещенные символы. Зарезервированные символы URI, пробелы, спецсимволы !*'()&$ не поддерживаются.",
10
+ },
11
+ },
12
+ },
5
13
  ccOutboundResource: {
6
14
  validatePhoneNumber: ({ linked }: MessageContext) =>
7
15
  `Файл содержит некорректные номера. ${linked('validation.phoneNumberSymbolsValidator')}`,
@@ -2,6 +2,14 @@ import type { MessageContext } from 'vue-i18n';
2
2
 
3
3
  export default {
4
4
  backendErrors: {
5
+ sip: {
6
+ gateway: {
7
+ password: {
8
+ invalid:
9
+ "Пароль містить заборонені символи. Зарезервовані символи URI, пробіли, спецсимволи !*'()&$ не підтримуються.",
10
+ },
11
+ },
12
+ },
5
13
  ccOutboundResource: {
6
14
  validatePhoneNumber: ({ linked }: MessageContext) =>
7
15
  `Файл містить некоректні номери. ${linked('validation.phoneNumberSymbolsValidator')}`,
@@ -2,6 +2,14 @@ import type { MessageContext } from 'vue-i18n';
2
2
 
3
3
  export default {
4
4
  backendErrors: {
5
+ sip: {
6
+ gateway: {
7
+ password: {
8
+ invalid:
9
+ "Parolda ruxsat etilmagan belgilar mavjud. Rezervlangan URI belgilari, bo'sh joylar va (! * ' ( ) & $) kabi maxsus belgilardan foydalanish mumkin emas.",
10
+ },
11
+ },
12
+ },
5
13
  ccOutboundResource: {
6
14
  validatePhoneNumber: ({ linked }: MessageContext) =>
7
15
  `Faylda noto'g'ri raqamlar mavjud. ${linked('validation.phoneNumberSymbolsValidator')}`,
@@ -2,6 +2,14 @@ import type { MessageContext } from 'vue-i18n';
2
2
 
3
3
  export default {
4
4
  backendErrors: {
5
+ sip: {
6
+ gateway: {
7
+ password: {
8
+ invalid:
9
+ "Mật khẩu chứa ký tự không hợp lệ. Không được phép dùng các ký hiệu URI dành riêng, khoảng trắng và ký tự đặc biệt như (! * ' ( ) & $).",
10
+ },
11
+ },
12
+ },
5
13
  ccOutboundResource: {
6
14
  validatePhoneNumber: ({ linked }: MessageContext) =>
7
15
  `Tệp chứa số không hợp lệ. ${linked('validation.phoneNumberSymbolsValidator')}`,
@@ -0,0 +1,10 @@
1
+ /** [Claude] IPv4 without anchors, so it can be embedded into bigger patterns (e.g. a SIP host) */
2
+ export const ipv4Pattern =
3
+ '(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])';
4
+
5
+ const ipv4Regex = new RegExp(`^${ipv4Pattern}$`);
6
+
7
+ /** [Claude] format rule only: an empty value passes; loopback and 0.0.0.0 are rejected */
8
+ export const isIp = (value?: string) =>
9
+ !value ||
10
+ (value !== '127.0.0.1' && value !== '0.0.0.0' && ipv4Regex.test(value));
@@ -0,0 +1,104 @@
1
+ import { getDefaultsFromZodSchema } from '@webitel/api-services/gen/utils';
2
+ import { describe, expect, it } from 'vitest';
3
+
4
+ import { backendProfileSchema } from '../backendProfile.validations';
5
+
6
+ const issuePaths = (
7
+ result: ReturnType<typeof backendProfileSchema.safeParse>,
8
+ ) => result.error?.issues.map(({ path }) => path.join('.')) ?? [];
9
+
10
+ const filledS3 = {
11
+ name: 'storage',
12
+ type: 's3',
13
+ properties: {
14
+ keyId: 'key',
15
+ accessKey: 'secret',
16
+ bucketName: 'bucket',
17
+ region: 'eu-central-1',
18
+ endpoint: 'amazonaws.com',
19
+ },
20
+ };
21
+
22
+ describe('backendProfileSchema', () => {
23
+ it('seeds a new storage as an aws s3 bucket', () => {
24
+ expect(getDefaultsFromZodSchema(backendProfileSchema, {})).toMatchObject({
25
+ name: '',
26
+ type: 's3',
27
+ maxSize: 0,
28
+ expireDays: 0,
29
+ priority: 0,
30
+ properties: {
31
+ keyId: '',
32
+ accessKey: '',
33
+ bucketName: '',
34
+ region: '',
35
+ endpoint: 'amazonaws.com',
36
+ pathPattern: '$DOMAIN/$Y/$M/$D',
37
+ },
38
+ });
39
+ });
40
+
41
+ it('requires name and s3 settings for a new storage', () => {
42
+ const paths = issuePaths(
43
+ backendProfileSchema.safeParse(
44
+ getDefaultsFromZodSchema(backendProfileSchema, {}),
45
+ ),
46
+ );
47
+
48
+ expect(paths).toEqual(
49
+ expect.arrayContaining([
50
+ 'name',
51
+ 'properties.keyId',
52
+ 'properties.accessKey',
53
+ 'properties.bucketName',
54
+ 'properties.region',
55
+ ]),
56
+ );
57
+ });
58
+
59
+ it('does not require the access key for an existing storage', () => {
60
+ const paths = issuePaths(
61
+ backendProfileSchema.safeParse({
62
+ ...filledS3,
63
+ id: '1',
64
+ properties: {
65
+ ...filledS3.properties,
66
+ accessKey: '',
67
+ },
68
+ }),
69
+ );
70
+
71
+ expect(paths).not.toContain('properties.accessKey');
72
+ });
73
+
74
+ it('does not require s3 settings for other storage types', () => {
75
+ const result = backendProfileSchema.safeParse({
76
+ id: '1',
77
+ name: 'local',
78
+ type: 'local',
79
+ properties: {
80
+ directory: '/data',
81
+ },
82
+ });
83
+
84
+ expect(result.success).toBe(true);
85
+ });
86
+
87
+ it('rejects negative numbers and reads maxSize given as a string', () => {
88
+ const result = backendProfileSchema.safeParse({
89
+ ...filledS3,
90
+ maxSize: '10',
91
+ expireDays: -1,
92
+ });
93
+
94
+ expect(issuePaths(result)).toEqual([
95
+ 'expireDays',
96
+ ]);
97
+ expect(
98
+ backendProfileSchema.safeParse({
99
+ ...filledS3,
100
+ maxSize: '10',
101
+ }).data?.maxSize,
102
+ ).toBe(10);
103
+ });
104
+ });
@@ -0,0 +1,79 @@
1
+ import type { StorageBackendProfile } from '@webitel/api-services/gen/models';
2
+ import { z } from 'zod';
3
+
4
+ import { StorageType } from '../../enums';
5
+ import { i18nIssue } from '../_shared/i18nIssue';
6
+ import type { ZodShape } from '../types';
7
+
8
+ /** [Claude] number inputs give numbers, the api gives `maxSize` as a string */
9
+ const nonNegativeNumberSchema = z.coerce.number().min(0).default(0);
10
+
11
+ /**
12
+ * [Claude] S3 settings, seeded for a new storage: only S3 can be created.
13
+ * The keys of other storage types pass through untouched.
14
+ */
15
+ const backendProfilePropertiesSchema = z
16
+ .object({
17
+ keyId: z.string().optional().default(''),
18
+ accessKey: z.string().optional().default(''),
19
+ bucketName: z.string().optional().default(''),
20
+ region: z.string().optional().default(''),
21
+ endpoint: z.string().optional().default('amazonaws.com'),
22
+ pathPattern: z.string().optional().default('$DOMAIN/$Y/$M/$D'),
23
+ })
24
+ .passthrough();
25
+
26
+ const requiredS3Properties = [
27
+ 'keyId',
28
+ 'bucketName',
29
+ 'region',
30
+ 'endpoint',
31
+ ] as const;
32
+
33
+ /**
34
+ * [Claude] Storage (backend profile) card schema.
35
+ *
36
+ * Access key is required only when creating (`id` absent): an empty key on
37
+ * update means "keep the current one".
38
+ */
39
+ export const backendProfileSchema = z
40
+ .object<ZodShape<StorageBackendProfile>>({
41
+ id: z.string().optional(),
42
+ name: z.string().min(1).default(''),
43
+ type: z.string().default(StorageType.S3),
44
+ maxSize: nonNegativeNumberSchema,
45
+ expireDays: nonNegativeNumberSchema,
46
+ priority: nonNegativeNumberSchema,
47
+ disabled: z.boolean().optional(),
48
+ // [Claude] `.prefault`, not `.default`: zod 4's `.default({})` would skip the s3 defaults
49
+ properties: backendProfilePropertiesSchema.prefault({}),
50
+ })
51
+ .passthrough()
52
+ .superRefine((profile, ctx) => {
53
+ if (profile.type !== StorageType.S3) return;
54
+
55
+ const properties = profile.properties as z.infer<
56
+ typeof backendProfilePropertiesSchema
57
+ >;
58
+ const required = [
59
+ ...requiredS3Properties,
60
+ ...(profile.id
61
+ ? []
62
+ : [
63
+ 'accessKey' as const,
64
+ ]),
65
+ ];
66
+
67
+ for (const key of required) {
68
+ if (!properties?.[key]) {
69
+ ctx.addIssue({
70
+ code: 'custom',
71
+ path: [
72
+ 'properties',
73
+ key,
74
+ ],
75
+ ...i18nIssue('required'),
76
+ });
77
+ }
78
+ }
79
+ });
@@ -0,0 +1,189 @@
1
+ import { describe, expect, it } from 'vitest';
2
+
3
+ import { getChatGatewayDefaults } from '../../../api/clients/chatGateways/defaults/chatGatewayProviderDefaults';
4
+ import { ChatGatewayProvider } from '../../../enums';
5
+ import { chatGatewaySchema } from '../chatGateway.validations';
6
+
7
+ const issuePaths = (value: unknown) => {
8
+ const result = chatGatewaySchema.safeParse(value);
9
+ return result.success
10
+ ? []
11
+ : result.error.issues.map(({ path }) => path.join('.'));
12
+ };
13
+
14
+ const flow = {
15
+ id: 1,
16
+ name: 'flow',
17
+ };
18
+
19
+ describe('chatGatewaySchema', () => {
20
+ it('keeps metadata keys it does not list', () => {
21
+ const parsed = chatGatewaySchema.parse({
22
+ name: 'bot',
23
+ uri: '/bot',
24
+ flow,
25
+ provider: ChatGatewayProvider.TELEGRAM_BOT,
26
+ metadata: {
27
+ token: 'token',
28
+ unknownKey: 'kept',
29
+ },
30
+ });
31
+ expect(parsed.metadata).toMatchObject({
32
+ unknownKey: 'kept',
33
+ });
34
+ });
35
+
36
+ it('requires name, uri, flow and the provider fields', () => {
37
+ expect(
38
+ issuePaths({
39
+ ...getChatGatewayDefaults(ChatGatewayProvider.TELEGRAM_BOT),
40
+ uri: '',
41
+ }),
42
+ ).toEqual([
43
+ 'name',
44
+ 'uri',
45
+ 'flow',
46
+ 'metadata.token',
47
+ ]);
48
+ });
49
+
50
+ it('reports a cleared lookup on its id', () => {
51
+ expect(
52
+ issuePaths({
53
+ name: 'bot',
54
+ uri: '/bot',
55
+ flow: {},
56
+ provider: ChatGatewayProvider.VIBER,
57
+ metadata: {
58
+ token: 'token',
59
+ },
60
+ }),
61
+ ).toEqual([
62
+ 'flow.id',
63
+ ]);
64
+ });
65
+
66
+ it('checks the uri length', () => {
67
+ expect(
68
+ issuePaths({
69
+ name: 'bot',
70
+ uri: '/b',
71
+ flow,
72
+ provider: ChatGatewayProvider.CUSTOM,
73
+ metadata: {
74
+ webhook: 'hook',
75
+ secret: 'secret',
76
+ },
77
+ }),
78
+ ).toEqual([
79
+ 'uri',
80
+ ]);
81
+ });
82
+
83
+ it('checks the infobip url and telegram app id format', () => {
84
+ expect(
85
+ issuePaths({
86
+ name: 'infobip',
87
+ uri: '/infobip',
88
+ flow,
89
+ provider: ChatGatewayProvider.INFOBIP,
90
+ metadata: {
91
+ apiKey: 'key',
92
+ url: 'not a url',
93
+ },
94
+ }),
95
+ ).toEqual([
96
+ 'metadata.url',
97
+ ]);
98
+ expect(
99
+ issuePaths({
100
+ name: 'app',
101
+ uri: '/app',
102
+ flow,
103
+ provider: ChatGatewayProvider.TELEGRAM_APP,
104
+ metadata: {
105
+ apiId: '12a',
106
+ apiHash: 'hash',
107
+ },
108
+ }),
109
+ ).toEqual([
110
+ 'metadata.apiId',
111
+ ]);
112
+ });
113
+
114
+ it('checks the meta api version only when it is set', () => {
115
+ const messenger = {
116
+ name: 'meta',
117
+ uri: '/meta',
118
+ flow,
119
+ provider: ChatGatewayProvider.MESSENGER,
120
+ metadata: {
121
+ clientId: 'id',
122
+ clientSecret: 'secret',
123
+ version: '',
124
+ },
125
+ };
126
+ expect(issuePaths(messenger)).toEqual([]);
127
+ expect(
128
+ issuePaths({
129
+ ...messenger,
130
+ metadata: {
131
+ ...messenger.metadata,
132
+ version: '24',
133
+ },
134
+ }),
135
+ ).toEqual([
136
+ 'metadata.version',
137
+ ]);
138
+ });
139
+
140
+ describe('webchat', () => {
141
+ const webchat = () => ({
142
+ ...getChatGatewayDefaults(ChatGatewayProvider.WEBCHAT),
143
+ name: 'webchat',
144
+ flow,
145
+ });
146
+
147
+ it('accepts the defaults', () => {
148
+ expect(issuePaths(webchat())).toEqual([]);
149
+ });
150
+
151
+ it('needs a flow only while the chat is enabled', () => {
152
+ const gateway = webchat();
153
+ gateway.flow = undefined;
154
+ expect(issuePaths(gateway)).toEqual([
155
+ 'flow',
156
+ ]);
157
+ gateway.metadata.chat.enabled = false;
158
+ expect(issuePaths(gateway)).toEqual([]);
159
+ });
160
+
161
+ it('checks timeout ranges', () => {
162
+ const gateway = webchat();
163
+ gateway.metadata.readTimeout = '10';
164
+ gateway.metadata.writeTimeout = '61';
165
+ expect(issuePaths(gateway)).toEqual([
166
+ 'metadata.readTimeout',
167
+ 'metadata.writeTimeout',
168
+ ]);
169
+ });
170
+
171
+ it('validates enabled sections only', () => {
172
+ const gateway = webchat();
173
+ gateway.metadata.captcha.enabled = true;
174
+ gateway.metadata.captcha.threshold = 2;
175
+ gateway.metadata.appointment.enabled = true;
176
+ gateway.metadata.call.enabled = true;
177
+ gateway.metadata.call.url = 'https://example.com';
178
+ expect(issuePaths(gateway)).toEqual([
179
+ 'metadata.captcha.sitekey',
180
+ 'metadata.captcha.secret',
181
+ 'metadata.appointment.queue',
182
+ 'metadata.appointment.communicationType',
183
+ 'metadata.call.flow',
184
+ 'metadata.call.url',
185
+ 'metadata.captcha.threshold',
186
+ ]);
187
+ });
188
+ });
189
+ });