UNPKG

@softr/sdk

Version:

The SDK for building Softr apps on TanStack Start. It lets an app interact with Softr: auth, datasources, workflows and integrations.

358 lines (356 loc) • 12.4 kB
import { softrApiUrl } from "./softr-api.js"; import { fetch } from "./fetch.js"; import { sessionConfig } from "./auth/config.js"; import { readSessionToken } from "./auth/session.js"; import { readCached } from "./cache.js"; import { z } from "zod"; import { useEffect, useSyncExternalStore } from "react"; import { createMiddleware } from "@tanstack/react-start"; import { rootRouteId, useRouteContext } from "@tanstack/react-router"; //#region src/notifications.ts const SETTINGS_PATH = "/_softr/notifications.json"; const FEED_PATH = "/_softr/notifications"; const UNREAD_COUNT_PATH = "/_softr/notifications/unread-count"; const READ_ALL_PATH = "/_softr/notifications/read-all"; const MARK_PATH = /^\/_softr\/notifications\/([0-9a-f-]{36})\/(read|unread)$/; const TTL_MS = 6e4; const POLL_MS = 3e4; const PAGE_SIZE = 20; const settingsSchema = z.object({ defaultIcon: z.string().nullable(), buttonLabel: z.string().nullable(), allTabName: z.string().nullable(), allTabEmptyMessage: z.string().nullable(), unreadTabName: z.string().nullable(), unreadTabEmptyMessage: z.string().nullable(), markAllAsReadLabel: z.string().nullable(), markAsReadLabel: z.string().nullable(), markAsUnreadLabel: z.string().nullable() }); const notificationSchema = z.object({ id: z.string(), title: z.string().nullable(), description: z.string().nullable(), link: z.string().nullable(), read: z.boolean(), createdAt: z.number().nullable() }); const feedSchema = z.object({ items: z.array(notificationSchema), nextCursor: z.string().nullable(), hasMore: z.boolean(), unreadTotal: z.number() }); const unreadCountSchema = z.object({ count: z.number() }); let cachedSettings; function platformUrl(path) { return `${softrApiUrl("SOFTR_PLATFORM_API_URL")}${path}`; } function readSettings() { return readCached("in-app notifications from Softr", TTL_MS, () => cachedSettings, (entry) => cachedSettings = entry, async () => { const { applicationId } = sessionConfig(); const response = await fetch(platformUrl(`/v1/vibe/applications/${applicationId}/in-app-notifications`), { headers: { accept: "application/json" } }); if (response.status === 404) return null; if (!response.ok) throw new Error(`The platform answered ${response.status}`); return settingsSchema.parse(await response.json()); }); } /** The platform request a visitor's inbox request stands for, or null when the path is not the inbox's. */ function platformRequestFor(pathname, method, search) { if (method === "GET" && pathname === FEED_PATH) { const forwarded = new URLSearchParams(); for (const name of [ "cursor", "unreadOnly", "limit" ]) { const value = search.get(name); if (value !== null) forwarded.set(name, value); } return { path: `/v1/notifications?${forwarded}`, method }; } if (method === "GET" && pathname === UNREAD_COUNT_PATH) return { path: "/v1/notifications/unread-count", method }; if (method === "POST" && pathname === READ_ALL_PATH) return { path: "/v1/notifications/read-all", method }; const mark = method === "POST" ? MARK_PATH.exec(pathname) : null; if (mark !== null) return { path: `/v1/notifications/${mark[1]}/${mark[2]}`, method }; return null; } /** * Serves the in-app notification inbox from the app's own origin: the app's * inbox settings, and the signed-in visitor's notifications, unread count and * read state. Every other request passes through untouched. */ function notificationsMiddleware() { return createMiddleware({ type: "request" }).server(async ({ next, pathname, request }) => { if (pathname === SETTINGS_PATH && request.method === "GET") { const settings = await readSettings(); if (settings === null) return new Response(null, { status: 404 }); return Response.json(settings, { headers: { "cache-control": "no-store" } }); } const url = new URL(request.url); const forward = platformRequestFor(pathname, request.method, url.searchParams); if (forward === null) return next(); if (forward.method === "POST" && !request.headers.get("content-type")?.startsWith("application/json")) return new Response(null, { status: 415 }); const token = readSessionToken(); if (token === null) return new Response(null, { status: 401 }); const response = await fetch(platformUrl(forward.path), { method: forward.method, headers: { accept: "application/json", authorization: `Bearer ${token}` } }).catch(() => null); if (response === null) return new Response(null, { status: 502 }); if (!response.ok || response.status === 204) return new Response(null, { status: response.ok ? 204 : response.status }); return new Response(await response.text(), { headers: { "content-type": "application/json", "cache-control": "no-store" } }); }); } const EMPTY = { settings: null, notifications: [], nextCursor: null, hasMore: false, unreadCount: 0, unreadOnly: false }; /** * One inbox per page, however many components show it: one settings read, one * poll, and the same list and count everywhere. It runs while at least one * signed-in component is mounted. */ const inboxStore = (() => { let state = EMPTY; const listeners = /* @__PURE__ */ new Set(); let members = 0; let session = 0; let listVersion = 0; let pagesLoaded = 0; let knownCount = null; let stopPolling = null; function setState(patch) { state = { ...state, ...patch }; for (const listener of listeners) listener(); } async function start() { const current = ++session; const response = await globalThis.fetch(SETTINGS_PATH, { headers: { accept: "application/json" } }); if (!response.ok || current !== session) return; const parsed = settingsSchema.safeParse(await response.json()); if (!parsed.success || current !== session) return; setState({ settings: parsed.data }); await reloadList(); if (current === session) stopPolling = startPolling(); } function stop() { session++; listVersion++; stopPolling?.(); stopPolling = null; knownCount = null; pagesLoaded = 0; setState(EMPTY); } async function reloadList() { const version = ++listVersion; const page = await readFeed(null, state.unreadOnly); if (page === null || version !== listVersion) return; pagesLoaded = 1; knownCount = page.unreadTotal; setState({ notifications: page.items, nextCursor: page.nextCursor, hasMore: page.hasMore, unreadCount: page.unreadTotal }); } async function addNewToTop() { const version = listVersion; const page = await readFeed(null, state.unreadOnly); if (page === null || version !== listVersion) return; setState({ notifications: mergeFirstPage(state.notifications, page.items), unreadCount: page.unreadTotal }); } function startPolling() { const pollQuietly = () => void poll().catch(() => void 0); const timer = setInterval(pollQuietly, POLL_MS); globalThis.document?.addEventListener("visibilitychange", pollQuietly); return () => { clearInterval(timer); globalThis.document?.removeEventListener("visibilitychange", pollQuietly); }; } async function poll() { if (globalThis.document?.visibilityState === "hidden") return; const current = session; const response = await globalThis.fetch(UNREAD_COUNT_PATH, { headers: { accept: "application/json" } }); if (!response.ok || current !== session) return; const parsed = unreadCountSchema.safeParse(await response.json()); if (!parsed.success || current !== session) return; const isChanged = knownCount !== null && knownCount !== parsed.data.count; knownCount = parsed.data.count; setState({ unreadCount: parsed.data.count }); if (!isChanged) return; await (pagesLoaded > 1 ? addNewToTop() : reloadList()); } async function loadMore() { if (!state.hasMore || state.nextCursor === null) return; const version = listVersion; const page = await readFeed(state.nextCursor, state.unreadOnly); if (page === null || version !== listVersion) return; pagesLoaded++; const known = new Set(state.notifications.map((notification) => notification.id)); setState({ notifications: [...state.notifications, ...page.items.filter((notification) => !known.has(notification.id))], nextCursor: page.nextCursor, hasMore: page.hasMore }); } async function mark(id, read) { if (!(await postJson(`${FEED_PATH}/${encodeURIComponent(id)}/${read ? "read" : "unread"}`)).ok) throw new Error("Could not change the notification"); const unreadCount = state.notifications.some((notification) => notification.id === id && notification.read !== read) ? Math.max(0, state.unreadCount + (read ? -1 : 1)) : state.unreadCount; knownCount = unreadCount; setState({ notifications: state.notifications.map((notification) => notification.id === id ? { ...notification, read } : notification), unreadCount }); } async function markAllRead() { if (!(await postJson(READ_ALL_PATH)).ok) throw new Error("Could not mark the notifications as read"); knownCount = 0; setState({ notifications: state.notifications.map((notification) => ({ ...notification, read: true })), unreadCount: 0 }); } function showUnreadOnly(unreadOnly) { if (unreadOnly === state.unreadOnly) return; setState({ unreadOnly, nextCursor: null, hasMore: false }); reloadList().catch(() => void 0); } return { getState: () => state, subscribe(listener) { listeners.add(listener); return () => listeners.delete(listener); }, join() { members++; if (members === 1) start().catch((error) => console.warn("[@softr/sdk] Could not load in-app notifications:", error)); let hasLeft = false; return () => { if (hasLeft) return; hasLeft = true; members--; if (members === 0) stop(); }; }, poll, loadMore, markRead: (id) => mark(id, true), markUnread: (id) => mark(id, false), markAllRead, showUnreadOnly }; })(); /** * The signed-in visitor's in-app notifications, sent to them from Softr * Workflows. Every component that calls it reads the same list and unread * count, and the page polls the count once, however many call it. * * @example * function Inbox() { * const inbox = useNotifications() * if (inbox.status !== "ready") return null * return <button>{inbox.texts.buttonLabel ?? "Notifications"} ({inbox.unreadCount})</button> * } */ function useNotifications() { const signedIn = useRouteContext({ from: rootRouteId, select: (context) => context.user !== null }); const state = useSyncExternalStore(inboxStore.subscribe, inboxStore.getState, () => EMPTY); useEffect(() => { if (!signedIn) return; return inboxStore.join(); }, [signedIn]); if (!signedIn || state.settings === null) return { status: "unavailable" }; const { defaultIcon,...texts } = state.settings; return { status: "ready", texts, defaultIcon, notifications: state.notifications, unreadCount: state.unreadCount, unreadOnly: state.unreadOnly, showUnreadOnly: inboxStore.showUnreadOnly, hasMore: state.hasMore, loadMore: inboxStore.loadMore, markRead: inboxStore.markRead, markUnread: inboxStore.markUnread, markAllRead: inboxStore.markAllRead }; } /** New notifications on top, the loaded ones kept with their state from the first page where it has them. */ function mergeFirstPage(current, firstPage) { const fresh = new Map(firstPage.map((notification) => [notification.id, notification])); const known = new Set(current.map((notification) => notification.id)); return [...firstPage.filter((notification) => !known.has(notification.id)), ...current.map((notification) => fresh.get(notification.id) ?? notification)]; } async function readFeed(cursor, unreadOnly) { const search = new URLSearchParams({ limit: String(PAGE_SIZE), unreadOnly: String(unreadOnly) }); if (cursor !== null) search.set("cursor", cursor); const response = await globalThis.fetch(`${FEED_PATH}?${search}`, { headers: { accept: "application/json" } }); if (!response.ok) return null; const parsed = feedSchema.safeParse(await response.json()); if (!parsed.success) return null; return { items: parsed.data.items, nextCursor: parsed.data.nextCursor, hasMore: parsed.data.hasMore, unreadTotal: parsed.data.unreadTotal }; } function postJson(path) { return globalThis.fetch(path, { method: "POST", headers: { "content-type": "application/json" }, body: "{}", keepalive: true }); } //#endregion export { notificationsMiddleware, useNotifications };