@marver-design/marver 0.29.0 → 0.30.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/CHANGELOG.md +44 -0
  2. package/README.md +2 -1
  3. package/dist/{anchor-check-DhlpKl2K.mjs → anchor-check-c52IDkiQ.mjs} +1 -1
  4. package/dist/{build-CWbrb2bl.mjs → build-C3mUtjEn.mjs} +5 -4
  5. package/dist/cli.mjs +5 -5
  6. package/dist/{daemon-Sc_z8gT6.mjs → daemon-B0Wi1OQ3.mjs} +5 -3
  7. package/dist/{dev-DWBKQhxf.mjs → dev-5dlxoW28.mjs} +8 -8
  8. package/dist/{perf-Denssrko.mjs → perf-6MOTHxay.mjs} +710 -99
  9. package/dist/perf-BCxAo0IS.mjs +1743 -0
  10. package/dist/{plugin-DqoZB-D6.mjs → plugin-CXRoMA8g.mjs} +898 -539
  11. package/dist/{poster-CrsjqhY4.mjs → poster-CYmCa00B.mjs} +1 -1
  12. package/dist/{publish-bakes-DW-NDgU2.mjs → publish-bakes-C_2ZtHou.mjs} +2 -2
  13. package/dist/{recover-GtJ9UDAB.mjs → recover-XD8iXJOj.mjs} +1 -1
  14. package/dist/{shot-T04Ixrvq.mjs → shot-CRRGgxru.mjs} +3 -3
  15. package/docs/app.md +194 -0
  16. package/docs/performance.md +98 -18
  17. package/package.json +1 -1
  18. package/src/client/frame-host/bridge.js +17 -8
  19. package/src/client/frame-host/inplace.ts +124 -0
  20. package/src/client/frame-host/inspect.d.ts +1 -0
  21. package/src/client/frame-host/inspect.js +13 -4
  22. package/src/client/frame-host/main.tsx +12 -3
  23. package/src/client/frame-host/messages.ts +85 -0
  24. package/src/client/frame-host/signals.d.ts +15 -0
  25. package/src/client/frame-host/signals.js +219 -0
  26. package/src/client/recorder-level.ts +41 -0
  27. package/src/client/shell/App.tsx +158 -88
  28. package/src/client/shell/BoardList.tsx +103 -48
  29. package/src/client/shell/Comments.tsx +66 -42
  30. package/src/client/shell/ContextMenu.tsx +3 -2
  31. package/src/client/shell/JamSurface.tsx +116 -71
  32. package/src/client/shell/LockedApp.tsx +19 -3
  33. package/src/client/shell/Play.tsx +94 -58
  34. package/src/client/shell/StatusPicker.tsx +19 -9
  35. package/src/client/shell/Toolbar.tsx +15 -7
  36. package/src/client/shell/api.ts +18 -4
  37. package/src/client/shell/app-bridge.ts +12 -6
  38. package/src/client/shell/app-perf.ts +31 -1
  39. package/src/client/shell/canvas/Canvas.tsx +17 -6
  40. package/src/client/shell/canvas/FrameNode.tsx +25 -12
  41. package/src/client/shell/canvas/Sticky.tsx +4 -2
  42. package/src/client/shell/canvas/ctl.ts +2 -0
  43. package/src/client/shell/canvas/ready-watch.ts +4 -0
  44. package/src/client/shell/canvas/sleep.ts +2 -0
  45. package/src/client/shell/canvas/updates.ts +13 -6
  46. package/src/client/shell/commands.ts +765 -0
  47. package/src/client/shell/comments-store.ts +42 -27
  48. package/src/client/shell/goto.ts +11 -6
  49. package/src/client/shell/jam-keys.ts +141 -75
  50. package/src/client/shell/jam-lane.tsx +19 -12
  51. package/src/client/shell/jam-panel.tsx +61 -48
  52. package/src/client/shell/jam-session.tsx +41 -37
  53. package/src/client/shell/jam-state.ts +9 -1
  54. package/src/client/shell/jam-surface-parts.tsx +8 -6
  55. package/src/client/shell/jam-ui.tsx +9 -6
  56. package/src/client/shell/jam-voice.ts +4 -2
  57. package/src/client/shell/main.tsx +7 -1
  58. package/src/client/shell/marks-ui.tsx +11 -0
  59. package/src/client/shell/perf.ts +51 -5
  60. package/src/client/shell/recorder-core.ts +4 -1
  61. package/src/client/shell/recorder-hmr.ts +36 -0
  62. package/src/client/shell/recorder-reloads.ts +264 -0
  63. package/src/client/shell/recorder-seams.ts +116 -0
  64. package/src/client/shell/recorder-self.ts +73 -0
  65. package/src/client/shell/recorder-signals-core.ts +139 -0
  66. package/src/client/shell/recorder-signals.ts +485 -0
  67. package/src/client/shell/recorder.ts +115 -41
  68. package/src/client/shell/store.ts +56 -22
  69. package/src/client/shell/whiteout-probes.ts +3 -1
  70. package/src/client/stage/main.tsx +10 -5
  71. package/src/shared/app-api.ts +28 -6
  72. package/src/shared/app-perf.ts +99 -6
  73. package/src/shared/app-report.ts +586 -0
  74. package/src/shared/perf-records.ts +445 -0
  75. package/src/shared/perf-run.ts +6 -2
  76. package/dist/perf-jam-CLkERSHo.mjs +0 -642
