@utk09/ui-observability 0.4.1 → 0.6.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.
Files changed (103) hide show
  1. package/CHANGELOG.md +63 -0
  2. package/README.md +114 -59
  3. package/dist/bus/bus.d.ts +10 -10
  4. package/dist/bus/links.d.ts +1 -1
  5. package/dist/bus-BTMuVkDk.js +378 -0
  6. package/dist/bus-BTMuVkDk.js.map +1 -0
  7. package/dist/bus-ChIXDAWD.cjs +2 -0
  8. package/dist/bus-ChIXDAWD.cjs.map +1 -0
  9. package/dist/capture/network.d.ts +2 -2
  10. package/dist/capture/types.d.ts +10 -10
  11. package/dist/capture/web-vitals.d.ts +7 -4
  12. package/dist/{constants-DVbpJ1tv.js → constants-0-YchbAL.js} +9 -8
  13. package/dist/constants-0-YchbAL.js.map +1 -0
  14. package/dist/constants-TUFcy95w.cjs +2 -0
  15. package/dist/constants-TUFcy95w.cjs.map +1 -0
  16. package/dist/constants.d.ts +55 -40
  17. package/dist/core/breadcrumbs.d.ts +14 -14
  18. package/dist/core/config.d.ts +5 -4
  19. package/dist/core/context.d.ts +2 -2
  20. package/dist/core/diagnostics.d.ts +10 -9
  21. package/dist/core/journey.d.ts +28 -22
  22. package/dist/core/logger.d.ts +29 -10
  23. package/dist/core/pipeline.d.ts +34 -29
  24. package/dist/core/record.d.ts +6 -6
  25. package/dist/core/runtime.d.ts +119 -35
  26. package/dist/core/sampling.d.ts +15 -16
  27. package/dist/core/sender.d.ts +58 -0
  28. package/dist/errors-DRXBRqvm.cjs +3 -0
  29. package/dist/errors-DRXBRqvm.cjs.map +1 -0
  30. package/dist/errors-Dwm2SzBa.js +76 -0
  31. package/dist/errors-Dwm2SzBa.js.map +1 -0
  32. package/dist/index.cjs +1 -3
  33. package/dist/index.cjs.map +1 -1
  34. package/dist/index.d.ts +6 -5
  35. package/dist/index.js +476 -2247
  36. package/dist/index.js.map +1 -1
  37. package/dist/indexeddb-storage-B5dwq4hW.cjs +2 -0
  38. package/dist/indexeddb-storage-B5dwq4hW.cjs.map +1 -0
  39. package/dist/{indexeddb-storage-B6uqejZb.js → indexeddb-storage-DjY4Ml6t.js} +18 -22
  40. package/dist/indexeddb-storage-DjY4Ml6t.js.map +1 -0
  41. package/dist/interactions-DVom6eYn.cjs +2 -0
  42. package/dist/interactions-DVom6eYn.cjs.map +1 -0
  43. package/dist/interactions-DZmLu7l2.js +67 -0
  44. package/dist/interactions-DZmLu7l2.js.map +1 -0
  45. package/dist/models/batch.d.ts +12 -9
  46. package/dist/models/bus.d.ts +12 -13
  47. package/dist/models/config.d.ts +84 -49
  48. package/dist/models/log-record.d.ts +12 -10
  49. package/dist/models/serializer.d.ts +3 -2
  50. package/dist/models/storage.d.ts +2 -2
  51. package/dist/network-C4d2uw2Z.js +111 -0
  52. package/dist/network-C4d2uw2Z.js.map +1 -0
  53. package/dist/network-CuqWadNn.cjs +2 -0
  54. package/dist/network-CuqWadNn.cjs.map +1 -0
  55. package/dist/platform-CXio0W2n.cjs +2 -0
  56. package/dist/platform-CXio0W2n.cjs.map +1 -0
  57. package/dist/platform-CY8S3hUs.js +48 -0
  58. package/dist/platform-CY8S3hUs.js.map +1 -0
  59. package/dist/sampling-CEthcmEX.cjs +2 -0
  60. package/dist/sampling-CEthcmEX.cjs.map +1 -0
  61. package/dist/sampling-CJsI_24L.js +251 -0
  62. package/dist/sampling-CJsI_24L.js.map +1 -0
  63. package/dist/sender-ByFAkXVd.cjs +3 -0
  64. package/dist/sender-ByFAkXVd.cjs.map +1 -0
  65. package/dist/sender-dpvR_bHM.js +907 -0
  66. package/dist/sender-dpvR_bHM.js.map +1 -0
  67. package/dist/storage/emergency-queue.d.ts +2 -2
  68. package/dist/storage/factory.d.ts +2 -1
  69. package/dist/storage/idb-driver.d.ts +19 -19
  70. package/dist/storage/indexeddb-storage.d.ts +18 -17
  71. package/dist/storage/keys.d.ts +1 -1
  72. package/dist/storage/local-storage.d.ts +19 -18
  73. package/dist/storage/memory-storage.d.ts +12 -11
  74. package/dist/transport/compression.d.ts +2 -2
  75. package/dist/transport/errors.d.ts +8 -7
  76. package/dist/transport/exit-flush.d.ts +27 -24
  77. package/dist/transport/http-transport.d.ts +19 -10
  78. package/dist/transport/retry-engine.d.ts +33 -28
  79. package/dist/transport/serializers/ecs.d.ts +1 -1
  80. package/dist/transport/serializers/otlp.d.ts +1 -1
  81. package/dist/transport/serializers/select.d.ts +8 -0
  82. package/dist/unref-16maCyKA.js +8 -0
  83. package/dist/unref-16maCyKA.js.map +1 -0
  84. package/dist/unref-CU9Nyz_9.cjs +2 -0
  85. package/dist/unref-CU9Nyz_9.cjs.map +1 -0
  86. package/dist/utils/console.d.ts +11 -3
  87. package/dist/utils/identity.d.ts +53 -8
  88. package/dist/utils/lock.d.ts +4 -4
  89. package/dist/utils/platform.d.ts +5 -3
  90. package/dist/utils/sanitize.d.ts +5 -2
  91. package/dist/utils/sequence.d.ts +2 -2
  92. package/dist/utils/tracing.d.ts +14 -12
  93. package/dist/web-vitals-B2FYsEAU.cjs +2 -0
  94. package/dist/web-vitals-B2FYsEAU.cjs.map +1 -0
  95. package/dist/web-vitals-DHZ0yA_H.js +51 -0
  96. package/dist/web-vitals-DHZ0yA_H.js.map +1 -0
  97. package/package.json +21 -11
  98. package/dist/constants-DVbpJ1tv.js.map +0 -1
  99. package/dist/constants-tQpoTzkY.cjs +0 -2
  100. package/dist/constants-tQpoTzkY.cjs.map +0 -1
  101. package/dist/indexeddb-storage-B6uqejZb.js.map +0 -1
  102. package/dist/indexeddb-storage-CgT1GLYj.cjs +0 -2
  103. package/dist/indexeddb-storage-CgT1GLYj.cjs.map +0 -1
