brumate 0.7.2 → 0.8.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.
- package/dist/{boot-CMy0f_iC.d.ts → boot-BkUdiYOF.d.ts} +2 -2
- package/dist/cli.js +3 -2
- package/dist/cli.js.map +1 -1
- package/dist/{client-COm1iA6w.js → client-B0FXW5Kw.js} +48 -14
- package/dist/client-B0FXW5Kw.js.map +1 -0
- package/dist/{client-DnFF9_lv.d.ts → client-Cq6aTiDs.d.ts} +15 -7
- package/dist/{defer-Cesb-k2Q.js → defer-BMIMP4Hq.js} +2 -2
- package/dist/{defer-Cesb-k2Q.js.map → defer-BMIMP4Hq.js.map} +1 -1
- package/dist/{devtools-C9IEkgc1.js → devtools-B4prrxht.js} +257 -118
- package/dist/devtools-B4prrxht.js.map +1 -0
- package/dist/devtools-calls-DGW6nLZ2.js +249 -0
- package/dist/devtools-calls-DGW6nLZ2.js.map +1 -0
- package/dist/devtools-panel-B1nF1KB7.js +3978 -0
- package/dist/devtools-panel-B1nF1KB7.js.map +1 -0
- package/dist/error-catalog-DakxjSgj.js +308 -0
- package/dist/error-catalog-DakxjSgj.js.map +1 -0
- package/dist/error-catalog-VxLbz-6p.js +1 -0
- package/dist/{files-BuQvpBwF.js → files-D5GtxwEQ.js} +2 -2
- package/dist/{files-BuQvpBwF.js.map → files-D5GtxwEQ.js.map} +1 -1
- package/dist/index.d.ts +73 -18
- package/dist/index.js +11 -1
- package/dist/index.js.map +1 -1
- package/dist/{inspect-BSHv1_25.js → inspect-CGl5Y8q6.js} +581 -399
- package/dist/inspect-CGl5Y8q6.js.map +1 -0
- package/dist/{loader-CLKrJMqw.js → loader-BsaSuIoG.js} +4 -4
- package/dist/{loader-CLKrJMqw.js.map → loader-BsaSuIoG.js.map} +1 -1
- package/dist/{navigate-OHb0Uw1P.js → navigate-BlowKvhB.js} +13 -6
- package/dist/navigate-BlowKvhB.js.map +1 -0
- package/dist/{rpc-BAKbRWOT.js → rpc-C1jYVNAe.js} +5 -4
- package/dist/rpc-C1jYVNAe.js.map +1 -0
- package/dist/runtime/bundles.d.ts +1 -1
- package/dist/runtime/client.d.ts +2 -2
- package/dist/runtime/client.js +4 -3
- package/dist/runtime/devtools.d.ts +59 -1
- package/dist/runtime/devtools.js +1 -1
- package/dist/runtime/hot.d.ts +1 -1
- package/dist/runtime/hot.js +6 -2
- package/dist/runtime/hot.js.map +1 -1
- package/dist/runtime/loader.d.ts +2 -2
- package/dist/runtime/loader.js +2 -2
- package/dist/runtime/server.d.ts +1 -1
- package/dist/runtime/server.js +3 -2
- package/dist/runtime/signals.d.ts +1 -1
- package/dist/runtime/static-loader.d.ts +2 -2
- package/dist/runtime/static-loader.js +1 -1
- package/dist/runtime/store.d.ts +2 -2
- package/dist/runtime/store.js +1 -1
- package/dist/runtime/testing.d.ts +2 -2
- package/dist/runtime/testing.js +2 -2
- package/dist/search-params-Wg-0FsMj.js +148 -0
- package/dist/search-params-Wg-0FsMj.js.map +1 -0
- package/dist/{stream-RXLadXx1.js → serial-ioa17MuY.js} +67 -168
- package/dist/serial-ioa17MuY.js.map +1 -0
- package/dist/serial-ribg9NAj.js +1 -0
- package/dist/{server-BVObWh-w.js → server-BUuf7XPZ.js} +61 -16
- package/dist/server-BUuf7XPZ.js.map +1 -0
- package/dist/{server-0rS5vUW1.d.ts → server-DesBZv5g.d.ts} +8 -3
- package/dist/{search-params-C64liRBj.js → shared-CX_YacDm.js} +3 -148
- package/dist/shared-CX_YacDm.js.map +1 -0
- package/dist/{signals-DBnq9QRW.d.ts → signals-7VVD9C_H.d.ts} +2 -2
- package/dist/{static-loader-CxANokZ4.js → static-loader-C_en-4v8.js} +2 -2
- package/dist/{static-loader-CxANokZ4.js.map → static-loader-C_en-4v8.js.map} +1 -1
- package/dist/{static-loader-BYbXVJDY.d.ts → static-loader-UKnK11Em.d.ts} +2 -2
- package/dist/{store-xlTzAM_r.d.ts → store-9_oa0HG1.d.ts} +15 -2
- package/dist/{store-BIBAYZo-.js → store-Cy4EEyZ7.js} +148 -2
- package/dist/store-Cy4EEyZ7.js.map +1 -0
- package/dist/stream-read-BTsYstJY.js +22 -0
- package/dist/stream-read-BTsYstJY.js.map +1 -0
- package/dist/stream-read-Dek3HnqO.js +1 -0
- package/dist/vite.d.ts +1 -1
- package/dist/vite.js +37 -5
- package/dist/vite.js.map +1 -1
- package/package.json +7 -4
- package/skills/brumate/SKILL.md +6 -2
- package/skills/brumate/references/errors.md +21 -2
- package/skills/brumate/references/state.md +31 -0
- package/skills/brumate/references/syntax.md +45 -1
- package/dist/client-COm1iA6w.js.map +0 -1
- package/dist/devtools-C9IEkgc1.js.map +0 -1
- package/dist/devtools-panel-Doit__YG.js +0 -2018
- package/dist/devtools-panel-Doit__YG.js.map +0 -1
- package/dist/inspect-BSHv1_25.js.map +0 -1
- package/dist/navigate-OHb0Uw1P.js.map +0 -1
- package/dist/rpc-BAKbRWOT.js.map +0 -1
- package/dist/search-params-C64liRBj.js.map +0 -1
- package/dist/server-BVObWh-w.js.map +0 -1
- package/dist/store-BIBAYZo-.js.map +0 -1
- package/dist/stream-RXLadXx1.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"devtools-B4prrxht.js","names":[],"sources":["../src/runtime/devtools-flash.ts","../src/runtime/devtools.ts"],"sourcesContent":["import type { DevtoolsState } from './devtools.ts';\n\n/** Where the choice to outline changed elements is kept. */\nconst FLASH_KEY = 'brumate:devtools:flash';\n/** How long an outline shows. */\nexport const FLASH_MS = 700;\n/** The most outlines that one frame draws, so a big change does not stall the page. */\nexport const MAX_FLASHES = 200;\n\n/** The colours of an outline, by how often the element changes. */\nconst HEAT = {\n cool: { line: '#7fd99a', fill: 'rgb(127 217 154 / 0.08)' },\n warm: { line: '#ffd166', fill: 'rgb(255 209 102 / 0.1)' },\n hot: { line: '#ff7a7a', fill: 'rgb(255 122 122 / 0.12)' },\n};\n\nexport type Heat = keyof typeof HEAT;\n\n/** One outline: the element, where it is in the viewport, its colour and when it began. */\nexport interface OutlineBox {\n /** Measured again on scroll and resize while the element is connected. */\n element: Element;\n x: number;\n y: number;\n width: number;\n height: number;\n heat: Heat;\n start: number;\n}\n\nexport interface Outlines {\n /** The boxes that are showing, oldest first. */\n boxes: OutlineBox[];\n canvas: HTMLCanvasElement;\n}\n\n/** The heat of an outline, by how many times the element changed in the last second. */\nfunction pickHeat(count: number): Heat {\n if (count >= 5) {\n return 'hot';\n }\n return count >= 2 ? 'warm' : 'cool';\n}\n\nfunction reducedMotion(): boolean {\n return typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches;\n}\n\n/**\n * Outlines the elements that change, as an update writes them: green for an\n * element that changes now and then, yellow and red for one that changes\n * often. A MutationObserver sees every change of the page, so it needs no\n * hook of the core. The boxes are drawn on one canvas in the shadow root, so\n * the page itself does not change.\n */\nexport function installFlash(state: DevtoolsState, root: ShadowRoot, host: Element): Outlines {\n const canvas = document.createElement('canvas');\n canvas.className = 'flashes';\n canvas.style.cssText =\n 'position:fixed;left:0;top:0;width:100vw;height:100vh;pointer-events:none;z-index:2147483646';\n root.append(canvas);\n const context = canvas.getContext('2d');\n const boxes: OutlineBox[] = [];\n // How many times each element changed lately, for its colour.\n const heat = new WeakMap<Element, { count: number; time: number }>();\n const pending = new Set<Element>();\n let observed = false;\n let mutationFrame = 0;\n let loop = 0;\n\n function fit(): void {\n const ratio = window.devicePixelRatio || 1;\n const width = Math.round(innerWidth * ratio);\n const height = Math.round(innerHeight * ratio);\n // Setting the size clears the canvas, so only do it when it changed.\n if (canvas.width !== width || canvas.height !== height) {\n canvas.width = width;\n canvas.height = height;\n }\n canvas.style.width = `${innerWidth}px`;\n canvas.style.height = `${innerHeight}px`;\n }\n\n function paint(now: number): void {\n if (!context) {\n return;\n }\n const ratio = window.devicePixelRatio || 1;\n context.setTransform(ratio, 0, 0, ratio, 0, 0);\n context.clearRect(0, 0, innerWidth, innerHeight);\n const still = reducedMotion();\n context.lineWidth = 2;\n for (const box of boxes) {\n const colours = HEAT[box.heat];\n context.globalAlpha = still ? 1 : Math.max(0, 1 - (now - box.start) / FLASH_MS);\n context.fillStyle = colours.fill;\n context.strokeStyle = colours.line;\n context.beginPath();\n const x = box.x;\n const y = box.y;\n if (typeof context.roundRect === 'function') {\n context.roundRect(x, y, box.width, box.height, 3);\n } else {\n context.rect(x, y, box.width, box.height);\n }\n context.fill();\n context.stroke();\n }\n context.globalAlpha = 1;\n }\n\n /** One frame of the loop: drops the boxes that ran out, draws the rest and goes on while any is left. */\n function tick(): void {\n loop = 0;\n const now = performance.now();\n let kept = 0;\n for (const box of boxes) {\n if (now - box.start < FLASH_MS) {\n boxes[kept++] = box;\n }\n }\n boxes.length = kept;\n paint(now);\n if (boxes.length > 0) {\n loop = requestAnimationFrame(tick);\n }\n }\n\n /** Measures the boxes again, since a scroll moves the elements but not the fixed ones. */\n function repaint(): void {\n if (boxes.length === 0) {\n return;\n }\n for (const box of boxes) {\n // A box whose element left the page keeps its last rect.\n if (box.element.isConnected) {\n const rect = box.element.getBoundingClientRect();\n box.x = rect.left;\n box.y = rect.top;\n box.width = rect.width;\n box.height = rect.height;\n }\n }\n paint(performance.now());\n }\n\n function resize(): void {\n fit();\n repaint();\n }\n\n function collect(): void {\n mutationFrame = 0;\n let drawn = 0;\n for (const target of pending) {\n if (drawn >= MAX_FLASHES) {\n break;\n }\n const rect = target.getBoundingClientRect();\n if (rect.width === 0 && rect.height === 0) {\n continue;\n }\n const now = performance.now();\n const last = heat.get(target);\n const count = last && now - last.time < 1000 ? last.count + 1 : 1;\n heat.set(target, { count, time: now });\n boxes.push({\n element: target,\n x: rect.left,\n y: rect.top,\n width: rect.width,\n height: rect.height,\n heat: pickHeat(count),\n start: now,\n });\n drawn++;\n }\n pending.clear();\n if (drawn > 0) {\n fit();\n paint(performance.now());\n if (loop === 0) {\n loop = requestAnimationFrame(tick);\n }\n }\n }\n\n const observer = new MutationObserver((records) => {\n for (const record of records) {\n let target: Node | null = record.target;\n if (record.type === 'childList') {\n // The elements that came in, or else the element that lost some.\n let added = 0;\n for (const node of record.addedNodes) {\n if (node.nodeType === 1) {\n pending.add(node as Element);\n added++;\n }\n }\n if (added > 0) {\n continue;\n }\n }\n if (target.nodeType !== 1) {\n target = target.parentElement;\n }\n if (\n target &&\n target !== host &&\n target !== document.documentElement &&\n target !== document.body\n ) {\n pending.add(target as Element);\n }\n }\n for (const target of pending) {\n // The devtools change their own markup, and the host carries their styles.\n if (target === host || host.contains(target)) {\n pending.delete(target);\n }\n }\n if (pending.size > 0 && mutationFrame === 0) {\n mutationFrame = requestAnimationFrame(collect);\n }\n });\n\n state.setFlash = (on) => {\n state.flash = on;\n if (on && !observed) {\n observed = true;\n fit();\n observer.observe(document.documentElement, {\n subtree: true,\n childList: true,\n attributes: true,\n characterData: true,\n });\n addEventListener('resize', resize);\n addEventListener('scroll', repaint, { passive: true, capture: true });\n } else if (!on && observed) {\n observed = false;\n observer.disconnect();\n removeEventListener('resize', resize);\n removeEventListener('scroll', repaint, { capture: true });\n pending.clear();\n boxes.length = 0;\n if (loop !== 0) {\n cancelAnimationFrame(loop);\n loop = 0;\n }\n paint(performance.now());\n }\n try {\n localStorage.setItem(FLASH_KEY, on ? '1' : '0');\n } catch {\n // Storage can be off.\n }\n state.changed?.();\n };\n let saved = false;\n try {\n saved = localStorage.getItem(FLASH_KEY) === '1';\n } catch {\n // Storage can be off.\n }\n if (saved) {\n state.setFlash(true);\n }\n return { boxes, canvas };\n}\n","// The devtools overlay of development builds. This module only listens to\n// the core and shows a button. The panel loads when the button is pressed,\n// so the page behaves as in production until then.\n\nimport type { NavigationReport } from './navigate.ts';\nimport type { DevtoolsHooks, Scope } from './client.ts';\nimport type * as Panel from './devtools-panel.ts';\nimport { installFlash } from './devtools-flash.ts';\nimport type { ScopeId } from './shared.ts';\n\n// The same key as the core's, without importing the core.\nconst DEVTOOLS = Symbol.for('brumate.devtools');\n/** The state and the button of the devtools that a page has, so a second install does nothing. */\nconst INSTALLED = Symbol.for('brumate.devtools.installed');\n\n/** What an install leaves on globalThis, so a second call can find it. */\ninterface Installed {\n state: DevtoolsState;\n host: Element;\n /** False until the host is in the page; it waits for DOMContentLoaded while the document loads. */\n appended: boolean;\n /** The fetch that the install wrapped, so a new install wraps it and not the wrapper. */\n fetch: typeof fetch;\n /** The wrapper that the install put on globalThis. */\n wrapper: typeof fetch;\n}\n\n/** Something that happened on the page, for the log of the panel. */\nexport interface DevtoolsEntry {\n time: number;\n kind: 'handler' | 'write' | 'call';\n text: string;\n /** The scope of a write, so the panel can mark it. */\n scope?: ScopeId;\n /** For a write: the component, the scope in the compiled component, and the slot. */\n write?: { component: string; k: number; slot: number };\n /** For a call: its timing and record, which the call detail of the dock shows. */\n call?: CallTiming;\n}\n\n/** What the plugin tells the devtools about the dev server. */\nexport interface DevtoolsMeta {\n version?: string;\n vite?: string;\n}\n\n/** An error for the Errors tab: of a render on the server, of Vite, or of code in the browser. */\nexport interface ErrorEntry {\n time: number;\n source: 'server' | 'compile' | 'browser';\n message: string;\n stack?: string;\n /** The lines around the error, as Vite's overlay shows them. */\n frame?: string;\n /** The place of the error, such as a compile error in a `.brm` file. */\n loc?: { file: string; line: number; column: number };\n /** The plugin that threw it, such as `brumate`. */\n plugin?: string;\n}\n\n/** What Vite's overlay gets, and what `errorPage` sends. */\nexport interface ErrorPayload {\n message: string;\n stack?: string;\n frame?: string;\n plugin?: string;\n id?: string;\n loc?: { file?: string; line: number; column: number };\n}\n\n/** The part of `import.meta.hot` that the devtools listen to. */\ninterface HotContext {\n on(event: string, listener: (payload: never) => void): void;\n}\n\n/** A server function call, for the Timeline tab. */\nexport interface CallTiming {\n name: string;\n start: number;\n end?: number;\n /** The status of the answer, `redirect` for a redirect, or `failed`. */\n status?: number | 'redirect' | 'failed';\n /** How long the function took on the server, from the `Server-Timing` of the dev server. */\n server?: number;\n /** The arguments, the result and what ran on the server. It arrives after the answer. */\n record?: CallRecord;\n /** What was sent, so the dock can run the call again and write it as a `fetch`. Dev only. */\n request?: {\n url: string;\n /** Only `content-type` and the `x-brumate-` headers, never cookies. */\n headers: Record<string, string>;\n body?: string | FormData;\n };\n}\n\n/**\n * What a server call needs for its detail, for the dock. The browser decodes the arguments and the\n * result, and the dev server sends `server` and the stack in the `x-brumate-dev` header, so a\n * production build has none of them. Values are cut at a length, and no cookies or headers are in it.\n */\nexport interface CallRecord {\n name: string;\n /** The decoded arguments, cut. */\n args: unknown[];\n /** The decoded result, cut. Absent for an error or a redirect. */\n result?: unknown;\n /** The error that the server function threw, with the real message and the stack of the server. */\n error?: { message: string; stack?: string };\n /** Milliseconds: `module` before the request left, `network` there and back, `server` in the function, `decode` reading the answer. */\n timing: { module: number; network: number; server: number; decode: number };\n /** What ran on the server. Absent when the answer did not come from the dev server. */\n server?: ServerRecord;\n}\n\n/** What ran on the server during a call. */\nexport interface ServerRecord {\n /** The server functions whose memos the answer asked to load again (`refresh`). */\n reads: string[];\n /** The IDs of the server functions that the function called. */\n calls: string[];\n /** The `console.*` output of the call, in order. */\n logs: { level: string; text: string }[];\n /** True when logs were left out to fit the header. */\n truncated?: boolean;\n}\n\n/** The content of the `x-brumate-dev` header of the dev server. */\nexport interface DevAnswer extends ServerRecord {\n error?: { message: string; stack?: string };\n}\n\n/** A batch of updates that a write ran, with its effects. */\nexport interface UpdateTiming {\n count: number;\n start: number;\n end: number;\n}\n\n/**\n * A handler that ran, for the Timeline tab: when its event came, when its\n * code was ready and the handlers before it had started, when its call\n * returned, and when the promise of an async handler settled. The server\n * calls and the updates that ran meanwhile are its own.\n */\nexport interface Interaction {\n ref: string;\n /** What happened, such as `click on <button>`. */\n label: string;\n begun: number;\n ready: number;\n end: number;\n settled?: number;\n failed?: boolean;\n calls: CallTiming[];\n updates: UpdateTiming[];\n}\n\n/** A block of the page that renders later, for the Blocks tab. */\nexport interface BlockEntry {\n kind: 'loading' | 'defer' | 'client' | '$client';\n /** The boundary of `#loading` and `#defer`, or the `b-b` of the template of the others. */\n id: string;\n /** The trigger of `#defer`, `#client` and `$client`. */\n trigger?: string;\n /** The reference that `#client` and `$client` run. */\n ref?: string;\n /** The template that the loader reads for `#defer`, `#client` and `$client`. */\n template?: Element;\n state: 'waiting' | 'loading' | 'streaming' | 'rendered' | 'failed';\n /** When the panel first saw the block, when its trigger fired, and when it rendered. */\n seen: number;\n fired?: number;\n rendered?: number;\n /** True while the devtools show its fallback in place of its body. */\n fallback?: boolean;\n}\n\n/** An effect or a `$client` callback of a scope, with how it ran. */\nexport interface EffectEntry {\n scope: ScopeId;\n /** The ID of the component of the scope, and the scope's number in it. */\n component: string;\n k: number;\n /** Its name in the update code: `e<n>` for an effect, `c<n>` for a `$client` callback. */\n name: string;\n runs: number;\n /** When its last runs were, the newest last, at most 50. */\n recent: number[];\n /** The time of all its runs, in milliseconds. */\n time: number;\n cleanups: number;\n lastCleanup?: number;\n /** False once its cleanup ran and it has not run again, such as in a removed scope. */\n active: boolean;\n}\n\nexport interface DevtoolsState {\n scopes?: Map<ScopeId, Scope>;\n /** Writes a slot, as a handler does, so the page updates. */\n set?: (scope: Scope, slot: number, value: unknown) => void;\n /** Runs a reference for an element, as the loader does for a trigger. */\n handle?: (element: Element, ref: string, event?: Event) => Promise<unknown>;\n log: DevtoolsEntry[];\n /** The blocks of the page, by kind and ID. */\n blocks: Map<string, BlockEntry>;\n /** Asks the server for the body of a `#defer` block now. */\n fire?: (block: BlockEntry) => void;\n /**\n * Shows the fallback of a `#loading` or `#defer` block in place of its\n * body, or its body again. False when the page did not keep its fallback.\n */\n showFallback?: (block: BlockEntry, on: boolean) => boolean;\n /** The scopes written since the panel last drew, by scope ID. */\n written: Set<ScopeId>;\n /** The URL prefix of the inspect endpoint of the dev server. */\n endpoint: string;\n /** The versions of brumate and Vite, from the plugin. */\n meta: DevtoolsMeta;\n /** The errors of the page, oldest first. */\n errors: ErrorEntry[];\n /** The handlers that ran, oldest first, with their calls and updates. */\n timeline: Interaction[];\n /** The effects and `$client` callbacks that ran, by scope and name. */\n effects: Map<string, EffectEntry>;\n /** The client navigations of the page, newest last, at most 20. */\n navigations: NavigationReport[];\n /** Opens the panel on a tab, such as `errors`. */\n open?: (tab: string) => void;\n /** Shows the number of errors on the tab. */\n errorCount?: () => void;\n /** True while the elements that change are outlined on the page. */\n flash: boolean;\n /** Turns the outlines of changed elements on or off, and keeps the choice. */\n setFlash?: (on: boolean) => void;\n /** While the panel is open: sets its top edge to a place of the pointer, and keeps it. */\n resize?: (clientY: number) => void;\n resized?: () => void;\n /** Called after each change, while the panel is open. */\n changed?: () => void;\n}\n\nconst MAX_LOG = 300;\n\nimport { LOGO } from './logo.ts';\nimport { trustedHTML } from './trusted.ts';\n\nexport { LOGO };\n\n/** The root scope of a scope, whose `m` names its component. */\nexport function findRootScope(scope: Scope): Scope {\n let root = scope;\n while (root.p) {\n root = root.p;\n }\n return root;\n}\n\n/** A short text for a value in the log. */\nexport function preview(value: unknown): string {\n if (typeof value === 'string') {\n return JSON.stringify(value.length > 40 ? `${value.slice(0, 40)}…` : value);\n }\n if (typeof value === 'function') {\n return 'function';\n }\n if (Array.isArray(value)) {\n return `Array(${value.length})`;\n }\n if (value instanceof Element) {\n return `<${value.tagName.toLowerCase()}>`;\n }\n if (value !== null && typeof value === 'object') {\n const name = value.constructor?.name;\n return name && name !== 'Object' ? name : `{${Object.keys(value).slice(0, 3).join(', ')}}`;\n }\n return String(value);\n}\n\n/**\n * What happens to a block. `rendered`: the markers of the page show its body. `fired`: its trigger\n * fired. `settled`: the request for the body of a `#defer` settled.\n */\nexport type BlockEvent = 'rendered' | 'fired' | 'settled';\n\n/**\n * The state of a block after an event. A rendered block stays rendered. A `#defer` loads when\n * it fires, and fails when its request settles with the fallback still shown. A `$client`\n * callback has rendered once it fired. A `#client` block waits for its marker.\n */\nexport function nextBlockState(block: BlockEntry, event: BlockEvent): BlockEntry['state'] {\n if (block.state === 'rendered' || event === 'rendered') {\n return 'rendered';\n }\n if (event === 'settled') {\n return block.state === 'loading' ? 'failed' : block.state;\n }\n if (block.kind === 'defer') {\n return 'loading';\n }\n return block.kind === '$client' ? 'rendered' : block.state;\n}\n\n/** Moves a block to its state after an event. Returns true when the state changed. */\nexport function moveBlock(block: BlockEntry, event: BlockEvent, now: number): boolean {\n const next = nextBlockState(block, event);\n if (next === block.state) {\n return false;\n }\n block.state = next;\n if (next === 'rendered') {\n block.rendered = now;\n }\n return true;\n}\n\n/**\n * Reads the blocks of the page from their markers, and updates their state.\n * Returns true when something changed.\n *\n * - `#defer`: a `<template b-defer>`, and `<!--l…-->` around its fallback until its body arrives.\n * - `#loading`: `<!--l…-->` around its fallback until the server streams its body.\n * - `#client`: a `<template b-client>` with a `#k` reference, and a marker that gets `:1` once\n * its body rendered.\n * - `$client`: a `<template b-client>` with a `#c` reference.\n */\nexport function scanBlocks(state: DevtoolsState): boolean {\n const now = performance.now();\n let changed = false;\n const open = new Map<string, Comment>();\n const markers = new Map<string, Comment>();\n const walker = document.createTreeWalker(document, NodeFilter.SHOW_COMMENT);\n for (let node = walker.nextNode(); node; node = walker.nextNode()) {\n const data = (node as Comment).data;\n if (/^l[\\d.-]+$/.test(data)) {\n open.set(data.slice(1), node as Comment);\n } else if (/^b-?[\\d.]+:\\d+/.test(data)) {\n markers.set(data.slice(1).split(':').slice(0, 2).join(':'), node as Comment);\n }\n }\n const seen = new Set<string>();\n function update(key: string, make: () => BlockEntry, rendered: boolean): void {\n seen.add(key);\n let block = state.blocks.get(key);\n if (!block) {\n block = make();\n state.blocks.set(key, block);\n changed = true;\n }\n if (rendered && moveBlock(block, 'rendered', now)) {\n changed = true;\n }\n }\n const deferBoundaries = new Set<string>();\n for (const template of document.querySelectorAll('template[b-defer]')) {\n const [trigger, boundary] = template.getAttribute('b-defer')!.split(':') as [string, string];\n deferBoundaries.add(boundary);\n update(\n `defer:${boundary}`,\n () => ({ kind: 'defer', id: boundary, trigger, template, state: 'waiting', seen: now }),\n !open.has(boundary),\n );\n }\n for (const boundary of open.keys()) {\n if (!deferBoundaries.has(boundary)) {\n update(\n `loading:${boundary}`,\n () => ({ kind: 'loading', id: boundary, state: 'streaming', seen: now }),\n false,\n );\n }\n }\n for (const template of document.querySelectorAll('template[b-client]')) {\n const [trigger, ref] = template.getAttribute('b-client')!.split('=') as [string, string];\n const id = template.getAttribute('b-b') ?? '';\n const block = /#k\\d+$/.test(ref);\n const marker = markers.get(id);\n update(\n `client:${id}`,\n () => ({\n kind: block ? 'client' : '$client',\n id,\n trigger,\n ref,\n template,\n state: 'waiting',\n seen: now,\n }),\n // A `$client` callback has run once its trigger fired.\n Boolean(\n block\n ? marker && marker.data.split(':').length > 2\n : state.blocks.get(`client:${id}`)?.fired,\n ),\n );\n }\n // A `#loading` block whose markers are gone rendered its body. Other blocks that left the page,\n // such as on navigation, are dropped.\n for (const [key, block] of state.blocks) {\n if (seen.has(key)) {\n continue;\n }\n if (block.kind === 'loading') {\n if (moveBlock(block, 'rendered', now)) {\n changed = true;\n }\n } else if (!block.template?.isConnected) {\n state.blocks.delete(key);\n changed = true;\n }\n }\n return changed;\n}\n\n/**\n * Adds an error to the Errors tab. An error of the server or of Vite opens\n * the panel on it, as Vite's overlay would. An error of the browser only\n * counts on the button.\n */\nexport function reportError(\n state: DevtoolsState,\n payload: ErrorPayload,\n source: ErrorEntry['source'],\n): void {\n const file = payload.loc?.file ?? payload.id;\n const entry: ErrorEntry = {\n time: performance.now(),\n // An error of a plugin, such as a compile error, is one, even when a render met it.\n source: source === 'server' && payload.plugin ? 'compile' : source,\n message: payload.message,\n ...(payload.stack ? { stack: payload.stack } : {}),\n ...(payload.frame ? { frame: payload.frame } : {}),\n ...(payload.plugin ? { plugin: payload.plugin } : {}),\n ...(payload.loc && file\n ? { loc: { file, line: payload.loc.line, column: payload.loc.column } }\n : {}),\n };\n // The same error again, such as on each request for the page, counts once.\n const last = state.errors.at(-1);\n if (last?.message !== entry.message || last.stack !== entry.stack) {\n state.errors.push(entry);\n if (state.errors.length > 50) {\n state.errors.shift();\n }\n }\n state.errorCount?.();\n state.changed?.();\n if (source !== 'browser') {\n state.open?.('errors');\n }\n}\n\n/** The code of the panel, which loads when it opens. */\nfunction panelModule(): Promise<typeof Panel> {\n return import('./devtools-panel.ts');\n}\n\n/** True for an error of code that is not of the page, such as of a browser extension. */\nfunction foreign(stack: string | undefined, file = ''): boolean {\n return (\n /^[a-z-]+-extension:/.test(file) ||\n (stack !== undefined &&\n /[a-z-]+-extension:\\/\\//.test(stack) &&\n !stack.includes(location.origin))\n );\n}\n\n/** Listens to the core, and adds the button that opens the panel. */\nexport function installDevtools(\n endpoint = '/__brumate/inspect',\n rpc = '/_brumate',\n meta: DevtoolsMeta = {},\n hot?: HotContext,\n): DevtoolsState {\n // The plugin installs the devtools on its own, so an entry that does it too must not add a second set.\n const installed = (globalThis as Record<symbol, Installed | undefined>)[INSTALLED];\n // A host that was removed (a test, or the user) lets a new install replace this one.\n if (installed && (installed.host.isConnected || !installed.appended)) {\n return installed.state;\n }\n const state: DevtoolsState = {\n log: [],\n blocks: new Map(),\n written: new Set(),\n endpoint,\n meta,\n errors: [],\n timeline: [],\n effects: new Map(),\n navigations: [],\n flash: false,\n };\n /** The handler that a server call or an update that starts now belongs to. */\n function owner(time: number): Interaction | undefined {\n for (let index = state.timeline.length - 1; index >= 0; index--) {\n const run = state.timeline[index]!;\n // An update of the answer of a call comes a moment after the handler settled.\n if (run.begun <= time && (run.settled === undefined || time <= run.settled + 32)) {\n return run;\n }\n }\n return undefined;\n }\n function add(entry: Omit<DevtoolsEntry, 'time'>): void {\n state.log.push({ ...entry, time: performance.now() });\n if (state.log.length > MAX_LOG) {\n state.log.splice(0, state.log.length - MAX_LOG);\n }\n state.changed?.();\n }\n const hooks: DevtoolsHooks = {\n attach(core) {\n state.scopes = core.scopes;\n state.set = core.set;\n state.handle = core.handle;\n state.changed?.();\n },\n handled(run) {\n const entry: Interaction = {\n ref: run.ref,\n label: `${run.event ?? 'call'} on <${run.element.tagName.toLowerCase()}>`,\n begun: run.begun,\n ready: run.ready,\n end: run.end,\n calls: [],\n updates: [],\n };\n if (run.result instanceof Promise) {\n run.result.then(\n () => {\n entry.settled = performance.now();\n state.changed?.();\n },\n () => {\n entry.settled = performance.now();\n entry.failed = true;\n state.changed?.();\n },\n );\n } else {\n entry.settled = run.end;\n }\n state.timeline.push(entry);\n if (state.timeline.length > 100) {\n state.timeline.shift();\n }\n state.changed?.();\n },\n updated(count, start, end) {\n if (count > 0) {\n owner(start)?.updates.push({ count, start, end });\n }\n },\n defer(template, done) {\n deferred(template, done);\n },\n handler(ref, element, event) {\n if (element.tagName === 'TEMPLATE') {\n let block: BlockEntry | undefined;\n for (const item of state.blocks.values()) {\n if (item.template === element) {\n block = item;\n break;\n }\n }\n if (block && block.fired === undefined) {\n block.fired = performance.now();\n moveBlock(block, 'fired', block.fired);\n }\n }\n add({\n kind: 'handler',\n text: `${event?.type ?? 'call'} on <${element.tagName.toLowerCase()}>: ${ref}`,\n });\n },\n effect(scope, name, kind, time) {\n const key = `${scope.id}:${name}`;\n let entry = state.effects.get(key);\n if (!entry) {\n entry = {\n scope: scope.id,\n component: findRootScope(scope).m ?? '',\n k: scope.k,\n name,\n runs: 0,\n recent: [],\n time: 0,\n cleanups: 0,\n active: false,\n };\n state.effects.set(key, entry);\n }\n const now = performance.now();\n if (kind === 'run') {\n entry.runs++;\n entry.time += time;\n entry.recent.push(now);\n if (entry.recent.length > 50) {\n entry.recent.shift();\n }\n entry.active = true;\n } else {\n entry.cleanups++;\n entry.lastCleanup = now;\n entry.active = false;\n }\n state.changed?.();\n },\n navigated(report) {\n state.navigations.push(report);\n if (state.navigations.length > 20) {\n state.navigations.shift();\n }\n state.changed?.();\n },\n write(scope, slot, value) {\n state.written.add(scope.id);\n const root = findRootScope(scope);\n add({\n kind: 'write',\n text: `scope ${scope.id} slot ${slot} = ${preview(value)}`,\n scope: scope.id,\n write: { component: root.m ?? '', k: scope.k, slot },\n });\n },\n };\n (globalThis as Record<symbol, DevtoolsHooks | undefined>)[DEVTOOLS] = hooks;\n\n // The swap of a body keeps its fallback in development, by boundary, so the fallback can show\n // again. While it shows, the body is out of the page, and updates of its nodes wait there.\n state.showFallback = (block, on) => {\n const kept = (globalThis as { $bD?: Record<string, { f: Node[]; b: Node[] }> }).$bD?.[block.id];\n if (!kept || (block.fallback ?? false) === on) {\n return false;\n }\n const [shown, hidden] = on ? [kept.b, kept.f] : [kept.f, kept.b];\n let anchor: Node | undefined;\n for (const node of shown) {\n if (node.parentNode) {\n anchor = node;\n break;\n }\n }\n if (!anchor) {\n return false;\n }\n for (const node of hidden) {\n anchor.parentNode!.insertBefore(node, anchor);\n }\n for (const node of shown) {\n node.parentNode?.removeChild(node);\n }\n block.fallback = on;\n state.changed?.();\n return true;\n };\n\n // Server function calls, with how long each took and how it answered.\n // Code that replaced fetch since the last install (a test stub) is kept and wrapped.\n const unwrapped =\n installed && globalThis.fetch === installed.wrapper ? installed.fetch : globalThis.fetch;\n const original = unwrapped.bind(globalThis);\n globalThis.fetch = async (input, init) => {\n const url = new URL(input instanceof Request ? input.url : String(input), location.href);\n if (url.origin !== location.origin || !url.pathname.startsWith(`${rpc}/`)) {\n return original(input, init);\n }\n const name = decodeURIComponent(url.pathname.slice(rpc.length + 1));\n const started = performance.now();\n const call: CallTiming = { name, start: started };\n const headers: Record<string, string> = {};\n for (const [header, value] of new Headers(init?.headers)) {\n if (header === 'content-type' || header.startsWith('x-brumate-')) {\n headers[header] = value;\n }\n }\n const body = init?.body;\n call.request = {\n url: url.pathname + url.search,\n headers,\n ...(typeof body === 'string' || body instanceof FormData ? { body } : {}),\n };\n owner(started)?.calls.push(call);\n try {\n const response = await original(input, init);\n const took = Math.round(performance.now() - started);\n const redirect = response.headers.get('x-brumate-redirect');\n call.end = performance.now();\n call.status = redirect ? 'redirect' : response.status;\n const server = /brumate;dur=([\\d.]+)/.exec(response.headers.get('server-timing') ?? '');\n if (server) {\n call.server = Number(server[1]);\n }\n // The record fills in once the arguments and the result are decoded. It reads a clone.\n const arrived = call.end;\n const copy = response.clone();\n void import('./devtools-calls.ts')\n .then(({ readCall }) =>\n readCall({\n name,\n init,\n response: copy,\n started,\n arrived,\n module: Math.max(0, started - (owner(started)?.ready ?? started)),\n }),\n )\n .then((record) => {\n call.record = record;\n state.changed?.();\n })\n .catch(() => {});\n state.changed?.();\n add({\n kind: 'call',\n text: `${name}: ${redirect ? `redirect to ${redirect}` : response.status} in ${took} ms`,\n call,\n });\n return response;\n } catch (error) {\n call.end = performance.now();\n call.status = 'failed';\n add({\n kind: 'call',\n text: `${name}: failed, ${error instanceof Error ? error.message : String(error)}`,\n call,\n });\n throw error;\n }\n };\n\n // Blocks: the markers of the page tell their state, so the panel follows the changes of the DOM.\n function deferred(template: Element, done: Promise<unknown>): void {\n let block: BlockEntry | undefined;\n for (const item of state.blocks.values()) {\n if (item.template === template) {\n block = item;\n break;\n }\n }\n // The loader asks once, so a block that is already loading waits for its first request.\n const asked = block !== undefined && block.state !== 'loading';\n if (block) {\n block.fired ??= performance.now();\n moveBlock(block, 'fired', block.fired);\n }\n void done.finally(() => {\n scanBlocks(state);\n // A body that arrived rendered the block in the scan, so one still loading got none.\n if (block && asked) {\n moveBlock(block, 'settled', performance.now());\n }\n state.changed?.();\n });\n }\n state.fire = (block) => {\n if (block.kind === 'defer' && block.template) {\n deferred(\n block.template,\n import('./defer.ts').then((module) => module.loadDeferred(block.template!)),\n );\n } else if (block.template && block.ref) {\n void state.handle?.(block.template, block.ref);\n }\n };\n if (typeof MutationObserver !== 'undefined') {\n let queued = false;\n new MutationObserver(() => {\n if (!queued) {\n queued = true;\n queueMicrotask(() => {\n queued = false;\n if (scanBlocks(state)) {\n state.changed?.();\n }\n });\n }\n }).observe(document, { childList: true, subtree: true, characterData: true });\n }\n scanBlocks(state);\n\n const host = document.createElement('brumate-devtools');\n (globalThis as Record<symbol, Installed | undefined>)[INSTALLED] = {\n state,\n host,\n appended: false,\n fetch: unwrapped,\n wrapper: globalThis.fetch,\n };\n const mark = (globalThis as Record<symbol, Installed | undefined>)[INSTALLED]!;\n const root = host.attachShadow({ mode: 'open' });\n const style = document.createElement('style');\n style.textContent = `\n.open { position: fixed; left: 50%; bottom: 0; z-index: 2147483647; transform: translateX(-50%); display: flex; align-items: center; gap: 8px; height: 6px; max-width: 44px; padding: 0 10px; overflow: hidden; border: 0; border-radius: 7px 7px 0 0; background: #3a373d; color: #ece8e4; font: 500 12px/1 system-ui, -apple-system, sans-serif; white-space: nowrap; cursor: pointer; touch-action: none; outline: none; transition: height 0.22s cubic-bezier(0.2, 0.8, 0.2, 1), max-width 0.3s cubic-bezier(0.2, 0.8, 0.2, 1), background 0.2s; }\n.open[hidden] { display: none; }\n.open > * { opacity: 0; transition: opacity 0.12s; }\n.open[data-errors] { background: #c94a4a; max-width: 64px; }\n.open:hover, .open:focus-visible { height: 30px; max-width: 320px; background: #1d1c1f; box-shadow: 0 0 0 1px #36333a; }\n.open[data-errors]:hover, .open[data-errors]:focus-visible { box-shadow: 0 0 0 1px #ff6b6b66; }\n.open:hover > *, .open:focus-visible > * { opacity: 1; transition-delay: 0.08s; }\n.mark { display: inline-flex; width: 16px; height: 16px; flex: none; }\n.name { font-weight: 600; }\n.version { color: #a39a92; font: 11px ui-monospace, 'SF Mono', SFMono-Regular, Menlo, monospace; }\n.count { padding: 0 6px; border-radius: 999px; background: #ff6b6b26; color: #ff6b6b; font: 600 10.5px/17px ui-monospace, 'SF Mono', SFMono-Regular, Menlo, monospace; }\n.count:empty { display: none; }\n@media (prefers-reduced-motion: reduce) { .open, .open > * { transition: none; } }\n`;\n // The closed panel: a grip on the bottom edge that grows into a pull tab on hover or focus, so\n // it covers almost none of the page. A click, or a drag up, opens the panel.\n const button = document.createElement('button');\n button.type = 'button';\n button.className = 'open';\n button.title = 'brumate devtools (Alt+Shift+D)';\n button.innerHTML = trustedHTML(\n `<span class=\"mark\">${LOGO}</span><span class=\"name\">brumate</span><span class=\"version\"></span><span class=\"count\"></span>`,\n );\n // The version of brumate, next to its mark.\n button.querySelector('.version')!.textContent = meta.version ?? '';\n function label(): void {\n const errors = state.errors.length;\n button.setAttribute(\n 'aria-label',\n `Open the brumate devtools${meta.version ? `, version ${meta.version}` : ''}${errors > 0 ? `, ${errors} errors` : ''}`,\n );\n }\n label();\n // The number of errors, in red on the tab, and a red grip, so an error shows while it is closed.\n const count = button.querySelector<HTMLElement>('.count')!;\n state.errorCount = (): void => {\n count.textContent =\n state.errors.length > 0\n ? `${state.errors.length} ${state.errors.length === 1 ? 'issue' : 'issues'}`\n : '';\n button.toggleAttribute('data-errors', state.errors.length > 0);\n label();\n };\n // Dragging the tab up past a few pixels opens the panel under the pointer. A press that does not\n // move is left to the click.\n let dragged = false;\n button.addEventListener('pointerdown', (event) => {\n if (event.button !== 0) {\n return;\n }\n const start = event.clientY;\n let opened = false;\n dragged = false;\n function move(next: PointerEvent): void {\n if (!opened) {\n if (start - next.clientY < 4) {\n return;\n }\n opened = true;\n dragged = true;\n void panelModule().then(({ openPanel }) => {\n openPanel(root, state);\n state.resize?.(next.clientY);\n });\n return;\n }\n state.resize?.(next.clientY);\n }\n // The tab hides as the panel opens, so the pointer is followed on the window.\n function end(): void {\n removeEventListener('pointermove', move);\n removeEventListener('pointerup', end);\n removeEventListener('pointercancel', end);\n if (opened) {\n state.resized?.();\n }\n }\n addEventListener('pointermove', move);\n addEventListener('pointerup', end);\n addEventListener('pointercancel', end);\n });\n button.addEventListener('click', () => {\n if (dragged) {\n dragged = false;\n return;\n }\n void panelModule().then(({ togglePanel }) => togglePanel(root, state));\n });\n // Alt+Shift+D opens and closes the panel. `code`, because Alt changes the key on macOS.\n addEventListener('keydown', (event) => {\n if (event.altKey && event.shiftKey && event.code === 'KeyD') {\n event.preventDefault();\n void panelModule().then(({ togglePanel }) => togglePanel(root, state));\n }\n });\n state.open = (tab) => {\n void import('./devtools-panel.ts').then(({ openPanel }) => openPanel(root, state, tab));\n };\n root.append(style, button);\n installFlash(state, root, host);\n\n // Errors of code of the page in the browser. Errors of other code are left out.\n addEventListener('error', (event) => {\n const stack = (event.error as Error | undefined)?.stack;\n if (foreign(stack, event.filename)) {\n return;\n }\n const error = event.error as Error | undefined;\n // The message of the error, without the `Uncaught` that the browser puts before it.\n reportError(\n state,\n { message: error?.message ?? event.message, stack: error?.stack },\n 'browser',\n );\n });\n addEventListener('unhandledrejection', (event) => {\n const reason = event.reason as Error | undefined;\n if (foreign(reason?.stack)) {\n return;\n }\n reportError(\n state,\n { message: reason?.message ?? String(event.reason), stack: reason?.stack },\n 'browser',\n );\n });\n // Errors of handlers and updates that no `#try` caught. The core catches them, so they do not\n // reach the listeners above.\n addEventListener('brumate:error', (event) => {\n const error = (event as CustomEvent<{ error: unknown }>).detail.error as Error | undefined;\n reportError(\n state,\n { message: error?.message ?? String(error), stack: error?.stack },\n 'browser',\n );\n });\n // Errors of Vite, such as a compile error after an edit, which its overlay would show. A good\n // update after them clears them.\n hot?.on('vite:error', (payload: { err: ErrorPayload }) => {\n reportError(state, payload.err, 'compile');\n });\n hot?.on('vite:afterUpdate', () => {\n const before = state.errors.length;\n const remaining: ErrorEntry[] = [];\n for (const error of state.errors) {\n if (error.source !== 'compile') {\n remaining.push(error);\n }\n }\n state.errors = remaining;\n if (state.errors.length !== before) {\n state.errorCount?.();\n state.changed?.();\n }\n });\n function append(): void {\n // Navigation replaces the body, so the button goes on the document element.\n document.documentElement.append(host);\n mark.appended = true;\n }\n if (document.readyState === 'loading') {\n document.addEventListener('DOMContentLoaded', append);\n } else {\n append();\n }\n return state;\n}\n"],"mappings":";;;;AAGA,MAAM,YAAY;;AAOlB,MAAM,OAAO;CACX,MAAM;EAAE,MAAM;EAAW,MAAM;CAA0B;CACzD,MAAM;EAAE,MAAM;EAAW,MAAM;CAAyB;CACxD,KAAK;EAAE,MAAM;EAAW,MAAM;CAA0B;AAC1D;;AAuBA,SAAS,SAAS,OAAqB;CACrC,IAAI,SAAS,GACX,OAAO;CAET,OAAO,SAAS,IAAI,SAAS;AAC/B;AAEA,SAAS,gBAAyB;CAChC,OAAO,OAAO,eAA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K,SAAS;CAC3C,CAAC;CACD,KAAK,GAAG,0BAA0B;EAChC,MAAM,SAAS,MAAM,OAAO;EAC5B,MAAM,YAA0B,CAAC;EACjC,KAAK,MAAM,SAAS,MAAM,QACxB,IAAI,MAAM,WAAW,WACnB,UAAU,KAAK,KAAK;EAGxB,MAAM,SAAS;EACf,IAAI,MAAM,OAAO,WAAW,QAAQ;GAClC,MAAM,aAAa;GACnB,MAAM,UAAU;EAClB;CACF,CAAC;CACD,SAAS,SAAe;EAEtB,SAAS,gBAAgB,OAAO,IAAI;EACpC,KAAK,WAAW;CAClB;CACA,IAAI,SAAS,eAAe,WAC1B,SAAS,iBAAiB,oBAAoB,MAAM;MAEpD,OAAO;CAET,OAAO;AACT"}
|
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
//#region src/runtime/devtools-calls.ts
|
|
2
|
+
/** The header that the dev server answers with. A production server never sets it. */
|
|
3
|
+
const DEV_HEADER = "x-brumate-dev";
|
|
4
|
+
/** The longest text of a value, a log line or a stack, in characters. */
|
|
5
|
+
const TEXT_LIMIT = 1e3;
|
|
6
|
+
const STACK_LIMIT = 2e3;
|
|
7
|
+
const ITEM_LIMIT = 50;
|
|
8
|
+
const DEPTH_LIMIT = 5;
|
|
9
|
+
/** The longest header, once encoded. Servers refuse headers of about 8 kB and more. */
|
|
10
|
+
const HEADER_LIMIT = 6e3;
|
|
11
|
+
/** The hook of `dedupe` in the server core, under a symbol of the registry. */
|
|
12
|
+
const CALL_HOOK = Symbol.for("brumate.callHook");
|
|
13
|
+
const LOG_SINK = Symbol.for("brumate.devLogSink");
|
|
14
|
+
const LEVELS = [
|
|
15
|
+
"log",
|
|
16
|
+
"info",
|
|
17
|
+
"warn",
|
|
18
|
+
"error",
|
|
19
|
+
"debug"
|
|
20
|
+
];
|
|
21
|
+
/** Cuts a text at a length, and marks the cut. */
|
|
22
|
+
function cutText(text, limit = TEXT_LIMIT) {
|
|
23
|
+
return text.length > limit ? `${text.slice(0, limit)}… (${text.length - limit} more)` : text;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* A copy of a value that is safe to keep and show: text cut, at most 50 items in a list or an
|
|
27
|
+
* object, 5 levels deep, no cycles. Functions, symbols, files and errors become text.
|
|
28
|
+
*/
|
|
29
|
+
function cutValue(value, depth = 0, seen = /* @__PURE__ */ new Set()) {
|
|
30
|
+
switch (typeof value) {
|
|
31
|
+
case "string": return cutText(value);
|
|
32
|
+
case "bigint": return `${value}n`;
|
|
33
|
+
case "symbol": return value.toString();
|
|
34
|
+
case "function": return `[Function ${value.name || "anonymous"}]`;
|
|
35
|
+
case "object": break;
|
|
36
|
+
default: return value;
|
|
37
|
+
}
|
|
38
|
+
if (value === null || value instanceof Date) return value;
|
|
39
|
+
if (value instanceof Error) return cutText(`[${value.name}: ${value.message}]`);
|
|
40
|
+
if (typeof Blob !== "undefined" && value instanceof Blob) {
|
|
41
|
+
const name = value.name;
|
|
42
|
+
return `[${name === void 0 ? "Blob" : `File ${name}`}, ${value.size} bytes, ${value.type}]`;
|
|
43
|
+
}
|
|
44
|
+
if (seen.has(value)) return "[Circular]";
|
|
45
|
+
if (depth >= DEPTH_LIMIT) return Array.isArray(value) ? "[Array]" : "[Object]";
|
|
46
|
+
seen.add(value);
|
|
47
|
+
let result;
|
|
48
|
+
if (Array.isArray(value) || value instanceof Set) {
|
|
49
|
+
const items = [];
|
|
50
|
+
for (const item of value) {
|
|
51
|
+
if (items.length === ITEM_LIMIT) {
|
|
52
|
+
items.push(`… ${(Array.isArray(value) ? value.length : value.size) - ITEM_LIMIT} more`);
|
|
53
|
+
break;
|
|
54
|
+
}
|
|
55
|
+
items.push(cutValue(item, depth + 1, seen));
|
|
56
|
+
}
|
|
57
|
+
result = value instanceof Set ? new Set(items) : items;
|
|
58
|
+
} else if (value instanceof Map) {
|
|
59
|
+
const entries = [];
|
|
60
|
+
for (const [key, item] of value) {
|
|
61
|
+
if (entries.length === ITEM_LIMIT) break;
|
|
62
|
+
entries.push([cutValue(key, depth + 1, seen), cutValue(item, depth + 1, seen)]);
|
|
63
|
+
}
|
|
64
|
+
result = new Map(entries);
|
|
65
|
+
} else if (typeof FormData !== "undefined" && value instanceof FormData) result = cutValue(Object.fromEntries(value), depth, seen);
|
|
66
|
+
else {
|
|
67
|
+
const copy = {};
|
|
68
|
+
let count = 0;
|
|
69
|
+
for (const key of Object.keys(value)) {
|
|
70
|
+
if (count === ITEM_LIMIT) {
|
|
71
|
+
copy["…"] = `${Object.keys(value).length - ITEM_LIMIT} more`;
|
|
72
|
+
break;
|
|
73
|
+
}
|
|
74
|
+
copy[key] = cutValue(value[key], depth + 1, seen);
|
|
75
|
+
count++;
|
|
76
|
+
}
|
|
77
|
+
result = copy;
|
|
78
|
+
}
|
|
79
|
+
seen.delete(value);
|
|
80
|
+
return result;
|
|
81
|
+
}
|
|
82
|
+
/** What went wrong in a call, with a stack that is cut. */
|
|
83
|
+
function describeError(error) {
|
|
84
|
+
if (error instanceof Error) return {
|
|
85
|
+
message: cutText(error.message),
|
|
86
|
+
...error.stack ? { stack: cutText(error.stack, STACK_LIMIT) } : {}
|
|
87
|
+
};
|
|
88
|
+
return { message: cutText(String(error)) };
|
|
89
|
+
}
|
|
90
|
+
/** Writes the server part of a record for the header. It shrinks the record to fit. */
|
|
91
|
+
function encodeServerRecord(record) {
|
|
92
|
+
const copy = {
|
|
93
|
+
...record,
|
|
94
|
+
logs: [...record.logs],
|
|
95
|
+
...record.error ? { error: { ...record.error } } : {}
|
|
96
|
+
};
|
|
97
|
+
let text = encodeURIComponent(JSON.stringify(copy));
|
|
98
|
+
while (text.length > HEADER_LIMIT && copy.logs.length > 0) {
|
|
99
|
+
copy.logs.length = Math.floor(copy.logs.length / 2);
|
|
100
|
+
copy.truncated = true;
|
|
101
|
+
text = encodeURIComponent(JSON.stringify(copy));
|
|
102
|
+
}
|
|
103
|
+
if (text.length > HEADER_LIMIT && copy.error?.stack) {
|
|
104
|
+
delete copy.error.stack;
|
|
105
|
+
text = encodeURIComponent(JSON.stringify(copy));
|
|
106
|
+
}
|
|
107
|
+
if (text.length > HEADER_LIMIT) {
|
|
108
|
+
copy.calls = [];
|
|
109
|
+
copy.reads = [];
|
|
110
|
+
text = encodeURIComponent(JSON.stringify(copy));
|
|
111
|
+
}
|
|
112
|
+
let limit = TEXT_LIMIT;
|
|
113
|
+
while (text.length > HEADER_LIMIT && copy.error && limit > 20) {
|
|
114
|
+
limit = Math.floor(limit / 2);
|
|
115
|
+
copy.error.message = cutText(copy.error.message, limit);
|
|
116
|
+
text = encodeURIComponent(JSON.stringify(copy));
|
|
117
|
+
}
|
|
118
|
+
return text;
|
|
119
|
+
}
|
|
120
|
+
/** Reads the header of the dev server, or undefined when the answer has none. */
|
|
121
|
+
function decodeServerRecord(header) {
|
|
122
|
+
if (!header) return;
|
|
123
|
+
try {
|
|
124
|
+
return JSON.parse(decodeURIComponent(header));
|
|
125
|
+
} catch {
|
|
126
|
+
return;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* Sets up the recording of calls on the dev server. `storage` is an `AsyncLocalStorage`, and
|
|
131
|
+
* `format` is `util.format`. Returns what wraps the handling of one call: it runs the handler,
|
|
132
|
+
* and adds the header to the answer. `console.*` is patched once for the process.
|
|
133
|
+
*/
|
|
134
|
+
function createRecorder(storage, format) {
|
|
135
|
+
const globals = globalThis;
|
|
136
|
+
globals[CALL_HOOK] = (id, run) => {
|
|
137
|
+
const collector = storage.getStore();
|
|
138
|
+
if (!collector) return run();
|
|
139
|
+
if (collector.top !== void 0) {
|
|
140
|
+
if (collector.calls.length < ITEM_LIMIT) collector.calls.push(id);
|
|
141
|
+
return run();
|
|
142
|
+
}
|
|
143
|
+
collector.top = id;
|
|
144
|
+
let result;
|
|
145
|
+
try {
|
|
146
|
+
result = run();
|
|
147
|
+
} catch (error) {
|
|
148
|
+
collector.error = describeError(error);
|
|
149
|
+
throw error;
|
|
150
|
+
}
|
|
151
|
+
if (result && typeof result.then === "function") result.catch((error) => {
|
|
152
|
+
collector.error = describeError(error);
|
|
153
|
+
});
|
|
154
|
+
return result;
|
|
155
|
+
};
|
|
156
|
+
const wasPatched = globals[LOG_SINK] !== void 0;
|
|
157
|
+
globals[LOG_SINK] = (level, args) => {
|
|
158
|
+
const collector = storage.getStore();
|
|
159
|
+
if (collector && collector.logs.length < ITEM_LIMIT) collector.logs.push({
|
|
160
|
+
level,
|
|
161
|
+
text: cutText(format(...args))
|
|
162
|
+
});
|
|
163
|
+
};
|
|
164
|
+
if (!wasPatched) for (const level of LEVELS) {
|
|
165
|
+
const original = console[level].bind(console);
|
|
166
|
+
console[level] = (...args) => {
|
|
167
|
+
globalThis[LOG_SINK]?.(level, args);
|
|
168
|
+
original(...args);
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
return async (run) => {
|
|
172
|
+
const collector = {
|
|
173
|
+
calls: [],
|
|
174
|
+
logs: []
|
|
175
|
+
};
|
|
176
|
+
const answer = await storage.run(collector, run);
|
|
177
|
+
const redirected = answer.headers.has("x-brumate-redirect");
|
|
178
|
+
const refreshed = answer.headers.get("x-brumate-refresh");
|
|
179
|
+
const record = {
|
|
180
|
+
reads: refreshed ? refreshed.split(",") : [],
|
|
181
|
+
calls: collector.calls,
|
|
182
|
+
logs: collector.logs
|
|
183
|
+
};
|
|
184
|
+
if (collector.error && !redirected) record.error = collector.error;
|
|
185
|
+
answer.headers.set(DEV_HEADER, encodeServerRecord(record));
|
|
186
|
+
return answer;
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
/**
|
|
190
|
+
* Makes the record of a call: decodes its arguments and its result, and joins them with the part
|
|
191
|
+
* that the dev server sent. `response` must be a clone, since this reads its body.
|
|
192
|
+
*/
|
|
193
|
+
async function readCall(input) {
|
|
194
|
+
const { name, init, response, started, arrived } = input;
|
|
195
|
+
const { error, ...server } = decodeServerRecord(response.headers.get("x-brumate-dev")) ?? {};
|
|
196
|
+
const took = /brumate;dur=([\d.]+)/.exec(response.headers.get("server-timing") ?? "");
|
|
197
|
+
const serverTime = took ? Number(took[1]) : 0;
|
|
198
|
+
const record = {
|
|
199
|
+
name,
|
|
200
|
+
args: [],
|
|
201
|
+
timing: {
|
|
202
|
+
module: Math.round(input.module),
|
|
203
|
+
network: Math.max(0, Math.round(arrived - started - serverTime)),
|
|
204
|
+
server: Math.round(serverTime),
|
|
205
|
+
decode: 0
|
|
206
|
+
},
|
|
207
|
+
...server.logs ? { server } : {},
|
|
208
|
+
...error ? { error } : {}
|
|
209
|
+
};
|
|
210
|
+
const [{ fromJSON }, { callPlugins, serialOptions }, { fromChunkStream }] = await Promise.all([
|
|
211
|
+
import("seroval/read"),
|
|
212
|
+
import("./serial-ribg9NAj.js"),
|
|
213
|
+
import("./stream-read-Dek3HnqO.js")
|
|
214
|
+
]);
|
|
215
|
+
try {
|
|
216
|
+
const body = init?.body;
|
|
217
|
+
if (typeof body === "string") record.args = cutValue(fromJSON(JSON.parse(body), {
|
|
218
|
+
plugins: callPlugins(),
|
|
219
|
+
...serialOptions()
|
|
220
|
+
}));
|
|
221
|
+
else if (body instanceof FormData) {
|
|
222
|
+
if (body.has("args")) record.args = cutValue(fromJSON(JSON.parse(String(body.get("args"))), {
|
|
223
|
+
plugins: callPlugins(void 0, body),
|
|
224
|
+
...serialOptions()
|
|
225
|
+
}));
|
|
226
|
+
else record.args = [cutValue(body)];
|
|
227
|
+
}
|
|
228
|
+
} catch {}
|
|
229
|
+
const decoding = performance.now();
|
|
230
|
+
try {
|
|
231
|
+
if (response.ok && !response.headers.has("x-brumate-redirect") && response.body) record.result = cutValue(await fromChunkStream(response.body));
|
|
232
|
+
else if (!response.ok) {
|
|
233
|
+
const text = await response.text();
|
|
234
|
+
let message = text;
|
|
235
|
+
try {
|
|
236
|
+
message = JSON.parse(text).error;
|
|
237
|
+
} catch {}
|
|
238
|
+
record.error ??= { message: cutText(message) };
|
|
239
|
+
}
|
|
240
|
+
} catch (failure) {
|
|
241
|
+
record.error ??= { message: cutText(failure instanceof Error ? failure.message : String(failure)) };
|
|
242
|
+
}
|
|
243
|
+
record.timing.decode = Math.round(performance.now() - decoding);
|
|
244
|
+
return record;
|
|
245
|
+
}
|
|
246
|
+
//#endregion
|
|
247
|
+
export { DEV_HEADER, TEXT_LIMIT, createRecorder, cutText, cutValue, decodeServerRecord, describeError, encodeServerRecord, readCall };
|
|
248
|
+
|
|
249
|
+
//# sourceMappingURL=devtools-calls-DGW6nLZ2.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"devtools-calls-DGW6nLZ2.js","names":[],"sources":["../src/runtime/devtools-calls.ts"],"sourcesContent":["// The record of a server function call for the dock, in development only.\n//\n// The dev server runs each call inside a collector: it gathers the `console.*` output of the call,\n// the server functions it called, the error with its stack, and sends them back in the\n// `x-brumate-dev` header of the answer. The browser decodes the arguments and the result itself and\n// joins both into a `CallRecord`. Nothing here is imported by a production build: the dev server\n// and the devtools load it. No cookies and no headers are recorded, and values are cut at a length.\n\nimport type { CallRecord, DevAnswer, ServerRecord } from './devtools.ts';\n\nexport type { CallRecord, DevAnswer, ServerRecord } from './devtools.ts';\n\n/** The header that the dev server answers with. A production server never sets it. */\nexport const DEV_HEADER = 'x-brumate-dev';\n\n/** The longest text of a value, a log line or a stack, in characters. */\nexport const TEXT_LIMIT = 1000;\nconst STACK_LIMIT = 2000;\nconst ITEM_LIMIT = 50;\nconst DEPTH_LIMIT = 5;\n/** The longest header, once encoded. Servers refuse headers of about 8 kB and more. */\nconst HEADER_LIMIT = 6000;\n\n/** The hook of `dedupe` in the server core, under a symbol of the registry. */\nconst CALL_HOOK = Symbol.for('brumate.callHook');\nconst LOG_SINK = Symbol.for('brumate.devLogSink');\nconst LEVELS = ['log', 'info', 'warn', 'error', 'debug'] as const;\n\n/** Cuts a text at a length, and marks the cut. */\nexport function cutText(text: string, limit: number = TEXT_LIMIT): string {\n return text.length > limit ? `${text.slice(0, limit)}… (${text.length - limit} more)` : text;\n}\n\n/**\n * A copy of a value that is safe to keep and show: text cut, at most 50 items in a list or an\n * object, 5 levels deep, no cycles. Functions, symbols, files and errors become text.\n */\nexport function cutValue(\n value: unknown,\n depth: number = 0,\n seen: Set<object> = new Set<object>(),\n): unknown {\n switch (typeof value) {\n case 'string':\n return cutText(value);\n case 'bigint':\n return `${value}n`;\n case 'symbol':\n return value.toString();\n case 'function':\n return `[Function ${value.name || 'anonymous'}]`;\n case 'object':\n break;\n default:\n return value;\n }\n if (value === null || value instanceof Date) {\n return value;\n }\n if (value instanceof Error) {\n return cutText(`[${value.name}: ${value.message}]`);\n }\n if (typeof Blob !== 'undefined' && value instanceof Blob) {\n const name = (value as Partial<File>).name;\n return `[${name === undefined ? 'Blob' : `File ${name}`}, ${value.size} bytes, ${value.type}]`;\n }\n if (seen.has(value)) {\n return '[Circular]';\n }\n if (depth >= DEPTH_LIMIT) {\n return Array.isArray(value) ? '[Array]' : '[Object]';\n }\n seen.add(value);\n let result: unknown;\n if (Array.isArray(value) || value instanceof Set) {\n const items: unknown[] = [];\n for (const item of value) {\n if (items.length === ITEM_LIMIT) {\n items.push(`… ${(Array.isArray(value) ? value.length : value.size) - ITEM_LIMIT} more`);\n break;\n }\n items.push(cutValue(item, depth + 1, seen));\n }\n result = value instanceof Set ? new Set(items) : items;\n } else if (value instanceof Map) {\n const entries: [unknown, unknown][] = [];\n for (const [key, item] of value) {\n if (entries.length === ITEM_LIMIT) {\n break;\n }\n entries.push([cutValue(key, depth + 1, seen), cutValue(item, depth + 1, seen)]);\n }\n result = new Map(entries);\n } else if (typeof FormData !== 'undefined' && value instanceof FormData) {\n result = cutValue(Object.fromEntries(value), depth, seen);\n } else {\n const copy: Record<string, unknown> = {};\n let count = 0;\n for (const key of Object.keys(value)) {\n if (count === ITEM_LIMIT) {\n copy['…'] = `${Object.keys(value).length - ITEM_LIMIT} more`;\n break;\n }\n copy[key] = cutValue((value as Record<string, unknown>)[key], depth + 1, seen);\n count++;\n }\n result = copy;\n }\n seen.delete(value);\n return result;\n}\n\n/** What went wrong in a call, with a stack that is cut. */\nexport function describeError(error: unknown): { message: string; stack?: string } {\n if (error instanceof Error) {\n return {\n message: cutText(error.message),\n ...(error.stack ? { stack: cutText(error.stack, STACK_LIMIT) } : {}),\n };\n }\n return { message: cutText(String(error)) };\n}\n\n/** Writes the server part of a record for the header. It shrinks the record to fit. */\nexport function encodeServerRecord(record: DevAnswer): string {\n const copy: DevAnswer = {\n ...record,\n logs: [...record.logs],\n ...(record.error ? { error: { ...record.error } } : {}),\n };\n let text = encodeURIComponent(JSON.stringify(copy));\n while (text.length > HEADER_LIMIT && copy.logs.length > 0) {\n copy.logs.length = Math.floor(copy.logs.length / 2);\n copy.truncated = true;\n text = encodeURIComponent(JSON.stringify(copy));\n }\n if (text.length > HEADER_LIMIT && copy.error?.stack) {\n delete copy.error.stack;\n text = encodeURIComponent(JSON.stringify(copy));\n }\n if (text.length > HEADER_LIMIT) {\n copy.calls = [];\n copy.reads = [];\n text = encodeURIComponent(JSON.stringify(copy));\n }\n // A long message is cut until the header fits.\n let limit = TEXT_LIMIT;\n while (text.length > HEADER_LIMIT && copy.error && limit > 20) {\n limit = Math.floor(limit / 2);\n copy.error.message = cutText(copy.error.message, limit);\n text = encodeURIComponent(JSON.stringify(copy));\n }\n return text;\n}\n\n/** Reads the header of the dev server, or undefined when the answer has none. */\nexport function decodeServerRecord(header: string | null): DevAnswer | undefined {\n if (!header) {\n return undefined;\n }\n try {\n return JSON.parse(decodeURIComponent(header)) as DevAnswer;\n } catch {\n return undefined;\n }\n}\n\n// The dev server.\n\n/** The part of `AsyncLocalStorage` that the collector needs, so this module imports no Node module. */\ninterface Storage {\n run<R>(store: Collector, callback: () => R): R;\n getStore(): Collector | undefined;\n}\n\ninterface Collector {\n top?: string;\n calls: string[];\n logs: { level: string; text: string }[];\n error?: { message: string; stack?: string };\n}\n\ntype Hook = (id: string, run: () => unknown) => unknown;\ntype Globals = { [CALL_HOOK]?: Hook; [LOG_SINK]?: (level: string, args: unknown[]) => void };\n\n/**\n * Sets up the recording of calls on the dev server. `storage` is an `AsyncLocalStorage`, and\n * `format` is `util.format`. Returns what wraps the handling of one call: it runs the handler,\n * and adds the header to the answer. `console.*` is patched once for the process.\n */\nexport function createRecorder(\n storage: Storage,\n format: (...args: unknown[]) => string,\n): (run: () => Promise<Response>) => Promise<Response> {\n const globals = globalThis as Globals;\n // The server core calls this around every server function that is not part of a page render.\n globals[CALL_HOOK] = (id, run) => {\n const collector = storage.getStore();\n if (!collector) {\n return run();\n }\n if (collector.top !== undefined) {\n if (collector.calls.length < ITEM_LIMIT) {\n collector.calls.push(id);\n }\n return run();\n }\n // The first call is the one the browser made. Its error is recorded, and passes on.\n collector.top = id;\n let result: unknown;\n try {\n result = run();\n } catch (error) {\n collector.error = describeError(error);\n throw error;\n }\n if (result && typeof (result as PromiseLike<unknown>).then === 'function') {\n (result as Promise<unknown>).catch((error: unknown) => {\n collector.error = describeError(error);\n });\n }\n return result;\n };\n const wasPatched = globals[LOG_SINK] !== undefined;\n globals[LOG_SINK] = (level, args) => {\n const collector = storage.getStore();\n if (collector && collector.logs.length < ITEM_LIMIT) {\n collector.logs.push({ level, text: cutText(format(...args)) });\n }\n };\n if (!wasPatched) {\n for (const level of LEVELS) {\n const original = console[level].bind(console);\n console[level] = (...args: unknown[]) => {\n (globalThis as Globals)[LOG_SINK]?.(level, args);\n original(...args);\n };\n }\n }\n return async (run) => {\n const collector: Collector = { calls: [], logs: [] };\n const answer = await storage.run(collector, run);\n // A redirect is not an error.\n const redirected = answer.headers.has('x-brumate-redirect');\n const refreshed = answer.headers.get('x-brumate-refresh');\n const record: DevAnswer = {\n reads: refreshed ? refreshed.split(',') : [],\n calls: collector.calls,\n logs: collector.logs,\n };\n if (collector.error && !redirected) {\n record.error = collector.error;\n }\n answer.headers.set(DEV_HEADER, encodeServerRecord(record));\n return answer;\n };\n}\n\n// The browser.\n\n/** What the browser knows of a call when its answer arrives. */\nexport interface CallInput {\n name: string;\n /** The `init` of the `fetch`: its body holds the arguments. */\n init?: RequestInit;\n response: Response;\n /** When `fetch` was called, by `performance.now()`. */\n started: number;\n /** When the headers arrived. */\n arrived: number;\n /** How long the page took to get to the call, such as to load the code and write the arguments. */\n module: number;\n}\n\n/**\n * Makes the record of a call: decodes its arguments and its result, and joins them with the part\n * that the dev server sent. `response` must be a clone, since this reads its body.\n */\nexport async function readCall(input: CallInput): Promise<CallRecord> {\n const { name, init, response, started, arrived } = input;\n const { error, ...server }: Partial<DevAnswer> =\n decodeServerRecord(response.headers.get(DEV_HEADER)) ?? {};\n const took = /brumate;dur=([\\d.]+)/.exec(response.headers.get('server-timing') ?? '');\n const serverTime = took ? Number(took[1]) : 0;\n const record: CallRecord = {\n name,\n args: [],\n timing: {\n module: Math.round(input.module),\n network: Math.max(0, Math.round(arrived - started - serverTime)),\n server: Math.round(serverTime),\n decode: 0,\n },\n ...(server.logs ? { server: server as ServerRecord } : {}),\n ...(error ? { error } : {}),\n };\n const [{ fromJSON }, { callPlugins, serialOptions }, { fromChunkStream }] = await Promise.all([\n import('seroval/read'),\n import('./serial.ts'),\n import('./stream-read.ts'),\n ]);\n // The arguments: seroval JSON, or form data that holds it, or the fields of a form.\n try {\n const body = init?.body;\n if (typeof body === 'string') {\n const args = fromJSON(JSON.parse(body), {\n plugins: callPlugins(),\n ...serialOptions(),\n }) as unknown[];\n record.args = cutValue(args) as unknown[];\n } else if (body instanceof FormData) {\n if (body.has('args')) {\n const args = fromJSON(JSON.parse(String(body.get('args'))), {\n plugins: callPlugins(undefined, body),\n ...serialOptions(),\n }) as unknown[];\n record.args = cutValue(args) as unknown[];\n } else {\n record.args = [cutValue(body)];\n }\n }\n } catch {\n // The arguments cannot be read, such as ones of a plugin that is not loaded: none are shown.\n }\n // The result, or the message of the error that the server answered with.\n const decoding = performance.now();\n try {\n if (response.ok && !response.headers.has('x-brumate-redirect') && response.body) {\n record.result = cutValue(await fromChunkStream(response.body));\n } else if (!response.ok) {\n const text = await response.text();\n let message = text;\n try {\n message = (JSON.parse(text) as { error: string }).error;\n } catch {\n // The body is not the error of a server function.\n }\n record.error ??= { message: cutText(message) };\n }\n } catch (failure) {\n record.error ??= {\n message: cutText(failure instanceof Error ? failure.message : String(failure)),\n };\n }\n record.timing.decode = Math.round(performance.now() - decoding);\n return record;\n}\n"],"mappings":";;AAaA,MAAa,aAAa;;AAG1B,MAAa,aAAa;AAC1B,MAAM,cAAc;AACpB,MAAM,aAAa;AACnB,MAAM,cAAc;;AAEpB,MAAM,eAAe;;AAGrB,MAAM,YAAY,OAAO,IAAI,kBAAkB;AAC/C,MAAM,WAAW,OAAO,IAAI,oBAAoB;AAChD,MAAM,SAAS;CAAC;CAAO;CAAQ;CAAQ;CAAS;AAAO;;AAGvD,SAAgB,QAAQ,MAAc,QAAgB,YAAoB;CACxE,OAAO,KAAK,SAAS,QAAQ,GAAG,KAAK,MAAM,GAAG,KAAK,EAAE,KAAK,KAAK,SAAS,MAAM,UAAU;AAC1F;;;;;AAMA,SAAgB,SACd,OACA,QAAgB,GAChB,uBAAoB,IAAI,IAAY,GAC3B;CACT,QAAQ,OAAO,OAAf;EACE,KAAK,UACH,OAAO,QAAQ,KAAK;EACtB,KAAK,UACH,OAAO,GAAG,MAAM;EAClB,KAAK,UACH,OAAO,MAAM,SAAS;EACxB,KAAK,YACH,OAAO,aAAa,MAAM,QAAQ,YAAY;EAChD,KAAK,UACH;EACF,SACE,OAAO;CACX;CACA,IAAI,UAAU,QAAQ,iBAAiB,MACrC,OAAO;CAET,IAAI,iBAAiB,OACnB,OAAO,QAAQ,IAAI,MAAM,KAAK,IAAI,MAAM,QAAQ,EAAE;CAEpD,IAAI,OAAO,SAAS,eAAe,iBAAiB,MAAM;EACxD,MAAM,OAAQ,MAAwB;EACtC,OAAO,IAAI,SAAS,KAAA,IAAY,SAAS,QAAQ,OAAO,IAAI,MAAM,KAAK,UAAU,MAAM,KAAK;CAC9F;CACA,IAAI,KAAK,IAAI,KAAK,GAChB,OAAO;CAET,IAAI,SAAS,aACX,OAAO,MA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