@marver-design/marver 0.29.0 → 0.30.1

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 +60 -0
  2. package/README.md +2 -1
  3. package/dist/{anchor-check-DhlpKl2K.mjs → anchor-check-Bv4o-R2T.mjs} +1 -1
  4. package/dist/{build-CWbrb2bl.mjs → build-zWGXSzly.mjs} +5 -4
  5. package/dist/cli.mjs +5 -5
  6. package/dist/{daemon-Sc_z8gT6.mjs → daemon-CChgWJNq.mjs} +2 -2
  7. package/dist/{dev-DWBKQhxf.mjs → dev-DOgIITpT.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-CFWBcAba.mjs} +928 -539
  11. package/dist/{poster-CrsjqhY4.mjs → poster-DPPpQiva.mjs} +1 -1
  12. package/dist/{publish-bakes-DW-NDgU2.mjs → publish-bakes-_Zx8crP3.mjs} +2 -2
  13. package/dist/{recover-GtJ9UDAB.mjs → recover-mDUVsnPd.mjs} +1 -1
  14. package/dist/{shot-T04Ixrvq.mjs → shot-d4h_hJi9.mjs} +3 -3
  15. package/docs/app.md +194 -0
  16. package/docs/performance.md +100 -19
  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 +118 -43
  68. package/src/client/shell/store.ts +112 -32
  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,124 @@
1
+ /**
2
+ * In-place updates, what this document saw and no more (spec 30 #15). Vite's client imports `<acceptedPath>?t=<timestamp>`
3
+ * only in a document whose module map holds the module, so a Resource Timing entry for that URL says this document
4
+ * fetched the update; a document that did not writes nothing. Updates only the frame host's registry accepts are left
5
+ * out: it accepts them without applying them (registry.ts), as main.tsx's `sh:hmr` filter does.
6
+ *
7
+ * What it cannot say, it does not: a fetch does not prove the update applied (Vite catches a failed import and still
8
+ * reaches `afterUpdate`), and the next commit need not be the refresh's (Fast Refresh is debounced, an unrelated update
9
+ * can commit first). So `applied` is never true: `'unknown'`, or `false` when Vite's own failure message for that path
10
+ * reached this document's console during the update.
11
+ *
12
+ * Runs only with a hot module at the full level (main.tsx). An observer, not the timeline's buffer: a frame's modules can
13
+ * fill the 250 entries Resource Timing keeps, and an observer still receives what the buffer refuses.
14
+ */
15
+ import { RELOAD_BOUNDS } from '../../shared/perf-records.ts'
16
+ import type { InplaceMsg } from './messages.ts'
17
+
18
+ interface Update { type?: string; path?: string; acceptedPath?: string; timestamp?: number }
19
+ /** The fields only this module knows; main.tsx adds the frame and the document. */
20
+ export type InplaceReport = Omit<InplaceMsg, 'id' | 'boot'>
21
+
22
+ let waiters: ((at: number) => void)[] = []
23
+ /** The frame root committed (the Profiler in main.tsx). */
24
+ export function rootCommitted(): void {
25
+ if (!waiters.length) return
26
+ const at = performance.now()
27
+ for (const w of waiters.splice(0)) w(at)
28
+ }
29
+ /** The next commit's time, or undefined past the wait. */
30
+ function nextCommit(ms: number): Promise<number | undefined> {
31
+ return new Promise((resolve) => {
32
+ const w = (at: number) => { clearTimeout(t); resolve(at) }
33
+ const t = setTimeout(() => { waiters = waiters.filter((x) => x !== w); resolve(undefined) }, ms)
34
+ waiters.push(w)
35
+ })
36
+ }
37
+
38
+ const isRegistry = (u: Update) => (u.acceptedPath ?? u.path ?? '').includes('/frame-host/registry')
39
+ const pathOf = (u: Update) => (u.acceptedPath ?? u.path ?? '').split('?')[0]
40
+ /** The URL Vite's client imports (client.mjs `importUpdatedModule`): this update's path, this update's timestamp. */
41
+ function fetchedBy(u: Update, url: URL): boolean {
42
+ return url.pathname.endsWith(pathOf(u)) && url.searchParams.get('t') === String(u.timestamp)
43
+ }
44
+
45
+ /** Vite's messages run one at a time (its client queues them), so one update round is open at most. It holds what its own
46
+ * updates left behind, no more - the observer sees every resource this document loads - and it ends by
47
+ * `vite:afterUpdate`, or with none (an accept callback threw, an import still pending) by the next update or
48
+ * `inplaceRoundMs`. Those last two write what was known by then, each update fetched so far, `noAfterUpdate`: an update
49
+ * that was seen is never lost silently. A `vite:afterUpdate` after that has no round, and writes nothing more. */
50
+ export function watchInplace(hot: { on(event: string, cb: (p: any) => void): void }, post: (m: InplaceReport) => void): void {
51
+ interface Round { at: number; updates: Update[]; fetched: Set<Update>; take: () => void; failed: Set<string>; close: () => void }
52
+ let round: Round | null = null
53
+ const appliedOf = (r: Round, u: Update) => (r.failed.has(u.acceptedPath ?? u.path ?? '') ? false as const : 'unknown' as const)
54
+ /** A round `afterUpdate` never came for: closed, and what it knew written now. */
55
+ const giveUp = (r: Round) => {
56
+ if (round === r) round = null
57
+ r.take()
58
+ r.close()
59
+ const applyMs = Math.round(performance.now() - r.at)
60
+ for (const u of r.updates) if (r.fetched.has(u)) post({ type: 'sh:inplace', hmrTs: u.timestamp!, applyMs, applied: appliedOf(r, u), noAfterUpdate: true })
61
+ }
62
+
63
+ hot.on('vite:beforeUpdate', (p: { updates?: Update[] }) => {
64
+ try {
65
+ if (round) giveUp(round)
66
+ const updates = (p.updates ?? []).filter((u) => u.type === 'js-update' && !isRegistry(u) && typeof u.timestamp === 'number')
67
+ if (!updates.length) return
68
+ const fetched = new Set<Update>()
69
+ const note = (entries: readonly PerformanceEntry[]) => {
70
+ for (const e of entries) {
71
+ let url: URL
72
+ try { url = new URL(e.name) } catch { continue }
73
+ for (const u of updates) if (fetchedBy(u, url)) fetched.add(u)
74
+ }
75
+ }
76
+ const observer = new PerformanceObserver((list) => note(list.getEntries()))
77
+ observer.observe({ type: 'resource' })
78
+ const paths = new Set(updates.map((u) => u.acceptedPath ?? u.path ?? ''))
79
+ const failed = new Set<string>()
80
+ const original = console.error
81
+ let open = true
82
+ // only while an update is on its way, and the original always runs: Vite's own words for a failed import
83
+ // (client.mjs `warnFailedUpdate`: `[vite] Failed to reload <acceptedPath>. …`), for this round's paths
84
+ const watching = function (this: unknown, ...a: unknown[]) {
85
+ original.apply(this, a)
86
+ if (!open) return
87
+ for (const x of a) {
88
+ if (typeof x !== 'string' || !x.startsWith('Failed to reload ')) continue
89
+ const path = x.slice('Failed to reload '.length).split('. ')[0]
90
+ if (paths.has(path)) failed.add(path)
91
+ }
92
+ }
93
+ console.error = watching
94
+ const close = () => {
95
+ open = false
96
+ clearTimeout(timer)
97
+ observer.disconnect()
98
+ if (console.error === watching) console.error = original // a frame's own replacement meanwhile stays
99
+ }
100
+ const r: Round = { at: performance.now(), updates, fetched, take: () => note(observer.takeRecords()), failed, close }
101
+ const timer = setTimeout(() => { try { giveUp(r) } catch { /* the same */ } }, RELOAD_BOUNDS.inplaceRoundMs)
102
+ round = r
103
+ } catch { /* the recorder never stands in the way */ }
104
+ })
105
+
106
+ hot.on('vite:afterUpdate', () => {
107
+ const r = round
108
+ round = null
109
+ if (!r) return
110
+ try {
111
+ const after = performance.now()
112
+ r.take()
113
+ r.close()
114
+ for (const u of r.updates) {
115
+ if (!r.fetched.has(u)) continue
116
+ const applied = appliedOf(r, u)
117
+ void nextCommit(RELOAD_BOUNDS.commitWaitMs).then((at) => post({
118
+ type: 'sh:inplace', hmrTs: u.timestamp!, applyMs: Math.round(after - r.at), applied,
119
+ ...(at !== undefined ? { nextObservedCommitMs: Math.round(at - after) } : {}),
120
+ }))
121
+ }
122
+ } catch { /* the same */ }
123
+ })
124
+ }
@@ -2,6 +2,7 @@
2
2
  export function createInspect(opts: {
3
3
  post: (msg: Record<string, unknown>) => void
4
4
  getId: () => string
5
+ getBoot?: () => string | undefined
5
6
  onModeChange?: (laser: boolean, pick: boolean) => void
6
7
  onLaserPick?: (el: Element, e: MouseEvent) => boolean
7
8
  }): { modeActive: () => boolean; isLaser: () => boolean; isPick: () => boolean; dispose: () => void }
