@marver-design/marver 0.28.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 (105) hide show
  1. package/CHANGELOG.md +103 -0
  2. package/README.md +4 -3
  3. package/dist/{anchor-check-PHUOFj1N.mjs → anchor-check-c52IDkiQ.mjs} +1 -1
  4. package/dist/{build-BsAyLMT1.mjs → build-C3mUtjEn.mjs} +7 -4
  5. package/dist/{capture-DdZ6xgoz.mjs → capture-DEtM4qm5.mjs} +168 -5
  6. package/dist/cli.mjs +11 -11
  7. package/dist/{comments-CrBHPEQl.mjs → comments-XNhMmSSu.mjs} +2 -2
  8. package/dist/{connectors-MR9d-EBP.mjs → connectors-DekQvKt9.mjs} +3 -1
  9. package/dist/{daemon-C5dg2R-V.mjs → daemon-B0Wi1OQ3.mjs} +30 -29
  10. package/dist/{dev-D7YS7iT2.mjs → dev-5dlxoW28.mjs} +19 -14
  11. package/dist/{init-WE5lQkQL.mjs → init-CYlFaRzG.mjs} +1 -1
  12. package/dist/logo-CXY-1yrn.mjs +305 -0
  13. package/dist/{ls-BZ5TAtd5.mjs → ls-NqmePKOf.mjs} +1 -1
  14. package/dist/{marks-Kmdab_5w.mjs → marks-BnNANic9.mjs} +20 -1
  15. package/dist/{marks-Dyn6tmjp.mjs → marks-DBp3h1Mc.mjs} +2 -5
  16. package/dist/{marver-id-gate-D-R0hSt_.mjs → marver-id-gate-vBLb_Icb.mjs} +1 -1
  17. package/dist/{perf-Cn5LiRaY.mjs → perf-6MOTHxay.mjs} +751 -122
  18. package/dist/perf-BCxAo0IS.mjs +1743 -0
  19. package/dist/{plugin-C_0yb-Fq.mjs → plugin-CXRoMA8g.mjs} +1382 -810
  20. package/dist/{poster-DHi6I1fO.mjs → poster-CYmCa00B.mjs} +1 -1
  21. package/dist/{profile-jIS6BcAs.mjs → profile-B1FKOM1e.mjs} +1 -1
  22. package/dist/{publish-bakes-r4PEZuPl.mjs → publish-bakes-C_2ZtHou.mjs} +3 -3
  23. package/dist/{queue-c-6aTHEz.mjs → queue-DeSQm24g.mjs} +29 -14
  24. package/dist/{recover-nrLEVLyJ.mjs → recover-XD8iXJOj.mjs} +2 -2
  25. package/dist/{serve-Dp3nHstu.mjs → serve-DQv3Ti6X.mjs} +8 -4
  26. package/dist/{session-DyVE7cCk.mjs → session-VDJfXEEm.mjs} +1 -1
  27. package/dist/{share-Ce4tP7ji.mjs → share-Bu_kuOKL.mjs} +1 -1
  28. package/dist/{shot-BrRtqaiS.mjs → shot-CRRGgxru.mjs} +3 -3
  29. package/dist/{slots-CFNnegCc.mjs → slots-Dn4Onb0V.mjs} +101 -3
  30. package/dist/{sync-CQdGARJ9.mjs → sync-CMozOwZ0.mjs} +1 -1
  31. package/docs/app.md +194 -0
  32. package/docs/boards-and-folders.md +11 -0
  33. package/docs/jam-session.md +12 -3
  34. package/docs/live-jam.md +3 -0
  35. package/docs/performance.md +99 -19
  36. package/docs/publish.md +7 -0
  37. package/package.json +1 -1
  38. package/src/client/frame-host/bridge.js +17 -8
  39. package/src/client/frame-host/inplace.ts +124 -0
  40. package/src/client/frame-host/inspect.d.ts +1 -0
  41. package/src/client/frame-host/inspect.js +13 -4
  42. package/src/client/frame-host/main.tsx +12 -3
  43. package/src/client/frame-host/messages.ts +85 -0
  44. package/src/client/frame-host/signals.d.ts +15 -0
  45. package/src/client/frame-host/signals.js +219 -0
  46. package/src/client/recorder-level.ts +41 -0
  47. package/src/client/shell/App.tsx +158 -88
  48. package/src/client/shell/BoardList.tsx +103 -48
  49. package/src/client/shell/Comments.tsx +71 -46
  50. package/src/client/shell/ContextMenu.tsx +8 -6
  51. package/src/client/shell/JamSurface.tsx +187 -71
  52. package/src/client/shell/LockedApp.tsx +19 -3
  53. package/src/client/shell/Play.tsx +110 -62
  54. package/src/client/shell/StatusPicker.tsx +19 -9
  55. package/src/client/shell/Toolbar.tsx +15 -7
  56. package/src/client/shell/api.ts +25 -7
  57. package/src/client/shell/app-bridge.ts +23 -9
  58. package/src/client/shell/app-perf.ts +31 -1
  59. package/src/client/shell/canvas/Canvas.tsx +17 -6
  60. package/src/client/shell/canvas/FrameNode.tsx +25 -12
  61. package/src/client/shell/canvas/Sticky.tsx +4 -2
  62. package/src/client/shell/canvas/ctl.ts +2 -0
  63. package/src/client/shell/canvas/ready-watch.ts +4 -0
  64. package/src/client/shell/canvas/sleep.ts +2 -0
  65. package/src/client/shell/canvas/updates.ts +13 -6
  66. package/src/client/shell/commands.ts +765 -0
  67. package/src/client/shell/comments-store.ts +56 -27
  68. package/src/client/shell/goto.ts +15 -9
  69. package/src/client/shell/jam-capture.ts +39 -15
  70. package/src/client/shell/jam-keys.ts +303 -111
  71. package/src/client/shell/jam-lane.tsx +19 -12
  72. package/src/client/shell/jam-lines.ts +10 -1
  73. package/src/client/shell/jam-panel.tsx +68 -53
  74. package/src/client/shell/jam-queue.ts +6 -1
  75. package/src/client/shell/jam-session.tsx +41 -37
  76. package/src/client/shell/jam-state.ts +28 -5
  77. package/src/client/shell/jam-surface-parts.tsx +8 -6
  78. package/src/client/shell/jam-ui.tsx +12 -5
  79. package/src/client/shell/jam-voice.ts +4 -2
  80. package/src/client/shell/live-picture.ts +134 -0
  81. package/src/client/shell/main.tsx +7 -1
  82. package/src/client/shell/marks-ui.tsx +11 -0
  83. package/src/client/shell/open-item.ts +83 -0
  84. package/src/client/shell/open-resolve.ts +50 -0
  85. package/src/client/shell/perf.ts +51 -5
  86. package/src/client/shell/recorder-core.ts +4 -1
  87. package/src/client/shell/recorder-hmr.ts +36 -0
  88. package/src/client/shell/recorder-reloads.ts +264 -0
  89. package/src/client/shell/recorder-seams.ts +116 -0
  90. package/src/client/shell/recorder-self.ts +73 -0
  91. package/src/client/shell/recorder-signals-core.ts +139 -0
  92. package/src/client/shell/recorder-signals.ts +485 -0
  93. package/src/client/shell/recorder.ts +115 -41
  94. package/src/client/shell/store.ts +62 -24
  95. package/src/client/shell/styles.css +2 -0
  96. package/src/client/shell/whiteout-probes.ts +3 -1
  97. package/src/client/stage/main.tsx +39 -12
  98. package/src/shared/app-api.ts +201 -9
  99. package/src/shared/app-perf.ts +103 -8
  100. package/src/shared/app-report.ts +586 -0
  101. package/src/shared/perf-records.ts +445 -0
  102. package/src/shared/perf-run.ts +6 -2
  103. package/templates/instructions/jam.md +4 -0
  104. package/dist/live-Cgzsicwi.mjs +0 -4
  105. package/dist/perf-jam-QxD_UnzN.mjs +0 -635
