doover-js 0.16.0 → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/dist/apis/agents-api.d.ts +47 -1
  2. package/dist/apis/agents-api.js +102 -5
  3. package/dist/client/capabilities.d.ts +1 -1
  4. package/dist/client/capabilities.js +2 -0
  5. package/dist/client/local-agent-client.js +2 -0
  6. package/dist/client/multiplex-client.js +23 -0
  7. package/dist/client/offline-cache.js +24 -0
  8. package/dist/esm/apis/agents-api.d.ts +47 -1
  9. package/dist/esm/apis/agents-api.js +100 -5
  10. package/dist/esm/client/capabilities.d.ts +1 -1
  11. package/dist/esm/client/capabilities.js +2 -0
  12. package/dist/esm/client/local-agent-client.js +2 -0
  13. package/dist/esm/client/multiplex-client.js +23 -0
  14. package/dist/esm/client/offline-cache.js +24 -0
  15. package/dist/esm/gateway/gateway-client.js +8 -0
  16. package/dist/esm/http/rest-client.d.ts +4 -0
  17. package/dist/esm/http/rest-client.js +20 -6
  18. package/dist/esm/index.d.ts +2 -1
  19. package/dist/esm/index.js +1 -0
  20. package/dist/esm/package.json +1 -1
  21. package/dist/esm/react/index.d.ts +4 -0
  22. package/dist/esm/react/index.js +2 -0
  23. package/dist/esm/react/useMultiAgentConnectionHistory.d.ts +35 -0
  24. package/dist/esm/react/useMultiAgentConnectionHistory.js +49 -0
  25. package/dist/esm/react/useMultiAgentMessageCounts.d.ts +25 -0
  26. package/dist/esm/react/useMultiAgentMessageCounts.js +40 -0
  27. package/dist/esm/types/connection.d.ts +48 -0
  28. package/dist/esm/types/openapi.d.ts +25 -0
  29. package/dist/esm/utils/view-as.d.ts +2 -0
  30. package/dist/esm/utils/view-as.js +6 -0
  31. package/dist/gateway/gateway-client.js +8 -0
  32. package/dist/http/rest-client.d.ts +4 -0
  33. package/dist/http/rest-client.js +20 -6
  34. package/dist/index.d.ts +2 -1
  35. package/dist/index.js +5 -2
  36. package/dist/react/index.d.ts +4 -0
  37. package/dist/react/index.js +8 -1
  38. package/dist/react/useMultiAgentConnectionHistory.d.ts +35 -0
  39. package/dist/react/useMultiAgentConnectionHistory.js +53 -0
  40. package/dist/react/useMultiAgentMessageCounts.d.ts +25 -0
  41. package/dist/react/useMultiAgentMessageCounts.js +44 -0
  42. package/dist/types/connection.d.ts +48 -0
  43. package/dist/types/openapi.d.ts +25 -0
  44. package/dist/utils/view-as.d.ts +2 -0
  45. package/dist/utils/view-as.js +9 -0
  46. package/package.json +1 -1
@@ -1,4 +1,5 @@
1
1
  import { DooverApiError, DooverMfaRequiredError, isMfaRequiredBody } from "./errors.js";
