@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/page.js ADDED
@@ -0,0 +1,905 @@
1
+ // @ts-self-types="./page.d.ts"
2
+ // Browser capture and the empty-page fallback, woven inline into every page
3
+ // an app serves, ahead of the page's own scripts (page-script.ts). Wrapped,
4
+ // so none of its names land in the page's global scope, where a classic
5
+ // script declaring its own `send` or `version` would refuse to run.
6
+ ;(() => {
7
+ let installed = Symbol.for('yaks.page-report')
8
+ if (globalThis[installed]) return
9
+ let script = document.currentScript
10
+ let door = new URL(`${script.dataset.yakAt}api/report`, location.href).href
11
+ // Keep the version this page loaded, even after another release is served.
12
+ let version = Number(script.dataset.yakVersion)
13
+ let deployment = script.dataset.yakDeploy
14
+ let sent = 0
15
+ let stalled = 0
16
+ let crumbs = []
17
+ let crumb = (category, message) => {
18
+ crumbs.push({ at: new Date().toISOString(), category, message })
19
+ crumbs = crumbs.slice(-20)
20
+ }
21
+ globalThis[Symbol.for('yaks.report-context')] = () =>
22
+ crumbs.filter(({ category }) =>
23
+ category == 'console' || category == 'fetch'
24
+ ).map(({ category, message }) => ({
25
+ category,
26
+ message: message
27
+ .replace(/(https?:\/\/[^?\s]+)\?\S+/g, '$1')
28
+ .replace(
29
+ /(Bearer\s+|(?:password|secret|token|api[_ -]?key)\s*[:=]\s*)\S+/gi,
30
+ '$1[redacted]',
31
+ )
32
+ .replace(/\b(?:\d[ -]?){13,19}\b/g, '[redacted]')
33
+ .slice(0, 120),
34
+ }))
35
+ crumb('navigation', location.pathname)
36
+ addEventListener('popstate', () => crumb('navigation', location.pathname))
37
+ addEventListener('hashchange', () => crumb('navigation', location.pathname))
38
+
39
+ // Pages are written in ES2023, the language of the oldest browsers they
40
+ // support, Safari 16 and Chrome 110 (check-platform.ts `LIBS`), and
41
+ // `toSorted` is among its newest built-ins. In a browser without it, a page
42
+ // breaking on a built-in it lacks is expected, not news: nothing is filed,
43
+ // and the soft state asks the person to update the browser.
44
+ let dated = !Array.prototype.toSorted
45
+
46
+ let send = (body) => {
47
+ // A render loop that throws every frame must not become a write loop.
48
+ if (dated || (body.mechanism == 'loading' ? stalled++ : sent++) >= 20) {
49
+ return
50
+ }
51
+ try {
52
+ let blob = new Blob([
53
+ // The page it happened on, beside `url`, which names where: the
54
+ // script that threw, or the file that would not load.
55
+ JSON.stringify({
56
+ ...body,
57
+ page: location.href,
58
+ version,
59
+ deployment,
60
+ breadcrumbs: crumbs,
61
+ }),
62
+ ], {
63
+ type: 'application/json',
64
+ })
65
+ // A beacon always sends credentials, and a sandboxed app's page — an
66
+ // opaque origin, `self.origin` "null" — reports to a door that answers
67
+ // any origin only because it takes none (@yaks/platform/installs), so the
68
+ // browser refuses the beacon. A keepalive fetch sends none from there.
69
+ let beacon = self.origin != 'null' && navigator.sendBeacon
70
+ if (!beacon || !navigator.sendBeacon(door, blob)) {
71
+ Promise.resolve(
72
+ fetch(door, { method: 'POST', body: blob, keepalive: true }),
73
+ ).catch(() => {})
74
+ }
75
+ } catch { /* a reporter that throws is worse than one that misses */ }
76
+ }
77
+
78
+ let said = (e) => (e && e.message) || String(e)
79
+ // Preserve the reason a handled, thrown, or rejected error wraps.
80
+ let causes = (error) => {
81
+ let out = []
82
+ let seen = new Set([error])
83
+ for (let c = error?.cause; c != null && !seen.has(c) && out.length < 5;) {
84
+ seen.add(c)
85
+ out.push(
86
+ c instanceof Error ? c.stack || `${c.name}: ${c.message}` : said(c),
87
+ )
88
+ c = c instanceof Error ? c.cause : undefined
89
+ }
90
+ return out.join('\nCaused by: ').slice(0, 4000) || undefined
91
+ }
92
+ let lastError
93
+ let remember = ({ message, stack }) => {
94
+ lastError = {
95
+ page: location.href,
96
+ cause: [message, stack].filter(Boolean).join('\n').slice(0, 4000),
97
+ }
98
+ }
99
+
100
+ // A break, and the page's own account of it: everything that goes through
101
+ // here is something nobody chose, so it may also draw the soft state.
102
+ let broke = (body) => {
103
+ remember(body)
104
+ send(body)
105
+ sorry()
106
+ }
107
+
108
+ // The element a resource error happened on, if that is what this was: a
109
+ // script, link, img, or the module graph one of them pulled. A script that
110
+ // threw targets the window instead, and has an `error` of its own.
111
+ // On the app's own origin, and not this script's door: what happened there
112
+ // is the app's, and what happened on somebody else's server is not ours to
113
+ // file — a script on another origin may have 404'd, or been blocked by the
114
+ // visitor, or been put in the page by the edge, and from here those are one
115
+ // event. The test is the origin and not a list of hostnames, which would rot
116
+ // the first time the platform injected something new. The reporter itself
117
+ // needs no line of its own: a script that never loaded never listens.
118
+ let mine = (url) => url.origin == location.origin && url.href != door
119
+
120
+ // A failed graph query needs its filter to be diagnosable. Other API query
121
+ // strings may carry credentials or an outbound URL, so their path is enough.
122
+ let asked = (url) =>
123
+ url.pathname +
124
+ (url.pathname.endsWith('/api/query') ? url.search : '')
125
+
126
+ // Where a src points, or nothing if the browser handed us something that is
127
+ // not an address: a reporter that throws is worse than one that misses.
128
+ let at = (url) => {
129
+ try {
130
+ return new URL(url, document.baseURI)
131
+ } catch {
132
+ return null
133
+ }
134
+ }
135
+
136
+ let missed = (e) =>
137
+ e.target && e.target != globalThis && e.target.tagName && !e.error
138
+ ? e.target
139
+ : null
140
+
141
+ // A browser that runs a script of its own in the page, as Firefox on iPhone
142
+ // does (`__firefox__`), has a failure there placed at the page's own
143
+ // address, on the first line of its snippet. None of the page's scripts are
144
+ // on that line: this one is woven ahead of all of them (apps.ts `reported`),
145
+ // and its own text runs many lines.
146
+ let here = location.href.split('#')[0]
147
+ let foreign = (e) => e.lineno == 1 && (e.filename || '').split('#')[0] == here
148
+
149
+ // A script from another origin that throws is muted by the browser: the
150
+ // event says "Script error." with no file, line or error. What the page can
151
+ // still say is where it was and which scripts from elsewhere it held, as the
152
+ // frames of its stack. The inventory is evidence of what the page held,
153
+ // not proof of which script threw: injected scripts may already be gone.
154
+ let muted = (e) => e.error == null && !e.filename && !e.lineno
155
+ let scripts = () =>
156
+ Array.from(document.scripts || [], (s) => ({
157
+ src: s.src || '',
158
+ type: s.type || 'classic',
159
+ crossOrigin: s.crossOrigin || '',
160
+ }))
161
+ let elsewhere = (all) =>
162
+ all.map((s) => s.src).filter((src) => src && !mine(at(src) || location))
163
+ // A muted "Script error." on a page that loaded no script from another
164
+ // origin came from none of the page's scripts: the browser mutes only a
165
+ // script from elsewhere, so it was an extension's or the browser's own.
166
+ let stranger = (e) =>
167
+ muted(e) && e.message == 'Script error.' &&
168
+ !elsewhere(scripts()).length
169
+ // A module the browser would not link (an import naming what its module
170
+ // does not export) throws before any of the page's code ran, so its
171
+ // SyntaxError's stack names no frame: Chrome's is its message alone,
172
+ // Firefox's is empty. The event still says where, which becomes its frame.
173
+ let placed = (e) => {
174
+ if (e.error == null) return undefined
175
+ let stack = e.error.stack || `${e.error.name || 'Error'}: ${said(e.error)}`
176
+ if (!e.filename || stack.includes(e.filename)) return stack
177
+ return `${stack}\n at ${e.filename}:${e.lineno || 0}:${e.colno || 0}`
178
+ }
179
+ let mutedStack = () => {
180
+ let all = scripts()
181
+ return [
182
+ ...[location.href, ...elsewhere(all)].map((u) => ` at ${u}`),
183
+ `Browser: ${navigator.userAgent || 'unknown'}`,
184
+ `Scripts: ${JSON.stringify(all)}`,
185
+ ].join('\n')
186
+ }
187
+
188
+ // The page's own fetch, from before the wrapper below.
189
+ let plain = globalThis.fetch
190
+
191
+ // Whether the file is there, asked of the server and not the cache. Only the
192
+ // answer's status is waited for; its body is let go.
193
+ let answers = (url) =>
194
+ plain(url, { cache: 'no-store' }).then((r) => {
195
+ r.body?.cancel()
196
+ return r.ok || r.headers.has('x-yak-filed')
197
+ })
198
+
199
+ // A load can fail with the file in place: Safari stops every load of a page
200
+ // the moment the person heads elsewhere, and a stopped stylesheet or module
201
+ // fires this same event while the page is still up, as does a phone dropping
202
+ // its connection. So a miss is asked for again, and only one the server
203
+ // refuses is news. One that answers, or that cannot be asked because the
204
+ // connection or the page is gone, is not a fault of the app's or ours. A
205
+ // page of an opaque origin cannot read its own server's answer, so its
206
+ // misses are said as they come.
207
+ let unasked = () => self.origin == 'null'
208
+
209
+ // A module's miss says only that its graph did not load: the entry, or any
210
+ // file it imports. So the graph is asked for again, the entry and then each
211
+ // file of this origin it imports by address, and the answer is the first
212
+ // file the server refuses, or null when every one answers. A bare name
213
+ // resolves through the page's import map, which only the browser reads. An
214
+ // address on a scheme no browser loads a module from, as `node:fs` is, is
215
+ // refused without asking: a bundle that kept one is dead in every browser.
216
+ let IMPORTS =
217
+ /(?:^|[;\s}])(?:import|export)\s*(?:[\w$*{}\s,]+from\s*)?['"]([^'"\n]+)['"]/g
218
+ let GRAPH = 32
219
+ let LOADABLE = ['http:', 'https:', 'data:', 'blob:']
220
+ let unloadable = (name) => {
221
+ try {
222
+ let url = new URL(name)
223
+ return LOADABLE.includes(url.protocol) ? null : url
224
+ } catch {
225
+ return null
226
+ }
227
+ }
228
+ let refused = async (url, seen = new Set()) => {
229
+ if (seen.has(url.href) || seen.size >= GRAPH) return null
230
+ seen.add(url.href)
231
+ let r = await plain(url.href, { cache: 'no-store' })
232
+ if (!r.ok) {
233
+ r.body?.cancel()
234
+ return url
235
+ }
236
+ for (let [, name] of (await r.text()).matchAll(IMPORTS)) {
237
+ let dead = unloadable(name)
238
+ if (dead) return dead
239
+ if (!/^\.{0,2}\//.test(name)) continue
240
+ let next
241
+ try {
242
+ next = new URL(name, r.url || url.href)
243
+ } catch {
244
+ continue
245
+ }
246
+ let missing = mine(next) && await refused(next, seen)
247
+ if (missing) return missing
248
+ }
249
+ return null
250
+ }
251
+ let module = (el) => el.tagName == 'SCRIPT' && el.type == 'module'
252
+
253
+ // A module `import()` that fails says no more than a module element's miss:
254
+ // its graph did not load. So it is judged the same way, asked again, and it
255
+ // is news only where the server refuses a file of it. Chrome and Firefox name
256
+ // the entry. Safari names nothing, so there the app's own server is asked
257
+ // whether it answers at all: one that cannot be reached is the connection
258
+ // gone, and one that answers leaves the failure news. An entry on another
259
+ // origin is not asked about; it is said as it comes.
260
+ let IMPORT =
261
+ /^(?:Failed to fetch dynamically imported module|error loading dynamically imported module|Importing a module script failed\.)(?::\s*(\S+))?/
262
+ let root = new URL(script.dataset.yakAt, location.href).href
263
+ let importOf = (reason) => {
264
+ for (let r = reason, n = 0; r && typeof r == 'object' && n < 5; n++) {
265
+ let m = IMPORT.exec(said(r))
266
+ if (m) return { url: m[1] ? at(m[1]) : null }
267
+ r = r.cause
268
+ }
269
+ return null
270
+ }
271
+ let passed = ({ url }) =>
272
+ url
273
+ ? refused(url).then((missing) => !missing, () => true)
274
+ : plain(root, { cache: 'no-store' }).then((r) => {
275
+ r.body?.cancel()
276
+ return false
277
+ }, () => true)
278
+ // Files the failure `reason` with `file` at once, or, where it holds a
279
+ // failed import, once that import asked again is news.
280
+ let news = (reason, file) => {
281
+ let failed = importOf(reason)
282
+ if (!failed || unasked() || failed.url && !mine(failed.url)) return file()
283
+ return passed(failed).then((gone) => gone ? undefined : file())
284
+ }
285
+
286
+ // What the fetch below already answered for: a rejection it judged (no
287
+ // answer, or one the page gave up on, said there). The caller hears it
288
+ // either way, and one it leaves uncaught, as itself or as another's cause,
289
+ // was decided once: a page losing its server is not a break, and a timeout
290
+ // is said once.
291
+ let judged = new WeakSet()
292
+ let decided = (reason) => {
293
+ for (let r = reason, n = 0; r && typeof r == 'object' && n < 5; n++) {
294
+ if (judged.has(r)) return true
295
+ r = r.cause
296
+ }
297
+ return false
298
+ }
299
+
300
+ // What the server already filed where it caught it: an error
301
+ // ./api/client.js built from an answer that said so (`x-yak-filed`), as
302
+ // itself or as another's cause. The report says so, and the door files it
303
+ // no second time (report.ts `broken`).
304
+ let onFile = (reason) => {
305
+ for (let r = reason, n = 0; r && typeof r == 'object' && n < 5; n++) {
306
+ if (r.filed === true) return { filed: true }
307
+ r = r.cause
308
+ }
309
+ return {}
310
+ }
311
+
312
+ // A miss is answered with its handling, settled once it is said or let go.
313
+ let error = (e) => {
314
+ let el = missed(e)
315
+ if (el) {
316
+ // The address that 404'd is the news — the page is dead for the want of
317
+ // it — so it is both what this says and where it says it happened.
318
+ let src = el.src || el.href || ''
319
+ let where = at(src)
320
+ // Off the app's origin is not the app's file: the analytics beacon the
321
+ // edge injects, blocked in the visitor's browser, is the platform's news
322
+ // and not this app's.
323
+ if (where && !mine(where)) return
324
+ let load = where && (el.tagName == 'SCRIPT' ||
325
+ el.tagName == 'LINK' && /^(stylesheet|modulepreload)$/.test(el.rel))
326
+ ? globalThis[Symbol.for('yaks.resource-load')]?.(e, where.href)
327
+ : null
328
+ if (load?.passing) return
329
+ // A module names its entry, and `url` the file that was refused: the
330
+ // entry loads it, and whoever fixes the break needs both.
331
+ let miss = (url = src) =>
332
+ broke({
333
+ message: `failed to load ${el.tagName.toLowerCase()}${
334
+ src ? ` ${src}` : ''
335
+ }`,
336
+ url: url || location.href,
337
+ cause: load ? 'Resource load: ' + JSON.stringify(load) : undefined,
338
+ mechanism: 'onerror',
339
+ })
340
+ if (!where || unasked()) return miss()
341
+ if (module(el)) {
342
+ return refused(where).then(
343
+ (url) => url ? miss(url.href) : sorry(),
344
+ sorry,
345
+ )
346
+ }
347
+ return answers(where.href).then(
348
+ (there) => there ? sorry() : miss(),
349
+ sorry,
350
+ )
351
+ }
352
+ // A fetch with no answer is judged where it rejected (the wrapper below),
353
+ // whether the page leaves it uncaught or hands it to reportError.
354
+ if (foreign(e) || stranger(e) || decided(e.error)) return
355
+ // A notice the browser raises itself, such as a ResizeObserver loop, has
356
+ // no error: its own message is the one that says what happened.
357
+ let body = {
358
+ message: (e.error == null && e.message) || said(e.error),
359
+ stack: muted(e) ? mutedStack() : placed(e),
360
+ cause: causes(e.error),
361
+ url: e.filename || location.href,
362
+ line: e.lineno,
363
+ mechanism: 'onerror',
364
+ ...onFile(e.error),
365
+ }
366
+ return news(e.error, () => broke(body))
367
+ }
368
+ addEventListener('error', error, true)
369
+
370
+ // A refusal from ./api/client.js that the page never caught carries the
371
+ // answer's status, and goes to the door as the fetch below sends it: the door
372
+ // judges a no somebody meant, and only a break draws over the page.
373
+ let rejection = (e) => {
374
+ if (decided(e.reason)) return
375
+ let status = e.reason && e.reason.status
376
+ let body = {
377
+ message: `unhandled rejection: ${said(e.reason)}`,
378
+ stack: e.reason && e.reason.stack,
379
+ cause: causes(e.reason),
380
+ url: location.href,
381
+ status,
382
+ mechanism: 'onunhandledrejection',
383
+ ...onFile(e.reason),
384
+ }
385
+ return news(e.reason, () => (status < 500 ? send : broke)(body))
386
+ }
387
+ addEventListener('unhandledrejection', rejection)
388
+
389
+ // A page that catches and shows a failure can file it with context the
390
+ // fetch wrapper cannot see. Its UI already tells the person what happened.
391
+ // A fetch with no answer it caught is the same fetch, judged where it
392
+ // rejected.
393
+ globalThis[Symbol.for('yaks.report-caught')] = (error, place, tags) => {
394
+ if (decided(error)) return
395
+ let body = {
396
+ message: `${place}: ${said(error)}`,
397
+ stack: error?.stack,
398
+ cause: error && causes(error),
399
+ url: location.href,
400
+ mechanism: 'catch',
401
+ tags: { place, ...tags },
402
+ ...onFile(error),
403
+ }
404
+ return news(error, () => send(body))
405
+ }
406
+
407
+ let consoleError = globalThis.console?.error
408
+ if (consoleError) {
409
+ globalThis.console.error = (...args) => {
410
+ // Console arguments can carry user data; only the first sentence is
411
+ // kept, and the stack of an error logged beside it, which says where
412
+ // the code that logged it was, as an uncaught one's does, and its cause,
413
+ // which says what it was wrapped around.
414
+ let message = said(args[0]).slice(0, 2000)
415
+ let error = args.find((a) => a instanceof Error)
416
+ crumb('console', message)
417
+ // A fetch with no answer the page logs is the same fetch, judged where
418
+ // it rejected: a page losing its server is not a break.
419
+ if (decided(error)) return consoleError.apply(console, args)
420
+ let cause = error && causes(error)
421
+ let body = {
422
+ message,
423
+ stack: error && error.stack,
424
+ ...cause ? { cause } : {},
425
+ url: location.href,
426
+ mechanism: 'console',
427
+ ...onFile(error),
428
+ }
429
+ news(error, () => {
430
+ remember(body)
431
+ send(body)
432
+ })
433
+ consoleError.apply(console, args)
434
+ }
435
+ }
436
+
437
+ // A 5xx or timeout without an attempt id is held while the page asks it
438
+ // again, and let go once it is answered. It is said once the page has not
439
+ // asked again for `HOLD` (an ask with no answer is asking), a minute after
440
+ // it was first held (`LONGEST`) whatever the page does, or as the page is
441
+ // left; the soft state waits with it.
442
+ let HOLD = 10_000
443
+ let LONGEST = 60_000
444
+ let held = new Map()
445
+ let pending = new Map()
446
+ let drop = (key) => {
447
+ let h = held.get(key)
448
+ if (!h) return null
449
+ held.delete(key)
450
+ clearTimeout(h.quiet)
451
+ clearTimeout(h.cap)
452
+ return h
453
+ }
454
+ let say = (key) => {
455
+ let h = drop(key)
456
+ if (!h) return
457
+ send(h.body)
458
+ sorry()
459
+ }
460
+ let hold = (key, body) => {
461
+ let h = held.get(key)
462
+ if (!h) held.set(key, h = { cap: setTimeout(() => say(key), LONGEST) })
463
+ h.body = body
464
+ }
465
+ let asking = (key) => {
466
+ pending.set(key, (pending.get(key) ?? 0) + 1)
467
+ clearTimeout(held.get(key)?.quiet)
468
+ return () => {
469
+ let left = pending.get(key) - 1
470
+ if (left) return pending.set(key, left)
471
+ pending.delete(key)
472
+ let h = held.get(key)
473
+ if (h) h.quiet = setTimeout(() => say(key), HOLD)
474
+ }
475
+ }
476
+ addEventListener('pagehide', () => {
477
+ for (let key of [...held.keys()]) say(key)
478
+ })
479
+
480
+ let reads = new Map()
481
+ let read = (name, phase) => {
482
+ let key = {}
483
+ reads.set(key, { name, phase })
484
+ return () => reads.delete(key)
485
+ }
486
+ let timedOut = (error, signal) =>
487
+ error?.name == 'TimeoutError'
488
+ ? error
489
+ : error?.name == 'AbortError' && signal?.reason?.name == 'TimeoutError'
490
+ ? signal.reason
491
+ : null
492
+
493
+ let reading = (response, name, failed) => {
494
+ for (
495
+ let method of ['arrayBuffer', 'blob', 'bytes', 'formData', 'json', 'text']
496
+ ) {
497
+ let consume = response[method]
498
+ if (!consume) continue
499
+ response[method] = async function () {
500
+ let done = read(name, 'reading response')
501
+ let began = failed ? performance.now() : 0
502
+ try {
503
+ return await consume.call(this)
504
+ } catch (e) {
505
+ failed?.(e, began)
506
+ throw e
507
+ } finally {
508
+ done()
509
+ }
510
+ }
511
+ }
512
+ }
513
+
514
+ let attemptOf = (headers, method, where) => {
515
+ if (!headers) return
516
+ let sent = new Headers(headers)
517
+ let id = sent.get('x-yak-page-request')
518
+ if (!id) return
519
+ let query = where.searchParams
520
+ let operation = query.has('line')
521
+ ? 'line'
522
+ : query.has('talk')
523
+ ? 'refresh'
524
+ : query.has('counts')
525
+ ? 'counts'
526
+ : 'open'
527
+ return {
528
+ page_request: id,
529
+ page_operation: `${method.toUpperCase()} ${operation}`,
530
+ page_retry: sent.get('x-yak-page-retry') ?? undefined,
531
+ }
532
+ }
533
+
534
+ let elapsed = (began) => String(Math.round(performance.now() - began))
535
+ // A computer that slept while the page waited (its lid shut) wakes to a
536
+ // wait its wall clock says ran far longer than the page's own clock, which
537
+ // stopped with it. The answer was lost to the sleep, not late from the
538
+ // server, and the page asks again: a connection dropping, said as one.
539
+ let SLEPT = 2_000
540
+ let slept = (began, wall) =>
541
+ Date.now() - wall - (performance.now() - began) > SLEPT
542
+ let server = (r) => {
543
+ let timing = ''
544
+ for (
545
+ let [, metric] of (r.headers.get('server-timing') ?? '').matchAll(
546
+ /(?:^|,\s*)([\w-]+;dur=\d+(?:\.\d+)?)(?=;|,|$)/g,
547
+ )
548
+ ) {
549
+ let next = timing ? `${timing}, ${metric}` : metric
550
+ if (next.length > 500) break
551
+ timing = next
552
+ }
553
+ return timing
554
+ }
555
+
556
+ globalThis.fetch = async (input, init) => {
557
+ // Against the page's base, not its address: the kernel gives every page a
558
+ // `<base>` at the app's own root (apps.ts `based`), so that is what the
559
+ // browser resolved `./api/query` against — resolving it against
560
+ // `location.href` here would name a path nothing was ever asked for.
561
+ let where = new URL((input && input.url) || input, document.baseURI)
562
+ let method = (init && init.method) || (input && input.method) || 'GET'
563
+ let key = `${method} ${where.href}`
564
+ let local = mine(where)
565
+ let settle = local && asking(key)
566
+ let name = local && /^(GET|HEAD)$/i.test(method) &&
567
+ `${method.toUpperCase()} ${asked(where)}`
568
+ let done = name && read(name, 'waiting for headers')
569
+ let attempt = local &&
570
+ attemptOf(init?.headers ?? input?.headers, method, where)
571
+ let began = performance.now()
572
+ let wall = Date.now()
573
+ let signal = init?.signal ?? input?.signal
574
+ let timeout = (e, late, tags) => {
575
+ if (judged.has(e)) return
576
+ judged.add(e)
577
+ if (slept(began, wall)) {
578
+ return crumb('fetch', `${asked(where)}: ${said(late)} across a sleep`)
579
+ }
580
+ let body = {
581
+ message: `${asked(where)}: ${said(late)}`,
582
+ url: location.href,
583
+ mechanism: 'wrapper',
584
+ tags,
585
+ }
586
+ remember(body)
587
+ if (tags) send(body)
588
+ else hold(key, body)
589
+ }
590
+ try {
591
+ let r = await plain(input, init)
592
+ let answered = attempt && {
593
+ ...attempt,
594
+ page_headers_ms: elapsed(began),
595
+ page_ray: r.headers.get('cf-ray') ?? undefined,
596
+ page_server_timing: server(r),
597
+ }
598
+ done && done()
599
+ // This browser's store for the app moved at this answer: a stranger's
600
+ // first write, the page's own or one the app's worker made for them, gave
601
+ // them a store of their own (@yaks/platform/visits). Every answer the
602
+ // page sees passes here, so this is where ./api/client.js hears it
603
+ // (`yak-moved`), and opens its socket again on the new store.
604
+ if (local && r.headers.has('x-yak-moved')) {
605
+ dispatchEvent(new CustomEvent('yak-moved', { detail: where.href }))
606
+ }
607
+ if (local && where.pathname.includes('/api/')) {
608
+ crumb('fetch', `${r.status} ${where.pathname}`)
609
+ }
610
+ if (r.ok && drop(key)) {
611
+ crumb('fetch', `${asked(where)}: answered once asked again`)
612
+ }
613
+ if (!r.ok && local) {
614
+ let why = await r.clone().text().catch(() => '')
615
+ let tags = answered || undefined
616
+ let body = {
617
+ message: `${r.status} ${asked(where)}: ${why}`.slice(0, 2000),
618
+ url: location.href,
619
+ // The answer as it came, so the door can tell a no it meant — a
620
+ // signed-out visitor sent to sign in — from one it did not
621
+ // (unseen.ts `refusal`). This script decides nothing: it is cached
622
+ // in browsers we cannot reach, and the rule lives where we can.
623
+ status: r.status,
624
+ answer: why.slice(0, 2000),
625
+ // The server reported this answer itself where it caught it
626
+ // (report.ts `FILED`); the door files it no second time.
627
+ filed: r.headers.has('x-yak-filed'),
628
+ mechanism: 'wrapper',
629
+ tags,
630
+ }
631
+ // The two things this script does read the status for: whether to
632
+ // draw over the page, and whether the page may yet recover. A no
633
+ // somebody meant is the platform working. A 5xx with an attempt id
634
+ // is reported even if the page later recovers.
635
+ if (r.status >= 500 && !tags) hold(key, body)
636
+ else send(body)
637
+ }
638
+ if (name) {
639
+ reading(
640
+ r,
641
+ name,
642
+ answered
643
+ ? (e, began) => {
644
+ let late = timedOut(e, signal)
645
+ if (late) {
646
+ timeout(e, late, { ...answered, page_body_ms: elapsed(began) })
647
+ }
648
+ }
649
+ : undefined,
650
+ )
651
+ }
652
+ return r
653
+ } catch (e) {
654
+ // A fetch that rejects never had an answer. One the page gave up waiting
655
+ // for carries its attempt id if the caller tracks each try. Any other
656
+ // rejection is the connection dropping, the person
657
+ // leaving, or the page's own abort, none of them the app's fault or
658
+ // ours (release.js checks again later), and a held failure asked again
659
+ // this way is still being asked. The caller hears it either way, and
660
+ // one it leaves uncaught is let go at `unhandledrejection` above, since
661
+ // it is decided here.
662
+ let late = local && timedOut(e, signal)
663
+ if (late) {
664
+ timeout(
665
+ e,
666
+ late,
667
+ attempt ? { ...attempt, page_wait_ms: elapsed(began) } : undefined,
668
+ )
669
+ } else if (local) {
670
+ if (e && typeof e == 'object') judged.add(e)
671
+ crumb('fetch', `${where.pathname}: ${said(e)}`)
672
+ }
673
+ throw e
674
+ } finally {
675
+ done && done()
676
+ settle && settle()
677
+ }
678
+ }
679
+
680
+ // The soft state: the app's page shows "something went wrong, your assistant
681
+ // has been told" rather than a stack trace.
682
+ //
683
+ // Only when the break left the person with nothing to look at. "Painted" is
684
+ // judged the cheap way — the body's own words, and whether anything that draws
685
+ // pixels is in it — because a heading and empty space is a page every paint
686
+ // timing in the browser calls a paint. A shell is under a line of text and
687
+ // has no picture in it; a page doing its job has one or the other.
688
+ let SHELL = 80
689
+ let bare = () => {
690
+ let b = document.body
691
+ if (!b) return true
692
+ if ((b.innerText || '').trim().length > SHELL) return false
693
+ return !b.querySelector('img, canvas, svg, video, iframe')
694
+ }
695
+
696
+ // Judged after the page has had its chance: a module that 404s reports before
697
+ // anything could have painted, so the answer waits for `load` — or two
698
+ // seconds, since a page that never finishes loading never fires it.
699
+ let settled = (draw) => {
700
+ let t
701
+ let now = () => {
702
+ clearTimeout(t)
703
+ removeEventListener('load', now)
704
+ draw()
705
+ }
706
+ if (document.readyState == 'complete') return setTimeout(now, 0)
707
+ t = setTimeout(now, 2000)
708
+ addEventListener('load', now)
709
+ }
710
+
711
+ // The home page's own colors (public/style.css): warm linen and warm brown,
712
+ // cocoa in the dark, never black. Set through CSSOM rather than a <style>
713
+ // element, so an app with its own strict CSP still shows it.
714
+ let SORRY = 'Something went wrong. Try reloading the page.'
715
+ let DATED = 'This browser is too old for this page. Update it and reload.'
716
+
717
+ let dark = () =>
718
+ globalThis.matchMedia &&
719
+ matchMedia('(prefers-color-scheme: dark)').matches
720
+
721
+ let told = false
722
+
723
+ let sorry = () => {
724
+ if (told) return
725
+ told = true
726
+ settled(() => {
727
+ if (!bare() || !dated && [...marks()].some(visible)) return
728
+ try {
729
+ let box = document.createElement('div')
730
+ box.id = 'yak-sorry'
731
+ box.setAttribute('role', 'status')
732
+ box.textContent = dated ? DATED : SORRY
733
+ box.style.cssText = 'position:fixed;inset:0;z-index:2147483647;' +
734
+ 'display:flex;align-items:center;justify-content:center;' +
735
+ 'margin:0;padding:2rem;text-align:center;' +
736
+ "font:600 1.05rem/1.6 'Nunito',system-ui,-apple-system,'Segoe UI'," +
737
+ 'Roboto,sans-serif;' +
738
+ (dark()
739
+ ? 'background:#2b231f;color:#f1e6d8'
740
+ : 'background:#fdf7ee;color:#523828')
741
+ ;(document.body || document.documentElement).append(box)
742
+ } catch { /* a reporter that throws is worse than one that misses */ }
743
+ })
744
+ }
745
+
746
+ // While ./api/client.js waits out a connection that dropped, before asking
747
+ // again (its `again`), the page says so, and stops saying so once it is
748
+ // answered: the person's work is held, not lost, and the page is not empty
749
+ // because there is nothing.
750
+ let RECONNECTING = 'Reconnecting…'
751
+ let line = null
752
+ addEventListener('yak-reconnecting', (e) => {
753
+ try {
754
+ if (!e.detail) {
755
+ line?.remove()
756
+ line = null
757
+ return
758
+ }
759
+ if (line) return
760
+ line = document.createElement('div')
761
+ line.id = 'yak-reconnecting'
762
+ line.setAttribute('role', 'status')
763
+ line.textContent = RECONNECTING
764
+ line.style.cssText = 'position:fixed;left:50%;bottom:1rem;' +
765
+ 'transform:translateX(-50%);z-index:2147483647;' +
766
+ 'padding:.4rem .9rem;border-radius:999px;' +
767
+ "font:600 .9rem/1.4 'Nunito',system-ui,-apple-system,'Segoe UI'," +
768
+ 'Roboto,sans-serif;' +
769
+ (dark()
770
+ ? 'background:#2b231f;color:#f1e6d8'
771
+ : 'background:#fdf7ee;color:#523828;box-shadow:0 1px 4px #5238283d')
772
+ ;(document.body || document.documentElement).append(line)
773
+ } catch { /* a reporter that throws is worse than one that misses */ }
774
+ })
775
+
776
+ // The Loading kit marks pending reads in both server HTML and client draws.
777
+ // The reporter can see the mark even when the code meant to clear it fails.
778
+ let MARK = '[data-yak-loading]'
779
+ let marks = () => document.querySelectorAll?.(MARK) ?? []
780
+ let visible = (mark) =>
781
+ mark.isConnected &&
782
+ !mark.closest('[hidden], [inert], details:not([open]), dialog:not([open])')
783
+ let waits = new Map()
784
+ let deadline = 15_000
785
+ let active = () => document.visibilityState != 'hidden'
786
+ let stop = (mark, wait) => {
787
+ clearTimeout(wait.timer)
788
+ wait.failure?.remove()
789
+ if (wait.words) wait.words.hidden = false
790
+ mark.removeAttribute('data-yak-loading-failed')
791
+ waits.delete(mark)
792
+ }
793
+ let overdue = (mark, wait) => {
794
+ if (!active() || !mark.matches(MARK) || !visible(mark)) {
795
+ return stop(mark, wait)
796
+ }
797
+ let open = [...reads.values()].slice(0, 12).map(({ name, phase }) =>
798
+ `${name.slice(0, 115)} (${phase})`
799
+ )
800
+ if (reads.size > open.length) {
801
+ open.push(`and ${reads.size - open.length} more`)
802
+ }
803
+ if (document.readyState == 'loading') open.push('Document (receiving HTML)')
804
+ if (wait.state == 'page opening') {
805
+ let sheets = [...document.querySelectorAll('link[rel=stylesheet][href]')]
806
+ .filter((link) => !link.sheet).map((link) => at(link.href))
807
+ .filter((url) => url && mine(url))
808
+ for (let url of sheets.slice(0, 5)) {
809
+ open.push(`Stylesheet ${url.pathname.slice(0, 115)}`)
810
+ }
811
+ }
812
+ crumb(
813
+ 'loading',
814
+ open.length ? `Open reads: ${open.join(', ')}` : 'No open reads',
815
+ )
816
+ let stage = mark.closest('[data-yak-loading-stage]')?.dataset
817
+ .yakLoadingStage
818
+ if (stage) {
819
+ crumb(
820
+ 'loading',
821
+ `Stage: ${stage.slice(0, 100)} (document: ${document.readyState})`,
822
+ )
823
+ }
824
+ send({
825
+ message: `Loading timed out: ${mark.dataset.yakLoading.slice(0, 100)}`,
826
+ url: location.origin + location.pathname,
827
+ mechanism: 'loading',
828
+ cause: lastError?.page == location.href ? lastError.cause : undefined,
829
+ })
830
+ let failure = document.createElement('span')
831
+ let retry = document.createElement('button')
832
+ failure.className = 'Loading_Failed'
833
+ retry.className = 'Button Button-quiet'
834
+ retry.type = 'button'
835
+ retry.textContent = 'Try again'
836
+ retry.onclick = () => {
837
+ stop(mark, wait)
838
+ if (
839
+ mark.dispatchEvent(
840
+ new CustomEvent('yak-loading-retry', {
841
+ bubbles: true,
842
+ cancelable: true,
843
+ }),
844
+ )
845
+ ) location.reload()
846
+ else scan()
847
+ }
848
+ failure.append('This took too long to load. ', retry)
849
+ mark.setAttribute('data-yak-loading-failed', '')
850
+ let words = mark.querySelector('[data-yak-loading-words]')
851
+ if (words && !words.hidden) {
852
+ wait.words = words
853
+ words.hidden = true
854
+ }
855
+ mark.append(wait.failure = failure)
856
+ }
857
+ let scan = () => {
858
+ for (let [mark, wait] of waits) {
859
+ if (
860
+ wait.state != mark.dataset.yakLoading || !visible(mark) ||
861
+ (wait.failure ? wait.failure.parentNode != mark : !active())
862
+ ) {
863
+ stop(mark, wait)
864
+ }
865
+ }
866
+ if (!active()) return
867
+ for (let mark of marks()) {
868
+ if (!visible(mark) || waits.has(mark)) continue
869
+ let wait = { state: mark.dataset.yakLoading }
870
+ wait.timer = setTimeout(() => overdue(mark, wait), deadline)
871
+ waits.set(mark, wait)
872
+ }
873
+ }
874
+ if (globalThis.MutationObserver && document.documentElement) {
875
+ let hasMark = (node) => node.matches?.(MARK) || node.querySelector?.(MARK)
876
+ new globalThis.MutationObserver((changes) => {
877
+ if (
878
+ changes.some((change) =>
879
+ change.type == 'attributes'
880
+ ? change.attributeName == 'data-yak-loading' ||
881
+ hasMark(change.target)
882
+ : [...change.addedNodes, ...change.removedNodes].some(hasMark) ||
883
+ [...change.removedNodes].some((node) =>
884
+ node.matches?.('.Loading_Failed')
885
+ )
886
+ )
887
+ ) scan()
888
+ }).observe(document.documentElement, {
889
+ subtree: true,
890
+ childList: true,
891
+ attributes: true,
892
+ attributeFilter: ['data-yak-loading', 'hidden', 'inert', 'open'],
893
+ })
894
+ document.addEventListener('visibilitychange', scan)
895
+ scan()
896
+ }
897
+
898
+ let earlyKey = Symbol.for('yaks.early-report')
899
+ let early = globalThis[earlyKey]?.() ?? []
900
+ globalThis[installed] = true
901
+ for (let event of early) {
902
+ if (event.type == 'error') error(event)
903
+ else rejection(event)
904
+ }
905
+ })()