@runic-artifex/vite-plugin-runic 0.14.0 → 0.15.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/README.md CHANGED
@@ -27,7 +27,7 @@ or later 24.x, or Node 26.
27
27
  same as omitting the option: the development client is injected while serving,
28
28
  and the Runic dock appears when `DevTools()` is registered. `true` also requires
29
29
  `DevTools()`: serving without it fails with
30
- [`RUNICP007`](https://github.com/Runic-Artifex/runic-sdk/blob/v0.14.0/docs/diagnostics.md#runicp007).
30
+ [`RUNICP007`](https://github.com/Runic-Artifex/runic-sdk/blob/v0.15.0/docs/diagnostics.md#runicp007).
31
31
  `false` turns off both the dock and the development client.
32
32
  `maxTimelineEntries` sets how many timeline entries the dock keeps: 200 by
33
33
  default, rounded down and limited to 1 to 500.
@@ -36,7 +36,7 @@ While serving, the plugin adds `virtual:runic/client`, which loads the
36
36
  development client (`@runic-artifex/vite-plugin-runic/client`), to `index.html`.
37
37
  The client has no exports. It shows the page's connection to its .NET host, as
38
38
  `@runic-artifex/views` reports it (`connecting`, `connected`, `reconnecting`,
39
- `lost`), on the dock's **Connection** card from page load, before a View
39
+ `lost`, and `closed` once the application closed the window), on the dock's **Connection** card from page load, before a View
40
40
  connects (with `@runic-artifex/views` 0.11 or later; earlier releases start it
41
41
  when the first View connects), and forwards
42
42
  `@runic-artifex/views` failures to the timeline: the failed route, the
@@ -70,6 +70,35 @@ fields with the text-field binding of your framework package
70
70
  `runic({ staleInputWarning: false })`, or from the page by setting
71
71
  `globalThis[Symbol.for("runic.vite.staleInputWarning")] = false`.
72
72
 
73
+ ### State inspector
74
+
75
+ With `@runic-artifex/views` 0.15 or later the development client also reports
76
+ each open View's state, as the page shows it, and the dock shows it on the
77
+ **Views** card: one card per View with its route, revision and presentation
78
+ epoch, the most recently changed first, and the state as a tree. The client
79
+ sends a View's latest state at most every 250 ms, and the server keeps the 32
80
+ Views that changed last, per page (several windows can share one development
81
+ server), and forgets a View when it closes and a page's Views when the page
82
+ goes away. The state is redacted and bounded like timeline details: a member
83
+ whose name suggests a credential or a path (`password`, `accessToken`,
84
+ `filePath`, …) and a string that looks like a credential or a path read
85
+ `[redacted]`, strings are shortened, long lists end with `… N more`, and deep
86
+ or large states are shown shallower. It is part of `/__runic/state` (`views`)
87
+ and of the copied diagnostic state, which hold no failures.
88
+
89
+ A command that the Bridge answered `superseded` (a
90
+ [command scoped to its page](https://github.com/Runic-Artifex/runic-sdk/blob/v0.15.0/packages/web/vite-plugin-runic/../views/README.md#scoped-commands) called from an earlier page)
91
+ resolves like one that ran, so the page shows nothing. The client reports it
92
+ as a timeline entry (`kind: "command"`, label `<member> superseded`,
93
+ `detail.code: "superseded"` with the route, member, the epoch it was issued for
94
+ and the reply's revision), and the dock lists the latest on the **Superseded
95
+ commands** card. With the Angular CLI, read both from `/__runic/state`.
96
+
97
+ The inspector runs only where the development client does: never in a build.
98
+ `@runic-artifex/views` reports to it only once the client asked for it
99
+ (`runic.views.inspector` in the
100
+ [shared globals](https://github.com/Runic-Artifex/runic-sdk/blob/v0.15.0/specs/application/README.md#shared-globals)).
101
+
73
102
  ## SvelteKit and Angular
74
103
 
75
104
  SvelteKit renders its pages itself and warns about every plugin with a
@@ -163,10 +192,9 @@ times out with `RAPPDEV1007`.
163
192
 
164
193
  `runicDevSessionProxy()` answers the session for the Angular CLI (above).
165
194
  `dotnet runic dev` expects the answer from an Angular frontend whose
166
- `package.json` declares this package. `runicDevSession()` is a Vite plugin
167
- that answers only the session, without the development client; SvelteKit
168
- configurations from before 0.14 use it. It is deprecated in 0.14 and removed
169
- in 0.15: use `runic({ html: false })` instead.
195
+ `package.json` declares this package. `runicDevSession()`, which answered only
196
+ the session, was removed in 0.15: SvelteKit uses `runic({ html: false })`
197
+ (above).
170
198
 
171
199
  The `runic-app` template's SvelteKit and Angular frontends are set up this way.
172
200
 
package/dist/channel.d.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  export declare const diagnosticEvent = "runic:diagnostic";
2
2
  export declare const connectionEvent = "runic:connection";
3
+ /** The state inspector: a View's state, a closed View, or a page that went away (`DevelopmentTimeline.applyView`). */
4
+ export declare const viewEvent = "runic:view";
3
5
  /** The endpoint a client posts `{ "event", "data" }` to, one message per request, answered with 204. */
4
6
  export declare const diagnosticsPath = "/__runic/diagnostics";
5
7
  /**
package/dist/channel.js CHANGED
@@ -4,8 +4,12 @@
4
4
  // the client sends with `import.meta.hot.send`, and the plugin listens on `server.ws`. A client that loads otherwise
5
5
  // (the Angular CLI's development server, which runs no Vite plugins, or an application import of the package) posts
6
6
  // each message to `diagnosticsPath` instead, which `runic()` and `runicDevSessionProxy()` answer.
7
+ //
8
+ // A sanitized View state is at most about 16,000 characters (diagnostics.ts, `sanitizeViewState`).
7
9
  export const diagnosticEvent = "runic:diagnostic";
8
10
  export const connectionEvent = "runic:connection";
11
+ /** The state inspector: a View's state, a closed View, or a page that went away (`DevelopmentTimeline.applyView`). */
12
+ export const viewEvent = "runic:view";
9
13
  /** The endpoint a client posts `{ "event", "data" }` to, one message per request, answered with 204. */
10
14
  export const diagnosticsPath = "/__runic/diagnostics";
11
15
  /**
package/dist/client.js CHANGED
@@ -1,5 +1,5 @@
1
- import { clientOptionsKey, connectionEvent, diagnosticEvent, diagnosticsPath, maximumClientMessageBytes, } from "./channel.js";
2
- import { sanitizeDiagnosticSummary } from "./diagnostics.js";
1
+ import { clientOptionsKey, connectionEvent, diagnosticEvent, diagnosticsPath, maximumClientMessageBytes, viewEvent, } from "./channel.js";
2
+ import { sanitizeDiagnosticSummary, sanitizeViewState } from "./diagnostics.js";
3
3
  import { installStaleInputWarning } from "./stale-input.js";
4
4
  const host = globalThis;
5
5
  const hot = import.meta.hot;
@@ -146,15 +146,96 @@ function connectViewsConnection() {
146
146
  if (typeof connection.start === "function")
147
147
  connection.start();
148
148
  }
149
+ // The state inspector. @runic-artifex/views 0.15 or later reports to this channel once a reader set `requested`
150
+ // (specs/application, "Shared globals"): each route's state as its presentations receive it, a closed route, and a
151
+ // command the producer answered `superseded`. The client sends a route's latest state at most every 250 ms.
152
+ const viewsInspectorKey = Symbol.for("runic.views.inspector");
153
+ const inspectorListenerKey = "runic:inspector-listener";
154
+ const pageHideListenerKey = "runic:page-hide-listener";
155
+ const pageKey = "runic:page";
156
+ const stateInterval = 250;
157
+ // Several windows can share one development server, so the server keeps Views per page.
158
+ const page = typeof data[pageKey] === "string" ? data[pageKey] : (data[pageKey] = randomPage());
159
+ const pendingStates = new Map();
160
+ let stateTimer;
161
+ function randomPage() {
162
+ return `${Date.now().toString(36)}${Math.random().toString(36).slice(2, 10)}`.slice(0, 32);
163
+ }
164
+ function sendStates() {
165
+ stateTimer = undefined;
166
+ for (const event of pendingStates.values()) {
167
+ send(viewEvent, {
168
+ page, route: event.route, revision: event.revision, epoch: event.epoch, presentations: event.presentations,
169
+ // Sanitized here too, so that the state leaves the page bounded and redacted.
170
+ state: sanitizeViewState(event.state),
171
+ });
172
+ }
173
+ pendingStates.clear();
174
+ }
175
+ function reportInspector(event) {
176
+ if (typeof event !== "object" || event === null || typeof event.route !== "string")
177
+ return;
178
+ if (event.kind === "state") {
179
+ pendingStates.set(event.route, event);
180
+ stateTimer ??= setTimeout(sendStates, stateInterval);
181
+ }
182
+ else if (event.kind === "closed") {
183
+ pendingStates.delete(event.route);
184
+ send(viewEvent, { page, route: event.route, closed: true });
185
+ }
186
+ else if (event.kind === "superseded") {
187
+ // The call resolved like one that ran, so only the timeline shows that nothing ran.
188
+ sendDiagnostic({
189
+ source: "views",
190
+ kind: "command",
191
+ label: `${String(event.member).slice(0, 80)} superseded`,
192
+ detail: {
193
+ code: "superseded", route: event.route.slice(0, 120), member: String(event.member).slice(0, 80),
194
+ ...(typeof event.epoch === "number" ? { epoch: event.epoch } : {}),
195
+ ...(typeof event.revision === "number" ? { revision: event.revision } : {}),
196
+ },
197
+ });
198
+ }
199
+ }
200
+ function viewsInspector() {
201
+ const channels = host;
202
+ return channels[viewsInspectorKey] ??= { listeners: new Set() };
203
+ }
204
+ function pageHidden() {
205
+ pendingStates.clear();
206
+ send(viewEvent, { page, closed: true });
207
+ }
208
+ function connectViewsInspector() {
209
+ const inspector = viewsInspector();
210
+ const previous = data[inspectorListenerKey];
211
+ if (previous)
212
+ inspector.listeners.delete(previous);
213
+ inspector.listeners.add(reportInspector);
214
+ data[inspectorListenerKey] = reportInspector;
215
+ inspector.requested = true;
216
+ // The page's Views go away with it; the server also keeps only the 32 most recent.
217
+ const previousHide = data[pageHideListenerKey];
218
+ if (previousHide)
219
+ host.removeEventListener?.("pagehide", previousHide);
220
+ host.addEventListener?.("pagehide", pageHidden);
221
+ data[pageHideListenerKey] = pageHidden;
222
+ }
149
223
  // Removes this copy's listeners once the HTTP channel has no server to report to.
150
224
  function close() {
151
225
  channel = "closed";
152
226
  pending.length = 0;
153
227
  viewsDiagnostics().delete(reportViewsDiagnostic);
154
228
  viewsConnection().listeners.delete(reportConnection);
229
+ viewsInspector().listeners.delete(reportInspector);
230
+ host.removeEventListener?.("pagehide", pageHidden);
231
+ if (stateTimer !== undefined)
232
+ clearTimeout(stateTimer);
233
+ stateTimer = undefined;
234
+ pendingStates.clear();
155
235
  }
156
236
  connectViewsDiagnostics();
157
237
  connectViewsConnection();
238
+ connectViewsInspector();
158
239
  // Vite's HMR context shows that a development server serves the page: install the warning now. Without it
159
240
  // (a production build that kept the client), the HTTP channel installs it once the server answers. Installs once
160
241
  // per page; HMR re-evaluation leaves it in place.
@@ -1,5 +1,5 @@
1
1
  import type { IncomingMessage, ServerResponse } from "node:http";
2
- import type { Plugin, ProxyOptions } from "vite";
2
+ import type { ProxyOptions } from "vite";
3
3
  import type { RunicDevelopmentState, RunicTimelineEntry } from "./timeline.js";
4
4
  export declare const devSessionVariable = "RUNIC_APPLICATION_DEV_SESSION";
5
5
  export declare const devSessionHeader = "X-Runic-Dev-Session";
@@ -13,15 +13,6 @@ export declare function answerState(response: ServerResponse, state: RunicDevelo
13
13
  * of at most `maximumClientMessageBytes`. Calls `deliver` with an accepted message and answers 204.
14
14
  */
15
15
  export declare function answerClientMessage(request: IncomingMessage, response: ServerResponse, deliver: (event: string, data: unknown) => void): Promise<void>;
16
- /**
17
- * A Vite plugin that only answers `/__runic/state` with the `dotnet runic dev` session. Without `dotnet runic dev`
18
- * the plugin does nothing.
19
- *
20
- * @deprecated Use `runic({ html: false })`, which answers the session too and adds the development client (load it
21
- * with `import "@runic-artifex/vite-plugin-runic/client"` from SvelteKit's `src/hooks.client.ts`). `runicDevSession`
22
- * is removed in 0.15.
23
- */
24
- export declare function runicDevSession(): Plugin;
25
16
  export interface RunicDevSessionProxyOptions {
26
17
  /** How many timeline entries `/__runic/state` keeps: 200 by default, rounded down and limited to 1 to 500. */
27
18
  readonly maxTimelineEntries?: number;
@@ -37,7 +28,8 @@ export interface RunicDevSessionProxyOptions {
37
28
  *
38
29
  * - `/__runic/state` with the path-free development state, and under `dotnet runic dev` with its session;
39
30
  * - `/__runic/diagnostics`, which the development client (`@runic-artifex/vite-plugin-runic/client`) posts the
40
- * page's Views diagnostics and connection state to. The timeline is bounded, and failures go to the terminal.
31
+ * page's Views diagnostics, connection state and View states to. The timeline is bounded, and failures go to the
32
+ * terminal.
41
33
  */
42
34
  export declare function runicDevSessionProxy(options?: RunicDevSessionProxyOptions): Record<string, ProxyOptions>;
43
35
  /** A failure for the terminal: the entry's source and label, then the exception type, message and stack. */
@@ -1,4 +1,4 @@
1
- import { connectionEvent, diagnosticEvent, diagnosticsPath, maximumClientMessageBytes } from "./channel.js";
1
+ import { connectionEvent, diagnosticEvent, diagnosticsPath, maximumClientMessageBytes, viewEvent } from "./channel.js";
2
2
  import { createDevelopmentTimeline, initialDevelopmentState, timelineLimit, withoutFailures } from "./timeline.js";
3
3
  // `dotnet runic dev` gives the development server process a random session value and accepts the server as ready
4
4
  // only when /__runic/state answers with it, so another process that takes the port first is not mistaken for this
@@ -10,12 +10,6 @@ export const statePath = "/__runic/state";
10
10
  export function devSessionValue(value) {
11
11
  return value !== undefined && /^[0-9a-f]{32,128}$/.test(value) ? value : undefined;
12
12
  }
13
- function answerSession(response, session) {
14
- response.statusCode = 204;
15
- response.setHeader("Cache-Control", "no-store");
16
- response.setHeader(devSessionHeader, session);
17
- response.end();
18
- }
19
13
  /** Answers `/__runic/state` with the path-free state, and with the `dotnet runic dev` session when there is one. */
20
14
  export function answerState(response, state, session) {
21
15
  response.statusCode = 200;
@@ -90,7 +84,7 @@ export async function answerClientMessage(request, response, deliver) {
90
84
  if (typeof message !== "object" || message === null || Array.isArray(message))
91
85
  return answerStatus(response, 400);
92
86
  const { event, data } = message;
93
- if (event !== diagnosticEvent && event !== connectionEvent)
87
+ if (event !== diagnosticEvent && event !== connectionEvent && event !== viewEvent)
94
88
  return answerStatus(response, 400);
95
89
  deliver(event, data);
96
90
  answerStatus(response, 204);
@@ -116,32 +110,14 @@ function readBody(request) {
116
110
  request.on("error", () => resolve(undefined));
117
111
  });
118
112
  }
119
- /**
120
- * A Vite plugin that only answers `/__runic/state` with the `dotnet runic dev` session. Without `dotnet runic dev`
121
- * the plugin does nothing.
122
- *
123
- * @deprecated Use `runic({ html: false })`, which answers the session too and adds the development client (load it
124
- * with `import "@runic-artifex/vite-plugin-runic/client"` from SvelteKit's `src/hooks.client.ts`). `runicDevSession`
125
- * is removed in 0.15.
126
- */
127
- export function runicDevSession() {
128
- return {
129
- name: "runic:dev-session",
130
- configureServer(server) {
131
- const session = devSessionValue(process.env[devSessionVariable]);
132
- if (session === undefined)
133
- return;
134
- server.middlewares.use(statePath, (_request, response) => answerSession(response, session));
135
- },
136
- };
137
- }
138
113
  /**
139
114
  * Vite proxy entries for a development server that takes a Vite proxy configuration but no Vite plugins: the
140
115
  * Angular CLI's `proxyConfig`. Spread the result into the proxy configuration. The entries never proxy; they answer:
141
116
  *
142
117
  * - `/__runic/state` with the path-free development state, and under `dotnet runic dev` with its session;
143
118
  * - `/__runic/diagnostics`, which the development client (`@runic-artifex/vite-plugin-runic/client`) posts the
144
- * page's Views diagnostics and connection state to. The timeline is bounded, and failures go to the terminal.
119
+ * page's Views diagnostics, connection state and View states to. The timeline is bounded, and failures go to the
120
+ * terminal.
145
121
  */
146
122
  export function runicDevSessionProxy(options = {}) {
147
123
  if (options.printFailures !== undefined && typeof options.printFailures !== "boolean") {
@@ -155,6 +131,10 @@ export function runicDevSessionProxy(options = {}) {
155
131
  timeline.applyConnection(data);
156
132
  return;
157
133
  }
134
+ if (event === viewEvent) {
135
+ timeline.applyView(data);
136
+ return;
137
+ }
158
138
  const entry = timeline.appendDiagnostic(data);
159
139
  if (entry?.failure && printFailures)
160
140
  console.warn(formatFailure(entry));
@@ -41,3 +41,15 @@ export interface RunicDiagnosticSummary {
41
41
  */
42
42
  export declare function sanitizeDiagnosticSummary(candidate: unknown, forcedSource?: RunicDiagnosticSource): RunicDiagnosticSummary | undefined;
43
43
  export declare function diagnosticSource(value: unknown): RunicDiagnosticSource | undefined;
44
+ /** A View state value as the state inspector shows it: JSON, bounded and redacted. */
45
+ export type RunicViewStateValue = string | number | boolean | null | readonly RunicViewStateValue[] | {
46
+ readonly [member: string]: RunicViewStateValue;
47
+ };
48
+ /**
49
+ * A View's state for the state inspector, under the rules of timeline details: a member whose name suggests a
50
+ * credential or a path, and a string that looks like a credential or a path, is `[redacted]`; a member whose name
51
+ * looks like a path is left out. Strings are shortened,
52
+ * objects and arrays end with a `…` entry that counts what was left out, and nesting stops at `…` once the state is
53
+ * deep. Functions, symbols and `undefined` are left out; other non-JSON values are their type.
54
+ */
55
+ export declare function sanitizeViewState(value: unknown): RunicViewStateValue;
@@ -140,6 +140,90 @@ function sanitizeText(value, maximumLength) {
140
140
  return undefined;
141
141
  return sensitiveContent.test(value) || pathLikeContent.test(value) ? redacted : value;
142
142
  }
143
+ // The state inspector's bounds: a View's sanitized state is at most about 16,000 characters of JSON. Larger states
144
+ // are shown shallower and with fewer entries.
145
+ const viewStateBudgets = [
146
+ { depth: 6, entries: 50, text: 200 },
147
+ { depth: 4, entries: 20, text: 96 },
148
+ { depth: 2, entries: 10, text: 48 },
149
+ ];
150
+ const maximumViewStateLength = 16_000;
151
+ const maximumViewStateKeyLength = 80;
152
+ const tooLarge = "[too large]";
153
+ /**
154
+ * A View's state for the state inspector, under the rules of timeline details: a member whose name suggests a
155
+ * credential or a path, and a string that looks like a credential or a path, is `[redacted]`; a member whose name
156
+ * looks like a path is left out. Strings are shortened,
157
+ * objects and arrays end with a `…` entry that counts what was left out, and nesting stops at `…` once the state is
158
+ * deep. Functions, symbols and `undefined` are left out; other non-JSON values are their type.
159
+ */
160
+ export function sanitizeViewState(value) {
161
+ for (const budget of viewStateBudgets) {
162
+ const sanitized = viewStateValue(value, budget, 0, new Set());
163
+ if (JSON.stringify(sanitized).length <= maximumViewStateLength)
164
+ return sanitized;
165
+ }
166
+ return tooLarge;
167
+ }
168
+ function viewStateValue(value, budget, depth, seen) {
169
+ if (value === null || typeof value === "boolean")
170
+ return value;
171
+ if (typeof value === "number")
172
+ return Number.isFinite(value) ? value : String(value);
173
+ if (typeof value === "bigint")
174
+ return `${value}n`;
175
+ if (typeof value === "string") {
176
+ if (sensitiveContent.test(value) || pathLikeContent.test(value))
177
+ return redacted;
178
+ const text = value.replace(failureControlCharacters, "");
179
+ return text.length > budget.text ? `${text.slice(0, budget.text - 1)}…` : text;
180
+ }
181
+ if (typeof value !== "object")
182
+ return `[${typeof value}]`;
183
+ if (depth >= budget.depth)
184
+ return "…";
185
+ if (seen.has(value))
186
+ return "[circular]";
187
+ seen.add(value);
188
+ try {
189
+ if (Array.isArray(value)) {
190
+ const items = value.slice(0, budget.entries).map((item) => viewStateValue(item, budget, depth + 1, seen));
191
+ if (value.length > budget.entries)
192
+ items.push(`… ${value.length - budget.entries} more`);
193
+ return items;
194
+ }
195
+ if (value instanceof Date)
196
+ return Number.isNaN(value.getTime()) ? "Invalid Date" : value.toISOString();
197
+ if (value instanceof Map || value instanceof Set)
198
+ return `[${value.constructor.name}(${value.size})]`;
199
+ const output = {};
200
+ let count = 0;
201
+ let omitted = 0;
202
+ for (const key of Object.keys(value)) {
203
+ const member = value[key];
204
+ if (member === undefined || typeof member === "function" || typeof member === "symbol")
205
+ continue;
206
+ if (count >= budget.entries) {
207
+ omitted += 1;
208
+ continue;
209
+ }
210
+ // A key that looks like a path is one, so it is left out like a detail's.
211
+ if (key.length > maximumViewStateKeyLength || controlCharacters.test(key) || pathLikeContent.test(key) ||
212
+ key === "__proto__" || key === "constructor" || key === "prototype") {
213
+ omitted += 1;
214
+ continue;
215
+ }
216
+ output[key] = sensitiveKey.test(key) ? redacted : viewStateValue(member, budget, depth + 1, seen);
217
+ count += 1;
218
+ }
219
+ if (omitted > 0)
220
+ output["…"] = `${omitted} more`;
221
+ return output;
222
+ }
223
+ finally {
224
+ seen.delete(value);
225
+ }
226
+ }
143
227
  function isRecord(value) {
144
228
  return typeof value === "object" && value !== null && !Array.isArray(value);
145
229
  }
package/dist/index.d.ts CHANGED
@@ -1,9 +1,9 @@
1
1
  import type { Plugin } from "vite";
2
2
  import type { RunicDiagnosticEntry } from "./diagnostics.js";
3
- export { runicDevSession, runicDevSessionProxy } from "./dev-session.js";
3
+ export { runicDevSessionProxy } from "./dev-session.js";
4
4
  export type { RunicDevSessionProxyOptions } from "./dev-session.js";
5
- export type { RunicDevelopmentState } from "./timeline.js";
6
- export type { RunicDiagnosticDetail, RunicDiagnosticDetailValue, RunicDiagnosticFailure, RunicDiagnosticEntry, RunicDiagnosticSource, RunicTraceKind, } from "./diagnostics.js";
5
+ export type { RunicDevelopmentState, RunicViewSnapshot } from "./timeline.js";
6
+ export type { RunicDiagnosticDetail, RunicDiagnosticDetailValue, RunicDiagnosticFailure, RunicDiagnosticEntry, RunicDiagnosticSource, RunicTraceKind, RunicViewStateValue, } from "./diagnostics.js";
7
7
  /** The API another Vite plugin reaches through `plugin.api`, Vite's inter-plugin convention. */
8
8
  export interface RunicVitePluginApi {
9
9
  /** Adds a display-safe entry to the DevTools timeline, for example from a companion plugin. */
package/dist/index.js CHANGED
@@ -1,10 +1,10 @@
1
1
  /// <reference types="@vitejs/devtools-kit" />
2
2
  import { isAbsolute, relative } from "node:path";
3
3
  import { rewriteHostScripts, webRootPrefix } from "./host-scripts.js";
4
- import { clientOptionsKey, connectionEvent, diagnosticEvent, diagnosticsPath } from "./channel.js";
4
+ import { clientOptionsKey, connectionEvent, diagnosticEvent, diagnosticsPath, viewEvent } from "./channel.js";
5
5
  import { answerClientMessage, answerState, devSessionValue, devSessionVariable, statePath } from "./dev-session.js";
6
6
  import { createDevelopmentTimeline, initialDevelopmentState, timelineLimit, withoutFailures } from "./timeline.js";
7
- export { runicDevSession, runicDevSessionProxy } from "./dev-session.js";
7
+ export { runicDevSessionProxy } from "./dev-session.js";
8
8
  const virtualClientId = "virtual:runic/client";
9
9
  const resolvedVirtualClientId = `\0${virtualClientId}`;
10
10
  const clientPackageId = "@runic-artifex/vite-plugin-runic/client";
@@ -45,6 +45,8 @@ export function runic(options = {}) {
45
45
  timeline.applyConnection(data);
46
46
  else if (event === diagnosticEvent)
47
47
  timeline.appendDiagnostic(data);
48
+ else if (event === viewEvent)
49
+ timeline.applyView(data);
48
50
  };
49
51
  const command = () => timeline.state.vite.command;
50
52
  const transformIndexHtml = {
@@ -132,6 +134,7 @@ export function runic(options = {}) {
132
134
  server = viteServer;
133
135
  viteServer.ws.on(connectionEvent, (payload) => deliver(connectionEvent, payload));
134
136
  viteServer.ws.on(diagnosticEvent, (payload) => deliver(diagnosticEvent, payload));
137
+ viteServer.ws.on(viewEvent, (payload) => deliver(viewEvent, payload));
135
138
  const devSession = devSessionValue(process.env[devSessionVariable]);
136
139
  viteServer.middlewares.use(statePath, (_request, response) => {
137
140
  answerState(response, timeline.state, devSession);
@@ -223,7 +226,7 @@ function createDevtoolsSpec(current) {
223
226
  root: {
224
227
  type: "Stack",
225
228
  props: { direction: "column", gap: 12 },
226
- children: ["heading", "connection", "contract", "failure", "timeline"],
229
+ children: ["heading", "connection", "contract", "views", "superseded", "failure", "timeline"],
227
230
  },
228
231
  heading: { type: "Text", props: { text: "Runic", variant: "heading" } },
229
232
  ...section("connection", "Connection", {
@@ -234,6 +237,8 @@ function createDevtoolsSpec(current) {
234
237
  Version: current.contract.version || "not reported",
235
238
  Fingerprint: current.contract.fingerprint || "not reported",
236
239
  }),
240
+ ...viewsSection(current),
241
+ ...section("superseded", "Superseded commands", supersededCommands(current)),
237
242
  ...section("failure", "Last failure", lastFailure(current)),
238
243
  ...section("timeline", "Recent timeline", current.timeline.length === 0
239
244
  ? { Events: "none" }
@@ -243,6 +248,39 @@ function createDevtoolsSpec(current) {
243
248
  },
244
249
  };
245
250
  }
251
+ // The state inspector: a card per open View with its state as a tree, the most recently changed first.
252
+ function viewsSection(current) {
253
+ const pages = new Set(current.views.map((view) => view.page));
254
+ const cards = current.views.map((view, index) => {
255
+ const revision = view.revision === undefined ? "" : ` · revision ${view.revision}`;
256
+ const epoch = view.epoch === undefined ? "" : ` · epoch ${view.epoch}`;
257
+ // Several windows can show the same route; the page tells them apart.
258
+ const page = pages.size > 1 ? ` · page ${view.page.slice(0, 6)}` : "";
259
+ return [`views-${index}`, {
260
+ card: { type: "Card", props: { title: `${view.route}${revision}${epoch}${page}` }, children: [`views-${index}-state`] },
261
+ state: { type: "Tree", props: { data: view.state, defaultExpanded: index === 0 } },
262
+ }];
263
+ });
264
+ return {
265
+ views: {
266
+ type: "Card",
267
+ props: { title: "Views" },
268
+ children: cards.length === 0 ? ["views-none"] : cards.map(([id]) => id),
269
+ },
270
+ ...(cards.length === 0 ? { "views-none": { type: "Text", props: { text: "No View connected" } } } : {}),
271
+ ...Object.fromEntries(cards.flatMap(([id, { card, state }]) => [[id, card], [`${id}-state`, state]])),
272
+ };
273
+ }
274
+ // Command replies the producer answered `superseded` (presentation-epoch/1): the call resolved without running.
275
+ function supersededCommands(current) {
276
+ const entries = current.timeline.filter((entry) => entry.kind === "command" && entry.detail.code === "superseded");
277
+ if (entries.length === 0)
278
+ return { Commands: "none" };
279
+ return Object.fromEntries(entries.slice(-12).reverse().map((entry) => [
280
+ `${entry.id} · ${entry.timestamp}`,
281
+ `${entry.detail.route ?? "?"}.${entry.detail.member ?? "?"} from epoch ${entry.detail.epoch ?? "?"}`,
282
+ ]));
283
+ }
246
284
  function lastFailure(current) {
247
285
  const entry = [...current.timeline].reverse().find((candidate) => candidate.failure !== undefined);
248
286
  if (!entry?.failure)
@@ -1,4 +1,4 @@
1
- import type { RunicDiagnosticDetail, RunicDiagnosticEntry, RunicDiagnosticFailure, RunicDiagnosticSource } from "./diagnostics.js";
1
+ import type { RunicDiagnosticDetail, RunicDiagnosticEntry, RunicDiagnosticFailure, RunicDiagnosticSource, RunicViewStateValue } from "./diagnostics.js";
2
2
  export interface RunicDevelopmentState {
3
3
  readonly contract: Readonly<{
4
4
  identity: string;
@@ -15,10 +15,31 @@ export interface RunicDevelopmentState {
15
15
  * (`BridgeConnectionState`), or `unknown` until a View connects.
16
16
  */
17
17
  readonly connection: Readonly<{
18
- state: "connecting" | "connected" | "reconnecting" | "lost" | "unknown";
18
+ state: "connecting" | "connected" | "reconnecting" | "lost" | "closed" | "unknown";
19
19
  }>;
20
+ /**
21
+ * The state inspector: each open View's current state, as the development client last reported it, the most
22
+ * recently changed first. Command replies that the producer answered `superseded` are timeline entries
23
+ * (`kind: "command"`, `detail.code: "superseded"`).
24
+ */
25
+ readonly views: readonly RunicViewSnapshot[];
20
26
  readonly timeline: readonly RunicTimelineEntry[];
21
27
  }
28
+ /** One View in the state inspector. */
29
+ export interface RunicViewSnapshot {
30
+ /** The page the View is open in: a random identifier per page load, as several windows share one server. */
31
+ readonly page: string;
32
+ /** The View's route, such as `editor`. */
33
+ readonly route: string;
34
+ /** The revision of `state`, and its presentation epoch on a connection with `presentation-epoch/1`. */
35
+ readonly revision?: number;
36
+ readonly epoch?: number;
37
+ /** How many presentations of the page show the route. */
38
+ readonly presentations: number;
39
+ readonly updatedAt: string;
40
+ /** The state the page shows, bounded and redacted like timeline details. */
41
+ readonly state: RunicViewStateValue;
42
+ }
22
43
  export type RunicTimelineEntry = Readonly<Required<Pick<RunicDiagnosticEntry, "id" | "timestamp" | "kind" | "label">> & {
23
44
  source?: RunicDiagnosticSource;
24
45
  detail: RunicDiagnosticDetail;
@@ -32,6 +53,12 @@ export interface DevelopmentTimeline {
32
53
  appendDiagnostic(candidate: unknown, defaultSource?: RunicDiagnosticSource): RunicTimelineEntry | undefined;
33
54
  /** Applies a `{ state }` connection report; returns whether the state changed. */
34
55
  applyConnection(candidate: unknown): boolean;
56
+ /**
57
+ * Applies a state inspector report: `{ page, route, revision?, epoch?, presentations, state }` for a View's state,
58
+ * `{ page, route, closed: true }` for a closed View, `{ page, closed: true }` for a page that went away. Returns
59
+ * whether the report was valid.
60
+ */
61
+ applyView(candidate: unknown): boolean;
35
62
  }
36
63
  export declare function createDevelopmentTimeline(initial: RunicDevelopmentState, maxTimelineEntries: number, changed: (state: RunicDevelopmentState) => void): DevelopmentTimeline;
37
64
  export declare function initialDevelopmentState(contract: Readonly<{
package/dist/timeline.js CHANGED
@@ -1,6 +1,8 @@
1
- import { sanitizeDiagnosticSummary } from "./diagnostics.js";
1
+ import { sanitizeDiagnosticSummary, sanitizeViewState } from "./diagnostics.js";
2
2
  const defaultTimelineLimit = 200;
3
3
  const maximumTimelineLimit = 500;
4
+ // The state inspector keeps the Views that changed most recently, over every page of the server.
5
+ const maximumInspectedViews = 32;
4
6
  export function createDevelopmentTimeline(initial, maxTimelineEntries, changed) {
5
7
  let state = initial;
6
8
  let nextSequence = 1;
@@ -29,8 +31,48 @@ export function createDevelopmentTimeline(initial, maxTimelineEntries, changed)
29
31
  changed(state);
30
32
  return true;
31
33
  },
34
+ applyView(candidate) {
35
+ if (!isRecord(candidate) || typeof candidate.page !== "string" || !pagePattern.test(candidate.page))
36
+ return false;
37
+ const page = candidate.page;
38
+ const route = typeof candidate.route === "string" && routePattern.test(candidate.route) ? candidate.route : undefined;
39
+ // An invalid route never stands for the whole page.
40
+ if (candidate.route !== undefined && route === undefined)
41
+ return false;
42
+ if (candidate.closed === true) {
43
+ const views = state.views.filter((view) => view.page !== page || (route !== undefined && view.route !== route));
44
+ if (views.length !== state.views.length) {
45
+ state = { ...state, views };
46
+ changed(state);
47
+ }
48
+ return true;
49
+ }
50
+ if (route === undefined || !Object.hasOwn(candidate, "state"))
51
+ return false;
52
+ const revision = counter(candidate.revision);
53
+ const epoch = counter(candidate.epoch);
54
+ const snapshot = {
55
+ page,
56
+ route,
57
+ ...(revision === undefined ? {} : { revision }),
58
+ ...(epoch === undefined ? {} : { epoch }),
59
+ presentations: counter(candidate.presentations) ?? 0,
60
+ updatedAt: new Date().toISOString(),
61
+ state: sanitizeViewState(candidate.state),
62
+ };
63
+ const others = state.views.filter((view) => view.page !== page || view.route !== route);
64
+ state = { ...state, views: [snapshot, ...others].slice(0, maximumInspectedViews) };
65
+ changed(state);
66
+ return true;
67
+ },
32
68
  };
33
69
  }
70
+ // The development client's page identifier, and a route name (specs/application, "Route names").
71
+ const pagePattern = /^[a-z0-9]{1,32}$/u;
72
+ const routePattern = /^[A-Za-z0-9_.-]{1,128}$/u;
73
+ function counter(value) {
74
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : undefined;
75
+ }
34
76
  export function initialDevelopmentState(contract, vite = { command: "serve", mode: "development", root: "" }) {
35
77
  return {
36
78
  contract: {
@@ -40,6 +82,7 @@ export function initialDevelopmentState(contract, vite = { command: "serve", mod
40
82
  },
41
83
  vite,
42
84
  connection: { state: "unknown" },
85
+ views: [],
43
86
  timeline: [],
44
87
  };
45
88
  }
@@ -57,7 +100,7 @@ export function timelineLimit(value) {
57
100
  return Math.min(maximumTimelineLimit, Math.max(1, Math.floor(value)));
58
101
  }
59
102
  function connectionState(value) {
60
- return value === "connecting" || value === "connected" || value === "reconnecting" || value === "lost"
103
+ return value === "connecting" || value === "connected" || value === "reconnecting" || value === "lost" || value === "closed"
61
104
  ? value
62
105
  : "unknown";
63
106
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@runic-artifex/vite-plugin-runic",
3
- "version": "0.14.0",
3
+ "version": "0.15.0",
4
4
  "description": "Vite 8 development and DevTools integration for Runic applications",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -61,7 +61,7 @@
61
61
  "url": "git+https://github.com/Runic-Artifex/runic-sdk.git",
62
62
  "directory": "packages/web/vite-plugin-runic"
63
63
  },
64
- "homepage": "https://github.com/Runic-Artifex/runic-sdk/tree/v0.14.0/packages/web/vite-plugin-runic#readme",
64
+ "homepage": "https://github.com/Runic-Artifex/runic-sdk/tree/v0.15.0/packages/web/vite-plugin-runic#readme",
65
65
  "bugs": {
66
66
  "url": "https://github.com/Runic-Artifex/runic-sdk/issues"
67
67
  },
@@ -72,5 +72,5 @@
72
72
  "vite-plugin",
73
73
  "devtools"
74
74
  ],
75
- "gitHead": "11dc038ea80315c4d2b7e15cbd03dfe175ed6124"
75
+ "gitHead": "c94bda07cf363bad056eda86ae77c514b66e61dd"
76
76
  }