@@ -0,0 +1,116 @@
1
+ /**
2
+ * The page recorder's seams (spec 30): what the shared shell files call and the spec 30 streams fill, so each stream's
3
+ * work stays in its own module. Dependency-free (recorder-core.ts and types only): store.ts, api.ts, App.tsx, Play.tsx
4
+ * and every stream module import it without a cycle - recorder.ts imports store.ts, so a stream module that store.ts
5
+ * or api.ts reaches must never import recorder.ts at its top level for a value it reads at load.
6
+ *
7
+ * Two shapes, as store.ts's `recorderHooks`: a settable function where one owner answers (a header, a transition id),
8
+ * and a tap (listeners, each run in a try, never in the way) where several streams listen to one point. Every tap is
9
+ * silent until a stream subscribes, and the streams subscribe only from their starters (recorder.ts `startRecorder`,
10
+ * never under the `core` level), so a published canvas, a `core` run and a page without the recorder pay one call.
11
+ *
12
+ * FROZEN before the spec 30 streams split. Who fills what (.r30-contracts.md has the whole map):
13
+ * - `record`, `load`, `leaving`: recorder.ts (the page recorder writes through `record`; its loads' phases and its
14
+ * `pagehide` are told to whoever listens - commands' `board-open`, app-store's `watch load`, edits' reload Outbox);
15
+ * - `requestHeaders`: edits (#18: a board write's `x-mv-page` and `x-mv-cmds`, from commands.ts `cmdsForWrite`);
16
+ * - `answered`: signals (#31: `api` errors), commands (#49: a write's or a call's answer ends its commands);
17
+ * - `frameMessage`, `stageMessage`: signals (acks with `t`, `sh:mode-applied`, `sh:dropped`, `sh:renders`,
18
+ * `sh:console`, `sh:resource-error`), edits (`sh:inplace`), commands (`sh:stage-shown` ends play commands);
19
+ * - `transition`: signals (#21: the `t` FrameNode and Play send with `sh:set-theme`, `sh:laser` and `sh:pick`);
20
+ * - `selfCost`: app-store (#58: `self` records' `hookMs`), charged by every stream through `hooked()`.
21
+ */
22
+ import { newId } from './recorder-core.ts'
23
+ import { busyWait, SLOW_HOOK, SLOW_HOOK_MS } from '../recorder-level.ts'
24
+ import type { LoadTrigger, PageKind, SelfHook } from '../../shared/perf-records.ts'
25
+ import type { LoadCause } from './store.ts'
26
+
27
+ /** This document, in every record (and, in the app, in its hello: the app's records about this tab carry it). */
28
+ export const PAGE_ID = newId()
29
+
30
+ let seq = 0
31
+ /** The page's one record order (spec 30 #7, #16): page records and reload lines share it, so `(page, seq)` names one
32
+ * record of this page whichever file it lands in. */
33
+ export const nextSeq = (): number => seq++
34
+
35
+ type Listener<A extends unknown[]> = (...a: A) => void
36
+ /** Listeners at one point: each runs in a try - a stream's hook never stands in the way, nor stops another's (#5). */
37
+ export interface Tap<A extends unknown[]> {
38
+ on(fn: Listener<A>): () => void
39
+ emit(...a: A): void
40
+ readonly size: number
41
+ }
42
+ export function tap<A extends unknown[]>(): Tap<A> {
43
+ const fns = new Set<Listener<A>>()
44
+ return {
45
+ on(fn) { fns.add(fn); return () => { fns.delete(fn) } },
46
+ emit(...a) { if (fns.size) for (const fn of [...fns]) { try { fn(...a) } catch { /* never in the way */ } } },
47
+ get size() { return fns.size },
48
+ }
49
+ }
50
+
51
+ /** A request mvFetch sent and how it ended: `status` the HTTP status, 0 the network, `timeout` its abort signal's
52
+ * timeout. `headers` as sent (the board write's `x-mv-cmds` among them). Never a body. */
53
+ export interface Answered { url: string; init: RequestInit; headers: Record<string, string> | undefined; status: number | 'timeout'; ms: number }
54
+
55
+ /** Why a load or a request ended unsettled (the server's `CUT_REASONS`). */
56
+ export type CutReason = 'switch' | 'reload' | 'hidden' | 'timeout' | 'superseded' | 'error' | 'edited' | 'unsaved'
57
+ /**
58
+ * A load's way, as the page recorder sees it (its records carry the same ids). `request`: asked for (#38's `load`
59
+ * window opens here); `visible`: the cohort chosen (`assumed` when no fit landed); `commit` (`late`: a request already
60
+ * cut mounted all the same); `settled`; `cut` (`request`: before it committed). `visible-ready` - the cohort's frames
61
+ * all ready (#49's step) - is the commands stream's to emit, from progress() (recorder.ts).
62
+ */
63
+ export type LoadPhase =
64
+ | { phase: 'request'; load: string; board: string; cause: LoadCause; trigger?: LoadTrigger }
65
+ | { phase: 'visible'; load: string; nodes: number; assumed?: true }
66
+ | { phase: 'visible-ready'; load: string }
67
+ | { phase: 'commit'; load: string; late?: true }
68
+ | { phase: 'settled'; load: string }
69
+ | { phase: 'cut'; load: string; reason: CutReason; request?: true }
70
+
71
+ /** The transitions whose id a message to a document carries (#21, #26). */
72
+ export type TransitionKind = 'theme' | 'mode'
73
+
74
+ export const perfSeams = {
75
+ /** recorder.ts sets it: true while the page records (dev, not published, a workspace) */
76
+ on: false,
77
+ /** recorder.ts sets it: a record of `kind` into page.jsonl, through the page's envelope (`page`, `seq`, `ts`) and
78
+ * outbox; `load` the load that owns the geometry unless given. Nothing while the page does not record */
79
+ record: (_kind: PageKind, _body: Record<string, unknown>, _load?: string): void => {},
80
+ /** recorder.ts: each load's phases */
81
+ load: tap<[p: LoadPhase]>(),
82
+ /** recorder.ts, at `pagehide`, after the page's own last records went (#7's order: Jam's captures, page records
83
+ * 16 KB, then reload lines 8 KB) - never while a capture holds the keepalive allowance */
84
+ leaving: tap<[]>(),
85
+ /** mvFetch (api.ts), before it sends a request this page's canvas will answer: headers to add, or undefined */
86
+ requestHeaders: (_url: string, _init: RequestInit): Record<string, string> | undefined => undefined,
87
+ /** mvFetch (api.ts): every request that got an answer or failed - `perf/*` included; a listener skips what it must */
88
+ answered: tap<[a: Answered]>(),
89
+ /** App.tsx: every `sh:*` message from a registered frame, before the shell handles it (a listener checks the
90
+ * document itself - `fromLiveDocument` - and never consumes the message) */
91
+ frameMessage: tap<[node: string, data: Record<string, unknown>]>(),
92
+ /** Play.tsx: every message from the play stage's live iframe, before the shell handles it */
93
+ stageMessage: tap<[data: Record<string, unknown>]>(),
94
+ /** FrameNode.tsx and Play.tsx, as they post a theme or a mode to a document: the transition it belongs to, or none */
95
+ transition: (_kind: TransitionKind): string | undefined => undefined,
96
+ /** app-store (#58): a hook's own time, by hook - `hooked()` charges it */
97
+ selfCost: (_hook: SelfHook, _ms: number): void => {},
98
+ }
99
+
100
+ let hookDepth = 0
101
+ /** Is a measured hook running? (`self` counts a record written inside one as that hook's.) */
102
+ export const insideHook = (): boolean => hookDepth > 0
103
+
104
+ /** A stream's hook, as recorder.ts's `guard`: nothing while the page does not record, never in the way - and its time
105
+ * charged to `hook` in `self` (#58) when it is one of the measured hooks. `?mvslowhook=<hook>` adds the cost run's
106
+ * injected wait here (recorder-level.ts, test only). */
107
+ export function hooked<A extends unknown[]>(hook: SelfHook | null, fn: (...a: A) => void): (...a: A) => void {
108
+ return (...a) => {
109
+ if (!perfSeams.on) return
110
+ const t0 = hook ? performance.now() : 0
111
+ if (hook) hookDepth++
112
+ if (hook && hook === SLOW_HOOK) busyWait(SLOW_HOOK_MS)
113
+ try { fn(...a) } catch { /* never in the way */ }
114
+ if (hook) { hookDepth--; try { perfSeams.selfCost(hook, performance.now() - t0) } catch { /* the same */ } }
115
+ }
116
+ }
@@ -0,0 +1,73 @@
1
+ /**
2
+ * The recorder's own cost (spec 30 R15 #58): every 5 minutes in which it recorded anything, a `self` record - `cpuMs`,
3
+ * `hookMs` by hook (charged through recorder-seams.ts `hooked()`, which calls `perfSeams.selfCost`), `records`,
4
+ * `bytes`, `dropped`. Also the page's `load` white-out window (R8 #38): from a load's request to its settled or cut,
5
+ * asked of the Mac app through app-perf.ts `watchWindow`. Owner: the app-store stream.
6
+ *
7
+ * recorder.ts calls `startSelf()` once, at the full level only, after the page recorder is on; under `core` nothing here
8
+ * runs and `selfCounts.on` stays false. `cpuMs` is what the recorder's code took on this thread as far as it can tell:
9
+ * the measured hooks and `rec()` outside them. `performance.now()` is coarse in a page (100 µs), so a figure is a sum
10
+ * of coarse readings, right on average and never to the microsecond.
11
+ */
12
+ import { SELF_MS, type SelfBody, type SelfHook } from '../../shared/perf-records.ts'
13
+ import { SLOW_HOOK, SLOW_HOOK_MS, busyWait } from '../recorder-level.ts'
14
+ import { watchWindow } from './app-perf.ts'
15
+ import { insideHook, perfSeams, type LoadPhase } from './recorder-seams.ts'
16
+
17
+ /** What recorder.ts's `rec()` and `send()` add to, read here; `on` keeps them silent under `core`. */
18
+ export const selfCounts = {
19
+ on: false,
20
+ records: 0,
21
+ bytes: 0,
22
+ dropped: 0,
23
+ /** `rec()` outside any hook (a hook's own time holds the records it writes) */
24
+ recMs: 0,
25
+ /** recorder.ts `rec()`, as it returns */
26
+ record(ms: number): void { this.records++; if (!insideHook()) this.recMs += ms },
27
+ }
28
+ let hookMs: Partial<Record<SelfHook, number>> = {}
29
+
30
+ const tenth = (n: number) => Math.round(n * 10) / 10
31
+
32
+ /** The period's record, when it recorded anything; the counts start over either way. */
33
+ export function writeSelf(): void {
34
+ if (selfCounts.records > 0) {
35
+ const hooks = Object.entries(hookMs).reduce((n, [, v]) => n + (v ?? 0), 0)
36
+ const body: SelfBody = {
37
+ cpuMs: tenth(hooks + selfCounts.recMs),
38
+ hookMs: Object.fromEntries(Object.entries(hookMs).map(([k, v]) => [k, tenth(v ?? 0)])),
39
+ records: selfCounts.records,
40
+ bytes: selfCounts.bytes,
41
+ dropped: selfCounts.dropped,
42
+ }
43
+ perfSeams.record('self', body as unknown as Record<string, unknown>)
44
+ }
45
+ selfCounts.records = 0
46
+ selfCounts.bytes = 0
47
+ selfCounts.dropped = 0
48
+ selfCounts.recMs = 0
49
+ hookMs = {}
50
+ }
51
+
52
+ /** #38: one window per load, open from its request until it settled or was cut. */
53
+ function loadWindows(): void {
54
+ const open = new Set<string>()
55
+ perfSeams.load.on((p: LoadPhase) => {
56
+ if (p.phase === 'request') { open.add(p.load); watchWindow('load', true); return }
57
+ if ((p.phase === 'settled' || p.phase === 'cut') && open.delete(p.load)) watchWindow('load', false)
58
+ })
59
+ }
60
+
61
+ /** recorder.ts `startRecorder`, at the full level. */
62
+ export function startSelf(): void {
63
+ selfCounts.on = true
64
+ perfSeams.selfCost = (hook, ms) => { hookMs[hook] = (hookMs[hook] ?? 0) + ms }
65
+ loadWindows()
66
+ setInterval(writeSelf, SELF_MS)
67
+ // #58's test-only switch (`?mvslowhook=console`): the console's way through this page costs 5 ms more, so the cost
68
+ // run must fail. `hooked('console', ...)` waits too (recorder-seams.ts); this holds for any console.error of the shell.
69
+ if (SLOW_HOOK === 'console') {
70
+ const was = console.error
71
+ console.error = (...a: unknown[]) => { busyWait(SLOW_HOOK_MS); was.apply(console, a) }
72
+ }
73
+ }
@@ -0,0 +1,139 @@
1
+ /**
2
+ * The pure parts of the page's signals (spec 30 R5, R6), kept apart from the browser-coupled module so they can be
3
+ * unit-tested (recorder-core.ts's precedent): a request's route without its names, a gesture's three longest Long
4
+ * Animation Frames and what they ran, a minute's heaviest re-render rows and warning nodes, a source's rate, the
5
+ * nodes a view shows. No imports but types and constants.
6
+ */
7
+ import { LOAF, RENDERS, WARNINGS, type Loaf, type RenderRow } from '../../shared/perf-records.ts'
8
+
9
+ // ---- #31: a request's route -----------------------------------------------------------------------------------------
10
+
11
+ /** The routes the dev server answers whose every segment is a fixed word: said as they are. */
12
+ const FIXED = new Set([
13
+ 'policy', 'boards', 'boards/status', 'boards/pin', 'boards/rename', 'boards/reorder', 'boards.rights', 'scenes/rename',
14
+ 'sizes', 'folders', 'membership', 'shot', 'shots', 'anchor', 'bakes', 'poster', 'me', 'profile', 'marks', 'marks/seen',
15
+ 'work', 'seen', 'update', 'sync', 'request-access', 'invite-info', 'auth/signin', 'auth/claim', 'hello',
16
+ 'jam/queue', 'jam/card', 'jam/audio-ticket', 'jam/voice', 'jam/session', 'jam/run', 'jam/prefs', 'jam/capture-open',
17
+ 'jam/record', 'jam/capture', 'jam/picture', 'jam/picture/live',
18
+ ])
19
+ /** Everything after the first segment that is not a fixed word is a name or an id. */
20
+ const WORD = /^[a-z][a-z-]*$/
21
+ /**
22
+ * #31: a request's route, ids and names replaced (`boards/:board`), never a query. Under the API: its path after
23
+ * `/api/`, a known route as it is, `boards/<x>` and `comments/<x>` by what `<x>` is, anything else its first word and
24
+ * `:id` for the rest. Elsewhere: the first segment, the rest `:path` - `design/manifest.json` is the one fixed name.
25
+ */
26
+ export function normRoute(url: string): string {
27
+ const path = url.replace(/^[a-z]+:\/\/[^/]+/i, '').split(/[?#]/)[0]
28
+ const api = /(?:^|\/)api\/(.*)$/.exec(path)
29
+ if (api) {
30
+ const rel = api[1].replace(/\/+$/, '')
31
+ if (FIXED.has(rel)) return rel
32
+ const segs = rel.split('/')
33
+ if (segs[0] === 'boards' && segs.length === 2) return 'boards/:board'
34
+ if (segs[0] === 'comments' && segs.length === 2) return 'comments/:board'
35
+ return segs.map((s, i) => (i === 0 && WORD.test(s) ? s : ':id')).join('/')
36
+ }
37
+ const rel = path.replace(/^\/+/, '')
38
+ if (rel === 'design/manifest.json') return rel
39
+ const segs = rel.split('/').filter(Boolean)
40
+ return segs.length ? `${WORD.test(segs[0]) ? segs[0] : ':path'}${segs.length > 1 ? '/:path' : ''}` : '/'
41
+ }
42
+
43
+ // ---- #35: a gesture's Long Animation Frames ----------------------------------------------------------------------
44
+
45
+ /** What this module reads of a `PerformanceScriptTiming`. */
46
+ export interface LoafScript { duration: number; sourceURL?: string; sourceFunctionName?: string; invoker?: string; windowAttribution?: string; window?: unknown }
47
+ /** What this module reads of a `long-animation-frame` entry; a `longtask` entry (Safari, Firefox) has `duration` alone. */
48
+ export interface LoafEntry { startTime?: number; duration: number; blockingDuration?: number; scripts?: readonly LoafScript[] }
49
+
50
+ /** A URL's path, no query, no host; '' when it is not one. */
51
+ export function urlPath(raw: string | undefined): string {
52
+ if (!raw) return ''
53
+ try { return new URL(raw, 'http://x').pathname } catch { return '' }
54
+ }
55
+ /** Keep the `kept` longest as they arrive (a heavy gesture has many, and an entry holds its scripts' windows). */
56
+ export function keepLongest(top: LoafEntry[], e: LoafEntry, kept: number = LOAF.kept): void {
57
+ top.push(e)
58
+ top.sort((a, b) => b.duration - a.duration)
59
+ if (top.length > kept) top.length = kept
60
+ }
61
+ /**
62
+ * #35: the longest frames, longest first: `ms`, `blockMs`, and the longest script's `src` (a URL path, no query),
63
+ * `frame` (what `frameOf` makes of its path and its window: a frame's module path names the frame), `fn` (64
64
+ * characters), `invoker` (no query, 64 characters), `ms` and `where` (`windowAttribution`). A `longtask` entry: `ms` alone.
65
+ */
66
+ export function pickLoafs(entries: readonly LoafEntry[], frameOf: (src: string, win: unknown) => string | undefined, kept: number = LOAF.kept): Loaf[] {
67
+ return [...entries].sort((a, b) => b.duration - a.duration).slice(0, kept).map((e) => {
68
+ const out: Loaf = { ms: Math.round(e.duration) }
69
+ if (typeof e.blockingDuration === 'number') out.blockMs = Math.round(e.blockingDuration)
70
+ const s = e.scripts?.length ? e.scripts.reduce((a, b) => (b.duration > a.duration ? b : a)) : undefined
71
+ if (s) {
72
+ const src = urlPath(s.sourceURL)
73
+ const frame = frameOf(src, s.window)
74
+ out.script = {
75
+ ms: Math.round(s.duration),
76
+ ...(src ? { src } : {}),
77
+ ...(frame ? { frame } : {}),
78
+ ...(s.sourceFunctionName ? { fn: s.sourceFunctionName.slice(0, LOAF.fn) } : {}),
79
+ ...(s.invoker ? { invoker: s.invoker.replace(/[?#].*$/, '').slice(0, LOAF.fn) } : {}),
80
+ ...(s.windowAttribution ? { where: s.windowAttribution } : {}),
81
+ }
82
+ }
83
+ return out
84
+ })
85
+ }
86
+
87
+ // ---- #36, #28: a minute's rows -------------------------------------------------------------------------------------
88
+
89
+ /** One minute's accumulating row (`who`, `frame`). */
90
+ export function addRow(rows: Map<string, RenderRow>, who: string, frame: string | undefined, r: { commits: number; ms: number; maxMs: number; inGesture: number }): void {
91
+ const cur = rows.get(who)
92
+ if (!cur) { rows.set(who, { who, ...(frame ? { frame } : {}), commits: r.commits, ms: r.ms, maxMs: r.maxMs, inGesture: r.inGesture }); return }
93
+ cur.commits += r.commits; cur.ms += r.ms; cur.inGesture += r.inGesture
94
+ if (r.maxMs > cur.maxMs) cur.maxMs = r.maxMs
95
+ if (frame) cur.frame = frame
96
+ }
97
+ /** #36: the `max` heaviest rows by `ms`, the rest folded into one `others` row that says how many it holds. */
98
+ export function foldRows(rows: Iterable<RenderRow>, max: number = RENDERS.rows): RenderRow[] {
99
+ const tenth = (x: number) => Math.round(x * 10) / 10
100
+ const all = [...rows].sort((a, b) => b.ms - a.ms).map((r) => ({ ...r, ms: tenth(r.ms), maxMs: tenth(r.maxMs) }))
101
+ if (all.length <= max) return all
102
+ const rest = all.slice(max)
103
+ const others: RenderRow = { who: 'others', commits: 0, ms: 0, maxMs: 0, inGesture: 0, rows: rest.length }
104
+ for (const r of rest) { others.commits += r.commits; others.ms += r.ms; others.inGesture += r.inGesture; if (r.maxMs > others.maxMs) others.maxMs = r.maxMs }
105
+ others.ms = tenth(others.ms)
106
+ return [...all.slice(0, max), others]
107
+ }
108
+ /** #28: the minute's total, and the `top` nodes with most. */
109
+ export function topWarnings(by: ReadonlyMap<string, number>, top: number = WARNINGS.top): { n: number; top: { node: string; n: number }[] } {
110
+ let n = 0
111
+ for (const c of by.values()) n += c
112
+ return { n, top: [...by].sort((a, b) => b[1] - a[1]).slice(0, top).map(([node, c]) => ({ node, n: c })) }
113
+ }
114
+
115
+ // ---- rates, percentiles, what a view shows --------------------------------------------------------------------------
116
+
117
+ /** At most `perSecond` in each wall second (the rule the frames' budget keeps). */
118
+ export function createRate(perSecond: number, now: () => number = () => performance.now()): () => boolean {
119
+ let sec = NaN, inSec = 0
120
+ return () => {
121
+ const s = Math.floor(now() / 1000)
122
+ if (s !== sec) { sec = s; inSec = 0 }
123
+ if (inSec >= perSecond) return false
124
+ inSec++
125
+ return true
126
+ }
127
+ }
128
+ /** The nearest-rank median of `xs` (cli/perf.ts `spread`'s rule), undefined with none. */
129
+ export function p50(xs: readonly number[]): number | undefined {
130
+ if (!xs.length) return undefined
131
+ const v = [...xs].sort((a, b) => a - b)
132
+ return v[Math.min(v.length - 1, Math.ceil(0.5 * v.length) - 1)]
133
+ }
134
+ /** A node's title bar is part of its box (FrameNode). */
135
+ const HEADER = 28
136
+ /** recorder.ts `cohortIn`: the nodes a view shows. */
137
+ export function nodesIn<N extends { key: string; x: number; y: number; w: number; h: number }>(nodes: readonly N[], v: { x: number; y: number; w: number; h: number }): N[] {
138
+ return nodes.filter((n) => n.x < v.x + v.w && n.x + n.w > v.x && n.y < v.y + v.h && n.y + n.h + HEADER > v.y)
139
+ }