@webitel/api-services 26.12.21 → 26.12.23

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 (103) 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/cognitiveProfiles/cognitiveProfiles.ts +8 -32
  11. package/src/api/clients/cognitiveProfiles/defaults/cognitiveProfileDefaults.ts +39 -0
  12. package/src/api/clients/emailProfiles/emailProfiles.ts +6 -19
  13. package/src/api/clients/gateways/__tests__/gateways.spec.ts +138 -0
  14. package/src/api/clients/gateways/gateways.ts +60 -52
  15. package/src/api/clients/importTemplates/importTemplates.ts +36 -21
  16. package/src/api/clients/index.ts +2 -0
  17. package/src/api/clients/storagePolicies/storagePolicies.ts +24 -36
  18. package/src/api/clients/triggers/triggerJobs.ts +22 -12
  19. package/src/api/clients/triggers/triggers.ts +12 -37
  20. package/src/enums/ChatGatewayChannelSetup/ChatGatewayChannelSetup.ts +10 -0
  21. package/src/enums/GatewayIpAclProtocol/GatewayIpAclProtocol.ts +8 -0
  22. package/src/enums/GatewayRegisterState/GatewayRegisterState.ts +17 -0
  23. package/src/enums/StorageType/StorageType.ts +10 -0
  24. package/src/enums/WebchatAlternativeChannel/WebchatAlternativeChannel.ts +15 -0
  25. package/src/enums/index.ts +10 -0
  26. package/src/locale/en/en.ts +8 -0
  27. package/src/locale/es/es.ts +8 -0
  28. package/src/locale/kz/kz.ts +8 -0
  29. package/src/locale/pl/pl.ts +8 -0
  30. package/src/locale/ro/ro.ts +8 -0
  31. package/src/locale/ru/ru.ts +8 -0
  32. package/src/locale/uk/uk.ts +8 -0
  33. package/src/locale/uz/uz.ts +8 -0
  34. package/src/locale/vi/vi.ts +8 -0
  35. package/src/scripts/convertDuration/__tests__/convertDurationWithMilliseconds.spec.ts +19 -0
  36. package/src/scripts/convertDuration/convertDurationWithMilliseconds.ts +18 -0
  37. package/src/scripts/index.ts +2 -0
  38. package/src/validations/_shared/ip.validations.ts +10 -0
  39. package/src/validations/backendProfile/__tests__/backendProfile.validations.spec.ts +104 -0
  40. package/src/validations/backendProfile/backendProfile.validations.ts +79 -0
  41. package/src/validations/chatGateway/__tests__/chatGateway.validations.spec.ts +189 -0
  42. package/src/validations/chatGateway/chatGateway.validations.ts +452 -0
  43. package/src/validations/cognitiveProfile/__tests__/cognitiveProfile.validations.spec.ts +83 -0
  44. package/src/validations/cognitiveProfile/cognitiveProfile.validations.ts +74 -0
  45. package/src/validations/device/device.validations.ts +2 -8
  46. package/src/validations/emailProfile/__tests__/emailProfile.validations.spec.ts +105 -0
  47. package/src/validations/emailProfile/emailProfile.validations.ts +113 -0
  48. package/src/validations/gateway/__tests__/gateway.validations.spec.ts +168 -0
  49. package/src/validations/gateway/gateway.validations.ts +138 -0
  50. package/src/validations/importTemplate/__tests__/importTemplate.validations.spec.ts +77 -0
  51. package/src/validations/importTemplate/importTemplate.validations.ts +56 -0
  52. package/src/validations/index.ts +8 -0
  53. package/src/validations/storagePolicy/__tests__/storagePolicy.validations.spec.ts +52 -0
  54. package/src/validations/storagePolicy/storagePolicy.validations.ts +36 -0
  55. package/src/validations/trigger/__tests__/trigger.validations.spec.ts +92 -0
  56. package/src/validations/trigger/trigger.validations.ts +82 -0
  57. package/types/.tsbuildinfo +1 -1
  58. package/types/api/clients/_shared/appUrls.d.ts +11 -0
  59. package/types/api/clients/chatGateways/chatGatewayChannels.d.ts +62 -0
  60. package/types/api/clients/chatGateways/chatGateways.d.ts +4 -4
  61. package/types/api/clients/chatGateways/defaults/chatGatewayProviderDefaults.d.ts +21 -0
  62. package/types/api/clients/chatGateways/defaults/defaultChatGateway.d.ts +3 -1
  63. package/types/api/clients/chatGateways/defaults/webChatGateway.d.ts +5 -4
  64. package/types/api/clients/cognitiveProfiles/cognitiveProfiles.d.ts +1 -1
  65. package/types/api/clients/cognitiveProfiles/defaults/cognitiveProfileDefaults.d.ts +13 -0
  66. package/types/api/clients/importTemplates/importTemplates.d.ts +2 -2
  67. package/types/api/clients/index.d.ts +2 -0
  68. package/types/enums/ChatGatewayChannelSetup/ChatGatewayChannelSetup.d.ts +8 -0
  69. package/types/enums/GatewayIpAclProtocol/GatewayIpAclProtocol.d.ts +6 -0
  70. package/types/enums/GatewayRegisterState/GatewayRegisterState.d.ts +15 -0
  71. package/types/enums/StorageType/StorageType.d.ts +9 -0
  72. package/types/enums/WebchatAlternativeChannel/WebchatAlternativeChannel.d.ts +13 -0
  73. package/types/enums/index.d.ts +6 -1
  74. package/types/locale/en/en.d.ts +7 -0
  75. package/types/locale/es/es.d.ts +7 -0
  76. package/types/locale/index.d.ts +63 -0
  77. package/types/locale/kz/kz.d.ts +7 -0
  78. package/types/locale/pl/pl.d.ts +7 -0
  79. package/types/locale/ro/ro.d.ts +7 -0
  80. package/types/locale/ru/ru.d.ts +7 -0
  81. package/types/locale/uk/uk.d.ts +7 -0
  82. package/types/locale/uz/uz.d.ts +7 -0
  83. package/types/locale/vi/vi.d.ts +7 -0
  84. package/types/scripts/convertDuration/convertDurationWithMilliseconds.d.ts +6 -0
  85. package/types/scripts/index.d.ts +2 -1
  86. package/types/validations/_shared/ip.validations.d.ts +4 -0
  87. package/types/validations/backendProfile/backendProfile.validations.d.ts +24 -0
  88. package/types/validations/chatGateway/chatGateway.validations.d.ts +165 -0
  89. package/types/validations/cognitiveProfile/cognitiveProfile.validations.d.ts +28 -0
  90. package/types/validations/emailProfile/emailProfile.validations.d.ts +36 -0
  91. package/types/validations/gateway/gateway.validations.d.ts +48 -0
  92. package/types/validations/importTemplate/importTemplate.validations.d.ts +62 -0
  93. package/types/validations/index.d.ts +8 -0
  94. package/types/validations/storagePolicy/storagePolicy.validations.d.ts +26 -0
  95. package/types/validations/trigger/trigger.validations.d.ts +38 -0
  96. package/src/api/clients/chatGateways/enums/WebchatAlternativeChannel.enum.ts +0 -12
  97. package/src/api/clients/gateways/defaults/defaultGateway.ts +0 -9
  98. package/src/api/clients/gateways/defaults/registerGateway.ts +0 -12
  99. package/src/api/clients/gateways/defaults/trunkingGateway.ts +0 -16
  100. package/types/api/clients/chatGateways/enums/WebchatAlternativeChannel.enum.d.ts +0 -12
  101. package/types/api/clients/gateways/defaults/defaultGateway.d.ts +0 -8
  102. package/types/api/clients/gateways/defaults/registerGateway.d.ts +0 -13
  103. package/types/api/clients/gateways/defaults/trunkingGateway.d.ts +0 -16
