@runic-artifex/vite-plugin-runic 0.19.0 → 0.20.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.
@@ -0,0 +1,343 @@
1
+ // The development source map (#951): the Bridge generator's `sources.json` in the project's `obj`, which maps every
2
+ // Bridge member to its C# symbol and file:line:column. `runic()` serves it at `/__runic/sources` while serving, and
3
+ // opens a location from it, a frontend file Vite serves or a Runic Translations message's source (translations-source.ts)
4
+ // in the editor at `/__runic/open`. Neither exists in `vite build` or `vite preview`, and
5
+ // nothing of the map reaches a bundle.
6
+ import { readdirSync, readFileSync, statSync } from "node:fs";
7
+ import { dirname, isAbsolute, join, normalize, resolve } from "node:path";
8
+ import launchEditor from "launch-editor";
9
+ import { isLoopbackRequest, mayRead, readLimitedBody, sameOrigin } from "./requests.js";
10
+ import { isLoopbackAddress } from "./access.js";
11
+ import { openPath, sourcesPath } from "./channel.js";
12
+ import { parseMessageReference } from "./translations-source.js";
13
+ export { openPath, sourcesPath };
14
+ /** The `sources.json` path that `dotnet runic dev` gives the development server. */
15
+ export const sourceMapVariable = "RUNIC_APPLICATION_DEV_SOURCE_MAP";
16
+ const projectVariable = "RUNIC_APPLICATION_DEV_PROJECT";
17
+ export const sourceMapFormat = "runic-bridge-sources/1";
18
+ const sourceMapFileName = "sources.json";
19
+ // A larger file is not a map the generator wrote.
20
+ const maximumMapBytes = 16 * 1024 * 1024;
21
+ const maximumOpenRequestBytes = 4096;
22
+ /** Why `/__runic/open` refuses a client of another machine. */
23
+ export const openLoopbackOnly = "Opening in the editor works only from a page on the development machine (localhost): " +
24
+ "/__runic/open launches the editor there. runic({ allow }) and RUNIC_DEV_ALLOW admit other machines to Runic Inspect's data, not to this action.";
25
+ const memberKinds = new Set(["state", "setter", "command", "commandState", "interaction", "request"]);
26
+ /**
27
+ * Reads the map where it is: the path `runic({ sourceMap })` names (a `sources.json` or a directory to search), else
28
+ * the one `dotnet runic dev` passes when it exists, else the newest `runic-bridge/sources.json` under `obj` of the project directory
29
+ * `dotnet runic dev` passes, of the Vite root or of its parent. A map is read again only when the file changed.
30
+ */
31
+ export function createSourceMapReader(option, root) {
32
+ let cached;
33
+ return () => {
34
+ const path = locateSourceMap(option, root());
35
+ if (path === undefined)
36
+ return undefined;
37
+ let stat;
38
+ try {
39
+ stat = statSync(path);
40
+ }
41
+ catch {
42
+ return undefined;
43
+ }
44
+ if (cached?.path === path && cached.modified === stat.mtimeMs && cached.size === stat.size)
45
+ return cached.map;
46
+ let map;
47
+ try {
48
+ map = stat.size <= maximumMapBytes ? parseSourceMap(JSON.parse(readFileSync(path, "utf8"))) : undefined;
49
+ }
50
+ catch {
51
+ map = undefined;
52
+ }
53
+ cached = { path, modified: stat.mtimeMs, size: stat.size, map };
54
+ return map;
55
+ };
56
+ }
57
+ function locateSourceMap(option, root) {
58
+ if (option !== undefined) {
59
+ const path = resolve(root, option);
60
+ if (isFile(path))
61
+ return path;
62
+ return newestUnder(join(path, "obj")) ?? newestUnder(path);
63
+ }
64
+ // dotnet runic dev evaluates the path without the build's own properties, so a missing file falls back to a search.
65
+ const passed = process.env[sourceMapVariable];
66
+ if (passed !== undefined && isAbsolute(passed) && isFile(passed))
67
+ return passed;
68
+ const project = process.env[projectVariable];
69
+ const directories = project !== undefined && isAbsolute(project) ? [dirname(project)] : [root, dirname(root)];
70
+ for (const directory of directories) {
71
+ const found = newestUnder(join(directory, "obj"));
72
+ if (found !== undefined)
73
+ return found;
74
+ }
75
+ return undefined;
76
+ }
77
+ // The newest runic-bridge/sources.json at most three directories below `directory`, as in a project's
78
+ // obj/<Configuration>/<TargetFramework>[/<RuntimeIdentifier>]/runic-bridge.
79
+ function newestUnder(directory) {
80
+ let newest;
81
+ const visit = (current, depth) => {
82
+ let entries;
83
+ try {
84
+ entries = readdirSync(current, { withFileTypes: true });
85
+ }
86
+ catch {
87
+ return;
88
+ }
89
+ for (const entry of entries) {
90
+ if (!entry.isDirectory())
91
+ continue;
92
+ const child = join(current, entry.name);
93
+ if (entry.name === "runic-bridge") {
94
+ const candidate = join(child, sourceMapFileName);
95
+ try {
96
+ const modified = statSync(candidate).mtimeMs;
97
+ if (newest === undefined || modified > newest.modified)
98
+ newest = { path: candidate, modified };
99
+ }
100
+ catch { /* no map here */ }
101
+ }
102
+ else if (depth < 3 && entry.name !== "node_modules" && !entry.name.startsWith(".")) {
103
+ visit(child, depth + 1);
104
+ }
105
+ }
106
+ };
107
+ visit(directory, 0);
108
+ return newest?.path;
109
+ }
110
+ function isFile(path) {
111
+ try {
112
+ return statSync(path).isFile();
113
+ }
114
+ catch {
115
+ return false;
116
+ }
117
+ }
118
+ /** The map with its well-formed entries, or undefined when it is not a `runic-bridge-sources/1` map. */
119
+ export function parseSourceMap(value) {
120
+ if (typeof value !== "object" || value === null || value.format !== sourceMapFormat)
121
+ return undefined;
122
+ const { viewModels, members } = value;
123
+ const strings = (entry, ...names) => names.every((name) => typeof entry[name] === "string");
124
+ return {
125
+ format: sourceMapFormat,
126
+ viewModels: (Array.isArray(viewModels) ? viewModels : []).flatMap((entry) => typeof entry === "object" && entry !== null && strings(entry, "id", "name", "route", "contract", "symbol")
127
+ && Array.isArray(entry.pageKinds) && entry.pageKinds.every((kind) => typeof kind === "string")
128
+ ? [withLocation({
129
+ id: entry.id, name: entry.name, route: entry.route, contract: entry.contract,
130
+ pageKinds: entry.pageKinds, symbol: entry.symbol,
131
+ }, entry.location)]
132
+ : []),
133
+ members: (Array.isArray(members) ? members : []).flatMap((entry) => typeof entry === "object" && entry !== null && strings(entry, "id", "viewModel", "member", "kind", "symbol")
134
+ && memberKinds.has(entry.kind) && (entry.property === undefined || typeof entry.property === "string")
135
+ ? [withLocation({
136
+ id: entry.id, viewModel: entry.viewModel, member: entry.member, kind: entry.kind, symbol: entry.symbol,
137
+ ...(entry.property === undefined ? {} : { property: entry.property }),
138
+ }, entry.location)]
139
+ : []),
140
+ };
141
+ }
142
+ function withLocation(entry, value) {
143
+ const location = sourceLocation(value);
144
+ return location === undefined ? entry : { ...entry, location };
145
+ }
146
+ function sourceLocation(value) {
147
+ if (typeof value !== "object" || value === null)
148
+ return undefined;
149
+ const { file, line, column } = value;
150
+ return typeof file === "string" && isAbsolute(file) && !file.includes("\0")
151
+ && Number.isSafeInteger(line) && line > 0 && Number.isSafeInteger(column) && column > 0
152
+ ? { file, line: line, column: column }
153
+ : undefined;
154
+ }
155
+ function answer(response, status, body, headers = {}) {
156
+ if (response.writableEnded)
157
+ return;
158
+ response.statusCode = status;
159
+ response.setHeader("Cache-Control", "no-store");
160
+ for (const [name, value] of Object.entries(headers))
161
+ response.setHeader(name, value);
162
+ if (body === undefined) {
163
+ response.end();
164
+ return;
165
+ }
166
+ response.setHeader("Content-Type", "application/json; charset=utf-8");
167
+ response.end(JSON.stringify(body));
168
+ }
169
+ /** Answers `GET /__runic/sources` with the map, or 404 without one. */
170
+ export async function answerSources(request, response, read, access) {
171
+ request.resume();
172
+ if (request.method !== "GET" && request.method !== "HEAD")
173
+ return answer(response, 405, undefined, { Allow: "GET, HEAD" });
174
+ if (!(await mayRead(request, access)))
175
+ return answer(response, 403);
176
+ const map = read();
177
+ if (map === undefined)
178
+ return answer(response, 404);
179
+ answer(response, 200, map);
180
+ }
181
+ /**
182
+ * The location `{ "id" }` of a map entry names, or `{ "file", "line", "column"? }` in a file the map lists, such as a
183
+ * frame of a .NET stack in a ViewModel's file; otherwise undefined. A `file` must be exactly the path of a location in
184
+ * the map, and `line` and `column` positive integers (`column` defaults to 1).
185
+ */
186
+ export function findOpenLocation(map, message) {
187
+ if (typeof message !== "object" || message === null || Array.isArray(message))
188
+ return undefined;
189
+ const { id, file, line, column = 1 } = message;
190
+ const entries = [...map.viewModels, ...map.members];
191
+ if (typeof id === "string")
192
+ return entries.find((entry) => entry.id === id)?.location;
193
+ if (typeof file !== "string" || !Number.isSafeInteger(line) || line < 1
194
+ || !Number.isSafeInteger(column) || column < 1)
195
+ return undefined;
196
+ const listed = entries.find((entry) => entry.location?.file === file)?.location;
197
+ return listed === undefined ? undefined : { file: listed.file, line: line, column: column };
198
+ }
199
+ /** Whether `file` is exactly the path of a location in the map, so that `/__runic/open` opens it. */
200
+ export function listsFile(map, file) {
201
+ return map !== undefined && [...map.viewModels, ...map.members].some((entry) => entry.location?.file === file);
202
+ }
203
+ /**
204
+ * What `/__runic/open`, its HMR route and the dock's open action open for a request's `{ id }`, `{ file, line, column? }`
205
+ * or `{ message: { catalog, key, locale } }`, else undefined (`invalid` for a malformed message reference): a location
206
+ * of the current map (`findOpenLocation`), a location in a frontend file that `frontendFile` accepts (the files Vite
207
+ * itself would serve to the page, which Runic Inspect links to), or where `findMessage` finds a Translations message;
208
+ * in every case only while the file exists (D066.36). The one decision of what may be opened; the endpoint checks the
209
+ * request's origin first, and the dock's RPC is limited to clients Vite DevTools trusts.
210
+ */
211
+ export async function resolveOpenLocation(read, message, resolution = {}) {
212
+ let location;
213
+ const translation = typeof message === "object" && message !== null && "message" in message
214
+ ? message.message : undefined;
215
+ if (translation !== undefined) {
216
+ const reference = parseMessageReference(translation);
217
+ if (reference === undefined)
218
+ return "invalid";
219
+ location = await resolution.findMessage?.(reference);
220
+ }
221
+ else {
222
+ const map = read();
223
+ location = (map === undefined ? undefined : findOpenLocation(map, message))
224
+ ?? frontendLocation(message, resolution.frontendFile ?? (() => false));
225
+ }
226
+ return location !== undefined && isFile(location.file) ? location : undefined;
227
+ }
228
+ // `{ file, line, column? }` of a frontend file: an absolute, normalized path that `accepts` admits.
229
+ function frontendLocation(message, accepts) {
230
+ if (typeof message !== "object" || message === null || Array.isArray(message))
231
+ return undefined;
232
+ const { id, file, line, column = 1 } = message;
233
+ if (id !== undefined || typeof file !== "string" || !isAbsolute(file) || normalize(file) !== file || file.includes("\0")
234
+ || !Number.isSafeInteger(line) || line < 1 || !Number.isSafeInteger(column) || column < 1) {
235
+ return undefined;
236
+ }
237
+ return accepts(file) ? { file, line: line, column: column } : undefined;
238
+ }
239
+ /**
240
+ * Opens a location in the editor with launch-editor, the package behind Vite's `/__open-in-editor`, so with the same
241
+ * editor resolution: `LAUNCH_EDITOR`, else a running editor such as VS Code or a JetBrains IDE, else `VISUAL`/`EDITOR`.
242
+ * `failed` receives launch-editor's message when no editor could be started.
243
+ */
244
+ export function launchSourceEditor(location, failed) {
245
+ launchEditor(`${location.file}:${location.line}:${location.column}`, (_file, message) => {
246
+ failed(message ?? `No editor could open ${location.file}.`);
247
+ });
248
+ }
249
+ /**
250
+ * Answers a development client's request over Vite's HMR connection (channel.ts, `requestEvent`) as the HTTP endpoints
251
+ * answer, under the same access rules, judged per request from the connection's `peer` address: `sources`, `handlers`
252
+ * and `message` for this machine or one the access list admits (`runic({ allow })`, `RUNIC_DEV_ALLOW`), `open` for
253
+ * this machine only, as `/__runic/open` (403 otherwise):
254
+ * `sources` with the map (200) or 404; `handlers` with Runic Inspect's handler analysis of a `file` (200), 404 or 400;
255
+ * `message` with the Translations message API's reply for a `target` `{ catalog, key }` (200), 404 or 400;
256
+ * `open` with the same decision as `/__runic/open` (`resolveOpenLocation`), 200 after `launch`, else 404 (400 for a
257
+ * malformed message reference) and nothing launched. A malformed request without an id gets no answer, one with an id
258
+ * but another kind gets 400.
259
+ */
260
+ export async function answerClientRequest(message, context) {
261
+ if (typeof message !== "object" || message === null || Array.isArray(message))
262
+ return undefined;
263
+ const { id, kind, target, file } = message;
264
+ if (typeof id !== "number" || !Number.isSafeInteger(id) || id < 0)
265
+ return undefined;
266
+ if (kind !== "sources" && kind !== "handlers" && kind !== "message" && kind !== "open")
267
+ return { id, status: 400 };
268
+ const admitted = kind === "open" ? isLoopbackAddress(context.peer)
269
+ : context.access === undefined ? isLoopbackAddress(context.peer) : await context.access.allows(context.peer);
270
+ if (!admitted)
271
+ return { id, status: 403 };
272
+ if (kind === "sources") {
273
+ const map = context.read();
274
+ return map === undefined ? { id, status: 404 } : { id, status: 200, body: map };
275
+ }
276
+ if (kind === "handlers") {
277
+ if (context.analyze === undefined)
278
+ return { id, status: 404 };
279
+ if (typeof file !== "string" || file.length === 0 || file.length > 4096)
280
+ return { id, status: 400 };
281
+ const analysis = await context.analyze(file);
282
+ return analysis === undefined ? { id, status: 404 } : { id, status: 200, body: analysis };
283
+ }
284
+ if (kind === "message") {
285
+ if (context.message === undefined)
286
+ return { id, status: 404 };
287
+ const reference = parseMessageReference(typeof target === "object" && target !== null ? { locale: "", ...target } : target);
288
+ if (reference === undefined)
289
+ return { id, status: 400 };
290
+ const reply = await context.message(reference);
291
+ return reply === undefined ? { id, status: 404 } : { id, status: 200, body: reply };
292
+ }
293
+ const location = await resolveOpenLocation(context.read, target, context.resolution);
294
+ if (location === "invalid")
295
+ return { id, status: 400 };
296
+ if (location === undefined)
297
+ return { id, status: 404 };
298
+ context.launch(location);
299
+ return { id, status: 200 };
300
+ }
301
+ /**
302
+ * Answers `POST /__runic/open`: `{ "id" }` of a map entry, `{ "file", "line", "column" }` in a file the map lists or a
303
+ * frontend file Vite serves, or `{ "message": { catalog, key, locale } }` of a Runic Translations message
304
+ * (`resolveOpenLocation`), as JSON from a page of this server on this machine. Anything else is refused and opens
305
+ * nothing. An accepted location goes to `launch` (launch-editor, as the dock's open action) and is answered 200.
306
+ */
307
+ export async function answerOpen(request, response, read, launch, resolution = {}) {
308
+ if (request.method !== "POST") {
309
+ request.resume();
310
+ return answer(response, 405, undefined, { Allow: "POST" });
311
+ }
312
+ if (!sameOrigin(request)) {
313
+ request.resume();
314
+ return answer(response, 403);
315
+ }
316
+ // Loopback only, whatever the allow list says: the editor opens on this machine, not on the client's.
317
+ if (!isLoopbackRequest(request)) {
318
+ request.resume();
319
+ return answer(response, 403, { error: "loopback-only", detail: openLoopbackOnly });
320
+ }
321
+ const type = request.headers["content-type"];
322
+ if (typeof type !== "string" || !/^application\/json\s*(?:;|$)/iu.test(type)) {
323
+ request.resume();
324
+ return answer(response, 415);
325
+ }
326
+ const body = await readLimitedBody(request, maximumOpenRequestBytes);
327
+ if (body === undefined)
328
+ return answer(response, 413);
329
+ let message;
330
+ try {
331
+ message = JSON.parse(body);
332
+ }
333
+ catch {
334
+ return answer(response, 400);
335
+ }
336
+ const location = await resolveOpenLocation(read, message, resolution);
337
+ if (location === "invalid")
338
+ return answer(response, 400);
339
+ if (location === undefined)
340
+ return answer(response, 404);
341
+ launch(location);
342
+ answer(response, 200);
343
+ }
@@ -1,4 +1,6 @@
1
1
  import type { RunicDiagnosticDetail, RunicDiagnosticEntry, RunicDiagnosticFailure, RunicDiagnosticSource, RunicViewStateValue } from "./diagnostics.js";
