@vehicle-sil/gui-client 0.0.0-stage → 0.1.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/package.json CHANGED
@@ -1,6 +1,23 @@
1
1
  {
2
2
  "name": "@vehicle-sil/gui-client",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Client library of the vehicle-sil GUI server: connection, run and time control, ECU variables. No dependencies; browser and Node.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "exports": {
8
+ ".": {
9
+ "types": "./types/index.d.ts",
10
+ "default": "./dist/index.js"
11
+ }
12
+ },
13
+ "types": "./types/index.d.ts",
14
+ "sideEffects": false,
15
+ "files": [
16
+ "dist",
17
+ "types",
18
+ "README.ja.md"
19
+ ],
20
+ "engines": {
21
+ "node": ">=22"
22
+ }
23
+ }
@@ -0,0 +1,112 @@
1
+ import { ClientConnection, SocketFactory } from './connection.js';
2
+ import { HttpTransport } from './http.js';
3
+ import { AppInfo, CheckRequest, CheckResult, ConfigList, DashboardResponse, Recording, ScenarioList, SessionSummary } from './protocol.js';
4
+ import { ClientRun } from './run.js';
5
+ import { ClientSession } from './session.js';
6
+ import { ClientTime } from './time.js';
7
+ import { ClientVariables } from './variables.js';
8
+ import { Readable } from './values.js';
9
+ /** Limits used while they are unknown (before the api/app answer). The same as the launcher's and server's defaults. */
10
+ export declare const DEFAULT_LIMITS: AppInfo['limits'];
11
+ /** Options of createClient. */
12
+ export interface ClientOptions {
13
+ /**
14
+ * URL of the GUI server (`http://127.0.0.1:<port>/`: the URL the server printed, without `#token=...`).
15
+ * HTTP paths and the WebSocket (`ws`) are relative to it. In the browser, use the server's root
16
+ * (`new URL('/', location.href).href`). `document.baseURI` is the screen's route on a page without
17
+ * `<base href="/">`.
18
+ */
19
+ baseUrl: string;
20
+ /**
21
+ * The token (what follows `#token=` in the URL the server printed). A function is called each time the token is
22
+ * used. While it is null, the client does not connect. Switching to another token after a refusal does not
23
+ * reconnect (create a new client instead).
24
+ */
25
+ token: string | (() => string | null);
26
+ /**
27
+ * Origin to send with POST and the WebSocket handshake. Not needed in browsers, which add it themselves. In Node,
28
+ * the origin of baseUrl is sent if omitted (the server accepts only its own origin). Do not pass it in a Web Worker
29
+ * (a Worker's WebSocket cannot add handshake headers; the browser adds Origin).
30
+ */
31
+ origin?: string;
32
+ /** HTTP transport (default fetchTransport). */
33
+ http?: HttpTransport;
34
+ /** Function that opens the WebSocket (default webSocketFactory). */
35
+ socket?: SocketFactory;
36
+ /** How long to wait for the answer to a time command (ms; default ANSWER_TIMEOUT_MS). */
37
+ answerTimeoutMs?: number;
38
+ /**
39
+ * Receives what subscribers (functions passed to subscribe, onBatch, onMessages, onUnreadable) threw. The client
40
+ * carries on (other subscribers still get notified, and handling such as disconnecting after a refusal still
41
+ * completes). The default prints to console.error.
42
+ */
43
+ onError?: (error: unknown) => void;
44
+ }
45
+ /**
46
+ * Client for the GUI server. Holds the connection (WebSocket), the session copy, run and time control, and the server
47
+ * information. All state comes as readable values (Readable: get and subscribe). No framework needed; runs in browsers
48
+ * and in Node.
49
+ *
50
+ * Lifetime: connect() connects (calling it again while connected does nothing). close() disconnects, stops pending
51
+ * timers, stops waiting for answers to time commands and fails writes still waiting for their result (variable
52
+ * watches stay and resume on reconnect). connect() after close() connects again (the session copy is kept and
53
+ * resumes from what it already has). HTTP requests (loadApp() and so on) work without a connection. After the server
54
+ * refused the token (session.rejected) or the versions differ (session.incompatible), connect() does nothing (create a
55
+ * new client).
56
+ */
57
+ export interface GuiClient {
58
+ /** The WebSocket connection (state, number of failed handshakes, close reason, notifications received). */
59
+ readonly connection: ClientConnection;
60
+ /** The session copy (current session, whether it is complete, notices). */
61
+ readonly session: ClientSession;
62
+ /** Run control (start, stop). */
63
+ readonly run: ClientRun;
64
+ /** Time state and commands. */
65
+ readonly time: ClientTime;
66
+ /** ECU variables: list and state, value watches, writes and their results. */
67
+ readonly variables: ClientVariables;
68
+ /** Server and launcher information (`GET api/app`, after loadApp()). null until then. */
69
+ readonly app: Readable<AppInfo | null>;
70
+ /** Speed range and the limits of stepping and checks (the limits of app; DEFAULT_LIMITS until then). */
71
+ readonly limits: Readable<AppInfo['limits']>;
72
+ /** Connects through WebSocket (does nothing without a token, after a refusal, or after a version mismatch). */
73
+ connect(): void;
74
+ /** Disconnects and stops pending timers. */
75
+ close(): void;
76
+ /** Reads `GET api/app` into app. */
77
+ loadApp(): Promise<AppInfo>;
78
+ /** `GET api/configs`: the configuration files to choose from. */
79
+ configs(): Promise<ConfigList>;
80
+ /**
81
+ * `POST api/check`: checks a configuration file (a failed check still gets a successful answer; its result is then
82
+ * not passed). Waits twice the server's check limit (limits.check_timeout_s; waiting its turn, then checking) plus
83
+ * the default HTTP timeout.
84
+ */
85
+ check(request: CheckRequest): Promise<CheckResult>;
86
+ /** `GET api/session`: summary of the current session (null if none). Also applied to the session copy. */
87
+ fetchSession(): Promise<SessionSummary | null>;
88
+ /**
89
+ * `GET api/dashboard`: reads the dashboard file next to the configuration file (relative to root) in the form the
90
+ * server checked (found is false if there is none; problems are in errors).
91
+ */
92
+ dashboard(file: string): Promise<DashboardResponse>;
93
+ /** `GET api/scenarios`: the scenario files in `scenarios` next to the configuration file (relative to root). */
94
+ scenarios(file: string): Promise<ScenarioList>;
95
+ /**
96
+ * `GET api/recording`: the values written through this server and applied in the current (or last) run, as scenario
97
+ * YAML (null if there has been no run yet). Not written to a file.
98
+ */
99
+ recording(): Promise<Recording | null>;
100
+ }
101
+ /**
102
+ * How long to wait for the answer to a start (`api/run`) and a check (`api/check`) (ms). The server runs one check at
103
+ * a time and spends up to check_timeout_s waiting and up to check_timeout_s checking (a start checks a changed
104
+ * configuration file again). Twice that, plus the launcher's start-up and an HTTP margin (DEFAULT_TIMEOUT_MS).
105
+ */
106
+ export declare function longRequestMs(limits: AppInfo['limits']): number;
107
+ /** Whether this runs on Node (only Node's WebSocket can add handshake headers). */
108
+ export declare function isNode(runtime?: object): boolean;
109
+ /** Default Origin outside the browser: the server's own origin on Node, none elsewhere. */
110
+ export declare function defaultOrigin(baseUrl: string, runtime?: object): string | undefined;
111
+ /** Creates a client for the GUI server. Creating it does not connect (call connect()). */
112
+ export declare function createClient(options: ClientOptions): GuiClient;
@@ -0,0 +1,155 @@
1
+ import { ErrorSink, Readable } from './values.js';
2
+ /** closed: not connected (also while waiting to reconnect), connecting: connecting, open: connected. */
3
+ export type ConnectionState = 'connecting' | 'open' | 'closed';
4
+ /** Close code and reason text of a closed connection. */
5
+ export interface CloseInfo {
6
+ code: number;
7
+ reason: string;
8
+ }
9
+ /** Close code the server uses for "try again later". The client reconnects (the token was not refused). */
10
+ export declare const TRY_AGAIN_LATER = 1013;
11
+ /**
12
+ * Interval at which received notifications are passed on in batches (ms). However fast the log flows, subscribers are
13
+ * notified at most this many times a second. A refusal (unauthorized) is also noticed when a batch is passed on. This
14
+ * is shorter than the reconnect delay after the server closes (500 ms at first), so the client never reconnects with a
15
+ * refused token (if it were longer, the client would reconnect once and then stop).
16
+ */
17
+ export declare const BATCH_MS = 100;
18
+ /** Receives WebSocket events. Passed to SocketFactory. */
19
+ export interface SocketHandlers {
20
+ open(): void;
21
+ /** A text message received. */
22
+ message(text: string): void;
23
+ /** Closed (including closed before opening, and could not connect). Called once. */
24
+ close(code: number, reason: string): void;
25
+ }
26
+ /** The part of an open WebSocket that the library uses. */
27
+ export interface SocketLike {
28
+ send(text: string): void;
29
+ close(): void;
30
+ }
31
+ /** Opens a WebSocket. Default webSocketFactory(). Tests replace it with a fake (FakeWebSockets of testing). */
32
+ export type SocketFactory = (url: string, handlers: SocketHandlers) => SocketLike;
33
+ /** How long the connection must stay up before the count of restarts caused by non-JSON notifications is reset (ms). */
34
+ export declare const STEADY_MS = 30000;
35
+ /**
36
+ * SocketFactory that opens the standard WebSocket (browsers, Web Workers, globalThis.WebSocket of Node 22 or later).
37
+ * With origin, the handshake carries Origin (for Node; uses the `{headers}` extension of Node's WebSocket; browser and
38
+ * Worker WebSockets read a second argument as subprotocols, so it is not passed there). If the socket cannot be opened
39
+ * (a wrong URL and so on), this counts as closed, with the cause in the close reason text (`lastClose.reason`).
40
+ */
41
+ export declare function webSocketFactory(options?: {
42
+ origin?: string;
43
+ }): SocketFactory;
44
+ /** Reconnect delay: 0.5 s, doubled each attempt, capped at the limit. attempt starts at 1. */
45
+ export declare function backoffMs(attempt: number, maxMs?: number): number;
46
+ /** Options of Connection. */
47
+ export interface ConnectionOptions {
48
+ /** WebSocket URL (`ws://127.0.0.1:<port>/ws`). */
49
+ url: string;
50
+ /** Opens the WebSocket. */
51
+ socket: SocketFactory;
52
+ /** Message sent right after each open, reconnects included (sent as JSON). Called when connecting. */
53
+ greeting: () => readonly unknown[];
54
+ /**
55
+ * Messages sent right after greeting (those that follow authentication, such as variable subscriptions). Called on
56
+ * open (includes those added between connecting and opening).
57
+ */
58
+ afterGreeting?: () => readonly unknown[];
59
+ /** Upper limit of the reconnect delay. */
60
+ maxBackoffMs?: number;
61
+ /** Interval for batching received notifications. */
62
+ batchMs?: number;
63
+ /** Receives what subscribers threw. */
64
+ onError?: ErrorSink;
65
+ }
66
+ /**
67
+ * Read side of the connection (GuiClient.connection). Connect and disconnect with GuiClient's connect() and close().
68
+ */
69
+ export interface ClientConnection {
70
+ /** Connection state. */
71
+ readonly state: Readable<ConnectionState>;
72
+ /**
73
+ * Number of times the socket closed before opening (refused at the handshake, or never reached the server). The
74
+ * browser does not show why, so when this grows, ask over HTTP (`GET api/app`).
75
+ */
76
+ readonly failures: Readable<number>;
77
+ /** Code and reason of the last close. Back to null when a notification arrives after the close (reconnected). */
78
+ readonly lastClose: Readable<CloseInfo | null>;
79
+ /**
80
+ * Reason text with which the server closed the connection as "try again later" (1013): `too-many-connections`,
81
+ * `too-many-unauthenticated`. The client reconnects after a delay; null once reconnected.
82
+ */
83
+ readonly tryAgainReason: Readable<string | null>;
84
+ /**
85
+ * Receives the notifications that arrived (parsed JSON, contents unchecked, unknown types included), one batch at a
86
+ * time. Call the returned function to unsubscribe.
87
+ */
88
+ onBatch(listener: (batch: readonly unknown[]) => void): () => void;
89
+ /** Receives messages (text) that cannot be parsed as JSON. The connection then reconnects after a delay. */
90
+ onUnreadable(listener: (text: string) => void): () => void;
91
+ }
92
+ /**
93
+ * One WebSocket connection to the GUI server. No framework needed.
94
+ *
95
+ * - connect() connects and close() disconnects (no reconnect). connect() after close() connects again. connect() while
96
+ * connected (also while waiting to reconnect) does nothing.
97
+ * - When the connection drops (an error or the server closing it), reconnects after backoffMs. Each consecutive drop
98
+ * lengthens the delay (so a server that keeps closing with 1013 "try again later" is not hammered with reconnects);
99
+ * a readable notification resets it.
100
+ * - Sends greeting right after each open (authentication, and where to resend from).
101
+ * - Batches the received notifications (parsed JSON, contents unchecked) every batchMs and passes them to the onBatch
102
+ * subscribers. Each feature's reader (the session copy and so on) reads the contents. When something arrives that
103
+ * cannot be parsed as JSON, notifies onUnreadable and reconnects after a delay (receiving again from hello; when in
104
+ * doubt, readers rebuild from the summary).
105
+ */
106
+ export declare class Connection implements ClientConnection {
107
+ private readonly options;
108
+ private readonly onError;
109
+ private readonly stateValue;
110
+ private readonly failureCount;
111
+ private readonly lastCloseValue;
112
+ private readonly batchListeners;
113
+ private readonly unreadableListeners;
114
+ private socket;
115
+ private wanted;
116
+ /** Consecutive drops without a readable notification. */
117
+ private attempts;
118
+ /** Consecutive restarts (restart). */
119
+ private restarts;
120
+ private restartAsked;
121
+ /** Consecutive restarts caused by non-JSON notifications. Reset to 0 after staying connected for STEADY_MS. */
122
+ private garbled;
123
+ private steadyTimer;
124
+ private retryTimer;
125
+ private batchTimer;
126
+ private pending;
127
+ readonly state: Readable<ConnectionState>;
128
+ readonly failures: Readable<number>;
129
+ readonly lastClose: Readable<CloseInfo | null>;
130
+ readonly tryAgainReason: Readable<string | null>;
131
+ constructor(options: ConnectionOptions);
132
+ /** Connects (does nothing if connected or waiting to reconnect). */
133
+ connect(): void;
134
+ /** Disconnects, without reconnecting. Drops notifications still being batched. */
135
+ close(): void;
136
+ /**
137
+ * Drops the current connection and reconnects after a delay (when a reader could not rebuild its state from the
138
+ * notifications). The delay grows with each consecutive restart.
139
+ */
140
+ restart(): void;
141
+ private restartAfter;
142
+ /**
143
+ * Sends a notification to the server (one that follows authentication, such as a variable subscription). Sends only
144
+ * while open and returns whether it sent. What could not be sent goes out with afterGreeting on the next open.
145
+ */
146
+ send(message: unknown): boolean;
147
+ onBatch(listener: (batch: readonly unknown[]) => void): () => void;
148
+ onUnreadable(listener: (text: string) => void): () => void;
149
+ /** Passes on the batched notifications without waiting. */
150
+ flush(): void;
151
+ private dropPending;
152
+ private open;
153
+ private openSocket;
154
+ private scheduleRetry;
155
+ }
@@ -0,0 +1,71 @@
1
+ import { ServerProblem } from './protocol.js';
2
+ /** One request to the GUI server. path is relative to the base (`api/run` and so on, with no leading /). */
3
+ export interface HttpRequest {
4
+ method: 'GET' | 'POST';
5
+ path: string;
6
+ /** Body of a POST (sent as JSON). */
7
+ body?: unknown;
8
+ /** How long to wait for the answer (ms). Omitted: the transport's default (DEFAULT_TIMEOUT_MS for fetchTransport). */
9
+ timeoutMs?: number;
10
+ }
11
+ /** Default time to wait for an answer (ms). A check (`api/check`) waits for the server's check limit plus this. */
12
+ export declare const DEFAULT_TIMEOUT_MS = 30000;
13
+ /** Outcome of a request: the answer's JSON on success, an HttpError on failure. */
14
+ export type HttpOutcome = {
15
+ ok: true;
16
+ body: unknown;
17
+ } | {
18
+ ok: false;
19
+ error: HttpError;
20
+ };
21
+ /**
22
+ * Sends requests to the GUI server. Calls done exactly once, with the outcome. Adding the token (Authorization) and
23
+ * Origin is the transport's job. The default is fetchTransport; it can be replaced with a framework's HTTP tool
24
+ * (such as Angular's HttpClient).
25
+ */
26
+ export type HttpTransport = (request: HttpRequest, done: (outcome: HttpOutcome) => void) => void;
27
+ /**
28
+ * HTTP failure. Status 0 means the server did not answer (the request never arrived, or the wait timed out). problem
29
+ * is the content of the server's error shape (`{"error": {...}}`). timedOut means the client gave up after the
30
+ * timeout (the server may have received the request and still be working on it).
31
+ */
32
+ export declare class HttpError extends Error {
33
+ readonly status: number;
34
+ readonly statusText: string;
35
+ readonly problem: ServerProblem | null;
36
+ readonly timedOut: boolean;
37
+ constructor(status: number, statusText: string, problem: ServerProblem | null, timedOut?: boolean);
38
+ /** Error for a request given up after the timeout. */
39
+ static noAnswer(method: string, path: string, timeoutMs: number): HttpError;
40
+ /**
41
+ * Builds the error from the answer's body (parsed JSON). problem is null unless the body has the server's error
42
+ * shape.
43
+ */
44
+ static from(status: number, statusText: string, body: unknown): HttpError;
45
+ }
46
+ /**
47
+ * Gets the text to show a person for a failure: the server's message for a server error (in English, including how
48
+ * to fix it), the status code for other HTTP failures.
49
+ */
50
+ export declare function errorMessage(error: unknown): string;
51
+ /** Options of fetchTransport. */
52
+ export interface FetchTransportOptions {
53
+ /** URL of the server (`http://127.0.0.1:<port>/`). Request paths are relative to it. */
54
+ baseUrl: string;
55
+ /** The token (what follows `#token=` in the URL the server printed). A function is called for each request. */
56
+ token: string | (() => string | null);
57
+ /**
58
+ * Origin to send with POST. Browsers add it themselves (a value given here is not used). Outside the browser (Node
59
+ * and so on), pass the server's own origin (the origin of baseUrl).
60
+ */
61
+ origin?: string;
62
+ /** The fetch to use (default globalThis.fetch). */
63
+ fetch?: typeof fetch;
64
+ /** Default time to wait for an answer (ms; a request's timeoutMs takes precedence). */
65
+ timeoutMs?: number;
66
+ }
67
+ /**
68
+ * HttpTransport that sends with the standard fetch. Works in browsers and in Node 18 or later. Does not follow
69
+ * redirects (so the token is never sent elsewhere). After the timeout, fails with an HttpError of status 0.
70
+ */
71
+ export declare function fetchTransport(options: FetchTransportOptions): HttpTransport;
@@ -0,0 +1,24 @@
1
+ export { DEFAULT_LIMITS, createClient } from './client.js';
2
+ export type { ClientOptions, GuiClient } from './client.js';
3
+ export type { ClientConnection, CloseInfo, ConnectionState } from './connection.js';
4
+ export type { ClientSession, Notice } from './session.js';
5
+ export type { ClientRun, StopAction } from './run.js';
6
+ export type { ClientTime, Lateness, NotSentReason, SendResult, TimeFailure, TimeState, } from './time.js';
7
+ export { ANSWER_TIMEOUT_MS, FEATURE_SPEED, FEATURE_START_PAUSED, FEATURE_TIME_COMMANDS, } from './time.js';
8
+ export { TOKEN_STORAGE_KEY, takeToken } from './token.js';
9
+ export type { TokenPlace } from './token.js';
10
+ export { HISTORY_MAX, HISTORY_TOTAL_MAX, OPERATIONS_KEPT, WATCH_PERIODS_MS, WATCH_PERIOD_MS, WRITE_TIMEOUT_MS, WriteError, } from './variables.js';
11
+ export type { ClientVariables, HistoryPoint, OperationPeer, OperationView, VariableInfo, VariablePeer, VariableReading, VariableRef, VariableValue, VariableWatch, VariablesState, VariablesStatus, WatchOptions, WatchProblem, WatchValues, WriteOptions, } from './variables.js';
12
+ export { DROPPED_MESSAGE } from './variable-binding.js';
13
+ export type { BindOptions, BoundVariable, VariableBinding } from './variable-binding.js';
14
+ export { hasRange, isWriteError, valueCondition, writeBlock } from './variable-state.js';
15
+ export type { ConditionInput, ValueCondition, WriteBlock, WriteBlockInput, WriteStatus, WriteValue, } from './variable-state.js';
16
+ export type { Readable } from './values.js';
17
+ export { BATCH_MS, TRY_AGAIN_LATER, webSocketFactory } from './connection.js';
18
+ export type { SocketFactory, SocketHandlers, SocketLike } from './connection.js';
19
+ export { DEFAULT_TIMEOUT_MS, HttpError, errorMessage, fetchTransport } from './http.js';
20
+ export type { FetchTransportOptions, HttpOutcome, HttpRequest, HttpTransport } from './http.js';
21
+ export { phaseIndex, runOutcome } from './session-state.js';
22
+ export type { CommandView, LauncherView, LogLine, LogSource, ParticipantView, RunOutcome, ScenarioView, SessionView, TimeView, } from './session-state.js';
23
+ export { FEATURE_SCENARIO, FEATURE_SCENARIO_CONTROL, FEATURE_MANUAL, PHASES, PROTOCOL_VERSION, ProtocolError, readAppInfo, readCheckResponse, readConfigList, readDashboardResponse, readRecording, readScenarioList, readServerMessage, readSessionResponse, readTimeResponse, readVariablesSummary, readWriteResponse, severityRank, } from './protocol.js';
24
+ export type { AppInfo, AuthMessage, CheckNetwork, CheckOutcome, CheckParticipant, CheckRequest, CheckResult, CheckScenario, CheckStatus, CommandReport, ConfigFile, ConfigList, ControlLink, ControlOffer, ControlState, DashboardFile, DashboardFileError, DashboardFileItem, DashboardFileSection, DashboardPanelModule, DashboardResponse, DashboardVariable, Dropped, Finding, LauncherEvent, LogCounts, Open, ParticipantState, Phase, Recording, Replay, RunParticipant, RunRequest, RunResult, RunResultName, RunTiming, ScenarioFile, ScenarioList, ScenarioResult, ScenarioStatus, ScenarioStep, ScenarioStepStatus, ServerMessage, ServerProblem, SessionSummary, Severity, Speed, StopRequest, StopRequestBody, SummaryCommand, SummaryLauncher, SummaryParticipant, SummaryScenario, TimeAnswer, TimeCommand, TimeCommandName, TimeReport, ValuesMessage, Variable, VariableSummary, VariablesSummary, OperationReport, WatchMessage, WriteAnswer, } from './protocol.js';