@autofleet/sadot 1.4.26 → 1.5.1

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 (55) hide show
  1. package/dist/api/v1/definition/index.cjs +1 -1
  2. package/dist/api/v1/definition/index.cjs.map +1 -1
  3. package/dist/api/v1/definition/index.js +1 -1
  4. package/dist/api/v1/definition/index.js.map +1 -1
  5. package/dist/api/v1/definition/validations.cjs +1 -1
  6. package/dist/api/v1/definition/validations.cjs.map +1 -1
  7. package/dist/api/v1/definition/validations.js +1 -1
  8. package/dist/api/v1/definition/validations.js.map +1 -1
  9. package/dist/hooks/enrich.cjs +1 -1
  10. package/dist/hooks/enrich.cjs.map +1 -1
  11. package/dist/hooks/enrich.js +1 -1
  12. package/dist/hooks/enrich.js.map +1 -1
  13. package/dist/hooks/hooks.cjs +1 -1
  14. package/dist/hooks/hooks.cjs.map +1 -1
  15. package/dist/hooks/hooks.js +1 -1
  16. package/dist/hooks/hooks.js.map +1 -1
  17. package/dist/index.cjs +1 -1
  18. package/dist/index.cjs.map +1 -1
  19. package/dist/index.js +1 -1
  20. package/dist/index.js.map +1 -1
  21. package/dist/mat-path-state.cjs +2 -0
  22. package/dist/mat-path-state.cjs.map +1 -0
  23. package/dist/mat-path-state.js +2 -0
  24. package/dist/mat-path-state.js.map +1 -0
  25. package/dist/models/index.cjs +1 -1
  26. package/dist/models/index.cjs.map +1 -1
  27. package/dist/models/index.js +1 -1
  28. package/dist/models/index.js.map +1 -1
  29. package/dist/types/index.d.cts +7 -0
  30. package/dist/types/index.d.ts +7 -0
  31. package/dist/utils/constants/index.cjs +1 -1
  32. package/dist/utils/constants/index.cjs.map +1 -1
  33. package/dist/utils/constants/index.d.cts +2 -0
  34. package/dist/utils/constants/index.d.ts +2 -0
  35. package/dist/utils/constants/index.js +1 -1
  36. package/dist/utils/constants/index.js.map +1 -1
  37. package/dist/utils/validations/validators/index.cjs +1 -1
  38. package/dist/utils/validations/validators/index.cjs.map +1 -1
  39. package/dist/utils/validations/validators/index.js +1 -1
  40. package/dist/utils/validations/validators/index.js.map +1 -1
  41. package/dist/utils/validations/validators/multi-select-dropdown.validator.cjs +2 -0
  42. package/dist/utils/validations/validators/multi-select-dropdown.validator.cjs.map +1 -0
  43. package/dist/utils/validations/validators/multi-select-dropdown.validator.js +2 -0
  44. package/dist/utils/validations/validators/multi-select-dropdown.validator.js.map +1 -0
  45. package/dist/utils/validations/validators/multi-select-status.validator.cjs +2 -0
  46. package/dist/utils/validations/validators/multi-select-status.validator.cjs.map +1 -0
  47. package/dist/utils/validations/validators/multi-select-status.validator.js +2 -0
  48. package/dist/utils/validations/validators/multi-select-status.validator.js.map +1 -0
  49. package/dist/utils/validations/validators/multi-select.helpers.cjs +2 -0
  50. package/dist/utils/validations/validators/multi-select.helpers.cjs.map +1 -0
  51. package/dist/utils/validations/validators/multi-select.helpers.js +2 -0
  52. package/dist/utils/validations/validators/multi-select.helpers.js.map +1 -0
  53. package/dist/utils/validations/validators/status.validator.cjs.map +1 -1
  54. package/dist/utils/validations/validators/status.validator.js.map +1 -1
  55. package/package.json +1 -1
@@ -1,2 +1,2 @@
1
- import e from"../utils/logger/index.js";import{CustomFieldDefinitionType as t}from"../utils/constants/index.js";import{InvalidValueError as n,MissingRequiredCustomFieldError as r}from"../errors/index.js";import{findAll as i,findByModelTypeId as a}from"../repository/definition.js";import{findAllByModelType as o}from"../repository/validator.js";import s from"../utils/scopeAttributes.js";import c from"./utils/updateInstanceValues.js";import l from"joi";import{BadRequest as u}from"@autofleet/errors";import d from"ajv";import f from"ajv-formats";import p from"ajv-errors";const m=[`id`,`schema`,`modelType`,`entityId`,`disabled`],h=new d({allErrors:!0,strict:!1,strictTypes:!1,$data:!0});f(h),p(h);const g=(e,t)=>({__proto__:null,...e,...t}),_=async(t,n)=>{if(!t.id||!t.customFields||Object.keys(t.customFields).length===0)return t.customFields||{};try{let r=await t.constructor.findOne({where:{id:t.id},attributes:[`customFields`],transaction:n.transaction,raw:!0});if(r?.customFields){let n=g(r.customFields,t.customFields);return e.debug(`sadot - fetched complete custom fields for validation`,{fieldsCount:Object.keys(n).length,updateFieldsCount:Object.keys(t.customFields).length}),n}}catch(t){e.error(`sadot - error fetching complete model for validation`,{error:t})}return t.customFields||{}},v=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},y=e=>e.reduce((e,t)=>{let n=((t.instancePath||``).split(`/`).filter(Boolean).join(`.`).replace(/^after\./,``)+(t.keyword===`required`?`.${t.params?.missingProperty}`:``)).replace(/^\./,``)||`root`;return e[n]=t.message||`Invalid value`,e},{}),b=async(t,n,r,i={},a=!1)=>{let c=t.constructor.name;e.debug(`sadot - validating model`,{isCreate:a,modelType:c});let l=s(t,r);if(e.debug(`sadot - identifiers`,{identifiers:l}),!l||Object.keys(l).length===0){e.debug(`sadot - skipping validation: no identifiers`);return}let d=Object.values(l)[0];if(e.debug(`sadot - entityId`,{entityId:d}),!d){e.debug(`sadot - skipping validation: no entityId`);return}let f,p;n.transaction&&(n.transaction.validationsCache??=new Map,p=`${c}-${d}`,f=n.transaction.validationsCache.get(p)),f||(f=o(c,d,{transaction:n.transaction,attributes:m,modelOptions:i}),n.transaction&&n?.transaction?.validationsCache.set(p,f));let b=await f;if(e.debug(`sadot - validators found`,{count:b.length}),!b.length){e.debug(`sadot - skipping validation: no validators found`);return}let x=null;a||(x=v(t));let S=a?t.customFields||{}:await _(t,n);for(let n of b){let{schema:r}=n,i=r;if(e.debug(`sadot - validating with schema`,{schema:r,hasAfterProps:!!i.properties?.after,hasBeforeProps:!!i.properties?.before}),a){if(i.properties?.after){let e=h.compile({...r,properties:{after:i.properties.after}});if(!e(JSON.parse(JSON.stringify({after:{...t.dataValues,customFields:S}})))){let t=e.errors?.map(e=>`${e.instancePath||``} ${e.message||`Invalid value`}`).join(`, `),n=y(e.errors);throw new u([Error(`Validation failed for ${c}: ${t}`)],void 0,{customError:n})}}}else{let n=h.compile(i),r=g(t.dataValues);r.customFields=S;let a={before:x,after:r},o=n(JSON.parse(JSON.stringify(a)));if(e.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=y(n.errors);throw new u([Error(`Validation failed for ${c}: ${e}`)],void 0,{customError:t})}}}},x=async({modelType:e,modelOptions:t,identifiers:n,options:r,instance:o,hasTypeId:s})=>{let{include:c,useEntityIdFromInclude:l}=t;return s&&o?.typeId?a(o.typeId,{withDisabled:!1,transaction:r.transaction,entityIds:n,modelType:e,modelOptions:t}):await i({modelType:e,disabled:!1,...!l&&{entityId:n}},{withDisabled:!1,transaction:r.transaction,include:c?.(n)})},S=(e,r)=>{(e||[]).forEach(e=>{let{fieldType:i,name:a}=e;if([t.DATE,t.DATETIME].includes(i)){let e=r.customFields?.[a];if(e){let{value:t,error:i}=l.date().validate(e);if(i)throw new n(e,a,i);r.customFields[a]=t.toISOString()}}})},C=(t,n={},i={useCustomFieldsEntries:!1})=>async(a,o)=>{e.debug(`sadot - before create hook`);let{fields:l}=o,u=a.constructor.name,d=s(a,t),f=await x({modelType:u,modelOptions:n,identifiers:d,options:o,instance:a,hasTypeId:i.hasTypeId}),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;m=i.getRequiredCustomFields?await Promise.resolve(i.getRequiredCustomFields(a,f,o)):Array.from(new Set(f.filter(({required:e})=>e).map(({name:e})=>e)));let{customFields:h}=a,g=Object.keys(h??{}),_=m.filter(e=>!g.includes(e));if(_?.length)throw new r(_);await b(a,o,t,n,!0),S(f,a);let v=l.indexOf(`customFields`);v===-1||!h||!Object.keys(h).length||(await c({modelId:a.id,modelType:u,identifiers:d,customFields:h,options:{useCustomFieldsEntries:i.useCustomFieldsEntries,transaction:o.transaction,modelOptions:n}}),l.splice(v,1))},w=(t,n={},r={useCustomFieldsEntries:!1})=>async(i,a)=>{e.debug(`sadot - before update hook`);let{fields:o}=a,l=i.constructor.name,u=s(i,t),d=await x({modelType:l,modelOptions:n,identifiers:u,options:a,instance:i,hasTypeId:r.hasTypeId});await b(i,a,t,n,!1),S(d,i);let f=o.indexOf(`customFields`);if(f>-1){let{customFields:e}=i;if(!Object.keys(e).length)return;await c({modelId:i.id,modelType:l,identifiers:u,customFields:e,options:{useCustomFieldsEntries:r.useCustomFieldsEntries,transaction:a.transaction,modelOptions:n}}),o.splice(f,1)}},T=e=>{e.individualHooks=!0},E=e=>{e.individualHooks=!0};export{T as beforeBulkCreate,E as beforeBulkUpdate,C as beforeCreate,w as beforeUpdate};
1
+ import e from"../utils/logger/index.js";import{CustomFieldDefinitionType as t}from"../utils/constants/index.js";import{InvalidValueError as n,MissingRequiredCustomFieldError as r}from"../errors/index.js";import{findAll as i,findByModelTypeId as a}from"../repository/definition.js";import{findAllByModelType as o}from"../repository/validator.js";import s from"../utils/scopeAttributes.js";import c from"./utils/updateInstanceValues.js";import l from"joi";import{BadRequest as u}from"@autofleet/errors";import d from"ajv";import f from"ajv-formats";import p from"ajv-errors";const m=[`id`,`schema`,`modelType`,`entityId`,`disabled`],h=new d({allErrors:!0,strict:!1,strictTypes:!1,$data:!0});f(h),p(h);const g=(e,t)=>({__proto__:null,...e,...t}),_=async(t,n)=>{if(!t.id||!t.customFields||Object.keys(t.customFields).length===0)return t.customFields||{};try{let r=await t.constructor.findOne({where:{id:t.id},attributes:[`customFields`],transaction:n.transaction,raw:!0});if(r?.customFields){let n=g(r.customFields,t.customFields);return e.debug(`sadot - fetched complete custom fields for validation`,{fieldsCount:Object.keys(n).length,updateFieldsCount:Object.keys(t.customFields).length}),n}}catch(t){e.error(`sadot - error fetching complete model for validation`,{error:t})}return t.customFields||{}},v=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},y=e=>e.reduce((e,t)=>{let n=((t.instancePath||``).split(`/`).filter(Boolean).join(`.`).replace(/^after\./,``)+(t.keyword===`required`?`.${t.params?.missingProperty}`:``)).replace(/^\./,``)||`root`;return e[n]=t.message||`Invalid value`,e},{}),b=async(t,n,r,i={},a=!1)=>{let c=t.constructor.name;e.debug(`sadot - validating model`,{isCreate:a,modelType:c});let l=s(t,r);if(e.debug(`sadot - identifiers`,{identifiers:l}),!l||Object.keys(l).length===0){e.debug(`sadot - skipping validation: no identifiers`);return}let d=Object.values(l)[0];if(e.debug(`sadot - entityId`,{entityId:d}),!d){e.debug(`sadot - skipping validation: no entityId`);return}let f,p;n.transaction&&(n.transaction.validationsCache??=new Map,p=`${c}-${d}`,f=n.transaction.validationsCache.get(p)),f||(f=o(c,d,{transaction:n.transaction,attributes:m,modelOptions:i}),n.transaction&&n?.transaction?.validationsCache.set(p,f));let b=await f;if(e.debug(`sadot - validators found`,{count:b.length}),!b.length){e.debug(`sadot - skipping validation: no validators found`);return}let x=null;a||(x=v(t));let S=a?t.customFields||{}:await _(t,n);for(let n of b){let{schema:r}=n,i=r;if(e.debug(`sadot - validating with schema`,{schema:r,hasAfterProps:!!i.properties?.after,hasBeforeProps:!!i.properties?.before}),a){if(i.properties?.after){let e=h.compile({...r,properties:{after:i.properties.after}});if(!e(JSON.parse(JSON.stringify({after:{...t.dataValues,customFields:S}})))){let t=e.errors?.map(e=>`${e.instancePath||``} ${e.message||`Invalid value`}`).join(`, `),n=y(e.errors);throw new u([Error(`Validation failed for ${c}: ${t}`)],void 0,{customError:n})}}}else{let n=h.compile(i),r=g(t.dataValues);r.customFields=S;let a={before:x,after:r},o=n(JSON.parse(JSON.stringify(a)));if(e.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=y(n.errors);throw new u([Error(`Validation failed for ${c}: ${e}`)],void 0,{customError:t})}}}},x=async({modelType:e,modelOptions:t,identifiers:n,options:r,instance:o,sadotOptions:s})=>{let{include:c,useEntityIdFromInclude:l}=t;return s.hasTypeId&&o?.typeId?a(o.typeId,{withDisabled:!1,transaction:r.transaction,entityIds:n,modelType:e,modelOptions:t}):i({modelType:e,disabled:!1,...!l&&{entityId:n}},{withDisabled:!1,transaction:r.transaction,include:c?.(n)})},S=(e,r)=>{(e||[]).forEach(e=>{let{fieldType:i,name:a}=e;if([t.DATE,t.DATETIME].includes(i)){let e=r.customFields?.[a];if(e){let{value:t,error:i}=l.date().validate(e);if(i)throw new n(e,a,i);r.customFields[a]=t.toISOString()}}})},C=(t,n={},i={useCustomFieldsEntries:!1})=>async(a,o)=>{e.debug(`sadot - before create hook`);let{fields:l}=o,u=a.constructor.name,d=s(a,t),f=await x({modelType:u,modelOptions:n,identifiers:d,options:o,instance:a,sadotOptions:i}),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;m=i.getRequiredCustomFields?await Promise.resolve(i.getRequiredCustomFields(a,f,o)):Array.from(new Set(f.filter(({required:e})=>e).map(({name:e})=>e)));let{customFields:h}=a,g=Object.keys(h??{}),_=m.filter(e=>!g.includes(e));if(_?.length)throw new r(_);await b(a,o,t,n,!0),S(f,a);let v=l.indexOf(`customFields`);v===-1||!h||!Object.keys(h).length||(await c({modelId:a.id,modelType:u,identifiers:d,customFields:h,options:{useCustomFieldsEntries:i.useCustomFieldsEntries,transaction:o.transaction,modelOptions:n}}),l.splice(v,1))},w=(t,n={},r={useCustomFieldsEntries:!1})=>async(i,a)=>{e.debug(`sadot - before update hook`);let{fields:o}=a,l=i.constructor.name,u=s(i,t),d=await x({modelType:l,modelOptions:n,identifiers:u,options:a,instance:i,sadotOptions:r});await b(i,a,t,n,!1),S(d,i);let f=o.indexOf(`customFields`);if(f>-1){let{customFields:e}=i;if(!Object.keys(e).length)return;await c({modelId:i.id,modelType:l,identifiers:u,customFields:e,options:{useCustomFieldsEntries:r.useCustomFieldsEntries,transaction:a.transaction,modelOptions:n}}),o.splice(f,1)}},T=e=>{e.individualHooks=!0},E=e=>{e.individualHooks=!0};export{T as beforeBulkCreate,E as beforeBulkUpdate,C as beforeCreate,w as beforeUpdate};
2
2
  //# sourceMappingURL=hooks.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"hooks.js","names":["beforeFull: any","applyScopeToInstance","cacheKey: string | undefined","ValidatorRepo.findAllByModelType","DefinitionRepo.findByModelTypeId","where: WhereOptions","DefinitionRepo.findAll","requiredFieldsNames: string[]","updateInstanceValues"],"sources":["../../src/hooks/hooks.ts"],"sourcesContent":["import type {\n BulkCreateOptions, CreateOptions, Transactionable, 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, TransactionOptions } 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 */\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: any, options: Transactionable): 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: any,\n options: TransactionOptions,\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: string | undefined;\n if (options.transaction) {\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 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 instance,\n hasTypeId,\n}: {\n modelType: any;\n modelOptions: ModelOptions;\n identifiers: any[];\n options: any;\n instance?: any;\n hasTypeId?: boolean;\n}) => {\n const { include, useEntityIdFromInclude } = modelOptions;\n\n // If hasTypeId is enabled and instance has a typeId, filter by modelTypeId\n if (hasTypeId && instance?.typeId) {\n return DefinitionRepo.findByModelTypeId(instance.typeId, {\n withDisabled: false,\n transaction: options.transaction,\n entityIds: identifiers,\n modelType,\n modelOptions,\n });\n }\n\n // Otherwise, use the standard findAll\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 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' | 'getRequiredCustomFields' | 'hasTypeId'> = {\n useCustomFieldsEntries: false,\n },\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, instance, hasTypeId: sadotOptions.hasTypeId,\n });\n\n // Apply default values\n const fieldsWithDefaultValue = fieldDefinitions.filter(def => ![null, undefined].includes(def.defaultValue));\n if (fieldsWithDefaultValue.length) {\n instance.customFields ||= {};\n fieldsWithDefaultValue\n .filter(def => (instance.customFields?.[def.name] === undefined))\n .forEach(({ name, defaultValue }) => {\n instance.customFields[name] = defaultValue;\n });\n }\n\n // Check for required fields\n let requiredFieldsNames: string[];\n\n if (sadotOptions.getRequiredCustomFields) {\n // Use consumer-provided logic to determine required fields\n requiredFieldsNames = await Promise.resolve(\n sadotOptions.getRequiredCustomFields(instance, fieldDefinitions, options),\n );\n } else {\n // Default behavior: use required flag from fieldDefinitions\n requiredFieldsNames = Array.from(\n new Set(fieldDefinitions.filter(({ required }) => required).map(({ name }) => name)),\n );\n }\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 as TransactionOptions, 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 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' | 'getRequiredCustomFields' | 'hasTypeId'> = {\n useCustomFieldsEntries: false,\n },\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, instance, hasTypeId: sadotOptions.hasTypeId,\n });\n\n // Step 1: Validate the model data (including custom fields)\n await validateModel(instance, options as TransactionOptions, 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 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 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 options.individualHooks = true;\n};\n"],"mappings":"6jBAmBA,MAAM,EAAsC,CAAC,KAAM,SAAU,YAAa,WAAY,WAAW,CAG3F,EAAM,IAAI,EAAI,CAClB,UAAW,GACX,OAAQ,GACR,YAAa,GACb,MAAO,GACR,CAAC,CAEF,EAAW,EAAI,CACf,EAAU,EAAI,CAMd,MAAM,GAAoB,EAAgC,KACvD,CAAE,UAAW,KAAM,GAAG,EAAW,GAAG,EAAiB,EAMlD,EAA0B,MAAO,EAAe,IAA2D,CAE/G,GAAI,CAAC,EAAS,IAAM,CAAC,EAAS,cAAgB,OAAO,KAAK,EAAS,aAAa,CAAC,SAAW,EAC1F,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"hooks.js","names":["beforeFull: any","applyScopeToInstance","cacheKey: string | undefined","ValidatorRepo.findAllByModelType","DefinitionRepo.findByModelTypeId","where: WhereOptions","DefinitionRepo.findAll","requiredFieldsNames: string[]","updateInstanceValues"],"sources":["../../src/hooks/hooks.ts"],"sourcesContent":["import type {\n BulkCreateOptions, CreateOptions, Transactionable, 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, TransactionOptions } from '../types';\nimport applyScopeToInstance from '../utils/scopeAttributes';\nimport updateInstanceValues from './utils/updateInstanceValues';\nimport { CustomFieldDefinitionType } from '../utils/constants';\nimport type { CustomFieldDefinition } from '../models';\n\ntype HookSadotOptions = Pick<\n CustomFieldOptions,\n 'useCustomFieldsEntries' | 'getRequiredCustomFields' | 'hasTypeId'\n>;\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 */\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: any, options: Transactionable): 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: any,\n options: TransactionOptions,\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: string | undefined;\n if (options.transaction) {\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 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 instance,\n sadotOptions,\n}: {\n modelType: any;\n modelOptions: ModelOptions;\n identifiers: any[];\n options: any;\n instance?: any;\n sadotOptions: HookSadotOptions;\n}) => {\n const { include, useEntityIdFromInclude } = modelOptions;\n\n if (sadotOptions.hasTypeId && instance?.typeId) {\n return DefinitionRepo.findByModelTypeId(instance.typeId, {\n withDisabled: false,\n transaction: options.transaction,\n entityIds: identifiers,\n modelType,\n modelOptions,\n });\n }\n const where: WhereOptions = {\n modelType,\n disabled: false,\n ...(!useEntityIdFromInclude && { entityId: identifiers }),\n };\n return DefinitionRepo.findAll(where, {\n withDisabled: false,\n transaction: options.transaction,\n include: include?.(identifiers),\n });\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 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: HookSadotOptions = { 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, instance, sadotOptions,\n });\n\n // Apply default values\n const fieldsWithDefaultValue = fieldDefinitions.filter(def => ![null, undefined].includes(def.defaultValue));\n if (fieldsWithDefaultValue.length) {\n instance.customFields ||= {};\n fieldsWithDefaultValue\n .filter(def => (instance.customFields?.[def.name] === undefined))\n .forEach(({ name, defaultValue }) => {\n instance.customFields[name] = defaultValue;\n });\n }\n\n // Check for required fields\n let requiredFieldsNames: string[];\n\n if (sadotOptions.getRequiredCustomFields) {\n // Use consumer-provided logic to determine required fields\n requiredFieldsNames = await Promise.resolve(\n sadotOptions.getRequiredCustomFields(instance, fieldDefinitions, options),\n );\n } else {\n // Default behavior: use required flag from fieldDefinitions\n requiredFieldsNames = Array.from(\n new Set(fieldDefinitions.filter(({ required }) => required).map(({ name }) => name)),\n );\n }\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 as TransactionOptions, 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 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: HookSadotOptions = { 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, instance, sadotOptions,\n });\n\n // Step 1: Validate the model data (including custom fields)\n await validateModel(instance, options as TransactionOptions, 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 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 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 options.individualHooks = true;\n};\n"],"mappings":"6jBAwBA,MAAM,EAAsC,CAAC,KAAM,SAAU,YAAa,WAAY,WAAW,CAG3F,EAAM,IAAI,EAAI,CAClB,UAAW,GACX,OAAQ,GACR,YAAa,GACb,MAAO,GACR,CAAC,CAEF,EAAW,EAAI,CACf,EAAU,EAAI,CAMd,MAAM,GAAoB,EAAgC,KACvD,CAAE,UAAW,KAAM,GAAG,EAAW,GAAG,EAAiB,EAMlD,EAA0B,MAAO,EAAe,IAA2D,CAE/G,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,EAAO,MAAM,wDAAyD,CACpE,YAAa,OAAO,KAAK,EAAe,CAAC,OACzC,kBAAmB,OAAO,KAAK,EAAS,aAAa,CAAC,OACvD,CAAC,CAEK,SAEF,EAAO,CACd,EAAO,MAAM,uDAAwD,CAAE,QAAO,CAAC,CAIjF,OAAO,EAAS,cAAgB,EAAE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AAE,CAC/B,EAAiC,CAAE,uBAAwB,GAAO,GAC/D,MACH,EACA,IACkB,CAClB,EAAO,MAAM,6BAA6B,CAC1C,GAAM,CAAE,UAAW,EACb,EAAY,EAAS,YAAY,KACjC,EAAcP,EAAqB,EAAU,EAAgB,CAE7D,EAAmB,MAAM,EAAoB,CACjD,YAAW,eAAc,cAAa,UAAS,WAAU,eAC1D,CAAC,CAGF,MAAM,EAAc,EAAU,EAA+B,EAAiB,EAAc,GAAM,CAGlG,EAAY,EAAkB,EAAS,CAGvC,IAAM,EAAkB,EAAQ,QAAQ,eAAe,CACvD,GAAI,EAAkB,GAAI,CACxB,GAAM,CAAE,gBAAiB,EAEzB,GAAI,CAAC,OAAO,KAAK,EAAa,CAAC,OAC7B,OAIF,MAAMO,EAAqB,CACzB,QAAS,EAAS,GAClB,YACA,cACA,eACA,QAAS,CACP,uBAAwB,EAAa,uBACrC,YAAa,EAAQ,YACrB,eACD,CACF,CAAC,CAGF,EAAQ,OAAO,EAAiB,EAAE,GAOzB,EAAoB,GAAqC,CAEpE,EAAQ,gBAAkB,IAMf,EAAoB,GAAiC,CAEhE,EAAQ,gBAAkB"}
