@autofleet/shtinker 3.2.1-beta-81f8d75f.0 → 3.4.0

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
+ "use strict";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/outbreak`)),d=s(require(`@autofleet/logger`)),f=s(require(`@autofleet/network`));let p=/* @__PURE__ */ 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}({}),m=/* @__PURE__ */ function(e){return e.RIDE=`Ride`,e.VEHICLE=`Vehicle`,e.DRIVER=`Driver`,e.PRICE_CALCULATION=`PriceCalculation`,e}({}),h=/* @__PURE__ */ function(e){return e.USER=`user`,e.AUTOMATION=`automation`,e}({});const g=`audit-log-context`,_=`audit-log-rows`,v=`auditLogContext`,y=`x-af-automation-id`,b=(0,d.default)();b.addContextMiddleware(()=>({traceId:(0,u.getCurrentContextTraceId)()}));var x=b;const S=`customFields`,C=()=>{let e=(0,l.getCurrentPayload)(),t=e?.nonHeaderContext?.get(v);return t},w={[p.BULK_CREATE]:p.BULK_CREATE,[p.BULK_EDIT]:p.BULK_EDIT,[p.BULK_ASSIGN]:p.BULK_ASSIGN,[p.BULK_DISPATCH]:p.BULK_DISPATCH,[p.BULK_UPSERT]:p.BULK_UPSERT},T=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,E=e=>Object.hasOwn(w,e),D=(e,t)=>e.filter(e=>!T(t.get(e))||!T(t.previous(e))),O=(e,t)=>{let n=t.returning?t.fields:e.changed(),r=D(n.filter(e=>e!==S),e);return r.map(t=>({property:t,previousValue:e.previous(t),newValue:e.get(t)}))},k=e=>{let t=e.changed(),n=t&&t.includes(S);if(!n)return[];let r=e.get(S),i=e.previous(S),a=Object.keys(r).filter(e=>{let t=r?.[e],n=i?.[e];return(!T(t)||!T(n))&&!(0,c.isDeepStrictEqual)(t,n)});return a.map(e=>({property:`${S}.${e}`,previousValue:i?.[e],newValue:r?.[e]}))};var A=class{constructor(e){this.rabbit=e.rabbit,this.sequelize=e.sequelize,this.logger=e.logger||x,this.excludeModels=e.excludeModels??[]}async manualSendAuditLog({auditContext:e,...t}){if(e??=C(),e)try{e?.entityType?.toLowerCase()===t.entityType?.toLowerCase()&&E(e.action)&&(e.entityId=t.entityId),await this.sendAuditLogRows(t)}catch(e){let{entityType:n,entityId:r}=t;this.logger.error(`Failed to send audit log rows`,{entityType:n,entityId:r,error:e})}}registerHooks(){Object.entries(this.sequelize.models).forEach(([e,t])=>{this.excludeModels.includes(e)||t.addHook(`afterSave`,async(t,n)=>{let r=C();if(!r)return;let{id:i}=t;await this.manualSendAuditLog({entityId:i,auditContext:r,entityType:e,rows:[...O(t,n),...k(t)]})})})}async sendAuditLogContext(e){try{await this.rabbit.sendToQueue(g,e)}catch(e){this.logger.error(`Failed to send audit log context`,e)}}async sendAuditLogRows(e){try{await this.rabbit.sendToQueue(_,e)}catch(e){this.logger.error(`Failed to send audit log rows`,e)}}},j=A;const M=new f.default({serviceName:`AUDIT_MS`,timeout:6e4,logger:x}),N=async e=>{let{data:t}=await M.get(`api/v1/audit-logs/${e}`);return t},P={getByEntityId:N};var F=P;let I;const L=e=>process.env.DISABLE_AUDIT_LOGS===`true`?!1:(I=new j(e),I.registerHooks(),!0),R=({action:e,endpoint:t,entityType:n,method:r,automationId:i,userId:a})=>{let o=a||(i??null),s=a&&h.USER||i&&h.AUTOMATION||null,c={entityType:n,action:e,endpoint:t,method:r,performedBy:o,actionOrigin:s},u=(0,l.getCurrentPayload)();return u.nonHeaderContext.set(v,c),c},z=async(e,t,n,r)=>{try{if(process.env.DISABLE_AUDIT_LOGS===`true`||!I)return;let i=R({action:r,endpoint:e.url,entityType:n,method:e.method,userId:(0,l.getUser)()?.id,automationId:e.headers[y]});if(!E(r)){await I.sendAuditLogContext(i);return}let a=async()=>{t.off(`finish`,a),t.off(`close`,a),t.off(`error`,a),await I?.sendAuditLogContext(i)};t.once(`finish`,a),t.once(`close`,a),t.once(`error`,a)}catch(e){x.error(`couldn't set audit context`,e)}},B=(e,t)=>async(n,{userId:r,automationId:i})=>{if(process.env.DISABLE_AUDIT_LOGS===`true`||!I)return;let a=R({action:t,endpoint:n,entityType:e,method:`rabbit`,userId:r,automationId:i});await I.sendAuditLogContext(a)};Object.defineProperty(exports,`AUDIT_LOG_CONTEXT_KEY`,{enumerable:!0,get:function(){return v}}),Object.defineProperty(exports,`AUDIT_LOG_CONTEXT_QUEUE`,{enumerable:!0,get:function(){return g}}),Object.defineProperty(exports,`AUDIT_LOG_ROWS_QUEUE`,{enumerable:!0,get:function(){return _}}),Object.defineProperty(exports,`AUTOMATION_ID_HEADER`,{enumerable:!0,get:function(){return y}}),Object.defineProperty(exports,`Action`,{enumerable:!0,get:function(){return p}}),Object.defineProperty(exports,`ActionOrigin`,{enumerable:!0,get:function(){return h}}),Object.defineProperty(exports,`EntityType`,{enumerable:!0,get:function(){return m}}),Object.defineProperty(exports,`__toESM`,{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,`audit_logger_default`,{enumerable:!0,get:function(){return j}}),Object.defineProperty(exports,`audit_ms_default`,{enumerable:!0,get:function(){return F}}),Object.defineProperty(exports,`innerEnableAuditing`,{enumerable:!0,get:function(){return L}}),Object.defineProperty(exports,`innerSetAuditContext`,{enumerable:!0,get:function(){return z}}),Object.defineProperty(exports,`setRabbitAuditContext`,{enumerable:!0,get:function(){return B}});
2
+ //# sourceMappingURL=common-DLsvf3zA.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"common-DLsvf3zA.cjs","names":["logger: LoggerInstanceManager","field: unknown","action: string","fields: string[]","instance: Model","options: CreateOptions | InstanceUpdateOptions","changedFields: string[]","property: string","options: AuditLoggerOptions","context: AuditLogContext","payload: AuditLogPayload","entityId: string","exportObj: { getByEntityId: typeof getByEntityId }","auditLogger: AuditLogger | undefined","options: AuditLoggerOptions","auditLogContext: AuditLogContext","req: PartialRequest","res: Writable","entityType: string","action: string","endpoint: string"],"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 type AuditLoggerOptions = {\n rabbit: RabbitMq;\n sequelize: Sequelize;\n logger: LoggerInstanceManager;\n router?: IRouter;\n fastify?: FastifyInstance;\n excludeModels?: string[];\n entityScopedModelMap?: { [modelName: 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 { getCurrentContextTraceId } from '@autofleet/outbreak';\nimport Logger, { type LoggerInstanceManager } from '@autofleet/logger';\n\nconst logger: LoggerInstanceManager = Logger();\nlogger.addContextMiddleware(() => ({ traceId: 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 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\nclass AuditLogger {\n private rabbit: RabbitMq;\n\n private sequelize: Sequelize;\n\n private logger: LoggerInstanceManager;\n\n private 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\n }: AuditLogSendData): 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.sendAuditLogRows(payload);\n } catch (error) {\n const { entityType, entityId } = payload;\n this.logger.error('Failed to send audit log rows', { entityType, entityId, error });\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 entityId,\n auditContext,\n entityType: modelName,\n rows: [...getChangedFieldsRows(instance, options), ...getChangedCustomFieldsRows(instance)],\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 async sendAuditLogRows(payload: AuditLogPayload): Promise<void> {\n try {\n await this.rabbit.sendToQueue(AUDIT_LOG_ROWS_QUEUE, payload);\n } catch (err) {\n this.logger.error('Failed to send audit log rows', err);\n }\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): boolean => {\n if (process.env.DISABLE_AUDIT_LOGS === 'true') {\n return false;\n }\n auditLogger = new AuditLogger(options);\n auditLogger.registerHooks();\n return true;\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":"qpBAkEA,IA3BY,kBAAA,SAAA,EAAL,QACL,EAAA,OAAA,SACA,EAAA,YAAA,cACA,EAAA,UAAA,YACA,EAAA,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,aACA,OAAQ,SACR,SACA,cACD,EAAC,CAEF,KAAM,GAAY,oBAAoB,EAAgB,AACvD"}
@@ -0,0 +1,2 @@
1
+ import{isDeepStrictEqual as e}from"node:util";import{getCurrentPayload as t,getUser as n}from"@autofleet/zehut";import{getCurrentContextTraceId as r}from"@autofleet/outbreak";import i from"@autofleet/logger";import a from"@autofleet/network";let o=/* @__PURE__ */ 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=/* @__PURE__ */ function(e){return e.RIDE=`Ride`,e.VEHICLE=`Vehicle`,e.DRIVER=`Driver`,e.PRICE_CALCULATION=`PriceCalculation`,e}({}),c=/* @__PURE__ */ 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()}));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{constructor(e){this.rabbit=e.rabbit,this.sequelize=e.sequelize,this.logger=e.logger||m,this.excludeModels=e.excludeModels??[]}async manualSendAuditLog({auditContext:e,...t}){if(e??=g(),e)try{e?.entityType?.toLowerCase()===t.entityType?.toLowerCase()&&y(e.action)&&(e.entityId=t.entityId),await this.sendAuditLogRows(t)}catch(e){let{entityType:n,entityId:r}=t;this.logger.error(`Failed to send audit log rows`,{entityType:n,entityId:r,error:e})}}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)]})})})}async sendAuditLogContext(e){try{await this.rabbit.sendToQueue(l,e)}catch(e){this.logger.error(`Failed to send audit log context`,e)}}async sendAuditLogRows(e){try{await this.rabbit.sendToQueue(u,e)}catch(e){this.logger.error(`Failed to send audit log rows`,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(),!0),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-oy2ugNvX.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"common-oy2ugNvX.js","names":["logger: LoggerInstanceManager","field: unknown","action: string","fields: string[]","instance: Model","options: CreateOptions | InstanceUpdateOptions","changedFields: string[]","property: string","options: AuditLoggerOptions","context: AuditLogContext","payload: AuditLogPayload","entityId: string","exportObj: { getByEntityId: typeof getByEntityId }","auditLogger: AuditLogger | undefined","options: AuditLoggerOptions","auditLogContext: AuditLogContext","req: PartialRequest","res: Writable","entityType: string","action: string","endpoint: string"],"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 type AuditLoggerOptions = {\n rabbit: RabbitMq;\n sequelize: Sequelize;\n logger: LoggerInstanceManager;\n router?: IRouter;\n fastify?: FastifyInstance;\n excludeModels?: string[];\n entityScopedModelMap?: { [modelName: 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 { getCurrentContextTraceId } from '@autofleet/outbreak';\nimport Logger, { type LoggerInstanceManager } from '@autofleet/logger';\n\nconst logger: LoggerInstanceManager = Logger();\nlogger.addContextMiddleware(() => ({ traceId: 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 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\nclass AuditLogger {\n private rabbit: RabbitMq;\n\n private sequelize: Sequelize;\n\n private logger: LoggerInstanceManager;\n\n private 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\n }: AuditLogSendData): 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.sendAuditLogRows(payload);\n } catch (error) {\n const { entityType, entityId } = payload;\n this.logger.error('Failed to send audit log rows', { entityType, entityId, error });\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 entityId,\n auditContext,\n entityType: modelName,\n rows: [...getChangedFieldsRows(instance, options), ...getChangedCustomFieldsRows(instance)],\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 async sendAuditLogRows(payload: AuditLogPayload): Promise<void> {\n try {\n await this.rabbit.sendToQueue(AUDIT_LOG_ROWS_QUEUE, payload);\n } catch (err) {\n this.logger.error('Failed to send audit log rows', err);\n }\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): boolean => {\n if (process.env.DISABLE_AUDIT_LOGS === 'true') {\n return false;\n }\n auditLogger = new AuditLogger(options);\n auditLogger.registerHooks();\n return true;\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":"kPAkEA,IA3BY,kBAAA,SAAA,EAAL,QACL,EAAA,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,kBACD,EAAA,CAAA,EAAA,CAEW,kBAAA,SAAA,EAAL,QACL,EAAA,KAAA,OACA,EAAA,QAAA,UACA,EAAA,OAAA,SACA,EAAA,kBAAA,oBACD,EAAA,CAAA,EAAA,CAEiB,kBAAA,SAAA,EAAX,QACL,EAAA,KAAA,OACA,EAAA,WAAA,cACD,EAAA,CAAA,EAAA,CElED,MDHa,EAA0B,oBAC1B,EAAuB,iBACvB,EAAwB,kBACxB,EAAuB,qBCA9BA,EAAgC,GAAQ,CAC9C,EAAO,qBAAqB,KAAO,CAAE,QAAS,GAA0B,AAAE,GAAE,CAC5E,IAAA,EAAe,ECsDf,MA9CM,EAAyB,eAEzB,EAAkB,IAAM,CAE5B,IADM,EAAe,GAAiB,CAChC,EAAe,GAAc,kBAAkB,IAAI,EAAsB,CAC/E,OAAO,CACR,EAEK,EAAyC,EAC5C,EAAO,aAAc,EAAO,aAC5B,EAAO,WAAY,EAAO,WAC1B,EAAO,aAAc,EAAO,aAC5B,EAAO,eAAgB,EAAO,eAC9B,EAAO,aAAc,EAAO,WAC9B,EAEK,EAAU,AAACC,GACX,CAAC,SAAA,EAAgB,EAAC,SAAS,EAAmB,EACzC,EAEL,MAAM,QAA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oBC,IAAmB,MAAOC,EAAkB,CAAE,SAAQ,eAAuD,GAAoB,CACzL,GAAI,QAAQ,IAAI,qBAAuB,SAAW,EAChD,OAEF,IAAM,EAAkB,EAAkC,CACxD,SACA,WACA,aACA,OAAQ,SACR,SACA,cACD,EAAC,CAEF,KAAM,GAAY,oBAAoB,EAAgB,AACvD"}
@@ -28,13 +28,13 @@ interface AuditLogContext {
28
28
  }
29
29
  interface AuditLogRow {
30
30
  property: string;
31
- previousValue: any;
32
- newValue: any;
31
+ previousValue: unknown;
32
+ newValue: unknown;
33
33
  }
34
34
  interface AuditLogPayload {
35
35
  entityType: string;
36
36
  entityId: string;
37
- rows: AuditLogRow[];
37
+ rows: readonly AuditLogRow[];
38
38
  }
39
39
  declare enum Action {
40
40
  CREATE = "create",
@@ -66,12 +66,19 @@ declare const enum ActionOrigin {
66
66
  AUTOMATION = "automation",
67
67
  } //#endregion
68
68
  //#region src/audit-logger.d.ts
69
+ interface AuditLogSendData extends AuditLogPayload {
70
+ auditContext?: AuditLogContext;
71
+ }
69
72
  declare class AuditLogger {
70
73
  private rabbit;
71
74
  private sequelize;
72
75
  private logger;
73
76
  private excludeModels;
74
77
  constructor(options: AuditLoggerOptions);
78
+ manualSendAuditLog({
79
+ auditContext,
80
+ ...payload
81
+ }: AuditLogSendData): Promise<void>;
75
82
  registerHooks(): void;
76
83
  sendAuditLogContext(context: AuditLogContext): Promise<void>;
77
84
  private sendAuditLogRows;
@@ -96,4 +103,4 @@ declare const AUTOMATION_ID_HEADER = "x-af-automation-id";
96
103
 
97
104
  //#endregion
98
105
  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 };
99
- //# sourceMappingURL=const-CC0vE16d.d.cts.map
106
+ //# sourceMappingURL=const-ByTOLhRM.d.cts.map
@@ -28,13 +28,13 @@ interface AuditLogContext {
28
28
  }
29
29
  interface AuditLogRow {
30
30
  property: string;
31
- previousValue: any;
32
- newValue: any;
31
+ previousValue: unknown;
32
+ newValue: unknown;
33
33
  }
34
34
  interface AuditLogPayload {
35
35
  entityType: string;
36
36
  entityId: string;
37
- rows: AuditLogRow[];
37
+ rows: readonly AuditLogRow[];
38
38
  }
39
39
  declare enum Action {
40
40
  CREATE = "create",
@@ -66,12 +66,19 @@ declare const enum ActionOrigin {
66
66
  AUTOMATION = "automation",
67
67
  } //#endregion
68
68
  //#region src/audit-logger.d.ts
69
+ interface AuditLogSendData extends AuditLogPayload {
70
+ auditContext?: AuditLogContext;
71
+ }
69
72
  declare class AuditLogger {
70
73
  private rabbit;
71
74
  private sequelize;
72
75
  private logger;
73
76
  private excludeModels;
74
77
  constructor(options: AuditLoggerOptions);
78
+ manualSendAuditLog({
79
+ auditContext,
80
+ ...payload
81
+ }: AuditLogSendData): Promise<void>;
75
82
  registerHooks(): void;
76
83
  sendAuditLogContext(context: AuditLogContext): Promise<void>;
77
84
  private sendAuditLogRows;
@@ -96,4 +103,4 @@ declare const AUTOMATION_ID_HEADER = "x-af-automation-id";
96
103
 
97
104
  //#endregion
98
105
  export { AUDIT_LOG_CONTEXT_KEY as AUDIT_LOG_CONTEXT_KEY$1, AUDIT_LOG_CONTEXT_QUEUE as AUDIT_LOG_CONTEXT_QUEUE$1, AUDIT_LOG_ROWS_QUEUE as AUDIT_LOG_ROWS_QUEUE$1, AUTOMATION_ID_HEADER as AUTOMATION_ID_HEADER$1, Action as Action$1, ActionOrigin as ActionOrigin$1, AuditLogContext, AuditLogPayload, AuditLogRow, AuditLogger, AuditLoggerOptions, EntityType as EntityType$1, setRabbitAuditContext as setRabbitAuditContext$1 };
99
- //# sourceMappingURL=const-DrgE261l.d.ts.map
106
+ //# sourceMappingURL=const-DTsi7GAD.d.ts.map
package/dist/fastify.cjs CHANGED
@@ -1,9 +1,11 @@
1
- "use strict";Object.defineProperty(exports,`__esModule`,{value:!0});const e=require(`./common-BWTPt3jo.cjs`),t=e.__toESM(require(`@autofleet/errors`));async function n({fastify:n,logger:r,entityScopedModelMap:i}){!i||!n||Object.entries(i).forEach(([i,a])=>{n.get(`/api/v1/${i}/:id/audit`,{schema:{tags:[`audit`],description:`Get audit logs for ${i} by ID`,params:{type:`object`,properties:{id:{type:`string`}},required:[`id`]}}},async n=>{let{id:o}=n.params,s=await a.findByPk(o);if(!s){let e=new t.ResourceNotFoundError;throw r.error(`Entity ${i} with id ${o} not found`,{err:e}),e}return e.audit_ms_default.getByEntityId(o)})})}
1
+ "use strict";Object.defineProperty(exports,`__esModule`,{value:!0});
2
+ /** Swagger tag for audit logs API. Add this to the `tags` array passed into the options of `fastify-plugin`. */
3
+ const e=require(`./common-DLsvf3zA.cjs`),t=e.__toESM(require(`@autofleet/errors`)),n={name:`audit`,description:`Audit logs API`};async 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)})})}
2
4
  /**
3
5
  * A builder of `onRequest` hook for the request handler, which sets the audit context for the request lifecycle.
4
6
  * @param entityType The type of the entity being audited.
5
7
  * @param action The action being performed on the entity.
6
8
  * @returns A Fastify `onRequest` hook.
7
9
  */