2
+ import { viewAsSession } from "../utils/view-as.js";
2
3
  export class RestClient {
3
4
  constructor(config, auth, onTransportFailure) {
4
5
  this.onTransportFailure = onTransportFailure;
@@ -39,14 +40,14 @@ export class RestClient {
39
40
  await this.prepareAuth();
40
41
  const request = this.prepareRequest(options);
41
42
  let response = await this.sendRequest(request);
42
- let payload = await this.parseResponse(response);
43
+ let payload = await this.parseResponse(response, options.responseType);
43
44
  if (response.status === 401 && this.auth) {
44
45
  const recovered = await this.auth.handleUnauthorized();
45
46
  if (recovered) {
46
47
  await this.prepareAuth();
47
48
  const retryRequest = this.prepareRequest(options);
48
49
  response = await this.sendRequest(retryRequest);
49
- payload = await this.parseResponse(response);
50
+ payload = await this.parseResponse(response, options.responseType);
50
51
  }
51
52
  }
52
53
  if (!response.ok) {
@@ -88,17 +89,23 @@ export class RestClient {
88
89
  if (!options.omitSharingHeader) {
89
90
  headers.set("X-Doover-Sharing", this.config.sharing);
90
91
  }
91
- if (this.config.organisationId && !headers.has("X-Doover-Organisation")) {
92
+ if (this.config.organisationId &&
93
+ !options.omitOrganisationHeader &&
94
+ !headers.has("X-Doover-Organisation")) {
92
95
  headers.set("X-Doover-Organisation", this.config.organisationId);
93
96
  }
94
97
  const impersonated = this.getImpersonatedUserId();
95
98
  if (impersonated) {
96
99
  headers.set("X-Doover-Assume", impersonated);
97
100
  }
101
+ const viewAs = viewAsSession();
102
+ if (viewAs) {
103
+ headers.set("X-Doover-View-As", viewAs);
104
+ }
98
105
  const credentials = this.auth
99
106
  ? this.auth.getFetchCredentials()
100
107
  : "include";
101
- return { url, method, headers, body, credentials };
108
+ return { url, method, headers, body, credentials, signal: options.signal };
102
109
  }
103
110
  async sendRequest(request) {
104
111
  // Merge auth headers immediately before fetch so a retry can use refreshed
@@ -116,6 +123,7 @@ export class RestClient {
116
123
  headers: request.headers,
117
124
  body: request.body,
118
125
  credentials: request.credentials,
126
+ signal: request.signal,
119
127
  });
120
128
  }
121
129
  catch (error) {
@@ -142,7 +150,10 @@ export class RestClient {
142
150
  buildUrl(baseUrl, path, query) {
143
151
  const normalizedBase = baseUrl.replace(/\/+$/, "");
144
152
  const normalizedPath = path.startsWith("/") ? path : `/${path}`;
145
- const finalUrl = new URL(`${normalizedBase}${normalizedPath}`);
153
+ // A full URL as the path is used as it is.
154
+ const finalUrl = /^https?:\/\//.test(path)
155
+ ? new URL(path)
156
+ : new URL(`${normalizedBase}${normalizedPath}`);
146
157
  if (query) {
147
158
  for (const [key, value] of Object.entries(query)) {
148
159
  if (value === undefined || value === null) {
@@ -172,10 +183,13 @@ export class RestClient {
172
183
  headers.set("Content-Type", "application/json");
173
184
  return JSON.stringify(body);
174
185
  }
175
- async parseResponse(response) {
186
+ async parseResponse(response, responseType) {
176
187
  if (response.status === 204) {
177
188
  return undefined;
178
189
  }
190
+ if (response.ok && responseType) {
191
+ return response[responseType]();
192
+ }
179
193
  const contentType = response.headers.get("content-type") ?? "";
180
194
  if (contentType.includes("application/json")) {
181
195
  return response.json();
@@ -8,7 +8,8 @@ export { DooverStatsCollector } from "./client/stats.js";
8
8
  export type { DooverStatsSnapshot, RestStatsSnapshot, GatewayStatsSnapshot, } from "./client/stats.js";
9
9
  export { AgentsApi } from "./apis/agents-api.js";
10
10
  export { policyAllows } from "./utils/policy.js";
11
- export type { AgentTokenState, AgentTokenPolicy, TokenPolicyField, AdhocTokenResponse, DeviceTokenResponse, ResourcePermission, AgentCredential, CreatedCredential, CredentialKind, KeyRestriction, KeyPolicy, } from "./apis/agents-api.js";
11
+ export { mergeConnectionHistory, mergeMessageCounts } from "./apis/agents-api.js";
12
+ export type { ConnectionHistoryParams, MultiAgentMessageCountsParams, AgentTokenState, AgentTokenPolicy, TokenPolicyField, AdhocTokenResponse, DeviceTokenResponse, ResourcePermission, AgentCredential, CreatedCredential, CredentialKind, KeyRestriction, KeyPolicy, } from "./apis/agents-api.js";
12
13
  export { AggregatesApi } from "./apis/aggregates-api.js";
13
14
  export { AlarmsApi } from "./apis/alarms-api.js";
14
15
  export { ChannelsApi } from "./apis/channels-api.js";
package/dist/esm/index.js CHANGED
@@ -5,6 +5,7 @@ export { getDooverClient, peekDooverClient, resetDooverClient, } from "./client/
5
5
  export { DooverStatsCollector } from "./client/stats.js";
6
6
  export { AgentsApi } from "./apis/agents-api.js";
7
7
  export { policyAllows } from "./utils/policy.js";
8
+ export { mergeConnectionHistory, mergeMessageCounts } from "./apis/agents-api.js";
8
9
  export { AggregatesApi } from "./apis/aggregates-api.js";
9
10
  export { AlarmsApi } from "./apis/alarms-api.js";
10
11
  export { ChannelsApi } from "./apis/channels-api.js";
@@ -1 +1 @@
1
- {"name":"doover-js","version":"0.16.0","type":"module","sideEffects":false}
1
+ {"name":"doover-js","version":"0.18.0","type":"module","sideEffects":false}
@@ -38,3 +38,7 @@ export type { UseAgentTokenStateOptions } from "./useAgentTokenState.js";
38
38
  export { useAgentCredentials, useOrganisationCredentials, organisationCredentialsQueryKey, useCreateApiKey, useAddDeviceKey, useCreateEnrolmentCode, useRevokeCredential, agentCredentialsQueryKey, } from "./useAgentCredentials.js";
39
39
  export { getSharedQueryClient, resetSharedQueryClient, } from "./sharedQueryClient.js";
40
40
  export { useServiceReachability } from "./useServiceReachability.js";
41
+ export { useMultiAgentConnectionHistory, multiAgentConnectionHistoryQueryKey, } from "./useMultiAgentConnectionHistory.js";
42
+ export type { UseMultiAgentConnectionHistoryOptions, UseMultiAgentConnectionHistoryResult, } from "./useMultiAgentConnectionHistory.js";
43
+ export { useMultiAgentMessageCounts, multiAgentMessageCountsQueryKey, } from "./useMultiAgentMessageCounts.js";
44
+ export type { UseMultiAgentMessageCountsOptions, UseMultiAgentMessageCountsResult, } from "./useMultiAgentMessageCounts.js";
@@ -21,3 +21,5 @@ export { useAgentTokenState, useSetAgentTokenPolicy, useSetAgentAuthLock, useRev
21
21
  export { useAgentCredentials, useOrganisationCredentials, organisationCredentialsQueryKey, useCreateApiKey, useAddDeviceKey, useCreateEnrolmentCode, useRevokeCredential, agentCredentialsQueryKey, } from "./useAgentCredentials.js";
22
22
  export { getSharedQueryClient, resetSharedQueryClient, } from "./sharedQueryClient.js";
23
23
  export { useServiceReachability } from "./useServiceReachability.js";
24
+ export { useMultiAgentConnectionHistory, multiAgentConnectionHistoryQueryKey, } from "./useMultiAgentConnectionHistory.js";
25
+ export { useMultiAgentMessageCounts, multiAgentMessageCountsQueryKey, } from "./useMultiAgentMessageCounts.js";
@@ -0,0 +1,35 @@
1
+ import { type UseQueryResult } from "@tanstack/react-query";
2
+ import type { AgentConnectionHistory, ConnectionHistoryResponse } from "../types/connection.js";
3
+ export interface UseMultiAgentConnectionHistoryOptions {
4
+ /** Snowflake id bounds. Defaults to the last 7 days; at most 31 days apart. */
5
+ before?: string;
6
+ after?: string;
7
+ /** Slot width in ms for the fleet `buckets` series. Omit for no buckets. */
8
+ bucketMs?: number;
9
+ /** Include each agent's state segments (at most 25 agents per call). */
10
+ includeSegments?: boolean;
11
+ /** Defaults true; the query also waits for a non-empty `agentIds`. */
12
+ enabled?: boolean;
13
+ }
14
+ export declare function multiAgentConnectionHistoryQueryKey(agentIds: string[], options?: UseMultiAgentConnectionHistoryOptions): readonly ["doover", "connection_history", string, {
15
+ readonly before: string | null;
16
+ readonly after: string | null;
17
+ readonly bucket_ms: number | null;
18
+ readonly include_segments: boolean;
19
+ }];
20
+ export interface UseMultiAgentConnectionHistoryResult {
21
+ history: ConnectionHistoryResponse | undefined;
22
+ /** Keyed by agent id for O(1) lookup. */
23
+ agentsById: Record<string, AgentConnectionHistory>;
24
+ query: UseQueryResult<ConnectionHistoryResponse>;
25
+ }
26
+ /**
27
+ * Connection state over time for a set of agents, in one request:
28
+ * per-agent summaries (and segments on request) plus an optional fleet
29
+ * series per slot. The window is part of the key, so callers that want a
30
+ * stable cache across remounts should snap `before` to a grid rather than
31
+ * pass a fresh "now" each render. Never stale on its own: history does
32
+ * not change, and the trailing edge moves only as far as the caller's
33
+ * `before` does.
34
+ */
35
+ export declare function useMultiAgentConnectionHistory(agentIds: string[], options?: UseMultiAgentConnectionHistoryOptions): UseMultiAgentConnectionHistoryResult;
@@ -0,0 +1,49 @@
1
+ import { useMemo } from "react";
2
+ import { useQuery } from "@tanstack/react-query";
3
+ import { useDooverClient } from "./context.js";
4
+ export function multiAgentConnectionHistoryQueryKey(agentIds, options) {
5
+ return [
6
+ "doover",
7
+ "connection_history",
8
+ [...agentIds].sort().join(","),
9
+ {
10
+ before: options?.before ?? null,
11
+ after: options?.after ?? null,
12
+ bucket_ms: options?.bucketMs ?? null,
13
+ include_segments: options?.includeSegments ?? false,
14
+ },
15
+ ];
16
+ }
17
+ /**
18
+ * Connection state over time for a set of agents, in one request:
19
+ * per-agent summaries (and segments on request) plus an optional fleet
20
+ * series per slot. The window is part of the key, so callers that want a
21
+ * stable cache across remounts should snap `before` to a grid rather than
22
+ * pass a fresh "now" each render. Never stale on its own: history does
23
+ * not change, and the trailing edge moves only as far as the caller's
24
+ * `before` does.
25
+ */
26
+ export function useMultiAgentConnectionHistory(agentIds, options) {
27
+ const client = useDooverClient();
28
+ const key = multiAgentConnectionHistoryQueryKey(agentIds, options);
29
+ const enabled = (options?.enabled ?? true) && agentIds.length > 0;
30
+ const query = useQuery({
31
+ queryKey: key,
32
+ enabled,
33
+ staleTime: Infinity,
34
+ queryFn: () => client.agents.getMultiAgentConnectionHistory({
35
+ agent_id: agentIds,
36
+ ...(options?.before !== undefined ? { before: options.before } : {}),
37
+ ...(options?.after !== undefined ? { after: options.after } : {}),
38
+ ...(options?.bucketMs !== undefined ? { bucket_ms: options.bucketMs } : {}),
39
+ ...(options?.includeSegments ? { include_segments: true } : {}),
40
+ }),
41
+ });
42
+ const agentsById = useMemo(() => {
43
+ const map = {};
44
+ for (const agent of query.data?.agents ?? [])
45
+ map[agent.id] = agent;
46
+ return map;
47
+ }, [query.data]);
48
+ return { history: query.data, agentsById, query };
49
+ }
@@ -0,0 +1,25 @@
1
+ import { type UseQueryResult } from "@tanstack/react-query";
2
+ import type { DayCount, MessageCountsResponse } from "../types/openapi.js";
3
+ export interface UseMultiAgentMessageCountsOptions {
4
+ /** Snowflake id bounds. Defaults to the last 7 days; at most 92 days apart. */
5
+ before?: string;
6
+ after?: string;
7
+ /** Defaults true; the query also waits for a non-empty `agentIds`. */
8
+ enabled?: boolean;
9
+ }
10
+ export declare function multiAgentMessageCountsQueryKey(channelName: string, agentIds: string[], options?: UseMultiAgentMessageCountsOptions): readonly ["doover", "channel", string, "message_counts", string, {
11
+ readonly before: string | null;
12
+ readonly after: string | null;
13
+ }];
14
+ export interface UseMultiAgentMessageCountsResult {
15
+ counts: MessageCountsResponse | undefined;
16
+ /** Each agent's days, keyed by agent id. */
17
+ daysByAgent: Record<string, DayCount[]>;
18
+ query: UseQueryResult<MessageCountsResponse>;
19
+ }
20
+ /**
21
+ * Messages stored per UTC day on a channel for a set of agents, with fleet
22
+ * totals. Cheap enough for a quarter of a fleet; the window is part of
23
+ * the key, so snap `before` to a grid for a cache that survives remounts.
24
+ */
25
+ export declare function useMultiAgentMessageCounts(channelName: string, agentIds: string[], options?: UseMultiAgentMessageCountsOptions): UseMultiAgentMessageCountsResult;
@@ -0,0 +1,40 @@
1
+ import { useMemo } from "react";
2
+ import { useQuery } from "@tanstack/react-query";
3
+ import { useDooverClient } from "./context.js";
4
+ export function multiAgentMessageCountsQueryKey(channelName, agentIds, options) {
5
+ return [
6
+ "doover",
7
+ "channel",
8
+ channelName,
9
+ "message_counts",
10
+ [...agentIds].sort().join(","),
11
+ { before: options?.before ?? null, after: options?.after ?? null },
12
+ ];
13
+ }
14
+ /**
15
+ * Messages stored per UTC day on a channel for a set of agents, with fleet
16
+ * totals. Cheap enough for a quarter of a fleet; the window is part of
17
+ * the key, so snap `before` to a grid for a cache that survives remounts.
18
+ */
19
+ export function useMultiAgentMessageCounts(channelName, agentIds, options) {
20
+ const client = useDooverClient();
21
+ const key = multiAgentMessageCountsQueryKey(channelName, agentIds, options);
22
+ const enabled = (options?.enabled ?? true) && agentIds.length > 0;
23
+ const query = useQuery({
24
+ queryKey: key,
25
+ enabled,
26
+ staleTime: Infinity,
27
+ queryFn: () => client.agents.getMultiAgentMessageCounts(channelName, {
28
+ agent_id: agentIds,
29
+ ...(options?.before !== undefined ? { before: options.before } : {}),
30
+ ...(options?.after !== undefined ? { after: options.after } : {}),
31
+ }),
32
+ });
33
+ const daysByAgent = useMemo(() => {
34
+ const map = {};
35
+ for (const agent of query.data?.agents ?? [])
36
+ map[agent.id] = agent.days;
37
+ return map;
38
+ }, [query.data]);
39
+ return { counts: query.data, daysByAgent, query };
40
+ }
@@ -70,3 +70,51 @@ export interface ConnectionAggregate {
70
70
  determination?: ConnectionDetermination | null;
71
71
  config?: ConnectionConfig | null;
72
72
  }
73
+ /**
74
+ * Coarse connection state over time. `Sleeping` is a `PeriodicContinuous`
75
+ * device between check-ins and counts as up; `Unknown` is before the
76
+ * agent's first message, or earlier than a truncated read reached.
77
+ */
78
+ export type ConnectionHistoryState = "Online" | "Sleeping" | "Offline" | "Unknown";
79
+ /** A stretch of one state. `start` inclusive, `end` exclusive, both epoch ms. */
80
+ export interface ConnectionSegment {
81
+ start: number;
82
+ end: number;
83
+ state: ConnectionHistoryState;
84
+ }
85
+ /** The fleet in one time slot. Counts are by the state each agent held for most of the slot. */
86
+ export interface ConnectionBucket {
87
+ /** Epoch ms, inclusive. */
88
+ start: number;
89
+ /** Epoch ms, exclusive. */
90
+ end: number;
91
+ online: number;
92
+ sleeping: number;
93
+ offline: number;
94
+ unknown: number;
95
+ /** Agents that went from down to up at least once inside the slot. */
96
+ came_up: string[];
97
+ /** Agents that went from up to down at least once inside the slot; a flapping agent is in both lists. */
98
+ went_down: string[];
99
+ }
100
+ export interface AgentConnectionHistory {
101
+ id: string;
102
+ state_at_start: ConnectionHistoryState;
103
+ state_at_end: ConnectionHistoryState;
104
+ /** Share of the known time the agent was up (online or asleep); null when nothing is known. */
105
+ uptime: number | null;
106
+ /** Some day in the window had more status changes than the server reads; its earliest stretch is unknown. */
107
+ truncated: boolean;
108
+ /** Present only when requested with `include_segments`. */
109
+ segments?: ConnectionSegment[];
110
+ }
111
+ export interface ConnectionHistoryResponse {
112
+ /** Epoch ms, inclusive. */
113
+ start: number;
114
+ /** Epoch ms, exclusive; the requested `before` clipped to now. */
115
+ end: number;
116
+ /** Sorted by id. Agents the caller cannot read are absent. */
117
+ agents: AgentConnectionHistory[];
118
+ /** Present only when requested with `bucket_ms`. */
119
+ buckets?: ConnectionBucket[];
120
+ }
@@ -33,6 +33,31 @@ export interface BatchAggregatesResponse {
33
33
  results: AgentAggregate[];
34
34
  count: number;
35
35
  }
36
+ /** Messages stored on a channel for one UTC day (`GET /agents/channels/{channel}/messages/counts`). */
37
+ export interface DayCount {
38
+ /** UTC day start, epoch ms. */
39
+ start: number;
40
+ /**
41
+ * Messages written for the day, less those deleted through the API.
42
+ * Messages expired by retention still count.
43
+ */
44
+ count: number;
45
+ }
46
+ export interface AgentMessageCounts {
47
+ id: string;
48
+ /** Oldest first; days with no messages are absent. */
49
+ days: DayCount[];
50
+ }
51
+ export interface MessageCountsResponse {
52
+ /** Epoch ms, inclusive. */
53
+ start: number;
54
+ /** Epoch ms, exclusive; the requested `before` clipped to now. */
55
+ end: number;
56
+ /** Sorted by id. Agents the caller cannot read are absent. */
57
+ agents: AgentMessageCounts[];
58
+ /** Every agent's counts summed, by day, oldest first. */
59
+ totals: DayCount[];
60
+ }
36
61
  export interface NotificationDataResponse {
37
62
  subscriptions: NotificationSubscription[];
38
63
  subscribers: NotificationSubscription[];
@@ -0,0 +1,2 @@
1
+ /** The view-as session the app started, if any (set by the site's "View as"). */
2
+ export declare function viewAsSession(): string | null;
@@ -0,0 +1,6 @@
1
+ /** The view-as session the app started, if any (set by the site's "View as"). */
2
+ export function viewAsSession() {
3
+ if (typeof sessionStorage === "undefined")
4
+ return null;
5
+ return sessionStorage.getItem("view_as_session");
6
+ }
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.GatewayClient = void 0;
4
4
  const errors_js_1 = require("../http/errors.js");
5
5
  const snowflake_js_1 = require("../utils/snowflake.js");
6
+ const view_as_js_1 = require("../utils/view-as.js");
6
7
  const RECONNECT_BASE_MS = 1000;
7
8
  const RECONNECT_CAP_MS = 30000;
8
9
  /** Schemes a WebSocket can be opened on — it maps http(s) to ws(s) itself. */
@@ -135,6 +136,13 @@ class GatewayClient {
135
136
  const wsParams = this.auth
136
137
  ? await this.auth.prepareWebSocket(this.config.dataWssUrl, hasFactory)
137
138
  : { url: this.config.dataWssUrl };
139
+ // A browser WebSocket can't send headers, so the session goes in the URL.
140
+ const viewAs = (0, view_as_js_1.viewAsSession)();
141
+ if (viewAs) {
142
+ const url = new URL(wsParams.url);
143
+ url.searchParams.set("view_as", viewAs);
144
+ wsParams.url = url.toString();
145
+ }
138
146
  let socket;
139
147
  if (this.config.webSocketFactory) {
140
148
  socket = this.config.webSocketFactory({
@@ -40,6 +40,10 @@ export interface RequestOptions {
40
40
  body?: BodyInit | object | null;
41
41
  headers?: HeadersInit;
42
42
  omitSharingHeader?: boolean;
43
+ omitOrganisationHeader?: boolean;
44
+ /** Read a successful response as this, whatever its content type. */
45
+ responseType?: "blob" | "text";
46
+ signal?: AbortSignal;
43
47
  }
44
48
  type QueryValue = string | number | boolean | null | undefined | Array<string | number | boolean>;
45
49
  type QueryParams = Record<string, QueryValue> | object;
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.RestClient = void 0;
4
4
  const errors_js_1 = require("./errors.js");
5
+ const view_as_js_1 = require("../utils/view-as.js");
5
6
  class RestClient {
6
7
  constructor(config, auth, onTransportFailure) {
7
8
  this.onTransportFailure = onTransportFailure;
@@ -42,14 +43,14 @@ class RestClient {
42
43
  await this.prepareAuth();
43
44
  const request = this.prepareRequest(options);
44
45
  let response = await this.sendRequest(request);
45
- let payload = await this.parseResponse(response);
46
+ let payload = await this.parseResponse(response, options.responseType);
46
47
  if (response.status === 401 && this.auth) {
47
48
  const recovered = await this.auth.handleUnauthorized();
48
49
  if (recovered) {
49
50
  await this.prepareAuth();
50
51
  const retryRequest = this.prepareRequest(options);
51
52
  response = await this.sendRequest(retryRequest);
52
- payload = await this.parseResponse(response);
53
+ payload = await this.parseResponse(response, options.responseType);
53
54
  }
54
55
  }
55
56
  if (!response.ok) {
@@ -91,17 +92,23 @@ class RestClient {
91
92
  if (!options.omitSharingHeader) {
92
93
  headers.set("X-Doover-Sharing", this.config.sharing);
93
94
  }
94
- if (this.config.organisationId && !headers.has("X-Doover-Organisation")) {
95
+ if (this.config.organisationId &&
96
+ !options.omitOrganisationHeader &&
97
+ !headers.has("X-Doover-Organisation")) {
95
98
  headers.set("X-Doover-Organisation", this.config.organisationId);
96
99
  }
97
100
  const impersonated = this.getImpersonatedUserId();
98
101
  if (impersonated) {
99
102
  headers.set("X-Doover-Assume", impersonated);
100
103
  }
104
+ const viewAs = (0, view_as_js_1.viewAsSession)();
105
+ if (viewAs) {
106
+ headers.set("X-Doover-View-As", viewAs);
107
+ }
101
108
  const credentials = this.auth
102
109
  ? this.auth.getFetchCredentials()
103
110
  : "include";
104
- return { url, method, headers, body, credentials };
111
+ return { url, method, headers, body, credentials, signal: options.signal };
105
112
  }
106
113
  async sendRequest(request) {
107
114
  // Merge auth headers immediately before fetch so a retry can use refreshed
@@ -119,6 +126,7 @@ class RestClient {
119
126
  headers: request.headers,
120
127
  body: request.body,
121
128
  credentials: request.credentials,
129
+ signal: request.signal,
122
130
  });
123
131
  }
124
132
  catch (error) {
@@ -145,7 +153,10 @@ class RestClient {
145
153
  buildUrl(baseUrl, path, query) {
146
154
  const normalizedBase = baseUrl.replace(/\/+$/, "");
147
155
  const normalizedPath = path.startsWith("/") ? path : `/${path}`;
148
- const finalUrl = new URL(`${normalizedBase}${normalizedPath}`);
156
+ // A full URL as the path is used as it is.
157
+ const finalUrl = /^https?:\/\//.test(path)
158
+ ? new URL(path)
159
+ : new URL(`${normalizedBase}${normalizedPath}`);
149
160
  if (query) {
150
161
  for (const [key, value] of Object.entries(query)) {
151
162
  if (value === undefined || value === null) {
@@ -175,10 +186,13 @@ class RestClient {
175
186
  headers.set("Content-Type", "application/json");
176
187
  return JSON.stringify(body);
177
188
  }
178
- async parseResponse(response) {
189
+ async parseResponse(response, responseType) {
179
190
  if (response.status === 204) {
180
191
  return undefined;
181
192
  }
193
+ if (response.ok && responseType) {
194
+ return response[responseType]();
195
+ }
182
196
  const contentType = response.headers.get("content-type") ?? "";
183
197
  if (contentType.includes("application/json")) {
184
198
  return response.json();
package/dist/index.d.ts CHANGED
@@ -8,7 +8,8 @@ export { DooverStatsCollector } from "./client/stats.js";
8
8
  export type { DooverStatsSnapshot, RestStatsSnapshot, GatewayStatsSnapshot, } from "./client/stats.js";
9
9
  export { AgentsApi } from "./apis/agents-api.js";
10
10
  export { policyAllows } from "./utils/policy.js";
11
- export type { AgentTokenState, AgentTokenPolicy, TokenPolicyField, AdhocTokenResponse, DeviceTokenResponse, ResourcePermission, AgentCredential, CreatedCredential, CredentialKind, KeyRestriction, KeyPolicy, } from "./apis/agents-api.js";
11
+ export { mergeConnectionHistory, mergeMessageCounts } from "./apis/agents-api.js";
12
+ export type { ConnectionHistoryParams, MultiAgentMessageCountsParams, AgentTokenState, AgentTokenPolicy, TokenPolicyField, AdhocTokenResponse, DeviceTokenResponse, ResourcePermission, AgentCredential, CreatedCredential, CredentialKind, KeyRestriction, KeyPolicy, } from "./apis/agents-api.js";
12
13
  export { AggregatesApi } from "./apis/aggregates-api.js";
13
14
  export { AlarmsApi } from "./apis/alarms-api.js";
14
15
  export { ChannelsApi } from "./apis/channels-api.js";
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getIdentifierFromPath = exports.DooverDataProvider = exports.isMfaRequiredBody = exports.DooverValidationError = exports.DooverMfaRequiredError = exports.DooverGatewayError = exports.DooverApiError = exports.RestClient = exports.GatewayClient = exports.buildAuth = exports.DooverAuthError = exports.AuthProfile = exports.DooverTokenAuth = exports.CookieAuth = exports.DooverAuth = exports.mergeBatchResponses = exports.chunkBatchItems = exports.MAX_BATCH_ITEMS = exports.splitRequestOptions = exports.isDooverRequestOptions = exports.requestOptions = exports.DEFAULT_OFFLINE_RETENTION_MS = exports.MemoryOfflineStorageAdapter = exports.OfflineDataClient = exports.DooverOfflineError = exports.AmbiguousWriteError = exports.UnsupportedCapabilityError = exports.ALL_CAPABILITIES = exports.DooverRpcError = exports.RpcDispatcher = exports.UsersApi = exports.TurnApi = exports.ProcessorsApi = exports.PermissionsApi = exports.OrganisationsApi = exports.NotificationsApi = exports.MessagesApi = exports.ConnectionsApi = exports.ChannelsApi = exports.AlarmsApi = exports.AggregatesApi = exports.policyAllows = exports.AgentsApi = exports.DooverStatsCollector = exports.resetDooverClient = exports.peekDooverClient = exports.getDooverClient = exports.MultiplexClient = exports.LocalAgentClient = exports.DooverClient = void 0;
4
- exports.createNetworkStatusStore = exports.browserNetworkStatus = exports.generateSnowflakeIdAtTime = exports.extractSnowflakeId = exports.addTimestampToMessage = exports.DV_AUDIT_CHANNEL = void 0;
3
+ exports.isMfaRequiredBody = exports.DooverValidationError = exports.DooverMfaRequiredError = exports.DooverGatewayError = exports.DooverApiError = exports.RestClient = exports.GatewayClient = exports.buildAuth = exports.DooverAuthError = exports.AuthProfile = exports.DooverTokenAuth = exports.CookieAuth = exports.DooverAuth = exports.mergeBatchResponses = exports.chunkBatchItems = exports.MAX_BATCH_ITEMS = exports.splitRequestOptions = exports.isDooverRequestOptions = exports.requestOptions = exports.DEFAULT_OFFLINE_RETENTION_MS = exports.MemoryOfflineStorageAdapter = exports.OfflineDataClient = exports.DooverOfflineError = exports.AmbiguousWriteError = exports.UnsupportedCapabilityError = exports.ALL_CAPABILITIES = exports.DooverRpcError = exports.RpcDispatcher = exports.UsersApi = exports.TurnApi = exports.ProcessorsApi = exports.PermissionsApi = exports.OrganisationsApi = exports.NotificationsApi = exports.MessagesApi = exports.ConnectionsApi = exports.ChannelsApi = exports.AlarmsApi = exports.AggregatesApi = exports.mergeMessageCounts = exports.mergeConnectionHistory = exports.policyAllows = exports.AgentsApi = exports.DooverStatsCollector = exports.resetDooverClient = exports.peekDooverClient = exports.getDooverClient = exports.MultiplexClient = exports.LocalAgentClient = exports.DooverClient = void 0;
4
+ exports.createNetworkStatusStore = exports.browserNetworkStatus = exports.generateSnowflakeIdAtTime = exports.extractSnowflakeId = exports.addTimestampToMessage = exports.DV_AUDIT_CHANNEL = exports.getIdentifierFromPath = exports.DooverDataProvider = void 0;
5
5
  var doover_client_js_1 = require("./client/doover-client.js");
6
6
  Object.defineProperty(exports, "DooverClient", { enumerable: true, get: function () { return doover_client_js_1.DooverClient; } });
7
7
  var local_agent_client_js_1 = require("./client/local-agent-client.js");
@@ -18,6 +18,9 @@ var agents_api_js_1 = require("./apis/agents-api.js");
18
18
  Object.defineProperty(exports, "AgentsApi", { enumerable: true, get: function () { return agents_api_js_1.AgentsApi; } });
19
19
  var policy_js_1 = require("./utils/policy.js");
20
20
  Object.defineProperty(exports, "policyAllows", { enumerable: true, get: function () { return policy_js_1.policyAllows; } });
21
+ var agents_api_js_2 = require("./apis/agents-api.js");
22
+ Object.defineProperty(exports, "mergeConnectionHistory", { enumerable: true, get: function () { return agents_api_js_2.mergeConnectionHistory; } });
23
+ Object.defineProperty(exports, "mergeMessageCounts", { enumerable: true, get: function () { return agents_api_js_2.mergeMessageCounts; } });
21
24
  var aggregates_api_js_1 = require("./apis/aggregates-api.js");
22
25
  Object.defineProperty(exports, "AggregatesApi", { enumerable: true, get: function () { return aggregates_api_js_1.AggregatesApi; } });
23
26
  var alarms_api_js_1 = require("./apis/alarms-api.js");
@@ -38,3 +38,7 @@ export type { UseAgentTokenStateOptions } from "./useAgentTokenState.js";
38
38
  export { useAgentCredentials, useOrganisationCredentials, organisationCredentialsQueryKey, useCreateApiKey, useAddDeviceKey, useCreateEnrolmentCode, useRevokeCredential, agentCredentialsQueryKey, } from "./useAgentCredentials.js";
39
39
  export { getSharedQueryClient, resetSharedQueryClient, } from "./sharedQueryClient.js";
40
40
  export { useServiceReachability } from "./useServiceReachability.js";
41
+ export { useMultiAgentConnectionHistory, multiAgentConnectionHistoryQueryKey, } from "./useMultiAgentConnectionHistory.js";
42
+ export type { UseMultiAgentConnectionHistoryOptions, UseMultiAgentConnectionHistoryResult, } from "./useMultiAgentConnectionHistory.js";
43
+ export { useMultiAgentMessageCounts, multiAgentMessageCountsQueryKey, } from "./useMultiAgentMessageCounts.js";
44
+ export type { UseMultiAgentMessageCountsOptions, UseMultiAgentMessageCountsResult, } from "./useMultiAgentMessageCounts.js";
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.useServiceReachability = exports.resetSharedQueryClient = exports.getSharedQueryClient = exports.agentCredentialsQueryKey = exports.useRevokeCredential = exports.useCreateEnrolmentCode = exports.useAddDeviceKey = exports.useCreateApiKey = exports.organisationCredentialsQueryKey = exports.useOrganisationCredentials = exports.useAgentCredentials = exports.agentTokenStateQueryKey = exports.useCreateDeviceToken = exports.useCreateAdhocToken = exports.useSetRevocationFloor = exports.useRevokeAgentTokens = exports.useSetAgentAuthLock = exports.useSetAgentTokenPolicy = exports.useAgentTokenState = exports.useTurnCredentials = exports.useDeviceMap = exports.MULTI_AGENT_MAX_WINDOW_MS = exports.multiAgentChannelMessagesQueryKey = exports.useMultiAgentChannelMessages = exports.multiAgentAggregatesQueryKey = exports.useMultiAgentAggregates = exports.useSendRpc = exports.invocationLogsQueryKey = exports.useInvocationLogs = exports.channelMessageQueryKey = exports.useChannelMessage = exports.channelMessagesQueryKey = exports.useChannelMessages = exports.useUpdateMessage = exports.useUpdateAggregate = exports.useSendMessage = exports.useAgentChannel = exports.channelAggregateQueryKey = exports.useChannelAggregate = exports.useChannelSubscription = exports.agentConnectionsQueryKey = exports.useAgentConnections = exports.useConnectionState = exports.hasOfflineStatus = exports.useOfflineStatus = exports.useClientStatus = exports.useDooverClient = exports.DooverProvider = void 0;
3
+ exports.multiAgentConnectionHistoryQueryKey = exports.useMultiAgentConnectionHistory = exports.useServiceReachability = exports.resetSharedQueryClient = exports.getSharedQueryClient = exports.agentCredentialsQueryKey = exports.useRevokeCredential = exports.useCreateEnrolmentCode = exports.useAddDeviceKey = exports.useCreateApiKey = exports.organisationCredentialsQueryKey = exports.useOrganisationCredentials = exports.useAgentCredentials = exports.agentTokenStateQueryKey = exports.useCreateDeviceToken = exports.useCreateAdhocToken = exports.useSetRevocationFloor = exports.useRevokeAgentTokens = exports.useSetAgentAuthLock = exports.useSetAgentTokenPolicy = exports.useAgentTokenState = exports.useTurnCredentials = exports.useDeviceMap = exports.MULTI_AGENT_MAX_WINDOW_MS = exports.multiAgentChannelMessagesQueryKey = exports.useMultiAgentChannelMessages = exports.multiAgentAggregatesQueryKey = exports.useMultiAgentAggregates = exports.useSendRpc = exports.invocationLogsQueryKey = exports.useInvocationLogs = exports.channelMessageQueryKey = exports.useChannelMessage = exports.channelMessagesQueryKey = exports.useChannelMessages = exports.useUpdateMessage = exports.useUpdateAggregate = exports.useSendMessage = exports.useAgentChannel = exports.channelAggregateQueryKey = exports.useChannelAggregate = exports.useChannelSubscription = exports.agentConnectionsQueryKey = exports.useAgentConnections = exports.useConnectionState = exports.hasOfflineStatus = exports.useOfflineStatus = exports.useClientStatus = exports.useDooverClient = exports.DooverProvider = void 0;
4
+ exports.multiAgentMessageCountsQueryKey = exports.useMultiAgentMessageCounts = void 0;
4
5
  var context_js_1 = require("./context.js");
5
6
  Object.defineProperty(exports, "DooverProvider", { enumerable: true, get: function () { return context_js_1.DooverProvider; } });
6
7
  Object.defineProperty(exports, "useDooverClient", { enumerable: true, get: function () { return context_js_1.useDooverClient; } });
@@ -72,3 +73,9 @@ Object.defineProperty(exports, "getSharedQueryClient", { enumerable: true, get:
72
73
  Object.defineProperty(exports, "resetSharedQueryClient", { enumerable: true, get: function () { return sharedQueryClient_js_1.resetSharedQueryClient; } });
73
74
  var useServiceReachability_js_1 = require("./useServiceReachability.js");
74
75
  Object.defineProperty(exports, "useServiceReachability", { enumerable: true, get: function () { return useServiceReachability_js_1.useServiceReachability; } });
76
+ var useMultiAgentConnectionHistory_js_1 = require("./useMultiAgentConnectionHistory.js");
77
+ Object.defineProperty(exports, "useMultiAgentConnectionHistory", { enumerable: true, get: function () { return useMultiAgentConnectionHistory_js_1.useMultiAgentConnectionHistory; } });
78
+ Object.defineProperty(exports, "multiAgentConnectionHistoryQueryKey", { enumerable: true, get: function () { return useMultiAgentConnectionHistory_js_1.multiAgentConnectionHistoryQueryKey; } });
79
+ var useMultiAgentMessageCounts_js_1 = require("./useMultiAgentMessageCounts.js");
80
+ Object.defineProperty(exports, "useMultiAgentMessageCounts", { enumerable: true, get: function () { return useMultiAgentMessageCounts_js_1.useMultiAgentMessageCounts; } });
81
+ Object.defineProperty(exports, "multiAgentMessageCountsQueryKey", { enumerable: true, get: function () { return useMultiAgentMessageCounts_js_1.multiAgentMessageCountsQueryKey; } });
@@ -0,0 +1,35 @@
1
+ import { type UseQueryResult } from "@tanstack/react-query";
2
+ import type { AgentConnectionHistory, ConnectionHistoryResponse } from "../types/connection.js";
3
+ export interface UseMultiAgentConnectionHistoryOptions {
4
+ /** Snowflake id bounds. Defaults to the last 7 days; at most 31 days apart. */
5
+ before?: string;
6
+ after?: string;
7
+ /** Slot width in ms for the fleet `buckets` series. Omit for no buckets. */
8
+ bucketMs?: number;
9
+ /** Include each agent's state segments (at most 25 agents per call). */
10
+ includeSegments?: boolean;
11
+ /** Defaults true; the query also waits for a non-empty `agentIds`. */
12
+ enabled?: boolean;
13
+ }
14
+ export declare function multiAgentConnectionHistoryQueryKey(agentIds: string[], options?: UseMultiAgentConnectionHistoryOptions): readonly ["doover", "connection_history", string, {
15
+ readonly before: string | null;
16
+ readonly after: string | null;
17
+ readonly bucket_ms: number | null;
18
+ readonly include_segments: boolean;
19
+ }];
20
+ export interface UseMultiAgentConnectionHistoryResult {
21
+ history: ConnectionHistoryResponse | undefined;
22
+ /** Keyed by agent id for O(1) lookup. */
23
+ agentsById: Record<string, AgentConnectionHistory>;
24
+ query: UseQueryResult<ConnectionHistoryResponse>;
25
+ }
26
+ /**
27
+ * Connection state over time for a set of agents, in one request:
28
+ * per-agent summaries (and segments on request) plus an optional fleet
29
+ * series per slot. The window is part of the key, so callers that want a
30
+ * stable cache across remounts should snap `before` to a grid rather than
31
+ * pass a fresh "now" each render. Never stale on its own: history does
32
+ * not change, and the trailing edge moves only as far as the caller's
33
+ * `before` does.
34
+ */
35
+ export declare function useMultiAgentConnectionHistory(agentIds: string[], options?: UseMultiAgentConnectionHistoryOptions): UseMultiAgentConnectionHistoryResult;