@servicetitan/log-service 40.2.2 → 40.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.
@@ -16,7 +16,7 @@ export declare class LogStorage extends Store {
16
16
  private readonly maxLogSize;
17
17
  private readonly version;
18
18
  private nextItemId;
19
- private channel?;
19
+ private readonly channel?;
20
20
  constructor(logConfig: LogConfig);
21
21
  dispose(): void;
22
22
  get config(): LogConfig;
@@ -1 +1 @@
1
- {"version":3,"file":"log-storage.d.ts","sourceRoot":"","sources":["../src/log-storage.ts"],"names":[],"mappings":"AAAA,OAAO,EAAsB,KAAK,EAAE,MAAM,yBAAyB,CAAC;AAEpE,OAAO,EAAE,aAAa,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AAChD,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAG9C,MAAM,WAAW,WAAW;IACxB,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,QAAQ,CAAC,MAAM,CAAC,CAAC;IAC3B,IAAI,EAAE,QAAQ,CAAC,MAAM,CAAC,CAAC;IACvB,OAAO,EAAE,QAAQ,CAAC,MAAM,CAAC,CAAC;IAC1B,IAAI,EAAE,MAAM,CAAC;IACb,SAAS,EAAE,MAAM,CAAC;CACrB;AAWD,qBACa,UAAW,SAAQ,KAAK;IAUK,OAAO,CAAC,QAAQ,CAAC,SAAS;IARhE,KAAK,EAAE,WAAW,EAAE,CAAM;IAE1B,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAQ;IACnC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAK;IAE7B,OAAO,CAAC,UAAU,CAAS;IAC3B,OAAO,CAAC,OAAO,CAAC,CAAmB;gBAEoB,SAAS,EAAE,SAAS;IA0B3E,OAAO;IAIP,IAAI,MAAM,IAAI,SAAS,CAEtB;IAED,KAAK,CAAC,KAAK,EAAE,aAAa;IAgB1B,UAAU,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,KAAK,CAAC,KAAK,EAAE,aAAa;IAgB1B,UAAU,CAAC,EAAE,EAAE,MAAM;IAcrB,SAAS,CAAC,SAAS,EAAE,MAAM;IAI3B,OAAO,CAAC,cAAc;IAiBtB,OAAO,CAAC,eAAe;IAUvB,OAAO,CAAC,iBAAiB;IAezB,OAAO,CAAC,QAAQ;IAUhB,OAAO,KAAK,UAAU,GAErB;IAED,OAAO,KAAK,iBAAiB,GAE5B;IAED,OAAO,CAAC,cAAc;CAIzB;AAMD,wBAAgB,MAAM,CAAC,KAAK,EAAE,WAAW,EAAE,GAAG,MAAM,CAMnD"}
@@ -115,17 +115,16 @@ export class LogStorage extends Store {
115
115
  // Discard deleted items
116
116
  const items = this.items.filter((item)=>!isEqual(item, map.get(item.id)));
117
117
  this.setItems(items);
118
- // If no more items, close channel; all saved items have been processed
119
- if (items.length === 0 && this.channel) {
120
- this.channel.close();
121
- delete this.channel;
122
- }
123
118
  }
124
119
  setItems(items) {
125
120
  this.items = [
126
121
  ...items
127
122
  ];
128
- localStorage.setItem(this.storageKey, JSON.stringify(this.items));
123
+ try {
124
+ localStorage.setItem(this.storageVersionKey, String(this.version));
125
+ localStorage.setItem(this.storageKey, JSON.stringify(this.items));
126
+ } catch (unused) {
127
+ /* Storage may be full; logging must not throw into the caller. */ }
129
128
  }
130
129
  get storageKey() {
131
130
  return this.logConfig.storageKey;
@@ -146,7 +145,6 @@ export class LogStorage extends Store {
146
145
  const version = window.parseInt(localStorage.getItem(this.storageVersionKey));
147
146
  if (version !== this.version) {
148
147
  localStorage.removeItem(this.storageKey);
149
- localStorage.setItem(this.storageVersionKey, String(this.version));
150
148
  }
151
149
  this.loadSavedItems();
152
150
  this.nextItemId = lastId(this.items) + 1;
@@ -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 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 localStorage.setItem(this.storageVersionKey, String(this.version));\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 // If no more items, close channel; all saved items have been processed\n if (items.length === 0 && this.channel) {\n this.channel.close();\n delete this.channel;\n }\n }\n\n @action\n private setItems(items: StorageItem[]) {\n this.items = [...items];\n localStorage.setItem(this.storageKey, JSON.stringify(this.items));\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","length","setItem","storageVersionKey","detail","toString","stack","version","window","parseInt","removeItem","String","lastId","globalThis","BroadcastChannel","addEventListener","a","b","Object","keys","every","key"],"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;IAoC5BQ,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,CAAC,IAAI,CAACC,UAAU;QACpC,IAAI,CAACC,QAAQ,CAACH;IAClB;IAEAI,WAAWhB,EAAU,EAAE;QACnB,MAAMiB,eAA8B,EAAE;QACtC,MAAML,QAAQ,IAAI,CAACA,KAAK,CAACM,MAAM,CAACnB,CAAAA;YAC5B,IAAIA,KAAKC,EAAE,GAAGA,IAAI;gBACd,OAAO;YACX;YACAiB,aAAa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IAAI,CAACnB,cAAc;QACnB,IAAI,CAACtB,UAAU,GAAG8C,OAAO,IAAI,CAACnC,KAAK,IAAI;QAEvC;;;;SAIC,GACD,IAAI,sBAAsBoC,YAAY;YAClC,IAAI,CAACvD,OAAO,GAAG,IAAIwD,iBAAiBrD,UAAU+B,UAAU;YACxD,IAAI,CAAClC,OAAO,CAACyD,gBAAgB,CAAC,WAAW,CAAC,EAAE5C,IAAI,EAA6B,GACzE,IAAI,CAAC0B,iBAAiB,CAAC1B;QAE/B;IACJ;AA6GJ;;;;;;;;;;;;;;;;;;;;;AAEA,SAAS4B,QAAQiB,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,OAAOnC,KAAoB;IACvC,IAAI,CAACA,MAAMwB,MAAM,EAAE;QACf,OAAO;IACX;IACA,MAAMrC,OAAOa,KAAK,CAACA,MAAMwB,MAAM,GAAG,EAAE;IACpC,OAAOrC,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,QAAQ,0BAA0B;AACpE,SAASC,MAAM,EAAEC,cAAc,EAAEC,UAAU,EAAEC,IAAI,QAAQ,OAAO;AAGhE,SAASC,gBAAgB,QAAQ,eAAe;AAYhD,IAAA,AAAKC;;;EAA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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,SAASC,qBAAqB,QAAQ,4BAA4B;AAElE,SAASC,gBAAgB,QAAQ,eAAe;AA8BhD,OAAO,IAAA,AAAKC,sCAAAA;;;;WAAAA;MAIX;AAiBD,OAAO,MAAMC,mBAAmBP,YAA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,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,EAAEC,QAAQ,EAAEC,WAAW,QAAQ,0BAA0B;AACpF,OAAOC,cAAc,kBAAkB;AACvC,SAASC,gBAAgB,QAAQ,eAAe;AAChD,SAASC,UAAU,QAAQ,gBAAgB;AAC3C,SAASC,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AAW;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.2.2",
3
+ "version": "40.4.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": {
@@ -13,19 +13,23 @@
13
13
  "sideEffects": false,
14
14
  "files": [
15
15
  "dist",
16
- "src"
16
+ "src",
17
+ "!**/__tests__",
18
+ "!**/__mocks__",
19
+ "!**/__snapshots__",
20
+ "!**/*.test.*"
17
21
  ],
18
22
  "devDependencies": {
19
- "@servicetitan/react-ioc": "40.2.2",
23
+ "@servicetitan/react-ioc": "40.4.0",
20
24
  "@testing-library/dom": "^10.4.2",
21
25
  "@testing-library/react": "^16.3.3",
22
26
  "@types/lodash.throttle": "~4.1.6",
23
- "axios": "^1.20.0",
27
+ "axios": "^1.21.0",
24
28
  "mobx": "~6.16.1",
25
29
  "react": "~18.3.1"
26
30
  },
27
31
  "peerDependencies": {
28
- "@servicetitan/react-ioc": "40.2.2",
32
+ "@servicetitan/react-ioc": "40.4.0",
29
33
  "axios": ">=0.30.0 <1 || ^1.8.3",
30
34
  "mobx": ">=6.13.5",
31
35
  "react": ">=17.0.2"
@@ -32,7 +32,7 @@ export class LogStorage extends Store {
32
32
  private readonly version = 1;
33
33
 
34
34
  private nextItemId: number;
35
- private channel?: BroadcastChannel;
35
+ private readonly channel?: BroadcastChannel;
36
36
 
37
37
  constructor(@inject(LOG_CONFIG_TOKEN) private readonly logConfig: LogConfig) {
38
38
  super();
@@ -41,7 +41,6 @@ export class LogStorage extends Store {
41
41
  const version = window.parseInt(localStorage.getItem(this.storageVersionKey) as string);
42
42
  if (version !== this.version) {
43
43
  localStorage.removeItem(this.storageKey);
44
- localStorage.setItem(this.storageVersionKey, String(this.version));
45
44
  }
46
45
 
47
46
  this.loadSavedItems();
@@ -141,18 +140,17 @@ export class LogStorage extends Store {
141
140
  // Discard deleted items
142
141
  const items = this.items.filter(item => !isEqual(item, map.get(item.id)));
143
142
  this.setItems(items);
144
-
145
- // If no more items, close channel; all saved items have been processed
146
- if (items.length === 0 && this.channel) {
147
- this.channel.close();
148
- delete this.channel;
149
- }
150
143
  }
151
144
 
152
145
  @action
153
146
  private setItems(items: StorageItem[]) {
154
147
  this.items = [...items];
155
- localStorage.setItem(this.storageKey, JSON.stringify(this.items));
148
+ try {
149
+ localStorage.setItem(this.storageVersionKey, String(this.version));
150
+ localStorage.setItem(this.storageKey, JSON.stringify(this.items));
151
+ } catch {
152
+ /* Storage may be full; logging must not throw into the caller. */
153
+ }
156
154
  }
157
155
 
158
156
  private get storageKey() {
@@ -1,39 +0,0 @@
1
- import { EventEmitter } from 'node:events';
2
-
3
- const channels: Map<string, EventEmitter> = new Map();
4
-
5
- export class MockBroadcastChannel implements BroadcastChannel {
6
- onmessage = jest.fn();
7
- onmessageerror = jest.fn();
8
- removeEventListener = jest.fn();
9
- dispatchEvent = jest.fn();
10
-
11
- postMessage = jest.fn().mockImplementation(message => {
12
- const event = { data: message, from: this };
13
- this.emitter.emit('message', event);
14
- });
15
-
16
- addEventListener = jest.fn().mockImplementation((_: string, listener: any) => {
17
- this.emitter.on('message', ({ from, ...event }) => {
18
- if (from !== this) {
19
- listener(event);
20
- }
21
- });
22
- });
23
-
24
- close = jest.fn().mockImplementation(() => {
25
- this.emitter.removeAllListeners();
26
- channels.delete(this.name);
27
- });
28
-
29
- private emitter: EventEmitter;
30
-
31
- constructor(public name: string) {
32
- this.emitter = channels.get(name)!;
33
- if (!this.emitter) {
34
- const emitter = new EventEmitter();
35
- channels.set(name, emitter);
36
- this.emitter = emitter;
37
- }
38
- }
39
- }
@@ -1 +0,0 @@
1
- export * from './broadcast-channel';
@@ -1,23 +0,0 @@
1
- // Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing
2
-
3
- exports[`Serialize with metadata 0 1`] = `"Type:object|Constructor:Error|Value:{}"`;
4
-
5
- exports[`Serialize with metadata 1 1`] = `"Type:object|Constructor:Abc|Value:{"a":1}"`;
6
-
7
- exports[`Serialize with metadata 2 1`] = `"Type:object|Constructor:Object|Value:{"b":1}"`;
8
-
9
- exports[`Serialize with metadata 3 1`] = `"Type:object|Constructor:undefined|Value:null"`;
10
-
11
- exports[`Serialize with metadata 4 1`] = `"Type:undefined|Value:undefined"`;
12
-
13
- exports[`Serialize with metadata 5 1`] = `"Type:function|Name:abc"`;
14
-
15
- exports[`Serialize with metadata 6 1`] = `"Type:number|Value:123"`;
16
-
17
- exports[`Serialize with metadata 7 1`] = `"Type:object|Constructor:Event|EventType:MyEvent|Value:{"isTrusted":false}"`;
18
-
19
- exports[`Serialize with metadata 8 1`] = `
20
- "Type:object|Constructor:Object|Unable to serialize: Converting circular structure to JSON
21
- --> starting at object with constructor 'Object'
22
- | "
23
- `;
@@ -1,56 +0,0 @@
1
- import { ConnectionService } from '../connection-service';
2
-
3
- describe(`[log-service] ${ConnectionService.name}`, () => {
4
- type Mutable<T> = { -readonly [P in keyof T]: T[P] };
5
- const navigator = window.navigator as Mutable<typeof window.navigator>;
6
-
7
- beforeAll(() => {
8
- Object.defineProperty(window.navigator, 'onLine', { value: undefined, writable: true });
9
- });
10
-
11
- const subject = () => new ConnectionService();
12
-
13
- describe('when browser is offline', () => {
14
- beforeEach(() => (navigator.onLine = false));
15
-
16
- test('reports offline', () => {
17
- expect(subject().online).toBe(false);
18
- });
19
-
20
- describe('when browser goes online', () => {
21
- const setup = () => {
22
- const service = subject();
23
- window.dispatchEvent(new Event('online'));
24
- return service;
25
- };
26
-
27
- test('reports online', () => {
28
- const service = setup();
29
-
30
- expect(service.online).toBe(true);
31
- });
32
- });
33
- });
34
-
35
- describe('when browser is online', () => {
36
- beforeEach(() => (navigator.onLine = true));
37
-
38
- test('reports online', () => {
39
- expect(subject().online).toBe(true);
40
- });
41
-
42
- describe('when browser goes offline', () => {
43
- const setup = () => {
44
- const service = subject();
45
- window.dispatchEvent(new Event('offline'));
46
- return service;
47
- };
48
-
49
- test('reports offline', () => {
50
- const service = setup();
51
-
52
- expect(service.online).toBe(false);
53
- });
54
- });
55
- });
56
- });
@@ -1,285 +0,0 @@
1
- import { GlobalErrorHandler } from '../global-error-handler';
2
- import { Log } from '../log';
3
- import { serializeWithMetadata } from '../serialize-with-metadata';
4
-
5
- describe(`[log-service] ${GlobalErrorHandler.name}`, () => {
6
- const log: Pick<Log, 'error'> = { error: jest.fn() };
7
- let handler: GlobalErrorHandler;
8
-
9
- beforeAll(() => (handler = new GlobalErrorHandler(log as Log)));
10
-
11
- beforeEach(() => jest.clearAllMocks());
12
-
13
- describe('onError', () => {
14
- const line = 12;
15
- const column = 34;
16
- const url = 'http://example.com';
17
- let message: string;
18
- let error: Error | undefined;
19
- let isUnhandled: boolean | undefined;
20
-
21
- beforeEach(() => {
22
- message = 'Oops!';
23
- error = new Error('Something went wrong');
24
- isUnhandled = undefined;
25
- });
26
-
27
- const subject = () => handler.onError(message, url, line, column, error, isUnhandled);
28
-
29
- test('reports error', () => {
30
- subject();
31
-
32
- expect(log.error).toHaveBeenCalledWith(
33
- {
34
- error,
35
- message: error!.message,
36
- category: 'UnhandledError',
37
- code: 'UnhandledError',
38
- data: undefined,
39
- },
40
- { skipConsole: true }
41
- );
42
- });
43
-
44
- describe('when error was handled', () => {
45
- beforeEach(() => (isUnhandled = false));
46
-
47
- test('omits category and code', () => {
48
- subject();
49
-
50
- expect(log.error).toHaveBeenCalledWith(
51
- {
52
- error,
53
- message: error!.message,
54
- },
55
- { skipConsole: true }
56
- );
57
- });
58
- });
59
-
60
- describe('with no error', () => {
61
- beforeEach(() => (error = undefined));
62
-
63
- test('reports synthetic error', () => {
64
- subject();
65
-
66
- expect(log.error).toHaveBeenCalledWith(
67
- {
68
- error: expect.objectContaining({
69
- message: `Message - ${message}`,
70
- stack: expect.stringContaining(`${url}:${line}:${column}`),
71
- }),
72
- message: `Message - ${message}`,
73
- category: 'UnhandledError',
74
- code: 'NonUniform',
75
- },
76
- { skipConsole: true }
77
- );
78
- });
79
-
80
- describe('when message is not a string', () => {
81
- beforeEach(() => ((message as any) = { foo: 'bar' }));
82
-
83
- test('serializes message', () => {
84
- subject();
85
-
86
- expect(log.error).toHaveBeenCalledWith(
87
- expect.objectContaining({
88
- message: `Message - ${serializeWithMetadata(message)}`,
89
- }),
90
- { skipConsole: true }
91
- );
92
- });
93
- });
94
- });
95
-
96
- describe('with a non-standard error', () => {
97
- beforeEach(() => ((error as any) = { data: 'foo' }));
98
-
99
- test('serializes error into message', () => {
100
- subject();
101
-
102
- expect(log.error).toHaveBeenCalledWith(
103
- expect.objectContaining({
104
- message: `Message - ${message};Error - ${serializeWithMetadata(error)}`,
105
- }),
106
- { skipConsole: true }
107
- );
108
- });
109
- });
110
-
111
- describe.each([
112
- 'gCrWeb',
113
- 'Geolocation',
114
- 'kCLErrorDomain',
115
- 'The last location provider was disabled',
116
- 'Location services are disabled',
117
- ])('when message contains "%s"', subString => {
118
- beforeEach(() => (message = `foo${subString}bar`));
119
-
120
- test('ignores error', () => {
121
- subject();
122
-
123
- expect(log.error).not.toHaveBeenCalled();
124
- });
125
- });
126
-
127
- describe('when report fails', () => {
128
- const reportError = new Error('Something went wrong');
129
-
130
- beforeEach(() => {
131
- jest.mocked(log.error).mockImplementation(() => {
132
- throw reportError;
133
- });
134
- });
135
-
136
- test('logs failure', () => {
137
- const consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(jest.fn());
138
-
139
- subject();
140
-
141
- expect(consoleErrorSpy).toHaveBeenCalledWith(
142
- '@log-service/onError/failsafe',
143
- message
144
- );
145
- expect(consoleErrorSpy).toHaveBeenCalledWith(
146
- '@log-service/onError/failsafe',
147
- reportError
148
- );
149
- });
150
- });
151
-
152
- describe('with existing readonly error.code and error.category', () => {
153
- const code = 401;
154
- const category = 'foo';
155
-
156
- class MockError extends Error {
157
- get category() {
158
- return category;
159
- }
160
- get code() {
161
- return code;
162
- }
163
- }
164
-
165
- beforeEach(() => (error = new MockError()));
166
-
167
- test('preserves existing values', () => {
168
- subject();
169
-
170
- expect(log.error).toHaveBeenCalledWith(
171
- expect.objectContaining({ category, code }),
172
- expect.anything()
173
- );
174
- });
175
- });
176
- });
177
-
178
- describe('onReject', () => {
179
- let reason: any;
180
-
181
- const subject = () => handler.onReject({ reason });
182
-
183
- describe('when reason is an Error', () => {
184
- const error = new Error('Oops!');
185
-
186
- beforeEach(() => (reason = error));
187
-
188
- test('reports error', () => {
189
- subject();
190
-
191
- expect(log.error).toHaveBeenCalledWith(
192
- {
193
- error,
194
- message: error.message,
195
- },
196
- { skipConsole: true }
197
- );
198
- });
199
- });
200
-
201
- describe('when reason is not an error', () => {
202
- beforeEach(() => (reason = { foo: 'bar' }));
203
-
204
- test('reports synthetic error', () => {
205
- subject();
206
-
207
- const message = `Unhandled rejection - ${serializeWithMetadata(reason)}`;
208
- expect(log.error).toHaveBeenCalledWith(
209
- {
210
- error: expect.objectContaining({ message }),
211
- message,
212
- code: 'NonUniform',
213
- },
214
- { skipConsole: true }
215
- );
216
- });
217
- });
218
-
219
- describe('when report fails', () => {
220
- const reportError = new Error('Something went wrong');
221
-
222
- beforeEach(() => {
223
- jest.mocked(log.error).mockImplementation(() => {
224
- throw reportError;
225
- });
226
- });
227
-
228
- test('logs failure', () => {
229
- const consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(jest.fn());
230
-
231
- subject();
232
-
233
- expect(consoleErrorSpy).toHaveBeenCalledWith(
234
- '@log-service/onReject/failsafe',
235
- reportError
236
- );
237
- });
238
- });
239
- });
240
-
241
- describe('instrument', () => {
242
- let window: { onerror?: any; onunhandledrejection?: any };
243
-
244
- beforeEach(() => (window = {}));
245
-
246
- const subject = () => handler.instrument(window as any);
247
-
248
- test('installs "onError" handler', () => {
249
- subject();
250
-
251
- expect(window.onerror).toBe(handler.onError);
252
- });
253
-
254
- test('installs "onReject" handler', () => {
255
- subject();
256
-
257
- expect(window.onunhandledrejection).toBe(handler.onReject);
258
- });
259
-
260
- describe('with existing handler', () => {
261
- const existingHandler = jest.fn();
262
-
263
- beforeEach(() => (window.onerror = existingHandler));
264
-
265
- test('chains the error handlers', () => {
266
- const onErrorSpy = jest.spyOn(handler, 'onError');
267
- const error = new Error('Oops!');
268
-
269
- subject();
270
- window.onerror(error);
271
-
272
- expect(existingHandler).toHaveBeenCalledWith(error);
273
- expect(onErrorSpy).toHaveBeenCalledWith(error);
274
- });
275
-
276
- describe('when existing error handler is not a function', () => {
277
- beforeEach(() => (window.onerror = 'Nope!'));
278
-
279
- test('throws error', () => {
280
- expect(subject).toThrow(/attempt to instrument non-function value/i);
281
- });
282
- });
283
- });
284
- });
285
- });