8
- const r=t=>{e.innerEnableAuditing(t),n(t)},i=(t,n)=>async(r,i)=>{await e.innerSetAuditContext(r,i.raw,t,n)};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;
10
+ const i=t=>{let n=e.innerEnableAuditing(t);n&&r(t)},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;
9
11
  //# sourceMappingURL=fastify.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"fastify.cjs","names":["options: AuditLoggerOptions","entityType: string","action: string"],"sources":["../src/audit-api/fastify.ts","../src/fastify.ts"],"sourcesContent":["import { ResourceNotFoundError } from '@autofleet/errors';\nimport auditMs from '../audit-ms';\nimport type { AuditLoggerOptions } from '../types';\n\nexport async function addAuditApi({ fastify, logger, entityScopedModelMap }: AuditLoggerOptions): Promise<void> {\n if (!entityScopedModelMap || !fastify) {\n return;\n }\n Object.entries(entityScopedModelMap).forEach(([entity, ScopedModel]) => {\n fastify.get(\n `/api/v1/${entity}/:id/audit`,\n {\n schema: {\n tags: ['audit'],\n description: `Get audit logs for ${entity} by ID`,\n params: {\n type: 'object',\n properties: {\n id: { type: 'string' },\n },\n required: ['id'],\n },\n },\n },\n async (req) => {\n const { id } = req.params as { id: string; };\n const entityData = await ScopedModel.findByPk(id);\n if (!entityData) {\n const err = new ResourceNotFoundError();\n logger.error(`Entity ${entity} with id ${id} not found`, { err });\n throw err;\n }\n return auditMs.getByEntityId(id);\n },\n );\n });\n}\n","import type { onRequestAsyncHookHandler } from 'fastify';\nimport AuditLogger from './audit-logger';\nimport { addAuditApi } from './audit-api/fastify';\nimport type { AuditLoggerOptions } from './types';\nimport { innerEnableAuditing, innerSetAuditContext, setRabbitAuditContext } from './common';\n\nexport const enableAuditing = (options: AuditLoggerOptions): void => {\n innerEnableAuditing(options);\n addAuditApi(options);\n};\n\n/**\n * A builder of `onRequest` hook for the request handler, which sets the audit context for the request lifecycle.\n * @param entityType The type of the entity being audited.\n * @param action The action being performed on the entity.\n * @returns A Fastify `onRequest` hook.\n */\nexport const setAuditContext = (entityType: string, action: string): onRequestAsyncHookHandler => async (request, reply) => {\n await innerSetAuditContext(request, reply.raw, entityType, action);\n};\n\nexport { setRabbitAuditContext };\n\nexport * from './types';\nexport * from './const';\n\nexport default AuditLogger;\n"],"mappings":"uJAIA,eAAsB,EAAY,CAAE,UAAS,SAAQ,uBAA0C,CAAiB,CAC9G,CAAK,IAAyB,GAG9B,OAAO,QAAQ,EAAqB,CAAC,QAAQ,CAAC,CAAC,EAAQ,EAAY,GAAK,CACtE,EAAQ,KACL,UAAU,EAAO,YAClB,CACE,OAAQ,CACN,KAAM,CAAC,OAAQ,EACf,aAAc,qBAAqB,EAAO,QAC1C,OAAQ,CACN,KAAM,SACN,WAAY,CACV,GAAI,CAAE,KAAM,QAAU,CACvB,EACD,SAAU,CAAC,IAAK,CACjB,CACF,CACF,EACD,MAAO,GAAQ,CAEb,GADM,CAAE,KAAI,CAAG,EAAI,OACb,EAAa,KAAM,GAAY,SAAS,EAAG,CACjD,IAAK,EAAY,CACf,IAAM,EAAM,IAAI,EAAA,sBAEhB,KADA,GAAO,OAAO,SAAS,EAAO,WAAW,EAAG,YAAa,CAAE,KAAK,EAAC,CAC3D,CACP,CACD,MAAO,GAAA,iBAAQ,cAAc,EAAG,AACjC,EACF,AACF,EAAC,AACH;;;;;;;ACnBD,MAXa,EAAiB,AAACA,GAAsC,CAEnE,AADA,EAAA,oBAAoB,EAAQ,CAC5B,EAAY,EAAQ,AACrB,EAQY,EAAkB,CAACC,EAAoBC,IAA8C,MAAO,EAAS,IAAU,CAC1H,KAAM,GAAA,qBAAqB,EAAS,EAAM,IAAK,EAAY,EAAO,AACnE,EAOD,IAAA,EAAe,EAAA"}