package/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- Object.defineProperty(exports,`__esModule`,{value:!0});const e=require(`./utils/logger/index.cjs`),t=require(`./utils/constants/index.cjs`),n=require(`./models/CustomFieldValue.cjs`),r=require(`./models/CustomFieldDefinition.cjs`),i=require(`./models/CustomFieldEntries.cjs`),a=require(`./models/CustomValidator.cjs`),o=require(`./models/index.cjs`),s=require(`./api/index.cjs`),c=require(`./utils/db/index.cjs`),l=require(`./utils/helpers/index.cjs`),u=require(`./scopes/filter.cjs`),d=require(`./utils/init.cjs`),f=require(`./init-state.cjs`),p=require(`./utils/validations/schema/custom-fields.cjs`),m=new f.SadotInitializationState,h=async(t,n,r)=>{e.tryAddingTraceIdMiddleware();let{models:i,useCustomFieldsEntries:a,useModelTypeMapping:l}=r;t&&t.use(`/api`,s.default);let u=r.sequelize??c.default(r.databaseConfig);return process.env.NODE_ENV===`test`&&await o.initTestModels(u),d.addHooks(i,n,{useCustomFieldsEntries:a}),await o.initTables(u,r.getUser,{useCustomFieldsEntries:a,useModelTypeMapping:l}),d.addScopes(i,n,{useCustomFieldsEntries:a}),d.applyCustomAssociation(i),e.default.debug(`sadot - custom fields finished initializing with models`,i),u},g=async(e,t,n)=>{let r=h(e,t,n);return m.setInitPromise(r,!n.sequelize),await r};var _=g;const v=(e,t)=>{d.removeHooks(e,t)};exports.CUSTOM_FIELDS_FILTER_SCOPE=t.CUSTOM_FIELDS_FILTER_SCOPE,exports.CustomFieldDefinition=r.default,exports.CustomFieldDefinitionType=t.CustomFieldDefinitionType,exports.CustomFieldEntries=i.default,exports.CustomFieldValue=n.default,exports.CustomFieldsSchema=p.CustomFieldsSchema,exports.CustomValidator=a.default,exports.customFieldsSortScope=u.customFieldsSortScope,exports.default=_,exports.disableCustomFields=v,exports.generateCustomFieldSearchQueryPayload=l.generateCustomFieldSearchQueryPayload,exports.generateRandomString=l.generateRandomString,exports.sadotInitState=m,exports.supportedEntities=t.supportedEntities;
1
+ Object.defineProperty(exports,`__esModule`,{value:!0});const e=require(`./utils/logger/index.cjs`),t=require(`./utils/constants/index.cjs`),n=require(`./models/CustomFieldValue.cjs`),r=require(`./models/CustomFieldDefinition.cjs`),i=require(`./models/CustomFieldEntries.cjs`),a=require(`./models/CustomValidator.cjs`),o=require(`./models/index.cjs`),s=require(`./mat-path-state.cjs`),c=require(`./api/index.cjs`),l=require(`./utils/db/index.cjs`),u=require(`./utils/helpers/index.cjs`),d=require(`./scopes/filter.cjs`),f=require(`./utils/init.cjs`),p=require(`./init-state.cjs`),m=require(`./utils/validations/schema/custom-fields.cjs`),h=new p.SadotInitializationState,g=async(t,n,r)=>{e.tryAddingTraceIdMiddleware();let{models:i,useCustomFieldsEntries:a,useModelTypeMapping:u,isMatPathEnabled:d}=r;s.matPathState.isMatPathEnabled=d,t&&t.use(`/api`,c.default);let p=r.sequelize??l.default(r.databaseConfig);return process.env.NODE_ENV===`test`&&await o.initTestModels(p),f.addHooks(i,n,{useCustomFieldsEntries:a}),await o.initTables(p,r.getUser,{useCustomFieldsEntries:a,useModelTypeMapping:u,isMatPathEnabled:d}),f.addScopes(i,n,{useCustomFieldsEntries:a}),f.applyCustomAssociation(i),e.default.debug(`sadot - custom fields finished initializing with models`,i),p},_=async(e,t,n)=>{let r=g(e,t,n);return h.setInitPromise(r,!n.sequelize),await r};var v=_;const y=(e,t)=>{f.removeHooks(e,t)};exports.CUSTOM_FIELDS_FILTER_SCOPE=t.CUSTOM_FIELDS_FILTER_SCOPE,exports.CustomFieldDefinition=r.default,exports.CustomFieldDefinitionType=t.CustomFieldDefinitionType,exports.CustomFieldEntries=i.default,exports.CustomFieldValue=n.default,exports.CustomFieldsSchema=m.CustomFieldsSchema,exports.CustomValidator=a.default,exports.customFieldsSortScope=d.customFieldsSortScope,exports.default=v,exports.disableCustomFields=y,exports.generateCustomFieldSearchQueryPayload=u.generateCustomFieldSearchQueryPayload,exports.generateRandomString=u.generateRandomString,exports.sadotInitState=h,exports.supportedEntities=t.supportedEntities;
2
2
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["sadotInitState: SadotInitializationState","SadotInitializationState","api","initDB","initTestModels","initTables"],"sources":["../src/index.ts"],"sourcesContent":["import type { Application } from 'express';\nimport type { Sequelize } from 'sequelize-typescript';\nimport {\n initTables, initTestModels,\n} from './models';\nimport api from './api';\nimport initDB from './utils/db';\nimport logger, { tryAddingTraceIdMiddleware } from './utils/logger';\nimport type { CustomFieldOptions, ModelFetcher, Models } from './types';\nimport {\n addHooks, addScopes, applyCustomAssociation, removeHooks,\n} from './utils/init';\nimport { SadotInitializationState } from './init-state';\n\nexport * from './utils/validations/schema/custom-fields';\n\nexport * from './utils/constants';\n\nexport * from './utils/helpers';\n\nexport { customFieldsSortScope } from './scopes/filter';\nexport {\n CustomFieldDefinition,\n CustomFieldEntries,\n CustomFieldValue,\n CustomValidator,\n} from './models';\n\nexport const sadotInitState: SadotInitializationState = new SadotInitializationState();\n\n/**\n * Internal implementation of custom fields initialization\n * Contains all the business logic without state tracking\n */\nconst internalUseCustomFields = async (\n app: Pick<Application, 'use'> | null,\n getModel: ModelFetcher,\n options: CustomFieldOptions,\n): Promise<Sequelize> => {\n tryAddingTraceIdMiddleware();\n const { models, useCustomFieldsEntries, useModelTypeMapping } = options;\n if (app) {\n app.use('/api', api);\n }\n const sequelize = options.sequelize ?? initDB(options.databaseConfig);\n if (process.env.NODE_ENV === 'test') {\n await initTestModels(sequelize);\n }\n // The order is important\n addHooks(models, getModel, { useCustomFieldsEntries });\n await initTables(sequelize, options.getUser, { useCustomFieldsEntries, useModelTypeMapping });\n addScopes(models, getModel, { useCustomFieldsEntries });\n applyCustomAssociation(models);\n\n logger.debug('sadot - custom fields finished initializing with models', models);\n return sequelize;\n};\n\n/**\n * Adding custom fields enrichment to the models inside the MODELS_FILE_NAME json file\n * @see {@link 'custom-fields/config'} for configurations\n */\nconst useCustomFields = async (\n app: Pick<Application, 'use'> | null,\n getModel: ModelFetcher,\n options: CustomFieldOptions,\n): Promise<Sequelize> => {\n const initPromise = internalUseCustomFields(app, getModel, options);\n\n sadotInitState.setInitPromise(initPromise, !options.sequelize);\n\n return await initPromise;\n};\n\nexport default useCustomFields;\n\nexport const disableCustomFields = (models: Models[], getModel: ModelFetcher): void => {\n removeHooks(models, getModel);\n};\n"],"mappings":"2lBA4BaA,EAA2C,IAAIC,EAAAA,yBAMtD,EAA0B,MAC9B,EACA,EACA,IACuB,CACvB,EAAA,4BAA4B,CAC5B,GAAM,CAAE,SAAQ,yBAAwB,uBAAwB,EAC5D,GACF,EAAI,IAAI,OAAQC,EAAAA,QAAI,CAEtB,IAAM,EAAY,EAAQ,WAAaC,EAAAA,QAAO,EAAQ,eAAe,CAWrE,OAVI,QAAQ,IAAI,WAAa,QAC3B,MAAMC,EAAAA,eAAe,EAAU,CAGjC,EAAA,SAAS,EAAQ,EAAU,CAAE,yBAAwB,CAAC,CACtD,MAAMC,EAAAA,WAAW,EAAW,EAAQ,QAAS,CAAE,yBAAwB,sBAAqB,CAAC,CAC7F,EAAA,UAAU,EAAQ,EAAU,CAAE,yBAAwB,CAAC,CACvD,EAAA,uBAAuB,EAAO,CAE9B,EAAA,QAAO,MAAM,0DAA2D,EAAO,CACxE,GAOH,EAAkB,MACtB,EACA,EACA,IACuB,CACvB,IAAM,EAAc,EAAwB,EAAK,EAAU,EAAQ,CAInE,OAFA,EAAe,eAAe,EAAa,CAAC,EAAQ,UAAU,CAEvD,MAAM,GAGf,IAAA,EAAe,EAEf,MAAa,GAAuB,EAAkB,IAAiC,CACrF,EAAA,YAAY,EAAQ,EAAS"}
1
+ {"version":3,"file":"index.cjs","names":["sadotInitState: SadotInitializationState","SadotInitializationState","api","initDB","initTestModels","initTables"],"sources":["../src/index.ts"],"sourcesContent":["import type { Application } from 'express';\nimport type { Sequelize } from 'sequelize-typescript';\nimport {\n initTables, initTestModels,\n} from './models';\nimport api from './api';\nimport initDB from './utils/db';\nimport logger, { tryAddingTraceIdMiddleware } from './utils/logger';\nimport type { CustomFieldOptions, ModelFetcher, Models } from './types';\nimport {\n addHooks, addScopes, applyCustomAssociation, removeHooks,\n} from './utils/init';\nimport { SadotInitializationState } from './init-state';\nimport { matPathState } from './mat-path-state';\n\nexport * from './utils/validations/schema/custom-fields';\n\nexport * from './utils/constants';\n\nexport * from './utils/helpers';\n\nexport { customFieldsSortScope } from './scopes/filter';\nexport {\n CustomFieldDefinition,\n CustomFieldEntries,\n CustomFieldValue,\n CustomValidator,\n} from './models';\n\nexport const sadotInitState: SadotInitializationState = new SadotInitializationState();\n\n/**\n * Internal implementation of custom fields initialization\n * Contains all the business logic without state tracking\n */\nconst internalUseCustomFields = async (\n app: Pick<Application, 'use'> | null,\n getModel: ModelFetcher,\n options: CustomFieldOptions,\n): Promise<Sequelize> => {\n tryAddingTraceIdMiddleware();\n const { models, useCustomFieldsEntries, useModelTypeMapping, isMatPathEnabled } = options;\n matPathState.isMatPathEnabled = isMatPathEnabled;\n if (app) {\n app.use('/api', api);\n }\n const sequelize = options.sequelize ?? initDB(options.databaseConfig);\n if (process.env.NODE_ENV === 'test') {\n await initTestModels(sequelize);\n }\n // The order is important\n addHooks(models, getModel, { useCustomFieldsEntries });\n await initTables(sequelize, options.getUser, { useCustomFieldsEntries, useModelTypeMapping, isMatPathEnabled });\n addScopes(models, getModel, { useCustomFieldsEntries });\n applyCustomAssociation(models);\n\n logger.debug('sadot - custom fields finished initializing with models', models);\n return sequelize;\n};\n\n/**\n * Adding custom fields enrichment to the models inside the MODELS_FILE_NAME json file\n * @see {@link 'custom-fields/config'} for configurations\n */\nconst useCustomFields = async (\n app: Pick<Application, 'use'> | null,\n getModel: ModelFetcher,\n options: CustomFieldOptions,\n): Promise<Sequelize> => {\n const initPromise = internalUseCustomFields(app, getModel, options);\n\n sadotInitState.setInitPromise(initPromise, !options.sequelize);\n\n return await initPromise;\n};\n\nexport default useCustomFields;\n\nexport const disableCustomFields = (models: Models[], getModel: ModelFetcher): void => {\n removeHooks(models, getModel);\n};\n"],"mappings":"6nBA6BaA,EAA2C,IAAIC,EAAAA,yBAMtD,EAA0B,MAC9B,EACA,EACA,IACuB,CACvB,EAAA,4BAA4B,CAC5B,GAAM,CAAE,SAAQ,yBAAwB,sBAAqB,oBAAqB,EAClF,EAAA,aAAa,iBAAmB,EAC5B,GACF,EAAI,IAAI,OAAQC,EAAAA,QAAI,CAEtB,IAAM,EAAY,EAAQ,WAAaC,EAAAA,QAAO,EAAQ,eAAe,CAWrE,OAVI,QAAQ,IAAI,WAAa,QAC3B,MAAMC,EAAAA,eAAe,EAAU,CAGjC,EAAA,SAAS,EAAQ,EAAU,CAAE,yBAAwB,CAAC,CACtD,MAAMC,EAAAA,WAAW,EAAW,EAAQ,QAAS,CAAE,yBAAwB,sBAAqB,mBAAkB,CAAC,CAC/G,EAAA,UAAU,EAAQ,EAAU,CAAE,yBAAwB,CAAC,CACvD,EAAA,uBAAuB,EAAO,CAE9B,EAAA,QAAO,MAAM,0DAA2D,EAAO,CACxE,GAOH,EAAkB,MACtB,EACA,EACA,IACuB,CACvB,IAAM,EAAc,EAAwB,EAAK,EAAU,EAAQ,CAInE,OAFA,EAAe,eAAe,EAAa,CAAC,EAAQ,UAAU,CAEvD,MAAM,GAGf,IAAA,EAAe,EAEf,MAAa,GAAuB,EAAkB,IAAiC,CACrF,EAAA,YAAY,EAAQ,EAAS"}
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- import e,{tryAddingTraceIdMiddleware as t}from"./utils/logger/index.js";import{CUSTOM_FIELDS_FILTER_SCOPE as n,CustomFieldDefinitionType as r,supportedEntities as i}from"./utils/constants/index.js";import a from"./models/CustomFieldValue.js";import o from"./models/CustomFieldDefinition.js";import s from"./models/CustomFieldEntries.js";import c from"./models/CustomValidator.js";import{initTables as l,initTestModels as u}from"./models/index.js";import d from"./api/index.js";import f from"./utils/db/index.js";import{generateCustomFieldSearchQueryPayload as p,generateRandomString as m}from"./utils/helpers/index.js";import{customFieldsSortScope as h}from"./scopes/filter.js";import{addHooks as g,addScopes as _,applyCustomAssociation as v,removeHooks as y}from"./utils/init.js";import{SadotInitializationState as b}from"./init-state.js";import{CustomFieldsSchema as x}from"./utils/validations/schema/custom-fields.js";const S=new b,C=async(n,r,i)=>{t();let{models:a,useCustomFieldsEntries:o,useModelTypeMapping:s}=i;n&&n.use(`/api`,d);let c=i.sequelize??f(i.databaseConfig);return process.env.NODE_ENV===`test`&&await u(c),g(a,r,{useCustomFieldsEntries:o}),await l(c,i.getUser,{useCustomFieldsEntries:o,useModelTypeMapping:s}),_(a,r,{useCustomFieldsEntries:o}),v(a),e.debug(`sadot - custom fields finished initializing with models`,a),c};var w=async(e,t,n)=>{let r=C(e,t,n);return S.setInitPromise(r,!n.sequelize),await r};const T=(e,t)=>{y(e,t)};export{n as CUSTOM_FIELDS_FILTER_SCOPE,o as CustomFieldDefinition,r as CustomFieldDefinitionType,s as CustomFieldEntries,a as CustomFieldValue,x as CustomFieldsSchema,c as CustomValidator,h as customFieldsSortScope,w as default,T as disableCustomFields,p as generateCustomFieldSearchQueryPayload,m as generateRandomString,S as sadotInitState,i as supportedEntities};
1
+ import e,{tryAddingTraceIdMiddleware as t}from"./utils/logger/index.js";import{CUSTOM_FIELDS_FILTER_SCOPE as n,CustomFieldDefinitionType as r,supportedEntities as i}from"./utils/constants/index.js";import a from"./models/CustomFieldValue.js";import o from"./models/CustomFieldDefinition.js";import s from"./models/CustomFieldEntries.js";import c from"./models/CustomValidator.js";import{initTables as l,initTestModels as u}from"./models/index.js";import{matPathState as d}from"./mat-path-state.js";import f from"./api/index.js";import p from"./utils/db/index.js";import{generateCustomFieldSearchQueryPayload as m,generateRandomString as h}from"./utils/helpers/index.js";import{customFieldsSortScope as g}from"./scopes/filter.js";import{addHooks as _,addScopes as v,applyCustomAssociation as y,removeHooks as b}from"./utils/init.js";import{SadotInitializationState as x}from"./init-state.js";import{CustomFieldsSchema as S}from"./utils/validations/schema/custom-fields.js";const C=new x,w=async(n,r,i)=>{t();let{models:a,useCustomFieldsEntries:o,useModelTypeMapping:s,isMatPathEnabled:c}=i;d.isMatPathEnabled=c,n&&n.use(`/api`,f);let m=i.sequelize??p(i.databaseConfig);return process.env.NODE_ENV===`test`&&await u(m),_(a,r,{useCustomFieldsEntries:o}),await l(m,i.getUser,{useCustomFieldsEntries:o,useModelTypeMapping:s,isMatPathEnabled:c}),v(a,r,{useCustomFieldsEntries:o}),y(a),e.debug(`sadot - custom fields finished initializing with models`,a),m};var T=async(e,t,n)=>{let r=w(e,t,n);return C.setInitPromise(r,!n.sequelize),await r};const E=(e,t)=>{b(e,t)};export{n as CUSTOM_FIELDS_FILTER_SCOPE,o as CustomFieldDefinition,r as CustomFieldDefinitionType,s as CustomFieldEntries,a as CustomFieldValue,S as CustomFieldsSchema,c as CustomValidator,g as customFieldsSortScope,T as default,E as disableCustomFields,m as generateCustomFieldSearchQueryPayload,h as generateRandomString,C as sadotInitState,i as supportedEntities};
2
2
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["sadotInitState: SadotInitializationState","api","initDB"],"sources":["../src/index.ts"],"sourcesContent":["import type { Application } from 'express';\nimport type { Sequelize } from 'sequelize-typescript';\nimport {\n initTables, initTestModels,\n} from './models';\nimport api from './api';\nimport initDB from './utils/db';\nimport logger, { tryAddingTraceIdMiddleware } from './utils/logger';\nimport type { CustomFieldOptions, ModelFetcher, Models } from './types';\nimport {\n addHooks, addScopes, applyCustomAssociation, removeHooks,\n} from './utils/init';\nimport { SadotInitializationState } from './init-state';\n\nexport * from './utils/validations/schema/custom-fields';\n\nexport * from './utils/constants';\n\nexport * from './utils/helpers';\n\nexport { customFieldsSortScope } from './scopes/filter';\nexport {\n CustomFieldDefinition,\n CustomFieldEntries,\n CustomFieldValue,\n CustomValidator,\n} from './models';\n\nexport const sadotInitState: SadotInitializationState = new SadotInitializationState();\n\n/**\n * Internal implementation of custom fields initialization\n * Contains all the business logic without state tracking\n */\nconst internalUseCustomFields = async (\n app: Pick<Application, 'use'> | null,\n getModel: ModelFetcher,\n options: CustomFieldOptions,\n): Promise<Sequelize> => {\n tryAddingTraceIdMiddleware();\n const { models, useCustomFieldsEntries, useModelTypeMapping } = options;\n if (app) {\n app.use('/api', api);\n }\n const sequelize = options.sequelize ?? initDB(options.databaseConfig);\n if (process.env.NODE_ENV === 'test') {\n await initTestModels(sequelize);\n }\n // The order is important\n addHooks(models, getModel, { useCustomFieldsEntries });\n await initTables(sequelize, options.getUser, { useCustomFieldsEntries, useModelTypeMapping });\n addScopes(models, getModel, { useCustomFieldsEntries });\n applyCustomAssociation(models);\n\n logger.debug('sadot - custom fields finished initializing with models', models);\n return sequelize;\n};\n\n/**\n * Adding custom fields enrichment to the models inside the MODELS_FILE_NAME json file\n * @see {@link 'custom-fields/config'} for configurations\n */\nconst useCustomFields = async (\n app: Pick<Application, 'use'> | null,\n getModel: ModelFetcher,\n options: CustomFieldOptions,\n): Promise<Sequelize> => {\n const initPromise = internalUseCustomFields(app, getModel, options);\n\n sadotInitState.setInitPromise(initPromise, !options.sequelize);\n\n return await initPromise;\n};\n\nexport default useCustomFields;\n\nexport const disableCustomFields = (models: Models[], getModel: ModelFetcher): void => {\n removeHooks(models, getModel);\n};\n"],"mappings":"y5BA4BA,MAAaA,EAA2C,IAAI,EAMtD,EAA0B,MAC9B,EACA,EACA,IACuB,CACvB,GAA4B,CAC5B,GAAM,CAAE,SAAQ,yBAAwB,uBAAwB,EAC5D,GACF,EAAI,IAAI,OAAQC,EAAI,CAEtB,IAAM,EAAY,EAAQ,WAAaC,EAAO,EAAQ,eAAe,CAWrE,OAVI,QAAQ,IAAI,WAAa,QAC3B,MAAM,EAAe,EAAU,CAGjC,EAAS,EAAQ,EAAU,CAAE,yBAAwB,CAAC,CACtD,MAAM,EAAW,EAAW,EAAQ,QAAS,CAAE,yBAAwB,sBAAqB,CAAC,CAC7F,EAAU,EAAQ,EAAU,CAAE,yBAAwB,CAAC,CACvD,EAAuB,EAAO,CAE9B,EAAO,MAAM,0DAA2D,EAAO,CACxE,GAmBT,IAAA,EAZwB,MACtB,EACA,EACA,IACuB,CACvB,IAAM,EAAc,EAAwB,EAAK,EAAU,EAAQ,CAInE,OAFA,EAAe,eAAe,EAAa,CAAC,EAAQ,UAAU,CAEvD,MAAM,GAKf,MAAa,GAAuB,EAAkB,IAAiC,CACrF,EAAY,EAAQ,EAAS"}
1
+ {"version":3,"file":"index.js","names":["sadotInitState: SadotInitializationState","api","initDB"],"sources":["../src/index.ts"],"sourcesContent":["import type { Application } from 'express';\nimport type { Sequelize } from 'sequelize-typescript';\nimport {\n initTables, initTestModels,\n} from './models';\nimport api from './api';\nimport initDB from './utils/db';\nimport logger, { tryAddingTraceIdMiddleware } from './utils/logger';\nimport type { CustomFieldOptions, ModelFetcher, Models } from './types';\nimport {\n addHooks, addScopes, applyCustomAssociation, removeHooks,\n} from './utils/init';\nimport { SadotInitializationState } from './init-state';\nimport { matPathState } from './mat-path-state';\n\nexport * from './utils/validations/schema/custom-fields';\n\nexport * from './utils/constants';\n\nexport * from './utils/helpers';\n\nexport { customFieldsSortScope } from './scopes/filter';\nexport {\n CustomFieldDefinition,\n CustomFieldEntries,\n CustomFieldValue,\n CustomValidator,\n} from './models';\n\nexport const sadotInitState: SadotInitializationState = new SadotInitializationState();\n\n/**\n * Internal implementation of custom fields initialization\n * Contains all the business logic without state tracking\n */\nconst internalUseCustomFields = async (\n app: Pick<Application, 'use'> | null,\n getModel: ModelFetcher,\n options: CustomFieldOptions,\n): Promise<Sequelize> => {\n tryAddingTraceIdMiddleware();\n const { models, useCustomFieldsEntries, useModelTypeMapping, isMatPathEnabled } = options;\n matPathState.isMatPathEnabled = isMatPathEnabled;\n if (app) {\n app.use('/api', api);\n }\n const sequelize = options.sequelize ?? initDB(options.databaseConfig);\n if (process.env.NODE_ENV === 'test') {\n await initTestModels(sequelize);\n }\n // The order is important\n addHooks(models, getModel, { useCustomFieldsEntries });\n await initTables(sequelize, options.getUser, { useCustomFieldsEntries, useModelTypeMapping, isMatPathEnabled });\n addScopes(models, getModel, { useCustomFieldsEntries });\n applyCustomAssociation(models);\n\n logger.debug('sadot - custom fields finished initializing with models', models);\n return sequelize;\n};\n\n/**\n * Adding custom fields enrichment to the models inside the MODELS_FILE_NAME json file\n * @see {@link 'custom-fields/config'} for configurations\n */\nconst useCustomFields = async (\n app: Pick<Application, 'use'> | null,\n getModel: ModelFetcher,\n options: CustomFieldOptions,\n): Promise<Sequelize> => {\n const initPromise = internalUseCustomFields(app, getModel, options);\n\n sadotInitState.setInitPromise(initPromise, !options.sequelize);\n\n return await initPromise;\n};\n\nexport default useCustomFields;\n\nexport const disableCustomFields = (models: Models[], getModel: ModelFetcher): void => {\n removeHooks(models, getModel);\n};\n"],"mappings":"48BA6BA,MAAaA,EAA2C,IAAI,EAMtD,EAA0B,MAC9B,EACA,EACA,IACuB,CACvB,GAA4B,CAC5B,GAAM,CAAE,SAAQ,yBAAwB,sBAAqB,oBAAqB,EAClF,EAAa,iBAAmB,EAC5B,GACF,EAAI,IAAI,OAAQC,EAAI,CAEtB,IAAM,EAAY,EAAQ,WAAaC,EAAO,EAAQ,eAAe,CAWrE,OAVI,QAAQ,IAAI,WAAa,QAC3B,MAAM,EAAe,EAAU,CAGjC,EAAS,EAAQ,EAAU,CAAE,yBAAwB,CAAC,CACtD,MAAM,EAAW,EAAW,EAAQ,QAAS,CAAE,yBAAwB,sBAAqB,mBAAkB,CAAC,CAC/G,EAAU,EAAQ,EAAU,CAAE,yBAAwB,CAAC,CACvD,EAAuB,EAAO,CAE9B,EAAO,MAAM,0DAA2D,EAAO,CACxE,GAmBT,IAAA,EAZwB,MACtB,EACA,EACA,IACuB,CACvB,IAAM,EAAc,EAAwB,EAAK,EAAU,EAAQ,CAInE,OAFA,EAAe,eAAe,EAAa,CAAC,EAAQ,UAAU,CAEvD,MAAM,GAKf,MAAa,GAAuB,EAAkB,IAAiC,CACrF,EAAY,EAAQ,EAAS"}
@@ -0,0 +1,2 @@
1
+ const e={};exports.matPathState=e;
2
+ //# sourceMappingURL=mat-path-state.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mat-path-state.cjs","names":["matPathState: { isMatPathEnabled?: CustomFieldOptions['isMatPathEnabled']; }"],"sources":["../src/mat-path-state.ts"],"sourcesContent":["import type { CustomFieldOptions } from './types';\n\n/**\n * Module-scoped holder for the optional `isMatPathEnabled` predicate so route handlers can\n * read it without threading the option through every layer. Set once during `useCustomFields()`.\n */\nexport const matPathState: { isMatPathEnabled?: CustomFieldOptions['isMatPathEnabled']; } = {};\n"],"mappings":"AAMA,MAAaA,EAA+E,EAAE"}
@@ -0,0 +1,2 @@
1
+ const e={};export{e as matPathState};
2
+ //# sourceMappingURL=mat-path-state.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mat-path-state.js","names":["matPathState: { isMatPathEnabled?: CustomFieldOptions['isMatPathEnabled']; }"],"sources":["../src/mat-path-state.ts"],"sourcesContent":["import type { CustomFieldOptions } from './types';\n\n/**\n * Module-scoped holder for the optional `isMatPathEnabled` predicate so route handlers can\n * read it without threading the option through every layer. Set once during `useCustomFields()`.\n */\nexport const matPathState: { isMatPathEnabled?: CustomFieldOptions['isMatPathEnabled']; } = {};\n"],"mappings":"AAMA,MAAaA,EAA+E,EAAE"}
@@ -1,2 +1,2 @@
1
- const e=require(`../_virtual/rolldown_runtime.cjs`),t=require(`../utils/logger/index.cjs`),n=require(`./CustomFieldValue.cjs`),r=require(`./CustomFieldDefinition.cjs`),i=require(`./tests/AssociatedTestModel.cjs`),a=require(`./tests/TestModel.cjs`),o=require(`./tests/contextAwareModels/ContextTestModel.cjs`),s=require(`./tests/contextAwareModels/ContextAwareTestModel.cjs`),c=require(`./CustomFieldEntries.cjs`),l=require(`./CustomValidator.cjs`),u=require(`./CustomFieldModelTypeMap.cjs`);let d=require(`sequelize`);const f=[a.default,i.default,s.default,o.default],p=`sadot-migration`,m=`5f8e4a7c-9b2d-4e1f-8c3a-b6d9e2f7a4c1`,h=async(e,i,{schemaPrefix:a=`sadot-migration`,schemaVersion:o=`5f8e4a7c-9b2d-4e1f-8c3a-b6d9e2f7a4c1`,useCustomFieldsEntries:s=!1,useModelTypeMapping:f=!1}={})=>{let p=`${a}_${o}${s?`_withEntries`:``}${f?`_withTypeMapping`:``}`;if(t.default.info(`custom-fields: initialize custom-fields tables`),!e.addModels)throw Error(`sequelize instance must have addModels function`);let m=[r.default,n.default,l.default,...s?[c.default]:[],...f?[u.default]:[]];e.addModels(m),f&&(r.default.hasMany(u.default,{foreignKey:`customFieldDefinitionId`,as:`modelTypeMappings`}),u.default.belongsTo(r.default,{foreignKey:`customFieldDefinitionId`,as:`customFieldDefinition`})),r.default.addScope(`userScope`,()=>{let e=i();return e?.permissions?{where:{entityId:[...Object.keys(e.permissions.fleets),...Object.keys(e.permissions.businessModels),...Object.keys(e.permissions.demandSources)]}}:{}}),l.default.addScope(`userScope`,()=>{let e=i();return e?.permissions?{where:{entityId:[...Object.keys(e.permissions.fleets),...Object.keys(e.permissions.businessModels),...Object.keys(e.permissions.demandSources)]}}:{}}),t.default.info(`custom-fields: models added`);let h=e.define(`SequelizeMeta`,{name:{type:d.DataTypes.STRING,allowNull:!1,unique:!0,primaryKey:!0,autoIncrement:!1}},{tableName:`SequelizeMeta`,timestamps:!1,schema:`public`});t.default.info(`custom-fields: starting migrations`);let g=await h.findAll({where:{name:{[d.Op.like]:`${a}%`}},raw:!0}),_=g.at(-1),v=g.findIndex(e=>e.name===p);if(t.default.info(`custom-fields: migrations`,{currentMigrations:g,currentSadotSchemaVersion:_,newSadotSchemaVersion:p,expectedSchemaVersionIndex:v}),!_||_.name!==p){t.default.info(`custom-fields: syncing models`);try{if(await r.default.sync({alter:!0}),t.default.info(`custom-fields: CustomFieldDefinition synced successfully`),await n.default.sync({alter:!0}),t.default.info(`custom-fields: CustomFieldValue synced successfully`),await l.default.sync({alter:!0}),t.default.info(`custom-fields: CustomValidator synced successfully`),s&&(await c.default.sync({alter:!0}),t.default.info(`custom-fields: CustomFieldEntries synced successfully`)),f&&(await u.default.sync({alter:!0}),t.default.info(`custom-fields: CustomFieldModelTypeMap synced successfully`)),v===-1&&(await h.create({name:p}),t.default.info(`custom-fields: SequelizeMeta entry created successfully`)),t.default.info(`custom-fields: models synced`),g.length&&v!==-1&&v<g.length-1){let e=g.slice(v+1);t.default.info(`custom-fields: deleting newer migrations during down migration`,{count:e.length}),await h.destroy({where:{name:{[d.Op.in]:e.map(e=>e.name)}}}),t.default.info(`custom-fields: newer migrations deleted successfully`)}}catch(e){throw t.default.error(`custom-fields: failed to sync models`,{error:e}),e}}},g=async e=>{if(t.default.info(`custom-fields: initialize custom-fields test models`),!e.addModels)throw Error(`sequelize instance must have addModels function`);e.addModels(f),await e.dropSchema(`custom-fields`,{logging:!1}),await e.createSchema(`custom-fields`,{logging:!1}),t.default.info(`custom-fields: test models added`),await a.default.sync({alter:!0}),await i.default.sync({alter:!0}),await o.default.sync({alter:!0}),await s.default.sync({alter:!0}),t.default.info(`custom-fields: test models synced`)};exports.initTables=h,exports.initTestModels=g;
1
+ const e=require(`../_virtual/rolldown_runtime.cjs`),t=require(`../utils/logger/index.cjs`),n=require(`./CustomFieldValue.cjs`),r=require(`./CustomFieldDefinition.cjs`),i=require(`./tests/AssociatedTestModel.cjs`),a=require(`./tests/TestModel.cjs`),o=require(`./tests/contextAwareModels/ContextTestModel.cjs`),s=require(`./tests/contextAwareModels/ContextAwareTestModel.cjs`),c=require(`./CustomFieldEntries.cjs`),l=require(`./CustomValidator.cjs`),u=require(`./CustomFieldModelTypeMap.cjs`);let d=require(`sequelize`);const f=[a.default,i.default,s.default,o.default],p=`sadot-migration`,m=`5f8e4a7c-9b2d-4e1f-8c3a-b6d9e2f7a4c1`,h=async(e,i,{schemaPrefix:a=`sadot-migration`,schemaVersion:o=`5f8e4a7c-9b2d-4e1f-8c3a-b6d9e2f7a4c1`,useCustomFieldsEntries:s=!1,useModelTypeMapping:f=!1,isMatPathEnabled:p}={})=>{let m=`${a}_${o}${s?`_withEntries`:``}${f?`_withTypeMapping`:``}`;if(t.default.info(`custom-fields: initialize custom-fields tables`),!e.addModels)throw Error(`sequelize instance must have addModels function`);let h=[r.default,n.default,l.default,...s?[c.default]:[],...f?[u.default]:[]];e.addModels(h),f&&(r.default.hasMany(u.default,{foreignKey:`customFieldDefinitionId`,as:`modelTypeMappings`}),u.default.belongsTo(r.default,{foreignKey:`customFieldDefinitionId`,as:`customFieldDefinition`})),r.default.addScope(`userScope`,()=>{if(p?.())return{};let e=i();return e?.permissions?{where:{entityId:[...Object.keys(e.permissions.fleets),...Object.keys(e.permissions.businessModels),...Object.keys(e.permissions.demandSources)]}}:{}}),l.default.addScope(`userScope`,()=>{if(p?.())return{};let e=i();return e?.permissions?{where:{entityId:[...Object.keys(e.permissions.fleets),...Object.keys(e.permissions.businessModels),...Object.keys(e.permissions.demandSources)]}}:{}}),t.default.info(`custom-fields: models added`);let g=e.define(`SequelizeMeta`,{name:{type:d.DataTypes.STRING,allowNull:!1,unique:!0,primaryKey:!0,autoIncrement:!1}},{tableName:`SequelizeMeta`,timestamps:!1,schema:`public`});t.default.info(`custom-fields: starting migrations`);let _=await g.findAll({where:{name:{[d.Op.like]:`${a}%`}},raw:!0}),v=_.at(-1),y=_.findIndex(e=>e.name===m);if(t.default.info(`custom-fields: migrations`,{currentMigrations:_,currentSadotSchemaVersion:v,newSadotSchemaVersion:m,expectedSchemaVersionIndex:y}),!v||v.name!==m){t.default.info(`custom-fields: syncing models`);try{if(await r.default.sync({alter:!0}),t.default.info(`custom-fields: CustomFieldDefinition synced successfully`),await n.default.sync({alter:!0}),t.default.info(`custom-fields: CustomFieldValue synced successfully`),await l.default.sync({alter:!0}),t.default.info(`custom-fields: CustomValidator synced successfully`),s&&(await c.default.sync({alter:!0}),t.default.info(`custom-fields: CustomFieldEntries synced successfully`)),f&&(await u.default.sync({alter:!0}),t.default.info(`custom-fields: CustomFieldModelTypeMap synced successfully`)),y===-1&&(await g.create({name:m}),t.default.info(`custom-fields: SequelizeMeta entry created successfully`)),t.default.info(`custom-fields: models synced`),_.length&&y!==-1&&y<_.length-1){let e=_.slice(y+1);t.default.info(`custom-fields: deleting newer migrations during down migration`,{count:e.length}),await g.destroy({where:{name:{[d.Op.in]:e.map(e=>e.name)}}}),t.default.info(`custom-fields: newer migrations deleted successfully`)}}catch(e){throw t.default.error(`custom-fields: failed to sync models`,{error:e}),e}}},g=async e=>{if(t.default.info(`custom-fields: initialize custom-fields test models`),!e.addModels)throw Error(`sequelize instance must have addModels function`);e.addModels(f),await e.dropSchema(`custom-fields`,{logging:!1}),await e.createSchema(`custom-fields`,{logging:!1}),t.default.info(`custom-fields: test models added`),await a.default.sync({alter:!0}),await i.default.sync({alter:!0}),await o.default.sync({alter:!0}),await s.default.sync({alter:!0}),t.default.info(`custom-fields: test models synced`)};exports.initTables=h,exports.initTestModels=g;
2
2
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["TestModel","AssociatedTestModel","ContextAwareTestModel","ContextTestModel","sequelize","productionModels: ProductionModel[]","CustomFieldDefinition","CustomFieldValue","CustomValidator","CustomFieldEntries","CustomFieldModelTypeMap","DataTypes","Op"],"sources":["../../src/models/index.ts"],"sourcesContent":["import { DataTypes, Op } from 'sequelize';\nimport type { Sequelize } from 'sequelize-typescript';\nimport logger from '../utils/logger';\nimport CustomFieldDefinition from './CustomFieldDefinition';\nimport CustomFieldValue from './CustomFieldValue';\nimport TestModel from './tests/TestModel';\nimport ContextAwareTestModel from './tests/contextAwareModels/ContextAwareTestModel';\nimport ContextTestModel from './tests/contextAwareModels/ContextTestModel';\nimport AssociatedTestModel from './tests/AssociatedTestModel';\nimport type { CustomFieldOptions } from '../types';\nimport CustomFieldEntries from './CustomFieldEntries';\nimport CustomValidator from './CustomValidator';\nimport CustomFieldModelTypeMap from './CustomFieldModelTypeMap';\n\ntype ProductionModel = typeof CustomFieldDefinition | typeof CustomFieldValue | typeof CustomFieldEntries | typeof CustomValidator | typeof CustomFieldModelTypeMap;\ninterface InitTablesOptions {\n schemaPrefix?: string;\n schemaVersion?: string;\n useCustomFieldsEntries?: boolean;\n useModelTypeMapping?: boolean;\n}\n\nconst testModels = [TestModel, AssociatedTestModel, ContextAwareTestModel, ContextTestModel];\n\nconst SADOT_MIGRATION_PREFIX = 'sadot-migration';\nconst SCHEMA_VERSION = '5f8e4a7c-9b2d-4e1f-8c3a-b6d9e2f7a4c1';\n\nconst initTables = async (\n sequelize: Sequelize,\n getUser: CustomFieldOptions['getUser'],\n {\n schemaPrefix = SADOT_MIGRATION_PREFIX,\n schemaVersion = SCHEMA_VERSION,\n useCustomFieldsEntries = false,\n useModelTypeMapping = false,\n }: InitTablesOptions = {},\n): Promise<void> => {\n const CUSTOM_FIELDS_SCHEMA_VERSION = `${schemaPrefix}_${schemaVersion}${useCustomFieldsEntries ? '_withEntries' : ''}${useModelTypeMapping ? '_withTypeMapping' : ''}`;\n logger.info('custom-fields: initialize custom-fields tables');\n // Detect models and import them to the orm\n if (!sequelize.addModels) {\n throw new Error('sequelize instance must have addModels function');\n }\n const productionModels: ProductionModel[] = [\n CustomFieldDefinition,\n CustomFieldValue,\n CustomValidator,\n ...(useCustomFieldsEntries ? [CustomFieldEntries] : []),\n ...(useModelTypeMapping ? [CustomFieldModelTypeMap] : []),\n ];\n\n sequelize.addModels(productionModels);\n\n // Add the association only when useModelTypeMapping is enabled\n if (useModelTypeMapping) {\n CustomFieldDefinition.hasMany(CustomFieldModelTypeMap, {\n foreignKey: 'customFieldDefinitionId',\n as: 'modelTypeMappings',\n });\n CustomFieldModelTypeMap.belongsTo(CustomFieldDefinition, {\n foreignKey: 'customFieldDefinitionId',\n as: 'customFieldDefinition',\n });\n }\n\n CustomFieldDefinition.addScope('userScope', () => {\n const user = getUser();\n if (!user?.permissions) {\n return {};\n }\n return {\n where: {\n entityId: [\n ...Object.keys(user.permissions.fleets),\n ...Object.keys(user.permissions.businessModels),\n ...Object.keys(user.permissions.demandSources),\n ],\n },\n };\n });\n\n CustomValidator.addScope('userScope', () => {\n const user = getUser();\n if (!user?.permissions) {\n return {};\n }\n return {\n where: {\n entityId: [\n ...Object.keys(user.permissions.fleets),\n ...Object.keys(user.permissions.businessModels),\n ...Object.keys(user.permissions.demandSources),\n ],\n },\n };\n });\n\n logger.info('custom-fields: models added');\n\n const SequelizeMeta = sequelize.define(\n 'SequelizeMeta',\n {\n name: {\n type: DataTypes.STRING,\n allowNull: false,\n unique: true,\n primaryKey: true,\n autoIncrement: false,\n },\n },\n {\n tableName: 'SequelizeMeta',\n timestamps: false,\n schema: 'public',\n },\n );\n\n logger.info('custom-fields: starting migrations');\n const migrations = await SequelizeMeta.findAll({ where: { name: { [Op.like]: `${schemaPrefix}%` } }, raw: true });\n const currentSadotSchemaVersion = migrations.at(-1);\n const expectedSchemaVersionIndex = migrations.findIndex(m => (m as any).name === CUSTOM_FIELDS_SCHEMA_VERSION);\n\n logger.info('custom-fields: migrations', {\n currentMigrations: migrations,\n currentSadotSchemaVersion,\n newSadotSchemaVersion: CUSTOM_FIELDS_SCHEMA_VERSION,\n expectedSchemaVersionIndex,\n });\n if (!currentSadotSchemaVersion || (currentSadotSchemaVersion as any).name !== CUSTOM_FIELDS_SCHEMA_VERSION) {\n logger.info('custom-fields: syncing models');\n try {\n await CustomFieldDefinition.sync({ alter: true });\n logger.info('custom-fields: CustomFieldDefinition synced successfully');\n\n await CustomFieldValue.sync({ alter: true });\n logger.info('custom-fields: CustomFieldValue synced successfully');\n\n await CustomValidator.sync({ alter: true });\n logger.info('custom-fields: CustomValidator synced successfully');\n\n // T.Y TODO: Remove the if statement once we're ready to add the new entries table for all MS\n if (useCustomFieldsEntries) {\n await CustomFieldEntries.sync({ alter: true });\n logger.info('custom-fields: CustomFieldEntries synced successfully');\n }\n\n if (useModelTypeMapping) {\n await CustomFieldModelTypeMap.sync({ alter: true });\n logger.info('custom-fields: CustomFieldModelTypeMap synced successfully');\n }\n\n if (expectedSchemaVersionIndex === -1) {\n await SequelizeMeta.create({ name: CUSTOM_FIELDS_SCHEMA_VERSION });\n logger.info('custom-fields: SequelizeMeta entry created successfully');\n }\n\n logger.info('custom-fields: models synced');\n if (migrations.length && expectedSchemaVersionIndex !== -1 && expectedSchemaVersionIndex < migrations.length - 1) {\n // We have existing migrations, and we are calling `sync`.\n // This means we are in a `down` migration, and hence we should delete newer migrations to ensure we can reapply them.\n const migrationsToDelete = migrations.slice(expectedSchemaVersionIndex + 1);\n logger.info('custom-fields: deleting newer migrations during down migration', { count: migrationsToDelete.length });\n await SequelizeMeta.destroy({ where: { name: { [Op.in]: migrationsToDelete.map(m => (m as any).name) } } });\n logger.info('custom-fields: newer migrations deleted successfully');\n }\n } catch (error) {\n logger.error('custom-fields: failed to sync models', { error });\n throw error;\n }\n }\n};\n\nconst initTestModels = async (sequelize: Sequelize): Promise<void> => {\n logger.info('custom-fields: initialize custom-fields test models');\n // Detect models and import them to the orm\n if (!sequelize.addModels) {\n throw new Error('sequelize instance must have addModels function');\n }\n\n sequelize.addModels(testModels);\n await sequelize.dropSchema('custom-fields', { logging: false });\n await sequelize.createSchema('custom-fields', { logging: false });\n\n logger.info('custom-fields: test models added');\n await TestModel.sync({ alter: true });\n await AssociatedTestModel.sync({ alter: true });\n await ContextTestModel.sync({ alter: true });\n await ContextAwareTestModel.sync({ alter: true });\n logger.info('custom-fields: test models synced');\n};\n\nexport {\n CustomFieldValue,\n CustomFieldDefinition,\n CustomFieldEntries,\n CustomValidator,\n CustomFieldModelTypeMap,\n TestModel,\n AssociatedTestModel,\n ContextAwareTestModel,\n ContextTestModel,\n initTables,\n initTestModels,\n};\n"],"mappings":"sgBAsBA,MAAM,EAAa,CAACA,EAAAA,QAAWC,EAAAA,QAAqBC,EAAAA,QAAuBC,EAAAA,QAAiB,CAEtF,EAAyB,kBACzB,EAAiB,uCAEjB,EAAa,MACjB,EACA,EACA,CACE,eAAe,kBACf,gBAAgB,uCAChB,yBAAyB,GACzB,sBAAsB,IACD,EAAE,GACP,CAClB,IAAM,EAA+B,GAAG,EAAa,GAAG,IAAgB,EAAyB,eAAiB,KAAK,EAAsB,mBAAqB,KAGlK,GAFA,EAAA,QAAO,KAAK,iDAAiD,CAEzD,CAACC,EAAU,UACb,MAAU,MAAM,kDAAkD,CAEpE,IAAMC,EAAsC,CAC1CC,EAAAA,QACAC,EAAAA,QACAC,EAAAA,QACA,GAAI,EAAyB,CAACC,EAAAA,QAAmB,CAAG,EAAE,CACtD,GAAI,EAAsB,CAACC,EAAAA,QAAwB,CAAG,EAAE,CACzD,CAED,EAAU,UAAU,EAAiB,CAGjC,IACF,EAAA,QAAsB,QAAQA,EAAAA,QAAyB,CACrD,WAAY,0BACZ,GAAI,oBACL,CAAC,CACF,EAAA,QAAwB,UAAUJ,EAAAA,QAAuB,CACv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AAE,QAAS,GAAO,CAAC,CAEjE,EAAA,QAAO,KAAK,mCAAmC,CAC/C,MAAMJ,EAAAA,QAAU,KAAK,CAAE,MAAO,GAAM,CAAC,CACrC,MAAMC,EAAAA,QAAoB,KAAK,CAAE,MAAO,GAAM,CAAC,CAC/C,MAAME,EAAAA,QAAiB,KAAK,CAAE,MAAO,GAAM,CAAC,CAC5C,MAAMD,EAAAA,QAAsB,KAAK,CAAE,MAAO,GAAM,CAAC,CACjD,EAAA,QAAO,KAAK,oCAAoC"}
1
+ {"version":3,"file":"index.cjs","names":["TestModel","AssociatedTestModel","ContextAwareTestModel","ContextTestModel","sequelize","productionModels: ProductionModel[]","CustomFieldDefinition","CustomFieldValue","CustomValidator","CustomFieldEntries","CustomFieldModelTypeMap","DataTypes","Op"],"sources":["../../src/models/index.ts"],"sourcesContent":["import { DataTypes, Op } from 'sequelize';\nimport type { Sequelize } from 'sequelize-typescript';\nimport logger from '../utils/logger';\nimport CustomFieldDefinition from './CustomFieldDefinition';\nimport CustomFieldValue from './CustomFieldValue';\nimport TestModel from './tests/TestModel';\nimport ContextAwareTestModel from './tests/contextAwareModels/ContextAwareTestModel';\nimport ContextTestModel from './tests/contextAwareModels/ContextTestModel';\nimport AssociatedTestModel from './tests/AssociatedTestModel';\nimport type { CustomFieldOptions } from '../types';\nimport CustomFieldEntries from './CustomFieldEntries';\nimport CustomValidator from './CustomValidator';\nimport CustomFieldModelTypeMap from './CustomFieldModelTypeMap';\n\ntype ProductionModel = typeof CustomFieldDefinition | typeof CustomFieldValue | typeof CustomFieldEntries | typeof CustomValidator | typeof CustomFieldModelTypeMap;\ninterface InitTablesOptions {\n schemaPrefix?: string;\n schemaVersion?: string;\n useCustomFieldsEntries?: boolean;\n useModelTypeMapping?: boolean;\n isMatPathEnabled?: CustomFieldOptions['isMatPathEnabled'];\n}\n\nconst testModels = [TestModel, AssociatedTestModel, ContextAwareTestModel, ContextTestModel];\n\nconst SADOT_MIGRATION_PREFIX = 'sadot-migration';\nconst SCHEMA_VERSION = '5f8e4a7c-9b2d-4e1f-8c3a-b6d9e2f7a4c1';\n\nconst initTables = async (\n sequelize: Sequelize,\n getUser: CustomFieldOptions['getUser'],\n {\n schemaPrefix = SADOT_MIGRATION_PREFIX,\n schemaVersion = SCHEMA_VERSION,\n useCustomFieldsEntries = false,\n useModelTypeMapping = false,\n isMatPathEnabled,\n }: InitTablesOptions = {},\n): Promise<void> => {\n const CUSTOM_FIELDS_SCHEMA_VERSION = `${schemaPrefix}_${schemaVersion}${useCustomFieldsEntries ? '_withEntries' : ''}${useModelTypeMapping ? '_withTypeMapping' : ''}`;\n logger.info('custom-fields: initialize custom-fields tables');\n // Detect models and import them to the orm\n if (!sequelize.addModels) {\n throw new Error('sequelize instance must have addModels function');\n }\n const productionModels: ProductionModel[] = [\n CustomFieldDefinition,\n CustomFieldValue,\n CustomValidator,\n ...(useCustomFieldsEntries ? [CustomFieldEntries] : []),\n ...(useModelTypeMapping ? [CustomFieldModelTypeMap] : []),\n ];\n\n sequelize.addModels(productionModels);\n\n // Add the association only when useModelTypeMapping is enabled\n if (useModelTypeMapping) {\n CustomFieldDefinition.hasMany(CustomFieldModelTypeMap, {\n foreignKey: 'customFieldDefinitionId',\n as: 'modelTypeMappings',\n });\n CustomFieldModelTypeMap.belongsTo(CustomFieldDefinition, {\n foreignKey: 'customFieldDefinitionId',\n as: 'customFieldDefinition',\n });\n }\n\n CustomFieldDefinition.addScope('userScope', () => {\n // When mat-path is active, the consumer is responsible for restricting entityIds\n // (typically by expanding the request's entityIds to include ancestor paths the\n // caller can see). Bypass the legacy permission filter so partner/ancestor\n // entityIds are not dropped.\n if (isMatPathEnabled?.()) return {};\n const user = getUser();\n if (!user?.permissions) {\n return {};\n }\n return {\n where: {\n entityId: [\n ...Object.keys(user.permissions.fleets),\n ...Object.keys(user.permissions.businessModels),\n ...Object.keys(user.permissions.demandSources),\n ],\n },\n };\n });\n\n CustomValidator.addScope('userScope', () => {\n if (isMatPathEnabled?.()) return {};\n const user = getUser();\n if (!user?.permissions) {\n return {};\n }\n return {\n where: {\n entityId: [\n ...Object.keys(user.permissions.fleets),\n ...Object.keys(user.permissions.businessModels),\n ...Object.keys(user.permissions.demandSources),\n ],\n },\n };\n });\n\n logger.info('custom-fields: models added');\n\n const SequelizeMeta = sequelize.define(\n 'SequelizeMeta',\n {\n name: {\n type: DataTypes.STRING,\n allowNull: false,\n unique: true,\n primaryKey: true,\n autoIncrement: false,\n },\n },\n {\n tableName: 'SequelizeMeta',\n timestamps: false,\n schema: 'public',\n },\n );\n\n logger.info('custom-fields: starting migrations');\n const migrations = await SequelizeMeta.findAll({ where: { name: { [Op.like]: `${schemaPrefix}%` } }, raw: true });\n const currentSadotSchemaVersion = migrations.at(-1);\n const expectedSchemaVersionIndex = migrations.findIndex(m => (m as any).name === CUSTOM_FIELDS_SCHEMA_VERSION);\n\n logger.info('custom-fields: migrations', {\n currentMigrations: migrations,\n currentSadotSchemaVersion,\n newSadotSchemaVersion: CUSTOM_FIELDS_SCHEMA_VERSION,\n expectedSchemaVersionIndex,\n });\n if (!currentSadotSchemaVersion || (currentSadotSchemaVersion as any).name !== CUSTOM_FIELDS_SCHEMA_VERSION) {\n logger.info('custom-fields: syncing models');\n try {\n await CustomFieldDefinition.sync({ alter: true });\n logger.info('custom-fields: CustomFieldDefinition synced successfully');\n\n await CustomFieldValue.sync({ alter: true });\n logger.info('custom-fields: CustomFieldValue synced successfully');\n\n await CustomValidator.sync({ alter: true });\n logger.info('custom-fields: CustomValidator synced successfully');\n\n // T.Y TODO: Remove the if statement once we're ready to add the new entries table for all MS\n if (useCustomFieldsEntries) {\n await CustomFieldEntries.sync({ alter: true });\n logger.info('custom-fields: CustomFieldEntries synced successfully');\n }\n\n if (useModelTypeMapping) {\n await CustomFieldModelTypeMap.sync({ alter: true });\n logger.info('custom-fields: CustomFieldModelTypeMap synced successfully');\n }\n\n if (expectedSchemaVersionIndex === -1) {\n await SequelizeMeta.create({ name: CUSTOM_FIELDS_SCHEMA_VERSION });\n logger.info('custom-fields: SequelizeMeta entry created successfully');\n }\n\n logger.info('custom-fields: models synced');\n if (migrations.length && expectedSchemaVersionIndex !== -1 && expectedSchemaVersionIndex < migrations.length - 1) {\n // We have existing migrations, and we are calling `sync`.\n // This means we are in a `down` migration, and hence we should delete newer migrations to ensure we can reapply them.\n const migrationsToDelete = migrations.slice(expectedSchemaVersionIndex + 1);\n logger.info('custom-fields: deleting newer migrations during down migration', { count: migrationsToDelete.length });\n await SequelizeMeta.destroy({ where: { name: { [Op.in]: migrationsToDelete.map(m => (m as any).name) } } });\n logger.info('custom-fields: newer migrations deleted successfully');\n }\n } catch (error) {\n logger.error('custom-fields: failed to sync models', { error });\n throw error;\n }\n }\n};\n\nconst initTestModels = async (sequelize: Sequelize): Promise<void> => {\n logger.info('custom-fields: initialize custom-fields test models');\n // Detect models and import them to the orm\n if (!sequelize.addModels) {\n throw new Error('sequelize instance must have addModels function');\n }\n\n sequelize.addModels(testModels);\n await sequelize.dropSchema('custom-fields', { logging: false });\n await sequelize.createSchema('custom-fields', { logging: false });\n\n logger.info('custom-fields: test models added');\n await TestModel.sync({ alter: true });\n await AssociatedTestModel.sync({ alter: true });\n await ContextTestModel.sync({ alter: true });\n await ContextAwareTestModel.sync({ alter: true });\n logger.info('custom-fields: test models synced');\n};\n\nexport {\n CustomFieldValue,\n CustomFieldDefinition,\n CustomFieldEntries,\n CustomValidator,\n CustomFieldModelTypeMap,\n TestModel,\n AssociatedTestModel,\n ContextAwareTestModel,\n ContextTestModel,\n initTables,\n initTestModels,\n};\n"],"mappings":"sgBAuBA,MAAM,EAAa,CAACA,EAAAA,QAAWC,EAAAA,QAAqBC,EAAAA,QAAuBC,EAAAA,QAAiB,CAEtF,EAAyB,kBACzB,EAAiB,uCAEjB,EAAa,MACjB,EACA,EACA,CACE,eAAe,kBACf,gBAAgB,uCAChB,yBAAyB,GACzB,sBAAsB,GACtB,oBACqB,EAAE,GACP,CAClB,IAAM,EAA+B,GAAG,EA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,CAC3E,EAAA,QAAO,KAAK,iEAAkE,CAAE,MAAO,EAAmB,OAAQ,CAAC,CACnH,MAAM,EAAc,QAAQ,CAAE,MAAO,CAAE,KAAM,EAAGE,EAAAA,GAAG,IAAK,EAAmB,IAAI,GAAM,EAAU,KAAK,CAAE,CAAE,CAAE,CAAC,CAC3G,EAAA,QAAO,KAAK,uDAAuD,QAE9D,EAAO,CAEd,MADA,EAAA,QAAO,MAAM,uCAAwC,CAAE,QAAO,CAAC,CACzD,KAKN,EAAiB,KAAO,IAAwC,CAGpE,GAFA,EAAA,QAAO,KAAK,sDAAsD,CAE9D,CAACR,EAAU,UACb,MAAU,MAAM,kDAAkD,CAGpE,EAAU,UAAU,EAAW,CAC/B,MAAMA,EAAU,WAAW,gBAAiB,CAAE,QAAS,GAAO,CAAC,CAC/D,MAAMA,EAAU,aAAa,gBAAiB,CAAE,QAAS,GAAO,CAAC,CAEjE,EAAA,QAAO,KAAK,mCAAmC,CAC/C,MAAMJ,EAAAA,QAAU,KAAK,CAAE,MAAO,GAAM,CAAC,CACrC,MAAMC,EAAAA,QAAoB,KAAK,CAAE,MAAO,GAAM,CAAC,CAC/C,MAAME,EAAAA,QAAiB,KAAK,CAAE,MAAO,GAAM,CAAC,CAC5C,MAAMD,EAAAA,QAAsB,KAAK,CAAE,MAAO,GAAM,CAAC,CACjD,EAAA,QAAO,KAAK,oCAAoC"}
@@ -1,2 +1,2 @@
1
- import e from"../utils/logger/index.js";import t from"./CustomFieldValue.js";import n from"./CustomFieldDefinition.js";import r from"./tests/AssociatedTestModel.js";import i from"./tests/TestModel.js";import a from"./tests/contextAwareModels/ContextTestModel.js";import o from"./tests/contextAwareModels/ContextAwareTestModel.js";import s from"./CustomFieldEntries.js";import c from"./CustomValidator.js";import l from"./CustomFieldModelTypeMap.js";import{DataTypes as u,Op as d}from"sequelize";const f=[i,r,o,a],p=async(r,i,{schemaPrefix:a=`sadot-migration`,schemaVersion:o=`5f8e4a7c-9b2d-4e1f-8c3a-b6d9e2f7a4c1`,useCustomFieldsEntries:f=!1,useModelTypeMapping:p=!1}={})=>{let m=`${a}_${o}${f?`_withEntries`:``}${p?`_withTypeMapping`:``}`;if(e.info(`custom-fields: initialize custom-fields tables`),!r.addModels)throw Error(`sequelize instance must have addModels function`);let h=[n,t,c,...f?[s]:[],...p?[l]:[]];r.addModels(h),p&&(n.hasMany(l,{foreignKey:`customFieldDefinitionId`,as:`modelTypeMappings`}),l.belongsTo(n,{foreignKey:`customFieldDefinitionId`,as:`customFieldDefinition`})),n.addScope(`userScope`,()=>{let e=i();return e?.permissions?{where:{entityId:[...Object.keys(e.permissions.fleets),...Object.keys(e.permissions.businessModels),...Object.keys(e.permissions.demandSources)]}}:{}}),c.addScope(`userScope`,()=>{let e=i();return e?.permissions?{where:{entityId:[...Object.keys(e.permissions.fleets),...Object.keys(e.permissions.businessModels),...Object.keys(e.permissions.demandSources)]}}:{}}),e.info(`custom-fields: models added`);let g=r.define(`SequelizeMeta`,{name:{type:u.STRING,allowNull:!1,unique:!0,primaryKey:!0,autoIncrement:!1}},{tableName:`SequelizeMeta`,timestamps:!1,schema:`public`});e.info(`custom-fields: starting migrations`);let _=await g.findAll({where:{name:{[d.like]:`${a}%`}},raw:!0}),v=_.at(-1),y=_.findIndex(e=>e.name===m);if(e.info(`custom-fields: migrations`,{currentMigrations:_,currentSadotSchemaVersion:v,newSadotSchemaVersion:m,expectedSchemaVersionIndex:y}),!v||v.name!==m){e.info(`custom-fields: syncing models`);try{if(await n.sync({alter:!0}),e.info(`custom-fields: CustomFieldDefinition synced successfully`),await t.sync({alter:!0}),e.info(`custom-fields: CustomFieldValue synced successfully`),await c.sync({alter:!0}),e.info(`custom-fields: CustomValidator synced successfully`),f&&(await s.sync({alter:!0}),e.info(`custom-fields: CustomFieldEntries synced successfully`)),p&&(await l.sync({alter:!0}),e.info(`custom-fields: CustomFieldModelTypeMap synced successfully`)),y===-1&&(await g.create({name:m}),e.info(`custom-fields: SequelizeMeta entry created successfully`)),e.info(`custom-fields: models synced`),_.length&&y!==-1&&y<_.length-1){let t=_.slice(y+1);e.info(`custom-fields: deleting newer migrations during down migration`,{count:t.length}),await g.destroy({where:{name:{[d.in]:t.map(e=>e.name)}}}),e.info(`custom-fields: newer migrations deleted successfully`)}}catch(t){throw e.error(`custom-fields: failed to sync models`,{error:t}),t}}},m=async t=>{if(e.info(`custom-fields: initialize custom-fields test models`),!t.addModels)throw Error(`sequelize instance must have addModels function`);t.addModels(f),await t.dropSchema(`custom-fields`,{logging:!1}),await t.createSchema(`custom-fields`,{logging:!1}),e.info(`custom-fields: test models added`),await i.sync({alter:!0}),await r.sync({alter:!0}),await a.sync({alter:!0}),await o.sync({alter:!0}),e.info(`custom-fields: test models synced`)};export{p as initTables,m as initTestModels};
1
+ import e from"../utils/logger/index.js";import t from"./CustomFieldValue.js";import n from"./CustomFieldDefinition.js";import r from"./tests/AssociatedTestModel.js";import i from"./tests/TestModel.js";import a from"./tests/contextAwareModels/ContextTestModel.js";import o from"./tests/contextAwareModels/ContextAwareTestModel.js";import s from"./CustomFieldEntries.js";import c from"./CustomValidator.js";import l from"./CustomFieldModelTypeMap.js";import{DataTypes as u,Op as d}from"sequelize";const f=[i,r,o,a],p=async(r,i,{schemaPrefix:a=`sadot-migration`,schemaVersion:o=`5f8e4a7c-9b2d-4e1f-8c3a-b6d9e2f7a4c1`,useCustomFieldsEntries:f=!1,useModelTypeMapping:p=!1,isMatPathEnabled:m}={})=>{let h=`${a}_${o}${f?`_withEntries`:``}${p?`_withTypeMapping`:``}`;if(e.info(`custom-fields: initialize custom-fields tables`),!r.addModels)throw Error(`sequelize instance must have addModels function`);let g=[n,t,c,...f?[s]:[],...p?[l]:[]];r.addModels(g),p&&(n.hasMany(l,{foreignKey:`customFieldDefinitionId`,as:`modelTypeMappings`}),l.belongsTo(n,{foreignKey:`customFieldDefinitionId`,as:`customFieldDefinition`})),n.addScope(`userScope`,()=>{if(m?.())return{};let e=i();return e?.permissions?{where:{entityId:[...Object.keys(e.permissions.fleets),...Object.keys(e.permissions.businessModels),...Object.keys(e.permissions.demandSources)]}}:{}}),c.addScope(`userScope`,()=>{if(m?.())return{};let e=i();return e?.permissions?{where:{entityId:[...Object.keys(e.permissions.fleets),...Object.keys(e.permissions.businessModels),...Object.keys(e.permissions.demandSources)]}}:{}}),e.info(`custom-fields: models added`);let _=r.define(`SequelizeMeta`,{name:{type:u.STRING,allowNull:!1,unique:!0,primaryKey:!0,autoIncrement:!1}},{tableName:`SequelizeMeta`,timestamps:!1,schema:`public`});e.info(`custom-fields: starting migrations`);let v=await _.findAll({where:{name:{[d.like]:`${a}%`}},raw:!0}),y=v.at(-1),b=v.findIndex(e=>e.name===h);if(e.info(`custom-fields: migrations`,{currentMigrations:v,currentSadotSchemaVersion:y,newSadotSchemaVersion:h,expectedSchemaVersionIndex:b}),!y||y.name!==h){e.info(`custom-fields: syncing models`);try{if(await n.sync({alter:!0}),e.info(`custom-fields: CustomFieldDefinition synced successfully`),await t.sync({alter:!0}),e.info(`custom-fields: CustomFieldValue synced successfully`),await c.sync({alter:!0}),e.info(`custom-fields: CustomValidator synced successfully`),f&&(await s.sync({alter:!0}),e.info(`custom-fields: CustomFieldEntries synced successfully`)),p&&(await l.sync({alter:!0}),e.info(`custom-fields: CustomFieldModelTypeMap synced successfully`)),b===-1&&(await _.create({name:h}),e.info(`custom-fields: SequelizeMeta entry created successfully`)),e.info(`custom-fields: models synced`),v.length&&b!==-1&&b<v.length-1){let t=v.slice(b+1);e.info(`custom-fields: deleting newer migrations during down migration`,{count:t.length}),await _.destroy({where:{name:{[d.in]:t.map(e=>e.name)}}}),e.info(`custom-fields: newer migrations deleted successfully`)}}catch(t){throw e.error(`custom-fields: failed to sync models`,{error:t}),t}}},m=async t=>{if(e.info(`custom-fields: initialize custom-fields test models`),!t.addModels)throw Error(`sequelize instance must have addModels function`);t.addModels(f),await t.dropSchema(`custom-fields`,{logging:!1}),await t.createSchema(`custom-fields`,{logging:!1}),e.info(`custom-fields: test models added`),await i.sync({alter:!0}),await r.sync({alter:!0}),await a.sync({alter:!0}),await o.sync({alter:!0}),e.info(`custom-fields: test models synced`)};export{p as initTables,m as initTestModels};
2
2
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["TestModel","AssociatedTestModel","ContextAwareTestModel","ContextTestModel","productionModels: ProductionModel[]","CustomFieldDefinition","CustomFieldValue","CustomValidator","CustomFieldEntries","CustomFieldModelTypeMap"],"sources":["../../src/models/index.ts"],"sourcesContent":["import { DataTypes, Op } from 'sequelize';\nimport type { Sequelize } from 'sequelize-typescript';\nimport logger from '../utils/logger';\nimport CustomFieldDefinition from './CustomFieldDefinition';\nimport CustomFieldValue from './CustomFieldValue';\nimport TestModel from './tests/TestModel';\nimport ContextAwareTestModel from './tests/contextAwareModels/ContextAwareTestModel';\nimport ContextTestModel from './tests/contextAwareModels/ContextTestModel';\nimport AssociatedTestModel from './tests/AssociatedTestModel';\nimport type { CustomFieldOptions } from '../types';\nimport CustomFieldEntries from './CustomFieldEntries';\nimport CustomValidator from './CustomValidator';\nimport CustomFieldModelTypeMap from './CustomFieldModelTypeMap';\n\ntype ProductionModel = typeof CustomFieldDefinition | typeof CustomFieldValue | typeof CustomFieldEntries | typeof CustomValidator | typeof CustomFieldModelTypeMap;\ninterface InitTablesOptions {\n schemaPrefix?: string;\n schemaVersion?: string;\n useCustomFieldsEntries?: boolean;\n useModelTypeMapping?: boolean;\n}\n\nconst testModels = [TestModel, AssociatedTestModel, ContextAwareTestModel, ContextTestModel];\n\nconst SADOT_MIGRATION_PREFIX = 'sadot-migration';\nconst SCHEMA_VERSION = '5f8e4a7c-9b2d-4e1f-8c3a-b6d9e2f7a4c1';\n\nconst initTables = async (\n sequelize: Sequelize,\n getUser: CustomFieldOptions['getUser'],\n {\n schemaPrefix = SADOT_MIGRATION_PREFIX,\n schemaVersion = SCHEMA_VERSION,\n useCustomFieldsEntries = false,\n useModelTypeMapping = false,\n }: InitTablesOptions = {},\n): Promise<void> => {\n const CUSTOM_FIELDS_SCHEMA_VERSION = `${schemaPrefix}_${schemaVersion}${useCustomFieldsEntries ? '_withEntries' : ''}${useModelTypeMapping ? '_withTypeMapping' : ''}`;\n logger.info('custom-fields: initialize custom-fields tables');\n // Detect models and import them to the orm\n if (!sequelize.addModels) {\n throw new Error('sequelize instance must have addModels function');\n }\n const productionModels: ProductionModel[] = [\n CustomFieldDefinition,\n CustomFieldValue,\n CustomValidator,\n ...(useCustomFieldsEntries ? [CustomFieldEntries] : []),\n ...(useModelTypeMapping ? [CustomFieldModelTypeMap] : []),\n ];\n\n sequelize.addModels(productionModels);\n\n // Add the association only when useModelTypeMapping is enabled\n if (useModelTypeMapping) {\n CustomFieldDefinition.hasMany(CustomFieldModelTypeMap, {\n foreignKey: 'customFieldDefinitionId',\n as: 'modelTypeMappings',\n });\n CustomFieldModelTypeMap.belongsTo(CustomFieldDefinition, {\n foreignKey: 'customFieldDefinitionId',\n as: 'customFieldDefinition',\n });\n }\n\n CustomFieldDefinition.addScope('userScope', () => {\n const user = getUser();\n if (!user?.permissions) {\n return {};\n }\n return {\n where: {\n entityId: [\n ...Object.keys(user.permissions.fleets),\n ...Object.keys(user.permissions.businessModels),\n ...Object.keys(user.permissions.demandSources),\n ],\n },\n };\n });\n\n CustomValidator.addScope('userScope', () => {\n const user = getUser();\n if (!user?.permissions) {\n return {};\n }\n return {\n where: {\n entityId: [\n ...Object.keys(user.permissions.fleets),\n ...Object.keys(user.permissions.businessModels),\n ...Object.keys(user.permissions.demandSources),\n ],\n },\n };\n });\n\n logger.info('custom-fields: models added');\n\n const SequelizeMeta = sequelize.define(\n 'SequelizeMeta',\n {\n name: {\n type: DataTypes.STRING,\n allowNull: false,\n unique: true,\n primaryKey: true,\n autoIncrement: false,\n },\n },\n {\n tableName: 'SequelizeMeta',\n timestamps: false,\n schema: 'public',\n },\n );\n\n logger.info('custom-fields: starting migrations');\n const migrations = await SequelizeMeta.findAll({ where: { name: { [Op.like]: `${schemaPrefix}%` } }, raw: true });\n const currentSadotSchemaVersion = migrations.at(-1);\n const expectedSchemaVersionIndex = migrations.findIndex(m => (m as any).name === CUSTOM_FIELDS_SCHEMA_VERSION);\n\n logger.info('custom-fields: migrations', {\n currentMigrations: migrations,\n currentSadotSchemaVersion,\n newSadotSchemaVersion: CUSTOM_FIELDS_SCHEMA_VERSION,\n expectedSchemaVersionIndex,\n });\n if (!currentSadotSchemaVersion || (currentSadotSchemaVersion as any).name !== CUSTOM_FIELDS_SCHEMA_VERSION) {\n logger.info('custom-fields: syncing models');\n try {\n await CustomFieldDefinition.sync({ alter: true });\n logger.info('custom-fields: CustomFieldDefinition synced successfully');\n\n await CustomFieldValue.sync({ alter: true });\n logger.info('custom-fields: CustomFieldValue synced successfully');\n\n await CustomValidator.sync({ alter: true });\n logger.info('custom-fields: CustomValidator synced successfully');\n\n // T.Y TODO: Remove the if statement once we're ready to add the new entries table for all MS\n if (useCustomFieldsEntries) {\n await CustomFieldEntries.sync({ alter: true });\n logger.info('custom-fields: CustomFieldEntries synced successfully');\n }\n\n if (useModelTypeMapping) {\n await CustomFieldModelTypeMap.sync({ alter: true });\n logger.info('custom-fields: CustomFieldModelTypeMap synced successfully');\n }\n\n if (expectedSchemaVersionIndex === -1) {\n await SequelizeMeta.create({ name: CUSTOM_FIELDS_SCHEMA_VERSION });\n logger.info('custom-fields: SequelizeMeta entry created successfully');\n }\n\n logger.info('custom-fields: models synced');\n if (migrations.length && expectedSchemaVersionIndex !== -1 && expectedSchemaVersionIndex < migrations.length - 1) {\n // We have existing migrations, and we are calling `sync`.\n // This means we are in a `down` migration, and hence we should delete newer migrations to ensure we can reapply them.\n const migrationsToDelete = migrations.slice(expectedSchemaVersionIndex + 1);\n logger.info('custom-fields: deleting newer migrations during down migration', { count: migrationsToDelete.length });\n await SequelizeMeta.destroy({ where: { name: { [Op.in]: migrationsToDelete.map(m => (m as any).name) } } });\n logger.info('custom-fields: newer migrations deleted successfully');\n }\n } catch (error) {\n logger.error('custom-fields: failed to sync models', { error });\n throw error;\n }\n }\n};\n\nconst initTestModels = async (sequelize: Sequelize): Promise<void> => {\n logger.info('custom-fields: initialize custom-fields test models');\n // Detect models and import them to the orm\n if (!sequelize.addModels) {\n throw new Error('sequelize instance must have addModels function');\n }\n\n sequelize.addModels(testModels);\n await sequelize.dropSchema('custom-fields', { logging: false });\n await sequelize.createSchema('custom-fields', { logging: false });\n\n logger.info('custom-fields: test models added');\n await TestModel.sync({ alter: true });\n await AssociatedTestModel.sync({ alter: true });\n await ContextTestModel.sync({ alter: true });\n await ContextAwareTestModel.sync({ alter: true });\n logger.info('custom-fields: test models synced');\n};\n\nexport {\n CustomFieldValue,\n CustomFieldDefinition,\n CustomFieldEntries,\n CustomValidator,\n CustomFieldModelTypeMap,\n TestModel,\n AssociatedTestModel,\n ContextAwareTestModel,\n ContextTestModel,\n initTables,\n initTestModels,\n};\n"],"mappings":"+eAsBA,MAAM,EAAa,CAACA,EAAWC,EAAqBC,EAAuBC,EAAiB,CAKtF,EAAa,MACjB,EACA,EACA,CACE,eAAe,kBACf,gBAAgB,uCAChB,yBAAyB,GACzB,sBAAsB,IACD,EAAE,GACP,CAClB,IAAM,EAA+B,GAAG,EAAa,GAAG,IAAgB,EAAyB,eAAiB,KAAK,EAAsB,mBAAqB,KAGlK,GAFA,EAAO,KAAK,iDAAiD,CAEzD,CAAC,EAAU,UACb,MAAU,MAAM,kDAAkD,CAEpE,IAAMC,EAAsC,CAC1CC,EACAC,EACAC,EACA,GAAI,EAAyB,CAACC,EAAmB,CAAG,EAAE,CACtD,GAAI,EAAsB,CAACC,EAAwB,CAAG,EAAE,CACzD,CAED,EAAU,UAAU,EAAiB,CAGjC,IACF,EAAsB,QAAQA,EAAyB,CACrD,WAAY,0BACZ,GAAI,oBACL,CAAC,CACF,EAAwB,UAAUJ,EAAuB,CACvD,WAAY,0BACZ,GAAI,wBACL,CAAC,EAGJ,EAAsB,SAAS,gBAAmB,CAChD,IAAM,EAAO,GAAS,CAIt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D,EAAO,KAAK,oCAAoC"}
1
+ {"version":3,"file":"index.js","names":["TestModel","AssociatedTestModel","ContextAwareTestModel","ContextTestModel","productionModels: ProductionModel[]","CustomFieldDefinition","CustomFieldValue","CustomValidator","CustomFieldEntries","CustomFieldModelTypeMap"],"sources":["../../src/models/index.ts"],"sourcesContent":["import { DataTypes, Op } from 'sequelize';\nimport type { Sequelize } from 'sequelize-typescript';\nimport logger from '../utils/logger';\nimport CustomFieldDefinition from './CustomFieldDefinition';\nimport CustomFieldValue from './CustomFieldValue';\nimport TestModel from './tests/TestModel';\nimport ContextAwareTestModel from './tests/contextAwareModels/ContextAwareTestModel';\nimport ContextTestModel from './tests/contextAwareModels/ContextTestModel';\nimport AssociatedTestModel from './tests/AssociatedTestModel';\nimport type { CustomFieldOptions } from '../types';\nimport CustomFieldEntries from './CustomFieldEntries';\nimport CustomValidator from './CustomValidator';\nimport CustomFieldModelTypeMap from './CustomFieldModelTypeMap';\n\ntype ProductionModel = typeof CustomFieldDefinition | typeof CustomFieldValue | typeof CustomFieldEntries | typeof CustomValidator | typeof CustomFieldModelTypeMap;\ninterface InitTablesOptions {\n schemaPrefix?: string;\n schemaVersion?: string;\n useCustomFieldsEntries?: boolean;\n useModelTypeMapping?: boolean;\n isMatPathEnabled?: CustomFieldOptions['isMatPathEnabled'];\n}\n\nconst testModels = [TestModel, AssociatedTestModel, ContextAwareTestModel, ContextTestModel];\n\nconst SADOT_MIGRATION_PREFIX = 'sadot-migration';\nconst SCHEMA_VERSION = '5f8e4a7c-9b2d-4e1f-8c3a-b6d9e2f7a4c1';\n\nconst initTables = async (\n sequelize: Sequelize,\n getUser: CustomFieldOptions['getUser'],\n {\n schemaPrefix = SADOT_MIGRATION_PREFIX,\n schemaVersion = SCHEMA_VERSION,\n useCustomFieldsEntries = false,\n useModelTypeMapping = false,\n isMatPathEnabled,\n }: InitTablesOptions = {},\n): Promise<void> => {\n const CUSTOM_FIELDS_SCHEMA_VERSION = `${schemaPrefix}_${schemaVersion}${useCustomFieldsEntries ? '_withEntries' : ''}${useModelTypeMapping ? '_withTypeMapping' : ''}`;\n logger.info('custom-fields: initialize custom-fields tables');\n // Detect models and import them to the orm\n if (!sequelize.addModels) {\n throw new Error('sequelize instance must have addModels function');\n }\n const productionModels: ProductionModel[] = [\n CustomFieldDefinition,\n CustomFieldValue,\n CustomValidator,\n ...(useCustomFieldsEntries ? [CustomFieldEntries] : []),\n ...(useModelTypeMapping ? [CustomFieldModelTypeMap] : []),\n ];\n\n sequelize.addModels(productionModels);\n\n // Add the association only when useModelTypeMapping is enabled\n if (useModelTypeMapping) {\n CustomFieldDefinition.hasMany(CustomFieldModelTypeMap, {\n foreignKey: 'customFieldDefinitionId',\n as: 'modelTypeMappings',\n });\n CustomFieldModelTypeMap.belongsTo(CustomFieldDefinition, {\n foreignKey: 'customFieldDefinitionId',\n as: 'customFieldDefinition',\n });\n }\n\n CustomFieldDefinition.addScope('userScope', () => {\n // When mat-path is active, the consumer is responsible for restricting entityIds\n // (typically by expanding the request's entityIds to include ancestor paths the\n // caller can see). Bypass the legacy permission filter so partner/ancestor\n // entityIds are not dropped.\n if (isMatPathEnabled?.()) return {};\n const user = getUser();\n if (!user?.permissions) {\n return {};\n }\n return {\n where: {\n entityId: [\n ...Object.keys(user.permissions.fleets),\n ...Object.keys(user.permissions.businessModels),\n ...Object.keys(user.permissions.demandSources),\n ],\n },\n };\n });\n\n CustomValidator.addScope('userScope', () => {\n if (isMatPathEnabled?.()) return {};\n const user = getUser();\n if (!user?.permissions) {\n return {};\n }\n return {\n where: {\n entityId: [\n ...Object.keys(user.permissions.fleets),\n ...Object.keys(user.permissions.businessModels),\n ...Object.keys(user.permissions.demandSources),\n ],\n },\n };\n });\n\n logger.info('custom-fields: models added');\n\n const SequelizeMeta = sequelize.define(\n 'SequelizeMeta',\n {\n name: {\n type: DataTypes.STRING,\n allowNull: false,\n unique: true,\n primaryKey: true,\n autoIncrement: false,\n },\n },\n {\n tableName: 'SequelizeMeta',\n timestamps: false,\n schema: 'public',\n },\n );\n\n logger.info('custom-fields: starting migrations');\n const migrations = await SequelizeMeta.findAll({ where: { name: { [Op.like]: `${schemaPrefix}%` } }, raw: true });\n const currentSadotSchemaVersion = migrations.at(-1);\n const expectedSchemaVersionIndex = migrations.findIndex(m => (m as any).name === CUSTOM_FIELDS_SCHEMA_VERSION);\n\n logger.info('custom-fields: migrations', {\n currentMigrations: migrations,\n currentSadotSchemaVersion,\n newSadotSchemaVersion: CUSTOM_FIELDS_SCHEMA_VERSION,\n expectedSchemaVersionIndex,\n });\n if (!currentSadotSchemaVersion || (currentSadotSchemaVersion as any).name !== CUSTOM_FIELDS_SCHEMA_VERSION) {\n logger.info('custom-fields: syncing models');\n try {\n await CustomFieldDefinition.sync({ alter: true });\n logger.info('custom-fields: CustomFieldDefinition synced successfully');\n\n await CustomFieldValue.sync({ alter: true });\n logger.info('custom-fields: CustomFieldValue synced successfully');\n\n await CustomValidator.sync({ alter: true });\n logger.info('custom-fields: CustomValidator synced successfully');\n\n // T.Y TODO: Remove the if statement once we're ready to add the new entries table for all MS\n if (useCustomFieldsEntries) {\n await CustomFieldEntries.sync({ alter: true });\n logger.info('custom-fields: CustomFieldEntries synced successfully');\n }\n\n if (useModelTypeMapping) {\n await CustomFieldModelTypeMap.sync({ alter: true });\n logger.info('custom-fields: CustomFieldModelTypeMap synced successfully');\n }\n\n if (expectedSchemaVersionIndex === -1) {\n await SequelizeMeta.create({ name: CUSTOM_FIELDS_SCHEMA_VERSION });\n logger.info('custom-fields: SequelizeMeta entry created successfully');\n }\n\n logger.info('custom-fields: models synced');\n if (migrations.length && expectedSchemaVersionIndex !== -1 && expectedSchemaVersionIndex < migrations.length - 1) {\n // We have existing migrations, and we are calling `sync`.\n // This means we are in a `down` migration, and hence we should delete newer migrations to ensure we can reapply them.\n const migrationsToDelete = migrations.slice(expectedSchemaVersionIndex + 1);\n logger.info('custom-fields: deleting newer migrations during down migration', { count: migrationsToDelete.length });\n await SequelizeMeta.destroy({ where: { name: { [Op.in]: migrationsToDelete.map(m => (m as any).name) } } });\n logger.info('custom-fields: newer migrations deleted successfully');\n }\n } catch (error) {\n logger.error('custom-fields: failed to sync models', { error });\n throw error;\n }\n }\n};\n\nconst initTestModels = async (sequelize: Sequelize): Promise<void> => {\n logger.info('custom-fields: initialize custom-fields test models');\n // Detect models and import them to the orm\n if (!sequelize.addModels) {\n throw new Error('sequelize instance must have addModels function');\n }\n\n sequelize.addModels(testModels);\n await sequelize.dropSchema('custom-fields', { logging: false });\n await sequelize.createSchema('custom-fields', { logging: false });\n\n logger.info('custom-fields: test models added');\n await TestModel.sync({ alter: true });\n await AssociatedTestModel.sync({ alter: true });\n await ContextTestModel.sync({ alter: true });\n await ContextAwareTestModel.sync({ alter: true });\n logger.info('custom-fields: test models synced');\n};\n\nexport {\n CustomFieldValue,\n CustomFieldDefinition,\n CustomFieldEntries,\n CustomValidator,\n CustomFieldModelTypeMap,\n TestModel,\n AssociatedTestModel,\n ContextAwareTestModel,\n ContextTestModel,\n initTables,\n initTestModels,\n};\n"],"mappings":"+eAuBA,MAAM,EAAa,CAACA,EAAWC,EAAqBC,EAAuBC,EAAiB,CAKtF,EAAa,MACjB,EACA,EACA,CACE,eAAe,kBACf,gBAAgB,uCAChB,yBAAyB,GACzB,sBAAsB,GACtB,oBACqB,EAAE,GACP,CAClB,IAAM,EAA+B,GAAG,EAAa,GAAG,IAAgB,EAAyB,eAAiB,KAAK,EAAsB,mBAAqB,KAGlK,GAFA,EAAO,KAAK,iDAAiD,CAEzD,CAAC,EAAU,UACb,MAAU,MAAM,kDAAkD,CAEpE,IAAMC,EAAsC,CAC1CC,EACAC,EACAC,EACA,GAAI,EAAyB,CAACC,EAAmB,CAAG,EAAE,CACtD,GAAI,EAAsB,CAACC,EAAwB,CAAG,EAAE,CACzD,CAED,EAAU,UAAU,EAAiB,CAGjC,IACF,EAAsB,QAAQA,EAAyB,CACrD,WAAY,0BACZ,GAAI,oBACL,CAAC,CACF,EAAwB,UAAU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CAAE,MAAO,GAAM,CAAC,CACrC,MAAMC,EAAoB,KAAK,CAAE,MAAO,GAAM,CAAC,CAC/C,MAAME,EAAiB,KAAK,CAAE,MAAO,GAAM,CAAC,CAC5C,MAAMD,EAAsB,KAAK,CAAE,MAAO,GAAM,CAAC,CACjD,EAAO,KAAK,oCAAoC"}
@@ -52,6 +52,13 @@ interface CustomFieldOptions {
52
52
  useValidators?: boolean;
53
53
  useModelTypeMapping?: boolean;
54
54
  getRequiredCustomFields?: (instance: any, fieldDefinitions: CustomFieldDefinition[], options: any) => Promise<string[]> | string[];
55
+ /**
56
+ * Optional predicate that returns true when materialized-path RLS is active for the current
57
+ * request. When it returns true, sadot's `userScope` on CFD/CV becomes a no-op so RLS is the
58
+ * sole filter (consumer typically decorates CFD/CV with their mat-path manager so RLS applies).
59
+ * Pass `matPathManager.isScopingRequest` if using `@autofleet/mat-path-mvp`.
60
+ */
61
+ isMatPathEnabled?: () => boolean;
55
62
  }
