@utk09/ui-observability 0.10.0 → 0.11.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/CHANGELOG.md +16 -1
- package/README.md +50 -11
- package/dist/{batch-BHXypM1j.cjs → batch-C8OcWR2L.cjs} +2 -2
- package/dist/{batch-BHXypM1j.cjs.map → batch-C8OcWR2L.cjs.map} +1 -1
- package/dist/{batch-BMdT9mKm.js → batch-CL9uWYY3.js} +4 -5
- package/dist/{batch-BMdT9mKm.js.map → batch-CL9uWYY3.js.map} +1 -1
- package/dist/{bus-DKfBaica.js → bus-BZ0GldpT.js} +23 -27
- package/dist/{bus-DKfBaica.js.map → bus-BZ0GldpT.js.map} +1 -1
- package/dist/{bus-Dea9rVhy.cjs → bus-VWlmM5xs.cjs} +2 -2
- package/dist/{bus-Dea9rVhy.cjs.map → bus-VWlmM5xs.cjs.map} +1 -1
- package/dist/console-BPZCuSLc.cjs +2 -0
- package/dist/{console-DZEcs7FL.cjs.map → console-BPZCuSLc.cjs.map} +1 -1
- package/dist/{console-BX_0UCV7.js → console-BeCF7n59.js} +14 -15
- package/dist/{console-BX_0UCV7.js.map → console-BeCF7n59.js.map} +1 -1
- package/dist/{constants-CL0ZdI2f.cjs → constants-DqKJH_MP.cjs} +2 -2
- package/dist/{constants-CL0ZdI2f.cjs.map → constants-DqKJH_MP.cjs.map} +1 -1
- package/dist/{constants-CU60FG4w.js → constants-zyrqveN4.js} +3 -4
- package/dist/{constants-CU60FG4w.js.map → constants-zyrqveN4.js.map} +1 -1
- package/dist/context-storage-BjzeBSxH.cjs.map +1 -1
- package/dist/{context-storage-DxZf4Gfh.js → context-storage-BzkoHzkQ.js} +2 -3
- package/dist/{context-storage-DxZf4Gfh.js.map → context-storage-BzkoHzkQ.js.map} +1 -1
- package/dist/{deadline-5_PecIl5.js → deadline-BOjOxNHj.js} +3 -5
- package/dist/{deadline-5_PecIl5.js.map → deadline-BOjOxNHj.js.map} +1 -1
- package/dist/deadline-XSnm95pg.cjs.map +1 -1
- package/dist/{debug-bundle-yRkrU1ny.cjs → debug-bundle-BzJNpbF0.cjs} +2 -2
- package/dist/{debug-bundle-yRkrU1ny.cjs.map → debug-bundle-BzJNpbF0.cjs.map} +1 -1
- package/dist/{debug-bundle-CZZ6SQQh.js → debug-bundle-C7UkHZ-q.js} +5 -6
- package/dist/{debug-bundle-CZZ6SQQh.js.map → debug-bundle-C7UkHZ-q.js.map} +1 -1
- package/dist/doctor.cjs +1 -1
- package/dist/doctor.cjs.map +1 -1
- package/dist/doctor.js +3 -4
- package/dist/{emergency-queue-CQ-9acZf.cjs → emergency-queue-CNTRui5t.cjs} +2 -2
- package/dist/{emergency-queue-CQ-9acZf.cjs.map → emergency-queue-CNTRui5t.cjs.map} +1 -1
- package/dist/{emergency-queue-Cs8-i2xw.js → emergency-queue-Zy6lNafo.js} +15 -17
- package/dist/{emergency-queue-Cs8-i2xw.js.map → emergency-queue-Zy6lNafo.js.map} +1 -1
- package/dist/{error-like-Ywo5uRHo.js → error-like-B11pB4aL.js} +2 -3
- package/dist/{error-like-Ywo5uRHo.js.map → error-like-B11pB4aL.js.map} +1 -1
- package/dist/error-like-gGRx2s36.cjs.map +1 -1
- package/dist/{errors-oyxrpHjY.js → errors-Dh7kef0i.js} +5 -6
- package/dist/{errors-oyxrpHjY.js.map → errors-Dh7kef0i.js.map} +1 -1
- package/dist/{errors-CigX45pL.cjs → errors-tfEr48bS.cjs} +2 -2
- package/dist/{errors-CigX45pL.cjs.map → errors-tfEr48bS.cjs.map} +1 -1
- package/dist/{factory-Bgsky_e0.js → factory-BonqI3NL.js} +9 -13
- package/dist/{factory-Bgsky_e0.js.map → factory-BonqI3NL.js.map} +1 -1
- package/dist/{factory-BkjNzPYL.cjs → factory-CJXVYp0R.cjs} +2 -2
- package/dist/{factory-BkjNzPYL.cjs.map → factory-CJXVYp0R.cjs.map} +1 -1
- package/dist/fixed-window-CvESpFYV.cjs.map +1 -1
- package/dist/{fixed-window-CtaFHanJ.js → fixed-window-Dq3MLUUv.js} +2 -3
- package/dist/{fixed-window-CtaFHanJ.js.map → fixed-window-Dq3MLUUv.js.map} +1 -1
- package/dist/global-scope-BN-Io_yv.cjs.map +1 -1
- package/dist/{global-scope-dp2jADRl.js → global-scope-D9I8s-oN.js} +2 -3
- package/dist/{global-scope-dp2jADRl.js.map → global-scope-D9I8s-oN.js.map} +1 -1
- package/dist/{guards-CpvOpJL6.js → guards-Cidk71ME.js} +2 -3
- package/dist/{guards-CpvOpJL6.js.map → guards-Cidk71ME.js.map} +1 -1
- package/dist/guards-nJ70syPt.cjs.map +1 -1
- package/dist/{identity-BMlKGHUM.cjs → identity-Cxgj6pZX.cjs} +2 -2
- package/dist/{identity-BMlKGHUM.cjs.map → identity-Cxgj6pZX.cjs.map} +1 -1
- package/dist/{identity-DOaHdfhT.js → identity-DT5VmvXy.js} +3 -4
- package/dist/{identity-DOaHdfhT.js.map → identity-DT5VmvXy.js.map} +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +46 -56
- package/dist/index.js.map +1 -1
- package/dist/{indexeddb-storage-D-lUW_5P.js → indexeddb-storage-BJVtiQKm.js} +5 -6
- package/dist/{indexeddb-storage-D-lUW_5P.js.map → indexeddb-storage-BJVtiQKm.js.map} +1 -1
- package/dist/{indexeddb-storage-CaXGJqDD.cjs → indexeddb-storage-CIoW21Xd.cjs} +2 -2
- package/dist/{indexeddb-storage-CaXGJqDD.cjs.map → indexeddb-storage-CIoW21Xd.cjs.map} +1 -1
- package/dist/{interactions-CqDNrtIR.js → interactions-DTgKy_6K.js} +10 -11
- package/dist/{interactions-CqDNrtIR.js.map → interactions-DTgKy_6K.js.map} +1 -1
- package/dist/{interactions-8DgxtmgO.cjs → interactions-fEN6FbVo.cjs} +2 -2
- package/dist/{interactions-8DgxtmgO.cjs.map → interactions-fEN6FbVo.cjs.map} +1 -1
- package/dist/{journey-DgIjhrIc.js → journey-CuJrHzEg.js} +9 -10
- package/dist/{journey-DgIjhrIc.js.map → journey-CuJrHzEg.js.map} +1 -1
- package/dist/{journey-5tcxEbnG.cjs → journey-pffMVMfa.cjs} +2 -2
- package/dist/{journey-5tcxEbnG.cjs.map → journey-pffMVMfa.cjs.map} +1 -1
- package/dist/keys-BHhw_0Wh.cjs.map +1 -1
- package/dist/{keys-D5r_GH9q.js → keys-BU9j5YqW.js} +2 -3
- package/dist/{keys-D5r_GH9q.js.map → keys-BU9j5YqW.js.map} +1 -1
- package/dist/library-console-C1m6g1BR.js +13 -0
- package/dist/{library-console-CabK2j2-.js.map → library-console-C1m6g1BR.js.map} +1 -1
- package/dist/{library-console-g_VU-wzP.cjs → library-console-D2GY9Or6.cjs} +2 -2
- package/dist/{library-console-g_VU-wzP.cjs.map → library-console-D2GY9Or6.cjs.map} +1 -1
- package/dist/{library-request-FQaiWjCP.cjs → library-request-1BX_UlaX.cjs} +2 -2
- package/dist/{library-request-FQaiWjCP.cjs.map → library-request-1BX_UlaX.cjs.map} +1 -1
- package/dist/{library-request-CyC-9IOk.js → library-request-BQBT9N9Q.js} +4 -5
- package/dist/{library-request-CyC-9IOk.js.map → library-request-BQBT9N9Q.js.map} +1 -1
- package/dist/{lifecycle-C2z_d8OX.cjs → lifecycle-2EtUaRpo.cjs} +2 -2
- package/dist/{lifecycle-C2z_d8OX.cjs.map → lifecycle-2EtUaRpo.cjs.map} +1 -1
- package/dist/{lifecycle-BLC4VU7c.js → lifecycle-BaKx_-32.js} +3 -4
- package/dist/{lifecycle-BLC4VU7c.js.map → lifecycle-BaKx_-32.js.map} +1 -1
- package/dist/{log-record-CndanC-p.js → log-record-CAoGBBf3.js} +3 -4
- package/dist/{log-record-CndanC-p.js.map → log-record-CAoGBBf3.js.map} +1 -1
- package/dist/{log-record-DKvo-B-d.cjs → log-record-i9zOTkpQ.cjs} +2 -2
- package/dist/{log-record-DKvo-B-d.cjs.map → log-record-i9zOTkpQ.cjs.map} +1 -1
- package/dist/{long-frames-CV5ZG2cx.cjs → long-frames-BVg4i5SC.cjs} +2 -2
- package/dist/{long-frames-CV5ZG2cx.cjs.map → long-frames-BVg4i5SC.cjs.map} +1 -1
- package/dist/{long-frames-BQef9rXR.js → long-frames-Czk7IupC.js} +4 -5
- package/dist/{long-frames-BQef9rXR.js.map → long-frames-Czk7IupC.js.map} +1 -1
- package/dist/{network-CvkvYzRU.js → network-DBNwApoF.js} +22 -24
- package/dist/{network-CvkvYzRU.js.map → network-DBNwApoF.js.map} +1 -1
- package/dist/{network-CqnQOqon.cjs → network-xbbuvG_6.cjs} +2 -2
- package/dist/{network-CqnQOqon.cjs.map → network-xbbuvG_6.cjs.map} +1 -1
- package/dist/openfin-Bxelt0yg.js +7 -0
- package/dist/{openfin-BwEN0uj4.js.map → openfin-Bxelt0yg.js.map} +1 -1
- package/dist/openfin-DtH2f7zX.cjs.map +1 -1
- package/dist/{otlp-RVbkNQRh.cjs → otlp-BDvFrLnc.cjs} +2 -2
- package/dist/{otlp-RVbkNQRh.cjs.map → otlp-BDvFrLnc.cjs.map} +1 -1
- package/dist/{otlp-CYIL7MOE.js → otlp-BTJdIa6F.js} +4 -6
- package/dist/{otlp-CYIL7MOE.js.map → otlp-BTJdIa6F.js.map} +1 -1
- package/dist/patch-BX8KrPCT.cjs.map +1 -1
- package/dist/{patch-CCWfuEY7.js → patch-UdPz1ea8.js} +2 -3
- package/dist/{patch-CCWfuEY7.js.map → patch-UdPz1ea8.js.map} +1 -1
- package/dist/{platform-KMWkoI-v.cjs → platform-C2Ez5kDc.cjs} +2 -2
- package/dist/{platform-KMWkoI-v.cjs.map → platform-C2Ez5kDc.cjs.map} +1 -1
- package/dist/{platform-wcAkkv9F.js → platform-DkcuXwe-.js} +4 -5
- package/dist/{platform-wcAkkv9F.js.map → platform-DkcuXwe-.js.map} +1 -1
- package/dist/{remote-rules-CH_7PphT.js → remote-rules-Cfb4K-Nl.js} +5 -6
- package/dist/{remote-rules-CH_7PphT.js.map → remote-rules-Cfb4K-Nl.js.map} +1 -1
- package/dist/{remote-rules-BL8km4xk.cjs → remote-rules-vzvk7aKf.cjs} +2 -2
- package/dist/{remote-rules-BL8km4xk.cjs.map → remote-rules-vzvk7aKf.cjs.map} +1 -1
- package/dist/{reports-Bh_-KpZ2.cjs → reports-Dk2YhKIh.cjs} +2 -2
- package/dist/{reports-Bh_-KpZ2.cjs.map → reports-Dk2YhKIh.cjs.map} +1 -1
- package/dist/{reports-BOKyY3_A.js → reports-TA-zInnq.js} +4 -5
- package/dist/{reports-BOKyY3_A.js.map → reports-TA-zInnq.js.map} +1 -1
- package/dist/{resource-timing-BROnEJ0E.js → resource-timing-BLv3EA2A.js} +6 -7
- package/dist/{resource-timing-BROnEJ0E.js.map → resource-timing-BLv3EA2A.js.map} +1 -1
- package/dist/{resource-timing-CbgwNpog.cjs → resource-timing-Cysw1S1f.cjs} +2 -2
- package/dist/{resource-timing-CbgwNpog.cjs.map → resource-timing-Cysw1S1f.cjs.map} +1 -1
- package/dist/{sampling-BLO_pcV4.js → sampling-C4VV-1MS.js} +4 -5
- package/dist/{sampling-BLO_pcV4.js.map → sampling-C4VV-1MS.js.map} +1 -1
- package/dist/{sampling-ECGVYiDD.cjs → sampling-Ckh2yW9k.cjs} +2 -2
- package/dist/{sampling-ECGVYiDD.cjs.map → sampling-Ckh2yW9k.cjs.map} +1 -1
- package/dist/{sanitize-DS0G4_ea.js → sanitize-6ymPlVvP.js} +4 -5
- package/dist/{sanitize-DS0G4_ea.js.map → sanitize-6ymPlVvP.js.map} +1 -1
- package/dist/{sanitize-Bsn8HQWC.cjs → sanitize-BAWzkZt0.cjs} +2 -2
- package/dist/{sanitize-Bsn8HQWC.cjs.map → sanitize-BAWzkZt0.cjs.map} +1 -1
- package/dist/{select-DWO0-w8_.cjs → select-ZF4by-lF.cjs} +2 -2
- package/dist/{select-DWO0-w8_.cjs.map → select-ZF4by-lF.cjs.map} +1 -1
- package/dist/{select-wqt9Wxio.js → select-xtQaenIi.js} +7 -10
- package/dist/{select-wqt9Wxio.js.map → select-xtQaenIi.js.map} +1 -1
- package/dist/{sender-BkAVt-Rq.js → sender-CiMHC9YG.js} +92 -96
- package/dist/{sender-BkAVt-Rq.js.map → sender-CiMHC9YG.js.map} +1 -1
- package/dist/{sender-D82PxlCY.cjs → sender-D5wBoXA8.cjs} +2 -2
- package/dist/{sender-D82PxlCY.cjs.map → sender-D5wBoXA8.cjs.map} +1 -1
- package/dist/storage-BA9RqRO-.cjs.map +1 -1
- package/dist/{storage-w7Tslvlq.js → storage-DZwed89z.js} +2 -3
- package/dist/{storage-w7Tslvlq.js.map → storage-DZwed89z.js.map} +1 -1
- package/dist/{storm-DCEsqViG.cjs → storm-CYi9Swpx.cjs} +2 -2
- package/dist/{storm-DCEsqViG.cjs.map → storm-CYi9Swpx.cjs.map} +1 -1
- package/dist/{storm-DD4cUkoL.js → storm-VR024_QN.js} +4 -5
- package/dist/{storm-DD4cUkoL.js.map → storm-VR024_QN.js.map} +1 -1
- package/dist/{types-BR9t_w28.js → types-BAerHgCq.js} +2 -3
- package/dist/{types-BR9t_w28.js.map → types-BAerHgCq.js.map} +1 -1
- package/dist/types-C7WNpnG1.cjs.map +1 -1
- package/dist/{unclean-exit-BYZ5yaSI.js → unclean-exit-CwcUhFOn.js} +3 -4
- package/dist/{unclean-exit-BYZ5yaSI.js.map → unclean-exit-CwcUhFOn.js.map} +1 -1
- package/dist/{unclean-exit-CwdpbUDg.cjs → unclean-exit-DFUN57wY.cjs} +2 -2
- package/dist/{unclean-exit-CwdpbUDg.cjs.map → unclean-exit-DFUN57wY.cjs.map} +1 -1
- package/dist/{user-timing-C1kB3JEg.cjs → user-timing-C9kfRq3J.cjs} +2 -2
- package/dist/{user-timing-C1kB3JEg.cjs.map → user-timing-C9kfRq3J.cjs.map} +1 -1
- package/dist/{user-timing-Di2ra5DB.js → user-timing-_jZIhDKI.js} +4 -5
- package/dist/{user-timing-Di2ra5DB.js.map → user-timing-_jZIhDKI.js.map} +1 -1
- package/dist/{web-socket-DwBNhgre.cjs → web-socket-BWUoqBh8.cjs} +2 -2
- package/dist/{web-socket-DwBNhgre.cjs.map → web-socket-BWUoqBh8.cjs.map} +1 -1
- package/dist/{web-socket-B-5qqPy7.js → web-socket-CV7yIMnm.js} +14 -15
- package/dist/{web-socket-B-5qqPy7.js.map → web-socket-CV7yIMnm.js.map} +1 -1
- package/dist/{web-vitals-Bflr5jSA.js → web-vitals-Bq4WFHQo.js} +2 -3
- package/dist/{web-vitals-Bflr5jSA.js.map → web-vitals-Bq4WFHQo.js.map} +1 -1
- package/dist/web-vitals-DFuoTQbZ.cjs.map +1 -1
- package/dist/{worker-protocol-DXekoADQ.cjs → worker-protocol-Bai7GAIA.cjs} +2 -2
- package/dist/{worker-protocol-DXekoADQ.cjs.map → worker-protocol-Bai7GAIA.cjs.map} +1 -1
- package/dist/{worker-protocol-0HMf4-kY.js → worker-protocol-CrsdSDLn.js} +6 -7
- package/dist/{worker-protocol-0HMf4-kY.js.map → worker-protocol-CrsdSDLn.js.map} +1 -1
- package/dist/worker-server-BrIYkfoa.cjs +2 -0
- package/dist/{worker-server-BQK5z2yl.cjs.map → worker-server-BrIYkfoa.cjs.map} +1 -1
- package/dist/{worker-server-CKcmX5m5.js → worker-server-Dp5HYm4b.js} +25 -26
- package/dist/{worker-server-CKcmX5m5.js.map → worker-server-Dp5HYm4b.js.map} +1 -1
- package/dist/{worker-transport-Dj2yCQN5.cjs → worker-transport-Bwej4N2e.cjs} +2 -2
- package/dist/{worker-transport-Dj2yCQN5.cjs.map → worker-transport-Bwej4N2e.cjs.map} +1 -1
- package/dist/{worker-transport-2220ghFZ.js → worker-transport-D6jtgpqN.js} +9 -11
- package/dist/{worker-transport-2220ghFZ.js.map → worker-transport-D6jtgpqN.js.map} +1 -1
- package/package.json +27 -41
- package/dist/console-DZEcs7FL.cjs +0 -2
- package/dist/library-console-CabK2j2-.js +0 -14
- package/dist/openfin-BwEN0uj4.js +0 -8
- package/dist/worker-server-BQK5z2yl.cjs +0 -2
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { Tn as e, gt as t, ht as n } from "./constants-
|
|
2
|
-
import { n as r } from "./batch-
|
|
3
|
-
import { i, n as a, r as o, t as s } from "./factory-
|
|
4
|
-
|
|
1
|
+
import { Tn as e, gt as t, ht as n } from "./constants-zyrqveN4.js";
|
|
2
|
+
import { n as r } from "./batch-CL9uWYY3.js";
|
|
3
|
+
import { i, n as a, r as o, t as s } from "./factory-BonqI3NL.js";
|
|
4
|
+
// src/storage/idb-driver.ts
|
|
5
5
|
function c(e) {
|
|
6
6
|
return e.error ?? /* @__PURE__ */ Error("The IndexedDB request failed.");
|
|
7
7
|
}
|
|
@@ -198,7 +198,6 @@ var u = class {
|
|
|
198
198
|
return await this.db.deleteMany(n.map((e) => e.id)), n;
|
|
199
199
|
}
|
|
200
200
|
};
|
|
201
|
-
//#endregion
|
|
202
201
|
export { d as IndexedDbStorage };
|
|
203
202
|
|
|
204
|
-
//# sourceMappingURL=indexeddb-storage-
|
|
203
|
+
//# sourceMappingURL=indexeddb-storage-BJVtiQKm.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"indexeddb-storage-D-lUW_5P.js","names":["STORAGE_NAME_INDEXEDDB","INDEXEDDB_STORE_NAME","INDEXEDDB_CREATED_AT_INDEX","countRecords","reportEviction","EvictionPick","addDrop","failureOf","request","promisify","IdbDriver","name","batch","store","range","id","limit","cursor","visit","resolve","cutoff","ids","connection","mode","existing","opening","abandoned","db","reject","error","IndexedDbStorage","limits","diagnostics","onGap","dbName","evicted","records","gap","attempts","result","expired","total","reason","dropped","pick","howMany","hasAction","doomed"],"sources":["../src/storage/idb-driver.ts","../src/storage/indexeddb-storage.ts"],"sourcesContent":["// src/storage/idb-driver.ts\n//\n// This module holds the raw IndexedDB code for the batch store. It opens the database, wraps\n// requests in promises and reads in createdAt order. Code above this file uses only batches\n// and ids.\n\nimport {\n INDEXEDDB_CREATED_AT_INDEX,\n INDEXEDDB_SCHEMA_VERSION,\n INDEXEDDB_STORE_NAME,\n} from \"../constants\";\nimport type { LogBatch } from \"../models/batch\";\n\n/**\n * Returns the failure of a request that fired onerror. Some hosts report no\n * error on the request. The function then returns a replacement Error. A rejection with null\n * makes the instanceof Error test in save() false. save() then reports a full disk as an\n * ordinary write failure.\n * @param request Request that fired onerror.\n * @returns The failure that stopped it.\n */\nfunction failureOf(request: IDBRequest): Error {\n return request.error ?? new Error(\"The IndexedDB request failed.\");\n}\n\n/**\n * Resolves when an IndexedDB request succeeds. It rejects with the request\n * error. It reads the request as IDBRequest<any>. Each caller must name the type that it\n * expects.\n * @param request Request to await.\n * @returns The request result.\n */\nfunction promisify<T>(request: IDBRequest): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n request.onsuccess = () => {\n resolve(request.result as T);\n };\n request.onerror = () => {\n reject(failureOf(request));\n };\n });\n}\n\n/** This class wraps one IndexedDB database that holds undelivered batches by id. */\nexport class IdbDriver {\n /** This field holds the pending or completed open. The driver reuses it for one database. */\n private connection: Promise<IDBDatabase> | null = null;\n\n /**\n * @param name IndexedDB database name.\n */\n constructor(private readonly name: string) {}\n\n /**\n * Writes a batch. It replaces a stored batch with the same id.\n * @param batch Batch to persist.\n */\n async put(batch: LogBatch): Promise<void> {\n const store = await this.store(\"readwrite\");\n await promisify(store.put(batch));\n }\n\n /**\n * Reads batches of one context in creation order without removing them.\n * @param id Delivery context id.\n * @param limit Maximum batches to return.\n * @returns Batches of this context, oldest first.\n */\n async takeContext(id: string, limit: number): Promise<LogBatch[]> {\n const store = await this.store(\"readonly\");\n const range = IDBKeyRange.bound([id, 0], [id, Number.MAX_SAFE_INTEGER]);\n return promisify<LogBatch[]>(store.index(\"routingContext\").getAll(range, limit));\n }\n\n /**\n * Counts stored batches of one context.\n * @param id Delivery context id.\n * @returns Number of batches in this context.\n */\n async countContext(id: string): Promise<number> {\n const store = await this.store(\"readonly\");\n return promisify<number>(\n store\n .index(\"routingContext\")\n .count(IDBKeyRange.bound([id, 0], [id, Number.MAX_SAFE_INTEGER])),\n );\n }\n\n /**\n * Reads the oldest batches by createdAt. It does not remove them.\n * @param limit Maximum number of batches to return.\n * @returns Batches in ascending createdAt order.\n */\n async takeOldest(limit: number): Promise<LogBatch[]> {\n const store = await this.store(\"readonly\");\n return promisify<LogBatch[]>(store.index(INDEXEDDB_CREATED_AT_INDEX).getAll(null, limit));\n }\n\n /**\n * Walks the batches by createdAt, oldest first. It does not remove them. A cursor reads one\n * batch at a time. The walk can then stop before it reads the full store.\n * @param visit Receives each batch. It returns false to stop the walk.\n */\n async walkOldest(visit: (batch: LogBatch) => boolean): Promise<void> {\n const store = await this.store(\"readonly\");\n const request = store.index(INDEXEDDB_CREATED_AT_INDEX).openCursor();\n\n await new Promise<void>((resolve, reject) => {\n request.onsuccess = () => {\n const cursor = request.result;\n if (cursor === null || !visit(cursor.value as LogBatch)) {\n resolve();\n return;\n }\n cursor.continue();\n };\n request.onerror = () => {\n reject(failureOf(request));\n };\n });\n }\n\n /**\n * Reads each batch with a createdAt value before the cutoff.\n * @param cutoff Exclusive upper bound in epoch milliseconds.\n * @returns Batches older than the cutoff.\n */\n async takeBefore(cutoff: number): Promise<LogBatch[]> {\n const store = await this.store(\"readonly\");\n const range = IDBKeyRange.upperBound(cutoff, true);\n return promisify<LogBatch[]>(store.index(INDEXEDDB_CREATED_AT_INDEX).getAll(range));\n }\n\n /**\n * Deletes one batch. An id that is not stored resolves without error.\n * @param id Batch identifier.\n */\n async delete(id: string): Promise<void> {\n const store = await this.store(\"readwrite\");\n await promisify(store.delete(id));\n }\n\n /**\n * Deletes several batches in one transaction. A partial failure deletes none of\n * them.\n * @param ids Batch identifiers.\n */\n async deleteMany(ids: string[]): Promise<void> {\n const store = await this.store(\"readwrite\");\n await Promise.all(ids.map((id) => promisify(store.delete(id))));\n }\n\n /**\n * Sets the attempt count of a stored batch. It ignores an id that is not stored.\n * A batch that the library delivered and deleted must not come back. The get and the put use one\n * transaction. With two transactions, a prune in another window can delete the batch\n * between them. The put then restores it.\n * @param id Batch identifier.\n * @param attempts New absolute attempt count.\n */\n async bumpAttempts(id: string, attempts: number): Promise<void> {\n const store = await this.store(\"readwrite\");\n const batch = await promisify<LogBatch | undefined>(store.get(id));\n if (batch === undefined) {\n return;\n }\n\n await promisify(store.put({ ...batch, attempts }));\n }\n\n /**\n * Counts the stored batches.\n * @returns Total batch count.\n */\n async count(): Promise<number> {\n const store = await this.store(\"readonly\");\n return promisify<number>(store.count());\n }\n\n /** This method deletes all stored batches. */\n async clear(): Promise<void> {\n const store = await this.store(\"readwrite\");\n await promisify(store.clear());\n }\n\n /**\n * Opens the connection. A host that defines indexedDB but rejects open() fails\n * here. The factory can then select a different adapter.\n */\n async ready(): Promise<void> {\n await this.open();\n }\n\n /** This method closes the connection when a connection exists. */\n async close(): Promise<void> {\n const connection = this.connection;\n if (connection === null) {\n return;\n }\n\n this.connection = null;\n const db = await connection;\n db.close();\n }\n\n /**\n * Opens the batch store in a new transaction. A transaction is valid only until\n * control returns to the event loop. Each call takes a new transaction.\n * @param mode Transaction mode.\n * @returns The batch object store.\n */\n private async store(mode: IDBTransactionMode): Promise<IDBObjectStore> {\n const db = await this.open();\n return db.transaction(INDEXEDDB_STORE_NAME, mode).objectStore(INDEXEDDB_STORE_NAME);\n }\n\n /**\n * Opens the database one time. It gives the same connection to each later call.\n * It does not keep a failed open. The next call then opens again.\n * @returns The open database.\n */\n private open(): Promise<IDBDatabase> {\n const existing = this.connection;\n if (existing !== null) {\n return existing;\n }\n\n const opening = new Promise<IDBDatabase>((resolve, reject) => {\n const request = indexedDB.open(this.name, INDEXEDDB_SCHEMA_VERSION);\n let abandoned = false;\n\n request.onupgradeneeded = () => {\n const db = request.result;\n // A database from an earlier release already contains the store. A second create\n // throws ConstraintError and aborts the upgrade.\n if (!db.objectStoreNames.contains(INDEXEDDB_STORE_NAME)) {\n const store = db.createObjectStore(INDEXEDDB_STORE_NAME, { keyPath: \"id\" });\n store.createIndex(INDEXEDDB_CREATED_AT_INDEX, INDEXEDDB_CREATED_AT_INDEX);\n }\n // IndexedDB supplies the versionchange transaction during upgradeneeded.\n // eslint-disable-next-line @typescript-eslint/non-nullable-type-assertion-style\n const transaction = request.transaction as IDBTransaction;\n const store = transaction.objectStore(INDEXEDDB_STORE_NAME);\n if (!store.indexNames.contains(\"routingContext\"))\n store.createIndex(\"routingContext\", [\"routingContextId\", \"createdAt\"]);\n };\n\n request.onsuccess = () => {\n const db = request.result;\n\n if (abandoned) {\n // The blocked handler already rejected. No reference to this connection remains.\n // An open connection blocks the next upgrade.\n db.close();\n return;\n }\n\n // Another window upgrades the schema. That upgrade blocks until this\n // connection closes.\n db.onversionchange = () => {\n db.close();\n this.connection = null;\n };\n resolve(db);\n };\n request.onerror = () => {\n reject(failureOf(request));\n };\n request.onblocked = () => {\n // An older window holds the previous schema version. This open does not settle\n // until that window closes. Each storage call waits for it.\n abandoned = true;\n reject(new Error(\"Another connection blocks the IndexedDB upgrade.\"));\n };\n });\n\n this.connection = opening.catch((error: unknown) => {\n this.connection = null;\n throw error;\n });\n\n return this.connection;\n }\n}\n","// src/storage/indexeddb-storage.ts\n//\n// This module stores batches in IndexedDB. It indexes them by creation time.\n\nimport { QUOTA_EVICTION_DIVISOR, QUOTA_EXCEEDED_ERROR, STORAGE_NAME_INDEXEDDB } from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport { countRecords, type LogBatch } from \"../models/batch\";\nimport type { GapReporter, PruneResult, StorageAdapter, StorageLimits } from \"../models/storage\";\nimport { EvictionPick, hasAction } from \"./eviction\";\nimport { addDrop, reportEviction } from \"./gap\";\nimport { IdbDriver } from \"./idb-driver\";\n\n/** This StorageAdapter keeps batches in IndexedDB. */\nexport class IndexedDbStorage implements StorageAdapter {\n /** This field holds the storage strategy name. */\n readonly name = STORAGE_NAME_INDEXEDDB;\n\n /** This driver holds the IndexedDB code for the batch store. */\n private readonly db: IdbDriver;\n\n /**\n * @param dbName Database name.\n * @param limits Storage capacity and retention thresholds.\n * @param diagnostics Diagnostics reporter.\n * @param onGap Optional callback for dropped record reporting.\n */\n constructor(\n dbName: string,\n private readonly limits: StorageLimits,\n private readonly diagnostics: Diagnostics,\n private readonly onGap?: GapReporter,\n ) {\n this.db = new IdbDriver(dbName);\n }\n\n /**\n * Opens the database. It has no guard. The factory needs the rejection to\n * select the next adapter.\n */\n async open(): Promise<void> {\n await this.db.ready();\n }\n\n /**\n * Writes a batch to IndexedDB. It then prunes the storage.\n * @param batch Batch to store.\n */\n async save(batch: LogBatch): Promise<void> {\n try {\n await this.db.put(batch);\n await this.prune();\n } catch (error) {\n if (error instanceof Error && error.name === QUOTA_EXCEEDED_ERROR) {\n this.diagnostics.report(\n \"storage.quota_exceeded\",\n \"IndexedDB is full. The library removes the oldest batches.\",\n );\n const evicted = await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not remove old batches after a full disk.\",\n () => this.evictOldest(Math.ceil(this.limits.maxBatches / QUOTA_EVICTION_DIVISOR)),\n );\n if (evicted) {\n const records = countRecords(evicted);\n const gap: PruneResult = { batches: evicted.length, records, reason: \"quota\" };\n reportEviction(this.diagnostics, this.onGap, gap, evicted);\n }\n\n // The eviction makes room for this batch. Without a second write, save() resolves.\n // The library then loses the batch. No counter shows the loss.\n const stored = await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not write the batch after it removed old batches.\",\n async () => {\n await this.db.put(batch);\n return true;\n },\n );\n if (stored !== true) {\n const gap: PruneResult = { batches: 1, records: batch.records.length, reason: \"quota\" };\n reportEviction(this.diagnostics, this.onGap, gap, [batch]);\n }\n return;\n }\n\n this.diagnostics.report(\n \"storage.degraded\",\n \"The library could not store a batch.\",\n { batchId: batch.id },\n error,\n );\n // The diagnostic above names the failure. A storage.evicted report counts it two times.\n this.onGap?.({ batches: 1, records: batch.records.length, reason: \"not_stored\" }, [batch]);\n }\n }\n\n /**\n * Reads batches of one context in creation order without removing them.\n * @param id Delivery context id.\n * @param limit Maximum batches to return.\n * @returns Batches of this context, oldest first.\n */\n async takeContext(id: string, limit: number): Promise<LogBatch[]> {\n return (\n (await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"Could not query the context partition.\",\n () => this.db.takeContext(id, Math.min(limit, 0xffffffff)),\n )) ?? []\n );\n }\n\n /**\n * Counts stored batches of one context.\n * @param id Delivery context id.\n * @returns Number of batches in this context.\n */\n async countContext(id: string): Promise<number> {\n return (\n (await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"Could not count the context partition.\",\n () => this.db.countContext(id),\n )) ?? 0\n );\n }\n\n /**\n * Reads up to `limit` batches in FIFO order. It does not delete them.\n * @param limit Maximum number of batches to retrieve.\n * @returns Array of retrieved batches.\n */\n async take(limit: number): Promise<LogBatch[]> {\n const batches = await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not read the stored batches.\",\n // getAll() takes an unsigned 32-bit count. A larger count throws. Then the read gives nothing.\n () => this.db.takeOldest(Math.min(limit, 0xffffffff)),\n );\n return batches ?? [];\n }\n\n /**\n * Deletes the batch with the given ID from IndexedDB.\n * @param id Batch identifier to delete.\n */\n async remove(id: string): Promise<void> {\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not delete a batch.\",\n () => this.db.delete(id),\n );\n }\n\n /**\n * Sets the delivery attempt count of a stored batch.\n * @param id Batch identifier.\n * @param attempts New absolute attempt count.\n */\n async bumpAttempts(id: string, attempts: number): Promise<void> {\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not update the attempt count.\",\n () => this.db.bumpAttempts(id, attempts),\n );\n }\n\n /**\n * Removes expired batches. It then removes the oldest batches above the\n * capacity limit.\n * @returns Prune summary metrics.\n */\n async prune(): Promise<PruneResult> {\n const result: PruneResult = { batches: 0, records: 0, reason: \"expired\" };\n\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not prune the stored batches.\",\n async () => {\n const cutoff = Date.now() - this.limits.maxAgeMs;\n const expired = await this.db.takeBefore(cutoff);\n if (expired.length > 0) {\n await this.db.deleteMany(expired.map((batch) => batch.id));\n this.addGap(result, \"expired\", expired);\n }\n\n const total = await this.db.count();\n if (total > this.limits.maxBatches) {\n const evicted = await this.evictOldest(total - this.limits.maxBatches);\n this.addGap(result, \"over_capacity\", evicted);\n }\n },\n );\n\n return result;\n }\n\n /**\n * Returns the number of stored batches.\n * @returns Total batch count or 0 on failure.\n */\n async count(): Promise<number> {\n const total = await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not count the stored batches.\",\n () => this.db.count(),\n );\n return total ?? 0;\n }\n\n /** This method deletes all stored batches from the database. */\n async clear(): Promise<void> {\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not clear the stored batches.\",\n () => this.db.clear(),\n );\n }\n\n /** This method closes the active IndexedDB connection. */\n async close(): Promise<void> {\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not close the database.\",\n () => this.db.close(),\n );\n }\n\n /**\n * Adds dropped batches to the prune result. It reports them with their own reason.\n * @param result Prune result of all rules.\n * @param reason Rule that dropped the batches.\n * @param dropped The dropped batches.\n */\n private addGap(result: PruneResult, reason: PruneResult[\"reason\"], dropped: LogBatch[]): void {\n const gap = addDrop(result, reason, dropped.length, countRecords(dropped));\n reportEviction(this.diagnostics, this.onGap, gap, dropped);\n }\n\n /**\n * Deletes the given number of stored batches. Batches without an action go first, oldest\n * first. An action is an audit fact. It has no guard. Both callers guard it. A guard here\n * hides the failure and reports an eviction that did not occur.\n * @param howMany Number of batches to evict.\n * @returns The evicted batches.\n */\n private async evictOldest(howMany: number): Promise<LogBatch[]> {\n // Only the records tell if a batch holds an action. The walk stops at enough plain batches.\n const pick = new EvictionPick(howMany, hasAction);\n await this.db.walkOldest((batch) => pick.add(batch));\n\n const doomed = pick.picked();\n await this.db.deleteMany(doomed.map((batch) => batch.id));\n\n return doomed;\n }\n}\n"],"mappings":";;;;AAqBA,SAASO,EAAU,GAA4B;CAC7C,OAAOC,EAAQ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;CACF;CAGA,MAAM,QAAuB;EAC3B,MAAM,KAAK,YAAY,WACrB,oBACA,mDACM,KAAK,GAAG,MAAM,CACtB;CACF;CAQA,OAAe,GAAqB,GAA+B,GAA2B;EAC5F,IAAMF,IAAM/B,EAAQiC,GAAQG,GAAQC,EAAQ,QAAQxC,EAAawC,CAAO,CAAC;EACzE,EAAe,KAAK,aAAa,KAAK,OAAON,GAAKM,CAAO;CAC3D;CASA,MAAc,YAAY,GAAsC;EAE9D,IAAMC,IAAO,IAAIvC,EAAawC,GAASC,CAAS;EAChD,MAAM,KAAK,GAAG,YAAY,MAAUF,EAAK,IAAIhC,CAAK,CAAC;EAEnD,IAAMmC,IAASH,EAAK,OAAO;EAG3B,OAFA,MAAM,KAAK,GAAG,WAAWG,EAAO,KAAK,MAAUnC,EAAM,EAAE,CAAC,GAEjDmC;CACT;AACF"}
|
|
1
|
+
{"version":3,"file":"indexeddb-storage-BJVtiQKm.js","names":["STORAGE_NAME_INDEXEDDB","INDEXEDDB_STORE_NAME","INDEXEDDB_CREATED_AT_INDEX","countRecords","reportEviction","EvictionPick","addDrop","failureOf","request","promisify","IdbDriver","name","batch","store","range","id","limit","cursor","visit","resolve","cutoff","ids","connection","mode","existing","opening","abandoned","db","reject","error","IndexedDbStorage","limits","diagnostics","onGap","dbName","evicted","records","gap","attempts","result","expired","total","reason","dropped","pick","howMany","hasAction","doomed"],"sources":["../src/storage/idb-driver.ts","../src/storage/indexeddb-storage.ts"],"sourcesContent":["// src/storage/idb-driver.ts\n//\n// This module holds the raw IndexedDB code for the batch store. It opens the database, wraps\n// requests in promises and reads in createdAt order. Code above this file uses only batches\n// and ids.\n\nimport {\n INDEXEDDB_CREATED_AT_INDEX,\n INDEXEDDB_SCHEMA_VERSION,\n INDEXEDDB_STORE_NAME,\n} from \"../constants\";\nimport type { LogBatch } from \"../models/batch\";\n\n/**\n * Returns the failure of a request that fired onerror. Some hosts report no\n * error on the request. The function then returns a replacement Error. A rejection with null\n * makes the instanceof Error test in save() false. save() then reports a full disk as an\n * ordinary write failure.\n * @param request Request that fired onerror.\n * @returns The failure that stopped it.\n */\nfunction failureOf(request: IDBRequest): Error {\n return request.error ?? new Error(\"The IndexedDB request failed.\");\n}\n\n/**\n * Resolves when an IndexedDB request succeeds. It rejects with the request\n * error. It reads the request as IDBRequest<any>. Each caller must name the type that it\n * expects.\n * @param request Request to await.\n * @returns The request result.\n */\nfunction promisify<T>(request: IDBRequest): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n request.onsuccess = () => {\n resolve(request.result as T);\n };\n request.onerror = () => {\n reject(failureOf(request));\n };\n });\n}\n\n/** This class wraps one IndexedDB database that holds undelivered batches by id. */\nexport class IdbDriver {\n /** This field holds the pending or completed open. The driver reuses it for one database. */\n private connection: Promise<IDBDatabase> | null = null;\n\n /**\n * @param name IndexedDB database name.\n */\n constructor(private readonly name: string) {}\n\n /**\n * Writes a batch. It replaces a stored batch with the same id.\n * @param batch Batch to persist.\n */\n async put(batch: LogBatch): Promise<void> {\n const store = await this.store(\"readwrite\");\n await promisify(store.put(batch));\n }\n\n /**\n * Reads batches of one context in creation order without removing them.\n * @param id Delivery context id.\n * @param limit Maximum batches to return.\n * @returns Batches of this context, oldest first.\n */\n async takeContext(id: string, limit: number): Promise<LogBatch[]> {\n const store = await this.store(\"readonly\");\n const range = IDBKeyRange.bound([id, 0], [id, Number.MAX_SAFE_INTEGER]);\n return promisify<LogBatch[]>(store.index(\"routingContext\").getAll(range, limit));\n }\n\n /**\n * Counts stored batches of one context.\n * @param id Delivery context id.\n * @returns Number of batches in this context.\n */\n async countContext(id: string): Promise<number> {\n const store = await this.store(\"readonly\");\n return promisify<number>(\n store\n .index(\"routingContext\")\n .count(IDBKeyRange.bound([id, 0], [id, Number.MAX_SAFE_INTEGER])),\n );\n }\n\n /**\n * Reads the oldest batches by createdAt. It does not remove them.\n * @param limit Maximum number of batches to return.\n * @returns Batches in ascending createdAt order.\n */\n async takeOldest(limit: number): Promise<LogBatch[]> {\n const store = await this.store(\"readonly\");\n return promisify<LogBatch[]>(store.index(INDEXEDDB_CREATED_AT_INDEX).getAll(null, limit));\n }\n\n /**\n * Walks the batches by createdAt, oldest first. It does not remove them. A cursor reads one\n * batch at a time. The walk can then stop before it reads the full store.\n * @param visit Receives each batch. It returns false to stop the walk.\n */\n async walkOldest(visit: (batch: LogBatch) => boolean): Promise<void> {\n const store = await this.store(\"readonly\");\n const request = store.index(INDEXEDDB_CREATED_AT_INDEX).openCursor();\n\n await new Promise<void>((resolve, reject) => {\n request.onsuccess = () => {\n const cursor = request.result;\n if (cursor === null || !visit(cursor.value as LogBatch)) {\n resolve();\n return;\n }\n cursor.continue();\n };\n request.onerror = () => {\n reject(failureOf(request));\n };\n });\n }\n\n /**\n * Reads each batch with a createdAt value before the cutoff.\n * @param cutoff Exclusive upper bound in epoch milliseconds.\n * @returns Batches older than the cutoff.\n */\n async takeBefore(cutoff: number): Promise<LogBatch[]> {\n const store = await this.store(\"readonly\");\n const range = IDBKeyRange.upperBound(cutoff, true);\n return promisify<LogBatch[]>(store.index(INDEXEDDB_CREATED_AT_INDEX).getAll(range));\n }\n\n /**\n * Deletes one batch. An id that is not stored resolves without error.\n * @param id Batch identifier.\n */\n async delete(id: string): Promise<void> {\n const store = await this.store(\"readwrite\");\n await promisify(store.delete(id));\n }\n\n /**\n * Deletes several batches in one transaction. A partial failure deletes none of\n * them.\n * @param ids Batch identifiers.\n */\n async deleteMany(ids: string[]): Promise<void> {\n const store = await this.store(\"readwrite\");\n await Promise.all(ids.map((id) => promisify(store.delete(id))));\n }\n\n /**\n * Sets the attempt count of a stored batch. It ignores an id that is not stored.\n * A batch that the library delivered and deleted must not come back. The get and the put use one\n * transaction. With two transactions, a prune in another window can delete the batch\n * between them. The put then restores it.\n * @param id Batch identifier.\n * @param attempts New absolute attempt count.\n */\n async bumpAttempts(id: string, attempts: number): Promise<void> {\n const store = await this.store(\"readwrite\");\n const batch = await promisify<LogBatch | undefined>(store.get(id));\n if (batch === undefined) {\n return;\n }\n\n await promisify(store.put({ ...batch, attempts }));\n }\n\n /**\n * Counts the stored batches.\n * @returns Total batch count.\n */\n async count(): Promise<number> {\n const store = await this.store(\"readonly\");\n return promisify<number>(store.count());\n }\n\n /** This method deletes all stored batches. */\n async clear(): Promise<void> {\n const store = await this.store(\"readwrite\");\n await promisify(store.clear());\n }\n\n /**\n * Opens the connection. A host that defines indexedDB but rejects open() fails\n * here. The factory can then select a different adapter.\n */\n async ready(): Promise<void> {\n await this.open();\n }\n\n /** This method closes the connection when a connection exists. */\n async close(): Promise<void> {\n const connection = this.connection;\n if (connection === null) {\n return;\n }\n\n this.connection = null;\n const db = await connection;\n db.close();\n }\n\n /**\n * Opens the batch store in a new transaction. A transaction is valid only until\n * control returns to the event loop. Each call takes a new transaction.\n * @param mode Transaction mode.\n * @returns The batch object store.\n */\n private async store(mode: IDBTransactionMode): Promise<IDBObjectStore> {\n const db = await this.open();\n return db.transaction(INDEXEDDB_STORE_NAME, mode).objectStore(INDEXEDDB_STORE_NAME);\n }\n\n /**\n * Opens the database one time. It gives the same connection to each later call.\n * It does not keep a failed open. The next call then opens again.\n * @returns The open database.\n */\n private open(): Promise<IDBDatabase> {\n const existing = this.connection;\n if (existing !== null) {\n return existing;\n }\n\n const opening = new Promise<IDBDatabase>((resolve, reject) => {\n const request = indexedDB.open(this.name, INDEXEDDB_SCHEMA_VERSION);\n let abandoned = false;\n\n request.onupgradeneeded = () => {\n const db = request.result;\n // A database from an earlier release already contains the store. A second create\n // throws ConstraintError and aborts the upgrade.\n if (!db.objectStoreNames.contains(INDEXEDDB_STORE_NAME)) {\n const store = db.createObjectStore(INDEXEDDB_STORE_NAME, { keyPath: \"id\" });\n store.createIndex(INDEXEDDB_CREATED_AT_INDEX, INDEXEDDB_CREATED_AT_INDEX);\n }\n // IndexedDB supplies the versionchange transaction during upgradeneeded.\n // eslint-disable-next-line @typescript-eslint/non-nullable-type-assertion-style\n const transaction = request.transaction as IDBTransaction;\n const store = transaction.objectStore(INDEXEDDB_STORE_NAME);\n if (!store.indexNames.contains(\"routingContext\"))\n store.createIndex(\"routingContext\", [\"routingContextId\", \"createdAt\"]);\n };\n\n request.onsuccess = () => {\n const db = request.result;\n\n if (abandoned) {\n // The blocked handler already rejected. No reference to this connection remains.\n // An open connection blocks the next upgrade.\n db.close();\n return;\n }\n\n // Another window upgrades the schema. That upgrade blocks until this\n // connection closes.\n db.onversionchange = () => {\n db.close();\n this.connection = null;\n };\n resolve(db);\n };\n request.onerror = () => {\n reject(failureOf(request));\n };\n request.onblocked = () => {\n // An older window holds the previous schema version. This open does not settle\n // until that window closes. Each storage call waits for it.\n abandoned = true;\n reject(new Error(\"Another connection blocks the IndexedDB upgrade.\"));\n };\n });\n\n this.connection = opening.catch((error: unknown) => {\n this.connection = null;\n throw error;\n });\n\n return this.connection;\n }\n}\n","// src/storage/indexeddb-storage.ts\n//\n// This module stores batches in IndexedDB. It indexes them by creation time.\n\nimport { QUOTA_EVICTION_DIVISOR, QUOTA_EXCEEDED_ERROR, STORAGE_NAME_INDEXEDDB } from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport { countRecords, type LogBatch } from \"../models/batch\";\nimport type { GapReporter, PruneResult, StorageAdapter, StorageLimits } from \"../models/storage\";\nimport { EvictionPick, hasAction } from \"./eviction\";\nimport { addDrop, reportEviction } from \"./gap\";\nimport { IdbDriver } from \"./idb-driver\";\n\n/** This StorageAdapter keeps batches in IndexedDB. */\nexport class IndexedDbStorage implements StorageAdapter {\n /** This field holds the storage strategy name. */\n readonly name = STORAGE_NAME_INDEXEDDB;\n\n /** This driver holds the IndexedDB code for the batch store. */\n private readonly db: IdbDriver;\n\n /**\n * @param dbName Database name.\n * @param limits Storage capacity and retention thresholds.\n * @param diagnostics Diagnostics reporter.\n * @param onGap Optional callback for dropped record reporting.\n */\n constructor(\n dbName: string,\n private readonly limits: StorageLimits,\n private readonly diagnostics: Diagnostics,\n private readonly onGap?: GapReporter,\n ) {\n this.db = new IdbDriver(dbName);\n }\n\n /**\n * Opens the database. It has no guard. The factory needs the rejection to\n * select the next adapter.\n */\n async open(): Promise<void> {\n await this.db.ready();\n }\n\n /**\n * Writes a batch to IndexedDB. It then prunes the storage.\n * @param batch Batch to store.\n */\n async save(batch: LogBatch): Promise<void> {\n try {\n await this.db.put(batch);\n await this.prune();\n } catch (error) {\n if (error instanceof Error && error.name === QUOTA_EXCEEDED_ERROR) {\n this.diagnostics.report(\n \"storage.quota_exceeded\",\n \"IndexedDB is full. The library removes the oldest batches.\",\n );\n const evicted = await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not remove old batches after a full disk.\",\n () => this.evictOldest(Math.ceil(this.limits.maxBatches / QUOTA_EVICTION_DIVISOR)),\n );\n if (evicted) {\n const records = countRecords(evicted);\n const gap: PruneResult = { batches: evicted.length, records, reason: \"quota\" };\n reportEviction(this.diagnostics, this.onGap, gap, evicted);\n }\n\n // The eviction makes room for this batch. Without a second write, save() resolves.\n // The library then loses the batch. No counter shows the loss.\n const stored = await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not write the batch after it removed old batches.\",\n async () => {\n await this.db.put(batch);\n return true;\n },\n );\n if (stored !== true) {\n const gap: PruneResult = { batches: 1, records: batch.records.length, reason: \"quota\" };\n reportEviction(this.diagnostics, this.onGap, gap, [batch]);\n }\n return;\n }\n\n this.diagnostics.report(\n \"storage.degraded\",\n \"The library could not store a batch.\",\n { batchId: batch.id },\n error,\n );\n // The diagnostic above names the failure. A storage.evicted report counts it two times.\n this.onGap?.({ batches: 1, records: batch.records.length, reason: \"not_stored\" }, [batch]);\n }\n }\n\n /**\n * Reads batches of one context in creation order without removing them.\n * @param id Delivery context id.\n * @param limit Maximum batches to return.\n * @returns Batches of this context, oldest first.\n */\n async takeContext(id: string, limit: number): Promise<LogBatch[]> {\n return (\n (await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"Could not query the context partition.\",\n () => this.db.takeContext(id, Math.min(limit, 0xffffffff)),\n )) ?? []\n );\n }\n\n /**\n * Counts stored batches of one context.\n * @param id Delivery context id.\n * @returns Number of batches in this context.\n */\n async countContext(id: string): Promise<number> {\n return (\n (await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"Could not count the context partition.\",\n () => this.db.countContext(id),\n )) ?? 0\n );\n }\n\n /**\n * Reads up to `limit` batches in FIFO order. It does not delete them.\n * @param limit Maximum number of batches to retrieve.\n * @returns Array of retrieved batches.\n */\n async take(limit: number): Promise<LogBatch[]> {\n const batches = await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not read the stored batches.\",\n // getAll() takes an unsigned 32-bit count. A larger count throws. Then the read gives nothing.\n () => this.db.takeOldest(Math.min(limit, 0xffffffff)),\n );\n return batches ?? [];\n }\n\n /**\n * Deletes the batch with the given ID from IndexedDB.\n * @param id Batch identifier to delete.\n */\n async remove(id: string): Promise<void> {\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not delete a batch.\",\n () => this.db.delete(id),\n );\n }\n\n /**\n * Sets the delivery attempt count of a stored batch.\n * @param id Batch identifier.\n * @param attempts New absolute attempt count.\n */\n async bumpAttempts(id: string, attempts: number): Promise<void> {\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not update the attempt count.\",\n () => this.db.bumpAttempts(id, attempts),\n );\n }\n\n /**\n * Removes expired batches. It then removes the oldest batches above the\n * capacity limit.\n * @returns Prune summary metrics.\n */\n async prune(): Promise<PruneResult> {\n const result: PruneResult = { batches: 0, records: 0, reason: \"expired\" };\n\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not prune the stored batches.\",\n async () => {\n const cutoff = Date.now() - this.limits.maxAgeMs;\n const expired = await this.db.takeBefore(cutoff);\n if (expired.length > 0) {\n await this.db.deleteMany(expired.map((batch) => batch.id));\n this.addGap(result, \"expired\", expired);\n }\n\n const total = await this.db.count();\n if (total > this.limits.maxBatches) {\n const evicted = await this.evictOldest(total - this.limits.maxBatches);\n this.addGap(result, \"over_capacity\", evicted);\n }\n },\n );\n\n return result;\n }\n\n /**\n * Returns the number of stored batches.\n * @returns Total batch count or 0 on failure.\n */\n async count(): Promise<number> {\n const total = await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not count the stored batches.\",\n () => this.db.count(),\n );\n return total ?? 0;\n }\n\n /** This method deletes all stored batches from the database. */\n async clear(): Promise<void> {\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not clear the stored batches.\",\n () => this.db.clear(),\n );\n }\n\n /** This method closes the active IndexedDB connection. */\n async close(): Promise<void> {\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not close the database.\",\n () => this.db.close(),\n );\n }\n\n /**\n * Adds dropped batches to the prune result. It reports them with their own reason.\n * @param result Prune result of all rules.\n * @param reason Rule that dropped the batches.\n * @param dropped The dropped batches.\n */\n private addGap(result: PruneResult, reason: PruneResult[\"reason\"], dropped: LogBatch[]): void {\n const gap = addDrop(result, reason, dropped.length, countRecords(dropped));\n reportEviction(this.diagnostics, this.onGap, gap, dropped);\n }\n\n /**\n * Deletes the given number of stored batches. Batches without an action go first, oldest\n * first. An action is an audit fact. It has no guard. Both callers guard it. A guard here\n * hides the failure and reports an eviction that did not occur.\n * @param howMany Number of batches to evict.\n * @returns The evicted batches.\n */\n private async evictOldest(howMany: number): Promise<LogBatch[]> {\n // Only the records tell if a batch holds an action. The walk stops at enough plain batches.\n const pick = new EvictionPick(howMany, hasAction);\n await this.db.walkOldest((batch) => pick.add(batch));\n\n const doomed = pick.picked();\n await this.db.deleteMany(doomed.map((batch) => batch.id));\n\n return doomed;\n }\n}\n"],"mappings":";;;;AAqBA,SAASO,EAAU,GAA4B;CAC7C,OAAOC,EAAQ,SAAS,gBAAI,MAAM,+BAA+B;AACnE;AASA,SAASC,EAAa,GAAiC;CACrD,OAAO,IAAI,SAAY,GAAS,MAAW;EAIzC,AAHA,EAAQ,kBAAkB;GACxB,EAAQD,EAAQ,MAAW;EAC7B,GACA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,GAAQG,GAAQC,EAAQ,QAAQxC,EAAawC,CAAO,CAAC;EACzE,EAAe,KAAK,aAAa,KAAK,OAAON,GAAKM,CAAO;CAC3D;CASA,MAAc,YAAY,GAAsC;EAE9D,IAAMC,IAAO,IAAIvC,EAAawC,GAASC,CAAS;EAChD,MAAM,KAAK,GAAG,YAAY,MAAUF,EAAK,IAAIhC,CAAK,CAAC;EAEnD,IAAMmC,IAASH,EAAK,OAAO;EAG3B,OAFA,MAAM,KAAK,GAAG,WAAWG,EAAO,KAAK,MAAUnC,EAAM,EAAE,CAAC,GAEjDmC;CACT;AACF"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("./constants-
|
|
2
|
-
//# sourceMappingURL=indexeddb-storage-
|
|
1
|
+
const e=require("./constants-DqKJH_MP.cjs"),t=require("./batch-C8OcWR2L.cjs"),n=require("./factory-CJXVYp0R.cjs");function r(e){return e.error??Error(`The IndexedDB request failed.`)}function i(e){return new Promise((t,n)=>{e.onsuccess=()=>{t(e.result)},e.onerror=()=>{n(r(e))}})}var a=class{name;connection=null;constructor(e){this.name=e}async put(e){await i((await this.store(`readwrite`)).put(e))}async takeContext(e,t){let n=await this.store(`readonly`),r=IDBKeyRange.bound([e,0],[e,2**53-1]);return i(n.index(`routingContext`).getAll(r,t))}async countContext(e){return i((await this.store(`readonly`)).index(`routingContext`).count(IDBKeyRange.bound([e,0],[e,2**53-1])))}async takeOldest(t){return i((await this.store(`readonly`)).index(e.ht).getAll(null,t))}async walkOldest(t){let n=(await this.store(`readonly`)).index(e.ht).openCursor();await new Promise((e,i)=>{n.onsuccess=()=>{let r=n.result;r===null||!t(r.value)?e():r.continue()},n.onerror=()=>{i(r(n))}})}async takeBefore(t){let n=await this.store(`readonly`),r=IDBKeyRange.upperBound(t,!0);return i(n.index(e.ht).getAll(r))}async delete(e){await i((await this.store(`readwrite`)).delete(e))}async deleteMany(e){let t=await this.store(`readwrite`);await Promise.all(e.map(e=>i(t.delete(e))))}async bumpAttempts(e,t){let n=await this.store(`readwrite`),r=await i(n.get(e));r!==void 0&&await i(n.put({...r,attempts:t}))}async count(){return i((await this.store(`readonly`)).count())}async clear(){await i((await this.store(`readwrite`)).clear())}async ready(){await this.open()}async close(){let e=this.connection;e!==null&&(this.connection=null,(await e).close())}async store(t){return(await this.open()).transaction(e.gt,t).objectStore(e.gt)}open(){let t=this.connection;if(t!==null)return t;let n=new Promise((t,n)=>{let i=indexedDB.open(this.name,12),a=!1;i.onupgradeneeded=()=>{let t=i.result;t.objectStoreNames.contains(`batches`)||t.createObjectStore(e.gt,{keyPath:`id`}).createIndex(e.ht,e.ht);let n=i.transaction.objectStore(e.gt);n.indexNames.contains(`routingContext`)||n.createIndex(`routingContext`,[`routingContextId`,`createdAt`])},i.onsuccess=()=>{let e=i.result;a?e.close():(e.onversionchange=()=>{e.close(),this.connection=null},t(e))},i.onerror=()=>{n(r(i))},i.onblocked=()=>{a=!0,n(Error(`Another connection blocks the IndexedDB upgrade.`))}});return this.connection=n.catch(e=>{throw this.connection=null,e}),this.connection}},o=class{limits;diagnostics;onGap;name=e.Tn;db;constructor(e,t,n,r){this.limits=t,this.diagnostics=n,this.onGap=r,this.db=new a(e)}async open(){await this.db.ready()}async save(e){try{await this.db.put(e),await this.prune()}catch(r){if(r instanceof Error&&r.name===`QuotaExceededError`){this.diagnostics.report(`storage.quota_exceeded`,`IndexedDB is full. The library removes the oldest batches.`);let r=await this.diagnostics.guardAsync(`storage.degraded`,`The library could not remove old batches after a full disk.`,()=>this.evictOldest(Math.ceil(this.limits.maxBatches/4)));if(r){let e=t.n(r),i={batches:r.length,records:e,reason:`quota`};n.n(this.diagnostics,this.onGap,i,r)}if(await this.diagnostics.guardAsync(`storage.degraded`,`The library could not write the batch after it removed old batches.`,async()=>(await this.db.put(e),!0))!==!0){let t={batches:1,records:e.records.length,reason:`quota`};n.n(this.diagnostics,this.onGap,t,[e])}return}this.diagnostics.report(`storage.degraded`,`The library could not store a batch.`,{batchId:e.id},r),this.onGap?.({batches:1,records:e.records.length,reason:`not_stored`},[e])}}async takeContext(e,t){return await this.diagnostics.guardAsync(`storage.degraded`,`Could not query the context partition.`,()=>this.db.takeContext(e,Math.min(t,4294967295)))??[]}async countContext(e){return await this.diagnostics.guardAsync(`storage.degraded`,`Could not count the context partition.`,()=>this.db.countContext(e))??0}async take(e){return await this.diagnostics.guardAsync(`storage.degraded`,`The library could not read the stored batches.`,()=>this.db.takeOldest(Math.min(e,4294967295)))??[]}async remove(e){await this.diagnostics.guardAsync(`storage.degraded`,`The library could not delete a batch.`,()=>this.db.delete(e))}async bumpAttempts(e,t){await this.diagnostics.guardAsync(`storage.degraded`,`The library could not update the attempt count.`,()=>this.db.bumpAttempts(e,t))}async prune(){let e={batches:0,records:0,reason:`expired`};return await this.diagnostics.guardAsync(`storage.degraded`,`The library could not prune the stored batches.`,async()=>{let t=Date.now()-this.limits.maxAgeMs,n=await this.db.takeBefore(t);n.length>0&&(await this.db.deleteMany(n.map(e=>e.id)),this.addGap(e,`expired`,n));let r=await this.db.count();if(r>this.limits.maxBatches){let t=await this.evictOldest(r-this.limits.maxBatches);this.addGap(e,`over_capacity`,t)}}),e}async count(){return await this.diagnostics.guardAsync(`storage.degraded`,`The library could not count the stored batches.`,()=>this.db.count())??0}async clear(){await this.diagnostics.guardAsync(`storage.degraded`,`The library could not clear the stored batches.`,()=>this.db.clear())}async close(){await this.diagnostics.guardAsync(`storage.degraded`,`The library could not close the database.`,()=>this.db.close())}addGap(e,r,i){let a=n.t(e,r,i.length,t.n(i));n.n(this.diagnostics,this.onGap,a,i)}async evictOldest(e){let t=new n.r(e,n.i);await this.db.walkOldest(e=>t.add(e));let r=t.picked();return await this.db.deleteMany(r.map(e=>e.id)),r}};exports.IndexedDbStorage=o;
|
|
2
|
+
//# sourceMappingURL=indexeddb-storage-CIoW21Xd.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"indexeddb-storage-CaXGJqDD.cjs","names":["INDEXEDDB_CREATED_AT_INDEX","INDEXEDDB_STORE_NAME","STORAGE_NAME_INDEXEDDB","countRecords","addDrop","EvictionPick","hasAction","require_constants","require_batch","require_factory","failureOf","request","promisify","resolve","reject","IdbDriver","name","batch","store","range","id","limit","cursor","visit","cutoff","ids","connection","mode","existing","opening","abandoned","db","error","IndexedDbStorage","limits","diagnostics","onGap","dbName","evicted","records","gap","attempts","result","expired","total","reason","dropped","pick","howMany","doomed"],"sources":["../src/storage/idb-driver.ts","../src/storage/indexeddb-storage.ts"],"sourcesContent":["// src/storage/idb-driver.ts\n//\n// This module holds the raw IndexedDB code for the batch store. It opens the database, wraps\n// requests in promises and reads in createdAt order. Code above this file uses only batches\n// and ids.\n\nimport {\n INDEXEDDB_CREATED_AT_INDEX,\n INDEXEDDB_SCHEMA_VERSION,\n INDEXEDDB_STORE_NAME,\n} from \"../constants\";\nimport type { LogBatch } from \"../models/batch\";\n\n/**\n * Returns the failure of a request that fired onerror. Some hosts report no\n * error on the request. The function then returns a replacement Error. A rejection with null\n * makes the instanceof Error test in save() false. save() then reports a full disk as an\n * ordinary write failure.\n * @param request Request that fired onerror.\n * @returns The failure that stopped it.\n */\nfunction failureOf(request: IDBRequest): Error {\n return request.error ?? new Error(\"The IndexedDB request failed.\");\n}\n\n/**\n * Resolves when an IndexedDB request succeeds. It rejects with the request\n * error. It reads the request as IDBRequest<any>. Each caller must name the type that it\n * expects.\n * @param request Request to await.\n * @returns The request result.\n */\nfunction promisify<T>(request: IDBRequest): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n request.onsuccess = () => {\n resolve(request.result as T);\n };\n request.onerror = () => {\n reject(failureOf(request));\n };\n });\n}\n\n/** This class wraps one IndexedDB database that holds undelivered batches by id. */\nexport class IdbDriver {\n /** This field holds the pending or completed open. The driver reuses it for one database. */\n private connection: Promise<IDBDatabase> | null = null;\n\n /**\n * @param name IndexedDB database name.\n */\n constructor(private readonly name: string) {}\n\n /**\n * Writes a batch. It replaces a stored batch with the same id.\n * @param batch Batch to persist.\n */\n async put(batch: LogBatch): Promise<void> {\n const store = await this.store(\"readwrite\");\n await promisify(store.put(batch));\n }\n\n /**\n * Reads batches of one context in creation order without removing them.\n * @param id Delivery context id.\n * @param limit Maximum batches to return.\n * @returns Batches of this context, oldest first.\n */\n async takeContext(id: string, limit: number): Promise<LogBatch[]> {\n const store = await this.store(\"readonly\");\n const range = IDBKeyRange.bound([id, 0], [id, Number.MAX_SAFE_INTEGER]);\n return promisify<LogBatch[]>(store.index(\"routingContext\").getAll(range, limit));\n }\n\n /**\n * Counts stored batches of one context.\n * @param id Delivery context id.\n * @returns Number of batches in this context.\n */\n async countContext(id: string): Promise<number> {\n const store = await this.store(\"readonly\");\n return promisify<number>(\n store\n .index(\"routingContext\")\n .count(IDBKeyRange.bound([id, 0], [id, Number.MAX_SAFE_INTEGER])),\n );\n }\n\n /**\n * Reads the oldest batches by createdAt. It does not remove them.\n * @param limit Maximum number of batches to return.\n * @returns Batches in ascending createdAt order.\n */\n async takeOldest(limit: number): Promise<LogBatch[]> {\n const store = await this.store(\"readonly\");\n return promisify<LogBatch[]>(store.index(INDEXEDDB_CREATED_AT_INDEX).getAll(null, limit));\n }\n\n /**\n * Walks the batches by createdAt, oldest first. It does not remove them. A cursor reads one\n * batch at a time. The walk can then stop before it reads the full store.\n * @param visit Receives each batch. It returns false to stop the walk.\n */\n async walkOldest(visit: (batch: LogBatch) => boolean): Promise<void> {\n const store = await this.store(\"readonly\");\n const request = store.index(INDEXEDDB_CREATED_AT_INDEX).openCursor();\n\n await new Promise<void>((resolve, reject) => {\n request.onsuccess = () => {\n const cursor = request.result;\n if (cursor === null || !visit(cursor.value as LogBatch)) {\n resolve();\n return;\n }\n cursor.continue();\n };\n request.onerror = () => {\n reject(failureOf(request));\n };\n });\n }\n\n /**\n * Reads each batch with a createdAt value before the cutoff.\n * @param cutoff Exclusive upper bound in epoch milliseconds.\n * @returns Batches older than the cutoff.\n */\n async takeBefore(cutoff: number): Promise<LogBatch[]> {\n const store = await this.store(\"readonly\");\n const range = IDBKeyRange.upperBound(cutoff, true);\n return promisify<LogBatch[]>(store.index(INDEXEDDB_CREATED_AT_INDEX).getAll(range));\n }\n\n /**\n * Deletes one batch. An id that is not stored resolves without error.\n * @param id Batch identifier.\n */\n async delete(id: string): Promise<void> {\n const store = await this.store(\"readwrite\");\n await promisify(store.delete(id));\n }\n\n /**\n * Deletes several batches in one transaction. A partial failure deletes none of\n * them.\n * @param ids Batch identifiers.\n */\n async deleteMany(ids: string[]): Promise<void> {\n const store = await this.store(\"readwrite\");\n await Promise.all(ids.map((id) => promisify(store.delete(id))));\n }\n\n /**\n * Sets the attempt count of a stored batch. It ignores an id that is not stored.\n * A batch that the library delivered and deleted must not come back. The get and the put use one\n * transaction. With two transactions, a prune in another window can delete the batch\n * between them. The put then restores it.\n * @param id Batch identifier.\n * @param attempts New absolute attempt count.\n */\n async bumpAttempts(id: string, attempts: number): Promise<void> {\n const store = await this.store(\"readwrite\");\n const batch = await promisify<LogBatch | undefined>(store.get(id));\n if (batch === undefined) {\n return;\n }\n\n await promisify(store.put({ ...batch, attempts }));\n }\n\n /**\n * Counts the stored batches.\n * @returns Total batch count.\n */\n async count(): Promise<number> {\n const store = await this.store(\"readonly\");\n return promisify<number>(store.count());\n }\n\n /** This method deletes all stored batches. */\n async clear(): Promise<void> {\n const store = await this.store(\"readwrite\");\n await promisify(store.clear());\n }\n\n /**\n * Opens the connection. A host that defines indexedDB but rejects open() fails\n * here. The factory can then select a different adapter.\n */\n async ready(): Promise<void> {\n await this.open();\n }\n\n /** This method closes the connection when a connection exists. */\n async close(): Promise<void> {\n const connection = this.connection;\n if (connection === null) {\n return;\n }\n\n this.connection = null;\n const db = await connection;\n db.close();\n }\n\n /**\n * Opens the batch store in a new transaction. A transaction is valid only until\n * control returns to the event loop. Each call takes a new transaction.\n * @param mode Transaction mode.\n * @returns The batch object store.\n */\n private async store(mode: IDBTransactionMode): Promise<IDBObjectStore> {\n const db = await this.open();\n return db.transaction(INDEXEDDB_STORE_NAME, mode).objectStore(INDEXEDDB_STORE_NAME);\n }\n\n /**\n * Opens the database one time. It gives the same connection to each later call.\n * It does not keep a failed open. The next call then opens again.\n * @returns The open database.\n */\n private open(): Promise<IDBDatabase> {\n const existing = this.connection;\n if (existing !== null) {\n return existing;\n }\n\n const opening = new Promise<IDBDatabase>((resolve, reject) => {\n const request = indexedDB.open(this.name, INDEXEDDB_SCHEMA_VERSION);\n let abandoned = false;\n\n request.onupgradeneeded = () => {\n const db = request.result;\n // A database from an earlier release already contains the store. A second create\n // throws ConstraintError and aborts the upgrade.\n if (!db.objectStoreNames.contains(INDEXEDDB_STORE_NAME)) {\n const store = db.createObjectStore(INDEXEDDB_STORE_NAME, { keyPath: \"id\" });\n store.createIndex(INDEXEDDB_CREATED_AT_INDEX, INDEXEDDB_CREATED_AT_INDEX);\n }\n // IndexedDB supplies the versionchange transaction during upgradeneeded.\n // eslint-disable-next-line @typescript-eslint/non-nullable-type-assertion-style\n const transaction = request.transaction as IDBTransaction;\n const store = transaction.objectStore(INDEXEDDB_STORE_NAME);\n if (!store.indexNames.contains(\"routingContext\"))\n store.createIndex(\"routingContext\", [\"routingContextId\", \"createdAt\"]);\n };\n\n request.onsuccess = () => {\n const db = request.result;\n\n if (abandoned) {\n // The blocked handler already rejected. No reference to this connection remains.\n // An open connection blocks the next upgrade.\n db.close();\n return;\n }\n\n // Another window upgrades the schema. That upgrade blocks until this\n // connection closes.\n db.onversionchange = () => {\n db.close();\n this.connection = null;\n };\n resolve(db);\n };\n request.onerror = () => {\n reject(failureOf(request));\n };\n request.onblocked = () => {\n // An older window holds the previous schema version. This open does not settle\n // until that window closes. Each storage call waits for it.\n abandoned = true;\n reject(new Error(\"Another connection blocks the IndexedDB upgrade.\"));\n };\n });\n\n this.connection = opening.catch((error: unknown) => {\n this.connection = null;\n throw error;\n });\n\n return this.connection;\n }\n}\n","// src/storage/indexeddb-storage.ts\n//\n// This module stores batches in IndexedDB. It indexes them by creation time.\n\nimport { QUOTA_EVICTION_DIVISOR, QUOTA_EXCEEDED_ERROR, STORAGE_NAME_INDEXEDDB } from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport { countRecords, type LogBatch } from \"../models/batch\";\nimport type { GapReporter, PruneResult, StorageAdapter, StorageLimits } from \"../models/storage\";\nimport { EvictionPick, hasAction } from \"./eviction\";\nimport { addDrop, reportEviction } from \"./gap\";\nimport { IdbDriver } from \"./idb-driver\";\n\n/** This StorageAdapter keeps batches in IndexedDB. */\nexport class IndexedDbStorage implements StorageAdapter {\n /** This field holds the storage strategy name. */\n readonly name = STORAGE_NAME_INDEXEDDB;\n\n /** This driver holds the IndexedDB code for the batch store. */\n private readonly db: IdbDriver;\n\n /**\n * @param dbName Database name.\n * @param limits Storage capacity and retention thresholds.\n * @param diagnostics Diagnostics reporter.\n * @param onGap Optional callback for dropped record reporting.\n */\n constructor(\n dbName: string,\n private readonly limits: StorageLimits,\n private readonly diagnostics: Diagnostics,\n private readonly onGap?: GapReporter,\n ) {\n this.db = new IdbDriver(dbName);\n }\n\n /**\n * Opens the database. It has no guard. The factory needs the rejection to\n * select the next adapter.\n */\n async open(): Promise<void> {\n await this.db.ready();\n }\n\n /**\n * Writes a batch to IndexedDB. It then prunes the storage.\n * @param batch Batch to store.\n */\n async save(batch: LogBatch): Promise<void> {\n try {\n await this.db.put(batch);\n await this.prune();\n } catch (error) {\n if (error instanceof Error && error.name === QUOTA_EXCEEDED_ERROR) {\n this.diagnostics.report(\n \"storage.quota_exceeded\",\n \"IndexedDB is full. The library removes the oldest batches.\",\n );\n const evicted = await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not remove old batches after a full disk.\",\n () => this.evictOldest(Math.ceil(this.limits.maxBatches / QUOTA_EVICTION_DIVISOR)),\n );\n if (evicted) {\n const records = countRecords(evicted);\n const gap: PruneResult = { batches: evicted.length, records, reason: \"quota\" };\n reportEviction(this.diagnostics, this.onGap, gap, evicted);\n }\n\n // The eviction makes room for this batch. Without a second write, save() resolves.\n // The library then loses the batch. No counter shows the loss.\n const stored = await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not write the batch after it removed old batches.\",\n async () => {\n await this.db.put(batch);\n return true;\n },\n );\n if (stored !== true) {\n const gap: PruneResult = { batches: 1, records: batch.records.length, reason: \"quota\" };\n reportEviction(this.diagnostics, this.onGap, gap, [batch]);\n }\n return;\n }\n\n this.diagnostics.report(\n \"storage.degraded\",\n \"The library could not store a batch.\",\n { batchId: batch.id },\n error,\n );\n // The diagnostic above names the failure. A storage.evicted report counts it two times.\n this.onGap?.({ batches: 1, records: batch.records.length, reason: \"not_stored\" }, [batch]);\n }\n }\n\n /**\n * Reads batches of one context in creation order without removing them.\n * @param id Delivery context id.\n * @param limit Maximum batches to return.\n * @returns Batches of this context, oldest first.\n */\n async takeContext(id: string, limit: number): Promise<LogBatch[]> {\n return (\n (await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"Could not query the context partition.\",\n () => this.db.takeContext(id, Math.min(limit, 0xffffffff)),\n )) ?? []\n );\n }\n\n /**\n * Counts stored batches of one context.\n * @param id Delivery context id.\n * @returns Number of batches in this context.\n */\n async countContext(id: string): Promise<number> {\n return (\n (await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"Could not count the context partition.\",\n () => this.db.countContext(id),\n )) ?? 0\n );\n }\n\n /**\n * Reads up to `limit` batches in FIFO order. It does not delete them.\n * @param limit Maximum number of batches to retrieve.\n * @returns Array of retrieved batches.\n */\n async take(limit: number): Promise<LogBatch[]> {\n const batches = await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not read the stored batches.\",\n // getAll() takes an unsigned 32-bit count. A larger count throws. Then the read gives nothing.\n () => this.db.takeOldest(Math.min(limit, 0xffffffff)),\n );\n return batches ?? [];\n }\n\n /**\n * Deletes the batch with the given ID from IndexedDB.\n * @param id Batch identifier to delete.\n */\n async remove(id: string): Promise<void> {\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not delete a batch.\",\n () => this.db.delete(id),\n );\n }\n\n /**\n * Sets the delivery attempt count of a stored batch.\n * @param id Batch identifier.\n * @param attempts New absolute attempt count.\n */\n async bumpAttempts(id: string, attempts: number): Promise<void> {\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not update the attempt count.\",\n () => this.db.bumpAttempts(id, attempts),\n );\n }\n\n /**\n * Removes expired batches. It then removes the oldest batches above the\n * capacity limit.\n * @returns Prune summary metrics.\n */\n async prune(): Promise<PruneResult> {\n const result: PruneResult = { batches: 0, records: 0, reason: \"expired\" };\n\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not prune the stored batches.\",\n async () => {\n const cutoff = Date.now() - this.limits.maxAgeMs;\n const expired = await this.db.takeBefore(cutoff);\n if (expired.length > 0) {\n await this.db.deleteMany(expired.map((batch) => batch.id));\n this.addGap(result, \"expired\", expired);\n }\n\n const total = await this.db.count();\n if (total > this.limits.maxBatches) {\n const evicted = await this.evictOldest(total - this.limits.maxBatches);\n this.addGap(result, \"over_capacity\", evicted);\n }\n },\n );\n\n return result;\n }\n\n /**\n * Returns the number of stored batches.\n * @returns Total batch count or 0 on failure.\n */\n async count(): Promise<number> {\n const total = await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not count the stored batches.\",\n () => this.db.count(),\n );\n return total ?? 0;\n }\n\n /** This method deletes all stored batches from the database. */\n async clear(): Promise<void> {\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not clear the stored batches.\",\n () => this.db.clear(),\n );\n }\n\n /** This method closes the active IndexedDB connection. */\n async close(): Promise<void> {\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not close the database.\",\n () => this.db.close(),\n );\n }\n\n /**\n * Adds dropped batches to the prune result. It reports them with their own reason.\n * @param result Prune result of all rules.\n * @param reason Rule that dropped the batches.\n * @param dropped The dropped batches.\n */\n private addGap(result: PruneResult, reason: PruneResult[\"reason\"], dropped: LogBatch[]): void {\n const gap = addDrop(result, reason, dropped.length, countRecords(dropped));\n reportEviction(this.diagnostics, this.onGap, gap, dropped);\n }\n\n /**\n * Deletes the given number of stored batches. Batches without an action go first, oldest\n * first. An action is an audit fact. It has no guard. Both callers guard it. A guard here\n * hides the failure and reports an eviction that did not occur.\n * @param howMany Number of batches to evict.\n * @returns The evicted batches.\n */\n private async evictOldest(howMany: number): Promise<LogBatch[]> {\n // Only the records tell if a batch holds an action. The walk stops at enough plain batches.\n const pick = new EvictionPick(howMany, hasAction);\n await this.db.walkOldest((batch) => pick.add(batch));\n\n const doomed = pick.picked();\n await this.db.deleteMany(doomed.map((batch) => batch.id));\n\n return doomed;\n }\n}\n"],"mappings":"kHAqBA,SAASU,EAAU,EAA4B,CAC7C,OAAOC,EAAQ,OAAa,MAAM,+BAA+B,CACnE,CASA,SAASC,EAAa,EAAiC,CACrD,OAAO,IAAI,SAAY,EAAS,IAAW,CACzC,EAAQ,cAAkB,CACxBC,EAAQF,EAAQ,MAAW,CAC7B,EACA,EAAQ,YAAgB,CACtBG,EAAOJ,EAAUC,CAAO,CAAC,CAC3B,CACF,CAAC,CACH,CAGA,IAAaI,EAAb,KAAuB,CAOQ,KAL7B,WAAkD,KAKlD,YAAY,EAA+B,CAAd,KAAA,KAAAC,CAAe,CAM5C,MAAM,IAAI,EAAgC,CAExC,MAAMJ,GAAU,MADI,KAAK,MAAM,WAAW,EAAA,CACpB,IAAIK,CAAK,CAAC,CAClC,CAQA,MAAM,YAAY,EAAY,EAAoC,CAChE,IAAMC,EAAQ,MAAM,KAAK,MAAM,UAAU,EACnCC,EAAQ,YAAY,MAAM,CAACC,EAAI,CAAC,EAAG,CAACA,SAA2B,CAAC,EACtE,OAAOR,EAAsBM,EAAM,MAAM,gBAAgB,CAAC,CAAC,OAAOC,EAAOE,CAAK,CAAC,CACjF,CAOA,MAAM,aAAa,EAA6B,CAE9C,OAAOT,GACL,MAFkB,KAAK,MAAM,UAAU,EAAA,CAGpC,MAAM,gBAAgB,CA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AK,GAAU1B,EAAM,EAAE,CAAC,EACzD,KAAK,OAAOyB,EAAQ,UAAWC,CAAO,GAGxC,IAAMC,EAAQ,MAAM,KAAK,GAAG,MAAM,EAClC,GAAIA,EAAQ,KAAK,OAAO,WAAY,CAClC,IAAMN,EAAU,MAAM,KAAK,YAAYM,EAAQ,KAAK,OAAO,UAAU,EACrE,KAAK,OAAOF,EAAQ,gBAAiBJ,CAAO,CAC9C,CACF,CACF,EAEOI,CACT,CAMA,MAAM,OAAyB,CAM7B,OAAO,MALa,KAAK,YAAY,WACnC,mBACA,sDACM,KAAK,GAAG,MAAM,CACtB,GACgB,CAClB,CAGA,MAAM,OAAuB,CAC3B,MAAM,KAAK,YAAY,WACrB,mBACA,sDACM,KAAK,GAAG,MAAM,CACtB,CACF,CAGA,MAAM,OAAuB,CAC3B,MAAM,KAAK,YAAY,WACrB,mBACA,gDACM,KAAK,GAAG,MAAM,CACtB,CACF,CAQA,OAAe,EAAqB,EAA+B,EAA2B,CAC5F,IAAMF,EAAMpC,EAAAA,EAAQsC,EAAQG,EAAQC,EAAQ,OAAQ3C,EAAAA,EAAa2C,CAAO,CAAC,EACzErC,EAAA,EAAe,KAAK,YAAa,KAAK,MAAO+B,EAAKM,CAAO,CAC3D,CASA,MAAc,YAAY,EAAsC,CAE9D,IAAMC,EAAO,IAAI1C,EAAAA,EAAa2C,EAAS1C,EAAAA,CAAS,EAChD,MAAM,KAAK,GAAG,WAAY,GAAUyC,EAAK,IAAI9B,CAAK,CAAC,EAEnD,IAAMgC,EAASF,EAAK,OAAO,EAG3B,OAFA,MAAM,KAAK,GAAG,WAAWE,EAAO,IAAK,GAAUhC,EAAM,EAAE,CAAC,EAEjDgC,CACT,CACF"}
|
|
1
|
+
{"version":3,"file":"indexeddb-storage-CIoW21Xd.cjs","names":["INDEXEDDB_CREATED_AT_INDEX","INDEXEDDB_STORE_NAME","STORAGE_NAME_INDEXEDDB","countRecords","addDrop","EvictionPick","hasAction","require_constants","require_batch","require_factory","failureOf","request","promisify","resolve","reject","IdbDriver","name","batch","store","range","id","limit","cursor","visit","cutoff","ids","connection","mode","existing","opening","abandoned","db","error","IndexedDbStorage","limits","diagnostics","onGap","dbName","evicted","records","gap","attempts","result","expired","total","reason","dropped","pick","howMany","doomed"],"sources":["../src/storage/idb-driver.ts","../src/storage/indexeddb-storage.ts"],"sourcesContent":["// src/storage/idb-driver.ts\n//\n// This module holds the raw IndexedDB code for the batch store. It opens the database, wraps\n// requests in promises and reads in createdAt order. Code above this file uses only batches\n// and ids.\n\nimport {\n INDEXEDDB_CREATED_AT_INDEX,\n INDEXEDDB_SCHEMA_VERSION,\n INDEXEDDB_STORE_NAME,\n} from \"../constants\";\nimport type { LogBatch } from \"../models/batch\";\n\n/**\n * Returns the failure of a request that fired onerror. Some hosts report no\n * error on the request. The function then returns a replacement Error. A rejection with null\n * makes the instanceof Error test in save() false. save() then reports a full disk as an\n * ordinary write failure.\n * @param request Request that fired onerror.\n * @returns The failure that stopped it.\n */\nfunction failureOf(request: IDBRequest): Error {\n return request.error ?? new Error(\"The IndexedDB request failed.\");\n}\n\n/**\n * Resolves when an IndexedDB request succeeds. It rejects with the request\n * error. It reads the request as IDBRequest<any>. Each caller must name the type that it\n * expects.\n * @param request Request to await.\n * @returns The request result.\n */\nfunction promisify<T>(request: IDBRequest): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n request.onsuccess = () => {\n resolve(request.result as T);\n };\n request.onerror = () => {\n reject(failureOf(request));\n };\n });\n}\n\n/** This class wraps one IndexedDB database that holds undelivered batches by id. */\nexport class IdbDriver {\n /** This field holds the pending or completed open. The driver reuses it for one database. */\n private connection: Promise<IDBDatabase> | null = null;\n\n /**\n * @param name IndexedDB database name.\n */\n constructor(private readonly name: string) {}\n\n /**\n * Writes a batch. It replaces a stored batch with the same id.\n * @param batch Batch to persist.\n */\n async put(batch: LogBatch): Promise<void> {\n const store = await this.store(\"readwrite\");\n await promisify(store.put(batch));\n }\n\n /**\n * Reads batches of one context in creation order without removing them.\n * @param id Delivery context id.\n * @param limit Maximum batches to return.\n * @returns Batches of this context, oldest first.\n */\n async takeContext(id: string, limit: number): Promise<LogBatch[]> {\n const store = await this.store(\"readonly\");\n const range = IDBKeyRange.bound([id, 0], [id, Number.MAX_SAFE_INTEGER]);\n return promisify<LogBatch[]>(store.index(\"routingContext\").getAll(range, limit));\n }\n\n /**\n * Counts stored batches of one context.\n * @param id Delivery context id.\n * @returns Number of batches in this context.\n */\n async countContext(id: string): Promise<number> {\n const store = await this.store(\"readonly\");\n return promisify<number>(\n store\n .index(\"routingContext\")\n .count(IDBKeyRange.bound([id, 0], [id, Number.MAX_SAFE_INTEGER])),\n );\n }\n\n /**\n * Reads the oldest batches by createdAt. It does not remove them.\n * @param limit Maximum number of batches to return.\n * @returns Batches in ascending createdAt order.\n */\n async takeOldest(limit: number): Promise<LogBatch[]> {\n const store = await this.store(\"readonly\");\n return promisify<LogBatch[]>(store.index(INDEXEDDB_CREATED_AT_INDEX).getAll(null, limit));\n }\n\n /**\n * Walks the batches by createdAt, oldest first. It does not remove them. A cursor reads one\n * batch at a time. The walk can then stop before it reads the full store.\n * @param visit Receives each batch. It returns false to stop the walk.\n */\n async walkOldest(visit: (batch: LogBatch) => boolean): Promise<void> {\n const store = await this.store(\"readonly\");\n const request = store.index(INDEXEDDB_CREATED_AT_INDEX).openCursor();\n\n await new Promise<void>((resolve, reject) => {\n request.onsuccess = () => {\n const cursor = request.result;\n if (cursor === null || !visit(cursor.value as LogBatch)) {\n resolve();\n return;\n }\n cursor.continue();\n };\n request.onerror = () => {\n reject(failureOf(request));\n };\n });\n }\n\n /**\n * Reads each batch with a createdAt value before the cutoff.\n * @param cutoff Exclusive upper bound in epoch milliseconds.\n * @returns Batches older than the cutoff.\n */\n async takeBefore(cutoff: number): Promise<LogBatch[]> {\n const store = await this.store(\"readonly\");\n const range = IDBKeyRange.upperBound(cutoff, true);\n return promisify<LogBatch[]>(store.index(INDEXEDDB_CREATED_AT_INDEX).getAll(range));\n }\n\n /**\n * Deletes one batch. An id that is not stored resolves without error.\n * @param id Batch identifier.\n */\n async delete(id: string): Promise<void> {\n const store = await this.store(\"readwrite\");\n await promisify(store.delete(id));\n }\n\n /**\n * Deletes several batches in one transaction. A partial failure deletes none of\n * them.\n * @param ids Batch identifiers.\n */\n async deleteMany(ids: string[]): Promise<void> {\n const store = await this.store(\"readwrite\");\n await Promise.all(ids.map((id) => promisify(store.delete(id))));\n }\n\n /**\n * Sets the attempt count of a stored batch. It ignores an id that is not stored.\n * A batch that the library delivered and deleted must not come back. The get and the put use one\n * transaction. With two transactions, a prune in another window can delete the batch\n * between them. The put then restores it.\n * @param id Batch identifier.\n * @param attempts New absolute attempt count.\n */\n async bumpAttempts(id: string, attempts: number): Promise<void> {\n const store = await this.store(\"readwrite\");\n const batch = await promisify<LogBatch | undefined>(store.get(id));\n if (batch === undefined) {\n return;\n }\n\n await promisify(store.put({ ...batch, attempts }));\n }\n\n /**\n * Counts the stored batches.\n * @returns Total batch count.\n */\n async count(): Promise<number> {\n const store = await this.store(\"readonly\");\n return promisify<number>(store.count());\n }\n\n /** This method deletes all stored batches. */\n async clear(): Promise<void> {\n const store = await this.store(\"readwrite\");\n await promisify(store.clear());\n }\n\n /**\n * Opens the connection. A host that defines indexedDB but rejects open() fails\n * here. The factory can then select a different adapter.\n */\n async ready(): Promise<void> {\n await this.open();\n }\n\n /** This method closes the connection when a connection exists. */\n async close(): Promise<void> {\n const connection = this.connection;\n if (connection === null) {\n return;\n }\n\n this.connection = null;\n const db = await connection;\n db.close();\n }\n\n /**\n * Opens the batch store in a new transaction. A transaction is valid only until\n * control returns to the event loop. Each call takes a new transaction.\n * @param mode Transaction mode.\n * @returns The batch object store.\n */\n private async store(mode: IDBTransactionMode): Promise<IDBObjectStore> {\n const db = await this.open();\n return db.transaction(INDEXEDDB_STORE_NAME, mode).objectStore(INDEXEDDB_STORE_NAME);\n }\n\n /**\n * Opens the database one time. It gives the same connection to each later call.\n * It does not keep a failed open. The next call then opens again.\n * @returns The open database.\n */\n private open(): Promise<IDBDatabase> {\n const existing = this.connection;\n if (existing !== null) {\n return existing;\n }\n\n const opening = new Promise<IDBDatabase>((resolve, reject) => {\n const request = indexedDB.open(this.name, INDEXEDDB_SCHEMA_VERSION);\n let abandoned = false;\n\n request.onupgradeneeded = () => {\n const db = request.result;\n // A database from an earlier release already contains the store. A second create\n // throws ConstraintError and aborts the upgrade.\n if (!db.objectStoreNames.contains(INDEXEDDB_STORE_NAME)) {\n const store = db.createObjectStore(INDEXEDDB_STORE_NAME, { keyPath: \"id\" });\n store.createIndex(INDEXEDDB_CREATED_AT_INDEX, INDEXEDDB_CREATED_AT_INDEX);\n }\n // IndexedDB supplies the versionchange transaction during upgradeneeded.\n // eslint-disable-next-line @typescript-eslint/non-nullable-type-assertion-style\n const transaction = request.transaction as IDBTransaction;\n const store = transaction.objectStore(INDEXEDDB_STORE_NAME);\n if (!store.indexNames.contains(\"routingContext\"))\n store.createIndex(\"routingContext\", [\"routingContextId\", \"createdAt\"]);\n };\n\n request.onsuccess = () => {\n const db = request.result;\n\n if (abandoned) {\n // The blocked handler already rejected. No reference to this connection remains.\n // An open connection blocks the next upgrade.\n db.close();\n return;\n }\n\n // Another window upgrades the schema. That upgrade blocks until this\n // connection closes.\n db.onversionchange = () => {\n db.close();\n this.connection = null;\n };\n resolve(db);\n };\n request.onerror = () => {\n reject(failureOf(request));\n };\n request.onblocked = () => {\n // An older window holds the previous schema version. This open does not settle\n // until that window closes. Each storage call waits for it.\n abandoned = true;\n reject(new Error(\"Another connection blocks the IndexedDB upgrade.\"));\n };\n });\n\n this.connection = opening.catch((error: unknown) => {\n this.connection = null;\n throw error;\n });\n\n return this.connection;\n }\n}\n","// src/storage/indexeddb-storage.ts\n//\n// This module stores batches in IndexedDB. It indexes them by creation time.\n\nimport { QUOTA_EVICTION_DIVISOR, QUOTA_EXCEEDED_ERROR, STORAGE_NAME_INDEXEDDB } from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport { countRecords, type LogBatch } from \"../models/batch\";\nimport type { GapReporter, PruneResult, StorageAdapter, StorageLimits } from \"../models/storage\";\nimport { EvictionPick, hasAction } from \"./eviction\";\nimport { addDrop, reportEviction } from \"./gap\";\nimport { IdbDriver } from \"./idb-driver\";\n\n/** This StorageAdapter keeps batches in IndexedDB. */\nexport class IndexedDbStorage implements StorageAdapter {\n /** This field holds the storage strategy name. */\n readonly name = STORAGE_NAME_INDEXEDDB;\n\n /** This driver holds the IndexedDB code for the batch store. */\n private readonly db: IdbDriver;\n\n /**\n * @param dbName Database name.\n * @param limits Storage capacity and retention thresholds.\n * @param diagnostics Diagnostics reporter.\n * @param onGap Optional callback for dropped record reporting.\n */\n constructor(\n dbName: string,\n private readonly limits: StorageLimits,\n private readonly diagnostics: Diagnostics,\n private readonly onGap?: GapReporter,\n ) {\n this.db = new IdbDriver(dbName);\n }\n\n /**\n * Opens the database. It has no guard. The factory needs the rejection to\n * select the next adapter.\n */\n async open(): Promise<void> {\n await this.db.ready();\n }\n\n /**\n * Writes a batch to IndexedDB. It then prunes the storage.\n * @param batch Batch to store.\n */\n async save(batch: LogBatch): Promise<void> {\n try {\n await this.db.put(batch);\n await this.prune();\n } catch (error) {\n if (error instanceof Error && error.name === QUOTA_EXCEEDED_ERROR) {\n this.diagnostics.report(\n \"storage.quota_exceeded\",\n \"IndexedDB is full. The library removes the oldest batches.\",\n );\n const evicted = await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not remove old batches after a full disk.\",\n () => this.evictOldest(Math.ceil(this.limits.maxBatches / QUOTA_EVICTION_DIVISOR)),\n );\n if (evicted) {\n const records = countRecords(evicted);\n const gap: PruneResult = { batches: evicted.length, records, reason: \"quota\" };\n reportEviction(this.diagnostics, this.onGap, gap, evicted);\n }\n\n // The eviction makes room for this batch. Without a second write, save() resolves.\n // The library then loses the batch. No counter shows the loss.\n const stored = await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not write the batch after it removed old batches.\",\n async () => {\n await this.db.put(batch);\n return true;\n },\n );\n if (stored !== true) {\n const gap: PruneResult = { batches: 1, records: batch.records.length, reason: \"quota\" };\n reportEviction(this.diagnostics, this.onGap, gap, [batch]);\n }\n return;\n }\n\n this.diagnostics.report(\n \"storage.degraded\",\n \"The library could not store a batch.\",\n { batchId: batch.id },\n error,\n );\n // The diagnostic above names the failure. A storage.evicted report counts it two times.\n this.onGap?.({ batches: 1, records: batch.records.length, reason: \"not_stored\" }, [batch]);\n }\n }\n\n /**\n * Reads batches of one context in creation order without removing them.\n * @param id Delivery context id.\n * @param limit Maximum batches to return.\n * @returns Batches of this context, oldest first.\n */\n async takeContext(id: string, limit: number): Promise<LogBatch[]> {\n return (\n (await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"Could not query the context partition.\",\n () => this.db.takeContext(id, Math.min(limit, 0xffffffff)),\n )) ?? []\n );\n }\n\n /**\n * Counts stored batches of one context.\n * @param id Delivery context id.\n * @returns Number of batches in this context.\n */\n async countContext(id: string): Promise<number> {\n return (\n (await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"Could not count the context partition.\",\n () => this.db.countContext(id),\n )) ?? 0\n );\n }\n\n /**\n * Reads up to `limit` batches in FIFO order. It does not delete them.\n * @param limit Maximum number of batches to retrieve.\n * @returns Array of retrieved batches.\n */\n async take(limit: number): Promise<LogBatch[]> {\n const batches = await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not read the stored batches.\",\n // getAll() takes an unsigned 32-bit count. A larger count throws. Then the read gives nothing.\n () => this.db.takeOldest(Math.min(limit, 0xffffffff)),\n );\n return batches ?? [];\n }\n\n /**\n * Deletes the batch with the given ID from IndexedDB.\n * @param id Batch identifier to delete.\n */\n async remove(id: string): Promise<void> {\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not delete a batch.\",\n () => this.db.delete(id),\n );\n }\n\n /**\n * Sets the delivery attempt count of a stored batch.\n * @param id Batch identifier.\n * @param attempts New absolute attempt count.\n */\n async bumpAttempts(id: string, attempts: number): Promise<void> {\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not update the attempt count.\",\n () => this.db.bumpAttempts(id, attempts),\n );\n }\n\n /**\n * Removes expired batches. It then removes the oldest batches above the\n * capacity limit.\n * @returns Prune summary metrics.\n */\n async prune(): Promise<PruneResult> {\n const result: PruneResult = { batches: 0, records: 0, reason: \"expired\" };\n\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not prune the stored batches.\",\n async () => {\n const cutoff = Date.now() - this.limits.maxAgeMs;\n const expired = await this.db.takeBefore(cutoff);\n if (expired.length > 0) {\n await this.db.deleteMany(expired.map((batch) => batch.id));\n this.addGap(result, \"expired\", expired);\n }\n\n const total = await this.db.count();\n if (total > this.limits.maxBatches) {\n const evicted = await this.evictOldest(total - this.limits.maxBatches);\n this.addGap(result, \"over_capacity\", evicted);\n }\n },\n );\n\n return result;\n }\n\n /**\n * Returns the number of stored batches.\n * @returns Total batch count or 0 on failure.\n */\n async count(): Promise<number> {\n const total = await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not count the stored batches.\",\n () => this.db.count(),\n );\n return total ?? 0;\n }\n\n /** This method deletes all stored batches from the database. */\n async clear(): Promise<void> {\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not clear the stored batches.\",\n () => this.db.clear(),\n );\n }\n\n /** This method closes the active IndexedDB connection. */\n async close(): Promise<void> {\n await this.diagnostics.guardAsync(\n \"storage.degraded\",\n \"The library could not close the database.\",\n () => this.db.close(),\n );\n }\n\n /**\n * Adds dropped batches to the prune result. It reports them with their own reason.\n * @param result Prune result of all rules.\n * @param reason Rule that dropped the batches.\n * @param dropped The dropped batches.\n */\n private addGap(result: PruneResult, reason: PruneResult[\"reason\"], dropped: LogBatch[]): void {\n const gap = addDrop(result, reason, dropped.length, countRecords(dropped));\n reportEviction(this.diagnostics, this.onGap, gap, dropped);\n }\n\n /**\n * Deletes the given number of stored batches. Batches without an action go first, oldest\n * first. An action is an audit fact. It has no guard. Both callers guard it. A guard here\n * hides the failure and reports an eviction that did not occur.\n * @param howMany Number of batches to evict.\n * @returns The evicted batches.\n */\n private async evictOldest(howMany: number): Promise<LogBatch[]> {\n // Only the records tell if a batch holds an action. The walk stops at enough plain batches.\n const pick = new EvictionPick(howMany, hasAction);\n await this.db.walkOldest((batch) => pick.add(batch));\n\n const doomed = pick.picked();\n await this.db.deleteMany(doomed.map((batch) => batch.id));\n\n return doomed;\n }\n}\n"],"mappings":"A,kHAqBA,SAASU,EAAU,EAA4B,CAC7C,OAAOC,EAAQ,OAAa,MAAM,+BAA+B,CACnE,CASA,SAASC,EAAa,EAAiC,CACrD,OAAO,IAAI,SAAY,EAAS,IAAW,CACzC,EAAQ,cAAkB,CACxBC,EAAQF,EAAQ,MAAW,CAC7B,EACA,EAAQ,YAAgB,CACtBG,EAAOJ,EAAUC,CAAO,CAAC,CAC3B,CACF,CAAC,CACH,CAGA,IAAaI,EAAb,KAAuB,CAOQ,KAL7B,WAAkD,KAKlD,YAAY,EAA+B,CAAd,KAAA,KAAAC,CAAe,CAM5C,MAAM,IAAI,EAAgC,CAExC,MAAMJ,GAAU,MADI,KAAK,MAAM,WAAW,EAAA,CACpB,IAAIK,CAAK,CAAC,CAClC,CAQA,MAAM,YAAY,EAAY,EAAoC,CAChE,IAAMC,EAAQ,MAAM,KAAK,MAAM,UAAU,EACnCC,EAAQ,YAAY,MAAM,CAACC,EAAI,CAAC,EAAG,CAACA,SAA2B,CAAC,EACtE,OAAOR,EAAsBM,EAAM,MAAM,gBAAgB,CAAC,CAAC,OAAOC,EAAOE,CAAK,CAAC,CACjF,CAOA,MAAM,aAAa,EAA6B,CAE9C,OAAOT,GACL,MAFkB,KAAK,MAAM,UAAU,EAAA,CAGpC,MAAM,gBAAgB,CAAC,CACvB,MAAM,YAAY,MAAM,CAACQ,EAAI,CAAC,EAAG,CAACA,SAA2B,CAAC,CAAC,CACpE,CACF,CAOA,MAAM,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AK,GAAG,MAAM,EAClC,GAAIA,EAAQ,KAAK,OAAO,WAAY,CAClC,IAAMN,EAAU,MAAM,KAAK,YAAYM,EAAQ,KAAK,OAAO,UAAU,EACrE,KAAK,OAAOF,EAAQ,gBAAiBJ,CAAO,CAC9C,CACF,CACF,EAEOI,CACT,CAMA,MAAM,OAAyB,CAM7B,OAAO,MALa,KAAK,YAAY,WACnC,mBACA,sDACM,KAAK,GAAG,MAAM,CACtB,GACgB,CAClB,CAGA,MAAM,OAAuB,CAC3B,MAAM,KAAK,YAAY,WACrB,mBACA,sDACM,KAAK,GAAG,MAAM,CACtB,CACF,CAGA,MAAM,OAAuB,CAC3B,MAAM,KAAK,YAAY,WACrB,mBACA,gDACM,KAAK,GAAG,MAAM,CACtB,CACF,CAQA,OAAe,EAAqB,EAA+B,EAA2B,CAC5F,IAAMF,EAAMpC,EAAAA,EAAQsC,EAAQG,EAAQC,EAAQ,OAAQ3C,EAAAA,EAAa2C,CAAO,CAAC,EACzErC,EAAA,EAAe,KAAK,YAAa,KAAK,MAAO+B,EAAKM,CAAO,CAC3D,CASA,MAAc,YAAY,EAAsC,CAE9D,IAAMC,EAAO,IAAI1C,EAAAA,EAAa2C,EAAS1C,EAAAA,CAAS,EAChD,MAAM,KAAK,GAAG,WAAY,GAAUyC,EAAK,IAAI9B,CAAK,CAAC,EAEnD,IAAMgC,EAASF,EAAK,OAAO,EAG3B,OAFA,MAAM,KAAK,GAAG,WAAWE,EAAO,IAAK,GAAUhC,EAAM,EAAE,CAAC,EAEjDgC,CACT,CACF,E"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import "./constants-
|
|
2
|
-
import {
|
|
3
|
-
import { t } from "./
|
|
4
|
-
|
|
1
|
+
import "./constants-zyrqveN4.js";
|
|
2
|
+
import { t as e } from "./patch-UdPz1ea8.js";
|
|
3
|
+
import { i as t } from "./platform-DkcuXwe-.js";
|
|
4
|
+
// src/capture/interactions.ts
|
|
5
5
|
var n = "a[target=\"_blank\"], a[download]";
|
|
6
6
|
function r(e) {
|
|
7
7
|
let t = e.tagName.toLowerCase(), n = e.getAttribute("data-testid") ?? e.getAttribute("data-test-id");
|
|
@@ -93,9 +93,9 @@ var a = class {
|
|
|
93
93
|
this.stopDeadCheck = o;
|
|
94
94
|
}
|
|
95
95
|
onNavigate = () => {
|
|
96
|
-
let
|
|
97
|
-
if (
|
|
98
|
-
let r = this.ctx.config.capture.fullUrls, { urlTransform: i } = this.ctx.config.capture, a = e
|
|
96
|
+
let e = this.lastUrl, n = location.href;
|
|
97
|
+
if (e === n || (this.lastUrl = n, this.ctx.isActive?.() === !1)) return;
|
|
98
|
+
let r = this.ctx.config.capture.fullUrls, { urlTransform: i } = this.ctx.config.capture, a = t(e, r, i, this.ctx.diagnostics), o = t(n, r, i, this.ctx.diagnostics);
|
|
99
99
|
this.ctx.tracing.rotate("navigation"), this.ctx.breadcrumbs.push({
|
|
100
100
|
t: Date.now(),
|
|
101
101
|
category: "navigation",
|
|
@@ -104,9 +104,9 @@ var a = class {
|
|
|
104
104
|
};
|
|
105
105
|
installHistory() {
|
|
106
106
|
if (typeof history > "u") return;
|
|
107
|
-
let
|
|
107
|
+
let t = i(), n = this.onNavigate, r = !0, a = e(t, "pushState", (e) => function(...t) {
|
|
108
108
|
e.apply(this, t), r && queueMicrotask(n);
|
|
109
|
-
}), o = t
|
|
109
|
+
}), o = e(t, "replaceState", (e) => function(...t) {
|
|
110
110
|
e.apply(this, t), r && queueMicrotask(n);
|
|
111
111
|
});
|
|
112
112
|
this.restores.push(() => {
|
|
@@ -114,7 +114,6 @@ var a = class {
|
|
|
114
114
|
});
|
|
115
115
|
}
|
|
116
116
|
};
|
|
117
|
-
//#endregion
|
|
118
117
|
export { a as InteractionCapture };
|
|
119
118
|
|
|
120
|
-
//# sourceMappingURL=interactions-
|
|
119
|
+
//# sourceMappingURL=interactions-DTgKy_6K.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"interactions-CqDNrtIR.js","names":["recordedUrl","LEAVING_LINKS","describeElement","tag","element","testId","label","classAttribute","historyMethods","InteractionCapture","ctx","restore","target","event","settings","options","ignore","attribute","message","data","now","windowMs","count","times","t","reported","reached","action","href","responded","respond","observer","stop","timer","from","to","full","fromUrl","urlTransform","toUrl","onNavigate","active","restorePushState","patch","args","original","restoreReplaceState"],"sources":["../src/capture/interactions.ts"],"sourcesContent":["// src/capture/interactions.ts\n//\n// Captures clicks and in-page navigations as breadcrumbs and trace boundaries. It also finds\n// rage clicks and dead clicks.\n\nimport {\n ACTION_ATTRIBUTE_DEFAULT,\n ARIA_LABEL_MAX_CHARS,\n CLICK_TEXT_MAX_CHARS,\n DEAD_CLICK_CONTROLS,\n DEAD_CLICK_MS,\n RAGE_CLICK_COUNT,\n RAGE_CLICK_WINDOW_MS,\n SELECTOR_MAX_CLASSES,\n} from \"../constants\";\nimport type { InteractionOptions } from \"../models/config\";\nimport { patch } from \"../utils/patch\";\nimport { recordedUrl } from \"../utils/platform\";\nimport type { Capture, CaptureContext } from \"./types\";\n\n/** Links that open elsewhere. The page gives no visible response, and the click is not dead. */\nconst LEAVING_LINKS = 'a[target=\"_blank\"], a[download]';\n\n/**\n * Generates a short CSS selector for an element. The order of preference is test ID, ID,\n * aria-label, then class names.\n * @param element Target DOM element.\n * @returns Generated CSS selector string.\n */\nfunction describeElement(element: Element): string {\n const tag = element.tagName.toLowerCase();\n\n const testId = element.getAttribute(\"data-testid\") ?? element.getAttribute(\"data-test-id\");\n if (testId !== null) {\n return `[data-testid=\"${testId}\"]`;\n }\n if (element.id !== \"\") {\n return `#${element.id}`;\n }\n\n const label = element.getAttribute(\"aria-label\");\n if (label !== null) {\n return `${tag}[aria-label=\"${label.slice(0, ARIA_LABEL_MAX_CHARS)}\"]`;\n }\n\n // Read the class through getAttribute. On an SVG element, `className` is an\n // SVGAnimatedString, and a slice of it throws.\n const classAttribute = element.getAttribute(\"class\")?.trim() ?? \"\";\n if (classAttribute === \"\") {\n return tag;\n }\n\n const classes = classAttribute.split(/\\s+/).slice(0, SELECTOR_MAX_CLASSES).join(\".\");\n return `${tag}.${classes}`;\n}\n\n/**\n * The two History members that this module replaces. The type declares them as\n * properties, not methods, to keep the original functions unbound. With a bound\n * copy, uninstall restores a different function than the one it replaced.\n * Each install cycle also adds one more bind over the previous bind.\n */\ninterface HistoryMethods {\n pushState: (this: History, ...args: never[]) => void;\n replaceState: (this: History, ...args: never[]) => void;\n}\n\n/**\n * Returns the History object with a type that holds its methods unbound.\n * @returns The global history.\n */\nfunction historyMethods(): HistoryMethods {\n return history;\n}\n\n/** Captures user click interactions and single-page navigation transitions. */\nexport class InteractionCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"interactions\";\n\n /** Prevents duplicate listener registration. */\n private installed = false;\n\n /** Restore functions of the history wrappers. */\n private readonly restores: (() => void)[] = [];\n\n /** Tracked URL prior to the latest navigation event. */\n private lastUrl = \"\";\n\n /** Element of the current click burst, and the times of its clicks. */\n private burst: { target: Element | null; times: number[]; reported: boolean } = {\n target: null,\n times: [],\n reported: false,\n };\n\n /** Stops the dead click check that runs now. */\n private stopDeadCheck: (() => void) | undefined;\n\n /**\n * @param ctx Capture context containing configuration, diagnostics, logger, breadcrumbs, and tracing.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Registers click listeners and patches history navigation APIs. */\n install(): void {\n if (this.installed || typeof document === \"undefined\") {\n return;\n }\n this.installed = true;\n this.lastUrl = location.href;\n\n if (this.ctx.config.capture.interactions) {\n // The capture phase sees a click before a page handler can stop propagation.\n addEventListener(\"click\", this.onClick, true);\n }\n if (this.ctx.config.capture.navigation) {\n this.installHistory();\n addEventListener(\"popstate\", this.onNavigate);\n addEventListener(\"hashchange\", this.onNavigate);\n }\n }\n\n /**\n * Removes interaction listeners and restores each history method that still holds the\n * wrapper. A wrapper that another script wrapped again stays in place and records nothing.\n */\n uninstall(): void {\n if (!this.installed) {\n return;\n }\n this.installed = false;\n\n removeEventListener(\"click\", this.onClick, true);\n removeEventListener(\"popstate\", this.onNavigate);\n removeEventListener(\"hashchange\", this.onNavigate);\n\n for (const restore of this.restores.splice(0)) {\n restore();\n }\n\n this.stopDeadCheck?.();\n this.burst = { target: null, times: [], reported: false };\n }\n\n /** Rotates trace context and records a click breadcrumb. */\n private readonly onClick = (event: Event): void => {\n if (this.ctx.isActive?.() === false) return;\n const target = event.target;\n if (!(target instanceof Element)) return;\n const settings = this.ctx.config.capture.interactions;\n const options = typeof settings === \"object\" ? settings : {};\n const ignore =\n options.ignoreSelector === undefined ? \"[data-observability-ignore]\" : options.ignoreSelector;\n if (ignore && target.closest(ignore)) return;\n // An absent or empty attribute gives \"\". The message is then \"unknown-click\".\n const attribute = options.actionAttribute ?? ACTION_ATTRIBUTE_DEFAULT;\n const action = target.closest(`[${attribute}]`)?.getAttribute(attribute) ?? \"\";\n const message = (action || \"unknown-click\").slice(0, this.ctx.config.limits.maxBodyChars);\n const data: Record<string, unknown> = {};\n if (options.selector) data.selector = describeElement(target);\n if (options.text)\n data.text = target.textContent.trim().slice(0, options.maxTextChars ?? CLICK_TEXT_MAX_CHARS);\n this.ctx.tracing.rotate(\"interaction\");\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"click\",\n message,\n data: Object.keys(data).length > 0 ? data : undefined,\n });\n\n if (options.rageClicks) {\n this.countRage(target, message, options);\n }\n if (\n options.deadClicks &&\n target.closest(`${DEAD_CLICK_CONTROLS}, [${attribute}]`) &&\n !target.closest(LEAVING_LINKS)\n ) {\n this.watchDead(message, options);\n }\n };\n\n /**\n * Counts the clicks on one element. It records `ui.rage_click` one time in each burst.\n * @param target Clicked element.\n * @param action Action name of the click.\n * @param options Interaction options.\n */\n private countRage(target: Element, action: string, options: InteractionOptions): void {\n const now = Date.now();\n const windowMs = options.rageClickWindowMs ?? RAGE_CLICK_WINDOW_MS;\n const count = options.rageClickCount ?? RAGE_CLICK_COUNT;\n const times =\n this.burst.target === target ? this.burst.times.filter((t) => now - t < windowMs) : [];\n // A burst ends when no click stays in the window. Clicks that slide through it give no event.\n const reported = times.length > 0 && this.burst.reported;\n times.push(now);\n const reached = times.length >= count;\n this.burst = { target, times, reported: reported || reached };\n\n if (reached && !reported) {\n this.ctx.logger.logEvent(\"ui.rage_click\", { \"click.action\": action, \"click.count\": count });\n }\n }\n\n /**\n * Watches the page after a click on a control. With no DOM change, no navigation and no scroll\n * in `deadClickMs`, it records `ui.dead_click`. One check runs at a time.\n * @param action Action name of the click.\n * @param options Interaction options.\n */\n private watchDead(action: string, options: InteractionOptions): void {\n if (this.stopDeadCheck || typeof MutationObserver === \"undefined\") {\n return;\n }\n\n const href = location.href;\n let responded = false;\n const respond = (): void => {\n responded = true;\n };\n const observer = new MutationObserver(respond);\n observer.observe(document, {\n subtree: true,\n childList: true,\n attributes: true,\n characterData: true,\n });\n addEventListener(\"scroll\", respond, { capture: true, passive: true });\n\n const stop = (): void => {\n // stop reads timer, which the code declares after stop. stop runs only after that line.\n clearTimeout(timer);\n observer.disconnect();\n removeEventListener(\"scroll\", respond, true);\n this.stopDeadCheck = undefined;\n };\n const timer = setTimeout(() => {\n stop();\n if (!responded && location.href === href && this.ctx.isActive?.() !== false) {\n this.ctx.logger.logEvent(\"ui.dead_click\", { \"click.action\": action });\n }\n }, options.deadClickMs ?? DEAD_CLICK_MS);\n this.stopDeadCheck = stop;\n }\n\n /** On a URL change, rotates the trace context. It also records a breadcrumb and an event. */\n private readonly onNavigate = (): void => {\n const from = this.lastUrl;\n const to = location.href;\n if (from === to) {\n return;\n }\n this.lastUrl = to;\n if (this.ctx.isActive?.() === false) return;\n\n // The comparison above uses the full URL. A change to the query only is a navigation.\n // The record does not keep the query unless you set fullUrls.\n const full = this.ctx.config.capture.fullUrls;\n const { urlTransform } = this.ctx.config.capture;\n const fromUrl = recordedUrl(from, full, urlTransform, this.ctx.diagnostics);\n const toUrl = recordedUrl(to, full, urlTransform, this.ctx.diagnostics);\n\n this.ctx.tracing.rotate(\"navigation\");\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"navigation\",\n message: `${fromUrl} -> ${toUrl}`,\n });\n\n // The event carries only the previous URL. The record builder adds the current URL as\n // `page.url`. A new URL in `url.full` makes a navigation look like an HTTP request.\n this.ctx.logger.logEvent(\"NAVIGATION\", { \"page.url.previous\": fromUrl });\n };\n\n /** Patches History.pushState and replaceState to observe programmatic navigations. */\n private installHistory(): void {\n if (typeof history === \"undefined\") {\n return;\n }\n\n // Wrap the instance, not History.prototype. A read from the prototype skips a patch\n // that a router installed on the instance. patch keeps the originals unbound.\n const target = historyMethods();\n const onNavigate = this.onNavigate;\n // Uninstall clears the flag. A wrapper that stays in place then only calls the original.\n let active = true;\n\n const restorePushState = patch(\n target,\n \"pushState\",\n (original) =>\n function (this: History, ...args: never[]): void {\n original.apply(this, args);\n // Queue the handler. The browser updates location.href after the call returns.\n // A synchronous read gives the previous URL as the new URL.\n if (active) {\n queueMicrotask(onNavigate);\n }\n },\n );\n\n const restoreReplaceState = patch(\n target,\n \"replaceState\",\n (original) =>\n function (this: History, ...args: never[]): void {\n original.apply(this, args);\n if (active) {\n queueMicrotask(onNavigate);\n }\n },\n );\n\n this.restores.push(() => {\n active = false;\n restorePushState();\n restoreReplaceState();\n });\n }\n}\n"],"mappings":";;;;AAqBA,IAAMC,IAAgB;AAQtB,SAASC,EAAgB,GAA0B;CACjD,IAAMC,IAAMC,EAAQ,QAAQ,YAAY,GAElCC,IAASD,EAAQ,aAAa,aAAa,KAAKA,EAAQ,aAAa,cAAc;CACzF,IAAIC,MAAW,MACb,OAAO,iBAAiBA,EAAO;CAEjC,IAAID,EAAQ,OAAO,IACjB,OAAO,IAAIA,EAAQ;CAGrB,IAAME,IAAQF,EAAQ,aAAa,YAAY;CAC/C,IAAIE,MAAU,MACZ,OAAO,GAAGH,EAAI,eAAeG,EAAM,MAAM,GAAA,EAAuB,EAAE;CAKpE,IAAMC,IAAiBH,EAAQ,aAAa,OAAO,CAAC,EAAE,KAAK,KAAK;CAMhE,OALIG,MAAmB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GD,EAAQ,MAAME;EAC5B,CAAC,GAID,KAAK,IAAI,OAAO,SAAS,cAAc,EAAE,qBAAqBF,EAAQ,CAAC;CACzE;CAGA,iBAA+B;EAC7B,IAAI,OAAO,UAAY,KACrB;EAKF,IAAMzB,IAASJ,EAAe,GACxBgC,IAAa,KAAK,YAEpBC,IAAS,IAEPC,IAAmBC,EACvB/B,GACA,cACC,MACC,SAAyB,GAAGgC,GAAqB;GAI/C,AAHAC,EAAS,MAAM,MAAMD,CAAI,GAGrBH,KACF,eAAeD,CAAU;EAE7B,CACJ,GAEMM,IAAsBH,EAC1B/B,GACA,iBACC,MACC,SAAyB,GAAGgC,GAAqB;GAE/C,AADAC,EAAS,MAAM,MAAMD,CAAI,GACrBH,KACF,eAAeD,CAAU;EAE7B,CACJ;EAEA,KAAK,SAAS,WAAW;GAGvB,AAFA,IAAS,IACTE,EAAiB,GACjBI,EAAoB;EACtB,CAAC;CACH;AACF"}
|
|
1
|
+
{"version":3,"file":"interactions-DTgKy_6K.js","names":["patch","recordedUrl","LEAVING_LINKS","describeElement","tag","element","testId","label","classAttribute","historyMethods","InteractionCapture","ctx","restore","target","event","settings","options","ignore","attribute","message","data","now","windowMs","count","times","t","reported","reached","action","href","responded","respond","observer","stop","timer","from","to","full","fromUrl","urlTransform","toUrl","onNavigate","active","restorePushState","args","original","restoreReplaceState"],"sources":["../src/capture/interactions.ts"],"sourcesContent":["// src/capture/interactions.ts\n//\n// Captures clicks and in-page navigations as breadcrumbs and trace boundaries. It also finds\n// rage clicks and dead clicks.\n\nimport {\n ACTION_ATTRIBUTE_DEFAULT,\n ARIA_LABEL_MAX_CHARS,\n CLICK_TEXT_MAX_CHARS,\n DEAD_CLICK_CONTROLS,\n DEAD_CLICK_MS,\n RAGE_CLICK_COUNT,\n RAGE_CLICK_WINDOW_MS,\n SELECTOR_MAX_CLASSES,\n} from \"../constants\";\nimport type { InteractionOptions } from \"../models/config\";\nimport { patch } from \"../utils/patch\";\nimport { recordedUrl } from \"../utils/platform\";\nimport type { Capture, CaptureContext } from \"./types\";\n\n/** Links that open elsewhere. The page gives no visible response, and the click is not dead. */\nconst LEAVING_LINKS = 'a[target=\"_blank\"], a[download]';\n\n/**\n * Generates a short CSS selector for an element. The order of preference is test ID, ID,\n * aria-label, then class names.\n * @param element Target DOM element.\n * @returns Generated CSS selector string.\n */\nfunction describeElement(element: Element): string {\n const tag = element.tagName.toLowerCase();\n\n const testId = element.getAttribute(\"data-testid\") ?? element.getAttribute(\"data-test-id\");\n if (testId !== null) {\n return `[data-testid=\"${testId}\"]`;\n }\n if (element.id !== \"\") {\n return `#${element.id}`;\n }\n\n const label = element.getAttribute(\"aria-label\");\n if (label !== null) {\n return `${tag}[aria-label=\"${label.slice(0, ARIA_LABEL_MAX_CHARS)}\"]`;\n }\n\n // Read the class through getAttribute. On an SVG element, `className` is an\n // SVGAnimatedString, and a slice of it throws.\n const classAttribute = element.getAttribute(\"class\")?.trim() ?? \"\";\n if (classAttribute === \"\") {\n return tag;\n }\n\n const classes = classAttribute.split(/\\s+/).slice(0, SELECTOR_MAX_CLASSES).join(\".\");\n return `${tag}.${classes}`;\n}\n\n/**\n * The two History members that this module replaces. The type declares them as\n * properties, not methods, to keep the original functions unbound. With a bound\n * copy, uninstall restores a different function than the one it replaced.\n * Each install cycle also adds one more bind over the previous bind.\n */\ninterface HistoryMethods {\n pushState: (this: History, ...args: never[]) => void;\n replaceState: (this: History, ...args: never[]) => void;\n}\n\n/**\n * Returns the History object with a type that holds its methods unbound.\n * @returns The global history.\n */\nfunction historyMethods(): HistoryMethods {\n return history;\n}\n\n/** Captures user click interactions and single-page navigation transitions. */\nexport class InteractionCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"interactions\";\n\n /** Prevents duplicate listener registration. */\n private installed = false;\n\n /** Restore functions of the history wrappers. */\n private readonly restores: (() => void)[] = [];\n\n /** Tracked URL prior to the latest navigation event. */\n private lastUrl = \"\";\n\n /** Element of the current click burst, and the times of its clicks. */\n private burst: { target: Element | null; times: number[]; reported: boolean } = {\n target: null,\n times: [],\n reported: false,\n };\n\n /** Stops the dead click check that runs now. */\n private stopDeadCheck: (() => void) | undefined;\n\n /**\n * @param ctx Capture context containing configuration, diagnostics, logger, breadcrumbs, and tracing.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Registers click listeners and patches history navigation APIs. */\n install(): void {\n if (this.installed || typeof document === \"undefined\") {\n return;\n }\n this.installed = true;\n this.lastUrl = location.href;\n\n if (this.ctx.config.capture.interactions) {\n // The capture phase sees a click before a page handler can stop propagation.\n addEventListener(\"click\", this.onClick, true);\n }\n if (this.ctx.config.capture.navigation) {\n this.installHistory();\n addEventListener(\"popstate\", this.onNavigate);\n addEventListener(\"hashchange\", this.onNavigate);\n }\n }\n\n /**\n * Removes interaction listeners and restores each history method that still holds the\n * wrapper. A wrapper that another script wrapped again stays in place and records nothing.\n */\n uninstall(): void {\n if (!this.installed) {\n return;\n }\n this.installed = false;\n\n removeEventListener(\"click\", this.onClick, true);\n removeEventListener(\"popstate\", this.onNavigate);\n removeEventListener(\"hashchange\", this.onNavigate);\n\n for (const restore of this.restores.splice(0)) {\n restore();\n }\n\n this.stopDeadCheck?.();\n this.burst = { target: null, times: [], reported: false };\n }\n\n /** Rotates trace context and records a click breadcrumb. */\n private readonly onClick = (event: Event): void => {\n if (this.ctx.isActive?.() === false) return;\n const target = event.target;\n if (!(target instanceof Element)) return;\n const settings = this.ctx.config.capture.interactions;\n const options = typeof settings === \"object\" ? settings : {};\n const ignore =\n options.ignoreSelector === undefined ? \"[data-observability-ignore]\" : options.ignoreSelector;\n if (ignore && target.closest(ignore)) return;\n // An absent or empty attribute gives \"\". The message is then \"unknown-click\".\n const attribute = options.actionAttribute ?? ACTION_ATTRIBUTE_DEFAULT;\n const action = target.closest(`[${attribute}]`)?.getAttribute(attribute) ?? \"\";\n const message = (action || \"unknown-click\").slice(0, this.ctx.config.limits.maxBodyChars);\n const data: Record<string, unknown> = {};\n if (options.selector) data.selector = describeElement(target);\n if (options.text)\n data.text = target.textContent.trim().slice(0, options.maxTextChars ?? CLICK_TEXT_MAX_CHARS);\n this.ctx.tracing.rotate(\"interaction\");\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"click\",\n message,\n data: Object.keys(data).length > 0 ? data : undefined,\n });\n\n if (options.rageClicks) {\n this.countRage(target, message, options);\n }\n if (\n options.deadClicks &&\n target.closest(`${DEAD_CLICK_CONTROLS}, [${attribute}]`) &&\n !target.closest(LEAVING_LINKS)\n ) {\n this.watchDead(message, options);\n }\n };\n\n /**\n * Counts the clicks on one element. It records `ui.rage_click` one time in each burst.\n * @param target Clicked element.\n * @param action Action name of the click.\n * @param options Interaction options.\n */\n private countRage(target: Element, action: string, options: InteractionOptions): void {\n const now = Date.now();\n const windowMs = options.rageClickWindowMs ?? RAGE_CLICK_WINDOW_MS;\n const count = options.rageClickCount ?? RAGE_CLICK_COUNT;\n const times =\n this.burst.target === target ? this.burst.times.filter((t) => now - t < windowMs) : [];\n // A burst ends when no click stays in the window. Clicks that slide through it give no event.\n const reported = times.length > 0 && this.burst.reported;\n times.push(now);\n const reached = times.length >= count;\n this.burst = { target, times, reported: reported || reached };\n\n if (reached && !reported) {\n this.ctx.logger.logEvent(\"ui.rage_click\", { \"click.action\": action, \"click.count\": count });\n }\n }\n\n /**\n * Watches the page after a click on a control. With no DOM change, no navigation and no scroll\n * in `deadClickMs`, it records `ui.dead_click`. One check runs at a time.\n * @param action Action name of the click.\n * @param options Interaction options.\n */\n private watchDead(action: string, options: InteractionOptions): void {\n if (this.stopDeadCheck || typeof MutationObserver === \"undefined\") {\n return;\n }\n\n const href = location.href;\n let responded = false;\n const respond = (): void => {\n responded = true;\n };\n const observer = new MutationObserver(respond);\n observer.observe(document, {\n subtree: true,\n childList: true,\n attributes: true,\n characterData: true,\n });\n addEventListener(\"scroll\", respond, { capture: true, passive: true });\n\n const stop = (): void => {\n // stop reads timer, which the code declares after stop. stop runs only after that line.\n clearTimeout(timer);\n observer.disconnect();\n removeEventListener(\"scroll\", respond, true);\n this.stopDeadCheck = undefined;\n };\n const timer = setTimeout(() => {\n stop();\n if (!responded && location.href === href && this.ctx.isActive?.() !== false) {\n this.ctx.logger.logEvent(\"ui.dead_click\", { \"click.action\": action });\n }\n }, options.deadClickMs ?? DEAD_CLICK_MS);\n this.stopDeadCheck = stop;\n }\n\n /** On a URL change, rotates the trace context. It also records a breadcrumb and an event. */\n private readonly onNavigate = (): void => {\n const from = this.lastUrl;\n const to = location.href;\n if (from === to) {\n return;\n }\n this.lastUrl = to;\n if (this.ctx.isActive?.() === false) return;\n\n // The comparison above uses the full URL. A change to the query only is a navigation.\n // The record does not keep the query unless you set fullUrls.\n const full = this.ctx.config.capture.fullUrls;\n const { urlTransform } = this.ctx.config.capture;\n const fromUrl = recordedUrl(from, full, urlTransform, this.ctx.diagnostics);\n const toUrl = recordedUrl(to, full, urlTransform, this.ctx.diagnostics);\n\n this.ctx.tracing.rotate(\"navigation\");\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"navigation\",\n message: `${fromUrl} -> ${toUrl}`,\n });\n\n // The event carries only the previous URL. The record builder adds the current URL as\n // `page.url`. A new URL in `url.full` makes a navigation look like an HTTP request.\n this.ctx.logger.logEvent(\"NAVIGATION\", { \"page.url.previous\": fromUrl });\n };\n\n /** Patches History.pushState and replaceState to observe programmatic navigations. */\n private installHistory(): void {\n if (typeof history === \"undefined\") {\n return;\n }\n\n // Wrap the instance, not History.prototype. A read from the prototype skips a patch\n // that a router installed on the instance. patch keeps the originals unbound.\n const target = historyMethods();\n const onNavigate = this.onNavigate;\n // Uninstall clears the flag. A wrapper that stays in place then only calls the original.\n let active = true;\n\n const restorePushState = patch(\n target,\n \"pushState\",\n (original) =>\n function (this: History, ...args: never[]): void {\n original.apply(this, args);\n // Queue the handler. The browser updates location.href after the call returns.\n // A synchronous read gives the previous URL as the new URL.\n if (active) {\n queueMicrotask(onNavigate);\n }\n },\n );\n\n const restoreReplaceState = patch(\n target,\n \"replaceState\",\n (original) =>\n function (this: History, ...args: never[]): void {\n original.apply(this, args);\n if (active) {\n queueMicrotask(onNavigate);\n }\n },\n );\n\n this.restores.push(() => {\n active = false;\n restorePushState();\n restoreReplaceState();\n });\n }\n}\n"],"mappings":";;;;AAqBA,IAAME,IAAgB;AAQtB,SAASC,EAAgB,GAA0B;CACjD,IAAMC,IAAMC,EAAQ,QAAQ,YAAY,GAElCC,IAASD,EAAQ,aAAa,aAAa,KAAKA,EAAQ,aAAa,cAAc;CACzF,IAAIC,MAAW,MACb,OAAO,iBAAiBA,EAAO;CAEjC,IAAID,EAAQ,OAAO,IACjB,OAAO,IAAIA,EAAQ;CAGrB,IAAME,IAAQF,EAAQ,aAAa,YAAY;CAC/C,IAAIE,MAAU,MACZ,OAAO,GAAGH,EAAI,eAAeG,EAAM,MAAM,GAAA,EAAuB,EAAE;CAKpE,IAAMC,IAAiBH,EAAQ,aAAa,OAAO,CAAC,EAAE,KAAK,KAAK;CAMhE,OALIG,MAAmB,KACdJ,IAIF,GAAGA,EAAI,GADEI,EAAe,MAAM,KAAK,CAAC,CAAC,MAAM,GAAA,CAAuB,CAAC,CAAC,KAAK,GAC/D;AACnB;AAiBA,SAASC,IAAiC;CACxC,OAAO;AACT;AAGA,IAAaC,IAAb,MAAmD;CA0BpB;CAxB7B,OAAgB;CAGhB,YAAoB;CAGpB,WAA4C,CAAC;CAG7C,UAAkB;CAGlB,QAAgF;EAC9E,QAAQ;EACR,OAAO,CAAC;EACR,UAAU;CACZ;CAGA;CAKA,YAAY,GAAsC;EAArB,KAAA,MAAAC;CAAsB;CAGnD,UAAgB;EACd,AAAI,KAAK,aAAa,OAAO,WAAa,QAG1C,KAAK,YAAY,IACjB,KAAK,UAAU,SAAS,MAEpB,KAAK,IAAI,OAAO,QAAQ,gBAE1B,iBAAiB,SAAS,KAAK,SAAS,EAAI,GAE1C,KAAK,IAAI,OAAO,QAAQ,eAC1B,KAAK,eAAe,GACpB,iBAAiB,YAAY,KAA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@
|
|
|
1
|
-
require("./constants-
|
|
2
|
-
//# sourceMappingURL=interactions-
|
|
1
|
+
require("./constants-DqKJH_MP.cjs");const e=require("./patch-BX8KrPCT.cjs"),t=require("./platform-C2Ez5kDc.cjs");var n=`a[target="_blank"], a[download]`;function r(e){let t=e.tagName.toLowerCase(),n=e.getAttribute(`data-testid`)??e.getAttribute(`data-test-id`);if(n!==null)return`[data-testid="${n}"]`;if(e.id!==``)return`#${e.id}`;let r=e.getAttribute(`aria-label`);if(r!==null)return`${t}[aria-label="${r.slice(0,40)}"]`;let i=e.getAttribute(`class`)?.trim()??``;return i===``?t:`${t}.${i.split(/\s+/).slice(0,2).join(`.`)}`}function i(){return history}var a=class{ctx;name=`interactions`;installed=!1;restores=[];lastUrl=``;burst={target:null,times:[],reported:!1};stopDeadCheck;constructor(e){this.ctx=e}install(){this.installed||typeof document>`u`||(this.installed=!0,this.lastUrl=location.href,this.ctx.config.capture.interactions&&addEventListener(`click`,this.onClick,!0),this.ctx.config.capture.navigation&&(this.installHistory(),addEventListener(`popstate`,this.onNavigate),addEventListener(`hashchange`,this.onNavigate)))}uninstall(){if(this.installed){this.installed=!1,removeEventListener(`click`,this.onClick,!0),removeEventListener(`popstate`,this.onNavigate),removeEventListener(`hashchange`,this.onNavigate);for(let e of this.restores.splice(0))e();this.stopDeadCheck?.(),this.burst={target:null,times:[],reported:!1}}}onClick=e=>{if(this.ctx.isActive?.()===!1)return;let t=e.target;if(!(t instanceof Element))return;let i=this.ctx.config.capture.interactions,a=typeof i==`object`?i:{},o=a.ignoreSelector===void 0?`[data-observability-ignore]`:a.ignoreSelector;if(o&&t.closest(o))return;let s=a.actionAttribute??`data-observability-action`,c=((t.closest(`[${s}]`)?.getAttribute(s)??``)||`unknown-click`).slice(0,this.ctx.config.limits.maxBodyChars),l={};a.selector&&(l.selector=r(t)),a.text&&(l.text=t.textContent.trim().slice(0,a.maxTextChars??50)),this.ctx.tracing.rotate(`interaction`),this.ctx.breadcrumbs.push({t:Date.now(),category:`click`,message:c,data:Object.keys(l).length>0?l:void 0}),a.rageClicks&&this.countRage(t,c,a),a.deadClicks&&t.closest(`a, button, summary, input[type="button"], input[type="submit"], input[type="reset"], [role="button"], [role="link"], [role="menuitem"], [role="tab"], [${s}]`)&&!t.closest(n)&&this.watchDead(c,a)};countRage(e,t,n){let r=Date.now(),i=n.rageClickWindowMs??1e3,a=n.rageClickCount??3,o=this.burst.target===e?this.burst.times.filter(e=>r-e<i):[],s=o.length>0&&this.burst.reported;o.push(r);let c=o.length>=a;this.burst={target:e,times:o,reported:s||c},c&&!s&&this.ctx.logger.logEvent(`ui.rage_click`,{"click.action":t,"click.count":a})}watchDead(e,t){if(this.stopDeadCheck||typeof MutationObserver>`u`)return;let n=location.href,r=!1,i=()=>{r=!0},a=new MutationObserver(i);a.observe(document,{subtree:!0,childList:!0,attributes:!0,characterData:!0}),addEventListener(`scroll`,i,{capture:!0,passive:!0});let o=()=>{clearTimeout(s),a.disconnect(),removeEventListener(`scroll`,i,!0),this.stopDeadCheck=void 0},s=setTimeout(()=>{o(),!r&&location.href===n&&this.ctx.isActive?.()!==!1&&this.ctx.logger.logEvent(`ui.dead_click`,{"click.action":e})},t.deadClickMs??1e3);this.stopDeadCheck=o}onNavigate=()=>{let e=this.lastUrl,n=location.href;if(e===n||(this.lastUrl=n,this.ctx.isActive?.()===!1))return;let r=this.ctx.config.capture.fullUrls,{urlTransform:i}=this.ctx.config.capture,a=t.i(e,r,i,this.ctx.diagnostics),o=t.i(n,r,i,this.ctx.diagnostics);this.ctx.tracing.rotate(`navigation`),this.ctx.breadcrumbs.push({t:Date.now(),category:`navigation`,message:`${a} -> ${o}`}),this.ctx.logger.logEvent(`NAVIGATION`,{"page.url.previous":a})};installHistory(){if(typeof history>`u`)return;let t=i(),n=this.onNavigate,r=!0,a=e.t(t,`pushState`,e=>function(...t){e.apply(this,t),r&&queueMicrotask(n)}),o=e.t(t,`replaceState`,e=>function(...t){e.apply(this,t),r&&queueMicrotask(n)});this.restores.push(()=>{r=!1,a(),o()})}};exports.InteractionCapture=a;
|
|
2
|
+
//# sourceMappingURL=interactions-fEN6FbVo.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"interactions-8DgxtmgO.cjs","names":["recordedUrl","patch","require_platform","require_patch","LEAVING_LINKS","describeElement","tag","element","testId","label","classAttribute","historyMethods","InteractionCapture","ctx","restore","target","event","settings","options","ignore","attribute","message","data","now","windowMs","count","times","t","reported","reached","action","href","responded","respond","observer","stop","timer","from","to","full","fromUrl","urlTransform","toUrl","onNavigate","active","restorePushState","args","original","restoreReplaceState"],"sources":["../src/capture/interactions.ts"],"sourcesContent":["// src/capture/interactions.ts\n//\n// Captures clicks and in-page navigations as breadcrumbs and trace boundaries. It also finds\n// rage clicks and dead clicks.\n\nimport {\n ACTION_ATTRIBUTE_DEFAULT,\n ARIA_LABEL_MAX_CHARS,\n CLICK_TEXT_MAX_CHARS,\n DEAD_CLICK_CONTROLS,\n DEAD_CLICK_MS,\n RAGE_CLICK_COUNT,\n RAGE_CLICK_WINDOW_MS,\n SELECTOR_MAX_CLASSES,\n} from \"../constants\";\nimport type { InteractionOptions } from \"../models/config\";\nimport { patch } from \"../utils/patch\";\nimport { recordedUrl } from \"../utils/platform\";\nimport type { Capture, CaptureContext } from \"./types\";\n\n/** Links that open elsewhere. The page gives no visible response, and the click is not dead. */\nconst LEAVING_LINKS = 'a[target=\"_blank\"], a[download]';\n\n/**\n * Generates a short CSS selector for an element. The order of preference is test ID, ID,\n * aria-label, then class names.\n * @param element Target DOM element.\n * @returns Generated CSS selector string.\n */\nfunction describeElement(element: Element): string {\n const tag = element.tagName.toLowerCase();\n\n const testId = element.getAttribute(\"data-testid\") ?? element.getAttribute(\"data-test-id\");\n if (testId !== null) {\n return `[data-testid=\"${testId}\"]`;\n }\n if (element.id !== \"\") {\n return `#${element.id}`;\n }\n\n const label = element.getAttribute(\"aria-label\");\n if (label !== null) {\n return `${tag}[aria-label=\"${label.slice(0, ARIA_LABEL_MAX_CHARS)}\"]`;\n }\n\n // Read the class through getAttribute. On an SVG element, `className` is an\n // SVGAnimatedString, and a slice of it throws.\n const classAttribute = element.getAttribute(\"class\")?.trim() ?? \"\";\n if (classAttribute === \"\") {\n return tag;\n }\n\n const classes = classAttribute.split(/\\s+/).slice(0, SELECTOR_MAX_CLASSES).join(\".\");\n return `${tag}.${classes}`;\n}\n\n/**\n * The two History members that this module replaces. The type declares them as\n * properties, not methods, to keep the original functions unbound. With a bound\n * copy, uninstall restores a different function than the one it replaced.\n * Each install cycle also adds one more bind over the previous bind.\n */\ninterface HistoryMethods {\n pushState: (this: History, ...args: never[]) => void;\n replaceState: (this: History, ...args: never[]) => void;\n}\n\n/**\n * Returns the History object with a type that holds its methods unbound.\n * @returns The global history.\n */\nfunction historyMethods(): HistoryMethods {\n return history;\n}\n\n/** Captures user click interactions and single-page navigation transitions. */\nexport class InteractionCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"interactions\";\n\n /** Prevents duplicate listener registration. */\n private installed = false;\n\n /** Restore functions of the history wrappers. */\n private readonly restores: (() => void)[] = [];\n\n /** Tracked URL prior to the latest navigation event. */\n private lastUrl = \"\";\n\n /** Element of the current click burst, and the times of its clicks. */\n private burst: { target: Element | null; times: number[]; reported: boolean } = {\n target: null,\n times: [],\n reported: false,\n };\n\n /** Stops the dead click check that runs now. */\n private stopDeadCheck: (() => void) | undefined;\n\n /**\n * @param ctx Capture context containing configuration, diagnostics, logger, breadcrumbs, and tracing.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Registers click listeners and patches history navigation APIs. */\n install(): void {\n if (this.installed || typeof document === \"undefined\") {\n return;\n }\n this.installed = true;\n this.lastUrl = location.href;\n\n if (this.ctx.config.capture.interactions) {\n // The capture phase sees a click before a page handler can stop propagation.\n addEventListener(\"click\", this.onClick, true);\n }\n if (this.ctx.config.capture.navigation) {\n this.installHistory();\n addEventListener(\"popstate\", this.onNavigate);\n addEventListener(\"hashchange\", this.onNavigate);\n }\n }\n\n /**\n * Removes interaction listeners and restores each history method that still holds the\n * wrapper. A wrapper that another script wrapped again stays in place and records nothing.\n */\n uninstall(): void {\n if (!this.installed) {\n return;\n }\n this.installed = false;\n\n removeEventListener(\"click\", this.onClick, true);\n removeEventListener(\"popstate\", this.onNavigate);\n removeEventListener(\"hashchange\", this.onNavigate);\n\n for (const restore of this.restores.splice(0)) {\n restore();\n }\n\n this.stopDeadCheck?.();\n this.burst = { target: null, times: [], reported: false };\n }\n\n /** Rotates trace context and records a click breadcrumb. */\n private readonly onClick = (event: Event): void => {\n if (this.ctx.isActive?.() === false) return;\n const target = event.target;\n if (!(target instanceof Element)) return;\n const settings = this.ctx.config.capture.interactions;\n const options = typeof settings === \"object\" ? settings : {};\n const ignore =\n options.ignoreSelector === undefined ? \"[data-observability-ignore]\" : options.ignoreSelector;\n if (ignore && target.closest(ignore)) return;\n // An absent or empty attribute gives \"\". The message is then \"unknown-click\".\n const attribute = options.actionAttribute ?? ACTION_ATTRIBUTE_DEFAULT;\n const action = target.closest(`[${attribute}]`)?.getAttribute(attribute) ?? \"\";\n const message = (action || \"unknown-click\").slice(0, this.ctx.config.limits.maxBodyChars);\n const data: Record<string, unknown> = {};\n if (options.selector) data.selector = describeElement(target);\n if (options.text)\n data.text = target.textContent.trim().slice(0, options.maxTextChars ?? CLICK_TEXT_MAX_CHARS);\n this.ctx.tracing.rotate(\"interaction\");\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"click\",\n message,\n data: Object.keys(data).length > 0 ? data : undefined,\n });\n\n if (options.rageClicks) {\n this.countRage(target, message, options);\n }\n if (\n options.deadClicks &&\n target.closest(`${DEAD_CLICK_CONTROLS}, [${attribute}]`) &&\n !target.closest(LEAVING_LINKS)\n ) {\n this.watchDead(message, options);\n }\n };\n\n /**\n * Counts the clicks on one element. It records `ui.rage_click` one time in each burst.\n * @param target Clicked element.\n * @param action Action name of the click.\n * @param options Interaction options.\n */\n private countRage(target: Element, action: string, options: InteractionOptions): void {\n const now = Date.now();\n const windowMs = options.rageClickWindowMs ?? RAGE_CLICK_WINDOW_MS;\n const count = options.rageClickCount ?? RAGE_CLICK_COUNT;\n const times =\n this.burst.target === target ? this.burst.times.filter((t) => now - t < windowMs) : [];\n // A burst ends when no click stays in the window. Clicks that slide through it give no event.\n const reported = times.length > 0 && this.burst.reported;\n times.push(now);\n const reached = times.length >= count;\n this.burst = { target, times, reported: reported || reached };\n\n if (reached && !reported) {\n this.ctx.logger.logEvent(\"ui.rage_click\", { \"click.action\": action, \"click.count\": count });\n }\n }\n\n /**\n * Watches the page after a click on a control. With no DOM change, no navigation and no scroll\n * in `deadClickMs`, it records `ui.dead_click`. One check runs at a time.\n * @param action Action name of the click.\n * @param options Interaction options.\n */\n private watchDead(action: string, options: InteractionOptions): void {\n if (this.stopDeadCheck || typeof MutationObserver === \"undefined\") {\n return;\n }\n\n const href = location.href;\n let responded = false;\n const respond = (): void => {\n responded = true;\n };\n const observer = new MutationObserver(respond);\n observer.observe(document, {\n subtree: true,\n childList: true,\n attributes: true,\n characterData: true,\n });\n addEventListener(\"scroll\", respond, { capture: true, passive: true });\n\n const stop = (): void => {\n // stop reads timer, which the code declares after stop. stop runs only after that line.\n clearTimeout(timer);\n observer.disconnect();\n removeEventListener(\"scroll\", respond, true);\n this.stopDeadCheck = undefined;\n };\n const timer = setTimeout(() => {\n stop();\n if (!responded && location.href === href && this.ctx.isActive?.() !== false) {\n this.ctx.logger.logEvent(\"ui.dead_click\", { \"click.action\": action });\n }\n }, options.deadClickMs ?? DEAD_CLICK_MS);\n this.stopDeadCheck = stop;\n }\n\n /** On a URL change, rotates the trace context. It also records a breadcrumb and an event. */\n private readonly onNavigate = (): void => {\n const from = this.lastUrl;\n const to = location.href;\n if (from === to) {\n return;\n }\n this.lastUrl = to;\n if (this.ctx.isActive?.() === false) return;\n\n // The comparison above uses the full URL. A change to the query only is a navigation.\n // The record does not keep the query unless you set fullUrls.\n const full = this.ctx.config.capture.fullUrls;\n const { urlTransform } = this.ctx.config.capture;\n const fromUrl = recordedUrl(from, full, urlTransform, this.ctx.diagnostics);\n const toUrl = recordedUrl(to, full, urlTransform, this.ctx.diagnostics);\n\n this.ctx.tracing.rotate(\"navigation\");\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"navigation\",\n message: `${fromUrl} -> ${toUrl}`,\n });\n\n // The event carries only the previous URL. The record builder adds the current URL as\n // `page.url`. A new URL in `url.full` makes a navigation look like an HTTP request.\n this.ctx.logger.logEvent(\"NAVIGATION\", { \"page.url.previous\": fromUrl });\n };\n\n /** Patches History.pushState and replaceState to observe programmatic navigations. */\n private installHistory(): void {\n if (typeof history === \"undefined\") {\n return;\n }\n\n // Wrap the instance, not History.prototype. A read from the prototype skips a patch\n // that a router installed on the instance. patch keeps the originals unbound.\n const target = historyMethods();\n const onNavigate = this.onNavigate;\n // Uninstall clears the flag. A wrapper that stays in place then only calls the original.\n let active = true;\n\n const restorePushState = patch(\n target,\n \"pushState\",\n (original) =>\n function (this: History, ...args: never[]): void {\n original.apply(this, args);\n // Queue the handler. The browser updates location.href after the call returns.\n // A synchronous read gives the previous URL as the new URL.\n if (active) {\n queueMicrotask(onNavigate);\n }\n },\n );\n\n const restoreReplaceState = patch(\n target,\n \"replaceState\",\n (original) =>\n function (this: History, ...args: never[]): void {\n original.apply(this, args);\n if (active) {\n queueMicrotask(onNavigate);\n }\n },\n );\n\n this.restores.push(() => {\n active = false;\n restorePushState();\n restoreReplaceState();\n });\n }\n}\n"],"mappings":"iHAqBA,IAAMI,EAAgB,kCAQtB,SAASC,EAAgB,EAA0B,CACjD,IAAMC,EAAMC,EAAQ,QAAQ,YAAY,EAElCC,EAASD,EAAQ,aAAa,aAAa,GAAKA,EAAQ,aAAa,cAAc,EACzF,GAAIC,IAAW,KACb,MAAO,iBAAiBA,EAAO,IAEjC,GAAID,EAAQ,KAAO,GACjB,MAAO,IAAIA,EAAQ,KAGrB,IAAME,EAAQF,EAAQ,aAAa,YAAY,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,EAEtE,KAAK,IAAI,QAAQ,OAAO,YAAY,EACpC,KAAK,IAAI,YAAY,KAAK,CACxB,EAAG,KAAK,IAAI,EACZ,SAAU,aACV,QAAS,GAAGD,EAAQ,MAAME,GAC5B,CAAC,EAID,KAAK,IAAI,OAAO,SAAS,aAAc,CAAE,oBAAqBF,CAAQ,CAAC,CACzE,EAGA,gBAA+B,CAC7B,GAAI,OAAO,QAAY,IACrB,OAKF,IAAMzB,EAASJ,EAAe,EACxBgC,EAAa,KAAK,WAEpBC,EAAS,GAEPC,EAAmB5C,EAAAA,EACvBc,EACA,YACC,GACC,SAAyB,GAAG+B,EAAqB,CAC/CC,EAAS,MAAM,KAAMD,CAAI,EAGrBF,GACF,eAAeD,CAAU,CAE7B,CACJ,EAEMK,EAAsB/C,EAAAA,EAC1Bc,EACA,eACC,GACC,SAAyB,GAAG+B,EAAqB,CAC/CC,EAAS,MAAM,KAAMD,CAAI,EACrBF,GACF,eAAeD,CAAU,CAE7B,CACJ,EAEA,KAAK,SAAS,SAAW,CACvB,EAAS,GACTE,EAAiB,EACjBG,EAAoB,CACtB,CAAC,CACH,CACF"}
|
|
1
|
+
{"version":3,"file":"interactions-fEN6FbVo.cjs","names":["recordedUrl","patch","require_patch","require_platform","LEAVING_LINKS","describeElement","tag","element","testId","label","classAttribute","historyMethods","InteractionCapture","ctx","restore","target","event","settings","options","ignore","attribute","message","data","now","windowMs","count","times","t","reported","reached","action","href","responded","respond","observer","stop","timer","from","to","full","fromUrl","urlTransform","toUrl","onNavigate","active","restorePushState","args","original","restoreReplaceState"],"sources":["../src/capture/interactions.ts"],"sourcesContent":["// src/capture/interactions.ts\n//\n// Captures clicks and in-page navigations as breadcrumbs and trace boundaries. It also finds\n// rage clicks and dead clicks.\n\nimport {\n ACTION_ATTRIBUTE_DEFAULT,\n ARIA_LABEL_MAX_CHARS,\n CLICK_TEXT_MAX_CHARS,\n DEAD_CLICK_CONTROLS,\n DEAD_CLICK_MS,\n RAGE_CLICK_COUNT,\n RAGE_CLICK_WINDOW_MS,\n SELECTOR_MAX_CLASSES,\n} from \"../constants\";\nimport type { InteractionOptions } from \"../models/config\";\nimport { patch } from \"../utils/patch\";\nimport { recordedUrl } from \"../utils/platform\";\nimport type { Capture, CaptureContext } from \"./types\";\n\n/** Links that open elsewhere. The page gives no visible response, and the click is not dead. */\nconst LEAVING_LINKS = 'a[target=\"_blank\"], a[download]';\n\n/**\n * Generates a short CSS selector for an element. The order of preference is test ID, ID,\n * aria-label, then class names.\n * @param element Target DOM element.\n * @returns Generated CSS selector string.\n */\nfunction describeElement(element: Element): string {\n const tag = element.tagName.toLowerCase();\n\n const testId = element.getAttribute(\"data-testid\") ?? element.getAttribute(\"data-test-id\");\n if (testId !== null) {\n return `[data-testid=\"${testId}\"]`;\n }\n if (element.id !== \"\") {\n return `#${element.id}`;\n }\n\n const label = element.getAttribute(\"aria-label\");\n if (label !== null) {\n return `${tag}[aria-label=\"${label.slice(0, ARIA_LABEL_MAX_CHARS)}\"]`;\n }\n\n // Read the class through getAttribute. On an SVG element, `className` is an\n // SVGAnimatedString, and a slice of it throws.\n const classAttribute = element.getAttribute(\"class\")?.trim() ?? \"\";\n if (classAttribute === \"\") {\n return tag;\n }\n\n const classes = classAttribute.split(/\\s+/).slice(0, SELECTOR_MAX_CLASSES).join(\".\");\n return `${tag}.${classes}`;\n}\n\n/**\n * The two History members that this module replaces. The type declares them as\n * properties, not methods, to keep the original functions unbound. With a bound\n * copy, uninstall restores a different function than the one it replaced.\n * Each install cycle also adds one more bind over the previous bind.\n */\ninterface HistoryMethods {\n pushState: (this: History, ...args: never[]) => void;\n replaceState: (this: History, ...args: never[]) => void;\n}\n\n/**\n * Returns the History object with a type that holds its methods unbound.\n * @returns The global history.\n */\nfunction historyMethods(): HistoryMethods {\n return history;\n}\n\n/** Captures user click interactions and single-page navigation transitions. */\nexport class InteractionCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"interactions\";\n\n /** Prevents duplicate listener registration. */\n private installed = false;\n\n /** Restore functions of the history wrappers. */\n private readonly restores: (() => void)[] = [];\n\n /** Tracked URL prior to the latest navigation event. */\n private lastUrl = \"\";\n\n /** Element of the current click burst, and the times of its clicks. */\n private burst: { target: Element | null; times: number[]; reported: boolean } = {\n target: null,\n times: [],\n reported: false,\n };\n\n /** Stops the dead click check that runs now. */\n private stopDeadCheck: (() => void) | undefined;\n\n /**\n * @param ctx Capture context containing configuration, diagnostics, logger, breadcrumbs, and tracing.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Registers click listeners and patches history navigation APIs. */\n install(): void {\n if (this.installed || typeof document === \"undefined\") {\n return;\n }\n this.installed = true;\n this.lastUrl = location.href;\n\n if (this.ctx.config.capture.interactions) {\n // The capture phase sees a click before a page handler can stop propagation.\n addEventListener(\"click\", this.onClick, true);\n }\n if (this.ctx.config.capture.navigation) {\n this.installHistory();\n addEventListener(\"popstate\", this.onNavigate);\n addEventListener(\"hashchange\", this.onNavigate);\n }\n }\n\n /**\n * Removes interaction listeners and restores each history method that still holds the\n * wrapper. A wrapper that another script wrapped again stays in place and records nothing.\n */\n uninstall(): void {\n if (!this.installed) {\n return;\n }\n this.installed = false;\n\n removeEventListener(\"click\", this.onClick, true);\n removeEventListener(\"popstate\", this.onNavigate);\n removeEventListener(\"hashchange\", this.onNavigate);\n\n for (const restore of this.restores.splice(0)) {\n restore();\n }\n\n this.stopDeadCheck?.();\n this.burst = { target: null, times: [], reported: false };\n }\n\n /** Rotates trace context and records a click breadcrumb. */\n private readonly onClick = (event: Event): void => {\n if (this.ctx.isActive?.() === false) return;\n const target = event.target;\n if (!(target instanceof Element)) return;\n const settings = this.ctx.config.capture.interactions;\n const options = typeof settings === \"object\" ? settings : {};\n const ignore =\n options.ignoreSelector === undefined ? \"[data-observability-ignore]\" : options.ignoreSelector;\n if (ignore && target.closest(ignore)) return;\n // An absent or empty attribute gives \"\". The message is then \"unknown-click\".\n const attribute = options.actionAttribute ?? ACTION_ATTRIBUTE_DEFAULT;\n const action = target.closest(`[${attribute}]`)?.getAttribute(attribute) ?? \"\";\n const message = (action || \"unknown-click\").slice(0, this.ctx.config.limits.maxBodyChars);\n const data: Record<string, unknown> = {};\n if (options.selector) data.selector = describeElement(target);\n if (options.text)\n data.text = target.textContent.trim().slice(0, options.maxTextChars ?? CLICK_TEXT_MAX_CHARS);\n this.ctx.tracing.rotate(\"interaction\");\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"click\",\n message,\n data: Object.keys(data).length > 0 ? data : undefined,\n });\n\n if (options.rageClicks) {\n this.countRage(target, message, options);\n }\n if (\n options.deadClicks &&\n target.closest(`${DEAD_CLICK_CONTROLS}, [${attribute}]`) &&\n !target.closest(LEAVING_LINKS)\n ) {\n this.watchDead(message, options);\n }\n };\n\n /**\n * Counts the clicks on one element. It records `ui.rage_click` one time in each burst.\n * @param target Clicked element.\n * @param action Action name of the click.\n * @param options Interaction options.\n */\n private countRage(target: Element, action: string, options: InteractionOptions): void {\n const now = Date.now();\n const windowMs = options.rageClickWindowMs ?? RAGE_CLICK_WINDOW_MS;\n const count = options.rageClickCount ?? RAGE_CLICK_COUNT;\n const times =\n this.burst.target === target ? this.burst.times.filter((t) => now - t < windowMs) : [];\n // A burst ends when no click stays in the window. Clicks that slide through it give no event.\n const reported = times.length > 0 && this.burst.reported;\n times.push(now);\n const reached = times.length >= count;\n this.burst = { target, times, reported: reported || reached };\n\n if (reached && !reported) {\n this.ctx.logger.logEvent(\"ui.rage_click\", { \"click.action\": action, \"click.count\": count });\n }\n }\n\n /**\n * Watches the page after a click on a control. With no DOM change, no navigation and no scroll\n * in `deadClickMs`, it records `ui.dead_click`. One check runs at a time.\n * @param action Action name of the click.\n * @param options Interaction options.\n */\n private watchDead(action: string, options: InteractionOptions): void {\n if (this.stopDeadCheck || typeof MutationObserver === \"undefined\") {\n return;\n }\n\n const href = location.href;\n let responded = false;\n const respond = (): void => {\n responded = true;\n };\n const observer = new MutationObserver(respond);\n observer.observe(document, {\n subtree: true,\n childList: true,\n attributes: true,\n characterData: true,\n });\n addEventListener(\"scroll\", respond, { capture: true, passive: true });\n\n const stop = (): void => {\n // stop reads timer, which the code declares after stop. stop runs only after that line.\n clearTimeout(timer);\n observer.disconnect();\n removeEventListener(\"scroll\", respond, true);\n this.stopDeadCheck = undefined;\n };\n const timer = setTimeout(() => {\n stop();\n if (!responded && location.href === href && this.ctx.isActive?.() !== false) {\n this.ctx.logger.logEvent(\"ui.dead_click\", { \"click.action\": action });\n }\n }, options.deadClickMs ?? DEAD_CLICK_MS);\n this.stopDeadCheck = stop;\n }\n\n /** On a URL change, rotates the trace context. It also records a breadcrumb and an event. */\n private readonly onNavigate = (): void => {\n const from = this.lastUrl;\n const to = location.href;\n if (from === to) {\n return;\n }\n this.lastUrl = to;\n if (this.ctx.isActive?.() === false) return;\n\n // The comparison above uses the full URL. A change to the query only is a navigation.\n // The record does not keep the query unless you set fullUrls.\n const full = this.ctx.config.capture.fullUrls;\n const { urlTransform } = this.ctx.config.capture;\n const fromUrl = recordedUrl(from, full, urlTransform, this.ctx.diagnostics);\n const toUrl = recordedUrl(to, full, urlTransform, this.ctx.diagnostics);\n\n this.ctx.tracing.rotate(\"navigation\");\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"navigation\",\n message: `${fromUrl} -> ${toUrl}`,\n });\n\n // The event carries only the previous URL. The record builder adds the current URL as\n // `page.url`. A new URL in `url.full` makes a navigation look like an HTTP request.\n this.ctx.logger.logEvent(\"NAVIGATION\", { \"page.url.previous\": fromUrl });\n };\n\n /** Patches History.pushState and replaceState to observe programmatic navigations. */\n private installHistory(): void {\n if (typeof history === \"undefined\") {\n return;\n }\n\n // Wrap the instance, not History.prototype. A read from the prototype skips a patch\n // that a router installed on the instance. patch keeps the originals unbound.\n const target = historyMethods();\n const onNavigate = this.onNavigate;\n // Uninstall clears the flag. A wrapper that stays in place then only calls the original.\n let active = true;\n\n const restorePushState = patch(\n target,\n \"pushState\",\n (original) =>\n function (this: History, ...args: never[]): void {\n original.apply(this, args);\n // Queue the handler. The browser updates location.href after the call returns.\n // A synchronous read gives the previous URL as the new URL.\n if (active) {\n queueMicrotask(onNavigate);\n }\n },\n );\n\n const restoreReplaceState = patch(\n target,\n \"replaceState\",\n (original) =>\n function (this: History, ...args: never[]): void {\n original.apply(this, args);\n if (active) {\n queueMicrotask(onNavigate);\n }\n },\n );\n\n this.restores.push(() => {\n active = false;\n restorePushState();\n restoreReplaceState();\n });\n }\n}\n"],"mappings":"A,iHAqBA,IAAMI,EAAgB,kCAQtB,SAASC,EAAgB,EAA0B,CACjD,IAAMC,EAAMC,EAAQ,QAAQ,YAAY,EAElCC,EAASD,EAAQ,aAAa,aAAa,GAAKA,EAAQ,aAAa,cAAc,EACzF,GAAIC,IAAW,KACb,MAAO,iBAAiBA,EAAO,IAEjC,GAAID,EAAQ,KAAO,GACjB,MAAO,IAAIA,EAAQ,KAGrB,IAAME,EAAQF,EAAQ,aAAa,YAAY,EAC/C,GAAIE,IAAU,KACZ,MAAO,GAAGH,EAAI,eAAeG,EAAM,MAAM,EAAA,EAAuB,EAAE,IAKpE,IAAMC,EAAiBH,EAAQ,aAAa,OAAO,CAAC,EAAE,KAAK,GAAK,GAMhE,OALIG,IAAmB,GACdJ,EAIF,GAAGA,EAAI,GADEI,EAAe,MAAM,KAAK,CAAC,CAAC,MAAM,EAAA,CAAuB,CAAC,CAAC,KAAK,GAC/D,GACnB,CAiBA,SAASC,GAAiC,CACxC,OAAO,OACT,CAGA,IAAaC,EAAb,KAAmD,CA0BpB,IAxB7B,KAAgB,eAGhB,UAAoB,GAGpB,SAA4C,CAAC,EAG7C,QAAkB,GAGlB,MAAgF,CAC9E,OAAQ,KACR,MAAO,CAAC,EACR,SAAU,EACZ,EAGA,cAKA,YAAY,EAAsC,CAArB,KAAA,IAAAC,CAAsB,CAGnD,SAAgB,CACV,KAAK,WAAa,OAAO,SAAa,MAG1C,KAAK,UAAY,GACjB,KAAK,QAAU,SAAS,KAEpB,KAAK,IAAI,OA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