@@ -10,17 +10,18 @@
10
10
  // touches laser/pick/anchor/highlight. It self-installs the pointer + message
11
11
  // listeners and returns { modeActive } so the host can guard its own nav clicks.
12
12
  //
13
- // createInspect({ post, getId, onModeChange?, onLaserPick? })
13
+ // createInspect({ post, getId, getBoot?, onModeChange?, onLaserPick? })
14
14
  // post(msg) send a message up to the shell (parent)
15
15
  // getId() the frame id to stamp on posts (static on canvas, the
16
16
  // current stage frame in play - it swaps without reload)
17
+ // getBoot?() this document's boot id, echoed in sh:mode-applied (spec 30 #26)
17
18
  // onModeChange?() called after any laser/pick flip (the canvas bridge uses it
18
19
  // to report its interaction lease; the stage ignores it)
19
20
  // onLaserPick?(el, e) a laser click; returning true means a capture took it as its pick
20
21
  // (trail.js) - no sh:laser-copy then
21
22
  //
22
23
  // shell -> frame : sh:laser · sh:pick · sh:copy-ok · sh:resolve-anchors · sh:highlight-anchor
23
- // frame -> shell : sh:frame-down · sh:picked · sh:laser-copy · sh:anchor-rects
24
+ // frame -> shell : sh:frame-down · sh:picked · sh:laser-copy · sh:anchor-rects · sh:mode-applied
24
25
  //
