@milaboratories/pl-client 3.14.3 → 3.14.5

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.
@@ -160,6 +160,7 @@ var LLPlClient = class LLPlClient {
160
160
  const clientOptions = {
161
161
  "grpc.keepalive_time_ms": 3e4,
162
162
  "grpc.service_config_disable_resolution": 1,
163
+ "grpc-node.flow_control_window": 16 * 1024 * 1024,
163
164
  interceptors: this._grpcInterceptors
164
165
  };
165
166
  if (gzip) clientOptions["grpc.default_compression_algorithm"] = _grpc_grpc_js.compressionAlgorithms.gzip;
@@ -1 +1 @@
1
- {"version":3,"file":"ll_client.cjs","names":["plAddressToConfig","inferAuthRefreshTime","interceptors","GrpcPlApiClient","createClient","SUPPORTED_WIRE_PROTOCOLS","compressionAlgorithms","ChannelCredentials","GrpcTransport","parsePlJwt","isUnauthenticated","parseResponseError","InterceptingCall","GrpcStatus","Timestamp","hasCapability","isAbortedError","LLPlTransaction","WebSocketBiDiStream","TxAPI_ClientMessage","TxAPI_ServerMessage"],"sources":["../../src/core/ll_client.ts"],"sourcesContent":["import { PlatformClient as GrpcPlApiClient } from \"../proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api.client\";\nimport type { ClientOptions, Interceptor } from \"@grpc/grpc-js\";\nimport {\n ChannelCredentials,\n InterceptingCall,\n status as GrpcStatus,\n compressionAlgorithms,\n} from \"@grpc/grpc-js\";\nimport type {\n AuthInformation,\n AuthOps,\n PlClientConfig,\n PlConnectionStatus,\n PlConnectionStatusListener,\n} from \"./config\";\nimport { plAddressToConfig, type wireProtocol, SUPPORTED_WIRE_PROTOCOLS } from \"./config\";\nimport type { GrpcOptions } from \"@protobuf-ts/grpc-transport\";\nimport { GrpcTransport } from \"@protobuf-ts/grpc-transport\";\nimport { LLPlTransaction } from \"./ll_transaction\";\nimport { setResourceSignaturesRequired } from \"./types\";\nimport { parsePlJwt } from \"../util/pl\";\nimport { type Dispatcher, interceptors } from \"undici\";\nimport type { Middleware } from \"openapi-fetch\";\nimport { inferAuthRefreshTime } from \"./auth\";\nimport { hasCapability, type BackendCapability } from \"./capabilities\";\nimport { defaultHttpDispatcher } from \"@milaboratories/pl-http\";\nimport type { WireClientProvider, WireClientProviderFactory, WireConnection } from \"./wire\";\nimport { parseHttpAuth } from \"@milaboratories/pl-model-common\";\nimport type * as grpcTypes from \"../proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api\";\nimport {\n type PlApiPaths,\n type PlRestClientType,\n createClient,\n parseResponseError,\n} from \"../proto-rest\";\nimport { notEmpty, retry, withTimeout, type RetryOptions } from \"@milaboratories/ts-helpers\";\nimport { Code } from \"../proto-grpc/google/rpc/code\";\nimport { WebSocketBiDiStream } from \"./websocket_stream\";\nimport {\n AuthAPI_Role,\n TxAPI_ClientMessage,\n TxAPI_ServerMessage,\n} from \"../proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api\";\nimport type { MiLogger } from \"@milaboratories/ts-helpers\";\nimport { isAbortedError, isUnauthenticated } from \"./errors\";\nimport { Timestamp } from \"../proto-grpc/google/protobuf/timestamp\";\n\nexport interface PlCallOps {\n timeout?: number;\n abortSignal?: AbortSignal;\n}\n\n// Parses leading \"<major>.<minor>.<patch>\" from a version string like\n// \"3.1.1\" or \"3.1.1-rc1\" and returns true if the parsed version is >= target.\n// Returns false for unparseable versions (safer to assume an old backend).\nfunction isVersionAtLeast(version: string, target: [number, number, number]): boolean {\n const match = /^v?(\\d+)\\.(\\d+)\\.(\\d+)/.exec(version);\n if (!match) return false;\n const parsed: [number, number, number] = [Number(match[1]), Number(match[2]), Number(match[3])];\n for (let i = 0; i < 3; i++) {\n if (parsed[i] !== target[i]) return parsed[i] > target[i];\n }\n return true;\n}\n\n// Returns true iff `version` is strictly after the release tag `target`. Dev\n// builds (`git describe`-style, e.g. \"3.5.0-224-g0ca182\") are considered\n// AFTER the matching release tag — they include commits past the tag and so\n// have any change merged after it. Released versions with the same triplet\n// return false (we want the tag itself to be excluded).\n//\n// Examples for target [3,5,0]:\n// \"3.5.0\" → false (the tagged release)\n// \"3.5.0-224-g0ca182\" → true (dev build past the tag)\n// \"3.5.1\" → true\n// \"3.4.9\" → false\n// Returns false for unparseable versions.\nfunction isAfterVersion(version: string, target: [number, number, number]): boolean {\n const match = /^v?(\\d+)\\.(\\d+)\\.(\\d+)(.*)$/.exec(version);\n if (!match) return false;\n const parsed: [number, number, number] = [Number(match[1]), Number(match[2]), Number(match[3])];\n const suffix = match[4];\n for (let i = 0; i < 3; i++) {\n if (parsed[i] !== target[i]) return parsed[i] > target[i];\n }\n return suffix !== \"\";\n}\n\nclass WireClientProviderImpl<Client> implements WireClientProvider<Client> {\n private client: Client | undefined = undefined;\n\n constructor(\n private readonly wireOpts: () => WireConnection,\n private readonly clientConstructor: (wireOpts: WireConnection) => Client,\n ) {}\n\n public reset(): void {\n this.client = undefined;\n }\n\n public get(): Client {\n if (this.client === undefined) this.client = this.clientConstructor(this.wireOpts());\n return this.client;\n }\n}\n\n/** Abstract out low level networking and authorization details */\nexport class LLPlClient implements WireClientProviderFactory {\n /** Initial authorization information */\n private authInformation?: AuthInformation;\n /** Will be executed by the client when it is required */\n private readonly onAuthUpdate?: (newInfo: AuthInformation) => void;\n /** Will be executed if auth-related error happens during normal client operation */\n private readonly onAuthError?: () => void;\n /** Will be executed by the client when it is required */\n private readonly onAuthRefreshProblem?: (error: unknown) => void;\n /** Threshold after which auth info refresh is required */\n private refreshTimestamp?: number;\n\n /** Cached Ping response. Populated by build() before it returns; refreshed by every later ping(). */\n private _serverInfo?: grpcTypes.MaintenanceAPI_Ping_Response;\n private _authMethodsSync?: grpcTypes.AuthAPI_ListMethods_Response;\n\n private _status: PlConnectionStatus = \"OK\";\n private authProbeInFlight = false;\n private readonly statusListener?: PlConnectionStatusListener;\n\n private _wireProto: wireProtocol = \"grpc\";\n private _wireConn!: WireConnection;\n\n private readonly _restInterceptors: Dispatcher.DispatcherComposeInterceptor[];\n private readonly _restMiddlewares: Middleware[];\n private readonly _grpcInterceptors: Interceptor[];\n private readonly providers: WeakRef<WireClientProviderImpl<any>>[] = [];\n\n public readonly clientProvider: WireClientProvider<PlRestClientType | GrpcPlApiClient>;\n\n public readonly httpDispatcher: Dispatcher;\n\n public static async build(\n configOrAddress: PlClientConfig | string,\n ops: {\n auth?: AuthOps;\n statusListener?: PlConnectionStatusListener;\n shouldUseGzip?: boolean;\n logger?: MiLogger;\n useAutoDetectWireProtocol?: boolean;\n } = {},\n ) {\n const conf =\n typeof configOrAddress === \"string\" ? plAddressToConfig(configOrAddress) : configOrAddress;\n\n const pl = new LLPlClient(conf, ops);\n\n // FIXME(rfiskov)[MILAB-5275]: Investigate why autodetect randomly fails; temporary turn it off.\n if (ops.useAutoDetectWireProtocol) {\n await pl.detectOptimalWireProtocol();\n }\n\n // Guarantee a ping happened so capability-gated paths (login, refresh) can branch synchronously.\n // In the autodetect path the loop's last successful ping already populated _serverInfo via the\n // side-effect in ping(); this fallback covers the path where autodetect is disabled.\n if (!pl._serverInfo) await pl.ping();\n\n // Install the process-global signature-strictness flag based on backend version.\n setResourceSignaturesRequired(pl.supportsResourceSignatures);\n\n // Guarantee authMethods happened so client can make weighted decision on which auth method to use.\n if (!pl._authMethodsSync) await pl.authMethods();\n\n return pl;\n }\n\n private constructor(\n public readonly conf: PlClientConfig,\n private readonly ops: {\n auth?: AuthOps;\n statusListener?: PlConnectionStatusListener;\n shouldUseGzip?: boolean;\n logger?: MiLogger;\n } = {},\n ) {\n const { auth, statusListener } = ops;\n\n if (auth !== undefined) {\n this.refreshTimestamp = inferAuthRefreshTime(\n auth.authInformation,\n this.conf.authMaxRefreshSeconds,\n );\n this.authInformation = auth.authInformation;\n this.onAuthUpdate = auth.onUpdate;\n this.onAuthRefreshProblem = auth.onUpdateError;\n this.onAuthError = auth.onAuthError;\n }\n\n this._restInterceptors = [];\n this._restMiddlewares = [];\n this._grpcInterceptors = [];\n\n if (auth !== undefined) {\n this._restInterceptors.push(this.createRestAuthInterceptor());\n this._grpcInterceptors.push(this.createGrpcAuthInterceptor());\n }\n this._restInterceptors.push(interceptors.retry({ statusCodes: [] })); // Handle errors with openapi-fetch middleware.\n this._restMiddlewares.push(this.createRestErrorMiddleware());\n this._grpcInterceptors.push(this.createGrpcErrorInterceptor());\n\n this.httpDispatcher = defaultHttpDispatcher(this.conf.httpProxy);\n if (this.conf.wireProtocol) {\n this._wireProto = this.conf.wireProtocol;\n }\n\n this.initWireConnection(this._wireProto);\n\n if (statusListener !== undefined) {\n this.statusListener = statusListener;\n statusListener(this._status);\n }\n\n this.clientProvider = this.createWireClientProvider((wireConn) => {\n if (wireConn.type === \"grpc\") {\n return new GrpcPlApiClient(wireConn.Transport);\n } else {\n return createClient<PlApiPaths>({\n hostAndPort: wireConn.Config.hostAndPort,\n ssl: wireConn.Config.ssl,\n dispatcher: wireConn.Dispatcher,\n middlewares: wireConn.Middlewares,\n });\n }\n });\n }\n\n private initWireConnection(protocol: wireProtocol) {\n switch (protocol) {\n case \"rest\":\n this.initRestConnection();\n return;\n case \"grpc\":\n this.initGrpcConnection(this.ops.shouldUseGzip ?? false);\n return;\n default:\n ((v: never) => {\n throw new Error(\n `Unsupported wire protocol '${v as string}'. Use one of: ${SUPPORTED_WIRE_PROTOCOLS.join(\", \")}`,\n );\n })(protocol);\n }\n }\n\n private initRestConnection(): void {\n const dispatcher = defaultHttpDispatcher(this.conf.grpcProxy, this._restInterceptors);\n this._replaceWireConnection({\n type: \"rest\",\n Config: this.conf,\n Dispatcher: dispatcher,\n Middlewares: this._restMiddlewares,\n });\n }\n\n /**\n * Initializes (or reinitializes) _grpcTransport\n * @param gzip - whether to enable gzip compression\n */\n private initGrpcConnection(gzip: boolean) {\n const clientOptions: ClientOptions = {\n \"grpc.keepalive_time_ms\": 30_000, // 30 seconds\n \"grpc.service_config_disable_resolution\": 1, // Disable DNS TXT lookups for service config\n interceptors: this._grpcInterceptors,\n };\n\n if (gzip) clientOptions[\"grpc.default_compression_algorithm\"] = compressionAlgorithms.gzip;\n\n //\n // Leaving it here for now\n // https://github.com/grpc/grpc-node/issues/2788\n //\n // We should implement message pooling algorithm to overcome hardcoded NO_DELAY behaviour\n // of HTTP/2 and allow our small messages to batch together.\n //\n const grpcOptions: GrpcOptions = {\n host: this.conf.hostAndPort,\n timeout: this.conf.defaultRequestTimeout,\n channelCredentials: this.conf.ssl\n ? ChannelCredentials.createSsl()\n : ChannelCredentials.createInsecure(),\n clientOptions,\n };\n\n const grpcProxy =\n typeof this.conf.grpcProxy === \"string\" ? { url: this.conf.grpcProxy } : this.conf.grpcProxy;\n\n if (grpcProxy?.url) {\n const url = new URL(grpcProxy.url);\n if (grpcProxy.auth) {\n const parsed = parseHttpAuth(grpcProxy.auth);\n if (parsed.scheme !== \"Basic\") {\n throw new Error(`Unsupported auth scheme: ${parsed.scheme as string}.`);\n }\n url.username = parsed.username;\n url.password = parsed.password;\n }\n process.env.grpc_proxy = url.toString();\n } else {\n delete process.env.grpc_proxy;\n }\n\n this._replaceWireConnection({ type: \"grpc\", Transport: new GrpcTransport(grpcOptions) });\n }\n\n private _replaceWireConnection(newConn: WireConnection): void {\n const oldConn = this._wireConn;\n this._wireConn = newConn;\n this._wireProto = newConn.type;\n\n // Reset all providers to let them reinitialize their clients\n for (let i = 0; i < this.providers.length; i++) {\n const provider = this.providers[i].deref();\n if (provider === undefined) {\n // at the same time we need to remove providers that are no longer valid\n this.providers.splice(i, 1);\n i--;\n } else {\n provider.reset();\n }\n }\n\n if (oldConn !== undefined && oldConn.type === \"grpc\") oldConn.Transport.close();\n }\n\n private providerCleanupCounter = 0;\n\n /**\n * Creates a provider for a grpc client. Returned provider will create fresh client whenever the underlying transport is reset.\n *\n * @param clientConstructor - a factory function that creates a grpc client\n */\n public createWireClientProvider<Client>(\n clientConstructor: (transport: WireConnection) => Client,\n ): WireClientProvider<Client> {\n // We need to cleanup providers periodically to avoid memory leaks.\n // This is a simple heuristic to avoid memory leaks.\n // We could use a more sophisticated algorithm, but this is good enough for now.\n this.providerCleanupCounter++;\n if (this.providerCleanupCounter >= 16) {\n for (let i = 0; i < this.providers.length; i++) {\n const provider = this.providers[i].deref();\n if (provider === undefined) {\n this.providers.splice(i, 1);\n i--;\n }\n }\n this.providerCleanupCounter = 0;\n }\n\n const provider = new WireClientProviderImpl<Client>(() => this._wireConn, clientConstructor);\n this.providers.push(new WeakRef(provider));\n return provider;\n }\n\n public get wireConnection(): WireConnection {\n return this._wireConn;\n }\n\n public get wireProtocol(): wireProtocol | undefined {\n return this._wireProto;\n }\n\n /** Returns true if client is authenticated. Even with anonymous auth information\n * connection is considered authenticated. Unauthenticated clients are used for\n * login and similar tasks, see {@link UnauthenticatedPlClient}. */\n public get authenticated(): boolean {\n return this.authInformation !== undefined;\n }\n\n /** null means anonymous connection */\n public get authUser(): string | null {\n if (!this.authenticated) throw new Error(\"Client is not authenticated\");\n if (this.authInformation?.jwtToken) {\n if (this.hasCapability(\"auth:v2\")) {\n return parsePlJwt(this.authInformation?.jwtToken).sub;\n }\n return parsePlJwt(this.authInformation?.jwtToken).user.login;\n } else return null;\n }\n\n private updateStatus(newStatus: PlConnectionStatus) {\n process.nextTick(() => {\n if (this._status !== newStatus) {\n this._status = newStatus;\n if (this.statusListener !== undefined) this.statusListener(this._status);\n if (newStatus === \"Unauthenticated\" && this.onAuthError !== undefined) this.onAuthError();\n }\n });\n }\n\n /**\n * UNAUTHENTICATED covers both a dead session (must reset) and a per-request authorization failure\n * such as a revoked resource signature (must not). Disambiguate by probing getSessionInfo — an\n * authenticated call with no resource signature: success means the session is alive and the failure\n * was resource-level; a probe that is itself Unauthenticated means real auth loss. Coalesced via\n * authProbeInFlight so a burst of failures costs one probe.\n */\n private async verifyThenMaybeEscalateUnauthenticated(): Promise<void> {\n if (this._status !== \"OK\" || this.authProbeInFlight) return;\n this.authProbeInFlight = true;\n try {\n await this.getSessionInfo();\n } catch (e) {\n if (isUnauthenticated(e)) this.updateStatus(\"Unauthenticated\");\n } finally {\n this.authProbeInFlight = false;\n }\n }\n\n public get status(): PlConnectionStatus {\n return this._status;\n }\n\n private authRefreshInProgress: boolean = false;\n\n private refreshAuthInformationIfNeeded(): void {\n if (\n this.refreshTimestamp === undefined ||\n Date.now() < this.refreshTimestamp ||\n this.authRefreshInProgress ||\n this._status === \"Unauthenticated\"\n )\n return;\n\n // Running refresh in background`\n this.authRefreshInProgress = true;\n void (async () => {\n try {\n const ttl = BigInt(this.conf.authTTLSeconds);\n const token = this.hasCapability(\"auth:v2\")\n ? await this.refreshToken({ ttlSeconds: ttl })\n : await this.getJwtToken(ttl);\n this.authInformation = { jwtToken: token };\n this.refreshTimestamp = inferAuthRefreshTime(\n this.authInformation,\n this.conf.authMaxRefreshSeconds,\n );\n if (this.onAuthUpdate) this.onAuthUpdate(this.authInformation);\n } catch (e: unknown) {\n if (this.onAuthRefreshProblem) this.onAuthRefreshProblem(e);\n } finally {\n this.authRefreshInProgress = false;\n }\n })();\n }\n\n /**\n * Creates middleware that parses error responses and handles them centrally.\n * This middleware runs before openapi-fetch parses the response, so we need to\n * manually parse the response body for error responses.\n */\n private createRestErrorMiddleware(): Middleware {\n return {\n onResponse: async ({ request: _request, response, options: _options }) => {\n const { body, ...resOptions } = response;\n\n if ([502, 503, 504].includes(response.status)) {\n // Service unavailable, bad gateway, gateway timeout\n this.updateStatus(\"Disconnected\");\n return new Response(body, { ...resOptions, status: response.status });\n }\n\n const respErr = await parseResponseError(response);\n if (!respErr.error) {\n // No error: nice!\n return new Response(respErr.origBody ?? body, { ...resOptions, status: response.status });\n }\n\n if (typeof respErr.error === \"string\") {\n // Non-standard error or normal response: let later middleware to deal wit it.\n return new Response(respErr.error, { ...resOptions, status: response.status });\n }\n\n if (respErr.error.code === Code.UNAUTHENTICATED) {\n void this.verifyThenMaybeEscalateUnauthenticated();\n }\n\n // Let later middleware to deal with standard gRPC error.\n return new Response(respErr.origBody, { ...resOptions, status: response.status });\n },\n };\n }\n\n /** Detects certain errors and update client status accordingly when using GRPC wire connection */\n private createGrpcErrorInterceptor(): Interceptor {\n return (options, nextCall) => {\n return new InterceptingCall(nextCall(options), {\n start: (metadata, listener, next) => {\n next(metadata, {\n onReceiveStatus: (status, next) => {\n if (status.code == GrpcStatus.UNAUTHENTICATED)\n // (!!!) don't change to \"===\"\n void this.verifyThenMaybeEscalateUnauthenticated();\n if (status.code == GrpcStatus.UNAVAILABLE)\n // (!!!) don't change to \"===\"\n this.updateStatus(\"Disconnected\");\n next(status);\n },\n });\n },\n });\n };\n }\n\n private createRestAuthInterceptor(): Dispatcher.DispatcherComposeInterceptor {\n return (dispatch) => {\n return (options, handler) => {\n if (this.authInformation?.jwtToken !== undefined) {\n // TODO: check this magic really works and gets called\n options.headers = {\n ...options.headers,\n authorization: \"Bearer \" + this.authInformation.jwtToken,\n };\n this.refreshAuthInformationIfNeeded();\n }\n\n return dispatch(options, handler);\n };\n };\n }\n\n /** Injects authentication information if needed */\n private createGrpcAuthInterceptor(): Interceptor {\n return (options, nextCall) => {\n return new InterceptingCall(nextCall(options), {\n start: (metadata, listener, next) => {\n if (this.authInformation?.jwtToken !== undefined) {\n metadata.set(\"authorization\", \"Bearer \" + this.authInformation.jwtToken);\n this.refreshAuthInformationIfNeeded();\n next(metadata, listener);\n } else {\n next(metadata, listener);\n }\n },\n });\n };\n }\n\n public async getJwtToken(\n ttlSeconds: bigint,\n options?: { authorization?: string; role?: AuthAPI_Role },\n ): Promise<string> {\n const cl = this.clientProvider.get();\n const role = options?.role ?? AuthAPI_Role.UNSPECIFIED;\n\n if (cl instanceof GrpcPlApiClient) {\n const meta: Record<string, string> = {};\n if (options?.authorization) meta.authorization = options.authorization;\n return (\n await cl.getJWTToken(\n {\n expiration: { seconds: ttlSeconds, nanos: 0 },\n requestedRole: role,\n },\n { meta },\n ).response\n ).token;\n } else {\n const headers: Record<string, string> = {};\n if (options?.authorization) headers.authorization = options.authorization;\n const resp = cl.POST(\"/v1/auth/jwt-token\", {\n body: { expiration: `${ttlSeconds}s`, requestedRole: role },\n headers,\n });\n return notEmpty((await resp).data, \"REST: empty response for JWT token request\").token;\n }\n }\n\n /** Login via username/password. Returns a fresh JWT. Backend creates a new session per call. */\n public async loginBasic(\n user: string,\n password: string,\n opts: { ttlSeconds?: bigint; role?: AuthAPI_Role } = {},\n ): Promise<string> {\n const cl = this.clientProvider.get();\n const ttl = opts.ttlSeconds ?? BigInt(this.conf.authTTLSeconds);\n const role = opts.role ?? AuthAPI_Role.UNSPECIFIED;\n\n if (cl instanceof GrpcPlApiClient) {\n return (\n await cl.login({\n credentials: {\n oneofKind: \"basic\",\n basic: { login: user, password },\n },\n expiration: { seconds: ttl, nanos: 0 },\n requestedRole: role,\n }).response\n ).token;\n } else {\n const resp = cl.POST(\"/v1/auth/login\", {\n // openapi-typescript generated all body fields as required, but Login.Request\n // has a credentials oneof — only one of `basic`/`token` is sent. Cast around it.\n body: {\n basic: { login: user, password },\n expiration: `${ttl}s`,\n requestedRole: role,\n } as any,\n });\n return notEmpty((await resp).data, \"REST: empty response for login request\").token;\n }\n }\n\n /** Login via opaque bearer token (controller pre-shared secret, OIDC id-token, etc.).\n * String input is UTF-8 encoded. Returns a fresh Platforma JWT. */\n public async loginWithToken(\n token: Uint8Array | string,\n opts: { ttlSeconds?: bigint; role?: AuthAPI_Role } = {},\n ): Promise<string> {\n const cl = this.clientProvider.get();\n const ttl = opts.ttlSeconds ?? BigInt(this.conf.authTTLSeconds);\n const role = opts.role ?? AuthAPI_Role.UNSPECIFIED;\n const bytes = typeof token === \"string\" ? Buffer.from(token, \"utf8\") : token;\n\n if (cl instanceof GrpcPlApiClient) {\n return (\n await cl.login({\n credentials: {\n oneofKind: \"token\",\n token: { token: bytes },\n },\n expiration: { seconds: ttl, nanos: 0 },\n requestedRole: role,\n }).response\n ).token;\n } else {\n const resp = cl.POST(\"/v1/auth/login\", {\n // openapi-typescript marks all body fields as required, but Login.Request has a oneof.\n // REST encodes `bytes` as a base64 string.\n body: {\n token: { token: Buffer.from(bytes).toString(\"base64\") },\n expiration: `${ttl}s`,\n requestedRole: role,\n } as any,\n });\n return notEmpty((await resp).data, \"REST: empty response for login request\").token;\n }\n }\n\n /** Login via SSO: forwards the raw IdP /token JSON body to the backend.\n * Backend validates signature + nonce + audience and mints a Platforma JWT. */\n public async loginSSO(tokenResponse: Uint8Array): Promise<string> {\n const cl = this.clientProvider.get();\n if (cl instanceof GrpcPlApiClient) {\n return (\n await cl.login({\n credentials: {\n oneofKind: \"sso\",\n sso: { tokenResponse },\n },\n }).response\n ).token;\n } else {\n const resp = cl.POST(\"/v1/auth/login\", {\n body: {\n sso: { tokenResponse: Buffer.from(tokenResponse).toString(\"base64\") },\n } as any,\n });\n return notEmpty((await resp).data, \"REST: empty response for SSO login request\").token;\n }\n }\n\n /** Request a one-time PKCE nonce + its expiry from the backend. The desktop is\n * expected to place the nonce verbatim into the OIDC auth-request before\n * redirecting to the IdP; the backend enforces the expiry on {@link loginSSO}. */\n public async beginSSOLogin(): Promise<{ nonce: string; expiresAt: Date; clientSecret?: string }> {\n const cl = this.clientProvider.get();\n if (cl instanceof GrpcPlApiClient) {\n const resp = (await cl.beginSSOLogin({}).response).flow;\n if (resp.oneofKind !== \"publicPkce\") {\n throw new Error(`beginSSOLogin: unsupported flow ${resp.oneofKind}`);\n }\n const exp = notEmpty(resp.publicPkce.expiresAt, \"beginSSOLogin: missing expiresAt\");\n return {\n nonce: resp.publicPkce.nonce,\n expiresAt: Timestamp.toDate(exp),\n clientSecret: resp.publicPkce.clientSecret,\n };\n } else {\n const wsResponse = notEmpty(\n (await cl.POST(\"/v1/auth/sso/begin-login\", { body: {} })).data,\n \"REST: empty response for beginSSOLogin request\",\n );\n const pkce = notEmpty(wsResponse.publicPkce, \"REST: missing publicPkce in beginSSOLogin\");\n return {\n nonce: pkce.nonce,\n expiresAt: new Date(pkce.expiresAt),\n clientSecret: pkce.clientSecret,\n };\n }\n }\n\n /** Refresh the current JWT, preserving session id and role. */\n public async refreshToken(opts: { ttlSeconds?: bigint } = {}): Promise<string> {\n const cl = this.clientProvider.get();\n const ttl = opts.ttlSeconds ?? BigInt(this.conf.authTTLSeconds);\n const currentToken = notEmpty(\n this.authInformation?.jwtToken,\n \"refreshToken called without a current JWT\",\n );\n\n if (cl instanceof GrpcPlApiClient) {\n return (\n await cl.refreshToken({\n token: currentToken,\n expiration: { seconds: ttl, nanos: 0 },\n }).response\n ).token;\n } else {\n const resp = cl.POST(\"/v1/auth/refresh\", {\n body: { token: currentToken, expiration: `${ttl}s` },\n });\n return notEmpty((await resp).data, \"REST: empty response for refresh request\").token;\n }\n }\n\n public async ping(): Promise<grpcTypes.MaintenanceAPI_Ping_Response> {\n const cl = this.clientProvider.get();\n let resp: grpcTypes.MaintenanceAPI_Ping_Response;\n if (cl instanceof GrpcPlApiClient) {\n resp = (await cl.ping({})).response;\n } else {\n // The REST ping response predates the `capabilities` field (proto field 9).\n // Old servers omit it; treat absence as empty capability list.\n const pingData = notEmpty(\n (await cl.GET(\"/v1/ping\")).data,\n \"REST: empty response for ping request\",\n );\n resp = {\n ...(pingData as unknown as grpcTypes.MaintenanceAPI_Ping_Response),\n capabilities: (pingData as any).capabilities ?? [],\n };\n }\n this._serverInfo = resp;\n return resp;\n }\n\n /** Cached Ping response. Always populated post-build(); throws if accessed earlier. */\n public get serverInfo(): grpcTypes.MaintenanceAPI_Ping_Response {\n if (!this._serverInfo) {\n throw new Error(\"LLPlClient.serverInfo accessed before build() completed\");\n }\n return this._serverInfo;\n }\n\n /** Synchronous capability check against the cached Ping response. */\n public hasCapability(capability: BackendCapability): boolean {\n return hasCapability(this.serverInfo.capabilities, capability);\n }\n\n /** True if the backend produces signed resource ids (and accepts the\n * setDefaultColor TX request). Tagged at 3.3.0 — backends older than this\n * return resources without signatures and reject color-proof requests. */\n public get supportsResourceSignatures(): boolean {\n return isVersionAtLeast(this.serverInfo.coreVersion, [3, 3, 0]);\n }\n\n /**\n * True if the backend honors per-file `permissions` on workdir fill rules, so\n * `exec.builder().writeFile/addFile({ writable: true })` takes effect. When false\n * the requested mode is ignored and files land at the canonical archive perm.\n *\n * [3, 5, 0] excludes the tagged 3.5.0 release but includes dev builds past the\n * tag (e.g. \"3.5.0-224-g0ca182\"), which is where the support lands.\n */\n public get supportsWritableWorkdirFiles(): boolean {\n return isAfterVersion(this.serverInfo.coreVersion, [3, 5, 0]);\n }\n\n /**\n * Detects the best available wire protocol.\n * If wireProtocol is explicitly configured, does nothing.\n * Otherwise probes the current protocol via ping; if it fails, switches to the alternative.\n */\n private async detectOptimalWireProtocol() {\n if (this.conf.wireProtocol) {\n return;\n }\n\n // Each retry is:\n // - ping request timeout (100 to 3_000ms)\n // - backoff delay (30 to 500ms)\n //\n // 30 attempts are ~43 seconds of overall waiting time.\n // Think twice on overall time this thing takes to complete when changing these parameters.\n // It may block UI when connecting to the server and loading projects list.\n const pingTimeoutFactor = 1.3;\n const maxPingTimeoutMs = 3_000;\n const retryOptions: RetryOptions = {\n type: \"exponentialBackoff\",\n maxAttempts: 30,\n initialDelay: 30,\n backoffMultiplier: 1.3,\n jitter: 0.2,\n maxDelay: 500,\n };\n\n let attempt = 1;\n let pingTimeoutMs = 100;\n await retry(\n () => withTimeout(this.ping(), pingTimeoutMs),\n retryOptions,\n (e: unknown) => {\n if (isAbortedError(e)) {\n this.ops.logger?.info(\n `Wire proto autodetect: ping timed out after ${pingTimeoutMs}ms: attempt=${attempt}, wire=${this._wireProto}`,\n );\n\n if (attempt % 2 === 0) {\n // We have 2 wire protocols to check. Increase timeout each 2 attempts.\n pingTimeoutMs = Math.min(\n Math.round(pingTimeoutMs * pingTimeoutFactor),\n maxPingTimeoutMs,\n );\n }\n } else {\n this.ops.logger?.info(\n `Wire proto autodetect: ping failed: attempt=${attempt}, wire=${this._wireProto}, err=${String(e)}`,\n );\n }\n\n attempt++;\n const protocol = this._wireProto === \"grpc\" ? \"rest\" : \"grpc\";\n this.ops.logger?.info(\n `Wire protocol autodetect next attempt: will try wire '${protocol}' with timeout ${pingTimeoutMs}ms`,\n );\n this.initWireConnection(protocol);\n return true;\n },\n );\n }\n\n public async license(): Promise<grpcTypes.MaintenanceAPI_License_Response> {\n const cl = this.clientProvider.get();\n if (cl instanceof GrpcPlApiClient) {\n return (await cl.license({})).response;\n } else {\n const resp = notEmpty(\n (await cl.GET(\"/v1/license\")).data,\n \"REST: empty response for license request\",\n );\n return {\n status: resp.status,\n isOk: resp.isOk,\n responseBody: Uint8Array.from(Buffer.from(resp.responseBody)),\n };\n }\n }\n\n public async authMethods(): Promise<grpcTypes.AuthAPI_ListMethods_Response> {\n const cl = this.clientProvider.get();\n let resp: grpcTypes.AuthAPI_ListMethods_Response;\n if (cl instanceof GrpcPlApiClient) {\n resp = (await cl.authMethods({})).response;\n } else {\n const wsResponse = notEmpty(\n (await cl.GET(\"/v1/auth/methods\")).data,\n \"REST: empty response for auth methods request\",\n );\n // OpenAPI schema flattens the protobuf oneof into `{ basic?, token? }`,\n // while protobuf-ts models it as a discriminated union. Reshape per item.\n resp = {\n methods: (wsResponse.methods ?? []).map((m): grpcTypes.AuthAPI_ListMethods_MethodInfo => {\n const base = { id: m.id, description: m.description };\n if (m.basic !== undefined) {\n return { ...base, method: { oneofKind: \"basic\", basic: m.basic } };\n }\n if (m.token !== undefined) {\n return { ...base, method: { oneofKind: \"token\", token: m.token } };\n }\n if (m.sso !== undefined) {\n return { ...base, method: { oneofKind: \"sso\", sso: m.sso } };\n }\n return { ...base, method: { oneofKind: undefined } };\n }),\n };\n }\n\n this._authMethodsSync = resp;\n return resp;\n }\n\n public get authMethodsSync(): grpcTypes.AuthAPI_ListMethods_Response {\n if (!this._authMethodsSync) {\n throw new Error(\"LLPlClient.authMethodsSync accessed before build() completed\");\n }\n return this._authMethodsSync;\n }\n\n public async getUserRoot(\n opts: { login?: string; createIfNotExists?: boolean } = {},\n ): Promise<grpcTypes.AuthAPI_GetUserRoot_Response> {\n const cl = this.clientProvider.get();\n if (cl instanceof GrpcPlApiClient) {\n return (\n await cl.getUserRoot({\n login: opts.login ?? \"\",\n createIfNotExists: opts.createIfNotExists ?? false,\n })\n ).response;\n } else {\n const resp = notEmpty(\n (\n await cl.POST(\"/v1/auth/user-root\", {\n body: {\n login: opts.login ?? \"\",\n createIfNotExists: opts.createIfNotExists ?? false,\n },\n })\n ).data,\n \"REST: empty response for getUserRoot request\",\n );\n return {\n userRoot: resp.userRoot\n ? {\n resourceId: BigInt(resp.userRoot.resourceId),\n resourceSignature: Uint8Array.from(\n Buffer.from(resp.userRoot.resourceSignature, \"base64\"),\n ),\n }\n : undefined,\n };\n }\n }\n\n public async listUserResources(\n opts: { login?: string; startFrom?: bigint; limit?: number } = {},\n ): Promise<grpcTypes.AuthAPI_ListUserResources_Response[]> {\n const cl = this.clientProvider.get();\n\n if (!(cl instanceof GrpcPlApiClient)) {\n throw new Error(\"ListUserResources requires gRPC wire protocol; REST is not supported\");\n }\n\n const call = cl.listUserResources({\n login: opts.login ?? \"\",\n startFrom: opts.startFrom ?? 0n,\n limit: opts.limit ?? 0,\n });\n const responses: grpcTypes.AuthAPI_ListUserResources_Response[] = [];\n for await (const msg of call.responses) {\n responses.push(msg);\n }\n return responses;\n }\n\n /** Returns the authenticated caller's session id and effective role.\n * Models the {@link getUserRoot} wrapper: gRPC unary with a REST fallback. */\n public async getSessionInfo(): Promise<grpcTypes.AuthAPI_GetSessionInfo_Response> {\n const cl = this.clientProvider.get();\n if (cl instanceof GrpcPlApiClient) {\n return (await cl.getSessionInfo({})).response;\n } else {\n const resp = notEmpty(\n (await cl.POST(\"/v1/auth/session-info\", { body: {} })).data,\n \"REST: empty response for getSessionInfo request\",\n );\n return {\n sessionId: Uint8Array.from(Buffer.from(resp.sessionId, \"base64\")),\n role: resp.role as AuthAPI_Role,\n };\n }\n }\n\n /** Lists the users known to the server — the recipient picker's source. A user\n * becomes known on first login; provisioned users who have never logged in do not\n * appear. gRPC-only (unary, no REST binding). */\n public async listUsers(): Promise<grpcTypes.AuthAPI_User[]> {\n const cl = this.clientProvider.get();\n\n if (!(cl instanceof GrpcPlApiClient)) {\n throw new Error(\"ListUsers requires gRPC wire protocol; REST is not supported\");\n }\n\n return (await cl.listUsers({})).response.users;\n }\n\n public async txSync(txId: bigint): Promise<void> {\n const cl = this.clientProvider.get();\n if (cl instanceof GrpcPlApiClient) {\n await cl.txSync({ txId: BigInt(txId) });\n } else {\n await cl.POST(\"/v1/tx-sync\", { body: { txId: txId.toString() } });\n }\n }\n\n createTx(rw: boolean, ops: PlCallOps = {}): LLPlTransaction {\n return new LLPlTransaction((abortSignal) => {\n let totalAbortSignal = abortSignal;\n if (ops.abortSignal) totalAbortSignal = AbortSignal.any([totalAbortSignal, ops.abortSignal]);\n\n const timeout =\n ops.timeout ??\n (rw ? this.conf.defaultRWTransactionTimeout : this.conf.defaultROTransactionTimeout);\n\n const cl = this.clientProvider.get();\n if (cl instanceof GrpcPlApiClient) {\n return cl.tx({\n abort: totalAbortSignal,\n timeout,\n });\n }\n\n const wireConn = this.wireConnection;\n if (wireConn.type === \"rest\") {\n // For REST/WebSocket protocol, timeout needs to be converted to AbortSignal\n if (timeout !== undefined) {\n totalAbortSignal = AbortSignal.any([totalAbortSignal, AbortSignal.timeout(timeout)]);\n }\n\n // The gRPC transport has the auth interceptor that already handles it, but here we need to refresh the auth information to be safe.\n this.refreshAuthInformationIfNeeded();\n\n const wsUrl = this.conf.ssl\n ? `wss://${this.conf.hostAndPort}/v1/ws/tx`\n : `ws://${this.conf.hostAndPort}/v1/ws/tx`;\n\n return new WebSocketBiDiStream(\n wsUrl,\n (msg) => TxAPI_ClientMessage.toBinary(msg),\n (data) => TxAPI_ServerMessage.fromBinary(new Uint8Array(data)),\n {\n abortSignal: totalAbortSignal,\n jwtToken: this.authInformation?.jwtToken,\n dispatcher: wireConn.Dispatcher,\n\n onComplete: async (stream) =>\n stream.requests.send({\n // Ask server to gracefully close the stream on its side, if not done yet.\n requestId: 0,\n request: { oneofKind: \"streamClose\", streamClose: {} },\n }),\n },\n );\n }\n\n throw new Error(`transactions are not supported for wire protocol ${this._wireProto}`);\n });\n }\n\n /** Closes underlying transport */\n public async close() {\n if (this.wireConnection.type === \"grpc\") {\n this.wireConnection.Transport.close();\n } else {\n // TODO: close all WS connections\n }\n await this.httpDispatcher.destroy();\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAuDA,SAAS,iBAAiB,SAAiB,QAA2C;CACpF,MAAM,QAAQ,yBAAyB,KAAK,OAAO;CACnD,IAAI,CAAC,OAAO,OAAO;CACnB,MAAM,SAAmC;EAAC,OAAO,MAAM,EAAE;EAAG,OAAO,MAAM,EAAE;EAAG,OAAO,MAAM,EAAE;CAAC;CAC9F,KAAK,IAAI,IAAI,GAAG,IAAI,GAAG,KACrB,IAAI,OAAO,OAAO,OAAO,IAAI,OAAO,OAAO,KAAK,OAAO;CAEzD,OAAO;AACT;AAcA,SAAS,eAAe,SAAiB,QAA2C;CAClF,MAAM,QAAQ,8BAA8B,KAAK,OAAO;CACxD,IAAI,CAAC,OAAO,OAAO;CACnB,MAAM,SAAmC;EAAC,OAAO,MAAM,EAAE;EAAG,OAAO,MAAM,EAAE;EAAG,OAAO,MAAM,EAAE;CAAC;CAC9F,MAAM,SAAS,MAAM;CACrB,KAAK,IAAI,IAAI,GAAG,IAAI,GAAG,KACrB,IAAI,OAAO,OAAO,OAAO,IAAI,OAAO,OAAO,KAAK,OAAO;CAEzD,OAAO,WAAW;AACpB;AAEA,IAAM,yBAAN,MAA2E;CAItD;CACA;CAJnB,SAAqC,KAAA;CAErC,YACE,UACA,mBACA;EAFiB,KAAA,WAAA;EACA,KAAA,oBAAA;CAChB;CAEH,QAAqB;EACnB,KAAK,SAAS,KAAA;CAChB;CAEA,MAAqB;EACnB,IAAI,KAAK,WAAW,KAAA,GAAW,KAAK,SAAS,KAAK,kBAAkB,KAAK,SAAS,CAAC;EACnF,OAAO,KAAK;CACd;AACF;;AAGA,IAAa,aAAb,MAAa,WAAgD;CAmEzC;CACC;;CAlEnB;;CAEA;;CAEA;;CAEA;;CAEA;;CAGA;CACA;CAEA,UAAs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AI,MAAM,oDAAoD,KAAK,YAAY;EACvF,CAAC;CACH;;CAGA,MAAa,QAAQ;EACnB,IAAI,KAAK,eAAe,SAAS,QAC/B,KAAK,eAAe,UAAU,MAAM;EAItC,MAAM,KAAK,eAAe,QAAQ;CACpC;AACF"}
1
+ {"version":3,"file":"ll_client.cjs","names":["plAddressToConfig","inferAuthRefreshTime","interceptors","GrpcPlApiClient","createClient","SUPPORTED_WIRE_PROTOCOLS","compressionAlgorithms","ChannelCredentials","GrpcTransport","parsePlJwt","isUnauthenticated","parseResponseError","InterceptingCall","GrpcStatus","Timestamp","hasCapability","isAbortedError","LLPlTransaction","WebSocketBiDiStream","TxAPI_ClientMessage","TxAPI_ServerMessage"],"sources":["../../src/core/ll_client.ts"],"sourcesContent":["import { PlatformClient as GrpcPlApiClient } from \"../proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api.client\";\nimport type { ClientOptions, Interceptor } from \"@grpc/grpc-js\";\nimport {\n ChannelCredentials,\n InterceptingCall,\n status as GrpcStatus,\n compressionAlgorithms,\n} from \"@grpc/grpc-js\";\nimport type {\n AuthInformation,\n AuthOps,\n PlClientConfig,\n PlConnectionStatus,\n PlConnectionStatusListener,\n} from \"./config\";\nimport { plAddressToConfig, type wireProtocol, SUPPORTED_WIRE_PROTOCOLS } from \"./config\";\nimport type { GrpcOptions } from \"@protobuf-ts/grpc-transport\";\nimport { GrpcTransport } from \"@protobuf-ts/grpc-transport\";\nimport { LLPlTransaction } from \"./ll_transaction\";\nimport { setResourceSignaturesRequired } from \"./types\";\nimport { parsePlJwt } from \"../util/pl\";\nimport { type Dispatcher, interceptors } from \"undici\";\nimport type { Middleware } from \"openapi-fetch\";\nimport { inferAuthRefreshTime } from \"./auth\";\nimport { hasCapability, type BackendCapability } from \"./capabilities\";\nimport { defaultHttpDispatcher } from \"@milaboratories/pl-http\";\nimport type { WireClientProvider, WireClientProviderFactory, WireConnection } from \"./wire\";\nimport { parseHttpAuth } from \"@milaboratories/pl-model-common\";\nimport type * as grpcTypes from \"../proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api\";\nimport {\n type PlApiPaths,\n type PlRestClientType,\n createClient,\n parseResponseError,\n} from \"../proto-rest\";\nimport { notEmpty, retry, withTimeout, type RetryOptions } from \"@milaboratories/ts-helpers\";\nimport { Code } from \"../proto-grpc/google/rpc/code\";\nimport { WebSocketBiDiStream } from \"./websocket_stream\";\nimport {\n AuthAPI_Role,\n TxAPI_ClientMessage,\n TxAPI_ServerMessage,\n} from \"../proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api\";\nimport type { MiLogger } from \"@milaboratories/ts-helpers\";\nimport { isAbortedError, isUnauthenticated } from \"./errors\";\nimport { Timestamp } from \"../proto-grpc/google/protobuf/timestamp\";\n\nexport interface PlCallOps {\n timeout?: number;\n abortSignal?: AbortSignal;\n}\n\n// Parses leading \"<major>.<minor>.<patch>\" from a version string like\n// \"3.1.1\" or \"3.1.1-rc1\" and returns true if the parsed version is >= target.\n// Returns false for unparseable versions (safer to assume an old backend).\nfunction isVersionAtLeast(version: string, target: [number, number, number]): boolean {\n const match = /^v?(\\d+)\\.(\\d+)\\.(\\d+)/.exec(version);\n if (!match) return false;\n const parsed: [number, number, number] = [Number(match[1]), Number(match[2]), Number(match[3])];\n for (let i = 0; i < 3; i++) {\n if (parsed[i] !== target[i]) return parsed[i] > target[i];\n }\n return true;\n}\n\n// Returns true iff `version` is strictly after the release tag `target`. Dev\n// builds (`git describe`-style, e.g. \"3.5.0-224-g0ca182\") are considered\n// AFTER the matching release tag — they include commits past the tag and so\n// have any change merged after it. Released versions with the same triplet\n// return false (we want the tag itself to be excluded).\n//\n// Examples for target [3,5,0]:\n// \"3.5.0\" → false (the tagged release)\n// \"3.5.0-224-g0ca182\" → true (dev build past the tag)\n// \"3.5.1\" → true\n// \"3.4.9\" → false\n// Returns false for unparseable versions.\nfunction isAfterVersion(version: string, target: [number, number, number]): boolean {\n const match = /^v?(\\d+)\\.(\\d+)\\.(\\d+)(.*)$/.exec(version);\n if (!match) return false;\n const parsed: [number, number, number] = [Number(match[1]), Number(match[2]), Number(match[3])];\n const suffix = match[4];\n for (let i = 0; i < 3; i++) {\n if (parsed[i] !== target[i]) return parsed[i] > target[i];\n }\n return suffix !== \"\";\n}\n\nclass WireClientProviderImpl<Client> implements WireClientProvider<Client> {\n private client: Client | undefined = undefined;\n\n constructor(\n private readonly wireOpts: () => WireConnection,\n private readonly clientConstructor: (wireOpts: WireConnection) => Client,\n ) {}\n\n public reset(): void {\n this.client = undefined;\n }\n\n public get(): Client {\n if (this.client === undefined) this.client = this.clientConstructor(this.wireOpts());\n return this.client;\n }\n}\n\n/** Abstract out low level networking and authorization details */\nexport class LLPlClient implements WireClientProviderFactory {\n /** Initial authorization information */\n private authInformation?: AuthInformation;\n /** Will be executed by the client when it is required */\n private readonly onAuthUpdate?: (newInfo: AuthInformation) => void;\n /** Will be executed if auth-related error happens during normal client operation */\n private readonly onAuthError?: () => void;\n /** Will be executed by the client when it is required */\n private readonly onAuthRefreshProblem?: (error: unknown) => void;\n /** Threshold after which auth info refresh is required */\n private refreshTimestamp?: number;\n\n /** Cached Ping response. Populated by build() before it returns; refreshed by every later ping(). */\n private _serverInfo?: grpcTypes.MaintenanceAPI_Ping_Response;\n private _authMethodsSync?: grpcTypes.AuthAPI_ListMethods_Response;\n\n private _status: PlConnectionStatus = \"OK\";\n private authProbeInFlight = false;\n private readonly statusListener?: PlConnectionStatusListener;\n\n private _wireProto: wireProtocol = \"grpc\";\n private _wireConn!: WireConnection;\n\n private readonly _restInterceptors: Dispatcher.DispatcherComposeInterceptor[];\n private readonly _restMiddlewares: Middleware[];\n private readonly _grpcInterceptors: Interceptor[];\n private readonly providers: WeakRef<WireClientProviderImpl<any>>[] = [];\n\n public readonly clientProvider: WireClientProvider<PlRestClientType | GrpcPlApiClient>;\n\n public readonly httpDispatcher: Dispatcher;\n\n public static async build(\n configOrAddress: PlClientConfig | string,\n ops: {\n auth?: AuthOps;\n statusListener?: PlConnectionStatusListener;\n shouldUseGzip?: boolean;\n logger?: MiLogger;\n useAutoDetectWireProtocol?: boolean;\n } = {},\n ) {\n const conf =\n typeof configOrAddress === \"string\" ? plAddressToConfig(configOrAddress) : configOrAddress;\n\n const pl = new LLPlClient(conf, ops);\n\n // FIXME(rfiskov)[MILAB-5275]: Investigate why autodetect randomly fails; temporary turn it off.\n if (ops.useAutoDetectWireProtocol) {\n await pl.detectOptimalWireProtocol();\n }\n\n // Guarantee a ping happened so capability-gated paths (login, refresh) can branch synchronously.\n // In the autodetect path the loop's last successful ping already populated _serverInfo via the\n // side-effect in ping(); this fallback covers the path where autodetect is disabled.\n if (!pl._serverInfo) await pl.ping();\n\n // Install the process-global signature-strictness flag based on backend version.\n setResourceSignaturesRequired(pl.supportsResourceSignatures);\n\n // Guarantee authMethods happened so client can make weighted decision on which auth method to use.\n if (!pl._authMethodsSync) await pl.authMethods();\n\n return pl;\n }\n\n private constructor(\n public readonly conf: PlClientConfig,\n private readonly ops: {\n auth?: AuthOps;\n statusListener?: PlConnectionStatusListener;\n shouldUseGzip?: boolean;\n logger?: MiLogger;\n } = {},\n ) {\n const { auth, statusListener } = ops;\n\n if (auth !== undefined) {\n this.refreshTimestamp = inferAuthRefreshTime(\n auth.authInformation,\n this.conf.authMaxRefreshSeconds,\n );\n this.authInformation = auth.authInformation;\n this.onAuthUpdate = auth.onUpdate;\n this.onAuthRefreshProblem = auth.onUpdateError;\n this.onAuthError = auth.onAuthError;\n }\n\n this._restInterceptors = [];\n this._restMiddlewares = [];\n this._grpcInterceptors = [];\n\n if (auth !== undefined) {\n this._restInterceptors.push(this.createRestAuthInterceptor());\n this._grpcInterceptors.push(this.createGrpcAuthInterceptor());\n }\n this._restInterceptors.push(interceptors.retry({ statusCodes: [] })); // Handle errors with openapi-fetch middleware.\n this._restMiddlewares.push(this.createRestErrorMiddleware());\n this._grpcInterceptors.push(this.createGrpcErrorInterceptor());\n\n this.httpDispatcher = defaultHttpDispatcher(this.conf.httpProxy);\n if (this.conf.wireProtocol) {\n this._wireProto = this.conf.wireProtocol;\n }\n\n this.initWireConnection(this._wireProto);\n\n if (statusListener !== undefined) {\n this.statusListener = statusListener;\n statusListener(this._status);\n }\n\n this.clientProvider = this.createWireClientProvider((wireConn) => {\n if (wireConn.type === \"grpc\") {\n return new GrpcPlApiClient(wireConn.Transport);\n } else {\n return createClient<PlApiPaths>({\n hostAndPort: wireConn.Config.hostAndPort,\n ssl: wireConn.Config.ssl,\n dispatcher: wireConn.Dispatcher,\n middlewares: wireConn.Middlewares,\n });\n }\n });\n }\n\n private initWireConnection(protocol: wireProtocol) {\n switch (protocol) {\n case \"rest\":\n this.initRestConnection();\n return;\n case \"grpc\":\n this.initGrpcConnection(this.ops.shouldUseGzip ?? false);\n return;\n default:\n ((v: never) => {\n throw new Error(\n `Unsupported wire protocol '${v as string}'. Use one of: ${SUPPORTED_WIRE_PROTOCOLS.join(\", \")}`,\n );\n })(protocol);\n }\n }\n\n private initRestConnection(): void {\n const dispatcher = defaultHttpDispatcher(this.conf.grpcProxy, this._restInterceptors);\n this._replaceWireConnection({\n type: \"rest\",\n Config: this.conf,\n Dispatcher: dispatcher,\n Middlewares: this._restMiddlewares,\n });\n }\n\n /**\n * Initializes (or reinitializes) _grpcTransport\n * @param gzip - whether to enable gzip compression\n */\n private initGrpcConnection(gzip: boolean) {\n const clientOptions: ClientOptions = {\n \"grpc.keepalive_time_ms\": 30_000, // 30 seconds\n \"grpc.service_config_disable_resolution\": 1, // Disable DNS TXT lookups for service config\n // Raises the per-stream and connection-level HTTP/2 windows. Node's 64 KB default\n // caps a big single-stream read (project open) at window/RTT rather than link speed,\n // and a lost WINDOW_UPDATE can deadlock it under packet loss.\n \"grpc-node.flow_control_window\": 16 * 1024 * 1024, // 16 MiB\n interceptors: this._grpcInterceptors,\n };\n\n if (gzip) clientOptions[\"grpc.default_compression_algorithm\"] = compressionAlgorithms.gzip;\n\n //\n // Leaving it here for now\n // https://github.com/grpc/grpc-node/issues/2788\n //\n // We should implement message pooling algorithm to overcome hardcoded NO_DELAY behaviour\n // of HTTP/2 and allow our small messages to batch together.\n //\n const grpcOptions: GrpcOptions = {\n host: this.conf.hostAndPort,\n timeout: this.conf.defaultRequestTimeout,\n channelCredentials: this.conf.ssl\n ? ChannelCredentials.createSsl()\n : ChannelCredentials.createInsecure(),\n clientOptions,\n };\n\n const grpcProxy =\n typeof this.conf.grpcProxy === \"string\" ? { url: this.conf.grpcProxy } : this.conf.grpcProxy;\n\n if (grpcProxy?.url) {\n const url = new URL(grpcProxy.url);\n if (grpcProxy.auth) {\n const parsed = parseHttpAuth(grpcProxy.auth);\n if (parsed.scheme !== \"Basic\") {\n throw new Error(`Unsupported auth scheme: ${parsed.scheme as string}.`);\n }\n url.username = parsed.username;\n url.password = parsed.password;\n }\n process.env.grpc_proxy = url.toString();\n } else {\n delete process.env.grpc_proxy;\n }\n\n this._replaceWireConnection({ type: \"grpc\", Transport: new GrpcTransport(grpcOptions) });\n }\n\n private _replaceWireConnection(newConn: WireConnection): void {\n const oldConn = this._wireConn;\n this._wireConn = newConn;\n this._wireProto = newConn.type;\n\n // Reset all providers to let them reinitialize their clients\n for (let i = 0; i < this.providers.length; i++) {\n const provider = this.providers[i].deref();\n if (provider === undefined) {\n // at the same time we need to remove providers that are no longer valid\n this.providers.splice(i, 1);\n i--;\n } else {\n provider.reset();\n }\n }\n\n if (oldConn !== undefined && oldConn.type === \"grpc\") oldConn.Transport.close();\n }\n\n private providerCleanupCounter = 0;\n\n /**\n * Creates a provider for a grpc client. Returned provider will create fresh client whenever the underlying transport is reset.\n *\n * @param clientConstructor - a factory function that creates a grpc client\n */\n public createWireClientProvider<Client>(\n clientConstructor: (transport: WireConnection) => Client,\n ): WireClientProvider<Client> {\n // We need to cleanup providers periodically to avoid memory leaks.\n // This is a simple heuristic to avoid memory leaks.\n // We could use a more sophisticated algorithm, but this is good enough for now.\n this.providerCleanupCounter++;\n if (this.providerCleanupCounter >= 16) {\n for (let i = 0; i < this.providers.length; i++) {\n const provider = this.providers[i].deref();\n if (provider === undefined) {\n this.providers.splice(i, 1);\n i--;\n }\n }\n this.providerCleanupCounter = 0;\n }\n\n const provider = new WireClientProviderImpl<Client>(() => this._wireConn, clientConstructor);\n this.providers.push(new WeakRef(provider));\n return provider;\n }\n\n public get wireConnection(): WireConnection {\n return this._wireConn;\n }\n\n public get wireProtocol(): wireProtocol | undefined {\n return this._wireProto;\n }\n\n /** Returns true if client is authenticated. Even with anonymous auth information\n * connection is considered authenticated. Unauthenticated clients are used for\n * login and similar tasks, see {@link UnauthenticatedPlClient}. */\n public get authenticated(): boolean {\n return this.authInformation !== undefined;\n }\n\n /** null means anonymous connection */\n public get authUser(): string | null {\n if (!this.authenticated) throw new Error(\"Client is not authenticated\");\n if (this.authInformation?.jwtToken) {\n if (this.hasCapability(\"auth:v2\")) {\n return parsePlJwt(this.authInformation?.jwtToken).sub;\n }\n return parsePlJwt(this.authInformation?.jwtToken).user.login;\n } else return null;\n }\n\n private updateStatus(newStatus: PlConnectionStatus) {\n process.nextTick(() => {\n if (this._status !== newStatus) {\n this._status = newStatus;\n if (this.statusListener !== undefined) this.statusListener(this._status);\n if (newStatus === \"Unauthenticated\" && this.onAuthError !== undefined) this.onAuthError();\n }\n });\n }\n\n /**\n * UNAUTHENTICATED covers both a dead session (must reset) and a per-request authorization failure\n * such as a revoked resource signature (must not). Disambiguate by probing getSessionInfo — an\n * authenticated call with no resource signature: success means the session is alive and the failure\n * was resource-level; a probe that is itself Unauthenticated means real auth loss. Coalesced via\n * authProbeInFlight so a burst of failures costs one probe.\n */\n private async verifyThenMaybeEscalateUnauthenticated(): Promise<void> {\n if (this._status !== \"OK\" || this.authProbeInFlight) return;\n this.authProbeInFlight = true;\n try {\n await this.getSessionInfo();\n } catch (e) {\n if (isUnauthenticated(e)) this.updateStatus(\"Unauthenticated\");\n } finally {\n this.authProbeInFlight = false;\n }\n }\n\n public get status(): PlConnectionStatus {\n return this._status;\n }\n\n private authRefreshInProgress: boolean = false;\n\n private refreshAuthInformationIfNeeded(): void {\n if (\n this.refreshTimestamp === undefined ||\n Date.now() < this.refreshTimestamp ||\n this.authRefreshInProgress ||\n this._status === \"Unauthenticated\"\n )\n return;\n\n // Running refresh in background`\n this.authRefreshInProgress = true;\n void (async () => {\n try {\n const ttl = BigInt(this.conf.authTTLSeconds);\n const token = this.hasCapability(\"auth:v2\")\n ? await this.refreshToken({ ttlSeconds: ttl })\n : await this.getJwtToken(ttl);\n this.authInformation = { jwtToken: token };\n this.refreshTimestamp = inferAuthRefreshTime(\n this.authInformation,\n this.conf.authMaxRefreshSeconds,\n );\n if (this.onAuthUpdate) this.onAuthUpdate(this.authInformation);\n } catch (e: unknown) {\n if (this.onAuthRefreshProblem) this.onAuthRefreshProblem(e);\n } finally {\n this.authRefreshInProgress = false;\n }\n })();\n }\n\n /**\n * Creates middleware that parses error responses and handles them centrally.\n * This middleware runs before openapi-fetch parses the response, so we need to\n * manually parse the response body for error responses.\n */\n private createRestErrorMiddleware(): Middleware {\n return {\n onResponse: async ({ request: _request, response, options: _options }) => {\n const { body, ...resOptions } = response;\n\n if ([502, 503, 504].includes(response.status)) {\n // Service unavailable, bad gateway, gateway timeout\n this.updateStatus(\"Disconnected\");\n return new Response(body, { ...resOptions, status: response.status });\n }\n\n const respErr = await parseResponseError(response);\n if (!respErr.error) {\n // No error: nice!\n return new Response(respErr.origBody ?? body, { ...resOptions, status: response.status });\n }\n\n if (typeof respErr.error === \"string\") {\n // Non-standard error or normal response: let later middleware to deal wit it.\n return new Response(respErr.error, { ...resOptions, status: response.status });\n }\n\n if (respErr.error.code === Code.UNAUTHENTICATED) {\n void this.verifyThenMaybeEscalateUnauthenticated();\n }\n\n // Let later middleware to deal with standard gRPC error.\n return new Response(respErr.origBody, { ...resOptions, status: response.status });\n },\n };\n }\n\n /** Detects certain errors and update client status accordingly when using GRPC wire connection */\n private createGrpcErrorInterceptor(): Interceptor {\n return (options, nextCall) => {\n return new InterceptingCall(nextCall(options), {\n start: (metadata, listener, next) => {\n next(metadata, {\n onReceiveStatus: (status, next) => {\n if (status.code == GrpcStatus.UNAUTHENTICATED)\n // (!!!) don't change to \"===\"\n void this.verifyThenMaybeEscalateUnauthenticated();\n if (status.code == GrpcStatus.UNAVAILABLE)\n // (!!!) don't change to \"===\"\n this.updateStatus(\"Disconnected\");\n next(status);\n },\n });\n },\n });\n };\n }\n\n private createRestAuthInterceptor(): Dispatcher.DispatcherComposeInterceptor {\n return (dispatch) => {\n return (options, handler) => {\n if (this.authInformation?.jwtToken !== undefined) {\n // TODO: check this magic really works and gets called\n options.headers = {\n ...options.headers,\n authorization: \"Bearer \" + this.authInformation.jwtToken,\n };\n this.refreshAuthInformationIfNeeded();\n }\n\n return dispatch(options, handler);\n };\n };\n }\n\n /** Injects authentication information if needed */\n private createGrpcAuthInterceptor(): Interceptor {\n return (options, nextCall) => {\n return new InterceptingCall(nextCall(options), {\n start: (metadata, listener, next) => {\n if (this.authInformation?.jwtToken !== undefined) {\n metadata.set(\"authorization\", \"Bearer \" + this.authInformation.jwtToken);\n this.refreshAuthInformationIfNeeded();\n next(metadata, listener);\n } else {\n next(metadata, listener);\n }\n },\n });\n };\n }\n\n public async getJwtToken(\n ttlSeconds: bigint,\n options?: { authorization?: string; role?: AuthAPI_Role },\n ): Promise<string> {\n const cl = this.clientProvider.get();\n const role = options?.role ?? AuthAPI_Role.UNSPECIFIED;\n\n if (cl instanceof GrpcPlApiClient) {\n const meta: Record<string, string> = {};\n if (options?.authorization) meta.authorization = options.authorization;\n return (\n await cl.getJWTToken(\n {\n expiration: { seconds: ttlSeconds, nanos: 0 },\n requestedRole: role,\n },\n { meta },\n ).response\n ).token;\n } else {\n const headers: Record<string, string> = {};\n if (options?.authorization) headers.authorization = options.authorization;\n const resp = cl.POST(\"/v1/auth/jwt-token\", {\n body: { expiration: `${ttlSeconds}s`, requestedRole: role },\n headers,\n });\n return notEmpty((await resp).data, \"REST: empty response for JWT token request\").token;\n }\n }\n\n /** Login via username/password. Returns a fresh JWT. Backend creates a new session per call. */\n public async loginBasic(\n user: string,\n password: string,\n opts: { ttlSeconds?: bigint; role?: AuthAPI_Role } = {},\n ): Promise<string> {\n const cl = this.clientProvider.get();\n const ttl = opts.ttlSeconds ?? BigInt(this.conf.authTTLSeconds);\n const role = opts.role ?? AuthAPI_Role.UNSPECIFIED;\n\n if (cl instanceof GrpcPlApiClient) {\n return (\n await cl.login({\n credentials: {\n oneofKind: \"basic\",\n basic: { login: user, password },\n },\n expiration: { seconds: ttl, nanos: 0 },\n requestedRole: role,\n }).response\n ).token;\n } else {\n const resp = cl.POST(\"/v1/auth/login\", {\n // openapi-typescript generated all body fields as required, but Login.Request\n // has a credentials oneof — only one of `basic`/`token` is sent. Cast around it.\n body: {\n basic: { login: user, password },\n expiration: `${ttl}s`,\n requestedRole: role,\n } as any,\n });\n return notEmpty((await resp).data, \"REST: empty response for login request\").token;\n }\n }\n\n /** Login via opaque bearer token (controller pre-shared secret, OIDC id-token, etc.).\n * String input is UTF-8 encoded. Returns a fresh Platforma JWT. */\n public async loginWithToken(\n token: Uint8Array | string,\n opts: { ttlSeconds?: bigint; role?: AuthAPI_Role } = {},\n ): Promise<string> {\n const cl = this.clientProvider.get();\n const ttl = opts.ttlSeconds ?? BigInt(this.conf.authTTLSeconds);\n const role = opts.role ?? AuthAPI_Role.UNSPECIFIED;\n const bytes = typeof token === \"string\" ? Buffer.from(token, \"utf8\") : token;\n\n if (cl instanceof GrpcPlApiClient) {\n return (\n await cl.login({\n credentials: {\n oneofKind: \"token\",\n token: { token: bytes },\n },\n expiration: { seconds: ttl, nanos: 0 },\n requestedRole: role,\n }).response\n ).token;\n } else {\n const resp = cl.POST(\"/v1/auth/login\", {\n // openapi-typescript marks all body fields as required, but Login.Request has a oneof.\n // REST encodes `bytes` as a base64 string.\n body: {\n token: { token: Buffer.from(bytes).toString(\"base64\") },\n expiration: `${ttl}s`,\n requestedRole: role,\n } as any,\n });\n return notEmpty((await resp).data, \"REST: empty response for login request\").token;\n }\n }\n\n /** Login via SSO: forwards the raw IdP /token JSON body to the backend.\n * Backend validates signature + nonce + audience and mints a Platforma JWT. */\n public async loginSSO(tokenResponse: Uint8Array): Promise<string> {\n const cl = this.clientProvider.get();\n if (cl instanceof GrpcPlApiClient) {\n return (\n await cl.login({\n credentials: {\n oneofKind: \"sso\",\n sso: { tokenResponse },\n },\n }).response\n ).token;\n } else {\n const resp = cl.POST(\"/v1/auth/login\", {\n body: {\n sso: { tokenResponse: Buffer.from(tokenResponse).toString(\"base64\") },\n } as any,\n });\n return notEmpty((await resp).data, \"REST: empty response for SSO login request\").token;\n }\n }\n\n /** Request a one-time PKCE nonce + its expiry from the backend. The desktop is\n * expected to place the nonce verbatim into the OIDC auth-request before\n * redirecting to the IdP; the backend enforces the expiry on {@link loginSSO}. */\n public async beginSSOLogin(): Promise<{ nonce: string; expiresAt: Date; clientSecret?: string }> {\n const cl = this.clientProvider.get();\n if (cl instanceof GrpcPlApiClient) {\n const resp = (await cl.beginSSOLogin({}).response).flow;\n if (resp.oneofKind !== \"publicPkce\") {\n throw new Error(`beginSSOLogin: unsupported flow ${resp.oneofKind}`);\n }\n const exp = notEmpty(resp.publicPkce.expiresAt, \"beginSSOLogin: missing expiresAt\");\n return {\n nonce: resp.publicPkce.nonce,\n expiresAt: Timestamp.toDate(exp),\n clientSecret: resp.publicPkce.clientSecret,\n };\n } else {\n const wsResponse = notEmpty(\n (await cl.POST(\"/v1/auth/sso/begin-login\", { body: {} })).data,\n \"REST: empty response for beginSSOLogin request\",\n );\n const pkce = notEmpty(wsResponse.publicPkce, \"REST: missing publicPkce in beginSSOLogin\");\n return {\n nonce: pkce.nonce,\n expiresAt: new Date(pkce.expiresAt),\n clientSecret: pkce.clientSecret,\n };\n }\n }\n\n /** Refresh the current JWT, preserving session id and role. */\n public async refreshToken(opts: { ttlSeconds?: bigint } = {}): Promise<string> {\n const cl = this.clientProvider.get();\n const ttl = opts.ttlSeconds ?? BigInt(this.conf.authTTLSeconds);\n const currentToken = notEmpty(\n this.authInformation?.jwtToken,\n \"refreshToken called without a current JWT\",\n );\n\n if (cl instanceof GrpcPlApiClient) {\n return (\n await cl.refreshToken({\n token: currentToken,\n expiration: { seconds: ttl, nanos: 0 },\n }).response\n ).token;\n } else {\n const resp = cl.POST(\"/v1/auth/refresh\", {\n body: { token: currentToken, expiration: `${ttl}s` },\n });\n return notEmpty((await resp).data, \"REST: empty response for refresh request\").token;\n }\n }\n\n public async ping(): Promise<grpcTypes.MaintenanceAPI_Ping_Response> {\n const cl = this.clientProvider.get();\n let resp: grpcTypes.MaintenanceAPI_Ping_Response;\n if (cl instanceof GrpcPlApiClient) {\n resp = (await cl.ping({})).response;\n } else {\n // The REST ping response predates the `capabilities` field (proto field 9).\n // Old servers omit it; treat absence as empty capability list.\n const pingData = notEmpty(\n (await cl.GET(\"/v1/ping\")).data,\n \"REST: empty response for ping request\",\n );\n resp = {\n ...(pingData as unknown as grpcTypes.MaintenanceAPI_Ping_Response),\n capabilities: (pingData as any).capabilities ?? [],\n };\n }\n this._serverInfo = resp;\n return resp;\n }\n\n /** Cached Ping response. Always populated post-build(); throws if accessed earlier. */\n public get serverInfo(): grpcTypes.MaintenanceAPI_Ping_Response {\n if (!this._serverInfo) {\n throw new Error(\"LLPlClient.serverInfo accessed before build() completed\");\n }\n return this._serverInfo;\n }\n\n /** Synchronous capability check against the cached Ping response. */\n public hasCapability(capability: BackendCapability): boolean {\n return hasCapability(this.serverInfo.capabilities, capability);\n }\n\n /** True if the backend produces signed resource ids (and accepts the\n * setDefaultColor TX request). Tagged at 3.3.0 — backends older than this\n * return resources without signatures and reject color-proof requests. */\n public get supportsResourceSignatures(): boolean {\n return isVersionAtLeast(this.serverInfo.coreVersion, [3, 3, 0]);\n }\n\n /**\n * True if the backend honors per-file `permissions` on workdir fill rules, so\n * `exec.builder().writeFile/addFile({ writable: true })` takes effect. When false\n * the requested mode is ignored and files land at the canonical archive perm.\n *\n * [3, 5, 0] excludes the tagged 3.5.0 release but includes dev builds past the\n * tag (e.g. \"3.5.0-224-g0ca182\"), which is where the support lands.\n */\n public get supportsWritableWorkdirFiles(): boolean {\n return isAfterVersion(this.serverInfo.coreVersion, [3, 5, 0]);\n }\n\n /**\n * Detects the best available wire protocol.\n * If wireProtocol is explicitly configured, does nothing.\n * Otherwise probes the current protocol via ping; if it fails, switches to the alternative.\n */\n private async detectOptimalWireProtocol() {\n if (this.conf.wireProtocol) {\n return;\n }\n\n // Each retry is:\n // - ping request timeout (100 to 3_000ms)\n // - backoff delay (30 to 500ms)\n //\n // 30 attempts are ~43 seconds of overall waiting time.\n // Think twice on overall time this thing takes to complete when changing these parameters.\n // It may block UI when connecting to the server and loading projects list.\n const pingTimeoutFactor = 1.3;\n const maxPingTimeoutMs = 3_000;\n const retryOptions: RetryOptions = {\n type: \"exponentialBackoff\",\n maxAttempts: 30,\n initialDelay: 30,\n backoffMultiplier: 1.3,\n jitter: 0.2,\n maxDelay: 500,\n };\n\n let attempt = 1;\n let pingTimeoutMs = 100;\n await retry(\n () => withTimeout(this.ping(), pingTimeoutMs),\n retryOptions,\n (e: unknown) => {\n if (isAbortedError(e)) {\n this.ops.logger?.info(\n `Wire proto autodetect: ping timed out after ${pingTimeoutMs}ms: attempt=${attempt}, wire=${this._wireProto}`,\n );\n\n if (attempt % 2 === 0) {\n // We have 2 wire protocols to check. Increase timeout each 2 attempts.\n pingTimeoutMs = Math.min(\n Math.round(pingTimeoutMs * pingTimeoutFactor),\n maxPingTimeoutMs,\n );\n }\n } else {\n this.ops.logger?.info(\n `Wire proto autodetect: ping failed: attempt=${attempt}, wire=${this._wireProto}, err=${String(e)}`,\n );\n }\n\n attempt++;\n const protocol = this._wireProto === \"grpc\" ? \"rest\" : \"grpc\";\n this.ops.logger?.info(\n `Wire protocol autodetect next attempt: will try wire '${protocol}' with timeout ${pingTimeoutMs}ms`,\n );\n this.initWireConnection(protocol);\n return true;\n },\n );\n }\n\n public async license(): Promise<grpcTypes.MaintenanceAPI_License_Response> {\n const cl = this.clientProvider.get();\n if (cl instanceof GrpcPlApiClient) {\n return (await cl.license({})).response;\n } else {\n const resp = notEmpty(\n (await cl.GET(\"/v1/license\")).data,\n \"REST: empty response for license request\",\n );\n return {\n status: resp.status,\n isOk: resp.isOk,\n responseBody: Uint8Array.from(Buffer.from(resp.responseBody)),\n };\n }\n }\n\n public async authMethods(): Promise<grpcTypes.AuthAPI_ListMethods_Response> {\n const cl = this.clientProvider.get();\n let resp: grpcTypes.AuthAPI_ListMethods_Response;\n if (cl instanceof GrpcPlApiClient) {\n resp = (await cl.authMethods({})).response;\n } else {\n const wsResponse = notEmpty(\n (await cl.GET(\"/v1/auth/methods\")).data,\n \"REST: empty response for auth methods request\",\n );\n // OpenAPI schema flattens the protobuf oneof into `{ basic?, token? }`,\n // while protobuf-ts models it as a discriminated union. Reshape per item.\n resp = {\n methods: (wsResponse.methods ?? []).map((m): grpcTypes.AuthAPI_ListMethods_MethodInfo => {\n const base = { id: m.id, description: m.description };\n if (m.basic !== undefined) {\n return { ...base, method: { oneofKind: \"basic\", basic: m.basic } };\n }\n if (m.token !== undefined) {\n return { ...base, method: { oneofKind: \"token\", token: m.token } };\n }\n if (m.sso !== undefined) {\n return { ...base, method: { oneofKind: \"sso\", sso: m.sso } };\n }\n return { ...base, method: { oneofKind: undefined } };\n }),\n };\n }\n\n this._authMethodsSync = resp;\n return resp;\n }\n\n public get authMethodsSync(): grpcTypes.AuthAPI_ListMethods_Response {\n if (!this._authMethodsSync) {\n throw new Error(\"LLPlClient.authMethodsSync accessed before build() completed\");\n }\n return this._authMethodsSync;\n }\n\n public async getUserRoot(\n opts: { login?: string; createIfNotExists?: boolean } = {},\n ): Promise<grpcTypes.AuthAPI_GetUserRoot_Response> {\n const cl = this.clientProvider.get();\n if (cl instanceof GrpcPlApiClient) {\n return (\n await cl.getUserRoot({\n login: opts.login ?? \"\",\n createIfNotExists: opts.createIfNotExists ?? false,\n })\n ).response;\n } else {\n const resp = notEmpty(\n (\n await cl.POST(\"/v1/auth/user-root\", {\n body: {\n login: opts.login ?? \"\",\n createIfNotExists: opts.createIfNotExists ?? false,\n },\n })\n ).data,\n \"REST: empty response for getUserRoot request\",\n );\n return {\n userRoot: resp.userRoot\n ? {\n resourceId: BigInt(resp.userRoot.resourceId),\n resourceSignature: Uint8Array.from(\n Buffer.from(resp.userRoot.resourceSignature, \"base64\"),\n ),\n }\n : undefined,\n };\n }\n }\n\n public async listUserResources(\n opts: { login?: string; startFrom?: bigint; limit?: number } = {},\n ): Promise<grpcTypes.AuthAPI_ListUserResources_Response[]> {\n const cl = this.clientProvider.get();\n\n if (!(cl instanceof GrpcPlApiClient)) {\n throw new Error(\"ListUserResources requires gRPC wire protocol; REST is not supported\");\n }\n\n const call = cl.listUserResources({\n login: opts.login ?? \"\",\n startFrom: opts.startFrom ?? 0n,\n limit: opts.limit ?? 0,\n });\n const responses: grpcTypes.AuthAPI_ListUserResources_Response[] = [];\n for await (const msg of call.responses) {\n responses.push(msg);\n }\n return responses;\n }\n\n /** Returns the authenticated caller's session id and effective role.\n * Models the {@link getUserRoot} wrapper: gRPC unary with a REST fallback. */\n public async getSessionInfo(): Promise<grpcTypes.AuthAPI_GetSessionInfo_Response> {\n const cl = this.clientProvider.get();\n if (cl instanceof GrpcPlApiClient) {\n return (await cl.getSessionInfo({})).response;\n } else {\n const resp = notEmpty(\n (await cl.POST(\"/v1/auth/session-info\", { body: {} })).data,\n \"REST: empty response for getSessionInfo request\",\n );\n return {\n sessionId: Uint8Array.from(Buffer.from(resp.sessionId, \"base64\")),\n role: resp.role as AuthAPI_Role,\n };\n }\n }\n\n /** Lists the users known to the server — the recipient picker's source. A user\n * becomes known on first login; provisioned users who have never logged in do not\n * appear. gRPC-only (unary, no REST binding). */\n public async listUsers(): Promise<grpcTypes.AuthAPI_User[]> {\n const cl = this.clientProvider.get();\n\n if (!(cl instanceof GrpcPlApiClient)) {\n throw new Error(\"ListUsers requires gRPC wire protocol; REST is not supported\");\n }\n\n return (await cl.listUsers({})).response.users;\n }\n\n public async txSync(txId: bigint): Promise<void> {\n const cl = this.clientProvider.get();\n if (cl instanceof GrpcPlApiClient) {\n await cl.txSync({ txId: BigInt(txId) });\n } else {\n await cl.POST(\"/v1/tx-sync\", { body: { txId: txId.toString() } });\n }\n }\n\n createTx(rw: boolean, ops: PlCallOps = {}): LLPlTransaction {\n return new LLPlTransaction((abortSignal) => {\n let totalAbortSignal = abortSignal;\n if (ops.abortSignal) totalAbortSignal = AbortSignal.any([totalAbortSignal, ops.abortSignal]);\n\n const timeout =\n ops.timeout ??\n (rw ? this.conf.defaultRWTransactionTimeout : this.conf.defaultROTransactionTimeout);\n\n const cl = this.clientProvider.get();\n if (cl instanceof GrpcPlApiClient) {\n return cl.tx({\n abort: totalAbortSignal,\n timeout,\n });\n }\n\n const wireConn = this.wireConnection;\n if (wireConn.type === \"rest\") {\n // For REST/WebSocket protocol, timeout needs to be converted to AbortSignal\n if (timeout !== undefined) {\n totalAbortSignal = AbortSignal.any([totalAbortSignal, AbortSignal.timeout(timeout)]);\n }\n\n // The gRPC transport has the auth interceptor that already handles it, but here we need to refresh the auth information to be safe.\n this.refreshAuthInformationIfNeeded();\n\n const wsUrl = this.conf.ssl\n ? `wss://${this.conf.hostAndPort}/v1/ws/tx`\n : `ws://${this.conf.hostAndPort}/v1/ws/tx`;\n\n return new WebSocketBiDiStream(\n wsUrl,\n (msg) => TxAPI_ClientMessage.toBinary(msg),\n (data) => TxAPI_ServerMessage.fromBinary(new Uint8Array(data)),\n {\n abortSignal: totalAbortSignal,\n jwtToken: this.authInformation?.jwtToken,\n dispatcher: wireConn.Dispatcher,\n\n onComplete: async (stream) =>\n stream.requests.send({\n // Ask server to gracefully close the stream on its side, if not done yet.\n requestId: 0,\n request: { oneofKind: \"streamClose\", streamClose: {} },\n }),\n },\n );\n }\n\n throw new Error(`transactions are not supported for wire protocol ${this._wireProto}`);\n });\n }\n\n /** Closes underlying transport */\n public async close() {\n if (this.wireConnection.type === \"grpc\") {\n this.wireConnection.Transport.close();\n } else {\n // TODO: close all WS connections\n }\n await this.httpDispatcher.destroy();\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAuDA,SAAS,iBAAiB,SAAiB,QAA2C;CACpF,MAAM,QAAQ,yBAAyB,KAAK,OAAO;CACnD,IAAI,CAAC,OAAO,OAAO;CACnB,MAAM,SAAmC;EAAC,OAAO,MAAM,EAAE;EAAG,OAAO,MAAM,EAAE;EAAG,OAAO,MAAM,EAAE;CAAC;CAC9F,KAAK,IAAI,IAAI,GAAG,IAAI,GAAG,KACrB,IAAI,OAAO,OAAO,OAAO,IAAI,OAAO,OAAO,KAAK,OAAO;CAEzD,OAAO;AACT;AAcA,SAAS,eAAe,SAAiB,QAA2C;CAClF,MAAM,QAAQ,8BAA8B,KAAK,OAAO;CACxD,IAAI,CAAC,OAAO,OAAO;CACnB,MAAM,SAAmC;EAAC,OAAO,MAAM,EAAE;EAAG,OAAO,MAAM,EAAE;EAAG,OAAO,MAAM,EAAE;CAAC;CAC9F,MAAM,SAAS,MAAM;CACrB,KAAK,IAAI,IAAI,GAAG,IAAI,GAAG,KACrB,IAAI,OAAO,OAAO,OAAO,IAAI,OAAO,OAAO,KAAK,OAAO;CAEzD,OAAO,WAAW;AACpB;AAEA,IAAM,yBAAN,MAA2E;CAItD;CACA;CAJnB,SAAqC,KAAA;CAErC,YACE,UACA,mBACA;EAFiB,KAAA,WAAA;EACA,KAAA,oBAAA;CAChB;CAEH,QAAqB;EACnB,KAAK,SAAS,KAAA;CAChB;CAEA,MAAqB;EACnB,IAAI,KAAK,WAAW,KAAA,GAAW,KAAK,SAAS,KAAK,kBAAkB,KAAK,SAAS,CAAC;EACnF,OAAO,KAAK;CACd;AACF;;AAGA,IAAa,aAAb,MAAa,WAAgD;CAmEzC;CACC;;CAlEnB;;CAEA;;CAEA;;CAEA;;CAEA;;CAGA;CACA;CAEA,UAAsC;CACtC,oBAA4B;CAC5B;CAEA,aAAmC;CACnC;CAEA;CACA;CAC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EA6Zf,aAAA,CAAc,UAAA,EAAY,iBAAA;EAxYJ;;;EAAA,IA+YlB,0BAAA;EA/XA;;;;;;;;EAAA,IA2YA,4BAAA;EArQH;;;;;EAAA,QA8QM,yBAAA;EA0DD,OAAA,IAAW,OAAA,CAAQ,+BAAA;EAiBnB,WAAA,IAAe,OAAA,CAAQ,4BAAA;EAAA,IAiCzB,eAAA,IAAmB,4BAAA;EAOjB,WAAA,CACX,IAAA;IAAQ,KAAA;IAAgB,iBAAA;EAAA,IACvB,OAAA,CAAQ,4BAAA;EAkCE,iBAAA,CACX,IAAA;IAAQ,KAAA;IAAgB,SAAA;IAAoB,KAAA;EAAA,IAC3C,OAAA,CAAQ,kCAAA;EAjUF;;EAsVI,cAAA,IAAkB,OAAA,CAAQ,+BAAA;EArVR;;;EAwWlB,SAAA,IAAa,OAAA,CAAQ,YAAA;EAUrB,MAAA,CAAO,IAAA,WAAe,OAAA;EASnC,QAAA,CAAS,EAAA,WAAa,GAAA,GAAK,SAAA,GAAiB,eAAA;EAzVtB;EAgZT,KAAA,IAAK,OAAA;AAAA"}
@@ -160,6 +160,7 @@ var LLPlClient = class LLPlClient {
160
160
  const clientOptions = {
161
161
  "grpc.keepalive_time_ms": 3e4,
162
162
  "grpc.service_config_disable_resolution": 1,
163
+ "grpc-node.flow_control_window": 16 * 1024 * 1024,
163
164
  interceptors: this._grpcInterceptors
164
165
  };
165
166
  if (gzip) clientOptions["grpc.default_compression_algorithm"] = compressionAlgorithms.gzip;
@@ -1 +1 @@
1
- {"version":3,"file":"ll_client.js","names":["GrpcPlApiClient","status","GrpcStatus"],"sources":["../../src/core/ll_client.ts"],"sourcesContent":["import { PlatformClient as GrpcPlApiClient } from \"../proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api.client\";\nimport type { ClientOptions, Interceptor } from \"@grpc/grpc-js\";\nimport {\n ChannelCredentials,\n InterceptingCall,\n status as GrpcStatus,\n compressionAlgorithms,\n} from \"@grpc/grpc-js\";\nimport type {\n AuthInformation,\n AuthOps,\n PlClientConfig,\n PlConnectionStatus,\n PlConnectionStatusListener,\n} from \"./config\";\nimport { plAddressToConfig, type wireProtocol, SUPPORTED_WIRE_PROTOCOLS } from \"./config\";\nimport type { GrpcOptions } from \"@protobuf-ts/grpc-transport\";\nimport { GrpcTransport } from \"@protobuf-ts/grpc-transport\";\nimport { LLPlTransaction } from \"./ll_transaction\";\nimport { setResourceSignaturesRequired } from \"./types\";\nimport { parsePlJwt } from \"../util/pl\";\nimport { type Dispatcher, interceptors } from \"undici\";\nimport type { Middleware } from \"openapi-fetch\";\nimport { inferAuthRefreshTime } from \"./auth\";\nimport { hasCapability, type BackendCapability } from \"./capabilities\";\nimport { defaultHttpDispatcher } from \"@milaboratories/pl-http\";\nimport type { WireClientProvider, WireClientProviderFactory, WireConnection } from \"./wire\";\nimport { parseHttpAuth } from \"@milaboratories/pl-model-common\";\nimport type * as grpcTypes from \"../proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api\";\nimport {\n type PlApiPaths,\n type PlRestClientType,\n createClient,\n parseResponseError,\n} from \"../proto-rest\";\nimport { notEmpty, retry, withTimeout, type RetryOptions } from \"@milaboratories/ts-helpers\";\nimport { Code } from \"../proto-grpc/google/rpc/code\";\nimport { WebSocketBiDiStream } from \"./websocket_stream\";\nimport {\n AuthAPI_Role,\n TxAPI_ClientMessage,\n TxAPI_ServerMessage,\n} from \"../proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api\";\nimport type { MiLogger } from \"@milaboratories/ts-helpers\";\nimport { isAbortedError, isUnauthenticated } from \"./errors\";\nimport { Timestamp } from \"../proto-grpc/google/protobuf/timestamp\";\n\nexport interface PlCallOps {\n timeout?: number;\n abortSignal?: AbortSignal;\n}\n\n// Parses leading \"<major>.<minor>.<patch>\" from a version string like\n// \"3.1.1\" or \"3.1.1-rc1\" and returns true if the parsed version is >= target.\n// Returns false for unparseable versions (safer to assume an old backend).\nfunction isVersionAtLeast(version: string, target: [number, number, number]): boolean {\n const match = /^v?(\\d+)\\.(\\d+)\\.(\\d+)/.exec(version);\n if (!match) return false;\n const parsed: [number, number, number] = [Number(match[1]), Number(match[2]), Number(match[3])];\n for (let i = 0; i < 3; i++) {\n if (parsed[i] !== target[i]) return parsed[i] > target[i];\n }\n return true;\n}\n\n// Returns true iff `version` is strictly after the release tag `target`. Dev\n// builds (`git describe`-style, e.g. \"3.5.0-224-g0ca182\") are considered\n// AFTER the matching release tag — they include commits past the tag and so\n// have any change merged after it. Released versions with the same triplet\n// return false (we want the tag itself to be excluded).\n//\n// Examples for target [3,5,0]:\n// \"3.5.0\" → false (the tagged release)\n// \"3.5.0-224-g0ca182\" → true (dev build past the tag)\n// \"3.5.1\" → true\n// \"3.4.9\" → false\n// Returns false for unparseable versions.\nfunction isAfterVersion(version: string, target: [number, number, number]): boolean {\n const match = /^v?(\\d+)\\.(\\d+)\\.(\\d+)(.*)$/.exec(version);\n if (!match) return false;\n const parsed: [number, number, number] = [Number(match[1]), Number(match[2]), Number(match[3])];\n const suffix = match[4];\n for (let i = 0; i < 3; i++) {\n if (parsed[i] !== target[i]) return parsed[i] > target[i];\n }\n return suffix !== \"\";\n}\n\nclass WireClientProviderImpl<Client> implements WireClientProvider<Client> {\n private client: Client | undefined = undefined;\n\n constructor(\n private readonly wireOpts: () => WireConnection,\n private readonly clientConstructor: (wireOpts: WireConnection) => Client,\n ) {}\n\n public reset(): void {\n this.client = undefined;\n }\n\n public get(): Client {\n if (this.client === undefined) this.client = this.clientConstructor(this.wireOpts());\n return this.client;\n }\n}\n\n/** Abstract out low level networking and authorization details */\nexport class LLPlClient implements WireClientProviderFactory {\n /** Initial authorization information */\n private authInformation?: AuthInformation;\n /** Will be executed by the client when it is required */\n private readonly onAuthUpdate?: (newInfo: AuthInformation) => void;\n /** Will be executed if auth-related error happens during normal client operation */\n private readonly onAuthError?: () => void;\n /** Will be executed by the client when it is required */\n private readonly onAuthRefreshProblem?: (error: unknown) => void;\n /** Threshold after which auth info refresh is required */\n private refreshTimestamp?: number;\n\n /** Cached Ping response. Populated by build() before it returns; refreshed by every later ping(). */\n private _serverInfo?: grpcTypes.MaintenanceAPI_Ping_Response;\n private _authMethodsSync?: grpcTypes.AuthAPI_ListMethods_Response;\n\n private _status: PlConnectionStatus = \"OK\";\n private authProbeInFlight = false;\n private readonly statusListener?: PlConnectionStatusListener;\n\n private _wireProto: wireProtocol = \"grpc\";\n private _wireConn!: WireConnection;\n\n private readonly _restInterceptors: Dispatcher.DispatcherComposeInterceptor[];\n private readonly _restMiddlewares: Middleware[];\n private readonly _grpcInterceptors: Interceptor[];\n private readonly providers: WeakRef<WireClientProviderImpl<any>>[] = [];\n\n public readonly clientProvider: WireClientProvider<PlRestClientType | GrpcPlApiClient>;\n\n public readonly httpDispatcher: Dispatcher;\n\n public static async build(\n configOrAddress: PlClientConfig | string,\n ops: {\n auth?: AuthOps;\n statusListener?: PlConnectionStatusListener;\n shouldUseGzip?: boolean;\n logger?: MiLogger;\n useAutoDetectWireProtocol?: boolean;\n } = {},\n ) {\n const conf =\n typeof configOrAddress === \"string\" ? plAddressToConfig(configOrAddress) : configOrAddress;\n\n const pl = new LLPlClient(conf, ops);\n\n // FIXME(rfiskov)[MILAB-5275]: Investigate why autodetect randomly fails; temporary turn it off.\n if (ops.useAutoDetectWireProtocol) {\n await pl.detectOptimalWireProtocol();\n }\n\n // Guarantee a ping happened so capability-gated paths (login, refresh) can branch synchronously.\n // In the autodetect path the loop's last successful ping already populated _serverInfo via the\n // side-effect in ping(); this fallback covers the path where autodetect is disabled.\n if (!pl._serverInfo) await pl.ping();\n\n // Install the process-global signature-strictness flag based on backend version.\n setResourceSignaturesRequired(pl.supportsResourceSignatures);\n\n // Guarantee authMethods happened so client can make weighted decision on which auth method to use.\n if (!pl._authMethodsSync) await pl.authMethods();\n\n return pl;\n }\n\n private constructor(\n public readonly conf: PlClientConfig,\n private readonly ops: {\n auth?: AuthOps;\n statusListener?: PlConnectionStatusListener;\n shouldUseGzip?: boolean;\n logger?: MiLogger;\n } = {},\n ) {\n const { auth, statusListener } = ops;\n\n if (auth !== undefined) {\n this.refreshTimestamp = inferAuthRefreshTime(\n auth.authInformation,\n this.conf.authMaxRefreshSeconds,\n );\n this.authInformation = auth.authInformation;\n this.onAuthUpdate = auth.onUpdate;\n this.onAuthRefreshProblem = auth.onUpdateError;\n this.onAuthError = auth.onAuthError;\n }\n\n this._restInterceptors = [];\n this._restMiddlewares = [];\n this._grpcInterceptors = [];\n\n if (auth !== undefined) {\n this._restInterceptors.push(this.createRestAuthInterceptor());\n this._grpcInterceptors.push(this.createGrpcAuthInterceptor());\n }\n this._restInterceptors.push(interceptors.retry({ statusCodes: [] })); // Handle errors with openapi-fetch middleware.\n this._restMiddlewares.push(this.createRestErrorMiddleware());\n this._grpcInterceptors.push(this.createGrpcErrorInterceptor());\n\n this.httpDispatcher = defaultHttpDispatcher(this.conf.httpProxy);\n if (this.conf.wireProtocol) {\n this._wireProto = this.conf.wireProtocol;\n }\n\n this.initWireConnection(this._wireProto);\n\n if (statusListener !== undefined) {\n this.statusListener = statusListener;\n statusListener(this._status);\n }\n\n this.clientProvider = this.createWireClientProvider((wireConn) => {\n if (wireConn.type === \"grpc\") {\n return new GrpcPlApiClient(wireConn.Transport);\n } else {\n return createClient<PlApiPaths>({\n hostAndPort: wireConn.Config.hostAndPort,\n ssl: wireConn.Config.ssl,\n dispatcher: wireConn.Dispatcher,\n middlewares: wireConn.Middlewares,\n });\n }\n });\n }\n\n private initWireConnection(protocol: wireProtocol) {\n switch (protocol) {\n case \"rest\":\n this.initRestConnection();\n return;\n case \"grpc\":\n this.initGrpcConnection(this.ops.shouldUseGzip ?? false);\n return;\n default:\n ((v: never) => {\n throw new Error(\n `Unsupported wire protocol '${v as string}'. Use one of: ${SUPPORTED_WIRE_PROTOCOLS.join(\", \")}`,\n );\n })(protocol);\n }\n }\n\n private initRestConnection(): void {\n const dispatcher = defaultHttpDispatcher(this.conf.grpcProxy, this._restInterceptors);\n this._replaceWireConnection({\n type: \"rest\",\n Config: this.conf,\n Dispatcher: dispatcher,\n Middlewares: this._restMiddlewares,\n });\n }\n\n /**\n * Initializes (or reinitializes) _grpcTransport\n * @param gzip - whether to enable gzip compression\n */\n private initGrpcConnection(gzip: boolean) {\n const clientOptions: ClientOptions = {\n \"grpc.keepalive_time_ms\": 30_000, // 30 seconds\n \"grpc.service_config_disable_resolution\": 1, // Disable DNS TXT lookups for service config\n interceptors: this._grpcInterceptors,\n };\n\n if (gzip) clientOptions[\"grpc.default_compression_algorithm\"] = compressionAlgorithms.gzip;\n\n //\n // Leaving it here for now\n // https://github.com/grpc/grpc-node/issues/2788\n //\n // We should implement message pooling algorithm to overcome hardcoded NO_DELAY behaviour\n // of HTTP/2 and allow our small messages to batch together.\n //\n const grpcOptions: GrpcOptions = {\n host: this.conf.hostAndPort,\n timeout: this.conf.defaultRequestTimeout,\n channelCredentials: this.conf.ssl\n ? ChannelCredentials.createSsl()\n : ChannelCredentials.createInsecure(),\n clientOptions,\n };\n\n const grpcProxy =\n typeof this.conf.grpcProxy === \"string\" ? { url: this.conf.grpcProxy } : this.conf.grpcProxy;\n\n if (grpcProxy?.url) {\n const url = new URL(grpcProxy.url);\n if (grpcProxy.auth) {\n const parsed = parseHttpAuth(grpcProxy.auth);\n if (parsed.scheme !== \"Basic\") {\n throw new Error(`Unsupported auth scheme: ${parsed.scheme as string}.`);\n }\n url.username = parsed.username;\n url.password = parsed.password;\n }\n process.env.grpc_proxy = url.toString();\n } else {\n delete process.env.grpc_proxy;\n }\n\n this._replaceWireConnection({ type: \"grpc\", Transport: new GrpcTransport(grpcOptions) });\n }\n\n private _replaceWireConnection(newConn: WireConnection): void {\n const oldConn = this._wireConn;\n this._wireConn = newConn;\n this._wireProto = newConn.type;\n\n // Reset all providers to let them reinitialize their clients\n for (let i = 0; i < this.providers.length; i++) {\n const provider = this.providers[i].deref();\n if (provider === undefined) {\n // at the same time we need to remove providers that are no longer valid\n this.providers.splice(i, 1);\n i--;\n } else {\n provider.reset();\n }\n }\n\n if (oldConn !== undefined && oldConn.type === \"grpc\") oldConn.Transport.close();\n }\n\n private providerCleanupCounter = 0;\n\n /**\n * Creates a provider for a grpc client. Returned provider will create fresh client whenever the underlying transport is reset.\n *\n * @param clientConstructor - a factory function that creates a grpc client\n */\n public createWireClientProvider<Client>(\n clientConstructor: (transport: WireConnection) => Client,\n ): WireClientProvider<Client> {\n // We need to cleanup providers periodically to avoid memory leaks.\n // This is a simple heuristic to avoid memory leaks.\n // We could use a more sophisticated algorithm, but this is good enough for now.\n this.providerCleanupCounter++;\n if (this.providerCleanupCounter >= 16) {\n for (let i = 0; i < this.providers.length; i++) {\n const provider = this.providers[i].deref();\n if (provider === undefined) {\n this.providers.splice(i, 1);\n i--;\n }\n }\n this.providerCleanupCounter = 0;\n }\n\n const provider = new WireClientProviderImpl<Client>(() => this._wireConn, clientConstructor);\n this.providers.push(new WeakRef(provider));\n return provider;\n }\n\n public get wireConnection(): WireConnection {\n return this._wireConn;\n }\n\n public get wireProtocol(): wireProtocol | undefined {\n return this._wireProto;\n }\n\n /** Returns true if client is authenticated. Even with anonymous auth information\n * connection is considered authenticated. Unauthenticated clients are used for\n * login and similar tasks, see {@link UnauthenticatedPlClient}. */\n public get authenticated(): boolean {\n return this.authInformation !== undefined;\n }\n\n /** null means anonymous connection */\n public get authUser(): string | null {\n if (!this.authenticated) throw new Error(\"Client is not authenticated\");\n if (this.authInformation?.jwtToken) {\n if (this.hasCapability(\"auth:v2\")) {\n return parsePlJwt(this.authInformation?.jwtToken).sub;\n }\n return parsePlJwt(this.authInformation?.jwtToken).user.login;\n } else return null;\n }\n\n private updateStatus(newStatus: PlConnectionStatus) {\n process.nextTick(() => {\n if (this._status !== newStatus) {\n this._status = newStatus;\n if (this.statusListener !== undefined) this.statusListener(this._status);\n if (newStatus === \"Unauthenticated\" && this.onAuthError !== undefined) this.onAuthError();\n }\n });\n }\n\n /**\n * UNAUTHENTICATED covers both a dead session (must reset) and a per-request authorization failure\n * such as a revoked resource signature (must not). Disambiguate by probing getSessionInfo — an\n * authenticated call with no resource signature: success means the session is alive and the failure\n * was resource-level; a probe that is itself Unauthenticated means real auth loss. Coalesced via\n * authProbeInFlight so a burst of failures costs one probe.\n */\n private async verifyThenMaybeEscalateUnauthenticated(): Promise<void> {\n if (this._status !== \"OK\" || this.authProbeInFlight) return;\n this.authProbeInFlight = true;\n try {\n await this.getSessionInfo();\n } catch (e) {\n if (isUnauthenticated(e)) this.updateStatus(\"Unauthenticated\");\n } finally {\n this.authProbeInFlight = false;\n }\n }\n\n public get status(): PlConnectionStatus {\n return this._status;\n }\n\n private authRefreshInProgress: boolean = false;\n\n private refreshAuthInformationIfNeeded(): void {\n if (\n this.refreshTimestamp === undefined ||\n Date.now() < this.refreshTimestamp ||\n this.authRefreshInProgress ||\n this._status === \"Unauthenticated\"\n )\n return;\n\n // Running refresh in background`\n this.authRefreshInProgress = true;\n void (async () => {\n try {\n const ttl = BigInt(this.conf.authTTLSeconds);\n const token = this.hasCapability(\"auth:v2\")\n ? await this.refreshToken({ ttlSeconds: ttl })\n : await this.getJwtToken(ttl);\n this.authInformation = { jwtToken: token };\n this.refreshTimestamp = inferAuthRefreshTime(\n this.authInformation,\n this.conf.authMaxRefreshSeconds,\n );\n if (this.onAuthUpdate) this.onAuthUpdate(this.authInformation);\n } catch (e: unknown) {\n if (this.onAuthRefreshProblem) this.onAuthRefreshProblem(e);\n } finally {\n this.authRefreshInProgress = false;\n }\n })();\n }\n\n /**\n * Creates middleware that parses error responses and handles them centrally.\n * This middleware runs before openapi-fetch parses the response, so we need to\n * manually parse the response body for error responses.\n */\n private createRestErrorMiddleware(): Middleware {\n return {\n onResponse: async ({ request: _request, response, options: _options }) => {\n const { body, ...resOptions } = response;\n\n if ([502, 503, 504].includes(response.status)) {\n // Service unavailable, bad gateway, gateway timeout\n this.updateStatus(\"Disconnected\");\n return new Response(body, { ...resOptions, status: response.status });\n }\n\n const respErr = await parseResponseError(response);\n if (!respErr.error) {\n // No error: nice!\n return new Response(respErr.origBody ?? body, { ...resOptions, status: response.status });\n }\n\n if (typeof respErr.error === \"string\") {\n // Non-standard error or normal response: let later middleware to deal wit it.\n return new Response(respErr.error, { ...resOptions, status: response.status });\n }\n\n if (respErr.error.code === Code.UNAUTHENTICATED) {\n void this.verifyThenMaybeEscalateUnauthenticated();\n }\n\n // Let later middleware to deal with standard gRPC error.\n return new Response(respErr.origBody, { ...resOptions, status: response.status });\n },\n };\n }\n\n /** Detects certain errors and update client status accordingly when using GRPC wire connection */\n private createGrpcErrorInterceptor(): Interceptor {\n return (options, nextCall) => {\n return new InterceptingCall(nextCall(options), {\n start: (metadata, listener, next) => {\n next(metadata, {\n onReceiveStatus: (status, next) => {\n if (status.code == GrpcStatus.UNAUTHENTICATED)\n // (!!!) don't change to \"===\"\n void this.verifyThenMaybeEscalateUnauthenticated();\n if (status.code == GrpcStatus.UNAVAILABLE)\n // (!!!) don't change to \"===\"\n this.updateStatus(\"Disconnected\");\n next(status);\n },\n });\n },\n });\n };\n }\n\n private createRestAuthInterceptor(): Dispatcher.DispatcherComposeInterceptor {\n return (dispatch) => {\n return (options, handler) => {\n if (this.authInformation?.jwtToken !== undefined) {\n // TODO: check this magic really works and gets called\n options.headers = {\n ...options.headers,\n authorization: \"Bearer \" + this.authInformation.jwtToken,\n };\n this.refreshAuthInformationIfNeeded();\n }\n\n return dispatch(options, handler);\n };\n };\n }\n\n /** Injects authentication information if needed */\n private createGrpcAuthInterceptor(): Interceptor {\n return (options, nextCall) => {\n return new InterceptingCall(nextCall(options), {\n start: (metadata, listener, next) => {\n if (this.authInformation?.jwtToken !== undefined) {\n metadata.set(\"authorization\", \"Bearer \" + this.authInformation.jwtToken);\n this.refreshAuthInformationIfNeeded();\n next(metadata, listener);\n } else {\n next(metadata, listener);\n }\n },\n });\n };\n }\n\n public async getJwtToken(\n ttlSeconds: bigint,\n options?: { authorization?: string; role?: AuthAPI_Role },\n ): Promise<string> {\n const cl = this.clientProvider.get();\n const role = options?.role ?? AuthAPI_Role.UNSPECIFIED;\n\n if (cl instanceof GrpcPlApiClient) {\n const meta: Record<string, string> = {};\n if (options?.authorization) meta.authorization = options.authorization;\n return (\n await cl.getJWTToken(\n {\n expiration: { seconds: ttlSeconds, nanos: 0 },\n requestedRole: role,\n },\n { meta },\n ).response\n ).token;\n } else {\n const headers: Record<string, string> = {};\n if (options?.authorization) headers.authorization = options.authorization;\n const resp = cl.POST(\"/v1/auth/jwt-token\", {\n body: { expiration: `${ttlSeconds}s`, requestedRole: role },\n headers,\n });\n return notEmpty((await resp).data, \"REST: empty response for JWT token request\").token;\n }\n }\n\n /** Login via username/password. Returns a fresh JWT. Backend creates a new session per call. */\n public async loginBasic(\n user: string,\n password: string,\n opts: { ttlSeconds?: bigint; role?: AuthAPI_Role } = {},\n ): Promise<string> {\n const cl = this.clientProvider.get();\n const ttl = opts.ttlSeconds ?? BigInt(this.conf.authTTLSeconds);\n const role = opts.role ?? AuthAPI_Role.UNSPECIFIED;\n\n if (cl instanceof GrpcPlApiClient) {\n return (\n await cl.login({\n credentials: {\n oneofKind: \"basic\",\n basic: { login: user, password },\n },\n expiration: { seconds: ttl, nanos: 0 },\n requestedRole: role,\n }).response\n ).token;\n } else {\n const resp = cl.POST(\"/v1/auth/login\", {\n // openapi-typescript generated all body fields as required, but Login.Request\n // has a credentials oneof — only one of `basic`/`token` is sent. Cast around it.\n body: {\n basic: { login: user, password },\n expiration: `${ttl}s`,\n requestedRole: role,\n } as any,\n });\n return notEmpty((await resp).data, \"REST: empty response for login request\").token;\n }\n }\n\n /** Login via opaque bearer token (controller pre-shared secret, OIDC id-token, etc.).\n * String input is UTF-8 encoded. Returns a fresh Platforma JWT. */\n public async loginWithToken(\n token: Uint8Array | string,\n opts: { ttlSeconds?: bigint; role?: AuthAPI_Role } = {},\n ): Promise<string> {\n const cl = this.clientProvider.get();\n const ttl = opts.ttlSeconds ?? BigInt(this.conf.authTTLSeconds);\n const role = opts.role ?? AuthAPI_Role.UNSPECIFIED;\n const bytes = typeof token === \"string\" ? Buffer.from(token, \"utf8\") : token;\n\n if (cl instanceof GrpcPlApiClient) {\n return (\n await cl.login({\n credentials: {\n oneofKind: \"token\",\n token: { token: bytes },\n },\n expiration: { seconds: ttl, nanos: 0 },\n requestedRole: role,\n }).response\n ).token;\n } else {\n const resp = cl.POST(\"/v1/auth/login\", {\n // openapi-typescript marks all body fields as required, but Login.Request has a oneof.\n // REST encodes `bytes` as a base64 string.\n body: {\n token: { token: Buffer.from(bytes).toString(\"base64\") },\n expiration: `${ttl}s`,\n requestedRole: role,\n } as any,\n });\n return notEmpty((await resp).data, \"REST: empty response for login request\").token;\n }\n }\n\n /** Login via SSO: forwards the raw IdP /token JSON body to the backend.\n * Backend validates signature + nonce + audience and mints a Platforma JWT. */\n public async loginSSO(tokenResponse: Uint8Array): Promise<string> {\n const cl = this.clientProvider.get();\n if (cl instanceof GrpcPlApiClient) {\n return (\n await cl.login({\n credentials: {\n oneofKind: \"sso\",\n sso: { tokenResponse },\n },\n }).response\n ).token;\n } else {\n const resp = cl.POST(\"/v1/auth/login\", {\n body: {\n sso: { tokenResponse: Buffer.from(tokenResponse).toString(\"base64\") },\n } as any,\n });\n return notEmpty((await resp).data, \"REST: empty response for SSO login request\").token;\n }\n }\n\n /** Request a one-time PKCE nonce + its expiry from the backend. The desktop is\n * expected to place the nonce verbatim into the OIDC auth-request before\n * redirecting to the IdP; the backend enforces the expiry on {@link loginSSO}. */\n public async beginSSOLogin(): Promise<{ nonce: string; expiresAt: Date; clientSecret?: string }> {\n const cl = this.clientProvider.get();\n if (cl instanceof GrpcPlApiClient) {\n const resp = (await cl.beginSSOLogin({}).response).flow;\n if (resp.oneofKind !== \"publicPkce\") {\n throw new Error(`beginSSOLogin: unsupported flow ${resp.oneofKind}`);\n }\n const exp = notEmpty(resp.publicPkce.expiresAt, \"beginSSOLogin: missing expiresAt\");\n return {\n nonce: resp.publicPkce.nonce,\n expiresAt: Timestamp.toDate(exp),\n clientSecret: resp.publicPkce.clientSecret,\n };\n } else {\n const wsResponse = notEmpty(\n (await cl.POST(\"/v1/auth/sso/begin-login\", { body: {} })).data,\n \"REST: empty response for beginSSOLogin request\",\n );\n const pkce = notEmpty(wsResponse.publicPkce, \"REST: missing publicPkce in beginSSOLogin\");\n return {\n nonce: pkce.nonce,\n expiresAt: new Date(pkce.expiresAt),\n clientSecret: pkce.clientSecret,\n };\n }\n }\n\n /** Refresh the current JWT, preserving session id and role. */\n public async refreshToken(opts: { ttlSeconds?: bigint } = {}): Promise<string> {\n const cl = this.clientProvider.get();\n const ttl = opts.ttlSeconds ?? BigInt(this.conf.authTTLSeconds);\n const currentToken = notEmpty(\n this.authInformation?.jwtToken,\n \"refreshToken called without a current JWT\",\n );\n\n if (cl instanceof GrpcPlApiClient) {\n return (\n await cl.refreshToken({\n token: currentToken,\n expiration: { seconds: ttl, nanos: 0 },\n }).response\n ).token;\n } else {\n const resp = cl.POST(\"/v1/auth/refresh\", {\n body: { token: currentToken, expiration: `${ttl}s` },\n });\n return notEmpty((await resp).data, \"REST: empty response for refresh request\").token;\n }\n }\n\n public async ping(): Promise<grpcTypes.MaintenanceAPI_Ping_Response> {\n const cl = this.clientProvider.get();\n let resp: grpcTypes.MaintenanceAPI_Ping_Response;\n if (cl instanceof GrpcPlApiClient) {\n resp = (await cl.ping({})).response;\n } else {\n // The REST ping response predates the `capabilities` field (proto field 9).\n // Old servers omit it; treat absence as empty capability list.\n const pingData = notEmpty(\n (await cl.GET(\"/v1/ping\")).data,\n \"REST: empty response for ping request\",\n );\n resp = {\n ...(pingData as unknown as grpcTypes.MaintenanceAPI_Ping_Response),\n capabilities: (pingData as any).capabilities ?? [],\n };\n }\n this._serverInfo = resp;\n return resp;\n }\n\n /** Cached Ping response. Always populated post-build(); throws if accessed earlier. */\n public get serverInfo(): grpcTypes.MaintenanceAPI_Ping_Response {\n if (!this._serverInfo) {\n throw new Error(\"LLPlClient.serverInfo accessed before build() completed\");\n }\n return this._serverInfo;\n }\n\n /** Synchronous capability check against the cached Ping response. */\n public hasCapability(capability: BackendCapability): boolean {\n return hasCapability(this.serverInfo.capabilities, capability);\n }\n\n /** True if the backend produces signed resource ids (and accepts the\n * setDefaultColor TX request). Tagged at 3.3.0 — backends older than this\n * return resources without signatures and reject color-proof requests. */\n public get supportsResourceSignatures(): boolean {\n return isVersionAtLeast(this.serverInfo.coreVersion, [3, 3, 0]);\n }\n\n /**\n * True if the backend honors per-file `permissions` on workdir fill rules, so\n * `exec.builder().writeFile/addFile({ writable: true })` takes effect. When false\n * the requested mode is ignored and files land at the canonical archive perm.\n *\n * [3, 5, 0] excludes the tagged 3.5.0 release but includes dev builds past the\n * tag (e.g. \"3.5.0-224-g0ca182\"), which is where the support lands.\n */\n public get supportsWritableWorkdirFiles(): boolean {\n return isAfterVersion(this.serverInfo.coreVersion, [3, 5, 0]);\n }\n\n /**\n * Detects the best available wire protocol.\n * If wireProtocol is explicitly configured, does nothing.\n * Otherwise probes the current protocol via ping; if it fails, switches to the alternative.\n */\n private async detectOptimalWireProtocol() {\n if (this.conf.wireProtocol) {\n return;\n }\n\n // Each retry is:\n // - ping request timeout (100 to 3_000ms)\n // - backoff delay (30 to 500ms)\n //\n // 30 attempts are ~43 seconds of overall waiting time.\n // Think twice on overall time this thing takes to complete when changing these parameters.\n // It may block UI when connecting to the server and loading projects list.\n const pingTimeoutFactor = 1.3;\n const maxPingTimeoutMs = 3_000;\n const retryOptions: RetryOptions = {\n type: \"exponentialBackoff\",\n maxAttempts: 30,\n initialDelay: 30,\n backoffMultiplier: 1.3,\n jitter: 0.2,\n maxDelay: 500,\n };\n\n let attempt = 1;\n let pingTimeoutMs = 100;\n await retry(\n () => withTimeout(this.ping(), pingTimeoutMs),\n retryOptions,\n (e: unknown) => {\n if (isAbortedError(e)) {\n this.ops.logger?.info(\n `Wire proto autodetect: ping timed out after ${pingTimeoutMs}ms: attempt=${attempt}, wire=${this._wireProto}`,\n );\n\n if (attempt % 2 === 0) {\n // We have 2 wire protocols to check. Increase timeout each 2 attempts.\n pingTimeoutMs = Math.min(\n Math.round(pingTimeoutMs * pingTimeoutFactor),\n maxPingTimeoutMs,\n );\n }\n } else {\n this.ops.logger?.info(\n `Wire proto autodetect: ping failed: attempt=${attempt}, wire=${this._wireProto}, err=${String(e)}`,\n );\n }\n\n attempt++;\n const protocol = this._wireProto === \"grpc\" ? \"rest\" : \"grpc\";\n this.ops.logger?.info(\n `Wire protocol autodetect next attempt: will try wire '${protocol}' with timeout ${pingTimeoutMs}ms`,\n );\n this.initWireConnection(protocol);\n return true;\n },\n );\n }\n\n public async license(): Promise<grpcTypes.MaintenanceAPI_License_Response> {\n const cl = this.clientProvider.get();\n if (cl instanceof GrpcPlApiClient) {\n return (await cl.license({})).response;\n } else {\n const resp = notEmpty(\n (await cl.GET(\"/v1/license\")).data,\n \"REST: empty response for license request\",\n );\n return {\n status: resp.status,\n isOk: resp.isOk,\n responseBody: Uint8Array.from(Buffer.from(resp.responseBody)),\n };\n }\n }\n\n public async authMethods(): Promise<grpcTypes.AuthAPI_ListMethods_Response> {\n const cl = this.clientProvider.get();\n let resp: grpcTypes.AuthAPI_ListMethods_Response;\n if (cl instanceof GrpcPlApiClient) {\n resp = (await cl.authMethods({})).response;\n } else {\n const wsResponse = notEmpty(\n (await cl.GET(\"/v1/auth/methods\")).data,\n \"REST: empty response for auth methods request\",\n );\n // OpenAPI schema flattens the protobuf oneof into `{ basic?, token? }`,\n // while protobuf-ts models it as a discriminated union. Reshape per item.\n resp = {\n methods: (wsResponse.methods ?? []).map((m): grpcTypes.AuthAPI_ListMethods_MethodInfo => {\n const base = { id: m.id, description: m.description };\n if (m.basic !== undefined) {\n return { ...base, method: { oneofKind: \"basic\", basic: m.basic } };\n }\n if (m.token !== undefined) {\n return { ...base, method: { oneofKind: \"token\", token: m.token } };\n }\n if (m.sso !== undefined) {\n return { ...base, method: { oneofKind: \"sso\", sso: m.sso } };\n }\n return { ...base, method: { oneofKind: undefined } };\n }),\n };\n }\n\n this._authMethodsSync = resp;\n return resp;\n }\n\n public get authMethodsSync(): grpcTypes.AuthAPI_ListMethods_Response {\n if (!this._authMethodsSync) {\n throw new Error(\"LLPlClient.authMethodsSync accessed before build() completed\");\n }\n return this._authMethodsSync;\n }\n\n public async getUserRoot(\n opts: { login?: string; createIfNotExists?: boolean } = {},\n ): Promise<grpcTypes.AuthAPI_GetUserRoot_Response> {\n const cl = this.clientProvider.get();\n if (cl instanceof GrpcPlApiClient) {\n return (\n await cl.getUserRoot({\n login: opts.login ?? \"\",\n createIfNotExists: opts.createIfNotExists ?? false,\n })\n ).response;\n } else {\n const resp = notEmpty(\n (\n await cl.POST(\"/v1/auth/user-root\", {\n body: {\n login: opts.login ?? \"\",\n createIfNotExists: opts.createIfNotExists ?? false,\n },\n })\n ).data,\n \"REST: empty response for getUserRoot request\",\n );\n return {\n userRoot: resp.userRoot\n ? {\n resourceId: BigInt(resp.userRoot.resourceId),\n resourceSignature: Uint8Array.from(\n Buffer.from(resp.userRoot.resourceSignature, \"base64\"),\n ),\n }\n : undefined,\n };\n }\n }\n\n public async listUserResources(\n opts: { login?: string; startFrom?: bigint; limit?: number } = {},\n ): Promise<grpcTypes.AuthAPI_ListUserResources_Response[]> {\n const cl = this.clientProvider.get();\n\n if (!(cl instanceof GrpcPlApiClient)) {\n throw new Error(\"ListUserResources requires gRPC wire protocol; REST is not supported\");\n }\n\n const call = cl.listUserResources({\n login: opts.login ?? \"\",\n startFrom: opts.startFrom ?? 0n,\n limit: opts.limit ?? 0,\n });\n const responses: grpcTypes.AuthAPI_ListUserResources_Response[] = [];\n for await (const msg of call.responses) {\n responses.push(msg);\n }\n return responses;\n }\n\n /** Returns the authenticated caller's session id and effective role.\n * Models the {@link getUserRoot} wrapper: gRPC unary with a REST fallback. */\n public async getSessionInfo(): Promise<grpcTypes.AuthAPI_GetSessionInfo_Response> {\n const cl = this.clientProvider.get();\n if (cl instanceof GrpcPlApiClient) {\n return (await cl.getSessionInfo({})).response;\n } else {\n const resp = notEmpty(\n (await cl.POST(\"/v1/auth/session-info\", { body: {} })).data,\n \"REST: empty response for getSessionInfo request\",\n );\n return {\n sessionId: Uint8Array.from(Buffer.from(resp.sessionId, \"base64\")),\n role: resp.role as AuthAPI_Role,\n };\n }\n }\n\n /** Lists the users known to the server — the recipient picker's source. A user\n * becomes known on first login; provisioned users who have never logged in do not\n * appear. gRPC-only (unary, no REST binding). */\n public async listUsers(): Promise<grpcTypes.AuthAPI_User[]> {\n const cl = this.clientProvider.get();\n\n if (!(cl instanceof GrpcPlApiClient)) {\n throw new Error(\"ListUsers requires gRPC wire protocol; REST is not supported\");\n }\n\n return (await cl.listUsers({})).response.users;\n }\n\n public async txSync(txId: bigint): Promise<void> {\n const cl = this.clientProvider.get();\n if (cl instanceof GrpcPlApiClient) {\n await cl.txSync({ txId: BigInt(txId) });\n } else {\n await cl.POST(\"/v1/tx-sync\", { body: { txId: txId.toString() } });\n }\n }\n\n createTx(rw: boolean, ops: PlCallOps = {}): LLPlTransaction {\n return new LLPlTransaction((abortSignal) => {\n let totalAbortSignal = abortSignal;\n if (ops.abortSignal) totalAbortSignal = AbortSignal.any([totalAbortSignal, ops.abortSignal]);\n\n const timeout =\n ops.timeout ??\n (rw ? this.conf.defaultRWTransactionTimeout : this.conf.defaultROTransactionTimeout);\n\n const cl = this.clientProvider.get();\n if (cl instanceof GrpcPlApiClient) {\n return cl.tx({\n abort: totalAbortSignal,\n timeout,\n });\n }\n\n const wireConn = this.wireConnection;\n if (wireConn.type === \"rest\") {\n // For REST/WebSocket protocol, timeout needs to be converted to AbortSignal\n if (timeout !== undefined) {\n totalAbortSignal = AbortSignal.any([totalAbortSignal, AbortSignal.timeout(timeout)]);\n }\n\n // The gRPC transport has the auth interceptor that already handles it, but here we need to refresh the auth information to be safe.\n this.refreshAuthInformationIfNeeded();\n\n const wsUrl = this.conf.ssl\n ? `wss://${this.conf.hostAndPort}/v1/ws/tx`\n : `ws://${this.conf.hostAndPort}/v1/ws/tx`;\n\n return new WebSocketBiDiStream(\n wsUrl,\n (msg) => TxAPI_ClientMessage.toBinary(msg),\n (data) => TxAPI_ServerMessage.fromBinary(new Uint8Array(data)),\n {\n abortSignal: totalAbortSignal,\n jwtToken: this.authInformation?.jwtToken,\n dispatcher: wireConn.Dispatcher,\n\n onComplete: async (stream) =>\n stream.requests.send({\n // Ask server to gracefully close the stream on its side, if not done yet.\n requestId: 0,\n request: { oneofKind: \"streamClose\", streamClose: {} },\n }),\n },\n );\n }\n\n throw new Error(`transactions are not supported for wire protocol ${this._wireProto}`);\n });\n }\n\n /** Closes underlying transport */\n public async close() {\n if (this.wireConnection.type === \"grpc\") {\n this.wireConnection.Transport.close();\n } else {\n // TODO: close all WS connections\n }\n await this.httpDispatcher.destroy();\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAuDA,SAAS,iBAAiB,SAAiB,QAA2C;CACpF,MAAM,QAAQ,yBAAyB,KAAK,OAAO;CACnD,IAAI,CAAC,OAAO,OAAO;CACnB,MAAM,SAAmC;EAAC,OAAO,MAAM,EAAE;EAAG,OAAO,MAAM,EAAE;EAAG,OAAO,MAAM,EAAE;CAAC;CAC9F,KAAK,IAAI,IAAI,GAAG,IAAI,GAAG,KACrB,IAAI,OAAO,OAAO,OAAO,IAAI,OAAO,OAAO,KAAK,OAAO;CAEzD,OAAO;AACT;AAcA,SAAS,eAAe,SAAiB,QAA2C;CAClF,MAAM,QAAQ,8BAA8B,KAAK,OAAO;CACxD,IAAI,CAAC,OAAO,OAAO;CACnB,MAAM,SAAmC;EAAC,OAAO,MAAM,EAAE;EAAG,OAAO,MAAM,EAAE;EAAG,OAAO,MAAM,EAAE;CAAC;CAC9F,MAAM,SAAS,MAAM;CACrB,KAAK,IAAI,IAAI,GAAG,IAAI,GAAG,KACrB,IAAI,OAAO,OAAO,OAAO,IAAI,OAAO,OAAO,KAAK,OAAO;CAEzD,OAAO,WAAW;AACpB;AAEA,IAAM,yBAAN,MAA2E;CAItD;CACA;CAJnB,SAAqC,KAAA;C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AAgB;GAC1C,IAAI,mBAAmB;GACvB,IAAI,IAAI,aAAa,mBAAmB,YAAY,IAAI,CAAC,kBAAkB,IAAI,WAAW,CAAC;GAE3F,MAAM,UACJ,IAAI,YACH,KAAK,KAAK,KAAK,8BAA8B,KAAK,KAAK;GAE1D,MAAM,KAAK,KAAK,eAAe,IAAI;GACnC,IAAI,cAAcA,gBAChB,OAAO,GAAG,GAAG;IACX,OAAO;IACP;GACF,CAAC;GAGH,MAAM,WAAW,KAAK;GACtB,IAAI,SAAS,SAAS,QAAQ;IAE5B,IAAI,YAAY,KAAA,GACd,mBAAmB,YAAY,IAAI,CAAC,kBAAkB,YAAY,QAAQ,OAAO,CAAC,CAAC;IAIrF,KAAK,+BAA+B;IAMpC,OAAO,IAAI,oBAJG,KAAK,KAAK,MACpB,SAAS,KAAK,KAAK,YAAY,aAC/B,QAAQ,KAAK,KAAK,YAAY,aAI/B,QAAQ,oBAAoB,SAAS,GAAG,IACxC,SAAS,oBAAoB,WAAW,IAAI,WAAW,IAAI,CAAC,GAC7D;KACE,aAAa;KACb,UAAU,KAAK,iBAAiB;KAChC,YAAY,SAAS;KAErB,YAAY,OAAO,WACjB,OAAO,SAAS,KAAK;MAEnB,WAAW;MACX,SAAS;OAAE,WAAW;OAAe,aAAa,CAAC;MAAE;KACvD,CAAC;IACL,CACF;GACF;GAEA,MAAM,IAAI,MAAM,oDAAoD,KAAK,YAAY;EACvF,CAAC;CACH;;CAGA,MAAa,QAAQ;EACnB,IAAI,KAAK,eAAe,SAAS,QAC/B,KAAK,eAAe,UAAU,MAAM;EAItC,MAAM,KAAK,eAAe,QAAQ;CACpC;AACF"}
1
+ {"version":3,"file":"ll_client.js","names":["GrpcPlApiClient","status","GrpcStatus"],"sources":["../../src/core/ll_client.ts"],"sourcesContent":["import { PlatformClient as GrpcPlApiClient } from \"../proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api.client\";\nimport type { ClientOptions, Interceptor } from \"@grpc/grpc-js\";\nimport {\n ChannelCredentials,\n InterceptingCall,\n status as GrpcStatus,\n compressionAlgorithms,\n} from \"@grpc/grpc-js\";\nimport type {\n AuthInformation,\n AuthOps,\n PlClientConfig,\n PlConnectionStatus,\n PlConnectionStatusListener,\n} from \"./config\";\nimport { plAddressToConfig, type wireProtocol, SUPPORTED_WIRE_PROTOCOLS } from \"./config\";\nimport type { GrpcOptions } from \"@protobuf-ts/grpc-transport\";\nimport { GrpcTransport } from \"@protobuf-ts/grpc-transport\";\nimport { LLPlTransaction } from \"./ll_transaction\";\nimport { setResourceSignaturesRequired } from \"./types\";\nimport { parsePlJwt } from \"../util/pl\";\nimport { type Dispatcher, interceptors } from \"undici\";\nimport type { Middleware } from \"openapi-fetch\";\nimport { inferAuthRefreshTime } from \"./auth\";\nimport { hasCapability, type BackendCapability } from \"./capabilities\";\nimport { defaultHttpDispatcher } from \"@milaboratories/pl-http\";\nimport type { WireClientProvider, WireClientProviderFactory, WireConnection } from \"./wire\";\nimport { parseHttpAuth } from \"@milaboratories/pl-model-common\";\nimport type * as grpcTypes from \"../proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api\";\nimport {\n type PlApiPaths,\n type PlRestClientType,\n createClient,\n parseResponseError,\n} from \"../proto-rest\";\nimport { notEmpty, retry, withTimeout, type RetryOptions } from \"@milaboratories/ts-helpers\";\nimport { Code } from \"../proto-grpc/google/rpc/code\";\nimport { WebSocketBiDiStream } from \"./websocket_stream\";\nimport {\n AuthAPI_Role,\n TxAPI_ClientMessage,\n TxAPI_ServerMessage,\n} from \"../proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api\";\nimport type { MiLogger } from \"@milaboratories/ts-helpers\";\nimport { isAbortedError, isUnauthenticated } from \"./errors\";\nimport { Timestamp } from \"../proto-grpc/google/protobuf/timestamp\";\n\nexport interface PlCallOps {\n timeout?: number;\n abortSignal?: AbortSignal;\n}\n\n// Parses leading \"<major>.<minor>.<patch>\" from a version string like\n// \"3.1.1\" or \"3.1.1-rc1\" and returns true if the parsed version is >= target.\n// Returns false for unparseable versions (safer to assume an old backend).\nfunction isVersionAtLeast(version: string, target: [number, number, number]): boolean {\n const match = /^v?(\\d+)\\.(\\d+)\\.(\\d+)/.exec(version);\n if (!match) return false;\n const parsed: [number, number, number] = [Number(match[1]), Number(match[2]), Number(match[3])];\n for (let i = 0; i < 3; i++) {\n if (parsed[i] !== target[i]) return parsed[i] > target[i];\n }\n return true;\n}\n\n// Returns true iff `version` is strictly after the release tag `target`. Dev\n// builds (`git describe`-style, e.g. \"3.5.0-224-g0ca182\") are considered\n// AFTER the matching release tag — they include commits past the tag and so\n// have any change merged after it. Released versions with the same triplet\n// return false (we want the tag itself to be excluded).\n//\n// Examples for target [3,5,0]:\n// \"3.5.0\" → false (the tagged release)\n// \"3.5.0-224-g0ca182\" → true (dev build past the tag)\n// \"3.5.1\" → true\n// \"3.4.9\" → false\n// Returns false for unparseable versions.\nfunction isAfterVersion(version: string, target: [number, number, number]): boolean {\n const match = /^v?(\\d+)\\.(\\d+)\\.(\\d+)(.*)$/.exec(version);\n if (!match) return false;\n const parsed: [number, number, number] = [Number(match[1]), Number(match[2]), Number(match[3])];\n const suffix = match[4];\n for (let i = 0; i < 3; i++) {\n if (parsed[i] !== target[i]) return parsed[i] > target[i];\n }\n return suffix !== \"\";\n}\n\nclass WireClientProviderImpl<Client> implements WireClientProvider<Client> {\n private client: Client | undefined = undefined;\n\n constructor(\n private readonly wireOpts: () => WireConnection,\n private readonly clientConstructor: (wireOpts: WireConnection) => Client,\n ) {}\n\n public reset(): void {\n this.client = undefined;\n }\n\n public get(): Client {\n if (this.client === undefined) this.client = this.clientConstructor(this.wireOpts());\n return this.client;\n }\n}\n\n/** Abstract out low level networking and authorization details */\nexport class LLPlClient implements WireClientProviderFactory {\n /** Initial authorization information */\n private authInformation?: AuthInformation;\n /** Will be executed by the client when it is required */\n private readonly onAuthUpdate?: (newInfo: AuthInformation) => void;\n /** Will be executed if auth-related error happens during normal client operation */\n private readonly onAuthError?: () => void;\n /** Will be executed by the client when it is required */\n private readonly onAuthRefreshProblem?: (error: unknown) => void;\n /** Threshold after which auth info refresh is required */\n private refreshTimestamp?: number;\n\n /** Cached Ping response. Populated by build() before it returns; refreshed by every later ping(). */\n private _serverInfo?: grpcTypes.MaintenanceAPI_Ping_Response;\n private _authMethodsSync?: grpcTypes.AuthAPI_ListMethods_Response;\n\n private _status: PlConnectionStatus = \"OK\";\n private authProbeInFlight = false;\n private readonly statusListener?: PlConnectionStatusListener;\n\n private _wireProto: wireProtocol = \"grpc\";\n private _wireConn!: WireConnection;\n\n private readonly _restInterceptors: Dispatcher.DispatcherComposeInterceptor[];\n private readonly _restMiddlewares: Middleware[];\n private readonly _grpcInterceptors: Interceptor[];\n private readonly providers: WeakRef<WireClientProviderImpl<any>>[] = [];\n\n public readonly clientProvider: WireClientProvider<PlRestClientType | GrpcPlApiClient>;\n\n public readonly httpDispatcher: Dispatcher;\n\n public static async build(\n configOrAddress: PlClientConfig | string,\n ops: {\n auth?: AuthOps;\n statusListener?: PlConnectionStatusListener;\n shouldUseGzip?: boolean;\n logger?: MiLogger;\n useAutoDetectWireProtocol?: boolean;\n } = {},\n ) {\n const conf =\n typeof configOrAddress === \"string\" ? plAddressToConfig(configOrAddress) : configOrAddress;\n\n const pl = new LLPlClient(conf, ops);\n\n // FIXME(rfiskov)[MILAB-5275]: Investigate why autodetect randomly fails; temporary turn it off.\n if (ops.useAutoDetectWireProtocol) {\n await pl.detectOptimalWireProtocol();\n }\n\n // Guarantee a ping happened so capability-gated paths (login, refresh) can branch synchronously.\n // In the autodetect path the loop's last successful ping already populated _serverInfo via the\n // side-effect in ping(); this fallback covers the path where autodetect is disabled.\n if (!pl._serverInfo) await pl.ping();\n\n // Install the process-global signature-strictness flag based on backend version.\n setResourceSignaturesRequired(pl.supportsResourceSignatures);\n\n // Guarantee authMethods happened so client can make weighted decision on which auth method to use.\n if (!pl._authMethodsSync) await pl.authMethods();\n\n return pl;\n }\n\n private constructor(\n public readonly conf: PlClientConfig,\n private readonly ops: {\n auth?: AuthOps;\n statusListener?: PlConnectionStatusListener;\n shouldUseGzip?: boolean;\n logger?: MiLogger;\n } = {},\n ) {\n const { auth, statusListener } = ops;\n\n if (auth !== undefined) {\n this.refreshTimestamp = inferAuthRefreshTime(\n auth.authInformation,\n this.conf.authMaxRefreshSeconds,\n );\n this.authInformation = auth.authInformation;\n this.onAuthUpdate = auth.onUpdate;\n this.onAuthRefreshProblem = auth.onUpdateError;\n this.onAuthError = auth.onAuthError;\n }\n\n this._restInterceptors = [];\n this._restMiddlewares = [];\n this._grpcInterceptors = [];\n\n if (auth !== undefined) {\n this._restInterceptors.push(this.createRestAuthInterceptor());\n this._grpcInterceptors.push(this.createGrpcAuthInterceptor());\n }\n this._restInterceptors.push(interceptors.retry({ statusCodes: [] })); // Handle errors with openapi-fetch middleware.\n this._restMiddlewares.push(this.createRestErrorMiddleware());\n this._grpcInterceptors.push(this.createGrpcErrorInterceptor());\n\n this.httpDispatcher = defaultHttpDispatcher(this.conf.httpProxy);\n if (this.conf.wireProtocol) {\n this._wireProto = this.conf.wireProtocol;\n }\n\n this.initWireConnection(this._wireProto);\n\n if (statusListener !== undefined) {\n this.statusListener = statusListener;\n statusListener(this._status);\n }\n\n this.clientProvider = this.createWireClientProvider((wireConn) => {\n if (wireConn.type === \"grpc\") {\n return new GrpcPlApiClient(wireConn.Transport);\n } else {\n return createClient<PlApiPaths>({\n hostAndPort: wireConn.Config.hostAndPort,\n ssl: wireConn.Config.ssl,\n dispatcher: wireConn.Dispatcher,\n middlewares: wireConn.Middlewares,\n });\n }\n });\n }\n\n private initWireConnection(protocol: wireProtocol) {\n switch (protocol) {\n case \"rest\":\n this.initRestConnection();\n return;\n case \"grpc\":\n this.initGrpcConnection(this.ops.shouldUseGzip ?? false);\n return;\n default:\n ((v: never) => {\n throw new Error(\n `Unsupported wire protocol '${v as string}'. Use one of: ${SUPPORTED_WIRE_PROTOCOLS.join(\", \")}`,\n );\n })(protocol);\n }\n }\n\n private initRestConnection(): void {\n const dispatcher = defaultHttpDispatcher(this.conf.grpcProxy, this._restInterceptors);\n this._replaceWireConnection({\n type: \"rest\",\n Config: this.conf,\n Dispatcher: dispatcher,\n Middlewares: this._restMiddlewares,\n });\n }\n\n /**\n * Initializes (or reinitializes) _grpcTransport\n * @param gzip - whether to enable gzip compression\n */\n private initGrpcConnection(gzip: boolean) {\n const clientOptions: ClientOptions = {\n \"grpc.keepalive_time_ms\": 30_000, // 30 seconds\n \"grpc.service_config_disable_resolution\": 1, // Disable DNS TXT lookups for service config\n // Raises the per-stream and connection-level HTTP/2 windows. Node's 64 KB default\n // caps a big single-stream read (project open) at window/RTT rather than link speed,\n // and a lost WINDOW_UPDATE can deadlock it under packet loss.\n \"grpc-node.flow_control_window\": 16 * 1024 * 1024, // 16 MiB\n interceptors: this._grpcInterceptors,\n };\n\n if (gzip) clientOptions[\"grpc.default_compression_algorithm\"] = compressionAlgorithms.gzip;\n\n //\n // Leaving it here for now\n // https://github.com/grpc/grpc-node/issues/2788\n //\n // We should implement message pooling algorithm to overcome hardcoded NO_DELAY behaviour\n // of HTTP/2 and allow our small messages to batch together.\n //\n const grpcOptions: GrpcOptions = {\n host: this.conf.hostAndPort,\n timeout: this.conf.defaultRequestTimeout,\n channelCredentials: this.conf.ssl\n ? ChannelCredentials.createSsl()\n : ChannelCredentials.createInsecure(),\n clientOptions,\n };\n\n const grpcProxy =\n typeof this.conf.grpcProxy === \"string\" ? { url: this.conf.grpcProxy } : this.conf.grpcProxy;\n\n if (grpcProxy?.url) {\n const url = new URL(grpcProxy.url);\n if (grpcProxy.auth) {\n const parsed = parseHttpAuth(grpcProxy.auth);\n if (parsed.scheme !== \"Basic\") {\n throw new Error(`Unsupported auth scheme: ${parsed.scheme as string}.`);\n }\n url.username = parsed.username;\n url.password = parsed.password;\n }\n process.env.grpc_proxy = url.toString();\n } else {\n delete process.env.grpc_proxy;\n }\n\n this._replaceWireConnection({ type: \"grpc\", Transport: new GrpcTransport(grpcOptions) });\n }\n\n private _replaceWireConnection(newConn: WireConnection): void {\n const oldConn = this._wireConn;\n this._wireConn = newConn;\n this._wireProto = newConn.type;\n\n // Reset all providers to let them reinitialize their clients\n for (let i = 0; i < this.providers.length; i++) {\n const provider = this.providers[i].deref();\n if (provider === undefined) {\n // at the same time we need to remove providers that are no longer valid\n this.providers.splice(i, 1);\n i--;\n } else {\n provider.reset();\n }\n }\n\n if (oldConn !== undefined && oldConn.type === \"grpc\") oldConn.Transport.close();\n }\n\n private providerCleanupCounter = 0;\n\n /**\n * Creates a provider for a grpc client. Returned provider will create fresh client whenever the underlying transport is reset.\n *\n * @param clientConstructor - a factory function that creates a grpc client\n */\n public createWireClientProvider<Client>(\n clientConstructor: (transport: WireConnection) => Client,\n ): WireClientProvider<Client> {\n // We need to cleanup providers periodically to avoid memory leaks.\n // This is a simple heuristic to avoid memory leaks.\n // We could use a more sophisticated algorithm, but this is good enough for now.\n this.providerCleanupCounter++;\n if (this.providerCleanupCounter >= 16) {\n for (let i = 0; i < this.providers.length; i++) {\n const provider = this.providers[i].deref();\n if (provider === undefined) {\n this.providers.splice(i, 1);\n i--;\n }\n }\n this.providerCleanupCounter = 0;\n }\n\n const provider = new WireClientProviderImpl<Client>(() => this._wireConn, clientConstructor);\n this.providers.push(new WeakRef(provider));\n return provider;\n }\n\n public get wireConnection(): WireConnection {\n return this._wireConn;\n }\n\n public get wireProtocol(): wireProtocol | undefined {\n return this._wireProto;\n }\n\n /** Returns true if client is authenticated. Even with anonymous auth information\n * connection is considered authenticated. Unauthenticated clients are used for\n * login and similar tasks, see {@link UnauthenticatedPlClient}. */\n public get authenticated(): boolean {\n return this.authInformation !== undefined;\n }\n\n /** null means anonymous connection */\n public get authUser(): string | null {\n if (!this.authenticated) throw new Error(\"Client is not authenticated\");\n if (this.authInformation?.jwtToken) {\n if (this.hasCapability(\"auth:v2\")) {\n return parsePlJwt(this.authInformation?.jwtToken).sub;\n }\n return parsePlJwt(this.authInformation?.jwtToken).user.login;\n } else return null;\n }\n\n private updateStatus(newStatus: PlConnectionStatus) {\n process.nextTick(() => {\n if (this._status !== newStatus) {\n this._status = newStatus;\n if (this.statusListener !== undefined) this.statusListener(this._status);\n if (newStatus === \"Unauthenticated\" && this.onAuthError !== undefined) this.onAuthError();\n }\n });\n }\n\n /**\n * UNAUTHENTICATED covers both a dead session (must reset) and a per-request authorization failure\n * such as a revoked resource signature (must not). Disambiguate by probing getSessionInfo — an\n * authenticated call with no resource signature: success means the session is alive and the failure\n * was resource-level; a probe that is itself Unauthenticated means real auth loss. Coalesced via\n * authProbeInFlight so a burst of failures costs one probe.\n */\n private async verifyThenMaybeEscalateUnauthenticated(): Promise<void> {\n if (this._status !== \"OK\" || this.authProbeInFlight) return;\n this.authProbeInFlight = true;\n try {\n await this.getSessionInfo();\n } catch (e) {\n if (isUnauthenticated(e)) this.updateStatus(\"Unauthenticated\");\n } finally {\n this.authProbeInFlight = false;\n }\n }\n\n public get status(): PlConnectionStatus {\n return this._status;\n }\n\n private authRefreshInProgress: boolean = false;\n\n private refreshAuthInformationIfNeeded(): void {\n if (\n this.refreshTimestamp === undefined ||\n Date.now() < this.refreshTimestamp ||\n this.authRefreshInProgress ||\n this._status === \"Unauthenticated\"\n )\n return;\n\n // Running refresh in background`\n this.authRefreshInProgress = true;\n void (async () => {\n try {\n const ttl = BigInt(this.conf.authTTLSeconds);\n const token = this.hasCapability(\"auth:v2\")\n ? await this.refreshToken({ ttlSeconds: ttl })\n : await this.getJwtToken(ttl);\n this.authInformation = { jwtToken: token };\n this.refreshTimestamp = inferAuthRefreshTime(\n this.authInformation,\n this.conf.authMaxRefreshSeconds,\n );\n if (this.onAuthUpdate) this.onAuthUpdate(this.authInformation);\n } catch (e: unknown) {\n if (this.onAuthRefreshProblem) this.onAuthRefreshProblem(e);\n } finally {\n this.authRefreshInProgress = false;\n }\n })();\n }\n\n /**\n * Creates middleware that parses error responses and handles them centrally.\n * This middleware runs before openapi-fetch parses the response, so we need to\n * manually parse the response body for error responses.\n */\n private createRestErrorMiddleware(): Middleware {\n return {\n onResponse: async ({ request: _request, response, options: _options }) => {\n const { body, ...resOptions } = response;\n\n if ([502, 503, 504].includes(response.status)) {\n // Service unavailable, bad gateway, gateway timeout\n this.updateStatus(\"Disconnected\");\n return new Response(body, { ...resOptions, status: response.status });\n }\n\n const respErr = await parseResponseError(response);\n if (!respErr.error) {\n // No error: nice!\n return new Response(respErr.origBody ?? body, { ...resOptions, status: response.status });\n }\n\n if (typeof respErr.error === \"string\") {\n // Non-standard error or normal response: let later middleware to deal wit it.\n return new Response(respErr.error, { ...resOptions, status: response.status });\n }\n\n if (respErr.error.code === Code.UNAUTHENTICATED) {\n void this.verifyThenMaybeEscalateUnauthenticated();\n }\n\n // Let later middleware to deal with standard gRPC error.\n return new Response(respErr.origBody, { ...resOptions, status: response.status });\n },\n };\n }\n\n /** Detects certain errors and update client status accordingly when using GRPC wire connection */\n private createGrpcErrorInterceptor(): Interceptor {\n return (options, nextCall) => {\n return new InterceptingCall(nextCall(options), {\n start: (metadata, listener, next) => {\n next(metadata, {\n onReceiveStatus: (status, next) => {\n if (status.code == GrpcStatus.UNAUTHENTICATED)\n // (!!!) don't change to \"===\"\n void this.verifyThenMaybeEscalateUnauthenticated();\n if (status.code == GrpcStatus.UNAVAILABLE)\n // (!!!) don't change to \"===\"\n this.updateStatus(\"Disconnected\");\n next(status);\n },\n });\n },\n });\n };\n }\n\n private createRestAuthInterceptor(): Dispatcher.DispatcherComposeInterceptor {\n return (dispatch) => {\n return (options, handler) => {\n if (this.authInformation?.jwtToken !== undefined) {\n // TODO: check this magic really works and gets called\n options.headers = {\n ...options.headers,\n authorization: \"Bearer \" + this.authInformation.jwtToken,\n };\n this.refreshAuthInformationIfNeeded();\n }\n\n return dispatch(options, handler);\n };\n };\n }\n\n /** Injects authentication information if needed */\n private createGrpcAuthInterceptor(): Interceptor {\n return (options, nextCall) => {\n return new InterceptingCall(nextCall(options), {\n start: (metadata, listener, next) => {\n if (this.authInformation?.jwtToken !== undefined) {\n metadata.set(\"authorization\", \"Bearer \" + this.authInformation.jwtToken);\n this.refreshAuthInformationIfNeeded();\n next(metadata, listener);\n } else {\n next(metadata, listener);\n }\n },\n });\n };\n }\n\n public async getJwtToken(\n ttlSeconds: bigint,\n options?: { authorization?: string; role?: AuthAPI_Role },\n ): Promise<string> {\n const cl = this.clientProvider.get();\n const role = options?.role ?? AuthAPI_Role.UNSPECIFIED;\n\n if (cl instanceof GrpcPlApiClient) {\n const meta: Record<string, string> = {};\n if (options?.authorization) meta.authorization = options.authorization;\n return (\n await cl.getJWTToken(\n {\n expiration: { seconds: ttlSeconds, nanos: 0 },\n requestedRole: role,\n },\n { meta },\n ).response\n ).token;\n } else {\n const headers: Record<string, string> = {};\n if (options?.authorization) headers.authorization = options.authorization;\n const resp = cl.POST(\"/v1/auth/jwt-token\", {\n body: { expiration: `${ttlSeconds}s`, requestedRole: role },\n headers,\n });\n return notEmpty((await resp).data, \"REST: empty response for JWT token request\").token;\n }\n }\n\n /** Login via username/password. Returns a fresh JWT. Backend creates a new session per call. */\n public async loginBasic(\n user: string,\n password: string,\n opts: { ttlSeconds?: bigint; role?: AuthAPI_Role } = {},\n ): Promise<string> {\n const cl = this.clientProvider.get();\n const ttl = opts.ttlSeconds ?? BigInt(this.conf.authTTLSeconds);\n const role = opts.role ?? AuthAPI_Role.UNSPECIFIED;\n\n if (cl instanceof GrpcPlApiClient) {\n return (\n await cl.login({\n credentials: {\n oneofKind: \"basic\",\n basic: { login: user, password },\n },\n expiration: { seconds: ttl, nanos: 0 },\n requestedRole: role,\n }).response\n ).token;\n } else {\n const resp = cl.POST(\"/v1/auth/login\", {\n // openapi-typescript generated all body fields as required, but Login.Request\n // has a credentials oneof — only one of `basic`/`token` is sent. Cast around it.\n body: {\n basic: { login: user, password },\n expiration: `${ttl}s`,\n requestedRole: role,\n } as any,\n });\n return notEmpty((await resp).data, \"REST: empty response for login request\").token;\n }\n }\n\n /** Login via opaque bearer token (controller pre-shared secret, OIDC id-token, etc.).\n * String input is UTF-8 encoded. Returns a fresh Platforma JWT. */\n public async loginWithToken(\n token: Uint8Array | string,\n opts: { ttlSeconds?: bigint; role?: AuthAPI_Role } = {},\n ): Promise<string> {\n const cl = this.clientProvider.get();\n const ttl = opts.ttlSeconds ?? BigInt(this.conf.authTTLSeconds);\n const role = opts.role ?? AuthAPI_Role.UNSPECIFIED;\n const bytes = typeof token === \"string\" ? Buffer.from(token, \"utf8\") : token;\n\n if (cl instanceof GrpcPlApiClient) {\n return (\n await cl.login({\n credentials: {\n oneofKind: \"token\",\n token: { token: bytes },\n },\n expiration: { seconds: ttl, nanos: 0 },\n requestedRole: role,\n }).response\n ).token;\n } else {\n const resp = cl.POST(\"/v1/auth/login\", {\n // openapi-typescript marks all body fields as required, but Login.Request has a oneof.\n // REST encodes `bytes` as a base64 string.\n body: {\n token: { token: Buffer.from(bytes).toString(\"base64\") },\n expiration: `${ttl}s`,\n requestedRole: role,\n } as any,\n });\n return notEmpty((await resp).data, \"REST: empty response for login request\").token;\n }\n }\n\n /** Login via SSO: forwards the raw IdP /token JSON body to the backend.\n * Backend validates signature + nonce + audience and mints a Platforma JWT. */\n public async loginSSO(tokenResponse: Uint8Array): Promise<string> {\n const cl = this.clientProvider.get();\n if (cl instanceof GrpcPlApiClient) {\n return (\n await cl.login({\n credentials: {\n oneofKind: \"sso\",\n sso: { tokenResponse },\n },\n }).response\n ).token;\n } else {\n const resp = cl.POST(\"/v1/auth/login\", {\n body: {\n sso: { tokenResponse: Buffer.from(tokenResponse).toString(\"base64\") },\n } as any,\n });\n return notEmpty((await resp).data, \"REST: empty response for SSO login request\").token;\n }\n }\n\n /** Request a one-time PKCE nonce + its expiry from the backend. The desktop is\n * expected to place the nonce verbatim into the OIDC auth-request before\n * redirecting to the IdP; the backend enforces the expiry on {@link loginSSO}. */\n public async beginSSOLogin(): Promise<{ nonce: string; expiresAt: Date; clientSecret?: string }> {\n const cl = this.clientProvider.get();\n if (cl instanceof GrpcPlApiClient) {\n const resp = (await cl.beginSSOLogin({}).response).flow;\n if (resp.oneofKind !== \"publicPkce\") {\n throw new Error(`beginSSOLogin: unsupported flow ${resp.oneofKind}`);\n }\n const exp = notEmpty(resp.publicPkce.expiresAt, \"beginSSOLogin: missing expiresAt\");\n return {\n nonce: resp.publicPkce.nonce,\n expiresAt: Timestamp.toDate(exp),\n clientSecret: resp.publicPkce.clientSecret,\n };\n } else {\n const wsResponse = notEmpty(\n (await cl.POST(\"/v1/auth/sso/begin-login\", { body: {} })).data,\n \"REST: empty response for beginSSOLogin request\",\n );\n const pkce = notEmpty(wsResponse.publicPkce, \"REST: missing publicPkce in beginSSOLogin\");\n return {\n nonce: pkce.nonce,\n expiresAt: new Date(pkce.expiresAt),\n clientSecret: pkce.clientSecret,\n };\n }\n }\n\n /** Refresh the current JWT, preserving session id and role. */\n public async refreshToken(opts: { ttlSeconds?: bigint } = {}): Promise<string> {\n const cl = this.clientProvider.get();\n const ttl = opts.ttlSeconds ?? BigInt(this.conf.authTTLSeconds);\n const currentToken = notEmpty(\n this.authInformation?.jwtToken,\n \"refreshToken called without a current JWT\",\n );\n\n if (cl instanceof GrpcPlApiClient) {\n return (\n await cl.refreshToken({\n token: currentToken,\n expiration: { seconds: ttl, nanos: 0 },\n }).response\n ).token;\n } else {\n const resp = cl.POST(\"/v1/auth/refresh\", {\n body: { token: currentToken, expiration: `${ttl}s` },\n });\n return notEmpty((await resp).data, \"REST: empty response for refresh request\").token;\n }\n }\n\n public async ping(): Promise<grpcTypes.MaintenanceAPI_Ping_Response> {\n const cl = this.clientProvider.get();\n let resp: grpcTypes.MaintenanceAPI_Ping_Response;\n if (cl instanceof GrpcPlApiClient) {\n resp = (await cl.ping({})).response;\n } else {\n // The REST ping response predates the `capabilities` field (proto field 9).\n // Old servers omit it; treat absence as empty capability list.\n const pingData = notEmpty(\n (await cl.GET(\"/v1/ping\")).data,\n \"REST: empty response for ping request\",\n );\n resp = {\n ...(pingData as unknown as grpcTypes.MaintenanceAPI_Ping_Response),\n capabilities: (pingData as any).capabilities ?? [],\n };\n }\n this._serverInfo = resp;\n return resp;\n }\n\n /** Cached Ping response. Always populated post-build(); throws if accessed earlier. */\n public get serverInfo(): grpcTypes.MaintenanceAPI_Ping_Response {\n if (!this._serverInfo) {\n throw new Error(\"LLPlClient.serverInfo accessed before build() completed\");\n }\n return this._serverInfo;\n }\n\n /** Synchronous capability check against the cached Ping response. */\n public hasCapability(capability: BackendCapability): boolean {\n return hasCapability(this.serverInfo.capabilities, capability);\n }\n\n /** True if the backend produces signed resource ids (and accepts the\n * setDefaultColor TX request). Tagged at 3.3.0 — backends older than this\n * return resources without signatures and reject color-proof requests. */\n public get supportsResourceSignatures(): boolean {\n return isVersionAtLeast(this.serverInfo.coreVersion, [3, 3, 0]);\n }\n\n /**\n * True if the backend honors per-file `permissions` on workdir fill rules, so\n * `exec.builder().writeFile/addFile({ writable: true })` takes effect. When false\n * the requested mode is ignored and files land at the canonical archive perm.\n *\n * [3, 5, 0] excludes the tagged 3.5.0 release but includes dev builds past the\n * tag (e.g. \"3.5.0-224-g0ca182\"), which is where the support lands.\n */\n public get supportsWritableWorkdirFiles(): boolean {\n return isAfterVersion(this.serverInfo.coreVersion, [3, 5, 0]);\n }\n\n /**\n * Detects the best available wire protocol.\n * If wireProtocol is explicitly configured, does nothing.\n * Otherwise probes the current protocol via ping; if it fails, switches to the alternative.\n */\n private async detectOptimalWireProtocol() {\n if (this.conf.wireProtocol) {\n return;\n }\n\n // Each retry is:\n // - ping request timeout (100 to 3_000ms)\n // - backoff delay (30 to 500ms)\n //\n // 30 attempts are ~43 seconds of overall waiting time.\n // Think twice on overall time this thing takes to complete when changing these parameters.\n // It may block UI when connecting to the server and loading projects list.\n const pingTimeoutFactor = 1.3;\n const maxPingTimeoutMs = 3_000;\n const retryOptions: RetryOptions = {\n type: \"exponentialBackoff\",\n maxAttempts: 30,\n initialDelay: 30,\n backoffMultiplier: 1.3,\n jitter: 0.2,\n maxDelay: 500,\n };\n\n let attempt = 1;\n let pingTimeoutMs = 100;\n await retry(\n () => withTimeout(this.ping(), pingTimeoutMs),\n retryOptions,\n (e: unknown) => {\n if (isAbortedError(e)) {\n this.ops.logger?.info(\n `Wire proto autodetect: ping timed out after ${pingTimeoutMs}ms: attempt=${attempt}, wire=${this._wireProto}`,\n );\n\n if (attempt % 2 === 0) {\n // We have 2 wire protocols to check. Increase timeout each 2 attempts.\n pingTimeoutMs = Math.min(\n Math.round(pingTimeoutMs * pingTimeoutFactor),\n maxPingTimeoutMs,\n );\n }\n } else {\n this.ops.logger?.info(\n `Wire proto autodetect: ping failed: attempt=${attempt}, wire=${this._wireProto}, err=${String(e)}`,\n );\n }\n\n attempt++;\n const protocol = this._wireProto === \"grpc\" ? \"rest\" : \"grpc\";\n this.ops.logger?.info(\n `Wire protocol autodetect next attempt: will try wire '${protocol}' with timeout ${pingTimeoutMs}ms`,\n );\n this.initWireConnection(protocol);\n return true;\n },\n );\n }\n\n public async license(): Promise<grpcTypes.MaintenanceAPI_License_Response> {\n const cl = this.clientProvider.get();\n if (cl instanceof GrpcPlApiClient) {\n return (await cl.license({})).response;\n } else {\n const resp = notEmpty(\n (await cl.GET(\"/v1/license\")).data,\n \"REST: empty response for license request\",\n );\n return {\n status: resp.status,\n isOk: resp.isOk,\n responseBody: Uint8Array.from(Buffer.from(resp.responseBody)),\n };\n }\n }\n\n public async authMethods(): Promise<grpcTypes.AuthAPI_ListMethods_Response> {\n const cl = this.clientProvider.get();\n let resp: grpcTypes.AuthAPI_ListMethods_Response;\n if (cl instanceof GrpcPlApiClient) {\n resp = (await cl.authMethods({})).response;\n } else {\n const wsResponse = notEmpty(\n (await cl.GET(\"/v1/auth/methods\")).data,\n \"REST: empty response for auth methods request\",\n );\n // OpenAPI schema flattens the protobuf oneof into `{ basic?, token? }`,\n // while protobuf-ts models it as a discriminated union. Reshape per item.\n resp = {\n methods: (wsResponse.methods ?? []).map((m): grpcTypes.AuthAPI_ListMethods_MethodInfo => {\n const base = { id: m.id, description: m.description };\n if (m.basic !== undefined) {\n return { ...base, method: { oneofKind: \"basic\", basic: m.basic } };\n }\n if (m.token !== undefined) {\n return { ...base, method: { oneofKind: \"token\", token: m.token } };\n }\n if (m.sso !== undefined) {\n return { ...base, method: { oneofKind: \"sso\", sso: m.sso } };\n }\n return { ...base, method: { oneofKind: undefined } };\n }),\n };\n }\n\n this._authMethodsSync = resp;\n return resp;\n }\n\n public get authMethodsSync(): grpcTypes.AuthAPI_ListMethods_Response {\n if (!this._authMethodsSync) {\n throw new Error(\"LLPlClient.authMethodsSync accessed before build() completed\");\n }\n return this._authMethodsSync;\n }\n\n public async getUserRoot(\n opts: { login?: string; createIfNotExists?: boolean } = {},\n ): Promise<grpcTypes.AuthAPI_GetUserRoot_Response> {\n const cl = this.clientProvider.get();\n if (cl instanceof GrpcPlApiClient) {\n return (\n await cl.getUserRoot({\n login: opts.login ?? \"\",\n createIfNotExists: opts.createIfNotExists ?? false,\n })\n ).response;\n } else {\n const resp = notEmpty(\n (\n await cl.POST(\"/v1/auth/user-root\", {\n body: {\n login: opts.login ?? \"\",\n createIfNotExists: opts.createIfNotExists ?? false,\n },\n })\n ).data,\n \"REST: empty response for getUserRoot request\",\n );\n return {\n userRoot: resp.userRoot\n ? {\n resourceId: BigInt(resp.userRoot.resourceId),\n resourceSignature: Uint8Array.from(\n Buffer.from(resp.userRoot.resourceSignature, \"base64\"),\n ),\n }\n : undefined,\n };\n }\n }\n\n public async listUserResources(\n opts: { login?: string; startFrom?: bigint; limit?: number } = {},\n ): Promise<grpcTypes.AuthAPI_ListUserResources_Response[]> {\n const cl = this.clientProvider.get();\n\n if (!(cl instanceof GrpcPlApiClient)) {\n throw new Error(\"ListUserResources requires gRPC wire protocol; REST is not supported\");\n }\n\n const call = cl.listUserResources({\n login: opts.login ?? \"\",\n startFrom: opts.startFrom ?? 0n,\n limit: opts.limit ?? 0,\n });\n const responses: grpcTypes.AuthAPI_ListUserResources_Response[] = [];\n for await (const msg of call.responses) {\n responses.push(msg);\n }\n return responses;\n }\n\n /** Returns the authenticated caller's session id and effective role.\n * Models the {@link getUserRoot} wrapper: gRPC unary with a REST fallback. */\n public async getSessionInfo(): Promise<grpcTypes.AuthAPI_GetSessionInfo_Response> {\n const cl = this.clientProvider.get();\n if (cl instanceof GrpcPlApiClient) {\n return (await cl.getSessionInfo({})).response;\n } else {\n const resp = notEmpty(\n (await cl.POST(\"/v1/auth/session-info\", { body: {} })).data,\n \"REST: empty response for getSessionInfo request\",\n );\n return {\n sessionId: Uint8Array.from(Buffer.from(resp.sessionId, \"base64\")),\n role: resp.role as AuthAPI_Role,\n };\n }\n }\n\n /** Lists the users known to the server — the recipient picker's source. A user\n * becomes known on first login; provisioned users who have never logged in do not\n * appear. gRPC-only (unary, no REST binding). */\n public async listUsers(): Promise<grpcTypes.AuthAPI_User[]> {\n const cl = this.clientProvider.get();\n\n if (!(cl instanceof GrpcPlApiClient)) {\n throw new Error(\"ListUsers requires gRPC wire protocol; REST is not supported\");\n }\n\n return (await cl.listUsers({})).response.users;\n }\n\n public async txSync(txId: bigint): Promise<void> {\n const cl = this.clientProvider.get();\n if (cl instanceof GrpcPlApiClient) {\n await cl.txSync({ txId: BigInt(txId) });\n } else {\n await cl.POST(\"/v1/tx-sync\", { body: { txId: txId.toString() } });\n }\n }\n\n createTx(rw: boolean, ops: PlCallOps = {}): LLPlTransaction {\n return new LLPlTransaction((abortSignal) => {\n let totalAbortSignal = abortSignal;\n if (ops.abortSignal) totalAbortSignal = AbortSignal.any([totalAbortSignal, ops.abortSignal]);\n\n const timeout =\n ops.timeout ??\n (rw ? this.conf.defaultRWTransactionTimeout : this.conf.defaultROTransactionTimeout);\n\n const cl = this.clientProvider.get();\n if (cl instanceof GrpcPlApiClient) {\n return cl.tx({\n abort: totalAbortSignal,\n timeout,\n });\n }\n\n const wireConn = this.wireConnection;\n if (wireConn.type === \"rest\") {\n // For REST/WebSocket protocol, timeout needs to be converted to AbortSignal\n if (timeout !== undefined) {\n totalAbortSignal = AbortSignal.any([totalAbortSignal, AbortSignal.timeout(timeout)]);\n }\n\n // The gRPC transport has the auth interceptor that already handles it, but here we need to refresh the auth information to be safe.\n this.refreshAuthInformationIfNeeded();\n\n const wsUrl = this.conf.ssl\n ? `wss://${this.conf.hostAndPort}/v1/ws/tx`\n : `ws://${this.conf.hostAndPort}/v1/ws/tx`;\n\n return new WebSocketBiDiStream(\n wsUrl,\n (msg) => TxAPI_ClientMessage.toBinary(msg),\n (data) => TxAPI_ServerMessage.fromBinary(new Uint8Array(data)),\n {\n abortSignal: totalAbortSignal,\n jwtToken: this.authInformation?.jwtToken,\n dispatcher: wireConn.Dispatcher,\n\n onComplete: async (stream) =>\n stream.requests.send({\n // Ask server to gracefully close the stream on its side, if not done yet.\n requestId: 0,\n request: { oneofKind: \"streamClose\", streamClose: {} },\n }),\n },\n );\n }\n\n throw new Error(`transactions are not supported for wire protocol ${this._wireProto}`);\n });\n }\n\n /** Closes underlying transport */\n public async close() {\n if (this.wireConnection.type === \"grpc\") {\n this.wireConnection.Transport.close();\n } else {\n // TODO: close all WS connections\n }\n await this.httpDispatcher.destroy();\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAuDA,SAAS,iBAAiB,SAAiB,QAA2C;CACpF,MAAM,QAAQ,yBAAyB,KAAK,OAAO;CACnD,IAAI,CAAC,OAAO,OAAO;CACnB,MAAM,SAAmC;EAAC,OAAO,MAAM,EAAE;EAAG,OAAO,MAAM,EAAE;EAAG,OAAO,MAAM,EAAE;CAAC;CAC9F,KAAK,IAAI,IAAI,GAAG,IAAI,GAAG,KACrB,IAAI,OAAO,OAAO,OAAO,IAAI,OAAO,OAAO,KAAK,OAAO;CAEzD,OAAO;AACT;AAcA,SAAS,eAAe,SAAiB,QAA2C;CAClF,MAAM,QAAQ,8BAA8B,KAAK,OAAO;CACxD,IAAI,CAAC,OAAO,OAAO;CACnB,MAAM,SAAmC;EAAC,OAAO,MAAM,EAAE;EAAG,OAAO,MAAM,EAAE;E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AAU,MAAM;EAItC,MAAM,KAAK,eAAe,QAAQ;CACpC;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@milaboratories/pl-client",
3
- "version": "3.14.3",
3
+ "version": "3.14.5",
4
4
  "description": "New TS/JS client for Platform API",
5
5
  "files": [
6
6
  "./dist/**/*",
@@ -18,7 +18,7 @@
18
18
  }
19
19
  },
20
20
  "dependencies": {
21
- "@grpc/grpc-js": "~1.13.4",
21
+ "@grpc/grpc-js": "~1.14.4",
22
22
  "@protobuf-ts/grpc-transport": "2.11.1",
23
23
  "@protobuf-ts/runtime": "2.11.1",
24
24
  "@protobuf-ts/runtime-rpc": "2.11.1",
@@ -31,7 +31,7 @@
31
31
  "utility-types": "^3.11.0",
32
32
  "yaml": "^2.8.0",
33
33
  "@milaboratories/ts-helpers": "1.8.6",
34
- "@milaboratories/pl-model-common": "1.47.2",
34
+ "@milaboratories/pl-model-common": "1.47.3",
35
35
  "@milaboratories/pl-http": "1.2.4"
36
36
  },
37
37
  "devDependencies": {
@@ -41,9 +41,9 @@
41
41
  "openapi-typescript": "^7.10.0",
42
42
  "typescript": "~5.9.3",
43
43
  "vitest": "^4.1.3",
44
+ "@milaboratories/build-configs": "2.0.0",
44
45
  "@milaboratories/ts-configs": "1.3.1",
45
- "@milaboratories/ts-builder": "1.6.1",
46
- "@milaboratories/build-configs": "2.0.0"
46
+ "@milaboratories/ts-builder": "1.6.1"
47
47
  },
48
48
  "engines": {
49
49
  "node": ">=22.19.0"
@@ -266,6 +266,10 @@ export class LLPlClient implements WireClientProviderFactory {
266
266
  const clientOptions: ClientOptions = {
267
267
  "grpc.keepalive_time_ms": 30_000, // 30 seconds
268
268
  "grpc.service_config_disable_resolution": 1, // Disable DNS TXT lookups for service config
269
+ // Raises the per-stream and connection-level HTTP/2 windows. Node's 64 KB default
270
+ // caps a big single-stream read (project open) at window/RTT rather than link speed,
271
+ // and a lost WINDOW_UPDATE can deadlock it under packet loss.
272
+ "grpc-node.flow_control_window": 16 * 1024 * 1024, // 16 MiB
269
273
  interceptors: this._grpcInterceptors,
270
274
  };
271
275