@base44-preview/sdk 0.8.35-pr.212.1d74ede → 0.8.35-pr.212.5aafd7f

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.
@@ -3,8 +3,17 @@ export declare function createRealtimeModule(config: {
3
3
  getToken(handlerName: string, instanceId: string): Promise<string>;
4
4
  dispatcherWsUrl: string;
5
5
  }): Record<string, RealtimeHandler>;
6
+ /** Handle for an active realtime subscription. */
7
+ interface RealtimeSubscription {
8
+ /** This connection's id — the same value the handler receives as `conn.id`. */
9
+ id: string;
10
+ /** Close the subscription and its underlying socket. */
11
+ unsubscribe(): void;
12
+ }
6
13
  interface RealtimeHandler {
7
- subscribe(instanceId: string, callback: (data: unknown) => void): () => void;
14
+ subscribe(instanceId: string, callback: (data: unknown) => void, options?: {
15
+ id?: string;
16
+ }): RealtimeSubscription;
8
17
  send(instanceId: string, data: unknown): void;
9
18
  }
10
19
  export {};
@@ -8,44 +8,68 @@ export function createRealtimeModule(config) {
8
8
  return new Proxy({}, {
9
9
  get(_, handlerName) {
10
10
  return {
11
- subscribe(instanceId, callback) {
11
+ subscribe(instanceId, callback, options) {
12
12
  var _a;
13
13
  const key = socketKey(handlerName, instanceId);
14
14
  // close existing if any
15
15
  (_a = activeSockets.get(key)) === null || _a === void 0 ? void 0 : _a.close();
16
+ // query as async fn: called on every (re)connect, fetches a fresh token each time
16
17
  const ws = new PartySocket({
17
18
  host: config.dispatcherWsUrl,
18
19
  party: handlerName,
19
20
  room: instanceId,
21
+ // Connection id: caller-supplied (stable — reuse across reconnects/tabs as
22
+ // you see fit) or auto-generated per connection. Server sees it as conn.id.
23
+ id: options === null || options === void 0 ? void 0 : options.id,
24
+ query: () => config.getToken(handlerName, instanceId).then((token) => ({ token })),
20
25
  });
21
26
  activeSockets.set(key, ws);
22
- // Fetch token and attach on connect
23
- config.getToken(handlerName, instanceId).then((token) => {
24
- ws.updateProperties({ party: handlerName, room: instanceId, query: { token } });
25
- });
27
+ // Heartbeat / half-open detection. PartySocket only reconnects on a
28
+ // browser close/error event, so a silently-dead connection (TCP alive,
29
+ // no data common behind proxies/LBs) hangs until the OS idle timeout
30
+ // (~60s). We ping periodically and force a reconnect if nothing comes
31
+ // back within DEAD_MS, cutting detection from ~60s to a few seconds.
32
+ // Pairs with the handler's setWebSocketAutoResponse("__ping"→"__pong"),
33
+ // so idle handlers (no app broadcasts) still keep the connection proven.
34
+ const PING_MS = 1000;
35
+ const DEAD_MS = 3000;
36
+ let lastMsg = Date.now();
37
+ const bumpAlive = () => { lastMsg = Date.now(); };
38
+ ws.addEventListener("open", bumpAlive);
26
39
  ws.addEventListener("message", (ev) => {
40
+ bumpAlive();
41
+ let data;
27
42
  try {
28
- callback(JSON.parse(ev.data));
43
+ data = JSON.parse(ev.data);
29
44
  }
30
45
  catch (_a) {
31
- // ignore malformed
46
+ return; // ignore malformed
32
47
  }
48
+ // Swallow heartbeat acks — never surface them to the app.
49
+ if (data && typeof data === "object" && data.type === "__pong")
50
+ return;
51
+ callback(data);
33
52
  });
34
- // Re-fetch token on reconnect
35
- ws.addEventListener("close", async () => {
36
- if (activeSockets.get(key) !== ws)
37
- return; // replaced
53
+ const heartbeat = setInterval(() => {
54
+ if (Date.now() - lastMsg > DEAD_MS) {
55
+ bumpAlive(); // avoid a reconnect storm while the new socket comes up
56
+ ws.reconnect();
57
+ return;
58
+ }
38
59
  try {
39
- const newToken = await config.getToken(handlerName, instanceId);
40
- ws.updateProperties({ party: handlerName, room: instanceId, query: { token: newToken } });
60
+ ws.send(JSON.stringify({ type: "__ping" }));
41
61
  }
42
62
  catch (_a) {
43
- // ignore token refresh failure
63
+ // socket not open; the watchdog above will force a reconnect
44
64
  }
45
- });
46
- return () => {
47
- activeSockets.delete(key);
48
- ws.close();
65
+ }, PING_MS);
66
+ return {
67
+ id: ws.id, // the connection id (same value the handler sees as conn.id)
68
+ unsubscribe() {
69
+ clearInterval(heartbeat);
70
+ activeSockets.delete(key);
71
+ ws.close();
72
+ },
49
73
  };
50
74
  },
51
75
  send(instanceId, data) {
@@ -37,11 +37,27 @@ type OutboundFor<N extends string> = N extends keyof RealtimeHandlerRegistry ? R
37
37
  * Typed automatically when the handler is registered in {@link RealtimeHandlerRegistry}.
38
38
  */
39
39
  export interface RealtimeHandlerClient<N extends string = string> {
40
- /** Open a WebSocket subscription. Returns a synchronous unsubscribe function. */
41
- subscribe(instanceId: string, callback: (data: InboundFor<N>) => void): () => void;
40
+ /**
41
+ * Open a WebSocket subscription. Returns a {@link RealtimeSubscription} with the
42
+ * connection `id` (same value the handler sees as `conn.id`) and an `unsubscribe()` method.
43
+ *
44
+ * Pass `options.id` to control the connection id (e.g. a stable per-tab id so a
45
+ * reconnect reuses the same server-side connection); omit it for an auto-generated
46
+ * per-connection id.
47
+ */
48
+ subscribe(instanceId: string, callback: (data: InboundFor<N>) => void, options?: {
49
+ id?: string;
50
+ }): RealtimeSubscription;
42
51
  /** Send a message over the open socket. Throws if not subscribed. */
43
52
  send(instanceId: string, data: OutboundFor<N>): void;
44
53
  }
54
+ /** Handle for an active realtime subscription. */
55
+ export interface RealtimeSubscription {
56
+ /** This connection's id — the same value the handler receives as `conn.id`. */
57
+ id: string;
58
+ /** Close the subscription and its underlying socket. */
59
+ unsubscribe(): void;
60
+ }
45
61
  /**
46
62
  * The realtime module provides access to Cloudflare Durable Object-backed
47
63
  * RealtimeHandlers deployed by the Base44 platform.
@@ -51,8 +67,8 @@ export interface RealtimeHandlerClient<N extends string = string> {
51
67
  * const sub = await base44.realtime.MyHandler.subscribe("room-1", (msg) => {
52
68
  * console.log(msg); // typed if MyHandler is in RealtimeHandlerRegistry
53
69
  * });
54
- * sub.send({ text: "hello" });
55
- * sub.close();
70
+ * const { id, unsubscribe } = sub;
71
+ * unsubscribe();
56
72
  * ```
57
73
  */
58
74
  export type RealtimeModule = {
@@ -8,6 +8,7 @@
8
8
  * At deploy time the bundler replaces this import with the compiled
9
9
  * Cloudflare Durable Object implementation — this file provides types only.
10
10
  */
11
+ import type { Base44Client } from "./client.types.js";
11
12
  export interface Conn {
12
13
  userId: string;
13
14
  appId: string;
@@ -15,13 +16,34 @@ export interface Conn {
15
16
  send(data: unknown): void;
16
17
  reject(code: number, reason: string): void;
17
18
  }
19
+ export interface Storage {
20
+ get<T>(key: string): Promise<T | undefined>;
21
+ put(key: string, value: unknown): Promise<void>;
22
+ delete(key: string): Promise<boolean>;
23
+ }
18
24
  export declare abstract class RealtimeHandler<_State = unknown, Message = unknown> {
19
25
  abstract handleConnect(conn: Conn): void | Promise<void>;
20
26
  abstract handleMessage(conn: Conn, msg: Message): void | Promise<void>;
21
27
  abstract handleClose(conn: Conn): void | Promise<void>;
22
28
  abstract handleTick(): void | Promise<void>;
29
+ onStart(): void | Promise<void>;
30
+ /**
31
+ * Managed ticker (opt-in). Override {@link shouldTick} and the platform runs
32
+ * {@link handleTick} on a timer of {@link tickIntervalMs} while it returns true,
33
+ * and stops (letting the Durable Object hibernate — no compute cost) when it
34
+ * returns false. The platform owns scheduling, rescheduling, self-heal, and
35
+ * error-safety — you don't call {@link startLoop}/{@link stopLoop}.
36
+ *
37
+ * Re-evaluated after every connect/message/close and on every tick, so keep it
38
+ * cheap and pure (no async, no side effects). Example: `return this.players >= 2`.
39
+ */
40
+ protected tickIntervalMs: number;
41
+ protected shouldTick?(): boolean;
23
42
  protected broadcast(_data: unknown): void;
24
43
  protected getConnections(): Conn[];
25
44
  protected startLoop(_ms: number): Promise<void>;
26
45
  protected stopLoop(): Promise<void>;
46
+ protected get instanceId(): string;
47
+ protected get storage(): Storage;
48
+ protected createServiceClient(): Base44Client;
27
49
  }
@@ -9,6 +9,20 @@
9
9
  * Cloudflare Durable Object implementation — this file provides types only.
10
10
  */
11
11
  export class RealtimeHandler {
12
+ constructor() {
13
+ /**
14
+ * Managed ticker (opt-in). Override {@link shouldTick} and the platform runs
15
+ * {@link handleTick} on a timer of {@link tickIntervalMs} while it returns true,
16
+ * and stops (letting the Durable Object hibernate — no compute cost) when it
17
+ * returns false. The platform owns scheduling, rescheduling, self-heal, and
18
+ * error-safety — you don't call {@link startLoop}/{@link stopLoop}.
19
+ *
20
+ * Re-evaluated after every connect/message/close and on every tick, so keep it
21
+ * cheap and pure (no async, no side effects). Example: `return this.players >= 2`.
22
+ */
23
+ this.tickIntervalMs = 100;
24
+ }
25
+ onStart() { }
12
26
  broadcast(_data) {
13
27
  throw new Error("RealtimeHandler.broadcast() is only available inside a deployed handler");
14
28
  }
@@ -21,4 +35,13 @@ export class RealtimeHandler {
21
35
  stopLoop() {
22
36
  throw new Error("RealtimeHandler.stopLoop() is only available inside a deployed handler");
23
37
  }
38
+ get instanceId() {
39
+ throw new Error("RealtimeHandler.instanceId is only available inside a deployed handler");
40
+ }
41
+ get storage() {
42
+ throw new Error("RealtimeHandler.storage is only available inside a deployed handler");
43
+ }
44
+ createServiceClient() {
45
+ throw new Error("RealtimeHandler.createServiceClient() is only available inside a deployed handler");
46
+ }
24
47
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@base44-preview/sdk",
3
- "version": "0.8.35-pr.212.1d74ede",
3
+ "version": "0.8.35-pr.212.5aafd7f",
4
4
  "description": "JavaScript SDK for Base44 API",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",