@autofleet/shtinker 3.5.1 → 3.6.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.
@@ -0,0 +1,2 @@
1
+ import{isDeepStrictEqual as e}from"node:util";import{getCurrentPayload as t,getUser as n,outbreak as r}from"@autofleet/zehut";import i from"@autofleet/logger";import a from"@autofleet/network";let o=function(e){return e.CREATE=`create`,e.BULK_CREATE=`bulk-create`,e.BULK_EDIT=`bulk-edit`,e.DELETE=`delete`,e.UPDATE=`update`,e.CANCEL=`cancel`,e.FAIL=`fail`,e.UNASSIGN=`unassign`,e.BULK_ASSIGN=`bulk-assign`,e.REASSIGN=`reassign`,e.DISPATCH=`dispatch`,e.BULK_DISPATCH=`bulk-dispatch`,e.BULK_UPSERT=`bulk-upsert`,e.UPSERT=`upsert`,e.JOIN=`join`,e.MOVE=`move`,e.REOPTIMIZATION=`reoptimization`,e}({}),s=function(e){return e.RIDE=`Ride`,e.VEHICLE=`Vehicle`,e.DRIVER=`Driver`,e.PRICE_CALCULATION=`PriceCalculation`,e}({}),c=function(e){return e.USER=`user`,e.AUTOMATION=`automation`,e}({});const l=`audit-log-context`,u=`audit-log-rows`,d=`auditLogContext`,f=`x-af-automation-id`,p=i();p.addContextMiddleware(()=>({traceId:r.getCurrentContextTraceId()}));var m=p;const h=`customFields`,g=()=>{let e=t();return e?.nonHeaderContext?.get(d)},_={[o.BULK_CREATE]:o.BULK_CREATE,[o.BULK_EDIT]:o.BULK_EDIT,[o.BULK_ASSIGN]:o.BULK_ASSIGN,[o.BULK_DISPATCH]:o.BULK_DISPATCH,[o.BULK_UPSERT]:o.BULK_UPSERT},v=e=>[null,void 0].includes(e)?!0:Array.isArray(e)?e.length===0:typeof e==`object`&&!(e instanceof Date)?Object.keys(e).length===0:!1,y=e=>!Object.hasOwn(_,e),b=(e,t)=>e.filter(e=>!v(t.get(e))||!v(t.previous(e))),x=(e,t)=>{let n=t.returning?t.fields:e.changed()||[],r=b(n.filter(e=>e!==h),e);return r.map(t=>({property:t,previousValue:e.previous(t),newValue:e.get(t)}))},S=t=>{let n=t.changed(),r=n&&n.includes(h);if(!r)return[];let i=t.get(h),a=t.previous(h),o=Object.keys(i).filter(t=>{let n=i?.[t],r=a?.[t];return(!v(n)||!v(r))&&!e(n,r)});return o.map(e=>({property:`${h}.${e}`,previousValue:a?.[e],newValue:i?.[e]}))};var C=class{rabbit;sequelize;logger;excludeModels;waitForTransactionCommit;constructor(e){this.rabbit=e.rabbit,this.sequelize=e.sequelize,this.logger=e.logger||m,this.excludeModels=e.excludeModels??[],this.waitForTransactionCommit=e.waitForTransactionCommit??!1}async manualSendAuditLog({auditContext:e,...t},n=this.logAndThrowError){if(e??=g(),e)try{e?.entityType?.toLowerCase()===t.entityType?.toLowerCase()&&y(e.action)&&(e.entityId=t.entityId),await this.rabbit.sendToQueue(u,t)}catch(e){n(e,t)}}registerHooks(){Object.entries(this.sequelize.models).forEach(([e,t])=>{this.excludeModels.includes(e)||t.addHook(`afterSave`,async(t,n)=>{let r=async()=>{let r=g();if(!r)return;let{id:i}=t;await this.manualSendAuditLog({entityId:i,auditContext:r,entityType:e,rows:[...x(t,n),...S(t)]},this.logError)};if(this.waitForTransactionCommit&&n.transaction){n.transaction.afterCommit(r);return}await r()})})}async sendAuditLogContext(e){try{await this.rabbit.sendToQueue(l,e)}catch(e){this.logger.error(`Failed to send audit log context`,e)}}logError=(e,t)=>{let{entityType:n,entityId:r}=t;this.logger.error(`Failed to send audit log rows`,{entityType:n,entityId:r,error:e})};logAndThrowError=(e,t)=>{throw this.logError(e,t),e}},w=C;const T=new a({serviceName:`AUDIT_MS`,timeout:6e4,logger:m}),E=async e=>{let{data:t}=await T.get(`api/v1/audit-logs/${e}`);return t},D={getByEntityId:E};var O=D;let k;const A=e=>process.env.DISABLE_AUDIT_LOGS===`true`?!1:(k=new w(e),k.registerHooks(),k),j=({action:e,endpoint:n,entityType:r,method:i,automationId:a,userId:o})=>{let s=o||(a??null),l=o&&c.USER||a&&c.AUTOMATION||null,u={entityType:r,action:e,endpoint:n,method:i,performedBy:s,actionOrigin:l},f=t();return f.nonHeaderContext.set(d,u),u},M=async(e,t,r,i)=>{try{if(process.env.DISABLE_AUDIT_LOGS===`true`||!k)return;let a=j({action:i,endpoint:e.url,entityType:r,method:e.method,userId:n()?.id,automationId:e.headers[f]});if(!y(i)){await k.sendAuditLogContext(a);return}let o=async()=>{t.off(`finish`,o),t.off(`close`,o),t.off(`error`,o),await k?.sendAuditLogContext(a)};t.once(`finish`,o),t.once(`close`,o),t.once(`error`,o)}catch(e){m.error(`couldn't set audit context`,e)}},N=(e,t)=>async(n,{userId:r,automationId:i})=>{if(process.env.DISABLE_AUDIT_LOGS===`true`||!k)return;let a=j({action:t,endpoint:n,entityType:e,method:`rabbit`,userId:r,automationId:i});await k.sendAuditLogContext(a)};export{d as AUDIT_LOG_CONTEXT_KEY,l as AUDIT_LOG_CONTEXT_QUEUE,u as AUDIT_LOG_ROWS_QUEUE,f as AUTOMATION_ID_HEADER,o as Action,c as ActionOrigin,s as EntityType,w as audit_logger_default,O as audit_ms_default,A as innerEnableAuditing,M as innerSetAuditContext,N as setRabbitAuditContext};
2
+ //# sourceMappingURL=common-CWEG3Eik.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"common-CWEG3Eik.js","names":["logger: LoggerInstanceManager","getCurrentTrace","changedFields: string[]","logger","exportObj: { getByEntityId: typeof getByEntityId; }","auditLogger: AuditLogger | undefined","AuditLogger","auditLogContext: AuditLogContext"],"sources":["../src/types.ts","../src/const.ts","../src/logger.ts","../src/audit-logger.ts","../src/audit-ms.ts","../src/common.ts"],"sourcesContent":["import type { ModelStatic, Model } from 'sequelize';\nimport type { Sequelize } from 'sequelize-typescript';\nimport type RabbitMq from '@autofleet/rabbit';\nimport type { LoggerInstanceManager } from '@autofleet/logger';\nimport type { IRouter } from 'express';\nimport type { FastifyInstance } from 'fastify';\n\nexport interface AuditLoggerOptions {\n rabbit: RabbitMq;\n sequelize: Sequelize;\n logger: LoggerInstanceManager;\n router?: IRouter;\n fastify?: FastifyInstance;\n excludeModels?: string[];\n entityScopedModelMap?: Record<string, ModelStatic<Model>>;\n /**\n * If true and the model was changed inside a transaction, the audit log will be sent only after the transaction is committed.\n * This is useful because sequelize afterSave hook doesn't include the previous values if the model was changed inside a transaction.\n * @default false\n */\n waitForTransactionCommit?: boolean;\n}\n\nexport interface AuditLogContext {\n entityType: string;\n entityId?: string;\n action: string;\n performedBy: string | null;\n endpoint: string;\n method: string;\n actionOrigin?: string | null;\n}\n\nexport interface AuditLogRow {\n property: string;\n previousValue: unknown;\n newValue: unknown;\n}\n\nexport interface AuditLogPayload {\n entityType: string;\n entityId: string;\n rows: readonly AuditLogRow[];\n}\n\nexport enum Action {\n CREATE = 'create',\n BULK_CREATE = 'bulk-create',\n BULK_EDIT = 'bulk-edit',\n DELETE = 'delete',\n UPDATE = 'update',\n CANCEL = 'cancel',\n FAIL = 'fail',\n UNASSIGN = 'unassign',\n BULK_ASSIGN = 'bulk-assign',\n REASSIGN = 'reassign',\n DISPATCH = 'dispatch',\n BULK_DISPATCH = 'bulk-dispatch',\n BULK_UPSERT = 'bulk-upsert',\n UPSERT = 'upsert',\n JOIN = 'join',\n MOVE = 'move',\n REOPTIMIZATION = 'reoptimization',\n}\n\nexport enum EntityType {\n RIDE = 'Ride',\n VEHICLE = 'Vehicle',\n DRIVER = 'Driver',\n PRICE_CALCULATION = 'PriceCalculation',\n}\n\nexport const enum ActionOrigin {\n USER = 'user',\n AUTOMATION = 'automation',\n}\n","export const AUDIT_LOG_CONTEXT_QUEUE = 'audit-log-context';\nexport const AUDIT_LOG_ROWS_QUEUE = 'audit-log-rows';\nexport const AUDIT_LOG_CONTEXT_KEY = 'auditLogContext';\nexport const AUTOMATION_ID_HEADER = 'x-af-automation-id';\n","import { outbreak } from '@autofleet/zehut';\nimport Logger, { type LoggerInstanceManager } from '@autofleet/logger';\n\nconst logger: LoggerInstanceManager = Logger();\nlogger.addContextMiddleware(() => ({ traceId: outbreak.getCurrentContextTraceId() }));\nexport default logger;\n","import { isDeepStrictEqual } from 'node:util';\nimport type RabbitMq from '@autofleet/rabbit';\nimport type { LoggerInstanceManager } from '@autofleet/logger';\nimport { getCurrentPayload as getCurrentTrace } from '@autofleet/zehut';\nimport type {\n CreateOptions, InstanceUpdateOptions, Model, Sequelize,\n} from 'sequelize';\nimport {\n type AuditLogPayload, type AuditLoggerOptions, type AuditLogContext, Action, type AuditLogRow,\n} from './types';\nimport { AUDIT_LOG_CONTEXT_QUEUE, AUDIT_LOG_ROWS_QUEUE, AUDIT_LOG_CONTEXT_KEY } from './const';\nimport logger from './logger';\n\nconst CUSTOM_FIELDS_PROPERTY = 'customFields';\n\nconst getAuditContext = () => {\n const currentTrace = getCurrentTrace();\n return currentTrace?.nonHeaderContext?.get(AUDIT_LOG_CONTEXT_KEY) as AuditLogContext | undefined;\n};\n\nconst ACTIONS_TO_OMIT_ENTITY_ID_FROM_CONTEXT = {\n [Action.BULK_CREATE]: Action.BULK_CREATE,\n [Action.BULK_EDIT]: Action.BULK_EDIT,\n [Action.BULK_ASSIGN]: Action.BULK_ASSIGN,\n [Action.BULK_DISPATCH]: Action.BULK_DISPATCH,\n [Action.BULK_UPSERT]: Action.BULK_UPSERT,\n};\n\nconst isEmpty = (field: unknown): boolean => {\n if ([null, undefined].includes(field as undefined)) {\n return true;\n }\n if (Array.isArray(field)) {\n return field.length === 0;\n }\n if (typeof field === 'object' && !(field instanceof Date)) {\n return Object.keys(field as Record<string, unknown>).length === 0;\n }\n return false;\n};\n\nexport const isEntityIdRequired = (action: string): boolean => !Object.hasOwn(ACTIONS_TO_OMIT_ENTITY_ID_FROM_CONTEXT, action);\n\nconst filterOutEmptyFields = (fields: string[], instance: Model) => fields.filter(field => !isEmpty(instance.get(field)) || !isEmpty(instance.previous(field)));\n\nconst getChangedFieldsRows = (instance: Model, options: CreateOptions | InstanceUpdateOptions): AuditLogRow[] => {\n // When bulk updating in sequelize using the \"returning\" option, the instance.changed() stops working.\n // It's a known issue with sequelize.\n const changedFields: string[] = options.returning ? options.fields as string[] : (instance.changed() || []);\n // Filter customFields - we'll handle them later\n const filteredChangedFields = filterOutEmptyFields(changedFields.filter(field => field !== CUSTOM_FIELDS_PROPERTY), instance);\n return filteredChangedFields.map(property => ({\n property,\n previousValue: instance.previous(property),\n newValue: instance.get(property),\n }));\n};\n\nconst getChangedCustomFieldsRows = (instance: Model): AuditLogRow[] => {\n // Based on the comment in getChangedFieldsRows, we cannot rely on instance.changed() when doing bulk updates with \"returning\".\n // So this seems like a possible bug.\n const changed = instance.changed();\n const customFieldsChanged = changed && changed.includes(CUSTOM_FIELDS_PROPERTY);\n if (!customFieldsChanged) {\n return [];\n }\n\n const customFields = instance.get(CUSTOM_FIELDS_PROPERTY) as Record<string, unknown>;\n const previousCustomFields = instance.previous(CUSTOM_FIELDS_PROPERTY);\n const changedCustomFields = Object.keys(customFields).filter((field) => {\n const newValue = customFields?.[field];\n const oldValue = previousCustomFields?.[field];\n return (!isEmpty(newValue) || !isEmpty(oldValue)) && !isDeepStrictEqual(newValue, oldValue);\n });\n return changedCustomFields.map(changedCustomField => ({\n property: `${CUSTOM_FIELDS_PROPERTY}.${changedCustomField}`,\n previousValue: previousCustomFields?.[changedCustomField],\n newValue: customFields?.[changedCustomField],\n }));\n};\n\ninterface AuditLogSendData extends AuditLogPayload {\n auditContext?: AuditLogContext;\n}\n\ntype AuditLogRowSendingErrorHandler = (error: unknown, payload: AuditLogPayload) => void;\n\nclass AuditLogger {\n private readonly rabbit: RabbitMq;\n private readonly sequelize: Sequelize;\n private readonly logger: LoggerInstanceManager;\n private readonly excludeModels: string[];\n private readonly waitForTransactionCommit: boolean;\n\n constructor(options: AuditLoggerOptions) {\n this.rabbit = options.rabbit;\n this.sequelize = options.sequelize;\n this.logger = options.logger || logger;\n this.excludeModels = options.excludeModels ?? [];\n this.waitForTransactionCommit = options.waitForTransactionCommit ?? false;\n }\n\n public async manualSendAuditLog(\n { auditContext, ...payload }: AuditLogSendData,\n errorHandler: AuditLogRowSendingErrorHandler = this.logAndThrowError,\n ): Promise<void> {\n auditContext ??= getAuditContext();\n if (!auditContext) {\n return;\n }\n try {\n // Make sure the current entity being changed it the \"main\" entity in the current audit context, and if so mark it as the \"entityId\".\n if (auditContext?.entityType?.toLowerCase() === payload.entityType?.toLowerCase() && isEntityIdRequired(auditContext.action)) {\n auditContext.entityId = payload.entityId;\n }\n await this.rabbit.sendToQueue(AUDIT_LOG_ROWS_QUEUE, payload);\n } catch (error) {\n errorHandler(error, payload);\n }\n }\n\n public registerHooks(): void {\n Object.entries(this.sequelize.models).forEach(([modelName, modelType]) => {\n if (this.excludeModels.includes(modelName)) {\n return;\n }\n modelType.addHook('afterSave', async (instance, options) => {\n const sendAuditLogForModel = async () => {\n const auditContext = getAuditContext();\n if (!auditContext) return;\n\n const { id: entityId } = instance as unknown as { id: string; };\n await this.manualSendAuditLog(\n {\n entityId,\n auditContext,\n entityType: modelName,\n rows: [...getChangedFieldsRows(instance, options), ...getChangedCustomFieldsRows(instance)],\n },\n this.logError,\n );\n };\n /*\n By default sequelize doesn't keep the previous values when using a transaction\n So we want to be able to call this function after the transaction is committed\n to be able to get the previous values\n */\n if (this.waitForTransactionCommit && options.transaction) {\n options.transaction.afterCommit(sendAuditLogForModel);\n return;\n }\n await sendAuditLogForModel();\n });\n });\n }\n\n public async sendAuditLogContext(context: AuditLogContext): Promise<void> {\n try {\n await this.rabbit.sendToQueue(AUDIT_LOG_CONTEXT_QUEUE, context);\n } catch (err) {\n this.logger.error('Failed to send audit log context', err);\n }\n }\n\n private logError: AuditLogRowSendingErrorHandler = (error: unknown, payload: AuditLogPayload) => {\n const { entityType, entityId } = payload;\n this.logger.error('Failed to send audit log rows', { entityType, entityId, error });\n };\n\n private logAndThrowError: AuditLogRowSendingErrorHandler = (error: unknown, payload: AuditLogPayload): never => {\n this.logError(error, payload);\n throw error;\n };\n}\n\nexport default AuditLogger;\n","import Network from '@autofleet/network';\nimport logger from './logger';\n\nconst auditMs = new Network({ serviceName: 'AUDIT_MS', timeout: 60_000, logger });\n\nconst getByEntityId = async (entityId: string): Promise<any> => {\n const { data } = await auditMs.get(`api/v1/audit-logs/${entityId}`);\n return data;\n};\n\nconst exportObj: { getByEntityId: typeof getByEntityId; } = { getByEntityId };\n\nexport default exportObj;\n","import type { Writable } from 'node:stream';\nimport type { IncomingHttpHeaders } from 'node:http';\nimport { getCurrentPayload, getUser } from '@autofleet/zehut';\nimport logger from './logger';\nimport AuditLogger, { isEntityIdRequired } from './audit-logger';\nimport { AUDIT_LOG_CONTEXT_KEY, AUTOMATION_ID_HEADER } from './const';\nimport { ActionOrigin, type AuditLogContext, type AuditLoggerOptions } from './types';\n\nlet auditLogger: AuditLogger | undefined;\n\nexport const innerEnableAuditing = (options: AuditLoggerOptions): false | AuditLogger => {\n if (process.env.DISABLE_AUDIT_LOGS === 'true') {\n return false;\n }\n auditLogger = new AuditLogger(options);\n auditLogger.registerHooks();\n return auditLogger;\n};\n\ninterface GetAuditLogContextParams {\n action: string;\n endpoint: string;\n entityType: string;\n method: string;\n automationId?: string;\n userId?: string;\n}\nconst getAuditLogContextAndSetToContext = ({\n action, endpoint, entityType, method, automationId, userId,\n}: GetAuditLogContextParams): AuditLogContext => {\n const performedBy = userId || (automationId ?? null);\n const actionOrigin = (userId && ActionOrigin.USER) || (automationId && ActionOrigin.AUTOMATION) || null;\n\n const auditLogContext: AuditLogContext = {\n entityType,\n action,\n endpoint,\n method,\n performedBy,\n actionOrigin,\n };\n const currentTrace = getCurrentPayload();\n currentTrace.nonHeaderContext.set(AUDIT_LOG_CONTEXT_KEY, auditLogContext);\n\n return auditLogContext;\n};\n\ninterface PartialRequest {\n url: string;\n method: string;\n headers: IncomingHttpHeaders;\n}\n\nexport const innerSetAuditContext = async (req: PartialRequest, res: Writable, entityType: string, action: string): Promise<void> => {\n try {\n if (process.env.DISABLE_AUDIT_LOGS === 'true' || !auditLogger) {\n return;\n }\n const auditLogContext = getAuditLogContextAndSetToContext({\n action,\n endpoint: req.url,\n entityType,\n method: req.method,\n userId: getUser()?.id,\n automationId: req.headers[AUTOMATION_ID_HEADER] as string | undefined,\n });\n\n if (!isEntityIdRequired(action)) { // if it's a bulk action, we don't want to wait for the response to add the entity id\n await auditLogger.sendAuditLogContext(auditLogContext);\n return;\n }\n\n const sendAuditLogContextEvent = async () => {\n res.off('finish', sendAuditLogContextEvent);\n res.off('close', sendAuditLogContextEvent);\n res.off('error', sendAuditLogContextEvent);\n await auditLogger?.sendAuditLogContext(auditLogContext);\n };\n res.once('finish', sendAuditLogContextEvent);\n res.once('close', sendAuditLogContextEvent);\n res.once('error', sendAuditLogContextEvent);\n } catch (err) {\n logger.error('couldn\\'t set audit context', err);\n }\n};\n\nexport const setRabbitAuditContext = (entityType: string, action: string) => async (endpoint: string, { userId, automationId }: { userId: string; automationId: string; }): Promise<void> => {\n if (process.env.DISABLE_AUDIT_LOGS === 'true' || !auditLogger) {\n return;\n }\n const auditLogContext = getAuditLogContextAndSetToContext({\n action,\n endpoint,\n entityType,\n method: 'rabbit',\n userId,\n automationId,\n });\n\n await auditLogger.sendAuditLogContext(auditLogContext);\n};\n"],"mappings":"iMA6CA,IAAY,EAAA,SAAA,EAAL,OACL,GAAA,OAAA,SACA,EAAA,YAAA,cACA,EAAA,UAAA,YACA,EAAA,OAAA,SACA,EAAA,OAAA,SACA,EAAA,OAAA,SACA,EAAA,KAAA,OACA,EAAA,SAAA,WACA,EAAA,YAAA,cACA,EAAA,SAAA,WACA,EAAA,SAAA,WACA,EAAA,cAAA,gBACA,EAAA,YAAA,cACA,EAAA,OAAA,SACA,EAAA,KAAA,OACA,EAAA,KAAA,OACA,EAAA,eAAA,wBAGU,EAAA,SAAA,EAAL,OACL,GAAA,KAAA,OACA,EAAA,QAAA,UACA,EAAA,OAAA,SACA,EAAA,kBAAA,0BAGgB,EAAA,SAAA,EAAX,OACL,GAAA,KAAA,OACA,EAAA,WAAA,o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,CAAE,SAAQ,kBAA6E,CAC3L,GAAI,QAAQ,IAAI,qBAAuB,QAAU,CAAC,EAChD,OAEF,IAAM,EAAkB,EAAkC,CACxD,SACA,WACA,aACA,OAAQ,SACR,SACA,iBAGF,MAAM,EAAY,oBAAoB"}
@@ -0,0 +1,2 @@
1
+ var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,a)=>(a=n==null?{}:e(i(n)),o(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));const c=s(require(`node:util`)),l=s(require(`@autofleet/zehut`)),u=s(require(`@autofleet/logger`)),d=s(require(`@autofleet/network`));let f=function(e){return e.CREATE=`create`,e.BULK_CREATE=`bulk-create`,e.BULK_EDIT=`bulk-edit`,e.DELETE=`delete`,e.UPDATE=`update`,e.CANCEL=`cancel`,e.FAIL=`fail`,e.UNASSIGN=`unassign`,e.BULK_ASSIGN=`bulk-assign`,e.REASSIGN=`reassign`,e.DISPATCH=`dispatch`,e.BULK_DISPATCH=`bulk-dispatch`,e.BULK_UPSERT=`bulk-upsert`,e.UPSERT=`upsert`,e.JOIN=`join`,e.MOVE=`move`,e.REOPTIMIZATION=`reoptimization`,e}({}),p=function(e){return e.RIDE=`Ride`,e.VEHICLE=`Vehicle`,e.DRIVER=`Driver`,e.PRICE_CALCULATION=`PriceCalculation`,e}({}),m=function(e){return e.USER=`user`,e.AUTOMATION=`automation`,e}({});const h=`audit-log-context`,g=`audit-log-rows`,_=`auditLogContext`,v=`x-af-automation-id`,y=(0,u.default)();y.addContextMiddleware(()=>({traceId:l.outbreak.getCurrentContextTraceId()}));var b=y;const x=`customFields`,S=()=>{let e=(0,l.getCurrentPayload)();return e?.nonHeaderContext?.get(_)},C={[f.BULK_CREATE]:f.BULK_CREATE,[f.BULK_EDIT]:f.BULK_EDIT,[f.BULK_ASSIGN]:f.BULK_ASSIGN,[f.BULK_DISPATCH]:f.BULK_DISPATCH,[f.BULK_UPSERT]:f.BULK_UPSERT},w=e=>[null,void 0].includes(e)?!0:Array.isArray(e)?e.length===0:typeof e==`object`&&!(e instanceof Date)?Object.keys(e).length===0:!1,T=e=>!Object.hasOwn(C,e),E=(e,t)=>e.filter(e=>!w(t.get(e))||!w(t.previous(e))),D=(e,t)=>{let n=t.returning?t.fields:e.changed()||[],r=E(n.filter(e=>e!==x),e);return r.map(t=>({property:t,previousValue:e.previous(t),newValue:e.get(t)}))},O=e=>{let t=e.changed(),n=t&&t.includes(x);if(!n)return[];let r=e.get(x),i=e.previous(x),a=Object.keys(r).filter(e=>{let t=r?.[e],n=i?.[e];return(!w(t)||!w(n))&&!(0,c.isDeepStrictEqual)(t,n)});return a.map(e=>({property:`${x}.${e}`,previousValue:i?.[e],newValue:r?.[e]}))};var k=class{rabbit;sequelize;logger;excludeModels;waitForTransactionCommit;constructor(e){this.rabbit=e.rabbit,this.sequelize=e.sequelize,this.logger=e.logger||b,this.excludeModels=e.excludeModels??[],this.waitForTransactionCommit=e.waitForTransactionCommit??!1}async manualSendAuditLog({auditContext:e,...t},n=this.logAndThrowError){if(e??=S(),e)try{e?.entityType?.toLowerCase()===t.entityType?.toLowerCase()&&T(e.action)&&(e.entityId=t.entityId),await this.rabbit.sendToQueue(g,t)}catch(e){n(e,t)}}registerHooks(){Object.entries(this.sequelize.models).forEach(([e,t])=>{this.excludeModels.includes(e)||t.addHook(`afterSave`,async(t,n)=>{let r=async()=>{let r=S();if(!r)return;let{id:i}=t;await this.manualSendAuditLog({entityId:i,auditContext:r,entityType:e,rows:[...D(t,n),...O(t)]},this.logError)};if(this.waitForTransactionCommit&&n.transaction){n.transaction.afterCommit(r);return}await r()})})}async sendAuditLogContext(e){try{await this.rabbit.sendToQueue(h,e)}catch(e){this.logger.error(`Failed to send audit log context`,e)}}logError=(e,t)=>{let{entityType:n,entityId:r}=t;this.logger.error(`Failed to send audit log rows`,{entityType:n,entityId:r,error:e})};logAndThrowError=(e,t)=>{throw this.logError(e,t),e}},A=k;const j=new d.default({serviceName:`AUDIT_MS`,timeout:6e4,logger:b}),M=async e=>{let{data:t}=await j.get(`api/v1/audit-logs/${e}`);return t},N={getByEntityId:M};var P=N;let F;const I=e=>process.env.DISABLE_AUDIT_LOGS===`true`?!1:(F=new A(e),F.registerHooks(),F),L=({action:e,endpoint:t,entityType:n,method:r,automationId:i,userId:a})=>{let o=a||(i??null),s=a&&m.USER||i&&m.AUTOMATION||null,c={entityType:n,action:e,endpoint:t,method:r,performedBy:o,actionOrigin:s},u=(0,l.getCurrentPayload)();return u.nonHeaderContext.set(_,c),c},R=async(e,t,n,r)=>{try{if(process.env.DISABLE_AUDIT_LOGS===`true`||!F)return;let i=L({action:r,endpoint:e.url,entityType:n,method:e.method,userId:(0,l.getUser)()?.id,automationId:e.headers[v]});if(!T(r)){await F.sendAuditLogContext(i);return}let a=async()=>{t.off(`finish`,a),t.off(`close`,a),t.off(`error`,a),await F?.sendAuditLogContext(i)};t.once(`finish`,a),t.once(`close`,a),t.once(`error`,a)}catch(e){b.error(`couldn't set audit context`,e)}},z=(e,t)=>async(n,{userId:r,automationId:i})=>{if(process.env.DISABLE_AUDIT_LOGS===`true`||!F)return;let a=L({action:t,endpoint:n,entityType:e,method:`rabbit`,userId:r,automationId:i});await F.sendAuditLogContext(a)};Object.defineProperty(exports,`AUDIT_LOG_CONTEXT_KEY`,{enumerable:!0,get:function(){return _}}),Object.defineProperty(exports,`AUDIT_LOG_CONTEXT_QUEUE`,{enumerable:!0,get:function(){return h}}),Object.defineProperty(exports,`AUDIT_LOG_ROWS_QUEUE`,{enumerable:!0,get:function(){return g}}),Object.defineProperty(exports,`AUTOMATION_ID_HEADER`,{enumerable:!0,get:function(){return v}}),Object.defineProperty(exports,`Action`,{enumerable:!0,get:function(){return f}}),Object.defineProperty(exports,`ActionOrigin`,{enumerable:!0,get:function(){return m}}),Object.defineProperty(exports,`EntityType`,{enumerable:!0,get:function(){return p}}),Object.defineProperty(exports,`__toESM`,{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,`audit_logger_default`,{enumerable:!0,get:function(){return A}}),Object.defineProperty(exports,`audit_ms_default`,{enumerable:!0,get:function(){return P}}),Object.defineProperty(exports,`innerEnableAuditing`,{enumerable:!0,get:function(){return I}}),Object.defineProperty(exports,`innerSetAuditContext`,{enumerable:!0,get:function(){return R}}),Object.defineProperty(exports,`setRabbitAuditContext`,{enumerable:!0,get:function(){return z}});
2
+ //# sourceMappingURL=common-DsOG1D2a.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"common-DsOG1D2a.cjs","names":["logger: LoggerInstanceManager","outbreak","changedFields: string[]","logger","Network","exportObj: { getByEntityId: typeof getByEntityId; }","auditLogger: AuditLogger | undefined","AuditLogger","auditLogContext: AuditLogContext"],"sources":["../src/types.ts","../src/const.ts","../src/logger.ts","../src/audit-logger.ts","../src/audit-ms.ts","../src/common.ts"],"sourcesContent":["import type { ModelStatic, Model } from 'sequelize';\nimport type { Sequelize } from 'sequelize-typescript';\nimport type RabbitMq from '@autofleet/rabbit';\nimport type { LoggerInstanceManager } from '@autofleet/logger';\nimport type { IRouter } from 'express';\nimport type { FastifyInstance } from 'fastify';\n\nexport interface AuditLoggerOptions {\n rabbit: RabbitMq;\n sequelize: Sequelize;\n logger: LoggerInstanceManager;\n router?: IRouter;\n fastify?: FastifyInstance;\n excludeModels?: string[];\n entityScopedModelMap?: Record<string, ModelStatic<Model>>;\n /**\n * If true and the model was changed inside a transaction, the audit log will be sent only after the transaction is committed.\n * This is useful because sequelize afterSave hook doesn't include the previous values if the model was changed inside a transaction.\n * @default false\n */\n waitForTransactionCommit?: boolean;\n}\n\nexport interface AuditLogContext {\n entityType: string;\n entityId?: string;\n action: string;\n performedBy: string | null;\n endpoint: string;\n method: string;\n actionOrigin?: string | null;\n}\n\nexport interface AuditLogRow {\n property: string;\n previousValue: unknown;\n newValue: unknown;\n}\n\nexport interface AuditLogPayload {\n entityType: string;\n entityId: string;\n rows: readonly AuditLogRow[];\n}\n\nexport enum Action {\n CREATE = 'create',\n BULK_CREATE = 'bulk-create',\n BULK_EDIT = 'bulk-edit',\n DELETE = 'delete',\n UPDATE = 'update',\n CANCEL = 'cancel',\n FAIL = 'fail',\n UNASSIGN = 'unassign',\n BULK_ASSIGN = 'bulk-assign',\n REASSIGN = 'reassign',\n DISPATCH = 'dispatch',\n BULK_DISPATCH = 'bulk-dispatch',\n BULK_UPSERT = 'bulk-upsert',\n UPSERT = 'upsert',\n JOIN = 'join',\n MOVE = 'move',\n REOPTIMIZATION = 'reoptimization',\n}\n\nexport enum EntityType {\n RIDE = 'Ride',\n VEHICLE = 'Vehicle',\n DRIVER = 'Driver',\n PRICE_CALCULATION = 'PriceCalculation',\n}\n\nexport const enum ActionOrigin {\n USER = 'user',\n AUTOMATION = 'automation',\n}\n","export const AUDIT_LOG_CONTEXT_QUEUE = 'audit-log-context';\nexport const AUDIT_LOG_ROWS_QUEUE = 'audit-log-rows';\nexport const AUDIT_LOG_CONTEXT_KEY = 'auditLogContext';\nexport const AUTOMATION_ID_HEADER = 'x-af-automation-id';\n","import { outbreak } from '@autofleet/zehut';\nimport Logger, { type LoggerInstanceManager } from '@autofleet/logger';\n\nconst logger: LoggerInstanceManager = Logger();\nlogger.addContextMiddleware(() => ({ traceId: outbreak.getCurrentContextTraceId() }));\nexport default logger;\n","import { isDeepStrictEqual } from 'node:util';\nimport type RabbitMq from '@autofleet/rabbit';\nimport type { LoggerInstanceManager } from '@autofleet/logger';\nimport { getCurrentPayload as getCurrentTrace } from '@autofleet/zehut';\nimport type {\n CreateOptions, InstanceUpdateOptions, Model, Sequelize,\n} from 'sequelize';\nimport {\n type AuditLogPayload, type AuditLoggerOptions, type AuditLogContext, Action, type AuditLogRow,\n} from './types';\nimport { AUDIT_LOG_CONTEXT_QUEUE, AUDIT_LOG_ROWS_QUEUE, AUDIT_LOG_CONTEXT_KEY } from './const';\nimport logger from './logger';\n\nconst CUSTOM_FIELDS_PROPERTY = 'customFields';\n\nconst getAuditContext = () => {\n const currentTrace = getCurrentTrace();\n return currentTrace?.nonHeaderContext?.get(AUDIT_LOG_CONTEXT_KEY) as AuditLogContext | undefined;\n};\n\nconst ACTIONS_TO_OMIT_ENTITY_ID_FROM_CONTEXT = {\n [Action.BULK_CREATE]: Action.BULK_CREATE,\n [Action.BULK_EDIT]: Action.BULK_EDIT,\n [Action.BULK_ASSIGN]: Action.BULK_ASSIGN,\n [Action.BULK_DISPATCH]: Action.BULK_DISPATCH,\n [Action.BULK_UPSERT]: Action.BULK_UPSERT,\n};\n\nconst isEmpty = (field: unknown): boolean => {\n if ([null, undefined].includes(field as undefined)) {\n return true;\n }\n if (Array.isArray(field)) {\n return field.length === 0;\n }\n if (typeof field === 'object' && !(field instanceof Date)) {\n return Object.keys(field as Record<string, unknown>).length === 0;\n }\n return false;\n};\n\nexport const isEntityIdRequired = (action: string): boolean => !Object.hasOwn(ACTIONS_TO_OMIT_ENTITY_ID_FROM_CONTEXT, action);\n\nconst filterOutEmptyFields = (fields: string[], instance: Model) => fields.filter(field => !isEmpty(instance.get(field)) || !isEmpty(instance.previous(field)));\n\nconst getChangedFieldsRows = (instance: Model, options: CreateOptions | InstanceUpdateOptions): AuditLogRow[] => {\n // When bulk updating in sequelize using the \"returning\" option, the instance.changed() stops working.\n // It's a known issue with sequelize.\n const changedFields: string[] = options.returning ? options.fields as string[] : (instance.changed() || []);\n // Filter customFields - we'll handle them later\n const filteredChangedFields = filterOutEmptyFields(changedFields.filter(field => field !== CUSTOM_FIELDS_PROPERTY), instance);\n return filteredChangedFields.map(property => ({\n property,\n previousValue: instance.previous(property),\n newValue: instance.get(property),\n }));\n};\n\nconst getChangedCustomFieldsRows = (instance: Model): AuditLogRow[] => {\n // Based on the comment in getChangedFieldsRows, we cannot rely on instance.changed() when doing bulk updates with \"returning\".\n // So this seems like a possible bug.\n const changed = instance.changed();\n const customFieldsChanged = changed && changed.includes(CUSTOM_FIELDS_PROPERTY);\n if (!customFieldsChanged) {\n return [];\n }\n\n const customFields = instance.get(CUSTOM_FIELDS_PROPERTY) as Record<string, unknown>;\n const previousCustomFields = instance.previous(CUSTOM_FIELDS_PROPERTY);\n const changedCustomFields = Object.keys(customFields).filter((field) => {\n const newValue = customFields?.[field];\n const oldValue = previousCustomFields?.[field];\n return (!isEmpty(newValue) || !isEmpty(oldValue)) && !isDeepStrictEqual(newValue, oldValue);\n });\n return changedCustomFields.map(changedCustomField => ({\n property: `${CUSTOM_FIELDS_PROPERTY}.${changedCustomField}`,\n previousValue: previousCustomFields?.[changedCustomField],\n newValue: customFields?.[changedCustomField],\n }));\n};\n\ninterface AuditLogSendData extends AuditLogPayload {\n auditContext?: AuditLogContext;\n}\n\ntype AuditLogRowSendingErrorHandler = (error: unknown, payload: AuditLogPayload) => void;\n\nclass AuditLogger {\n private readonly rabbit: RabbitMq;\n private readonly sequelize: Sequelize;\n private readonly logger: LoggerInstanceManager;\n private readonly excludeModels: string[];\n private readonly waitForTransactionCommit: boolean;\n\n constructor(options: AuditLoggerOptions) {\n this.rabbit = options.rabbit;\n this.sequelize = options.sequelize;\n this.logger = options.logger || logger;\n this.excludeModels = options.excludeModels ?? [];\n this.waitForTransactionCommit = options.waitForTransactionCommit ?? false;\n }\n\n public async manualSendAuditLog(\n { auditContext, ...payload }: AuditLogSendData,\n errorHandler: AuditLogRowSendingErrorHandler = this.logAndThrowError,\n ): Promise<void> {\n auditContext ??= getAuditContext();\n if (!auditContext) {\n return;\n }\n try {\n // Make sure the current entity being changed it the \"main\" entity in the current audit context, and if so mark it as the \"entityId\".\n if (auditContext?.entityType?.toLowerCase() === payload.entityType?.toLowerCase() && isEntityIdRequired(auditContext.action)) {\n auditContext.entityId = payload.entityId;\n }\n await this.rabbit.sendToQueue(AUDIT_LOG_ROWS_QUEUE, payload);\n } catch (error) {\n errorHandler(error, payload);\n }\n }\n\n public registerHooks(): void {\n Object.entries(this.sequelize.models).forEach(([modelName, modelType]) => {\n if (this.excludeModels.includes(modelName)) {\n return;\n }\n modelType.addHook('afterSave', async (instance, options) => {\n const sendAuditLogForModel = async () => {\n const auditContext = getAuditContext();\n if (!auditContext) return;\n\n const { id: entityId } = instance as unknown as { id: string; };\n await this.manualSendAuditLog(\n {\n entityId,\n auditContext,\n entityType: modelName,\n rows: [...getChangedFieldsRows(instance, options), ...getChangedCustomFieldsRows(instance)],\n },\n this.logError,\n );\n };\n /*\n By default sequelize doesn't keep the previous values when using a transaction\n So we want to be able to call this function after the transaction is committed\n to be able to get the previous values\n */\n if (this.waitForTransactionCommit && options.transaction) {\n options.transaction.afterCommit(sendAuditLogForModel);\n return;\n }\n await sendAuditLogForModel();\n });\n });\n }\n\n public async sendAuditLogContext(context: AuditLogContext): Promise<void> {\n try {\n await this.rabbit.sendToQueue(AUDIT_LOG_CONTEXT_QUEUE, context);\n } catch (err) {\n this.logger.error('Failed to send audit log context', err);\n }\n }\n\n private logError: AuditLogRowSendingErrorHandler = (error: unknown, payload: AuditLogPayload) => {\n const { entityType, entityId } = payload;\n this.logger.error('Failed to send audit log rows', { entityType, entityId, error });\n };\n\n private logAndThrowError: AuditLogRowSendingErrorHandler = (error: unknown, payload: AuditLogPayload): never => {\n this.logError(error, payload);\n throw error;\n };\n}\n\nexport default AuditLogger;\n","import Network from '@autofleet/network';\nimport logger from './logger';\n\nconst auditMs = new Network({ serviceName: 'AUDIT_MS', timeout: 60_000, logger });\n\nconst getByEntityId = async (entityId: string): Promise<any> => {\n const { data } = await auditMs.get(`api/v1/audit-logs/${entityId}`);\n return data;\n};\n\nconst exportObj: { getByEntityId: typeof getByEntityId; } = { getByEntityId };\n\nexport default exportObj;\n","import type { Writable } from 'node:stream';\nimport type { IncomingHttpHeaders } from 'node:http';\nimport { getCurrentPayload, getUser } from '@autofleet/zehut';\nimport logger from './logger';\nimport AuditLogger, { isEntityIdRequired } from './audit-logger';\nimport { AUDIT_LOG_CONTEXT_KEY, AUTOMATION_ID_HEADER } from './const';\nimport { ActionOrigin, type AuditLogContext, type AuditLoggerOptions } from './types';\n\nlet auditLogger: AuditLogger | undefined;\n\nexport const innerEnableAuditing = (options: AuditLoggerOptions): false | AuditLogger => {\n if (process.env.DISABLE_AUDIT_LOGS === 'true') {\n return false;\n }\n auditLogger = new AuditLogger(options);\n auditLogger.registerHooks();\n return auditLogger;\n};\n\ninterface GetAuditLogContextParams {\n action: string;\n endpoint: string;\n entityType: string;\n method: string;\n automationId?: string;\n userId?: string;\n}\nconst getAuditLogContextAndSetToContext = ({\n action, endpoint, entityType, method, automationId, userId,\n}: GetAuditLogContextParams): AuditLogContext => {\n const performedBy = userId || (automationId ?? null);\n const actionOrigin = (userId && ActionOrigin.USER) || (automationId && ActionOrigin.AUTOMATION) || null;\n\n const auditLogContext: AuditLogContext = {\n entityType,\n action,\n endpoint,\n method,\n performedBy,\n actionOrigin,\n };\n const currentTrace = getCurrentPayload();\n currentTrace.nonHeaderContext.set(AUDIT_LOG_CONTEXT_KEY, auditLogContext);\n\n return auditLogContext;\n};\n\ninterface PartialRequest {\n url: string;\n method: string;\n headers: IncomingHttpHeaders;\n}\n\nexport const innerSetAuditContext = async (req: PartialRequest, res: Writable, entityType: string, action: string): Promise<void> => {\n try {\n if (process.env.DISABLE_AUDIT_LOGS === 'true' || !auditLogger) {\n return;\n }\n const auditLogContext = getAuditLogContextAndSetToContext({\n action,\n endpoint: req.url,\n entityType,\n method: req.method,\n userId: getUser()?.id,\n automationId: req.headers[AUTOMATION_ID_HEADER] as string | undefined,\n });\n\n if (!isEntityIdRequired(action)) { // if it's a bulk action, we don't want to wait for the response to add the entity id\n await auditLogger.sendAuditLogContext(auditLogContext);\n return;\n }\n\n const sendAuditLogContextEvent = async () => {\n res.off('finish', sendAuditLogContextEvent);\n res.off('close', sendAuditLogContextEvent);\n res.off('error', sendAuditLogContextEvent);\n await auditLogger?.sendAuditLogContext(auditLogContext);\n };\n res.once('finish', sendAuditLogContextEvent);\n res.once('close', sendAuditLogContextEvent);\n res.once('error', sendAuditLogContextEvent);\n } catch (err) {\n logger.error('couldn\\'t set audit context', err);\n }\n};\n\nexport const setRabbitAuditContext = (entityType: string, action: string) => async (endpoint: string, { userId, automationId }: { userId: string; automationId: string; }): Promise<void> => {\n if (process.env.DISABLE_AUDIT_LOGS === 'true' || !auditLogger) {\n return;\n }\n const auditLogContext = getAuditLogContextAndSetToContext({\n action,\n endpoint,\n entityType,\n method: 'rabbit',\n userId,\n automationId,\n });\n\n await auditLogger.sendAuditLogContext(auditLogContext);\n};\n"],"mappings":"omBA6CA,IAAY,EAAA,SAAA,EAAL,OACL,GAAA,OAAA,SACA,EAAA,YAAA,cACA,EAAA,UAAA,YACA,EAAA,OAAA,SACA,EAAA,OAAA,SACA,EAAA,OAAA,SACA,EAAA,KAAA,OACA,EAAA,SAAA,WACA,EAAA,YAAA,cACA,EAAA,SAAA,WACA,EAAA,SAAA,WACA,EAAA,cAAA,gBACA,EAAA,YAAA,cACA,EAAA,OAAA,SACA,EAAA,KAAA,OACA,EAAA,KAAA,OACA,EAAA,eAAA,wBAGU,EAAA,SAAA,EAAL,OACL,GAAA,KAAA,OACA,EAAA,QAAA,UACA,EAAA,OAAA,SACA,EAAA,kBAAA,0BAGgB,EAAA,SAAA,EAAX,OACL,GAAA,KAAA,OACA,EAAA,WAAA,oBC1EF,MAAa,EAA0B,oBAC1B,EAAuB,iBACvB,EAAwB,kBACxB,EAAuB,qBCA9BA,GAAAA,EAAAA,EAAAA,WACN,EAAO,0BAA4B,CAAE,QAASC,EAAAA,SAAS,8BACvD,IAAA,EAAe,ECQf,MAAM,EAAyB,eAEzB,MAAwB,CAC5B,IAAM,GAAA,EAAA,EAAA,qBACN,OAAO,GAAc,kBAAkB,IAAI,IAGvC,EAAyC,EA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ggerOptions {
14
14
  fastify?: FastifyInstance;
15
15
  excludeModels?: string[];
16
16
  entityScopedModelMap?: Record<string, ModelStatic<Model>>;
17
+ /**
18
+ * If true and the model was changed inside a transaction, the audit log will be sent only after the transaction is committed.
19
+ * This is useful because sequelize afterSave hook doesn't include the previous values if the model was changed inside a transaction.
20
+ * @default false
21
+ */
22
+ waitForTransactionCommit?: boolean;
17
23
  }