@@ -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
+ });
@@ -0,0 +1,452 @@
1
+ import { get, isPlainObject } from 'lodash-es';
2
+ import { z } from 'zod';
3
+
4
+ import { ChatGatewayProvider } from '../../enums';
5
+ import { i18nIssue } from '../_shared/i18nIssue';
6
+ import { isFilled } from '../_shared/isFilled';
7
+ import { flexibleLookupSchema } from '../_shared/lookup.validations';
8
+
9
+ /** [Claude] timeouts and counters come as strings from the defaults and as numbers from number inputs */
10
+ const numberLikeSchema = z
11
+ .union([
12
+ z.string(),
13
+ z.number(),
14
+ ])
15
+ .nullish();
16
+
17
+ const optionalLookupSchema = flexibleLookupSchema.nullish();
18
+
19
+ /** [Claude] vuelidate's `numeric`: an empty value passes, otherwise a non-negative decimal */
20
+ const isNumeric = (value: unknown) =>
21
+ !isFilled(value) || /^\d*(\.\d+)?$/.test(String(value));
22
+
23
+ const hasProtocol = (value: string, protocol: RegExp) => {
24
+ try {
25
+ return protocol.test(new URL(value).protocol);
26
+ } catch {
27
+ return false;
28
+ }
29
+ };
30
+
31
+ const isUrl = (value: unknown) =>
32
+ !isFilled(value) || hasProtocol(String(value), /^(https?|ftp):$/i);
33
+
34
+ const isWebsocketUrl = (value: unknown) =>
35
+ !isFilled(value) || hasProtocol(String(value), /^wss?:$/i);
36
+
37
+ /** [Claude] Meta Graph API version: v1.0, v19.0, v24.0 ([WTEL-7923](https://webitel.atlassian.net/browse/WTEL-7923)) */
38
+ const isMetaApiVersion = (value: unknown) =>
39
+ !isFilled(value) || /^v([1-9]\d*)(\.(0|[1-9]\d*))$/.test(String(value));
40
+
41
+ /**
42
+ * [Claude] Every provider keeps its settings in `metadata`, so it is one loose
43
+ * object with all known keys optional: `.passthrough()` keeps the keys this
44
+ * schema does not list (regle syncs the parsed value back into the form).
45
+ * Which keys a provider requires is checked in `superRefine` below.
46
+ */
47
+ const chatGatewayMetadataSchema = z
48
+ .object({
49
+ // [Claude] telegram bot, viber
50
+ token: z.string().optional(),
51
+ // [Claude] telegram app
52
+ apiId: numberLikeSchema,
53
+ apiHash: z.string().optional(),
54
+ // [Claude] messenger (meta)
55
+ clientId: z.string().optional(),
56
+ clientSecret: z.string().optional(),
57
+ version: z.string().optional(),
58
+ instagramComments: z.boolean().optional(),
59
+ instagramMentions: z.boolean().optional(),
60
+ whatsappToken: z.string().optional(),
61
+ // [Claude] infobip
62
+ apiKey: z.string().optional(),
63
+ url: z.string().optional(),
64
+ // [Claude] viber
65
+ botName: z.string().optional(),
66
+ btnBackColor: z.string().optional(),
67
+ btnFontColor: z.string().optional(),
68
+ // [Claude] custom
69
+ secret: z.string().optional(),
70
+ webhook: z.string().optional(),
71
+ // [Claude] webchat
72
+ allowOrigin: z.array(z.string()).optional(),
73
+ readTimeout: numberLikeSchema,
74
+ writeTimeout: numberLikeSchema,
75
+ handshakeTimeout: numberLikeSchema,
76
+ mediaMaxSize: numberLikeSchema,
77
+ _btnCodeDirty: z.boolean().optional(),
78
+ view: z
79
+ .object({
80
+ logoUrl: z.string().optional(),
81
+ })
82
+ .passthrough()
83
+ .optional(),
84
+ captcha: z
85
+ .object({
86
+ enabled: z.boolean().optional(),
87
+ sitekey: z.string().optional(),
88
+ secret: z.string().optional(),
89
+ threshold: numberLikeSchema,
90
+ // [Claude] stored as 1/0 by older versions of the form
91
+ showFlag: z
92
+ .union([
93
+ z.boolean(),
94
+ z.number(),
95
+ ])
96
+ .optional(),
97
+ })
98
+ .passthrough()
99
+ .optional(),
100
+ chat: z
101
+ .object({
102
+ enabled: z.boolean().optional(),
103
+ timeoutIsActive: z.boolean().optional(),
104
+ openTimeout: numberLikeSchema,
105
+ })
106
+ .passthrough()
107
+ .optional(),
108
+ appointment: z
109
+ .object({
110
+ enabled: z.boolean().optional(),
111
+ queue: optionalLookupSchema,
112
+ communicationType: optionalLookupSchema,
113
+ duration: z.string().optional(),
114
+ days: numberLikeSchema,
115
+ availableAgents: numberLikeSchema,
116
+ })
117
+ .passthrough()
118
+ .optional(),
119
+ call: z
120
+ .object({
121
+ enabled: z.boolean().optional(),
122
+ url: z.string().optional(),
123
+ flow: optionalLookupSchema,
124
+ })
125
+ .passthrough()
126
+ .optional(),
127
+ alternativeChannels: z
128
+ .record(
129
+ z.string(),
130
+ z
131
+ .object({
132
+ url: z.string().optional(),
133
+ enabled: z.boolean().optional(),
134
+ })
135
+ .passthrough(),
136
+ )
137
+ .optional(),
138
+ })
139
+ .passthrough();
140
+
141
+ const chatGatewayUpdatesSchema = z
142
+ .object({
143
+ title: z.string().optional(),
144
+ close: z.string().optional(),
145
+ join: z.string().optional(),
146
+ left: z.string().optional(),
147
+ filePolicyFail: z.string().optional(),
148
+ })
149
+ .passthrough();
150
+
151
+ interface NumberRange {
152
+ min?: number;
153
+ max?: number;
154
+ }
155
+
156
+ interface ProviderRules {
157
+ required?: string[];
158
+ numeric?: string[];
159
+ url?: string[];
160
+ websocketUrl?: string[];
161
+ metaApiVersion?: string[];
162
+ range?: Record<string, NumberRange>;
163
+ }
164
+
165
+ const sharedRules: ProviderRules = {
166
+ required: [
167
+ 'name',
168
+ 'uri',
169
+ ],
170
+ };
171
+
172
+ /**
173
+ * [Claude] Webchat's nested sections only validate when they are enabled,
174
+ * so its rules are built from the item itself.
175
+ */
176
+ const webchatRules = (
177
+ metadata: z.infer<typeof chatGatewayMetadataSchema>,
178
+ ): ProviderRules => {
179
+ const required: string[] = [];
180
+ const numeric = [
181
+ 'metadata.readTimeout',
182
+ 'metadata.writeTimeout',
183
+ 'metadata.handshakeTimeout',
184
+ 'metadata.chat.openTimeout',
185
+ ];
186
+ const range: Record<string, NumberRange> = {
187
+ 'metadata.readTimeout': {
188
+ min: 30,
189
+ max: 300,
190
+ },
191
+ 'metadata.writeTimeout': {
192
+ min: 1,
193
+ max: 60,
194
+ },
195
+ 'metadata.handshakeTimeout': {
196
+ min: 10,
197
+ max: 60,
198
+ },
199
+ 'metadata.chat.openTimeout': {
200
+ min: 0,
201
+ },
202
+ };
203
+ const websocketUrl: string[] = [];
204
+
205
+ // [Claude] the flow serves the chat only, so a widget without chat needs none
206
+ if (metadata.chat?.enabled) required.push('flow');
207
+
208
+ if (metadata.captcha?.enabled) {
209
+ required.push(
210
+ 'metadata.captcha.sitekey',
211
+ 'metadata.captcha.secret',
212
+ 'metadata.captcha.threshold',
213
+ );
214
+ numeric.push('metadata.captcha.threshold');
215
+ range['metadata.captcha.threshold'] = {
216
+ min: 0,
217
+ max: 1,
218
+ };
219
+ }
220
+
221
+ if (metadata.appointment?.enabled) {
222
+ required.push(
223
+ 'metadata.appointment.queue',
224
+ 'metadata.appointment.communicationType',
225
+ 'metadata.appointment.duration',
226
+ 'metadata.appointment.days',
227
+ 'metadata.appointment.availableAgents',
228
+ );
229
+ range['metadata.appointment.days'] = {
230
+ min: 1,
231
+ max: 7,
232
+ };
233
+ range['metadata.appointment.availableAgents'] = {
234
+ min: 1,
235
+ };
236
+ }
237
+
238
+ if (metadata.call?.enabled) {
239
+ required.push('metadata.call.url', 'metadata.call.flow');
240
+ websocketUrl.push('metadata.call.url');
241
+ }
242
+
243
+ return {
244
+ required,
245
+ numeric,
246
+ range,
247
+ url: [
248
+ 'metadata.view.logoUrl',
249
+ ],
250
+ websocketUrl,
251
+ };
252
+ };
253
+
254
+ const providerRules = (
255
+ provider: string,
256
+ metadata: z.infer<typeof chatGatewayMetadataSchema>,
257
+ ): ProviderRules => {
258
+ switch (provider) {
259
+ case ChatGatewayProvider.TELEGRAM_BOT:
260
+ case ChatGatewayProvider.VIBER:
261
+ return {
262
+ required: [
263
+ 'flow',
264
+ 'metadata.token',
265
+ ],
266
+ };
267
+ case ChatGatewayProvider.TELEGRAM_APP:
268
+ return {
269
+ required: [
270
+ 'flow',
271
+ 'metadata.apiId',
272
+ 'metadata.apiHash',
273
+ ],
274
+ numeric: [
275
+ 'metadata.apiId',
276
+ ],
277
+ };
278
+ case ChatGatewayProvider.MESSENGER:
279
+ return {
280
+ required: [
281
+ 'flow',
282
+ 'metadata.clientId',
283
+ 'metadata.clientSecret',
284
+ ],
285
+ metaApiVersion: [
286
+ 'metadata.version',
287
+ ],
288
+ };
289
+ case ChatGatewayProvider.INFOBIP:
290
+ return {
291
+ required: [
292
+ 'flow',
293
+ 'metadata.apiKey',
294
+ 'metadata.url',
295
+ ],
296
+ url: [
297
+ 'metadata.url',
298
+ ],
299
+ };
300
+ case ChatGatewayProvider.CUSTOM:
301
+ return {
302
+ required: [
303
+ 'flow',
304
+ 'metadata.webhook',
305
+ 'metadata.secret',
306
+ ],
307
+ };
308
+ case ChatGatewayProvider.WEBCHAT:
309
+ return webchatRules(metadata);
310
+ default:
311
+ return {
312
+ required: [
313
+ 'flow',
314
+ ],
315
+ };
316
+ }
317
+ };
318
+
319
+ const URI_MIN_LENGTH = 3;
320
+
321
+ /**
322
+ * [Claude] One flat schema for all providers rather than a union on `provider`:
323
+ * a union would make regle's `validationFields` a union too, and every tab would
324
+ * have to narrow it first. The per-provider rules live in `superRefine`, with
325
+ * dotted paths, so `metadata.token` lands on `validationFields.metadata.$fields.token`.
326
+ */
327
+ export const chatGatewaySchema = z
328
+ .object({
329
+ id: z
330
+ .union([
331
+ z.string(),
332
+ z.number(),
333
+ ])
334
+ .optional(),
335
+ name: z.string().default(''),
336
+ uri: z.string().default(''),
337
+ flow: optionalLookupSchema,
338
+ enabled: z.boolean().default(false),
339
+ provider: z.string().default(''),
340
+ metadata: chatGatewayMetadataSchema.default({}),
341
+ updates: chatGatewayUpdatesSchema.optional(),
342
+ })
343
+ .passthrough()
344
+ .superRefine((gateway, ctx) => {
345
+ const rules = [
346
+ sharedRules,
347
+ providerRules(gateway.provider, gateway.metadata),
348
+ ];
349
+
350
+ const addIssue = (
351
+ path: string,
352
+ issue: Record<string, unknown>,
353
+ value = get(gateway, path),
354
+ ) =>
355
+ ctx.addIssue({
356
+ code: 'custom',
357
+ ...issue,
358
+ // [Claude] an object field gets a nested status in regle, so its issue goes on `id`
359
+ path: isPlainObject(value)
360
+ ? [
361
+ ...path.split('.'),
362
+ 'id',
363
+ ]
364
+ : path.split('.'),
365
+ } as Parameters<typeof ctx.addIssue>[0]);
366
+
367
+ for (const rule of rules) {
368
+ for (const path of rule.required ?? []) {
369
+ if (!isFilled(get(gateway, path))) {
370
+ addIssue(path, i18nIssue('required'));
371
+ }
372
+ }
373
+
374
+ const formatRules: [
375
+ string[] | undefined,
376
+ (value: unknown) => boolean,
377
+ string,
378
+ ][] = [
379
+ [
380
+ rule.numeric,
381
+ isNumeric,
382
+ 'numeric',
383
+ ],
384
+ [
385
+ rule.url,
386
+ isUrl,
387
+ 'url',
388
+ ],
389
+ [
390
+ rule.websocketUrl,
391
+ isWebsocketUrl,
392
+ 'websocketValidator',
393
+ ],
394
+ [
395
+ rule.metaApiVersion,
396
+ isMetaApiVersion,
397
+ 'metaApiVersion',
398
+ ],
399
+ ];
400
+
401
+ for (const [paths, isValid, i18nKey] of formatRules) {
402
+ for (const path of paths ?? []) {
403
+ if (!isValid(get(gateway, path))) {
404
+ addIssue(path, i18nIssue(i18nKey));
405
+ }
406
+ }
407
+ }
408
+
409
+ for (const [path, { min, max }] of Object.entries(rule.range ?? {})) {
410
+ const value = get(gateway, path);
411
+ // [Claude] an empty field is the required rule's business, a non-number the numeric one's
412
+ if (!isFilled(value) || !isNumeric(value)) continue;
413
+ const number = Number(value);
414
+ /**
415
+ * [Claude] `too_small`/`too_big`, not a message: a message wins over the
416
+ * app's error map, the only thing that translates. WTEL-10294
417
+ */
418
+ if (min !== undefined && number < min) {
419
+ addIssue(path, {
420
+ code: 'too_small',
421
+ origin: 'number',
422
+ minimum: min,
423
+ inclusive: true,
424
+ input: value,
425
+ });
426
+ }
427
+ if (max !== undefined && number > max) {
428
+ addIssue(path, {
429
+ code: 'too_big',
430
+ origin: 'number',
431
+ maximum: max,
432
+ inclusive: true,
433
+ input: value,
434
+ });
435
+ }
436
+ }
437
+ }
438
+
439
+ if (gateway.uri && gateway.uri.length < URI_MIN_LENGTH) {
440
+ addIssue('uri', {
441
+ code: 'too_small',
442
+ origin: 'string',
443
+ minimum: URI_MIN_LENGTH,
444
+ inclusive: true,
445
+ input: gateway.uri,
446
+ });
447
+ }
448
+ });
449
+
450
+ export type ChatGatewayFormShape = z.input<typeof chatGatewaySchema>;
451
+ export type ChatGatewayCard = ChatGatewayFormShape;
452
+ export type ChatGatewayMetadata = z.input<typeof chatGatewayMetadataSchema>;
@@ -0,0 +1,83 @@
1
+ import { StorageProviderType } from '@webitel/api-services/gen/models';
2
+ import { describe, expect, it } from 'vitest';
3
+
4
+ import { getCognitiveProfileDefaults } from '../../../api/clients/cognitiveProfiles/defaults/cognitiveProfileDefaults';
5
+ import { cognitiveProfileSchema } from '../cognitiveProfile.validations';
6
+
7
+ const issuePaths = (
8
+ result: ReturnType<typeof cognitiveProfileSchema.safeParse>,
9
+ ) => result.error?.issues.map(({ path }) => path.join('.')) ?? [];
10
+
11
+ describe('cognitiveProfileSchema', () => {
12
+ it('requires name, key and region for a new microsoft profile', () => {
13
+ const paths = issuePaths(
14
+ cognitiveProfileSchema.safeParse(
15
+ getCognitiveProfileDefaults(StorageProviderType.Microsoft),
16
+ ),
17
+ );
18
+
19
+ expect(paths).toEqual(
20
+ expect.arrayContaining([
21
+ 'name',
22
+ 'properties.key',
23
+ 'properties.region',
24
+ ]),
25
+ );
26
+ });
27
+
28
+ it('does not require the key of a saved microsoft or elevenlabs profile', () => {
29
+ for (const provider of [
30
+ StorageProviderType.Microsoft,
31
+ StorageProviderType.ElevenLabs,
32
+ ]) {
33
+ const paths = issuePaths(
34
+ cognitiveProfileSchema.safeParse({
35
+ ...getCognitiveProfileDefaults(provider),
36
+ id: '1',
37
+ name: 'profile',
38
+ properties: {
39
+ region: 'West Europe',
40
+ },
41
+ }),
42
+ );
43
+
44
+ expect(paths).not.toContain('properties.key');
45
+ }
46
+ });
47
+
48
+ it('requires a google key until a key file is chosen', () => {
49
+ const profile = {
50
+ ...getCognitiveProfileDefaults(StorageProviderType.Google),
51
+ id: '1',
52
+ name: 'profile',
53
+ };
54
+
55
+ expect(issuePaths(cognitiveProfileSchema.safeParse(profile))).toContain(
56
+ 'properties.key',
57
+ );
58
+ expect(
59
+ cognitiveProfileSchema.safeParse({
60
+ ...profile,
61
+ properties: {
62
+ keyFilename: 'key.json',
63
+ },
64
+ }).success,
65
+ ).toBe(true);
66
+ });
67
+
68
+ it('keeps the provider settings it does not list', () => {
69
+ const result = cognitiveProfileSchema.safeParse({
70
+ ...getCognitiveProfileDefaults(StorageProviderType.ElevenLabs),
71
+ name: 'profile',
72
+ properties: {
73
+ key: 'secret',
74
+ voice: 'rachel',
75
+ },
76
+ });
77
+
78
+ expect(result.data?.properties).toMatchObject({
79
+ key: 'secret',
80
+ voice: 'rachel',
81
+ });
82
+ });
83
+ });