@athenaintel/react 0.12.1 → 0.12.2

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.
@@ -0,0 +1,13 @@
1
+ "use strict";
2
+ const React = require("react");
3
+ const AthenaContext = React.createContext(null);
4
+ function useAthenaConfig() {
5
+ const ctx = React.useContext(AthenaContext);
6
+ if (!ctx) {
7
+ throw new Error("[AthenaSDK] useAthenaConfig must be used within <AthenaProvider>");
8
+ }
9
+ return ctx;
10
+ }
11
+ exports.AthenaContext = AthenaContext;
12
+ exports.useAthenaConfig = useAthenaConfig;
13
+ //# sourceMappingURL=AthenaContext-B1QMhIP-.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"AthenaContext-B1QMhIP-.cjs","sources":["../src/provider/AthenaContext.ts"],"sourcesContent":["import { createContext, useContext } from 'react';\nimport type { AthenaTransport } from '../runtime/transport';\nimport type { AthenaProviderConfig } from './config';\nimport type { AthenaCitationLinkOptions, AthenaLinkClickOptions } from './citation-links';\n\nexport interface AthenaConfig extends Pick<AthenaProviderConfig, 'apiKey' | 'token'> {\n backendUrl: string;\n appUrl: string;\n enabledToolkits: string[];\n /** Effective chat transport; absent means `legacy`. Optional so existing\n * `AthenaConfig` object literals keep compiling. */\n transport?: AthenaTransport;\n linkClicks?: AthenaLinkClickOptions;\n citationLinks?: AthenaCitationLinkOptions;\n}\n\nexport const AthenaContext = createContext<AthenaConfig | null>(null);\n\nexport function useAthenaConfig(): AthenaConfig {\n const ctx = useContext(AthenaContext);\n if (!ctx) {\n throw new Error('[AthenaSDK] useAthenaConfig must be used within <AthenaProvider>');\n }\n return ctx;\n}\n"],"names":["createContext","useContext"],"mappings":";;AAgBO,MAAM,gBAAgBA,MAAAA,cAAmC,IAAI;AAE7D,SAAS,kBAAgC;AAC9C,QAAM,MAAMC,MAAAA,WAAW,aAAa;AACpC,MAAI,CAAC,KAAK;AACR,UAAM,IAAI,MAAM,kEAAkE;AAAA,EACpF;AACA,SAAO;AACT;;;"}
@@ -0,0 +1,14 @@
1
+ import { useContext, createContext } from "react";
2
+ const AthenaContext = createContext(null);
3
+ function useAthenaConfig() {
4
+ const ctx = useContext(AthenaContext);
5
+ if (!ctx) {
6
+ throw new Error("[AthenaSDK] useAthenaConfig must be used within <AthenaProvider>");
7
+ }
8
+ return ctx;
9
+ }
10
+ export {
11
+ AthenaContext as A,
12
+ useAthenaConfig as u
13
+ };
14
+ //# sourceMappingURL=AthenaContext-MOslgOmE.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"AthenaContext-MOslgOmE.js","sources":["../src/provider/AthenaContext.ts"],"sourcesContent":["import { createContext, useContext } from 'react';\nimport type { AthenaTransport } from '../runtime/transport';\nimport type { AthenaProviderConfig } from './config';\nimport type { AthenaCitationLinkOptions, AthenaLinkClickOptions } from './citation-links';\n\nexport interface AthenaConfig extends Pick<AthenaProviderConfig, 'apiKey' | 'token'> {\n backendUrl: string;\n appUrl: string;\n enabledToolkits: string[];\n /** Effective chat transport; absent means `legacy`. Optional so existing\n * `AthenaConfig` object literals keep compiling. */\n transport?: AthenaTransport;\n linkClicks?: AthenaLinkClickOptions;\n citationLinks?: AthenaCitationLinkOptions;\n}\n\nexport const AthenaContext = createContext<AthenaConfig | null>(null);\n\nexport function useAthenaConfig(): AthenaConfig {\n const ctx = useContext(AthenaContext);\n if (!ctx) {\n throw new Error('[AthenaSDK] useAthenaConfig must be used within <AthenaProvider>');\n }\n return ctx;\n}\n"],"names":[],"mappings":";AAgBO,MAAM,gBAAgB,cAAmC,IAAI;AAE7D,SAAS,kBAAgC;AAC9C,QAAM,MAAM,WAAW,aAAa;AACpC,MAAI,CAAC,KAAK;AACR,UAAM,IAAI,MAAM,kEAAkE;AAAA,EACpF;AACA,SAAO;AACT;"}
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Vanilla (framework-agnostic) live client for Generic Doc assets.
3
+ *
4
+ * `connectGenericDoc` owns the full connection lifecycle: mint a room-bound
5
+ * token via the public API, open the Keryx WebSocket with the v14 provider
6
+ * (`@y/websocket` + `@y/y`), re-mint before expiry, apply the close-code
7
+ * policy (4401 → one fresh mint, other 44xx → permanent stop, everything
8
+ * else → provider backoff), and expose presence from awareness. React apps
9
+ * use `useGenericDoc` from `@athenaintel/react/collab` instead of calling
10
+ * this directly.
11
+ */
12
+ import * as Y from '@y/y';
13
+ import { type CollabAuth, type CollabTokenResponse, CollabTokenError } from './mint';
14
+ export type GenericDocStatus = 'connecting' | 'connected' | 'disconnected' | 'closed' | 'error';
15
+ export interface PresenceEntry {
16
+ clientId: number;
17
+ state: Record<string, unknown>;
18
+ }
19
+ export interface GenericDocHandle {
20
+ /** The live shared document. Owned by the handle; destroyed with it. */
21
+ readonly doc: Y.Doc;
22
+ readonly status: GenericDocStatus;
23
+ /** Granted access from the last successful mint. */
24
+ readonly accessType: 'r' | 'rw' | null;
25
+ /** Terminal error, when status is 'error' or 'closed'. */
26
+ readonly error: Error | null;
27
+ /** Monotonic change counter — bumps on every status/presence notification. */
28
+ readonly version: number;
29
+ getPresence: () => PresenceEntry[];
30
+ /** Broadcast this client's presence state (requires a live connection). */
31
+ setPresence: (state: Record<string, unknown> | null) => void;
32
+ /**
33
+ * Force an early token refresh. Session-preserving: the live connection
34
+ * stays up until the fresh token is minted; a failed mint retries on a
35
+ * short timer instead of dropping the session.
36
+ */
37
+ refreshNow: () => Promise<void>;
38
+ onChange: (listener: () => void) => () => void;
39
+ destroy: () => void;
40
+ }
41
+ export declare function connectGenericDoc(args: {
42
+ assetId: string;
43
+ auth: CollabAuth;
44
+ access?: 'view' | 'edit';
45
+ }): GenericDocHandle;
46
+ export { CollabTokenError };
47
+ export type { CollabAuth, CollabTokenResponse };
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Keryx WebSocket close-code policy.
3
+ *
4
+ * Keryx (@y/hub) encodes retry semantics in close codes: 4400–4499 are
5
+ * permanent application errors — the client must stop reconnecting until the
6
+ * app acts — while everything else is transient and left to the provider's
7
+ * exponential backoff. Two permanent codes carry specific meaning:
8
+ *
9
+ * - 4401 "permission revoked": the token was rejected mid-session (access
10
+ * revoked, permissions changed, or the token aged out server-side). The
11
+ * right response is one fresh mint — which re-runs the server-side
12
+ * permission check — and a reconnect only if the mint succeeds.
13
+ * - 4404 "document deleted": permanent; the document is not coming back.
14
+ */
15
+ export declare const WS_CLOSE_AUTH_REVOKED = 4401;
16
+ export declare const WS_CLOSE_DOC_DELETED = 4404;
17
+ export type CloseAction = 'remint' | 'stop' | 'retry';
18
+ export declare function classifyClose(code: number | undefined): CloseAction;
@@ -0,0 +1,13 @@
1
+ /**
2
+ * `@athenaintel/react/collab` — live collaboration for Generic Doc assets.
3
+ *
4
+ * Built on yjs v14 (`@y/y`) and the v14-line WebSocket provider
5
+ * (`@y/websocket`). Auth flows through the public collab-token mint
6
+ * (`POST /api/v0/assets/{id}/collab-token`), which is allowlisted server-side
7
+ * to `generic_doc` assets and admin-only during the initial rollout.
8
+ */
9
+ export { classifyClose, WS_CLOSE_AUTH_REVOKED, WS_CLOSE_DOC_DELETED } from './close-policy';
10
+ export { CollabTokenError, connectGenericDoc, type CollabAuth, type CollabTokenResponse, type GenericDocHandle, type GenericDocStatus, type PresenceEntry, } from './client';
11
+ export { getAthenaApiBaseUrl, mintCollabToken } from './mint';
12
+ export { useGenericDoc, type UseGenericDocResult } from './react';
13
+ export { defineDocShape, type BoundDocShape, type DocShapeKind } from './shape';
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Collab-token mint client for Generic Doc assets.
3
+ *
4
+ * Calls `POST /api/v0/assets/{assetId}/collab-token` — the only public surface
5
+ * that issues Keryx capability tokens, allowlisted server-side to the
6
+ * `generic_doc` asset type and admin-only during the initial rollout. Tokens
7
+ * are room-bound and short-lived; `connectGenericDoc` re-mints automatically
8
+ * before expiry.
9
+ */
10
+ export interface CollabAuth {
11
+ /** Athena API base or any Athena backend URL (e.g. the AthenaProvider `backendUrl`). */
12
+ backendUrl: string;
13
+ /** Personal or sandbox API key. Used when no bearer token is provided. */
14
+ apiKey?: string;
15
+ /** Per-viewer bearer token. Takes precedence over the API key. */
16
+ token?: string | null;
17
+ }
18
+ export interface CollabTokenResponse {
19
+ token: string;
20
+ access_type: 'r' | 'rw';
21
+ expires_at_ms: number;
22
+ ws_url: string;
23
+ rest_url: string;
24
+ org: string;
25
+ doc_id: string;
26
+ branch: string;
27
+ }
28
+ export declare class CollabTokenError extends Error {
29
+ readonly status: number;
30
+ constructor(status: number, message: string);
31
+ }
32
+ /** Trim a nested Athena endpoint (e.g. `/api/assistant-ui`) back to the API origin. */
33
+ export declare function getAthenaApiBaseUrl(backendUrl: string): string;
34
+ export declare function mintCollabToken(args: {
35
+ auth: CollabAuth;
36
+ assetId: string;
37
+ access: 'view' | 'edit';
38
+ signal?: AbortSignal;
39
+ }): Promise<CollabTokenResponse>;
@@ -0,0 +1,22 @@
1
+ /**
2
+ * React bindings for Generic Doc live collaboration.
3
+ *
4
+ * `useGenericDoc(assetId)` opens (and owns) a `connectGenericDoc` handle,
5
+ * resolving auth from the surrounding `AthenaProvider` (per-viewer bearer when
6
+ * present, API key otherwise) and re-rendering on status/presence changes via
7
+ * `useSyncExternalStore`.
8
+ */
9
+ import { type GenericDocStatus, type PresenceEntry } from './client';
10
+ import type * as Y from '@y/y';
11
+ export interface UseGenericDocResult {
12
+ /** Null until the handle is created (first render effect). */
13
+ doc: Y.Doc | null;
14
+ status: GenericDocStatus;
15
+ accessType: 'r' | 'rw' | null;
16
+ error: Error | null;
17
+ presence: PresenceEntry[];
18
+ setPresence: (state: Record<string, unknown> | null) => void;
19
+ }
20
+ export declare function useGenericDoc(assetId: string, options?: {
21
+ access?: 'view' | 'edit';
22
+ }): UseGenericDocResult;
@@ -0,0 +1,25 @@
1
+ /**
2
+ * `defineDocShape` — a typed lens over a Generic Doc's root types.
3
+ *
4
+ * A shape is documentation + ergonomics, not a migration system: it names the
5
+ * root keys an app expects and gives JSON-level reads (`toJSON`, `subscribe`)
6
+ * that hide CRDT mechanics for the common case. The raw `Y.Doc` (yjs v14 /
7
+ * `@y/y`) stays available on the handle for full delta-level power.
8
+ */
9
+ import type * as Y from '@y/y';
10
+ export type DocShapeKind = 'map' | 'array' | 'text' | 'xml';
11
+ export interface BoundDocShape<S extends Record<string, DocShapeKind>> {
12
+ /** The live root type for a declared key (v14 unified `YType`). */
13
+ get: <K extends keyof S & string>(key: K) => ReturnType<Y.Doc['get']>;
14
+ /** JSON snapshot of every declared root (v14 node shape: attributes + `children`). */
15
+ toJSON: () => Record<keyof S & string, unknown>;
16
+ /**
17
+ * Subscribe to JSON snapshots. Fires once immediately, then after every
18
+ * change to any declared root (batched per transaction flush).
19
+ */
20
+ subscribe: (listener: (json: Record<keyof S & string, unknown>) => void) => () => void;
21
+ }
22
+ export declare function defineDocShape<S extends Record<string, DocShapeKind>>(shape: S): {
23
+ shape: S;
24
+ bind(doc: Y.Doc): BoundDocShape<S>;
25
+ };
@@ -0,0 +1,351 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
4
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
5
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
6
+ const websocket = require("@y/websocket");
7
+ const Y = require("@y/y");
8
+ const React = require("react");
9
+ const AthenaContext = require("./AthenaContext-B1QMhIP-.cjs");
10
+ function _interopNamespaceDefault(e) {
11
+ const n = Object.create(null, { [Symbol.toStringTag]: { value: "Module" } });
12
+ if (e) {
13
+ for (const k in e) {
14
+ if (k !== "default") {
15
+ const d = Object.getOwnPropertyDescriptor(e, k);
16
+ Object.defineProperty(n, k, d.get ? d : {
17
+ enumerable: true,
18
+ get: () => e[k]
19
+ });
20
+ }
21
+ }
22
+ }
23
+ n.default = e;
24
+ return Object.freeze(n);
25
+ }
26
+ const Y__namespace = /* @__PURE__ */ _interopNamespaceDefault(Y);
27
+ const WS_CLOSE_AUTH_REVOKED = 4401;
28
+ const WS_CLOSE_DOC_DELETED = 4404;
29
+ function classifyClose(code) {
30
+ if (code === void 0) return "retry";
31
+ if (code === WS_CLOSE_AUTH_REVOKED) return "remint";
32
+ if (code >= 4400 && code < 4500) return "stop";
33
+ return "retry";
34
+ }
35
+ class CollabTokenError extends Error {
36
+ constructor(status, message) {
37
+ super(message);
38
+ __publicField(this, "status");
39
+ this.name = "CollabTokenError";
40
+ this.status = status;
41
+ }
42
+ }
43
+ function getAuthHeaders(auth) {
44
+ if (auth.token) {
45
+ return { Authorization: `Bearer ${auth.token}` };
46
+ }
47
+ if (auth.apiKey) {
48
+ return { "X-API-KEY": auth.apiKey };
49
+ }
50
+ return {};
51
+ }
52
+ function getAthenaApiBaseUrl(backendUrl) {
53
+ const stripped = backendUrl.replace(/\/api\/assistant-ui\/?$/, "");
54
+ return stripped.replace(/\/$/, "");
55
+ }
56
+ async function mintCollabToken(args) {
57
+ const base = getAthenaApiBaseUrl(args.auth.backendUrl);
58
+ const response = await fetch(
59
+ `${base}/api/v0/assets/${encodeURIComponent(args.assetId)}/collab-token`,
60
+ {
61
+ method: "POST",
62
+ headers: {
63
+ "Content-Type": "application/json",
64
+ ...getAuthHeaders(args.auth)
65
+ },
66
+ body: JSON.stringify({ access: args.access }),
67
+ signal: args.signal
68
+ }
69
+ );
70
+ if (!response.ok) {
71
+ let detail = "";
72
+ try {
73
+ const body = await response.json();
74
+ if (body && typeof body === "object" && "detail" in body) {
75
+ detail = String(body.detail);
76
+ }
77
+ } catch {
78
+ }
79
+ throw new CollabTokenError(
80
+ response.status,
81
+ detail || `Collab token mint failed with status ${response.status}`
82
+ );
83
+ }
84
+ return await response.json();
85
+ }
86
+ const REFRESH_HEADROOM_MS = 5 * 60 * 1e3;
87
+ const MIN_REFRESH_DELAY_MS = 30 * 1e3;
88
+ const MAX_CONSECUTIVE_REMINTS = 2;
89
+ function connectGenericDoc(args) {
90
+ const access = args.access ?? "view";
91
+ const doc = new Y__namespace.Doc();
92
+ const listeners = /* @__PURE__ */ new Set();
93
+ let provider = null;
94
+ let refreshTimer = null;
95
+ let destroyed = false;
96
+ let status = "connecting";
97
+ let accessType = null;
98
+ let error = null;
99
+ let lastPresence = null;
100
+ let version = 0;
101
+ let consecutiveRemints = 0;
102
+ const notify = () => {
103
+ version += 1;
104
+ for (const listener of listeners) listener();
105
+ };
106
+ const setStatus = (next, err = null) => {
107
+ if (destroyed && next !== "closed") return;
108
+ status = next;
109
+ error = err;
110
+ notify();
111
+ };
112
+ const clearRefreshTimer = () => {
113
+ if (refreshTimer !== null) {
114
+ clearTimeout(refreshTimer);
115
+ refreshTimer = null;
116
+ }
117
+ };
118
+ const teardownProvider = () => {
119
+ clearRefreshTimer();
120
+ if (provider) {
121
+ provider.destroy();
122
+ provider = null;
123
+ }
124
+ };
125
+ const scheduleRefresh = (grant) => {
126
+ clearRefreshTimer();
127
+ const delay = Math.max(
128
+ grant.expires_at_ms - Date.now() - REFRESH_HEADROOM_MS,
129
+ MIN_REFRESH_DELAY_MS
130
+ );
131
+ refreshTimer = setTimeout(() => {
132
+ void connect({ scheduledRefresh: true });
133
+ }, delay);
134
+ };
135
+ const connect = async (opts) => {
136
+ if (destroyed) return;
137
+ const scheduledRefresh = (opts == null ? void 0 : opts.scheduledRefresh) === true;
138
+ if (!scheduledRefresh) {
139
+ teardownProvider();
140
+ } else {
141
+ clearRefreshTimer();
142
+ }
143
+ let grant;
144
+ try {
145
+ grant = await mintCollabToken({ auth: args.auth, assetId: args.assetId, access });
146
+ } catch (err) {
147
+ if (scheduledRefresh && !destroyed) {
148
+ refreshTimer = setTimeout(() => {
149
+ void connect({ scheduledRefresh: true });
150
+ }, MIN_REFRESH_DELAY_MS);
151
+ return;
152
+ }
153
+ setStatus("error", err instanceof Error ? err : new Error(String(err)));
154
+ return;
155
+ }
156
+ if (destroyed) return;
157
+ if (scheduledRefresh) {
158
+ teardownProvider();
159
+ }
160
+ accessType = grant.access_type;
161
+ const nextProvider = new websocket.WebsocketProvider(grant.ws_url, `${grant.org}/${grant.doc_id}`, doc, {
162
+ params: {
163
+ yauth: grant.token,
164
+ branch: grant.branch,
165
+ gc: "true"
166
+ }
167
+ });
168
+ provider = nextProvider;
169
+ nextProvider.on("status", (event) => {
170
+ if (provider !== nextProvider) return;
171
+ if (event.status === "connected") {
172
+ consecutiveRemints = 0;
173
+ }
174
+ setStatus(event.status);
175
+ if (event.status === "connected" && lastPresence !== null) {
176
+ nextProvider.awareness.setLocalState(lastPresence);
177
+ }
178
+ });
179
+ nextProvider.on("connection-close", (event) => {
180
+ if (provider !== nextProvider) return;
181
+ const action = classifyClose(event == null ? void 0 : event.code);
182
+ if (action === "remint") {
183
+ consecutiveRemints += 1;
184
+ teardownProvider();
185
+ if (consecutiveRemints > MAX_CONSECUTIVE_REMINTS) {
186
+ setStatus(
187
+ "closed",
188
+ new Error("Access repeatedly revoked mid-session (4401); giving up.")
189
+ );
190
+ return;
191
+ }
192
+ void connect();
193
+ } else if (action === "stop") {
194
+ teardownProvider();
195
+ setStatus(
196
+ "closed",
197
+ new Error(`Connection closed permanently (code ${(event == null ? void 0 : event.code) ?? "unknown"})`)
198
+ );
199
+ }
200
+ });
201
+ nextProvider.awareness.on("change", () => {
202
+ if (provider !== nextProvider) return;
203
+ notify();
204
+ });
205
+ scheduleRefresh(grant);
206
+ };
207
+ void connect();
208
+ return {
209
+ doc,
210
+ get status() {
211
+ return status;
212
+ },
213
+ get accessType() {
214
+ return accessType;
215
+ },
216
+ get error() {
217
+ return error;
218
+ },
219
+ get version() {
220
+ return version;
221
+ },
222
+ getPresence: () => {
223
+ if (!provider) return [];
224
+ const entries = [];
225
+ provider.awareness.getStates().forEach((state, clientId) => {
226
+ entries.push({ clientId, state });
227
+ });
228
+ return entries;
229
+ },
230
+ setPresence: (state) => {
231
+ lastPresence = state;
232
+ provider == null ? void 0 : provider.awareness.setLocalState(state);
233
+ },
234
+ refreshNow: () => connect({ scheduledRefresh: true }),
235
+ onChange: (listener) => {
236
+ listeners.add(listener);
237
+ return () => {
238
+ listeners.delete(listener);
239
+ };
240
+ },
241
+ destroy: () => {
242
+ if (destroyed) return;
243
+ destroyed = true;
244
+ teardownProvider();
245
+ listeners.clear();
246
+ doc.destroy();
247
+ status = "closed";
248
+ }
249
+ };
250
+ }
251
+ function useGenericDoc(assetId, options) {
252
+ const config = AthenaContext.useAthenaConfig();
253
+ const access = (options == null ? void 0 : options.access) ?? "view";
254
+ const [handle, setHandle] = React.useState(null);
255
+ const handleRef = React.useRef(null);
256
+ React.useEffect(() => {
257
+ const next = connectGenericDoc({
258
+ assetId,
259
+ access,
260
+ auth: {
261
+ backendUrl: config.backendUrl,
262
+ apiKey: config.apiKey,
263
+ token: config.token
264
+ }
265
+ });
266
+ handleRef.current = next;
267
+ setHandle(next);
268
+ return () => {
269
+ handleRef.current = null;
270
+ next.destroy();
271
+ };
272
+ }, [assetId, access, config.backendUrl, config.apiKey, config.token]);
273
+ const subscribe = React.useMemo(() => {
274
+ return (onStoreChange) => {
275
+ if (!handle) return () => {
276
+ };
277
+ return handle.onChange(onStoreChange);
278
+ };
279
+ }, [handle]);
280
+ React.useSyncExternalStore(
281
+ subscribe,
282
+ () => {
283
+ if (!handle) return EMPTY_SNAPSHOT;
284
+ return `${handle.status}|${handle.accessType ?? ""}|${handle.version}`;
285
+ },
286
+ () => EMPTY_SNAPSHOT
287
+ );
288
+ return {
289
+ doc: (handle == null ? void 0 : handle.doc) ?? null,
290
+ status: (handle == null ? void 0 : handle.status) ?? "connecting",
291
+ accessType: (handle == null ? void 0 : handle.accessType) ?? null,
292
+ error: (handle == null ? void 0 : handle.error) ?? null,
293
+ presence: (handle == null ? void 0 : handle.getPresence()) ?? [],
294
+ setPresence: (state) => {
295
+ var _a;
296
+ return (_a = handleRef.current) == null ? void 0 : _a.setPresence(state);
297
+ }
298
+ };
299
+ }
300
+ const EMPTY_SNAPSHOT = "init||0";
301
+ function defineDocShape(shape) {
302
+ const keys = Object.keys(shape);
303
+ return {
304
+ shape,
305
+ bind(doc) {
306
+ const toJSON = () => {
307
+ const out = {};
308
+ for (const key of keys) {
309
+ out[key] = doc.get(key).toJSON();
310
+ }
311
+ return out;
312
+ };
313
+ return {
314
+ get: (key) => doc.get(key),
315
+ toJSON,
316
+ subscribe: (listener) => {
317
+ let scheduled = false;
318
+ const emit = () => {
319
+ scheduled = false;
320
+ listener(toJSON());
321
+ };
322
+ const onDeepChange = () => {
323
+ if (scheduled) return;
324
+ scheduled = true;
325
+ queueMicrotask(emit);
326
+ };
327
+ const roots = keys.map((key) => doc.get(key));
328
+ for (const root of roots) {
329
+ root.observeDeep(onDeepChange);
330
+ }
331
+ listener(toJSON());
332
+ return () => {
333
+ for (const root of roots) {
334
+ root.unobserveDeep(onDeepChange);
335
+ }
336
+ };
337
+ }
338
+ };
339
+ }
340
+ };
341
+ }
342
+ exports.CollabTokenError = CollabTokenError;
343
+ exports.WS_CLOSE_AUTH_REVOKED = WS_CLOSE_AUTH_REVOKED;
344
+ exports.WS_CLOSE_DOC_DELETED = WS_CLOSE_DOC_DELETED;
345
+ exports.classifyClose = classifyClose;
346
+ exports.connectGenericDoc = connectGenericDoc;
347
+ exports.defineDocShape = defineDocShape;
348
+ exports.getAthenaApiBaseUrl = getAthenaApiBaseUrl;
349
+ exports.mintCollabToken = mintCollabToken;
350
+ exports.useGenericDoc = useGenericDoc;
351
+ //# sourceMappingURL=collab.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"collab.cjs","sources":["../src/collab/close-policy.ts","../src/collab/mint.ts","../src/collab/client.ts","../src/collab/react.ts","../src/collab/shape.ts"],"sourcesContent":["/**\n * Keryx WebSocket close-code policy.\n *\n * Keryx (@y/hub) encodes retry semantics in close codes: 4400–4499 are\n * permanent application errors — the client must stop reconnecting until the\n * app acts — while everything else is transient and left to the provider's\n * exponential backoff. Two permanent codes carry specific meaning:\n *\n * - 4401 \"permission revoked\": the token was rejected mid-session (access\n * revoked, permissions changed, or the token aged out server-side). The\n * right response is one fresh mint — which re-runs the server-side\n * permission check — and a reconnect only if the mint succeeds.\n * - 4404 \"document deleted\": permanent; the document is not coming back.\n */\n\nexport const WS_CLOSE_AUTH_REVOKED = 4401;\nexport const WS_CLOSE_DOC_DELETED = 4404;\n\nexport type CloseAction = 'remint' | 'stop' | 'retry';\n\nexport function classifyClose(code: number | undefined): CloseAction {\n if (code === undefined) return 'retry';\n if (code === WS_CLOSE_AUTH_REVOKED) return 'remint';\n if (code >= 4400 && code < 4500) return 'stop';\n return 'retry';\n}\n","/**\n * Collab-token mint client for Generic Doc assets.\n *\n * Calls `POST /api/v0/assets/{assetId}/collab-token` — the only public surface\n * that issues Keryx capability tokens, allowlisted server-side to the\n * `generic_doc` asset type and admin-only during the initial rollout. Tokens\n * are room-bound and short-lived; `connectGenericDoc` re-mints automatically\n * before expiry.\n */\n\nexport interface CollabAuth {\n /** Athena API base or any Athena backend URL (e.g. the AthenaProvider `backendUrl`). */\n backendUrl: string;\n /** Personal or sandbox API key. Used when no bearer token is provided. */\n apiKey?: string;\n /** Per-viewer bearer token. Takes precedence over the API key. */\n token?: string | null;\n}\n\nexport interface CollabTokenResponse {\n token: string;\n access_type: 'r' | 'rw';\n expires_at_ms: number;\n ws_url: string;\n rest_url: string;\n org: string;\n doc_id: string;\n branch: string;\n}\n\nexport class CollabTokenError extends Error {\n readonly status: number;\n\n constructor(status: number, message: string) {\n super(message);\n this.name = 'CollabTokenError';\n this.status = status;\n }\n}\n\nfunction getAuthHeaders(auth: CollabAuth): Record<string, string> {\n if (auth.token) {\n return { Authorization: `Bearer ${auth.token}` };\n }\n if (auth.apiKey) {\n return { 'X-API-KEY': auth.apiKey };\n }\n return {};\n}\n\n/** Trim a nested Athena endpoint (e.g. `/api/assistant-ui`) back to the API origin. */\nexport function getAthenaApiBaseUrl(backendUrl: string): string {\n const stripped = backendUrl.replace(/\\/api\\/assistant-ui\\/?$/, '');\n return stripped.replace(/\\/$/, '');\n}\n\nexport async function mintCollabToken(args: {\n auth: CollabAuth;\n assetId: string;\n access: 'view' | 'edit';\n signal?: AbortSignal;\n}): Promise<CollabTokenResponse> {\n const base = getAthenaApiBaseUrl(args.auth.backendUrl);\n const response = await fetch(\n `${base}/api/v0/assets/${encodeURIComponent(args.assetId)}/collab-token`,\n {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...getAuthHeaders(args.auth),\n },\n body: JSON.stringify({ access: args.access }),\n signal: args.signal,\n }\n );\n if (!response.ok) {\n let detail = '';\n try {\n const body: unknown = await response.json();\n if (body && typeof body === 'object' && 'detail' in body) {\n detail = String((body as { detail: unknown }).detail);\n }\n } catch {\n // non-JSON error body; status alone tells the story\n }\n throw new CollabTokenError(\n response.status,\n detail || `Collab token mint failed with status ${response.status}`\n );\n }\n return (await response.json()) as CollabTokenResponse;\n}\n","/**\n * Vanilla (framework-agnostic) live client for Generic Doc assets.\n *\n * `connectGenericDoc` owns the full connection lifecycle: mint a room-bound\n * token via the public API, open the Keryx WebSocket with the v14 provider\n * (`@y/websocket` + `@y/y`), re-mint before expiry, apply the close-code\n * policy (4401 → one fresh mint, other 44xx → permanent stop, everything\n * else → provider backoff), and expose presence from awareness. React apps\n * use `useGenericDoc` from `@athenaintel/react/collab` instead of calling\n * this directly.\n */\n\nimport { WebsocketProvider } from '@y/websocket';\nimport * as Y from '@y/y';\nimport { classifyClose } from './close-policy';\nimport {\n type CollabAuth,\n type CollabTokenResponse,\n CollabTokenError,\n mintCollabToken,\n} from './mint';\n\nexport type GenericDocStatus =\n | 'connecting'\n | 'connected'\n | 'disconnected'\n | 'closed'\n | 'error';\n\nexport interface PresenceEntry {\n clientId: number;\n state: Record<string, unknown>;\n}\n\nexport interface GenericDocHandle {\n /** The live shared document. Owned by the handle; destroyed with it. */\n readonly doc: Y.Doc;\n readonly status: GenericDocStatus;\n /** Granted access from the last successful mint. */\n readonly accessType: 'r' | 'rw' | null;\n /** Terminal error, when status is 'error' or 'closed'. */\n readonly error: Error | null;\n /** Monotonic change counter — bumps on every status/presence notification. */\n readonly version: number;\n getPresence: () => PresenceEntry[];\n /** Broadcast this client's presence state (requires a live connection). */\n setPresence: (state: Record<string, unknown> | null) => void;\n /**\n * Force an early token refresh. Session-preserving: the live connection\n * stays up until the fresh token is minted; a failed mint retries on a\n * short timer instead of dropping the session.\n */\n refreshNow: () => Promise<void>;\n onChange: (listener: () => void) => () => void;\n destroy: () => void;\n}\n\n/** Re-mint this long before token expiry (clamped to a floor for short TTLs). */\nconst REFRESH_HEADROOM_MS = 5 * 60 * 1000;\nconst MIN_REFRESH_DELAY_MS = 30 * 1000;\n\n/** Consecutive 4401→mint cycles allowed without a successful connect between. */\nconst MAX_CONSECUTIVE_REMINTS = 2;\n\nexport function connectGenericDoc(args: {\n assetId: string;\n auth: CollabAuth;\n access?: 'view' | 'edit';\n}): GenericDocHandle {\n const access = args.access ?? 'view';\n const doc = new Y.Doc();\n const listeners = new Set<() => void>();\n\n let provider: WebsocketProvider | null = null;\n let refreshTimer: ReturnType<typeof setTimeout> | null = null;\n let destroyed = false;\n let status: GenericDocStatus = 'connecting';\n let accessType: 'r' | 'rw' | null = null;\n let error: Error | null = null;\n let lastPresence: Record<string, unknown> | null = null;\n let version = 0;\n let consecutiveRemints = 0;\n\n const notify = () => {\n version += 1;\n for (const listener of listeners) listener();\n };\n\n const setStatus = (next: GenericDocStatus, err: Error | null = null) => {\n if (destroyed && next !== 'closed') return;\n status = next;\n error = err;\n notify();\n };\n\n const clearRefreshTimer = () => {\n if (refreshTimer !== null) {\n clearTimeout(refreshTimer);\n refreshTimer = null;\n }\n };\n\n const teardownProvider = () => {\n clearRefreshTimer();\n if (provider) {\n provider.destroy();\n provider = null;\n }\n };\n\n const scheduleRefresh = (grant: CollabTokenResponse) => {\n clearRefreshTimer();\n const delay = Math.max(\n grant.expires_at_ms - Date.now() - REFRESH_HEADROOM_MS,\n MIN_REFRESH_DELAY_MS\n );\n refreshTimer = setTimeout(() => {\n void connect({ scheduledRefresh: true });\n }, delay);\n };\n\n const connect = async (opts?: { scheduledRefresh?: boolean }): Promise<void> => {\n if (destroyed) return;\n const scheduledRefresh = opts?.scheduledRefresh === true;\n // A scheduled refresh mints FIRST and keeps the live session up: the old\n // token has ~5 minutes of headroom, so a transient mint failure retries\n // on a short timer instead of dropping a healthy connection.\n if (!scheduledRefresh) {\n teardownProvider();\n } else {\n clearRefreshTimer();\n }\n let grant: CollabTokenResponse;\n try {\n grant = await mintCollabToken({ auth: args.auth, assetId: args.assetId, access });\n } catch (err) {\n if (scheduledRefresh && !destroyed) {\n refreshTimer = setTimeout(() => {\n void connect({ scheduledRefresh: true });\n }, MIN_REFRESH_DELAY_MS);\n return;\n }\n // A denied mint is authoritative (revoked / not shared / not eligible);\n // anything else (network) is worth telling the caller about too — the\n // handle stays usable via a later explicit reconnect-by-recreate.\n setStatus('error', err instanceof Error ? err : new Error(String(err)));\n return;\n }\n if (destroyed) return;\n if (scheduledRefresh) {\n teardownProvider();\n }\n accessType = grant.access_type;\n\n const nextProvider = new WebsocketProvider(grant.ws_url, `${grant.org}/${grant.doc_id}`, doc, {\n params: {\n yauth: grant.token,\n branch: grant.branch,\n gc: 'true',\n },\n });\n provider = nextProvider;\n\n nextProvider.on('status', (event: { status: 'connecting' | 'connected' | 'disconnected' }) => {\n if (provider !== nextProvider) return;\n if (event.status === 'connected') {\n consecutiveRemints = 0;\n }\n setStatus(event.status);\n if (event.status === 'connected' && lastPresence !== null) {\n nextProvider.awareness.setLocalState(lastPresence);\n }\n });\n\n nextProvider.on('connection-close', (event: CloseEvent | null) => {\n if (provider !== nextProvider) return;\n const action = classifyClose(event?.code);\n if (action === 'remint') {\n // Revoked mid-session: a fresh mint re-runs the server-side permission\n // check. If access is truly gone the mint 403s and we land in 'error'.\n // Bounded: repeated 4401s without an intervening successful connect\n // mean the server keeps rejecting freshly minted tokens — stop rather\n // than loop mint→connect→kick.\n consecutiveRemints += 1;\n teardownProvider();\n if (consecutiveRemints > MAX_CONSECUTIVE_REMINTS) {\n setStatus(\n 'closed',\n new Error('Access repeatedly revoked mid-session (4401); giving up.')\n );\n return;\n }\n void connect();\n } else if (action === 'stop') {\n teardownProvider();\n setStatus(\n 'closed',\n new Error(`Connection closed permanently (code ${event?.code ?? 'unknown'})`)\n );\n }\n // 'retry': the provider's exponential backoff handles it.\n });\n\n nextProvider.awareness.on('change', () => {\n if (provider !== nextProvider) return;\n notify();\n });\n\n scheduleRefresh(grant);\n };\n\n void connect();\n\n return {\n doc,\n get status() {\n return status;\n },\n get accessType() {\n return accessType;\n },\n get error() {\n return error;\n },\n get version() {\n return version;\n },\n getPresence: () => {\n if (!provider) return [];\n const entries: PresenceEntry[] = [];\n provider.awareness.getStates().forEach((state, clientId) => {\n entries.push({ clientId, state: state as Record<string, unknown> });\n });\n return entries;\n },\n setPresence: (state) => {\n lastPresence = state;\n provider?.awareness.setLocalState(state);\n },\n refreshNow: () => connect({ scheduledRefresh: true }),\n onChange: (listener) => {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n destroy: () => {\n if (destroyed) return;\n destroyed = true;\n teardownProvider();\n listeners.clear();\n doc.destroy();\n status = 'closed';\n },\n };\n}\n\nexport { CollabTokenError };\nexport type { CollabAuth, CollabTokenResponse };\n","/**\n * React bindings for Generic Doc live collaboration.\n *\n * `useGenericDoc(assetId)` opens (and owns) a `connectGenericDoc` handle,\n * resolving auth from the surrounding `AthenaProvider` (per-viewer bearer when\n * present, API key otherwise) and re-rendering on status/presence changes via\n * `useSyncExternalStore`.\n */\n\nimport { useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';\nimport { useAthenaConfig } from '../provider/AthenaContext';\nimport {\n type GenericDocHandle,\n type GenericDocStatus,\n type PresenceEntry,\n connectGenericDoc,\n} from './client';\nimport type * as Y from '@y/y';\n\nexport interface UseGenericDocResult {\n /** Null until the handle is created (first render effect). */\n doc: Y.Doc | null;\n status: GenericDocStatus;\n accessType: 'r' | 'rw' | null;\n error: Error | null;\n presence: PresenceEntry[];\n setPresence: (state: Record<string, unknown> | null) => void;\n}\n\nexport function useGenericDoc(\n assetId: string,\n options?: { access?: 'view' | 'edit' }\n): UseGenericDocResult {\n const config = useAthenaConfig();\n const access = options?.access ?? 'view';\n const [handle, setHandle] = useState<GenericDocHandle | null>(null);\n const handleRef = useRef<GenericDocHandle | null>(null);\n\n useEffect(() => {\n const next = connectGenericDoc({\n assetId,\n access,\n auth: {\n backendUrl: config.backendUrl,\n apiKey: config.apiKey,\n token: config.token,\n },\n });\n handleRef.current = next;\n setHandle(next);\n return () => {\n handleRef.current = null;\n next.destroy();\n };\n // Recreate when the target or credentials change; the handle re-mints on\n // its own schedule otherwise.\n }, [assetId, access, config.backendUrl, config.apiKey, config.token]);\n\n const subscribe = useMemo(() => {\n return (onStoreChange: () => void) => {\n if (!handle) return () => {};\n return handle.onChange(onStoreChange);\n };\n }, [handle]);\n\n const snapshot = useSyncExternalStore(\n subscribe,\n () => {\n if (!handle) return EMPTY_SNAPSHOT;\n return `${handle.status}|${handle.accessType ?? ''}|${handle.version}`;\n },\n () => EMPTY_SNAPSHOT\n );\n void snapshot;\n\n return {\n doc: handle?.doc ?? null,\n status: handle?.status ?? 'connecting',\n accessType: handle?.accessType ?? null,\n error: handle?.error ?? null,\n presence: handle?.getPresence() ?? [],\n setPresence: (state) => handleRef.current?.setPresence(state),\n };\n}\n\nconst EMPTY_SNAPSHOT = 'init||0';\n","/**\n * `defineDocShape` — a typed lens over a Generic Doc's root types.\n *\n * A shape is documentation + ergonomics, not a migration system: it names the\n * root keys an app expects and gives JSON-level reads (`toJSON`, `subscribe`)\n * that hide CRDT mechanics for the common case. The raw `Y.Doc` (yjs v14 /\n * `@y/y`) stays available on the handle for full delta-level power.\n */\n\nimport type * as Y from '@y/y';\n\nexport type DocShapeKind = 'map' | 'array' | 'text' | 'xml';\n\nexport interface BoundDocShape<S extends Record<string, DocShapeKind>> {\n /** The live root type for a declared key (v14 unified `YType`). */\n get: <K extends keyof S & string>(key: K) => ReturnType<Y.Doc['get']>;\n /** JSON snapshot of every declared root (v14 node shape: attributes + `children`). */\n toJSON: () => Record<keyof S & string, unknown>;\n /**\n * Subscribe to JSON snapshots. Fires once immediately, then after every\n * change to any declared root (batched per transaction flush).\n */\n subscribe: (listener: (json: Record<keyof S & string, unknown>) => void) => () => void;\n}\n\nexport function defineDocShape<S extends Record<string, DocShapeKind>>(shape: S) {\n const keys = Object.keys(shape) as Array<keyof S & string>;\n return {\n shape,\n bind(doc: Y.Doc): BoundDocShape<S> {\n const toJSON = () => {\n const out: Record<string, unknown> = {};\n for (const key of keys) {\n out[key] = doc.get(key).toJSON();\n }\n return out as Record<keyof S & string, unknown>;\n };\n return {\n get: (key) => doc.get(key),\n toJSON,\n subscribe: (listener) => {\n let scheduled = false;\n const emit = () => {\n scheduled = false;\n listener(toJSON());\n };\n const onDeepChange = () => {\n if (scheduled) return;\n scheduled = true;\n queueMicrotask(emit);\n };\n const roots = keys.map((key) => doc.get(key));\n for (const root of roots) {\n root.observeDeep(onDeepChange);\n }\n listener(toJSON());\n return () => {\n for (const root of roots) {\n root.unobserveDeep(onDeepChange);\n }\n };\n },\n };\n },\n };\n}\n"],"names":["Y","WebsocketProvider","useAthenaConfig","useState","useRef","useEffect","useMemo","useSyncExternalStore"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAeO,MAAM,wBAAwB;AAC9B,MAAM,uBAAuB;AAI7B,SAAS,cAAc,MAAuC;AACnE,MAAI,SAAS,OAAW,QAAO;AAC/B,MAAI,SAAS,sBAAuB,QAAO;AAC3C,MAAI,QAAQ,QAAQ,OAAO,KAAM,QAAO;AACxC,SAAO;AACT;ACKO,MAAM,yBAAyB,MAAM;AAAA,EAG1C,YAAY,QAAgB,SAAiB;AAC3C,UAAM,OAAO;AAHN;AAIP,SAAK,OAAO;AACZ,SAAK,SAAS;AAAA,EAChB;AACF;AAEA,SAAS,eAAe,MAA0C;AAChE,MAAI,KAAK,OAAO;AACd,WAAO,E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