18
24
  interface AuditLogContext {
19
25
  entityType: string;
@@ -74,6 +80,7 @@ declare class AuditLogger {
74
80
  private readonly sequelize;
75
81
  private readonly logger;
76
82
  private readonly excludeModels;
83
+ private readonly waitForTransactionCommit;
77
84
  constructor(options: AuditLoggerOptions);
78
85
  manualSendAuditLog({
79
86
  auditContext,
@@ -101,4 +108,4 @@ declare const AUDIT_LOG_CONTEXT_KEY = "auditLogContext";
101
108
  declare const AUTOMATION_ID_HEADER = "x-af-automation-id";
102
109
  //#endregion
103
110
  export { AUDIT_LOG_CONTEXT_KEY, AUDIT_LOG_CONTEXT_QUEUE, AUDIT_LOG_ROWS_QUEUE, AUTOMATION_ID_HEADER, Action, ActionOrigin, AuditLogContext, AuditLogPayload, AuditLogRow, AuditLogger, AuditLoggerOptions, EntityType, setRabbitAuditContext };
104
- //# sourceMappingURL=const-DuEIHV2f.d.cts.map
111
+ //# sourceMappingURL=const-CN1ji4Ar.d.cts.map
@@ -14,6 +14,12 @@ interface AuditLoggerOptions {
14
14
  fastify?: FastifyInstance;
15
15
  excludeModels?: string[];
16
16
  entityScopedModelMap?: Record<string, ModelStatic<Model>>;
17
+ /**
18
+ * If true and the model was changed inside a transaction, the audit log will be sent only after the transaction is committed.
19
+ * This is useful because sequelize afterSave hook doesn't include the previous values if the model was changed inside a transaction.
20
+ * @default false
21
+ */
22
+ waitForTransactionCommit?: boolean;
17
23
  }
18
24
  interface AuditLogContext {
19
25
  entityType: string;
@@ -74,6 +80,7 @@ declare class AuditLogger {
74
80
  private readonly sequelize;
75
81
  private readonly logger;
76
82
  private readonly excludeModels;
83
+ private readonly waitForTransactionCommit;
77
84
  constructor(options: AuditLoggerOptions);
78
85
  manualSendAuditLog({
79
86
  auditContext,
@@ -101,4 +108,4 @@ declare const AUDIT_LOG_CONTEXT_KEY = "auditLogContext";
101
108
  declare const AUTOMATION_ID_HEADER = "x-af-automation-id";
102
109
  //#endregion
103
110
  export { AUDIT_LOG_CONTEXT_KEY, AUDIT_LOG_CONTEXT_QUEUE, AUDIT_LOG_ROWS_QUEUE, AUTOMATION_ID_HEADER, Action, ActionOrigin, AuditLogContext, AuditLogPayload, AuditLogRow, AuditLogger, AuditLoggerOptions, EntityType, setRabbitAuditContext };
104
- //# sourceMappingURL=const-CTWZrE1v.d.ts.map
111
+ //# sourceMappingURL=const-DtXVFwFs.d.ts.map
package/dist/fastify.cjs CHANGED
@@ -1,2 +1,2 @@
1
- Object.defineProperty(exports,`__esModule`,{value:!0});const e=require(`./common-CLXNjq7Z.cjs`),t=e.__toESM(require(`@autofleet/errors`)),n={name:`audit`,description:`Audit logs API`};function r({fastify:r,logger:i,entityScopedModelMap:a}){!a||!r||Object.entries(a).forEach(([a,o])=>{r.get(`/api/v1/${a}/:id/audit`,{schema:{tags:[n.name],description:`Get audit logs for ${a} by ID`,params:{type:`object`,properties:{id:{type:`string`}},required:[`id`]}}},async n=>{let{id:r}=n.params,s=await o.findByPk(r);if(!s){let e=new t.ResourceNotFoundError;throw i.error(`Entity ${a} with id ${r} not found`,{err:e}),e}return e.audit_ms_default.getByEntityId(r)})})}const i=t=>{let n=e.innerEnableAuditing(t);if(n)return r(t),n},a=(t,n)=>async(r,i)=>{await e.innerSetAuditContext(r,i.raw,t,n)};var o=e.audit_logger_default;exports.AUDIT_LOG_CONTEXT_KEY=e.AUDIT_LOG_CONTEXT_KEY,exports.AUDIT_LOG_CONTEXT_QUEUE=e.AUDIT_LOG_CONTEXT_QUEUE,exports.AUDIT_LOG_ROWS_QUEUE=e.AUDIT_LOG_ROWS_QUEUE,exports.AUTOMATION_ID_HEADER=e.AUTOMATION_ID_HEADER,exports.Action=e.Action,exports.ActionOrigin=e.ActionOrigin,exports.EntityType=e.EntityType,exports.SWAGGER_TAG=n,exports.default=o,exports.enableAuditing=i,exports.setAuditContext=a,exports.setRabbitAuditContext=e.setRabbitAuditContext;
1
+ Object.defineProperty(exports,`__esModule`,{value:!0});const e=require(`./common-DsOG1D2a.cjs`),t=e.__toESM(require(`@autofleet/errors`)),n={name:`audit`,description:`Audit logs API`};function r({fastify:r,logger:i,entityScopedModelMap:a}){!a||!r||Object.entries(a).forEach(([a,o])=>{r.get(`/api/v1/${a}/:id/audit`,{schema:{tags:[n.name],description:`Get audit logs for ${a} by ID`,params:{type:`object`,properties:{id:{type:`string`}},required:[`id`]}}},async n=>{let{id:r}=n.params,s=await o.findByPk(r);if(!s){let e=new t.ResourceNotFoundError;throw i.error(`Entity ${a} with id ${r} not found`,{err:e}),e}return e.audit_ms_default.getByEntityId(r)})})}const i=t=>{let n=e.innerEnableAuditing(t);if(n)return r(t),n},a=(t,n)=>async(r,i)=>{await e.innerSetAuditContext(r,i.raw,t,n)};var o=e.audit_logger_default;exports.AUDIT_LOG_CONTEXT_KEY=e.AUDIT_LOG_CONTEXT_KEY,exports.AUDIT_LOG_CONTEXT_QUEUE=e.AUDIT_LOG_CONTEXT_QUEUE,exports.AUDIT_LOG_ROWS_QUEUE=e.AUDIT_LOG_ROWS_QUEUE,exports.AUTOMATION_ID_HEADER=e.AUTOMATION_ID_HEADER,exports.Action=e.Action,exports.ActionOrigin=e.ActionOrigin,exports.EntityType=e.EntityType,exports.SWAGGER_TAG=n,exports.default=o,exports.enableAuditing=i,exports.setAuditContext=a,exports.setRabbitAuditContext=e.setRabbitAuditContext;
2
2
  //# sourceMappingURL=fastify.cjs.map
@@ -1,4 +1,4 @@
1
- import { AUDIT_LOG_CONTEXT_KEY, AUDIT_LOG_CONTEXT_QUEUE, AUDIT_LOG_ROWS_QUEUE, AUTOMATION_ID_HEADER, Action, ActionOrigin, AuditLogContext, AuditLogPayload, AuditLogRow, AuditLogger, AuditLoggerOptions, EntityType, setRabbitAuditContext } from "./const-DuEIHV2f.cjs";
1
+ import { AUDIT_LOG_CONTEXT_KEY, AUDIT_LOG_CONTEXT_QUEUE, AUDIT_LOG_ROWS_QUEUE, AUTOMATION_ID_HEADER, Action, ActionOrigin, AuditLogContext, AuditLogPayload, AuditLogRow, AuditLogger, AuditLoggerOptions, EntityType, setRabbitAuditContext } from "./const-CN1ji4Ar.cjs";
2
2
  import { onRequestAsyncHookHandler } from "fastify";
3
3
 
4
4
  //#region src/audit-api/fastify.d.ts
package/dist/fastify.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { AUDIT_LOG_CONTEXT_KEY, AUDIT_LOG_CONTEXT_QUEUE, AUDIT_LOG_ROWS_QUEUE, AUTOMATION_ID_HEADER, Action, ActionOrigin, AuditLogContext, AuditLogPayload, AuditLogRow, AuditLogger, AuditLoggerOptions, EntityType, setRabbitAuditContext } from "./const-CTWZrE1v.js";
1
+ import { AUDIT_LOG_CONTEXT_KEY, AUDIT_LOG_CONTEXT_QUEUE, AUDIT_LOG_ROWS_QUEUE, AUTOMATION_ID_HEADER, Action, ActionOrigin, AuditLogContext, AuditLogPayload, AuditLogRow, AuditLogger, AuditLoggerOptions, EntityType, setRabbitAuditContext } from "./const-DtXVFwFs.js";
2
2
  import { onRequestAsyncHookHandler } from "fastify";
3
3
 
4
4
  //#region src/audit-api/fastify.d.ts
package/dist/fastify.js CHANGED
@@ -1,2 +1,2 @@
1
- import{AUDIT_LOG_CONTEXT_KEY as e,AUDIT_LOG_CONTEXT_QUEUE as t,AUDIT_LOG_ROWS_QUEUE as n,AUTOMATION_ID_HEADER as r,Action as i,ActionOrigin as a,EntityType as o,audit_logger_default as s,audit_ms_default as c,innerEnableAuditing as l,innerSetAuditContext as u,setRabbitAuditContext as d}from"./common-BBbssR1Z.js";import{ResourceNotFoundError as f}from"@autofleet/errors";const p={name:`audit`,description:`Audit logs API`};function m({fastify:e,logger:t,entityScopedModelMap:n}){!n||!e||Object.entries(n).forEach(([n,r])=>{e.get(`/api/v1/${n}/:id/audit`,{schema:{tags:[p.name],description:`Get audit logs for ${n} by ID`,params:{type:`object`,properties:{id:{type:`string`}},required:[`id`]}}},async e=>{let{id:i}=e.params,a=await r.findByPk(i);if(!a){let e=new f;throw t.error(`Entity ${n} with id ${i} not found`,{err:e}),e}return c.getByEntityId(i)})})}const h=e=>{let t=l(e);if(t)return m(e),t},g=(e,t)=>async(n,r)=>{await u(n,r.raw,e,t)};var _=s;export{e as AUDIT_LOG_CONTEXT_KEY,t as AUDIT_LOG_CONTEXT_QUEUE,n as AUDIT_LOG_ROWS_QUEUE,r as AUTOMATION_ID_HEADER,i as Action,a as ActionOrigin,o as EntityType,p as SWAGGER_TAG,_ as default,h as enableAuditing,g as setAuditContext,d as setRabbitAuditContext};
1
+ import{AUDIT_LOG_CONTEXT_KEY as e,AUDIT_LOG_CONTEXT_QUEUE as t,AUDIT_LOG_ROWS_QUEUE as n,AUTOMATION_ID_HEADER as r,Action as i,ActionOrigin as a,EntityType as o,audit_logger_default as s,audit_ms_default as c,innerEnableAuditing as l,innerSetAuditContext as u,setRabbitAuditContext as d}from"./common-CWEG3Eik.js";import{ResourceNotFoundError as f}from"@autofleet/errors";const p={name:`audit`,description:`Audit logs API`};function m({fastify:e,logger:t,entityScopedModelMap:n}){!n||!e||Object.entries(n).forEach(([n,r])=>{e.get(`/api/v1/${n}/:id/audit`,{schema:{tags:[p.name],description:`Get audit logs for ${n} by ID`,params:{type:`object`,properties:{id:{type:`string`}},required:[`id`]}}},async e=>{let{id:i}=e.params,a=await r.findByPk(i);if(!a){let e=new f;throw t.error(`Entity ${n} with id ${i} not found`,{err:e}),e}return c.getByEntityId(i)})})}const h=e=>{let t=l(e);if(t)return m(e),t},g=(e,t)=>async(n,r)=>{await u(n,r.raw,e,t)};var _=s;export{e as AUDIT_LOG_CONTEXT_KEY,t as AUDIT_LOG_CONTEXT_QUEUE,n as AUDIT_LOG_ROWS_QUEUE,r as AUTOMATION_ID_HEADER,i as Action,a as ActionOrigin,o as EntityType,p as SWAGGER_TAG,_ as default,h as enableAuditing,g as setAuditContext,d as setRabbitAuditContext};
2
2
  //# sourceMappingURL=fastify.js.map
package/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- Object.defineProperty(exports,`__esModule`,{value:!0});const e=require(`./common-CLXNjq7Z.cjs`),t=e.__toESM(require(`@autofleet/errors`));function n({router:n,logger:r,entityScopedModelMap:i}){!i||!n||Object.entries(i).forEach(([i,a])=>{n.get(`/${i}/:id/audit`,async(n,o)=>{try{let{id:s}=n.params,c=await a.findByPk(s);if(!c)return(0,t.handleError)(new t.ResourceNotFoundError,o,{logger:r,message:`Entity ${i} with id ${s} not found`});let l=await e.audit_ms_default.getByEntityId(s);return o.json(l)}catch(e){return(0,t.handleError)(new t.UnexpectedError(e),o,{logger:r})}})})}const r=t=>{let r=e.innerEnableAuditing(t);if(r)return n(t),r},i=(t,n)=>async(r,i,a)=>(await e.innerSetAuditContext(r,i,t,n),a());var a=e.audit_logger_default;exports.AUDIT_LOG_CONTEXT_KEY=e.AUDIT_LOG_CONTEXT_KEY,exports.AUDIT_LOG_CONTEXT_QUEUE=e.AUDIT_LOG_CONTEXT_QUEUE,exports.AUDIT_LOG_ROWS_QUEUE=e.AUDIT_LOG_ROWS_QUEUE,exports.AUTOMATION_ID_HEADER=e.AUTOMATION_ID_HEADER,exports.Action=e.Action,exports.ActionOrigin=e.ActionOrigin,exports.EntityType=e.EntityType,exports.default=a,exports.enableAuditing=r,exports.setAuditContext=i,exports.setRabbitAuditContext=e.setRabbitAuditContext;
1
+ Object.defineProperty(exports,`__esModule`,{value:!0});const e=require(`./common-DsOG1D2a.cjs`),t=e.__toESM(require(`@autofleet/errors`));function n({router:n,logger:r,entityScopedModelMap:i}){!i||!n||Object.entries(i).forEach(([i,a])=>{n.get(`/${i}/:id/audit`,async(n,o)=>{try{let{id:s}=n.params,c=await a.findByPk(s);if(!c)return(0,t.handleError)(new t.ResourceNotFoundError,o,{logger:r,message:`Entity ${i} with id ${s} not found`});let l=await e.audit_ms_default.getByEntityId(s);return o.json(l)}catch(e){return(0,t.handleError)(new t.UnexpectedError(e),o,{logger:r})}})})}const r=t=>{let r=e.innerEnableAuditing(t);if(r)return n(t),r},i=(t,n)=>async(r,i,a)=>(await e.innerSetAuditContext(r,i,t,n),a());var a=e.audit_logger_default;exports.AUDIT_LOG_CONTEXT_KEY=e.AUDIT_LOG_CONTEXT_KEY,exports.AUDIT_LOG_CONTEXT_QUEUE=e.AUDIT_LOG_CONTEXT_QUEUE,exports.AUDIT_LOG_ROWS_QUEUE=e.AUDIT_LOG_ROWS_QUEUE,exports.AUTOMATION_ID_HEADER=e.AUTOMATION_ID_HEADER,exports.Action=e.Action,exports.ActionOrigin=e.ActionOrigin,exports.EntityType=e.EntityType,exports.default=a,exports.enableAuditing=r,exports.setAuditContext=i,exports.setRabbitAuditContext=e.setRabbitAuditContext;
2
2
  //# sourceMappingURL=index.cjs.map
package/dist/index.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- import { AUDIT_LOG_CONTEXT_KEY, AUDIT_LOG_CONTEXT_QUEUE, AUDIT_LOG_ROWS_QUEUE, AUTOMATION_ID_HEADER, Action, ActionOrigin, AuditLogContext, AuditLogPayload, AuditLogRow, AuditLogger, AuditLoggerOptions, EntityType, setRabbitAuditContext } from "./const-DuEIHV2f.cjs";
1
+ import { AUDIT_LOG_CONTEXT_KEY, AUDIT_LOG_CONTEXT_QUEUE, AUDIT_LOG_ROWS_QUEUE, AUTOMATION_ID_HEADER, Action, ActionOrigin, AuditLogContext, AuditLogPayload, AuditLogRow, AuditLogger, AuditLoggerOptions, EntityType, setRabbitAuditContext } from "./const-CN1ji4Ar.cjs";
2
2
  import { NextFunction, Request, Response } from "express";
3
3
 
4
4
  //#region src/index.d.ts
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { AUDIT_LOG_CONTEXT_KEY, AUDIT_LOG_CONTEXT_QUEUE, AUDIT_LOG_ROWS_QUEUE, AUTOMATION_ID_HEADER, Action, ActionOrigin, AuditLogContext, AuditLogPayload, AuditLogRow, AuditLogger, AuditLoggerOptions, EntityType, setRabbitAuditContext } from "./const-CTWZrE1v.js";
1
+ import { AUDIT_LOG_CONTEXT_KEY, AUDIT_LOG_CONTEXT_QUEUE, AUDIT_LOG_ROWS_QUEUE, AUTOMATION_ID_HEADER, Action, ActionOrigin, AuditLogContext, AuditLogPayload, AuditLogRow, AuditLogger, AuditLoggerOptions, EntityType, setRabbitAuditContext } from "./const-DtXVFwFs.js";
2
2
  import { NextFunction, Request, Response } from "express";
3
3
 
4
4
  //#region src/index.d.ts
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- import{AUDIT_LOG_CONTEXT_KEY as e,AUDIT_LOG_CONTEXT_QUEUE as t,AUDIT_LOG_ROWS_QUEUE as n,AUTOMATION_ID_HEADER as r,Action as i,ActionOrigin as a,EntityType as o,audit_logger_default as s,audit_ms_default as c,innerEnableAuditing as l,innerSetAuditContext as u,setRabbitAuditContext as d}from"./common-BBbssR1Z.js";import{ResourceNotFoundError as f,UnexpectedError as p,handleError as m}from"@autofleet/errors";function h({router:e,logger:t,entityScopedModelMap:n}){!n||!e||Object.entries(n).forEach(([n,r])=>{e.get(`/${n}/:id/audit`,async(e,i)=>{try{let{id:a}=e.params,o=await r.findByPk(a);if(!o)return m(new f,i,{logger:t,message:`Entity ${n} with id ${a} not found`});let s=await c.getByEntityId(a);return i.json(s)}catch(e){return m(new p(e),i,{logger:t})}})})}const g=e=>{let t=l(e);if(t)return h(e),t},_=(e,t)=>async(n,r,i)=>(await u(n,r,e,t),i());var v=s;export{e as AUDIT_LOG_CONTEXT_KEY,t as AUDIT_LOG_CONTEXT_QUEUE,n as AUDIT_LOG_ROWS_QUEUE,r as AUTOMATION_ID_HEADER,i as Action,a as ActionOrigin,o as EntityType,v as default,g as enableAuditing,_ as setAuditContext,d as setRabbitAuditContext};
1
+ import{AUDIT_LOG_CONTEXT_KEY as e,AUDIT_LOG_CONTEXT_QUEUE as t,AUDIT_LOG_ROWS_QUEUE as n,AUTOMATION_ID_HEADER as r,Action as i,ActionOrigin as a,EntityType as o,audit_logger_default as s,audit_ms_default as c,innerEnableAuditing as l,innerSetAuditContext as u,setRabbitAuditContext as d}from"./common-CWEG3Eik.js";import{ResourceNotFoundError as f,UnexpectedError as p,handleError as m}from"@autofleet/errors";function h({router:e,logger:t,entityScopedModelMap:n}){!n||!e||Object.entries(n).forEach(([n,r])=>{e.get(`/${n}/:id/audit`,async(e,i)=>{try{let{id:a}=e.params,o=await r.findByPk(a);if(!o)return m(new f,i,{logger:t,message:`Entity ${n} with id ${a} not found`});let s=await c.getByEntityId(a);return i.json(s)}catch(e){return m(new p(e),i,{logger:t})}})})}const g=e=>{let t=l(e);if(t)return h(e),t},_=(e,t)=>async(n,r,i)=>(await u(n,r,e,t),i());var v=s;export{e as AUDIT_LOG_CONTEXT_KEY,t as AUDIT_LOG_CONTEXT_QUEUE,n as AUDIT_LOG_ROWS_QUEUE,r as AUTOMATION_ID_HEADER,i as Action,a as ActionOrigin,o as EntityType,v as default,g as enableAuditing,_ as setAuditContext,d as setRabbitAuditContext};
2
2
  //# sourceMappingURL=index.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@autofleet/shtinker",
3
- "version": "3.5.1",
3
+ "version": "3.6.1",
4
4
  "description": "",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -1,2 +0,0 @@
1
- import{isDeepStrictEqual as e}from"node:util";import{getCurrentPayload as t,getUser as n,outbreak as r}from"@autofleet/zehut";import i from"@autofleet/logger";import a from"@autofleet/network";let o=function(e){return e.CREATE=`create`,e.BULK_CREATE=`bulk-create`,e.BULK_EDIT=`bulk-edit`,e.DELETE=`delete`,e.UPDATE=`update`,e.CANCEL=`cancel`,e.FAIL=`fail`,e.UNASSIGN=`unassign`,e.BULK_ASSIGN=`bulk-assign`,e.REASSIGN=`reassign`,e.DISPATCH=`dispatch`,e.BULK_DISPATCH=`bulk-dispatch`,e.BULK_UPSERT=`bulk-upsert`,e.UPSERT=`upsert`,e.JOIN=`join`,e.MOVE=`move`,e.REOPTIMIZATION=`reoptimization`,e}({}),s=function(e){return e.RIDE=`Ride`,e.VEHICLE=`Vehicle`,e.DRIVER=`Driver`,e.PRICE_CALCULATION=`PriceCalculation`,e}({}),c=function(e){return e.USER=`user`,e.AUTOMATION=`automation`,e}({});const l=`audit-log-context`,u=`audit-log-rows`,d=`auditLogContext`,f=`x-af-automation-id`,p=i();p.addContextMiddleware(()=>({traceId:r.getCurrentContextTraceId()}));var m=p;const h=`customFields`,g=()=>{let e=t(),n=e?.nonHeaderContext?.get(d);return n},_={[o.BULK_CREATE]:o.BULK_CREATE,[o.BULK_EDIT]:o.BULK_EDIT,[o.BULK_ASSIGN]:o.BULK_ASSIGN,[o.BULK_DISPATCH]:o.BULK_DISPATCH,[o.BULK_UPSERT]:o.BULK_UPSERT},v=e=>[null,void 0].includes(e)?!0:Array.isArray(e)?e.length===0:typeof e==`object`&&!(e instanceof Date)?Object.keys(e).length===0:!1,y=e=>!Object.hasOwn(_,e),b=(e,t)=>e.filter(e=>!v(t.get(e))||!v(t.previous(e))),x=(e,t)=>{let n=t.returning?t.fields:e.changed(),r=b(n.filter(e=>e!==h),e);return r.map(t=>({property:t,previousValue:e.previous(t),newValue:e.get(t)}))},S=t=>{let n=t.changed(),r=n&&n.includes(h);if(!r)return[];let i=t.get(h),a=t.previous(h),o=Object.keys(i).filter(t=>{let n=i?.[t],r=a?.[t];return(!v(n)||!v(r))&&!e(n,r)});return o.map(e=>({property:`${h}.${e}`,previousValue:a?.[e],newValue:i?.[e]}))};var C=class{rabbit;sequelize;logger;excludeModels;constructor(e){this.rabbit=e.rabbit,this.sequelize=e.sequelize,this.logger=e.logger||m,this.excludeModels=e.excludeModels??[]}async manualSendAuditLog({auditContext:e,...t},n=this.logAndThrowError){if(e??=g(),e)try{e?.entityType?.toLowerCase()===t.entityType?.toLowerCase()&&y(e.action)&&(e.entityId=t.entityId),await this.rabbit.sendToQueue(u,t)}catch(e){n(e,t)}}registerHooks(){Object.entries(this.sequelize.models).forEach(([e,t])=>{this.excludeModels.includes(e)||t.addHook(`afterSave`,async(t,n)=>{let r=g();if(!r)return;let{id:i}=t;await this.manualSendAuditLog({entityId:i,auditContext:r,entityType:e,rows:[...x(t,n),...S(t)]},this.logError)})})}async sendAuditLogContext(e){try{await this.rabbit.sendToQueue(l,e)}catch(e){this.logger.error(`Failed to send audit log context`,e)}}logError=(e,t)=>{let{entityType:n,entityId:r}=t;this.logger.error(`Failed to send audit log rows`,{entityType:n,entityId:r,error:e})};logAndThrowError=(e,t)=>{throw this.logError(e,t),e}},w=C;const T=new a({serviceName:`AUDIT_MS`,timeout:6e4,logger:m}),E=async e=>{let{data:t}=await T.get(`api/v1/audit-logs/${e}`);return t},D={getByEntityId:E};var O=D;let k;const A=e=>process.env.DISABLE_AUDIT_LOGS===`true`?!1:(k=new w(e),k.registerHooks(),k),j=({action:e,endpoint:n,entityType:r,method:i,automationId:a,userId:o})=>{let s=o||(a??null),l=o&&c.USER||a&&c.AUTOMATION||null,u={entityType:r,action:e,endpoint:n,method:i,performedBy:s,actionOrigin:l},f=t();return f.nonHeaderContext.set(d,u),u},M=async(e,t,r,i)=>{try{if(process.env.DISABLE_AUDIT_LOGS===`true`||!k)return;let a=j({action:i,endpoint:e.url,entityType:r,method:e.method,userId:n()?.id,automationId:e.headers[f]});if(!y(i)){await k.sendAuditLogContext(a);return}let o=async()=>{t.off(`finish`,o),t.off(`close`,o),t.off(`error`,o),await k?.sendAuditLogContext(a)};t.once(`finish`,o),t.once(`close`,o),t.once(`error`,o)}catch(e){m.error(`couldn't set audit context`,e)}},N=(e,t)=>async(n,{userId:r,automationId:i})=>{if(process.env.DISABLE_AUDIT_LOGS===`true`||!k)return;let a=j({action:t,endpoint:n,entityType:e,method:`rabbit`,userId:r,automationId:i});await k.sendAuditLogContext(a)};export{d as AUDIT_LOG_CONTEXT_KEY,l as AUDIT_LOG_CONTEXT_QUEUE,u as AUDIT_LOG_ROWS_QUEUE,f as AUTOMATION_ID_HEADER,o as Action,c as ActionOrigin,s as EntityType,w as audit_logger_default,O as audit_ms_default,A as innerEnableAuditing,M as innerSetAuditContext,N as setRabbitAuditContext};
2
- //# sourceMappingURL=common-BBbssR1Z.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"common-BBbssR1Z.js","names":["logger: LoggerInstanceManager","getCurrentTrace","changedFields: string[]","logger","exportObj: { getByEntityId: typeof getByEntityId; }","auditLogger: AuditLogger | undefined","AuditLogger","auditLogContext: AuditLogContext"],"sources":["../src/types.ts","../src/const.ts","../src/logger.ts","../src/audit-logger.ts","../src/audit-ms.ts","../src/common.ts"],"sourcesContent":["import type { ModelStatic, Model } from 'sequelize';\nimport type { Sequelize } from 'sequelize-typescript';\nimport type RabbitMq from '@autofleet/rabbit';\nimport type { LoggerInstanceManager } from '@autofleet/logger';\nimport type { IRouter } from 'express';\nimport type { FastifyInstance } from 'fastify';\n\nexport interface AuditLoggerOptions {\n rabbit: RabbitMq;\n sequelize: Sequelize;\n logger: LoggerInstanceManager;\n router?: IRouter;\n fastify?: FastifyInstance;\n excludeModels?: string[];\n entityScopedModelMap?: Record<string, ModelStatic<Model>>;\n}\n\nexport interface AuditLogContext {\n entityType: string;\n entityId?: string;\n action: string;\n performedBy: string | null;\n endpoint: string;\n method: string;\n actionOrigin?: string | null;\n}\n\nexport interface AuditLogRow {\n property: string;\n previousValue: unknown;\n newValue: unknown;\n}\n\nexport interface AuditLogPayload {\n entityType: string;\n entityId: string;\n rows: readonly AuditLogRow[];\n}\n\nexport enum Action {\n CREATE = 'create',\n BULK_CREATE = 'bulk-create',\n BULK_EDIT = 'bulk-edit',\n DELETE = 'delete',\n UPDATE = 'update',\n CANCEL = 'cancel',\n FAIL = 'fail',\n UNASSIGN = 'unassign',\n BULK_ASSIGN = 'bulk-assign',\n REASSIGN = 'reassign',\n DISPATCH = 'dispatch',\n BULK_DISPATCH = 'bulk-dispatch',\n BULK_UPSERT = 'bulk-upsert',\n UPSERT = 'upsert',\n JOIN = 'join',\n MOVE = 'move',\n REOPTIMIZATION = 'reoptimization',\n}\n\nexport enum EntityType {\n RIDE = 'Ride',\n VEHICLE = 'Vehicle',\n DRIVER = 'Driver',\n PRICE_CALCULATION = 'PriceCalculation',\n}\n\nexport const enum ActionOrigin {\n USER = 'user',\n AUTOMATION = 'automation',\n}\n","export const AUDIT_LOG_CONTEXT_QUEUE = 'audit-log-context';\nexport const AUDIT_LOG_ROWS_QUEUE = 'audit-log-rows';\nexport const AUDIT_LOG_CONTEXT_KEY = 'auditLogContext';\nexport const AUTOMATION_ID_HEADER = 'x-af-automation-id';\n","import { outbreak } from '@autofleet/zehut';\nimport Logger, { type LoggerInstanceManager } from '@autofleet/logger';\n\nconst logger: LoggerInstanceManager = Logger();\nlogger.addContextMiddleware(() => ({ traceId: outbreak.getCurrentContextTraceId() }));\nexport default logger;\n","import { isDeepStrictEqual } from 'node:util';\nimport type RabbitMq from '@autofleet/rabbit';\nimport type { LoggerInstanceManager } from '@autofleet/logger';\nimport { getCurrentPayload as getCurrentTrace } from '@autofleet/zehut';\nimport type {\n CreateOptions, InstanceUpdateOptions, Model, Sequelize,\n} from 'sequelize';\nimport {\n type AuditLogPayload, type AuditLoggerOptions, type AuditLogContext, Action, type AuditLogRow,\n} from './types';\nimport { AUDIT_LOG_CONTEXT_QUEUE, AUDIT_LOG_ROWS_QUEUE, AUDIT_LOG_CONTEXT_KEY } from './const';\nimport logger from './logger';\n\nconst CUSTOM_FIELDS_PROPERTY = 'customFields';\n\nconst getAuditContext = () => {\n const currentTrace = getCurrentTrace();\n const auditContext = currentTrace?.nonHeaderContext?.get(AUDIT_LOG_CONTEXT_KEY);\n return auditContext as AuditLogContext;\n};\n\nconst ACTIONS_TO_OMIT_ENTITY_ID_FROM_CONTEXT = {\n [Action.BULK_CREATE]: Action.BULK_CREATE,\n [Action.BULK_EDIT]: Action.BULK_EDIT,\n [Action.BULK_ASSIGN]: Action.BULK_ASSIGN,\n [Action.BULK_DISPATCH]: Action.BULK_DISPATCH,\n [Action.BULK_UPSERT]: Action.BULK_UPSERT,\n};\n\nconst isEmpty = (field: unknown): boolean => {\n if ([null, undefined].includes(field as undefined)) {\n return true;\n }\n if (Array.isArray(field)) {\n return field.length === 0;\n }\n if (typeof field === 'object' && !(field instanceof Date)) {\n return Object.keys(field as Record<string, unknown>).length === 0;\n }\n return false;\n};\n\nexport const isEntityIdRequired = (action: string): boolean => !Object.hasOwn(ACTIONS_TO_OMIT_ENTITY_ID_FROM_CONTEXT, action);\n\nconst filterOutEmptyFields = (fields: string[], instance: Model) => fields.filter(field => !isEmpty(instance.get(field)) || !isEmpty(instance.previous(field)));\n\nconst getChangedFieldsRows = (instance: Model, options: CreateOptions | InstanceUpdateOptions): AuditLogRow[] => {\n // When bulk updating in sequelize using the \"returning\" option, the instance.changed() stops working.\n // It's a known issue with sequelize.\n const changedFields: string[] = options.returning ? options.fields as string[] : instance.changed() as string[];\n // Filter customFields - we'll handle them later\n const filteredChangedFields = filterOutEmptyFields(changedFields.filter(field => field !== CUSTOM_FIELDS_PROPERTY), instance);\n return filteredChangedFields.map((property: string) => ({\n property,\n previousValue: instance.previous(property),\n newValue: instance.get(property),\n }));\n};\n\nconst getChangedCustomFieldsRows = (instance: Model): AuditLogRow[] => {\n // Based on the comment in getChangedFieldsRows, we cannot rely on instance.changed() when doing bulk updates with \"returning\".\n // So this seems like a possible bug.\n const changed = instance.changed();\n const customFieldsChanged = changed && changed.includes(CUSTOM_FIELDS_PROPERTY);\n if (!customFieldsChanged) {\n return [];\n }\n\n const customFields = instance.get(CUSTOM_FIELDS_PROPERTY) as Record<string, unknown>;\n const previousCustomFields = instance.previous(CUSTOM_FIELDS_PROPERTY);\n const changedCustomFields = Object.keys(customFields).filter((field) => {\n const newValue = customFields?.[field];\n const oldValue = previousCustomFields?.[field];\n return (!isEmpty(newValue) || !isEmpty(oldValue)) && !isDeepStrictEqual(newValue, oldValue);\n });\n return changedCustomFields.map(changedCustomField => ({\n property: `${CUSTOM_FIELDS_PROPERTY}.${changedCustomField}`,\n previousValue: previousCustomFields?.[changedCustomField],\n newValue: customFields?.[changedCustomField],\n }));\n};\n\ninterface AuditLogSendData extends AuditLogPayload {\n auditContext?: AuditLogContext;\n}\n\ntype AuditLogRowSendingErrorHandler = (error: unknown, payload: AuditLogPayload) => void;\n\nclass AuditLogger {\n private readonly rabbit: RabbitMq;\n\n private readonly sequelize: Sequelize;\n\n private readonly logger: LoggerInstanceManager;\n\n private readonly excludeModels: string[];\n\n constructor(options: AuditLoggerOptions) {\n this.rabbit = options.rabbit;\n this.sequelize = options.sequelize;\n this.logger = options.logger || logger;\n this.excludeModels = options.excludeModels ?? [];\n }\n\n public async manualSendAuditLog(\n { auditContext, ...payload }: AuditLogSendData,\n errorHandler: AuditLogRowSendingErrorHandler = this.logAndThrowError,\n ): Promise<void> {\n auditContext ??= getAuditContext();\n if (!auditContext) {\n return;\n }\n try {\n // Make sure the current entity being changed it the \"main\" entity in the current audit context, and if so mark it as the \"entityId\".\n if (auditContext?.entityType?.toLowerCase() === payload.entityType?.toLowerCase() && isEntityIdRequired(auditContext.action)) {\n auditContext.entityId = payload.entityId;\n }\n await this.rabbit.sendToQueue(AUDIT_LOG_ROWS_QUEUE, payload);\n } catch (error) {\n errorHandler(error, payload);\n }\n }\n\n public registerHooks(): void {\n Object.entries(this.sequelize.models).forEach(([modelName, modelType]) => {\n if (this.excludeModels.includes(modelName)) {\n return;\n }\n modelType.addHook('afterSave', async (instance, options) => {\n const auditContext = getAuditContext();\n if (!auditContext) return;\n\n const { id: entityId } = instance as unknown as { id: string; };\n await this.manualSendAuditLog(\n {\n entityId,\n auditContext,\n entityType: modelName,\n rows: [...getChangedFieldsRows(instance, options), ...getChangedCustomFieldsRows(instance)],\n },\n this.logError,\n );\n });\n });\n }\n\n public async sendAuditLogContext(context: AuditLogContext): Promise<void> {\n try {\n await this.rabbit.sendToQueue(AUDIT_LOG_CONTEXT_QUEUE, context);\n } catch (err) {\n this.logger.error('Failed to send audit log context', err);\n }\n }\n\n private logError: AuditLogRowSendingErrorHandler = (error: unknown, payload: AuditLogPayload) => {\n const { entityType, entityId } = payload;\n this.logger.error('Failed to send audit log rows', { entityType, entityId, error });\n };\n\n private logAndThrowError: AuditLogRowSendingErrorHandler = (error: unknown, payload: AuditLogPayload): never => {\n this.logError(error, payload);\n throw error;\n };\n}\n\nexport default AuditLogger;\n","import Network from '@autofleet/network';\nimport logger from './logger';\n\nconst auditMs = new Network({ serviceName: 'AUDIT_MS', timeout: 60_000, logger });\n\nconst getByEntityId = async (entityId: string): Promise<any> => {\n const { data } = await auditMs.get(`api/v1/audit-logs/${entityId}`);\n return data;\n};\n\nconst exportObj: { getByEntityId: typeof getByEntityId; } = { getByEntityId };\n\nexport default exportObj;\n","import type { Writable } from 'node:stream';\nimport type { IncomingHttpHeaders } from 'node:http';\nimport { getCurrentPayload, getUser } from '@autofleet/zehut';\nimport logger from './logger';\nimport AuditLogger, { isEntityIdRequired } from './audit-logger';\nimport { AUDIT_LOG_CONTEXT_KEY, AUTOMATION_ID_HEADER } from './const';\nimport { ActionOrigin, type AuditLogContext, type AuditLoggerOptions } from './types';\n\nlet auditLogger: AuditLogger | undefined;\n\nexport const innerEnableAuditing = (options: AuditLoggerOptions): false | AuditLogger => {\n if (process.env.DISABLE_AUDIT_LOGS === 'true') {\n return false;\n }\n auditLogger = new AuditLogger(options);\n auditLogger.registerHooks();\n return auditLogger;\n};\n\ninterface GetAuditLogContextParams {\n action: string;\n endpoint: string;\n entityType: string;\n method: string;\n automationId?: string;\n userId?: string;\n}\nconst getAuditLogContextAndSetToContext = ({\n action, endpoint, entityType, method, automationId, userId,\n}: GetAuditLogContextParams): AuditLogContext => {\n const performedBy = userId || (automationId ?? null);\n const actionOrigin = (userId && ActionOrigin.USER) || (automationId && ActionOrigin.AUTOMATION) || null;\n\n const auditLogContext: AuditLogContext = {\n entityType,\n action,\n endpoint,\n method,\n performedBy,\n actionOrigin,\n };\n const currentTrace = getCurrentPayload();\n currentTrace.nonHeaderContext.set(AUDIT_LOG_CONTEXT_KEY, auditLogContext);\n\n return auditLogContext;\n};\n\ninterface PartialRequest {\n url: string;\n method: string;\n headers: IncomingHttpHeaders;\n}\n\nexport const innerSetAuditContext = async (req: PartialRequest, res: Writable, entityType: string, action: string): Promise<void> => {\n try {\n if (process.env.DISABLE_AUDIT_LOGS === 'true' || !auditLogger) {\n return;\n }\n const auditLogContext = getAuditLogContextAndSetToContext({\n action,\n endpoint: req.url,\n entityType,\n method: req.method,\n userId: getUser()?.id,\n automationId: req.headers[AUTOMATION_ID_HEADER] as string | undefined,\n });\n\n if (!isEntityIdRequired(action)) { // if it's a bulk action, we don't want to wait for the response to add the entity id\n await auditLogger.sendAuditLogContext(auditLogContext);\n return;\n }\n\n const sendAuditLogContextEvent = async () => {\n res.off('finish', sendAuditLogContextEvent);\n res.off('close', sendAuditLogContextEvent);\n res.off('error', sendAuditLogContextEvent);\n await auditLogger?.sendAuditLogContext(auditLogContext);\n };\n res.once('finish', sendAuditLogContextEvent);\n res.once('close', sendAuditLogContextEvent);\n res.once('error', sendAuditLogContextEvent);\n } catch (err) {\n logger.error('couldn\\'t set audit context', err);\n }\n};\n\nexport const setRabbitAuditContext = (entityType: string, action: string) => async (endpoint: string, { userId, automationId }: { userId: string; automationId: string; }): Promise<void> => {\n if (process.env.DISABLE_AUDIT_LOGS === 'true' || !auditLogger) {\n return;\n }\n const auditLogContext = getAuditLogContextAndSetToContext({\n action,\n endpoint,\n entityType,\n method: 'rabbit',\n userId,\n automationId,\n });\n\n await auditLogger.sendAuditLogContext(auditLogContext);\n};\n"],"mappings":"iMAuCA,IAAY,EAAA,SAAA,EAAL,OACL,GAAA,OAAA,SACA,EAAA,YAAA,cACA,EAAA,UAAA,YACA,EAAA,OAAA,SACA,EAAA,OA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I,IAAI,QAAS,GACjB,EAAI,IAAI,QAAS,GACjB,MAAM,GAAa,oBAAoB,IAEzC,EAAI,KAAK,SAAU,GACnB,EAAI,KAAK,QAAS,GAClB,EAAI,KAAK,QAAS,SACX,EAAK,CACZ,EAAO,MAAM,6BAA+B,KAInC,GAAyB,EAAoB,IAAmB,MAAO,EAAkB,CAAE,SAAQ,kBAA6E,CAC3L,GAAI,QAAQ,IAAI,qBAAuB,QAAU,CAAC,EAChD,OAEF,IAAM,EAAkB,EAAkC,CACxD,SACA,WACA,aACA,OAAQ,SACR,SACA,iBAGF,MAAM,EAAY,oBAAoB"}
@@ -1,2 +0,0 @@
1
- var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,a)=>(a=n==null?{}:e(i(n)),o(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));const c=s(require(`node:util`)),l=s(require(`@autofleet/zehut`)),u=s(require(`@autofleet/logger`)),d=s(require(`@autofleet/network`));let f=function(e){return e.CREATE=`create`,e.BULK_CREATE=`bulk-create`,e.BULK_EDIT=`bulk-edit`,e.DELETE=`delete`,e.UPDATE=`update`,e.CANCEL=`cancel`,e.FAIL=`fail`,e.UNASSIGN=`unassign`,e.BULK_ASSIGN=`bulk-assign`,e.REASSIGN=`reassign`,e.DISPATCH=`dispatch`,e.BULK_DISPATCH=`bulk-dispatch`,e.BULK_UPSERT=`bulk-upsert`,e.UPSERT=`upsert`,e.JOIN=`join`,e.MOVE=`move`,e.REOPTIMIZATION=`reoptimization`,e}({}),p=function(e){return e.RIDE=`Ride`,e.VEHICLE=`Vehicle`,e.DRIVER=`Driver`,e.PRICE_CALCULATION=`PriceCalculation`,e}({}),m=function(e){return e.USER=`user`,e.AUTOMATION=`automation`,e}({});const h=`audit-log-context`,g=`audit-log-rows`,_=`auditLogContext`,v=`x-af-automation-id`,y=(0,u.default)();y.addContextMiddleware(()=>({traceId:l.outbreak.getCurrentContextTraceId()}));var b=y;const x=`customFields`,S=()=>{let e=(0,l.getCurrentPayload)(),t=e?.nonHeaderContext?.get(_);return t},C={[f.BULK_CREATE]:f.BULK_CREATE,[f.BULK_EDIT]:f.BULK_EDIT,[f.BULK_ASSIGN]:f.BULK_ASSIGN,[f.BULK_DISPATCH]:f.BULK_DISPATCH,[f.BULK_UPSERT]:f.BULK_UPSERT},w=e=>[null,void 0].includes(e)?!0:Array.isArray(e)?e.length===0:typeof e==`object`&&!(e instanceof Date)?Object.keys(e).length===0:!1,T=e=>!Object.hasOwn(C,e),E=(e,t)=>e.filter(e=>!w(t.get(e))||!w(t.previous(e))),D=(e,t)=>{let n=t.returning?t.fields:e.changed(),r=E(n.filter(e=>e!==x),e);return r.map(t=>({property:t,previousValue:e.previous(t),newValue:e.get(t)}))},O=e=>{let t=e.changed(),n=t&&t.includes(x);if(!n)return[];let r=e.get(x),i=e.previous(x),a=Object.keys(r).filter(e=>{let t=r?.[e],n=i?.[e];return(!w(t)||!w(n))&&!(0,c.isDeepStrictEqual)(t,n)});return a.map(e=>({property:`${x}.${e}`,previousValue:i?.[e],newValue:r?.[e]}))};var k=class{rabbit;sequelize;logger;excludeModels;constructor(e){this.rabbit=e.rabbit,this.sequelize=e.sequelize,this.logger=e.logger||b,this.excludeModels=e.excludeModels??[]}async manualSendAuditLog({auditContext:e,...t},n=this.logAndThrowError){if(e??=S(),e)try{e?.entityType?.toLowerCase()===t.entityType?.toLowerCase()&&T(e.action)&&(e.entityId=t.entityId),await this.rabbit.sendToQueue(g,t)}catch(e){n(e,t)}}registerHooks(){Object.entries(this.sequelize.models).forEach(([e,t])=>{this.excludeModels.includes(e)||t.addHook(`afterSave`,async(t,n)=>{let r=S();if(!r)return;let{id:i}=t;await this.manualSendAuditLog({entityId:i,auditContext:r,entityType:e,rows:[...D(t,n),...O(t)]},this.logError)})})}async sendAuditLogContext(e){try{await this.rabbit.sendToQueue(h,e)}catch(e){this.logger.error(`Failed to send audit log context`,e)}}logError=(e,t)=>{let{entityType:n,entityId:r}=t;this.logger.error(`Failed to send audit log rows`,{entityType:n,entityId:r,error:e})};logAndThrowError=(e,t)=>{throw this.logError(e,t),e}},A=k;const j=new d.default({serviceName:`AUDIT_MS`,timeout:6e4,logger:b}),M=async e=>{let{data:t}=await j.get(`api/v1/audit-logs/${e}`);return t},N={getByEntityId:M};var P=N;let F;const I=e=>process.env.DISABLE_AUDIT_LOGS===`true`?!1:(F=new A(e),F.registerHooks(),F),L=({action:e,endpoint:t,entityType:n,method:r,automationId:i,userId:a})=>{let o=a||(i??null),s=a&&m.USER||i&&m.AUTOMATION||null,c={entityType:n,action:e,endpoint:t,method:r,performedBy:o,actionOrigin:s},u=(0,l.getCurrentPayload)();return u.nonHeaderContext.set(_,c),c},R=async(e,t,n,r)=>{try{if(process.env.DISABLE_AUDIT_LOGS===`true`||!F)return;let i=L({action:r,endpoint:e.url,entityType:n,method:e.method,userId:(0,l.getUser)()?.id,automationId:e.headers[v]});if(!T(r)){await F.sendAuditLogContext(i);return}let a=async()=>{t.off(`finish`,a),t.off(`close`,a),t.off(`error`,a),await F?.sendAuditLogContext(i)};t.once(`finish`,a),t.once(`close`,a),t.once(`error`,a)}catch(e){b.error(`couldn't set audit context`,e)}},z=(e,t)=>async(n,{userId:r,automationId:i})=>{if(process.env.DISABLE_AUDIT_LOGS===`true`||!F)return;let a=L({action:t,endpoint:n,entityType:e,method:`rabbit`,userId:r,automationId:i});await F.sendAuditLogContext(a)};Object.defineProperty(exports,`AUDIT_LOG_CONTEXT_KEY`,{enumerable:!0,get:function(){return _}}),Object.defineProperty(exports,`AUDIT_LOG_CONTEXT_QUEUE`,{enumerable:!0,get:function(){return h}}),Object.defineProperty(exports,`AUDIT_LOG_ROWS_QUEUE`,{enumerable:!0,get:function(){return g}}),Object.defineProperty(exports,`AUTOMATION_ID_HEADER`,{enumerable:!0,get:function(){return v}}),Object.defineProperty(exports,`Action`,{enumerable:!0,get:function(){return f}}),Object.defineProperty(exports,`ActionOrigin`,{enumerable:!0,get:function(){return m}}),Object.defineProperty(exports,`EntityType`,{enumerable:!0,get:function(){return p}}),Object.defineProperty(exports,`__toESM`,{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,`audit_logger_default`,{enumerable:!0,get:function(){return A}}),Object.defineProperty(exports,`audit_ms_default`,{enumerable:!0,get:function(){return P}}),Object.defineProperty(exports,`innerEnableAuditing`,{enumerable:!0,get:function(){return I}}),Object.defineProperty(exports,`innerSetAuditContext`,{enumerable:!0,get:function(){return R}}),Object.defineProperty(exports,`setRabbitAuditContext`,{enumerable:!0,get:function(){return z}});
2
- //# sourceMappingURL=common-CLXNjq7Z.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"common-CLXNjq7Z.cjs","names":["logger: LoggerInstanceManager","outbreak","changedFields: string[]","logger","Network","exportObj: { getByEntityId: typeof getByEntityId; }","auditLogger: AuditLogger | undefined","AuditLogger","auditLogContext: AuditLogContext"],"sources":["../src/types.ts","../src/const.ts","../src/logger.ts","../src/audit-logger.ts","../src/audit-ms.ts","../src/common.ts"],"sourcesContent":["import type { ModelStatic, Model } from 'sequelize';\nimport type { Sequelize } from 'sequelize-typescript';\nimport type RabbitMq from '@autofleet/rabbit';\nimport type { LoggerInstanceManager } from '@autofleet/logger';\nimport type { IRouter } from 'express';\nimport type { FastifyInstance } from 'fastify';\n\nexport interface AuditLoggerOptions {\n rabbit: RabbitMq;\n sequelize: Sequelize;\n logger: LoggerInstanceManager;\n router?: IRouter;\n fastify?: FastifyInstance;\n excludeModels?: string[];\n entityScopedModelMap?: Record<string, ModelStatic<Model>>;\n}\n\nexport interface AuditLogContext {\n entityType: string;\n entityId?: string;\n action: string;\n performedBy: string | null;\n endpoint: string;\n method: string;\n actionOrigin?: string | null;\n}\n\nexport interface AuditLogRow {\n property: string;\n previousValue: unknown;\n newValue: unknown;\n}\n\nexport interface AuditLogPayload {\n entityType: string;\n entityId: string;\n rows: readonly AuditLogRow[];\n}\n\nexport enum Action {\n CREATE = 'create',\n BULK_CREATE = 'bulk-create',\n BULK_EDIT = 'bulk-edit',\n DELETE = 'delete',\n UPDATE = 'update',\n CANCEL = 'cancel',\n FAIL = 'fail',\n UNASSIGN = 'unassign',\n BULK_ASSIGN = 'bulk-assign',\n REASSIGN = 'reassign',\n DISPATCH = 'dispatch',\n BULK_DISPATCH = 'bulk-dispatch',\n BULK_UPSERT = 'bulk-upsert',\n UPSERT = 'upsert',\n JOIN = 'join',\n MOVE = 'move',\n REOPTIMIZATION = 'reoptimization',\n}\n\nexport enum EntityType {\n RIDE = 'Ride',\n VEHICLE = 'Vehicle',\n DRIVER = 'Driver',\n PRICE_CALCULATION = 'PriceCalculation',\n}\n\nexport const enum ActionOrigin {\n USER = 'user',\n AUTOMATION = 'automation',\n}\n","export const AUDIT_LOG_CONTEXT_QUEUE = 'audit-log-context';\nexport const AUDIT_LOG_ROWS_QUEUE = 'audit-log-rows';\nexport const AUDIT_LOG_CONTEXT_KEY = 'auditLogContext';\nexport const AUTOMATION_ID_HEADER = 'x-af-automation-id';\n","import { outbreak } from '@autofleet/zehut';\nimport Logger, { type LoggerInstanceManager } from '@autofleet/logger';\n\nconst logger: LoggerInstanceManager = Logger();\nlogger.addContextMiddleware(() => ({ traceId: outbreak.getCurrentContextTraceId() }));\nexport default logger;\n","import { isDeepStrictEqual } from 'node:util';\nimport type RabbitMq from '@autofleet/rabbit';\nimport type { LoggerInstanceManager } from '@autofleet/logger';\nimport { getCurrentPayload as getCurrentTrace } from '@autofleet/zehut';\nimport type {\n CreateOptions, InstanceUpdateOptions, Model, Sequelize,\n} from 'sequelize';\nimport {\n type AuditLogPayload, type AuditLoggerOptions, type AuditLogContext, Action, type AuditLogRow,\n} from './types';\nimport { AUDIT_LOG_CONTEXT_QUEUE, AUDIT_LOG_ROWS_QUEUE, AUDIT_LOG_CONTEXT_KEY } from './const';\nimport logger from './logger';\n\nconst CUSTOM_FIELDS_PROPERTY = 'customFields';\n\nconst getAuditContext = () => {\n const currentTrace = getCurrentTrace();\n const auditContext = currentTrace?.nonHeaderContext?.get(AUDIT_LOG_CONTEXT_KEY);\n return auditContext as AuditLogContext;\n};\n\nconst ACTIONS_TO_OMIT_ENTITY_ID_FROM_CONTEXT = {\n [Action.BULK_CREATE]: Action.BULK_CREATE,\n [Action.BULK_EDIT]: Action.BULK_EDIT,\n [Action.BULK_ASSIGN]: Action.BULK_ASSIGN,\n [Action.BULK_DISPATCH]: Action.BULK_DISPATCH,\n [Action.BULK_UPSERT]: Action.BULK_UPSERT,\n};\n\nconst isEmpty = (field: unknown): boolean => {\n if ([null, undefined].includes(field as undefined)) {\n return true;\n }\n if (Array.isArray(field)) {\n return field.length === 0;\n }\n if (typeof field === 'object' && !(field instanceof Date)) {\n return Object.keys(field as Record<string, unknown>).length === 0;\n }\n return false;\n};\n\nexport const isEntityIdRequired = (action: string): boolean => !Object.hasOwn(ACTIONS_TO_OMIT_ENTITY_ID_FROM_CONTEXT, action);\n\nconst filterOutEmptyFields = (fields: string[], instance: Model) => fields.filter(field => !isEmpty(instance.get(field)) || !isEmpty(instance.previous(field)));\n\nconst getChangedFieldsRows = (instance: Model, options: CreateOptions | InstanceUpdateOptions): AuditLogRow[] => {\n // When bulk updating in sequelize using the \"returning\" option, the instance.changed() stops working.\n // It's a known issue with sequelize.\n const changedFields: string[] = options.returning ? options.fields as string[] : instance.changed() as string[];\n // Filter customFields - we'll handle them later\n const filteredChangedFields = filterOutEmptyFields(changedFields.filter(field => field !== CUSTOM_FIELDS_PROPERTY), instance);\n return filteredChangedFields.map((property: string) => ({\n property,\n previousValue: instance.previous(property),\n newValue: instance.get(property),\n }));\n};\n\nconst getChangedCustomFieldsRows = (instance: Model): AuditLogRow[] => {\n // Based on the comment in getChangedFieldsRows, we cannot rely on instance.changed() when doing bulk updates with \"returning\".\n // So this seems like a possible bug.\n const changed = instance.changed();\n const customFieldsChanged = changed && changed.includes(CUSTOM_FIELDS_PROPERTY);\n if (!customFieldsChanged) {\n return [];\n }\n\n const customFields = instance.get(CUSTOM_FIELDS_PROPERTY) as Record<string, unknown>;\n const previousCustomFields = instance.previous(CUSTOM_FIELDS_PROPERTY);\n const changedCustomFields = Object.keys(customFields).filter((field) => {\n const newValue = customFields?.[field];\n const oldValue = previousCustomFields?.[field];\n return (!isEmpty(newValue) || !isEmpty(oldValue)) && !isDeepStrictEqual(newValue, oldValue);\n });\n return changedCustomFields.map(changedCustomField => ({\n property: `${CUSTOM_FIELDS_PROPERTY}.${changedCustomField}`,\n previousValue: previousCustomFields?.[changedCustomField],\n newValue: customFields?.[changedCustomField],\n }));\n};\n\ninterface AuditLogSendData extends AuditLogPayload {\n auditContext?: AuditLogContext;\n}\n\ntype AuditLogRowSendingErrorHandler = (error: unknown, payload: AuditLogPayload) => void;\n\nclass AuditLogger {\n private readonly rabbit: RabbitMq;\n\n private readonly sequelize: Sequelize;\n\n private readonly logger: LoggerInstanceManager;\n\n private readonly excludeModels: string[];\n\n constructor(options: AuditLoggerOptions) {\n this.rabbit = options.rabbit;\n this.sequelize = options.sequelize;\n this.logger = options.logger || logger;\n this.excludeModels = options.excludeModels ?? [];\n }\n\n public async manualSendAuditLog(\n { auditContext, ...payload }: AuditLogSendData,\n errorHandler: AuditLogRowSendingErrorHandler = this.logAndThrowError,\n ): Promise<void> {\n auditContext ??= getAuditContext();\n if (!auditContext) {\n return;\n }\n try {\n // Make sure the current entity being changed it the \"main\" entity in the current audit context, and if so mark it as the \"entityId\".\n if (auditContext?.entityType?.toLowerCase() === payload.entityType?.toLowerCase() && isEntityIdRequired(auditContext.action)) {\n auditContext.entityId = payload.entityId;\n }\n await this.rabbit.sendToQueue(AUDIT_LOG_ROWS_QUEUE, payload);\n } catch (error) {\n errorHandler(error, payload);\n }\n }\n\n public registerHooks(): void {\n Object.entries(this.sequelize.models).forEach(([modelName, modelType]) => {\n if (this.excludeModels.includes(modelName)) {\n return;\n }\n modelType.addHook('afterSave', async (instance, options) => {\n const auditContext = getAuditContext();\n if (!auditContext) return;\n\n const { id: entityId } = instance as unknown as { id: string; };\n await this.manualSendAuditLog(\n {\n entityId,\n auditContext,\n entityType: modelName,\n rows: [...getChangedFieldsRows(instance, options), ...getChangedCustomFieldsRows(instance)],\n },\n this.logError,\n );\n });\n });\n }\n\n public async sendAuditLogContext(context: AuditLogContext): Promise<void> {\n try {\n await this.rabbit.sendToQueue(AUDIT_LOG_CONTEXT_QUEUE, context);\n } catch (err) {\n this.logger.error('Failed to send audit log context', err);\n }\n }\n\n private logError: AuditLogRowSendingErrorHandler = (error: unknown, payload: AuditLogPayload) => {\n const { entityType, entityId } = payload;\n this.logger.error('Failed to send audit log rows', { entityType, entityId, error });\n };\n\n private logAndThrowError: AuditLogRowSendingErrorHandler = (error: unknown, payload: AuditLogPayload): never => {\n this.logError(error, payload);\n throw error;\n };\n}\n\nexport default AuditLogger;\n","import Network from '@autofleet/network';\nimport logger from './logger';\n\nconst auditMs = new Network({ serviceName: 'AUDIT_MS', timeout: 60_000, logger });\n\nconst getByEntityId = async (entityId: string): Promise<any> => {\n const { data } = await auditMs.get(`api/v1/audit-logs/${entityId}`);\n return data;\n};\n\nconst exportObj: { getByEntityId: typeof getByEntityId; } = { getByEntityId };\n\nexport default exportObj;\n","import type { Writable } from 'node:stream';\nimport type { IncomingHttpHeaders } from 'node:http';\nimport { getCurrentPayload, getUser } from '@autofleet/zehut';\nimport logger from './logger';\nimport AuditLogger, { isEntityIdRequired } from './audit-logger';\nimport { AUDIT_LOG_CONTEXT_KEY, AUTOMATION_ID_HEADER } from './const';\nimport { ActionOrigin, type AuditLogContext, type AuditLoggerOptions } from './types';\n\nlet auditLogger: AuditLogger | undefined;\n\nexport const innerEnableAuditing = (options: AuditLoggerOptions): false | AuditLogger => {\n if (process.env.DISABLE_AUDIT_LOGS === 'true') {\n return false;\n }\n auditLogger = new AuditLogger(options);\n auditLogger.registerHooks();\n return auditLogger;\n};\n\ninterface GetAuditLogContextParams {\n action: string;\n endpoint: string;\n entityType: string;\n method: string;\n automationId?: string;\n userId?: string;\n}\nconst getAuditLogContextAndSetToContext = ({\n action, endpoint, entityType, method, automationId, userId,\n}: GetAuditLogContextParams): AuditLogContext => {\n const performedBy = userId || (automationId ?? null);\n const actionOrigin = (userId && ActionOrigin.USER) || (automationId && ActionOrigin.AUTOMATION) || null;\n\n const auditLogContext: AuditLogContext = {\n entityType,\n action,\n endpoint,\n method,\n performedBy,\n actionOrigin,\n };\n const currentTrace = getCurrentPayload();\n currentTrace.nonHeaderContext.set(AUDIT_LOG_CONTEXT_KEY, auditLogContext);\n\n return auditLogContext;\n};\n\ninterface PartialRequest {\n url: string;\n method: string;\n headers: IncomingHttpHeaders;\n}\n\nexport const innerSetAuditContext = async (req: PartialRequest, res: Writable, entityType: string, action: string): Promise<void> => {\n try {\n if (process.env.DISABLE_AUDIT_LOGS === 'true' || !auditLogger) {\n return;\n }\n const auditLogContext = getAuditLogContextAndSetToContext({\n action,\n endpoint: req.url,\n entityType,\n method: req.method,\n userId: getUser()?.id,\n automationId: req.headers[AUTOMATION_ID_HEADER] as string | undefined,\n });\n\n if (!isEntityIdRequired(action)) { // if it's a bulk action, we don't want to wait for the response to add the entity id\n await auditLogger.sendAuditLogContext(auditLogContext);\n return;\n }\n\n const sendAuditLogContextEvent = async () => {\n res.off('finish', sendAuditLogContextEvent);\n res.off('close', sendAuditLogContextEvent);\n res.off('error', sendAuditLogContextEvent);\n await auditLogger?.sendAuditLogContext(auditLogContext);\n };\n res.once('finish', sendAuditLogContextEvent);\n res.once('close', sendAuditLogContextEvent);\n res.once('error', sendAuditLogContextEvent);\n } catch (err) {\n logger.error('couldn\\'t set audit context', err);\n }\n};\n\nexport const setRabbitAuditContext = (entityType: string, action: string) => async (endpoint: string, { userId, automationId }: { userId: string; automationId: string; }): Promise<void> => {\n if (process.env.DISABLE_AUDIT_LOGS === 'true' || !auditLogger) {\n return;\n }\n const auditLogContext = getAuditLogContextAndSetToContext({\n action,\n endpoint,\n entityType,\n method: 'rabbit',\n userId,\n automationId,\n });\n\n await auditLogger.sendAuditLogContext(auditLogContext);\n};\n"],"mappings":"omBAuCA,IAAY,EAAA,SAAA,EAAL,OACL,GAAA,OAAA,SACA,EAAA,YAAA,cACA,EAAA,UAAA,YACA,EAAA,OAAA,SACA,EAAA,OAAA,SACA,EAAA,OAAA,SACA,EAAA,KAAA,OACA,EAAA,SAAA,WACA,EAAA,YAAA,cACA,EAAA,SAAA,WACA,EAAA,SAAA,WACA,EAAA,cAAA,gBACA,EAAA,YAAA,cACA,EAAA,OAAA,SACA,EAAA,KAAA,OACA,EAAA,KAAA,OACA,EAAA,eAAA,wBAGU,EAAA,SAAA,EAAL,OACL,GAAA,KAAA,OACA,EAAA,QAAA,UACA,EAAA,OAAA,SACA,EAAA,kBAAA,0BAGgB,EAAA,SAAA,EAAX,OACL,GAAA,KAAA,OACA,EAAA,WAAA,oBCpEF,MAAa,EAA0B,oBAC1B,EAAuB,iBACvB,EAAwB,kBACxB,EAAuB,qBCA9BA,GAAAA,EAAAA,EAAAA,WACN,EAAO,0BAA4B,CAAE,QAASC,EAAAA,SAAS,8BACvD,IAAA,EAAe,ECQf,MAAM,EAAyB,eAEzB,MAAwB,CAC5B,IAAM,GAAA,EAAA,EAAA,qBACA,EAAe,GAAc,kBAAkB,IAAI,GACzD,OAAO,GAGH,EAAyC,EAC5C,EAAO,aAAc,EAAO,aAC5B,EAAO,WAAY,EAAO,WAC1B,EAAO,aAAc,EAAO,aAC5B,EAAO,eAAgB,EAAO,eAC9B,EAAO,aAAc,EAAO,aAGzB,EAAW,GACX,CAAC,KAAM,IAAA,IAAW,SAAS,GACtB,GAEL,MAAM,QAAQ,GACT,EAAM,SAAW,EAEtB,OAAO,GAAU,U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