1
+ {"version":3,"file":"fastify.cjs","names":["options: AuditLoggerOptions","entityType: string","action: string"],"sources":["../src/audit-api/fastify.ts","../src/fastify.ts"],"sourcesContent":["import { ResourceNotFoundError } from '@autofleet/errors';\nimport auditMs from '../audit-ms';\nimport type { AuditLoggerOptions } from '../types';\n\n/** Swagger tag for audit logs API. Add this to the `tags` array passed into the options of `fastify-plugin`. */\nexport const SWAGGER_TAG = { name: 'audit', description: 'Audit logs API' };\n\nexport async function addAuditApi({ fastify, logger, entityScopedModelMap }: AuditLoggerOptions): Promise<void> {\n if (!entityScopedModelMap || !fastify) {\n return;\n }\n Object.entries(entityScopedModelMap).forEach(([entity, ScopedModel]) => {\n fastify.get(\n `/api/v1/${entity}/:id/audit`,\n {\n schema: {\n tags: [SWAGGER_TAG.name],\n description: `Get audit logs for ${entity} by ID`,\n params: {\n type: 'object',\n properties: {\n id: { type: 'string' },\n },\n required: ['id'],\n },\n },\n },\n async (req) => {\n const { id } = req.params as { id: string; };\n const entityData = await ScopedModel.findByPk(id);\n if (!entityData) {\n const err = new ResourceNotFoundError();\n logger.error(`Entity ${entity} with id ${id} not found`, { err });\n throw err;\n }\n return auditMs.getByEntityId(id);\n },\n );\n });\n}\n","import type { onRequestAsyncHookHandler } from 'fastify';\nimport AuditLogger from './audit-logger';\nimport { addAuditApi, SWAGGER_TAG } from './audit-api/fastify';\nimport type { AuditLoggerOptions } from './types';\nimport { innerEnableAuditing, innerSetAuditContext, setRabbitAuditContext } from './common';\n\nexport const enableAuditing = (options: AuditLoggerOptions): void => {\n const addApi = innerEnableAuditing(options);\n if (!addApi) {\n return;\n }\n addAuditApi(options);\n};\n\n/**\n * A builder of `onRequest` hook for the request handler, which sets the audit context for the request lifecycle.\n * @param entityType The type of the entity being audited.\n * @param action The action being performed on the entity.\n * @returns A Fastify `onRequest` hook.\n */\nexport const setAuditContext = (entityType: string, action: string): onRequestAsyncHookHandler => async (request, reply) => {\n await innerSetAuditContext(request, reply.raw, entityType, action);\n};\n\nexport { setRabbitAuditContext, SWAGGER_TAG };\n\nexport * from './types';\nexport * from './const';\n\nexport default AuditLogger;\n"],"mappings":";;AAKA,mFAAa,EAAc,CAAE,KAAM,QAAS,YAAa,gBAAkB,EAE3E,eAAsB,EAAY,CAAE,UAAS,SAAQ,uBAA0C,CAAiB,CAC9G,CAAK,IAAyB,GAG9B,OAAO,QAAQ,EAAqB,CAAC,QAAQ,CAAC,CAAC,EAAQ,EAAY,GAAK,CACtE,EAAQ,KACL,UAAU,EAAO,YAClB,CACE,OAAQ,CACN,KAAM,CAAC,EAAY,IAAK,EACxB,aAAc,qBAAqB,EAAO,QAC1C,OAAQ,CACN,KAAM,SACN,WAAY,CACV,GAAI,CAAE,KAAM,QAAU,CACvB,EACD,SAAU,CAAC,IAAK,CACjB,CACF,CACF,EACD,MAAO,GAAQ,CAEb,GADM,CAAE,KAAI,CAAG,EAAI,OACb,EAAa,KAAM,GAAY,SAAS,EAAG,CACjD,IAAK,EAAY,CACf,IAAM,EAAM,IAAI,EAAA,sBAEhB,KADA,GAAO,OAAO,SAAS,EAAO,WAAW,EAAG,YAAa,CAAE,KAAK,EAAC,CAC3D,CACP,CACD,MAAO,GAAA,iBAAQ,cAAc,EAAG,AACjC,EACF,AACF,EAAC,AACH;;;;;;;ACnBD,MAda,EAAiB,AAACA,GAAsC,CACnE,IAAM,EAAS,EAAA,oBAAoB,EAAQ,CACtC,GAGL,EAAY,EAAQ,AACrB,EAQY,EAAkB,CAACC,EAAoBC,IAA8C,MAAO,EAAS,IAAU,CAC1H,KAAM,GAAA,qBAAqB,EAAS,EAAM,IAAK,EAAY,EAAO,AACnE,EAOD,IAAA,EAAe,EAAA"}
@@ -1,6 +1,15 @@
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-CC0vE16d.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-ByTOLhRM.cjs";
2
2
  import { onRequestAsyncHookHandler } from "fastify";