56
63
  //#endregion
57
64
  export { CustomFieldOptions, ModelFetcher, Models };
@@ -53,6 +53,13 @@ interface CustomFieldOptions {
53
53
  useValidators?: boolean;
54
54
  useModelTypeMapping?: boolean;
55
55
  getRequiredCustomFields?: (instance: any, fieldDefinitions: CustomFieldDefinition[], options: any) => Promise<string[]> | string[];
56
+ /**
57
+ * Optional predicate that returns true when materialized-path RLS is active for the current
58
+ * request. When it returns true, sadot's `userScope` on CFD/CV becomes a no-op so RLS is the
59
+ * sole filter (consumer typically decorates CFD/CV with their mat-path manager so RLS applies).
60
+ * Pass `matPathManager.isScopingRequest` if using `@autofleet/mat-path-mvp`.
61
+ */
62
+ isMatPathEnabled?: () => boolean;
56
63
  }
57
64
  //#endregion
58
65
  export { CustomFieldOptions, ModelFetcher, Models };
@@ -1,2 +1,2 @@
1
- const e=require(`../../_virtual/rolldown_runtime.cjs`);let t=require(`@autofleet/common-types`);const n=[`businessModelId`,`fleetId`,`demandSourceId`];let r=function(e){return e.NUMBER=`number`,e.BOOLEAN=`boolean`,e.DATE=`date`,e.DATETIME=`datetime`,e.TEXT=`text`,e.IMAGE=`image`,e.SELECT=`select`,e.STATUS=`status`,e.FILE=`file`,e}({});const i=t.customFields.CUSTOM_FIELDS_FILTER_SCOPE;exports.CUSTOM_FIELDS_FILTER_SCOPE=i,exports.CustomFieldDefinitionType=r,exports.supportedEntities=n;
1
+ const e=require(`../../_virtual/rolldown_runtime.cjs`);let t=require(`@autofleet/common-types`);const n=[`businessModelId`,`fleetId`,`demandSourceId`];let r=function(e){return e.NUMBER=`number`,e.BOOLEAN=`boolean`,e.DATE=`date`,e.DATETIME=`datetime`,e.TEXT=`text`,e.IMAGE=`image`,e.SELECT=`select`,e.STATUS=`status`,e.FILE=`file`,e.MULTI_SELECT_STATUS=`multi-select-status`,e.MULTI_SELECT_DROPDOWN=`multi-select-dropdown`,e}({});const i=t.customFields.CUSTOM_FIELDS_FILTER_SCOPE;exports.CUSTOM_FIELDS_FILTER_SCOPE=i,exports.CustomFieldDefinitionType=r,exports.supportedEntities=n;
2
2
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["CUSTOM_FIELDS_FILTER_SCOPE: typeof customFields.CUSTOM_FIELDS_FILTER_SCOPE","customFields"],"sources":["../../../src/utils/constants/index.ts"],"sourcesContent":["import { customFields } from '@autofleet/common-types';\n\nexport const supportedEntities = ['businessModelId', 'fleetId', 'demandSourceId'] as const;\n\n/**\n * Supported custom field types\n */\nexport enum CustomFieldDefinitionType {\n NUMBER = 'number',\n BOOLEAN = 'boolean',\n DATE = 'date',\n DATETIME = 'datetime',\n TEXT = 'text',\n IMAGE = 'image',\n SELECT = 'select',\n STATUS = 'status',\n FILE = 'file',\n}\n\nconst CUSTOM_FIELDS_FILTER_SCOPE: typeof customFields.CUSTOM_FIELDS_FILTER_SCOPE = customFields.CUSTOM_FIELDS_FILTER_SCOPE;\n\nexport {\n /** @deprecated Use the value from `@autofleet/common-types` instead */\n CUSTOM_FIELDS_FILTER_SCOPE,\n};\n"],"mappings":"gGAEA,MAAa,EAAoB,CAAC,kBAAmB,UAAW,iBAAiB,CAKjF,IAAY,EAAA,SAAA,EAAL,OACL,GAAA,OAAA,SACA,EAAA,QAAA,UACA,EAAA,KAAA,OACA,EAAA,SAAA,WACA,EAAA,KAAA,OACA,EAAA,MAAA,QACA,EAAA,OAAA,SACA,EAAA,OAAA,SACA,EAAA,KAAA,cAGF,MAAMA,EAA6EC,EAAAA,aAAa"}
1
+ {"version":3,"file":"index.cjs","names":["CUSTOM_FIELDS_FILTER_SCOPE: typeof customFields.CUSTOM_FIELDS_FILTER_SCOPE","customFields"],"sources":["../../../src/utils/constants/index.ts"],"sourcesContent":["import { customFields } from '@autofleet/common-types';\n\nexport const supportedEntities = ['businessModelId', 'fleetId', 'demandSourceId'] as const;\n\n/**\n * Supported custom field types\n */\nexport enum CustomFieldDefinitionType {\n NUMBER = 'number',\n BOOLEAN = 'boolean',\n DATE = 'date',\n DATETIME = 'datetime',\n TEXT = 'text',\n IMAGE = 'image',\n SELECT = 'select',\n STATUS = 'status',\n FILE = 'file',\n MULTI_SELECT_STATUS = 'multi-select-status',\n MULTI_SELECT_DROPDOWN = 'multi-select-dropdown',\n}\n\nconst CUSTOM_FIELDS_FILTER_SCOPE: typeof customFields.CUSTOM_FIELDS_FILTER_SCOPE = customFields.CUSTOM_FIELDS_FILTER_SCOPE;\n\nexport {\n /** @deprecated Use the value from `@autofleet/common-types` instead */\n CUSTOM_FIELDS_FILTER_SCOPE,\n};\n"],"mappings":"gGAEA,MAAa,EAAoB,CAAC,kBAAmB,UAAW,iBAAiB,CAKjF,IAAY,EAAA,SAAA,EAAL,OACL,GAAA,OAAA,SACA,EAAA,QAAA,UACA,EAAA,KAAA,OACA,EAAA,SAAA,WACA,EAAA,KAAA,OACA,EAAA,MAAA,QACA,EAAA,OAAA,SACA,EAAA,OAAA,SACA,EAAA,KAAA,OACA,EAAA,oBAAA,sBACA,EAAA,sBAAA,+BAGF,MAAMA,EAA6EC,EAAAA,aAAa"}
@@ -15,6 +15,8 @@ declare enum CustomFieldDefinitionType {
15
15
  SELECT = "select",
16
16
  STATUS = "status",
17
17
  FILE = "file",
18
+ MULTI_SELECT_STATUS = "multi-select-status",
19
+ MULTI_SELECT_DROPDOWN = "multi-select-dropdown",
18
20
  }
