heliumts 0.9.6 → 0.10.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 (81) hide show
  1. package/README.md +39 -14
  2. package/dist/bin/helium.js +19 -10
  3. package/dist/bin/helium.js.map +1 -1
  4. package/dist/client/Router.d.ts.map +1 -1
  5. package/dist/client/Router.js +2 -4
  6. package/dist/client/Router.js.map +1 -1
  7. package/dist/client/callMethod.d.ts +8 -0
  8. package/dist/client/callMethod.d.ts.map +1 -0
  9. package/dist/client/callMethod.js +9 -0
  10. package/dist/client/callMethod.js.map +1 -0
  11. package/dist/client/index.d.ts +3 -2
  12. package/dist/client/index.d.ts.map +1 -1
  13. package/dist/client/index.js +2 -1
  14. package/dist/client/index.js.map +1 -1
  15. package/dist/client/rpcClient.d.ts +7 -37
  16. package/dist/client/rpcClient.d.ts.map +1 -1
  17. package/dist/client/rpcClient.js +118 -749
  18. package/dist/client/rpcClient.js.map +1 -1
  19. package/dist/client/rpcStreaming.d.ts +10 -0
  20. package/dist/client/rpcStreaming.d.ts.map +1 -0
  21. package/dist/client/rpcStreaming.js +125 -0
  22. package/dist/client/rpcStreaming.js.map +1 -0
  23. package/dist/client/useStreaming.d.ts +26 -0
  24. package/dist/client/useStreaming.d.ts.map +1 -0
  25. package/dist/client/useStreaming.js +126 -0
  26. package/dist/client/useStreaming.js.map +1 -0
  27. package/dist/runtime/protocol.d.ts +14 -0
  28. package/dist/runtime/protocol.d.ts.map +1 -1
  29. package/dist/runtime/protocol.js +3 -1
  30. package/dist/runtime/protocol.js.map +1 -1
  31. package/dist/server/config.d.ts +16 -101
  32. package/dist/server/config.d.ts.map +1 -1
  33. package/dist/server/config.js +5 -27
  34. package/dist/server/config.js.map +1 -1
  35. package/dist/server/context.d.ts +8 -6
  36. package/dist/server/context.d.ts.map +1 -1
  37. package/dist/server/context.js.map +1 -1
  38. package/dist/server/defineWorker.d.ts +1 -1
  39. package/dist/server/defineWorker.d.ts.map +1 -1
  40. package/dist/server/defineWorker.js +2 -1
  41. package/dist/server/defineWorker.js.map +1 -1
  42. package/dist/server/devServer.d.ts +1 -1
  43. package/dist/server/devServer.d.ts.map +1 -1
  44. package/dist/server/devServer.js +13 -250
  45. package/dist/server/devServer.js.map +1 -1
  46. package/dist/server/httpCompression.d.ts +8 -0
  47. package/dist/server/httpCompression.d.ts.map +1 -0
  48. package/dist/server/httpCompression.js +58 -0
  49. package/dist/server/httpCompression.js.map +1 -0
  50. package/dist/server/httpRouter.d.ts.map +1 -1
  51. package/dist/server/httpRouter.js +5 -2
  52. package/dist/server/httpRouter.js.map +1 -1
  53. package/dist/server/httpRpc.d.ts +10 -0
  54. package/dist/server/httpRpc.d.ts.map +1 -0
  55. package/dist/server/httpRpc.js +186 -0
  56. package/dist/server/httpRpc.js.map +1 -0
  57. package/dist/server/prodServer.d.ts +3 -1
  58. package/dist/server/prodServer.d.ts.map +1 -1
  59. package/dist/server/prodServer.js +36 -229
  60. package/dist/server/prodServer.js.map +1 -1
  61. package/dist/server/rateLimiter.d.ts +6 -36
  62. package/dist/server/rateLimiter.d.ts.map +1 -1
  63. package/dist/server/rateLimiter.js +18 -125
  64. package/dist/server/rateLimiter.js.map +1 -1
  65. package/dist/server/requestSignal.d.ts +10 -0
  66. package/dist/server/requestSignal.d.ts.map +1 -0
  67. package/dist/server/requestSignal.js +79 -0
  68. package/dist/server/requestSignal.js.map +1 -0
  69. package/dist/server/rpcRegistry.d.ts +10 -18
  70. package/dist/server/rpcRegistry.d.ts.map +1 -1
  71. package/dist/server/rpcRegistry.js +181 -269
  72. package/dist/server/rpcRegistry.js.map +1 -1
  73. package/dist/server/serializer.js +12 -6
  74. package/dist/server/serializer.js.map +1 -1
  75. package/dist/vite/heliumPlugin.d.ts.map +1 -1
  76. package/dist/vite/heliumPlugin.js +77 -43
  77. package/dist/vite/heliumPlugin.js.map +1 -1
  78. package/dist/vite/ssg.d.ts.map +1 -1
  79. package/dist/vite/ssg.js +20 -1
  80. package/dist/vite/ssg.js.map +1 -1
  81. package/package.json +2 -4
@@ -1,789 +1,158 @@
1
1
  import { decode as msgpackDecode, encode as msgpackEncode } from "@msgpack/msgpack";
2
2
  import { RpcError } from "./RpcError.js";