3
3
 
4
+ //#region src/audit-api/fastify.d.ts
5
+ /** Swagger tag for audit logs API. Add this to the `tags` array passed into the options of `fastify-plugin`. */
6
+ /** Swagger tag for audit logs API. Add this to the `tags` array passed into the options of `fastify-plugin`. */
7
+ declare const SWAGGER_TAG: {
8
+ name: string;
9
+ description: string;
10
+ };
11
+
12
+ //#endregion
4
13
  //#region src/fastify.d.ts
5
14
  declare const enableAuditing: (options: AuditLoggerOptions) => void;
6
15
  /**
@@ -12,5 +21,5 @@ declare const enableAuditing: (options: AuditLoggerOptions) => void;
12
21
  declare const setAuditContext: (entityType: string, action: string) => onRequestAsyncHookHandler;
13
22
 
14
23
  //#endregion
15
- export { AUDIT_LOG_CONTEXT_KEY, AUDIT_LOG_CONTEXT_QUEUE, AUDIT_LOG_ROWS_QUEUE, AUTOMATION_ID_HEADER, Action, ActionOrigin, AuditLogContext, AuditLogPayload, AuditLogRow, AuditLoggerOptions, EntityType, AuditLogger as default, enableAuditing, setAuditContext, setRabbitAuditContext };
24
+ export { AUDIT_LOG_CONTEXT_KEY, AUDIT_LOG_CONTEXT_QUEUE, AUDIT_LOG_ROWS_QUEUE, AUTOMATION_ID_HEADER, Action, ActionOrigin, AuditLogContext, AuditLogPayload, AuditLogRow, AuditLoggerOptions, EntityType, SWAGGER_TAG, AuditLogger as default, enableAuditing, setAuditContext, setRabbitAuditContext };
16
25
  //# sourceMappingURL=fastify.d.cts.map
package/dist/fastify.d.ts CHANGED
@@ -1,6 +1,15 @@
1
- import { AUDIT_LOG_CONTEXT_KEY$1 as AUDIT_LOG_CONTEXT_KEY, AUDIT_LOG_CONTEXT_QUEUE$1 as AUDIT_LOG_CONTEXT_QUEUE, AUDIT_LOG_ROWS_QUEUE$1 as AUDIT_LOG_ROWS_QUEUE, AUTOMATION_ID_HEADER$1 as AUTOMATION_ID_HEADER, Action$1 as Action, ActionOrigin$1 as ActionOrigin, AuditLogContext, AuditLogPayload, AuditLogRow, AuditLogger, AuditLoggerOptions, EntityType$1 as EntityType, setRabbitAuditContext$1 as setRabbitAuditContext } from "./const-DrgE261l.js";
1
+ import { AUDIT_LOG_CONTEXT_KEY$1 as AUDIT_LOG_CONTEXT_KEY, AUDIT_LOG_CONTEXT_QUEUE$1 as AUDIT_LOG_CONTEXT_QUEUE, AUDIT_LOG_ROWS_QUEUE$1 as AUDIT_LOG_ROWS_QUEUE, AUTOMATION_ID_HEADER$1 as AUTOMATION_ID_HEADER, Action$1 as Action, ActionOrigin$1 as ActionOrigin, AuditLogContext, AuditLogPayload, AuditLogRow, AuditLogger, AuditLoggerOptions, EntityType$1 as EntityType, setRabbitAuditContext$1 as setRabbitAuditContext } from "./const-DTsi7GAD.js";
2
2
  import { onRequestAsyncHookHandler } from "fastify";
3
3
 
4
+ //#region src/audit-api/fastify.d.ts
5
+ /** Swagger tag for audit logs API. Add this to the `tags` array passed into the options of `fastify-plugin`. */
6
+ /** Swagger tag for audit logs API. Add this to the `tags` array passed into the options of `fastify-plugin`. */
7
+ declare const SWAGGER_TAG: {
8
+ name: string;
9
+ description: string;
10
+ };
11
+
12
+ //#endregion
4
13
  //#region src/fastify.d.ts
5
14
  declare const enableAuditing: (options: AuditLoggerOptions) => void;
6
15
  /**
@@ -12,5 +21,5 @@ declare const enableAuditing: (options: AuditLoggerOptions) => void;
12
21
  declare const setAuditContext: (entityType: string, action: string) => onRequestAsyncHookHandler;
13
22
 
14
23
  //#endregion
15
- export { AUDIT_LOG_CONTEXT_KEY, AUDIT_LOG_CONTEXT_QUEUE, AUDIT_LOG_ROWS_QUEUE, AUTOMATION_ID_HEADER, Action, ActionOrigin, AuditLogContext, AuditLogPayload, AuditLogRow, AuditLoggerOptions, EntityType, AuditLogger as default, enableAuditing, setAuditContext, setRabbitAuditContext };
24
+ export { AUDIT_LOG_CONTEXT_KEY, AUDIT_LOG_CONTEXT_QUEUE, AUDIT_LOG_ROWS_QUEUE, AUTOMATION_ID_HEADER, Action, ActionOrigin, AuditLogContext, AuditLogPayload, AuditLogRow, AuditLoggerOptions, EntityType, SWAGGER_TAG, AuditLogger as default, enableAuditing, setAuditContext, setRabbitAuditContext };
16
25
  //# sourceMappingURL=fastify.d.ts.map
package/dist/fastify.js CHANGED
@@ -1,9 +1,11 @@
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-CJByaCJF.js";import{ResourceNotFoundError as f}from"@autofleet/errors";async function p({fastify:e,logger:t,entityScopedModelMap:n}){!n||!e||Object.entries(n).forEach(([n,r])=>{e.get(`/api/v1/${n}/:id/audit`,{schema:{tags:[`audit`],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)})})}
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-oy2ugNvX.js";import{ResourceNotFoundError as f}from"@autofleet/errors";
2
+ /** Swagger tag for audit logs API. Add this to the `tags` array passed into the options of `fastify-plugin`. */
3
+ const p={name:`audit`,description:`Audit logs API`};async 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)})})}
2
4
  /**
3
5
  * A builder of `onRequest` hook for the request handler, which sets the audit context for the request lifecycle.
4
6
  * @param entityType The type of the entity being audited.
5
7
  * @param action The action being performed on the entity.
6
8
  * @returns A Fastify `onRequest` hook.
7
9
  */
8
- const m=e=>{l(e),p(e)},h=(e,t)=>async(n,r)=>{await u(n,r.raw,e,t)};var g=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,g as default,m as enableAuditing,h as setAuditContext,d as setRabbitAuditContext};
10
+ const h=e=>{let t=l(e);t&&m(e)},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};
9
11
  //# sourceMappingURL=fastify.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"fastify.js","names":["options: AuditLoggerOptions","entityType: string","action: string"],"sources":["../src/audit-api/fastify.ts","../src/fastify.ts"],"sourcesContent":["import { ResourceNotFoundError } from '@autofleet/errors';\nimport auditMs from '../audit-ms';\nimport type { AuditLoggerOptions } from '../types';\n\nexport async function addAuditApi({ fastify, logger, entityScopedModelMap }: AuditLoggerOptions): Promise<void> {\n if (!entityScopedModelMap || !fastify) {\n return;\n }\n Object.entries(entityScopedModelMap).forEach(([entity, ScopedModel]) => {\n fastify.get(\n `/api/v1/${entity}/:id/audit`,\n {\n schema: {\n tags: ['audit'],\n description: `Get audit logs for ${entity} by ID`,\n params: {\n type: 'object',\n properties: {\n id: { type: 'string' },\n },\n required: ['id'],\n },\n },\n },\n async (req) => {\n const { id } = req.params as { id: string; };\n const entityData = await ScopedModel.findByPk(id);\n if (!entityData) {\n const err = new ResourceNotFoundError();\n logger.error(`Entity ${entity} with id ${id} not found`, { err });\n throw err;\n }\n return auditMs.getByEntityId(id);\n },\n );\n });\n}\n","import type { onRequestAsyncHookHandler } from 'fastify';\nimport AuditLogger from './audit-logger';\nimport { addAuditApi } from './audit-api/fastify';\nimport type { AuditLoggerOptions } from './types';\nimport { innerEnableAuditing, innerSetAuditContext, setRabbitAuditContext } from './common';\n\nexport const enableAuditing = (options: AuditLoggerOptions): void => {\n innerEnableAuditing(options);\n addAuditApi(options);\n};\n\n/**\n * A builder of `onRequest` hook for the request handler, which sets the audit context for the request lifecycle.\n * @param entityType The type of the entity being audited.\n * @param action The action being performed on the entity.\n * @returns A Fastify `onRequest` hook.\n */\nexport const setAuditContext = (entityType: string, action: string): onRequestAsyncHookHandler => async (request, reply) => {\n await innerSetAuditContext(request, reply.raw, entityType, action);\n};\n\nexport { setRabbitAuditContext };\n\nexport * from './types';\nexport * from './const';\n\nexport default AuditLogger;\n"],"mappings":"oXAIA,eAAsB,EAAY,CAAE,UAAS,SAAQ,uBAA0C,CAAiB,CAC9G,CAAK,IAAyB,GAG9B,OAAO,QAAQ,EAAqB,CAAC,QAAQ,CAAC,CAAC,EAAQ,EAAY,GAAK,CACtE,EAAQ,KACL,UAAU,EAAO,YAClB,CACE,OAAQ,CACN,KAAM,CAAC,OAAQ,EACf,aAAc,qBAAqB,EAAO,QAC1C,OAAQ,CACN,KAAM,SACN,WAAY,CACV,GAAI,CAAE,KAAM,QAAU,CACvB,EACD,SAAU,CAAC,IAAK,CACjB,CACF,CACF,EACD,MAAO,GAAQ,CAEb,GADM,CAAE,KAAI,CAAG,EAAI,OACb,EAAa,KAAM,GAAY,SAAS,EAAG,CACjD,IAAK,EAAY,CACf,IAAM,EAAM,IAAI,EAEhB,KADA,GAAO,OAAO,SAAS,EAAO,WAAW,EAAG,YAAa,CAAE,KAAK,EAAC,CAC3D,CACP,CACD,MAAO,GAAQ,cAAc,EAAG,AACjC,EACF,AACF,EAAC,AACH;;;;;;;ACnBD,MAXa,EAAiB,AAACA,GAAsC,CAEnE,AADA,EAAoB,EAAQ,CAC5B,EAAY,EAAQ,AACrB,EAQY,EAAkB,CAACC,EAAoBC,IAA8C,MAAO,EAAS,IAAU,CAC1H,KAAM,GAAqB,EAAS,EAAM,IAAK,EAAY,EAAO,AACnE,EAOD,IAAA,EAAe"}
