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