@yaks/tracker 0.0.0-stage → 0.2.36

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 (198) hide show
  1. package/Histogram.js +71 -0
  2. package/Histogram.js.map +1 -0
  3. package/Histogram.ts +100 -0
  4. package/LICENSE +202 -0
  5. package/README.md +639 -2
  6. package/_dist/brief.d.ts +25 -0
  7. package/_dist/brief.d.ts.map +1 -0
  8. package/_dist/changes.d.ts +9 -0
  9. package/_dist/changes.d.ts.map +1 -0
  10. package/_dist/chart.d.ts +24 -0
  11. package/_dist/chart.d.ts.map +1 -0
  12. package/_dist/digest.d.ts +64 -0
  13. package/_dist/digest.d.ts.map +1 -0
  14. package/_dist/effects.d.ts +73 -0
  15. package/_dist/effects.d.ts.map +1 -0
  16. package/_dist/errors.d.ts +14 -0
  17. package/_dist/errors.d.ts.map +1 -0
  18. package/_dist/everywhere.d.ts +13 -0
  19. package/_dist/everywhere.d.ts.map +1 -0
  20. package/_dist/fault.d.ts +29 -0
  21. package/_dist/fault.d.ts.map +1 -0
  22. package/_dist/file.d.ts +6 -0
  23. package/_dist/file.d.ts.map +1 -0
  24. package/_dist/fixtime.d.ts +20 -0
  25. package/_dist/fixtime.d.ts.map +1 -0
  26. package/_dist/frames.d.ts +6 -0
  27. package/_dist/frames.d.ts.map +1 -0
  28. package/_dist/graph.d.ts +3 -0
  29. package/_dist/graph.d.ts.map +1 -0
  30. package/_dist/group.d.ts +21 -0
  31. package/_dist/group.d.ts.map +1 -0
  32. package/_dist/instrument.d.ts +37 -0
  33. package/_dist/instrument.d.ts.map +1 -0
  34. package/_dist/intake.d.ts +21 -0
  35. package/_dist/intake.d.ts.map +1 -0
  36. package/_dist/merge.d.ts +11 -0
  37. package/_dist/merge.d.ts.map +1 -0
  38. package/_dist/mod.d.ts +7 -0
  39. package/_dist/mod.d.ts.map +1 -0
  40. package/_dist/model.d.ts +20 -0
  41. package/_dist/model.d.ts.map +1 -0
  42. package/_dist/outage.d.ts +7 -0
  43. package/_dist/outage.d.ts.map +1 -0
  44. package/_dist/people.d.ts +3 -0
  45. package/_dist/people.d.ts.map +1 -0
  46. package/_dist/poll.d.ts +101 -0
  47. package/_dist/poll.d.ts.map +1 -0
  48. package/_dist/poll_thread.d.ts +8 -0
  49. package/_dist/poll_thread.d.ts.map +1 -0
  50. package/_dist/reading.d.ts +34 -0
  51. package/_dist/reading.d.ts.map +1 -0
  52. package/_dist/remote.d.ts +61 -0
  53. package/_dist/remote.d.ts.map +1 -0
  54. package/_dist/report.d.ts +324 -0
  55. package/_dist/report.d.ts.map +1 -0
  56. package/_dist/resolution.d.ts +22 -0
  57. package/_dist/resolution.d.ts.map +1 -0
  58. package/_dist/routes.d.ts +33 -0
  59. package/_dist/routes.d.ts.map +1 -0
  60. package/_dist/script.d.ts +8 -0
  61. package/_dist/script.d.ts.map +1 -0
  62. package/_dist/service.d.ts +30 -0
  63. package/_dist/service.d.ts.map +1 -0
  64. package/_dist/sync_health.d.ts +4 -0
  65. package/_dist/sync_health.d.ts.map +1 -0
  66. package/_dist/ticket.d.ts +14 -0
  67. package/_dist/ticket.d.ts.map +1 -0
  68. package/_dist/tools.d.ts +39 -0
  69. package/_dist/tools.d.ts.map +1 -0
  70. package/_dist/trace-intake.d.ts +25 -0
  71. package/_dist/trace-intake.d.ts.map +1 -0
  72. package/_dist/views.d.ts +11 -0
  73. package/_dist/views.d.ts.map +1 -0
  74. package/_dist/vocab.d.ts +9 -0
  75. package/_dist/vocab.d.ts.map +1 -0
  76. package/box.json +51 -0
  77. package/brief.js +86 -0
  78. package/brief.js.map +1 -0
  79. package/brief.ts +120 -0
  80. package/changes.js +57 -0
  81. package/changes.js.map +1 -0
  82. package/changes.ts +70 -0
  83. package/chart.js +186 -0
  84. package/chart.js.map +1 -0
  85. package/chart.ts +193 -0
  86. package/deno.json +1 -0
  87. package/digest.js +329 -0
  88. package/digest.js.map +1 -0
  89. package/digest.ts +406 -0
  90. package/effects.js +136 -0
  91. package/effects.js.map +1 -0
  92. package/effects.ts +178 -0
  93. package/errors.js +130 -0
  94. package/errors.js.map +1 -0
  95. package/errors.ts +185 -0
  96. package/everywhere.js +46 -0
  97. package/everywhere.js.map +1 -0
  98. package/everywhere.ts +66 -0
  99. package/fault.js +65 -0
  100. package/fault.js.map +1 -0
  101. package/fault.ts +107 -0
  102. package/file.js +87 -0
  103. package/file.js.map +1 -0
  104. package/file.ts +93 -0
  105. package/fixtime.js +67 -0
  106. package/fixtime.js.map +1 -0
  107. package/fixtime.ts +86 -0
  108. package/frames.js +77 -0
  109. package/frames.js.map +1 -0
  110. package/frames.ts +69 -0
  111. package/graph.js +7 -0
  112. package/graph.js.map +1 -0
  113. package/graph.ts +8 -0
  114. package/group.js +444 -0
  115. package/group.js.map +1 -0
  116. package/group.ts +533 -0
  117. package/inspect.js +471 -0
  118. package/inspect.js.map +1 -0
  119. package/inspect.ts +693 -0
  120. package/instrument.js +69 -0
  121. package/instrument.js.map +1 -0
  122. package/instrument.ts +93 -0
  123. package/intake.js +43 -0
  124. package/intake.js.map +1 -0
  125. package/intake.ts +84 -0
  126. package/merge.js +126 -0
  127. package/merge.js.map +1 -0
  128. package/merge.ts +115 -0
  129. package/migrate.ts +36 -0
  130. package/mod.js +8 -0
  131. package/mod.js.map +1 -0
  132. package/mod.ts +19 -0
  133. package/model.js +8 -0
  134. package/model.js.map +1 -0
  135. package/model.ts +27 -0
  136. package/outage.js +129 -0
  137. package/outage.js.map +1 -0
  138. package/outage.ts +158 -0
  139. package/package.json +133 -4
  140. package/page.d.ts +2 -0
  141. package/page.js +905 -0
  142. package/people.js +51 -0
  143. package/people.js.map +1 -0
  144. package/people.ts +82 -0
  145. package/poll.js +277 -0
  146. package/poll.js.map +1 -0
  147. package/poll.ts +411 -0
  148. package/poll_thread.js +104 -0
  149. package/poll_thread.js.map +1 -0
  150. package/poll_thread.ts +126 -0
  151. package/poll_worker.ts +45 -0
  152. package/reading.js +122 -0
  153. package/reading.js.map +1 -0
  154. package/reading.ts +162 -0
  155. package/reconcile.js +113 -0
  156. package/reconcile.js.map +1 -0
  157. package/reconcile.ts +130 -0
  158. package/remote.js +312 -0
  159. package/remote.js.map +1 -0
  160. package/remote.ts +397 -0
  161. package/report.js +825 -0
  162. package/report.js.map +1 -0
  163. package/report.ts +944 -0
  164. package/resolution.js +114 -0
  165. package/resolution.js.map +1 -0
  166. package/resolution.ts +123 -0
  167. package/routes.js +130 -0
  168. package/routes.js.map +1 -0
  169. package/routes.ts +163 -0
  170. package/script.js +13 -0
  171. package/script.js.map +1 -0
  172. package/script.ts +16 -0
  173. package/service.js +174 -0
  174. package/service.js.map +1 -0
  175. package/service.ts +215 -0
  176. package/spread.js +94 -0
  177. package/spread.js.map +1 -0
  178. package/spread.ts +101 -0
  179. package/sync_health.js +36 -0
  180. package/sync_health.js.map +1 -0
  181. package/sync_health.ts +65 -0
  182. package/ticket.js +6 -0
  183. package/ticket.js.map +1 -0
  184. package/ticket.ts +24 -0
  185. package/tools.js +305 -0
  186. package/tools.js.map +1 -0
  187. package/tools.ts +411 -0
  188. package/trace-intake.js +164 -0
  189. package/trace-intake.js.map +1 -0
  190. package/trace-intake.ts +148 -0
  191. package/views.js +247 -0
  192. package/views.js.map +1 -0
  193. package/views.ts +254 -0
  194. package/vocab.js +20 -0
  195. package/vocab.js.map +1 -0
  196. package/vocab.json +834 -0
  197. package/vocab.ts +14 -0
  198. package/yak-tracker@.service +22 -0
