@autofleet/sadot 1.0.5 → 1.0.7

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 (325) hide show
  1. package/dist/_virtual/_@oxc-project_runtime@0.89.0/helpers/decorate.cjs +1 -0
  2. package/dist/_virtual/_@oxc-project_runtime@0.89.0/helpers/decorate.js +1 -0
  3. package/dist/_virtual/_@oxc-project_runtime@0.89.0/helpers/decorateMetadata.cjs +1 -0
  4. package/dist/_virtual/_@oxc-project_runtime@0.89.0/helpers/decorateMetadata.js +1 -0
  5. package/dist/_virtual/rolldown_runtime.cjs +1 -0
  6. package/dist/api/index.cjs +2 -0
  7. package/dist/api/index.cjs.map +1 -0
  8. package/dist/api/index.js +2 -12
  9. package/dist/api/index.js.map +1 -0
  10. package/dist/api/v1/definition/index.cjs +2 -0
  11. package/dist/api/v1/definition/index.cjs.map +1 -0
  12. package/dist/api/v1/definition/index.js +2 -116
  13. package/dist/api/v1/definition/index.js.map +1 -0
  14. package/dist/api/v1/definition/validations.cjs +2 -0
  15. package/dist/api/v1/definition/validations.cjs.map +1 -0
  16. package/dist/api/v1/definition/validations.js +2 -77
  17. package/dist/api/v1/definition/validations.js.map +1 -0
  18. package/dist/api/v1/errors.cjs +2 -0
  19. package/dist/api/v1/errors.cjs.map +1 -0
  20. package/dist/api/v1/errors.js +2 -12
  21. package/dist/api/v1/errors.js.map +1 -0
  22. package/dist/api/v1/index.cjs +2 -0
  23. package/dist/api/v1/index.cjs.map +1 -0
  24. package/dist/api/v1/index.js +2 -13
  25. package/dist/api/v1/index.js.map +1 -0
  26. package/dist/api/v1/validator/index.cjs +2 -0
  27. package/dist/api/v1/validator/index.cjs.map +1 -0
  28. package/dist/api/v1/validator/index.js +2 -143
  29. package/dist/api/v1/validator/index.js.map +1 -0
  30. package/dist/api/v1/validator/validations.cjs +2 -0
  31. package/dist/api/v1/validator/validations.cjs.map +1 -0
  32. package/dist/api/v1/validator/validations.js +2 -38
  33. package/dist/api/v1/validator/validations.js.map +1 -0
  34. package/dist/errors/index.cjs +3 -0
  35. package/dist/errors/index.cjs.map +1 -0
  36. package/dist/errors/index.js +3 -66
  37. package/dist/errors/index.js.map +1 -0
  38. package/dist/events/index.cjs +2 -0
  39. package/dist/events/index.cjs.map +1 -0
  40. package/dist/events/index.js +2 -54
  41. package/dist/events/index.js.map +1 -0
  42. package/dist/hooks/enrich.cjs +2 -0
  43. package/dist/hooks/enrich.cjs.map +1 -0
  44. package/dist/hooks/enrich.js +2 -198
  45. package/dist/hooks/enrich.js.map +1 -0
  46. package/dist/hooks/find.cjs +2 -0
  47. package/dist/hooks/find.cjs.map +1 -0
  48. package/dist/hooks/find.js +2 -29
  49. package/dist/hooks/find.js.map +1 -0
  50. package/dist/hooks/hooks.cjs +2 -0
  51. package/dist/hooks/hooks.cjs.map +1 -0
  52. package/dist/hooks/hooks.js +2 -388
  53. package/dist/hooks/hooks.js.map +1 -0
  54. package/dist/hooks/index.cjs +1 -0
  55. package/dist/hooks/index.js +1 -17
  56. package/dist/hooks/utils/updateInstanceValues.cjs +2 -0
  57. package/dist/hooks/utils/updateInstanceValues.cjs.map +1 -0
  58. package/dist/hooks/utils/updateInstanceValues.js +2 -50
  59. package/dist/hooks/utils/updateInstanceValues.js.map +1 -0
  60. package/dist/index.cjs +2 -0
  61. package/dist/index.cjs.map +1 -0
  62. package/dist/index.d.cts +19 -0
  63. package/dist/index.d.ts +18 -12
  64. package/dist/index.js +2 -67
  65. package/dist/index.js.map +1 -0
  66. package/dist/models/CustomFieldDefinition.cjs +2 -0
  67. package/dist/models/CustomFieldDefinition.cjs.map +1 -0
  68. package/dist/models/CustomFieldDefinition.js +2 -192
  69. package/dist/models/CustomFieldDefinition.js.map +1 -0
  70. package/dist/models/CustomFieldEntries.cjs +2 -0
  71. package/dist/models/CustomFieldEntries.cjs.map +1 -0
  72. package/dist/models/CustomFieldEntries.js +2 -123
  73. package/dist/models/CustomFieldEntries.js.map +1 -0
  74. package/dist/models/CustomFieldValue.cjs +2 -0
  75. package/dist/models/CustomFieldValue.cjs.map +1 -0
  76. package/dist/models/CustomFieldValue.js +2 -151
  77. package/dist/models/CustomFieldValue.js.map +1 -0
  78. package/dist/models/CustomValidator.cjs +2 -0
  79. package/dist/models/CustomValidator.cjs.map +1 -0
  80. package/dist/models/CustomValidator.js +2 -98
  81. package/dist/models/CustomValidator.js.map +1 -0
  82. package/dist/models/index.cjs +2 -0
  83. package/dist/models/index.cjs.map +1 -0
  84. package/dist/models/index.js +2 -131
  85. package/dist/models/index.js.map +1 -0
  86. package/dist/models/tests/AssociatedTestModel.cjs +2 -0
  87. package/dist/models/tests/AssociatedTestModel.cjs.map +1 -0
  88. package/dist/models/tests/AssociatedTestModel.js +2 -71
  89. package/dist/models/tests/AssociatedTestModel.js.map +1 -0
  90. package/dist/models/tests/TestModel.cjs +2 -0
  91. package/dist/models/tests/TestModel.cjs.map +1 -0
  92. package/dist/models/tests/TestModel.js +2 -69
  93. package/dist/models/tests/TestModel.js.map +1 -0
  94. package/dist/models/tests/contextAwareModels/ContextAwareTestModel.cjs +2 -0
  95. package/dist/models/tests/contextAwareModels/ContextAwareTestModel.cjs.map +1 -0
  96. package/dist/models/tests/contextAwareModels/ContextAwareTestModel.js +2 -53
  97. package/dist/models/tests/contextAwareModels/ContextAwareTestModel.js.map +1 -0
  98. package/dist/models/tests/contextAwareModels/ContextTestModel.cjs +2 -0
  99. package/dist/models/tests/contextAwareModels/ContextTestModel.cjs.map +1 -0
  100. package/dist/models/tests/contextAwareModels/ContextTestModel.js +2 -47
  101. package/dist/models/tests/contextAwareModels/ContextTestModel.js.map +1 -0
  102. package/dist/repository/definition.cjs +2 -0
  103. package/dist/repository/definition.cjs.map +1 -0
  104. package/dist/repository/definition.js +2 -121
  105. package/dist/repository/definition.js.map +1 -0
  106. package/dist/repository/entries.cjs +2 -0
  107. package/dist/repository/entries.cjs.map +1 -0
  108. package/dist/repository/entries.js +2 -92
  109. package/dist/repository/entries.js.map +1 -0
  110. package/dist/repository/utils/formatValues.cjs +2 -0
  111. package/dist/repository/utils/formatValues.cjs.map +1 -0
  112. package/dist/repository/utils/formatValues.js +2 -16
  113. package/dist/repository/utils/formatValues.js.map +1 -0
  114. package/dist/repository/validator.cjs +2 -0
  115. package/dist/repository/validator.cjs.map +1 -0
  116. package/dist/repository/validator.js +2 -69
  117. package/dist/repository/validator.js.map +1 -0
  118. package/dist/repository/value.cjs +2 -0
  119. package/dist/repository/value.cjs.map +1 -0
  120. package/dist/repository/value.js +2 -124
  121. package/dist/repository/value.js.map +1 -0
  122. package/dist/scopes/filter.cjs +2 -0
  123. package/dist/scopes/filter.cjs.map +1 -0
  124. package/dist/scopes/filter.d.cts +23 -0
  125. package/dist/scopes/filter.d.ts +22 -29
  126. package/dist/scopes/filter.js +2 -75
  127. package/dist/scopes/filter.js.map +1 -0
  128. package/dist/scopes/helpers/filter.helpers.cjs +46 -0
  129. package/dist/scopes/helpers/filter.helpers.cjs.map +1 -0
  130. package/dist/scopes/helpers/filter.helpers.d.cts +17 -0
  131. package/dist/scopes/helpers/filter.helpers.d.ts +15 -40
  132. package/dist/scopes/helpers/filter.helpers.js +25 -183
  133. package/dist/scopes/helpers/filter.helpers.js.map +1 -0
  134. package/dist/scopes/index.cjs +1 -0
  135. package/dist/scopes/index.js +1 -6
  136. package/dist/types/index.d.cts +44 -0
  137. package/dist/types/index.d.ts +41 -44
  138. package/dist/utils/constants/index.cjs +2 -0
  139. package/dist/utils/constants/index.cjs.map +1 -0
  140. package/dist/utils/constants/index.d.cts +22 -0
  141. package/dist/utils/constants/index.d.ts +20 -17
  142. package/dist/utils/constants/index.js +2 -22
  143. package/dist/utils/constants/index.js.map +1 -0
  144. package/dist/utils/db/index.cjs +2 -0
  145. package/dist/utils/db/index.cjs.map +1 -0
  146. package/dist/utils/db/index.js +2 -24
  147. package/dist/utils/db/index.js.map +1 -0
  148. package/dist/utils/helpers/index.cjs +2 -0
  149. package/dist/utils/helpers/index.cjs.map +1 -0
  150. package/dist/utils/helpers/index.d.cts +31 -0
  151. package/dist/utils/helpers/index.d.ts +28 -23
  152. package/dist/utils/helpers/index.js +2 -40
  153. package/dist/utils/helpers/index.js.map +1 -0
  154. package/dist/utils/init.cjs +2 -0
  155. package/dist/utils/init.cjs.map +1 -0
  156. package/dist/utils/init.js +2 -112
  157. package/dist/utils/init.js.map +1 -0
  158. package/dist/utils/logger/index.cjs +2 -0
  159. package/dist/utils/logger/index.cjs.map +1 -0
  160. package/dist/utils/logger/index.js +2 -42
  161. package/dist/utils/logger/index.js.map +1 -0
  162. package/dist/utils/scopeAttributes.cjs +2 -0
  163. package/dist/utils/scopeAttributes.cjs.map +1 -0
  164. package/dist/utils/scopeAttributes.js +2 -11
  165. package/dist/utils/scopeAttributes.js.map +1 -0
  166. package/dist/utils/validations/index.cjs +2 -0
  167. package/dist/utils/validations/index.cjs.map +1 -0
  168. package/dist/utils/validations/index.js +2 -41
  169. package/dist/utils/validations/index.js.map +1 -0
  170. package/dist/utils/validations/schema/custom-fields.cjs +2 -0
  171. package/dist/utils/validations/schema/custom-fields.cjs.map +1 -0
  172. package/dist/utils/validations/schema/custom-fields.d.cts +7 -0
  173. package/dist/utils/validations/schema/custom-fields.d.ts +6 -2
  174. package/dist/utils/validations/schema/custom-fields.js +2 -9
  175. package/dist/utils/validations/schema/custom-fields.js.map +1 -0
  176. package/dist/utils/validations/schema/validator-schema.cjs +2 -0
  177. package/dist/utils/validations/schema/validator-schema.cjs.map +1 -0
  178. package/dist/utils/validations/schema/validator-schema.js +2 -95
  179. package/dist/utils/validations/schema/validator-schema.js.map +1 -0
  180. package/dist/utils/validations/validators/index.cjs +2 -0
  181. package/dist/utils/validations/validators/index.cjs.map +1 -0
  182. package/dist/utils/validations/validators/index.js +2 -40
  183. package/dist/utils/validations/validators/index.js.map +1 -0
  184. package/dist/utils/validations/validators/select.validator.cjs +2 -0
  185. package/dist/utils/validations/validators/select.validator.cjs.map +1 -0
  186. package/dist/utils/validations/validators/select.validator.js +2 -12
  187. package/dist/utils/validations/validators/select.validator.js.map +1 -0
  188. package/dist/utils/validations/validators/status.validator.cjs +2 -0
  189. package/dist/utils/validations/validators/status.validator.cjs.map +1 -0
  190. package/dist/utils/validations/validators/status.validator.js +2 -15
  191. package/dist/utils/validations/validators/status.validator.js.map +1 -0
  192. package/package.json +26 -23
  193. package/.nvmrc +0 -1
  194. package/dist/api/index.d.ts +0 -3
  195. package/dist/api/v1/definition/index.d.ts +0 -3
  196. package/dist/api/v1/definition/validations.d.ts +0 -2
  197. package/dist/api/v1/errors.d.ts +0 -4
  198. package/dist/api/v1/index.d.ts +0 -3
  199. package/dist/api/v1/validator/index.d.ts +0 -3
  200. package/dist/api/v1/validator/validations.d.ts +0 -6
  201. package/dist/errors/index.d.ts +0 -24
  202. package/dist/events/index.d.ts +0 -5
  203. package/dist/hooks/create.d.ts +0 -10
  204. package/dist/hooks/create.js +0 -95
  205. package/dist/hooks/enrich.d.ts +0 -25
  206. package/dist/hooks/find.d.ts +0 -1
  207. package/dist/hooks/hooks.d.ts +0 -17
  208. package/dist/hooks/index.d.ts +0 -5
  209. package/dist/hooks/update.d.ts +0 -10
  210. package/dist/hooks/update.js +0 -49
  211. package/dist/hooks/utils/updateInstanceValues.d.ts +0 -15
  212. package/dist/hooks/workaround.d.ts +0 -10
  213. package/dist/hooks/workaround.js +0 -37
  214. package/dist/models/CustomFieldDefinition.d.ts +0 -25
  215. package/dist/models/CustomFieldEntries.d.ts +0 -15
  216. package/dist/models/CustomFieldValue.d.ts +0 -16
  217. package/dist/models/CustomValidator.d.ts +0 -17
  218. package/dist/models/index.d.ts +0 -18
  219. package/dist/models/tests/AssociatedTestModel.d.ts +0 -12
  220. package/dist/models/tests/TestModel.d.ts +0 -12
  221. package/dist/models/tests/contextAwareModels/ContextAwareTestModel.d.ts +0 -10
  222. package/dist/models/tests/contextAwareModels/ContextTestModel.d.ts +0 -13
  223. package/dist/repository/definition.d.ts +0 -36
  224. package/dist/repository/entries.d.ts +0 -13
  225. package/dist/repository/utils/formatValues.d.ts +0 -3
  226. package/dist/repository/validator.d.ts +0 -28
  227. package/dist/repository/value.d.ts +0 -28
  228. package/dist/scopes/index.d.ts +0 -2
  229. package/dist/tests/api/test-api.d.ts +0 -2
  230. package/dist/tests/api/test-api.js +0 -38
  231. package/dist/tests/functional/searching/index.d.ts +0 -8
  232. package/dist/tests/functional/searching/index.js +0 -44
  233. package/dist/tests/helpers/commonHooks.d.ts +0 -6
  234. package/dist/tests/helpers/commonHooks.js +0 -62
  235. package/dist/tests/helpers/database-config.d.ts +0 -16
  236. package/dist/tests/helpers/database-config.js +0 -17
  237. package/dist/tests/helpers/index.d.ts +0 -7
  238. package/dist/tests/helpers/index.js +0 -33
  239. package/dist/tests/mocks/definition.mock.d.ts +0 -48
  240. package/dist/tests/mocks/definition.mock.js +0 -78
  241. package/dist/tests/mocks/events.mock.d.ts +0 -4
  242. package/dist/tests/mocks/events.mock.js +0 -21
  243. package/dist/tests/mocks/testModel.d.ts +0 -12
  244. package/dist/tests/mocks/testModel.js +0 -35
  245. package/dist/types/definition/index.d.ts +0 -25
  246. package/dist/types/definition/index.js +0 -2
  247. package/dist/types/entries/index.d.ts +0 -25
  248. package/dist/types/entries/index.js +0 -2
  249. package/dist/types/index.js +0 -2
  250. package/dist/types/value/index.d.ts +0 -15
  251. package/dist/types/value/index.js +0 -2
  252. package/dist/utils/db/index.d.ts +0 -4
  253. package/dist/utils/init.d.ts +0 -7
  254. package/dist/utils/logger/index.d.ts +0 -3
  255. package/dist/utils/scopeAttributes.d.ts +0 -2
  256. package/dist/utils/validations/index.d.ts +0 -8
  257. package/dist/utils/validations/schema/validator-schema.d.ts +0 -9
  258. package/dist/utils/validations/type.d.ts +0 -15
  259. package/dist/utils/validations/type.js +0 -2
  260. package/dist/utils/validations/validators/index.d.ts +0 -14
  261. package/dist/utils/validations/validators/select.validator.d.ts +0 -5
  262. package/dist/utils/validations/validators/status.validator.d.ts +0 -12
  263. package/src/api/index.ts +0 -10
  264. package/src/api/v1/definition/index.ts +0 -104
  265. package/src/api/v1/definition/validations.ts +0 -75
  266. package/src/api/v1/errors.ts +0 -13
  267. package/src/api/v1/index.ts +0 -11
  268. package/src/api/v1/validator/index.ts +0 -141
  269. package/src/api/v1/validator/validations.ts +0 -38
  270. package/src/errors/index.ts +0 -70
  271. package/src/events/index.ts +0 -63
  272. package/src/hooks/create.ts +0 -81
  273. package/src/hooks/enrich.ts +0 -255
  274. package/src/hooks/find.ts +0 -27
  275. package/src/hooks/hooks.ts +0 -479
  276. package/src/hooks/index.ts +0 -20
  277. package/src/hooks/update.ts +0 -55
  278. package/src/hooks/utils/updateInstanceValues.ts +0 -63
  279. package/src/hooks/workaround.ts +0 -47
  280. package/src/index.ts +0 -52
  281. package/src/models/CustomFieldDefinition.ts +0 -162
  282. package/src/models/CustomFieldEntries.ts +0 -81
  283. package/src/models/CustomFieldValue.ts +0 -118
  284. package/src/models/CustomValidator.ts +0 -78
  285. package/src/models/index.ts +0 -165
  286. package/src/models/tests/AssociatedTestModel.ts +0 -57
  287. package/src/models/tests/TestModel.ts +0 -54
  288. package/src/models/tests/contextAwareModels/ContextAwareTestModel.ts +0 -43
  289. package/src/models/tests/contextAwareModels/ContextTestModel.ts +0 -38
  290. package/src/repository/definition.ts +0 -175
  291. package/src/repository/entries.ts +0 -88
  292. package/src/repository/utils/formatValues.ts +0 -14
  293. package/src/repository/validator.ts +0 -119
  294. package/src/repository/value.ts +0 -116
  295. package/src/scopes/filter.ts +0 -100
  296. package/src/scopes/helpers/filter.helpers.ts +0 -227
  297. package/src/scopes/index.ts +0 -6
  298. package/src/tests/api/test-api.ts +0 -40
  299. package/src/tests/functional/searching/index.ts +0 -39
  300. package/src/tests/helpers/commonHooks.ts +0 -43
  301. package/src/tests/helpers/database-config.ts +0 -15
  302. package/src/tests/helpers/index.ts +0 -35
  303. package/src/tests/mocks/definition.mock.ts +0 -84
  304. package/src/tests/mocks/events.mock.ts +0 -21
  305. package/src/tests/mocks/testModel.ts +0 -37
  306. package/src/types/definition/index.ts +0 -24
  307. package/src/types/entries/index.ts +0 -27
  308. package/src/types/index.ts +0 -52
  309. package/src/types/value/index.ts +0 -14
  310. package/src/utils/constants/index.ts +0 -25
  311. package/src/utils/db/index.ts +0 -21
  312. package/src/utils/helpers/index.ts +0 -66
  313. package/src/utils/init.ts +0 -122
  314. package/src/utils/logger/index.ts +0 -14
  315. package/src/utils/scopeAttributes.ts +0 -12
  316. package/src/utils/validations/index.ts +0 -46
  317. package/src/utils/validations/schema/README.md +0 -93
  318. package/src/utils/validations/schema/custom-fields.ts +0 -8
  319. package/src/utils/validations/schema/validator-schema.ts +0 -106
  320. package/src/utils/validations/type.ts +0 -20
  321. package/src/utils/validations/validators/index.ts +0 -38
  322. package/src/utils/validations/validators/select.validator.ts +0 -12
  323. package/src/utils/validations/validators/status.validator.ts +0 -22
  324. package/tsconfig.build.json +0 -7
  325. package/tsconfig.json +0 -16
