@react-grab/utils 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Aiden Bai
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,170 @@
1
+ 'use strict';
2
+
3
+ // src/client.ts
4
+ var CONNECTION_CHECK_TTL_MS = 5e3;
5
+ var STORAGE_KEY = "react-grab:agent-sessions";
6
+ var parseSSEEvent = (eventBlock) => {
7
+ let eventType = "";
8
+ let data = "";
9
+ for (const line of eventBlock.split("\n")) {
10
+ if (line.startsWith("event:")) eventType = line.slice(6).trim();
11
+ else if (line.startsWith("data:")) data = line.slice(5).trim();
12
+ }
13
+ return { eventType, data };
14
+ };
15
+ var streamSSE = async function* (stream, signal) {
16
+ const reader = stream.getReader();
17
+ const decoder = new TextDecoder();
18
+ let buffer = "";
19
+ let aborted = false;
20
+ const onAbort = () => {
21
+ aborted = true;
22
+ reader.cancel().catch(() => {
23
+ });
24
+ };
25
+ signal.addEventListener("abort", onAbort, { once: true });
26
+ try {
27
+ if (signal.aborted) {
28
+ throw new DOMException("Aborted", "AbortError");
29
+ }
30
+ while (true) {
31
+ const result = await reader.read();
32
+ if (aborted || signal.aborted) {
33
+ throw new DOMException("Aborted", "AbortError");
34
+ }
35
+ const { done, value } = result;
36
+ if (value) buffer += decoder.decode(value, { stream: true });
37
+ let boundary;
38
+ while ((boundary = buffer.indexOf("\n\n")) !== -1) {
39
+ const { eventType, data } = parseSSEEvent(buffer.slice(0, boundary));
40
+ buffer = buffer.slice(boundary + 2);
41
+ if (eventType === "done") return;
42
+ if (eventType === "error") throw new Error(data || "Agent error");
43
+ if (data) yield data;
44
+ }
45
+ if (done) break;
46
+ }
47
+ } finally {
48
+ signal.removeEventListener("abort", onAbort);
49
+ try {
50
+ reader.releaseLock();
51
+ } catch {
52
+ }
53
+ }
54
+ };
55
+ var isRecord = (value) => typeof value === "object" && value !== null;
56
+ var getStoredAgentContext = (storage, sessionId, storageKey = STORAGE_KEY) => {
57
+ const rawSessions = storage.getItem(storageKey);
58
+ if (!rawSessions) throw new Error("No sessions to resume");
59
+ let parsed;
60
+ try {
61
+ parsed = JSON.parse(rawSessions);
62
+ } catch {
63
+ throw new Error("Failed to parse stored sessions");
64
+ }
65
+ if (!isRecord(parsed)) throw new Error("Invalid stored sessions");
66
+ const storedSession = parsed[sessionId];
67
+ if (!isRecord(storedSession)) {
68
+ throw new Error(`Session ${sessionId} not found`);
69
+ }
70
+ const context = storedSession.context;
71
+ if (!isRecord(context)) throw new Error(`Session ${sessionId} is invalid`);
72
+ const content = context.content;
73
+ const prompt = context.prompt;
74
+ if (!Array.isArray(content) || typeof prompt !== "string") {
75
+ throw new Error(`Session ${sessionId} is invalid`);
76
+ }
77
+ const options = context.options;
78
+ const storedSessionId = context.sessionId;
79
+ return {
80
+ content,
81
+ prompt,
82
+ options,
83
+ sessionId: typeof storedSessionId === "string" ? storedSessionId : void 0
84
+ };
85
+ };
86
+ var streamAgentStatusFromServer = async function* (options, context, signal) {
87
+ const startTime = Date.now();
88
+ const sessionId = context.sessionId;
89
+ const pollIntervalMs = options.pollIntervalMs ?? 100;
90
+ const agentUrl = `${options.serverUrl}${options.agentPath ?? "/agent"}`;
91
+ const handleAbort = () => {
92
+ if (!sessionId) return;
93
+ const abortPath = options.abortPath?.(sessionId) ?? `/abort/${sessionId}`;
94
+ fetch(`${options.serverUrl}${abortPath}`, { method: "POST" }).catch(
95
+ () => {
96
+ }
97
+ );
98
+ };
99
+ signal.addEventListener("abort", handleAbort, { once: true });
100
+ try {
101
+ const response = await fetch(agentUrl, {
102
+ method: "POST",
103
+ headers: { "Content-Type": "application/json" },
104
+ body: JSON.stringify(context),
105
+ signal
106
+ });
107
+ if (!response.ok) {
108
+ throw new Error(`Server error: ${response.status}`);
109
+ }
110
+ if (!response.body) {
111
+ throw new Error("No response body");
112
+ }
113
+ const iterator = streamSSE(response.body, signal)[Symbol.asyncIterator]();
114
+ let isDone = false;
115
+ let pendingNext = iterator.next();
116
+ let lastStatus = null;
117
+ while (!isDone) {
118
+ const result = await Promise.race([
119
+ pendingNext.then((iteratorResult) => ({
120
+ type: "status",
121
+ iteratorResult
122
+ })),
123
+ new Promise(
124
+ (resolve) => setTimeout(() => resolve({ type: "timeout" }), pollIntervalMs)
125
+ )
126
+ ]);
127
+ const elapsedSeconds = (Date.now() - startTime) / 1e3;
128
+ if (result.type === "status") {
129
+ const iteratorResult = result.iteratorResult;
130
+ isDone = iteratorResult.done ?? false;
131
+ if (!isDone && iteratorResult.value) {
132
+ lastStatus = iteratorResult.value;
133
+ pendingNext = iterator.next();
134
+ }
135
+ }
136
+ if (lastStatus === options.completedStatus) {
137
+ yield `Completed in ${elapsedSeconds.toFixed(1)}s`;
138
+ } else if (lastStatus) {
139
+ yield `${lastStatus} ${elapsedSeconds.toFixed(1)}s`;
140
+ } else {
141
+ yield `Working\u2026 ${elapsedSeconds.toFixed(1)}s`;
142
+ }
143
+ }
144
+ } finally {
145
+ signal.removeEventListener("abort", handleAbort);
146
+ }
147
+ };
148
+ var createCachedConnectionChecker = (checkConnection, ttlMs = CONNECTION_CHECK_TTL_MS) => {
149
+ let cache = null;
150
+ return async () => {
151
+ const now = Date.now();
152
+ if (cache && now - cache.timestamp < ttlMs) return cache.result;
153
+ try {
154
+ const result = await checkConnection();
155
+ cache = { result, timestamp: now };
156
+ return result;
157
+ } catch {
158
+ cache = { result: false, timestamp: now };
159
+ return false;
160
+ }
161
+ };
162
+ };
163
+
164
+ exports.CONNECTION_CHECK_TTL_MS = CONNECTION_CHECK_TTL_MS;
165
+ exports.STORAGE_KEY = STORAGE_KEY;
166
+ exports.createCachedConnectionChecker = createCachedConnectionChecker;
167
+ exports.getStoredAgentContext = getStoredAgentContext;
168
+ exports.parseSSEEvent = parseSSEEvent;
169
+ exports.streamAgentStatusFromServer = streamAgentStatusFromServer;
170
+ exports.streamSSE = streamSSE;
@@ -0,0 +1,30 @@
1
+ declare const CONNECTION_CHECK_TTL_MS = 5000;
2
+ declare const STORAGE_KEY = "react-grab:agent-sessions";
3
+ interface SSEEvent {
4
+ eventType: string;
5
+ data: string;
6
+ }
7
+ declare const parseSSEEvent: (eventBlock: string) => SSEEvent;
8
+ declare const streamSSE: (stream: ReadableStream<Uint8Array>, signal: AbortSignal) => AsyncGenerator<string, void, unknown>;
9
+ interface StoredAgentContext {
10
+ content: string[];
11
+ prompt: string;
12
+ options?: unknown;
13
+ sessionId?: string;
14
+ }
15
+ declare const getStoredAgentContext: (storage: {
16
+ getItem: (key: string) => string | null;
17
+ }, sessionId: string, storageKey?: string) => StoredAgentContext;
18
+ interface StreamAgentStatusFromServerOptions {
19
+ serverUrl: string;
20
+ completedStatus: string;
21
+ agentPath?: string;
22
+ abortPath?: (sessionId: string) => string;
23
+ pollIntervalMs?: number;
24
+ }
25
+ declare const streamAgentStatusFromServer: <TContext extends {
26
+ sessionId?: string;
27
+ }>(options: StreamAgentStatusFromServerOptions, context: TContext, signal: AbortSignal) => AsyncGenerator<string, void, unknown>;
28
+ declare const createCachedConnectionChecker: (checkConnection: () => Promise<boolean>, ttlMs?: number) => (() => Promise<boolean>);
29
+
30
+ export { CONNECTION_CHECK_TTL_MS, type SSEEvent, STORAGE_KEY, type StoredAgentContext, type StreamAgentStatusFromServerOptions, createCachedConnectionChecker, getStoredAgentContext, parseSSEEvent, streamAgentStatusFromServer, streamSSE };
@@ -0,0 +1,30 @@
1
+ declare const CONNECTION_CHECK_TTL_MS = 5000;
2
+ declare const STORAGE_KEY = "react-grab:agent-sessions";
3
+ interface SSEEvent {
4
+ eventType: string;
5
+ data: string;
6
+ }
7
+ declare const parseSSEEvent: (eventBlock: string) => SSEEvent;
8
+ declare const streamSSE: (stream: ReadableStream<Uint8Array>, signal: AbortSignal) => AsyncGenerator<string, void, unknown>;
9
+ interface StoredAgentContext {
10
+ content: string[];
11
+ prompt: string;
12
+ options?: unknown;
13
+ sessionId?: string;
14
+ }
15
+ declare const getStoredAgentContext: (storage: {
16
+ getItem: (key: string) => string | null;
17
+ }, sessionId: string, storageKey?: string) => StoredAgentContext;
18
+ interface StreamAgentStatusFromServerOptions {
19
+ serverUrl: string;
20
+ completedStatus: string;
21
+ agentPath?: string;
22
+ abortPath?: (sessionId: string) => string;
23
+ pollIntervalMs?: number;
24
+ }
25
+ declare const streamAgentStatusFromServer: <TContext extends {
26
+ sessionId?: string;
27
+ }>(options: StreamAgentStatusFromServerOptions, context: TContext, signal: AbortSignal) => AsyncGenerator<string, void, unknown>;
28
+ declare const createCachedConnectionChecker: (checkConnection: () => Promise<boolean>, ttlMs?: number) => (() => Promise<boolean>);
29
+
30
+ export { CONNECTION_CHECK_TTL_MS, type SSEEvent, STORAGE_KEY, type StoredAgentContext, type StreamAgentStatusFromServerOptions, createCachedConnectionChecker, getStoredAgentContext, parseSSEEvent, streamAgentStatusFromServer, streamSSE };
package/dist/client.js ADDED
@@ -0,0 +1,162 @@
1
+ // src/client.ts
2
+ var CONNECTION_CHECK_TTL_MS = 5e3;
3
+ var STORAGE_KEY = "react-grab:agent-sessions";
4
+ var parseSSEEvent = (eventBlock) => {
5
+ let eventType = "";
6
+ let data = "";
7
+ for (const line of eventBlock.split("\n")) {
8
+ if (line.startsWith("event:")) eventType = line.slice(6).trim();
9
+ else if (line.startsWith("data:")) data = line.slice(5).trim();
10
+ }
11
+ return { eventType, data };
12
+ };
13
+ var streamSSE = async function* (stream, signal) {
14
+ const reader = stream.getReader();
15
+ const decoder = new TextDecoder();
16
+ let buffer = "";
17
+ let aborted = false;
18
+ const onAbort = () => {
19
+ aborted = true;
20
+ reader.cancel().catch(() => {
21
+ });
22
+ };
23
+ signal.addEventListener("abort", onAbort, { once: true });
24
+ try {
25
+ if (signal.aborted) {
26
+ throw new DOMException("Aborted", "AbortError");
27
+ }
28
+ while (true) {
29
+ const result = await reader.read();
30
+ if (aborted || signal.aborted) {
31
+ throw new DOMException("Aborted", "AbortError");
32
+ }
33
+ const { done, value } = result;
34
+ if (value) buffer += decoder.decode(value, { stream: true });
35
+ let boundary;
36
+ while ((boundary = buffer.indexOf("\n\n")) !== -1) {
37
+ const { eventType, data } = parseSSEEvent(buffer.slice(0, boundary));
38
+ buffer = buffer.slice(boundary + 2);
39
+ if (eventType === "done") return;
40
+ if (eventType === "error") throw new Error(data || "Agent error");
41
+ if (data) yield data;
42
+ }
43
+ if (done) break;
44
+ }
45
+ } finally {
46
+ signal.removeEventListener("abort", onAbort);
47
+ try {
48
+ reader.releaseLock();
49
+ } catch {
50
+ }
51
+ }
52
+ };
53
+ var isRecord = (value) => typeof value === "object" && value !== null;
54
+ var getStoredAgentContext = (storage, sessionId, storageKey = STORAGE_KEY) => {
55
+ const rawSessions = storage.getItem(storageKey);
56
+ if (!rawSessions) throw new Error("No sessions to resume");
57
+ let parsed;
58
+ try {
59
+ parsed = JSON.parse(rawSessions);
60
+ } catch {
61
+ throw new Error("Failed to parse stored sessions");
62
+ }
63
+ if (!isRecord(parsed)) throw new Error("Invalid stored sessions");
64
+ const storedSession = parsed[sessionId];
65
+ if (!isRecord(storedSession)) {
66
+ throw new Error(`Session ${sessionId} not found`);
67
+ }
68
+ const context = storedSession.context;
69
+ if (!isRecord(context)) throw new Error(`Session ${sessionId} is invalid`);
70
+ const content = context.content;
71
+ const prompt = context.prompt;
72
+ if (!Array.isArray(content) || typeof prompt !== "string") {
73
+ throw new Error(`Session ${sessionId} is invalid`);
74
+ }
75
+ const options = context.options;
76
+ const storedSessionId = context.sessionId;
77
+ return {
78
+ content,
79
+ prompt,
80
+ options,
81
+ sessionId: typeof storedSessionId === "string" ? storedSessionId : void 0
82
+ };
83
+ };
84
+ var streamAgentStatusFromServer = async function* (options, context, signal) {
85
+ const startTime = Date.now();
86
+ const sessionId = context.sessionId;
87
+ const pollIntervalMs = options.pollIntervalMs ?? 100;
88
+ const agentUrl = `${options.serverUrl}${options.agentPath ?? "/agent"}`;
89
+ const handleAbort = () => {
90
+ if (!sessionId) return;
91
+ const abortPath = options.abortPath?.(sessionId) ?? `/abort/${sessionId}`;
92
+ fetch(`${options.serverUrl}${abortPath}`, { method: "POST" }).catch(
93
+ () => {
94
+ }
95
+ );
96
+ };
97
+ signal.addEventListener("abort", handleAbort, { once: true });
98
+ try {
99
+ const response = await fetch(agentUrl, {
100
+ method: "POST",
101
+ headers: { "Content-Type": "application/json" },
102
+ body: JSON.stringify(context),
103
+ signal
104
+ });
105
+ if (!response.ok) {
106
+ throw new Error(`Server error: ${response.status}`);
107
+ }
108
+ if (!response.body) {
109
+ throw new Error("No response body");
110
+ }
111
+ const iterator = streamSSE(response.body, signal)[Symbol.asyncIterator]();
112
+ let isDone = false;
113
+ let pendingNext = iterator.next();
114
+ let lastStatus = null;
115
+ while (!isDone) {
116
+ const result = await Promise.race([
117
+ pendingNext.then((iteratorResult) => ({
118
+ type: "status",
119
+ iteratorResult
120
+ })),
121
+ new Promise(
122
+ (resolve) => setTimeout(() => resolve({ type: "timeout" }), pollIntervalMs)
123
+ )
124
+ ]);
125
+ const elapsedSeconds = (Date.now() - startTime) / 1e3;
126
+ if (result.type === "status") {
127
+ const iteratorResult = result.iteratorResult;
128
+ isDone = iteratorResult.done ?? false;
129
+ if (!isDone && iteratorResult.value) {
130
+ lastStatus = iteratorResult.value;
131
+ pendingNext = iterator.next();
132
+ }
133
+ }
134
+ if (lastStatus === options.completedStatus) {
135
+ yield `Completed in ${elapsedSeconds.toFixed(1)}s`;
136
+ } else if (lastStatus) {
137
+ yield `${lastStatus} ${elapsedSeconds.toFixed(1)}s`;
138
+ } else {
139
+ yield `Working\u2026 ${elapsedSeconds.toFixed(1)}s`;
140
+ }
141
+ }
142
+ } finally {
143
+ signal.removeEventListener("abort", handleAbort);
144
+ }
145
+ };
146
+ var createCachedConnectionChecker = (checkConnection, ttlMs = CONNECTION_CHECK_TTL_MS) => {
147
+ let cache = null;
148
+ return async () => {
149
+ const now = Date.now();
150
+ if (cache && now - cache.timestamp < ttlMs) return cache.result;
151
+ try {
152
+ const result = await checkConnection();
153
+ cache = { result, timestamp: now };
154
+ return result;
155
+ } catch {
156
+ cache = { result: false, timestamp: now };
157
+ return false;
158
+ }
159
+ };
160
+ };
161
+
162
+ export { CONNECTION_CHECK_TTL_MS, STORAGE_KEY, createCachedConnectionChecker, getStoredAgentContext, parseSSEEvent, streamAgentStatusFromServer, streamSSE };
@@ -0,0 +1,35 @@
1
+ 'use strict';
2
+
3
+ // src/server.ts
4
+ var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
5
+ var COMMAND_INSTALL_MAP = {
6
+ "cursor-agent": "Install Cursor (https://cursor.com) and ensure 'cursor-agent' is in your PATH.",
7
+ gemini: "Install the Gemini CLI: npm install -g @anthropic-ai/gemini-cli\nOr see: https://github.com/google-gemini/gemini-cli",
8
+ claude: "Install Claude Code: npm install -g @anthropic-ai/claude-code\nOr see: https://github.com/anthropics/claude-code"
9
+ };
10
+ var formatSpawnError = (error, commandName) => {
11
+ const spawnError = error;
12
+ const isNotFound = spawnError.code === "ENOENT" || spawnError.message && spawnError.message.includes("ENOENT");
13
+ if (isNotFound) {
14
+ const installInfo = COMMAND_INSTALL_MAP[commandName];
15
+ const baseMessage = `Command '${commandName}' not found.`;
16
+ if (installInfo) {
17
+ return `${baseMessage}
18
+
19
+ ${installInfo}`;
20
+ }
21
+ return `${baseMessage}
22
+
23
+ Make sure '${commandName}' is installed and available in your PATH.`;
24
+ }
25
+ const isPermissionDenied = spawnError.code === "EACCES" || spawnError.message && spawnError.message.includes("EACCES");
26
+ if (isPermissionDenied) {
27
+ return `Permission denied when trying to run '${commandName}'.
28
+
29
+ Check that the command is executable: chmod +x $(which ${commandName})`;
30
+ }
31
+ return error.message;
32
+ };
33
+
34
+ exports.formatSpawnError = formatSpawnError;
35
+ exports.sleep = sleep;
@@ -0,0 +1,13 @@
1
+ declare const sleep: (ms: number) => Promise<void>;
2
+ interface AgentMessage {
3
+ type: "status" | "error" | "done";
4
+ content: string;
5
+ }
6
+ interface AgentCoreOptions {
7
+ cwd?: string;
8
+ signal?: AbortSignal;
9
+ sessionId?: string;
10
+ }
11
+ declare const formatSpawnError: (error: Error, commandName: string) => string;
12
+
13
+ export { type AgentCoreOptions, type AgentMessage, formatSpawnError, sleep };
@@ -0,0 +1,13 @@
1
+ declare const sleep: (ms: number) => Promise<void>;
2
+ interface AgentMessage {
3
+ type: "status" | "error" | "done";
4
+ content: string;
5
+ }
6
+ interface AgentCoreOptions {
7
+ cwd?: string;
8
+ signal?: AbortSignal;
9
+ sessionId?: string;
10
+ }
11
+ declare const formatSpawnError: (error: Error, commandName: string) => string;
12
+
13
+ export { type AgentCoreOptions, type AgentMessage, formatSpawnError, sleep };
package/dist/server.js ADDED
@@ -0,0 +1,32 @@
1
+ // src/server.ts
2
+ var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
3
+ var COMMAND_INSTALL_MAP = {
4
+ "cursor-agent": "Install Cursor (https://cursor.com) and ensure 'cursor-agent' is in your PATH.",
5
+ gemini: "Install the Gemini CLI: npm install -g @anthropic-ai/gemini-cli\nOr see: https://github.com/google-gemini/gemini-cli",
6
+ claude: "Install Claude Code: npm install -g @anthropic-ai/claude-code\nOr see: https://github.com/anthropics/claude-code"
7
+ };
8
+ var formatSpawnError = (error, commandName) => {
9
+ const spawnError = error;
10
+ const isNotFound = spawnError.code === "ENOENT" || spawnError.message && spawnError.message.includes("ENOENT");
11
+ if (isNotFound) {
12
+ const installInfo = COMMAND_INSTALL_MAP[commandName];
13
+ const baseMessage = `Command '${commandName}' not found.`;
14
+ if (installInfo) {
15
+ return `${baseMessage}
16
+
17
+ ${installInfo}`;
18
+ }
19
+ return `${baseMessage}
20
+
21
+ Make sure '${commandName}' is installed and available in your PATH.`;
22
+ }
23
+ const isPermissionDenied = spawnError.code === "EACCES" || spawnError.message && spawnError.message.includes("EACCES");
24
+ if (isPermissionDenied) {
25
+ return `Permission denied when trying to run '${commandName}'.
26
+
27
+ Check that the command is executable: chmod +x $(which ${commandName})`;
28
+ }
29
+ return error.message;
30
+ };
31
+
32
+ export { formatSpawnError, sleep };
package/package.json ADDED
@@ -0,0 +1,27 @@
1
+ {
2
+ "name": "@react-grab/utils",
3
+ "version": "0.1.3",
4
+ "files": [
5
+ "dist"
6
+ ],
7
+ "type": "module",
8
+ "exports": {
9
+ "./client": {
10
+ "types": "./dist/client.d.ts",
11
+ "import": "./dist/client.js",
12
+ "require": "./dist/client.cjs"
13
+ },
14
+ "./server": {
15
+ "types": "./dist/server.d.ts",
16
+ "import": "./dist/server.js",
17
+ "require": "./dist/server.cjs"
18
+ }
19
+ },
20
+ "devDependencies": {
21
+ "tsup": "^8.4.0"
22
+ },
23
+ "scripts": {
24
+ "dev": "tsup --watch",
25
+ "build": "rm -rf dist && NODE_ENV=production tsup"
26
+ }
27
+ }