@@ -0,0 +1,2 @@
1
+ const e=require("./constants-TUFcy95w.cjs");function t(e){return e.error??Error(`The IndexedDB request failed.`)}function n(e){return new Promise((n,r)=>{e.onsuccess=()=>{n(e.result)},e.onerror=()=>{r(t(e))}})}var r=class{name;connection=null;constructor(e){this.name=e}async put(e){await n((await this.store(`readwrite`)).put(e))}async takeOldest(t){return n((await this.store(`readonly`)).index(e.Q).getAll(null,t))}async takeBefore(t){let r=await this.store(`readonly`),i=IDBKeyRange.upperBound(t,!0);return n(r.index(e.Q).getAll(i))}async delete(e){await n((await this.store(`readwrite`)).delete(e))}async deleteMany(e){let t=await this.store(`readwrite`);await Promise.all(e.map(e=>n(t.delete(e))))}async bumpAttempts(e,t){let r=await this.store(`readwrite`),i=await n(r.get(e));i!==void 0&&await n(r.put({...i,attempts:t}))}async count(){return n((await this.store(`readonly`)).count())}async clear(){await n((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.$,t).objectStore(e.$)}open(){let n=this.connection;if(n!==null)return n;let r=new Promise((n,r)=>{let i=indexedDB.open(this.name,11),a=!1;i.onupgradeneeded=()=>{let t=i.result;t.objectStoreNames.contains(`batches`)||t.createObjectStore(e.$,{keyPath:`id`}).createIndex(e.Q,e.Q)},i.onsuccess=()=>{let e=i.result;a?e.close():(e.onversionchange=()=>{e.close(),this.connection=null},n(e))},i.onerror=()=>{r(t(i))},i.onblocked=()=>{a=!0,r(Error(`Another connection blocks the IndexedDB upgrade.`))}});return this.connection=r.catch(e=>{throw this.connection=null,e}),this.connection}};function i(e){return e.reduce((e,t)=>e+t.records.length,0)}var a=class{limits;diagnostics;onGap;name=e.Xt;db;constructor(e,t,n,i){this.limits=t,this.diagnostics=n,this.onGap=i,this.db=new r(e)}async open(){await this.db.ready()}async save(e){try{await this.db.put(e),await this.prune()}catch(t){if(t instanceof Error&&t.name===`QuotaExceededError`){this.diagnostics.report(`storage.quota_exceeded`,`IndexedDB is full. The library removes the oldest batches.`);let t=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)));t&&this.reportGap({...t,reason:`quota`}),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&&this.reportGap({batches:1,records:e.records.length,reason:`quota`});return}this.diagnostics.report(`storage.degraded`,`The library could not store a batch.`,{batchId:e.id},t)}}async take(e){return await this.diagnostics.guardAsync(`storage.degraded`,`The library could not read the stored batches.`,()=>this.db.takeOldest(e))??[]}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)),e.batches+=n.length,e.records+=i(n));let r=await this.db.count();if(r>this.limits.maxBatches){e.reason=`over_capacity`;let t=await this.evictOldest(r-this.limits.maxBatches);e.batches+=t.batches,e.records+=t.records}}),this.reportGap(e),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())}reportGap(e){e.batches!==0&&(this.diagnostics.report(`storage.evicted`,`The library dropped ${String(e.batches)} stored batches (${String(e.records)} records).`,{...e}),this.onGap?.(e))}async evictOldest(e){let t=await this.db.takeOldest(e);return await this.db.deleteMany(t.map(e=>e.id)),{batches:t.length,records:i(t)}}};exports.IndexedDbStorage=a;
2
+ //# sourceMappingURL=indexeddb-storage-B5dwq4hW.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"indexeddb-storage-B5dwq4hW.cjs","names":["INDEXEDDB_CREATED_AT_INDEX","INDEXEDDB_STORE_NAME","STORAGE_NAME_INDEXEDDB","require_constants","failureOf","request","promisify","resolve","reject","IdbDriver","name","batch","limit","store","range","cutoff","id","ids","connection","mode","existing","opening","abandoned","db","error","countRecords","batches","total","IndexedDbStorage","limits","diagnostics","onGap","dbName","evicted","attempts","result","expired","doomed","howMany"],"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 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 * 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 was 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 };\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 type { LogBatch } from \"../models/batch\";\nimport type { GapReporter, PruneResult, StorageAdapter, StorageLimits } from \"../models/storage\";\nimport { IdbDriver } from \"./idb-driver\";\n\n/**\n * Returns the total record count of the batches.\n * @param batches Batches to measure.\n * @returns Total record count.\n */\nfunction countRecords(batches: LogBatch[]): number {\n return batches.reduce((total, batch) => total + batch.records.length, 0);\n}\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 this.reportGap({ ...evicted, reason: \"quota\" });\n }\n\n // The eviction makes room for this batch. Without a second write, save() resolves\n // but the batch is lost and not counted.\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 this.reportGap({ batches: 1, records: batch.records.length, reason: \"quota\" });\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 }\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 () => this.db.takeOldest(limit),\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 result.batches += expired.length;\n result.records += countRecords(expired);\n }\n\n const total = await this.db.count();\n if (total > this.limits.maxBatches) {\n result.reason = \"over_capacity\";\n const evicted = await this.evictOldest(total - this.limits.maxBatches);\n result.batches += evicted.batches;\n result.records += evicted.records;\n }\n },\n );\n\n this.reportGap(result);\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 * Reports dropped records to diagnostics and to the gap handler.\n * @param result Prune result metrics.\n */\n private reportGap(result: PruneResult): void {\n if (result.batches === 0) {\n return;\n }\n\n this.diagnostics.report(\n \"storage.evicted\",\n `The library dropped ${String(result.batches)} stored batches (${String(result.records)} records).`,\n { ...result },\n );\n this.onGap?.(result);\n }\n\n /**\n * Deletes the given number of oldest stored batches. It has no guard. Both\n * callers guard it. A guard here hides the failure and reports an eviction that did not\n * occur.\n * @param howMany Number of oldest batches to evict.\n * @returns Metrics of evicted batches and records.\n */\n private async evictOldest(howMany: number): Promise<Omit<PruneResult, \"reason\">> {\n const doomed = await this.db.takeOldest(howMany);\n await this.db.deleteMany(doomed.map((batch) => batch.id));\n\n return { batches: doomed.length, records: countRecords(doomed) };\n }\n}\n"],"mappings":"4CAqBA,SAASI,EAAU,EAA4B,CAC7C,OAAOC,EAAQ,OAAa,MAAM,+BAA+B,CACnE,CASA,SAASC,EAAa,EAAiC,CACrD,OAAO,IAAI,SAAY,EAAS,IAAW,CACzC,EAAQ,cAAkB,CACx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AAO,CACd,EACA,KAAK,QAAQA,CAAM,EACrB,CASA,MAAc,YAAY,EAAuD,CAC/E,IAAME,EAAS,MAAM,KAAK,GAAG,WAAWC,CAAO,EAG/C,OAFA,MAAM,KAAK,GAAG,WAAWD,EAAO,IAAK,GAAU1B,EAAM,EAAE,CAAC,EAEjD,CAAE,QAAS0B,EAAO,OAAQ,QAASZ,EAAaY,CAAM,CAAE,CACjE,CACF"}
@@ -1,7 +1,7 @@
1
- import { $ as e, Q as t, Yt as n } from "./constants-DVbpJ1tv.js";
1
+ import { $ as e, Q as t, Xt as n } from "./constants-0-YchbAL.js";
2
2
  //#region src/storage/idb-driver.ts
