@runic-artifex/vite-plugin-runic 0.12.1 → 0.14.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/index.d.ts CHANGED
@@ -1,6 +1,8 @@
1
1
  import type { Plugin } from "vite";
2
- import type { RunicDiagnosticEntry, RunicDiagnosticDetail, RunicDiagnosticFailure, RunicDiagnosticSource } from "./diagnostics.js";
2
+ import type { RunicDiagnosticEntry } from "./diagnostics.js";
3
3
  export { runicDevSession, runicDevSessionProxy } from "./dev-session.js";
4
+ export type { RunicDevSessionProxyOptions } from "./dev-session.js";
5
+ export type { RunicDevelopmentState } from "./timeline.js";
4
6
  export type { RunicDiagnosticDetail, RunicDiagnosticDetailValue, RunicDiagnosticFailure, RunicDiagnosticEntry, RunicDiagnosticSource, RunicTraceKind, } from "./diagnostics.js";
5
7
  /** The API another Vite plugin reaches through `plugin.api`, Vite's inter-plugin convention. */
6
8
  export interface RunicVitePluginApi {
@@ -23,34 +25,23 @@ export interface RunicViteOptions {
23
25
  */
24
26
  readonly devtools?: boolean | "auto";
25
27
  readonly maxTimelineEntries?: number;
28
+ /**
29
+ * `false` turns off the development client's `stale-input` warning: script that sets a
30
+ * focused text field to a value from before the user's last edit while a Bridge request
31
+ * is in flight. Defaults to `true`.
32
+ */
33
+ readonly staleInputWarning?: boolean;
34
+ /**
35
+ * `false` leaves HTML alone: the plugin has no `transformIndexHtml` hook, which SvelteKit warns about, injects
36
+ * neither the development client nor the Desktop bootstrap, and does not rewrite host scripts. The page loads the
37
+ * client itself with `import "@runic-artifex/vite-plugin-runic/client"`, which the plugin serves while serving and
38
+ * replaces with an empty module in the build. Cannot be combined with `desktop`. Defaults to `true`.
39
+ */
40
+ readonly html?: boolean;
26
41
  /** Injects the Runic Desktop bootstrap without taking ownership of Vite or HMR. */
27
42
  readonly desktop?: boolean | Readonly<{
28
43
  /** Absolute development bootstrap URL; production uses the surface-relative default. */
29
44
  bootstrapUrl?: string;
30
45
  }>;
31
46
  }
32
- export interface RunicDevelopmentState {
33
- readonly contract: Readonly<{
34
- identity: string;
35
- version: string;
36
- fingerprint: string;
37
- }>;
38
- readonly vite: Readonly<{
39
- command: string;
40
- mode: string;
41
- root: string;
42
- }>;
43
- /**
44
- * The page's connection to its .NET host, as `@runic-artifex/views` reports it
45
- * (`BridgeConnectionState`), or `unknown` until a View connects.
46
- */
47
- readonly connection: Readonly<{
48
- state: "connecting" | "connected" | "reconnecting" | "lost" | "unknown";
49
- }>;
50
- readonly timeline: readonly Readonly<Required<Pick<RunicDiagnosticEntry, "id" | "timestamp" | "kind" | "label">> & {
51
- source?: RunicDiagnosticSource;
52
- detail: RunicDiagnosticDetail;
53
- failure?: RunicDiagnosticFailure;
54
- }>[];
55
- }
56
47
  export declare function runic(options?: RunicViteOptions): RunicVitePlugin;
package/dist/index.js CHANGED
@@ -1,55 +1,79 @@
1
1
  /// <reference types="@vitejs/devtools-kit" />
2
2
  import { isAbsolute, relative } from "node:path";
3
- import { sanitizeDiagnosticSummary } from "./diagnostics.js";
4
3
  import { rewriteHostScripts, webRootPrefix } from "./host-scripts.js";
5
- import { devSessionHeader, devSessionValue, devSessionVariable } from "./dev-session.js";
4
+ import { clientOptionsKey, connectionEvent, diagnosticEvent, diagnosticsPath } from "./channel.js";
5
+ import { answerClientMessage, answerState, devSessionValue, devSessionVariable, statePath } from "./dev-session.js";
6
+ import { createDevelopmentTimeline, initialDevelopmentState, timelineLimit, withoutFailures } from "./timeline.js";
6
7
  export { runicDevSession, runicDevSessionProxy } from "./dev-session.js";
7
8
  const virtualClientId = "virtual:runic/client";
8
9
  const resolvedVirtualClientId = `\0${virtualClientId}`;
9
10
  const clientPackageId = "@runic-artifex/vite-plugin-runic/client";
11
+ // Sets the client's options (the HMR channel, the `stale-input` warning) on `globalThis`. A separate module, because
12
+ // the import of the client is hoisted above any statement in the virtual client module.
13
+ const clientOptionsId = "virtual:runic/client-options";
14
+ const resolvedClientOptionsId = `\0${clientOptionsId}`;
15
+ // What an import of the client resolves to where it must not run: the build, the server, `devtools: false`.
16
+ const resolvedEmptyClientId = "\0virtual:runic/client-disabled";
10
17
  const stateEvent = "runic:state";
11
- const diagnosticEvent = "runic:diagnostic";
12
- const connectionEvent = "runic:connection";
13
18
  const stateKey = "runic:state";
14
- const defaultTimelineLimit = 200;
15
- const maximumTimelineLimit = 500;
16
19
  export function runic(options = {}) {
17
20
  const maxTimelineEntries = timelineLimit(options.maxTimelineEntries);
21
+ if (options.staleInputWarning !== undefined && typeof options.staleInputWarning !== "boolean") {
22
+ throw new TypeError("staleInputWarning must be true or false.");
23
+ }
24
+ if (options.html !== undefined && typeof options.html !== "boolean") {
25
+ throw new TypeError("html must be true or false.");
26
+ }
27
+ const html = options.html !== false;
28
+ const client = options.devtools !== false;
18
29
  let server;
19
30
  let sharedState;
20
31
  let jsonRenderer;
21
- let state = initialState(options);
22
- let nextDiagnosticSequence = 1;
23
32
  let resolvedRoot = process.cwd();
24
33
  let base = "/";
25
34
  const desktopBootstrapUrl = resolveDesktopBootstrapUrl(options.desktop);
26
- const publish = () => {
35
+ if (!html && desktopBootstrapUrl !== undefined) {
36
+ throw new TypeError("desktop requires html: true: the Desktop bootstrap is a script tag the plugin adds to the HTML.");
37
+ }
38
+ const timeline = createDevelopmentTimeline(initialDevelopmentState(options.contract), maxTimelineEntries, (state) => {
27
39
  sharedState?.mutate((draft) => Object.assign(draft, structuredClone(state)));
28
40
  void jsonRenderer?.updateSpec(createDevtoolsSpec(state));
29
41
  server?.ws.send({ type: "custom", event: stateEvent, data: state });
42
+ });
43
+ const deliver = (event, data) => {
44
+ if (event === connectionEvent)
45
+ timeline.applyConnection(data);
46
+ else if (event === diagnosticEvent)
47
+ timeline.appendDiagnostic(data);
30
48
  };
31
- const applyConnection = (candidate) => {
32
- const next = connectionState(isRecord(candidate) ? candidate.state : undefined);
33
- if (next === state.connection.state)
34
- return;
35
- state = { ...state, connection: { state: next } };
36
- publish();
37
- };
38
- const appendDiagnostic = (candidate, defaultSource) => {
39
- const summary = sanitizeDiagnosticSummary(candidate, defaultSource);
40
- if (!summary)
41
- return;
42
- const entry = {
43
- ...summary,
44
- id: `diagnostic-${nextDiagnosticSequence}`,
45
- timestamp: new Date().toISOString(),
46
- };
47
- nextDiagnosticSequence += 1;
48
- state = {
49
- ...state,
50
- timeline: [...state.timeline, entry].slice(-maxTimelineEntries),
51
- };
52
- publish();
49
+ const command = () => timeline.state.vite.command;
50
+ const transformIndexHtml = {
51
+ order: "post",
52
+ handler: (document, context) => {
53
+ const prefix = webRootPrefix(context.path);
54
+ const tags = [
55
+ ...(desktopBootstrapUrl === undefined ? [] : [{
56
+ tag: "script",
57
+ attrs: {
58
+ src: command() === "build" || desktopBootstrapUrl === "./runic-desktop.js"
59
+ ? `${prefix}runic-desktop.js`
60
+ : desktopBootstrapUrl,
61
+ },
62
+ injectTo: "head-prepend",
63
+ }]),
64
+ // The development client forwards Views runtime failures to the
65
+ // timeline. It loads before application modules, so a missing Bridge
66
+ // at startup is reported too.
67
+ ...(command() !== "serve" || !client ? [] : [{
68
+ tag: "script",
69
+ attrs: { type: "module", src: `${base}@id/${virtualClientId}` },
70
+ injectTo: "head",
71
+ }]),
72
+ ];
73
+ return command() === "serve"
74
+ ? { html: rewriteHostScripts(document, context.path, false), tags }
75
+ : tags;
76
+ },
53
77
  };
54
78
  return {
55
79
  name: "runic",
@@ -60,7 +84,7 @@ export function runic(options = {}) {
60
84
  // which the dependency scanner cannot see. Pre-bundling it up front
61
85
  // keeps a cold optimizer cache from discovering it on the first page
62
86
  // load and reloading the page, which drops a host's Bridge connection.
63
- return options.devtools === false ? undefined : { optimizeDeps: { include: [clientPackageId] } };
87
+ return client ? { optimizeDeps: { include: [clientPackageId] } } : undefined;
64
88
  }
65
89
  if (desktopBootstrapUrl === undefined)
66
90
  return undefined;
@@ -69,49 +93,25 @@ export function runic(options = {}) {
69
93
  }
70
94
  return { base: "./" };
71
95
  },
72
- // The build parses HTML in a later transform, so host scripts are marked
73
- // vite-ignore here; the dev server has no such pass and uses the hook below.
74
- transform: {
75
- filter: { id: /\.html$/ },
76
- handler(code, id) {
77
- if (state.vite.command !== "build" || !id.endsWith(".html"))
78
- return undefined;
79
- const documentPath = relative(resolvedRoot, id);
80
- if (documentPath.startsWith("..") || isAbsolute(documentPath))
81
- return undefined;
82
- const rewritten = rewriteHostScripts(code, documentPath, true);
83
- return rewritten === code ? undefined : { code: rewritten, map: null };
96
+ // With html: false there is no transformIndexHtml property at all: SvelteKit warns about any plugin that has one.
97
+ ...(html ? {
98
+ // The build parses HTML in a later transform, so host scripts are marked
99
+ // vite-ignore here; the dev server has no such pass and uses the hook below.
100
+ transform: {
101
+ filter: { id: /\.html$/ },
102
+ handler(code, id) {
103
+ if (command() !== "build" || !id.endsWith(".html"))
104
+ return undefined;
105
+ const documentPath = relative(resolvedRoot, id);
106
+ if (documentPath.startsWith("..") || isAbsolute(documentPath))
107
+ return undefined;
108
+ const rewritten = rewriteHostScripts(code, documentPath, true);
109
+ return rewritten === code ? undefined : { code: rewritten, map: null };
110
+ },
84
111
  },
85
- },
86
- transformIndexHtml: {
87
- order: "post",
88
- handler: (html, context) => {
89
- const prefix = webRootPrefix(context.path);
90
- const tags = [
91
- ...(desktopBootstrapUrl === undefined ? [] : [{
92
- tag: "script",
93
- attrs: {
94
- src: state.vite.command === "build" || desktopBootstrapUrl === "./runic-desktop.js"
95
- ? `${prefix}runic-desktop.js`
96
- : desktopBootstrapUrl,
97
- },
98
- injectTo: "head-prepend",
99
- }]),
100
- // The development client forwards Views runtime failures to the
101
- // timeline. It loads before application modules, so a missing Bridge
102
- // at startup is reported too.
103
- ...(state.vite.command !== "serve" || options.devtools === false ? [] : [{
104
- tag: "script",
105
- attrs: { type: "module", src: `${base}@id/${virtualClientId}` },
106
- injectTo: "head",
107
- }]),
108
- ];
109
- return state.vite.command === "serve"
110
- ? { html: rewriteHostScripts(html, context.path, false), tags }
111
- : tags;
112
- },
113
- },
114
- api: { reportDiagnostic: (entry) => appendDiagnostic(entry) },
112
+ transformIndexHtml,
113
+ } : {}),
114
+ api: { reportDiagnostic: (entry) => { timeline.appendDiagnostic(entry); } },
115
115
  configResolved(resolved) {
116
116
  if (resolved.command === "build" && desktopBootstrapUrl !== undefined && resolved.base !== "./") {
117
117
  throw new TypeError("desktop: true requires the resolved Vite base to be './' for relocatable surface output.");
@@ -123,42 +123,58 @@ export function runic(options = {}) {
123
123
  resolvedRoot = resolved.root;
124
124
  const configuredBase = resolved.base || "/";
125
125
  base = configuredBase.endsWith("/") ? configuredBase : `${configuredBase}/`;
126
- state = {
126
+ timeline.configure((state) => ({
127
127
  ...state,
128
128
  vite: { command: resolved.command, mode: resolved.mode, root: resolved.root },
129
- };
129
+ }));
130
130
  },
131
131
  async configureServer(viteServer) {
132
132
  server = viteServer;
133
- viteServer.ws.on(connectionEvent, (payload) => applyConnection(payload));
134
- viteServer.ws.on(diagnosticEvent, (payload) => appendDiagnostic(payload));
133
+ viteServer.ws.on(connectionEvent, (payload) => deliver(connectionEvent, payload));
134
+ viteServer.ws.on(diagnosticEvent, (payload) => deliver(diagnosticEvent, payload));
135
135
  const devSession = devSessionValue(process.env[devSessionVariable]);
136
- viteServer.middlewares.use("/__runic/state", (_request, response) => {
137
- response.statusCode = 200;
138
- response.setHeader("Content-Type", "application/json; charset=utf-8");
139
- response.setHeader("Cache-Control", "no-store");
140
- if (devSession !== undefined)
141
- response.setHeader(devSessionHeader, devSession);
142
- response.end(JSON.stringify(withoutFailures(state)));
136
+ viteServer.middlewares.use(statePath, (_request, response) => {
137
+ answerState(response, timeline.state, devSession);
138
+ });
139
+ // A client that the page loads without the HMR channel posts here (channel.ts).
140
+ viteServer.middlewares.use(diagnosticsPath, (request, response, next) => {
141
+ answerClientMessage(request, response, deliver).catch(next);
143
142
  });
144
143
  viteServer.httpServer?.once("close", () => {
145
144
  server = undefined;
146
145
  });
147
146
  },
148
- resolveId(id) {
149
- return id === virtualClientId ? resolvedVirtualClientId : undefined;
147
+ resolveId(id, importer, resolveOptions) {
148
+ if (id === virtualClientId || (id === clientPackageId && importer !== resolvedVirtualClientId)) {
149
+ // The client runs only in a served page. An application import of the package goes through the virtual
150
+ // module too, so that it takes this plugin's options and channel, and is empty in the build.
151
+ const served = client && command() === "serve" && resolveOptions?.ssr !== true &&
152
+ this.environment?.config.consumer !== "server";
153
+ return served ? resolvedVirtualClientId : resolvedEmptyClientId;
154
+ }
155
+ return id === clientOptionsId ? resolvedClientOptionsId : undefined;
150
156
  },
151
157
  load(id) {
158
+ if (id === resolvedEmptyClientId)
159
+ return "export {};";
160
+ if (id === resolvedClientOptionsId) {
161
+ const statements = [`globalThis[Symbol.for(${JSON.stringify(clientOptionsKey.description)})] = { channel: "hot" };`];
162
+ if (options.staleInputWarning === false) {
163
+ statements.push(`globalThis[Symbol.for("runic.vite.staleInputWarning")] = false;`);
164
+ }
165
+ return statements.join("\n");
166
+ }
152
167
  if (id !== resolvedVirtualClientId)
153
168
  return undefined;
154
- return `import ${JSON.stringify(clientPackageId)};`;
169
+ // Imports evaluate in order, so the options are set before the client reads them.
170
+ return `import ${JSON.stringify(clientOptionsId)};\nimport ${JSON.stringify(clientPackageId)};`;
155
171
  },
156
172
  devtools: {
157
173
  async setup(context) {
158
- if (options.devtools === false)
174
+ if (!client)
159
175
  return;
160
- sharedState = await context.rpc.sharedState.get(stateKey, { initialValue: state });
161
- const renderer = context.createJsonRenderer(createDevtoolsSpec(state));
176
+ sharedState = await context.rpc.sharedState.get(stateKey, { initialValue: timeline.state });
177
+ const renderer = context.createJsonRenderer(createDevtoolsSpec(timeline.state));
162
178
  jsonRenderer = renderer;
163
179
  context.docks.register({
164
180
  id: "runic:overview",
@@ -170,7 +186,7 @@ export function runic(options = {}) {
170
186
  context.commands.register({
171
187
  id: "runic:copy-diagnostic-state",
172
188
  title: "Runic: Copy sanitized diagnostic state",
173
- handler: () => JSON.stringify(withoutFailures(state), null, 2),
189
+ handler: () => JSON.stringify(withoutFailures(timeline.state), null, 2),
174
190
  });
175
191
  },
176
192
  },
@@ -196,18 +212,6 @@ function resolveDesktopBootstrapUrl(options) {
196
212
  }
197
213
  return url.href;
198
214
  }
199
- function initialState(options) {
200
- return {
201
- contract: {
202
- identity: cleanString(options.contract?.identity),
203
- version: cleanString(options.contract?.version),
204
- fingerprint: cleanString(options.contract?.fingerprint),
205
- },
206
- vite: { command: "serve", mode: "development", root: "" },
207
- connection: { state: "unknown" },
208
- timeline: [],
209
- };
210
- }
211
215
  function createDevtoolsSpec(current) {
212
216
  const section = (id, title, data) => ({
213
217
  [id]: { type: "Card", props: { title }, children: [`${id}-data`] },
@@ -239,14 +243,6 @@ function createDevtoolsSpec(current) {
239
243
  },
240
244
  };
241
245
  }
242
- // Failures keep file paths and stacks for the local dock only. The state
243
- // endpoint and the copied state stay path-free.
244
- function withoutFailures(current) {
245
- return {
246
- ...current,
247
- timeline: current.timeline.map(({ failure: _failure, ...entry }) => entry),
248
- };
249
- }
250
246
  function lastFailure(current) {
251
247
  const entry = [...current.timeline].reverse().find((candidate) => candidate.failure !== undefined);
252
248
  if (!entry?.failure)
@@ -259,19 +255,3 @@ function lastFailure(current) {
259
255
  ...(entry.failure.stack ? { Stack: entry.failure.stack } : {}),
260
256
  };
261
257
  }
262
- function connectionState(value) {
263
- return value === "connecting" || value === "connected" || value === "reconnecting" || value === "lost"
264
- ? value
265
- : "unknown";
266
- }
267
- function timelineLimit(value) {
268
- if (typeof value !== "number" || !Number.isFinite(value))
269
- return defaultTimelineLimit;
270
- return Math.min(maximumTimelineLimit, Math.max(1, Math.floor(value)));
271
- }
272
- function cleanString(value) {
273
- return typeof value === "string" ? value.slice(0, 512) : "";
274
- }
275
- function isRecord(value) {
276
- return typeof value === "object" && value !== null && !Array.isArray(value);
277
- }
@@ -0,0 +1,19 @@
1
+ /** Set to `false` on `globalThis` to turn the warning off, before or after this module loads. */
2
+ export declare const staleInputWarningKey: unique symbol;
3
+ /**
4
+ * A typing burst ends on blur or after this long without an `input` event. One second
5
+ * covers a normal Bridge round trip while the user keeps typing, and a script write
6
+ * after a pause is no longer a race with the user's keystrokes.
7
+ */
8
+ export declare const burstQuietPeriodMs = 1000;
9
+ export declare const staleInputMessage: string;
10
+ export interface StaleInputOptions {
11
+ /** The clock, in milliseconds; tests replace it. */
12
+ readonly now?: () => number;
13
+ }
14
+ /**
15
+ * Installs the warning on `host` (normally `globalThis`) once. Does nothing without a DOM,
16
+ * when it is already installed, or when `host[staleInputWarningKey]` is `false`.
17
+ * Returns whether this call installed it.
18
+ */
19
+ export declare function installStaleInputWarning(host: object, options?: StaleInputOptions): boolean;
@@ -0,0 +1,202 @@
1
+ // The `stale-input` development warning (views-protocol-4 design, section 2.4 item 5).
2
+ //
3
+ // A text field bound with a command per key can lose typed characters: the user types
4
+ // "ab", the command for "a" is still in flight, and the framework writes the model's older
5
+ // "a" back into the focused field. Frameworks (React, the Angular renderer, Vue, Svelte)
6
+ // write through the `value` property, so wrapping the `value` setters of
7
+ // `HTMLInputElement` and `HTMLTextAreaElement` sees every such write.
8
+ //
9
+ // The warning fires when script sets `.value` on the focused field to a value that
10
+ // - differs from the field's current value and from the user's latest value, and
11
+ // - the field had earlier in the user's current typing burst,
12
+ // while a Bridge request is in flight. A value equal to an earlier burst value counts as
13
+ // stale even when it looks like a normalization (the user typed "ab " after "ab", and
14
+ // script sets "ab"): the check compares values, not intent.
15
+ //
16
+ // The warning never carries the typed value, which may be a secret: only the element's
17
+ // tag and its id or name.
18
+ /** Set to `false` on `globalThis` to turn the warning off, before or after this module loads. */
19
+ export const staleInputWarningKey = Symbol.for("runic.vite.staleInputWarning");
20
+ // The installed state, shared by every evaluation of this module (HMR, duplicate copies),
21
+ // so the setters and the Bridge are wrapped once per page.
22
+ const installedKey = Symbol.for("runic.vite.staleInput");
23
+ const viewsDiagnosticsKey = Symbol.for("runic.views.diagnostics");
24
+ /**
25
+ * A typing burst ends on blur or after this long without an `input` event. One second
26
+ * covers a normal Bridge round trip while the user keeps typing, and a script write
27
+ * after a pause is no longer a race with the user's keystrokes.
28
+ */
29
+ export const burstQuietPeriodMs = 1_000;
30
+ // Bounds the values remembered per burst; older values are dropped first.
31
+ const maximumBurstValues = 64;
32
+ const maximumNameLength = 40;
33
+ export const staleInputMessage = "to a value it had before the user's last edit while a Bridge request was in flight, which loses " +
34
+ "typed characters. Bind text inputs with the text-field binding of your framework package " +
35
+ "(`injectTextField` in @runic-artifex/angular, `useTextField` in @runic-artifex/react, vue or svelte) " +
36
+ "or a setter instead of a command per key. This warning comes from @runic-artifex/vite-plugin-runic " +
37
+ "in development; turn it off with runic({ staleInputWarning: false }) or, without runic(), by setting " +
38
+ "globalThis[Symbol.for(\"runic.vite.staleInputWarning\")] = false.";
39
+ /**
40
+ * Installs the warning on `host` (normally `globalThis`) once. Does nothing without a DOM,
41
+ * when it is already installed, or when `host[staleInputWarningKey]` is `false`.
42
+ * Returns whether this call installed it.
43
+ */
44
+ export function installStaleInputWarning(host, options = {}) {
45
+ const scope = host;
46
+ if (scope[installedKey] !== undefined || scope[staleInputWarningKey] === false)
47
+ return false;
48
+ const inputClass = scope.HTMLInputElement;
49
+ const textAreaClass = scope.HTMLTextAreaElement;
50
+ const document = scope.document;
51
+ if (typeof inputClass !== "function" || typeof textAreaClass !== "function" ||
52
+ typeof document?.addEventListener !== "function")
53
+ return false;
54
+ const now = options.now ?? (() => Date.now());
55
+ const bursts = new WeakMap();
56
+ const warned = new WeakSet();
57
+ // "In flight" counts the Bridge's `request` promises from call until they settle.
58
+ let inFlight = 0;
59
+ let wrappedBridge;
60
+ const wrappers = new WeakSet();
61
+ const unwrappable = new WeakSet();
62
+ // The host script, or a mock bridge, may install `__runicBridge` after this client runs
63
+ // or replace it later, so the Bridge is (re)wrapped lazily: on every user edit, before
64
+ // the application handles it, and on every value write.
65
+ const wrapBridge = () => {
66
+ const bridge = scope.__runicBridge;
67
+ if (typeof bridge !== "object" || bridge === null || unwrappable.has(bridge))
68
+ return;
69
+ const request = bridge.request;
70
+ if (typeof request !== "function")
71
+ return;
72
+ if (bridge === wrappedBridge && wrappers.has(request))
73
+ return;
74
+ if (wrappers.has(request)) {
75
+ wrappedBridge = bridge;
76
+ return;
77
+ }
78
+ const original = request;
79
+ const wrapper = function (...args) {
80
+ inFlight += 1;
81
+ let result;
82
+ try {
83
+ result = original.apply(this, args);
84
+ }
85
+ catch (error) {
86
+ inFlight -= 1;
87
+ throw error;
88
+ }
89
+ const settled = () => { inFlight -= 1; };
90
+ // The caller keeps the original promise; only this observer waits for it.
91
+ Promise.resolve(result).then(settled, settled);
92
+ return result;
93
+ };
94
+ wrappers.add(wrapper);
95
+ try {
96
+ bridge.request = wrapper;
97
+ }
98
+ catch { /* not writable */ }
99
+ if (bridge.request === wrapper)
100
+ wrappedBridge = bridge;
101
+ else
102
+ unwrappable.add(bridge);
103
+ };
104
+ const isField = (target) => target instanceof inputClass || target instanceof textAreaClass;
105
+ const record = (target, value) => {
106
+ const time = now();
107
+ let burst = bursts.get(target);
108
+ if (!burst || time - burst.lastInput > burstQuietPeriodMs) {
109
+ burst = { values: new Set(), latest: undefined, lastInput: time };
110
+ bursts.set(target, burst);
111
+ }
112
+ burst.values.delete(value);
113
+ burst.values.add(value);
114
+ if (burst.values.size > maximumBurstValues) {
115
+ const oldest = burst.values.values().next();
116
+ if (!oldest.done)
117
+ burst.values.delete(oldest.value);
118
+ }
119
+ burst.lastInput = time;
120
+ };
121
+ // `beforeinput` records the value before the user's edit, so overwriting the first
122
+ // typed character with the value from before it counts too.
123
+ document.addEventListener("beforeinput", (event) => {
124
+ wrapBridge();
125
+ const target = event.target;
126
+ if (isField(target))
127
+ record(target, String(target.value ?? ""));
128
+ }, true);
129
+ document.addEventListener("input", (event) => {
130
+ wrapBridge();
131
+ const target = event.target;
132
+ if (!isField(target))
133
+ return;
134
+ const value = String(target.value ?? "");
135
+ record(target, value);
136
+ const burst = bursts.get(target);
137
+ if (burst)
138
+ burst.latest = value;
139
+ }, true);
140
+ document.addEventListener("focusout", (event) => {
141
+ if (typeof event.target === "object" && event.target !== null)
142
+ bursts.delete(event.target);
143
+ }, true);
144
+ const check = (element, current, next) => {
145
+ if (scope[staleInputWarningKey] === false || inFlight <= 0 || warned.has(element))
146
+ return;
147
+ if (document.activeElement !== element || next === current)
148
+ return;
149
+ const burst = bursts.get(element);
150
+ if (!burst || burst.latest === undefined || now() - burst.lastInput > burstQuietPeriodMs)
151
+ return;
152
+ if (next === burst.latest || !burst.values.has(next))
153
+ return;
154
+ warned.add(element);
155
+ report(scope, element);
156
+ };
157
+ for (const prototype of [inputClass.prototype, textAreaClass.prototype]) {
158
+ const descriptor = Object.getOwnPropertyDescriptor(prototype, "value");
159
+ const { get, set } = descriptor ?? {};
160
+ if (!descriptor || !get || !set || !descriptor.configurable)
161
+ continue;
162
+ Object.defineProperty(prototype, "value", {
163
+ ...descriptor,
164
+ get,
165
+ set(value) {
166
+ try {
167
+ wrapBridge();
168
+ // The setters treat null as the empty string.
169
+ check(this, String(get.call(this)), value === null ? "" : String(value));
170
+ }
171
+ catch { /* the warning never breaks a write */ }
172
+ set.call(this, value);
173
+ },
174
+ });
175
+ }
176
+ scope[installedKey] = true;
177
+ return true;
178
+ }
179
+ function describe(element) {
180
+ const field = element;
181
+ const tag = typeof field.tagName === "string" && field.tagName.toLowerCase() === "textarea" ? "textarea" : "input";
182
+ const name = typeof field.getAttribute === "function" ? field.getAttribute("name") : undefined;
183
+ for (const [attribute, value] of [["id", field.id], ["name", name]]) {
184
+ if (typeof value !== "string")
185
+ continue;
186
+ const clean = value.replace(/[^\w.:-]/gu, "").slice(0, maximumNameLength);
187
+ if (clean)
188
+ return `<${tag} ${attribute}="${clean}">`;
189
+ }
190
+ return `<${tag}>`;
191
+ }
192
+ function report(scope, element) {
193
+ const message = `A script set the focused ${describe(element)} ${staleInputMessage}`;
194
+ scope.console?.warn(message);
195
+ const listeners = (scope[viewsDiagnosticsKey] ??= new Set());
196
+ for (const listener of [...listeners]) {
197
+ try {
198
+ listener({ kind: "error", code: "stale-input", message });
199
+ }
200
+ catch { /* a listener's failure does not stop the others */ }
201
+ }
202
+ }
@@ -0,0 +1,43 @@
1
+ import type { RunicDiagnosticDetail, RunicDiagnosticEntry, RunicDiagnosticFailure, RunicDiagnosticSource } from "./diagnostics.js";
2
+ export interface RunicDevelopmentState {
3
+ readonly contract: Readonly<{
4
+ identity: string;
5
+ version: string;
6
+ fingerprint: string;
7
+ }>;
8
+ readonly vite: Readonly<{
9
+ command: string;
10
+ mode: string;
11
+ root: string;
12
+ }>;
13
+ /**
14
+ * The page's connection to its .NET host, as `@runic-artifex/views` reports it
15
+ * (`BridgeConnectionState`), or `unknown` until a View connects.
16
+ */
17
+ readonly connection: Readonly<{
18
+ state: "connecting" | "connected" | "reconnecting" | "lost" | "unknown";
19
+ }>;
20
+ readonly timeline: readonly RunicTimelineEntry[];
21
+ }
22
+ export type RunicTimelineEntry = Readonly<Required<Pick<RunicDiagnosticEntry, "id" | "timestamp" | "kind" | "label">> & {
23
+ source?: RunicDiagnosticSource;
24
+ detail: RunicDiagnosticDetail;
25
+ failure?: RunicDiagnosticFailure;
26
+ }>;
27
+ export interface DevelopmentTimeline {
28
+ readonly state: RunicDevelopmentState;
29
+ /** Replaces the state without notifying, for configuration such as the resolved Vite command. */
30
+ configure(update: (current: RunicDevelopmentState) => RunicDevelopmentState): void;
31
+ /** Sanitizes and appends an entry; returns it, or `undefined` for a candidate that is not a diagnostic. */
32
+ appendDiagnostic(candidate: unknown, defaultSource?: RunicDiagnosticSource): RunicTimelineEntry | undefined;
33
+ /** Applies a `{ state }` connection report; returns whether the state changed. */
34
+ applyConnection(candidate: unknown): boolean;
35
+ }
36
+ export declare function createDevelopmentTimeline(initial: RunicDevelopmentState, maxTimelineEntries: number, changed: (state: RunicDevelopmentState) => void): DevelopmentTimeline;
37
+ export declare function initialDevelopmentState(contract: Readonly<{
38
+ identity?: string;
39
+ version?: string;
40
+ fingerprint?: string;
41
+ }> | undefined, vite?: RunicDevelopmentState["vite"]): RunicDevelopmentState;
42
+ export declare function withoutFailures(current: RunicDevelopmentState): RunicDevelopmentState;
43
+ export declare function timelineLimit(value: number | undefined): number;