19
21
  declare const CUSTOM_FIELDS_FILTER_SCOPE: typeof customFields.CUSTOM_FIELDS_FILTER_SCOPE;
20
22
  //#endregion
@@ -15,6 +15,8 @@ declare enum CustomFieldDefinitionType {
15
15
  SELECT = "select",
16
16
  STATUS = "status",
17
17
  FILE = "file",
18
+ MULTI_SELECT_STATUS = "multi-select-status",
19
+ MULTI_SELECT_DROPDOWN = "multi-select-dropdown",
18
20
  }
19
21
  declare const CUSTOM_FIELDS_FILTER_SCOPE: typeof customFields.CUSTOM_FIELDS_FILTER_SCOPE;
20
22
  //#endregion
@@ -1,2 +1,2 @@
1
- import{customFields as e}from"@autofleet/common-types";const t=[`businessModelId`,`fleetId`,`demandSourceId`];let n=function(e){return e.NUMBER=`number`,e.BOOLEAN=`boolean`,e.DATE=`date`,e.DATETIME=`datetime`,e.TEXT=`text`,e.IMAGE=`image`,e.SELECT=`select`,e.STATUS=`status`,e.FILE=`file`,e}({});const r=e.CUSTOM_FIELDS_FILTER_SCOPE;export{r as CUSTOM_FIELDS_FILTER_SCOPE,n as CustomFieldDefinitionType,t as supportedEntities};
1
+ import{customFields as e}from"@autofleet/common-types";const t=[`businessModelId`,`fleetId`,`demandSourceId`];let n=function(e){return e.NUMBER=`number`,e.BOOLEAN=`boolean`,e.DATE=`date`,e.DATETIME=`datetime`,e.TEXT=`text`,e.IMAGE=`image`,e.SELECT=`select`,e.STATUS=`status`,e.FILE=`file`,e.MULTI_SELECT_STATUS=`multi-select-status`,e.MULTI_SELECT_DROPDOWN=`multi-select-dropdown`,e}({});const r=e.CUSTOM_FIELDS_FILTER_SCOPE;export{r as CUSTOM_FIELDS_FILTER_SCOPE,n as CustomFieldDefinitionType,t as supportedEntities};
2
2
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["CUSTOM_FIELDS_FILTER_SCOPE: typeof customFields.CUSTOM_FIELDS_FILTER_SCOPE"],"sources":["../../../src/utils/constants/index.ts"],"sourcesContent":["import { customFields } from '@autofleet/common-types';\n\nexport const supportedEntities = ['businessModelId', 'fleetId', 'demandSourceId'] as const;\n\n/**\n * Supported custom field types\n */\nexport enum CustomFieldDefinitionType {\n NUMBER = 'number',\n BOOLEAN = 'boolean',\n DATE = 'date',\n DATETIME = 'datetime',\n TEXT = 'text',\n IMAGE = 'image',\n SELECT = 'select',\n STATUS = 'status',\n FILE = 'file',\n}\n\nconst CUSTOM_FIELDS_FILTER_SCOPE: typeof customFields.CUSTOM_FIELDS_FILTER_SCOPE = customFields.CUSTOM_FIELDS_FILTER_SCOPE;\n\nexport {\n /** @deprecated Use the value from `@autofleet/common-types` instead */\n CUSTOM_FIELDS_FILTER_SCOPE,\n};\n"],"mappings":"uDAEA,MAAa,EAAoB,CAAC,kBAAmB,UAAW,iBAAiB,CAKjF,IAAY,EAAA,SAAA,EAAL,OACL,GAAA,OAAA,SACA,EAAA,QAAA,UACA,EAAA,KAAA,OACA,EAAA,SAAA,WACA,EAAA,KAAA,OACA,EAAA,MAAA,QACA,EAAA,OAAA,SACA,EAAA,OAAA,SACA,EAAA,KAAA,cAGF,MAAMA,EAA6E,EAAa"}
1
+ {"version":3,"file":"index.js","names":["CUSTOM_FIELDS_FILTER_SCOPE: typeof customFields.CUSTOM_FIELDS_FILTER_SCOPE"],"sources":["../../../src/utils/constants/index.ts"],"sourcesContent":["import { customFields } from '@autofleet/common-types';\n\nexport const supportedEntities = ['businessModelId', 'fleetId', 'demandSourceId'] as const;\n\n/**\n * Supported custom field types\n */\nexport enum CustomFieldDefinitionType {\n NUMBER = 'number',\n BOOLEAN = 'boolean',\n DATE = 'date',\n DATETIME = 'datetime',\n TEXT = 'text',\n IMAGE = 'image',\n SELECT = 'select',\n STATUS = 'status',\n FILE = 'file',\n MULTI_SELECT_STATUS = 'multi-select-status',\n MULTI_SELECT_DROPDOWN = 'multi-select-dropdown',\n}\n\nconst CUSTOM_FIELDS_FILTER_SCOPE: typeof customFields.CUSTOM_FIELDS_FILTER_SCOPE = customFields.CUSTOM_FIELDS_FILTER_SCOPE;\n\nexport {\n /** @deprecated Use the value from `@autofleet/common-types` instead */\n CUSTOM_FIELDS_FILTER_SCOPE,\n};\n"],"mappings":"uDAEA,MAAa,EAAoB,CAAC,kBAAmB,UAAW,iBAAiB,CAKjF,IAAY,EAAA,SAAA,EAAL,OACL,GAAA,OAAA,SACA,EAAA,QAAA,UACA,EAAA,KAAA,OACA,EAAA,SAAA,WACA,EAAA,KAAA,OACA,EAAA,MAAA,QACA,EAAA,OAAA,SACA,EAAA,OAAA,SACA,EAAA,KAAA,OACA,EAAA,oBAAA,sBACA,EAAA,sBAAA,+BAGF,MAAMA,EAA6E,EAAa"}
@@ -1,2 +1,2 @@
1
- const e=require(`../../../_virtual/rolldown_runtime.cjs`),t=require(`../../constants/index.cjs`),n=require(`./select.validator.cjs`),r=require(`./status.validator.cjs`);let i=require(`joi`);i=e.__toESM(i);const a={[t.CustomFieldDefinitionType.SELECT]:t.CustomFieldDefinitionType.SELECT,[t.CustomFieldDefinitionType.STATUS]:t.CustomFieldDefinitionType.STATUS},o={[t.CustomFieldDefinitionType.SELECT]:n.validateSelect,[t.CustomFieldDefinitionType.STATUS]:r.validateStatus,[t.CustomFieldDefinitionType.TEXT]:e=>i.default.string().min(0).validate(e),[t.CustomFieldDefinitionType.NUMBER]:e=>i.default.number().strict(!0).validate(e),[t.CustomFieldDefinitionType.BOOLEAN]:e=>i.default.boolean().strict().validate(e),[t.CustomFieldDefinitionType.DATE]:e=>i.default.date().validate(e),[t.CustomFieldDefinitionType.DATETIME]:e=>i.default.date().validate(e),[t.CustomFieldDefinitionType.IMAGE]:e=>i.default.array().min(1).unique().items(i.default.string().uri()).validate(e),[t.CustomFieldDefinitionType.FILE]:e=>i.default.array().min(1).unique().items(i.default.object({name:i.default.string().required(),type:i.default.string(),size:i.default.string(),addedBy:i.default.string().uuid()})).validate(e)};exports.CustomValidationTypes=a,exports.validators=o;
1
+ const e=require(`../../../_virtual/rolldown_runtime.cjs`),t=require(`../../constants/index.cjs`),n=require(`./select.validator.cjs`),r=require(`./status.validator.cjs`),i=require(`./multi-select-status.validator.cjs`),a=require(`./multi-select-dropdown.validator.cjs`);let o=require(`joi`);o=e.__toESM(o);const s={[t.CustomFieldDefinitionType.SELECT]:t.CustomFieldDefinitionType.SELECT,[t.CustomFieldDefinitionType.STATUS]:t.CustomFieldDefinitionType.STATUS,[t.CustomFieldDefinitionType.MULTI_SELECT_STATUS]:t.CustomFieldDefinitionType.MULTI_SELECT_STATUS,[t.CustomFieldDefinitionType.MULTI_SELECT_DROPDOWN]:t.CustomFieldDefinitionType.MULTI_SELECT_DROPDOWN},c={[t.CustomFieldDefinitionType.SELECT]:n.validateSelect,[t.CustomFieldDefinitionType.STATUS]:r.validateStatus,[t.CustomFieldDefinitionType.MULTI_SELECT_STATUS]:i.validateMultiSelectStatus,[t.CustomFieldDefinitionType.MULTI_SELECT_DROPDOWN]:a.validateMultiSelectDropdown,[t.CustomFieldDefinitionType.TEXT]:e=>o.default.string().min(0).validate(e),[t.CustomFieldDefinitionType.NUMBER]:e=>o.default.number().strict(!0).validate(e),[t.CustomFieldDefinitionType.BOOLEAN]:e=>o.default.boolean().strict().validate(e),[t.CustomFieldDefinitionType.DATE]:e=>o.default.date().validate(e),[t.CustomFieldDefinitionType.DATETIME]:e=>o.default.date().validate(e),[t.CustomFieldDefinitionType.IMAGE]:e=>o.default.array().min(1).unique().items(o.default.string().uri()).validate(e),[t.CustomFieldDefinitionType.FILE]:e=>o.default.array().min(1).unique().items(o.default.object({name:o.default.string().required(),type:o.default.string(),size:o.default.string(),addedBy:o.default.string().uuid()})).validate(e)};exports.CustomValidationTypes=s,exports.validators=c;
2
2
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["CustomValidationTypes: Record<Extract<CustomFieldDefinitionType, 'select' | 'status'>, CustomFieldDefinitionType>","CustomFieldDefinitionType","validators: Validators","validateSelect","validateStatus","Joi"],"sources":["../../../../src/utils/validations/validators/index.ts"],"sourcesContent":["import Joi from 'joi';\nimport { CustomFieldDefinitionType } from '../../constants';\nimport type { Validator, Validators } from '../type';\nimport { validateSelect } from './select.validator';\nimport { validateStatus } from './status.validator';\n\ntype CustomValidationTypes = Extract<CustomFieldDefinitionType, 'select' | 'status'>;\n/**\n * Custom field types that must have custom validation.\n * TODO: remove this after moving to schema-based validation\n */\nexport const CustomValidationTypes: Record<Extract<CustomFieldDefinitionType, 'select' | 'status'>, CustomFieldDefinitionType> = {\n [CustomFieldDefinitionType.SELECT]: CustomFieldDefinitionType.SELECT,\n [CustomFieldDefinitionType.STATUS]: CustomFieldDefinitionType.STATUS,\n} as const;\n\n/**\n * Validators for custom fields\n */\nexport const validators: Validators = {\n [CustomFieldDefinitionType.SELECT]: validateSelect as Validator<unknown, unknown>,\n [CustomFieldDefinitionType.STATUS]: validateStatus as Validator<unknown, unknown>,\n [CustomFieldDefinitionType.TEXT]: value => Joi.string().min(0).validate(value),\n [CustomFieldDefinitionType.NUMBER]: value => Joi.number().strict(true).validate(value),\n [CustomFieldDefinitionType.BOOLEAN]: value => Joi.boolean().strict().validate(value),\n [CustomFieldDefinitionType.DATE]: value => Joi.date().validate(value),\n [CustomFieldDefinitionType.DATETIME]: value => Joi.date().validate(value),\n [CustomFieldDefinitionType.IMAGE]: value => Joi.array().min(1).unique()\n .items(Joi.string().uri())\n .validate(value),\n [CustomFieldDefinitionType.FILE]: value => Joi.array().min(1).unique().items(Joi.object({\n name: Joi.string().required(),\n type: Joi.string(),\n size: Joi.string(),\n addedBy: Joi.string().uuid(),\n }))\n .validate(value),\n};\n"],"mappings":"6MAWA,MAAaA,EAAoH,EAC9HC,EAAAA,0BAA0B,QAASA,EAAAA,0BAA0B,QAC7DA,EAAAA,0BAA0B,QAASA,EAAAA,0BAA0B,OAC/D,CAKYC,EAAyB,EACnCD,EAAAA,0BAA0B,QAASE,EAAAA,gBACnCF,EAAAA,0BAA0B,QAASG,EAAAA,gBACnCH,EAAAA,0BAA0B,MAAO,GAASI,EAAAA,QAAI,QAAQ,CAAC,IAAI,EAAE,CAAC,SAAS,EAAM,EAC7EJ,EAAAA,0BAA0B,QAAS,GAASI,EAAAA,QAAI,QAAQ,CAAC,OAAO,GAAK,CAAC,SAAS,EAAM,EACrFJ,EAAAA,0BAA0B,SAAU,GAASI,EAAAA,QAAI,SAAS,CAAC,QAAQ,CAAC,SAAS,EAAM,EACnFJ,EAAAA,0BAA0B,MAAO,GAASI,EAAAA,QAAI,MAAM,CAAC,SAAS,EAAM,EACpEJ,EAAAA,0BAA0B,UAAW,GAASI,EAAAA,QAAI,MAAM,CAAC,SAAS,EAAM,EACxEJ,EAAAA,0BAA0B,OAAQ,GAASI,EAAAA,QAAI,OAAO,CAAC,IAAI,EAAE,CAAC,QAAQ,CACpE,MAAMA,EAAAA,QAAI,QAAQ,CAAC,KAAK,CAAC,CACzB,SAAS,EAAM,EACjBJ,EAAAA,0BAA0B,MAAO,GAASI,EAAAA,QAAI,OAAO,CAAC,IAAI,EAAE,CAAC,QAAQ,CAAC,MAAMA,EAAAA,QAAI,OAAO,CACtF,KAAMA,EAAAA,QAAI,QAAQ,CAAC,UAAU,CAC7B,KAAMA,EAAAA,QAAI,QAAQ,CAClB,KAAMA,EAAAA,QAAI,QAAQ,CAClB,QAASA,EAAAA,QAAI,QAAQ,CAAC,MAAM,CAC7B,CAAC,CAAC,CACA,SAAS,EAAM,CACnB"}
1
+ {"version":3,"file":"index.cjs","names":["CustomValidationTypes: Record<CustomValidationTypes, CustomFieldDefinitionType>","CustomFieldDefinitionType","validators: Validators","validateSelect","validateStatus","validateMultiSelectStatus","validateMultiSelectDropdown","Joi"],"sources":["../../../../src/utils/validations/validators/index.ts"],"sourcesContent":["import Joi from 'joi';\nimport { CustomFieldDefinitionType } from '../../constants';\nimport type { Validator, Validators } from '../type';\nimport { validateSelect } from './select.validator';\nimport { validateStatus } from './status.validator';\nimport { validateMultiSelectStatus } from './multi-select-status.validator';\nimport { validateMultiSelectDropdown } from './multi-select-dropdown.validator';\n\ntype CustomValidationTypes = Extract<CustomFieldDefinitionType, 'select' | 'status' | 'multi-select-status' | 'multi-select-dropdown'>;\n/**\n * Custom field types that must have custom validation.\n * TODO: remove this after moving to schema-based validation\n */\nexport const CustomValidationTypes: Record<CustomValidationTypes, CustomFieldDefinitionType> = {\n [CustomFieldDefinitionType.SELECT]: CustomFieldDefinitionType.SELECT,\n [CustomFieldDefinitionType.STATUS]: CustomFieldDefinitionType.STATUS,\n [CustomFieldDefinitionType.MULTI_SELECT_STATUS]: CustomFieldDefinitionType.MULTI_SELECT_STATUS,\n [CustomFieldDefinitionType.MULTI_SELECT_DROPDOWN]: CustomFieldDefinitionType.MULTI_SELECT_DROPDOWN,\n} as const;\n\n/**\n * Validators for custom fields\n */\nexport const validators: Validators = {\n [CustomFieldDefinitionType.SELECT]: validateSelect as Validator<unknown, unknown>,\n [CustomFieldDefinitionType.STATUS]: validateStatus as Validator<unknown, unknown>,\n [CustomFieldDefinitionType.MULTI_SELECT_STATUS]: validateMultiSelectStatus as Validator<unknown, unknown>,\n [CustomFieldDefinitionType.MULTI_SELECT_DROPDOWN]: validateMultiSelectDropdown as Validator<unknown, unknown>,\n [CustomFieldDefinitionType.TEXT]: value => Joi.string().min(0).validate(value),\n [CustomFieldDefinitionType.NUMBER]: value => Joi.number().strict(true).validate(value),\n [CustomFieldDefinitionType.BOOLEAN]: value => Joi.boolean().strict().validate(value),\n [CustomFieldDefinitionType.DATE]: value => Joi.date().validate(value),\n [CustomFieldDefinitionType.DATETIME]: value => Joi.date().validate(value),\n [CustomFieldDefinitionType.IMAGE]: value => Joi.array().min(1).unique()\n .items(Joi.string().uri())\n .validate(value),\n [CustomFieldDefinitionType.FILE]: value => Joi.array().min(1).unique().items(Joi.object({\n name: Joi.string().required(),\n type: Joi.string(),\n size: Joi.string(),\n addedBy: Joi.string().uuid(),\n }))\n .validate(value),\n};\n"],"mappings":"iTAaA,MAAaA,EAAkF,EAC5FC,EAAAA,0BAA0B,QAASA,EAAAA,0BAA0B,QAC7DA,EAAAA,0BAA0B,QAASA,EAAAA,0BAA0B,QAC7DA,EAAAA,0BAA0B,qBAAsBA,EAAAA,0BAA0B,qBAC1EA,EAAAA,0BAA0B,uBAAwBA,EAAAA,0BAA0B,sBAC9E,CAKYC,EAAyB,EACnCD,EAAAA,0BAA0B,QAASE,EAAAA,gBACnCF,EAAAA,0BAA0B,QAASG,EAAAA,gBACnCH,EAAAA,0BAA0B,qBAAsBI,EAAAA,2BAChDJ,EAAAA,0BAA0B,uBAAwBK,EAAAA,6BAClDL,EAAAA,0BAA0B,MAAO,GAASM,EAAAA,QAAI,QAAQ,CAAC,IAAI,EAAE,CAAC,SAAS,EAAM,EAC7EN,EAAAA,0BAA0B,QAAS,GAASM,EAAAA,QAAI,QAAQ,CAAC,OAAO,GAAK,CAAC,SAAS,EAAM,EACrFN,EAAAA,0BAA0B,SAAU,GAASM,EAAAA,QAAI,SAAS,CAAC,QAAQ,CAAC,SAAS,EAAM,EACnFN,EAAAA,0BAA0B,MAAO,GAASM,EAAAA,QAAI,MAAM,CAAC,SAAS,EAAM,EACpEN,EAAAA,0BAA0B,UAAW,GAASM,EAAAA,QAAI,MAAM,CAAC,SAAS,EAAM,EACxEN,EAAAA,0BAA0B,OAAQ,GAASM,EAAAA,QAAI,OAAO,CAAC,IAAI,EAAE,CAAC,QAAQ,CACpE,MAAMA,EAAAA,QAAI,QAAQ,CAAC,KAAK,CAAC,CACzB,SAAS,EAAM,EACjBN,EAAAA,0BAA0B,MAAO,GAASM,EAAAA,QAAI,OAAO,CAAC,IAAI,EAAE,CAAC,QAAQ,CAAC,MAAMA,EAAAA,QAAI,OAAO,CACtF,KAAMA,EAAAA,QAAI,QAAQ,CAAC,UAAU,CAC7B,KAAMA,EAAAA,QAAI,QAAQ,CAClB,KAAMA,EAAAA,QAAI,QAAQ,CAClB,QAASA,EAAAA,QAAI,QAAQ,CAAC,MAAM,CAC7B,CAAC,CAAC,CACA,SAAS,EAAM,CACnB"}
@@ -1,2 +1,2 @@
1
- import{CustomFieldDefinitionType as e}from"../../constants/index.js";import{validateSelect as t}from"./select.validator.js";import{validateStatus as n}from"./status.validator.js";import r from"joi";const i={[e.SELECT]:e.SELECT,[e.STATUS]:e.STATUS},a={[e.SELECT]:t,[e.STATUS]:n,[e.TEXT]:e=>r.string().min(0).validate(e),[e.NUMBER]:e=>r.number().strict(!0).validate(e),[e.BOOLEAN]:e=>r.boolean().strict().validate(e),[e.DATE]:e=>r.date().validate(e),[e.DATETIME]:e=>r.date().validate(e),[e.IMAGE]:e=>r.array().min(1).unique().items(r.string().uri()).validate(e),[e.FILE]:e=>r.array().min(1).unique().items(r.object({name:r.string().required(),type:r.string(),size:r.string(),addedBy:r.string().uuid()})).validate(e)};export{i as CustomValidationTypes,a as validators};
1
+ import{CustomFieldDefinitionType as e}from"../../constants/index.js";import{validateSelect as t}from"./select.validator.js";import{validateStatus as n}from"./status.validator.js";import{validateMultiSelectStatus as r}from"./multi-select-status.validator.js";import{validateMultiSelectDropdown as i}from"./multi-select-dropdown.validator.js";import a from"joi";const o={[e.SELECT]:e.SELECT,[e.STATUS]:e.STATUS,[e.MULTI_SELECT_STATUS]:e.MULTI_SELECT_STATUS,[e.MULTI_SELECT_DROPDOWN]:e.MULTI_SELECT_DROPDOWN},s={[e.SELECT]:t,[e.STATUS]:n,[e.MULTI_SELECT_STATUS]:r,[e.MULTI_SELECT_DROPDOWN]:i,[e.TEXT]:e=>a.string().min(0).validate(e),[e.NUMBER]:e=>a.number().strict(!0).validate(e),[e.BOOLEAN]:e=>a.boolean().strict().validate(e),[e.DATE]:e=>a.date().validate(e),[e.DATETIME]:e=>a.date().validate(e),[e.IMAGE]:e=>a.array().min(1).unique().items(a.string().uri()).validate(e),[e.FILE]:e=>a.array().min(1).unique().items(a.object({name:a.string().required(),type:a.string(),size:a.string(),addedBy:a.string().uuid()})).validate(e)};export{o as CustomValidationTypes,s as validators};
2
2
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["CustomValidationTypes: Record<Extract<CustomFieldDefinitionType, 'select' | 'status'>, CustomFieldDefinitionType>","validators: Validators"],"sources":["../../../../src/utils/validations/validators/index.ts"],"sourcesContent":["import Joi from 'joi';\nimport { CustomFieldDefinitionType } from '../../constants';\nimport type { Validator, Validators } from '../type';\nimport { validateSelect } from './select.validator';\nimport { validateStatus } from './status.validator';\n\ntype CustomValidationTypes = Extract<CustomFieldDefinitionType, 'select' | 'status'>;\n/**\n * Custom field types that must have custom validation.\n * TODO: remove this after moving to schema-based validation\n */\nexport const CustomValidationTypes: Record<Extract<CustomFieldDefinitionType, 'select' | 'status'>, CustomFieldDefinitionType> = {\n [CustomFieldDefinitionType.SELECT]: CustomFieldDefinitionType.SELECT,\n [CustomFieldDefinitionType.STATUS]: CustomFieldDefinitionType.STATUS,\n} as const;\n\n/**\n * Validators for custom fields\n */\nexport const validators: Validators = {\n [CustomFieldDefinitionType.SELECT]: validateSelect as Validator<unknown, unknown>,\n [CustomFieldDefinitionType.STATUS]: validateStatus as Validator<unknown, unknown>,\n [CustomFieldDefinitionType.TEXT]: value => Joi.string().min(0).validate(value),\n [CustomFieldDefinitionType.NUMBER]: value => Joi.number().strict(true).validate(value),\n [CustomFieldDefinitionType.BOOLEAN]: value => Joi.boolean().strict().validate(value),\n [CustomFieldDefinitionType.DATE]: value => Joi.date().validate(value),\n [CustomFieldDefinitionType.DATETIME]: value => Joi.date().validate(value),\n [CustomFieldDefinitionType.IMAGE]: value => Joi.array().min(1).unique()\n .items(Joi.string().uri())\n .validate(value),\n [CustomFieldDefinitionType.FILE]: value => Joi.array().min(1).unique().items(Joi.object({\n name: Joi.string().required(),\n type: Joi.string(),\n size: Joi.string(),\n addedBy: Joi.string().uuid(),\n }))\n .validate(value),\n};\n"],"mappings":"sMAWA,MAAaA,EAAoH,EAC9H,EAA0B,QAAS,EAA0B,QAC7D,EAA0B,QAAS,EAA0B,OAC/D,CAKYC,EAAyB,EACnC,EAA0B,QAAS,GACnC,EAA0B,QAAS,GACnC,EAA0B,MAAO,GAAS,EAAI,QAAQ,CAAC,IAAI,EAAE,CAAC,SAAS,EAAM,EAC7E,EAA0B,QAAS,GAAS,EAAI,QAAQ,CAAC,OAAO,GAAK,CAAC,SAAS,EAAM,EACrF,EAA0B,SAAU,GAAS,EAAI,SAAS,CAAC,QAAQ,CAAC,SAAS,EAAM,EACnF,EAA0B,MAAO,GAAS,EAAI,MAAM,CAAC,SAAS,EAAM,EACpE,EAA0B,UAAW,GAAS,EAAI,MAAM,CAAC,SAAS,EAAM,EACxE,EAA0B,OAAQ,GAAS,EAAI,OAAO,CAAC,IAAI,EAAE,CAAC,QAAQ,CACpE,MAAM,EAAI,QAAQ,CAAC,KAAK,CAAC,CACzB,SAAS,EAAM,EACjB,EAA0B,MAAO,GAAS,EAAI,OAAO,CAAC,IAAI,EAAE,CAAC,QAAQ,CAAC,MAAM,EAAI,OAAO,CACtF,KAAM,EAAI,QAAQ,CAAC,UAAU,CAC7B,KAAM,EAAI,QAAQ,CAClB,KAAM,EAAI,QAAQ,CAClB,QAAS,EAAI,QAAQ,CAAC,MAAM,CAC7B,CAAC,CAAC,CACA,SAAS,EAAM,CACnB"}
1
+ {"version":3,"file":"index.js","names":["CustomValidationTypes: Record<CustomValidationTypes, CustomFieldDefinitionType>","validators: Validators"],"sources":["../../../../src/utils/validations/validators/index.ts"],"sourcesContent":["import Joi from 'joi';\nimport { CustomFieldDefinitionType } from '../../constants';\nimport type { Validator, Validators } from '../type';\nimport { validateSelect } from './select.validator';\nimport { validateStatus } from './status.validator';\nimport { validateMultiSelectStatus } from './multi-select-status.validator';\nimport { validateMultiSelectDropdown } from './multi-select-dropdown.validator';\n\ntype CustomValidationTypes = Extract<CustomFieldDefinitionType, 'select' | 'status' | 'multi-select-status' | 'multi-select-dropdown'>;\n/**\n * Custom field types that must have custom validation.\n * TODO: remove this after moving to schema-based validation\n */\nexport const CustomValidationTypes: Record<CustomValidationTypes, CustomFieldDefinitionType> = {\n [CustomFieldDefinitionType.SELECT]: CustomFieldDefinitionType.SELECT,\n [CustomFieldDefinitionType.STATUS]: CustomFieldDefinitionType.STATUS,\n [CustomFieldDefinitionType.MULTI_SELECT_STATUS]: CustomFieldDefinitionType.MULTI_SELECT_STATUS,\n [CustomFieldDefinitionType.MULTI_SELECT_DROPDOWN]: CustomFieldDefinitionType.MULTI_SELECT_DROPDOWN,\n} as const;\n\n/**\n * Validators for custom fields\n */\nexport const validators: Validators = {\n [CustomFieldDefinitionType.SELECT]: validateSelect as Validator<unknown, unknown>,\n [CustomFieldDefinitionType.STATUS]: validateStatus as Validator<unknown, unknown>,\n [CustomFieldDefinitionType.MULTI_SELECT_STATUS]: validateMultiSelectStatus as Validator<unknown, unknown>,\n [CustomFieldDefinitionType.MULTI_SELECT_DROPDOWN]: validateMultiSelectDropdown as Validator<unknown, unknown>,\n [CustomFieldDefinitionType.TEXT]: value => Joi.string().min(0).validate(value),\n [CustomFieldDefinitionType.NUMBER]: value => Joi.number().strict(true).validate(value),\n [CustomFieldDefinitionType.BOOLEAN]: value => Joi.boolean().strict().validate(value),\n [CustomFieldDefinitionType.DATE]: value => Joi.date().validate(value),\n [CustomFieldDefinitionType.DATETIME]: value => Joi.date().validate(value),\n [CustomFieldDefinitionType.IMAGE]: value => Joi.array().min(1).unique()\n .items(Joi.string().uri())\n .validate(value),\n [CustomFieldDefinitionType.FILE]: value => Joi.array().min(1).unique().items(Joi.object({\n name: Joi.string().required(),\n type: Joi.string(),\n size: Joi.string(),\n addedBy: Joi.string().uuid(),\n }))\n .validate(value),\n};\n"],"mappings":"wWAaA,MAAaA,EAAkF,EAC5F,EAA0B,QAAS,EAA0B,QAC7D,EAA0B,QAAS,EAA0B,QAC7D,EAA0B,qBAAsB,EAA0B,qBAC1E,EAA0B,uBAAwB,EAA0B,sBAC9E,CAKYC,EAAyB,EACnC,EAA0B,QAAS,GACnC,EAA0B,QAAS,GACnC,EAA0B,qBAAsB,GAChD,EAA0B,uBAAwB,GAClD,EAA0B,MAAO,GAAS,EAAI,QAAQ,CAAC,IAAI,EAAE,CAAC,SAAS,EAAM,EAC7E,EAA0B,QAAS,GAAS,EAAI,QAAQ,CAAC,OAAO,GAAK,CAAC,SAAS,EAAM,EACrF,EAA0B,SAAU,GAAS,EAAI,SAAS,CAAC,QAAQ,CAAC,SAAS,EAAM,EACnF,EAA0B,MAAO,GAAS,EAAI,MAAM,CAAC,SAAS,EAAM,EACpE,EAA0B,UAAW,GAAS,EAAI,MAAM,CAAC,SAAS,EAAM,EACxE,EAA0B,OAAQ,GAAS,EAAI,OAAO,CAAC,IAAI,EAAE,CAAC,QAAQ,CACpE,MAAM,EAAI,QAAQ,CAAC,KAAK,CAAC,CACzB,SAAS,EAAM,EACjB,EAA0B,MAAO,GAAS,EAAI,OAAO,CAAC,IAAI,EAAE,CAAC,QAAQ,CAAC,MAAM,EAAI,OAAO,CACtF,KAAM,EAAI,QAAQ,CAAC,UAAU,CAC7B,KAAM,EAAI,QAAQ,CAClB,KAAM,EAAI,QAAQ,CAClB,QAAS,EAAI,QAAQ,CAAC,MAAM,CAC7B,CAAC,CAAC,CACA,SAAS,EAAM,CACnB"}
@@ -0,0 +1,2 @@
1
+ const e=require(`./multi-select.helpers.cjs`),t=(t,n)=>e.validateMultiSelect(t,n??[]);exports.validateMultiSelectDropdown=t;
2
+ //# sourceMappingURL=multi-select-dropdown.validator.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"multi-select-dropdown.validator.cjs","names":["validateMultiSelectDropdown: Validator<string[], string[]>","validateMultiSelect"],"sources":["../../../../src/utils/validations/validators/multi-select-dropdown.validator.ts"],"sourcesContent":["import type { Validator } from '../type';\nimport { validateMultiSelect } from './multi-select.helpers';\n\nexport const validateMultiSelectDropdown: Validator<string[], string[]> = (value, options) =>\n validateMultiSelect(value, options ?? []);\n"],"mappings":"8CAGaA,GAA8D,EAAO,IAChFC,EAAAA,oBAAoB,EAAO,GAAW,EAAE,CAAC"}
@@ -0,0 +1,2 @@
1
+ import{validateMultiSelect as e}from"./multi-select.helpers.js";const t=(t,n)=>e(t,n??[]);export{t as validateMultiSelectDropdown};
2
+ //# sourceMappingURL=multi-select-dropdown.validator.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"multi-select-dropdown.validator.js","names":["validateMultiSelectDropdown: Validator<string[], string[]>"],"sources":["../../../../src/utils/validations/validators/multi-select-dropdown.validator.ts"],"sourcesContent":["import type { Validator } from '../type';\nimport { validateMultiSelect } from './multi-select.helpers';\n\nexport const validateMultiSelectDropdown: Validator<string[], string[]> = (value, options) =>\n validateMultiSelect(value, options ?? []);\n"],"mappings":"gEAGA,MAAaA,GAA8D,EAAO,IAChF,EAAoB,EAAO,GAAW,EAAE,CAAC"}
@@ -0,0 +1,2 @@
1
+ const e=require(`./multi-select.helpers.cjs`),t=(t,n)=>e.validateMultiSelect(t,(n??[]).map(e=>e.value));exports.validateMultiSelectStatus=t;
2
+ //# sourceMappingURL=multi-select-status.validator.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"multi-select-status.validator.cjs","names":["validateMultiSelectStatus: Validator<string[], StatusOption[]>","validateMultiSelect"],"sources":["../../../../src/utils/validations/validators/multi-select-status.validator.ts"],"sourcesContent":["import type { Validator } from '../type';\nimport type { StatusOption } from './status.validator';\nimport { validateMultiSelect } from './multi-select.helpers';\n\n/**\n * Validate that the value is an array containing only the allowed multi-select values\n */\nexport const validateMultiSelectStatus: Validator<string[], StatusOption[]> = (value, multiSelectOptions) =>\n validateMultiSelect(value, (multiSelectOptions ?? []).map(option => option.value));\n"],"mappings":"8CAOaA,GAAkE,EAAO,IACpFC,EAAAA,oBAAoB,GAAQ,GAAsB,EAAE,EAAE,IAAI,GAAU,EAAO,MAAM,CAAC"}