@mitumba/sdk 5.24.0 → 5.25.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.
package/dist/index.mjs CHANGED
@@ -1880,13 +1880,241 @@ var MessagesModule = class {
1880
1880
  }
1881
1881
  };
1882
1882
 
1883
+ // src/realtime/notification-stream.ts
1884
+ var TICKET_PATH = "/notify/notifications/stream/tickets";
1885
+ var CLOSE_EXPIRED = 4001;
1886
+ var CLOSE_FINAL = [4003, 4004];
1887
+ function isRecord3(value) {
1888
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
1889
+ }
1890
+ var isCount = (value) => Number.isSafeInteger(value) && value >= 0;
1891
+ function isItem(value) {
1892
+ return isRecord3(value) && typeof value.id === "string" && typeof value.type === "string" && typeof value.category === "string" && typeof value.title === "string" && typeof value.body === "string" && Array.isArray(value.actions) && typeof value.createdAt === "string" && (value.readAt === null || typeof value.readAt === "string") && (value.flash === null || isRecord3(value.flash));
1893
+ }
1894
+ function parseNotificationFrame(value) {
1895
+ if (!isRecord3(value) || typeof value.type !== "string") throw new RealtimeProtocolError();
1896
+ switch (value.type) {
1897
+ case "hello":
1898
+ if (isCount(value.unread) && (value.flash === null || isItem(value.flash))) return value;
1899
+ break;
1900
+ case "item":
1901
+ if (isCount(value.unread) && isItem(value.item)) return value;
1902
+ break;
1903
+ case "read":
1904
+ if (isCount(value.unread) && (value.ids === "all" || Array.isArray(value.ids) && value.ids.every((id) => typeof id === "string"))) {
1905
+ return value;
1906
+ }
1907
+ break;
1908
+ case "flash":
1909
+ if (isItem(value.flash) && value.flash.flash !== null) return value;
1910
+ break;
1911
+ case "flash_resolved":
1912
+ if (typeof value.id === "string" && isCount(value.unread)) return value;
1913
+ break;
1914
+ case "pong":
1915
+ return { type: "pong" };
1916
+ }
1917
+ throw new RealtimeProtocolError();
1918
+ }
1919
+ function parseTicket2(value) {
1920
+ if (!isRecord3(value) || typeof value.ticket !== "string" || typeof value.expires_at !== "string" || typeof value.websocket_url !== "string" || typeof value.socket_closes_at !== "string") {
1921
+ throw new RealtimeProtocolError();
1922
+ }
1923
+ let url;
1924
+ try {
1925
+ url = new URL(value.websocket_url);
1926
+ } catch {
1927
+ throw new RealtimeProtocolError();
1928
+ }
1929
+ if (!["ws:", "wss:"].includes(url.protocol) || url.searchParams.has("token") || !url.searchParams.has("ticket")) throw new RealtimeProtocolError();
1930
+ return value;
1931
+ }
1932
+ var ManagedNotificationStream = class {
1933
+ constructor(client, options = {}) {
1934
+ this.client = client;
1935
+ this.options = options;
1936
+ }
1937
+ currentState = "closed";
1938
+ currentUnread = null;
1939
+ socket = null;
1940
+ reconnectTimer = null;
1941
+ frameListeners = /* @__PURE__ */ new Set();
1942
+ stateListeners = /* @__PURE__ */ new Set();
1943
+ explicitClose = false;
1944
+ reconnectAttempt = 0;
1945
+ startPromise = null;
1946
+ resolveStart = null;
1947
+ rejectStart = null;
1948
+ onMessage = (event) => {
1949
+ this.handleMessage(event);
1950
+ };
1951
+ onClose = (event) => {
1952
+ this.handleClose(event);
1953
+ };
1954
+ onIgnored = () => void 0;
1955
+ get state() {
1956
+ return this.currentState;
1957
+ }
1958
+ get unread() {
1959
+ return this.currentUnread;
1960
+ }
1961
+ onFrame(listener) {
1962
+ this.frameListeners.add(listener);
1963
+ return () => {
1964
+ this.frameListeners.delete(listener);
1965
+ };
1966
+ }
1967
+ onStateChange(listener) {
1968
+ this.stateListeners.add(listener);
1969
+ return () => {
1970
+ this.stateListeners.delete(listener);
1971
+ };
1972
+ }
1973
+ start() {
1974
+ if (this.explicitClose) return Promise.reject(new RealtimeUnavailableError());
1975
+ if (this.currentState === "open") return Promise.resolve();
1976
+ if (this.startPromise) return this.startPromise;
1977
+ this.startPromise = new Promise((resolve, reject) => {
1978
+ this.resolveStart = resolve;
1979
+ this.rejectStart = reject;
1980
+ });
1981
+ const pending = this.startPromise;
1982
+ void this.open(false).catch((error) => this.openFailed(error));
1983
+ return pending;
1984
+ }
1985
+ close() {
1986
+ this.explicitClose = true;
1987
+ this.clearReconnect();
1988
+ this.detachSocket(true);
1989
+ this.transition("closed");
1990
+ this.resolveStart?.();
1991
+ this.finishStart();
1992
+ this.frameListeners.clear();
1993
+ this.stateListeners.clear();
1994
+ }
1995
+ async open(reconnecting) {
1996
+ this.transition(reconnecting ? "reconnecting" : "connecting");
1997
+ const raw = await this.client.post(TICKET_PATH, {}, { signal: this.options.signal });
1998
+ if (this.explicitClose) return;
1999
+ const ticket = parseTicket2(raw);
2000
+ const url = new URL(ticket.websocket_url);
2001
+ url.searchParams.set("surface", this.options.surface ?? "web");
2002
+ const socket = this.client.createWebSocket(url.toString(), []);
2003
+ this.socket = socket;
2004
+ socket.addEventListener("open", this.onIgnored);
2005
+ socket.addEventListener("message", this.onMessage);
2006
+ socket.addEventListener("close", this.onClose);
2007
+ socket.addEventListener("error", this.onIgnored);
2008
+ }
2009
+ /** A ticket that cannot be had because of who is asking is final; anything else is retried. */
2010
+ openFailed(error) {
2011
+ if (error instanceof RealtimeProtocolError || error instanceof RealtimeUnavailableError || error instanceof APIError && [401, 403].includes(error.status)) {
2012
+ this.fail(error);
2013
+ } else {
2014
+ this.scheduleReconnect();
2015
+ }
2016
+ }
2017
+ handleMessage(event) {
2018
+ let frame;
2019
+ try {
2020
+ if (typeof event.data !== "string") throw new RealtimeProtocolError();
2021
+ let decoded;
2022
+ try {
2023
+ decoded = JSON.parse(event.data);
2024
+ } catch {
2025
+ throw new RealtimeProtocolError();
2026
+ }
2027
+ frame = parseNotificationFrame(decoded);
2028
+ } catch (error) {
2029
+ this.fail(error);
2030
+ try {
2031
+ this.socket?.close(4004, "protocol_error");
2032
+ } catch {
2033
+ }
2034
+ return;
2035
+ }
2036
+ if (frame.type === "pong") return;
2037
+ if ("unread" in frame) this.currentUnread = frame.unread;
2038
+ if (frame.type === "hello") {
2039
+ this.reconnectAttempt = 0;
2040
+ this.transition("open");
2041
+ this.resolveStart?.();
2042
+ this.finishStart();
2043
+ }
2044
+ for (const listener of [...this.frameListeners]) {
2045
+ try {
2046
+ listener(frame);
2047
+ } catch {
2048
+ }
2049
+ }
2050
+ }
2051
+ handleClose(event) {
2052
+ this.detachSocket(false);
2053
+ if (this.explicitClose || this.currentState === "failed") return;
2054
+ if (CLOSE_FINAL.includes(event.code)) {
2055
+ this.fail(new RealtimeUnavailableError());
2056
+ return;
2057
+ }
2058
+ if (event.code === CLOSE_EXPIRED) this.reconnectAttempt = 0;
2059
+ this.scheduleReconnect();
2060
+ }
2061
+ scheduleReconnect() {
2062
+ if (this.reconnectTimer || this.explicitClose) return;
2063
+ this.transition("reconnecting");
2064
+ const base = Math.max(10, this.options.reconnectBaseDelayMs ?? 500);
2065
+ const maximum = Math.max(base, this.options.reconnectMaxDelayMs ?? 3e4);
2066
+ const cap = Math.min(maximum, base * 2 ** this.reconnectAttempt);
2067
+ const delay = Math.floor((this.options.random ?? Math.random)() * cap);
2068
+ this.reconnectAttempt += 1;
2069
+ this.reconnectTimer = setTimeout(() => {
2070
+ this.reconnectTimer = null;
2071
+ void this.open(true).catch((error) => this.openFailed(error));
2072
+ }, delay);
2073
+ }
2074
+ clearReconnect() {
2075
+ if (this.reconnectTimer) clearTimeout(this.reconnectTimer);
2076
+ this.reconnectTimer = null;
2077
+ }
2078
+ detachSocket(close) {
2079
+ const socket = this.socket;
2080
+ if (!socket) return;
2081
+ socket.removeEventListener("open", this.onIgnored);
2082
+ socket.removeEventListener("message", this.onMessage);
2083
+ socket.removeEventListener("close", this.onClose);
2084
+ socket.removeEventListener("error", this.onIgnored);
2085
+ if (close) {
2086
+ try {
2087
+ socket.close(1e3, "client_close");
2088
+ } catch {
2089
+ }
2090
+ }
2091
+ this.socket = null;
2092
+ }
2093
+ transition(state) {
2094
+ if (this.currentState === state) return;
2095
+ this.currentState = state;
2096
+ for (const listener of [...this.stateListeners]) listener(state);
2097
+ }
2098
+ fail(error) {
2099
+ this.clearReconnect();
2100
+ this.transition("failed");
2101
+ this.rejectStart?.(error);
2102
+ this.finishStart();
2103
+ }
2104
+ finishStart() {
2105
+ this.resolveStart = null;
2106
+ this.rejectStart = null;
2107
+ this.startPromise = null;
2108
+ }
2109
+ };
2110
+
1883
2111
  // src/modules/notifications.ts
