@autofleet/sadot 1.0.6 → 1.0.8
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.
- package/dist/_virtual/_@oxc-project_runtime@0.89.0/helpers/decorate.cjs +1 -0
- package/dist/_virtual/_@oxc-project_runtime@0.89.0/helpers/decorate.js +1 -0
- package/dist/_virtual/_@oxc-project_runtime@0.89.0/helpers/decorateMetadata.cjs +1 -0
- package/dist/_virtual/_@oxc-project_runtime@0.89.0/helpers/decorateMetadata.js +1 -0
- package/dist/_virtual/rolldown_runtime.cjs +1 -0
- package/dist/api/index.cjs +2 -0
- package/dist/api/index.cjs.map +1 -0
- package/dist/api/index.js +1 -12
- package/dist/api/index.js.map +1 -1
- package/dist/api/v1/definition/index.cjs +2 -0
- package/dist/api/v1/definition/index.cjs.map +1 -0
- package/dist/api/v1/definition/index.js +1 -116
- package/dist/api/v1/definition/index.js.map +1 -1
- package/dist/api/v1/definition/validations.cjs +2 -0
- package/dist/api/v1/definition/validations.cjs.map +1 -0
- package/dist/api/v1/definition/validations.js +1 -77
- package/dist/api/v1/definition/validations.js.map +1 -1
- package/dist/api/v1/errors.cjs +2 -0
- package/dist/api/v1/errors.cjs.map +1 -0
- package/dist/api/v1/errors.js +1 -12
- package/dist/api/v1/errors.js.map +1 -1
- package/dist/api/v1/index.cjs +2 -0
- package/dist/api/v1/index.cjs.map +1 -0
- package/dist/api/v1/index.js +1 -13
- package/dist/api/v1/index.js.map +1 -1
- package/dist/api/v1/validator/index.cjs +2 -0
- package/dist/api/v1/validator/index.cjs.map +1 -0
- package/dist/api/v1/validator/index.js +1 -143
- package/dist/api/v1/validator/index.js.map +1 -1
- package/dist/api/v1/validator/validations.cjs +2 -0
- package/dist/api/v1/validator/validations.cjs.map +1 -0
- package/dist/api/v1/validator/validations.js +1 -38
- package/dist/api/v1/validator/validations.js.map +1 -1
- package/dist/errors/index.cjs +3 -0
- package/dist/errors/index.cjs.map +1 -0
- package/dist/errors/index.js +2 -66
- package/dist/errors/index.js.map +1 -1
- package/dist/events/index.cjs +2 -0
- package/dist/events/index.cjs.map +1 -0
- package/dist/events/index.js +1 -54
- package/dist/events/index.js.map +1 -1
- package/dist/hooks/enrich.cjs +2 -0
- package/dist/hooks/enrich.cjs.map +1 -0
- package/dist/hooks/enrich.js +1 -197
- package/dist/hooks/enrich.js.map +1 -1
- package/dist/hooks/find.cjs +2 -0
- package/dist/hooks/find.cjs.map +1 -0
- package/dist/hooks/find.js +1 -29
- package/dist/hooks/find.js.map +1 -1
- package/dist/hooks/hooks.cjs +2 -0
- package/dist/hooks/hooks.cjs.map +1 -0
- package/dist/hooks/hooks.js +1 -387
- package/dist/hooks/hooks.js.map +1 -1
- package/dist/hooks/index.cjs +1 -0
- package/dist/hooks/index.js +1 -18
- package/dist/hooks/utils/updateInstanceValues.cjs +2 -0
- package/dist/hooks/utils/updateInstanceValues.cjs.map +1 -0
- package/dist/hooks/utils/updateInstanceValues.js +1 -50
- package/dist/hooks/utils/updateInstanceValues.js.map +1 -1
- package/dist/index.cjs +2 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +19 -0
- package/dist/index.d.ts +18 -12
- package/dist/index.js +1 -67
- package/dist/index.js.map +1 -1
- package/dist/models/CustomFieldDefinition.cjs +2 -0
- package/dist/models/CustomFieldDefinition.cjs.map +1 -0
- package/dist/models/CustomFieldDefinition.js +1 -201
- package/dist/models/CustomFieldDefinition.js.map +1 -1
- package/dist/models/CustomFieldEntries.cjs +2 -0
- package/dist/models/CustomFieldEntries.cjs.map +1 -0
- package/dist/models/CustomFieldEntries.js +1 -129
- package/dist/models/CustomFieldEntries.js.map +1 -1
- package/dist/models/CustomFieldValue.cjs +2 -0
- package/dist/models/CustomFieldValue.cjs.map +1 -0
- package/dist/models/CustomFieldValue.js +1 -160
- package/dist/models/CustomFieldValue.js.map +1 -1
- package/dist/models/CustomValidator.cjs +2 -0
- package/dist/models/CustomValidator.cjs.map +1 -0
- package/dist/models/CustomValidator.js +1 -104
- package/dist/models/CustomValidator.js.map +1 -1
- package/dist/models/index.cjs +2 -0
- package/dist/models/index.cjs.map +1 -0
- package/dist/models/index.js +1 -131
- package/dist/models/index.js.map +1 -1
- package/dist/models/tests/AssociatedTestModel.cjs +2 -0
- package/dist/models/tests/AssociatedTestModel.cjs.map +1 -0
- package/dist/models/tests/AssociatedTestModel.js +1 -73
- package/dist/models/tests/AssociatedTestModel.js.map +1 -1
- package/dist/models/tests/TestModel.cjs +2 -0
- package/dist/models/tests/TestModel.cjs.map +1 -0
- package/dist/models/tests/TestModel.js +1 -71
- package/dist/models/tests/TestModel.js.map +1 -1
- package/dist/models/tests/contextAwareModels/ContextAwareTestModel.cjs +2 -0
- package/dist/models/tests/contextAwareModels/ContextAwareTestModel.cjs.map +1 -0
- package/dist/models/tests/contextAwareModels/ContextAwareTestModel.js +1 -53
- package/dist/models/tests/contextAwareModels/ContextAwareTestModel.js.map +1 -1
- package/dist/models/tests/contextAwareModels/ContextTestModel.cjs +2 -0
- package/dist/models/tests/contextAwareModels/ContextTestModel.cjs.map +1 -0
- package/dist/models/tests/contextAwareModels/ContextTestModel.js +1 -47
- package/dist/models/tests/contextAwareModels/ContextTestModel.js.map +1 -1
- package/dist/repository/definition.cjs +2 -0
- package/dist/repository/definition.cjs.map +1 -0
- package/dist/repository/definition.js +1 -123
- package/dist/repository/definition.js.map +1 -1
- package/dist/repository/entries.cjs +2 -0
- package/dist/repository/entries.cjs.map +1 -0
- package/dist/repository/entries.js +1 -92
- package/dist/repository/entries.js.map +1 -1
- package/dist/repository/utils/formatValues.cjs +2 -0
- package/dist/repository/utils/formatValues.cjs.map +1 -0
- package/dist/repository/utils/formatValues.js +1 -16
- package/dist/repository/utils/formatValues.js.map +1 -1
- package/dist/repository/validator.cjs +2 -0
- package/dist/repository/validator.cjs.map +1 -0
- package/dist/repository/validator.js +1 -69
- package/dist/repository/validator.js.map +1 -1
- package/dist/repository/value.cjs +2 -0
- package/dist/repository/value.cjs.map +1 -0
- package/dist/repository/value.js +1 -124
- package/dist/repository/value.js.map +1 -1
- package/dist/scopes/filter.cjs +2 -0
- package/dist/scopes/filter.cjs.map +1 -0
- package/dist/scopes/filter.d.cts +23 -0
- package/dist/scopes/filter.d.ts +22 -29
- package/dist/scopes/filter.js +1 -75
- package/dist/scopes/filter.js.map +1 -1
- package/dist/scopes/helpers/filter.helpers.cjs +46 -0
- package/dist/scopes/helpers/filter.helpers.cjs.map +1 -0
- package/dist/scopes/helpers/filter.helpers.d.cts +17 -0
- package/dist/scopes/helpers/filter.helpers.d.ts +15 -40
- package/dist/scopes/helpers/filter.helpers.js +24 -183
- package/dist/scopes/helpers/filter.helpers.js.map +1 -1
- package/dist/scopes/index.cjs +1 -0
- package/dist/scopes/index.js +1 -7
- package/dist/types/index.d.cts +44 -0
- package/dist/types/index.d.ts +41 -44
- package/dist/utils/constants/index.cjs +2 -0
- package/dist/utils/constants/index.cjs.map +1 -0
- package/dist/utils/constants/index.d.cts +22 -0
- package/dist/utils/constants/index.d.ts +20 -17
- package/dist/utils/constants/index.js +1 -22
- package/dist/utils/constants/index.js.map +1 -1
- package/dist/utils/db/index.cjs +2 -0
- package/dist/utils/db/index.cjs.map +1 -0
- package/dist/utils/db/index.js +1 -24
- package/dist/utils/db/index.js.map +1 -1
- package/dist/utils/helpers/index.cjs +2 -0
- package/dist/utils/helpers/index.cjs.map +1 -0
- package/dist/utils/helpers/index.d.cts +31 -0
- package/dist/utils/helpers/index.d.ts +28 -23
- package/dist/utils/helpers/index.js +1 -40
- package/dist/utils/helpers/index.js.map +1 -1
- package/dist/utils/init.cjs +2 -0
- package/dist/utils/init.cjs.map +1 -0
- package/dist/utils/init.js +1 -112
- package/dist/utils/init.js.map +1 -1
- package/dist/utils/logger/index.cjs +2 -0
- package/dist/utils/logger/index.cjs.map +1 -0
- package/dist/utils/logger/index.js +1 -42
- package/dist/utils/logger/index.js.map +1 -1
- package/dist/utils/scopeAttributes.cjs +2 -0
- package/dist/utils/scopeAttributes.cjs.map +1 -0
- package/dist/utils/scopeAttributes.js +1 -11
- package/dist/utils/scopeAttributes.js.map +1 -1
- package/dist/utils/validations/index.cjs +2 -0
- package/dist/utils/validations/index.cjs.map +1 -0
- package/dist/utils/validations/index.js +1 -41
- package/dist/utils/validations/index.js.map +1 -1
- package/dist/utils/validations/schema/custom-fields.cjs +2 -0
- package/dist/utils/validations/schema/custom-fields.cjs.map +1 -0
- package/dist/utils/validations/schema/custom-fields.d.cts +7 -0
- package/dist/utils/validations/schema/custom-fields.d.ts +6 -2
- package/dist/utils/validations/schema/custom-fields.js +1 -9
- package/dist/utils/validations/schema/custom-fields.js.map +1 -1
- package/dist/utils/validations/schema/validator-schema.cjs +2 -0
- package/dist/utils/validations/schema/validator-schema.cjs.map +1 -0
- package/dist/utils/validations/schema/validator-schema.js +1 -95
- package/dist/utils/validations/schema/validator-schema.js.map +1 -1
- package/dist/utils/validations/validators/index.cjs +2 -0
- package/dist/utils/validations/validators/index.cjs.map +1 -0
- package/dist/utils/validations/validators/index.js +1 -40
- package/dist/utils/validations/validators/index.js.map +1 -1
- package/dist/utils/validations/validators/select.validator.cjs +2 -0
- package/dist/utils/validations/validators/select.validator.cjs.map +1 -0
- package/dist/utils/validations/validators/select.validator.js +1 -12
- package/dist/utils/validations/validators/select.validator.js.map +1 -1
- package/dist/utils/validations/validators/status.validator.cjs +2 -0
- package/dist/utils/validations/validators/status.validator.cjs.map +1 -0
- package/dist/utils/validations/validators/status.validator.js +1 -15
- package/dist/utils/validations/validators/status.validator.js.map +1 -1
- package/package.json +20 -4
- package/dist/api/index.d.ts +0 -3
- package/dist/api/v1/definition/index.d.ts +0 -3
- package/dist/api/v1/definition/validations.d.ts +0 -2
- package/dist/api/v1/errors.d.ts +0 -4
- package/dist/api/v1/index.d.ts +0 -3
- package/dist/api/v1/validator/index.d.ts +0 -3
- package/dist/api/v1/validator/validations.d.ts +0 -6
- package/dist/errors/index.d.ts +0 -24
- package/dist/events/index.d.ts +0 -5
- package/dist/hooks/create.d.ts +0 -10
- package/dist/hooks/create.js +0 -96
- package/dist/hooks/create.js.map +0 -1
- package/dist/hooks/enrich.d.ts +0 -25
- package/dist/hooks/find.d.ts +0 -1
- package/dist/hooks/hooks.d.ts +0 -17
- package/dist/hooks/index.d.ts +0 -5
- package/dist/hooks/index.js.map +0 -1
- package/dist/hooks/update.d.ts +0 -10
- package/dist/hooks/update.js +0 -50
- package/dist/hooks/update.js.map +0 -1
- package/dist/hooks/utils/updateInstanceValues.d.ts +0 -15
- package/dist/hooks/workaround.d.ts +0 -10
- package/dist/hooks/workaround.js +0 -38
- package/dist/hooks/workaround.js.map +0 -1
- package/dist/models/CustomFieldDefinition.d.ts +0 -25
- package/dist/models/CustomFieldEntries.d.ts +0 -15
- package/dist/models/CustomFieldValue.d.ts +0 -16
- package/dist/models/CustomValidator.d.ts +0 -17
- package/dist/models/index.d.ts +0 -18
- package/dist/models/tests/AssociatedTestModel.d.ts +0 -12
- package/dist/models/tests/TestModel.d.ts +0 -12
- package/dist/models/tests/contextAwareModels/ContextAwareTestModel.d.ts +0 -10
- package/dist/models/tests/contextAwareModels/ContextTestModel.d.ts +0 -13
- package/dist/repository/definition.d.ts +0 -37
- package/dist/repository/entries.d.ts +0 -13
- package/dist/repository/utils/formatValues.d.ts +0 -3
- package/dist/repository/validator.d.ts +0 -28
- package/dist/repository/value.d.ts +0 -28
- package/dist/scopes/index.d.ts +0 -2
- package/dist/scopes/index.js.map +0 -1
- package/dist/types/definition/index.d.ts +0 -25
- package/dist/types/definition/index.js +0 -3
- package/dist/types/definition/index.js.map +0 -1
- package/dist/types/entries/index.d.ts +0 -25
- package/dist/types/entries/index.js +0 -3
- package/dist/types/entries/index.js.map +0 -1
- package/dist/types/index.js +0 -3
- package/dist/types/index.js.map +0 -1
- package/dist/types/value/index.d.ts +0 -15
- package/dist/types/value/index.js +0 -3
- package/dist/types/value/index.js.map +0 -1
- package/dist/utils/db/index.d.ts +0 -4
- package/dist/utils/init.d.ts +0 -7
- package/dist/utils/logger/index.d.ts +0 -3
- package/dist/utils/scopeAttributes.d.ts +0 -2
- package/dist/utils/validations/index.d.ts +0 -8
- package/dist/utils/validations/schema/validator-schema.d.ts +0 -9
- package/dist/utils/validations/type.d.ts +0 -15
- package/dist/utils/validations/type.js +0 -3
- package/dist/utils/validations/type.js.map +0 -1
- package/dist/utils/validations/validators/index.d.ts +0 -14
- package/dist/utils/validations/validators/select.validator.d.ts +0 -5
- package/dist/utils/validations/validators/status.validator.d.ts +0 -12
package/dist/hooks/enrich.js
CHANGED
|
@@ -1,198 +1,2 @@
|
|
|
1
|
-
"
|
|
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] ??= {};
|
|
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] ??= [];
|
|
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
|
-
if (options.originalAttributes?.length > 0
|
|
97
|
-
&& !options.originalAttributes?.includes?.('customFields')) {
|
|
98
|
-
return;
|
|
99
|
-
}
|
|
100
|
-
const primaryKey = 'id';
|
|
101
|
-
let instances = Array.isArray(instancesOrInstance)
|
|
102
|
-
? instancesOrInstance
|
|
103
|
-
: [instancesOrInstance];
|
|
104
|
-
instances = instances.filter(Boolean);
|
|
105
|
-
const identifiers = (0, scopeAttributes_1.default)(instances, scopeAttributes);
|
|
106
|
-
const uniqueIdentifiers = [...new Set(identifiers)].filter(Boolean);
|
|
107
|
-
const identifierCustomFieldDefinitionsMapping = uniqueIdentifiers.reduce((map, identifier) => ({
|
|
108
|
-
...map,
|
|
109
|
-
[identifier]: [],
|
|
110
|
-
}), {});
|
|
111
|
-
// Cache for definitions by model type and transaction to avoid redundant DB queries
|
|
112
|
-
let customFieldDefinitionsPromise;
|
|
113
|
-
let cacheKey;
|
|
114
|
-
if (options.transaction) {
|
|
115
|
-
// Initialize definition cache Map if not already present directly on the transaction object
|
|
116
|
-
options.transaction.definitionCache ||= new Map();
|
|
117
|
-
cacheKey = `${modelType}:${uniqueIdentifiers.slice().sort().join(',')}`;
|
|
118
|
-
customFieldDefinitionsPromise = options.transaction.definitionCache.get(cacheKey);
|
|
119
|
-
}
|
|
120
|
-
if (!customFieldDefinitionsPromise) {
|
|
121
|
-
// Fetch from database (either first time in this transaction or no transaction)
|
|
122
|
-
customFieldDefinitionsPromise = DefinitionRepo.findByEntityIds(modelType, uniqueIdentifiers, { transaction: options.transaction, modelOptions, attributes: CUSTOM_FIELD_DEFINITION_ATTRIBUTES_TO_PULL });
|
|
123
|
-
options.transaction?.definitionCache?.set(cacheKey, customFieldDefinitionsPromise);
|
|
124
|
-
}
|
|
125
|
-
const customFieldDefinitions = await customFieldDefinitionsPromise;
|
|
126
|
-
if (customFieldDefinitions.length === 0) {
|
|
127
|
-
// if no custom fields, we can return
|
|
128
|
-
instances.forEach((instance) => {
|
|
129
|
-
instance.customFields = {};
|
|
130
|
-
});
|
|
131
|
-
return;
|
|
132
|
-
}
|
|
133
|
-
if (modelOptions?.include && modelOptions.useEntityIdFromInclude) {
|
|
134
|
-
// if we pass useEntityIdFromInclude,
|
|
135
|
-
// map the entity from the options to the identifierCustomFieldDefinitionsMapping
|
|
136
|
-
modelOptions.include(identifiers).forEach(({ model }) => {
|
|
137
|
-
customFieldDefinitions.forEach((cfd) => {
|
|
138
|
-
const entityId = cfd[`${model.name}.entityId`];
|
|
139
|
-
identifierCustomFieldDefinitionsMapping[entityId] = [];
|
|
140
|
-
});
|
|
141
|
-
});
|
|
142
|
-
}
|
|
143
|
-
const definitionsMap = customFieldDefinitions.reduce((map, definition) => ({
|
|
144
|
-
...map,
|
|
145
|
-
[definition.id]: definition,
|
|
146
|
-
}), {});
|
|
147
|
-
customFieldDefinitions.forEach((cfd) => {
|
|
148
|
-
identifierCustomFieldDefinitionsMapping[cfd.entityId].push(cfd);
|
|
149
|
-
});
|
|
150
|
-
// Get the values per instates ids:
|
|
151
|
-
const instancesIds = instances.map((i) => i[primaryKey]);
|
|
152
|
-
// Group fields by modelId
|
|
153
|
-
const [valuesGroupByInstance, customFieldEntriesByInstanceId] = await Promise.all([
|
|
154
|
-
(0, exports.getValuesGroupByInstance)({
|
|
155
|
-
instancesIds,
|
|
156
|
-
options,
|
|
157
|
-
sadotOptions,
|
|
158
|
-
}),
|
|
159
|
-
(0, exports.getCustomFieldEntriesByInstanceId)({
|
|
160
|
-
instancesIds,
|
|
161
|
-
options,
|
|
162
|
-
sadotOptions,
|
|
163
|
-
}),
|
|
164
|
-
]);
|
|
165
|
-
// Attach custom fields to the instances
|
|
166
|
-
instances.forEach((instance) => {
|
|
167
|
-
const { id } = instance;
|
|
168
|
-
const instanceValues = valuesGroupByInstance[id];
|
|
169
|
-
const serializedCustomFieldsValues = instanceValues ? serializeCustomFields(instanceValues, definitionsMap) : {};
|
|
170
|
-
const customFields = sadotOptions.useCustomFieldsEntries
|
|
171
|
-
? customFieldEntriesByInstanceId[id]
|
|
172
|
-
: serializedCustomFieldsValues;
|
|
173
|
-
scopeAttributes.forEach((attribute) => {
|
|
174
|
-
const identifier = instance[attribute];
|
|
175
|
-
const entityCustomFieldDefinitions = identifierCustomFieldDefinitionsMapping[identifier];
|
|
176
|
-
if (entityCustomFieldDefinitions?.length > 0) {
|
|
177
|
-
entityCustomFieldDefinitions.forEach((customFieldDefinition) => {
|
|
178
|
-
if (customFields[customFieldDefinition.name] === undefined) {
|
|
179
|
-
customFields[customFieldDefinition.name] = null;
|
|
180
|
-
}
|
|
181
|
-
});
|
|
182
|
-
}
|
|
183
|
-
});
|
|
184
|
-
instance.customFields = customFields;
|
|
185
|
-
options.attributesToRemove?.forEach?.((attribute) => {
|
|
186
|
-
delete instance.dataValues?.[attribute];
|
|
187
|
-
// if raw:
|
|
188
|
-
delete instance?.[attribute];
|
|
189
|
-
});
|
|
190
|
-
// sequelize will think customFields changed also in 'find', so we need to mark it as unchanged
|
|
191
|
-
if (hookType === 'afterFind') {
|
|
192
|
-
// changed() could be undefined, i.e in raw: true
|
|
193
|
-
instance?.changed?.('customFields', false);
|
|
194
|
-
}
|
|
195
|
-
});
|
|
196
|
-
};
|
|
197
|
-
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};
|
|
198
2
|
//# sourceMappingURL=enrich.js.map
|
package/dist/hooks/enrich.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"enrich.js","sourceRoot":"","sources":["../../src/hooks/enrich.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,sCAAsC;AACtC,+DAAiD;AACjD,yEAA2D;AAC3D,mEAAqD;AAKrD,+EAA4D;AAE5D,qDAAqD;AACrD,MAAM,0CAA0C,GAAG;IACjD,IAAI;IACJ,MAAM;IACN,UAAU;IACV,WAAW;IACX,aAAa;IACb,YAAY;IACZ,YAAY;IACZ,WAAW;IACX,UAAU;IACV,UAAU;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Q,CAAC,UAAU,EAAE,CAAC,SAAS,CAAC,CAAC;YACxC,UAAU;YACV,OAAO,QAAQ,EAAE,CAAC,SAAS,CAAC,CAAC;QAC/B,CAAC,CAAC,CAAC;QACH,+FAA+F;QAC/F,IAAI,QAAQ,KAAK,WAAW,EAAE,CAAC;YAC7B,iDAAiD;YACjD,QAAQ,EAAE,OAAO,EAAE,CAAC,cAAc,EAAE,KAAK,CAAC,CAAC;QAC7C,CAAC;IACH,CAAC,CAAC,CAAC;AACL,CAAC,CAAC;AAEF,kBAAe,aAAa,CAAC"}
|
|
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":"wOAWA,MAAM,EAA6C,CACjD,KACA,OACA,WACA,YACA,cACA,aACA,aACA,YACA,WACA,WACA,eACD,CAcY,EAAoC,MAAO,CACtD,eACA,UACA,kBAKwD,CACxD,GAAI,CAAC,EAAa,uBAChB,MAAO,EAAE,CAG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KAC/C,EAAa,EAAsB,MAAQ,OAE7C,EAEJ,CACF,EAAS,aAAe,EACxB,EAAQ,oBAAoB,UAAW,GAAc,CACnD,OAAO,EAAS,aAAa,GAE7B,OAAO,IAAW,IAClB,CAEE,IAAa,aAEf,GAAU,UAAU,eAAgB,GAAM,EAE5C"}
|
|
@@ -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"}
|
package/dist/hooks/find.js
CHANGED
|
@@ -1,30 +1,2 @@
|
|
|
1
|
-
|
|
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};
|
|
30
2
|
//# sourceMappingURL=find.js.map
|
package/dist/hooks/find.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"find.js","
|
|
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
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"hooks.cjs","names":["ajv","Ajv","beforeFull: any","applyScopeToInstance","BadRequest","where: WhereOptions","CustomFieldDefinitionType","Joi","InvalidValueError","MissingRequiredCustomFieldError","updateInstanceValues"],"sources":["../../src/hooks/hooks.ts"],"sourcesContent":["import type {\n BulkCreateOptions, CreateOptions, UpdateOptions, WhereOptions,\n} from 'sequelize';\nimport Ajv from 'ajv';\nimport Joi from 'joi';\nimport addFormats from 'ajv-formats';\nimport { BadRequest } from '@autofleet/errors';\nimport ajvErrors from 'ajv-errors';\nimport logger from '../utils/logger';\nimport * as ValidatorRepo from '../repository/validator';\nimport * as DefinitionRepo from '../repository/definition';\nimport { InvalidValueError, MissingRequiredCustomFieldError } from '../errors';\nimport type { CustomFieldOptions, ModelOptions } from '../types';\nimport applyScopeToInstance from '../utils/scopeAttributes';\nimport updateInstanceValues from './utils/updateInstanceValues';\nimport { CustomFieldDefinitionType } from '../utils/constants';\nimport type { CustomFieldDefinition } from '../models';\n\n// Include all required fields for proper validation\nconst CUSTOM_VALIDATOR_ATTRIBUTES_TO_PULL = ['id', 'schema', 'modelType', 'entityId', 'disabled'];\n\n// Initialize Ajv with relaxed settings to avoid warnings\nconst ajv = new Ajv({\n allErrors: true,\n strict: false, // Disable strict mode to avoid warnings\n strictTypes: false, // Disable strict type checking\n $data: true, // Enable $data references\n});\n\naddFormats(ajv);\najvErrors(ajv);\n\n/**\n * Helper function to manually copy object properties\n * This is more efficient for large objects and avoids excessive object creation\n */\n// eslint-disable-next-line prefer-object-spread\nconst manualObjectCopy = (sourceObj: Record<string, any>, additionalProps?: Record<string, any>): Record<string, any> =>\n ({ __proto__: null, ...sourceObj, ...additionalProps });\n\n/**\n * Fetches complete custom fields for an instance by merging DB values with update values\n * This is needed for partial updates to ensure all related fields are available for validation\n */\nconst getCompleteCustomFields = async (instance, options): Promise<Record<string, any>> => {\n // If we don't have an instance id or no custom fields being updated, return original fields\n if (!instance.id || !instance.customFields || Object.keys(instance.customFields).length === 0) {\n return instance.customFields || {};\n }\n\n try {\n const ModelClass = instance.constructor;\n // Only select the customFields column to minimize data transfer\n const currentCustomFields = await ModelClass.findOne({\n where: { id: instance.id },\n attributes: ['customFields'],\n transaction: options.transaction,\n raw: true, // Get plain object instead of model instance for better performance\n });\n\n if (currentCustomFields?.customFields) {\n // Merge existing fields with update fields using our helper function\n const completeFields = manualObjectCopy(\n currentCustomFields.customFields,\n instance.customFields,\n );\n\n logger.debug('sadot - fetched complete custom fields for validation', {\n fieldsCount: Object.keys(completeFields).length,\n updateFieldsCount: Object.keys(instance.customFields).length,\n });\n\n return completeFields;\n }\n } catch (error) {\n logger.error('sadot - error fetching complete model for validation', { error });\n // Continue with partial data if we can't fetch the complete model\n }\n\n return instance.customFields || {};\n};\n\nconst buildPreChangeState = (instance: any) => {\n const beforeFull: any = { ...instance.dataValues };\n\n const changedKeys: string[] = instance.changed?.() || [];\n changedKeys.forEach((key) => {\n const prevVal = instance.previous?.(key);\n if (prevVal !== undefined) {\n beforeFull[key] = prevVal;\n }\n });\n\n const prevCF = instance.previous?.('customFields');\n if (prevCF !== undefined) {\n beforeFull.customFields = prevCF;\n }\n\n return beforeFull;\n};\n\nconst formatAjvErrors = (\n errors: {\n instancePath?: string;\n keyword: string;\n message?: string;\n params?: Record<string, any>;\n}[],\n): Record<string, string> => errors.reduce((acc, err) => {\n const basePath = (err.instancePath || '')\n .split('/')\n .filter(Boolean)\n .join('.')\n .replace(/^after\\./, '');\n\n const missingProp = err.keyword === 'required' ? `.${err.params?.missingProperty}` : '';\n const key = (basePath + missingProp).replace(/^\\./, '') || 'root';\n\n const message = err.message || 'Invalid value';\n acc[key] = message;\n\n return acc;\n}, {} as Record<string, string>);\n\n/**\n * Validates the model using custom validators\n */\nconst validateModel = async (\n instance,\n options,\n scopeAttributes: string[],\n modelOptions: ModelOptions = {},\n isCreate = false,\n): Promise<void> => {\n const modelType = instance.constructor.name;\n\n logger.debug('sadot - validating model', { isCreate, modelType });\n const identifiers = applyScopeToInstance(instance, scopeAttributes);\n\n logger.debug('sadot - identifiers', { identifiers });\n\n // Skip if no identifiers\n if (!identifiers || Object.keys(identifiers).length === 0) {\n logger.debug('sadot - skipping validation: no identifiers');\n return;\n }\n\n // Find the entityId from identifiers (fleetId, businessModelId, etc.)\n const entityId = Object.values(identifiers)[0]; // Get the first value as entityId\n\n logger.debug('sadot - entityId', { entityId });\n\n if (!entityId) {\n logger.debug('sadot - skipping validation: no entityId');\n return;\n }\n\n let validatorsPromise;\n let cacheKey;\n if (options.transaction) {\n // eslint-disable-next-line no-param-reassign\n options.transaction.validationsCache ||= new Map();\n cacheKey = `${modelType}-${entityId}`;\n validatorsPromise = options.transaction.validationsCache.get(cacheKey);\n }\n\n if (!validatorsPromise) {\n validatorsPromise = ValidatorRepo.findAllByModelType(\n modelType,\n entityId,\n {\n transaction: options.transaction,\n attributes: CUSTOM_VALIDATOR_ATTRIBUTES_TO_PULL,\n modelOptions,\n },\n );\n if (options.transaction) {\n options?.transaction?.validationsCache.set(cacheKey, validatorsPromise);\n }\n }\n const validators = await validatorsPromise;\n\n logger.debug('sadot - validators found', { count: validators.length });\n\n if (!validators.length) {\n logger.debug('sadot - skipping validation: no validators found');\n return;\n }\n\n // For updates, get the previous values\n let originalValues = null;\n if (!isCreate) {\n originalValues = buildPreChangeState(instance);\n }\n\n // Get complete custom fields by merging DB values with update values\n // This is especially important for partial updates to ensure all related fields are available\n const completeCustomFields = !isCreate\n ? await getCompleteCustomFields(instance, options)\n : instance.customFields || {};\n\n // eslint-disable-next-line no-restricted-syntax\n for (const validator of validators) {\n const { schema } = validator;\n const typedSchema = schema as Record<string, any>;\n\n logger.debug('sadot - validating with schema', {\n schema,\n hasAfterProps: !!typedSchema.properties?.after,\n hasBeforeProps: !!typedSchema.properties?.before,\n });\n\n if (isCreate) {\n // For create operations, we only need the 'after' state\n if (typedSchema.properties?.after) {\n const validateSchema = ajv.compile({\n ...schema,\n // Focus only on the 'after' validation part for create\n properties: {\n after: typedSchema.properties.after,\n },\n });\n\n const isValid = validateSchema(JSON.parse(JSON.stringify({\n after: {\n ...instance.dataValues,\n customFields: completeCustomFields,\n },\n })));\n\n if (!isValid) {\n const errorDetails = validateSchema.errors?.map((err) =>\n `${(err as any).instancePath || ''} ${(err as any).message || 'Invalid value'}`).join(', ');\n\n const formattedErrors = formatAjvErrors(validateSchema.errors);\n throw new BadRequest(\n [new Error(`Validation failed for ${modelType}: ${errorDetails}`)],\n undefined,\n {\n customError: formattedErrors,\n },\n );\n }\n }\n } else {\n // For update operations, we need both before and after\n const validateSchema = ajv.compile(typedSchema);\n\n // Create after object with our helper function\n const afterObj = manualObjectCopy(instance.dataValues);\n\n // Add complete custom fields\n afterObj.customFields = completeCustomFields;\n\n // Create validation payload\n const payload = {\n before: originalValues,\n after: afterObj,\n };\n\n // Validate\n const isValid = validateSchema(JSON.parse(JSON.stringify(payload)));\n\n logger.debug('sadot - validation result', {\n isValid,\n test: {\n before: originalValues,\n after: afterObj,\n },\n });\n\n if (!isValid) {\n const errorDetails = validateSchema\n .errors\n ?.map((err) => `${(err as any).instancePath || ''} ${(err as any).message || 'Invalid value'}`).join(', ');\n\n const formattedErrors = formatAjvErrors(validateSchema.errors);\n throw new BadRequest(\n [new Error(`Validation failed for ${modelType}: ${errorDetails}`)],\n undefined,\n {\n customError: formattedErrors,\n },\n );\n }\n }\n }\n};\n\nconst getFieldDefinitions = async ({\n modelType,\n modelOptions,\n identifiers,\n options,\n}: {\n modelType: any,\n modelOptions: ModelOptions,\n identifiers: any[],\n options: any\n}) => {\n const { include, useEntityIdFromInclude } = modelOptions;\n const where: WhereOptions = {\n modelType,\n disabled: false,\n ...(!useEntityIdFromInclude && { entityId: identifiers }),\n };\n\n const fieldDefinitions = await DefinitionRepo.findAll(where, {\n withDisabled: false,\n transaction: options.transaction,\n include: include?.(identifiers),\n });\n return fieldDefinitions;\n};\n\nconst formatDates = (fieldDefinitions: CustomFieldDefinition[], instance: any) => {\n (fieldDefinitions || []).forEach((fieldDefinition) => {\n const { fieldType, name } = fieldDefinition;\n if ([CustomFieldDefinitionType.DATE, CustomFieldDefinitionType.DATETIME].includes(fieldType)) {\n const value = instance.customFields?.[name];\n if (value) {\n const { value: joiValue, error: validationError } = Joi.date().validate(value);\n if (validationError) {\n throw new InvalidValueError(value, name, validationError);\n }\n // eslint-disable-next-line no-param-reassign\n instance.customFields[name] = joiValue.toISOString();\n }\n }\n });\n};\n\n/**\n * Hook to handle validation and custom fields during creation\n */\nexport const beforeCreate = (\n scopeAttributes: string[],\n modelOptions: ModelOptions = {},\n sadotOptions: Pick<CustomFieldOptions, 'useCustomFieldsEntries'> = { useCustomFieldsEntries: false },\n) => async (\n instance: any,\n options: CreateOptions,\n): Promise<void> => {\n logger.debug('sadot - before create hook');\n const { fields } = options;\n const modelType = instance.constructor.name;\n\n const identifiers = applyScopeToInstance(instance, scopeAttributes);\n\n // Step 1: Handle custom fields default values and required fields\n\n const fieldDefinitions = await getFieldDefinitions({\n modelType, modelOptions, identifiers, options,\n });\n\n // Apply default values\n const fieldsWithDefaultValue = fieldDefinitions.filter((def) => ![null, undefined].includes(def.defaultValue));\n if (fieldsWithDefaultValue.length) {\n // eslint-disable-next-line no-param-reassign\n instance.customFields ||= {};\n fieldsWithDefaultValue\n .filter((def) => (instance.customFields?.[def.name] === undefined))\n .forEach(({ name, defaultValue }) => {\n // eslint-disable-next-line no-param-reassign\n instance.customFields[name] = defaultValue;\n });\n }\n\n // Check for required fields\n const requiredFieldsNames = Array.from(\n new Set(fieldDefinitions.filter(({ required }) => required).map(({ name }) => name)),\n );\n const { customFields } = instance;\n const fieldsNames = Object.keys(customFields ?? {});\n const missingFields = requiredFieldsNames.filter((name) => !fieldsNames.includes(name));\n if (missingFields?.length) {\n throw new MissingRequiredCustomFieldError(missingFields);\n }\n\n // Step 2: Validate the model data (including custom fields)\n await validateModel(instance, options, scopeAttributes, modelOptions, true);\n\n // format date and datetime fields\n formatDates(fieldDefinitions, instance);\n\n // Step 3: Save custom field values if they exist\n const customFieldsIdx = fields.indexOf('customFields');\n if (customFieldsIdx === -1 || !customFields || !Object.keys(customFields).length) {\n // No custom fields to update\n return;\n }\n\n // Save custom field values\n await updateInstanceValues({\n modelId: instance.id,\n modelType,\n identifiers,\n customFields,\n options: {\n useCustomFieldsEntries: sadotOptions.useCustomFieldsEntries,\n transaction: options.transaction,\n modelOptions,\n },\n });\n\n // Remove customFields from fields array after handling\n // eslint-disable-next-line no-param-reassign\n fields.splice(customFieldsIdx, 1);\n};\n\n/**\n * Hook to handle validation and custom fields during update\n */\nexport const beforeUpdate = (\n scopeAttributes: string[],\n modelOptions: ModelOptions = {},\n sadotOptions: Pick<CustomFieldOptions, 'useCustomFieldsEntries'> = { useCustomFieldsEntries: false },\n) => async (\n instance: any,\n options: UpdateOptions,\n): Promise<void> => {\n logger.debug('sadot - before update hook');\n const { fields } = options;\n const modelType = instance.constructor.name;\n const identifiers = applyScopeToInstance(instance, scopeAttributes);\n\n const fieldDefinitions = await getFieldDefinitions({\n modelType, modelOptions, identifiers, options,\n });\n\n // Step 1: Validate the model data (including custom fields)\n await validateModel(instance, options, scopeAttributes, modelOptions, false);\n\n // format date and datetime fields\n formatDates(fieldDefinitions, instance);\n\n // Step 2: Update custom field values if they exist\n const customFieldsIdx = fields.indexOf('customFields');\n if (customFieldsIdx > -1) {\n const { customFields } = instance;\n\n if (!Object.keys(customFields).length) {\n return;\n }\n\n // Save custom field values\n await updateInstanceValues({\n modelId: instance.id,\n modelType,\n identifiers,\n customFields,\n options: {\n useCustomFieldsEntries: sadotOptions.useCustomFieldsEntries,\n transaction: options.transaction,\n modelOptions,\n },\n });\n\n // Remove customFields from fields array after handling\n // eslint-disable-next-line no-param-reassign\n fields.splice(customFieldsIdx, 1);\n }\n};\n\n/**\n * Hook to enable individual hooks for bulk create operations\n */\nexport const beforeBulkCreate = (options: BulkCreateOptions): void => {\n // This will activate the beforeCreate hook on each instance\n // eslint-disable-next-line no-param-reassign\n options.individualHooks = true;\n};\n\n/**\n * Hook to enable individual hooks for bulk update operations\n */\nexport const beforeBulkUpdate = (options: UpdateOptions): void => {\n // This will activate the beforeUpdate hook on each instance\n // eslint-disable-next-line no-param-reassign\n options.individualHooks = true;\n};\n"],"mappings":"kiBAmBA,MAAM,EAAsC,CAAC,KAAM,SAAU,YAAa,WAAY,WAAW,CAG3FA,EAAM,IAAIC,EAAAA,QAAI,CAClB,UAAW,GACX,OAAQ,GACR,YAAa,GACb,MAAO,GACR,CAAC,eAESD,EAAI,eACLA,EAAI,CAOd,MAAM,GAAoB,EAAgC,KACvD,CAAE,UAAW,KAAM,GAAG,EAAW,GAAG,EAAiB,EAMlD,EAA0B,MAAO,EAAU,IAA0C,CAEzF,GAAI,CAAC,EAAS,IAAM,CAAC,EAAS,cAAgB,OAAO,KAAK,EAAS,aAAa,CAAC,SAAW,EAC1F,OAAO,EAAS,cAAgB,EAAE,CAGpC,GAAI,CAGF,IAAM,EAAsB,MAFT,EAAS,YAEiB,QAAQ,CACnD,MAAO,CAAE,GAAI,EAAS,GAAI,CAC1B,WAAY,CAAC,eAAe,CAC5B,YAAa,EAAQ,YACrB,IAAK,GACN,CAAC,CAEF,GAAI,GAAqB,aAAc,CAErC,IAAM,EAAiB,EACrB,EAAoB,aACpB,EAAS,aACV,CAOD,OALA,EAAA,QAAO,MAAM,wDAAyD,CACpE,YAAa,OAAO,KAAK,EAAe,CAAC,OACzC,kBAAmB,OAAO,KAAK,EAAS,aAAa,CAAC,OACvD,CAAC,CAEK,SAEF,EAAO,CACd,EAAA,QAAO,MAAM,uDAAwD,CAAE,QAAO,CAAC,CAIjF,OAAO,EAAS,cAAgB,EAAE,EAG9B,EAAuB,GAAkB,CAC7C,IAAME,EAAkB,CAAE,GAAG,EAAS,WAAY,EAEpB,EAAS,WAAW,EAAI,EAAE,EAC5C,QAAS,GAAQ,CAC3B,IAAM,EAAU,EAAS,WAAW,EAAI,CACpC,IAAY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