2
+ import type { RunicBridgeCall } from "./calls.js";
3
+ import type { RunicSourceMap } from "./sources.js";
2
4
  export interface RunicDevelopmentState {
3
5
  readonly contract: Readonly<{
4
6
  identity: string;
@@ -24,6 +26,11 @@ export interface RunicDevelopmentState {
24
26
  */
25
27
  readonly views: readonly RunicViewSnapshot[];
26
28
  readonly timeline: readonly RunicTimelineEntry[];
29
+ /**
30
+ * The page's settled Bridge calls, the oldest first, as many as the timeline keeps: each with its duration, its C#
31
+ * handler from the development source map and, from a .NET host that measures it, the handler's own duration.
32
+ */
33
+ readonly calls: readonly RunicBridgeCall[];
27
34
  }
28
35
  /** One View in the state inspector. */
29
36
  export interface RunicViewSnapshot {
@@ -59,6 +66,11 @@ export interface DevelopmentTimeline {
59
66
  * whether the report was valid.
60
67
  */
61
68
  applyView(candidate: unknown): boolean;
69
+ /**
70
+ * Sanitizes and appends a call the development client reported, with the handler `map` names; returns it, or
71
+ * `undefined` for a candidate that is not a call report.
72
+ */
73
+ appendCall(candidate: unknown, map?: RunicSourceMap): RunicBridgeCall | undefined;
62
74
  }
63
75
  export declare function createDevelopmentTimeline(initial: RunicDevelopmentState, maxTimelineEntries: number, changed: (state: RunicDevelopmentState) => void): DevelopmentTimeline;
64
76
  export declare function initialDevelopmentState(contract: Readonly<{
package/dist/timeline.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { sanitizeDiagnosticSummary, sanitizeViewState } from "./diagnostics.js";
2
+ import { callEntry, sanitizeCallReport } from "./calls.js";
2
3
  const defaultTimelineLimit = 200;
3
4
  const maximumTimelineLimit = 500;
4
5
  // The state inspector keeps the Views that changed most recently, over every page of the server.
@@ -6,6 +7,7 @@ const maximumInspectedViews = 32;
6
7
  export function createDevelopmentTimeline(initial, maxTimelineEntries, changed) {
7
8
  let state = initial;
8
9
  let nextSequence = 1;
10
+ let nextCall = 1;
9
11
  return {
10
12
  get state() { return state; },
11
13
  configure(update) { state = update(state); },
@@ -23,6 +25,16 @@ export function createDevelopmentTimeline(initial, maxTimelineEntries, changed)
23
25
  changed(state);
24
26
  return entry;
25
27
  },
28
+ appendCall(candidate, map) {
29
+ const report = sanitizeCallReport(candidate);
30
+ if (!report)
31
+ return undefined;
32
+ const entry = callEntry(report, map, `call-${nextCall}`, new Date().toISOString());
33
+ nextCall += 1;
34
+ state = { ...state, calls: [...state.calls, entry].slice(-maxTimelineEntries) };
35
+ changed(state);
36
+ return entry;
37
+ },
26
38
  applyConnection(candidate) {
27
39
  const next = connectionState(isRecord(candidate) ? candidate.state : undefined);
28
40
  if (next === state.connection.state)
@@ -84,6 +96,7 @@ export function initialDevelopmentState(contract, vite = { command: "serve", mod
84
96
  connection: { state: "unknown" },
85
97
  views: [],
86
98
  timeline: [],
99
+ calls: [],
87
100
  };
88
101
  }
89
102
  // Failures keep file paths and stacks for local display only (the dock, the development server's terminal). The
@@ -92,6 +105,7 @@ export function withoutFailures(current) {
92
105
  return {
93
106
  ...current,
94
107
  timeline: current.timeline.map(({ failure: _failure, ...entry }) => entry),
108
+ calls: current.calls.map(({ failure: _failure, ...call }) => call),
95
109
  };
96
110
  }
97
111
  export function timelineLimit(value) {
@@ -0,0 +1,36 @@
1
+ import type { AddressInfo } from "node:net";
2
+ import type { RunicSourceLocation } from "./sources.js";
3
+ /** A message as Runic Inspect names it: its catalog, key and the locale whose text the page shows. */
4
+ export interface MessageReference {
5
+ readonly catalog: string;
6
+ readonly key: string;
7
+ /** Empty when the page's Translations runtime did not tell it; the base locale is used then. */
8
+ readonly locale: string;
9
+ }
10
+ /** The development server, as the request to its message API needs it. */
11
+ export interface TranslationsServer {
12
+ readonly address: AddressInfo | string | null | undefined;
13
+ readonly https: boolean;
14
+ /** Vite's `base`, a path or a URL. */
15
+ readonly base: string;
16
+ }
17
+ /** The `{ "message": { catalog, key, locale } }` of an open request, when it is well formed. */
18
+ export declare function parseMessageReference(value: unknown): MessageReference | undefined;
19
+ /**
20
+ * The source of a message's locale in the message API's reply (`message.locales[].source`), when it is a `.rmf2` or
21
+ * `.mf2` file. A message without a locale takes the base locale, which the reply lists first.
22
+ */
23
+ export declare function messageLocation(reply: unknown, message: MessageReference): RunicSourceLocation | undefined;
24
+ /** The message API's URL on this server: loopback, the server's port, below its base. */
25
+ export declare function messageUrl(server: TranslationsServer, message: MessageReference): URL | undefined;
26
+ /**
27
+ * Asks this development server's Translations message API where a message's locale is defined. Undefined when the API
28
+ * is not there (an earlier plugin, manifest mode, `inPageEditing: false`), refuses, or names no `.rmf2`/`.mf2` source.
29
+ */
30
+ export declare function findMessageSource(server: TranslationsServer, message: MessageReference): Promise<RunicSourceLocation | undefined>;
31
+ /**
32
+ * This development server's Translations message API reply for a message (`message.locales[]`), for Runic Inspect's
33
+ * requests over Vite's HMR connection (sources.ts, `answerClientRequest`). Undefined when the API is not there or
34
+ * refuses.
35
+ */
36
+ export declare function readMessageReply(server: TranslationsServer, message: MessageReference): Promise<unknown>;
@@ -0,0 +1,109 @@
1
+ // Where a Runic Translations message is defined, for Runic Inspect's "open in editor" (#956). The open action never takes
2
+ // a path from the page for a message: it asks the Translations dev server's message API (`GET
3
+ // /__runic-translations/message`, vite-plugin-runic-translations 0.12 in project mode) for the message's locale, on the
4
+ // same development server, and opens the `.rmf2`/`.mf2` source that answer names. So it opens only a source the
5
+ // Translations catalog lists.
6
+ import { request as httpRequest } from "node:http";
7
+ import { request as httpsRequest } from "node:https";
8
+ const maximumReplyBytes = 4 * 1024 * 1024;
9
+ const messagePath = "__runic-translations/message";
10
+ /** The `{ "message": { catalog, key, locale } }` of an open request, when it is well formed. */
11
+ export function parseMessageReference(value) {
12
+ if (typeof value !== "object" || value === null || Array.isArray(value))
13
+ return undefined;
14
+ const { catalog, key, locale } = value;
15
+ if (typeof catalog !== "string" || !/^[a-z][a-z0-9.-]{0,127}$/u.test(catalog))
16
+ return undefined;
17
+ if (typeof key !== "string" || !/^[A-Za-z_][A-Za-z0-9_.]{0,511}$/u.test(key))
18
+ return undefined;
19
+ if (typeof locale !== "string" || !/^(?:[A-Za-z0-9]{1,8}(?:-[A-Za-z0-9]{1,8}){0,7})?$/u.test(locale))
20
+ return undefined;
21
+ return { catalog, key, locale };
22
+ }
23
+ /**
24
+ * The source of a message's locale in the message API's reply (`message.locales[].source`), when it is a `.rmf2` or
25
+ * `.mf2` file. A message without a locale takes the base locale, which the reply lists first.
26
+ */
27
+ export function messageLocation(reply, message) {
28
+ const locales = reply?.message?.locales;
29
+ if (!Array.isArray(locales))
30
+ return undefined;
31
+ const entry = locales.find((item) => item?.locale === message.locale)
32
+ ?? (message.locale === "" ? locales[0] : undefined);
33
+ const source = entry?.source;
34
+ const { path, line, column } = source ?? {};
35
+ if (typeof path !== "string" || !/\.(?:rmf2|mf2)$/iu.test(path) || !Number.isSafeInteger(line) || line < 1)
36
+ return undefined;
37
+ return { file: path, line: line, column: Number.isSafeInteger(column) && column > 0 ? column : 1 };
38
+ }
39
+ /** The message API's URL on this server: loopback, the server's port, below its base. */
40
+ export function messageUrl(server, message) {
41
+ const address = server.address;
42
+ if (address === null || address === undefined || typeof address === "string")
43
+ return undefined;
44
+ const host = address.family === "IPv6" || address.family === 6
45
+ ? (address.address === "::" ? "127.0.0.1" : `[${address.address}]`)
46
+ : (address.address === "0.0.0.0" ? "127.0.0.1" : address.address);
47
+ let path = /^https?:/iu.test(server.base) ? new URL(server.base).pathname : server.base;
48
+ if (!path.startsWith("/"))
49
+ path = `/${path}`;
50
+ if (!path.endsWith("/"))
51
+ path += "/";
52
+ const url = new URL(`${server.https ? "https" : "http"}://${host}:${address.port}${path}${messagePath}`);
53
+ url.searchParams.set("key", message.key);
54
+ url.searchParams.set("catalog", message.catalog);
55
+ return url;
56
+ }
57
+ /**
58
+ * Asks this development server's Translations message API where a message's locale is defined. Undefined when the API
59
+ * is not there (an earlier plugin, manifest mode, `inPageEditing: false`), refuses, or names no `.rmf2`/`.mf2` source.
60
+ */
61
+ export async function findMessageSource(server, message) {
62
+ const url = messageUrl(server, message);
63
+ if (url === undefined)
64
+ return undefined;
65
+ return messageLocation(await getJson(url), message);
66
+ }
67
+ /**
68
+ * This development server's Translations message API reply for a message (`message.locales[]`), for Runic Inspect's
69
+ * requests over Vite's HMR connection (sources.ts, `answerClientRequest`). Undefined when the API is not there or
70
+ * refuses.
71
+ */
72
+ export async function readMessageReply(server, message) {
73
+ const url = messageUrl(server, message);
74
+ return url === undefined ? undefined : getJson(url);
75
+ }
76
+ // The request goes to this process's own listening socket. With HTTPS that is the dev server's own certificate, often
77
+ // self-signed, so it is not verified; the connection never leaves the machine.
78
+ function getJson(url) {
79
+ return new Promise((resolve) => {
80
+ const https = url.protocol === "https:";
81
+ const request = (https ? httpsRequest : httpRequest)(url, {
82
+ method: "GET", headers: { Accept: "application/json" }, timeout: 15_000, ...(https ? { rejectUnauthorized: false } : {}),
83
+ }, (response) => {
84
+ const chunks = [];
85
+ let size = 0;
86
+ response.on("data", (chunk) => {
87
+ size += chunk.byteLength;
88
+ if (size > maximumReplyBytes)
89
+ request.destroy();
90
+ else
91
+ chunks.push(chunk);
92
+ });
93
+ response.on("end", () => {
94
+ if (response.statusCode !== 200)
95
+ return resolve(undefined);
96
+ try {
97
+ resolve(JSON.parse(Buffer.concat(chunks).toString("utf8")));
98
+ }
99
+ catch {
100
+ resolve(undefined);
101
+ }
102
+ });
103
+ response.on("error", () => resolve(undefined));
104
+ });
105
+ request.on("timeout", () => request.destroy());
106
+ request.on("error", () => resolve(undefined));
107
+ request.end();
108
+ });
109
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@runic-artifex/vite-plugin-runic",
3
- "version": "0.19.0",
3
+ "version": "0.20.0",
4
4
  "description": "Vite 8 development and DevTools integration for Runic applications",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -33,6 +33,9 @@
33
33
  "verify": "bun run --bun typecheck && bun run --bun test && bun pm pack --dry-run",
34
34
  "pack:preview": "bun pm pack"
35
35
  },
36
+ "dependencies": {
37
+ "launch-editor": "2.14.2"
38
+ },
36
39
  "peerDependencies": {
37
40
  "@vitejs/devtools": "^0.7.6",
38
41
  "vite": ">=8.3.3 <9"
@@ -43,14 +46,17 @@
43
46
  }
44
47
  },
45
48
  "devDependencies": {
46
- "@runic-artifex/react": "0.19.0",
47
- "@runic-artifex/views": "0.19.0",
48
- "@runic-artifex/vue": "0.19.0",
49
+ "@runic-artifex/react": "0.20.0",
50
+ "@runic-artifex/views": "0.20.0",
51
+ "@runic-artifex/vue": "0.20.0",
52
+ "@sveltejs/vite-plugin-svelte": "7.3.1",
49
53
  "@types/node": "24.19.1",
50
54
  "@vitejs/devtools": "0.7.6",
51
55
  "@vitejs/devtools-kit": "0.7.6",
56
+ "@vitejs/plugin-vue": "6.0.9",
52
57
  "react": "19.3.0",
53
58
  "react-dom": "19.3.0",
59
+ "svelte": "5.57.1",
54
60
  "typescript": "6.0.3",
55
61
  "vite": "8.3.4",
56
62
  "vue": "3.5.43"
@@ -67,7 +73,7 @@
67
73
  "url": "git+https://github.com/Runic-Artifex/runic-sdk.git",
68
74
  "directory": "packages/web/vite-plugin-runic"
69
75
  },
70
- "homepage": "https://github.com/Runic-Artifex/runic-sdk/tree/v0.19.0/packages/web/vite-plugin-runic#readme",
76
+ "homepage": "https://github.com/Runic-Artifex/runic-sdk/tree/v0.20.0/packages/web/vite-plugin-runic#readme",
71
77
  "bugs": {
72
78
  "url": "https://github.com/Runic-Artifex/runic-sdk/issues"
73
79
  },
@@ -78,5 +84,5 @@
78
84
  "vite-plugin",
79
85
  "devtools"
80
86
  ],
81
- "gitHead": "9a09c23055f09f7505552d236c8acf69bdeeb02e"
87
+ "gitHead": "8288005e35e9cc377ca280db1ab44b91582cd705"
82
88
  }