3
- function toArrayBuffer(data) {
4
- if (data.buffer instanceof ArrayBuffer && data.byteOffset === 0 && data.byteLength === data.buffer.byteLength) {
5
- return data.buffer;
6
- }
7
- const buffer = new ArrayBuffer(data.byteLength);
8
- new Uint8Array(buffer).set(data);
9
- return buffer;
10
- }
11
- // Read build-time config with fallback defaults
12
- const configuredTransport = typeof __HELIUM_RPC_TRANSPORT__ !== "undefined" ? __HELIUM_RPC_TRANSPORT__ : "websocket";
13
- const configuredAutoHttpOnMobile = typeof __HELIUM_RPC_AUTO_HTTP_ON_MOBILE__ !== "undefined" ? __HELIUM_RPC_AUTO_HTTP_ON_MOBILE__ : false;
14
- const configuredTokenValidityMs = typeof __HELIUM_RPC_TOKEN_VALIDITY_MS__ !== "undefined" && Number.isFinite(__HELIUM_RPC_TOKEN_VALIDITY_MS__) && __HELIUM_RPC_TOKEN_VALIDITY_MS__ > 0
3
+ const tokenValidityMs = typeof __HELIUM_RPC_TOKEN_VALIDITY_MS__ !== "undefined" && Number.isFinite(__HELIUM_RPC_TOKEN_VALIDITY_MS__) && __HELIUM_RPC_TOKEN_VALIDITY_MS__ > 0
15
4
  ? __HELIUM_RPC_TOKEN_VALIDITY_MS__
16
5
  : 30000;
17
- const configuredMaxBatchSize = typeof __HELIUM_RPC_MAX_BATCH_SIZE__ !== "undefined" && Number.isInteger(__HELIUM_RPC_MAX_BATCH_SIZE__) && __HELIUM_RPC_MAX_BATCH_SIZE__ > 0
6
+ const maxBatchSize = typeof __HELIUM_RPC_MAX_BATCH_SIZE__ !== "undefined" && Number.isInteger(__HELIUM_RPC_MAX_BATCH_SIZE__) && __HELIUM_RPC_MAX_BATCH_SIZE__ > 0
18
7
  ? __HELIUM_RPC_MAX_BATCH_SIZE__
19
8
  : 20;