@@ -0,0 +1,485 @@
1
+ /**
2
+ * What the page signals beyond loads (spec 30 R3-R6): theme switches by transition (#21-#23), modes (#24-#27), the new
3
+ * error sources and their budgets (#28-#33: console, vite, api, resource, the frames' `sh:dropped` counts), the gesture
4
+ * posts to the frames (#36; its scale, awake count and Long Animation Frames are perf.ts's and recorder.ts's, #34, #35)
5
+ * and the React Profiler's minutes (#36). Owner: the signals stream.
6
+ *
7
+ * `startSignals()` runs once, at the full level only, after the page recorder is on (recorder.ts `startRecorder`). It
8
+ * subscribes through recorder-seams.ts and the stores, writes through `perfSeams.record` (and `signalSink`, which
9
+ * recorder.ts fills beside `logError`), sets `perfSeams.transition`, and asks the Mac app for `theme` windows.
10
+ *
11
+ * A record never lies (R0): an ack counts only with the transition's own `t` and from the live document; what never
12
+ * acknowledged is `late` at the timeout; a newer change makes the older one `superseded` with what it had.
13
+ */
14
+ import { ERROR_BUDGET, TRANSITION, type DropReason, type ErrorFields, type ErrorSource, type ModeName, type RenderRow, type ThemeScope, type TransitionOutcome } from '../../shared/perf-records.ts'
15
+ import { formatConsole, periodMs, RESOURCE_TAGS, resourceOf, stackOfArgs, viteEcho } from '../frame-host/signals.js'
16
+ import { watchWindow } from './app-perf.ts'
17
+ import { onMotion } from './canvas/camera-broadcast.ts'
18
+ import { canvasCtl } from './canvas/ctl.ts'
19
+ import { bootOf, iframeOf } from './canvas/frame-registry.ts'
20
+ import { currentCmd } from './commands.ts'
21
+ import { useComments } from './comments-store.ts'
22
+ import { useJamCapture } from './jam-capture.ts'
23
+ import { useJamQueue } from './jam-queue.ts'
24
+ import { useJamUi } from './jam-state.ts'
25
+ import { newId } from './recorder-core.ts'
26
+ import { hooked, perfSeams, type Answered } from './recorder-seams.ts'
27
+ import { addRow, createRate, foldRows, nodesIn, normRoute, p50, topWarnings } from './recorder-signals-core.ts'
28
+ import { useStore } from './store.ts'
29
+ import { isHideUI, onHideUI } from './Toolbar.tsx'
30
+
31
+ type State = ReturnType<typeof useStore.getState>
32
+
33
+ /** What recorder.ts takes from here, set beside `logError`: this module never imports recorder.ts. */
34
+ export interface SignalError { source: ErrorSource; frame?: string; component?: string; message: unknown; stack?: unknown; fields?: ErrorFields }
35
+ export const signalSink = {
36
+ error: (_e: SignalError): void => {},
37
+ dropped: (_reason: DropReason, _n: number): void => {},
38
+ }
39
+
40
+ let started = false
41
+ const now = () => performance.now()
42
+
43
+ // ---- transitions' rate (#57) -----------------------------------------------------------------------------------------
44
+
45
+ const rates = { theme: createRate(TRANSITION.perSecond), mode: createRate(TRANSITION.perSecond) }
46
+ /** A `theme` or `mode` record, at most 10 a second each; past that counted. */
47
+ function transitionRecord(kind: 'theme' | 'mode', body: Record<string, unknown>): void {
48
+ if (!rates[kind]()) { signalSink.dropped(kind, 1); return }
49
+ perfSeams.record(kind, body)
50
+ }
51
+
52
+ // ---- documents -------------------------------------------------------------------------------------------------------
53
+
54
+ /** The play stage's iframe, and the document it shows now (`__mvStage`). */
55
+ function liveStageBoot(): string | undefined {
56
+ try {
57
+ const f = document.querySelector<HTMLIFrameElement>('.sh-play-stage iframe')
58
+ const b = (f?.contentWindow as { __mvStage?: { boot?: unknown } } | null | undefined)?.__mvStage?.boot
59
+ return typeof b === 'string' ? b : undefined
60
+ } catch { return undefined }
61
+ }
62
+ const liveFrame = (key: string, boot: unknown) => typeof boot === 'string' && !!boot && boot === bootOf(iframeOf(key))
63
+ /** The nodes the camera shows now (recorder.ts `cohortIn`) - none with no canvas. */
64
+ function shownNodes(s: State) {
65
+ const v = canvasCtl.view()
66
+ return v ? nodesIn(s.nodes, v) : []
67
+ }
68
+
69
+ // ---- R3: theme switches ----------------------------------------------------------------------------------------------
70
+
71
+ interface Switch {
72
+ t: string; scope: ThemeScope; to: string; by?: string; at: number
73
+ /** the displayed cohort: node keys, or the stage alone */
74
+ cohort: Set<string>; stage: boolean
75
+ acked: Set<string>; times: number[]
76
+ timer?: ReturnType<typeof setTimeout>
77
+ }
78
+ let sw: Switch | null = null
79
+
80
+ const themeSize = (s: Switch) => (s.stage ? 1 : s.cohort.size)
81
+ function themeEnd(s: Switch, outcome: TransitionOutcome): void {
82
+ clearTimeout(s.timer)
83
+ if (sw === s) sw = null
84
+ const frames = themeSize(s), applied = s.acked.size
85
+ if (frames) watchWindow('theme', false)
86
+ const ms = p50(s.times)
87
+ transitionRecord('theme', {
88
+ t: s.t, scope: s.scope, to: s.to, by: s.by, frames, applied,
89
+ ...(ms !== undefined ? { p50Ms: Math.round(ms), maxMs: Math.round(Math.max(...s.times)) } : {}),
90
+ ...(outcome === 'timeout' ? { late: frames - applied } : {}),
91
+ outcome,
92
+ })
93
+ }
94
+ /** #21-#23: a switch begins. A newer switch finishes the running one with what it had. */
95
+ function themeStart(scope: ThemeScope, to: string, cohort: Set<string>, stage: boolean): void {
96
+ if (sw) themeEnd(sw, 'superseded')
97
+ const s: Switch = { t: newId(), scope, to, by: currentCmd(), at: now(), cohort, stage, acked: new Set(), times: [] }
98
+ // nothing displayed changes: nothing to wait for
99
+ if (!themeSize(s)) { themeEnd(s, 'done'); return }
100
+ sw = s
101
+ watchWindow('theme', true)
102
+ s.timer = setTimeout(hooked('theme', () => { if (sw === s) themeEnd(s, 'timeout') }), TRANSITION.timeoutMs)
103
+ }
104
+ function themeAck(key: string, data: Record<string, unknown>): void {
105
+ const s = sw
106
+ if (!s || data.t !== s.t || data.theme !== s.to || s.acked.has(key)) return
107
+ s.acked.add(key)
108
+ s.times.push(now() - s.at)
109
+ if (s.acked.size >= themeSize(s)) themeEnd(s, 'done')
110
+ }
111
+
112
+ /** The nodes whose resolved theme this change moved. */
113
+ function themeMoved(s: State, prev: State): string[] {
114
+ if (s.nodes === prev.nodes) return []
115
+ let was: Map<string, State['nodes'][number]> | undefined
116
+ const out: string[] = []
117
+ s.nodes.forEach((n, i) => {
118
+ let p: State['nodes'][number] | undefined = prev.nodes[i]
119
+ if (p === n) return
120
+ if (p?.key !== n.key) p = (was ??= new Map(prev.nodes.map((x) => [x.key, x]))).get(n.key)
121
+ if (p && p.theme !== n.theme) out.push(n.key)
122
+ })
123
+ return out
124
+ }
125
+ /** A selection pin (`setSelectedTheme`): a moved node whose own pin is the theme it moved to. A manifest's new
126
+ * `meta.theme` moves only nodes with no pin; a view switch clears them all. */
127
+ function pinnedTo(s: State, moved: readonly string[]): string | undefined {
128
+ for (const k of moved) {
129
+ const n = s.nodes.find((x) => x.key === k)
130
+ if (n?.themeUser && n.themeUser === n.theme) return n.theme
131
+ }
132
+ return undefined
133
+ }
134
+ /** The canvas's displayed cohort: on screen, its theme moved, a document there to answer - none under a covering play
135
+ * stage (#22: covered frames are not waited for). */
136
+ function themeCohort(s: State, moved: readonly string[]): Set<string> {
137
+ if (s.play) return new Set()
138
+ const m = new Set(moved)
139
+ return new Set(shownNodes(s).filter((n) => m.has(n.key) && !n.missing && bootOf(iframeOf(n.key))).map((n) => n.key))
140
+ }
141
+ function onStoreTheme(s: State, prev: State): void {
142
+ if (s.play && prev.play && s.play.theme !== prev.play.theme) {
143
+ // Play's own switch changes nothing else; a new session is no switch (its board or its slides differ, PlayInner remounts)
144
+ if (s.board === prev.board && !!s.play.slides === !!prev.play.slides) themeStart('play', s.play.theme, new Set(), true)
145
+ }
146
+ if (s.viewTheme !== prev.viewTheme) { themeStart('view', s.viewTheme, themeCohort(s, themeMoved(s, prev)), false); return }
147
+ if (s.nodes === prev.nodes) return
148
+ const moved = themeMoved(s, prev)
149
+ if (!moved.length) return
150
+ const to = pinnedTo(s, moved)
151
+ if (to) themeStart('selection', to, themeCohort(s, moved), false)
152
+ }
153
+
154
+ // ---- R4: modes -------------------------------------------------------------------------------------------------------
155
+
156
+ /** How a mode's enter is shown: acknowledged by the displayed cohort (#26), the stage's first frame, or two frames. */
157
+ type Shown = 'cohort' | 'first-frame' | 'two-frames'
158
+ const SHOWN: Record<ModeName, Shown> = {
159
+ laser: 'cohort', inspect: 'cohort', comments: 'cohort',
160
+ play: 'first-frame', slides: 'first-frame',
161
+ interact: 'two-frames', 'hide-ui': 'two-frames', 'jam-session': 'two-frames', 'jam-capture': 'two-frames', 'jam-review': 'two-frames', 'jam-lane': 'two-frames',
162
+ }
163
+ /** The first frame of a stage is a cold boot: the command's own deadline (`play`, `slides`: 30 s), not a toggle's 5 s - a
164
+ * slow first frame is the answer that record exists for. */
165
+ const FIRST_FRAME_MS = 30_000
166
+
167
+ interface Enter {
168
+ mode: ModeName; t: string; by?: string; at: number; shown: Shown
169
+ cohort: Set<string>; stage: boolean; acked: Set<string>
170
+ ended?: boolean; timer?: ReturnType<typeof setTimeout>
171
+ }
172
+ interface ModeOn { since: number; errors: number; enter?: Enter }
173
+ const modes = new Map<ModeName, ModeOn>()
174
+ /** The enter still waiting for its cohort: the `t` a laser or a pick message to a document carries */
175
+ let waiting: Enter | null = null
176
+
177
+ function enterEnd(e: Enter, outcome: TransitionOutcome): void {
178
+ if (e.ended) return
179
+ e.ended = true
180
+ clearTimeout(e.timer)
181
+ if (waiting === e) waiting = null
182
+ const ms = Math.round(now() - e.at)
183
+ const firstFrame = e.shown === 'first-frame'
184
+ const frames = SHOWN[e.mode] === 'two-frames' ? undefined : firstFrame || e.stage ? 1 : e.cohort.size
185
+ transitionRecord('mode', {
186
+ mode: e.mode, phase: 'enter', t: e.t, by: e.by,
187
+ ...(outcome === 'done' ? (firstFrame ? { firstFrameMs: ms } : { shownMs: ms }) : {}),
188
+ frames, outcome,
189
+ })
190
+ }
191
+ const twoFrames = (fn: () => void) => requestAnimationFrame(() => requestAnimationFrame(fn))
192
+
193
+ function enter(mode: ModeName): void {
194
+ const m: ModeOn = { since: now(), errors: 0 }
195
+ modes.set(mode, m)
196
+ const s = useStore.getState()
197
+ let shown = SHOWN[mode], stage = false
198
+ let cohort = new Set<string>()
199
+ if (shown === 'cohort') {
200
+ if (s.play) stage = true
201
+ else {
202
+ cohort = new Set(shownNodes(s).filter((n) => n.status === 'ready' && !n.missing && bootOf(iframeOf(n.key))).map((n) => n.key))
203
+ if (!cohort.size) shown = 'two-frames' // no frame to tell: the shell's own chrome is all that shows it
204
+ }
205
+ }
206
+ const e: Enter = { mode, t: newId(), by: currentCmd(), at: now(), shown, cohort, stage, acked: new Set() }
207
+ m.enter = e
208
+ if (shown === 'cohort') {
209
+ if (waiting) enterEnd(waiting, 'superseded')
210
+ waiting = e
211
+ }
212
+ e.timer = setTimeout(hooked('mode', () => enterEnd(e, 'timeout')), shown === 'first-frame' ? FIRST_FRAME_MS : TRANSITION.timeoutMs)
213
+ if (shown === 'two-frames') twoFrames(hooked('mode', () => enterEnd(e, 'done')))
214
+ }
215
+ function exit(mode: ModeName): void {
216
+ const m = modes.get(mode)
217
+ if (!m) return
218
+ modes.delete(mode)
219
+ if (m.enter && !m.enter.ended) enterEnd(m.enter, 'superseded')
220
+ transitionRecord('mode', { mode, phase: 'exit', t: newId(), by: currentCmd(), heldMs: Math.round(now() - m.since), errors: m.errors })
221
+ }
222
+ /** One store's say on its modes: exits first, so a switch from one to another reads in order. */
223
+ function setModes(want: Partial<Record<ModeName, boolean>>): void {
224
+ const names = Object.keys(want) as ModeName[]
225
+ for (const k of names) if (!want[k] && modes.has(k)) exit(k)
226
+ for (const k of names) if (want[k] && !modes.has(k)) enter(k)
227
+ }
228
+ /** An ack counts for the mode being entered only if it shows that mode: the frame applied what the shell asked. */
229
+ function ackShows(mode: ModeName, d: Record<string, unknown>): boolean {
230
+ if (mode === 'comments') return d.pick === true
231
+ if (mode === 'inspect') return d.laser === true && d.inspect === true
232
+ return d.laser === true && d.inspect !== true
233
+ }
234
+ function modeAck(key: string, data: Record<string, unknown>): void {
235
+ const e = waiting
236
+ if (!e || data.t !== e.t || !ackShows(e.mode, data) || e.acked.has(key)) return
237
+ e.acked.add(key)
238
+ if (e.acked.size >= (e.stage ? 1 : e.cohort.size)) enterEnd(e, 'done')
239
+ }
240
+
241
+ const canvasModes = (s: State): Partial<Record<ModeName, boolean>> => ({
242
+ laser: s.laser && !s.laserInspect,
243
+ inspect: s.laser && s.laserInspect,
244
+ interact: s.interact !== null,
245
+ play: !!s.play && !s.play.slides,
246
+ slides: !!s.play?.slides,
247
+ })
248
+ const reviewModes = () => {
249
+ const j = useJamUi.getState()
250
+ return { 'jam-review': j.panel?.kind === 'review', 'jam-lane': j.laneKeys }
251
+ }
252
+
253
+ /** #27: the modes on now, for an error (recorder.ts `logError`). */
254
+ export const modesOn = (): ModeName[] => [...modes.keys()]
255
+ /** #27: an error recorded with these modes on: each exit counts it. */
256
+ export function errorCounted(on: readonly ModeName[]): void {
257
+ for (const k of on) { const m = modes.get(k); if (m) m.errors++ }
258
+ }
259
+
260
+ // ---- R5: the sources -------------------------------------------------------------------------------------------------
261
+
262
+ /** #33, in the shell: 5 a second each for console, api and resource, before anything is formatted. */
263
+ const { perSourcePerSecond } = ERROR_BUDGET.shell
264
+ const budgets = { console: createRate(perSourcePerSecond), api: createRate(perSourcePerSecond), resource: createRate(perSourcePerSecond) }
265
+ function takeSource(source: keyof typeof budgets): boolean {
266
+ if (budgets[source]()) return true
267
+ signalSink.dropped(source, 1)
268
+ return false
269
+ }
270
+
271
+ const onConsole = hooked('console', (args: unknown[]) => {
272
+ if (viteEcho(args) || !takeSource('console')) return
273
+ signalSink.error({ source: 'console', message: formatConsole(args), stack: stackOfArgs(args) })
274
+ })
275
+ const onWarn = hooked('console', () => countWarning('shell', 1))
276
+ /** The shell's own console, wrapped once: the original runs first (#28). */
277
+ function wrapConsole(): void {
278
+ const w = window as { __mvConsoleWrapped?: boolean }
279
+ if (w.__mvConsoleWrapped) return
280
+ w.__mvConsoleWrapped = true
281
+ const error0 = console.error, warn0 = console.warn
282
+ console.error = function (this: Console, ...args: unknown[]) { error0.apply(this, args); onConsole(args) }
283
+ console.warn = function (this: Console, ...args: unknown[]) { warn0.apply(this, args); onWarn() }
284
+ }
285
+
286
+ /** #31: a failure mvFetch saw. A save's 409 is the save-conflict command's outcome; `perf/*` is the recorder's own; a
287
+ * request its caller aborted did not fail. */
288
+ const hasCookie = () => { try { return /(?:^|;\s*)mv_c=/.test(document.cookie) } catch { return true } }
289
+ let cookieSeen = hasCookie()
290
+ function onAnswered(a: Answered): void {
291
+ if (/\/api\/perf\//.test(a.url)) return
292
+ const { status } = a
293
+ if (typeof status === 'number' && status !== 0 && status < 400) return
294
+ if (status === 0 && a.init.signal?.aborted) return
295
+ const route = normRoute(a.url), method = (a.init.method ?? 'GET').toUpperCase()
296
+ if (status === 409 && method === 'PUT' && route === 'boards/:board') return
297
+ // a fresh page's first asks, before its double-submit cookie exists: the refusal primes it and the caller asks again
298
+ // (store.ts `syncWorking`); once the cookie has been seen, a 403 is a 403
299
+ if (status === 403 && !cookieSeen) { cookieSeen = hasCookie(); if (method === 'GET') return }
300
+ if (!takeSource('api')) return
301
+ signalSink.error({ source: 'api', message: `${method} ${route} ${status}`, fields: { route, method, status, ms: Math.round(a.ms) } })
302
+ }
303
+
304
+ /** #29: the shell's `vite:error`; frames ignore the broadcast, so it is recorded once. The server makes `file`
305
+ * repo-relative (it knows the root). */
306
+ function onViteError(p: { err?: { message?: unknown; id?: unknown; plugin?: unknown; loc?: { file?: unknown } } }): void {
307
+ const err = p?.err
308
+ if (!err) return
309
+ const raw = typeof err.loc?.file === 'string' ? err.loc.file : typeof err.id === 'string' ? err.id : undefined
310
+ signalSink.error({
311
+ source: 'vite', message: String(err.message ?? 'vite error'),
312
+ fields: { ...(raw ? { file: raw.split('?')[0] } : {}), ...(typeof err.plugin === 'string' ? { plugin: err.plugin.slice(0, 64) } : {}) },
313
+ })
314
+ }
315
+
316
+ /** #32: the shell's own elements. */
317
+ function onElementError(e: Event): void {
318
+ if (!(e.target instanceof Element)) return
319
+ const r = resourceOf(e.target)
320
+ if (!r || !takeSource('resource')) return
321
+ signalSink.error({ source: 'resource', message: `${r.tag} ${r.url}`, fields: { tag: r.tag as ErrorFields['tag'], url: r.url } })
322
+ }
323
+
324
+ // ---- R6, R5: the minute's rows ---------------------------------------------------------------------------------------
325
+
326
+ interface Minute { rows: Map<string, RenderRow>; warnings: Map<string, number>; timer?: ReturnType<typeof setTimeout> }
327
+ const minutes = new Map<number, Minute>()
328
+ /** Frames post their minute as it ends: the shell writes it a little after, with theirs in it. A later one writes a
329
+ * second record for that minute; readers sum them. */
330
+ const GRACE_MS = 2_000
331
+ const minuteOf = (ms: number) => { const p = periodMs(); return Math.floor(ms / p) * p }
332
+ function slot(minute: number): Minute {
333
+ let m = minutes.get(minute)
334
+ if (m) return m
335
+ m = { rows: new Map(), warnings: new Map() }
336
+ minutes.set(minute, m)
337
+ m.timer = setTimeout(hooked('renders', () => writeMinute(minute)), Math.max(0, minute + periodMs() - Date.now()) + GRACE_MS)
338
+ return m
339
+ }
340
+ function writeMinute(minute: number): void {
341
+ const m = minutes.get(minute)
342
+ if (!m) return
343
+ clearTimeout(m.timer)
344
+ minutes.delete(minute)
345
+ if (m.rows.size) perfSeams.record('renders', { minute, rows: foldRows(m.rows.values()) })
346
+ if (m.warnings.size) perfSeams.record('warnings', topWarnings(m.warnings))
347
+ }
348
+ function countWarning(node: string, n: number): void {
349
+ const w = slot(minuteOf(Date.now())).warnings
350
+ w.set(node, (w.get(node) ?? 0) + n)
351
+ }
352
+ /** a gesture runs now (the shell's own `inGesture`) */
353
+ let moving = false
354
+ /** The Profiler around the shell's root (shell/main.tsx). */
355
+ export const shellRendered = hooked('renders', (_id: string, _phase: string, actual: number) => {
356
+ if (!started) return
357
+ addRow(slot(minuteOf(Date.now())).rows, 'shell', undefined, { commits: 1, ms: actual, maxMs: actual, inGesture: moving ? 1 : 0 })
358
+ })
359
+ /** Another document's minute (`sh:renders`): its numbers are checked, its row added under who it is. */
360
+ function rowFrom(who: string, frame: string | undefined, d: Record<string, unknown>): void {
361
+ const num = (v: unknown) => (typeof v === 'number' && Number.isFinite(v) && v >= 0 ? v : 0)
362
+ if (typeof d.minute !== 'number' || !Number.isFinite(d.minute)) return
363
+ addRow(slot(d.minute).rows, who, frame, { commits: num(d.commits), ms: num(d.ms), maxMs: num(d.maxMs), inGesture: num(d.inGesture) })
364
+ }
365
+
366
+ /** #36: the on-screen frames at a gesture's start hear its start and its end. */
367
+ let inGesture: string[] | null = null
368
+ function tellGesture(keys: readonly string[], on: boolean): void {
369
+ for (const k of keys) { try { iframeOf(k)?.contentWindow?.postMessage({ type: 'sh:gesture', on }, location.origin) } catch { /* its document's timing */ } }
370
+ }
371
+ function onCanvasMotion(m: { camera: boolean; preset: boolean }): void {
372
+ moving = m.camera || m.preset
373
+ if (moving && !inGesture) { inGesture = shownNodes(useStore.getState()).map((n) => n.key); tellGesture(inGesture, true) }
374
+ else if (!moving && inGesture) { tellGesture(inGesture, false); inGesture = null }
375
+ }
376
+
377
+ // ---- the messages ------------------------------------------------------------------------------------------------------
378
+
379
+ const FROM_FRAME_DROPS = ['console', 'resource'] as const
380
+ /** Which node a document was (its `sh:boot`): its last counts come with no source once it has gone, below. */
381
+ const bootNodes = new Map<string, string>()
382
+ function onFrameMessage(node: string, d: Record<string, unknown>): void {
383
+ switch (d.type) {
384
+ case 'sh:boot':
385
+ if (typeof d.boot === 'string') {
386
+ bootNodes.set(d.boot, node)
387
+ if (bootNodes.size > 256) bootNodes.delete(bootNodes.keys().next().value!)
388
+ }
389
+ return
390
+ case 'sh:theme-applied':
391
+ if (sw && !sw.stage && sw.cohort.has(node) && liveFrame(node, d.boot)) themeAck(node, d)
392
+ return
393
+ case 'sh:mode-applied':
394
+ if (waiting && !waiting.stage && waiting.cohort.has(node) && liveFrame(node, d.boot)) modeAck(node, d)
395
+ return
396
+ case 'sh:console':
397
+ if (typeof d.message === 'string' && takeSource('console')) signalSink.error({ source: 'console', frame: typeof d.id === 'string' ? d.id : undefined, message: d.message, stack: d.stack })
398
+ return
399
+ case 'sh:resource-error':
400
+ if (typeof d.url === 'string' && RESOURCE_TAGS.includes(String(d.tag)) && takeSource('resource')) {
401
+ signalSink.error({ source: 'resource', frame: typeof d.id === 'string' ? d.id : undefined, message: `${String(d.tag)} ${d.url}`, fields: { tag: d.tag as ErrorFields['tag'], url: d.url } })
402
+ }
403
+ return
404
+ case 'sh:dropped': {
405
+ // a document since replaced says what it refused too (its final count, a frame reloaded mid-burst)
406
+ const counts = d.counts as Record<string, unknown> | undefined
407
+ for (const k of FROM_FRAME_DROPS) { const n = counts?.[k]; if (typeof n === 'number' && Number.isInteger(n) && n > 0) signalSink.dropped(k, n) }
408
+ return
409
+ }
410
+ case 'sh:warnings':
411
+ if (typeof d.n === 'number' && Number.isInteger(d.n) && d.n > 0) countWarning(node, d.n)
412
+ return
413
+ case 'sh:renders':
414
+ rowFrom(node, typeof d.id === 'string' ? d.id : undefined, d)
415
+ return
416
+ }
417
+ }
418
+ function onStageMessage(d: Record<string, unknown>): void {
419
+ switch (d.type) {
420
+ case 'sh:theme-applied':
421
+ if (sw?.stage && d.boot === liveStageBoot()) themeAck('stage', d)
422
+ return
423
+ case 'sh:mode-applied':
424
+ if (waiting?.stage && d.boot === liveStageBoot()) modeAck('stage', d)
425
+ return
426
+ case 'sh:stage-shown':
427
+ // #26: the first frame of the stage up now
428
+ for (const k of ['play', 'slides'] as const) {
429
+ const e = modes.get(k)?.enter
430
+ if (e && !e.ended && d.boot === liveStageBoot()) enterEnd(e, 'done')
431
+ }
432
+ return
433
+ case 'sh:renders':
434
+ rowFrom('stage', undefined, d)
435
+ return
436
+ }
437
+ }
438
+
439
+ /** A document's last counts, posted at its `pagehide` (#33: a frame reloaded mid-burst): by the time they arrive it has
440
+ * gone, so the message has no source and App.tsx's registry knows nothing of it. Counts only, and only from this origin. */
441
+ function onGoneMessage(e: MessageEvent): void {
442
+ if (e.source !== null || e.origin !== location.origin) return
443
+ const d = e.data as Record<string, unknown> | null
444
+ if (d?.type !== 'sh:dropped' && d?.type !== 'sh:warnings' && d?.type !== 'sh:renders') return
445
+ if (d.id === 'stage') onStageMessage(d)
446
+ else onFrameMessage(bootNodes.get(String(d.boot)) ?? 'others', d)
447
+ }
448
+
449
+ // ---- start -------------------------------------------------------------------------------------------------------------
450
+
451
+ /** recorder.ts `startRecorder`, at the full level: the watchers and listeners. */
452
+ export function startSignals(): void {
453
+ if (started) return
454
+ started = true
455
+
456
+ // what is on already counts from here, with no enter record of its own
457
+ const s0 = useStore.getState()
458
+ const held = { ...canvasModes(s0), comments: useComments.getState().commentMode, 'hide-ui': isHideUI(), 'jam-session': !!useJamQueue.getState().session, 'jam-capture': !!useJamCapture.getState().current, ...reviewModes() }
459
+ for (const k of Object.keys(held) as ModeName[]) if (held[k]) modes.set(k, { since: now(), errors: 0 })
460
+
461
+ // #21, #26: the `t` a message to a document carries
462
+ perfSeams.transition = (kind) => (kind === 'theme' ? sw?.t : waiting?.t)
463
+
464
+ // the store's own turn: a theme or a mode change is seen before anything renders, so the effects that post it read `t`
465
+ useStore.subscribe(hooked('theme', onStoreTheme))
466
+ useStore.subscribe(hooked('mode', (s: State, prev: State) => {
467
+ if (s.laser !== prev.laser || s.laserInspect !== prev.laserInspect || s.interact !== prev.interact || s.play !== prev.play) setModes(canvasModes(s))
468
+ }))
469
+ useComments.subscribe(hooked('mode', (s: { commentMode: boolean }, p: { commentMode: boolean }) => { if (s.commentMode !== p.commentMode) setModes({ comments: s.commentMode }) }))
470
+ useJamQueue.subscribe(hooked('mode', (s: { session: unknown }, p: { session: unknown }) => { if (s.session !== p.session) setModes({ 'jam-session': !!s.session }) }))
471
+ useJamCapture.subscribe(hooked('mode', (s: { current: string | null }, p: { current: string | null }) => { if (s.current !== p.current) setModes({ 'jam-capture': !!s.current }) }))
472
+ useJamUi.subscribe(hooked('mode', () => setModes(reviewModes())))
473
+ onHideUI(hooked('mode', () => setModes({ 'hide-ui': isHideUI() })))
474
+
475
+ perfSeams.frameMessage.on(hooked(null, onFrameMessage))
476
+ perfSeams.stageMessage.on(hooked(null, onStageMessage))
477
+ addEventListener('message', hooked(null, onGoneMessage))
478
+ perfSeams.answered.on(hooked(null, onAnswered))
479
+ onMotion(hooked(null, onCanvasMotion))
480
+ wrapConsole()
481
+ addEventListener('error', hooked(null, onElementError), true)
482
+ if (import.meta.hot) import.meta.hot.on('vite:error', hooked(null, onViteError))
483
+ // before the page's last records go (recorder.ts `leave`, in the same event): capture runs first at the target
484
+ addEventListener('pagehide', hooked('renders', () => { for (const m of [...minutes.keys()]) writeMinute(m) }), true)
485
+ }