@runic-artifex/vite-plugin-runic 0.18.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.
- package/README.md +532 -12
- package/dist/access.d.ts +46 -0
- package/dist/access.js +123 -0
- package/dist/calls.d.ts +83 -0
- package/dist/calls.js +140 -0
- package/dist/channel.d.ts +58 -1
- package/dist/channel.js +20 -1
- package/dist/client.js +210 -1
- package/dist/dev-session.d.ts +19 -2
- package/dist/dev-session.js +67 -46
- package/dist/diagnostics.d.ts +2 -0
- package/dist/diagnostics.js +2 -1
- package/dist/handlers.d.ts +140 -0
- package/dist/handlers.js +773 -0
- package/dist/index.d.ts +39 -0
- package/dist/index.js +226 -11
- package/dist/inspect-data.d.ts +268 -0
- package/dist/inspect-data.js +442 -0
- package/dist/inspect-edit.d.ts +164 -0
- package/dist/inspect-edit.js +273 -0
- package/dist/inspect-editor.d.ts +34 -0
- package/dist/inspect-editor.js +282 -0
- package/dist/inspect-frameworks.d.ts +72 -0
- package/dist/inspect-frameworks.js +333 -0
- package/dist/inspect-handlers.d.ts +84 -0
- package/dist/inspect-handlers.js +331 -0
- package/dist/inspect.d.ts +42 -0
- package/dist/inspect.js +783 -0
- package/dist/otlp.d.ts +80 -0
- package/dist/otlp.js +254 -0
- package/dist/requests.d.ts +17 -0
- package/dist/requests.js +67 -0
- package/dist/sources.d.ts +135 -0
- package/dist/sources.js +343 -0
- package/dist/timeline.d.ts +12 -0
- package/dist/timeline.js +14 -0
- package/dist/translations-source.d.ts +36 -0
- package/dist/translations-source.js +109 -0
- package/package.json +12 -6
package/dist/otlp.d.ts
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
export { spanEvent } from "./channel.js";
|
|
2
|
+
/** Where and how the development server exports the page's spans of Bridge calls. */
|
|
3
|
+
export interface RunicOtlpOptions {
|
|
4
|
+
/**
|
|
5
|
+
* The OTLP/HTTP traces URL, such as `http://localhost:4318/v1/traces`. Defaults to
|
|
6
|
+
* `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT`, or else `OTEL_EXPORTER_OTLP_ENDPOINT` with `/v1/traces` appended.
|
|
7
|
+
*/
|
|
8
|
+
readonly url?: string;
|
|
9
|
+
/** Headers of each export, such as an API key. Defaults to `OTEL_EXPORTER_OTLP_TRACES_HEADERS` or `OTEL_EXPORTER_OTLP_HEADERS`. */
|
|
10
|
+
readonly headers?: Readonly<Record<string, string>>;
|
|
11
|
+
/**
|
|
12
|
+
* The `service.name` of the page's spans. Defaults to `OTEL_SERVICE_NAME` with `-page` appended, or else the Vite root's
|
|
13
|
+
* package name with `-page` appended, so the page and the .NET host are separate services of one trace.
|
|
14
|
+
*/
|
|
15
|
+
readonly serviceName?: string;
|
|
16
|
+
}
|
|
17
|
+
/** The resolved export: the traces URL, its headers and the page's service name. */
|
|
18
|
+
export interface ResolvedOtlp {
|
|
19
|
+
readonly url: string;
|
|
20
|
+
readonly headers: Readonly<Record<string, string>>;
|
|
21
|
+
readonly serviceName: string;
|
|
22
|
+
}
|
|
23
|
+
type Environment = Readonly<Record<string, string | undefined>>;
|
|
24
|
+
/**
|
|
25
|
+
* The export the option and the environment ask for, or `undefined` for none: `false`, `OTEL_SDK_DISABLED=true`,
|
|
26
|
+
* `OTEL_TRACES_EXPORTER=none`, or no endpoint at all.
|
|
27
|
+
*/
|
|
28
|
+
export declare function resolveOtlp(option: boolean | RunicOtlpOptions | undefined, environment: Environment, root: string): ResolvedOtlp | undefined;
|
|
29
|
+
/** One settled Bridge call with a trace context, as the development client sends it. */
|
|
30
|
+
export interface BrowserSpan {
|
|
31
|
+
readonly traceId: string;
|
|
32
|
+
readonly spanId: string;
|
|
33
|
+
readonly name: string;
|
|
34
|
+
/** Unix epoch milliseconds (`performance.timeOrigin + performance.now()`). */
|
|
35
|
+
readonly start: number;
|
|
36
|
+
readonly end: number;
|
|
37
|
+
readonly kind: string;
|
|
38
|
+
readonly request: string;
|
|
39
|
+
readonly route: string;
|
|
40
|
+
readonly contract: string;
|
|
41
|
+
readonly member: string;
|
|
42
|
+
readonly outcome: string;
|
|
43
|
+
readonly reason?: string;
|
|
44
|
+
readonly revision?: number;
|
|
45
|
+
readonly handler?: {
|
|
46
|
+
readonly name: string;
|
|
47
|
+
readonly duration: number;
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
/** The span a `runic:span` message describes, or `undefined` for one that is not well formed. */
|
|
51
|
+
export declare function readBrowserSpan(data: unknown): BrowserSpan | undefined;
|
|
52
|
+
/**
|
|
53
|
+
* An OTLP/JSON `ExportTraceServiceRequest` of the page's spans: one resource (the page's service), one scope, and a
|
|
54
|
+
* `SPAN_KIND_CLIENT` span per call with the attributes of the .NET Bridge span (`runic.bridge.*`).
|
|
55
|
+
*/
|
|
56
|
+
export declare function otlpTraces(spans: readonly BrowserSpan[], serviceName: string, version: string): object;
|
|
57
|
+
/** Batches the page's spans and posts them to the OTLP endpoint. */
|
|
58
|
+
export interface OtlpForwarder {
|
|
59
|
+
/** Queues the span of a `runic:span` message; ignores one that is not well formed. */
|
|
60
|
+
add(data: unknown): void;
|
|
61
|
+
/** Posts the queued spans now. */
|
|
62
|
+
flush(): Promise<void>;
|
|
63
|
+
/** Posts the queued spans and stops. */
|
|
64
|
+
close(): Promise<void>;
|
|
65
|
+
}
|
|
66
|
+
export interface OtlpForwarderHooks {
|
|
67
|
+
readonly fetch?: (url: string, init: {
|
|
68
|
+
method: string;
|
|
69
|
+
headers: Record<string, string>;
|
|
70
|
+
body: string;
|
|
71
|
+
}) => Promise<{
|
|
72
|
+
readonly ok: boolean;
|
|
73
|
+
readonly status: number;
|
|
74
|
+
}>;
|
|
75
|
+
readonly warn?: (message: string) => void;
|
|
76
|
+
readonly version?: string;
|
|
77
|
+
/** How long a span waits for others before the batch is posted: 500 ms by default. */
|
|
78
|
+
readonly delay?: number;
|
|
79
|
+
}
|
|
80
|
+
export declare function createOtlpForwarder(otlp: ResolvedOtlp, hooks?: OtlpForwarderHooks): OtlpForwarder;
|
package/dist/otlp.js
ADDED
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
// Browser spans of Bridge calls, exported over OTLP by the development server.
|
|
2
|
+
//
|
|
3
|
+
// While a reader of the `@runic-artifex/views` Bridge-call channel gives each call a W3C trace context, the call's
|
|
4
|
+
// request carries it to .NET (trace-context/1), whose `runic.bridge.*` span becomes the child of the page's span. The
|
|
5
|
+
// development client sends each settled call that has one to this server as a `runic:span` message; the server builds
|
|
6
|
+
// the page's span from it and forwards it as OTLP/JSON (OTLP/HTTP, `application/json`) to the endpoint the standard
|
|
7
|
+
// OpenTelemetry variables name. The page needs no OpenTelemetry SDK, sends nothing cross-origin, and the production
|
|
8
|
+
// build contains none of it: the client is development only, and this module runs in the development server.
|
|
9
|
+
import { readFileSync } from "node:fs";
|
|
10
|
+
import { join } from "node:path";
|
|
11
|
+
export { spanEvent } from "./channel.js";
|
|
12
|
+
/**
|
|
13
|
+
* The export the option and the environment ask for, or `undefined` for none: `false`, `OTEL_SDK_DISABLED=true`,
|
|
14
|
+
* `OTEL_TRACES_EXPORTER=none`, or no endpoint at all.
|
|
15
|
+
*/
|
|
16
|
+
export function resolveOtlp(option, environment, root) {
|
|
17
|
+
if (option === false)
|
|
18
|
+
return undefined;
|
|
19
|
+
if (option !== undefined && option !== true && (typeof option !== "object" || option === null)) {
|
|
20
|
+
throw new TypeError("otlp must be true, false or { url?, headers?, serviceName? }.");
|
|
21
|
+
}
|
|
22
|
+
const configured = typeof option === "object" ? option : {};
|
|
23
|
+
if (option === undefined || option === true) {
|
|
24
|
+
if (environment["OTEL_SDK_DISABLED"]?.trim().toLowerCase() === "true")
|
|
25
|
+
return undefined;
|
|
26
|
+
if (environment["OTEL_TRACES_EXPORTER"]?.split(",").map(name => name.trim().toLowerCase()).includes("none"))
|
|
27
|
+
return undefined;
|
|
28
|
+
}
|
|
29
|
+
const url = configured.url ?? tracesUrl(environment);
|
|
30
|
+
if (url === undefined) {
|
|
31
|
+
if (option === true)
|
|
32
|
+
throw new TypeError("otlp: true needs otlp.url or OTEL_EXPORTER_OTLP_ENDPOINT.");
|
|
33
|
+
return undefined;
|
|
34
|
+
}
|
|
35
|
+
let parsed;
|
|
36
|
+
try {
|
|
37
|
+
parsed = new URL(url);
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
throw new TypeError(`otlp.url is not a URL: ${url}`);
|
|
41
|
+
}
|
|
42
|
+
if (parsed.protocol !== "http:" && parsed.protocol !== "https:")
|
|
43
|
+
throw new TypeError(`otlp.url must be http or https: ${url}`);
|
|
44
|
+
const headers = configured.headers ?? parseHeaders(environment["OTEL_EXPORTER_OTLP_TRACES_HEADERS"] ?? environment["OTEL_EXPORTER_OTLP_HEADERS"]);
|
|
45
|
+
for (const [name, value] of Object.entries(headers)) {
|
|
46
|
+
if (typeof value !== "string")
|
|
47
|
+
throw new TypeError(`otlp.headers.${name} must be a string.`);
|
|
48
|
+
}
|
|
49
|
+
const serviceName = configured.serviceName ?? `${environment["OTEL_SERVICE_NAME"]?.trim() || packageName(root) || "runic"}-page`;
|
|
50
|
+
return { url: parsed.href, headers, serviceName };
|
|
51
|
+
}
|
|
52
|
+
// The OpenTelemetry exporter rules: the signal's own variable is the URL; the general one is a base for /v1/traces.
|
|
53
|
+
function tracesUrl(environment) {
|
|
54
|
+
const traces = environment["OTEL_EXPORTER_OTLP_TRACES_ENDPOINT"]?.trim();
|
|
55
|
+
if (traces)
|
|
56
|
+
return traces;
|
|
57
|
+
const base = environment["OTEL_EXPORTER_OTLP_ENDPOINT"]?.trim();
|
|
58
|
+
if (!base)
|
|
59
|
+
return undefined;
|
|
60
|
+
return `${base.replace(/\/+$/u, "")}/v1/traces`;
|
|
61
|
+
}
|
|
62
|
+
// `name=value,name=value`, values percent-encoded (the OpenTelemetry exporter specification).
|
|
63
|
+
function parseHeaders(text) {
|
|
64
|
+
const headers = {};
|
|
65
|
+
for (const pair of text?.split(",") ?? []) {
|
|
66
|
+
const separator = pair.indexOf("=");
|
|
67
|
+
if (separator <= 0)
|
|
68
|
+
continue;
|
|
69
|
+
const name = pair.slice(0, separator).trim();
|
|
70
|
+
let value = pair.slice(separator + 1).trim();
|
|
71
|
+
try {
|
|
72
|
+
value = decodeURIComponent(value);
|
|
73
|
+
}
|
|
74
|
+
catch { /* Kept as written. */ }
|
|
75
|
+
if (name)
|
|
76
|
+
headers[name] = value;
|
|
77
|
+
}
|
|
78
|
+
return headers;
|
|
79
|
+
}
|
|
80
|
+
function packageName(root) {
|
|
81
|
+
try {
|
|
82
|
+
const name = JSON.parse(readFileSync(join(root, "package.json"), "utf8")).name;
|
|
83
|
+
return typeof name === "string" && name.length > 0 ? name.replace(/^@[^/]+\//u, "") : undefined;
|
|
84
|
+
}
|
|
85
|
+
catch {
|
|
86
|
+
return undefined;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
const traceparentPattern = /^00-([0-9a-f]{32})-([0-9a-f]{16})-[0-9a-f]{2}$/u;
|
|
90
|
+
const maximumText = 256;
|
|
91
|
+
const text = (value) => typeof value === "string" && value.length > 0 ? value.slice(0, maximumText) : undefined;
|
|
92
|
+
const finite = (value) => typeof value === "number" && Number.isFinite(value) ? value : undefined;
|
|
93
|
+
/** The span a `runic:span` message describes, or `undefined` for one that is not well formed. */
|
|
94
|
+
export function readBrowserSpan(data) {
|
|
95
|
+
if (typeof data !== "object" || data === null)
|
|
96
|
+
return undefined;
|
|
97
|
+
const value = data;
|
|
98
|
+
const ids = typeof value["traceparent"] === "string" ? traceparentPattern.exec(value["traceparent"]) : null;
|
|
99
|
+
if (!ids || /^0+$/u.test(ids[1]) || /^0+$/u.test(ids[2]))
|
|
100
|
+
return undefined;
|
|
101
|
+
const start = finite(value["start"]);
|
|
102
|
+
const end = finite(value["end"]);
|
|
103
|
+
const name = text(value["name"]);
|
|
104
|
+
if (start === undefined || end === undefined || end < start || name === undefined)
|
|
105
|
+
return undefined;
|
|
106
|
+
const handlerValue = value["handler"];
|
|
107
|
+
const handlerName = text(handlerValue?.["name"]);
|
|
108
|
+
const handlerDuration = finite(handlerValue?.["duration"]);
|
|
109
|
+
const reason = text(value["reason"]);
|
|
110
|
+
const revision = finite(value["revision"]);
|
|
111
|
+
return {
|
|
112
|
+
traceId: ids[1], spanId: ids[2], name, start, end,
|
|
113
|
+
kind: text(value["kind"]) ?? "call", request: text(value["request"]) ?? "", route: text(value["route"]) ?? "",
|
|
114
|
+
contract: text(value["contract"]) ?? "", member: text(value["member"]) ?? "", outcome: text(value["outcome"]) ?? "ok",
|
|
115
|
+
...reason === undefined ? {} : { reason },
|
|
116
|
+
...revision === undefined ? {} : { revision },
|
|
117
|
+
...handlerName === undefined || handlerDuration === undefined ? {} : { handler: { name: handlerName, duration: handlerDuration } },
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
const attribute = (key, value) => ({
|
|
121
|
+
key,
|
|
122
|
+
value: typeof value === "string" ? { stringValue: value }
|
|
123
|
+
: Number.isInteger(value) ? { intValue: String(value) } : { doubleValue: value },
|
|
124
|
+
});
|
|
125
|
+
// Epoch milliseconds as OTLP's fixed64 nanoseconds, which JSON carries as a decimal string.
|
|
126
|
+
function nanoseconds(milliseconds) {
|
|
127
|
+
const whole = Math.floor(milliseconds);
|
|
128
|
+
return (BigInt(whole) * 1000000n + BigInt(Math.round((milliseconds - whole) * 1_000_000))).toString();
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* An OTLP/JSON `ExportTraceServiceRequest` of the page's spans: one resource (the page's service), one scope, and a
|
|
132
|
+
* `SPAN_KIND_CLIENT` span per call with the attributes of the .NET Bridge span (`runic.bridge.*`).
|
|
133
|
+
*/
|
|
134
|
+
export function otlpTraces(spans, serviceName, version) {
|
|
135
|
+
return {
|
|
136
|
+
resourceSpans: [{
|
|
137
|
+
resource: {
|
|
138
|
+
attributes: [
|
|
139
|
+
attribute("service.name", serviceName),
|
|
140
|
+
attribute("telemetry.sdk.name", "@runic-artifex/vite-plugin-runic"),
|
|
141
|
+
attribute("telemetry.sdk.language", "webjs"),
|
|
142
|
+
attribute("telemetry.sdk.version", version),
|
|
143
|
+
],
|
|
144
|
+
},
|
|
145
|
+
scopeSpans: [{
|
|
146
|
+
scope: { name: "@runic-artifex/views", version },
|
|
147
|
+
spans: spans.map(span => {
|
|
148
|
+
const model = span.contract.split(":", 1)[0].split(".").pop() || span.route;
|
|
149
|
+
const attributes = [
|
|
150
|
+
attribute("runic.bridge.kind", span.kind),
|
|
151
|
+
attribute("runic.bridge.request", span.request),
|
|
152
|
+
attribute("runic.bridge.route", span.route),
|
|
153
|
+
attribute("runic.bridge.model", model),
|
|
154
|
+
attribute("runic.bridge.member", span.member),
|
|
155
|
+
attribute("runic.bridge.contract", span.contract),
|
|
156
|
+
attribute("runic.bridge.outcome", span.outcome),
|
|
157
|
+
];
|
|
158
|
+
if (span.reason !== undefined)
|
|
159
|
+
attributes.push(attribute("runic.bridge.reason", span.reason));
|
|
160
|
+
if (span.revision !== undefined)
|
|
161
|
+
attributes.push(attribute("runic.bridge.revision", span.revision));
|
|
162
|
+
if (span.handler !== undefined) {
|
|
163
|
+
attributes.push(attribute("runic.bridge.handler", span.handler.name));
|
|
164
|
+
attributes.push(attribute("runic.bridge.handler.duration_ms", span.handler.duration));
|
|
165
|
+
}
|
|
166
|
+
if (span.outcome === "error")
|
|
167
|
+
attributes.push(attribute("error.type", span.reason ?? "error"));
|
|
168
|
+
return {
|
|
169
|
+
traceId: span.traceId,
|
|
170
|
+
spanId: span.spanId,
|
|
171
|
+
name: span.name,
|
|
172
|
+
kind: 3,
|
|
173
|
+
startTimeUnixNano: nanoseconds(span.start),
|
|
174
|
+
endTimeUnixNano: nanoseconds(span.end),
|
|
175
|
+
attributes,
|
|
176
|
+
...span.outcome === "error" ? { status: { code: 2, message: span.reason ?? "error" } } : {},
|
|
177
|
+
};
|
|
178
|
+
}),
|
|
179
|
+
}],
|
|
180
|
+
}],
|
|
181
|
+
};
|
|
182
|
+
}
|
|
183
|
+
// A batch is posted when it is this large or after the delay; a page that calls faster than the endpoint answers loses
|
|
184
|
+
// the oldest spans beyond the queue limit.
|
|
185
|
+
const batchSize = 64;
|
|
186
|
+
const queueLimit = 2_048;
|
|
187
|
+
export function createOtlpForwarder(otlp, hooks = {}) {
|
|
188
|
+
const post = hooks.fetch ?? globalThis.fetch;
|
|
189
|
+
const warn = hooks.warn ?? ((message) => console.warn(message));
|
|
190
|
+
const delay = hooks.delay ?? 500;
|
|
191
|
+
const version = hooks.version ?? "0";
|
|
192
|
+
const queue = [];
|
|
193
|
+
let timer;
|
|
194
|
+
let posting = Promise.resolve();
|
|
195
|
+
// A failing endpoint is reported once, until an export succeeds again.
|
|
196
|
+
let failing = false;
|
|
197
|
+
let closed = false;
|
|
198
|
+
const send = async (spans) => {
|
|
199
|
+
let failure;
|
|
200
|
+
try {
|
|
201
|
+
const response = await post(otlp.url, {
|
|
202
|
+
method: "POST",
|
|
203
|
+
headers: { ...otlp.headers, "Content-Type": "application/json" },
|
|
204
|
+
body: JSON.stringify(otlpTraces(spans, otlp.serviceName, version)),
|
|
205
|
+
});
|
|
206
|
+
if (!response.ok)
|
|
207
|
+
failure = `HTTP ${response.status}`;
|
|
208
|
+
}
|
|
209
|
+
catch (error) {
|
|
210
|
+
failure = error instanceof Error ? error.message : String(error);
|
|
211
|
+
}
|
|
212
|
+
if (failure === undefined) {
|
|
213
|
+
failing = false;
|
|
214
|
+
return;
|
|
215
|
+
}
|
|
216
|
+
if (failing)
|
|
217
|
+
return;
|
|
218
|
+
failing = true;
|
|
219
|
+
warn(`[runic] Exporting ${spans.length} page span(s) to ${otlp.url} failed (${failure}). The development server sends OTLP/HTTP JSON: ` +
|
|
220
|
+
"point OTEL_EXPORTER_OTLP_ENDPOINT at an OTLP/HTTP receiver (port 4318, or the Aspire dashboard's HTTP port), not an OTLP/gRPC one.");
|
|
221
|
+
};
|
|
222
|
+
const flush = () => {
|
|
223
|
+
if (timer !== undefined) {
|
|
224
|
+
clearTimeout(timer);
|
|
225
|
+
timer = undefined;
|
|
226
|
+
}
|
|
227
|
+
if (queue.length === 0)
|
|
228
|
+
return posting;
|
|
229
|
+
const spans = queue.splice(0, queue.length);
|
|
230
|
+
posting = posting.then(() => send(spans));
|
|
231
|
+
return posting;
|
|
232
|
+
};
|
|
233
|
+
return {
|
|
234
|
+
add(data) {
|
|
235
|
+
if (closed)
|
|
236
|
+
return;
|
|
237
|
+
const span = readBrowserSpan(data);
|
|
238
|
+
if (span === undefined)
|
|
239
|
+
return;
|
|
240
|
+
queue.push(span);
|
|
241
|
+
if (queue.length > queueLimit)
|
|
242
|
+
queue.splice(0, queue.length - queueLimit);
|
|
243
|
+
if (queue.length >= batchSize)
|
|
244
|
+
void flush();
|
|
245
|
+
else
|
|
246
|
+
timer ??= setTimeout(() => { timer = undefined; void flush(); }, delay);
|
|
247
|
+
},
|
|
248
|
+
flush,
|
|
249
|
+
async close() {
|
|
250
|
+
closed = true;
|
|
251
|
+
await flush();
|
|
252
|
+
},
|
|
253
|
+
};
|
|
254
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { IncomingMessage } from "node:http";
|
|
2
|
+
import { type AccessList } from "./access.js";
|
|
3
|
+
/**
|
|
4
|
+
* Whether a request comes from a page of this server: a browser sends `Origin` with every POST, and a cross-site
|
|
5
|
+
* page that posts JSON needs a CORS preflight, which the endpoint never grants.
|
|
6
|
+
*/
|
|
7
|
+
export declare function sameOrigin(request: IncomingMessage): boolean;
|
|
8
|
+
/** Whether a request comes from this machine: a loopback peer address. */
|
|
9
|
+
export declare function isLoopbackRequest(request: IncomingMessage): boolean;
|
|
10
|
+
/** The body as UTF-8, or undefined once it exceeds `limit` bytes; the rest is drained so that the answer reaches the client. */
|
|
11
|
+
export declare function readLimitedBody(request: IncomingMessage, limit: number): Promise<string | undefined>;
|
|
12
|
+
/**
|
|
13
|
+
* Whether a GET may read development data (the source map, the handler analysis): not a page of another origin, and
|
|
14
|
+
* a client of this machine or one the allow list admits (`runic({ allow })`, `RUNIC_DEV_ALLOW`). A browser marks a
|
|
15
|
+
* cross-origin fetch with `Sec-Fetch-Site` and `Origin`; neither is required, so that a tool such as `curl` reads it.
|
|
16
|
+
*/
|
|
17
|
+
export declare function mayRead(request: IncomingMessage, access?: AccessList): Promise<boolean>;
|
package/dist/requests.js
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
// Guards of the development server's endpoints: same-origin pages of this machine, and for the data Runic Inspect reads,
|
|
2
|
+
// of the hosts and networks the allow list admits (access.ts).
|
|
3
|
+
import { isLoopbackAddress, loopbackOnly } from "./access.js";
|
|
4
|
+
/**
|
|
5
|
+
* Whether a request comes from a page of this server: a browser sends `Origin` with every POST, and a cross-site
|
|
6
|
+
* page that posts JSON needs a CORS preflight, which the endpoint never grants.
|
|
7
|
+
*/
|
|
8
|
+
export function sameOrigin(request) {
|
|
9
|
+
const site = request.headers["sec-fetch-site"];
|
|
10
|
+
if (site !== undefined && site !== "same-origin")
|
|
11
|
+
return false;
|
|
12
|
+
const origin = request.headers.origin;
|
|
13
|
+
const host = request.headers.host;
|
|
14
|
+
if (typeof origin !== "string" || typeof host !== "string")
|
|
15
|
+
return false;
|
|
16
|
+
try {
|
|
17
|
+
const url = new URL(origin);
|
|
18
|
+
return (url.protocol === "http:" || url.protocol === "https:") && url.host === host.toLowerCase();
|
|
19
|
+
}
|
|
20
|
+
catch {
|
|
21
|
+
return false;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
/** Whether a request comes from this machine: a loopback peer address. */
|
|
25
|
+
export function isLoopbackRequest(request) {
|
|
26
|
+
return isLoopbackAddress(request.socket?.remoteAddress);
|
|
27
|
+
}
|
|
28
|
+
/** The body as UTF-8, or undefined once it exceeds `limit` bytes; the rest is drained so that the answer reaches the client. */
|
|
29
|
+
export function readLimitedBody(request, limit) {
|
|
30
|
+
const declared = Number(request.headers["content-length"]);
|
|
31
|
+
if (Number.isFinite(declared) && declared > limit) {
|
|
32
|
+
request.resume();
|
|
33
|
+
return Promise.resolve(undefined);
|
|
34
|
+
}
|
|
35
|
+
return new Promise((resolve) => {
|
|
36
|
+
const chunks = [];
|
|
37
|
+
let size = 0;
|
|
38
|
+
let exceeded = false;
|
|
39
|
+
request.on("data", (chunk) => {
|
|
40
|
+
if (exceeded)
|
|
41
|
+
return;
|
|
42
|
+
size += chunk.byteLength;
|
|
43
|
+
if (size > limit) {
|
|
44
|
+
exceeded = true;
|
|
45
|
+
chunks.length = 0;
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
48
|
+
chunks.push(chunk);
|
|
49
|
+
});
|
|
50
|
+
request.on("end", () => resolve(exceeded ? undefined : Buffer.concat(chunks).toString("utf8")));
|
|
51
|
+
request.on("error", () => resolve(undefined));
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Whether a GET may read development data (the source map, the handler analysis): not a page of another origin, and
|
|
56
|
+
* a client of this machine or one the allow list admits (`runic({ allow })`, `RUNIC_DEV_ALLOW`). A browser marks a
|
|
57
|
+
* cross-origin fetch with `Sec-Fetch-Site` and `Origin`; neither is required, so that a tool such as `curl` reads it.
|
|
58
|
+
*/
|
|
59
|
+
export async function mayRead(request, access = loopbackOnly) {
|
|
60
|
+
const site = request.headers["sec-fetch-site"];
|
|
61
|
+
if (site !== undefined && site !== "same-origin" && site !== "none")
|
|
62
|
+
return false;
|
|
63
|
+
const origin = request.headers.origin;
|
|
64
|
+
if (origin !== undefined && !sameOrigin(request))
|
|
65
|
+
return false;
|
|
66
|
+
return access.allowsRequest(request);
|
|
67
|
+
}
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import type { IncomingMessage, ServerResponse } from "node:http";
|
|
2
|
+
import type { AccessList } from "./access.js";
|
|
3
|
+
import type { RunicClientResponse } from "./channel.js";
|
|
4
|
+
import { openPath, sourcesPath } from "./channel.js";
|
|
5
|
+
import { type MessageReference } from "./translations-source.js";
|
|
6
|
+
export { openPath, sourcesPath };
|
|
7
|
+
/** The `sources.json` path that `dotnet runic dev` gives the development server. */
|
|
8
|
+
export declare const sourceMapVariable = "RUNIC_APPLICATION_DEV_SOURCE_MAP";
|
|
9
|
+
export declare const sourceMapFormat = "runic-bridge-sources/1";
|
|
10
|
+
/** Why `/__runic/open` refuses a client of another machine. */
|
|
11
|
+
export declare const openLoopbackOnly: string;
|
|
12
|
+
/**
|
|
13
|
+
* A source location: the absolute path of a local file and a 1-based line and column, as in a compiler diagnostic.
|
|
14
|
+
* The generated clients' declaration maps are made from the same locations.
|
|
15
|
+
*/
|
|
16
|
+
export interface RunicSourceLocation {
|
|
17
|
+
readonly file: string;
|
|
18
|
+
readonly line: number;
|
|
19
|
+
readonly column: number;
|
|
20
|
+
}
|
|
21
|
+
/** A ViewModel with a generated Bridge. */
|
|
22
|
+
export interface RunicSourceViewModel {
|
|
23
|
+
/** The ViewModel's full CLR type name, the part of a generated client's contract before the colon. */
|
|
24
|
+
readonly id: string;
|
|
25
|
+
/** The public name: `Counter` for `CounterViewModel`. */
|
|
26
|
+
readonly name: string;
|
|
27
|
+
/** The route `connect<Name>()` connects: `counter`. A View presented as content connects another route. */
|
|
28
|
+
readonly route: string;
|
|
29
|
+
/** The generated client's contract, `{type}:{fingerprint}`. */
|
|
30
|
+
readonly contract: string;
|
|
31
|
+
/** The `kind` of its page references: the route, with a View contract appended for each contract variant. */
|
|
32
|
+
readonly pageKinds: readonly string[];
|
|
33
|
+
readonly symbol: string;
|
|
34
|
+
readonly location?: RunicSourceLocation;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* What a member is for the page:
|
|
38
|
+
*
|
|
39
|
+
* - `state`: a state member, read through the C# getter;
|
|
40
|
+
* - `setter`: a state member the page sets (`set…` and `write…`), through the C# setter;
|
|
41
|
+
* - `command`: a command; `symbol` and `location` are its handler, such as the `[RelayCommand]` method;
|
|
42
|
+
* - `commandState`: a state member a command adds, such as `canSave`, located at the command's handler;
|
|
43
|
+
* - `interaction` and `request`: an interaction or a View request the page handles.
|
|
44
|
+
*/
|
|
45
|
+
export type RunicSourceMemberKind = "state" | "setter" | "command" | "commandState" | "interaction" | "request";
|
|
46
|
+
export interface RunicSourceMember {
|
|
47
|
+
/** `{viewModel}/{kind}/{member}`. */
|
|
48
|
+
readonly id: string;
|
|
49
|
+
readonly viewModel: string;
|
|
50
|
+
/** The member as the generated client and the Bridge frames name it: `count`, `increment`. */
|
|
51
|
+
readonly member: string;
|
|
52
|
+
readonly kind: RunicSourceMemberKind;
|
|
53
|
+
/** The C# member that runs: `Ns.CounterViewModel.Increment()`, `Ns.CounterViewModel.Step.set`. */
|
|
54
|
+
readonly symbol: string;
|
|
55
|
+
/** For a command whose handler is a method: the command property. */
|
|
56
|
+
readonly property?: string;
|
|
57
|
+
/** Absent when the build had no PDB or no source file for the member. */
|
|
58
|
+
readonly location?: RunicSourceLocation;
|
|
59
|
+
}
|
|
60
|
+
/** `/__runic/sources`: the `sources.json` the Bridge generator wrote, version `runic-bridge-sources/1`. */
|
|
61
|
+
export interface RunicSourceMap {
|
|
62
|
+
readonly format: typeof sourceMapFormat;
|
|
63
|
+
readonly viewModels: readonly RunicSourceViewModel[];
|
|
64
|
+
readonly members: readonly RunicSourceMember[];
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Reads the map where it is: the path `runic({ sourceMap })` names (a `sources.json` or a directory to search), else
|
|
68
|
+
* the one `dotnet runic dev` passes when it exists, else the newest `runic-bridge/sources.json` under `obj` of the project directory
|
|
69
|
+
* `dotnet runic dev` passes, of the Vite root or of its parent. A map is read again only when the file changed.
|
|
70
|
+
*/
|
|
71
|
+
export declare function createSourceMapReader(option: string | undefined, root: () => string): () => RunicSourceMap | undefined;
|
|
72
|
+
/** The map with its well-formed entries, or undefined when it is not a `runic-bridge-sources/1` map. */
|
|
73
|
+
export declare function parseSourceMap(value: unknown): RunicSourceMap | undefined;
|
|
74
|
+
/** Answers `GET /__runic/sources` with the map, or 404 without one. */
|
|
75
|
+
export declare function answerSources(request: IncomingMessage, response: ServerResponse, read: () => RunicSourceMap | undefined, access?: AccessList): Promise<void>;
|
|
76
|
+
/**
|
|
77
|
+
* The location `{ "id" }` of a map entry names, or `{ "file", "line", "column"? }` in a file the map lists, such as a
|
|
78
|
+
* frame of a .NET stack in a ViewModel's file; otherwise undefined. A `file` must be exactly the path of a location in
|
|
79
|
+
* the map, and `line` and `column` positive integers (`column` defaults to 1).
|
|
80
|
+
*/
|
|
81
|
+
export declare function findOpenLocation(map: RunicSourceMap, message: unknown): RunicSourceLocation | undefined;
|
|
82
|
+
/** Whether `file` is exactly the path of a location in the map, so that `/__runic/open` opens it. */
|
|
83
|
+
export declare function listsFile(map: RunicSourceMap | undefined, file: string): boolean;
|
|
84
|
+
/**
|
|
85
|
+
* What decides, besides the source map, which locations may be opened (`resolveOpenLocation`).
|
|
86
|
+
*/
|
|
87
|
+
export interface RunicOpenResolution {
|
|
88
|
+
/** Whether Vite serves a frontend file to the page (index.ts: `isFileLoadingAllowed`). Without it, no frontend file. */
|
|
89
|
+
readonly frontendFile?: (file: string) => boolean;
|
|
90
|
+
/** Where a Runic Translations message is (translations-source.ts). Without it, a message is refused. */
|
|
91
|
+
readonly findMessage?: (message: MessageReference) => Promise<RunicSourceLocation | undefined>;
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* What `/__runic/open`, its HMR route and the dock's open action open for a request's `{ id }`, `{ file, line, column? }`
|
|
95
|
+
* or `{ message: { catalog, key, locale } }`, else undefined (`invalid` for a malformed message reference): a location
|
|
96
|
+
* of the current map (`findOpenLocation`), a location in a frontend file that `frontendFile` accepts (the files Vite
|
|
97
|
+
* itself would serve to the page, which Runic Inspect links to), or where `findMessage` finds a Translations message;
|
|
98
|
+
* in every case only while the file exists (D066.36). The one decision of what may be opened; the endpoint checks the
|
|
99
|
+
* request's origin first, and the dock's RPC is limited to clients Vite DevTools trusts.
|
|
100
|
+
*/
|
|
101
|
+
export declare function resolveOpenLocation(read: () => RunicSourceMap | undefined, message: unknown, resolution?: RunicOpenResolution): Promise<RunicSourceLocation | "invalid" | undefined>;
|
|
102
|
+
/**
|
|
103
|
+
* Opens a location in the editor with launch-editor, the package behind Vite's `/__open-in-editor`, so with the same
|
|
104
|
+
* editor resolution: `LAUNCH_EDITOR`, else a running editor such as VS Code or a JetBrains IDE, else `VISUAL`/`EDITOR`.
|
|
105
|
+
* `failed` receives launch-editor's message when no editor could be started.
|
|
106
|
+
*/
|
|
107
|
+
export declare function launchSourceEditor(location: RunicSourceLocation, failed: (message: string) => void): void;
|
|
108
|
+
/**
|
|
109
|
+
* Answers a development client's request over Vite's HMR connection (channel.ts, `requestEvent`) as the HTTP endpoints
|
|
110
|
+
* answer, under the same access rules, judged per request from the connection's `peer` address: `sources`, `handlers`
|
|
111
|
+
* and `message` for this machine or one the access list admits (`runic({ allow })`, `RUNIC_DEV_ALLOW`), `open` for
|
|
112
|
+
* this machine only, as `/__runic/open` (403 otherwise):
|
|
113
|
+
* `sources` with the map (200) or 404; `handlers` with Runic Inspect's handler analysis of a `file` (200), 404 or 400;
|
|
114
|
+
* `message` with the Translations message API's reply for a `target` `{ catalog, key }` (200), 404 or 400;
|
|
115
|
+
* `open` with the same decision as `/__runic/open` (`resolveOpenLocation`), 200 after `launch`, else 404 (400 for a
|
|
116
|
+
* malformed message reference) and nothing launched. A malformed request without an id gets no answer, one with an id
|
|
117
|
+
* but another kind gets 400.
|
|
118
|
+
*/
|
|
119
|
+
export declare function answerClientRequest(message: unknown, context: {
|
|
120
|
+
readonly read: () => RunicSourceMap | undefined;
|
|
121
|
+
readonly launch: (location: RunicSourceLocation) => void;
|
|
122
|
+
readonly resolution?: RunicOpenResolution;
|
|
123
|
+
readonly analyze?: (file: string) => Promise<unknown>;
|
|
124
|
+
readonly message?: (message: MessageReference) => Promise<unknown>;
|
|
125
|
+
/** The HMR connection's client address, and who besides this machine may read (loopback only without it). */
|
|
126
|
+
readonly peer: string | undefined;
|
|
127
|
+
readonly access?: AccessList;
|
|
128
|
+
}): Promise<RunicClientResponse | undefined>;
|
|
129
|
+
/**
|
|
130
|
+
* Answers `POST /__runic/open`: `{ "id" }` of a map entry, `{ "file", "line", "column" }` in a file the map lists or a
|
|
131
|
+
* frontend file Vite serves, or `{ "message": { catalog, key, locale } }` of a Runic Translations message
|
|
132
|
+
* (`resolveOpenLocation`), as JSON from a page of this server on this machine. Anything else is refused and opens
|
|
133
|
+
* nothing. An accepted location goes to `launch` (launch-editor, as the dock's open action) and is answered 200.
|
|
134
|
+
*/
|
|
135
|
+
export declare function answerOpen(request: IncomingMessage, response: ServerResponse, read: () => RunicSourceMap | undefined, launch: (location: RunicSourceLocation) => void, resolution?: RunicOpenResolution): Promise<void>;
|