@servicetitan/log-service 40.2.1 → 40.3.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.
- package/dist/log-storage.d.ts +1 -1
- package/dist/log-storage.d.ts.map +1 -1
- package/dist/log-storage.js +5 -7
- package/dist/log-storage.js.map +1 -1
- package/package.json +9 -5
- package/src/log-storage.ts +7 -9
- package/src/__tests__/__mocks__/broadcast-channel.ts +0 -39
- package/src/__tests__/__mocks__/index.ts +0 -1
- package/src/__tests__/__snapshots__/serialize-with-metadata.test.ts.snap +0 -23
- package/src/__tests__/connection-service.test.ts +0 -56
- package/src/__tests__/global-error-handler.test.ts +0 -285
- package/src/__tests__/log-config-provider.test.tsx +0 -29
- package/src/__tests__/log-sender.test.ts +0 -145
- package/src/__tests__/log-service.test.tsx +0 -76
- package/src/__tests__/log-storage.test.ts +0 -194
- package/src/__tests__/log.test.ts +0 -250
- package/src/__tests__/serialize-with-metadata.test.ts +0 -22
package/dist/log-storage.d.ts
CHANGED
|
@@ -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,QA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,UAAU,CAAS;IAC3B,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAmB;gBAEW,SAAS,EAAE,SAAS;IAyB3E,OAAO;IAIP,IAAI,MAAM,IAAI,SAAS,CAEtB;IAED,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"}
|
package/dist/log-storage.js
CHANGED
|
@@ -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
|
-
|
|
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;
|
package/dist/log-storage.js.map
CHANGED
|
@@ -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,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,IACA,uBAAQR,WAAR,KAAA,SAEuDG,YAAAA,gBARvDgB,QAAuB,EAAE,OAERE,aAAa,WACb4B,UAAU;QAOvBxD,eAAe,IAAI;QAEnB,MAAMwD,UAAUC,OAAOC,QAAQ,CAACnB,aAAaC,OAAO,CAAC,IAAI,CAACY,iBAAiB;QAC3E,IAAII,YAAY,IAAI,CAACA,OAAO,EAAE;YAC1BjB,aAAaoB,UAAU,CAAC,IAAI,CAAClB,UAAU;YACvCF,aAAaY,OAAO,CAAC,IAAI,CAACC,iBAAiB,EAAEQ,OAAO,IAAI,CAACJ,OAAO;QACpE;QAEA,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,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,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,aAAaE,IAAI,CAAC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AsBmC,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"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@servicetitan/log-service",
|
|
3
|
-
"version": "40.
|
|
3
|
+
"version": "40.3.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.
|
|
23
|
+
"@servicetitan/react-ioc": "40.3.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.
|
|
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.
|
|
32
|
+
"@servicetitan/react-ioc": "40.3.0",
|
|
29
33
|
"axios": ">=0.30.0 <1 || ^1.8.3",
|
|
30
34
|
"mobx": ">=6.13.5",
|
|
31
35
|
"react": ">=17.0.2"
|
package/src/log-storage.ts
CHANGED
|
@@ -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
|
-
|
|
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
|
-
});
|
|
@@ -1,29 +0,0 @@
|
|
|
1
|
-
import { useDependencies } from '@servicetitan/react-ioc';
|
|
2
|
-
import { render } from '@testing-library/react';
|
|
3
|
-
import { FC } from 'react';
|
|
4
|
-
import { LOG_CONFIG_TOKEN, LogConfig } from '../log-config';
|
|
5
|
-
import { LogConfigProvider } from '../log-config-provider';
|
|
6
|
-
|
|
7
|
-
describe(`[log-service] ${LogConfigProvider.name}`, () => {
|
|
8
|
-
const logConfig: LogConfig = { endpoint: '/Log/Foo', storageKey: 'LogStorage_Foo' };
|
|
9
|
-
let providedLogConfig: LogConfig;
|
|
10
|
-
|
|
11
|
-
const Wrapper: FC = () => {
|
|
12
|
-
const [logConfig] = useDependencies(LOG_CONFIG_TOKEN);
|
|
13
|
-
providedLogConfig = logConfig;
|
|
14
|
-
return null;
|
|
15
|
-
};
|
|
16
|
-
|
|
17
|
-
const subject = () =>
|
|
18
|
-
render(
|
|
19
|
-
<LogConfigProvider value={logConfig}>
|
|
20
|
-
<Wrapper />
|
|
21
|
-
</LogConfigProvider>
|
|
22
|
-
);
|
|
23
|
-
|
|
24
|
-
test('provides LOG_CONFIG_TOKEN', () => {
|
|
25
|
-
subject();
|
|
26
|
-
|
|
27
|
-
expect(providedLogConfig).toBe(logConfig);
|
|
28
|
-
});
|
|
29
|
-
});
|
|
@@ -1,145 +0,0 @@
|
|
|
1
|
-
import axios from 'axios';
|
|
2
|
-
import { ConnectionService } from '../connection-service';
|
|
3
|
-
import { Log, LogConfig, LogEntryType, LogInfo, LogWarning } from '../log';
|
|
4
|
-
import { LogSender } from '../log-sender';
|
|
5
|
-
import { lastId, LogStorage } from '../log-storage';
|
|
6
|
-
|
|
7
|
-
jest.mock('axios', () => ({ post: jest.fn() }));
|
|
8
|
-
|
|
9
|
-
class MockLog {
|
|
10
|
-
constructor(private readonly logStorage: LogStorage) {}
|
|
11
|
-
|
|
12
|
-
info(entry: LogInfo) {
|
|
13
|
-
this.logStorage.store({
|
|
14
|
-
type: LogEntryType.Info,
|
|
15
|
-
...entry,
|
|
16
|
-
category: null,
|
|
17
|
-
code: null,
|
|
18
|
-
data: {},
|
|
19
|
-
error: null,
|
|
20
|
-
message: null,
|
|
21
|
-
});
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
warning(_entry: LogWarning) {}
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
const SECOND = 1000;
|
|
28
|
-
const MINUTE = 60 * SECOND;
|
|
29
|
-
|
|
30
|
-
describe(`[log-service] ${LogSender.name}`, () => {
|
|
31
|
-
const connectionService = new ConnectionService();
|
|
32
|
-
const logConfig: LogConfig = { endpoint: '/Log/Foo', storageKey: 'LogStorage_Foo' };
|
|
33
|
-
let logStorage: LogStorage;
|
|
34
|
-
let log: Pick<Log, 'info' | 'warning'>;
|
|
35
|
-
|
|
36
|
-
beforeAll(() => {
|
|
37
|
-
process.env.NODE_ENV ??= 'test'; // workaround issue with Jest not setting NODE_ENV=test
|
|
38
|
-
jest.spyOn(window, 'setInterval').mockImplementation(jest.fn());
|
|
39
|
-
jest.spyOn(axios, 'post').mockImplementation(jest.fn());
|
|
40
|
-
});
|
|
41
|
-
|
|
42
|
-
beforeEach(() => {
|
|
43
|
-
jest.clearAllMocks();
|
|
44
|
-
|
|
45
|
-
logStorage = new LogStorage(logConfig);
|
|
46
|
-
log = new MockLog(logStorage);
|
|
47
|
-
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
48
|
-
const logSender = new LogSender(connectionService, logStorage, logConfig, log as Log);
|
|
49
|
-
});
|
|
50
|
-
|
|
51
|
-
afterEach(() => logStorage.deleteToId(lastId(logStorage.items)));
|
|
52
|
-
|
|
53
|
-
const subject = async () => {
|
|
54
|
-
getHandler().fn();
|
|
55
|
-
await Promise.resolve(); // resolve pending promises
|
|
56
|
-
};
|
|
57
|
-
|
|
58
|
-
function getHandler() {
|
|
59
|
-
const [fn, interval] = jest.mocked(window.setInterval).mock.calls[0];
|
|
60
|
-
return { fn, interval };
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
function initLog(count: number) {
|
|
64
|
-
Array.from({ length: count }).map((_, index) => log.info({ message: `Message ${index}` }));
|
|
65
|
-
return logStorage.items;
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
test('schedules handler to run once per minute', async () => {
|
|
69
|
-
await subject();
|
|
70
|
-
|
|
71
|
-
expect(getHandler().interval).toBe(MINUTE);
|
|
72
|
-
});
|
|
73
|
-
|
|
74
|
-
describe('when there are items waiting to be sent', () => {
|
|
75
|
-
beforeEach(() => initLog(3));
|
|
76
|
-
|
|
77
|
-
test('handler posts then purges log', async () => {
|
|
78
|
-
const { items } = logStorage;
|
|
79
|
-
|
|
80
|
-
await subject();
|
|
81
|
-
|
|
82
|
-
expect(axios.post).toHaveBeenCalledWith(logConfig.endpoint, items);
|
|
83
|
-
expect(logStorage.items).toEqual([]);
|
|
84
|
-
});
|
|
85
|
-
|
|
86
|
-
describe('when post fails', () => {
|
|
87
|
-
beforeEach(() => jest.mocked(axios.post).mockRejectedValue(new Error('Oops!')));
|
|
88
|
-
|
|
89
|
-
test('reschedules handler to run in exponentially increasing intervals until it succeeds', async () => {
|
|
90
|
-
for (let n = 0; n <= 10; n++) {
|
|
91
|
-
// eslint-disable-next-line no-await-in-loop
|
|
92
|
-
await subject();
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
for (let n = 0; n < 10; n++) {
|
|
96
|
-
expect(window.setInterval).toHaveBeenCalledWith(
|
|
97
|
-
expect.any(Function),
|
|
98
|
-
2 ** n * SECOND
|
|
99
|
-
);
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
jest.mocked(axios.post).mockReset();
|
|
103
|
-
await subject();
|
|
104
|
-
|
|
105
|
-
expect(logStorage.items).toEqual([]);
|
|
106
|
-
expect(window.setInterval).toHaveBeenCalledWith(expect.any(Function), MINUTE);
|
|
107
|
-
});
|
|
108
|
-
});
|
|
109
|
-
|
|
110
|
-
describe('when handler runs while posting', () => {
|
|
111
|
-
beforeEach(() =>
|
|
112
|
-
jest.spyOn(axios, 'post').mockImplementation(() => {
|
|
113
|
-
getHandler().fn();
|
|
114
|
-
return Promise.resolve({});
|
|
115
|
-
})
|
|
116
|
-
);
|
|
117
|
-
|
|
118
|
-
test('skips redundant post', async () => {
|
|
119
|
-
await subject();
|
|
120
|
-
|
|
121
|
-
expect(axios.post).toHaveBeenCalledTimes(1);
|
|
122
|
-
});
|
|
123
|
-
});
|
|
124
|
-
|
|
125
|
-
describe('when offline', () => {
|
|
126
|
-
beforeEach(() => connectionService.setOnline(false));
|
|
127
|
-
afterEach(() => connectionService.setOnline(true));
|
|
128
|
-
|
|
129
|
-
test('does not post', async () => {
|
|
130
|
-
await subject();
|
|
131
|
-
|
|
132
|
-
expect(axios.post).not.toHaveBeenCalled();
|
|
133
|
-
});
|
|
134
|
-
});
|
|
135
|
-
});
|
|
136
|
-
|
|
137
|
-
test('automatically posts when log >= 128 items', async () => {
|
|
138
|
-
await subject();
|
|
139
|
-
expect(axios.post).not.toHaveBeenCalled();
|
|
140
|
-
|
|
141
|
-
const items = initLog(128);
|
|
142
|
-
|
|
143
|
-
expect(axios.post).toHaveBeenCalledWith(logConfig.endpoint, items);
|
|
144
|
-
});
|
|
145
|
-
});
|
|
@@ -1,76 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
Provider,
|
|
3
|
-
ProviderProps,
|
|
4
|
-
useDependencies,
|
|
5
|
-
useOptionalDependencies,
|
|
6
|
-
} from '@servicetitan/react-ioc';
|
|
7
|
-
import { render } from '@testing-library/react';
|
|
8
|
-
import { FC } from 'react';
|
|
9
|
-
import { LOG_CONFIG_TOKEN, LOG_PARENT_TOKEN, Log, LogConfig } from '../log';
|
|
10
|
-
import { defaultLogConfig } from '../log-config';
|
|
11
|
-
import { LogService, LogServiceProps } from '../log-service';
|
|
12
|
-
import { LogStorage } from '../log-storage';
|
|
13
|
-
|
|
14
|
-
describe(`[log-service] ${LogService.name}`, () => {
|
|
15
|
-
let props: LogServiceProps;
|
|
16
|
-
let providedLog: Log;
|
|
17
|
-
let providedLogConfig: LogConfig;
|
|
18
|
-
let providedParent: Log | undefined;
|
|
19
|
-
let singletons: ProviderProps['singletons'];
|
|
20
|
-
|
|
21
|
-
const Component: FC = () => {
|
|
22
|
-
[providedLog, providedLogConfig] = useDependencies(Log, LOG_CONFIG_TOKEN);
|
|
23
|
-
[providedParent] = useOptionalDependencies(LOG_PARENT_TOKEN);
|
|
24
|
-
return null;
|
|
25
|
-
};
|
|
26
|
-
|
|
27
|
-
const subject = () => {
|
|
28
|
-
return render(
|
|
29
|
-
<Provider singletons={singletons}>
|
|
30
|
-
<LogService {...props}>
|
|
31
|
-
<Component />
|
|
32
|
-
</LogService>
|
|
33
|
-
</Provider>
|
|
34
|
-
);
|
|
35
|
-
};
|
|
36
|
-
|
|
37
|
-
test('provides Log instance', () => {
|
|
38
|
-
subject();
|
|
39
|
-
|
|
40
|
-
expect(providedLog).toBeInstanceOf(Log);
|
|
41
|
-
});
|
|
42
|
-
|
|
43
|
-
test('defaults to endpoint "/Log/Send" and storageKey "LogStorage"', () => {
|
|
44
|
-
subject();
|
|
45
|
-
|
|
46
|
-
expect(providedLogConfig).toEqual({ endpoint: '/Log/Send', storageKey: 'LogStorage' });
|
|
47
|
-
});
|
|
48
|
-
|
|
49
|
-
describe.each(['endpoint', 'storageKey'] as (keyof LogConfig)[])(
|
|
50
|
-
'when "%s" is specified',
|
|
51
|
-
prop => {
|
|
52
|
-
beforeEach(() => (props = { [prop]: 'Foo' }));
|
|
53
|
-
|
|
54
|
-
test(`uses the specified ${prop}`, () => {
|
|
55
|
-
subject();
|
|
56
|
-
|
|
57
|
-
expect(providedLogConfig[prop]).toEqual(props[prop]);
|
|
58
|
-
});
|
|
59
|
-
}
|
|
60
|
-
);
|
|
61
|
-
|
|
62
|
-
describe('with a parent log', () => {
|
|
63
|
-
const parent: Log = new Log(new LogStorage(defaultLogConfig));
|
|
64
|
-
|
|
65
|
-
beforeEach(() => {
|
|
66
|
-
singletons = [{ provide: Log, useValue: parent }];
|
|
67
|
-
props = { endpoint: '/Log/Foo', storageKey: 'LogStorage_Foo' };
|
|
68
|
-
});
|
|
69
|
-
|
|
70
|
-
test('provides parent Log', () => {
|
|
71
|
-
subject();
|
|
72
|
-
|
|
73
|
-
expect(providedParent).toBe(parent);
|
|
74
|
-
});
|
|
75
|
-
});
|
|
76
|
-
});
|
|
@@ -1,194 +0,0 @@
|
|
|
1
|
-
import { EntryComplete, LogEntryType } from '../log';
|
|
2
|
-
import { LogConfig } from '../log-config';
|
|
3
|
-
import { lastId, LogStorage } from '../log-storage';
|
|
4
|
-
import { MockBroadcastChannel } from './__mocks__';
|
|
5
|
-
|
|
6
|
-
describe(`${LogStorage.name}`, () => {
|
|
7
|
-
const LOCAL_STORAGE_VERSION = '1';
|
|
8
|
-
const logConfig: LogConfig = { endpoint: '/Log/Foo', storageKey: 'LogStorage_Foo' };
|
|
9
|
-
let logStorage: LogStorage;
|
|
10
|
-
|
|
11
|
-
beforeAll(() => {
|
|
12
|
-
jest.spyOn(globalThis, 'BroadcastChannel').mockImplementation(
|
|
13
|
-
(name: string) => new MockBroadcastChannel(name)
|
|
14
|
-
);
|
|
15
|
-
});
|
|
16
|
-
|
|
17
|
-
beforeEach(() => window.localStorage.clear());
|
|
18
|
-
afterEach(() => logStorage.dispose());
|
|
19
|
-
|
|
20
|
-
const subject = (entryOrEntries: EntryComplete | EntryComplete[] = []) => {
|
|
21
|
-
logStorage = new LogStorage(logConfig);
|
|
22
|
-
[entryOrEntries].flat().forEach(entry => logStorage.store(entry));
|
|
23
|
-
return logStorage;
|
|
24
|
-
};
|
|
25
|
-
|
|
26
|
-
function itLoadsNoItems() {
|
|
27
|
-
test('loads no items', () => {
|
|
28
|
-
expect(subject().items).toEqual([]);
|
|
29
|
-
});
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
itLoadsNoItems();
|
|
33
|
-
|
|
34
|
-
describe('with previously saved items', () => {
|
|
35
|
-
const entries = createEntries(3);
|
|
36
|
-
|
|
37
|
-
beforeEach(() => {
|
|
38
|
-
const logStorage = new LogStorage(logConfig);
|
|
39
|
-
entries.map(entry => logStorage.store(entry));
|
|
40
|
-
logStorage.dispose();
|
|
41
|
-
});
|
|
42
|
-
|
|
43
|
-
function itLoadsSavedItems() {
|
|
44
|
-
test('loads saved items', () => {
|
|
45
|
-
expect(subject().items).toEqual(buildItems(entries).map(expect.objectContaining));
|
|
46
|
-
});
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
itLoadsSavedItems();
|
|
50
|
-
|
|
51
|
-
describe('when saved data has incompatible version', () => {
|
|
52
|
-
const storageVersionKey = `${logConfig.storageKey}Version`;
|
|
53
|
-
|
|
54
|
-
beforeEach(() => window.localStorage.setItem(storageVersionKey, '-1'));
|
|
55
|
-
|
|
56
|
-
itLoadsNoItems();
|
|
57
|
-
|
|
58
|
-
test('updates version', () => {
|
|
59
|
-
subject();
|
|
60
|
-
|
|
61
|
-
expect(localStorage.getItem(storageVersionKey)).toBe(LOCAL_STORAGE_VERSION);
|
|
62
|
-
});
|
|
63
|
-
});
|
|
64
|
-
|
|
65
|
-
describe('when saved data is not valid', () => {
|
|
66
|
-
beforeEach(() => {
|
|
67
|
-
window.localStorage.setItem(logConfig.storageKey, '}{');
|
|
68
|
-
});
|
|
69
|
-
|
|
70
|
-
itLoadsNoItems();
|
|
71
|
-
});
|
|
72
|
-
|
|
73
|
-
describe('when saved data contains old "error" field', () => {
|
|
74
|
-
beforeEach(() => {
|
|
75
|
-
const itemsWithErrorField = (
|
|
76
|
-
JSON.parse(localStorage.getItem(logConfig.storageKey)!) as LogStorage['items']
|
|
77
|
-
).map(({ exception, ...rest }) => ({ ...rest, error: exception }));
|
|
78
|
-
localStorage.setItem(logConfig.storageKey, JSON.stringify(itemsWithErrorField));
|
|
79
|
-
});
|
|
80
|
-
|
|
81
|
-
itLoadsSavedItems();
|
|
82
|
-
});
|
|
83
|
-
|
|
84
|
-
describe('when multiple instances are running simultaneously', () => {
|
|
85
|
-
let otherLogStorage: LogStorage;
|
|
86
|
-
|
|
87
|
-
beforeEach(() => (otherLogStorage = new LogStorage(logConfig)));
|
|
88
|
-
afterEach(() => otherLogStorage.dispose());
|
|
89
|
-
|
|
90
|
-
test('deleteToId removes items from both instances', () => {
|
|
91
|
-
const logStorage = subject();
|
|
92
|
-
|
|
93
|
-
expect(logStorage.items.length).toEqual(entries.length);
|
|
94
|
-
expect(otherLogStorage.items.length).toEqual(entries.length);
|
|
95
|
-
|
|
96
|
-
logStorage.deleteToId(lastId(logStorage.items));
|
|
97
|
-
|
|
98
|
-
expect(logStorage.items).toEqual([]);
|
|
99
|
-
expect(otherLogStorage.items).toEqual([]);
|
|
100
|
-
});
|
|
101
|
-
|
|
102
|
-
test('deleteToId does not remove private items', () => {
|
|
103
|
-
const logStorage = subject();
|
|
104
|
-
|
|
105
|
-
const entry = createEntry({ message: 'foo' });
|
|
106
|
-
otherLogStorage.store(entry);
|
|
107
|
-
|
|
108
|
-
logStorage.deleteToId(lastId(logStorage.items));
|
|
109
|
-
|
|
110
|
-
expect(logStorage.items).toEqual([]);
|
|
111
|
-
expect(otherLogStorage.items).toEqual(
|
|
112
|
-
buildItems([entry]).map(expect.objectContaining)
|
|
113
|
-
);
|
|
114
|
-
});
|
|
115
|
-
});
|
|
116
|
-
});
|
|
117
|
-
|
|
118
|
-
test('stores items with unique ids', () => {
|
|
119
|
-
const entries = createEntries(3);
|
|
120
|
-
|
|
121
|
-
const logStorage = subject(entries);
|
|
122
|
-
|
|
123
|
-
expect(logStorage.items).toEqual(buildItems(entries).map(expect.objectContaining));
|
|
124
|
-
expect(new Set(logStorage.items.map(({ id }) => id)).size).toBe(entries.length);
|
|
125
|
-
});
|
|
126
|
-
|
|
127
|
-
test('limits storage to 1000 items', () => {
|
|
128
|
-
const logStorage = subject(createEntries(1001));
|
|
129
|
-
|
|
130
|
-
expect(logStorage.items).toHaveLength(1000);
|
|
131
|
-
});
|
|
132
|
-
|
|
133
|
-
test('stringifies entry data', () => {
|
|
134
|
-
const entry = createEntry({ message: 'foo', data: { foo: 'bar' } });
|
|
135
|
-
|
|
136
|
-
const { data } = subject(entry).items[0];
|
|
137
|
-
|
|
138
|
-
expect(data).toBe(JSON.stringify(entry.data));
|
|
139
|
-
});
|
|
140
|
-
|
|
141
|
-
test('converts entry error to exception', () => {
|
|
142
|
-
const error = new Error('Oops!');
|
|
143
|
-
|
|
144
|
-
const { exception } = subject(createEntry({ error })).items[0];
|
|
145
|
-
|
|
146
|
-
expect(exception).toEqual(JSON.stringify({ message: error.message, stack: error.stack }));
|
|
147
|
-
});
|
|
148
|
-
|
|
149
|
-
test('deleteToId removes entries with same or lower id', () => {
|
|
150
|
-
const entries = createEntries(10);
|
|
151
|
-
const logStorage = subject(entries);
|
|
152
|
-
|
|
153
|
-
const index = 2;
|
|
154
|
-
const { id } = logStorage.items[index];
|
|
155
|
-
logStorage.deleteToId(id);
|
|
156
|
-
|
|
157
|
-
expect(logStorage.items.length).toBe(entries.length - index - 1);
|
|
158
|
-
expect(logStorage.items.every(entry => entry.id > id)).toBe(true);
|
|
159
|
-
});
|
|
160
|
-
|
|
161
|
-
test('loadBatch returns first N items', () => {
|
|
162
|
-
const entries = createEntries(10);
|
|
163
|
-
const logStorage = subject(entries);
|
|
164
|
-
|
|
165
|
-
const count = 5;
|
|
166
|
-
const batch = logStorage.loadBatch(count);
|
|
167
|
-
|
|
168
|
-
expect(batch).toEqual(buildItems(entries.slice(0, count)).map(expect.objectContaining));
|
|
169
|
-
});
|
|
170
|
-
});
|
|
171
|
-
|
|
172
|
-
function buildItems(entries: EntryComplete[]) {
|
|
173
|
-
return entries.map(({ data, error, ...rest }) => ({
|
|
174
|
-
...rest,
|
|
175
|
-
data: JSON.stringify(data),
|
|
176
|
-
exception: JSON.stringify(error && { message: error.message, stack: error.stack }),
|
|
177
|
-
}));
|
|
178
|
-
}
|
|
179
|
-
|
|
180
|
-
function createEntries(length: number) {
|
|
181
|
-
return Array.from({ length }).map((_, index) => createEntry({ message: `Entry ${index}` }));
|
|
182
|
-
}
|
|
183
|
-
|
|
184
|
-
function createEntry(entry: Partial<EntryComplete>): EntryComplete {
|
|
185
|
-
return {
|
|
186
|
-
type: LogEntryType.Info,
|
|
187
|
-
message: null,
|
|
188
|
-
code: null,
|
|
189
|
-
category: null,
|
|
190
|
-
error: null,
|
|
191
|
-
data: {},
|
|
192
|
-
...entry,
|
|
193
|
-
};
|
|
194
|
-
}
|
|
@@ -1,250 +0,0 @@
|
|
|
1
|
-
import { Log, LogConfig, LogEntry, LogEntryType, LogError } from '../log';
|
|
2
|
-
import { defaultLogConfig } from '../log-config';
|
|
3
|
-
import { LogStorage } from '../log-storage';
|
|
4
|
-
import { serializeWithMetadata } from '../serialize-with-metadata';
|
|
5
|
-
|
|
6
|
-
const SECOND = 1000;
|
|
7
|
-
const THROTTLE_INTERVAL = 30 * SECOND;
|
|
8
|
-
|
|
9
|
-
describe(`[log-service] ${Log.name}`, () => {
|
|
10
|
-
const logConfig: LogConfig = { endpoint: '/Log/Foo', storageKey: 'LogStorage_Foo' };
|
|
11
|
-
const entry: LogEntry = { category: 'category', code: 'code', message: 'foo' };
|
|
12
|
-
let parentLog: Log;
|
|
13
|
-
|
|
14
|
-
beforeAll(() => jest.useFakeTimers());
|
|
15
|
-
|
|
16
|
-
beforeEach(() => {
|
|
17
|
-
jest.clearAllTimers();
|
|
18
|
-
jest.spyOn(console, 'error').mockImplementation(jest.fn());
|
|
19
|
-
window.localStorage.clear();
|
|
20
|
-
});
|
|
21
|
-
|
|
22
|
-
const subject = () => {
|
|
23
|
-
const logStorage = new LogStorage(logConfig);
|
|
24
|
-
const log = new Log(logStorage, parentLog);
|
|
25
|
-
jest.spyOn(logStorage, 'store');
|
|
26
|
-
return { log, logStorage };
|
|
27
|
-
};
|
|
28
|
-
|
|
29
|
-
test('logs info', () => {
|
|
30
|
-
const { log, logStorage } = subject();
|
|
31
|
-
|
|
32
|
-
log.info(entry);
|
|
33
|
-
|
|
34
|
-
expect(logStorage.store).toHaveBeenCalledWith(
|
|
35
|
-
expect.objectContaining({ ...entry, type: LogEntryType.Info })
|
|
36
|
-
);
|
|
37
|
-
});
|
|
38
|
-
|
|
39
|
-
test('logs warnings', () => {
|
|
40
|
-
const { log, logStorage } = subject();
|
|
41
|
-
|
|
42
|
-
log.warning(entry);
|
|
43
|
-
|
|
44
|
-
expect(logStorage.store).toHaveBeenCalledWith(
|
|
45
|
-
expect.objectContaining({ ...entry, type: LogEntryType.Warning })
|
|
46
|
-
);
|
|
47
|
-
});
|
|
48
|
-
|
|
49
|
-
describe('error', () => {
|
|
50
|
-
const { log, logStorage } = subject();
|
|
51
|
-
let error: Error | string;
|
|
52
|
-
let errorEntry: LogError;
|
|
53
|
-
let errorOptions: Parameters<typeof log.error>[1];
|
|
54
|
-
|
|
55
|
-
beforeEach(() => {
|
|
56
|
-
jest.clearAllMocks();
|
|
57
|
-
errorOptions = undefined;
|
|
58
|
-
});
|
|
59
|
-
|
|
60
|
-
const errorSubject = () => {
|
|
61
|
-
errorEntry = { ...entry, error, message: undefined };
|
|
62
|
-
log.error(errorEntry, errorOptions);
|
|
63
|
-
jest.runOnlyPendingTimers();
|
|
64
|
-
};
|
|
65
|
-
|
|
66
|
-
function itLogsError() {
|
|
67
|
-
const expectMessage = () =>
|
|
68
|
-
expect.stringContaining((errorEntry.error as Error)?.message ?? errorEntry.error);
|
|
69
|
-
|
|
70
|
-
test('stores the error', () => {
|
|
71
|
-
errorSubject();
|
|
72
|
-
|
|
73
|
-
expect(logStorage.store).toHaveBeenCalledWith(
|
|
74
|
-
expect.objectContaining({
|
|
75
|
-
...errorEntry,
|
|
76
|
-
type: LogEntryType.Error,
|
|
77
|
-
error: expect.objectContaining({ message: expectMessage() }),
|
|
78
|
-
message: expectMessage(),
|
|
79
|
-
})
|
|
80
|
-
);
|
|
81
|
-
});
|
|
82
|
-
|
|
83
|
-
test('writes the error to the console', () => {
|
|
84
|
-
errorSubject();
|
|
85
|
-
|
|
86
|
-
// eslint-disable-next-line no-console
|
|
87
|
-
expect(console.error).toHaveBeenCalledWith(
|
|
88
|
-
'@log-service/error',
|
|
89
|
-
errorEntry,
|
|
90
|
-
expect.objectContaining({ message: expectMessage() })
|
|
91
|
-
);
|
|
92
|
-
});
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
describe('with an error object', () => {
|
|
96
|
-
beforeEach(() => (error = new Error('Oops!')));
|
|
97
|
-
|
|
98
|
-
itLogsError();
|
|
99
|
-
});
|
|
100
|
-
|
|
101
|
-
describe('with an error string', () => {
|
|
102
|
-
beforeEach(() => (error = 'Oops!'));
|
|
103
|
-
|
|
104
|
-
itLogsError();
|
|
105
|
-
});
|
|
106
|
-
|
|
107
|
-
describe('with { skipConsole: true }', () => {
|
|
108
|
-
beforeEach(() => {
|
|
109
|
-
error = new Error('Oops!');
|
|
110
|
-
errorOptions = { skipConsole: true };
|
|
111
|
-
});
|
|
112
|
-
test('does not write error to console', () => {
|
|
113
|
-
errorSubject();
|
|
114
|
-
// eslint-disable-next-line no-console
|
|
115
|
-
expect(console.error).not.toHaveBeenCalled();
|
|
116
|
-
});
|
|
117
|
-
});
|
|
118
|
-
});
|
|
119
|
-
|
|
120
|
-
test(`skips redundant error logged within ${THROTTLE_INTERVAL / SECOND}s`, () => {
|
|
121
|
-
const errorEntry = { ...entry, error: new Error('Oops!') };
|
|
122
|
-
const { log, logStorage } = subject();
|
|
123
|
-
|
|
124
|
-
Array.from({ length: 5 }).forEach(() => log.error(errorEntry));
|
|
125
|
-
jest.advanceTimersByTime(THROTTLE_INTERVAL);
|
|
126
|
-
|
|
127
|
-
expect(logStorage.store).toHaveBeenCalledTimes(1);
|
|
128
|
-
});
|
|
129
|
-
|
|
130
|
-
test(`keeps redundant error logged after ${THROTTLE_INTERVAL / SECOND}s`, () => {
|
|
131
|
-
const errorEntry = { ...entry, error: new Error('Oops!') };
|
|
132
|
-
const { log, logStorage } = subject();
|
|
133
|
-
|
|
134
|
-
Array.from({ length: 5 }).forEach(() => log.error(errorEntry));
|
|
135
|
-
jest.advanceTimersByTime(THROTTLE_INTERVAL);
|
|
136
|
-
Array.from({ length: 5 }).forEach(() => log.error(errorEntry));
|
|
137
|
-
jest.runOnlyPendingTimers();
|
|
138
|
-
|
|
139
|
-
expect(logStorage.store).toHaveBeenCalledTimes(2);
|
|
140
|
-
});
|
|
141
|
-
|
|
142
|
-
test('serializes non-standard errors', () => {
|
|
143
|
-
const errorEntry = { ...entry, error: { foo: 'bar' } };
|
|
144
|
-
const { log, logStorage } = subject();
|
|
145
|
-
|
|
146
|
-
log.error(errorEntry);
|
|
147
|
-
jest.runOnlyPendingTimers();
|
|
148
|
-
|
|
149
|
-
expect(logStorage.store).toHaveBeenCalledWith(
|
|
150
|
-
expect.objectContaining({
|
|
151
|
-
message: errorEntry.message,
|
|
152
|
-
error: expect.objectContaining({
|
|
153
|
-
message: serializeWithMetadata(errorEntry.error),
|
|
154
|
-
}),
|
|
155
|
-
})
|
|
156
|
-
);
|
|
157
|
-
});
|
|
158
|
-
|
|
159
|
-
test('extends log data', () => {
|
|
160
|
-
const data = { foo: 'bar' };
|
|
161
|
-
const { log, logStorage } = subject();
|
|
162
|
-
|
|
163
|
-
log.info({ ...entry, data });
|
|
164
|
-
|
|
165
|
-
expect(logStorage.store).toHaveBeenCalledWith(
|
|
166
|
-
expect.objectContaining({
|
|
167
|
-
data: {
|
|
168
|
-
...data,
|
|
169
|
-
CreatedOn: new Date(),
|
|
170
|
-
Online: window.navigator.onLine,
|
|
171
|
-
Url: window.location.toString(),
|
|
172
|
-
UserAgent: window.navigator.userAgent,
|
|
173
|
-
Source: 'Frontend',
|
|
174
|
-
Plugins: '',
|
|
175
|
-
TzOffset: expect.any(Number),
|
|
176
|
-
IsDst: expect.any(Boolean),
|
|
177
|
-
IsDstSubject: expect.any(Boolean),
|
|
178
|
-
},
|
|
179
|
-
})
|
|
180
|
-
);
|
|
181
|
-
});
|
|
182
|
-
|
|
183
|
-
describe('when browser has plugins', () => {
|
|
184
|
-
const plugins: Partial<(typeof window.navigator.plugins)[0]>[] = [
|
|
185
|
-
{ name: 'foo', filename: 'filename', description: 'description' },
|
|
186
|
-
{ name: 'bar', filename: 'filename', description: 'description' },
|
|
187
|
-
];
|
|
188
|
-
|
|
189
|
-
beforeEach(() => {
|
|
190
|
-
Object.defineProperty(window.navigator, 'plugins', { value: plugins, writable: true });
|
|
191
|
-
});
|
|
192
|
-
|
|
193
|
-
test('adds plugins to log data', () => {
|
|
194
|
-
const { log, logStorage } = subject();
|
|
195
|
-
|
|
196
|
-
log.info(entry);
|
|
197
|
-
|
|
198
|
-
expect(logStorage.store).toHaveBeenCalledWith(
|
|
199
|
-
expect.objectContaining({
|
|
200
|
-
data: expect.objectContaining({
|
|
201
|
-
Plugins: plugins.map(p => [p.name, p.filename, p.description]).join('/'),
|
|
202
|
-
}),
|
|
203
|
-
})
|
|
204
|
-
);
|
|
205
|
-
});
|
|
206
|
-
|
|
207
|
-
describe('when error occurs reading plugins', () => {
|
|
208
|
-
beforeEach(() => Object.assign(window.navigator, { plugins: [undefined] }));
|
|
209
|
-
|
|
210
|
-
test('reports "unknown"', () => {
|
|
211
|
-
const { log, logStorage } = subject();
|
|
212
|
-
|
|
213
|
-
log.info(entry);
|
|
214
|
-
|
|
215
|
-
expect(logStorage.store).toHaveBeenCalledWith(
|
|
216
|
-
expect.objectContaining({
|
|
217
|
-
data: expect.objectContaining({ Plugins: 'unknown' }),
|
|
218
|
-
})
|
|
219
|
-
);
|
|
220
|
-
});
|
|
221
|
-
});
|
|
222
|
-
});
|
|
223
|
-
|
|
224
|
-
describe('when log has parent', () => {
|
|
225
|
-
beforeEach(() => (parentLog = new Log(new LogStorage(defaultLogConfig))));
|
|
226
|
-
|
|
227
|
-
test.each(['info', 'warning', 'error'] as (keyof Log)[])(
|
|
228
|
-
'forwards %s to parent log',
|
|
229
|
-
method => {
|
|
230
|
-
jest.spyOn(parentLog, method);
|
|
231
|
-
|
|
232
|
-
const logEntry = { ...entry, error: new Error('Oops!') };
|
|
233
|
-
subject().log[method](logEntry);
|
|
234
|
-
|
|
235
|
-
expect(parentLog[method]).toHaveBeenCalledWith(logEntry);
|
|
236
|
-
}
|
|
237
|
-
);
|
|
238
|
-
|
|
239
|
-
describe.each(['endpoint', 'storageKey'] as (keyof LogConfig)[])(
|
|
240
|
-
'when log uses default %s',
|
|
241
|
-
key => {
|
|
242
|
-
beforeEach(() => (logConfig[key] = defaultLogConfig[key]));
|
|
243
|
-
|
|
244
|
-
test('throws error', () => {
|
|
245
|
-
expect(() => subject()).toThrow(/cannot use default configuration/);
|
|
246
|
-
});
|
|
247
|
-
}
|
|
248
|
-
);
|
|
249
|
-
});
|
|
250
|
-
});
|
|
@@ -1,22 +0,0 @@
|
|
|
1
|
-
import { serializeWithMetadata } from '../serialize-with-metadata';
|
|
2
|
-
|
|
3
|
-
class Abc {
|
|
4
|
-
a = 1;
|
|
5
|
-
}
|
|
6
|
-
|
|
7
|
-
const cyclicObject = { a: { b: {} } };
|
|
8
|
-
cyclicObject.a.b = cyclicObject;
|
|
9
|
-
|
|
10
|
-
test.each([
|
|
11
|
-
[new Error('Error')],
|
|
12
|
-
[new Abc()],
|
|
13
|
-
[{ b: 1 }],
|
|
14
|
-
[null],
|
|
15
|
-
[undefined],
|
|
16
|
-
[function abc() {}],
|
|
17
|
-
[123],
|
|
18
|
-
[new Event('MyEvent')],
|
|
19
|
-
[cyclicObject],
|
|
20
|
-
])('Serialize with metadata %#', error => {
|
|
21
|
-
expect(serializeWithMetadata(error)).toMatchSnapshot();
|
|
22
|
-
});
|