@impz/client 2.4.1 → 2.5.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 +18 -6
- package/dist/index.d.ts +132 -2
- package/dist/index.js +549 -144
- package/package.json +3 -1
package/README.md
CHANGED
|
@@ -51,6 +51,16 @@ stops, calls fail with `SERVICE_UNAVAILABLE`, and while it restarts, `fetch` can
|
|
|
51
51
|
`{ retryUnavailable: { attempts, delayMs } }` to wait for it to come back. `RAM_BUDGET_EXCEEDED` is
|
|
52
52
|
never retried.
|
|
53
53
|
|
|
54
|
+
`watchEvents(imp, { onEvent })` follows `events.stream`: every imp first, then each change. `name`
|
|
55
|
+
keeps one imp's events, and `reconnect: { delayMs }` opens a fresh stream whenever one ends, until
|
|
56
|
+
impd refuses the call or `signal` aborts. `onOpen` runs as each stream opens, so a caller can catch
|
|
57
|
+
up on what changed while it was away.
|
|
58
|
+
|
|
59
|
+
`openForwardTunnel` relays one connection to a port in the imp over `/tunnel`, and
|
|
60
|
+
`openReverseForward` listens in the imp and relays each client back. `openToolExec` runs an agent
|
|
61
|
+
tool such as `tar` over `/exec` with acked stdin and stdout. Each takes a `connect` that opens the
|
|
62
|
+
WebSocket, and `resolveImpdWebSocketUrl` gives the URL for an impd endpoint.
|
|
63
|
+
|
|
54
64
|
## Run commands
|
|
55
65
|
|
|
56
66
|
`imp.run` runs a command to its exit and collects its output. Without `stdin`, stdin closes at once.
|
|
@@ -193,8 +203,8 @@ A 401 means the token is wrong.
|
|
|
193
203
|
|
|
194
204
|
## Features
|
|
195
205
|
|
|
196
|
-
An older impd drops an input field it does not know, and the call succeeds without it. Check
|
|
197
|
-
|
|
206
|
+
An older impd drops an input field it does not know, and the call succeeds without it. Check its
|
|
207
|
+
features before you send a field that a later impd added:
|
|
198
208
|
|
|
199
209
|
| Field | Feature | Since |
|
|
200
210
|
| ------------------------------------------------- | ----------------- | ------ |
|
|
@@ -203,12 +213,14 @@ An older impd drops an input field it does not know, and the call succeeds witho
|
|
|
203
213
|
| `require` on `openExec` | `execRequire` | 0.30.0 |
|
|
204
214
|
| `secretFiles`, `removeSecretFiles` on `system.gc` | `secretFilesGc` | 0.31.0 |
|
|
205
215
|
|
|
216
|
+
`requireFeatures` reads the flags once, from `system.features`, or from `system.info` on an impd
|
|
217
|
+
older than it. It throws a `MissingFeatureError` for the first feature missing, with what that impd
|
|
218
|
+
would do instead:
|
|
219
|
+
|
|
206
220
|
```ts
|
|
207
|
-
|
|
221
|
+
import { requireFeatures } from '@impz/client';
|
|
208
222
|
|
|
209
|
-
|
|
210
|
-
throw new Error('this impd makes tokens without a grantable list');
|
|
211
|
-
}
|
|
223
|
+
await requireFeatures(imp, { grantableTokens: 'make the token without a grantable list' });
|
|
212
224
|
```
|
|
213
225
|
|
|
214
226
|
Without the `secretRebind` feature, a `replace` that changes the hosts keeps every grant. With it,
|
package/dist/index.d.ts
CHANGED
|
@@ -56,6 +56,8 @@ type ImageBuildPhase = z.infer<typeof ImageBuildPhaseSchema>;
|
|
|
56
56
|
type ImageBuildProgress = z.infer<typeof ImageBuildProgressSchema>;
|
|
57
57
|
//#endregion
|
|
58
58
|
//#region ../api/src/protocols/exec-protocol.d.ts
|
|
59
|
+
declare const EXEC_TOOLS: readonly ['tar'];
|
|
60
|
+
type ExecTool = (typeof EXEC_TOOLS)[number];
|
|
59
61
|
export declare const EXEC_REQUIREMENTS: readonly ['broker'];
|
|
60
62
|
type ExecRequirement = (typeof EXEC_REQUIREMENTS)[number];
|
|
61
63
|
declare const ExecStartMessageSchema: z.ZodObject<{
|
|
@@ -20738,6 +20740,34 @@ declare const SystemInfoSchema: z.ZodObject<{
|
|
|
20738
20740
|
}, z.core.$strip>>;
|
|
20739
20741
|
}, z.core.$strip>;
|
|
20740
20742
|
type SystemInfo = z.infer<typeof SystemInfoSchema>;
|
|
20743
|
+
declare const SystemFeaturesInfoSchema: z.ZodObject<{
|
|
20744
|
+
version: z.ZodString;
|
|
20745
|
+
features: z.ZodObject<{
|
|
20746
|
+
sessionOffsets: z.ZodBoolean;
|
|
20747
|
+
leases: z.ZodBoolean;
|
|
20748
|
+
grantableTokens: z.ZodOptional<z.ZodBoolean>;
|
|
20749
|
+
secretRebind: z.ZodOptional<z.ZodBoolean>;
|
|
20750
|
+
tokenUpdate: z.ZodOptional<z.ZodBoolean>;
|
|
20751
|
+
tokenImageAdd: z.ZodOptional<z.ZodBoolean>;
|
|
20752
|
+
databaseCopy: z.ZodOptional<z.ZodBoolean>;
|
|
20753
|
+
imageBuildStream: z.ZodOptional<z.ZodBoolean>;
|
|
20754
|
+
imageOpStream: z.ZodOptional<z.ZodBoolean>;
|
|
20755
|
+
imageBuilds: z.ZodOptional<z.ZodBoolean>;
|
|
20756
|
+
execRequire: z.ZodOptional<z.ZodBoolean>;
|
|
20757
|
+
oauthGrants: z.ZodOptional<z.ZodBoolean>;
|
|
20758
|
+
secretFilesGc: z.ZodOptional<z.ZodBoolean>;
|
|
20759
|
+
sessionLog: z.ZodOptional<z.ZodBoolean>;
|
|
20760
|
+
publicEgress: z.ZodOptional<z.ZodBoolean>;
|
|
20761
|
+
oauthSecrets: z.ZodOptional<z.ZodBoolean>;
|
|
20762
|
+
secretUpstream: z.ZodOptional<z.ZodBoolean>;
|
|
20763
|
+
backupOptOut: z.ZodOptional<z.ZodBoolean>;
|
|
20764
|
+
brokerRefusals: z.ZodOptional<z.ZodBoolean>;
|
|
20765
|
+
grantFilters: z.ZodOptional<z.ZodBoolean>;
|
|
20766
|
+
readOnlyFiles: z.ZodOptional<z.ZodBoolean>;
|
|
20767
|
+
execDropSysAdmin: z.ZodOptional<z.ZodBoolean>;
|
|
20768
|
+
}, z.core.$strip>;
|
|
20769
|
+
}, z.core.$strip>;
|
|
20770
|
+
type SystemFeaturesInfo = z.infer<typeof SystemFeaturesInfoSchema>;
|
|
20741
20771
|
//#endregion
|
|
20742
20772
|
//#region ../api/src/schemas/token-schema.d.ts
|
|
20743
20773
|
declare const ScopeSchema: z.ZodEnum<{
|
|
@@ -20953,13 +20983,113 @@ interface ImpClient extends RpcClient {
|
|
|
20953
20983
|
}
|
|
20954
20984
|
export declare function createImpClient(options: Readonly<ImpClientOptions>): ImpClient;
|
|
20955
20985
|
//#endregion
|
|
20986
|
+
//#region src/exec/open-tool-exec.d.ts
|
|
20987
|
+
interface ToolExec {
|
|
20988
|
+
readonly writeStdin: (data: Uint8Array) => Promise<void>;
|
|
20989
|
+
readonly endStdin: () => void;
|
|
20990
|
+
readonly waitExit: () => Promise<number>;
|
|
20991
|
+
readonly close: () => void;
|
|
20992
|
+
}
|
|
20993
|
+
interface ToolExecOptions {
|
|
20994
|
+
readonly baseUrl: string;
|
|
20995
|
+
readonly token: string | null;
|
|
20996
|
+
readonly name: string;
|
|
20997
|
+
readonly tool: ExecTool;
|
|
20998
|
+
readonly args: readonly string[];
|
|
20999
|
+
readonly onStdout: (data: Uint8Array) => Promise<void>;
|
|
21000
|
+
readonly onStderr: (data: Uint8Array) => void;
|
|
21001
|
+
readonly connect: (url: string, headers: Readonly<Record<string, string>>) => ExecSocket;
|
|
21002
|
+
}
|
|
21003
|
+
export declare function openToolExec(options: ToolExecOptions): Promise<ToolExec>;
|
|
21004
|
+
//#endregion
|
|
20956
21005
|
//#region src/unknown-procedure-error.d.ts
|
|
20957
21006
|
export declare class UnknownProcedureError extends Error {
|
|
20958
21007
|
readonly procedure: string;
|
|
20959
21008
|
constructor(procedure: string);
|
|
20960
21009
|
}
|
|
20961
21010
|
//#endregion
|
|
20962
|
-
//#region src/
|
|
21011
|
+
//#region src/resolve-impd-web-socket-url.d.ts
|
|
21012
|
+
export declare function resolveImpdWebSocketUrl(base: string, path: string): URL;
|
|
21013
|
+
//#endregion
|
|
21014
|
+
//#region src/types.d.ts
|
|
21015
|
+
interface CallOptions {
|
|
21016
|
+
readonly signal?: AbortSignal;
|
|
21017
|
+
}
|
|
21018
|
+
//#endregion
|
|
21019
|
+
//#region src/events/watch-events.d.ts
|
|
21020
|
+
interface EventSource {
|
|
21021
|
+
readonly events: {
|
|
21022
|
+
readonly stream: (input?: undefined, options?: CallOptions) => Promise<AsyncIterable<ImpEvent>>;
|
|
21023
|
+
};
|
|
21024
|
+
}
|
|
21025
|
+
interface WatchEventsOptions {
|
|
21026
|
+
readonly onEvent: (event: ImpEvent) => Promise<void> | void;
|
|
21027
|
+
readonly name?: string;
|
|
21028
|
+
readonly signal?: AbortSignal;
|
|
21029
|
+
readonly onOpen?: (attempt: number) => Promise<void> | void;
|
|
21030
|
+
readonly reconnect?: WatchReconnect;
|
|
21031
|
+
}
|
|
21032
|
+
interface WatchReconnect {
|
|
21033
|
+
readonly delayMs: number;
|
|
21034
|
+
readonly shouldRetry?: (error: unknown) => boolean;
|
|
21035
|
+
}
|
|
21036
|
+
export declare function watchEvents(client: EventSource, options: Readonly<WatchEventsOptions>): Promise<void>;
|
|
21037
|
+
//#endregion
|
|
21038
|
+
//#region src/require-features.d.ts
|
|
21039
|
+
type ImpdFeatures = SystemFeaturesInfo['features'];
|
|
21040
|
+
type ImpdFeature = keyof ImpdFeatures;
|
|
21041
|
+
interface FeatureSource {
|
|
21042
|
+
readonly system: {
|
|
21043
|
+
readonly features: (input?: undefined, options?: CallOptions) => Promise<SystemFeaturesInfo>;
|
|
21044
|
+
readonly info: (input?: undefined, options?: CallOptions) => Promise<SystemInfo>;
|
|
21045
|
+
};
|
|
21046
|
+
}
|
|
21047
|
+
type FeatureNeeds = Partial<Readonly<Record<ImpdFeature, string>>>;
|
|
21048
|
+
export declare class MissingFeatureError extends Error {
|
|
21049
|
+
name: string;
|
|
21050
|
+
readonly feature: ImpdFeature;
|
|
21051
|
+
readonly gap: string;
|
|
21052
|
+
readonly outcome: string;
|
|
21053
|
+
constructor(feature: ImpdFeature, gap: string, outcome: string);
|
|
21054
|
+
}
|
|
21055
|
+
export declare function requireFeatures(client: FeatureSource, needs: FeatureNeeds, options?: CallOptions): Promise<void>;
|
|
21056
|
+
export declare function readFeatures(client: FeatureSource, options?: CallOptions): Promise<Partial<ImpdFeatures>>;
|
|
21057
|
+
export declare function findMissingFeatures(info: Pick<SystemInfo, 'features'>, wanted: readonly ImpdFeature[]): ImpdFeature[];
|
|
21058
|
+
//#endregion
|
|
21059
|
+
//#region src/tunnel/open-forward-tunnel.d.ts
|
|
21060
|
+
type ForwardTunnelEnd = {
|
|
21061
|
+
readonly kind: 'done';
|
|
21062
|
+
} | {
|
|
21063
|
+
readonly kind: 'unreachable';
|
|
21064
|
+
} | {
|
|
21065
|
+
readonly kind: 'failed';
|
|
21066
|
+
readonly code: string | null;
|
|
21067
|
+
readonly message: string;
|
|
21068
|
+
} | {
|
|
21069
|
+
readonly kind: 'closed';
|
|
21070
|
+
readonly code: number;
|
|
21071
|
+
};
|
|
21072
|
+
interface ForwardTunnelOptions {
|
|
21073
|
+
readonly baseUrl: string;
|
|
21074
|
+
readonly token: string | null;
|
|
21075
|
+
readonly name: string;
|
|
21076
|
+
readonly port: number;
|
|
21077
|
+
readonly connect: (url: string, headers: Readonly<Record<string, string>>) => WebSocket;
|
|
21078
|
+
readonly onOpened: () => void;
|
|
21079
|
+
readonly onData: (data: Uint8Array) => Promise<void> | void;
|
|
21080
|
+
readonly onEof: () => void;
|
|
21081
|
+
readonly onEnd: (end: ForwardTunnelEnd) => void;
|
|
21082
|
+
}
|
|
21083
|
+
interface ForwardTunnel {
|
|
21084
|
+
readonly send: (data: Uint8Array) => boolean;
|
|
21085
|
+
readonly waitForRoom: () => Promise<void>;
|
|
21086
|
+
readonly countUnackedBytes: () => number;
|
|
21087
|
+
readonly sendEof: () => void;
|
|
21088
|
+
readonly close: () => void;
|
|
21089
|
+
}
|
|
21090
|
+
export declare function openForwardTunnel(options: Readonly<ForwardTunnelOptions>): ForwardTunnel;
|
|
21091
|
+
//#endregion
|
|
21092
|
+
//#region src/tunnel/open-reverse-forward.d.ts
|
|
20963
21093
|
type ReverseGuest = {
|
|
20964
21094
|
readonly network: 'unix';
|
|
20965
21095
|
readonly path: Exclude<TunnelListen['path'], undefined>;
|
|
@@ -21040,4 +21170,4 @@ export declare class NoSessionError extends ExecError {
|
|
|
21040
21170
|
constructor(message: string, data: NoSessionData | undefined);
|
|
21041
21171
|
}
|
|
21042
21172
|
//#endregion
|
|
21043
|
-
export { type ApiCall, type AttachOptions, type BuildContext, type BuildImageOptions, type Checkpoint, type ColdBoot, type ColdBootCause, type ConsoleOptions, type DetachReason, type ExecClientErrorCode, type ExecExit, type ExecHandle, type ExecOptions, type ExecOutcome, type ExecRequirement, type ExecSession, type ExecSessionOptions, type ExecSocket, type ExecStarted, type Identity, type Image, type ImageBuildPhase, type ImageBuildProgress, type Imp, type ImpClient, type ImpClientOptions, type ImpEvent, type ImpState, type InvalidResumeData, type InvalidStateData, type NoSessionData, ORPCError, type PreviousGeneration, type RequireAwakeOptions, type ResumeFrom, type ResumeResult, type ReverseForward, type ReverseForwardEnd, type ReverseForwardOptions, type ReverseGuest, type ReverseListening, type ReverseRelay, type ReverseRelayHandlers, type RunOptions, type RunResult, type Scope, type ServerCheck, type Session, type SessionLog, type SessionLogRead, type SessionOutput, type SshKey, type SystemInfo, type Token, isDefinedError, safe };
|
|
21173
|
+
export { type ApiCall, type AttachOptions, type BuildContext, type BuildImageOptions, type Checkpoint, type ColdBoot, type ColdBootCause, type ConsoleOptions, type DetachReason, type EventSource, type ExecClientErrorCode, type ExecExit, type ExecHandle, type ExecOptions, type ExecOutcome, type ExecRequirement, type ExecSession, type ExecSessionOptions, type ExecSocket, type ExecStarted, type FeatureNeeds, type FeatureSource, type ForwardTunnel, type ForwardTunnelEnd, type ForwardTunnelOptions, type Identity, type Image, type ImageBuildPhase, type ImageBuildProgress, type Imp, type ImpClient, type ImpClientOptions, type ImpEvent, type ImpState, type ImpdFeature, type ImpdFeatures, type InvalidResumeData, type InvalidStateData, type NoSessionData, ORPCError, type PreviousGeneration, type RequireAwakeOptions, type ResumeFrom, type ResumeResult, type ReverseForward, type ReverseForwardEnd, type ReverseForwardOptions, type ReverseGuest, type ReverseListening, type ReverseRelay, type ReverseRelayHandlers, type RunOptions, type RunResult, type Scope, type ServerCheck, type Session, type SessionLog, type SessionLogRead, type SessionOutput, type SshKey, type SystemInfo, type Token, type ToolExec, type ToolExecOptions, type WatchEventsOptions, type WatchReconnect, isDefinedError, safe };
|
package/dist/index.js
CHANGED
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
import { ORPCError, ORPCError as ORPCError$1, createORPCClient, isDefinedError, safe } from "@orpc/client";
|
|
2
2
|
import { RPCLink } from "@orpc/client/fetch";
|
|
3
3
|
import * as z from "zod";
|
|
4
|
+
import { P, match } from "ts-pattern";
|
|
5
|
+
import pRetry, { AbortError } from "p-retry";
|
|
4
6
|
//#endregion
|
|
5
7
|
//#region src/check-server.ts
|
|
6
|
-
const CLIENT_VERSION = "2.
|
|
8
|
+
const CLIENT_VERSION = "2.5.0";
|
|
7
9
|
async function checkServer(rpc) {
|
|
8
10
|
const info = await rpc.system.info();
|
|
9
11
|
return {
|
|
@@ -205,6 +207,7 @@ const EXEC_CHANNELS = {
|
|
|
205
207
|
const DimensionSchema = z.int().min(1).max(65535);
|
|
206
208
|
const EXEC_TOOLS = ["tar"];
|
|
207
209
|
const EXEC_REQUIREMENTS = ["broker"];
|
|
210
|
+
const EXEC_MAX_STDIN_FRAME_BYTES = 65536;
|
|
208
211
|
const EXEC_HIGH_WATER_BYTES = 1048576;
|
|
209
212
|
const ExecStartMessageSchema = z.object({
|
|
210
213
|
type: z.literal("start"),
|
|
@@ -910,68 +913,148 @@ var ExecError = class extends Error {
|
|
|
910
913
|
}
|
|
911
914
|
};
|
|
912
915
|
//#endregion
|
|
913
|
-
//#region src/
|
|
914
|
-
|
|
915
|
-
const
|
|
916
|
-
|
|
917
|
-
|
|
916
|
+
//#region src/create-rpc-client.ts
|
|
917
|
+
function createRpcClient(options) {
|
|
918
|
+
const customFetch = options.fetch;
|
|
919
|
+
return createORPCClient(new RPCLink({
|
|
920
|
+
url: resolveImpdUrl(options.url, "/rpc").href,
|
|
921
|
+
headers: options.token === null ? {} : { authorization: `Bearer ${options.token}` },
|
|
922
|
+
fetch: async (request, init) => {
|
|
923
|
+
const response = await (customFetch === void 0 ? fetch(request, init) : customFetch(request));
|
|
924
|
+
if (response.ok || isJson(response.headers.get("content-type"))) return response;
|
|
925
|
+
await response.body?.cancel();
|
|
926
|
+
throw new ORPCError$1("UNEXPECTED_ANSWER", {
|
|
927
|
+
status: response.status,
|
|
928
|
+
message: `impd answered with ${String(response.status)}`
|
|
929
|
+
});
|
|
930
|
+
}
|
|
931
|
+
}));
|
|
932
|
+
}
|
|
933
|
+
function isJson(contentType) {
|
|
934
|
+
return (contentType ?? "").startsWith("application/json");
|
|
935
|
+
}
|
|
936
|
+
//#endregion
|
|
937
|
+
//#region src/resolve-impd-web-socket-url.ts
|
|
938
|
+
function resolveImpdWebSocketUrl(base, path) {
|
|
939
|
+
const url = resolveImpdUrl(base, path);
|
|
940
|
+
url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
|
|
941
|
+
return url;
|
|
942
|
+
}
|
|
943
|
+
//#endregion
|
|
944
|
+
//#region src/unknown-procedure-error.ts
|
|
945
|
+
var UnknownProcedureError = class extends Error {
|
|
946
|
+
procedure;
|
|
947
|
+
constructor(procedure) {
|
|
948
|
+
super(`impd has no procedure ${procedure}`);
|
|
949
|
+
this.name = "UnknownProcedureError";
|
|
950
|
+
this.procedure = procedure;
|
|
951
|
+
}
|
|
918
952
|
};
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
953
|
+
//#endregion
|
|
954
|
+
//#region src/require-features.ts
|
|
955
|
+
const FEATURE_GAPS = {
|
|
956
|
+
sessionOffsets: "has no session offsets",
|
|
957
|
+
leases: "has no leases",
|
|
958
|
+
grantableTokens: "is older than 0.27.0",
|
|
959
|
+
secretRebind: "is older than 0.27.0",
|
|
960
|
+
tokenUpdate: "is older than 0.34.0",
|
|
961
|
+
tokenImageAdd: "has no token image adds",
|
|
962
|
+
databaseCopy: "is older than 0.30.0",
|
|
963
|
+
imageBuildStream: "has no build stream",
|
|
964
|
+
imageOpStream: "has no image add or build streams",
|
|
965
|
+
imageBuilds: "has no list of running image builds",
|
|
966
|
+
execRequire: "is older than 0.30.0",
|
|
967
|
+
oauthGrants: "has no oauth grants",
|
|
968
|
+
secretFilesGc: "has no gc of secret files",
|
|
969
|
+
sessionLog: "has no session logs",
|
|
970
|
+
publicEgress: "is older than 0.35.0",
|
|
971
|
+
oauthSecrets: "has no oauth secrets",
|
|
972
|
+
secretUpstream: "has no secret upstreams",
|
|
973
|
+
backupOptOut: "has no backup opt-out",
|
|
974
|
+
brokerRefusals: "has no audit of refused broker requests",
|
|
975
|
+
grantFilters: "has no grant filters",
|
|
976
|
+
readOnlyFiles: "has no read-only files",
|
|
977
|
+
execDropSysAdmin: "cannot drop CAP_SYS_ADMIN from a command"
|
|
978
|
+
};
|
|
979
|
+
var MissingFeatureError = class extends Error {
|
|
980
|
+
name = "MissingFeatureError";
|
|
981
|
+
feature;
|
|
982
|
+
gap;
|
|
983
|
+
outcome;
|
|
984
|
+
constructor(feature, gap, outcome) {
|
|
985
|
+
super(`this impd ${gap} and would ${outcome}; nothing was changed`);
|
|
986
|
+
this.feature = feature;
|
|
987
|
+
this.gap = gap;
|
|
988
|
+
this.outcome = outcome;
|
|
989
|
+
}
|
|
990
|
+
};
|
|
991
|
+
async function requireFeatures(client, needs, options = {}) {
|
|
992
|
+
if (Object.keys(needs).length === 0) return;
|
|
993
|
+
const features = await readFeatures(client, options);
|
|
994
|
+
for (const [feature, outcome] of Object.entries(needs)) if (isImpdFeature(feature) && outcome !== void 0 && features[feature] !== true) throw new MissingFeatureError(feature, FEATURE_GAPS[feature], outcome);
|
|
995
|
+
}
|
|
996
|
+
async function readFeatures(client, options = {}) {
|
|
926
997
|
try {
|
|
927
|
-
|
|
928
|
-
method: "POST",
|
|
929
|
-
headers: token === null ? {} : { authorization: `Bearer ${token}` },
|
|
930
|
-
signal: AbortSignal.timeout(CHECK_TIMEOUT_MS$1)
|
|
931
|
-
}));
|
|
998
|
+
return (await client.system.features(void 0, options)).features ?? {};
|
|
932
999
|
} catch (error) {
|
|
1000
|
+
if (!isMissingProcedure(error)) throw error;
|
|
1001
|
+
}
|
|
1002
|
+
return (await client.system.info(void 0, options)).features ?? {};
|
|
1003
|
+
}
|
|
1004
|
+
function findMissingFeatures(info, wanted) {
|
|
1005
|
+
return wanted.filter((feature) => info.features?.[feature] !== true);
|
|
1006
|
+
}
|
|
1007
|
+
function isMissingProcedure(error) {
|
|
1008
|
+
return error instanceof UnknownProcedureError || error instanceof ORPCError$1 && error.status === 404;
|
|
1009
|
+
}
|
|
1010
|
+
function isImpdFeature(key) {
|
|
1011
|
+
return Object.hasOwn(FEATURE_GAPS, key);
|
|
1012
|
+
}
|
|
1013
|
+
//#endregion
|
|
1014
|
+
//#region src/exec/check-exec-features.ts
|
|
1015
|
+
const CHECK_TIMEOUT_MS$1 = 5e3;
|
|
1016
|
+
async function checkExecFeatures(rpc, needs) {
|
|
1017
|
+
try {
|
|
1018
|
+
await requireFeatures(rpc, needs, { signal: AbortSignal.timeout(CHECK_TIMEOUT_MS$1) });
|
|
1019
|
+
return null;
|
|
1020
|
+
} catch (error) {
|
|
1021
|
+
return buildRefusal(error);
|
|
1022
|
+
}
|
|
1023
|
+
}
|
|
1024
|
+
function buildRefusal(error) {
|
|
1025
|
+
if (error instanceof MissingFeatureError) {
|
|
1026
|
+
const detail = `this impd ${error.gap} and would ${error.outcome}`;
|
|
933
1027
|
return {
|
|
934
|
-
kind: "
|
|
935
|
-
|
|
1028
|
+
kind: "failed",
|
|
1029
|
+
code: "PRECONDITION_FAILED",
|
|
1030
|
+
message: `nothing was started: ${detail}`,
|
|
1031
|
+
data: {
|
|
1032
|
+
reason: "impd_outdated",
|
|
1033
|
+
detail
|
|
1034
|
+
}
|
|
936
1035
|
};
|
|
937
1036
|
}
|
|
938
|
-
if (
|
|
939
|
-
|
|
940
|
-
return { kind: "unauthorized" };
|
|
941
|
-
}
|
|
942
|
-
const body = await response.json().catch(() => null);
|
|
943
|
-
const parsed = InfoAnswerSchema.safeParse(body);
|
|
944
|
-
if (!response.ok || !parsed.success) return {
|
|
1037
|
+
if (error instanceof ORPCError$1 && error.status === 401) return { kind: "unauthorized" };
|
|
1038
|
+
if (error instanceof ORPCError$1) return {
|
|
945
1039
|
kind: "failed",
|
|
946
1040
|
code: null,
|
|
947
|
-
message: `impd answered
|
|
1041
|
+
message: `impd answered the feature check with ${String(error.status)}; nothing was started`
|
|
948
1042
|
};
|
|
949
|
-
if (parsed.data.json.features?.[feature] === true) return null;
|
|
950
|
-
const detail = EXEC_FEATURE_GAPS[feature];
|
|
951
1043
|
return {
|
|
952
|
-
kind: "
|
|
953
|
-
|
|
954
|
-
message: `nothing was started: ${detail}`,
|
|
955
|
-
data: {
|
|
956
|
-
reason: "impd_outdated",
|
|
957
|
-
detail
|
|
958
|
-
}
|
|
1044
|
+
kind: "unreachable",
|
|
1045
|
+
detail: `feature check: ${error instanceof Error ? error.message : String(error)}`
|
|
959
1046
|
};
|
|
960
1047
|
}
|
|
961
1048
|
//#endregion
|
|
962
1049
|
//#region src/exec/check-impd-access.ts
|
|
963
1050
|
const CHECK_TIMEOUT_MS = 5e3;
|
|
964
|
-
async function checkImpdAccess(
|
|
1051
|
+
async function checkImpdAccess(rpc) {
|
|
965
1052
|
try {
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
await response.body?.cancel();
|
|
972
|
-
return response.status === 401 ? "unauthorized" : "reachable";
|
|
973
|
-
} catch {
|
|
974
|
-
return "unreachable";
|
|
1053
|
+
await rpc.system.features(void 0, { signal: AbortSignal.timeout(CHECK_TIMEOUT_MS) });
|
|
1054
|
+
return "reachable";
|
|
1055
|
+
} catch (error) {
|
|
1056
|
+
if (!(error instanceof ORPCError$1)) return "unreachable";
|
|
1057
|
+
return error.status === 401 ? "unauthorized" : "reachable";
|
|
975
1058
|
}
|
|
976
1059
|
}
|
|
977
1060
|
//#endregion
|
|
@@ -982,11 +1065,15 @@ var BadMessageError = class extends Error {
|
|
|
982
1065
|
name = "BadMessageError";
|
|
983
1066
|
};
|
|
984
1067
|
function openExecSession(options) {
|
|
985
|
-
const url =
|
|
986
|
-
url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
|
|
1068
|
+
const url = resolveImpdWebSocketUrl(options.baseUrl, EXEC_PATH);
|
|
987
1069
|
if (options.ticket !== void 0) url.searchParams.set(EXEC_TICKET_PARAM, options.ticket);
|
|
988
1070
|
const headers = options.token === null ? {} : { authorization: `Bearer ${options.token}` };
|
|
989
1071
|
const ws = options.connect(url.href, headers);
|
|
1072
|
+
const rpc = createRpcClient({
|
|
1073
|
+
url: options.baseUrl,
|
|
1074
|
+
token: options.token,
|
|
1075
|
+
...options.fetch !== void 0 && { fetch: options.fetch }
|
|
1076
|
+
});
|
|
990
1077
|
const outcome = Promise.withResolvers();
|
|
991
1078
|
const state = {
|
|
992
1079
|
opened: false,
|
|
@@ -1044,45 +1131,48 @@ function openExecSession(options) {
|
|
|
1044
1131
|
const parsed = ExecServerMessageSchema.safeParse(json);
|
|
1045
1132
|
if (!parsed.success) throw new BadMessageError(`unknown message: ${text.slice(0, 80)}`);
|
|
1046
1133
|
const message = parsed.data;
|
|
1047
|
-
|
|
1134
|
+
match(message).with({ type: "started" }, (start) => {
|
|
1048
1135
|
if (state.started) return;
|
|
1049
1136
|
state.started = true;
|
|
1050
1137
|
options.onStarted({
|
|
1051
|
-
pid:
|
|
1052
|
-
session:
|
|
1053
|
-
created:
|
|
1054
|
-
groupKill:
|
|
1055
|
-
output:
|
|
1138
|
+
pid: start.pid,
|
|
1139
|
+
session: start.session ?? null,
|
|
1140
|
+
created: start.created ?? false,
|
|
1141
|
+
groupKill: start.groupKill ?? false,
|
|
1142
|
+
output: start.output ?? { continuity: "none" }
|
|
1056
1143
|
});
|
|
1057
|
-
}
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1144
|
+
}).with({ type: "exit" }, (exit) => {
|
|
1145
|
+
resolveOutcome({
|
|
1146
|
+
kind: "exit",
|
|
1147
|
+
code: exit.code,
|
|
1148
|
+
signal: exit.signal,
|
|
1149
|
+
...exit.offset !== void 0 && { offset: exit.offset }
|
|
1150
|
+
});
|
|
1151
|
+
}).with({ type: "detached" }, (detached) => {
|
|
1152
|
+
resolveOutcome({
|
|
1153
|
+
kind: "detached",
|
|
1154
|
+
reason: detached.reason,
|
|
1155
|
+
...detached.offset !== void 0 && { offset: detached.offset }
|
|
1156
|
+
});
|
|
1157
|
+
}).with({ type: "stdin_ack" }, () => {}).with({ type: "error" }, (failure) => {
|
|
1158
|
+
resolveOutcome({
|
|
1159
|
+
kind: "failed",
|
|
1160
|
+
code: failure.code ?? null,
|
|
1161
|
+
message: failure.message,
|
|
1162
|
+
...failure.data !== void 0 && { data: failure.data }
|
|
1163
|
+
});
|
|
1164
|
+
}).exhaustive();
|
|
1074
1165
|
};
|
|
1075
1166
|
const sendOpen = async () => {
|
|
1076
1167
|
const start = options.start;
|
|
1077
|
-
const
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
}
|
|
1168
|
+
const needs = {
|
|
1169
|
+
..."argv" in start && start.require !== void 0 && start.require.length > 0 && { execRequire: "run the command without checking its requirements" },
|
|
1170
|
+
..."argv" in start && start.dropSysAdmin === true && { execDropSysAdmin: "run the command with CAP_SYS_ADMIN" }
|
|
1171
|
+
};
|
|
1172
|
+
const refusal = await checkExecFeatures(rpc, needs);
|
|
1173
|
+
if (refusal !== null) {
|
|
1174
|
+
resolveOutcome(refusal);
|
|
1175
|
+
return;
|
|
1086
1176
|
}
|
|
1087
1177
|
if (state.finished || ws.readyState !== WebSocket.OPEN) return;
|
|
1088
1178
|
ws.send(JSON.stringify(buildOpenMessage(start)));
|
|
@@ -1114,7 +1204,7 @@ function openExecSession(options) {
|
|
|
1114
1204
|
const resolveRefusal = async (reason) => {
|
|
1115
1205
|
if (state.refused) return;
|
|
1116
1206
|
state.refused = true;
|
|
1117
|
-
const access = await checkImpdAccess(
|
|
1207
|
+
const access = await checkImpdAccess(rpc);
|
|
1118
1208
|
if (access === "unauthorized") resolveOutcome({ kind: "unauthorized" });
|
|
1119
1209
|
else if (access === "reachable" && options.ticket !== void 0) resolveOutcome({
|
|
1120
1210
|
kind: "unauthorized",
|
|
@@ -1221,16 +1311,12 @@ var NoSessionError = class extends ExecError {
|
|
|
1221
1311
|
//#endregion
|
|
1222
1312
|
//#region src/exec/to-exec-error.ts
|
|
1223
1313
|
function toExecError(outcome) {
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
} });
|
|
1231
|
-
if (outcome.kind === "closed") return outcome.closeCode === 1012 ? new ExecError("RESTARTING", "impd is restarting") : new ExecError("CONNECTION_CLOSED", `exec connection closed (${outcome.reason})`);
|
|
1232
|
-
if (outcome.kind === "bad_message") return new ExecError("BAD_MESSAGE", `bad message from impd: ${outcome.detail}`);
|
|
1233
|
-
return new ExecError("LOCAL_ERROR", "an output handler threw", { cause: outcome.error });
|
|
1314
|
+
return match(outcome).with({ kind: "failed" }, (failed) => toFailedError(failed.code, failed.message, failed.data)).with({ kind: "unauthorized" }, (refused) => {
|
|
1315
|
+
return new ExecError("UNAUTHORIZED", refused.ticketRefused === true ? "impd refused the exec ticket: it expired (30 s) or was used already" : "impd rejected the token");
|
|
1316
|
+
}).with({ kind: "unreachable" }, (unreachable) => new ExecError("UNREACHABLE", `cannot reach impd (${unreachable.detail})`)).with({ kind: "detached" }, (detached) => new ExecError("DETACHED", `detached from the session (${detached.reason})`, { data: {
|
|
1317
|
+
reason: detached.reason,
|
|
1318
|
+
...detached.offset !== void 0 && { offset: detached.offset }
|
|
1319
|
+
} })).with({ kind: "closed" }, (closed) => closed.closeCode === 1012 ? new ExecError("RESTARTING", "impd is restarting") : new ExecError("CONNECTION_CLOSED", `exec connection closed (${closed.reason})`)).with({ kind: "bad_message" }, (bad) => new ExecError("BAD_MESSAGE", `bad message from impd: ${bad.detail}`)).with({ kind: "local_error" }, (local) => new ExecError("LOCAL_ERROR", "an output handler threw", { cause: local.error })).exhaustive();
|
|
1234
1320
|
}
|
|
1235
1321
|
function toFailedError(code, message, data) {
|
|
1236
1322
|
if (code === "NO_SESSION") {
|
|
@@ -1512,31 +1598,38 @@ async function requireAwake(rpc, name, options = {}) {
|
|
|
1512
1598
|
name,
|
|
1513
1599
|
restartError: options.restartError === true
|
|
1514
1600
|
};
|
|
1515
|
-
|
|
1516
|
-
|
|
1601
|
+
const wake = async () => {
|
|
1602
|
+
try {
|
|
1603
|
+
return await rpc.imps.wake(input, callOptions);
|
|
1604
|
+
} catch (error) {
|
|
1605
|
+
throw new WakeFailureError(error);
|
|
1606
|
+
}
|
|
1607
|
+
};
|
|
1608
|
+
try {
|
|
1609
|
+
return await pRetry(wake, {
|
|
1610
|
+
retries: retry.attempts,
|
|
1611
|
+
minTimeout: retry.delayMs,
|
|
1612
|
+
factor: 1,
|
|
1613
|
+
...signal !== void 0 && { signal },
|
|
1614
|
+
shouldRetry: (context) => context.error instanceof WakeFailureError && isUnavailable(context.error.failure)
|
|
1615
|
+
});
|
|
1517
1616
|
} catch (error) {
|
|
1518
|
-
|
|
1519
|
-
await waitFor(retry.delayMs, signal);
|
|
1617
|
+
throw error instanceof WakeFailureError ? error.failure : error;
|
|
1520
1618
|
}
|
|
1521
1619
|
}
|
|
1620
|
+
var WakeFailureError = class extends Error {
|
|
1621
|
+
name = "WakeFailureError";
|
|
1622
|
+
failure;
|
|
1623
|
+
constructor(failure) {
|
|
1624
|
+
const message = failure instanceof Error ? failure.message : String(failure);
|
|
1625
|
+
super(message);
|
|
1626
|
+
this.failure = failure;
|
|
1627
|
+
}
|
|
1628
|
+
};
|
|
1522
1629
|
function isUnavailable(error) {
|
|
1523
1630
|
if (error instanceof ORPCError$1) return error.code === "SERVICE_UNAVAILABLE";
|
|
1524
1631
|
return error instanceof TypeError;
|
|
1525
1632
|
}
|
|
1526
|
-
function waitFor(ms, signal) {
|
|
1527
|
-
signal?.throwIfAborted();
|
|
1528
|
-
const done = Promise.withResolvers();
|
|
1529
|
-
const onAbort = () => {
|
|
1530
|
-
clearTimeout(timer);
|
|
1531
|
-
done.reject(signal?.reason);
|
|
1532
|
-
};
|
|
1533
|
-
const timer = setTimeout(() => {
|
|
1534
|
-
signal?.removeEventListener("abort", onAbort);
|
|
1535
|
-
done.resolve();
|
|
1536
|
-
}, ms);
|
|
1537
|
-
signal?.addEventListener("abort", onAbort, { once: true });
|
|
1538
|
-
return done.promise;
|
|
1539
|
-
}
|
|
1540
1633
|
//#endregion
|
|
1541
1634
|
//#region src/send-long-call.ts
|
|
1542
1635
|
const HOUR_MS = 36e5;
|
|
@@ -1582,16 +1675,6 @@ function formatHours(ms) {
|
|
|
1582
1675
|
return hours === 1 ? "an hour" : `${String(hours)} hours`;
|
|
1583
1676
|
}
|
|
1584
1677
|
//#endregion
|
|
1585
|
-
//#region src/unknown-procedure-error.ts
|
|
1586
|
-
var UnknownProcedureError = class extends Error {
|
|
1587
|
-
procedure;
|
|
1588
|
-
constructor(procedure) {
|
|
1589
|
-
super(`impd has no procedure ${procedure}`);
|
|
1590
|
-
this.name = "UnknownProcedureError";
|
|
1591
|
-
this.procedure = procedure;
|
|
1592
|
-
}
|
|
1593
|
-
};
|
|
1594
|
-
//#endregion
|
|
1595
1678
|
//#region src/create-imp-client.ts
|
|
1596
1679
|
function createImpClient(options) {
|
|
1597
1680
|
const token = options.token;
|
|
@@ -1666,8 +1749,204 @@ function isUnknownProcedure(status, contentType) {
|
|
|
1666
1749
|
return status === 404 && !(contentType ?? "").startsWith("application/json");
|
|
1667
1750
|
}
|
|
1668
1751
|
//#endregion
|
|
1669
|
-
//#region src/
|
|
1670
|
-
|
|
1752
|
+
//#region src/exec/open-tool-exec.ts
|
|
1753
|
+
var ToolExecError = class extends Error {
|
|
1754
|
+
name = "ToolExecError";
|
|
1755
|
+
};
|
|
1756
|
+
function parseServerMessage(text) {
|
|
1757
|
+
try {
|
|
1758
|
+
const parsed = ExecServerMessageSchema.safeParse(JSON.parse(text));
|
|
1759
|
+
return parsed.success ? parsed.data : null;
|
|
1760
|
+
} catch {
|
|
1761
|
+
return null;
|
|
1762
|
+
}
|
|
1763
|
+
}
|
|
1764
|
+
async function openToolExec(options) {
|
|
1765
|
+
const headers = options.token === null ? {} : { authorization: `Bearer ${options.token}` };
|
|
1766
|
+
const ws = options.connect(resolveImpdWebSocketUrl(options.baseUrl, EXEC_PATH).href, headers);
|
|
1767
|
+
const started = Promise.withResolvers();
|
|
1768
|
+
const exited = Promise.withResolvers();
|
|
1769
|
+
const waiter = { wake: null };
|
|
1770
|
+
const state = {
|
|
1771
|
+
unacked: 0,
|
|
1772
|
+
done: false
|
|
1773
|
+
};
|
|
1774
|
+
ws.binaryType = "arraybuffer";
|
|
1775
|
+
const sendStdoutAck = async (data) => {
|
|
1776
|
+
await options.onStdout(data);
|
|
1777
|
+
if (data.byteLength > 0 && ws.readyState === WebSocket.OPEN) {
|
|
1778
|
+
const ack = {
|
|
1779
|
+
type: "stdout_ack",
|
|
1780
|
+
bytes: data.byteLength
|
|
1781
|
+
};
|
|
1782
|
+
ws.send(JSON.stringify(ack));
|
|
1783
|
+
}
|
|
1784
|
+
};
|
|
1785
|
+
const stopWithError = (error) => {
|
|
1786
|
+
state.done = true;
|
|
1787
|
+
started.reject(error);
|
|
1788
|
+
exited.resolve({ error });
|
|
1789
|
+
waiter.wake?.();
|
|
1790
|
+
};
|
|
1791
|
+
const handleControl = (message) => {
|
|
1792
|
+
match(message).with({ type: "started" }, () => {
|
|
1793
|
+
started.resolve();
|
|
1794
|
+
}).with({ type: "stdin_ack" }, (ack) => {
|
|
1795
|
+
state.unacked -= ack.bytes;
|
|
1796
|
+
waiter.wake?.();
|
|
1797
|
+
}).with({ type: "exit" }, (exit) => {
|
|
1798
|
+
state.done = true;
|
|
1799
|
+
exited.resolve({ code: exit.code ?? 1 });
|
|
1800
|
+
waiter.wake?.();
|
|
1801
|
+
}).with({ type: "error" }, (failure) => {
|
|
1802
|
+
stopWithError(new ToolExecError(`${failure.code ?? "error"}: ${failure.message}`));
|
|
1803
|
+
}).with({ type: "detached" }, () => {
|
|
1804
|
+
stopWithError(new ToolExecError("impd detached a tool exec"));
|
|
1805
|
+
}).exhaustive();
|
|
1806
|
+
};
|
|
1807
|
+
ws.addEventListener("open", () => {
|
|
1808
|
+
const start = {
|
|
1809
|
+
type: "start",
|
|
1810
|
+
name: options.name,
|
|
1811
|
+
tool: options.tool,
|
|
1812
|
+
argv: [...options.args],
|
|
1813
|
+
tty: false
|
|
1814
|
+
};
|
|
1815
|
+
ws.send(JSON.stringify(start));
|
|
1816
|
+
});
|
|
1817
|
+
ws.addEventListener("message", (event) => {
|
|
1818
|
+
if (event.data instanceof ArrayBuffer) {
|
|
1819
|
+
const frame = decodeExecFrame(new Uint8Array(event.data));
|
|
1820
|
+
if (frame.channel === EXEC_CHANNELS.stdout) sendStdoutAck(frame.data);
|
|
1821
|
+
else if (frame.channel === EXEC_CHANNELS.stderr) options.onStderr(frame.data);
|
|
1822
|
+
return;
|
|
1823
|
+
}
|
|
1824
|
+
const message = parseServerMessage(String(event.data));
|
|
1825
|
+
if (message === null) {
|
|
1826
|
+
stopWithError(new ToolExecError("impd sent a message the client does not know"));
|
|
1827
|
+
ws.close();
|
|
1828
|
+
} else handleControl(message);
|
|
1829
|
+
});
|
|
1830
|
+
ws.addEventListener("close", () => {
|
|
1831
|
+
if (!state.done) stopWithError(new ToolExecError(`the connection to impd at ${options.baseUrl} closed`));
|
|
1832
|
+
});
|
|
1833
|
+
ws.addEventListener("error", () => {});
|
|
1834
|
+
await started.promise;
|
|
1835
|
+
const waitForWindow = async () => {
|
|
1836
|
+
while (!state.done && state.unacked > 1048576) {
|
|
1837
|
+
await new Promise((resolve) => {
|
|
1838
|
+
waiter.wake = resolve;
|
|
1839
|
+
});
|
|
1840
|
+
waiter.wake = null;
|
|
1841
|
+
}
|
|
1842
|
+
};
|
|
1843
|
+
return {
|
|
1844
|
+
writeStdin: async (data) => {
|
|
1845
|
+
for (let offset = 0; offset < data.byteLength; offset += EXEC_MAX_STDIN_FRAME_BYTES) {
|
|
1846
|
+
await waitForWindow();
|
|
1847
|
+
if (state.done) return;
|
|
1848
|
+
const slice = data.subarray(offset, offset + EXEC_MAX_STDIN_FRAME_BYTES);
|
|
1849
|
+
ws.send(encodeExecFrame(EXEC_CHANNELS.stdin, slice));
|
|
1850
|
+
state.unacked += slice.byteLength;
|
|
1851
|
+
}
|
|
1852
|
+
},
|
|
1853
|
+
endStdin: () => {
|
|
1854
|
+
if (!state.done) ws.send(JSON.stringify({ type: "stdin_eof" }));
|
|
1855
|
+
},
|
|
1856
|
+
waitExit: async () => {
|
|
1857
|
+
const outcome = await exited.promise;
|
|
1858
|
+
if ("error" in outcome) throw outcome.error;
|
|
1859
|
+
return outcome.code;
|
|
1860
|
+
},
|
|
1861
|
+
close: () => {
|
|
1862
|
+
state.done = true;
|
|
1863
|
+
ws.close();
|
|
1864
|
+
}
|
|
1865
|
+
};
|
|
1866
|
+
}
|
|
1867
|
+
//#endregion
|
|
1868
|
+
//#region src/events/watch-events.ts
|
|
1869
|
+
async function watchEvents(client, options) {
|
|
1870
|
+
const signal = options.signal;
|
|
1871
|
+
const reconnect = options.reconnect;
|
|
1872
|
+
const callOptions = signal === void 0 ? {} : { signal };
|
|
1873
|
+
const readStream = async (attempt) => {
|
|
1874
|
+
const events = (await client.events.stream(void 0, callOptions).catch((error) => {
|
|
1875
|
+
throw new StreamEndError(error);
|
|
1876
|
+
}))[Symbol.asyncIterator]();
|
|
1877
|
+
const reading = { done: false };
|
|
1878
|
+
try {
|
|
1879
|
+
await runCallback(() => options.onOpen?.(attempt));
|
|
1880
|
+
for (;;) {
|
|
1881
|
+
const next = await events.next().catch((error) => {
|
|
1882
|
+
throw new StreamEndError(error);
|
|
1883
|
+
});
|
|
1884
|
+
if (next.done === true) {
|
|
1885
|
+
reading.done = true;
|
|
1886
|
+
throw new StreamEndError(null);
|
|
1887
|
+
}
|
|
1888
|
+
if (options.name === void 0 || readEventImpName(next.value) === options.name) await runCallback(() => options.onEvent(next.value));
|
|
1889
|
+
}
|
|
1890
|
+
} finally {
|
|
1891
|
+
if (!reading.done) await disposeEvents(events);
|
|
1892
|
+
}
|
|
1893
|
+
};
|
|
1894
|
+
const shouldReconnect = (context) => {
|
|
1895
|
+
const error = context.error;
|
|
1896
|
+
const shouldRetry = reconnect?.shouldRetry ?? isNotRefused;
|
|
1897
|
+
return error instanceof StreamEndError && (error.reason === null || shouldRetry(error.reason));
|
|
1898
|
+
};
|
|
1899
|
+
try {
|
|
1900
|
+
await (reconnect === void 0 ? readStream(1) : pRetry(readStream, {
|
|
1901
|
+
retries: Number.POSITIVE_INFINITY,
|
|
1902
|
+
minTimeout: reconnect.delayMs,
|
|
1903
|
+
factor: 1,
|
|
1904
|
+
...signal !== void 0 && { signal },
|
|
1905
|
+
shouldRetry: shouldReconnect
|
|
1906
|
+
}));
|
|
1907
|
+
} catch (error) {
|
|
1908
|
+
requireCleanEnd(error, signal);
|
|
1909
|
+
}
|
|
1910
|
+
}
|
|
1911
|
+
var StreamEndError = class extends Error {
|
|
1912
|
+
name = "StreamEndError";
|
|
1913
|
+
reason;
|
|
1914
|
+
constructor(reason) {
|
|
1915
|
+
const message = reason instanceof Error ? reason.message : "the event stream ended";
|
|
1916
|
+
super(message);
|
|
1917
|
+
this.reason = reason;
|
|
1918
|
+
}
|
|
1919
|
+
};
|
|
1920
|
+
async function runCallback(run) {
|
|
1921
|
+
try {
|
|
1922
|
+
await run();
|
|
1923
|
+
} catch (error) {
|
|
1924
|
+
const failure = error instanceof Error ? error : new Error(String(error));
|
|
1925
|
+
throw new AbortError(failure);
|
|
1926
|
+
}
|
|
1927
|
+
}
|
|
1928
|
+
function readEventImpName(event) {
|
|
1929
|
+
return match(event).with({ ev: P.union("ImpAdded", "ImpChanged", "ImpRemoved") }, (changed) => changed.imp.name).with({ ev: P.union("CheckpointAdded", "CheckpointRemoved", "GovernorDecision", "AgentExec") }, (named) => named.name).exhaustive();
|
|
1930
|
+
}
|
|
1931
|
+
async function disposeEvents(events) {
|
|
1932
|
+
try {
|
|
1933
|
+
await events.return?.();
|
|
1934
|
+
} catch {}
|
|
1935
|
+
}
|
|
1936
|
+
function isNotRefused(error) {
|
|
1937
|
+
if (error instanceof UnknownProcedureError) return false;
|
|
1938
|
+
return !(error instanceof ORPCError$1 && error.status >= 400 && error.status < 500);
|
|
1939
|
+
}
|
|
1940
|
+
function requireCleanEnd(error, signal) {
|
|
1941
|
+
if (signal?.aborted === true) return;
|
|
1942
|
+
if (error instanceof AbortError) throw error.originalError;
|
|
1943
|
+
if (!(error instanceof StreamEndError)) throw error;
|
|
1944
|
+
if (error.reason instanceof Error) throw error.reason;
|
|
1945
|
+
if (error.reason !== null) throw new Error("the event stream failed", { cause: error.reason });
|
|
1946
|
+
}
|
|
1947
|
+
//#endregion
|
|
1948
|
+
//#region src/tunnel/parse-tunnel-server-message.ts
|
|
1949
|
+
function parseTunnelServerMessage(text) {
|
|
1671
1950
|
try {
|
|
1672
1951
|
const parsed = TunnelServerMessageSchema.safeParse(JSON.parse(text));
|
|
1673
1952
|
return parsed.success ? parsed.data : null;
|
|
@@ -1675,6 +1954,129 @@ function parseMessage(text) {
|
|
|
1675
1954
|
return null;
|
|
1676
1955
|
}
|
|
1677
1956
|
}
|
|
1957
|
+
//#endregion
|
|
1958
|
+
//#region src/tunnel/open-forward-tunnel.ts
|
|
1959
|
+
const CLOSE_ABNORMAL = 1006;
|
|
1960
|
+
function openForwardTunnel(options) {
|
|
1961
|
+
const url = resolveImpdWebSocketUrl(options.baseUrl, TUNNEL_PATH);
|
|
1962
|
+
const headers = options.token === null ? {} : { authorization: `Bearer ${options.token}` };
|
|
1963
|
+
const ws = options.connect(url.href, headers);
|
|
1964
|
+
const state = {
|
|
1965
|
+
opened: false,
|
|
1966
|
+
unacked: 0,
|
|
1967
|
+
isEofHeld: false,
|
|
1968
|
+
done: false
|
|
1969
|
+
};
|
|
1970
|
+
const held = [];
|
|
1971
|
+
const waiters = [];
|
|
1972
|
+
ws.binaryType = "arraybuffer";
|
|
1973
|
+
const hasRoom = () => state.opened && held.length === 0 && state.unacked <= 1048576;
|
|
1974
|
+
const wakeWaiters = () => {
|
|
1975
|
+
for (const wake of waiters.splice(0)) wake();
|
|
1976
|
+
};
|
|
1977
|
+
const sendText = (message) => {
|
|
1978
|
+
if (ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify(message));
|
|
1979
|
+
};
|
|
1980
|
+
const sendHeld = () => {
|
|
1981
|
+
if (!state.opened) return;
|
|
1982
|
+
for (;;) {
|
|
1983
|
+
const [frame] = held;
|
|
1984
|
+
if (frame === void 0 || state.unacked > 1048576) break;
|
|
1985
|
+
held.shift();
|
|
1986
|
+
ws.send(frame);
|
|
1987
|
+
state.unacked += frame.byteLength;
|
|
1988
|
+
}
|
|
1989
|
+
if (held.length === 0 && state.isEofHeld) {
|
|
1990
|
+
state.isEofHeld = false;
|
|
1991
|
+
sendText({ type: "eof" });
|
|
1992
|
+
}
|
|
1993
|
+
if (hasRoom()) wakeWaiters();
|
|
1994
|
+
};
|
|
1995
|
+
const stopTunnel = (end) => {
|
|
1996
|
+
if (state.done) return;
|
|
1997
|
+
state.done = true;
|
|
1998
|
+
wakeWaiters();
|
|
1999
|
+
if (end !== null) options.onEnd(end);
|
|
2000
|
+
};
|
|
2001
|
+
const sendAck = async (data) => {
|
|
2002
|
+
await options.onData(data);
|
|
2003
|
+
sendText({
|
|
2004
|
+
type: "ack",
|
|
2005
|
+
bytes: data.byteLength
|
|
2006
|
+
});
|
|
2007
|
+
};
|
|
2008
|
+
const handleControl = (message) => {
|
|
2009
|
+
match(message).with({ type: "opened" }, () => {
|
|
2010
|
+
state.opened = true;
|
|
2011
|
+
options.onOpened();
|
|
2012
|
+
sendHeld();
|
|
2013
|
+
}).with({ type: "eof" }, () => {
|
|
2014
|
+
options.onEof();
|
|
2015
|
+
}).with({ type: "ack" }, (ack) => {
|
|
2016
|
+
state.unacked -= ack.bytes;
|
|
2017
|
+
sendHeld();
|
|
2018
|
+
}).with({ type: "error" }, (failure) => {
|
|
2019
|
+
stopTunnel({
|
|
2020
|
+
kind: "failed",
|
|
2021
|
+
code: failure.code ?? null,
|
|
2022
|
+
message: failure.message
|
|
2023
|
+
});
|
|
2024
|
+
ws.close(TUNNEL_CLOSE_NORMAL, "tunnel failed");
|
|
2025
|
+
}).with({ type: P.union("listening", "connection") }, () => {
|
|
2026
|
+
ws.close(TUNNEL_CLOSE_PROTOCOL, "bad message");
|
|
2027
|
+
}).exhaustive();
|
|
2028
|
+
};
|
|
2029
|
+
ws.addEventListener("open", () => {
|
|
2030
|
+
sendText({
|
|
2031
|
+
type: "open",
|
|
2032
|
+
name: options.name,
|
|
2033
|
+
port: options.port
|
|
2034
|
+
});
|
|
2035
|
+
});
|
|
2036
|
+
ws.addEventListener("message", (event) => {
|
|
2037
|
+
if (state.done) return;
|
|
2038
|
+
if (event.data instanceof ArrayBuffer) {
|
|
2039
|
+
sendAck(new Uint8Array(event.data));
|
|
2040
|
+
return;
|
|
2041
|
+
}
|
|
2042
|
+
const message = parseTunnelServerMessage(String(event.data));
|
|
2043
|
+
if (message === null) ws.close(TUNNEL_CLOSE_PROTOCOL, "bad message");
|
|
2044
|
+
else handleControl(message);
|
|
2045
|
+
});
|
|
2046
|
+
ws.addEventListener("close", (event) => {
|
|
2047
|
+
if (event.code === 1e3) stopTunnel({ kind: "done" });
|
|
2048
|
+
else if (event.code === CLOSE_ABNORMAL) stopTunnel({ kind: "unreachable" });
|
|
2049
|
+
else stopTunnel({
|
|
2050
|
+
kind: "closed",
|
|
2051
|
+
code: event.code
|
|
2052
|
+
});
|
|
2053
|
+
});
|
|
2054
|
+
ws.addEventListener("error", () => {});
|
|
2055
|
+
return {
|
|
2056
|
+
send: (data) => {
|
|
2057
|
+
if (state.done) return true;
|
|
2058
|
+
for (let offset = 0; offset < data.byteLength; offset += TUNNEL_MAX_FRAME_BYTES) held.push(Uint8Array.from(data.subarray(offset, offset + TUNNEL_MAX_FRAME_BYTES)));
|
|
2059
|
+
sendHeld();
|
|
2060
|
+
return hasRoom();
|
|
2061
|
+
},
|
|
2062
|
+
waitForRoom: async () => {
|
|
2063
|
+
while (!state.done && !hasRoom()) await new Promise((resolve) => {
|
|
2064
|
+
waiters.push(resolve);
|
|
2065
|
+
});
|
|
2066
|
+
},
|
|
2067
|
+
countUnackedBytes: () => state.unacked,
|
|
2068
|
+
sendEof: () => {
|
|
2069
|
+
state.isEofHeld = true;
|
|
2070
|
+
sendHeld();
|
|
2071
|
+
},
|
|
2072
|
+
close: () => {
|
|
2073
|
+
if (ws.readyState === WebSocket.CONNECTING || ws.readyState === WebSocket.OPEN) ws.close(TUNNEL_CLOSE_NORMAL, "local connection closed");
|
|
2074
|
+
stopTunnel(null);
|
|
2075
|
+
}
|
|
2076
|
+
};
|
|
2077
|
+
}
|
|
2078
|
+
//#endregion
|
|
2079
|
+
//#region src/tunnel/open-reverse-forward.ts
|
|
1678
2080
|
function buildListenMessage(name, guest) {
|
|
1679
2081
|
return guest.network === "tcp" ? {
|
|
1680
2082
|
type: "listen",
|
|
@@ -1723,20 +2125,20 @@ function openRelay(target, accept, handlers) {
|
|
|
1723
2125
|
});
|
|
1724
2126
|
};
|
|
1725
2127
|
const handleControl = (message) => {
|
|
1726
|
-
|
|
2128
|
+
match(message).with({ type: "opened" }, () => {
|
|
1727
2129
|
state.opened = true;
|
|
1728
2130
|
for (const data of pending.splice(0)) sendFrames(data);
|
|
1729
2131
|
if (state.peerEof) sendText({ type: "eof" });
|
|
1730
|
-
}
|
|
2132
|
+
}).with({ type: "eof" }, () => {
|
|
1731
2133
|
state.guestEof = true;
|
|
1732
2134
|
handlers.onEof();
|
|
1733
|
-
}
|
|
1734
|
-
state.unacked -=
|
|
2135
|
+
}).with({ type: "ack" }, (ack) => {
|
|
2136
|
+
state.unacked -= ack.bytes;
|
|
1735
2137
|
if (state.unacked <= 1048576) wakeWaiters();
|
|
1736
|
-
}
|
|
2138
|
+
}).with({ type: P.union("error", "listening", "connection") }, () => {
|
|
1737
2139
|
ws.close(TUNNEL_CLOSE_NORMAL, "relay failed");
|
|
1738
2140
|
stopRelay(true);
|
|
1739
|
-
}
|
|
2141
|
+
}).exhaustive();
|
|
1740
2142
|
};
|
|
1741
2143
|
ws.addEventListener("open", () => {
|
|
1742
2144
|
sendText(accept);
|
|
@@ -1746,7 +2148,7 @@ function openRelay(target, accept, handlers) {
|
|
|
1746
2148
|
sendAck(new Uint8Array(event.data));
|
|
1747
2149
|
return;
|
|
1748
2150
|
}
|
|
1749
|
-
const message =
|
|
2151
|
+
const message = parseTunnelServerMessage(String(event.data));
|
|
1750
2152
|
if (message === null) {
|
|
1751
2153
|
ws.close(TUNNEL_CLOSE_PROTOCOL, "bad message");
|
|
1752
2154
|
stopRelay(true);
|
|
@@ -1780,8 +2182,7 @@ function openRelay(target, accept, handlers) {
|
|
|
1780
2182
|
};
|
|
1781
2183
|
}
|
|
1782
2184
|
function openReverseForward(options) {
|
|
1783
|
-
const url =
|
|
1784
|
-
url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
|
|
2185
|
+
const url = resolveImpdWebSocketUrl(options.baseUrl, TUNNEL_PATH);
|
|
1785
2186
|
const headers = options.token === null ? {} : { authorization: `Bearer ${options.token}` };
|
|
1786
2187
|
const target = {
|
|
1787
2188
|
url: url.href,
|
|
@@ -1830,26 +2231,30 @@ function openReverseForward(options) {
|
|
|
1830
2231
|
});
|
|
1831
2232
|
};
|
|
1832
2233
|
const handleControl = (message) => {
|
|
1833
|
-
|
|
1834
|
-
state.listener =
|
|
2234
|
+
match(message).with({ type: "listening" }, (listen) => {
|
|
2235
|
+
state.listener = listen.listener;
|
|
1835
2236
|
listening.resolve({
|
|
1836
|
-
path:
|
|
1837
|
-
port:
|
|
2237
|
+
path: listen.path,
|
|
2238
|
+
port: listen.port
|
|
1838
2239
|
});
|
|
1839
|
-
}
|
|
1840
|
-
|
|
1841
|
-
|
|
1842
|
-
|
|
1843
|
-
|
|
1844
|
-
|
|
1845
|
-
|
|
2240
|
+
}).with({ type: "connection" }, (connection) => {
|
|
2241
|
+
openClientRelay(connection.id);
|
|
2242
|
+
}).with({ type: "error" }, (failure) => {
|
|
2243
|
+
stopForward({
|
|
2244
|
+
kind: "failed",
|
|
2245
|
+
code: failure.code ?? null,
|
|
2246
|
+
message: failure.message
|
|
2247
|
+
});
|
|
2248
|
+
}).with({ type: P.union("opened", "eof", "ack") }, () => {
|
|
2249
|
+
ws.close(TUNNEL_CLOSE_PROTOCOL, "bad message");
|
|
2250
|
+
}).exhaustive();
|
|
1846
2251
|
};
|
|
1847
2252
|
ws.binaryType = "arraybuffer";
|
|
1848
2253
|
ws.addEventListener("open", () => {
|
|
1849
2254
|
ws.send(JSON.stringify(buildListenMessage(options.name, options.guest)));
|
|
1850
2255
|
});
|
|
1851
2256
|
ws.addEventListener("message", (event) => {
|
|
1852
|
-
const message = event.data instanceof ArrayBuffer ? null :
|
|
2257
|
+
const message = event.data instanceof ArrayBuffer ? null : parseTunnelServerMessage(String(event.data));
|
|
1853
2258
|
if (message === null) ws.close(TUNNEL_CLOSE_PROTOCOL, "bad message");
|
|
1854
2259
|
else handleControl(message);
|
|
1855
2260
|
});
|
|
@@ -1872,4 +2277,4 @@ function openReverseForward(options) {
|
|
|
1872
2277
|
};
|
|
1873
2278
|
}
|
|
1874
2279
|
//#endregion
|
|
1875
|
-
export { CLIENT_VERSION, CONSOLE_SHELL, EXEC_REQUIREMENTS, ExecError, InvalidResumeError, InvalidStateError, NoSessionError, ORPCError, UnknownProcedureError, createImpClient, isDefinedError, openExecSession, openReverseForward, safe };
|
|
2280
|
+
export { CLIENT_VERSION, CONSOLE_SHELL, EXEC_REQUIREMENTS, ExecError, InvalidResumeError, InvalidStateError, MissingFeatureError, NoSessionError, ORPCError, UnknownProcedureError, createImpClient, findMissingFeatures, isDefinedError, openExecSession, openForwardTunnel, openReverseForward, openToolExec, readFeatures, requireFeatures, resolveImpdWebSocketUrl, safe, watchEvents };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@impz/client",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.5.0",
|
|
4
4
|
"description": "Typed client for impd, the imp host daemon: imps, checkpoints, images and exec",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
@@ -18,6 +18,8 @@
|
|
|
18
18
|
"dependencies": {
|
|
19
19
|
"@orpc/client": "^1.14.15",
|
|
20
20
|
"@orpc/contract": "^1.14.15",
|
|
21
|
+
"p-retry": "^8.0.1",
|
|
22
|
+
"ts-pattern": "^5.9.0",
|
|
21
23
|
"zod": "^4.4.3"
|
|
22
24
|
},
|
|
23
25
|
"peerDependencies": {
|