20
- /**
21
- * Get the configured RPC transport mode (from helium.config.js).
22
- */
23
- export function getRpcTransport() {
24
- return configuredTransport;
25
- }
26
- /**
27
- * Check if auto HTTP on mobile is enabled (from helium.config.js).
28
- */
29
- export function isAutoHttpOnMobileEnabled() {
30
- return configuredAutoHttpOnMobile;
31
- }
32
- function isMobileDevice() {
33
- if (typeof navigator === "undefined") {
34
- return false;
35
- }
36
- const MOBILE_BREAKPOINT_MAX_WIDTH = 1024; // 1024px or less is a common breakpoint for mobile devices
37
- const nav = navigator;
38
- if (nav.userAgentData?.mobile === true) {
39
- return true;
40
- }
41
- const userAgent = navigator.userAgent || "";
42
- if (/Android|iPhone|iPad|iPod|IEMobile|Opera Mini|Mobi/i.test(userAgent)) {
43
- return true;
44
- }
45
- if (typeof window !== "undefined" && typeof window.matchMedia === "function") {
46
- if (window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT_MAX_WIDTH}px)`).matches) {
47
- return true;
48
- }
49
- if (window.matchMedia("(pointer: coarse)").matches || window.matchMedia("(any-pointer: coarse)").matches) {
50
- return true;
51
- }
52
- }
53
- return navigator.platform === "MacIntel" && navigator.maxTouchPoints > 1;
54
- }
55
- export function isMobileRpcDevice() {
56
- return isMobileDevice();
57
- }
58
- // Detect if we should prefer HTTP transport (mobile/slow networks)
59
- function shouldUseHttpTransport() {
60
- if (isTemporaryHttpFallbackActive()) {
61
- return true;
62
- }
63
- if (configuredTransport === "http") {
64
- return true;
65
- }
66
- const mobileDevice = isMobileDevice();
67
- if (mobileDevice && configuredAutoHttpOnMobile) {
68
- return true;
69
- }
70
- if (configuredTransport === "websocket") {
71
- return false;
72
- }
73
- // Auto mode: check if mobile HTTP optimization is enabled
74
- if (!configuredAutoHttpOnMobile) {
75
- return false;
76
- }
77
- // For non-mobile devices, prefer HTTP on slow/cellular connections
78
- if (typeof navigator !== "undefined") {
79
- const conn = navigator.connection;
80
- if (conn) {
81
- // Use HTTP for cellular connections or slow effective types
82
- const slowTypes = ["slow-2g", "2g", "3g"];
83
- if (conn.type === "cellular" || (conn.effectiveType && slowTypes.includes(conn.effectiveType))) {
84
- return true;
85
- }
86
- }
87
- }
88
- return false;
9
+ const REQUEST_TIMEOUT_MS = 30000;
10
+ let cachedToken;
11
+ let tokenExpiresAt = 0;
12
+ let tokenRequest = null;
13
+ let requestId = 0;
14
+ export function createRpcRequest(method, args) {
15
+ return { id: requestId++, method, args };
89
16
  }
90
- let pendingBatch = [];
91
- let isBatchScheduled = false;
92
- function scheduleBatch() {
93
- if (isBatchScheduled) {
94
- return;
17
+ function waitWithSignal(promise, signal) {
18
+ if (signal.aborted) {
19
+ return Promise.reject(signal.reason);
95
20
  }
96
- isBatchScheduled = true;
97
- queueMicrotask(() => {
98
- isBatchScheduled = false;
99
- flushBatch();
21
+ return new Promise((resolve, reject) => {
22
+ const onAbort = () => reject(signal.reason);
23
+ signal.addEventListener("abort", onAbort, { once: true });
24
+ promise.then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort));
100
25
  });
101
26
  }
102
- function flushBatch() {
103
- const batch = pendingBatch;
104
- pendingBatch = [];
105
- // Keep each HTTP envelope within the same cap enforced by the server.
106
- // Groups run concurrently and a transport failure rejects only its own calls.
107
- for (let offset = 0; offset < batch.length; offset += configuredMaxBatchSize) {
108
- const group = batch.slice(offset, offset + configuredMaxBatchSize);
109
- void sendBatchHttp(group).catch((error) => {
110
- for (const item of group) {
111
- item.reject(error);
112
- }
113
- });
27
+ async function getToken(signal, rejectedToken) {
28
+ if (cachedToken === rejectedToken) {
29
+ cachedToken = undefined;
114
30
  }
115
- }
116
- async function sendBatchHttp(batch) {
117
- const controller = new AbortController();
118
- const timeout = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
119
- try {
120
- const requests = batch.map((b) => b.req);
121
- const encoded = msgpackEncode(requests);
122
- const sendWithToken = async (token) => {
123
- const headers = {
124
- "Content-Type": "application/msgpack",
125
- Accept: "application/msgpack",
126
- };
127
- if (token) {
128
- headers["X-Helium-Token"] = token;
129
- }
130
- return fetch("/__helium__/rpc", {
31
+ if (cachedToken && Date.now() < tokenExpiresAt) {
32
+ return cachedToken;
33
+ }
34
+ if (!tokenRequest) {
35
+ const controller = new AbortController();
36
+ const timeout = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
37
+ tokenRequest = (async () => {
38
+ const response = await fetch("/__helium__/refresh-token", {
131
39
  method: "POST",
132
- headers,
133
- body: encoded,
40
+ headers: { "X-Requested-With": "HeliumRPC" },
41
+ credentials: "same-origin",
42
+ cache: "no-store",
134
43
  signal: controller.signal,
135
44
  });
136
- };
137
- let response = await sendWithToken(await fetchFreshToken(false, controller.signal));
138
- if (response.status === 401) {
139
- const refreshedToken = await fetchFreshToken(true, controller.signal);
140
- if (refreshedToken) {
141
- response = await sendWithToken(refreshedToken);
142
- }
143
- }
144
- handleBlockedResponse(response.status, "rpc-http");
145
- if (!response.ok) {
146
- throw new Error(`HTTP RPC failed: ${response.status}`);
147
- }
148
- const responseBuffer = await response.arrayBuffer();
149
- const msg = msgpackDecode(new Uint8Array(responseBuffer));
150
- const responses = Array.isArray(msg) ? msg : [msg];
151
- const responseMap = new Map(responses.map((r) => [r.id, r]));
152
- for (const item of batch) {
153
- const res = responseMap.get(item.req.id);
154
- if (res) {
155
- if (res.ok) {
156
- item.resolve({ data: res.result, stats: res.stats });
157
- }
158
- else {
159
- item.reject(new RpcError(res.error, res.stats));
160
- }
161
- }
162
- else {
163
- item.reject(new RpcError("No response for request"));
164
- }
165
- }
166
- }
167
- catch (error) {
168
- if (controller.signal.aborted) {
169
- throw new RpcError("Request timed out");
170
- }
171
- throw error;
172
- }
173
- finally {
174
- clearTimeout(timeout);
175
- }
176
- }
177
- // ============================================================================
178
- // WebSocket Transport (original implementation)
179
- // ============================================================================
180
- let socket = null;
181
- let connectionPromise = null;
182
- const pending = new Map();
183
- const pendingTimeouts = new Map();
184
- const BLOCKED_HTTP_STATUSES = new Set([401, 403, 429]);
185
- const BLOCKED_WS_CLOSE_CODES = new Set([1008, 1011, 1013]);
186
- const BLOCKED_RETRY_THRESHOLD = 3;
187
- const BLOCKED_RETRY_WINDOW_MS = 1000;
188
- const BLOCKED_RELOAD_COOLDOWN_MS = 120000;
189
- const BLOCKED_RELOAD_KEY = "helium:blocked-reload-ts";
190
- const blockedAttempts = new Map();
191
- let lastBlockedReloadAt = 0;
192
- function shouldAutoReloadOnBlock(now) {
193
- if (typeof window === "undefined") {
194
- return false;
195
- }
196
- try {
197
- const stored = window.sessionStorage.getItem(BLOCKED_RELOAD_KEY);
198
- const storedTs = stored ? Number(stored) : 0;
199
- if (storedTs && now - storedTs < BLOCKED_RELOAD_COOLDOWN_MS) {
200
- return false;
201
- }
202
- window.sessionStorage.setItem(BLOCKED_RELOAD_KEY, String(now));
203
- return true;
204
- }
205
- catch {
206
- if (now - lastBlockedReloadAt < BLOCKED_RELOAD_COOLDOWN_MS) {
207
- return false;
208
- }
209
- lastBlockedReloadAt = now;
210
- return true;
211
- }
212
- }
213
- function shouldTriggerBlockedAction(source, now) {
214
- const state = blockedAttempts.get(source);
215
- if (!state || now - state.lastTs > BLOCKED_RETRY_WINDOW_MS) {
216
- blockedAttempts.set(source, { count: 1, lastTs: now });
217
- return false;
218
- }
219
- const nextCount = state.count + 1;
220
- blockedAttempts.set(source, { count: nextCount, lastTs: now });
221
- return nextCount > BLOCKED_RETRY_THRESHOLD;
222
- }
223
- function dispatchBlockedEvent(detail) {
224
- if (typeof window === "undefined") {
225
- return;
226
- }
227
- window.dispatchEvent(new CustomEvent("helium:blocked", {
228
- detail,
229
- }));
230
- }
231
- function handleBlockedResponse(status, source) {
232
- if (!BLOCKED_HTTP_STATUSES.has(status)) {
233
- return;
234
- }
235
- const now = Date.now();
236
- if (!shouldTriggerBlockedAction(source, now)) {
237
- return;
238
- }
239
- dispatchBlockedEvent({ status, source });
240
- if (shouldAutoReloadOnBlock(now) && typeof window.location?.reload === "function") {
241
- window.location.reload();
242
- }
243
- }
244
- function handleBlockedSocketClose(code) {
245
- if (!BLOCKED_WS_CLOSE_CODES.has(code)) {
246
- return;
247
- }
248
- const now = Date.now();
249
- if (!shouldTriggerBlockedAction("rpc-websocket", now)) {
250
- return;
251
- }
252
- dispatchBlockedEvent({ code, source: "rpc-websocket" });
253
- if (shouldAutoReloadOnBlock(now) && typeof window.location?.reload === "function") {
254
- window.location.reload();
255
- }
256
- }
257
- // ── Connection resilience constants ──────────────────────────────────────────
258
- /** How long (ms) the page must be hidden before we consider the WebSocket stale. */
259
- const STALE_THRESHOLD_MS = 15000;
260
- /** Max time (ms) to wait for a WebSocket connection to open. */
261
- const SOCKET_CONNECT_TIMEOUT_MS = 10000;
262
- /** Duration (ms) to temporarily force HTTP after repeated WebSocket failures. */
263
- const WS_FAILURE_HTTP_COOLDOWN_MS = 60000;
264
- /** Max time (ms) to wait for a response before timing out a request. */
265
- const REQUEST_TIMEOUT_MS = 30000;
266
- /** Number of automatic retries on retriable connection errors. */
267
- const MAX_RETRIES = 3;
268
- /** Base delay (ms) for exponential backoff between retries (doubles each attempt). */
269
- const RETRY_BASE_DELAY_MS = 500;
270
- /** Maximum delay (ms) cap for backoff to avoid excessively long waits. */
271
- const RETRY_MAX_DELAY_MS = 5000;
272
- /** Timestamp when the page was last hidden (for visibility-change detection). */
273
- let lastHiddenTimestamp = null;
274
- let forceHttpUntilTimestamp = 0;
275
- function isTemporaryHttpFallbackActive(now = Date.now()) {
276
- return now < forceHttpUntilTimestamp;
277
- }
278
- function activateTemporaryHttpFallback(now = Date.now()) {
279
- forceHttpUntilTimestamp = now + WS_FAILURE_HTTP_COOLDOWN_MS;
280
- }
281
- // ── Pending-request helpers ──────────────────────────────────────────────────
282
- /**
283
- * Register a pending request with an automatic timeout safeguard.
284
- * If no response arrives within REQUEST_TIMEOUT_MS the promise is rejected
285
- * so the caller's retry logic can kick in.
286
- */
287
- function trackPending(id, resolve, reject) {
288
- pending.set(id, { resolve, reject });
289
- const timer = setTimeout(() => {
290
- const entry = pending.get(id);
291
- if (entry) {
292
- pending.delete(id);
293
- pendingTimeouts.delete(id);
294
- entry.reject(new RpcError("Request timed out"));
295
- }
296
- }, REQUEST_TIMEOUT_MS);
297
- pendingTimeouts.set(id, timer);
298
- }
299
- /**
300
- * Remove a pending request and clear its timeout.
301
- * Returns the entry so the caller can resolve/reject it.
302
- */
303
- function removePending(id) {
304
- const entry = pending.get(id);
305
- if (!entry) {
306
- return undefined;
307
- }
308
- pending.delete(id);
309
- const timer = pendingTimeouts.get(id);
310
- if (timer) {
311
- clearTimeout(timer);
312
- pendingTimeouts.delete(id);
313
- }
314
- return entry;
315
- }
316
- /** Reject every in-flight request (e.g. when the socket closes unexpectedly). */
317
- function rejectAllPending(reason) {
318
- for (const timer of pendingTimeouts.values()) {
319
- clearTimeout(timer);
320
- }
321
- pendingTimeouts.clear();
322
- const entries = [...pending.entries()];
323
- pending.clear();
324
- for (const [, entry] of entries) {
325
- entry.reject(reason);
326
- }
327
- }
328
- // ── Reconnection helpers ─────────────────────────────────────────────────────
329
- /**
330
- * Force-close the current WebSocket so the next call creates a fresh
331
- * connection (which fetches a brand-new token).
332
- */
333
- function forceReconnect() {
334
- const oldSocket = socket;
335
- socket = null;
336
- connectionPromise = null;
337
- if (oldSocket) {
338
- // Detach handlers to avoid double-rejecting pending from the close event
339
- oldSocket.onclose = null;
340
- oldSocket.onerror = null;
341
- oldSocket.onmessage = null;
342
- oldSocket.close();
343
- }
344
- // Reject all in-flight requests – callers with retry logic will resend
345
- rejectAllPending(new Error("Connection reset"));
346
- }
347
- function reconnectIfLikelyStale(force = false) {
348
- if (!socket) {
349
- lastHiddenTimestamp = null;
350
- return;
351
- }
352
- if (force) {
353
- forceReconnect();
354
- lastHiddenTimestamp = null;
355
- return;
356
- }
357
- if (lastHiddenTimestamp !== null) {
358
- const hiddenDuration = Date.now() - lastHiddenTimestamp;
359
- if (hiddenDuration > STALE_THRESHOLD_MS) {
360
- forceReconnect();
361
- }
362
- }
363
- lastHiddenTimestamp = null;
364
- }
365
- /** Determine whether an error warrants an automatic retry. */
366
- function isRetriableError(err) {
367
- // Network / connection errors are always retriable
368
- if (err instanceof Error && !(err instanceof RpcError)) {
369
- return true;
370
- }
371
- // Timed-out requests are retriable (socket may have died silently)
372
- if (err instanceof RpcError && err.message === "Request timed out") {
373
- return true;
374
- }
375
- return false;
376
- }
377
- // Clean up WebSocket connection on HMR (Hot Module Replacement)
378
- if (import.meta.hot) {
379
- import.meta.hot.dispose(() => {
380
- if (socket) {
381
- socket.onclose = null;
382
- socket.close();
383
- socket = null;
384
- connectionPromise = null;
385
- }
386
- clearTokenRefreshTimer();
387
- rejectAllPending(new Error("Module reloaded"));
388
- });
389
- }
390
- let msgId = 0;
391
- function nextId() {
392
- return msgId++;
393
- }
394
- let cachedAuthToken;
395
- let tokenRefreshTimer = null;
396
- const TOKEN_REFRESH_MIN_DELAY_MS = 5000;
397
- const TOKEN_REFRESH_RETRY_DELAY_MS = 5000;
398
- const TOKEN_REFRESH_SAFETY_WINDOW_MS = Math.min(5000, Math.max(1000, Math.floor(configuredTokenValidityMs * 0.2)));
399
- function clearTokenRefreshTimer() {
400
- if (!tokenRefreshTimer) {
401
- return;
402
- }
403
- clearTimeout(tokenRefreshTimer);
404
- tokenRefreshTimer = null;
405
- }
406
- function parseTokenIssuedAt(token) {
407
- const [timestampPart] = token.split(".");
408
- if (!timestampPart) {
409
- return null;
410
- }
411
- const issuedAt = Number.parseInt(timestampPart, 10);
412
- if (!Number.isFinite(issuedAt) || issuedAt <= 0) {
413
- return null;
414
- }
415
- return issuedAt;
416
- }
417
- function scheduleTokenRefreshFromToken(token) {
418
- if (typeof window === "undefined") {
419
- return;
420
- }
421
- const issuedAt = parseTokenIssuedAt(token);
422
- if (!issuedAt) {
423
- clearTokenRefreshTimer();
424
- return;
425
- }
426
- const expiresAt = issuedAt + configuredTokenValidityMs;
427
- const refreshAt = expiresAt - TOKEN_REFRESH_SAFETY_WINDOW_MS;
428
- const delay = Math.max(TOKEN_REFRESH_MIN_DELAY_MS, refreshAt - Date.now());
429
- clearTokenRefreshTimer();
430
- tokenRefreshTimer = setTimeout(() => {
431
- void fetchFreshToken(true).then((nextToken) => {
432
- if (!nextToken) {
433
- clearTokenRefreshTimer();
434
- tokenRefreshTimer = setTimeout(() => {
435
- void fetchFreshToken(true);
436
- }, TOKEN_REFRESH_RETRY_DELAY_MS);
437
- }
45
+ if (!response.ok) {
46
+ throw new RpcError(`RPC authorization failed (${response.status})`);
47
+ }
48
+ const result = (await response.json());
49
+ if (typeof result.token !== "string" || !result.token) {
50
+ throw new RpcError("Invalid RPC authorization response");
51
+ }
52
+ const issuedAt = Number.parseInt(result.token.split(".")[0], 10);
53
+ const safetyWindow = Math.min(5000, tokenValidityMs * 0.2);
54
+ cachedToken = result.token;
55
+ tokenExpiresAt = (Number.isFinite(issuedAt) && issuedAt > 0 ? issuedAt : Date.now()) + tokenValidityMs - safetyWindow;
56
+ return cachedToken;
57
+ })()
58
+ .catch((error) => {
59
+ if (controller.signal.aborted) {
60
+ throw new RpcError("RPC authorization timed out");
61
+ }
62
+ throw error;
63
+ })
64
+ .finally(() => {
65
+ clearTimeout(timeout);
66
+ tokenRequest = null;
438
67
  });
439
- }, delay);
440
- }
441
- function hasCachedToken() {
442
- return Boolean(cachedAuthToken);
443
- }
444
- function setCachedToken(token) {
445
- if (!token) {
446
- cachedAuthToken = undefined;
447
- clearTokenRefreshTimer();
448
- return;
449
68
  }
450
- cachedAuthToken = token;
451
- scheduleTokenRefreshFromToken(token);
69
+ // A cancelled caller must not cancel another caller's shared token request.
70
+ return waitWithSignal(tokenRequest, signal);
452
71
  }
453
- async function fetchFreshToken(forceRefresh = false, signal) {
454
- if (!forceRefresh && hasCachedToken()) {
455
- return cachedAuthToken;
456
- }
457
- const controller = signal ? undefined : new AbortController();
458
- const timeout = controller ? setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS) : undefined;
459
- try {
460
- const response = await fetch("/__helium__/refresh-token", {
72
+ /** Shared HTTP request authentication for unary and streaming calls. */
73
+ export async function postRpc(endpoint, request, signal) {
74
+ const body = msgpackEncode(request);
75
+ const send = (token) => {
76
+ signal.throwIfAborted();
77
+ return fetch(endpoint, {
461
78
  method: "POST",
462
- headers: {
463
- "X-Requested-With": "HeliumRPC",
464
- },
465
- signal: signal ?? controller?.signal,
79
+ headers: { "Content-Type": "application/msgpack", "X-Helium-Token": token },
80
+ credentials: "same-origin",
81
+ cache: "no-store",
82
+ body,
83
+ signal,
466
84
  });
467
- handleBlockedResponse(response.status, "refresh-token");
468
- if (!response.ok) {
469
- console.warn("Failed to fetch fresh token:", response.status);
470
- setCachedToken(undefined);
471
- return undefined;
472
- }
473
- const data = await response.json();
474
- const token = data.token;
475
- setCachedToken(token);
476
- return token;
85
+ };
86
+ const token = await getToken(signal);
87
+ let response = await send(token);
88
+ if (response.status === 401) {
89
+ void response.body?.cancel().catch(() => { });
90
+ response = await send(await getToken(signal, token));
477
91
  }
478
- catch (error) {
479
- console.warn("Error fetching fresh token:", error);
480
- setCachedToken(undefined);
481
- return undefined;
92
+ if (!response.ok) {
93
+ void response.body?.cancel().catch(() => { });
94
+ throw new RpcError(`RPC request failed (${response.status})`);
482
95
  }
483
- finally {
484
- if (timeout !== undefined) {
485
- clearTimeout(timeout);
486
- }
96
+ return response;
97
+ }
98
+ export function isRpcStats(value) {
99
+ if (!value || typeof value !== "object") {
100
+ return false;
487
101
  }
102
+ const stats = value;
103
+ return typeof stats.remainingRequests === "number" && stats.remainingRequests >= 0 && typeof stats.resetInSeconds === "number" && stats.resetInSeconds >= 0;
488
104
  }
489
- async function createSocket() {
490
- // Fetch a token before creating the WebSocket connection
491
- const token = await fetchFreshToken();
492
- // Use the same protocol, hostname and port as the current page
493
- const protocol = window.location.protocol === "https:" ? "wss:" : "ws:";
494
- const host = window.location.host; // includes hostname and port
495
- const url = `${protocol}//${host}/rpc`;
496
- // Security: pass token via Sec-WebSocket-Protocol header instead of query string
497
- const ws = token ? new WebSocket(url, [token]) : new WebSocket(url);
498
- ws.binaryType = "arraybuffer";
499
- ws.onmessage = async (event) => {
500
- let data = new Uint8Array(event.data);
501
- // Check for Gzip header (0x1f 0x8b) to detect compressed messages
502
- if (data.length > 2 && data[0] === 0x1f && data[1] === 0x8b) {
503
- try {
504
- // Use DecompressionStream if available (Chrome 80+, Firefox 113+, Safari 16.4+)
505
- if (typeof DecompressionStream !== "undefined") {
506
- const ds = new DecompressionStream("gzip");
507
- const stream = new Response(data).body;
508
- if (stream) {
509
- const decompressed = stream.pipeThrough(ds);
510
- const reader = decompressed.getReader();
511
- const chunks = [];
512
- let totalSize = 0;
513
- const MAX_DECOMPRESSED_SIZE = 10 * 1024 * 1024; // 10 MB
514
- while (true) {
515
- const { value, done } = await reader.read();
516
- if (done) {
517
- break;
518
- }
519
- totalSize += value.length;
520
- if (totalSize > MAX_DECOMPRESSED_SIZE) {
521
- reader.cancel();
522
- console.error("Decompressed message exceeds size limit");
523
- return;
524
- }
525
- chunks.push(value);
526
- }
527
- const combined = new Uint8Array(totalSize);
528
- let offset = 0;
529
- for (const chunk of chunks) {
530
- combined.set(chunk, offset);
531
- offset += chunk.length;
532
- }
533
- data = combined;
534
- }
535
- }
536
- }
537
- catch (err) {
538
- console.error("Failed to decompress WebSocket message:", err);
539
- return;
105
+ let pending = [];
106
+ let scheduled = false;
107
+ async function sendBatch(batch) {
108
+ const controller = new AbortController();
109
+ const timeout = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
110
+ try {
111
+ const response = await postRpc("/__helium__/rpc", batch.map((item) => item.request), controller.signal);
112
+ const decoded = msgpackDecode(new Uint8Array(await response.arrayBuffer()));
113
+ const responses = Array.isArray(decoded) ? decoded : [decoded];
114
+ const byId = new Map();
115
+ for (const value of responses) {
116
+ if (value && typeof value === "object" && (typeof value.id === "string" || typeof value.id === "number") && typeof value.ok === "boolean" && isRpcStats(value.stats)) {
117
+ byId.set(value.id, value);
540
118
  }
541
119
  }
542
- // Always expect binary MessagePack
543
- const msg = msgpackDecode(data);
544
- const handleResponse = (res) => {
545
- const entry = removePending(res.id);
546
- if (!entry) {
547
- return;
120
+ for (const item of batch) {
121
+ const result = byId.get(item.request.id);
122
+ if (!result) {
123
+ item.reject(new RpcError("Invalid or missing RPC response"));
548
124
  }
549
- if (res.ok) {
550
- entry.resolve({ data: res.result, stats: res.stats });
125
+ else if (result.ok) {
126
+ item.resolve({ data: result.result, stats: result.stats });
551
127
  }
552
128
  else {
553
- entry.reject(new RpcError(res.error, res.stats));
129
+ item.reject(new RpcError(typeof result.error === "string" ? result.error : "Invalid RPC error response", result.stats));
554
130
  }
555
- };
556
- if (Array.isArray(msg)) {
557
- msg.forEach(handleResponse);
558
- }
559
- else {
560
- handleResponse(msg);
561
- }
562
- };
563
- ws.onerror = () => {
564
- // WebSocket errors are always followed by a close event.
565
- // The close handler takes care of rejecting pending promises.
566
- };
567
- ws.onclose = (event) => {
568
- handleBlockedSocketClose(event.code);
569
- if (socket === ws) {
570
- socket = null;
571
- connectionPromise = null;
572
- // Reject every in-flight request so callers can retry
573
- rejectAllPending(new Error("WebSocket connection closed"));
574
131
  }
575
- };
576
- return ws;
577
- }
578
- function waitForSocketOpen(ws) {
579
- if (ws.readyState === WebSocket.OPEN) {
580
- return Promise.resolve(ws);
581
- }
582
- return new Promise((resolve, reject) => {
583
- const cleanup = () => {
584
- ws.removeEventListener("open", handleOpen);
585
- ws.removeEventListener("error", handleError);
586
- ws.removeEventListener("close", handleClose);
587
- clearTimeout(timeout);
588
- };
589
- const handleOpen = () => {
590
- cleanup();
591
- resolve(ws);
592
- };
593
- const handleError = () => {
594
- cleanup();
595
- if (socket === ws) {
596
- socket = null;
597
- }
598
- setCachedToken(undefined);
599
- reject(new Error("WebSocket connection failed"));
600
- };
601
- const handleClose = () => {
602
- cleanup();
603
- if (socket === ws) {
604
- socket = null;
605
- }
606
- setCachedToken(undefined);
607
- reject(new Error("WebSocket closed before opening"));
608
- };
609
- const timeout = setTimeout(() => {
610
- cleanup();
611
- if (socket === ws) {
612
- socket = null;
613
- }
614
- setCachedToken(undefined);
615
- reject(new Error("WebSocket connection timed out"));
616
- }, SOCKET_CONNECT_TIMEOUT_MS);
617
- ws.addEventListener("open", handleOpen);
618
- ws.addEventListener("error", handleError);
619
- ws.addEventListener("close", handleClose);
620
- });
621
- }
622
- async function ensureSocketReady() {
623
- // If we have an open socket, return it immediately
624
- if (socket && socket.readyState === WebSocket.OPEN) {
625
- return socket;
626
- }
627
- // If we have a connection in progress, reuse that promise
628
- if (connectionPromise) {
629
- return connectionPromise;
630
132
  }
631
- const pendingConnectPromise = (async () => {
632
- if (!socket || socket.readyState === WebSocket.CLOSED || socket.readyState === WebSocket.CLOSING) {
633
- socket = await createSocket();
634
- }
635
- return waitForSocketOpen(socket);
636
- })();
637
- connectionPromise = pendingConnectPromise;
638
- try {
639
- return await pendingConnectPromise;
133
+ catch (error) {
134
+ const failure = controller.signal.aborted ? new RpcError("Request timed out") : error;
135
+ batch.forEach((item) => item.reject(failure));
640
136
  }
641
137
  finally {
642
- if (connectionPromise === pendingConnectPromise) {
643
- connectionPromise = null;
644
- }
138
+ clearTimeout(timeout);
645
139
  }
646
140
  }
647
- async function rpcCallWebSocket(methodId, args) {
648
- // Optimization: If socket is open, send immediately without awaiting ensureSocketReady (which adds a microtask tick)
649
- if (socket && socket.readyState === WebSocket.OPEN) {
650
- const id = nextId();
651
- const req = { id, method: methodId, args };
652
- return new Promise((resolve, reject) => {
653
- trackPending(id, (v) => resolve(v), reject);
654
- try {
655
- const encoded = msgpackEncode(req);
656
- socket.send(toArrayBuffer(encoded));
657
- }
658
- catch (err) {
659
- removePending(id);
660
- reject(err);
141
+ /** Call an RPC method over HTTP; simultaneous calls share capped batch envelopes. */
142
+ export function rpcCall(method, args) {
143
+ const result = new Promise((resolve, reject) => pending.push({ request: createRpcRequest(method, args), resolve, reject }));
144
+ if (!scheduled) {
145
+ scheduled = true;
146
+ queueMicrotask(() => {
147
+ scheduled = false;
148
+ const batch = pending;
149
+ pending = [];
150
+ for (let offset = 0; offset < batch.length; offset += maxBatchSize) {
151
+ void sendBatch(batch.slice(offset, offset + maxBatchSize));
661
152
  }
662
153
  });
663
154
  }
664
- const ws = await ensureSocketReady();
665
- const id = nextId();
666
- const req = { id, method: methodId, args };
667
- return new Promise((resolve, reject) => {
668
- trackPending(id, (v) => resolve(v), reject);
669
- try {
670
- // Always use msgpack encoding
671
- const encoded = msgpackEncode(req);
672
- ws.send(toArrayBuffer(encoded));
673
- }
674
- catch (err) {
675
- removePending(id);
676
- reject(err);
677
- }
678
- });
679
- }
680
- /**
681
- * Make an RPC call using the appropriate transport.
682
- * Automatically selects HTTP or WebSocket based on network conditions and configuration.
683
- *
684
- * Includes automatic retry logic: if a call fails due to a connection error
685
- * (e.g. stale WebSocket after mobile browser was backgrounded), the client
686
- * forces a fresh connection (with a new token) and retries once.
687
- */
688
- export async function rpcCall(methodId, args) {
689
- return rpcCallWithRetry(methodId, args, 0, {});
690
- }
691
- export async function rpcCallWithOptions(methodId, args, options) {
692
- return rpcCallWithRetry(methodId, args, 0, options);
693
- }
694
- async function rpcCallViaHttpBatch(methodId, args) {
695
- const id = nextId();
696
- const req = { id, method: methodId, args };
697
- return new Promise((resolve, reject) => {
698
- pendingBatch.push({ req, resolve: resolve, reject });
699
- scheduleBatch();
700
- });
701
- }
702
- async function rpcCallWithRetry(methodId, args, attempt = 0, options = {}) {
703
- try {
704
- if (options.forceHttp || shouldUseHttpTransport()) {
705
- return await rpcCallViaHttpBatch(methodId, args);
706
- }
707
- return await rpcCallWebSocket(methodId, args);
708
- }
709
- catch (err) {
710
- if (attempt < MAX_RETRIES && isRetriableError(err)) {
711
- // Force a fresh connection (fetches a new token)
712
- forceReconnect();
713
- // Exponential backoff with jitter: 500ms, 1000ms, 2000ms (capped at 5s)
714
- const baseDelay = Math.min(RETRY_BASE_DELAY_MS * 2 ** attempt, RETRY_MAX_DELAY_MS);
715
- const jitter = Math.random() * baseDelay * 0.3;
716
- await new Promise((r) => setTimeout(r, baseDelay + jitter));
717
- return rpcCallWithRetry(methodId, args, attempt + 1, options);
718
- }
719
- if (isRetriableError(err) && configuredTransport !== "http" && !options.forceHttp) {
720
- activateTemporaryHttpFallback();
721
- return rpcCallViaHttpBatch(methodId, args);
722
- }
723
- throw err;
724
- }
725
- }
726
- /**
727
- * Pre-establishes the WebSocket connection.
728
- * Call this early (e.g., on page load) to avoid connection latency on first RPC call.
729
- * This is especially beneficial on high-latency networks like mobile LTE.
730
- * Note: Only effective when using WebSocket transport (not HTTP transport).
731
- */
732
- export function preconnect() {
733
- if (typeof window === "undefined") {
734
- return;
735
- }
736
- // Only preconnect if we're using WebSocket transport
737
- if (shouldUseHttpTransport()) {
738
- return;
739
- }
740
- // Fire and forget - establishes connection in background
741
- ensureSocketReady().catch(() => {
742
- // Silently ignore preconnect failures, will retry on actual call
743
- });
744
- }
745
- // Auto-preconnect when the module loads (browser only, WebSocket transport only)
746
- if (typeof window !== "undefined" && typeof document !== "undefined") {
747
- // Use requestIdleCallback if available, otherwise setTimeout
748
- const schedulePreconnect = window.requestIdleCallback || ((cb) => setTimeout(cb, 1));
749
- schedulePreconnect(() => preconnect());
750
- }
751
- // ============================================================================
752
- // Visibility-change reconnection (critical for mobile browsers)
753
- // ============================================================================
754
- //
755
- // Mobile browsers freeze or kill WebSocket connections when the tab is
756
- // backgrounded. When the user returns the socket may *appear* open but
757
- // is actually stale. We detect this via the Page Visibility API and
758
- // proactively tear down the old connection so the next RPC call creates
759
- // a fresh one (with a brand-new auth token).
760
- // ============================================================================
761
- if (typeof document !== "undefined") {
762
- document.addEventListener("visibilitychange", () => {
763
- if (document.hidden) {
764
- lastHiddenTimestamp = Date.now();
765
- }
766
- else {
767
- reconnectIfLikelyStale(false);
768
- }
769
- });
770
- document.addEventListener("pagehide", () => {
771
- lastHiddenTimestamp = Date.now();
772
- });
773
- }
774
- if (typeof window !== "undefined") {
775
- window.addEventListener("pageshow", (event) => {
776
- if (event.persisted) {
777
- reconnectIfLikelyStale(true);
778
- return;
779
- }
780
- reconnectIfLikelyStale(false);
781
- });
782
- window.addEventListener("focus", () => {
783
- reconnectIfLikelyStale(false);
784
- });
785
- window.addEventListener("online", () => {
786
- reconnectIfLikelyStale(true);
787
- });
155
+ // Network failures are not replayed: a lost response may follow a successful mutation.
156
+ return result;
788
157
  }
789
158
  //# sourceMappingURL=rpcClient.js.map