package/report.ts ADDED
@@ -0,0 +1,944 @@
1
+ // Reporting hands scrubbed bundles to a generic sink. Neither capture nor a
2
+ // failed sink can change the caller's result; fallback never calls the reporter.
3
+
4
+ import type { Actor, Bundle } from 'jsr:@yaks/graph@0.2.36'
5
+ import { status, unheard } from '@yaks/graph/errors'
6
+ import { comp, type Crumb, type Level, str } from './model.js'
7
+ import { faultOf, rerunOf } from './fault.js'
8
+ export { faultOf, normalize } from './fault.js'
9
+
10
+ let PAGE_ID = '[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}'
11
+ let PAGE_REQUEST = new RegExp(`^${PAGE_ID}$`)
12
+ let PAGE_RETRY = new RegExp(`^${PAGE_ID}:[1-9]\\d{0,2}:\\d{1,5}$`)
13
+
14
+ /** Browser request correlation, with only the shapes the page emits. */
15
+ export let pageAttempt = (
16
+ id?: string | null,
17
+ retry?: string | null,
18
+ ): { page_request: string; page_retry?: string } | undefined =>
19
+ id && PAGE_REQUEST.test(id)
20
+ ? {
21
+ page_request: id,
22
+ ...retry && PAGE_RETRY.test(retry) ? { page_retry: retry } : {},
23
+ }
24
+ : undefined
25
+
26
+ export type Sink = (rows: Bundle[]) => void | Promise<void>
27
+ export type Context = {
28
+ sink: Sink
29
+ actor?: Actor
30
+ eid?: string
31
+ at?: string
32
+ /** start of the observation window when a failure was measured over time */
33
+ windowStart?: string
34
+ level?: Level
35
+ /** the bug this files under; default the error's own `fault`, if it names
36
+ * one, else one derived from its kind, message and top frame */
37
+ fault?: string
38
+ commit?: string
39
+ version?: number
40
+ environment?: 'production' | 'staging'
41
+ tags?: Record<string, unknown>
42
+ during?: {
43
+ entity?: string
44
+ kind?: string
45
+ app?: string
46
+ space?: string
47
+ session?: string
48
+ process?: string
49
+ request?: string
50
+ }
51
+ mechanism?:
52
+ | 'catch'
53
+ | 'wrapper'
54
+ | 'onerror'
55
+ | 'onunhandledrejection'
56
+ | 'console'
57
+ | 'loading'
58
+ breadcrumbs?: Crumb[]
59
+ request?: Bundle
60
+ fallback?: Sink
61
+ }
62
+
63
+ // The header an agent's call names its session in (@yaks/api `VIA`): the
64
+ // fleet's own sessions send it, so a failure one of them caused says so.
65
+ let VIA = 'x-via'
66
+
67
+ /** Runtime provenance uses the same request association on every reporting path.
68
+ * Non-HTTP entries name their operation without inventing an HTTP request.
69
+ * A request naming its session in `x-via` is tagged `via`: one of our own
70
+ * agents made it. */
71
+ export let origin = (
72
+ script: string,
73
+ version: string | undefined,
74
+ entrypoint: string,
75
+ request?: Request,
76
+ eid: string = crypto.randomUUID(),
77
+ ): Pick<Context, 'tags' | 'commit' | 'during' | 'request'> => {
78
+ let via = request?.headers.get(VIA)
79
+ return {
80
+ tags: {
81
+ script,
82
+ version: version ?? 'unknown',
83
+ entrypoint,
84
+ ...via ? { via } : {},
85
+ },
86
+ commit: version,
87
+ during: { request: eid },
88
+ request: {
89
+ entity: { eid },
90
+ request: {
91
+ route: entrypoint,
92
+ ...request ? { method: request.method, url: request.url } : {},
93
+ },
94
+ },
95
+ }
96
+ }
97
+
98
+ /** A caller that hung up, in the words of the Workers runtime.
99
+ *
100
+ * ```ts
101
+ * import { ok } from '@yaks/testing'
102
+ * import { disconnected } from '@yaks/tracker/report'
103
+ * ok(disconnected(new TypeError(
104
+ * "Can't read from request stream because client disconnected.",
105
+ * )))
106
+ * ok(disconnected(new DOMException('The client has disconnected', 'AbortError')))
107
+ * ok(!disconnected(new DOMException('The operation was aborted', 'AbortError')))
108
+ * ok(!disconnected(new TypeError('x is undefined')))
109
+ * ```
110
+ */
111
+ export let disconnected = (error: unknown): boolean =>
112
+ error instanceof Error && (
113
+ error.name == 'AbortError' &&
114
+ error.message == 'The client has disconnected' ||
115
+ error instanceof TypeError &&
116
+ error.message ==
117
+ "Can't read from request stream because client disconnected."
118
+ )
119
+
120
+ /** Refusals are control flow, not tracked mistakes, and neither is a caller
121
+ * that hung up, nor a service that did not answer for now (@yaks/graph
122
+ * `unheard`), which is asked again: only one that stays slow is reported,
123
+ * by whoever watches it. Hosts can exclude their own accepted/deferred
124
+ * operation before calling caught. */
125
+ export let refused = (error: unknown): boolean => {
126
+ let e = error && typeof error == 'object' ? error : {}
127
+ let named = 'name' in e ? e.name : ''
128
+ let code = 'status' in e ? e.status : undefined
129
+ return named == 'CallError' || status(error) < 500 || unheard(error) ||
130
+ (typeof code == 'number' && code >= 400 && code < 500) ||
131
+ disconnected(error)
132
+ }
133
+
134
+ // The credentials an address carries, each with what stands in its place: a
135
+ // page token or a link's code in a `~` segment, a sealed ticket after
136
+ // `_preview/` (@yaks/platform/routes `paged`), the user and password before
137
+ // a host, and a query parameter named for a secret.
138
+ let CARRIED: [RegExp, string][] = [
139
+ [/\/(~|_preview\/)[^/\s?#'"`<>()]+/g, '/$1token'],
140
+ [/(\w+:\/\/)[^/\s@:'"`<>()]+:[^/\s@'"`<>()]*@/g, '$1redacted@'],
141
+ [
142
+ /([?&;](?:[\w.-]*[_.-])?(?:token|key|apikey|secret|sig|signature|pass|password|auth|credential|ticket|code)=)[^&#\s'"`<>()]*/gi,
143
+ '$1redacted',
144
+ ],
145
+ ]
146
+
147
+ /** `text` with every credential an address in it carries out of sight. A
148
+ * failure quotes the addresses it asked, and the credential in one opens
149
+ * what it guards to whoever reads the bug.
150
+ *
151
+ * ```ts
152
+ * import { equal } from '@yaks/testing'
153
+ * import { redacted } from '@yaks/tracker/report'
154
+ *
155
+ * equal(
156
+ * redacted('/emberwild/~eyJhIjoxfQ.c2ln/trail: signal timed out'),
157
+ * '/emberwild/~token/trail: signal timed out',
158
+ * )
159
+ * equal(redacted('at https://ada.yaks.app/~abc.def/api/query'), 'at https://ada.yaks.app/~token/api/query')
160
+ * equal(redacted('/cookbook/_preview/t.mac/about'), '/cookbook/_preview/token/about')
161
+ * equal(redacted('GET https://bo:pw@host/x?page=2&access_token=s3'), 'GET https://redacted@host/x?page=2&access_token=redacted')
162
+ * equal(redacted('/b.js?X-Amz-Signature=f0&transform.bytecode=1'), '/b.js?X-Amz-Signature=redacted&transform.bytecode=1')
163
+ * equal(redacted('2 ~ 3, /home/ and /cookbook/_preview'), '2 ~ 3, /home/ and /cookbook/_preview')
164
+ * ```
165
+ */
166
+ export let redacted = (text: string): string =>
167
+ CARRIED.reduce((out, [carried, shown]) => out.replace(carried, shown), text)
168
+
169
+ let unseen = (value: unknown): unknown =>
170
+ typeof value == 'string'
171
+ ? redacted(value)
172
+ : Array.isArray(value)
173
+ ? value.map(unseen)
174
+ : value && typeof value == 'object'
175
+ ? Object.fromEntries(
176
+ Object.entries(value).map(([key, v]) => [key, unseen(v)]),
177
+ )
178
+ : value
179
+
180
+ /** `row` with every credential an address carries ({@link redacted}) out of
181
+ * each of its components: what capture keeps, and what a row captured
182
+ * before it kept them is scrubbed to. Its eid and stamps stand.
183
+ *
184
+ * ```ts
185
+ * import { equal } from '@yaks/testing'
186
+ * import { withheld } from '@yaks/tracker/report'
187
+ *
188
+ * equal(
189
+ * withheld({ entity: { eid: 'e' }, request: { url: 'https://a.test/x/~s.t/y' } }),
190
+ * { entity: { eid: 'e' }, request: { url: 'https://a.test/x/~token/y' } },
191
+ * )
192
+ * ```
193
+ */
194
+ export let withheld = (row: Bundle): Bundle =>
195
+ Object.fromEntries(
196
+ Object.entries(row).map(([name, c]) =>
197
+ name == 'entity' || name.startsWith('$') ? [name, c] : [name, unseen(c)]
198
+ ),
199
+ ) as Bundle
200
+
201
+ /** No request query, headers, body, cookies, or console arguments leave, and
202
+ * no credential an address carries ({@link redacted}), in any component. */
203
+ export let scrub = (rows: Bundle[]): Bundle[] =>
204
+ rows.map((row) => {
205
+ let out = { ...row }
206
+ if (out.request && typeof out.request == 'object') {
207
+ let { method, url, route, status, ms, agent } = comp(out, 'request')
208
+ out.request = {
209
+ method,
210
+ url: typeof url == 'string' ? url.split(/[?#]/)[0] : url,
211
+ route,
212
+ status,
213
+ ms,
214
+ agent,
215
+ }
216
+ }
217
+ if (out.error && typeof out.error == 'object') {
218
+ let tags = comp(out, 'error').tags
219
+ if (tags && typeof tags == 'object' && !Array.isArray(tags)) {
220
+ let safe = Object.fromEntries(
221
+ Object.entries(tags)
222
+ .filter(([key]) => key != 'arguments'),
223
+ )
224
+ out.error = { ...comp(out, 'error'), tags: safe }
225
+ }
226
+ }
227
+ return withheld(out)
228
+ })
229
+
230
+ let json = (value: object): string => {
231
+ try {
232
+ return (JSON.stringify(value) ?? String(value)).slice(0, 1000)
233
+ } catch {
234
+ return String(value)
235
+ }
236
+ }
237
+
238
+ // The stack below this module's outermost door, where a value was reported.
239
+ // The cut is by function, never by file: a Worker bundles every module into
240
+ // one file, where import.meta.url names none of them. A door not on the stack
241
+ // leaves no frames. V8 and JavaScriptCore cut; their types do not declare it,
242
+ // and a runtime without it leaves no stack.
243
+ let cut: unknown = Reflect.get(Error, 'captureStackTrace')
244
+ let below = (): string => {
245
+ if (typeof cut != 'function') return ''
246
+ for (let door of [caught, report, capture, described]) {
247
+ let at: { stack?: string } = {}
248
+ cut.call(Error, at, door)
249
+ let frames = (at.stack ?? '').split('\n').slice(1).join('\n')
250
+ if (frames) return frames
251
+ }
252
+ return ''
253
+ }
254
+
255
+ // What an Error was wrapped around, down its `cause` chain and into each of
256
+ // an AggregateError's `errors`: each link's stack (which opens with its name
257
+ // and message), else the value itself, once however many links repeat it. A
258
+ // wrapper says what it was doing; the chain says why it failed.
259
+ let causes = (error: Error): string => {
260
+ let out: string[] = []
261
+ let seen = new Set<unknown>([error])
262
+ let inner = (e: unknown): unknown[] =>
263
+ e instanceof Error
264
+ ? [e.cause, ...e instanceof AggregateError ? e.errors : []]
265
+ : []
266
+ for (let queue = inner(error); queue.length && out.length < 5;) {
267
+ let c = queue.shift()
268
+ if (c == null || seen.has(c)) continue
269
+ seen.add(c)
270
+ let text = c instanceof Error
271
+ ? c.stack || `${c.name}: ${c.message}`
272
+ : json1(c)
273
+ if (!out.includes(text)) out.push(text)
274
+ queue.unshift(...inner(c))
275
+ }
276
+ return out.join('\nCaused by: ')
277
+ }
278
+
279
+ // What an Error says about itself beyond its message: its own enumerable
280
+ // properties, such as the statement SQLite would not compile (@yaks/sqlite
281
+ // `prepared`). Its fault names its bug already.
282
+ let detail = (error: Error): string => {
283
+ let own = Object.entries(error).filter(([k]) => k != 'fault')
284
+ return own.length ? `Details: ${json(Object.fromEntries(own))}` : ''
285
+ }
286
+
287
+ let json1 = (v: unknown): string =>
288
+ typeof v == 'object' && v ? json(v) : String(v)
289
+
290
+ /** What a thrown value says it is. An Error says so itself. Any other object
291
+ * (a refusal's `{error, message}`, a plain `{code, …}`) says its own name and
292
+ * message, or its JSON, never `[object Object]`; it carries no stack, so the
293
+ * stack is where it was reported from. A string or number is its message.
294
+ *
295
+ * ```ts
296
+ * import { equal, ok } from '@yaks/testing'
297
+ * import { described } from '@yaks/tracker/report'
298
+ *
299
+ * equal(described({ error: 'Refused', message: 'no' })?.type, 'Refused')
300
+ * equal(described({ id: 7 })?.value, '{"id":7}')
301
+ * equal(described('broken'), undefined)
302
+ * let wrapped = new Error('could not take', { cause: new Error('refused') })
303
+ * ok(described(wrapped)?.cause?.startsWith('Error: refused'))
304
+ * let locked = Array.from({ length: 2 }, () => new Error('database is locked'))
305
+ * let many = new AggregateError([...locked, new Error('no such table')], '3 failed')
306
+ * equal(described(many)?.cause?.split('\nCaused by: ').map((c) => c.split('\n')[0]), [
307
+ * 'Error: database is locked',
308
+ * 'Error: no such table',
309
+ * ])
310
+ * let failed = Object.assign(new Error('no such table: t'), { statement: 'select 1 from t' })
311
+ * equal(described(failed)?.cause, 'Details: {"statement":"select 1 from t"}')
312
+ * ```
313
+ */
314
+ export let described = (
315
+ error: unknown,
316
+ ):
317
+ | { type: string; value: string; stack?: string; cause?: string }
318
+ | undefined => {
319
+ if (error instanceof Error) {
320
+ let cause = [causes(error), detail(error)].filter(Boolean).join('\n')
321
+ return {
322
+ type: error.name,
323
+ value: error.message,
324
+ ...error.stack ? { stack: error.stack } : {},
325
+ ...cause ? { cause } : {},
326
+ }
327
+ }
328
+ if (!error || typeof error != 'object') return undefined
329
+ let own = error as Record<string, unknown>
330
+ let named = [own.name, own.error, own.code]
331
+ .find((v): v is string => typeof v == 'string' && v != '')
332
+ let stack = below()
333
+ return {
334
+ type: named ?? error.constructor?.name ?? 'Object',
335
+ value: typeof own.message == 'string' ? own.message : json(error),
336
+ ...stack ? { stack: `${named ?? 'Object'}\n${stack}` } : {},
337
+ }
338
+ }
339
+
340
+ // The fault a failure names for itself, wherever it is caught: one cause met
341
+ // by many callers is one bug.
342
+ let named = (error: unknown) => {
343
+ let fault = error && typeof error == 'object'
344
+ ? (error as { fault?: unknown }).fault
345
+ : undefined
346
+ return typeof fault == 'string' ? fault : undefined
347
+ }
348
+
349
+ export let capture = (error: unknown, context: Context): Bundle[] => {
350
+ let shown = described(error)
351
+ let fault = context.fault ?? named(error)
352
+ let row: Bundle = {
353
+ entity: { eid: context.eid ?? crypto.randomUUID() },
354
+ ...context.actor ? { $actor: context.actor } : {},
355
+ error: {
356
+ at: context.at ?? new Date().toISOString(),
357
+ ...context.windowStart ? { window_start: context.windowStart } : {},
358
+ level: context.level ?? 'error',
359
+ ...error instanceof Error
360
+ ? {}
361
+ : { message: shown ? `${shown.type}: ${shown.value}` : String(error) },
362
+ ...fault ? { fault } : {},
363
+ ...context.commit ? { commit: context.commit } : {},
364
+ ...context.version != null ? { version: context.version } : {},
365
+ ...context.environment ? { environment: context.environment } : {},
366
+ ...context.tags ? { tags: context.tags } : {},
367
+ },
368
+ ...shown
369
+ ? { exception: { ...shown, mechanism: context.mechanism ?? 'catch' } }
370
+ : {},
371
+ ...context.during ? { during: context.during } : {},
372
+ ...context.breadcrumbs
373
+ ? {
374
+ breadcrumbs: { items: context.breadcrumbs.slice(-20) },
375
+ }
376
+ : {},
377
+ }
378
+ return scrub([row, ...context.request ? [context.request] : []])
379
+ }
380
+
381
+ export let report = async (error: unknown, context: Context): Promise<void> => {
382
+ let rows: Bundle[] = []
383
+ try {
384
+ rows = capture(error, context)
385
+ await context.sink(rows)
386
+ } catch {
387
+ try {
388
+ await (context.fallback ?? consoleRows)(rows)
389
+ } catch { /* no recursion */ }
390
+ }
391
+ }
392
+ let consoleRows: Sink = (rows) => console.error(JSON.stringify(rows))
393
+ export let caught = (error: unknown, context: Context): Promise<void> => {
394
+ try {
395
+ // A refusal is control flow only where someone catches it: one that
396
+ // escaped as an uncaught error or a rejection nobody held answered no one.
397
+ let stray = context.mechanism == 'onerror' ||
398
+ context.mechanism == 'onunhandledrejection'
399
+ return !stray && refused(error) ? Promise.resolve() : report(error, context)
400
+ } catch {
401
+ return Promise.resolve()
402
+ }
403
+ }
404
+
405
+ /** One break a page reported to its door: the page reporter's own body
406
+ * (./page), an entry the browser's Reporting API sent, or a native shell's,
407
+ * which names itself by `type` and says what it runs in its `tags`. */
408
+ export type Break = {
409
+ /** the page's release, when its reporter said which it loaded */
410
+ version: number | null
411
+ /** the platform deployment that drew the page, when it named one */
412
+ deployment?: string
413
+ /** `page /path`, or the Reporting API's type and the page's path */
414
+ request: string
415
+ message: string
416
+ stack: string
417
+ /** what the error was wrapped around, down its `cause` chain */
418
+ cause?: string
419
+ mechanism?: Mechanism
420
+ breadcrumbs?: Crumb[]
421
+ /** the file the reporter named apart from its page: for a resource that
422
+ * failed to load, the one that was refused */
423
+ file?: string
424
+ /** the browser that sent it, its user agent ({@link received}) */
425
+ agent?: string
426
+ /** what its sender says of itself, which its door decides whether to keep:
427
+ * a native shell's variant and the update it runs */
428
+ tags?: Record<string, string>
429
+ }
430
+ type Mechanism = NonNullable<Context['mechanism']>
431
+ let MECHANISMS = new Set<unknown>([
432
+ 'catch',
433
+ 'wrapper',
434
+ 'onerror',
435
+ 'onunhandledrejection',
436
+ 'console',
437
+ 'loading',
438
+ ])
439
+
440
+ // What one report says broke, in whatever words its sender has: the page
441
+ // reporter's `message`, or the fields the Reporting API fills in for a CSP
442
+ // violation, a crash, a deprecation, a network error.
443
+ let saying = (b: Record<string, unknown>) =>
444
+ String(
445
+ b.message ??
446
+ [b.type, b.effectiveDirective, b.blockedURL, b.statusCode, b.phase]
447
+ .filter(Boolean).join(' '),
448
+ ).slice(0, 4000)
449
+
450
+ let pathOf = (url: unknown) => {
451
+ try {
452
+ return new URL(String(url)).pathname
453
+ } catch {
454
+ return String(url ?? '')
455
+ }
456
+ }
457
+
458
+ let crumbs = (sent: unknown): Crumb[] | undefined => {
459
+ if (!Array.isArray(sent)) return undefined
460
+ let kept = sent.slice(-20).flatMap((c) =>
461
+ c && typeof c == 'object' && typeof c.at == 'string' &&
462
+ typeof c.category == 'string' && typeof c.message == 'string'
463
+ ? [{
464
+ at: c.at,
465
+ category: c.category.slice(0, 100),
466
+ message: c.message.slice(0, 2000),
467
+ }]
468
+ : []
469
+ )
470
+ return kept.length ? kept : undefined
471
+ }
472
+
473
+ let tagged = (sent: unknown): Record<string, string> | undefined => {
474
+ if (!sent || typeof sent != 'object' || Array.isArray(sent)) return undefined
475
+ let kept = Object.entries(sent).filter(([k, v]) =>
476
+ typeof v == 'string' && v && k.length <= 40
477
+ ).slice(0, 12).map(([k, v]) => [k, (v as string).slice(0, 500)])
478
+ return kept.length ? Object.fromEntries(kept) : undefined
479
+ }
480
+
481
+ // The header a server sets on an answer whose failure it has already reported,
482
+ // where it caught it (@yaks/api `FILED`): the page reporter carries it as
483
+ // `filed`, and {@link broken} files that answer no second time.
484
+ export { FILED } from '@yaks/api/refuse'
485
+
486
+ // A fetch of the page's own origin that never had an answer, as the reporter's
487
+ // fetch wrapper says it (`<path>: <message>`) in the words of the browser that
488
+ // asked: Chrome, Safari, Firefox. That is the connection dropping or the person
489
+ // leaving, never a break, and the wrapper has let it go since T-124729. But the
490
+ // reporter is woven into each page as it loads, and a tab opened before then,
491
+ // or a copy the browser reopened from its cache, still runs the one that filed
492
+ // it: untagged, or as the app logged or dropped the same rejection, where the
493
+ // message is the browser's bare words and the wrapper's last crumb says which
494
+ // request had no answer, or as the page caught it, after the place it names.
495
+ // The judgment is kept here too, where every reporter's report arrives. An
496
+ // answer of any status is not this, and neither is a fetch of another origin,
497
+ // which leaves no crumb.
498
+ let NO_ANSWER =
499
+ /^\/\S*: (?:Failed to fetch|Load failed|NetworkError when attempting to fetch resource\.)$/
500
+ let unanswered = (b: Record<string, unknown>) => {
501
+ let message = String(b.message ?? '')
502
+ if (b.mechanism == null || b.mechanism == 'wrapper') {
503
+ return NO_ANSWER.test(message)
504
+ }
505
+ let place = (b.tags as Record<string, unknown> | undefined)?.place
506
+ let own = b.mechanism == 'catch' && typeof place == 'string' &&
507
+ message.startsWith(`${place}: `)
508
+ ? message.slice(place.length + 2)
509
+ : message.replace(/^unhandled rejection: /, '')
510
+ let last = crumbs(b.breadcrumbs)?.findLast((c) => c.category == 'fetch')
511
+ return !!last && NO_ANSWER.test(last.message) &&
512
+ last.message.endsWith(`: ${own}`)
513
+ }
514
+
515
+ /** A no the page was answered on purpose: a 4xx status. */
516
+ export let meant = (_answer: string, status: number): boolean =>
517
+ status >= 400 && status < 500
518
+
519
+ /**
520
+ * The breaks a page's report door was sent, out of either body: the page
521
+ * reporter's `{message, stack?, cause?, url?, page?, line?, status?, answer?,
522
+ * mechanism?, version?, breadcrumbs?}`, or the Reporting API's array of `{type, url,
523
+ * body}`. A native shell sends the reporter's, naming itself as `type` and
524
+ * adding `tags` of its own. Junk answers with nothing: a malformed body is the sender's bug, not
525
+ * a break in the page. An answer the reporter saw that `refusal` calls a no
526
+ * somebody meant (default {@link meant}) is the page working, not a break,
527
+ * and so is a fetch of the page's own origin that had no answer, which an older
528
+ * reporter, in a tab left open or a copy reopened from the cache, still sends.
529
+ *
530
+ * ```ts
531
+ * import { equal } from '@yaks/testing'
532
+ * import { broken } from '@yaks/tracker/report'
533
+ *
534
+ * let [one] = broken(JSON.stringify({
535
+ * message: 'x is undefined',
536
+ * url: 'https://box.test/T-9',
537
+ * mechanism: 'onerror',
538
+ * }))
539
+ * equal([one.request, one.message, one.mechanism], [
540
+ * 'page /T-9',
541
+ * 'x is undefined',
542
+ * 'onerror',
543
+ * ])
544
+ * let [missed] = broken(JSON.stringify({
545
+ * message: 'failed to load img https://box.test/a.webp',
546
+ * url: 'https://box.test/a.webp',
547
+ * page: 'https://box.test/T-9',
548
+ * }))
549
+ * equal([missed.request, missed.file], ['page /T-9', 'https://box.test/a.webp'])
550
+ * let [wrapped] = broken(JSON.stringify({
551
+ * message: 'live client — Dropped: wss://box.test/ws closed (1006)',
552
+ * cause: 'it has not reopened: 7 attempts',
553
+ * mechanism: 'console',
554
+ * }))
555
+ * equal(wrapped.cause, 'it has not reopened: 7 attempts')
556
+ * let [shell] = broken(JSON.stringify({
557
+ * type: 'shell',
558
+ * message: 'no store',
559
+ * page: 'https://yaks.app/manage/ada/operator',
560
+ * tags: { variant: 'yaks-app', update: 'u1', bad: 7 },
561
+ * }))
562
+ * equal([shell.request, shell.tags], [
563
+ * 'shell /manage/ada/operator',
564
+ * { variant: 'yaks-app', update: 'u1' },
565
+ * ])
566
+ * equal(broken(JSON.stringify({ message: '403 /apply', status: 403 })), [])
567
+ * equal(broken(JSON.stringify({ message: '502 /x', status: 502, filed: true })), [])
568
+ * let fetched = (message: string) =>
569
+ * broken(JSON.stringify({ message, url: 'https://box.test/app/' })).length
570
+ * equal([
571
+ * fetched('/app/api/release: Failed to fetch'),
572
+ * fetched('/app/api/release: Load failed'),
573
+ * fetched('/app/api/query: signal timed out'),
574
+ * ], [0, 0, 1])
575
+ * let logged = (asked: string) =>
576
+ * broken(JSON.stringify({
577
+ * message: 'Failed to fetch',
578
+ * mechanism: 'console',
579
+ * breadcrumbs: [{ at: '2026-10-31', category: 'fetch', message: asked }],
580
+ * })).length
581
+ * equal([
582
+ * logged('/app/api/query: Failed to fetch'),
583
+ * logged('200 /app/api/query'),
584
+ * ], [0, 1])
585
+ * let caught = (asked: string) =>
586
+ * broken(JSON.stringify({
587
+ * message: 'app page update: Failed to fetch',
588
+ * mechanism: 'catch',
589
+ * tags: { place: 'app page update' },
590
+ * breadcrumbs: [{ at: '2026-12-02', category: 'fetch', message: asked }],
591
+ * })).length
592
+ * equal([caught('/: Failed to fetch'), caught('200 /api/release')], [0, 1])
593
+ * equal(broken('not json'), [])
594
+ * ```
595
+ */
596
+ export let broken = (
597
+ body: string,
598
+ refusal: (answer: string, status: number) => boolean = meant,
599
+ ): Break[] => {
600
+ let sent: unknown
601
+ try {
602
+ sent = JSON.parse(body)
603
+ } catch {
604
+ return []
605
+ }
606
+ let reports = (Array.isArray(sent) ? sent : [sent]) as Record<
607
+ string,
608
+ unknown
609
+ >[]
610
+ return reports.flatMap((r): Break[] => {
611
+ if (!r || typeof r != 'object') return []
612
+ let b = (r.body ?? r) as Record<string, unknown>
613
+ // The reporter sends the answer's status beside its bytes (./page); a
614
+ // report with no status at all is a script error or an unhandled
615
+ // rejection, and those are breaks.
616
+ if (refusal(String(b.answer ?? ''), Number(b.status))) return []
617
+ if (b.filed === true || unanswered(b)) return []
618
+ let message = saying(b)
619
+ if (!message) return []
620
+ // The page it broke on, which the reporter names apart from `url`, the
621
+ // script or file at fault; an older reporter's `url` is the best left.
622
+ let at = pathOf(b.page ?? r.url ?? b.url ?? b.documentURL)
623
+ let source = b.sourceFile ?? b.url
624
+ let breadcrumbs = crumbs(b.breadcrumbs)
625
+ let tags = tagged(b.tags)
626
+ return [{
627
+ version:
628
+ typeof b.version == 'number' && Number.isSafeInteger(b.version) &&
629
+ b.version >= 0
630
+ ? b.version
631
+ : null,
632
+ ...typeof b.deployment == 'string' &&
633
+ /^[0-9a-f-]{36}$/i.test(b.deployment)
634
+ ? { deployment: b.deployment }
635
+ : {},
636
+ request: `${typeof r.type == 'string' ? r.type : 'page'} ${at}`.trim(),
637
+ message,
638
+ stack: String(
639
+ b.stack ?? (source ? `${source}:${b.lineNumber ?? b.line ?? ''}` : ''),
640
+ ),
641
+ ...typeof b.cause == 'string' && b.cause
642
+ ? { cause: b.cause.slice(0, 4000) }
643
+ : {},
644
+ ...MECHANISMS.has(b.mechanism)
645
+ ? { mechanism: b.mechanism as Mechanism }
646
+ : {},
647
+ ...breadcrumbs ? { breadcrumbs } : {},
648
+ ...tags ? { tags } : {},
649
+ ...b.page != null && typeof b.url == 'string' && b.url
650
+ ? { file: b.url }
651
+ : {},
652
+ }]
653
+ })
654
+ }
655
+
656
+ /**
657
+ * The breaks a report door was sent ({@link broken}), each carrying the
658
+ * browser that sent them: its user agent, which tells one Safari from another.
659
+ *
660
+ * ```ts
661
+ * import { equal } from '@yaks/testing'
662
+ * import { received } from '@yaks/tracker/report'
663
+ *
664
+ * let [one] = await received(
665
+ * new Request('https://box.test/api/report', {
666
+ * method: 'POST',
667
+ * body: JSON.stringify({ message: 'x is undefined' }),
668
+ * headers: { 'user-agent': 'Mozilla/5.0 Version/18.2 Safari/605.1.15' },
669
+ * }),
670
+ * )
671
+ * equal(one.agent, 'Mozilla/5.0 Version/18.2 Safari/605.1.15')
672
+ * ```
673
+ */
674
+ export let received = async (
675
+ request: Request,
676
+ refusal?: (answer: string, status: number) => boolean,
677
+ ): Promise<Break[]> => {
678
+ let agent = request.headers.get('user-agent')?.slice(0, 1000)
679
+ let breaks = broken(await request.text(), refusal)
680
+ return agent ? breaks.map((b) => ({ ...b, agent })) : breaks
681
+ }
682
+
683
+ /** Whether `key` has passed more than `rate` times this minute. A flood
684
+ * guard, not a quota: counted in this process and no further, so something
685
+ * looping cannot write a thousand entities a second, and a key spread over
686
+ * many isolates passing a few extra times is the harmless direction to err.
687
+ *
688
+ * ```ts
689
+ * import { equal } from '@yaks/testing'
690
+ * import { flood } from '@yaks/tracker/report'
691
+ *
692
+ * let over = flood(2)
693
+ * equal([over('a'), over('a'), over('a'), over('b')], [false, false, true, false])
694
+ * ```
695
+ */
696
+ export let flood = (rate: number): (key: string) => boolean => {
697
+ let counted = new Map<string, { minute: number; n: number }>()
698
+ return (key) => {
699
+ let minute = Math.floor(Date.now() / 60_000)
700
+ let hit = counted.get(key)
701
+ if (!hit || hit.minute != minute) {
702
+ counted.set(key, { minute, n: 1 })
703
+ return false
704
+ }
705
+ return ++hit.n > rate
706
+ }
707
+ }
708
+
709
+ // A page a verified bot renders, nobody is looking at: a search engine's or an
710
+ // AI company's crawler, a link previewer, a monitor. It loads on budgets and
711
+ // through proxies of its own, which drop loads the doors answered, so a miss
712
+ // it reports is the bot's, and filed it would read as the page's break.
713
+ // Cloudflare verifies the network it came from and says so on the request it
714
+ // hands a Worker, so the list is Cloudflare's to keep, never a list of user
715
+ // agents here to rot. A request that says nothing (any other runtime, or a
716
+ // bot Cloudflare could not verify) reads as a person: the safe direction.
717
+ let unwatched = (request: Request): boolean =>
718
+ !!(request as { cf?: { verifiedBotCategory?: string } }).cf
719
+ ?.verifiedBotCategory
720
+
721
+ /** What a report door ({@link door}) does with the breaks it was sent. */
722
+ export type Filing = {
723
+ /** files one break, which carries the release its page ran */
724
+ file: (broke: Break, index: number) => unknown
725
+ /** a no somebody answered on purpose (default {@link meant}) */
726
+ refusal?: (answer: string, status: number) => boolean
727
+ /** whether whoever this door files for has sent too many this minute
728
+ * ({@link flood}) */
729
+ flooding?: () => boolean
730
+ /** the release being served, for a break whose page named none: an older
731
+ * reporter's, or the browser's own Reporting API's */
732
+ serving?: () => number | null | undefined | Promise<number | null | undefined>
733
+ }
734
+
735
+ let no = (status: number, error: string, message: string) =>
736
+ Response.json({ error, message }, { status })
737
+
738
+ /**
739
+ * A page's report door: anyone may post to it, since a break belongs to
740
+ * whoever was looking at the page, and asking a stranger to sign in first
741
+ * would lose exactly the breaks nobody sees. What a verified bot's render
742
+ * sends is dropped before the flood ceiling, so a bot never spends the
743
+ * reports a person's page may need; past the ceiling the door says stop; a
744
+ * no somebody meant is no break ({@link broken}); and each break is filed
745
+ * with the release its page ran, else the one serving.
746
+ *
747
+ * ```ts
748
+ * import { equal } from '@yaks/testing'
749
+ * import { door } from '@yaks/tracker/report'
750
+ *
751
+ * let filed: (number | null)[] = []
752
+ * let report = door({ file: (b) => filed.push(b.version), serving: () => 7 })
753
+ * let post = (body: unknown) =>
754
+ * report(new Request('https://box.test/api/report', {
755
+ * method: 'POST',
756
+ * body: JSON.stringify(body),
757
+ * }))
758
+ * equal((await post([{ message: 'a', version: 3 }, { message: 'b' }])).status, 204)
759
+ * await post({ message: '403 /apply', status: 403 })
760
+ * equal(filed, [3, 7])
761
+ * ```
762
+ */
763
+ export let door =
764
+ (filing: Filing) => async (request: Request): Promise<Response> => {
765
+ if (request.method != 'POST') {
766
+ return no(405, 'method_not_allowed', 'a report is posted')
767
+ }
768
+ if (unwatched(request)) {
769
+ await request.body?.cancel()
770
+ return new Response(null, { status: 204 })
771
+ }
772
+ if (filing.flooding?.()) {
773
+ return no(429, 'too_many_reports', 'too many breaks reported this minute')
774
+ }
775
+ let breaks = await received(request, filing.refusal)
776
+ let version = breaks.some((b) => b.version == null)
777
+ ? await filing.serving?.() ?? null
778
+ : null
779
+ for (let [index, b] of breaks.entries()) {
780
+ await filing.file({ ...b, version: b.version ?? version }, index)
781
+ }
782
+ return new Response(null, { status: 204 })
783
+ }
784
+
785
+ /** A break as the error and context a host's telemetry files it with
786
+ * (@yaks/host `Host.report`): thrown in a browser, by the release its page
787
+ * ran, with `tags` beside its own.
788
+ *
789
+ * ```ts
790
+ * import { equal } from '@yaks/testing'
791
+ * import { thrown } from '@yaks/tracker/report'
792
+ *
793
+ * let [error, context] = thrown(
794
+ * { version: 3, request: 'page /', message: 'boom', stack: 'at x' },
795
+ * { user_id: 'ada' },
796
+ * )
797
+ * equal([error.message, error.stack, context.version], ['boom', 'at x', 3])
798
+ * equal(context.tags, {
799
+ * entrypoint: 'browser report',
800
+ * request: 'page /',
801
+ * user_id: 'ada',
802
+ * })
803
+ * ```
804
+ */
805
+ export let thrown = (
806
+ b: Break,
807
+ tags: Record<string, string> = {},
808
+ ): [Error, Partial<Context>] => [
809
+ Object.assign(
810
+ new Error(b.message, b.cause ? { cause: b.cause } : undefined),
811
+ { stack: b.stack },
812
+ ),
813
+ {
814
+ mechanism: b.mechanism,
815
+ breadcrumbs: b.breadcrumbs,
816
+ ...b.version != null ? { version: b.version } : {},
817
+ tags: {
818
+ ...Object.fromEntries(
819
+ Object.entries(b.tags ?? {}).map((
820
+ [key, value],
821
+ ) => [`page.${key}`, value]),
822
+ ),
823
+ entrypoint: 'browser report',
824
+ request: b.request,
825
+ ...tags,
826
+ ...b.agent ? { agent: b.agent } : {},
827
+ },
828
+ },
829
+ ]
830
+
831
+ export let queue =
832
+ (binding: { send: (body: Bundle[]) => Promise<void> }): Sink => (rows) =>
833
+ binding.send(rows)
834
+ export let spool =
835
+ (append: (line: string) => void | Promise<void>): Sink => (rows) =>
836
+ append(`${JSON.stringify(rows)}\n`)
837
+ export let post =
838
+ (url: string, send: typeof fetch = fetch): Sink => async (rows) => {
839
+ let response = await send(url, {
840
+ method: 'POST',
841
+ headers: { 'content-type': 'application/json' },
842
+ body: JSON.stringify(rows),
843
+ keepalive: true,
844
+ })
845
+ if (!response.ok) throw new Error(`tracker intake: ${response.status}`)
846
+ }
847
+
848
+ export type WindowClock = {
849
+ now: () => number
850
+ after: (ms: number, run: () => Promise<void>) => () => void
851
+ }
852
+ export type Coalesced = Sink & {
853
+ flush: () => Promise<void>
854
+ close: () => Promise<void>
855
+ }
856
+ let clock: WindowClock = {
857
+ now: Date.now,
858
+ after: (ms, run) => {
859
+ let timer = setTimeout(() => void run(), ms)
860
+ return () => clearTimeout(timer)
861
+ },
862
+ }
863
+
864
+ /** First samples leave immediately. Each app/fault window keeps only its latest
865
+ * repeat sample, whose hits count reaches every sink and downstream grouping. */
866
+ export let coalesce = (
867
+ sink: Sink,
868
+ options: { window?: number; clock?: WindowClock } = {},
869
+ ): Coalesced => {
870
+ let time = options.clock ?? clock
871
+ let span = options.window ?? 60_000
872
+ let windows = new Map<string, {
873
+ until: number
874
+ cancel: () => void
875
+ rows?: Bundle[]
876
+ hits: number
877
+ }>()
878
+ let pending = new Set<Promise<void>>()
879
+ let closed = false
880
+ let send = (rows: Bundle[]): Promise<void> => {
881
+ let delivery = reportRows(rows, sink)
882
+ pending.add(delivery)
883
+ void delivery.then(() => pending.delete(delivery))
884
+ return delivery
885
+ }
886
+ let finish = (key: string): Promise<void> => {
887
+ let window = windows.get(key)
888
+ if (!window) return Promise.resolve()
889
+ windows.delete(key)
890
+ window.cancel()
891
+ if (!window.rows) return Promise.resolve()
892
+ let [row, ...rest] = window.rows
893
+ return send([{
894
+ ...row,
895
+ error: { ...comp(row, 'error'), hits: window.hits },
896
+ }, ...rest])
897
+ }
898
+ let flush = async () => {
899
+ await Promise.all([...windows.keys()].map(finish))
900
+ await Promise.all(pending)
901
+ }
902
+ return Object.assign((rows: Bundle[]): Promise<void> => {
903
+ let row = rows[0]
904
+ if (closed || !row?.error) return send(rows)
905
+ let key = JSON.stringify([
906
+ str(comp(row, 'during').app),
907
+ faultOf(row),
908
+ rerunOf(row),
909
+ ])
910
+ let window = windows.get(key)
911
+ // A delayed timer must not hold the next window's first occurrence.
912
+ if (window && time.now() >= window.until) {
913
+ void finish(key)
914
+ window = undefined
915
+ }
916
+ if (window) {
917
+ window.rows = rows
918
+ window.hits += Number(comp(row, 'error').hits ?? 1)
919
+ return Promise.resolve()
920
+ }
921
+ windows.set(key, {
922
+ until: time.now() + span,
923
+ cancel: time.after(span, () => finish(key)),
924
+ hits: 0,
925
+ })
926
+ return send(rows)
927
+ }, {
928
+ flush,
929
+ close: () => {
930
+ closed = true
931
+ return flush()
932
+ },
933
+ })
934
+ }
935
+
936
+ let reportRows = async (rows: Bundle[], sink: Sink) => {
937
+ try {
938
+ await sink(rows)
939
+ } catch {
940
+ try {
941
+ await consoleRows(rows)
942
+ } catch { /* no recursion */ }
943
+ }
944
+ }