@@ -1,38 +1,2 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- const joi_1 = __importDefault(require("joi"));
7
- const jsonSchemaValidation = joi_1.default.object().unknown(true);
8
- const schemaObject = joi_1.default.object({
9
- type: joi_1.default.string().valid('object'),
10
- properties: joi_1.default.object({
11
- before: jsonSchemaValidation,
12
- after: jsonSchemaValidation,
13
- }).required(),
14
- required: joi_1.default.array().items(joi_1.default.string()),
15
- allOf: joi_1.default.array().items(joi_1.default.object()),
16
- anyOf: joi_1.default.array().items(joi_1.default.object()),
17
- oneOf: joi_1.default.array().items(joi_1.default.object()),
18
- additionalProperties: joi_1.default.alternatives().try(joi_1.default.boolean(), joi_1.default.object()),
19
- $id: joi_1.default.string(),
20
- $schema: joi_1.default.string(),
21
- if: joi_1.default.object(),
22
- then: joi_1.default.object(),
23
- else: joi_1.default.object(),
24
- });
25
- const validationSchemas = {
26
- create: joi_1.default.object({
27
- entityId: joi_1.default.string().uuid().required(),
28
- entityType: joi_1.default.string().required(),
29
- schema: schemaObject.required(),
30
- }),
31
- update: joi_1.default.object({
32
- entityId: joi_1.default.string().uuid(),
33
- entityType: joi_1.default.string(),
34
- schema: schemaObject,
35
- disabled: joi_1.default.boolean(),
36
- }).min(1),
37
- };
38
- exports.default = validationSchemas;
1
+ import e from"joi";const t=e.object().unknown(!0),n=e.object({type:e.string().valid(`object`),properties:e.object({before:t,after:t}).required(),required:e.array().items(e.string()),allOf:e.array().items(e.object()),anyOf:e.array().items(e.object()),oneOf:e.array().items(e.object()),additionalProperties:e.alternatives().try(e.boolean(),e.object()),$id:e.string(),$schema:e.string(),if:e.object(),then:e.object(),else:e.object()});var r={create:e.object({entityId:e.string().uuid().required(),entityType:e.string().required(),schema:n.required()}),update:e.object({entityId:e.string().uuid(),entityType:e.string(),schema:n,disabled:e.boolean()}).min(1)};export{r as default};
2
+ //# sourceMappingURL=validations.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"validations.js","names":["validationSchemas: ValidationSchemas"],"sources":["../../../../src/api/v1/validator/validations.ts"],"sourcesContent":["import Joi from 'joi';\n\nconst jsonSchemaValidation = Joi.object().unknown(true);\n\nexport interface SchemaObject {\n type: 'object';\n properties?: {\n before?: object;\n after?: object;\n };\n required?: string[];\n allOf?: object[];\n anyOf?: object[];\n oneOf?: object[];\n additionalProperties?: boolean | object;\n $id?: string;\n $schema?: string;\n if?: object;\n then?: object;\n else?: object;\n}\n\nconst schemaObject = Joi.object<SchemaObject>({\n type: Joi.string().valid('object'),\n properties: Joi.object({\n before: jsonSchemaValidation,\n after: jsonSchemaValidation,\n }).required(),\n required: Joi.array().items(Joi.string()),\n allOf: Joi.array().items(Joi.object()),\n anyOf: Joi.array().items(Joi.object()),\n oneOf: Joi.array().items(Joi.object()),\n additionalProperties: Joi.alternatives().try(Joi.boolean(), Joi.object()),\n $id: Joi.string(),\n $schema: Joi.string(),\n if: Joi.object(),\n then: Joi.object(),\n else: Joi.object(),\n});\n\nexport interface CreateValidatorPayload {\n entityId: string;\n entityType: string;\n schema: SchemaObject;\n}\n\nexport interface UpdateValidatorPayload extends Partial<CreateValidatorPayload> {\n disabled?: boolean;\n}\n\ninterface ValidationSchemas {\n create: Joi.ObjectSchema<CreateValidatorPayload>;\n update: Joi.ObjectSchema<UpdateValidatorPayload>;\n}\n\nconst validationSchemas: ValidationSchemas = {\n create: Joi.object<CreateValidatorPayload>({\n entityId: Joi.string().uuid().required(),\n entityType: Joi.string().required(),\n schema: schemaObject.required(),\n }),\n\n update: Joi.object<UpdateValidatorPayload>({\n entityId: Joi.string().uuid(),\n entityType: Joi.string(),\n schema: schemaObject,\n disabled: Joi.boolean(),\n }).min(1),\n};\n\nexport default validationSchemas;\n"],"mappings":"mBAEA,MAAM,EAAuB,EAAI,QAAQ,CAAC,QAAQ,GAAK,CAoBjD,EAAe,EAAI,OAAqB,CAC5C,KAAM,EAAI,QAAQ,CAAC,MAAM,SAAS,CAClC,WAAY,EAAI,OAAO,CACrB,OAAQ,EACR,MAAO,EACR,CAAC,CAAC,UAAU,CACb,SAAU,EAAI,OAAO,CAAC,MAAM,EAAI,QAAQ,CAAC,CACzC,MAAO,EAAI,OAAO,CAAC,MAAM,EAAI,QAAQ,CAAC,CACtC,MAAO,EAAI,OAAO,CAAC,MAAM,EAAI,QAAQ,CAAC,CACtC,MAAO,EAAI,OAAO,CAAC,MAAM,EAAI,QAAQ,CAAC,CACtC,qBAAsB,EAAI,cAAc,CAAC,IAAI,EAAI,SAAS,CAAE,EAAI,QAAQ,CAAC,CACzE,IAAK,EAAI,QAAQ,CACjB,QAAS,EAAI,QAAQ,CACrB,GAAI,EAAI,QAAQ,CAChB,KAAM,EAAI,QAAQ,CAClB,KAAM,EAAI,QAAQ,CACnB,CAAC,CAgCF,IAAA,EAf6C,CAC3C,OAAQ,EAAI,OAA+B,CACzC,SAAU,EAAI,QAAQ,CAAC,MAAM,CAAC,UAAU,CACxC,WAAY,EAAI,QAAQ,CAAC,UAAU,CACnC,OAAQ,EAAa,UAAU,CAChC,CAAC,CAEF,OAAQ,EAAI,OAA+B,CACzC,SAAU,EAAI,QAAQ,CAAC,MAAM,CAC7B,WAAY,EAAI,QAAQ,CACxB,OAAQ,EACR,SAAU,EAAI,SAAS,CACxB,CAAC,CAAC,IAAI,EAAE,CACV"}
@@ -0,0 +1,3 @@
1
+ const e=require(`../_virtual/rolldown_runtime.cjs`);let t=require(`@autofleet/errors`);t=e.__toESM(t);var n=class extends t.BadRequest{constructor(e){let t=Error(`The following custom fields are required: ${e.join(`,`)}`);super([t],null,e),this.message=`MISSING_REQUIRED_CUSTOM_FIELDS`}},r=class extends t.BadRequest{constructor(e){let t=Error(`Type "${e}" is not supported`);super([t],null,null),this.message=`UNSUPPORTED_CUSTOM_FIELD_TYPE`}},i=class extends t.BadRequest{constructor(e){let t=Error(`Validation for "${e}" is not supported`);super([t],null,null),this.message=`UNSUPPORTED_CUSTOM_VALIDATION_TYPE`}},a=class extends t.BadRequest{constructor(e){let t=Error(`Invalid field type ${e}`);super([t],null,null),this.message=`INVALID_FIELD_TYPE`}},o=class extends t.BadRequest{constructor(e,t,n){let r=n.message.replace(/"/g,``).replace(`value`,`'${t}'`),i=typeof e==`object`?JSON.stringify(e):e,a=`Invalid Value on field '${t}'. ${r}. received: '${i}'`;super([Error(a)],null,null),this.message=a}},s=class extends t.BadRequest{constructor(e,t){let n=t.map(e=>new o(e.value,e.fieldDefinitionName,e.joiValidationError));super(n,null,null),this.message=`Invalid entries on ${e}\n${t.map(e=>`${e.fieldDefinitionName} - ${e.joiValidationError.message}`).join(`
2
+ `)}`}},c=class extends t.BadRequest{constructor(e){let t=Error(`Missing custom field definition for field ${e.join(`,`)}`);super([t],null,null),this.message=`MISSING_DEFINITION`}};exports.InvalidEntriesError=s,exports.InvalidFieldTypeError=a,exports.InvalidValueError=o,exports.MissingDefinitionError=c,exports.MissingRequiredCustomFieldError=n,exports.UnsupportedCustomFieldTypeError=r,exports.UnsupportedCustomValidationError=i;
3
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.cjs","names":["BadRequest"],"sources":["../../src/errors/index.ts"],"sourcesContent":["/* eslint-disable max-classes-per-file */\nimport { BadRequest } from '@autofleet/errors';\nimport type { ValidationError } from 'joi';\nimport type { EntriesValidationError } from '../types/entries';\n\nexport class MissingRequiredCustomFieldError extends BadRequest {\n constructor(missingFields: string[]) {\n const err = new Error(`The following custom fields are required: ${missingFields.join(',')}`);\n super([err], null, missingFields);\n this.message = 'MISSING_REQUIRED_CUSTOM_FIELDS';\n }\n}\n\nexport class UnsupportedCustomFieldTypeError extends BadRequest {\n constructor(fieldType: string) {\n const err = new Error(`Type \"${fieldType}\" is not supported`);\n super([err], null, null);\n this.message = 'UNSUPPORTED_CUSTOM_FIELD_TYPE';\n }\n}\n\nexport class UnsupportedCustomValidationError extends BadRequest {\n constructor(fieldType: string) {\n const err = new Error(`Validation for \"${fieldType}\" is not supported`);\n super([err], null, null);\n this.message = 'UNSUPPORTED_CUSTOM_VALIDATION_TYPE';\n }\n}\n\nexport class InvalidFieldTypeError extends BadRequest {\n constructor(fieldType: string) {\n const err = new Error(`Invalid field type ${fieldType}`);\n super([err], null, null);\n this.message = 'INVALID_FIELD_TYPE';\n }\n}\n\nexport class InvalidValueError extends BadRequest {\n constructor(value: any, fieldDefinitionName: string, joiValidationError: ValidationError) {\n const formattedErrorMessage = joiValidationError.message\n .replace(/\"/g, '')\n .replace('value', `'${fieldDefinitionName}'`);\n\n const formattedValue = typeof value === 'object' ? JSON.stringify(value) : value;\n\n const invalidValueMessage = `Invalid Value on field '${fieldDefinitionName}'. ${formattedErrorMessage}. received: '${formattedValue}'`;\n\n const err = new Error(invalidValueMessage);\n super([err], null, null);\n this.message = invalidValueMessage;\n }\n}\n\nexport class InvalidEntriesError extends BadRequest {\n constructor(modelId: string, validationErrors: EntriesValidationError[]) {\n const errors = validationErrors.map((validationError) => new InvalidValueError(validationError.value, validationError.fieldDefinitionName, validationError.joiValidationError));\n super(errors, null, null);\n this.message = `Invalid entries on ${modelId}\\n${validationErrors.map((validationError) => (\n `${validationError.fieldDefinitionName} - ${validationError.joiValidationError.message}`\n )).join('\\n')}`;\n }\n}\n\nexport class MissingDefinitionError extends BadRequest {\n constructor(fieldNames: string[]) {\n const err = new Error(`Missing custom field definition for field ${fieldNames.join(',')}`);\n super([err], null, null);\n this.message = 'MISSING_DEFINITION';\n }\n}\n"],"mappings":"sGAKA,IAAa,EAAb,cAAqDA,EAAAA,UAAW,CAC9D,YAAY,EAAyB,CACnC,IAAM,EAAU,MAAM,6CAA6C,EAAc,KAAK,IAAI,GAAG,CAC7F,MAAM,CAAC,EAAI,CAAE,KAAM,EAAc,CACjC,KAAK,QAAU,mCAIN,EAAb,cAAqDA,EAAAA,UAAW,CAC9D,YAAY,EAAmB,CAC7B,IAAM,EAAU,MAAM,SAAS,EAAU,oBAAoB,CAC7D,MAAM,CAAC,EAAI,CAAE,KAAM,KAAK,CACxB,KAAK,QAAU,kCAIN,EAAb,cAAsDA,EAAAA,UAAW,CAC/D,YAAY,EAAmB,CAC7B,IAAM,EAAU,MAAM,mBAAmB,EAAU,oBAAoB,CACvE,MAAM,CAAC,EAAI,CAAE,KAAM,KAAK,CACxB,KAAK,QAAU,uCAIN,EAAb,cAA2CA,EAAAA,UAAW,CACpD,YAAY,EAAmB,CAC7B,IAAM,EAAU,MAAM,sBAAsB,IAAY,CACxD,MAAM,CAAC,EAAI,CAAE,KAAM,KAAK,CACxB,KAAK,QAAU,uBAIN,EAAb,cAAuCA,EAAAA,UAAW,CAChD,YAAY,EAAY,EAA6B,EAAqC,CACxF,IAAM,EAAwB,EAAmB,QAC9C,QAAQ,KAAM,GAAG,CACjB,QAAQ,QAAS,IAAI,EAAoB,GAAG,CAEzC,EAAiB,OAAO,GAAU,SAAW,KAAK,UAAU,EAAM,CAAG,EAErE,EAAsB,2BAA2B,EAAoB,KAAK,EAAsB,eAAe,EAAe,GAGpI,MAAM,CADU,MAAM,EAAoB,CAC/B,CAAE,KAAM,KAAK,CACxB,KAAK,QAAU,IAIN,EAAb,cAAyCA,EAAAA,UAAW,CAClD,YAAY,EAAiB,EAA4C,CACvE,IAAM,EAAS,EAAiB,IAAK,GAAoB,IAAI,EAAkB,EAAgB,MAAO,EAAgB,oBAAqB,EAAgB,mBAAmB,CAAC,CAC/K,MAAM,EAAQ,KAAM,KAAK,CACzB,KAAK,QAAU,sBAAsB,EAAQ,IAAI,EAAiB,IAAK,GACrE,GAAG,EAAgB,oBAAoB,KAAK,EAAgB,mBAAmB,UAC/E,CAAC,KAAK;EAAK,KAIJ,EAAb,cAA4CA,EAAAA,UAAW,CACrD,YAAY,EAAsB,CAChC,IAAM,EAAU,MAAM,6CAA6C,EAAW,KAAK,IAAI,GAAG,CAC1F,MAAM,CAAC,EAAI,CAAE,KAAM,KAAK,CACxB,KAAK,QAAU"}
@@ -1,66 +1,3 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.MissingDefinitionError = exports.InvalidEntriesError = exports.InvalidValueError = exports.InvalidFieldTypeError = exports.UnsupportedCustomValidationError = exports.UnsupportedCustomFieldTypeError = exports.MissingRequiredCustomFieldError = void 0;
4
- /* eslint-disable max-classes-per-file */
5
- const errors_1 = require("@autofleet/errors");
6
- class MissingRequiredCustomFieldError extends errors_1.BadRequest {
7
- constructor(missingFields) {
8
- const err = new Error(`The following custom fields are required: ${missingFields.join(',')}`);
9
- super([err], null, missingFields);
10
- this.message = 'MISSING_REQUIRED_CUSTOM_FIELDS';
11
- }
12
- }
13
- exports.MissingRequiredCustomFieldError = MissingRequiredCustomFieldError;
14
- class UnsupportedCustomFieldTypeError extends errors_1.BadRequest {
15
- constructor(fieldType) {
16
- const err = new Error(`Type "${fieldType}" is not supported`);
17
- super([err], null, null);
18
- this.message = 'UNSUPPORTED_CUSTOM_FIELD_TYPE';
19
- }
20
- }
21
- exports.UnsupportedCustomFieldTypeError = UnsupportedCustomFieldTypeError;
22
- class UnsupportedCustomValidationError extends errors_1.BadRequest {
23
- constructor(fieldType) {
24
- const err = new Error(`Validation for "${fieldType}" is not supported`);
25
- super([err], null, null);
26
- this.message = 'UNSUPPORTED_CUSTOM_VALIDATION_TYPE';
27
- }
28
- }
29
- exports.UnsupportedCustomValidationError = UnsupportedCustomValidationError;
30
- class InvalidFieldTypeError extends errors_1.BadRequest {
31
- constructor(fieldType) {
32
- const err = new Error(`Invalid field type ${fieldType}`);
33
- super([err], null, null);
34
- this.message = 'INVALID_FIELD_TYPE';
35
- }
36
- }
37
- exports.InvalidFieldTypeError = InvalidFieldTypeError;
38
- class InvalidValueError extends errors_1.BadRequest {
39
- constructor(value, fieldDefinitionName, joiValidationError) {
40
- const formattedErrorMessage = joiValidationError.message
41
- .replace(/"/g, '')
42
- .replace('value', `'${fieldDefinitionName}'`);
43
- const formattedValue = typeof value === 'object' ? JSON.stringify(value) : value;
44
- const invalidValueMessage = `Invalid Value on field '${fieldDefinitionName}'. ${formattedErrorMessage}. received: '${formattedValue}'`;
45
- const err = new Error(invalidValueMessage);
46
- super([err], null, null);
47
- this.message = invalidValueMessage;
48
- }
49
- }
50
- exports.InvalidValueError = InvalidValueError;
51
- class InvalidEntriesError extends errors_1.BadRequest {
52
- constructor(modelId, validationErrors) {
53
- const errors = validationErrors.map((validationError) => new InvalidValueError(validationError.value, validationError.fieldDefinitionName, validationError.joiValidationError));
54
- super(errors, null, null);
55
- this.message = `Invalid entries on ${modelId}\n${validationErrors.map((validationError) => (`${validationError.fieldDefinitionName} - ${validationError.joiValidationError.message}`)).join('\n')}`;
56
- }
57
- }
58
- exports.InvalidEntriesError = InvalidEntriesError;
59
- class MissingDefinitionError extends errors_1.BadRequest {
60
- constructor(fieldNames) {
61
- const err = new Error(`Missing custom field definition for field ${fieldNames.join(',')}`);
62
- super([err], null, null);
63
- this.message = 'MISSING_DEFINITION';
64
- }
65
- }
66
- exports.MissingDefinitionError = MissingDefinitionError;
1
+ import{BadRequest as e}from"@autofleet/errors";var t=class extends e{constructor(e){let t=Error(`The following custom fields are required: ${e.join(`,`)}`);super([t],null,e),this.message=`MISSING_REQUIRED_CUSTOM_FIELDS`}},n=class extends e{constructor(e){let t=Error(`Type "${e}" is not supported`);super([t],null,null),this.message=`UNSUPPORTED_CUSTOM_FIELD_TYPE`}},r=class extends e{constructor(e){let t=Error(`Validation for "${e}" is not supported`);super([t],null,null),this.message=`UNSUPPORTED_CUSTOM_VALIDATION_TYPE`}},i=class extends e{constructor(e){let t=Error(`Invalid field type ${e}`);super([t],null,null),this.message=`INVALID_FIELD_TYPE`}},a=class extends e{constructor(e,t,n){let r=n.message.replace(/"/g,``).replace(`value`,`'${t}'`),i=typeof e==`object`?JSON.stringify(e):e,a=`Invalid Value on field '${t}'. ${r}. received: '${i}'`;super([Error(a)],null,null),this.message=a}},o=class extends e{constructor(e,t){let n=t.map(e=>new a(e.value,e.fieldDefinitionName,e.joiValidationError));super(n,null,null),this.message=`Invalid entries on ${e}\n${t.map(e=>`${e.fieldDefinitionName} - ${e.joiValidationError.message}`).join(`
2
+ `)}`}},s=class extends e{constructor(e){let t=Error(`Missing custom field definition for field ${e.join(`,`)}`);super([t],null,null),this.message=`MISSING_DEFINITION`}};export{o as InvalidEntriesError,i as InvalidFieldTypeError,a as InvalidValueError,s as MissingDefinitionError,t as MissingRequiredCustomFieldError,n as UnsupportedCustomFieldTypeError,r as UnsupportedCustomValidationError};
3
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../src/errors/index.ts"],"sourcesContent":["/* eslint-disable max-classes-per-file */\nimport { BadRequest } from '@autofleet/errors';\nimport type { ValidationError } from 'joi';\nimport type { EntriesValidationError } from '../types/entries';\n\nexport class MissingRequiredCustomFieldError extends BadRequest {\n constructor(missingFields: string[]) {\n const err = new Error(`The following custom fields are required: ${missingFields.join(',')}`);\n super([err], null, missingFields);\n this.message = 'MISSING_REQUIRED_CUSTOM_FIELDS';\n }\n}\n\nexport class UnsupportedCustomFieldTypeError extends BadRequest {\n constructor(fieldType: string) {\n const err = new Error(`Type \"${fieldType}\" is not supported`);\n super([err], null, null);\n this.message = 'UNSUPPORTED_CUSTOM_FIELD_TYPE';\n }\n}\n\nexport class UnsupportedCustomValidationError extends BadRequest {\n constructor(fieldType: string) {\n const err = new Error(`Validation for \"${fieldType}\" is not supported`);\n super([err], null, null);\n this.message = 'UNSUPPORTED_CUSTOM_VALIDATION_TYPE';\n }\n}\n\nexport class InvalidFieldTypeError extends BadRequest {\n constructor(fieldType: string) {\n const err = new Error(`Invalid field type ${fieldType}`);\n super([err], null, null);\n this.message = 'INVALID_FIELD_TYPE';\n }\n}\n\nexport class InvalidValueError extends BadRequest {\n constructor(value: any, fieldDefinitionName: string, joiValidationError: ValidationError) {\n const formattedErrorMessage = joiValidationError.message\n .replace(/\"/g, '')\n .replace('value', `'${fieldDefinitionName}'`);\n\n const formattedValue = typeof value === 'object' ? JSON.stringify(value) : value;\n\n const invalidValueMessage = `Invalid Value on field '${fieldDefinitionName}'. ${formattedErrorMessage}. received: '${formattedValue}'`;\n\n const err = new Error(invalidValueMessage);\n super([err], null, null);\n this.message = invalidValueMessage;\n }\n}\n\nexport class InvalidEntriesError extends BadRequest {\n constructor(modelId: string, validationErrors: EntriesValidationError[]) {\n const errors = validationErrors.map((validationError) => new InvalidValueError(validationError.value, validationError.fieldDefinitionName, validationError.joiValidationError));\n super(errors, null, null);\n this.message = `Invalid entries on ${modelId}\\n${validationErrors.map((validationError) => (\n `${validationError.fieldDefinitionName} - ${validationError.joiValidationError.message}`\n )).join('\\n')}`;\n }\n}\n\nexport class MissingDefinitionError extends BadRequest {\n constructor(fieldNames: string[]) {\n const err = new Error(`Missing custom field definition for field ${fieldNames.join(',')}`);\n super([err], null, null);\n this.message = 'MISSING_DEFINITION';\n }\n}\n"],"mappings":"+CAKA,IAAa,EAAb,cAAqD,CAAW,CAC9D,YAAY,EAAyB,CACnC,IAAM,EAAU,MAAM,6CAA6C,EAAc,KAAK,IAAI,GAAG,CAC7F,MAAM,CAAC,EAAI,CAAE,KAAM,EAAc,CACjC,KAAK,QAAU,mCAIN,EAAb,cAAqD,CAAW,CAC9D,YAAY,EAAmB,CAC7B,IAAM,EAAU,MAAM,SAAS,EAAU,oBAAoB,CAC7D,MAAM,CAAC,EAAI,CAAE,KAAM,KAAK,CACxB,KAAK,QAAU,kCAIN,EAAb,cAAsD,CAAW,CAC/D,YAAY,EAAmB,CAC7B,IAAM,EAAU,MAAM,mBAAmB,EAAU,oBAAoB,CACvE,MAAM,CAAC,EAAI,CAAE,KAAM,KAAK,CACxB,KAAK,QAAU,uCAIN,EAAb,cAA2C,CAAW,CACpD,YAAY,EAAmB,CAC7B,IAAM,EAAU,MAAM,sBAAsB,IAAY,CACxD,MAAM,CAAC,EAAI,CAAE,KAAM,KAAK,CACxB,KAAK,QAAU,uBAIN,EAAb,cAAuC,CAAW,CAChD,YAAY,EAAY,EAA6B,EAAqC,CACxF,IAAM,EAAwB,EAAmB,QAC9C,QAAQ,KAAM,GAAG,CACjB,QAAQ,QAAS,IAAI,EAAoB,GAAG,CAEzC,EAAiB,OAAO,GAAU,SAAW,KAAK,UAAU,EAAM,CAAG,EAErE,EAAsB,2BAA2B,EAAoB,KAAK,EAAsB,eAAe,EAAe,GAGpI,MAAM,CADU,MAAM,EAAoB,CAC/B,CAAE,KAAM,KAAK,CACxB,KAAK,QAAU,IAIN,EAAb,cAAyC,CAAW,CAClD,YAAY,EAAiB,EAA4C,CACvE,IAAM,EAAS,EAAiB,IAAK,GAAoB,IAAI,EAAkB,EAAgB,MAAO,EAAgB,oBAAqB,EAAgB,mBAAmB,CAAC,CAC/K,MAAM,EAAQ,KAAM,KAAK,CACzB,KAAK,QAAU,sBAAsB,EAAQ,IAAI,EAAiB,IAAK,GACrE,GAAG,EAAgB,oBAAoB,KAAK,EAAgB,mBAAmB,UAC/E,CAAC,KAAK;EAAK,KAIJ,EAAb,cAA4C,CAAW,CACrD,YAAY,EAAsB,CAChC,IAAM,EAAU,MAAM,6CAA6C,EAAW,KAAK,IAAI,GAAG,CAC1F,MAAM,CAAC,EAAI,CAAE,KAAM,KAAK,CACxB,KAAK,QAAU"}
@@ -0,0 +1,2 @@
1
+ const e=require(`../_virtual/rolldown_runtime.cjs`),t=require(`../utils/logger/index.cjs`);let n=require(`@autofleet/events`);n=e.__toESM(n);let r=require(`@autofleet/zehut`);r=e.__toESM(r);const i=new n.default({logger:t.default,getUserId:e=>e?.user_id??(0,r.getUser)()?.id??null}),a=[`value`,`defaultValue`,`blockEditingFromUI`],o=(e,t)=>{let n=new Set(Object.keys(e));return t.every(e=>!n.has(e))?e:{...e,...Object.fromEntries(t.map(t=>[t,typeof e[t]==`boolean`?e[t].toString():e[t]]))}},s={CustomFieldDefinition:{tableName:`dim_custom_field_definition`,eventVersion:`1`},CustomFieldValue:{tableName:`dim_custom_field_value`,eventVersion:`1`},CustomFieldEntries:{tableName:`dim_custom_field_entries`,eventVersion:`1`}},c=e=>{let n=s[e.constructor.name];if(!n)return;let r=e.get();try{r=o(e.get(),a)}catch(e){t.default.error(`Failed to convert booleans in dim event payload`,e)}i.sendObject(n.tableName,n.eventVersion,r).catch(()=>{})};exports.sendDimEvent=c;
2
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.cjs","names":["events: Events","Events"],"sources":["../../src/events/index.ts"],"sourcesContent":["import Events from '@autofleet/events';\nimport { getUser } from '@autofleet/zehut';\nimport logger from '../utils/logger';\nimport type {\n CustomFieldDefinition,\n CustomFieldEntries,\n CustomFieldValue,\n CustomValidator,\n} from '../models';\n\nconst events: Events = new Events({\n logger,\n getUserId: (payload) => payload?.user_id ?? getUser()?.id ?? null,\n});\n\nconst KEYS_TO_CONVERT = ['value', 'defaultValue', 'blockEditingFromUI'];\n\nconst stringifyBooleans = (savedObject: any, keysToConvert: string[]) => {\n const savedObjectKeySet = new Set(Object.keys(savedObject));\n if (keysToConvert.every((key) => !savedObjectKeySet.has(key))) {\n return savedObject;\n }\n return {\n ...savedObject,\n ...Object.fromEntries(keysToConvert.map((key) => [key, typeof savedObject[key] === 'boolean' ? savedObject[key].toString() : savedObject[key]])),\n };\n};\n\nconst modelTableMapping = {\n CustomFieldDefinition: {\n tableName: 'dim_custom_field_definition',\n eventVersion: '1',\n },\n CustomFieldValue: {\n tableName: 'dim_custom_field_value',\n eventVersion: '1',\n },\n CustomFieldEntries: {\n tableName: 'dim_custom_field_entries',\n eventVersion: '1',\n },\n};\n\nexport const sendDimEvent = (instance: CustomFieldDefinition | CustomFieldValue | CustomFieldEntries | CustomValidator): void => {\n const mapping = modelTableMapping[instance.constructor.name];\n if (!mapping) {\n return;\n }\n let objectToSend = instance.get();\n try {\n objectToSend = stringifyBooleans(instance.get(), KEYS_TO_CONVERT);\n } catch (err) {\n logger.error('Failed to convert booleans in dim event payload', err);\n }\n\n events.sendObject(\n mapping.tableName,\n mapping.eventVersion,\n objectToSend,\n ).catch(() => {});\n};\n\nexport default events;\n"],"mappings":"8LAUA,MAAMA,EAAiB,IAAIC,EAAAA,QAAO,CAChC,OAAA,EAAA,QACA,UAAY,GAAY,GAAS,UAAA,EAAA,EAAA,UAAoB,EAAE,IAAM,KAC9D,CAAC,CAEI,EAAkB,CAAC,QAAS,eAAgB,qBAAqB,CAEjE,GAAqB,EAAkB,IAA4B,CACvE,IAAM,EAAoB,IAAI,IAAI,OAAO,KAAK,EAAY,CAAC,CAI3D,OAHI,EAAc,MAAO,GAAQ,CAAC,EAAkB,IAAI,EAAI,CAAC,CACpD,EAEF,CACL,GAAG,EACH,GAAG,OAAO,YAAY,EAAc,IAAK,GAAQ,CAAC,EAAK,OAAO,EAAY,IAAS,UAAY,EAAY,GAAK,UAAU,CAAG,EAAY,GAAK,CAAC,CAAC,CACjJ,EAGG,EAAoB,CACxB,sBAAuB,CACrB,UAAW,8BACX,aAAc,IACf,CACD,iBAAkB,CAChB,UAAW,yBACX,aAAc,IACf,CACD,mBAAoB,CAClB,UAAW,2BACX,aAAc,IACf,CACF,CAEY,EAAgB,GAAoG,CAC/H,IAAM,EAAU,EAAkB,EAAS,YAAY,MACvD,GAAI,CAAC,EACH,OAEF,IAAI,EAAe,EAAS,KAAK,CACjC,GAAI,CACF,EAAe,EAAkB,EAAS,KAAK,CAAE,EAAgB,OAC1D,EAAK,CACZ,EAAA,QAAO,MAAM,kDAAmD,EAAI,CAGtE,EAAO,WACL,EAAQ,UACR,EAAQ,aACR,EACD,CAAC,UAAY,GAAG"}
@@ -1,54 +1,2 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.sendDimEvent = void 0;
7
- const events_1 = __importDefault(require("@autofleet/events"));
8
- const zehut_1 = require("@autofleet/zehut");
9
- const logger_1 = __importDefault(require("../utils/logger"));
10
- const events = new events_1.default({
11
- logger: logger_1.default,
12
- getUserId: (payload) => payload?.user_id ?? (0, zehut_1.getUser)()?.id ?? null,
13
- });
14
- const KEYS_TO_CONVERT = ['value', 'defaultValue', 'blockEditingFromUI'];
15
- const stringifyBooleans = (savedObject, keysToConvert) => {
16
- const savedObjectKeySet = new Set(Object.keys(savedObject));
17
- if (keysToConvert.every((key) => !savedObjectKeySet.has(key))) {
18
- return savedObject;
19
- }
20
- return {
21
- ...savedObject,
22
- ...Object.fromEntries(keysToConvert.map((key) => [key, typeof savedObject[key] === 'boolean' ? savedObject[key].toString() : savedObject[key]])),
23
- };
24
- };
25
- const modelTableMapping = {
26
- CustomFieldDefinition: {
27
- tableName: 'dim_custom_field_definition',
28
- eventVersion: '1',
29
- },
30
- CustomFieldValue: {
31
- tableName: 'dim_custom_field_value',
32
- eventVersion: '1',
33
- },
34
- CustomFieldEntries: {
35
- tableName: 'dim_custom_field_entries',
36
- eventVersion: '1',
37
- },
38
- };
39
- const sendDimEvent = (instance) => {
40
- const mapping = modelTableMapping[instance.constructor.name];
41
- if (!mapping) {
42
- return;
43
- }
44
- let objectToSend = instance.get();
45
- try {
46
- objectToSend = stringifyBooleans(instance.get(), KEYS_TO_CONVERT);
47
- }
48
- catch (err) {
49
- logger_1.default.error('Failed to convert booleans in dim event payload', err);
50
- }
51
- events.sendObject(mapping.tableName, mapping.eventVersion, objectToSend).catch(() => { });
52
- };
53
- exports.sendDimEvent = sendDimEvent;
54
- exports.default = events;
1
+ import e from"../utils/logger/index.js";import t from"@autofleet/events";import{getUser as n}from"@autofleet/zehut";const r=new t({logger:e,getUserId:e=>e?.user_id??n()?.id??null}),i=[`value`,`defaultValue`,`blockEditingFromUI`],a=(e,t)=>{let n=new Set(Object.keys(e));return t.every(e=>!n.has(e))?e:{...e,...Object.fromEntries(t.map(t=>[t,typeof e[t]==`boolean`?e[t].toString():e[t]]))}},o={CustomFieldDefinition:{tableName:`dim_custom_field_definition`,eventVersion:`1`},CustomFieldValue:{tableName:`dim_custom_field_value`,eventVersion:`1`},CustomFieldEntries:{tableName:`dim_custom_field_entries`,eventVersion:`1`}},s=t=>{let n=o[t.constructor.name];if(!n)return;let s=t.get();try{s=a(t.get(),i)}catch(t){e.error(`Failed to convert booleans in dim event payload`,t)}r.sendObject(n.tableName,n.eventVersion,s).catch(()=>{})};export{s as sendDimEvent};
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":["events: Events"],"sources":["../../src/events/index.ts"],"sourcesContent":["import Events from '@autofleet/events';\nimport { getUser } from '@autofleet/zehut';\nimport logger from '../utils/logger';\nimport type {\n CustomFieldDefinition,\n CustomFieldEntries,\n CustomFieldValue,\n CustomValidator,\n} from '../models';\n\nconst events: Events = new Events({\n logger,\n getUserId: (payload) => payload?.user_id ?? getUser()?.id ?? null,\n});\n\nconst KEYS_TO_CONVERT = ['value', 'defaultValue', 'blockEditingFromUI'];\n\nconst stringifyBooleans = (savedObject: any, keysToConvert: string[]) => {\n const savedObjectKeySet = new Set(Object.keys(savedObject));\n if (keysToConvert.every((key) => !savedObjectKeySet.has(key))) {\n return savedObject;\n }\n return {\n ...savedObject,\n ...Object.fromEntries(keysToConvert.map((key) => [key, typeof savedObject[key] === 'boolean' ? savedObject[key].toString() : savedObject[key]])),\n };\n};\n\nconst modelTableMapping = {\n CustomFieldDefinition: {\n tableName: 'dim_custom_field_definition',\n eventVersion: '1',\n },\n CustomFieldValue: {\n tableName: 'dim_custom_field_value',\n eventVersion: '1',\n },\n CustomFieldEntries: {\n tableName: 'dim_custom_field_entries',\n eventVersion: '1',\n },\n};\n\nexport const sendDimEvent = (instance: CustomFieldDefinition | CustomFieldValue | CustomFieldEntries | CustomValidator): void => {\n const mapping = modelTableMapping[instance.constructor.name];\n if (!mapping) {\n return;\n }\n let objectToSend = instance.get();\n try {\n objectToSend = stringifyBooleans(instance.get(), KEYS_TO_CONVERT);\n } catch (err) {\n logger.error('Failed to convert booleans in dim event payload', err);\n }\n\n events.sendObject(\n mapping.tableName,\n mapping.eventVersion,\n objectToSend,\n ).catch(() => {});\n};\n\nexport default events;\n"],"mappings":"oHAUA,MAAMA,EAAiB,IAAI,EAAO,CAChC,OAAA,EACA,UAAY,GAAY,GAAS,SAAW,GAAS,EAAE,IAAM,KAC9D,CAAC,CAEI,EAAkB,CAAC,QAAS,eAAgB,qBAAqB,CAEjE,GAAqB,EAAkB,IAA4B,CACvE,IAAM,EAAoB,IAAI,IAAI,OAAO,KAAK,EAAY,CAAC,CAI3D,OAHI,EAAc,MAAO,GAAQ,CAAC,EAAkB,IAAI,EAAI,CAAC,CACpD,EAEF,CACL,GAAG,EACH,GAAG,OAAO,YAAY,EAAc,IAAK,GAAQ,CAAC,EAAK,OAAO,EAAY,IAAS,UAAY,EAAY,GAAK,UAAU,CAAG,EAAY,GAAK,CAAC,CAAC,CACjJ,EAGG,EAAoB,CACxB,sBAAuB,CACrB,UAAW,8BACX,aAAc,IACf,CACD,iBAAkB,CAChB,UAAW,yBACX,aAAc,IACf,CACD,mBAAoB,CAClB,UAAW,2BACX,aAAc,IACf,CACF,CAEY,EAAgB,GAAoG,CAC/H,IAAM,EAAU,EAAkB,EAAS,YAAY,MACvD,GAAI,CAAC,EACH,OAEF,IAAI,EAAe,EAAS,KAAK,CACjC,GAAI,CACF,EAAe,EAAkB,EAAS,KAAK,CAAE,EAAgB,OAC1D,EAAK,CACZ,EAAO,MAAM,kDAAmD,EAAI,CAGtE,EAAO,WACL,EAAQ,UACR,EAAQ,aACR,EACD,CAAC,UAAY,GAAG"}
@@ -0,0 +1,2 @@
1
+ const e=require(`../repository/definition.cjs`),t=require(`../repository/value.cjs`),n=require(`../repository/entries.cjs`),r=require(`../utils/scopeAttributes.cjs`),i=[`id`,`name`,`entityId`,`fieldType`,`displayName`,`validation`,`entityType`,`modelType`,`required`,`disabled`,`defaultValue`],a=async({instancesIds:e,options:t,sadotOptions:r})=>{if(!r.useCustomFieldsEntries)return{};let i=await n.findEntriesByModelIds(e,t??{}),a=Object.fromEntries(i.map(e=>{let{modelId:t,customFields:n}=e?.dataValues??{};if(t)return[t,n]}).filter(Boolean));return e.forEach(e=>{a[e]??={}}),a},o=async({instancesIds:e,options:n,sadotOptions:r})=>r.useCustomFieldsEntries?{}:(await t.findValuesByModelIds(e,n??{})).reduce((e,t)=>{let{modelId:n}=t;return e[n]??=[],e[n].push(t),e},{}),s=(e,t)=>e.reduce((e,n)=>({...e,...t[n.customFieldDefinitionId]&&{[t[n.customFieldDefinitionId].name]:n.value}}),{}),c=(t,n,c,l={},u={useCustomFieldsEntries:!1})=>async(d,f)=>{if(f.originalAttributes?.length>0&&!f.originalAttributes?.includes?.(`customFields`))return;let p=Array.isArray(d)?d:[d];p=p.filter(Boolean);let m=r.default(p,n),h=[...new Set(m)].filter(Boolean),g=h.reduce((e,t)=>({...e,[t]:[]}),{}),_,v;f.transaction&&(f.transaction.definitionCache||=new Map,v=`${t}:${h.slice().sort().join(`,`)}`,_=f.transaction.definitionCache.get(v)),_||(_=e.findByEntityIds(t,h,{transaction:f.transaction,modelOptions:l,attributes:i}),f.transaction?.definitionCache?.set(v,_));let y=await _;if(y.length===0){p.forEach(e=>{e.customFields={}});return}l?.include&&l.useEntityIdFromInclude&&l.include(m).forEach(({model:e})=>{y.forEach(t=>{let n=t[`${e.name}.entityId`];g[n]=[]})});let b=y.reduce((e,t)=>({...e,[t.id]:t}),{});y.forEach(e=>{g[e.entityId].push(e)});let x=p.map(e=>e.id),[S,C]=await Promise.all([o({instancesIds:x,options:f,sadotOptions:u}),a({instancesIds:x,options:f,sadotOptions:u})]);p.forEach(e=>{let{id:t}=e,r=S[t],i=r?s(r,b):{},a=u.useCustomFieldsEntries?C[t]:i;n.forEach(t=>{let n=e[t],r=g[n];r?.length>0&&r.forEach(e=>{a[e.name]===void 0&&(a[e.name]=null)})}),e.customFields=a,f.attributesToRemove?.forEach?.(t=>{delete e.dataValues?.[t],delete e?.[t]}),c===`afterFind`&&e?.changed?.(`customFields`,!1)})};var l=c;exports.default=l;
2
+ //# sourceMappingURL=enrich.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"enrich.cjs","names":["applyScopeToInstance"],"sources":["../../src/hooks/enrich.ts"],"sourcesContent":["/* eslint-disable no-param-reassign */\nimport * as ValueRepo from '../repository/value';\nimport * as DefinitionRepo from '../repository/definition';\nimport * as EntriesRepo from '../repository/entries';\nimport type CustomFieldValue from '../models/CustomFieldValue';\nimport type CustomFieldDefinition from '../models/CustomFieldDefinition';\nimport type { SerializedCustomFields } from '../types/definition';\nimport type { CustomFieldOptions, ModelOptions, TransactionOptions } from '../types';\nimport applyScopeToInstance from '../utils/scopeAttributes';\n\n// Include all required fields for proper functioning\nconst CUSTOM_FIELD_DEFINITION_ATTRIBUTES_TO_PULL = [\n 'id',\n 'name',\n 'entityId',\n 'fieldType',\n 'displayName',\n 'validation',\n 'entityType',\n 'modelType',\n 'required',\n 'disabled',\n 'defaultValue',\n];\n\ntype SupportedHookTypes = 'afterFind' | 'afterCreate' | 'afterUpdate';\n\ntype CustomFieldEntries = Record<string, any>;\n\ninterface GetValuesGroupByInstanceResponse {\n [modelId: string]: CustomFieldValue[];\n}\n\ninterface GetCustomFieldEntriesByInstanceIdResponse {\n [modelId: string]: CustomFieldEntries;\n}\n\nexport const getCustomFieldEntriesByInstanceId = async ({\n instancesIds,\n options,\n sadotOptions,\n}: {\n instancesIds: string[],\n options?: TransactionOptions,\n sadotOptions: Pick<CustomFieldOptions, 'useCustomFieldsEntries'>,\n}): Promise<GetCustomFieldEntriesByInstanceIdResponse> => {\n if (!sadotOptions.useCustomFieldsEntries) {\n return {};\n }\n\n const customFieldEntries = await EntriesRepo.findEntriesByModelIds(\n instancesIds,\n options ?? {},\n );\n\n const customFieldEntriesByInstanceId = Object.fromEntries(customFieldEntries.map((instanceEntries) => {\n const { modelId, customFields } = instanceEntries?.dataValues ?? {};\n if (!modelId) {\n return undefined;\n }\n return [modelId, customFields];\n }).filter(Boolean));\n\n instancesIds.forEach((instanceId) => {\n customFieldEntriesByInstanceId[instanceId] ??= {};\n });\n\n return customFieldEntriesByInstanceId;\n};\n\nexport const getValuesGroupByInstance = async ({\n instancesIds,\n options,\n sadotOptions,\n}: {\n instancesIds: string[],\n options?: TransactionOptions,\n sadotOptions: Pick<CustomFieldOptions, 'useCustomFieldsEntries'>,\n}): Promise<GetValuesGroupByInstanceResponse> => {\n if (sadotOptions.useCustomFieldsEntries) {\n return {};\n }\n\n const customFieldValues = await ValueRepo.findValuesByModelIds(\n instancesIds,\n options ?? {},\n );\n\n // Group fields by modelId\n return customFieldValues.reduce((acc, v) => {\n const { modelId } = v;\n acc[modelId] ??= [];\n acc[modelId].push(v);\n return acc;\n }, {});\n};\n\n/**\n * Serialize custom fields value into the format of {[name] -> [fieldData]}\n */\nconst serializeCustomFields = (\n customFieldValues: CustomFieldValue[],\n customFieldDefinitionsHash: Record<string, CustomFieldDefinition>,\n): SerializedCustomFields => {\n const customFields = customFieldValues.reduce((acc, cfv) => ({\n ...acc,\n ...(\n customFieldDefinitionsHash[cfv.customFieldDefinitionId]\n && { [customFieldDefinitionsHash[cfv.customFieldDefinitionId].name]: cfv.value }\n ),\n }), {});\n return customFields;\n};\n/**\n * A hook to attach the custom fields when fetching a model instances.\n */\nconst enrichResults = (\n modelType: string,\n scopeAttributes: string[],\n hookType?: SupportedHookTypes,\n modelOptions: ModelOptions = {},\n sadotOptions: Pick<CustomFieldOptions, 'useCustomFieldsEntries'> = { useCustomFieldsEntries: false },\n) => async (\n instancesOrInstance: any | any[],\n options: TransactionOptions,\n): Promise<void> => {\n if (\n options.originalAttributes?.length > 0\n && !options.originalAttributes?.includes?.('customFields')\n ) {\n return;\n }\n\n const primaryKey = 'id';\n let instances = Array.isArray(instancesOrInstance)\n ? instancesOrInstance\n : [instancesOrInstance];\n\n instances = instances.filter(Boolean);\n\n const identifiers = applyScopeToInstance(instances, scopeAttributes);\n\n const uniqueIdentifiers = [...new Set(identifiers)].filter(Boolean);\n\n const identifierCustomFieldDefinitionsMapping = uniqueIdentifiers.reduce((map, identifier) => ({\n ...map,\n [identifier]: [],\n }), {});\n\n // Cache for definitions by model type and transaction to avoid redundant DB queries\n let customFieldDefinitionsPromise;\n let cacheKey;\n\n if (options.transaction) {\n // Initialize definition cache Map if not already present directly on the transaction object\n options.transaction.definitionCache ||= new Map();\n cacheKey = `${modelType}:${uniqueIdentifiers.slice().sort().join(',')}`;\n customFieldDefinitionsPromise = options.transaction.definitionCache.get(cacheKey);\n }\n\n if (!customFieldDefinitionsPromise) {\n // Fetch from database (either first time in this transaction or no transaction)\n customFieldDefinitionsPromise = DefinitionRepo.findByEntityIds(\n modelType,\n uniqueIdentifiers,\n { transaction: options.transaction, modelOptions, attributes: CUSTOM_FIELD_DEFINITION_ATTRIBUTES_TO_PULL },\n );\n\n options.transaction?.definitionCache?.set(cacheKey, customFieldDefinitionsPromise);\n }\n const customFieldDefinitions = await customFieldDefinitionsPromise;\n\n if (customFieldDefinitions.length === 0) {\n // if no custom fields, we can return\n instances.forEach((instance) => {\n instance.customFields = {};\n });\n return;\n }\n\n if (modelOptions?.include && modelOptions.useEntityIdFromInclude) {\n // if we pass useEntityIdFromInclude,\n // map the entity from the options to the identifierCustomFieldDefinitionsMapping\n modelOptions.include(identifiers).forEach(({ model }) => {\n customFieldDefinitions.forEach((cfd) => {\n const entityId = cfd[`${model.name}.entityId`];\n identifierCustomFieldDefinitionsMapping[entityId] = [];\n });\n });\n }\n\n const definitionsMap = customFieldDefinitions.reduce((map, definition) => ({\n ...map,\n [definition.id]: definition,\n }), {});\n\n customFieldDefinitions.forEach((cfd) => {\n identifierCustomFieldDefinitionsMapping[cfd.entityId].push(cfd);\n });\n\n // Get the values per instates ids:\n const instancesIds = instances.map((i) => i[primaryKey]);\n\n // Group fields by modelId\n const [valuesGroupByInstance, customFieldEntriesByInstanceId] = await Promise.all([\n getValuesGroupByInstance({\n instancesIds,\n options,\n sadotOptions,\n }),\n getCustomFieldEntriesByInstanceId({\n instancesIds,\n options,\n sadotOptions,\n }),\n ]);\n\n // Attach custom fields to the instances\n instances.forEach((instance) => {\n const { id } = instance;\n\n const instanceValues = valuesGroupByInstance[id];\n const serializedCustomFieldsValues = instanceValues ? serializeCustomFields(instanceValues, definitionsMap) : {};\n\n const customFields = sadotOptions.useCustomFieldsEntries\n ? customFieldEntriesByInstanceId[id]\n : serializedCustomFieldsValues;\n\n scopeAttributes.forEach((attribute) => {\n const identifier = instance[attribute];\n\n const entityCustomFieldDefinitions = identifierCustomFieldDefinitionsMapping[identifier];\n if (entityCustomFieldDefinitions?.length > 0) {\n entityCustomFieldDefinitions.forEach((customFieldDefinition) => {\n if (customFields[customFieldDefinition.name] === undefined) {\n customFields[customFieldDefinition.name] = null;\n }\n });\n }\n });\n instance.customFields = customFields;\n options.attributesToRemove?.forEach?.((attribute) => {\n delete instance.dataValues?.[attribute];\n // if raw:\n delete instance?.[attribute];\n });\n // sequelize will think customFields changed also in 'find', so we need to mark it as unchanged\n if (hookType === 'afterFind') {\n // changed() could be undefined, i.e in raw: true\n instance?.changed?.('customFields', false);\n }\n });\n};\n\nexport default enrichResults;\n"],"mappings":"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"}
@@ -1,198 +1,2 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || function (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
24
- };
25
- var __importDefault = (this && this.__importDefault) || function (mod) {
26
- return (mod && mod.__esModule) ? mod : { "default": mod };
27
- };
28
- Object.defineProperty(exports, "__esModule", { value: true });
29
- exports.getValuesGroupByInstance = exports.getCustomFieldEntriesByInstanceId = void 0;
30
- /* eslint-disable no-param-reassign */
31
- const ValueRepo = __importStar(require("../repository/value"));
32
- const DefinitionRepo = __importStar(require("../repository/definition"));
33
- const EntriesRepo = __importStar(require("../repository/entries"));
34
- const scopeAttributes_1 = __importDefault(require("../utils/scopeAttributes"));
35
- // Include all required fields for proper functioning
36
- const CUSTOM_FIELD_DEFINITION_ATTRIBUTES_TO_PULL = [
37
- 'id',
38
- 'name',
39
- 'entityId',
40
- 'fieldType',
41
- 'displayName',
42
- 'validation',
43
- 'entityType',
44
- 'modelType',
45
- 'required',
46
- 'disabled',
47
- 'defaultValue',
48
- ];
49
- const getCustomFieldEntriesByInstanceId = async ({ instancesIds, options, sadotOptions, }) => {
50
- if (!sadotOptions.useCustomFieldsEntries) {
51
- return {};
52
- }
53
- const customFieldEntries = await EntriesRepo.findEntriesByModelIds(instancesIds, options ?? {});
54
- const customFieldEntriesByInstanceId = Object.fromEntries(customFieldEntries.map((instanceEntries) => {
55
- const { modelId, customFields } = instanceEntries?.dataValues ?? {};
56
- if (!modelId) {
57
- return undefined;
58
- }
59
- return [modelId, customFields];
60
- }).filter(Boolean));
61
- instancesIds.forEach((instanceId) => {
62
- customFieldEntriesByInstanceId[instanceId] ?? (customFieldEntriesByInstanceId[instanceId] = {});
63
- });
64
- return customFieldEntriesByInstanceId;
65
- };
66
- exports.getCustomFieldEntriesByInstanceId = getCustomFieldEntriesByInstanceId;
67
- const getValuesGroupByInstance = async ({ instancesIds, options, sadotOptions, }) => {
68
- if (sadotOptions.useCustomFieldsEntries) {
69
- return {};
70
- }
71
- const customFieldValues = await ValueRepo.findValuesByModelIds(instancesIds, options ?? {});
72
- // Group fields by modelId
73
- return customFieldValues.reduce((acc, v) => {
74
- const { modelId } = v;
75
- acc[modelId] ?? (acc[modelId] = []);
76
- acc[modelId].push(v);
77
- return acc;
78
- }, {});
79
- };
80
- exports.getValuesGroupByInstance = getValuesGroupByInstance;
81
- /**
82
- * Serialize custom fields value into the format of {[name] -> [fieldData]}
83
- */
84
- const serializeCustomFields = (customFieldValues, customFieldDefinitionsHash) => {
85
- const customFields = customFieldValues.reduce((acc, cfv) => ({
86
- ...acc,
87
- ...(customFieldDefinitionsHash[cfv.customFieldDefinitionId]
88
- && { [customFieldDefinitionsHash[cfv.customFieldDefinitionId].name]: cfv.value }),
89
- }), {});
90
- return customFields;
91
- };
92
- /**
93
- * A hook to attach the custom fields when fetching a model instances.
94
- */
95
- const enrichResults = (modelType, scopeAttributes, hookType, modelOptions = {}, sadotOptions = { useCustomFieldsEntries: false }) => async (instancesOrInstance, options) => {
96
- var _a;
97
- if (options.originalAttributes?.length > 0
98
- && !options.originalAttributes?.includes?.('customFields')) {
99
- return;
100
- }
101
- const primaryKey = 'id';
102
- let instances = Array.isArray(instancesOrInstance)
103
- ? instancesOrInstance
104
- : [instancesOrInstance];
105
- instances = instances.filter(Boolean);
106
- const identifiers = (0, scopeAttributes_1.default)(instances, scopeAttributes);
107
- const uniqueIdentifiers = [...new Set(identifiers)].filter(Boolean);
108
- const identifierCustomFieldDefinitionsMapping = uniqueIdentifiers.reduce((map, identifier) => ({
109
- ...map,
110
- [identifier]: [],
111
- }), {});
112
- // Cache for definitions by model type and transaction to avoid redundant DB queries
113
- let customFieldDefinitionsPromise;
114
- let cacheKey;
115
- if (options.transaction) {
116
- // Initialize definition cache Map if not already present directly on the transaction object
117
- (_a = options.transaction).definitionCache || (_a.definitionCache = new Map());
118
- cacheKey = `${modelType}:${uniqueIdentifiers.slice().sort().join(',')}`;
119
- customFieldDefinitionsPromise = options.transaction.definitionCache.get(cacheKey);
120
- }
121
- if (!customFieldDefinitionsPromise) {
122
- // Fetch from database (either first time in this transaction or no transaction)
123
- customFieldDefinitionsPromise = DefinitionRepo.findByEntityIds(modelType, uniqueIdentifiers, { transaction: options.transaction, modelOptions, attributes: CUSTOM_FIELD_DEFINITION_ATTRIBUTES_TO_PULL });
124
- options.transaction?.definitionCache?.set(cacheKey, customFieldDefinitionsPromise);
125
- }
126
- const customFieldDefinitions = await customFieldDefinitionsPromise;
127
- if (customFieldDefinitions.length === 0) {
128
- // if no custom fields, we can return
129
- instances.forEach((instance) => {
130
- instance.customFields = {};
131
- });
132
- return;
133
- }
134
- if (modelOptions?.include && modelOptions.useEntityIdFromInclude) {
135
- // if we pass useEntityIdFromInclude,
136
- // map the entity from the options to the identifierCustomFieldDefinitionsMapping
137
- modelOptions.include(identifiers).forEach(({ model }) => {
138
- customFieldDefinitions.forEach((cfd) => {
139
- const entityId = cfd[`${model.name}.entityId`];
140
- identifierCustomFieldDefinitionsMapping[entityId] = [];
141
- });
142
- });
143
- }
144
- const definitionsMap = customFieldDefinitions.reduce((map, definition) => ({
145
- ...map,
146
- [definition.id]: definition,
147
- }), {});
148
- customFieldDefinitions.forEach((cfd) => {
149
- identifierCustomFieldDefinitionsMapping[cfd.entityId].push(cfd);
150
- });
151
- // Get the values per instates ids:
152
- const instancesIds = instances.map((i) => i[primaryKey]);
153
- // Group fields by modelId
154
- const [valuesGroupByInstance, customFieldEntriesByInstanceId] = await Promise.all([
155
- (0, exports.getValuesGroupByInstance)({
156
- instancesIds,
157
- options,
158
- sadotOptions,
159
- }),
160
- (0, exports.getCustomFieldEntriesByInstanceId)({
161
- instancesIds,
162
- options,
163
- sadotOptions,
164
- }),
165
- ]);
166
- // Attach custom fields to the instances
167
- instances.forEach((instance) => {
168
- const { id } = instance;
169
- const instanceValues = valuesGroupByInstance[id];
170
- const serializedCustomFieldsValues = instanceValues ? serializeCustomFields(instanceValues, definitionsMap) : {};
171
- const customFields = sadotOptions.useCustomFieldsEntries
172
- ? customFieldEntriesByInstanceId[id]
173
- : serializedCustomFieldsValues;
174
- scopeAttributes.forEach((attribute) => {
175
- const identifier = instance[attribute];
176
- const entityCustomFieldDefinitions = identifierCustomFieldDefinitionsMapping[identifier];
177
- if (entityCustomFieldDefinitions?.length > 0) {
178
- entityCustomFieldDefinitions.forEach((customFieldDefinition) => {
179
- if (customFields[customFieldDefinition.name] === undefined) {
180
- customFields[customFieldDefinition.name] = null;
181
- }
182
- });
183
- }
184
- });
185
- instance.customFields = customFields;
186
- options.attributesToRemove?.forEach?.((attribute) => {
187
- delete instance.dataValues?.[attribute];
188
- // if raw:
189
- delete instance?.[attribute];
190
- });
191
- // sequelize will think customFields changed also in 'find', so we need to mark it as unchanged
192
- if (hookType === 'afterFind') {
193
- // changed() could be undefined, i.e in raw: true
194
- instance?.changed?.('customFields', false);
195
- }
196
- });
197
- };
198
- exports.default = enrichResults;
1
+ import{findByEntityIds as e}from"../repository/definition.js";import{findValuesByModelIds as t}from"../repository/value.js";import{findEntriesByModelIds as n}from"../repository/entries.js";import r from"../utils/scopeAttributes.js";const i=[`id`,`name`,`entityId`,`fieldType`,`displayName`,`validation`,`entityType`,`modelType`,`required`,`disabled`,`defaultValue`],a=async({instancesIds:e,options:t,sadotOptions:r})=>{if(!r.useCustomFieldsEntries)return{};let i=await n(e,t??{}),a=Object.fromEntries(i.map(e=>{let{modelId:t,customFields:n}=e?.dataValues??{};if(t)return[t,n]}).filter(Boolean));return e.forEach(e=>{a[e]??={}}),a},o=async({instancesIds:e,options:n,sadotOptions:r})=>r.useCustomFieldsEntries?{}:(await t(e,n??{})).reduce((e,t)=>{let{modelId:n}=t;return e[n]??=[],e[n].push(t),e},{}),s=(e,t)=>e.reduce((e,n)=>({...e,...t[n.customFieldDefinitionId]&&{[t[n.customFieldDefinitionId].name]:n.value}}),{});var c=(t,n,c,l={},u={useCustomFieldsEntries:!1})=>async(d,f)=>{if(f.originalAttributes?.length>0&&!f.originalAttributes?.includes?.(`customFields`))return;let p=Array.isArray(d)?d:[d];p=p.filter(Boolean);let m=r(p,n),h=[...new Set(m)].filter(Boolean),g=h.reduce((e,t)=>({...e,[t]:[]}),{}),_,v;f.transaction&&(f.transaction.definitionCache||=new Map,v=`${t}:${h.slice().sort().join(`,`)}`,_=f.transaction.definitionCache.get(v)),_||(_=e(t,h,{transaction:f.transaction,modelOptions:l,attributes:i}),f.transaction?.definitionCache?.set(v,_));let y=await _;if(y.length===0){p.forEach(e=>{e.customFields={}});return}l?.include&&l.useEntityIdFromInclude&&l.include(m).forEach(({model:e})=>{y.forEach(t=>{let n=t[`${e.name}.entityId`];g[n]=[]})});let b=y.reduce((e,t)=>({...e,[t.id]:t}),{});y.forEach(e=>{g[e.entityId].push(e)});let x=p.map(e=>e.id),[S,C]=await Promise.all([o({instancesIds:x,options:f,sadotOptions:u}),a({instancesIds:x,options:f,sadotOptions:u})]);p.forEach(e=>{let{id:t}=e,r=S[t],i=r?s(r,b):{},a=u.useCustomFieldsEntries?C[t]:i;n.forEach(t=>{let n=e[t],r=g[n];r?.length>0&&r.forEach(e=>{a[e.name]===void 0&&(a[e.name]=null)})}),e.customFields=a,f.attributesToRemove?.forEach?.(t=>{delete e.dataValues?.[t],delete e?.[t]}),c===`afterFind`&&e?.changed?.(`customFields`,!1)})};export{c as default};
2
+ //# sourceMappingURL=enrich.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"enrich.js","names":["EntriesRepo.findEntriesByModelIds","ValueRepo.findValuesByModelIds","applyScopeToInstance","DefinitionRepo.findByEntityIds"],"sources":["../../src/hooks/enrich.ts"],"sourcesContent":["/* eslint-disable no-param-reassign */\nimport * as ValueRepo from '../repository/value';\nimport * as DefinitionRepo from '../repository/definition';\nimport * as EntriesRepo from '../repository/entries';\nimport type CustomFieldValue from '../models/CustomFieldValue';\nimport type CustomFieldDefinition from '../models/CustomFieldDefinition';\nimport type { SerializedCustomFields } from '../types/definition';\nimport type { CustomFieldOptions, ModelOptions, TransactionOptions } from '../types';\nimport applyScopeToInstance from '../utils/scopeAttributes';\n\n// Include all required fields for proper functioning\nconst CUSTOM_FIELD_DEFINITION_ATTRIBUTES_TO_PULL = [\n 'id',\n 'name',\n 'entityId',\n 'fieldType',\n 'displayName',\n 'validation',\n 'entityType',\n 'modelType',\n 'required',\n 'disabled',\n 'defaultValue',\n];\n\ntype SupportedHookTypes = 'afterFind' | 'afterCreate' | 'afterUpdate';\n\ntype CustomFieldEntries = Record<string, any>;\n\ninterface GetValuesGroupByInstanceResponse {\n [modelId: string]: CustomFieldValue[];\n}\n\ninterface GetCustomFieldEntriesByInstanceIdResponse {\n [modelId: string]: CustomFieldEntries;\n}\n\nexport const getCustomFieldEntriesByInstanceId = async ({\n instancesIds,\n options,\n sadotOptions,\n}: {\n instancesIds: string[],\n options?: TransactionOptions,\n sadotOptions: Pick<CustomFieldOptions, 'useCustomFieldsEntries'>,\n}): Promise<GetCustomFieldEntriesByInstanceIdResponse> => {\n if (!sadotOptions.useCustomFieldsEntries) {\n return {};\n }\n\n const customFieldEntries = await EntriesRepo.findEntriesByModelIds(\n instancesIds,\n options ?? {},\n );\n\n const customFieldEntriesByInstanceId = Object.fromEntries(customFieldEntries.map((instanceEntries) => {\n const { modelId, customFields } = instanceEntries?.dataValues ?? {};\n if (!modelId) {\n return undefined;\n }\n return [modelId, customFields];\n }).filter(Boolean));\n\n instancesIds.forEach((instanceId) => {\n customFieldEntriesByInstanceId[instanceId] ??= {};\n });\n\n return customFieldEntriesByInstanceId;\n};\n\nexport const getValuesGroupByInstance = async ({\n instancesIds,\n options,\n sadotOptions,\n}: {\n instancesIds: string[],\n options?: TransactionOptions,\n sadotOptions: Pick<CustomFieldOptions, 'useCustomFieldsEntries'>,\n}): Promise<GetValuesGroupByInstanceResponse> => {\n if (sadotOptions.useCustomFieldsEntries) {\n return {};\n }\n\n const customFieldValues = await ValueRepo.findValuesByModelIds(\n instancesIds,\n options ?? {},\n );\n\n // Group fields by modelId\n return customFieldValues.reduce((acc, v) => {\n const { modelId } = v;\n acc[modelId] ??= [];\n acc[modelId].push(v);\n return acc;\n }, {});\n};\n\n/**\n * Serialize custom fields value into the format of {[name] -> [fieldData]}\n */\nconst serializeCustomFields = (\n customFieldValues: CustomFieldValue[],\n customFieldDefinitionsHash: Record<string, CustomFieldDefinition>,\n): SerializedCustomFields => {\n const customFields = customFieldValues.reduce((acc, cfv) => ({\n ...acc,\n ...(\n customFieldDefinitionsHash[cfv.customFieldDefinitionId]\n && { [customFieldDefinitionsHash[cfv.customFieldDefinitionId].name]: cfv.value }\n ),\n }), {});\n return customFields;\n};\n/**\n * A hook to attach the custom fields when fetching a model instances.\n */\nconst enrichResults = (\n modelType: string,\n scopeAttributes: string[],\n hookType?: SupportedHookTypes,\n modelOptions: ModelOptions = {},\n sadotOptions: Pick<CustomFieldOptions, 'useCustomFieldsEntries'> = { useCustomFieldsEntries: false },\n) => async (\n instancesOrInstance: any | any[],\n options: TransactionOptions,\n): Promise<void> => {\n if (\n options.originalAttributes?.length > 0\n && !options.originalAttributes?.includes?.('customFields')\n ) {\n return;\n }\n\n const primaryKey = 'id';\n let instances = Array.isArray(instancesOrInstance)\n ? instancesOrInstance\n : [instancesOrInstance];\n\n instances = instances.filter(Boolean);\n\n const identifiers = applyScopeToInstance(instances, scopeAttributes);\n\n const uniqueIdentifiers = [...new Set(identifiers)].filter(Boolean);\n\n const identifierCustomFieldDefinitionsMapping = uniqueIdentifiers.reduce((map, identifier) => ({\n ...map,\n [identifier]: [],\n }), {});\n\n // Cache for definitions by model type and transaction to avoid redundant DB queries\n let customFieldDefinitionsPromise;\n let cacheKey;\n\n if (options.transaction) {\n // Initialize definition cache Map if not already present directly on the transaction object\n options.transaction.definitionCache ||= new Map();\n cacheKey = `${modelType}:${uniqueIdentifiers.slice().sort().join(',')}`;\n customFieldDefinitionsPromise = options.transaction.definitionCache.get(cacheKey);\n }\n\n if (!customFieldDefinitionsPromise) {\n // Fetch from database (either first time in this transaction or no transaction)\n customFieldDefinitionsPromise = DefinitionRepo.findByEntityIds(\n modelType,\n uniqueIdentifiers,\n { transaction: options.transaction, modelOptions, attributes: CUSTOM_FIELD_DEFINITION_ATTRIBUTES_TO_PULL },\n );\n\n options.transaction?.definitionCache?.set(cacheKey, customFieldDefinitionsPromise);\n }\n const customFieldDefinitions = await customFieldDefinitionsPromise;\n\n if (customFieldDefinitions.length === 0) {\n // if no custom fields, we can return\n instances.forEach((instance) => {\n instance.customFields = {};\n });\n return;\n }\n\n if (modelOptions?.include && modelOptions.useEntityIdFromInclude) {\n // if we pass useEntityIdFromInclude,\n // map the entity from the options to the identifierCustomFieldDefinitionsMapping\n modelOptions.include(identifiers).forEach(({ model }) => {\n customFieldDefinitions.forEach((cfd) => {\n const entityId = cfd[`${model.name}.entityId`];\n identifierCustomFieldDefinitionsMapping[entityId] = [];\n });\n });\n }\n\n const definitionsMap = customFieldDefinitions.reduce((map, definition) => ({\n ...map,\n [definition.id]: definition,\n }), {});\n\n customFieldDefinitions.forEach((cfd) => {\n identifierCustomFieldDefinitionsMapping[cfd.entityId].push(cfd);\n });\n\n // Get the values per instates ids:\n const instancesIds = instances.map((i) => i[primaryKey]);\n\n // Group fields by modelId\n const [valuesGroupByInstance, customFieldEntriesByInstanceId] = await Promise.all([\n getValuesGroupByInstance({\n instancesIds,\n options,\n sadotOptions,\n }),\n getCustomFieldEntriesByInstanceId({\n instancesIds,\n options,\n sadotOptions,\n }),\n ]);\n\n // Attach custom fields to the instances\n instances.forEach((instance) => {\n const { id } = instance;\n\n const instanceValues = valuesGroupByInstance[id];\n const serializedCustomFieldsValues = instanceValues ? serializeCustomFields(instanceValues, definitionsMap) : {};\n\n const customFields = sadotOptions.useCustomFieldsEntries\n ? customFieldEntriesByInstanceId[id]\n : serializedCustomFieldsValues;\n\n scopeAttributes.forEach((attribute) => {\n const identifier = instance[attribute];\n\n const entityCustomFieldDefinitions = identifierCustomFieldDefinitionsMapping[identifier];\n if (entityCustomFieldDefinitions?.length > 0) {\n entityCustomFieldDefinitions.forEach((customFieldDefinition) => {\n if (customFields[customFieldDefinition.name] === undefined) {\n customFields[customFieldDefinition.name] = null;\n }\n });\n }\n });\n instance.customFields = customFields;\n options.attributesToRemove?.forEach?.((attribute) => {\n delete instance.dataValues?.[attribute];\n // if raw:\n delete instance?.[attribute];\n });\n // sequelize will think customFields changed also in 'find', so we need to mark it as unchanged\n if (hookType === 'afterFind') {\n // changed() could be undefined, i.e in raw: true\n instance?.changed?.('customFields', false);\n }\n });\n};\n\nexport default enrichResults;\n"],"mappings":"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"}
@@ -0,0 +1,2 @@
1
+ const e=require(`../utils/logger/index.cjs`),t=(e,t)=>{let n=e.filter(e=>!t.includes(e));return t.includes?.(`id`)||n.push(`id`),n},n=n=>r=>{let{attributes:i}=r;if(i?.includes?.(`customFields`)){let a=t(n,i);e.default.debug(`sadot - before find hook`),a?.length>0&&(i.push(...a),r.attributesToRemove=a)}};exports.beforeFind=n;
2
+ //# sourceMappingURL=find.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"find.cjs","names":[],"sources":["../../src/hooks/find.ts"],"sourcesContent":["/* eslint-disable no-param-reassign */\nimport type { FindOptions } from 'sequelize';\nimport logger from '../utils/logger';\n\nconst doScopeAttributesMissing = (\n scopeAttributes: string[],\n queryAttributes: (string | string[])[],\n): string[] => {\n const attributes = scopeAttributes\n .filter((attribute) => !queryAttributes.includes(attribute));\n if (!queryAttributes.includes?.('id')) {\n attributes.push('id');\n }\n return attributes;\n};\n\n// eslint-disable-next-line import/prefer-default-export\nexport const beforeFind = (scopeAttributes: string[]) => (options: FindOptions): void => {\n const { attributes: queryAttributes } = options;\n if ((queryAttributes as string[])?.includes?.('customFields')) {\n const missingScopeAttributes = doScopeAttributesMissing(scopeAttributes, queryAttributes as string[]);\n logger.debug('sadot - before find hook');\n if (missingScopeAttributes?.length > 0) {\n (queryAttributes as string[]).push(...missingScopeAttributes);\n (options as any).attributesToRemove = missingScopeAttributes;\n }\n }\n};\n"],"mappings":"6CAIM,GACJ,EACA,IACa,CACb,IAAM,EAAa,EAChB,OAAQ,GAAc,CAAC,EAAgB,SAAS,EAAU,CAAC,CAI9D,OAHK,EAAgB,WAAW,KAAK,EACnC,EAAW,KAAK,KAAK,CAEhB,GAII,EAAc,GAA+B,GAA+B,CACvF,GAAM,CAAE,WAAY,GAAoB,EACxC,GAAK,GAA8B,WAAW,eAAe,CAAE,CAC7D,IAAM,EAAyB,EAAyB,EAAiB,EAA4B,CACrG,EAAA,QAAO,MAAM,2BAA2B,CACpC,GAAwB,OAAS,IAClC,EAA6B,KAAK,GAAG,EAAuB,CAC5D,EAAgB,mBAAqB"}
@@ -1,29 +1,2 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.beforeFind = void 0;
7
- /* eslint-disable no-param-reassign */
8
- const logger_1 = __importDefault(require("../utils/logger"));
9
- const doScopeAttributesMissing = (scopeAttributes, queryAttributes) => {
10
- const attributes = scopeAttributes
11
- .filter((attribute) => !queryAttributes.includes(attribute));
12
- if (!queryAttributes.includes?.('id')) {
13
- attributes.push('id');
14
- }
15
- return attributes;
16
- };
17
- // eslint-disable-next-line import/prefer-default-export
18
- const beforeFind = (scopeAttributes) => (options) => {
19
- const { attributes: queryAttributes } = options;
20
- if (queryAttributes?.includes?.('customFields')) {
21
- const missingScopeAttributes = doScopeAttributesMissing(scopeAttributes, queryAttributes);
22
- logger_1.default.debug('sadot - before find hook');
23
- if (missingScopeAttributes?.length > 0) {
24
- queryAttributes.push(...missingScopeAttributes);
25
- options.attributesToRemove = missingScopeAttributes;
26
- }
27
- }
28
- };
29
- exports.beforeFind = beforeFind;
1
+ import e from"../utils/logger/index.js";const t=(e,t)=>{let n=e.filter(e=>!t.includes(e));return t.includes?.(`id`)||n.push(`id`),n},n=n=>r=>{let{attributes:i}=r;if(i?.includes?.(`customFields`)){let a=t(n,i);e.debug(`sadot - before find hook`),a?.length>0&&(i.push(...a),r.attributesToRemove=a)}};export{n as beforeFind};
2
+ //# sourceMappingURL=find.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"find.js","names":[],"sources":["../../src/hooks/find.ts"],"sourcesContent":["/* eslint-disable no-param-reassign */\nimport type { FindOptions } from 'sequelize';\nimport logger from '../utils/logger';\n\nconst doScopeAttributesMissing = (\n scopeAttributes: string[],\n queryAttributes: (string | string[])[],\n): string[] => {\n const attributes = scopeAttributes\n .filter((attribute) => !queryAttributes.includes(attribute));\n if (!queryAttributes.includes?.('id')) {\n attributes.push('id');\n }\n return attributes;\n};\n\n// eslint-disable-next-line import/prefer-default-export\nexport const beforeFind = (scopeAttributes: string[]) => (options: FindOptions): void => {\n const { attributes: queryAttributes } = options;\n if ((queryAttributes as string[])?.includes?.('customFields')) {\n const missingScopeAttributes = doScopeAttributesMissing(scopeAttributes, queryAttributes as string[]);\n logger.debug('sadot - before find hook');\n if (missingScopeAttributes?.length > 0) {\n (queryAttributes as string[]).push(...missingScopeAttributes);\n (options as any).attributesToRemove = missingScopeAttributes;\n }\n }\n};\n"],"mappings":"wCAIA,MAAM,GACJ,EACA,IACa,CACb,IAAM,EAAa,EAChB,OAAQ,GAAc,CAAC,EAAgB,SAAS,EAAU,CAAC,CAI9D,OAHK,EAAgB,WAAW,KAAK,EACnC,EAAW,KAAK,KAAK,CAEhB,GAII,EAAc,GAA+B,GAA+B,CACvF,GAAM,CAAE,WAAY,GAAoB,EACxC,GAAK,GAA8B,WAAW,eAAe,CAAE,CAC7D,IAAM,EAAyB,EAAyB,EAAiB,EAA4B,CACrG,EAAO,MAAM,2BAA2B,CACpC,GAAwB,OAAS,IAClC,EAA6B,KAAK,GAAG,EAAuB,CAC5D,EAAgB,mBAAqB"}
@@ -0,0 +1,2 @@
1
+ const e=require(`../_virtual/rolldown_runtime.cjs`),t=require(`../utils/logger/index.cjs`),n=require(`../utils/constants/index.cjs`),r=require(`../errors/index.cjs`),i=require(`../repository/definition.cjs`),a=require(`../repository/validator.cjs`),o=require(`../utils/scopeAttributes.cjs`),s=require(`./utils/updateInstanceValues.cjs`);let c=require(`joi`);c=e.__toESM(c);let l=require(`@autofleet/errors`);l=e.__toESM(l);let u=require(`ajv`);u=e.__toESM(u);let d=require(`ajv-formats`);d=e.__toESM(d);let f=require(`ajv-errors`);f=e.__toESM(f);const p=[`id`,`schema`,`modelType`,`entityId`,`disabled`],m=new u.default({allErrors:!0,strict:!1,strictTypes:!1,$data:!0});(0,d.default)(m),(0,f.default)(m);const h=(e,t)=>({__proto__:null,...e,...t}),g=async(e,n)=>{if(!e.id||!e.customFields||Object.keys(e.customFields).length===0)return e.customFields||{};try{let r=await e.constructor.findOne({where:{id:e.id},attributes:[`customFields`],transaction:n.transaction,raw:!0});if(r?.customFields){let n=h(r.customFields,e.customFields);return t.default.debug(`sadot - fetched complete custom fields for validation`,{fieldsCount:Object.keys(n).length,updateFieldsCount:Object.keys(e.customFields).length}),n}}catch(e){t.default.error(`sadot - error fetching complete model for validation`,{error:e})}return e.customFields||{}},_=e=>{let t={...e.dataValues};(e.changed?.()||[]).forEach(n=>{let r=e.previous?.(n);r!==void 0&&(t[n]=r)});let n=e.previous?.(`customFields`);return n!==void 0&&(t.customFields=n),t},v=e=>e.reduce((e,t)=>{let n=(t.instancePath||``).split(`/`).filter(Boolean).join(`.`).replace(/^after\./,``),r=t.keyword===`required`?`.${t.params?.missingProperty}`:``,i=(n+r).replace(/^\./,``)||`root`;return e[i]=t.message||`Invalid value`,e},{}),y=async(e,n,r,i={},s=!1)=>{let c=e.constructor.name;t.default.debug(`sadot - validating model`,{isCreate:s,modelType:c});let u=o.default(e,r);if(t.default.debug(`sadot - identifiers`,{identifiers:u}),!u||Object.keys(u).length===0){t.default.debug(`sadot - skipping validation: no identifiers`);return}let d=Object.values(u)[0];if(t.default.debug(`sadot - entityId`,{entityId:d}),!d){t.default.debug(`sadot - skipping validation: no entityId`);return}let f,y;n.transaction&&(n.transaction.validationsCache||=new Map,y=`${c}-${d}`,f=n.transaction.validationsCache.get(y)),f||(f=a.findAllByModelType(c,d,{transaction:n.transaction,attributes:p,modelOptions:i}),n.transaction&&n?.transaction?.validationsCache.set(y,f));let b=await f;if(t.default.debug(`sadot - validators found`,{count:b.length}),!b.length){t.default.debug(`sadot - skipping validation: no validators found`);return}let x=null;s||(x=_(e));let S=s?e.customFields||{}:await g(e,n);for(let n of b){let{schema:r}=n,i=r;if(t.default.debug(`sadot - validating with schema`,{schema:r,hasAfterProps:!!i.properties?.after,hasBeforeProps:!!i.properties?.before}),s){if(i.properties?.after){let t=m.compile({...r,properties:{after:i.properties.after}});if(!t(JSON.parse(JSON.stringify({after:{...e.dataValues,customFields:S}})))){let e=t.errors?.map(e=>`${e.instancePath||``} ${e.message||`Invalid value`}`).join(`, `),n=v(t.errors);throw new l.BadRequest([Error(`Validation failed for ${c}: ${e}`)],void 0,{customError:n})}}}else{let n=m.compile(i),r=h(e.dataValues);r.customFields=S;let a={before:x,after:r},o=n(JSON.parse(JSON.stringify(a)));if(t.default.debug(`sadot - validation result`,{isValid:o,test:{before:x,after:r}}),!o){let e=n.errors?.map(e=>`${e.instancePath||``} ${e.message||`Invalid value`}`).join(`, `),t=v(n.errors);throw new l.BadRequest([Error(`Validation failed for ${c}: ${e}`)],void 0,{customError:t})}}}},b=async({modelType:e,modelOptions:t,identifiers:n,options:r})=>{let{include:a,useEntityIdFromInclude:o}=t,s={modelType:e,disabled:!1,...!o&&{entityId:n}};return await i.findAll(s,{withDisabled:!1,transaction:r.transaction,include:a?.(n)})},x=(e,t)=>{(e||[]).forEach(e=>{let{fieldType:i,name:a}=e;if([n.CustomFieldDefinitionType.DATE,n.CustomFieldDefinitionType.DATETIME].includes(i)){let e=t.customFields?.[a];if(e){let{value:n,error:i}=c.default.date().validate(e);if(i)throw new r.InvalidValueError(e,a,i);t.customFields[a]=n.toISOString()}}})},S=(e,n={},i={useCustomFieldsEntries:!1})=>async(a,c)=>{t.default.debug(`sadot - before create hook`);let{fields:l}=c,u=a.constructor.name,d=o.default(a,e),f=await b({modelType:u,modelOptions:n,identifiers:d,options:c}),p=f.filter(e=>![null,void 0].includes(e.defaultValue));p.length&&(a.customFields||={},p.filter(e=>a.customFields?.[e.name]===void 0).forEach(({name:e,defaultValue:t})=>{a.customFields[e]=t}));let m=Array.from(new Set(f.filter(({required:e})=>e).map(({name:e})=>e))),{customFields:h}=a,g=Object.keys(h??{}),_=m.filter(e=>!g.includes(e));if(_?.length)throw new r.MissingRequiredCustomFieldError(_);await y(a,c,e,n,!0),x(f,a);let v=l.indexOf(`customFields`);v===-1||!h||!Object.keys(h).length||(await s.default({modelId:a.id,modelType:u,identifiers:d,customFields:h,options:{useCustomFieldsEntries:i.useCustomFieldsEntries,transaction:c.transaction,modelOptions:n}}),l.splice(v,1))},C=(e,n={},r={useCustomFieldsEntries:!1})=>async(i,a)=>{t.default.debug(`sadot - before update hook`);let{fields:c}=a,l=i.constructor.name,u=o.default(i,e),d=await b({modelType:l,modelOptions:n,identifiers:u,options:a});await y(i,a,e,n,!1),x(d,i);let f=c.indexOf(`customFields`);if(f>-1){let{customFields:e}=i;if(!Object.keys(e).length)return;await s.default({modelId:i.id,modelType:l,identifiers:u,customFields:e,options:{useCustomFieldsEntries:r.useCustomFieldsEntries,transaction:a.transaction,modelOptions:n}}),c.splice(f,1)}},w=e=>{e.individualHooks=!0},T=e=>{e.individualHooks=!0};exports.beforeBulkCreate=w,exports.beforeBulkUpdate=T,exports.beforeCreate=S,exports.beforeUpdate=C;
2
+ //# sourceMappingURL=hooks.cjs.map