25
26
  // Anchors (spec 26): only VISIBLE elements ever match, a pin attaches at the end of its element's
26
27
  // first rendered line (a person's pin: where they clicked), and `window.__mvAnchorCheck` is the
@@ -323,7 +324,7 @@ const checkTarget = ({ on, at, nth } = {}, others = []) => {
323
324
  }
324
325
  if (typeof window !== 'undefined') window.__mvAnchorCheck = checkTarget
325
326
 
326
- export function createInspect({ post, getId, onModeChange, onLaserPick }) {
327
+ export function createInspect({ post, getId, getBoot, onModeChange, onLaserPick }) {
327
328
  let laserOn = false, pickOn = false
328
329
  // the laser as inspect (⌥L): every element outlined. Off, the laser is a pointer - the element under the cursor lit,
329
330
  // as comment mode lights it
@@ -526,13 +527,20 @@ body [data-mv-hover] { outline: 2px solid hsl(var(--mv-hue) 95% 45%); outline-of
526
527
  applyLock(resolveAnchor(highlightAnchor), highlightAnchor?.el?.hue)
527
528
  }
528
529
 
530
+ // spec 30 #26: a mode change that names its transition is acknowledged two animation frames after it applied - this
531
+ // document's modes as they stand then. A shell that records nothing sends no `t`, and hears nothing back.
532
+ const ackMode = (t) => {
533
+ if (typeof t !== 'string') return
534
+ requestAnimationFrame(() => requestAnimationFrame(() => post({ type: 'sh:mode-applied', id: getId(), t, boot: getBoot?.() ?? '', laser: laserOn, inspect: inspectOn, pick: pickOn })))
535
+ }
536
+
529
537
  const onMessage = (e) => {
530
538
  if (e.source !== window.parent || window.parent === window) return
531
539
  if (e.origin && e.origin !== location.origin) return // a navigated frame must not spoof shell commands
532
540
  const m = e?.data
533
541
  if (!m || typeof m !== 'object') return
534
542
  // (a shell from before 0.26.1 sends no `inspect`: its laser is the outlined one)
535
- if (m.type === 'sh:laser') { laserOn = !!m.on; inspectOn = laserOn && (m.inspect === undefined ? true : !!m.inspect); applyModes(); onModeChange?.(laserOn, pickOn) }
543
+ if (m.type === 'sh:laser') { laserOn = !!m.on; inspectOn = laserOn && (m.inspect === undefined ? true : !!m.inspect); applyModes(); onModeChange?.(laserOn, pickOn); ackMode(m.t) }
536
544
  else if (m.type === 'sh:pick') {
537
545
  pickOn = !!m.on; pickQuiet = !!m.quiet; applyModes()
538
546
  if (pickQuiet) clearHover() // a hover lit before the toggle landed must not linger
@@ -540,6 +548,7 @@ body [data-mv-hover] { outline: 2px solid hsl(var(--mv-hue) 95% 45%); outline-of
540
548
  // a shell-owned highlight (highlightAnchor set, e.g. #5) survives
541
549
  if (!pickOn && !highlightAnchor) clearLock()
542
550
  onModeChange?.(laserOn, pickOn)
551
+ ackMode(m.t)
543
552
  }
544
553
  else if (m.type === 'sh:copy-ok') showCopied(m.seq)
545
554
  else if (m.type === 'sh:highlight-anchor') {
@@ -3,12 +3,15 @@
3
3
  * Boot failures (theme, providers, layouts, the frame itself) render a plain-DOM error card
4
4
  * and post sh:error; an ErrorBoundary catches render-time throws the same way.
5
5
  */
6
- import { Component, createElement, useLayoutEffect, type ReactNode } from 'react'
6
+ import { Component, createElement, Profiler, useLayoutEffect, type ReactNode } from 'react'
7
7
  import { createRoot } from 'react-dom/client'
8
8
 
9
9
  import './bridge.js'
10
+ import { frameRenders } from './signals.js'
10
11
  import { frameFile, frames, layoutChain, layouts, providers } from './registry.ts'
11
12
  import { SLIDE_DOC_CSS } from '../const.ts'
13
+ import { fullRecorder } from '../recorder-level.ts'
14
+ import { rootCommitted, watchInplace } from './inplace.ts'
12
15
 
13
16
  const params = new URLSearchParams(location.search)
14
17
  const id = params.get('id') ?? ''
@@ -70,7 +73,8 @@ class Boundary extends Component<{ children: ReactNode }, { err: Error | null }>
70
73
  * outermost element runs after every child's, before the first paint of the tree). */
71
74
  function Committed({ onCommit, children }: { onCommit: () => void; children?: ReactNode }) {
72
75
  useLayoutEffect(onCommit, [])
73
- return children
76
+ // spec 30 #15: an in-place update's next observed commit (dev, the full level; a published frame has no hot module)
77
+ return import.meta.hot && fullRecorder() ? createElement(Profiler, { id: 'mv-inplace', onRender: rootCommitted }, children) : children
74
78
  }
75
79
 
76
80
  async function boot() {
@@ -113,7 +117,10 @@ async function boot() {
113
117
  // by a superseded document (one it auto-renavigated past) - a WindowProxy survives navigation, so
114
118
  // a stale ready could otherwise mark a reloading frame ready. Mirrors the sh:measure generation guard.
115
119
  const ready = () => { phases.commit = Math.round(performance.now()); post({ type: 'sh:ready', id, gen, boot: docId(), doc: document.querySelector('meta[name="mv-doc"]')?.getAttribute('content') ?? '', meta: frameMod.meta && typeof frameMod.meta === 'object' ? frameMod.meta : undefined, phases }) }
116
- createRoot(document.getElementById('root')!).render(createElement(Boundary, null, createElement(Committed, { onCommit: ready }, tree)))
120
+ const app = createElement(Boundary, null, createElement(Committed, { onCommit: ready }, tree))
121
+ // the recorder's minute of this root's commits (spec 30 #36): none where nothing records
122
+ const onRender = frameRenders(post, id, docId)
123
+ createRoot(document.getElementById('root')!).render(onRender ? createElement(Profiler, { id: 'frame', onRender }, app) : app)
117
124
  } catch (err) {
118
125
  fail((err as Error).message, err)
119
126
  }
@@ -128,3 +135,5 @@ boot()
128
135
  if (import.meta.hot) import.meta.hot.on('vite:afterUpdate', (p: { updates?: { acceptedPath?: string; path?: string }[] }) => {
129
136
  if (p.updates?.some((u) => !(u.acceptedPath ?? u.path ?? '').includes('/frame-host/registry'))) post({ type: 'sh:hmr', id })
130
137
  })
138
+ // spec 30 #15: what this document saw of an update applied in place, and only if it fetched it
139
+ if (import.meta.hot && fullRecorder()) watchInplace(import.meta.hot, (m) => post({ ...m, id, boot: docId() }))
@@ -0,0 +1,85 @@
1
+ /**
2
+ * The messages spec 30 adds or extends between the shell and its documents - canvas frames (bridge.js, inspect.js,
3
+ * main.tsx) and the play stage (stage/main.tsx) - beside the ones they already exchange. Types and constants only.
4
+ * Every field spec 30 adds to an existing message is optional: an older document, a document of another level
5
+ * (`core`) or a document whose bridge has not run yet sends none, and the shell then counts nothing for it.
6
+ *
7
+ * bridge.js and inspect.js are plain JS that ship verbatim (build.ts copies them for published HTML frames): they
8
+ * post these shapes by hand and repeat `ERROR_BUDGET.frame` (perf-records.ts) inline. A new module either imports
9
+ * must be added to build.ts's copy list, or every published HTML frame stops.
10
+ *
11
+ * FROZEN before the spec 30 streams split. Owners: signals (theme and mode acks, `sh:gesture`, `sh:console`,
12
+ * `sh:resource-error`, `sh:dropped`, `sh:warnings`, `sh:renders`), edits (`sh:inplace`), commands (`sh:stage-key`'s `origin`).
13
+ */
14
+ import type { ResourceTag } from '../../shared/perf-records.ts'
15
+
16
+ /** The names, one place. The first block is new; the second extends existing messages. */
17
+ export const SH = {
18
+ modeApplied: 'sh:mode-applied',
19
+ console: 'sh:console',
20
+ resourceError: 'sh:resource-error',
21
+ dropped: 'sh:dropped',
22
+ warnings: 'sh:warnings',
23
+ renders: 'sh:renders',
24
+ gesture: 'sh:gesture',
25
+ inplace: 'sh:inplace',
26
+ // extended
27
+ setTheme: 'sh:set-theme',
28
+ themeApplied: 'sh:theme-applied',
29
+ laser: 'sh:laser',
30
+ pick: 'sh:pick',
31
+ hmr: 'sh:hmr',
32
+ stageKey: 'sh:stage-key',
33
+ stageShown: 'sh:stage-shown',
34
+ } as const
35
+
36
+ // ---- the shell to a document --------------------------------------------------------------------------------------
37
+
38
+ /** #21: a theme switch carries its transition `t` (FrameNode.tsx:139, Play.tsx:390). The spec's "`sh:theme`
39
+ * (FrameNode)" is this message. */
40
+ export interface SetThemeMsg { type: 'sh:set-theme'; theme: string; t?: string }
41
+ /** #26: a mode change carries its transition `t` (FrameNode.tsx:180, :187; Play.tsx:356-357). */
42
+ export interface LaserMsg { type: 'sh:laser'; on: boolean; inspect: boolean; t?: string }
43
+ export interface PickMsg { type: 'sh:pick'; on: boolean; quiet: boolean; t?: string }
44
+ /** #36: a gesture's start and end, to the on-screen frames - their Profiler counts `inGesture` between them. */
45
+ export interface GestureMsg { type: 'sh:gesture'; on: boolean }
46
+
47
+ // ---- a document to the shell --------------------------------------------------------------------------------------
48
+
49
+ /** #21: the ack echoes the switch's `t` and the document's boot id (bridge.js:36-40; the stage posts the same, two
50
+ * animation frames after). An ack with an old `t`, or from a document no longer the live one, does not count. */
51
+ export interface ThemeAppliedMsg { type: 'sh:theme-applied'; id: string; theme: string; t?: string; boot?: string }
52
+ /** #26: inspect.js, two animation frames after `applyModes` (:535-536): the modes it applied, for transition `t`. */
53
+ export interface ModeAppliedMsg { type: 'sh:mode-applied'; id: string; t: string; boot: string; laser: boolean; inspect: boolean; pick: boolean }
54
+ /** #28: a frame's `console.error`, as produced (the original runs first). Its own message: `sh:error` marks the
55
+ * frame failed, a console error does not. */
56
+ export interface ConsoleMsg { type: 'sh:console'; id: string; gen: string; boot: string; message: string; stack?: string[] }
57
+ /** #32: an element's load error, caught in the capture phase: `url` a same-origin path without query, else the
58
+ * other origin alone. */
59
+ export interface ResourceErrorMsg { type: 'sh:resource-error'; id: string; gen: string; boot: string; tag: ResourceTag; url: string }
60
+ /** What a frame's budget refuses, by source (#33): console errors, resource errors. A window error spends it and is never refused. */
61
+ export type FrameDropSource = 'console' | 'resource'
62
+ /** #33: counter-only, independent of the detail budget, at most one a second, a final one at `pagehide`. Counts since
63
+ * the document's previous `sh:dropped`: the shell adds them to `dropped { reason: <source>, n }`. */
64
+ export interface DroppedMsg { type: 'sh:dropped'; id: string; boot: string; counts: Partial<Record<FrameDropSource, number>>; final?: true }
65
+ /** #28: a frame's `console.warn` calls, counted - no text. Counter-only, at most one a second, a final one at
66
+ * `pagehide`; the shell adds them up by node into the minute's `warnings` record. */
67
+ export interface WarningsMsg { type: 'sh:warnings'; id: string; boot: string; n: number; final?: true }
68
+ /** #36: a document's minute of React commits (the frame root's, or the stage root's: `id` 'stage'). `minute`: the
69
+ * minute's start, epoch ms. */
70
+ export interface RendersMsg { type: 'sh:renders'; id: string; boot: string; minute: number; commits: number; ms: number; maxMs: number; inGesture: number }
71
+ /** Today's (main.tsx:129): an update applied in place, so a sleeping frame wakes. Unchanged; `sh:inplace` reports. */
72
+ export interface HmrMsg { type: 'sh:hmr'; id: string }
73
+ /** #15: a document that fetched `<acceptedPath>?t=<hmrTs>` (Resource Timing) reports what it saw - after its next
74
+ * observed commit, or `RELOAD_BOUNDS.commitWaitMs` with none. `applied` is `false` only on Vite's own failure message
75
+ * for that path; never `true`. Registry-only updates send nothing (main.tsx:129's filter). `noAfterUpdate`: its round
76
+ * ended with no `vite:afterUpdate`, so this is what was known by then, `applyMs` how long the round stood open. */
77
+ export interface InplaceMsg { type: 'sh:inplace'; id: string; boot: string; hmrTs: number; applyMs?: number; nextObservedCommitMs?: number; applied: 'unknown' | false; noAfterUpdate?: true }
78
+ /** #50: the stage's background click posted as Space (stage/main.tsx:273) says so. */
79
+ export interface StageKeyMsg { type: 'sh:stage-key'; key: string; code: string; alt?: boolean; meta?: boolean; origin?: 'click' }
80
+ /** #26: Play's first `sh:stage-shown` after `enterPlay`/`enterSlides` ends the mode's `firstFrameMs`; the existing
81
+ * fields (stage/main.tsx:152), with the stage's boot id so an old stage's never counts. */
82
+ export interface StageShownMsg { type: 'sh:stage-shown'; at: string; nav: string; epoch: string; doc: number; boot?: string }
83
+
84
+ export type DocMsg = ThemeAppliedMsg | ModeAppliedMsg | ConsoleMsg | ResourceErrorMsg | DroppedMsg | WarningsMsg | RendersMsg | HmrMsg | InplaceMsg | StageKeyMsg | StageShownMsg
85
+ export type ShellMsg = SetThemeMsg | LaserMsg | PickMsg | GestureMsg
@@ -0,0 +1,15 @@
1
+ // Types for signals.js (plain JS: it serves into frames like bridge.js).
2
+ export const FRAME_BUDGET: { perSecond: number; perDoc: number; countsMs: number }
3
+ export const RESOURCE_TAGS: string[]
4
+ export function documentRecords(search?: string): boolean
5
+ export function periodMs(): number
6
+ export function formatConsole(args: readonly unknown[], max?: number): string
7
+ export function stackOfArgs(args: readonly unknown[]): string[] | undefined
8
+ export function viteEcho(args: readonly unknown[]): boolean
9
+ export function resourceUrl(raw: string, base?: string): string
10
+ export function resourceOf(target: unknown, base?: string): { tag: string; url: string } | null
11
+ export function createBudget<S extends string>(limits: { perSecond: number; perDoc: number }, refused: (source: S) => void, now?: () => number): { take(source: S, force?: boolean): boolean }
12
+ export function createCounter(ms: number, send: (counts: Record<string, number>, final: boolean) => void, now?: () => number): { add(key: string, n?: number): void; final(): void }
13
+ export function onConsoleError(fn: (args: unknown[]) => void): () => void
14
+ export function startDocumentSignals(o: { post: (msg: Record<string, unknown>) => void; id: string; gen: string; boot: string }): { take(source: 'frame' | 'console' | 'resource', force?: boolean): boolean } | null
15
+ export function frameRenders(post: (msg: Record<string, unknown>) => void, id: string, getBoot: () => string | undefined): ((id: string, phase: string, actualDuration: number) => void) | null
@@ -0,0 +1,219 @@
1
+ // The recorder's signals inside a document (spec 30 R5, R6): what a canvas frame (bridge.js) tells the shell beyond its
2
+ // ready and errors - its console errors and counted warnings (#28), its elements' load errors (#32), what its budget
3
+ // refused (#33) - and the React Profiler's minute, which the frames and the play stage post (#36). The shell takes the
4
+ // same rules for its own console and elements (recorder-signals.ts imports this module).
5
+ //
6
+ // Plain JS that ships verbatim beside bridge.js (build.ts copies it for published HTML frames): it repeats
7
+ // perf-records.ts `ERROR_BUDGET.frame` and the minute inline. Nothing runs at import; `startDocumentSignals` and
8
+ // `frameRenders` do nothing unless the document records (dev: its URL names the workspace, at the full level, in a
9
+ // shell's iframe) - a published canvas, a `core` run and a frame opened on its own pay one check.
10
+ //
11
+ // Limited at the source (#33): every count is taken BEFORE a message is formatted or posted. Errors, console errors and
12
+ // resource errors share 5 a second and 50 per document; what the budget refuses is counted by source and travels on
13
+ // its own, in counter-only `sh:dropped` messages (at most one a second, a final one at `pagehide`). A window error spends
14
+ // the budget but is never refused: it marks the frame failed (bridge.js, #5).
15
+
16
+ /** perf-records.ts `ERROR_BUDGET.frame`, repeated (this file ships verbatim). */
17
+ export const FRAME_BUDGET = { perSecond: 5, perDoc: 50, countsMs: 1000 }
18
+ /** perf-records.ts `RESOURCE_TAGS` (#32). */
19
+ export const RESOURCE_TAGS = ['img', 'script', 'link', 'video', 'audio', 'source']
20
+ const MAX = 200
21
+
22
+ /** Does this document record spec 30's signals? In a shell's iframe, on a page that records (its URL names the
23
+ * workspace, as `withWs()` writes it in dev), at the full level (`?mvrecorder=core` turns it off, #58). */
24
+ export function documentRecords(search = location.search) {
25
+ try {
26
+ if (window.parent === window) return false
27
+ const q = new URLSearchParams(search)
28
+ return q.has('ws') && q.get('mvrecorder') !== 'core'
29
+ } catch { return false }
30
+ }
31
+
32
+ /** The period renders and warnings are counted over: a minute. A test shortens it (`__mvSignalsPeriodMs`, set before the
33
+ * document loads); nothing else does. */
34
+ export function periodMs() {
35
+ const v = globalThis.__mvSignalsPeriodMs
36
+ return typeof v === 'number' && v >= 100 ? v : 60000
37
+ }
38
+
39
+ const piece = (x) => {
40
+ if (typeof x === 'string') return x
41
+ if (x instanceof Error) return `${x.name && x.name !== 'Error' ? `${x.name}: ` : ''}${x.message}`
42
+ if (x === null || typeof x !== 'object' && typeof x !== 'function') return String(x)
43
+ if (typeof x === 'function') return `[function ${x.name || 'anonymous'}]`
44
+ if (Array.isArray(x)) return `[Array(${x.length})]`
45
+ // never a deep read: an object's own text is the code's to put in a string (#4)
46
+ return `[${x.constructor?.name || 'Object'}]`
47
+ }
48
+ /** A console call's message as the code produced it (#4, #28): its strings, `%s`/`%d`/`%i`/`%f`/`%o`/`%O`
49
+ * substituted, `%c` styles dropped, errors by their message, objects by their kind - `max` characters, built no
50
+ * further than that. */
51
+ export function formatConsole(args, max = MAX) {
52
+ let out = ''
53
+ let i = 0
54
+ if (typeof args[0] === 'string') {
55
+ i = 1
56
+ out = args[0].replace(/%[sdifoOc%]/g, (spec) => {
57
+ if (spec === '%%') return '%'
58
+ if (i >= args.length) return spec
59
+ const a = args[i++]
60
+ if (spec === '%c') return ''
61
+ try { return spec === '%d' || spec === '%i' ? String(parseInt(a, 10)) : spec === '%f' ? String(Number(a)) : piece(a) } catch { return '?' }
62
+ })
63
+ }
64
+ for (; i < args.length && out.length < max; i++) {
65
+ let p
66
+ try { p = piece(args[i]) } catch { p = '?' }
67
+ out = out ? `${out} ${p}` : p
68
+ }
69
+ return out.slice(0, max)
70
+ }
71
+ /** The first error's first three stack lines among a console call's arguments, when it has them. */
72
+ export function stackOfArgs(args) {
73
+ const err = args.find((a) => a instanceof Error)
74
+ if (!err || typeof err.stack !== 'string') return undefined
75
+ const lines = err.stack.split('\n')
76
+ const chrome = lines.filter((l) => /^\s*at /.test(l))
77
+ const out = (chrome.length ? chrome : lines.filter((l) => /@.*:\d+(:\d+)?$/.test(l.trim()))).slice(0, 3).map((l) => l.trim().slice(0, MAX))
78
+ return out.length ? out : undefined
79
+ }
80
+ /** Vite's own echo of a server error into every document's console (overlay off): the shell's `vite:error` listener
81
+ * records it once (#29), so no console hook does. */
82
+ export const viteEcho = (args) => typeof args[0] === 'string' && args[0].startsWith('[vite] Internal Server Error')
83
+
84
+ /** #32: a same-origin URL's path without its query; another origin, its origin alone; any other scheme, the scheme. */
85
+ export function resourceUrl(raw, base = location.href) {
86
+ try {
87
+ const u = new URL(raw, base)
88
+ if (u.protocol !== 'http:' && u.protocol !== 'https:') return u.protocol
89
+ return u.origin === new URL(base).origin ? u.pathname : u.origin
90
+ } catch { return '' }
91
+ }
92
+ /** An element whose load failed, as #32 records it: its tag and URL, or null for anything else. */
93
+ export function resourceOf(target, base) {
94
+ if (!target || typeof target.tagName !== 'string') return null
95
+ const tag = target.tagName.toLowerCase()
96
+ if (!RESOURCE_TAGS.includes(tag)) return null
97
+ const raw = tag === 'link' ? target.href : (target.currentSrc || target.src || target.getAttribute?.('src') || '')
98
+ return { tag, url: resourceUrl(String(raw ?? ''), base) }
99
+ }
100
+
101
+ /** #33: the document's budget - `perSecond` and `perDoc`, shared by every source. A refusal is told to `refused` with
102
+ * its source; `force` passes whatever the budget says (and counts against it). */
103
+ export function createBudget(limits, refused, now = () => performance.now()) {
104
+ let used = 0, sec = NaN, inSec = 0
105
+ return {
106
+ take(source, force = false) {
107
+ const s = Math.floor(now() / 1000)
108
+ if (s !== sec) { sec = s; inSec = 0 }
109
+ if (!force && (used >= limits.perDoc || inSec >= limits.perSecond)) { refused(source); return false }
110
+ used++; inSec++
111
+ return true
112
+ },
113
+ }
114
+ }
115
+
116
+ /** Counts that travel on their own: added up and sent at most once every `ms` (the first at once, after a quiet
117
+ * `ms`), a final send when asked - nothing when there is nothing to say. */
118
+ export function createCounter(ms, send, now = () => performance.now()) {
119
+ let counts = null, timer = null, last = -Infinity
120
+ const go = (final) => {
121
+ if (timer !== null) { clearTimeout(timer); timer = null }
122
+ if (!counts) return
123
+ const c = counts
124
+ counts = null
125
+ last = now()
126
+ send(c, final)
127
+ }
128
+ return {
129
+ add(key, n = 1) {
130
+ if (!counts) counts = {}
131
+ counts[key] = (counts[key] ?? 0) + n
132
+ if (timer === null) timer = setTimeout(() => go(false), Math.max(0, last + ms - now()))
133
+ },
134
+ final() { go(true) },
135
+ }
136
+ }
137
+
138
+ // ---- a document's hooks (bridge.js) ------------------------------------------------------------------------------
139
+
140
+ /** a gesture runs on the canvas over this frame (`sh:gesture`): its commits count `inGesture` */
141
+ let gesture = false
142
+ let started = null
143
+ const consoleListeners = new Set()
144
+ /** Told every `console.error` of this document with its arguments, before any budget (the edits stream's #15 reads
145
+ * Vite's own failure message here). Returns the unsubscribe. */
146
+ export function onConsoleError(fn) { consoleListeners.add(fn); return () => { consoleListeners.delete(fn) } }
147
+
148
+ /**
149
+ * A canvas frame's hooks, once (bridge.js, before anything else it posts): `console.error` and `console.warn` wrapped
150
+ * (the original runs first), the capture-phase element error listener, the budget, the counters, and the shell's
151
+ * `sh:gesture`. Returns `take(source, force?)` - the budget, which the bridge's own window errors spend with `force` -
152
+ * or null when this document does not record.
153
+ */
154
+ export function startDocumentSignals({ post, id, gen, boot }) {
155
+ if (started) return started
156
+ if (!documentRecords()) return null
157
+ const dropped = createCounter(FRAME_BUDGET.countsMs, (counts, final) => post({ type: 'sh:dropped', id, boot, counts, ...(final ? { final: true } : {}) }))
158
+ const budget = createBudget(FRAME_BUDGET, (source) => dropped.add(source, 1))
159
+ const warns = createCounter(FRAME_BUDGET.countsMs, (counts, final) => post({ type: 'sh:warnings', id, boot, n: counts.n, ...(final ? { final: true } : {}) }))
160
+
161
+ const error0 = console.error, warn0 = console.warn
162
+ console.error = function (...args) {
163
+ error0.apply(this, args)
164
+ try {
165
+ for (const fn of consoleListeners) { try { fn(args) } catch { /* one listener, not the rest */ } }
166
+ if (viteEcho(args) || !budget.take('console')) return
167
+ const stack = stackOfArgs(args)
168
+ post({ type: 'sh:console', id, gen, boot, message: formatConsole(args), ...(stack ? { stack } : {}) })
169
+ } catch { /* never in the way */ }
170
+ }
171
+ console.warn = function (...args) {
172
+ warn0.apply(this, args)
173
+ try { warns.add('n', 1) } catch { /* never in the way */ }
174
+ }
175
+ // an element's load error does not bubble: the capture phase at the window sees every one
176
+ addEventListener('error', (e) => {
177
+ try {
178
+ if (!(e.target instanceof Element)) return
179
+ const r = resourceOf(e.target)
180
+ if (!r || !budget.take('resource')) return
181
+ post({ type: 'sh:resource-error', id, gen, boot, tag: r.tag, url: r.url })
182
+ } catch { /* never in the way */ }
183
+ }, true)
184
+ addEventListener('message', (e) => {
185
+ if (e.source !== window.parent || window.parent === window || (e.origin && e.origin !== location.origin)) return
186
+ if (e.data?.type === 'sh:gesture') gesture = !!e.data.on
187
+ })
188
+ addEventListener('pagehide', () => { dropped.final(); warns.final() })
189
+ started = { take: (source, force) => budget.take(source, force) }
190
+ return started
191
+ }
192
+
193
+ /**
194
+ * #36: a document's React commits, by minute - the frame root's (frame-host/main.tsx) or the stage root's: `commits`,
195
+ * `ms` (the sum of `actualDuration`), `maxMs` and `inGesture`, posted as `sh:renders` once the minute is over, and the
196
+ * minute so far at `pagehide`. The Profiler's `onRender`, or null when this document does not record. No props, state
197
+ * or text: numbers only.
198
+ */
199
+ export function frameRenders(post, id, getBoot) {
200
+ if (!documentRecords()) return null
201
+ let minute = -1, commits = 0, ms = 0, maxMs = 0, inGesture = 0, timer = null
202
+ const flush = () => {
203
+ if (timer !== null) { clearTimeout(timer); timer = null }
204
+ if (!commits) return
205
+ post({ type: 'sh:renders', id, boot: getBoot() ?? '', minute, commits, ms: Math.round(ms * 10) / 10, maxMs: Math.round(maxMs * 10) / 10, inGesture })
206
+ commits = 0; ms = 0; maxMs = 0; inGesture = 0
207
+ }
208
+ addEventListener('pagehide', flush)
209
+ return (_id, _phase, actual) => {
210
+ try {
211
+ const p = periodMs(), now = Date.now(), m = Math.floor(now / p) * p
212
+ if (m !== minute) { flush(); minute = m }
213
+ commits++
214
+ if (typeof actual === 'number' && actual > 0) { ms += actual; if (actual > maxMs) maxMs = actual }
215
+ if (gesture) inGesture++
216
+ if (timer === null) timer = setTimeout(flush, m + p - now + 50)
217
+ } catch { /* never in the way */ }
218
+ }
219
+ }
@@ -0,0 +1,41 @@
1
+ /**
2
+ * The recorder's level (spec 30 #57, #58): the one switch every spec 30 hook is gated by, in the shell, the frame host
3
+ * and the stage alike. `core` records what 0.29 recorded - the load tracking a headless run's driver reads
4
+ * (`currentLoad`, recorder.ts) - and nothing spec 30 adds; `full`, the default, records everything.
5
+ *
6
+ * Set by the page's URL, `?mvrecorder=core` (perf-records.ts `RECORDER_PARAM`): `marver perf run <board> --recorder
7
+ * core` puts it on the shell's URL, and `withWs()` (api.ts) carries it onto every frame and stage URL, so a document's
8
+ * hooks keep its page's level. Dev only: a production build has no recorder and reads `full`. bridge.js ships
9
+ * verbatim and imports nothing new (build.ts copies it): it reads the parameter itself, the same way.
10
+ *
11
+ * Owner: app-store (R15) - the run's `--recorder` input, `self` records and the cost test. Every other stream calls
12
+ * `fullRecorder()` (or starts from recorder.ts's stream starters, which are not called under `core`).
13
+ */
14
+ import { RECORDER_PARAM, SELF_HOOKS, type RecorderLevel, type SelfHook } from '../shared/perf-records.ts'
15
+
16
+ /** This document's level, read once at module load. */
17
+ export const RECORDER_LEVEL: RecorderLevel = (() => {
18
+ if (!import.meta.env.DEV) return 'full'
19
+ try { return new URLSearchParams(location.search).get(RECORDER_PARAM) === 'core' ? 'core' : 'full' } catch { return 'full' }
20
+ })()
21
+
22
+ /** The level, for a hook deciding whether to run. */
23
+ export const recorderLevel = (): RecorderLevel => RECORDER_LEVEL
24
+ /** Does this document record what spec 30 adds? */
25
+ export const fullRecorder = (): boolean => RECORDER_LEVEL === 'full'
26
+
27
+ /**
28
+ * Test-only (#58): `?mvslowhook=<hook>` on the shell's URL adds a 5 ms busy wait to that hook, so the cost run has a
29
+ * cost to find: the run must fail with it, or the run measures nothing. Dev only, set only by a test.
30
+ */
31
+ export const SLOW_HOOK_PARAM = 'mvslowhook'
32
+ export const SLOW_HOOK_MS = 5
33
+ export const SLOW_HOOK: SelfHook | null = (() => {
34
+ if (!import.meta.env.DEV) return null
35
+ try { const h = new URLSearchParams(location.search).get(SLOW_HOOK_PARAM); return (SELF_HOOKS as readonly string[]).includes(h ?? '') ? h as SelfHook : null } catch { return null }
36
+ })()
37
+ /** The wait itself: this thread held, as a hook's work would hold it. */
38
+ export function busyWait(ms: number): void {
39
+ const end = performance.now() + ms
40
+ while (performance.now() < end) { /* the point */ }
41
+ }