@servicetitan/log-service 40.3.0 → 41.0.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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/log-storage.ts"],"sourcesContent":["import { inject, injectable, Store } from '@servicetitan/react-ioc';\nimport { action, makeObservable, observable, toJS } from 'mobx';\nimport { EntryComplete, Nullable } from './log';\nimport type { LogConfig } from './log-config';\nimport { LOG_CONFIG_TOKEN } from './log-config';\n\nexport interface StorageItem {\n id: number;\n type: string;\n category: Nullable<string>;\n code: Nullable<string>;\n message: Nullable<string>;\n data: string;\n exception: string;\n}\n\nenum EventType {\n Delete = 'delete',\n}\n\ninterface DeleteEvent {\n type: EventType;\n items: StorageItem[];\n}\n\n@injectable()\nexport class LogStorage extends Store {\n @observable\n items: StorageItem[] = [];\n\n private readonly maxLogSize = 1000;\n private readonly version = 1;\n\n private nextItemId: number;\n private readonly channel?: BroadcastChannel;\n\n constructor(@inject(LOG_CONFIG_TOKEN) private readonly logConfig: LogConfig) {\n super();\n makeObservable(this);\n\n const version = window.parseInt(localStorage.getItem(this.storageVersionKey) as string);\n if (version !== this.version) {\n localStorage.removeItem(this.storageKey);\n }\n\n this.loadSavedItems();\n this.nextItemId = lastId(this.items) + 1;\n\n /*\n * Use the BroadcastChannel API to prevent different tabs from processing\n * the saved items. The first one to process the items sends a \"delete\" event\n * that causes all other instances to discard them from memory.\n */\n if ('BroadcastChannel' in globalThis) {\n this.channel = new BroadcastChannel(logConfig.storageKey);\n this.channel.addEventListener('message', ({ data }: MessageEvent<DeleteEvent>) =>\n this.handleDeleteEvent(data)\n );\n }\n }\n\n dispose() {\n this.channel?.close();\n }\n\n get config(): LogConfig {\n return this.logConfig;\n }\n\n store(entry: EntryComplete) {\n const item: StorageItem = {\n id: this.nextItemId++,\n type: entry.type,\n category: entry.category,\n code: entry.code,\n message: entry.message,\n data: JSON.stringify(entry.data),\n exception: this.stringifyError(entry.error),\n };\n\n let items = [...this.items, item];\n items = items.slice(-this.maxLogSize);\n this.setItems(items);\n }\n\n deleteToId(id: number) {\n const deletedItems: StorageItem[] = [];\n const items = this.items.filter(item => {\n if (item.id > id) {\n return true;\n }\n deletedItems.push(item);\n return false;\n });\n\n this.setItems(items);\n this.postDeleteEvent(deletedItems);\n }\n\n loadBatch(batchSize: number) {\n return this.items.slice(0, batchSize);\n }\n\n private loadSavedItems() {\n try {\n const items = JSON.parse(localStorage.getItem(this.storageKey) as string) ?? [];\n\n /* migrate error -> exception */\n items.forEach((item: StorageItem & { error?: string }) => {\n if (typeof item.error === 'string') {\n item.exception = item.error;\n delete item.error;\n }\n });\n this.setItems(items);\n } catch {\n this.setItems([]);\n }\n }\n\n private postDeleteEvent(items: StorageItem[]) {\n if (this.channel) {\n const event: DeleteEvent = {\n type: EventType.Delete,\n items: items.map(item => toJS(item)),\n };\n this.channel.postMessage(event);\n }\n }\n\n private handleDeleteEvent(event: DeleteEvent) {\n /* istanbul ignore next: because there's only one event type */\n if (event.type !== EventType.Delete) {\n return;\n }\n\n // Map item id to object for fast lookup\n const map = new Map<number, StorageItem>(event.items.map(item => [item.id, item]));\n\n // Discard deleted items\n const items = this.items.filter(item => !isEqual(item, map.get(item.id)));\n this.setItems(items);\n }\n\n @action\n private setItems(items: StorageItem[]) {\n this.items = [...items];\n try {\n localStorage.setItem(this.storageVersionKey, String(this.version));\n localStorage.setItem(this.storageKey, JSON.stringify(this.items));\n } catch {\n /* Storage may be full; logging must not throw into the caller. */\n }\n }\n\n private get storageKey() {\n return this.logConfig.storageKey;\n }\n\n private get storageVersionKey() {\n return `${this.storageKey}Version`;\n }\n\n private stringifyError(error: Nullable<Error>) {\n const detail = error ? { message: error.message.toString(), stack: error.stack } : null;\n return JSON.stringify(detail);\n }\n}\n\nfunction isEqual(a: StorageItem, b?: StorageItem) {\n return b && Object.keys(a).every((key: keyof StorageItem) => a[key] === b[key]);\n}\n\nexport function lastId(items: StorageItem[]): number {\n if (!items.length) {\n return 0;\n }\n const item = items[items.length - 1];\n return item.id;\n}\n"],"names":["inject","injectable","Store","action","makeObservable","observable","toJS","LOG_CONFIG_TOKEN","EventType","LogStorage","dispose","channel","close","config","logConfig","store","entry","item","id","nextItemId","type","category","code","message","data","JSON","stringify","exception","stringifyError","error","items","slice","maxLogSize","setItems","deleteToId","deletedItems","filter","push","postDeleteEvent","loadBatch","batchSize","loadSavedItems","parse","localStorage","getItem","storageKey","forEach","event","map","postMessage","handleDeleteEvent","Map","isEqual","get","setItem","storageVersionKey","String","version","detail","toString","stack","window","parseInt","removeItem","lastId","globalThis","BroadcastChannel","addEventListener","a","b","Object","keys","every","key","length"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAASA,MAAM,EAAEC,UAAU,EAAEC,KAAK,QAAQ,0BAA0B;AACpE,SAASC,MAAM,EAAEC,cAAc,EAAEC,UAAU,EAAEC,IAAI,QAAQ,OAAO;AAGhE,SAASC,gBAAgB,QAAQ,eAAe;AAYhD,IAAA,AAAKC,mCAAAA;;WAAAA;EAAAA;AAUL,OAAO,MAAMC,mBAAmBP;IAmC5BQ,UAAU;YACN;SAAA,gBAAA,IAAI,CAACC,OAAO,cAAZ,oCAAA,cAAcC,KAAK;IACvB;IAEA,IAAIC,SAAoB;QACpB,OAAO,IAAI,CAACC,SAAS;IACzB;IAEAC,MAAMC,KAAoB,EAAE;QACxB,MAAMC,OAAoB;YACtBC,IAAI,IAAI,CAACC,UAAU;YACnBC,MAAMJ,MAAMI,IAAI;YAChBC,UAAUL,MAAMK,QAAQ;YACxBC,MAAMN,MAAMM,IAAI;YAChBC,SAASP,MAAMO,OAAO;YACtBC,MAAMC,KAAKC,SAAS,CAACV,MAAMQ,IAAI;YAC/BG,WAAW,IAAI,CAACC,cAAc,CAACZ,MAAMa,KAAK;QAC9C;QAEA,IAAIC,QAAQ;eAAI,IAAI,CAACA,KAAK;YAAEb;SAAK;QACjCa,QAAQA,MAAMC,KAAK,CAAC,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aAAaC,OAAO,CAAC,IAAI,CAACW,iBAAiB;QAC3E,IAAIE,YAAY,IAAI,CAACA,OAAO,EAAE;YAC1Bd,aAAaoB,UAAU,CAAC,IAAI,CAAClB,UAAU;QAC3C;QAEA,IAAI,CAACJ,cAAc;QACnB,IAAI,CAACtB,UAAU,GAAG6C,OAAO,IAAI,CAAClC,KAAK,IAAI;QAEvC;;;;SAIC,GACD,IAAI,sBAAsBmC,YAAY;YAClC,IAAI,CAACtD,OAAO,GAAG,IAAIuD,iBAAiBpD,UAAU+B,UAAU;YACxD,IAAI,CAAClC,OAAO,CAACwD,gBAAgB,CAAC,WAAW,CAAC,EAAE3C,IAAI,EAA6B,GACzE,IAAI,CAAC0B,iBAAiB,CAAC1B;QAE/B;IACJ;AA4GJ;;;;;;;;;;;;;;;;;;;;;AAEA,SAAS4B,QAAQgB,CAAc,EAAEC,CAAe;IAC5C,OAAOA,KAAKC,OAAOC,IAAI,CAACH,GAAGI,KAAK,CAAC,CAACC,MAA2BL,CAAC,CAACK,IAAI,KAAKJ,CAAC,CAACI,IAAI;AAClF;AAEA,OAAO,SAAST,OAAOlC,KAAoB;IACvC,IAAI,CAACA,MAAM4C,MAAM,EAAE;QACf,OAAO;IACX;IACA,MAAMzD,OAAOa,KAAK,CAACA,MAAM4C,MAAM,GAAG,EAAE;IACpC,OAAOzD,KAAKC,EAAE;AAClB"}
1
+ {"version":3,"sources":["../src/log-storage.ts"],"sourcesContent":["import { inject, injectable, Store } from '@servicetitan/react-ioc';\nimport { action, makeObservable, observable, toJS } from 'mobx';\nimport { EntryComplete, Nullable } from './log';\nimport type { LogConfig } from './log-config';\nimport { LOG_CONFIG_TOKEN } from './log-config';\n\nexport interface StorageItem {\n id: number;\n type: string;\n category: Nullable<string>;\n code: Nullable<string>;\n message: Nullable<string>;\n data: string;\n exception: string;\n}\n\nenum EventType {\n Delete = 'delete',\n}\n\ninterface DeleteEvent {\n type: EventType;\n items: StorageItem[];\n}\n\n@injectable()\nexport class LogStorage extends Store {\n @observable\n items: StorageItem[] = [];\n\n private readonly maxLogSize = 1000;\n private readonly version = 1;\n\n private nextItemId: number;\n private readonly channel?: BroadcastChannel;\n\n constructor(@inject(LOG_CONFIG_TOKEN) private readonly logConfig: LogConfig) {\n super();\n makeObservable(this);\n\n const version = window.parseInt(localStorage.getItem(this.storageVersionKey) as string);\n if (version !== this.version) {\n localStorage.removeItem(this.storageKey);\n }\n\n this.loadSavedItems();\n this.nextItemId = lastId(this.items) + 1;\n\n /*\n * Use the BroadcastChannel API to prevent different tabs from processing\n * the saved items. The first one to process the items sends a \"delete\" event\n * that causes all other instances to discard them from memory.\n */\n if ('BroadcastChannel' in globalThis) {\n this.channel = new BroadcastChannel(logConfig.storageKey);\n this.channel.addEventListener('message', ({ data }: MessageEvent<DeleteEvent>) =>\n this.handleDeleteEvent(data)\n );\n }\n }\n\n dispose() {\n this.channel?.close();\n }\n\n get config(): LogConfig {\n return this.logConfig;\n }\n\n store(entry: EntryComplete) {\n const item: StorageItem = {\n id: this.nextItemId++,\n type: entry.type,\n category: entry.category,\n code: entry.code,\n message: entry.message,\n data: JSON.stringify(entry.data),\n exception: this.stringifyError(entry.error),\n };\n\n let items = [...this.items, item];\n items = items.slice(-this.maxLogSize);\n this.setItems(items);\n }\n\n deleteToId(id: number) {\n const deletedItems: StorageItem[] = [];\n const items = this.items.filter(item => {\n if (item.id > id) {\n return true;\n }\n deletedItems.push(item);\n return false;\n });\n\n this.setItems(items);\n this.postDeleteEvent(deletedItems);\n }\n\n loadBatch(batchSize: number) {\n return this.items.slice(0, batchSize);\n }\n\n private loadSavedItems() {\n try {\n const items = JSON.parse(localStorage.getItem(this.storageKey) as string) ?? [];\n\n /* migrate error -> exception */\n items.forEach((item: StorageItem & { error?: string }) => {\n if (typeof item.error === 'string') {\n item.exception = item.error;\n delete item.error;\n }\n });\n this.setItems(items);\n } catch {\n this.setItems([]);\n }\n }\n\n private postDeleteEvent(items: StorageItem[]) {\n if (this.channel) {\n const event: DeleteEvent = {\n type: EventType.Delete,\n items: items.map(item => toJS(item)),\n };\n this.channel.postMessage(event);\n }\n }\n\n private handleDeleteEvent(event: DeleteEvent) {\n /* istanbul ignore next: because there's only one event type */\n if (event.type !== EventType.Delete) {\n return;\n }\n\n // Map item id to object for fast lookup\n const map = new Map<number, StorageItem>(event.items.map(item => [item.id, item]));\n\n // Discard deleted items\n const items = this.items.filter(item => !isEqual(item, map.get(item.id)));\n this.setItems(items);\n }\n\n @action\n private setItems(items: StorageItem[]) {\n this.items = [...items];\n try {\n localStorage.setItem(this.storageVersionKey, String(this.version));\n localStorage.setItem(this.storageKey, JSON.stringify(this.items));\n } catch {\n /* Storage may be full; logging must not throw into the caller. */\n }\n }\n\n private get storageKey() {\n return this.logConfig.storageKey;\n }\n\n private get storageVersionKey() {\n return `${this.storageKey}Version`;\n }\n\n private stringifyError(error: Nullable<Error>) {\n const detail = error ? { message: error.message.toString(), stack: error.stack } : null;\n return JSON.stringify(detail);\n }\n}\n\nfunction isEqual(a: StorageItem, b?: StorageItem) {\n return b && Object.keys(a).every((key: keyof StorageItem) => a[key] === b[key]);\n}\n\nexport function lastId(items: StorageItem[]): number {\n if (!items.length) {\n return 0;\n }\n const item = items[items.length - 1];\n return item.id;\n}\n"],"names":["inject","injectable","Store","action","makeObservable","observable","toJS","LOG_CONFIG_TOKEN","EventType","LogStorage","dispose","channel","close","config","logConfig","store","entry","item","id","nextItemId","type","category","code","message","data","JSON","stringify","exception","stringifyError","error","items","slice","maxLogSize","setItems","deleteToId","deletedItems","filter","push","postDeleteEvent","loadBatch","batchSize","loadSavedItems","parse","localStorage","getItem","storageKey","forEach","event","map","postMessage","handleDeleteEvent","Map","isEqual","get","setItem","storageVersionKey","String","version","detail","toString","stack","window","parseInt","removeItem","lastId","globalThis","BroadcastChannel","addEventListener","a","b","Object","keys","every","key","length"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAASA,MAAM,EAAEC,UAAU,EAAEC,KAAK,Q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QAAQgB,CAAc,EAAEC,CAAe;IAC5C,OAAOA,KAAKC,OAAOC,IAAI,CAACH,GAAGI,KAAK,CAAC,CAACC,MAA2BL,CAAC,CAACK,IAAI,KAAKJ,CAAC,CAACI,IAAI;AAClF;AAEA,OAAO,SAAST,OAAOlC,KAAoB;IACvC,IAAI,CAACA,MAAM4C,MAAM,EAAE;QACf,OAAO;IACX;IACA,MAAMzD,OAAOa,KAAK,CAACA,MAAM4C,MAAM,GAAG,EAAE;IACpC,OAAOzD,KAAKC,EAAE;AAClB"}
package/dist/log.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/log.ts"],"sourcesContent":["import { inject, injectable, optional, symbolToken } from '@servicetitan/react-ioc';\nimport throttle from 'lodash.throttle';\nimport { defaultLogConfig } from './log-config';\nimport { LogStorage } from './log-storage';\nimport { serializeWithMetadata } from './serialize-with-metadata';\n\nexport { LOG_CONFIG_TOKEN } from './log-config';\nexport type { LogConfig } from './log-config';\n\nexport interface ArbitraryData extends Record<string, boolean | number | string | Date> {}\n\nexport interface LogEntry {\n category?: string;\n code?: string;\n message?: string;\n data?: ArbitraryData;\n}\n\nexport interface LogInfo extends LogEntry {}\n\nexport interface LogWarning extends LogEntry {}\n\nexport interface LogError extends LogEntry {\n error: unknown;\n}\n\nexport interface ErrorOptions {\n skipConsole?: boolean;\n}\n\nexport interface ILog {\n info(entry: LogInfo): void;\n warning(entry: LogWarning): void;\n error(entry: LogError, options?: ErrorOptions): void;\n}\n\nexport enum LogEntryType {\n Info = 'Info',\n Warning = 'Warning',\n Error = 'Error',\n}\n\nexport type Nullable<T> = T | null;\n\nexport interface EntryComplete {\n type: LogEntryType;\n category: Nullable<string>;\n code: Nullable<string>;\n message: Nullable<string>;\n data: ArbitraryData;\n error: Nullable<Error>;\n}\n\nexport type EntryCompleteError = EntryComplete & {\n error: Error;\n};\n\nexport const LOG_PARENT_TOKEN = symbolToken<Log>('LOG_PARENT_TOKEN');\n\nfunction ensureError(error: unknown): Error {\n if (error instanceof Error) {\n return error;\n }\n if (typeof error === 'string') {\n return new Error(error);\n }\n return new Error(serializeWithMetadata(error));\n}\n\n@injectable()\nexport class Log implements ILog {\n private errorLogHandler: ErrorLogHandler;\n\n constructor(\n @inject(LogStorage) private readonly logStorage: LogStorage,\n @inject(LOG_PARENT_TOKEN) @optional() private readonly parent?: Log\n ) {\n this.validate();\n this.errorLogHandler = new ErrorLogHandler(this, this.logStorage);\n }\n\n info(entry: LogInfo): void {\n this.parent?.info(entry);\n return this.store(this.expand(LogEntryType.Info, entry));\n }\n\n warning(entry: LogWarning): void {\n this.parent?.warning(entry);\n return this.store(this.expand(LogEntryType.Warning, entry));\n }\n\n error(entry: LogError, { skipConsole = false } = {}): void {\n this.parent?.error(entry);\n if (!skipConsole) {\n // eslint-disable-next-line no-console\n console.error(\n '@log-service/error',\n entry,\n ensureError(entry?.error ?? entry?.message ?? 'Undefined entry')\n );\n }\n return this.errorLogHandler.handle(this.expandError(entry)); // with errorLogHandler throttling\n }\n\n private store(entry: EntryComplete) {\n return this.logStorage.store(entry);\n }\n\n private expand(type: LogEntryType, entry: LogEntry): EntryComplete {\n const data = {\n ...entry.data,\n ...this.dataDefault(),\n };\n\n return {\n type,\n category: null,\n message: null,\n code: null,\n ...entry,\n error: null,\n data,\n };\n }\n\n private expandError(entry: LogError): EntryCompleteError {\n let error: Error;\n if (entry.error instanceof Error) {\n error = entry.error;\n } else {\n error = new Error(serializeWithMetadata(entry.error));\n }\n\n const { message, ...rest } = this.expand(LogEntryType.Error, entry);\n\n return {\n message: message ?? error.message,\n ...rest,\n error,\n };\n }\n\n private dataDefault() {\n return {\n CreatedOn: new Date(),\n Online: window.navigator.onLine,\n Url: window.location.toString(),\n UserAgent: window.navigator.userAgent,\n Source: 'Frontend',\n Plugins: plugins(),\n ...timezoneInfo(),\n };\n }\n\n private validate() {\n if (!this.parent) {\n return;\n }\n\n const { endpoint, storageKey } = this.logStorage.config;\n if (endpoint === defaultLogConfig.endpoint || storageKey === defaultLogConfig.storageKey) {\n throw new Error('nested Log cannot use default configuration');\n }\n }\n}\n\nclass ErrorLogHandler {\n private logService: Log;\n private logStorage: LogStorage;\n\n private logTable = new HashTable<EntryCompleteError>();\n private repetitiveLogsCache = new HashTable<boolean>();\n\n private readonly cacheFlushDuration = 30000;\n private readonly throttleLogsDuration = 2000;\n\n private flushThrottled = throttle(() => this.flush(), this.throttleLogsDuration, {\n leading: false,\n trailing: true,\n });\n\n constructor(logService: Log, logStorage: LogStorage) {\n this.logService = logService;\n this.logStorage = logStorage;\n\n setInterval(() => this.repetitiveLogsCache.clear(), this.cacheFlushDuration);\n }\n\n handle(entry: EntryCompleteError) {\n this.add(entry);\n this.flushThrottled();\n }\n\n private add(entry: EntryCompleteError) {\n const key = this.keyFor(entry);\n if (this.repetitiveLogsCache.get(key)) {\n /* error is a repetitive error and has been reported, we don't need to report it again */\n return;\n }\n\n if (this.logTable.get(key) == null) {\n this.logTable.set(key, entry);\n } else {\n /* present in entry table, hence a duplicate, don't set, rather increase count */\n const entry = this.logTable.get(key) as EntryCompleteError & {\n data: { count?: number };\n };\n if (typeof entry.data.count === 'number') {\n entry.data.count++;\n } else {\n entry.data.count = 2;\n }\n this.logTable.set(key, entry);\n }\n }\n\n private keyFor(entry: EntryCompleteError) {\n return {\n message: entry.error.message,\n stack: entry.error.stack ?? '',\n };\n }\n\n private flush() {\n const hashes = this.logTable.getHashes();\n for (const key of hashes) {\n const entry = this.logTable.get(key);\n\n if ('count' in entry.data) {\n /* insert into cache if it is a repetitive error */\n this.repetitiveLogsCache.set(key, true);\n }\n\n this.logStorage.store(entry);\n }\n\n this.logTable.clear();\n }\n}\n\nclass HashTable<T> {\n private hashes: Record<string, T> = {};\n\n set(key: { message: string; stack: string }, value: T) {\n this.hashes[JSON.stringify(key)] = value;\n }\n\n get(key: { message: string; stack: string }): T {\n return this.hashes[JSON.stringify(key)];\n }\n\n getHashes() {\n return Object.keys(this.hashes).map(value => JSON.parse(value));\n }\n\n clear() {\n this.hashes = {};\n }\n}\n\nfunction plugins() {\n try {\n return Array.prototype.slice\n .call(window.navigator.plugins)\n .map(p => [p.name, p.filename, p.description].join(','))\n .join('/');\n } catch {\n return 'unknown';\n }\n}\n\nfunction timezoneInfo() {\n // https://stackoverflow.com/questions/11887934/how-to-check-if-dst-daylight-saving-time-is-in-effect-and-if-so-the-offset\n\n const now = new Date();\n const jan = new Date(now.getFullYear(), 0, 1);\n const jul = new Date(now.getFullYear(), 6, 1);\n\n const TzOffset = now.getTimezoneOffset();\n const IsDst = TzOffset < Math.max(jan.getTimezoneOffset(), jul.getTimezoneOffset());\n const IsDstSubject = jan.getTimezoneOffset() !== jul.getTimezoneOffset();\n\n return {\n TzOffset,\n IsDst,\n IsDstSubject,\n };\n}\n"],"names":["inject","injectable","optional","symbolToken","throttle","defaultLogConfig","LogStorage","serializeWithMetadata","LOG_CONFIG_TOKEN","LogEntryType","LOG_PARENT_TOKEN","ensureError","error","Error","Log","info","entry","parent","store","expand","warning","skipConsole","console","message","errorLogHandler","handle","expandError","logStorage","type","data","dataDefault","category","code","rest","CreatedOn","Date","Online","window","navigator","onLine","Url","location","toString","UserAgent","userAgent","Source","Plugins","plugins","timezoneInfo","validate","endpoint","storageKey","config","ErrorLogHandler","add","flushThrottled","key","keyFor","repetitiveLogsCache","get","logTable","set","count","stack","flush","hashes","getHashes","clear","logService","HashTable","cacheFlushDuration","throttleLogsDuration","leading","trailing","setInterval","value","JSON","stringify","Object","keys","map","parse","Array","prototype","slice","call","p","name","filename","description","join","now","jan","getFullYear","jul","TzOffset","getTimezoneOffset","IsDst","Math","max","IsDstSubject"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAASA,MAAM,EAAEC,UAAU,EAAEC,QAAQ,EAAEC,WAAW,QAAQ,0BAA0B;AACpF,OAAOC,cAAc,kBAAkB;AACvC,SAASC,gBAAgB,QAAQ,eAAe;AAChD,SAASC,UAAU,QAAQ,gBAAgB;AAC3C,SAAS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gBAAEF,EAAEG,WAAW;aAAC,CAACC,IAAI,CAAC,MAClDA,IAAI,CAAC;IACd,EAAE,eAAM;QACJ,OAAO;IACX;AACJ;AAEA,SAAS1C;IACL,0HAA0H;IAE1H,MAAM2C,MAAM,IAAIxD;IAChB,MAAMyD,MAAM,IAAIzD,KAAKwD,IAAIE,WAAW,IAAI,GAAG;IAC3C,MAAMC,MAAM,IAAI3D,KAAKwD,IAAIE,WAAW,IAAI,GAAG;IAE3C,MAAME,WAAWJ,IAAIK,iBAAiB;IACtC,MAAMC,QAAQF,WAAWG,KAAKC,GAAG,CAACP,IAAII,iBAAiB,IAAIF,IAAIE,iBAAiB;IAChF,MAAMI,eAAeR,IAAII,iBAAiB,OAAOF,IAAIE,iBAAiB;IAEtE,OAAO;QACHD;QACAE;QACAG;IACJ;AACJ"}
1
+ {"version":3,"sources":["../src/log.ts"],"sourcesContent":["import { inject, injectable, optional, symbolToken } from '@servicetitan/react-ioc';\nimport throttle from 'lodash.throttle';\nimport { defaultLogConfig } from './log-config';\nimport { LogStorage } from './log-storage';\nimport { serializeWithMetadata } from './serialize-with-metadata';\n\nexport { LOG_CONFIG_TOKEN } from './log-config';\nexport type { LogConfig } from './log-config';\n\nexport interface ArbitraryData extends Record<string, boolean | number | string | Date> {}\n\nexport interface LogEntry {\n category?: string;\n code?: string;\n message?: string;\n data?: ArbitraryData;\n}\n\nexport interface LogInfo extends LogEntry {}\n\nexport interface LogWarning extends LogEntry {}\n\nexport interface LogError extends LogEntry {\n error: unknown;\n}\n\nexport interface ErrorOptions {\n skipConsole?: boolean;\n}\n\nexport interface ILog {\n info(entry: LogInfo): void;\n warning(entry: LogWarning): void;\n error(entry: LogError, options?: ErrorOptions): void;\n}\n\nexport enum LogEntryType {\n Info = 'Info',\n Warning = 'Warning',\n Error = 'Error',\n}\n\nexport type Nullable<T> = T | null;\n\nexport interface EntryComplete {\n type: LogEntryType;\n category: Nullable<string>;\n code: Nullable<string>;\n message: Nullable<string>;\n data: ArbitraryData;\n error: Nullable<Error>;\n}\n\nexport type EntryCompleteError = EntryComplete & {\n error: Error;\n};\n\nexport const LOG_PARENT_TOKEN = symbolToken<Log>('LOG_PARENT_TOKEN');\n\nfunction ensureError(error: unknown): Error {\n if (error instanceof Error) {\n return error;\n }\n if (typeof error === 'string') {\n return new Error(error);\n }\n return new Error(serializeWithMetadata(error));\n}\n\n@injectable()\nexport class Log implements ILog {\n private errorLogHandler: ErrorLogHandler;\n\n constructor(\n @inject(LogStorage) private readonly logStorage: LogStorage,\n @inject(LOG_PARENT_TOKEN) @optional() private readonly parent?: Log\n ) {\n this.validate();\n this.errorLogHandler = new ErrorLogHandler(this, this.logStorage);\n }\n\n info(entry: LogInfo): void {\n this.parent?.info(entry);\n return this.store(this.expand(LogEntryType.Info, entry));\n }\n\n warning(entry: LogWarning): void {\n this.parent?.warning(entry);\n return this.store(this.expand(LogEntryType.Warning, entry));\n }\n\n error(entry: LogError, { skipConsole = false } = {}): void {\n this.parent?.error(entry);\n if (!skipConsole) {\n // eslint-disable-next-line no-console\n console.error(\n '@log-service/error',\n entry,\n ensureError(entry?.error ?? entry?.message ?? 'Undefined entry')\n );\n }\n return this.errorLogHandler.handle(this.expandError(entry)); // with errorLogHandler throttling\n }\n\n private store(entry: EntryComplete) {\n return this.logStorage.store(entry);\n }\n\n private expand(type: LogEntryType, entry: LogEntry): EntryComplete {\n const data = {\n ...entry.data,\n ...this.dataDefault(),\n };\n\n return {\n type,\n category: null,\n message: null,\n code: null,\n ...entry,\n error: null,\n data,\n };\n }\n\n private expandError(entry: LogError): EntryCompleteError {\n let error: Error;\n if (entry.error instanceof Error) {\n error = entry.error;\n } else {\n error = new Error(serializeWithMetadata(entry.error));\n }\n\n const { message, ...rest } = this.expand(LogEntryType.Error, entry);\n\n return {\n message: message ?? error.message,\n ...rest,\n error,\n };\n }\n\n private dataDefault() {\n return {\n CreatedOn: new Date(),\n Online: window.navigator.onLine,\n Url: window.location.toString(),\n UserAgent: window.navigator.userAgent,\n Source: 'Frontend',\n Plugins: plugins(),\n ...timezoneInfo(),\n };\n }\n\n private validate() {\n if (!this.parent) {\n return;\n }\n\n const { endpoint, storageKey } = this.logStorage.config;\n if (endpoint === defaultLogConfig.endpoint || storageKey === defaultLogConfig.storageKey) {\n throw new Error('nested Log cannot use default configuration');\n }\n }\n}\n\nclass ErrorLogHandler {\n private logService: Log;\n private logStorage: LogStorage;\n\n private logTable = new HashTable<EntryCompleteError>();\n private repetitiveLogsCache = new HashTable<boolean>();\n\n private readonly cacheFlushDuration = 30000;\n private readonly throttleLogsDuration = 2000;\n\n private flushThrottled = throttle(() => this.flush(), this.throttleLogsDuration, {\n leading: false,\n trailing: true,\n });\n\n constructor(logService: Log, logStorage: LogStorage) {\n this.logService = logService;\n this.logStorage = logStorage;\n\n setInterval(() => this.repetitiveLogsCache.clear(), this.cacheFlushDuration);\n }\n\n handle(entry: EntryCompleteError) {\n this.add(entry);\n this.flushThrottled();\n }\n\n private add(entry: EntryCompleteError) {\n const key = this.keyFor(entry);\n if (this.repetitiveLogsCache.get(key)) {\n /* error is a repetitive error and has been reported, we don't need to report it again */\n return;\n }\n\n if (this.logTable.get(key) == null) {\n this.logTable.set(key, entry);\n } else {\n /* present in entry table, hence a duplicate, don't set, rather increase count */\n const entry = this.logTable.get(key) as EntryCompleteError & {\n data: { count?: number };\n };\n if (typeof entry.data.count === 'number') {\n entry.data.count++;\n } else {\n entry.data.count = 2;\n }\n this.logTable.set(key, entry);\n }\n }\n\n private keyFor(entry: EntryCompleteError) {\n return {\n message: entry.error.message,\n stack: entry.error.stack ?? '',\n };\n }\n\n private flush() {\n const hashes = this.logTable.getHashes();\n for (const key of hashes) {\n const entry = this.logTable.get(key);\n\n if ('count' in entry.data) {\n /* insert into cache if it is a repetitive error */\n this.repetitiveLogsCache.set(key, true);\n }\n\n this.logStorage.store(entry);\n }\n\n this.logTable.clear();\n }\n}\n\nclass HashTable<T> {\n private hashes: Record<string, T> = {};\n\n set(key: { message: string; stack: string }, value: T) {\n this.hashes[JSON.stringify(key)] = value;\n }\n\n get(key: { message: string; stack: string }): T {\n return this.hashes[JSON.stringify(key)];\n }\n\n getHashes() {\n return Object.keys(this.hashes).map(value => JSON.parse(value));\n }\n\n clear() {\n this.hashes = {};\n }\n}\n\nfunction plugins() {\n try {\n return Array.prototype.slice\n .call(window.navigator.plugins)\n .map(p => [p.name, p.filename, p.description].join(','))\n .join('/');\n } catch {\n return 'unknown';\n }\n}\n\nfunction timezoneInfo() {\n // https://stackoverflow.com/questions/11887934/how-to-check-if-dst-daylight-saving-time-is-in-effect-and-if-so-the-offset\n\n const now = new Date();\n const jan = new Date(now.getFullYear(), 0, 1);\n const jul = new Date(now.getFullYear(), 6, 1);\n\n const TzOffset = now.getTimezoneOffset();\n const IsDst = TzOffset < Math.max(jan.getTimezoneOffset(), jul.getTimezoneOffset());\n const IsDstSubject = jan.getTimezoneOffset() !== jul.getTimezoneOffset();\n\n return {\n TzOffset,\n IsDst,\n IsDstSubject,\n };\n}\n"],"names":["inject","injectable","optional","symbolToken","throttle","defaultLogConfig","LogStorage","serializeWithMetadata","LOG_CONFIG_TOKEN","LogEntryType","LOG_PARENT_TOKEN","ensureError","error","Error","Log","info","entry","parent","store","expand","warning","skipConsole","console","message","errorLogHandler","handle","expandError","logStorage","type","data","dataDefault","category","code","rest","CreatedOn","Date","Online","window","navigator","onLine","Url","location","toString","UserAgent","userAgent","Source","Plugins","plugins","timezoneInfo","validate","endpoint","storageKey","config","ErrorLogHandler","add","flushThrottled","key","keyFor","repetitiveLogsCache","get","logTable","set","count","stack","flush","hashes","getHashes","clear","logService","HashTable","cacheFlushDuration","throttleLogsDuration","leading","trailing","setInterval","value","JSON","stringify","Object","keys","map","parse","Array","prototype","slice","call","p","name","filename","description","join","now","jan","getFullYear","jul","TzOffset","getTimezoneOffset","IsDst","Math","max","IsDstSubject"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAASA,MAAM,EAAEC,UAAU,EAAE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,KAAK,CACvBC,IAAI,CAAChD,OAAOC,SAAS,CAACS,OAAO,EAC7BiC,GAAG,CAACM,CAAAA,IAAK;gBAACA,EAAEC,IAAI;gBAAED,EAAEE,QAAQ;gBAAEF,EAAEG,WAAW;aAAC,CAACC,IAAI,CAAC,MAClDA,IAAI,CAAC;IACd,EAAE,eAAM;QACJ,OAAO;IACX;AACJ;AAEA,SAAS1C;IACL,0HAA0H;IAE1H,MAAM2C,MAAM,IAAIxD;IAChB,MAAMyD,MAAM,IAAIzD,KAAKwD,IAAIE,WAAW,IAAI,GAAG;IAC3C,MAAMC,MAAM,IAAI3D,KAAKwD,IAAIE,WAAW,IAAI,GAAG;IAE3C,MAAME,WAAWJ,IAAIK,iBAAiB;IACtC,MAAMC,QAAQF,WAAWG,KAAKC,GAAG,CAACP,IAAII,iBAAiB,IAAIF,IAAIE,iBAAiB;IAChF,MAAMI,eAAeR,IAAII,iBAAiB,OAAOF,IAAIE,iBAAiB;IAEtE,OAAO;QACHD;QACAE;QACAG;IACJ;AACJ"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@servicetitan/log-service",
3
- "version": "40.3.0",
3
+ "version": "41.0.0",
4
4
  "description": "Service to send events to Kibana logs via the backend log service",
5
5
  "homepage": "https://docs.st.dev/docs/frontend/uikit/log-service",
6
6
  "repository": {
@@ -20,16 +20,16 @@
20
20
  "!**/*.test.*"
21
21
  ],
22
22
  "devDependencies": {
23
- "@servicetitan/react-ioc": "40.3.0",
23
+ "@servicetitan/react-ioc": "41.0.0",
24
24
  "@testing-library/dom": "^10.4.2",
25
25
  "@testing-library/react": "^16.3.3",
26
26
  "@types/lodash.throttle": "~4.1.6",
27
- "axios": "^1.21.0",
27
+ "axios": "^1.21.1",
28
28
  "mobx": "~6.16.1",
29
29
  "react": "~18.3.1"
30
30
  },
31
31
  "peerDependencies": {
32
- "@servicetitan/react-ioc": "40.3.0",
32
+ "@servicetitan/react-ioc": "41.0.0",
33
33
  "axios": ">=0.30.0 <1 || ^1.8.3",
34
34
  "mobx": ">=6.13.5",
35
35
  "react": ">=17.0.2"