3
3
  function r(e) {
4
- return e.error ?? /* @__PURE__ */ Error("the IndexedDB request failed");
4
+ return e.error ?? /* @__PURE__ */ Error("The IndexedDB request failed.");
5
5
  }
6
6
  function i(e) {
7
7
  return new Promise((t, n) => {
@@ -68,17 +68,13 @@ var a = class {
68
68
  n.objectStoreNames.contains("batches") || n.createObjectStore(e, { keyPath: "id" }).createIndex(t, t);
69
69
  }, a.onsuccess = () => {
70
70
  let e = a.result;
71
- if (o) {
72
- e.close();
73
- return;
74
- }
75
- e.onversionchange = () => {
71
+ o ? e.close() : (e.onversionchange = () => {
76
72
  e.close(), this.connection = null;
77
- }, n(e);
73
+ }, n(e));
78
74
  }, a.onerror = () => {
79
75
  i(r(a));
80
76
  }, a.onblocked = () => {
81
- o = !0, i(/* @__PURE__ */ Error("another connection is blocking the IndexedDB upgrade"));
77
+ o = !0, i(/* @__PURE__ */ Error("Another connection blocks the IndexedDB upgrade."));
82
78
  };
83
79
  });
84
80
  return this.connection = i.catch((e) => {
@@ -108,29 +104,29 @@ var s = class {
108
104
  await this.db.put(e), await this.prune();
109
105
  } catch (t) {
110
106
  if (t instanceof Error && t.name === "QuotaExceededError") {
111
- this.diagnostics.report("storage.quota_exceeded", "IndexedDB is full, evicting the oldest");
112
- let t = await this.diagnostics.guardAsync("storage.degraded", "evicting after a full disk", () => this.evictOldest(Math.ceil(this.limits.maxBatches / 4)));
107
+ this.diagnostics.report("storage.quota_exceeded", "IndexedDB is full. The library removes the oldest batches.");
108
+ let t = 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)));
113
109
  t && this.reportGap({
114
110
  ...t,
115
111
  reason: "quota"
116
- }), await this.diagnostics.guardAsync("storage.degraded", "writing a batch after evicting", async () => (await this.db.put(e), !0)) !== !0 && this.reportGap({
112
+ }), 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 && this.reportGap({
117
113
  batches: 1,
118
114
  records: e.records.length,
119
115
  reason: "quota"
120
116
  });
121
117
  return;
122
118
  }
123
- this.diagnostics.report("storage.degraded", "could not persist a batch", { batchId: e.id }, t);
119
+ this.diagnostics.report("storage.degraded", "The library could not store a batch.", { batchId: e.id }, t);
124
120
  }