1
+ {"version":3,"file":"fastify.js","names":["options: AuditLoggerOptions","entityType: string","action: string"],"sources":["../src/audit-api/fastify.ts","../src/fastify.ts"],"sourcesContent":["import { ResourceNotFoundError } from '@autofleet/errors';\nimport auditMs from '../audit-ms';\nimport type { AuditLoggerOptions } from '../types';\n\n/** Swagger tag for audit logs API. Add this to the `tags` array passed into the options of `fastify-plugin`. */\nexport const SWAGGER_TAG = { name: 'audit', description: 'Audit logs API' };\n\nexport async function addAuditApi({ fastify, logger, entityScopedModelMap }: AuditLoggerOptions): Promise<void> {\n if (!entityScopedModelMap || !fastify) {\n return;\n }\n Object.entries(entityScopedModelMap).forEach(([entity, ScopedModel]) => {\n fastify.get(\n `/api/v1/${entity}/:id/audit`,\n {\n schema: {\n tags: [SWAGGER_TAG.name],\n description: `Get audit logs for ${entity} by ID`,\n params: {\n type: 'object',\n properties: {\n id: { type: 'string' },\n },\n required: ['id'],\n },\n },\n },\n async (req) => {\n const { id } = req.params as { id: string; };\n const entityData = await ScopedModel.findByPk(id);\n if (!entityData) {\n const err = new ResourceNotFoundError();\n logger.error(`Entity ${entity} with id ${id} not found`, { err });\n throw err;\n }\n return auditMs.getByEntityId(id);\n },\n );\n });\n}\n","import type { onRequestAsyncHookHandler } from 'fastify';\nimport AuditLogger from './audit-logger';\nimport { addAuditApi, SWAGGER_TAG } from './audit-api/fastify';\nimport type { AuditLoggerOptions } from './types';\nimport { innerEnableAuditing, innerSetAuditContext, setRabbitAuditContext } from './common';\n\nexport const enableAuditing = (options: AuditLoggerOptions): void => {\n const addApi = innerEnableAuditing(options);\n if (!addApi) {\n return;\n }\n addAuditApi(options);\n};\n\n/**\n * A builder of `onRequest` hook for the request handler, which sets the audit context for the request lifecycle.\n * @param entityType The type of the entity being audited.\n * @param action The action being performed on the entity.\n * @returns A Fastify `onRequest` hook.\n */\nexport const setAuditContext = (entityType: string, action: string): onRequestAsyncHookHandler => async (request, reply) => {\n await innerSetAuditContext(request, reply.raw, entityType, action);\n};\n\nexport { setRabbitAuditContext, SWAGGER_TAG };\n\nexport * from './types';\nexport * from './const';\n\nexport default AuditLogger;\n"],"mappings":";;AAKA,MAAa,EAAc,CAAE,KAAM,QAAS,YAAa,gBAAkB,EAE3E,eAAsB,EAAY,CAAE,UAAS,SAAQ,uBAA0C,CAAiB,CAC9G,CAAK,IAAyB,GAG9B,OAAO,QAAQ,EAAqB,CAAC,QAAQ,CAAC,CAAC,EAAQ,EAAY,GAAK,CACtE,EAAQ,KACL,UAAU,EAAO,YAClB,CACE,OAAQ,CACN,KAAM,CAAC,EAAY,IAAK,EACxB,aAAc,qBAAqB,EAAO,QAC1C,OAAQ,CACN,KAAM,SACN,WAAY,CACV,GAAI,CAAE,KAAM,QAAU,CACvB,EACD,SAAU,CAAC,IAAK,CACjB,CACF,CACF,EACD,MAAO,GAAQ,CAEb,GADM,CAAE,KAAI,CAAG,EAAI,OACb,EAAa,KAAM,GAAY,SAAS,EAAG,CACjD,IAAK,EAAY,CACf,IAAM,EAAM,IAAI,EAEhB,KADA,GAAO,OAAO,SAAS,EAAO,WAAW,EAAG,YAAa,CAAE,KAAK,EAAC,CAC3D,CACP,CACD,MAAO,GAAQ,cAAc,EAAG,AACjC,EACF,AACF,EAAC,AACH;;;;;;;ACnBD,MAda,EAAiB,AAACA,GAAsC,CACnE,IAAM,EAAS,EAAoB,EAAQ,CACtC,GAGL,EAAY,EAAQ,AACrB,EAQY,EAAkB,CAACC,EAAoBC,IAA8C,MAAO,EAAS,IAAU,CAC1H,KAAM,GAAqB,EAAS,EAAM,IAAK,EAAY,EAAO,AACnE,EAOD,IAAA,EAAe"}
package/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,`__esModule`,{value:!0});const e=require(`./common-BWTPt3jo.cjs`),t=e.__toESM(require(`@autofleet/errors`));async 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=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=>{e.innerEnableAuditing(t),n(t)},i=(t,n)=>async(r,i,a)=>(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
+ "use strict";Object.defineProperty(exports,`__esModule`,{value:!0});const e=require(`./common-DLsvf3zA.cjs`),t=e.__toESM(require(`@autofleet/errors`));async 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=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);r&&n(t)},i=(t,n)=>async(r,i,a)=>(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
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["options: AuditLoggerOptions","entityType: string","action: string","req: Request","res: Response","next: NextFunction"],"sources":["../src/audit-api/express.ts","../src/index.ts"],"sourcesContent":["import { handleError, ResourceNotFoundError, UnexpectedError } from '@autofleet/errors';\nimport auditMs from '../audit-ms';\nimport type { AuditLoggerOptions } from '../types';\n\nexport async function addAuditApi({ router, logger, entityScopedModelMap }: AuditLoggerOptions): Promise<void> {\n if (!entityScopedModelMap || !router) {\n return;\n }\n Object.entries(entityScopedModelMap).forEach(([entity, ScopedModel]) => {\n router.get(`${entity}/:id/audit`, async (req, res) => {\n try {\n const { id } = req.params;\n const entityData = await ScopedModel.findByPk(id);\n if (!entityData) {\n return handleError(new ResourceNotFoundError(), res, { logger, message: `Entity ${entity} with id ${id} not found` });\n }\n const auditData = auditMs.getByEntityId(id);\n return res.json(auditData);\n } catch (err) {\n return handleError(new UnexpectedError(err as Error), res, { logger });\n }\n });\n });\n}\n","import type { Request, Response, NextFunction } from 'express';\nimport AuditLogger from './audit-logger';\nimport { addAuditApi } from './audit-api/express';\nimport type { AuditLoggerOptions } from './types';\nimport { innerEnableAuditing, innerSetAuditContext, setRabbitAuditContext } from './common';\n\nexport const enableAuditing = (options: AuditLoggerOptions): void => {\n innerEnableAuditing(options);\n addAuditApi(options);\n};\n\nexport const setAuditContext = (entityType: string, action: string) => async (req: Request, res: Response, next: NextFunction): Promise<void> => {\n innerSetAuditContext(req, res, entityType, action);\n return next();\n};\n\nexport { setRabbitAuditContext };\n\nexport * from './types';\nexport * from './const';\n\nexport default AuditLogger;\n"],"mappings":"uJAIA,eAAsB,EAAY,CAAE,SAAQ,SAAQ,uBAA0C,CAAiB,CAC7G,CAAK,IAAyB,GAG9B,OAAO,QAAQ,EAAqB,CAAC,QAAQ,CAAC,CAAC,EAAQ,EAAY,GAAK,CACtE,EAAO,KAAK,EAAE,EAAO,YAAa,MAAO,EAAK,IAAQ,CACpD,GAAI,CAEF,GADM,CAAE,KAAI,CAAG,EAAI,OACb,EAAa,KAAM,GAAY,SAAS,EAAG,CACjD,IAAK,EACH,MAAO,CAAA,EAAA,EAAA,aAAY,IAAI,EAAA,sBAAyB,EAAK,CAAE,SAAQ,SAAU,SAAS,EAAO,WAAW,EAAG,WAAa,EAAC,CAEvH,IAAM,EAAY,EAAA,iBAAQ,cAAc,EAAG,CAC3C,MAAO,GAAI,KAAK,EAAU,AAC3B,OAAQ,EAAK,CACZ,MAAO,CAAA,EAAA,EAAA,aAAY,IAAI,EAAA,gBAAgB,GAAe,EAAK,CAAE,QAAQ,EAAC,AACvE,CACF,EAAC,AACH,EAAC,AACH,CCZD,MALa,EAAiB,AAACA,GAAsC,CAEnE,AADA,EAAA,oBAAoB,EAAQ,CAC5B,EAAY,EAAQ,AACrB,EAEY,EAAkB,CAACC,EAAoBC,IAAmB,MAAOC,EAAcC,EAAeC,KACzG,EAAA,qBAAqB,EAAK,EAAK,EAAY,EAAO,CAC3C,GAAM,EAQf,IAAA,EAAe,EAAA"}
1
+ {"version":3,"file":"index.cjs","names":["options: AuditLoggerOptions","entityType: string","action: string","req: Request","res: Response","next: NextFunction"],"sources":["../src/audit-api/express.ts","../src/index.ts"],"sourcesContent":["import { handleError, ResourceNotFoundError, UnexpectedError } from '@autofleet/errors';\nimport auditMs from '../audit-ms';\nimport type { AuditLoggerOptions } from '../types';\n\nexport async function addAuditApi({ router, logger, entityScopedModelMap }: AuditLoggerOptions): Promise<void> {\n if (!entityScopedModelMap || !router) {\n return;\n }\n Object.entries(entityScopedModelMap).forEach(([entity, ScopedModel]) => {\n router.get(`${entity}/:id/audit`, async (req, res) => {\n try {\n const { id } = req.params;\n const entityData = await ScopedModel.findByPk(id);\n if (!entityData) {\n return handleError(new ResourceNotFoundError(), res, { logger, message: `Entity ${entity} with id ${id} not found` });\n }\n const auditData = auditMs.getByEntityId(id);\n return res.json(auditData);\n } catch (err) {\n return handleError(new UnexpectedError(err as Error), res, { logger });\n }\n });\n });\n}\n","import type { Request, Response, NextFunction } from 'express';\nimport AuditLogger from './audit-logger';\nimport { addAuditApi } from './audit-api/express';\nimport type { AuditLoggerOptions } from './types';\nimport { innerEnableAuditing, innerSetAuditContext, setRabbitAuditContext } from './common';\n\nexport const enableAuditing = (options: AuditLoggerOptions): void => {\n const addApi = innerEnableAuditing(options);\n if (!addApi) {\n return;\n }\n addAuditApi(options);\n};\n\nexport const setAuditContext = (entityType: string, action: string) => async (req: Request, res: Response, next: NextFunction): Promise<void> => {\n innerSetAuditContext(req, res, entityType, action);\n return next();\n};\n\nexport { setRabbitAuditContext };\n\nexport * from './types';\nexport * from './const';\n\nexport default AuditLogger;\n"],"mappings":"uJAIA,eAAsB,EAAY,CAAE,SAAQ,SAAQ,uBAA0C,CAAiB,CAC7G,CAAK,IAAyB,GAG9B,OAAO,QAAQ,EAAqB,CAAC,QAAQ,CAAC,CAAC,EAAQ,EAAY,GAAK,CACtE,EAAO,KAAK,EAAE,EAAO,YAAa,MAAO,EAAK,IAAQ,CACpD,GAAI,CAEF,GADM,CAAE,KAAI,CAAG,EAAI,OACb,EAAa,KAAM,GAAY,SAAS,EAAG,CACjD,IAAK,EACH,MAAO,CAAA,EAAA,EAAA,aAAY,IAAI,EAAA,sBAAyB,EAAK,CAAE,SAAQ,SAAU,SAAS,EAAO,WAAW,EAAG,WAAa,EAAC,CAEvH,IAAM,EAAY,EAAA,iBAAQ,cAAc,EAAG,CAC3C,MAAO,GAAI,KAAK,EAAU,AAC3B,OAAQ,EAAK,CACZ,MAAO,CAAA,EAAA,EAAA,aAAY,IAAI,EAAA,gBAAgB,GAAe,EAAK,CAAE,QAAQ,EAAC,AACvE,CACF,EAAC,AACH,EAAC,AACH,CCTD,MARa,EAAiB,AAACA,GAAsC,CACnE,IAAM,EAAS,EAAA,oBAAoB,EAAQ,CACtC,GAGL,EAAY,EAAQ,AACrB,EAEY,EAAkB,CAACC,EAAoBC,IAAmB,MAAOC,EAAcC,EAAeC,KACzG,EAAA,qBAAqB,EAAK,EAAK,EAAY,EAAO,CAC3C,GAAM,EAQf,IAAA,EAAe,EAAA"}
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-CC0vE16d.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-ByTOLhRM.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$1 as AUDIT_LOG_CONTEXT_KEY, AUDIT_LOG_CONTEXT_QUEUE$1 as AUDIT_LOG_CONTEXT_QUEUE, AUDIT_LOG_ROWS_QUEUE$1 as AUDIT_LOG_ROWS_QUEUE, AUTOMATION_ID_HEADER$1 as AUTOMATION_ID_HEADER, Action$1 as Action, ActionOrigin$1 as ActionOrigin, AuditLogContext, AuditLogPayload, AuditLogRow, AuditLogger, AuditLoggerOptions, EntityType$1 as EntityType, setRabbitAuditContext$1 as setRabbitAuditContext } from "./const-DrgE261l.js";
1
+ import { AUDIT_LOG_CONTEXT_KEY$1 as AUDIT_LOG_CONTEXT_KEY, AUDIT_LOG_CONTEXT_QUEUE$1 as AUDIT_LOG_CONTEXT_QUEUE, AUDIT_LOG_ROWS_QUEUE$1 as AUDIT_LOG_ROWS_QUEUE, AUTOMATION_ID_HEADER$1 as AUTOMATION_ID_HEADER, Action$1 as Action, ActionOrigin$1 as ActionOrigin, AuditLogContext, AuditLogPayload, AuditLogRow, AuditLogger, AuditLoggerOptions, EntityType$1 as EntityType, setRabbitAuditContext$1 as setRabbitAuditContext } from "./const-DTsi7GAD.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-CJByaCJF.js";import{ResourceNotFoundError as f,UnexpectedError as p,handleError as m}from"@autofleet/errors";async 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=c.getByEntityId(a);return i.json(s)}catch(e){return m(new p(e),i,{logger:t})}})})}const g=e=>{l(e),h(e)},_=(e,t)=>async(n,r,i)=>(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-oy2ugNvX.js";import{ResourceNotFoundError as f,UnexpectedError as p,handleError as m}from"@autofleet/errors";async 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=c.getByEntityId(a);return i.json(s)}catch(e){return m(new p(e),i,{logger:t})}})})}const g=e=>{let t=l(e);t&&h(e)},_=(e,t)=>async(n,r,i)=>(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/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["options: AuditLoggerOptions","entityType: string","action: string","req: Request","res: Response","next: NextFunction"],"sources":["../src/audit-api/express.ts","../src/index.ts"],"sourcesContent":["import { handleError, ResourceNotFoundError, UnexpectedError } from '@autofleet/errors';\nimport auditMs from '../audit-ms';\nimport type { AuditLoggerOptions } from '../types';\n\nexport async function addAuditApi({ router, logger, entityScopedModelMap }: AuditLoggerOptions): Promise<void> {\n if (!entityScopedModelMap || !router) {\n return;\n }\n Object.entries(entityScopedModelMap).forEach(([entity, ScopedModel]) => {\n router.get(`${entity}/:id/audit`, async (req, res) => {\n try {\n const { id } = req.params;\n const entityData = await ScopedModel.findByPk(id);\n if (!entityData) {\n return handleError(new ResourceNotFoundError(), res, { logger, message: `Entity ${entity} with id ${id} not found` });\n }\n const auditData = auditMs.getByEntityId(id);\n return res.json(auditData);\n } catch (err) {\n return handleError(new UnexpectedError(err as Error), res, { logger });\n }\n });\n });\n}\n","import type { Request, Response, NextFunction } from 'express';\nimport AuditLogger from './audit-logger';\nimport { addAuditApi } from './audit-api/express';\nimport type { AuditLoggerOptions } from './types';\nimport { innerEnableAuditing, innerSetAuditContext, setRabbitAuditContext } from './common';\n\nexport const enableAuditing = (options: AuditLoggerOptions): void => {\n innerEnableAuditing(options);\n addAuditApi(options);\n};\n\nexport const setAuditContext = (entityType: string, action: string) => async (req: Request, res: Response, next: NextFunction): Promise<void> => {\n innerSetAuditContext(req, res, entityType, action);\n return next();\n};\n\nexport { setRabbitAuditContext };\n\nexport * from './types';\nexport * from './const';\n\nexport default AuditLogger;\n"],"mappings":"0ZAIA,eAAsB,EAAY,CAAE,SAAQ,SAAQ,uBAA0C,CAAiB,CAC7G,CAAK,IAAyB,GAG9B,OAAO,QAAQ,EAAqB,CAAC,QAAQ,CAAC,CAAC,EAAQ,EAAY,GAAK,CACtE,EAAO,KAAK,EAAE,EAAO,YAAa,MAAO,EAAK,IAAQ,CACpD,GAAI,CAEF,GADM,CAAE,KAAI,CAAG,EAAI,OACb,EAAa,KAAM,GAAY,SAAS,EAAG,CACjD,IAAK,EACH,MAAO,GAAY,IAAI,EAAyB,EAAK,CAAE,SAAQ,SAAU,SAAS,EAAO,WAAW,EAAG,WAAa,EAAC,CAEvH,IAAM,EAAY,EAAQ,cAAc,EAAG,CAC3C,MAAO,GAAI,KAAK,EAAU,AAC3B,OAAQ,EAAK,CACZ,MAAO,GAAY,IAAI,EAAgB,GAAe,EAAK,CAAE,QAAQ,EAAC,AACvE,CACF,EAAC,AACH,EAAC,AACH,CCZD,MALa,EAAiB,AAACA,GAAsC,CAEnE,AADA,EAAoB,EAAQ,CAC5B,EAAY,EAAQ,AACrB,EAEY,EAAkB,CAACC,EAAoBC,IAAmB,MAAOC,EAAcC,EAAeC,KACzG,EAAqB,EAAK,EAAK,EAAY,EAAO,CAC3C,GAAM,EAQf,IAAA,EAAe"}
1
+ {"version":3,"file":"index.js","names":["options: AuditLoggerOptions","entityType: string","action: string","req: Request","res: Response","next: NextFunction"],"sources":["../src/audit-api/express.ts","../src/index.ts"],"sourcesContent":["import { handleError, ResourceNotFoundError, UnexpectedError } from '@autofleet/errors';\nimport auditMs from '../audit-ms';\nimport type { AuditLoggerOptions } from '../types';\n\nexport async function addAuditApi({ router, logger, entityScopedModelMap }: AuditLoggerOptions): Promise<void> {\n if (!entityScopedModelMap || !router) {\n return;\n }\n Object.entries(entityScopedModelMap).forEach(([entity, ScopedModel]) => {\n router.get(`${entity}/:id/audit`, async (req, res) => {\n try {\n const { id } = req.params;\n const entityData = await ScopedModel.findByPk(id);\n if (!entityData) {\n return handleError(new ResourceNotFoundError(), res, { logger, message: `Entity ${entity} with id ${id} not found` });\n }\n const auditData = auditMs.getByEntityId(id);\n return res.json(auditData);\n } catch (err) {\n return handleError(new UnexpectedError(err as Error), res, { logger });\n }\n });\n });\n}\n","import type { Request, Response, NextFunction } from 'express';\nimport AuditLogger from './audit-logger';\nimport { addAuditApi } from './audit-api/express';\nimport type { AuditLoggerOptions } from './types';\nimport { innerEnableAuditing, innerSetAuditContext, setRabbitAuditContext } from './common';\n\nexport const enableAuditing = (options: AuditLoggerOptions): void => {\n const addApi = innerEnableAuditing(options);\n if (!addApi) {\n return;\n }\n addAuditApi(options);\n};\n\nexport const setAuditContext = (entityType: string, action: string) => async (req: Request, res: Response, next: NextFunction): Promise<void> => {\n innerSetAuditContext(req, res, entityType, action);\n return next();\n};\n\nexport { setRabbitAuditContext };\n\nexport * from './types';\nexport * from './const';\n\nexport default AuditLogger;\n"],"mappings":"0ZAIA,eAAsB,EAAY,CAAE,SAAQ,SAAQ,uBAA0C,CAAiB,CAC7G,CAAK,IAAyB,GAG9B,OAAO,QAAQ,EAAqB,CAAC,QAAQ,CAAC,CAAC,EAAQ,EAAY,GAAK,CACtE,EAAO,KAAK,EAAE,EAAO,YAAa,MAAO,EAAK,IAAQ,CACpD,GAAI,CAEF,GADM,CAAE,KAAI,CAAG,EAAI,OACb,EAAa,KAAM,GAAY,SAAS,EAAG,CACjD,IAAK,EACH,MAAO,GAAY,IAAI,EAAyB,EAAK,CAAE,SAAQ,SAAU,SAAS,EAAO,WAAW,EAAG,WAAa,EAAC,CAEvH,IAAM,EAAY,EAAQ,cAAc,EAAG,CAC3C,MAAO,GAAI,KAAK,EAAU,AAC3B,OAAQ,EAAK,CACZ,MAAO,GAAY,IAAI,EAAgB,GAAe,EAAK,CAAE,QAAQ,EAAC,AACvE,CACF,EAAC,AACH,EAAC,AACH,CCTD,MARa,EAAiB,AAACA,GAAsC,CACnE,IAAM,EAAS,EAAoB,EAAQ,CACtC,GAGL,EAAY,EAAQ,AACrB,EAEY,EAAkB,CAACC,EAAoBC,IAAmB,MAAOC,EAAcC,EAAeC,KACzG,EAAqB,EAAK,EAAK,EAAY,EAAO,CAC3C,GAAM,EAQf,IAAA,EAAe"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@autofleet/shtinker",
3
- "version": "3.2.1-beta-81f8d75f.0",
3
+ "version": "3.4.0",
4
4
  "description": "",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -38,8 +38,7 @@
38
38
  "node": ">=18"
39
39
  },
40
40
  "dependencies": {
41
- "@autofleet/network": "^1.8.1",
42
- "lodash": "^4.17.21"
41
+ "@autofleet/network": "^1.8.1"
43
42
  },
44
43
  "devDependencies": {
45
44
  "@autofleet/zehut": "^4.2.2",
@@ -1,2 +0,0 @@
1
- "use strict";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/outbreak`)),d=s(require(`@autofleet/logger`)),f=s(require(`@autofleet/network`));let p=/* @__PURE__ */ 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}({}),m=/* @__PURE__ */ function(e){return e.RIDE=`Ride`,e.VEHICLE=`Vehicle`,e.DRIVER=`Driver`,e.PRICE_CALCULATION=`PriceCalculation`,e}({}),h=/* @__PURE__ */ function(e){return e.USER=`user`,e.AUTOMATION=`automation`,e}({});const g=`audit-log-context`,_=`audit-log-rows`,v=`auditLogContext`,y=`x-af-automation-id`,b=(0,d.default)();b.addContextMiddleware(()=>({traceId:(0,u.getCurrentContextTraceId)()}));var x=b;const S=`customFields`,C=()=>{let e=(0,l.getCurrentPayload)(),t=e?.nonHeaderContext?.get(v);return t},w={[p.BULK_CREATE]:p.BULK_CREATE,[p.BULK_EDIT]:p.BULK_EDIT,[p.BULK_ASSIGN]:p.BULK_ASSIGN,[p.BULK_DISPATCH]:p.BULK_DISPATCH,[p.BULK_UPSERT]:p.BULK_UPSERT},T=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,E=e=>Object.hasOwn(w,e),D=(e,t)=>e.filter(e=>!T(t.get(e))||!T(t.previous(e))),O=(e,t)=>{let n=t.returning?t.fields:e.changed(),r=D(n.filter(e=>e!==S),e);return r.map(t=>({property:t,previousValue:e.previous(t),newValue:e.get(t)}))},k=e=>{let t=e.changed(),n=t&&t.includes(S);if(!n)return[];let r=e.get(S),i=e.previous(S),a=Object.keys(r).filter(e=>{let t=r?.[e],n=i?.[e];return(!T(t)||!T(n))&&!(0,c.isDeepStrictEqual)(t,n)});return a.map(e=>({property:`${S}.${e}`,previousValue:i?.[e],newValue:r?.[e]}))};var A=class{constructor(e){this.rabbit=e.rabbit,this.sequelize=e.sequelize,this.logger=e.logger||x,this.excludeModels=e.excludeModels??[]}registerHooks(){Object.entries(this.sequelize.models).forEach(([e,t])=>{this.excludeModels.includes(e)||t.addHook(`afterSave`,async(t,n)=>{try{let r=C();if(!r)return;let{id:i}=t;r?.entityType?.toLowerCase()===e?.toLowerCase()&&E(r.action)&&(r.entityId=i);let a=O(t,n),o=k(t),s={entityType:e,entityId:i,rows:[...a,...o]};this.sendAuditLogRows(s)}catch(e){this.logger.error(`Failed to send audit log rows`,e)}})})}async sendAuditLogContext(e){try{await this.rabbit.sendToQueue(g,e)}catch(e){this.logger.error(`Failed to send audit log context`,e)}}async sendAuditLogRows(e){try{await this.rabbit.sendToQueue(_,e)}catch(e){this.logger.error(`Failed to send audit log rows`,e)}}},j=A;const M=new f.default({serviceName:`AUDIT_MS`,timeout:6e4,logger:x}),N=async e=>{let{data:t}=await M.get(`api/v1/audit-logs/${e}`);return t},P={getByEntityId:N};var F=P;let I;const L=e=>process.env.DISABLE_AUDIT_LOGS===`true`?!1:(I=new j(e),I.registerHooks(),!0),R=({action:e,endpoint:t,entityType:n,method:r,automationId:i,userId:a})=>{let o=a||(i??null),s=a&&h.USER||i&&h.AUTOMATION||null,c={entityType:n,action:e,endpoint:t,method:r,performedBy:o,actionOrigin:s},u=(0,l.getCurrentPayload)();return u.nonHeaderContext.set(v,c),c},z=async(e,t,n,r)=>{try{if(process.env.DISABLE_AUDIT_LOGS===`true`||!I)return;let i=R({action:r,endpoint:e.url,entityType:n,method:e.method,userId:(0,l.getUser)()?.id,automationId:e.headers[y]});if(!E(r)){await I.sendAuditLogContext(i);return}let a=async()=>{t.off(`finish`,a),t.off(`close`,a),t.off(`error`,a),await I?.sendAuditLogContext(i)};t.once(`finish`,a),t.once(`close`,a),t.once(`error`,a)}catch(e){x.error(`couldn't set audit context`,e)}},B=(e,t)=>async(n,{userId:r,automationId:i})=>{if(process.env.DISABLE_AUDIT_LOGS===`true`||!I)return;let a=R({action:t,endpoint:n,entityType:e,method:`rabbit`,userId:r,automationId:i});await I.sendAuditLogContext(a)};Object.defineProperty(exports,`AUDIT_LOG_CONTEXT_KEY`,{enumerable:!0,get:function(){return v}}),Object.defineProperty(exports,`AUDIT_LOG_CONTEXT_QUEUE`,{enumerable:!0,get:function(){return g}}),Object.defineProperty(exports,`AUDIT_LOG_ROWS_QUEUE`,{enumerable:!0,get:function(){return _}}),Object.defineProperty(exports,`AUTOMATION_ID_HEADER`,{enumerable:!0,get:function(){return y}}),Object.defineProperty(exports,`Action`,{enumerable:!0,get:function(){return p}}),Object.defineProperty(exports,`ActionOrigin`,{enumerable:!0,get:function(){return h}}),Object.defineProperty(exports,`EntityType`,{enumerable:!0,get:function(){return m}}),Object.defineProperty(exports,`__toESM`,{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,`audit_logger_default`,{enumerable:!0,get:function(){return j}}),Object.defineProperty(exports,`audit_ms_default`,{enumerable:!0,get:function(){return F}}),Object.defineProperty(exports,`innerEnableAuditing`,{enumerable:!0,get:function(){return L}}),Object.defineProperty(exports,`innerSetAuditContext`,{enumerable:!0,get:function(){return z}}),Object.defineProperty(exports,`setRabbitAuditContext`,{enumerable:!0,get:function(){return B}});
2
- //# sourceMappingURL=common-BWTPt3jo.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"common-BWTPt3jo.cjs","names":["logger: LoggerInstanceManager","field: unknown","action: string","fields: string[]","instance: Model","options: CreateOptions<any> | InstanceUpdateOptions<any>","changedFields: string[]","property: string","options: AuditLoggerOptions","payload: AuditLogPayload","context: AuditLogContext","entityId: string","exportObj: { getByEntityId: typeof getByEntityId }","auditLogger: AuditLogger | undefined","options: AuditLoggerOptions","auditLogContext: AuditLogContext","req: PartialRequest","res: Writable","entityType: string","action: string","endpoint: string"],"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 type AuditLoggerOptions = {\n rabbit: RabbitMq;\n sequelize: Sequelize;\n logger: LoggerInstanceManager;\n router?: IRouter;\n fastify?: FastifyInstance;\n excludeModels?: string[];\n entityScopedModelMap?: { [modelName: 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: any;\n newValue: any;\n}\n\nexport interface AuditLogPayload {\n entityType: string;\n entityId: string;\n rows: 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 { getCurrentContextTraceId } from '@autofleet/outbreak';\nimport Logger, { type LoggerInstanceManager } from '@autofleet/logger';\n\nconst logger: LoggerInstanceManager = Logger();\nlogger.addContextMiddleware(() => ({ traceId: 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,\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<any> | InstanceUpdateOptions<any>) => {\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) => {\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\nclass AuditLogger {\n private rabbit: RabbitMq;\n\n private sequelize: Sequelize;\n\n private logger: LoggerInstanceManager;\n\n private 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 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 try {\n const auditContext = getAuditContext();\n if (!auditContext) {\n return;\n }\n const { id: entityId } = instance as unknown as { id: string; };\n if (auditContext?.entityType?.toLowerCase() === modelName?.toLowerCase() && isEntityIdRequired(auditContext.action)) {\n auditContext.entityId = entityId;\n }\n const changedFieldsRows = getChangedFieldsRows(instance, options);\n const changedCustomFieldsRows = getChangedCustomFieldsRows(instance);\n const payload: AuditLogPayload = {\n entityType: modelName,\n entityId,\n rows: [...changedFieldsRows, ...changedCustomFieldsRows],\n };\n this.sendAuditLogRows(payload);\n } catch (error) {\n this.logger.error('Failed to send audit log rows', error);\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 async sendAuditLogRows(payload: AuditLogPayload): Promise<void> {\n try {\n await this.rabbit.sendToQueue(AUDIT_LOG_ROWS_QUEUE, payload);\n } catch (err) {\n this.logger.error('Failed to send audit log rows', err);\n }\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): boolean => {\n if (process.env.DISABLE_AUDIT_LOGS === 'true') {\n return false;\n }\n auditLogger = new AuditLogger(options);\n auditLogger.registerHooks();\n return true;\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":"qpBAkEA,IA3BY,kBAAA,SAAA,EAAL,QACL,EAAA,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,kBACD,EAAA,CAAA,EAAA,CAEW,kBAAA,SAAA,EAAL,QACL,EAAA,KAAA,OACA,EAAA,QAAA,UACA,EAAA,OAAA,SACA,EAAA,kBAAA,oBACD,EAAA,CAAA,EAAA,CAEiB,kBAAA,SAAA,EAAX,QACL,EAAA,KAAA,OACA,EAAA,WAAA,cACD,EAAA,CAAA,EAAA,CElED,MDHa,EAA0B,oBAC1B,EAAuB,iBACvB,EAAwB,kBACxB,EAAuB,qBCA9BA,EAAgC,CAAA,EAAA,EAAA,UAAQ,CAC9C,EAAO,qBAAqB,KAAO,CAAE,QAAS,CAAA,EAAA,EAAA,2BAA0B,AAAE,GAAE,CAC5E,IAAA,EAAe,ECsDf,MA9CM,EAAyB,eAEzB,EAAkB,IAAM,CAE5B,IADM,EAAe,CAAA,EAAA,EAAA,oBAAiB,CAChC,EAAe,GAAc,kBAAkB,IAAI,EAAsB,CAC/E,OAAO,CACR,EAEK,EAAyC,EAC5C,EAAO,aAAc,EAAO,aAC5B,EAAO,WAAY,EAAO,WAC1B,EAAO,aAAc,EAAO,aAC5B,EAAO,eAAgB,EAAO,eAC9B,EAAO,aAAc,EAAO,WAC9B,EAEK,EAAU,AAACC,GACX,CAAC,SAAA,EAAgB,EAAC,SAAS,E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AAI,QAAQ,IAAI,qBAAuB,SAAW,EAChD,OAEF,IAAM,EAAkB,EAAkC,CACxD,SACA,WACA,aACA,OAAQ,SACR,SACA,cACD,EAAC,CAEF,KAAM,GAAY,oBAAoB,EAAgB,AACvD"}
@@ -1,2 +0,0 @@
1
- import{isDeepStrictEqual as e}from"node:util";import{getCurrentPayload as t,getUser as n}from"@autofleet/zehut";import{getCurrentContextTraceId as r}from"@autofleet/outbreak";import i from"@autofleet/logger";import a from"@autofleet/network";let o=/* @__PURE__ */ 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=/* @__PURE__ */ function(e){return e.RIDE=`Ride`,e.VEHICLE=`Vehicle`,e.DRIVER=`Driver`,e.PRICE_CALCULATION=`PriceCalculation`,e}({}),c=/* @__PURE__ */ 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()}));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{constructor(e){this.rabbit=e.rabbit,this.sequelize=e.sequelize,this.logger=e.logger||m,this.excludeModels=e.excludeModels??[]}registerHooks(){Object.entries(this.sequelize.models).forEach(([e,t])=>{this.excludeModels.includes(e)||t.addHook(`afterSave`,async(t,n)=>{try{let r=g();if(!r)return;let{id:i}=t;r?.entityType?.toLowerCase()===e?.toLowerCase()&&y(r.action)&&(r.entityId=i);let a=x(t,n),o=S(t),s={entityType:e,entityId:i,rows:[...a,...o]};this.sendAuditLogRows(s)}catch(e){this.logger.error(`Failed to send audit log rows`,e)}})})}async sendAuditLogContext(e){try{await this.rabbit.sendToQueue(l,e)}catch(e){this.logger.error(`Failed to send audit log context`,e)}}async sendAuditLogRows(e){try{await this.rabbit.sendToQueue(u,e)}catch(e){this.logger.error(`Failed to send audit log rows`,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(),!0),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-CJByaCJF.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"common-CJByaCJF.js","names":["logger: LoggerInstanceManager","field: unknown","action: string","fields: string[]","instance: Model","options: CreateOptions<any> | InstanceUpdateOptions<any>","changedFields: string[]","property: string","options: AuditLoggerOptions","payload: AuditLogPayload","context: AuditLogContext","entityId: string","exportObj: { getByEntityId: typeof getByEntityId }","auditLogger: AuditLogger | undefined","options: AuditLoggerOptions","auditLogContext: AuditLogContext","req: PartialRequest","res: Writable","entityType: string","action: string","endpoint: string"],"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 type AuditLoggerOptions = {\n rabbit: RabbitMq;\n sequelize: Sequelize;\n logger: LoggerInstanceManager;\n router?: IRouter;\n fastify?: FastifyInstance;\n excludeModels?: string[];\n entityScopedModelMap?: { [modelName: 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: any;\n newValue: any;\n}\n\nexport interface AuditLogPayload {\n entityType: string;\n entityId: string;\n rows: 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 { getCurrentContextTraceId } from '@autofleet/outbreak';\nimport Logger, { type LoggerInstanceManager } from '@autofleet/logger';\n\nconst logger: LoggerInstanceManager = Logger();\nlogger.addContextMiddleware(() => ({ traceId: 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,\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<any> | InstanceUpdateOptions<any>) => {\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) => {\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\nclass AuditLogger {\n private rabbit: RabbitMq;\n\n private sequelize: Sequelize;\n\n private logger: LoggerInstanceManager;\n\n private 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 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 try {\n const auditContext = getAuditContext();\n if (!auditContext) {\n return;\n }\n const { id: entityId } = instance as unknown as { id: string; };\n if (auditContext?.entityType?.toLowerCase() === modelName?.toLowerCase() && isEntityIdRequired(auditContext.action)) {\n auditContext.entityId = entityId;\n }\n const changedFieldsRows = getChangedFieldsRows(instance, options);\n const changedCustomFieldsRows = getChangedCustomFieldsRows(instance);\n const payload: AuditLogPayload = {\n entityType: modelName,\n entityId,\n rows: [...changedFieldsRows, ...changedCustomFieldsRows],\n };\n this.sendAuditLogRows(payload);\n } catch (error) {\n this.logger.error('Failed to send audit log rows', error);\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 async sendAuditLogRows(payload: AuditLogPayload): Promise<void> {\n try {\n await this.rabbit.sendToQueue(AUDIT_LOG_ROWS_QUEUE, payload);\n } catch (err) {\n this.logger.error('Failed to send audit log rows', err);\n }\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): boolean => {\n if (process.env.DISABLE_AUDIT_LOGS === 'true') {\n return false;\n }\n auditLogger = new AuditLogger(options);\n auditLogger.registerHooks();\n return true;\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":"kPAkEA,IA3BY,kBAAA,SAAA,EAAL,QACL,EAAA,OAAA,SACA,EAAA,YAAA,cACA,EAAA,UAAA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