1884
2112
  var NotificationsModule = class {
1885
2113
  constructor(client) {
1886
2114
  this.client = client;
1887
2115
  }
1888
2116
  /**
1889
- * List paginated notifications with unread count.
2117
+ * List paginated notifications (20 per page, newest first) with the unread count.
1890
2118
  */
1891
2119
  async list(page, options) {
1892
2120
  return this.client.get(
@@ -1896,11 +2124,27 @@ var NotificationsModule = class {
1896
2124
  );
1897
2125
  }
1898
2126
  /**
1899
- * Mark notifications as read. If ids omitted, marks all as read.
2127
+ * The unread count alone: for a badge, on focus or on an interval when no stream is open.
2128
+ */
2129
+ async unread(options) {
2130
+ return this.client.get("/notify/notifications/unread", void 0, options);
2131
+ }
2132
+ /**
2133
+ * Mark notifications as read (at most 90 ids per call). If ids are omitted, marks all as read.
1900
2134
  */
1901
2135
  async markRead(ids, options) {
1902
2136
  return this.client.post("/notify/notifications/read", ids ? { ids } : {}, options);
1903
2137
  }
2138
+ /** Create an inert live notification stream. Register listeners before `start()`. */
2139
+ stream(options) {
2140
+ return new ManagedNotificationStream(this.client, options);
2141
+ }
2142
+ /** Create and start a live notification stream. Resolves once connected. */
2143
+ async connectStream(options) {
2144
+ const stream = this.stream(options);
2145
+ await stream.start();
2146
+ return stream;
2147
+ }
1904
2148
  };
1905
2149
 
1906
2150
  // src/modules/stores.ts