125
121
  }
126
122
  async take(e) {
127
- return await this.diagnostics.guardAsync("storage.degraded", "reading stored batches", () => this.db.takeOldest(e)) ?? [];
123
+ return await this.diagnostics.guardAsync("storage.degraded", "The library could not read the stored batches.", () => this.db.takeOldest(e)) ?? [];
128
124
  }
129
125
  async remove(e) {
130
- await this.diagnostics.guardAsync("storage.degraded", "deleting a batch", () => this.db.delete(e));
126
+ await this.diagnostics.guardAsync("storage.degraded", "The library could not delete a batch.", () => this.db.delete(e));
131
127
  }
132
128
  async bumpAttempts(e, t) {
133
- await this.diagnostics.guardAsync("storage.degraded", "updating attempts", () => this.db.bumpAttempts(e, t));
129
+ await this.diagnostics.guardAsync("storage.degraded", "The library could not update the attempt count.", () => this.db.bumpAttempts(e, t));
134
130
  }
135
131
  async prune() {
136
132
  let e = {
@@ -138,7 +134,7 @@ var s = class {
138
134
  records: 0,
139
135
  reason: "expired"
140
136
  };
141
- return await this.diagnostics.guardAsync("storage.degraded", "pruning", async () => {
137
+ return await this.diagnostics.guardAsync("storage.degraded", "The library could not prune the stored batches.", async () => {
142
138
  let t = Date.now() - this.limits.maxAgeMs, n = await this.db.takeBefore(t);
143
139
  n.length > 0 && (await this.db.deleteMany(n.map((e) => e.id)), e.batches += n.length, e.records += o(n));
144
140
  let r = await this.db.count();
@@ -150,16 +146,16 @@ var s = class {
150
146
  }), this.reportGap(e), e;
151
147
  }
152
148
  async count() {
153
- return await this.diagnostics.guardAsync("storage.degraded", "counting", () => this.db.count()) ?? 0;
149
+ return await this.diagnostics.guardAsync("storage.degraded", "The library could not count the stored batches.", () => this.db.count()) ?? 0;
154
150
  }
155
151
  async clear() {
156
- await this.diagnostics.guardAsync("storage.degraded", "clearing", () => this.db.clear());
152
+ await this.diagnostics.guardAsync("storage.degraded", "The library could not clear the stored batches.", () => this.db.clear());
157
153
  }
158
154
  async close() {
159
- await this.diagnostics.guardAsync("storage.degraded", "closing the database", () => this.db.close());
155
+ await this.diagnostics.guardAsync("storage.degraded", "The library could not close the database.", () => this.db.close());
160
156
  }
161
157
  reportGap(e) {
162
- e.batches !== 0 && (this.diagnostics.report("storage.evicted", `dropped ${String(e.batches)} stored batches (${String(e.records)} records)`, { ...e }), this.onGap?.(e));
158
+ e.batches !== 0 && (this.diagnostics.report("storage.evicted", `The library dropped ${String(e.batches)} stored batches (${String(e.records)} records).`, { ...e }), this.onGap?.(e));
163
159
  }
164
160
  async evictOldest(e) {
165
161
  let t = await this.db.takeOldest(e);
@@ -172,4 +168,4 @@ var s = class {
172
168
  //#endregion
173
169
  export { s as IndexedDbStorage };
174
170
 
175
- //# sourceMappingURL=indexeddb-storage-B6uqejZb.js.map
171
+ //# sourceMappingURL=indexeddb-storage-DjY4Ml6t.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"indexeddb-storage-DjY4Ml6t.js","names":["INDEXEDDB_STORE_NAME","INDEXEDDB_CREATED_AT_INDEX","STORAGE_NAME_INDEXEDDB","failureOf","request","promisify","IdbDriver","name","batch","limit","store","range","cutoff","id","ids","connection","mode","existing","opening","abandoned","db","resolve","reject","error","countRecords","batches","total","IndexedDbStorage","limits","diagnostics","onGap","dbName","evicted","attempts","result","expired","doomed","howMany"],"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 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 * 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 was 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 };\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 type { LogBatch } from \"../models/batch\";\nimport type { GapReporter, PruneResult, StorageAdapter, StorageLimits } from \"../models/storage\";\nimport { IdbDriver } from \"./idb-driver\";\n\n/**\n * Returns the total record count of the batches.\n * @param batches Batches to measure.\n * @returns Total record count.\n */\nfunction countRecords(batches: LogBatch[]): number {\n return batches.reduce((total, batch) => total + batch.records.length, 0);\n}\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 this.reportGap({ ...evicted, reason: \"quota\" });\n }\n\n // The eviction makes room for this batch. Without a second write, save() resolves\n // but the batch is lost and not counted.\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 this.reportGap({ batches: 1, records: batch.records.length, reason: \"quota\" });\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 }\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 () => this.db.takeOldest(limit),\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 result.batches += expired.length;\n result.records += countRecords(expired);\n }\n\n const total = await this.db.count();\n if (total > this.limits.maxBatches) {\n result.reason = \"over_capacity\";\n const evicted = await this.evictOldest(total - this.limits.maxBatches);\n result.batches += evicted.batches;\n result.records += evicted.records;\n }\n },\n );\n\n this.reportGap(result);\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 * Reports dropped records to diagnostics and to the gap handler.\n * @param result Prune result metrics.\n */\n private reportGap(result: PruneResult): void {\n if (result.batches === 0) {\n return;\n }\n\n this.diagnostics.report(\n \"storage.evicted\",\n `The library dropped ${String(result.batches)} stored batches (${String(result.records)} records).`,\n { ...result },\n );\n this.onGap?.(result);\n }\n\n /**\n * Deletes the given number of oldest stored batches. It has no guard. Both\n * callers guard it. A guard here hides the failure and reports an eviction that did not\n * occur.\n * @param howMany Number of oldest batches to evict.\n * @returns Metrics of evicted batches and records.\n */\n private async evictOldest(howMany: number): Promise<Omit<PruneResult, \"reason\">> {\n const doomed = await this.db.takeOldest(howMany);\n await this.db.deleteMany(doomed.map((batch) => batch.id));\n\n return { batches: doomed.length, records: countRecords(doomed) };\n }\n}\n"],"mappings":";;AAqBA,SAASG,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,EAAQ,gBA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AK,QAAQA,CAAM;CACrB;CASA,MAAc,YAAY,GAAuD;EAC/E,IAAME,IAAS,MAAM,KAAK,GAAG,WAAWC,CAAO;EAG/C,OAFA,MAAM,KAAK,GAAG,WAAWD,EAAO,KAAK,MAAU5B,EAAM,EAAE,CAAC,GAEjD;GAAE,SAAS4B,EAAO;GAAQ,SAASZ,EAAaY,CAAM;EAAE;CACjE;AACF"}
@@ -0,0 +1,2 @@
1
+ const e=require("./platform-CXio0W2n.cjs");function t(e){if(e===null)return`unknown`;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 n(){return history}var r=class{ctx;name=`interactions`;installed=!1;originalPushState=null;originalReplaceState=null;lastUrl=``;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(){this.installed&&(this.installed=!1,removeEventListener(`click`,this.onClick,!0),removeEventListener(`popstate`,this.onNavigate),removeEventListener(`hashchange`,this.onNavigate),this.originalPushState&&(n().pushState=this.originalPushState),this.originalReplaceState&&(n().replaceState=this.originalReplaceState),this.originalPushState=null,this.originalReplaceState=null)}onClick=e=>{let n=e.target,r=t(n instanceof Element?n:null),i=n instanceof HTMLElement?n.textContent.trim().slice(0,50):``;this.ctx.tracing.rotate(`interaction`),this.ctx.breadcrumbs.push({t:Date.now(),category:`click`,message:r,data:i===``?void 0:{text:i}})};onNavigate=()=>{let t=this.lastUrl,n=location.href;if(t===n)return;this.lastUrl=n;let r=this.ctx.config.capture.fullUrls,i=r?t:e.r(t),a=r?n:e.r(n);this.ctx.tracing.rotate(`navigation`),this.ctx.breadcrumbs.push({t:Date.now(),category:`navigation`,message:`${i} -> ${a}`}),this.ctx.logger.logEvent(`NAVIGATION`,{"page.url.previous":i})};installHistory(){if(typeof history>`u`||this.originalPushState)return;let e=n(),t=e.pushState,r=e.replaceState;this.originalPushState=t,this.originalReplaceState=r;let i=this.onNavigate;e.pushState=function(...e){t.apply(this,e),queueMicrotask(i)},e.replaceState=function(...e){r.apply(this,e),queueMicrotask(i)}}};exports.InteractionCapture=r;
2
+ //# sourceMappingURL=interactions-DVom6eYn.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"interactions-DVom6eYn.cjs","names":["stripUrlQuery","require_platform","describeElement","element","tag","testId","label","classAttribute","historyMethods","InteractionCapture","ctx","target","event","selector","text","from","to","full","fromUrl","toUrl","originalPushState","originalReplaceState","onNavigate","args"],"sources":["../src/capture/interactions.ts"],"sourcesContent":["// src/capture/interactions.ts\n//\n// Captures clicks and in-page navigations as breadcrumbs and trace boundaries.\n\nimport { ARIA_LABEL_MAX_CHARS, CLICK_TEXT_MAX_CHARS, SELECTOR_MAX_CLASSES } from \"../constants\";\nimport { stripUrlQuery } from \"../utils/platform\";\nimport type { Capture, CaptureContext } from \"./types\";\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 | null): string {\n if (element === null) {\n return \"unknown\";\n }\n\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 /** Unpatched History.pushState implementation. */\n private originalPushState: HistoryMethods[\"pushState\"] | null = null;\n\n /** Unpatched History.replaceState implementation. */\n private originalReplaceState: HistoryMethods[\"replaceState\"] | null = null;\n\n /** Tracked URL prior to the latest navigation event. */\n private lastUrl = \"\";\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 /** Removes interaction listeners and restores native history methods. */\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 if (this.originalPushState) {\n historyMethods().pushState = this.originalPushState;\n }\n if (this.originalReplaceState) {\n historyMethods().replaceState = this.originalReplaceState;\n }\n this.originalPushState = null;\n this.originalReplaceState = null;\n }\n\n /** Rotates trace context and records a click breadcrumb. */\n private readonly onClick = (event: Event): void => {\n const target = event.target;\n const selector = describeElement(target instanceof Element ? target : null);\n // Use textContent, not innerText. A read of innerText causes style and layout work\n // at each click.\n const text =\n target instanceof HTMLElement ? target.textContent.trim().slice(0, CLICK_TEXT_MAX_CHARS) : \"\";\n\n // A click starts a new logical operation. All work that the click causes shares one\n // trace id. Without the rotation, one query cannot find a click and its API calls.\n this.ctx.tracing.rotate(\"interaction\");\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"click\",\n message: selector,\n data: text === \"\" ? undefined : { text },\n });\n };\n\n /** Rotates trace context and records a navigation breadcrumb and event on URL changes. */\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\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 fullUrls is set.\n const full = this.ctx.config.capture.fullUrls;\n const fromUrl = full ? from : stripUrlQuery(from);\n const toUrl = full ? to : stripUrlQuery(to);\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\" || this.originalPushState) {\n return;\n }\n\n // Keep the originals unbound and call them through apply. A read from History.prototype\n // skips a patch that a router installed on the instance. Uninstall then adds an own\n // property that was not there before.\n const target = historyMethods();\n const originalPushState = target.pushState;\n const originalReplaceState = target.replaceState;\n this.originalPushState = originalPushState;\n this.originalReplaceState = originalReplaceState;\n const onNavigate = this.onNavigate;\n\n target.pushState = function (this: History, ...args: never[]): void {\n originalPushState.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 queueMicrotask(onNavigate);\n };\n\n target.replaceState = function (this: History, ...args: never[]): void {\n originalReplaceState.apply(this, args);\n queueMicrotask(onNavigate);\n };\n }\n}\n"],"mappings":"2CAcA,SAASE,EAAgB,EAAiC,CACxD,GAAIC,IAAY,KACd,MAAO,UAGT,IAAMC,EAAMD,EAAQ,QAAQ,YAAY,EAElCE,EAASF,EAAQ,aAAa,aAAa,GAAKA,EAAQ,aAAa,cAAc,EACzF,GAAIE,IAAW,KACb,MAAO,iBAAiBA,EAAO,IAEjC,GAAIF,EAAQ,KAAO,GACjB,MAAO,IAAIA,EAAQ,KAGrB,IAAMG,EAAQH,EAAQ,aAAa,YAAY,EAC/C,GAAIG,IAAU,KACZ,MAAO,GAAGF,EAAI,eAAeE,EAAM,MAAM,EAAA,EAAuB,EAAE,IAKpE,IAAMC,EAAiBJ,EAAQ,aAAa,OAAO,CAAC,EAAE,KAAK,GAAK,GAMhE,OALII,IAAmB,GACdH,EAIF,GAAGA,EAAI,GADEG,EAAe,MAAM,KAAK,CAAC,CAAC,MAAM,EAAA,CAAuB,CAAC,CAAC,KAAK,GAC/D,GACnB,CAiBA,SAASC,GAAiC,CACxC,OAAO,OACT,CAGA,IAAaC,EAAb,KAAmD,CAmBpB,IAjB7B,KAAgB,eAGhB,UAAoB,GAGpB,kBAAgE,KAGhE,qBAAsE,KAGtE,QAAkB,GAKlB,YAAY,EAAsC,CAArB,KAAA,IAAAC,CAAsB,CAGnD,SAAgB,CACV,KAAK,WAAa,OAAO,SAAa,MAG1C,KAAK,UAAY,GACjB,KAAK,QAAU,SAAS,KAEp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GAC5B,CAAC,EAID,KAAK,IAAI,OAAO,SAAS,aAAc,CAAE,oBAAqBD,CAAQ,CAAC,CACzE,EAGA,gBAA+B,CAC7B,GAAI,OAAO,QAAY,KAAe,KAAK,kBACzC,OAMF,IAAMP,EAASH,EAAe,EACxBY,EAAoBT,EAAO,UAC3BU,EAAuBV,EAAO,aACpC,KAAK,kBAAoBS,EACzB,KAAK,qBAAuBC,EAC5B,IAAMC,EAAa,KAAK,WAExB,EAAO,UAAY,SAAyB,GAAGC,EAAqB,CAClEH,EAAkB,MAAM,KAAMG,CAAI,EAGlC,eAAeD,CAAU,CAC3B,EAEA,EAAO,aAAe,SAAyB,GAAGC,EAAqB,CACrEF,EAAqB,MAAM,KAAME,CAAI,EACrC,eAAeD,CAAU,CAC3B,CACF,CACF"}
@@ -0,0 +1,67 @@
1
+ import { r as e } from "./platform-CY8S3hUs.js";
2
+ //#region src/capture/interactions.ts
3
+ function t(e) {
4
+ if (e === null) return "unknown";
5
+ let t = e.tagName.toLowerCase(), n = e.getAttribute("data-testid") ?? e.getAttribute("data-test-id");
6
+ if (n !== null) return `[data-testid="${n}"]`;
7
+ if (e.id !== "") return `#${e.id}`;
8
+ let r = e.getAttribute("aria-label");
9
+ if (r !== null) return `${t}[aria-label="${r.slice(0, 40)}"]`;
10
+ let i = e.getAttribute("class")?.trim() ?? "";
11
+ return i === "" ? t : `${t}.${i.split(/\s+/).slice(0, 2).join(".")}`;
12
+ }
13
+ function n() {
14
+ return history;
15
+ }
16
+ var r = class {
17
+ ctx;
18
+ name = "interactions";
19
+ installed = !1;
20
+ originalPushState = null;
21
+ originalReplaceState = null;
22
+ lastUrl = "";
23
+ constructor(e) {
24
+ this.ctx = e;
25
+ }
26
+ install() {
27
+ 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)));
28
+ }
29
+ uninstall() {
30
+ this.installed && (this.installed = !1, removeEventListener("click", this.onClick, !0), removeEventListener("popstate", this.onNavigate), removeEventListener("hashchange", this.onNavigate), this.originalPushState && (n().pushState = this.originalPushState), this.originalReplaceState && (n().replaceState = this.originalReplaceState), this.originalPushState = null, this.originalReplaceState = null);
31
+ }
32
+ onClick = (e) => {
33
+ let n = e.target, r = t(n instanceof Element ? n : null), i = n instanceof HTMLElement ? n.textContent.trim().slice(0, 50) : "";
34
+ this.ctx.tracing.rotate("interaction"), this.ctx.breadcrumbs.push({
35
+ t: Date.now(),
36
+ category: "click",
37
+ message: r,
38
+ data: i === "" ? void 0 : { text: i }
39
+ });
40
+ };
41
+ onNavigate = () => {
42
+ let t = this.lastUrl, n = location.href;
43
+ if (t === n) return;
44
+ this.lastUrl = n;
45
+ let r = this.ctx.config.capture.fullUrls, i = r ? t : e(t), a = r ? n : e(n);
46
+ this.ctx.tracing.rotate("navigation"), this.ctx.breadcrumbs.push({
47
+ t: Date.now(),
48
+ category: "navigation",
49
+ message: `${i} -> ${a}`
50
+ }), this.ctx.logger.logEvent("NAVIGATION", { "page.url.previous": i });
51
+ };
52
+ installHistory() {
53
+ if (typeof history > "u" || this.originalPushState) return;
54
+ let e = n(), t = e.pushState, r = e.replaceState;
55
+ this.originalPushState = t, this.originalReplaceState = r;
56
+ let i = this.onNavigate;
57
+ e.pushState = function(...e) {
58
+ t.apply(this, e), queueMicrotask(i);
59
+ }, e.replaceState = function(...e) {
60
+ r.apply(this, e), queueMicrotask(i);
61
+ };
62
+ }
63
+ };
64
+ //#endregion
65
+ export { r as InteractionCapture };
66
+
67
+ //# sourceMappingURL=interactions-DZmLu7l2.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"interactions-DZmLu7l2.js","names":["stripUrlQuery","describeElement","element","tag","testId","label","classAttribute","historyMethods","InteractionCapture","ctx","target","event","selector","text","from","to","full","fromUrl","toUrl","originalPushState","originalReplaceState","onNavigate","args"],"sources":["../src/capture/interactions.ts"],"sourcesContent":["// src/capture/interactions.ts\n//\n// Captures clicks and in-page navigations as breadcrumbs and trace boundaries.\n\nimport { ARIA_LABEL_MAX_CHARS, CLICK_TEXT_MAX_CHARS, SELECTOR_MAX_CLASSES } from \"../constants\";\nimport { stripUrlQuery } from \"../utils/platform\";\nimport type { Capture, CaptureContext } from \"./types\";\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 | null): string {\n if (element === null) {\n return \"unknown\";\n }\n\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 /** Unpatched History.pushState implementation. */\n private originalPushState: HistoryMethods[\"pushState\"] | null = null;\n\n /** Unpatched History.replaceState implementation. */\n private originalReplaceState: HistoryMethods[\"replaceState\"] | null = null;\n\n /** Tracked URL prior to the latest navigation event. */\n private lastUrl = \"\";\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 /** Removes interaction listeners and restores native history methods. */\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 if (this.originalPushState) {\n historyMethods().pushState = this.originalPushState;\n }\n if (this.originalReplaceState) {\n historyMethods().replaceState = this.originalReplaceState;\n }\n this.originalPushState = null;\n this.originalReplaceState = null;\n }\n\n /** Rotates trace context and records a click breadcrumb. */\n private readonly onClick = (event: Event): void => {\n const target = event.target;\n const selector = describeElement(target instanceof Element ? target : null);\n // Use textContent, not innerText. A read of innerText causes style and layout work\n // at each click.\n const text =\n target instanceof HTMLElement ? target.textContent.trim().slice(0, CLICK_TEXT_MAX_CHARS) : \"\";\n\n // A click starts a new logical operation. All work that the click causes shares one\n // trace id. Without the rotation, one query cannot find a click and its API calls.\n this.ctx.tracing.rotate(\"interaction\");\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"click\",\n message: selector,\n data: text === \"\" ? undefined : { text },\n });\n };\n\n /** Rotates trace context and records a navigation breadcrumb and event on URL changes. */\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\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 fullUrls is set.\n const full = this.ctx.config.capture.fullUrls;\n const fromUrl = full ? from : stripUrlQuery(from);\n const toUrl = full ? to : stripUrlQuery(to);\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\" || this.originalPushState) {\n return;\n }\n\n // Keep the originals unbound and call them through apply. A read from History.prototype\n // skips a patch that a router installed on the instance. Uninstall then adds an own\n // property that was not there before.\n const target = historyMethods();\n const originalPushState = target.pushState;\n const originalReplaceState = target.replaceState;\n this.originalPushState = originalPushState;\n this.originalReplaceState = originalReplaceState;\n const onNavigate = this.onNavigate;\n\n target.pushState = function (this: History, ...args: never[]): void {\n originalPushState.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 queueMicrotask(onNavigate);\n };\n\n target.replaceState = function (this: History, ...args: never[]): void {\n originalReplaceState.apply(this, args);\n queueMicrotask(onNavigate);\n };\n }\n}\n"],"mappings":";;AAcA,SAASC,EAAgB,GAAiC;CACxD,IAAIC,MAAY,MACd,OAAO;CAGT,IAAMC,IAAMD,EAAQ,QAAQ,YAAY,GAElCE,IAASF,EAAQ,aAAa,aAAa,KAAKA,EAAQ,aAAa,cAAc;CACzF,IAAIE,MAAW,MACb,OAAO,iBAAiBA,EAAO;CAEjC,IAAIF,EAAQ,OAAO,IACj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record";
2
3
  /**
3
4
  * A batch of records with a stable id used for server-side deduplication across retries.
4
5
  * @see {@link splitBatch}
5
6
  */
6
7
  export interface LogBatch {
7
- /** Deduplication key. Stable across retries and reloads. */
8
+ /** Deduplication key. It stays the same across retries and reloads. */
8
9
  id: string;
9
10
  /** Records to deliver, in log order. */
10
11
  records: LogRecord[];
@@ -14,18 +15,20 @@ export interface LogBatch {
14
15
  attempts: number;
15
16
  }
16
17
  /**
17
- * Whether a value parsed out of storage carries the whole batch contract. An entry
18
- * missing `id` is never matched by `keyOf` after delivery, so it is retried forever
19
- * and blocks every batch behind it. One missing `attempts` counts as NaN, never
20
- * reaches `maxAttempts`, and is never dead-lettered.
18
+ * Tells whether a value from storage has all fields of a batch. `keyOf` cannot match
19
+ * an entry without `id` after delivery. The library then retries that entry with no
20
+ * end, and the entry blocks each batch behind it. An entry without `attempts` counts
21
+ * as NaN. That count never reaches `maxAttempts`. Thus the library never drops the
22
+ * entry as a dead letter.
21
23
  * @param value Parsed storage entry.
22
- * @returns True when every required field is present and correctly typed.
24
+ * @returns True when each required field is present and has the correct type.
23
25
  */
24
26
  export declare function isLogBatch(value: unknown): value is LogBatch;
25
27
  /**
26
- * Splits a batch the server rejected as too large into two halves.
27
- * Each half gets a fresh id; age and attempts carry over unchanged.
28
+ * Splits a batch that the server rejected as too large into two halves.
29
+ * Each half gets a new id. Each half keeps the age and attempts of the original batch.
28
30
  * @param batch The rejected batch.
31
+ * @param diagnostics Diagnostics reporter for the new batch ids.
29
32
  * @returns Two batches, or `null` if a single record is already over the limit.
30
33
  */
31
- export declare function splitBatch(batch: LogBatch): [LogBatch, LogBatch] | null;
34
+ export declare function splitBatch(batch: LogBatch, diagnostics: Diagnostics): [LogBatch, LogBatch] | null;
@@ -4,9 +4,9 @@ import type { LogRecord } from "./log-record";
4
4
  /** Delivery role indicating whether this context sends records directly or forwards upstream. */
5
5
  export type BusRole = "sender" | "forwarder";
6
6
  /**
7
- * Transport channel classification used to route incoming and outgoing bus
8
- * messages. If `receive` switches on the message alone and cannot tell the
9
- * channels apart, a same-origin iframe looks like a duplicated tab.
7
+ * Kind of transport channel. The bus uses it to route incoming and outgoing messages.
8
+ * Without it, `receive` cannot tell the channels apart. Then a same-origin iframe
9
+ * looks like a duplicated tab.
10
10
  */
11
11
  export type LinkKind =
12
12
  /** Synchronous call into a same-origin parent runtime. */
@@ -27,22 +27,21 @@ export type LinkKind =
27
27
  export interface MessageSource {
28
28
  /** Inbound transport channel kind. */
29
29
  link: LinkKind;
30
- /** `event.origin` for `parent` and `children`; otherwise `"same-origin"` or `"openfin"`. */
30
+ /** `event.origin` for `parent` and `children`. Other links use `"same-origin"` or `"openfin"`. */
31
31
  origin: string;
32
32
  }
33
33
  /** Discriminated union of control and telemetry payload messages. */
34
34
  export type BusMessage =
35
- /** Handshake discovery announcement from a booting forwarder. */
35
+ /** Handshake discovery announcement from a starting forwarder. */
36
36
  {
37
37
  t: "hello";
38
38
  from: string;
39
39
  tabId: string;
40
40
  }
41
41
  /**
42
- * Handshake response acknowledging an upstream owner relationship. Addressed
43
- * through `to`: a welcome published over InterApplicationBus reaches every
44
- * subscriber, so an unaddressed one lets three waiting views each conclude
45
- * it has found an owner of its own.
42
+ * Handshake response from an upstream owner. The `to` field holds the address.
43
+ * A welcome on InterApplicationBus goes to every subscriber. Without an address,
44
+ * each waiting view accepts the welcome as its own.
46
45
  */
47
46
  | {
48
47
  t: "welcome";
@@ -87,10 +86,10 @@ export interface BusEnvelope {
87
86
  */
88
87
  export declare function envelope(message: BusMessage): BusEnvelope;
89
88
  /**
90
- * Validates protocol tags and unpacks raw payloads into bus messages. A
91
- * document receives `message` events from every embedded thing on the page,
92
- * including analytics tags, video players and extensions. Without the tag
93
- * check a video player's message is parsed as a log record.
89
+ * Validates the protocol tag and unpacks a raw payload into a bus message. A
90
+ * document gets `message` events from all embedded content on the page. This
91
+ * includes analytics tags, video players and extensions. Without the tag check,
92
+ * the bus parses a message from a video player as a log record.
94
93
  * @param data Raw payload received over a transport link.
95
94
  * @returns Validated message, or null if payload is invalid or unrecognized.
96
95
  */