@softr/sdk
Version:
The SDK for building Softr apps on TanStack Start. It lets an app interact with Softr: auth, datasources, workflows and integrations.
295 lines (293 loc) • 11.6 kB
JavaScript
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 { detectPlatform, isStandalone } from "./pwa.js";
import { z } from "zod";
import { useCallback, useEffect, useState } from "react";
import { createMiddleware } from "@tanstack/react-start";
import { rootRouteId, useRouteContext } from "@tanstack/react-router";
//#region src/push.ts
const WORKER_PATH = "/_softr/sw.js";
const SETTINGS_PATH = "/_softr/push.json";
const SUBSCRIPTION_PATH = "/_softr/push";
const TTL_MS = 6e4;
const promptSchema = z.object({
title: z.string().nullable(),
message: z.string().nullable(),
enableButtonLabel: z.string().nullable(),
skipDays: z.number().nullable()
});
const settingsSchema = z.object({
vapidPublicKey: z.string(),
desktopEnabled: z.boolean(),
mobileEnabled: z.boolean(),
permissionPrompt: promptSchema.nullable()
});
const browserSubscriptionSchema = z.object({
endpoint: z.string(),
keys: z.object({
p256dh: z.string(),
auth: z.string()
})
});
let cachedSettings;
let cachedWorker;
function platformPushUrl() {
const { applicationId } = sessionConfig();
return `${softrApiUrl("SOFTR_PLATFORM_API_URL")}/v1/vibe/applications/${applicationId}/push`;
}
function readSettings() {
return readCached("push notifications from Softr", TTL_MS, () => cachedSettings, (entry) => cachedSettings = entry, async () => {
const response = await fetch(platformPushUrl(), { 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());
});
}
function readWorker() {
return readCached("the push service worker from Softr", TTL_MS, () => cachedWorker, (entry) => cachedWorker = entry, async () => {
const response = await fetch(`${softrApiUrl("SOFTR_PLATFORM_API_URL")}/pwa/sw.js`);
if (!response.ok) throw new Error(`The platform answered ${response.status}`);
return response.text();
});
}
/**
* Serves push notifications from the app's own origin: the service worker, the
* app's push settings, and saving or removing this browser's subscription for
* the signed-in visitor. Every other request passes through untouched.
*/
function pushMiddleware() {
return createMiddleware({ type: "request" }).server(async ({ next, pathname, request }) => {
if (pathname === WORKER_PATH && request.method === "GET") {
const worker = await readWorker();
if (worker === null) return new Response(null, {
status: 503,
headers: { "cache-control": "no-store" }
});
return new Response(worker, { headers: {
"content-type": "text/javascript; charset=utf-8",
"cache-control": "no-cache",
"service-worker-allowed": "/"
} });
}
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" } });
}
if (pathname === SUBSCRIPTION_PATH && (request.method === "POST" || request.method === "DELETE")) {
if (!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 body = z.object({ subscription: browserSubscriptionSchema }).safeParse(await request.json().catch(() => null));
if (!body.success) return new Response(null, { status: 400 });
const response = await (request.method === "POST" ? fetch(platformPushUrl(), {
method: "POST",
headers: {
"content-type": "application/json",
authorization: `Bearer ${token}`
},
body: JSON.stringify({
origin: new URL(request.url).origin,
userAgent: request.headers.get("user-agent"),
subscription: body.data.subscription
})
}) : fetch(`${platformPushUrl()}?${new URLSearchParams({ endpoint: body.data.subscription.endpoint })}`, {
method: "DELETE",
headers: { authorization: `Bearer ${token}` }
})).catch(() => null);
if (response === null) return new Response(null, { status: 502 });
return new Response(null, { status: response.ok ? 204 : response.status });
}
return next();
});
}
const DISMISSED_AT_KEY = "softr-push-dismissed-at";
/**
* Push notifications for the signed-in visitor. Call it once, in the one
* component that shows the prompt, rendered once in the root route's
* `RootDocument`, so this browser stays registered. Each call keeps state of
* its own, so a second call does not see a subscribe made through the first.
* Show a prompt only while `status` is `ask`
* and the prompt is not `dismissed`.
*
* @example
* function EnableNotifications() {
* const push = usePushNotifications()
* if (push.status !== "ask" || push.dismissed) return null
* const turnOn = () => push.subscribe().catch(() => toast.error("Notifications could not be turned on."))
* return <button onClick={turnOn}>{push.prompt.enableButtonLabel ?? "Turn on"}</button>
* }
*/
function usePushNotifications() {
const signedIn = useRouteContext({
from: rootRouteId,
select: (context) => context.user !== null
});
const [settings, setSettings] = useState(null);
const [registration, setRegistration] = useState(null);
const [subscribed, setSubscribed] = useState(false);
const [permission, setPermission] = useState("default");
const [dismissedAt, setDismissedAt] = useState(null);
useEffect(() => {
if (process.env.NODE_ENV !== "production" || !("serviceWorker" in navigator)) return;
if (!signedIn) {
try {
localStorage.removeItem(DISMISSED_AT_KEY);
} catch {}
setDismissedAt(null);
setSettings(null);
setSubscribed(false);
return;
}
let cancelled = false;
(async () => {
const response = await globalThis.fetch(SETTINGS_PATH, { headers: { accept: "application/json" } });
if (!response.ok) return;
const parsed = settingsSchema.safeParse(await response.json());
if (!parsed.success || cancelled) return;
setDismissedAt(readDismissedAt());
setSettings(parsed.data);
if (!("PushManager" in window) || !("Notification" in window)) return;
setPermission(Notification.permission);
const registered = await navigator.serviceWorker.register(WORKER_PATH, { scope: "/" });
if (cancelled) return;
if (Notification.permission !== "granted") {
setRegistration(registered);
return;
}
const subscription = await registered.pushManager.getSubscription() ?? await registered.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: decodeBase64Url(parsed.data.vapidPublicKey)
});
if (cancelled) return;
setSubscribed(await sendSubscription("POST", subscription));
setRegistration(registered);
})().catch((error) => console.warn("[@softr/sdk] Could not set up push notifications:", error));
return () => {
cancelled = true;
};
}, [signedIn]);
useEffect(() => {
if (registration === null) return;
return listenToWorker();
}, [registration]);
const subscribe = useCallback(async () => {
if (registration === null || settings === null) return;
const granted = await Notification.requestPermission();
setPermission(granted);
if (granted !== "granted") return;
const subscription = await registration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: decodeBase64Url(settings.vapidPublicKey)
});
if (!await sendSubscription("POST", subscription)) {
await subscription.unsubscribe();
throw new Error("Could not turn on push notifications");
}
setSubscribed(true);
}, [registration, settings]);
const unsubscribe = useCallback(async () => {
const subscription = await registration?.pushManager.getSubscription();
if (!subscription) return;
await sendSubscription("DELETE", subscription);
await subscription.unsubscribe();
setSubscribed(false);
}, [registration]);
const dismiss = useCallback(() => {
const now = Date.now();
try {
localStorage.setItem(DISMISSED_AT_KEY, String(now));
} catch {}
setDismissedAt(now);
}, []);
if (settings === null) return { status: "unavailable" };
const platform = detectPlatform();
if (platform !== "desktop" ? !settings.mobileEnabled : !settings.desktopEnabled) return { status: "unavailable" };
const prompt = {
title: settings.permissionPrompt?.title ?? null,
message: settings.permissionPrompt?.message ?? null,
enableButtonLabel: settings.permissionPrompt?.enableButtonLabel ?? null
};
if (platform === "ios" && !isStandalone()) return {
status: "install-first",
prompt
};
if (registration === null) return { status: "unavailable" };
if (subscribed) return {
status: "subscribed",
unsubscribe
};
if (permission === "denied") return { status: "blocked" };
return {
status: "ask",
prompt,
dismissed: isDismissed(dismissedAt, settings.permissionPrompt?.skipDays ?? null),
subscribe,
dismiss
};
}
async function sendSubscription(method, subscription) {
return (await globalThis.fetch(SUBSCRIPTION_PATH, {
method,
headers: { "content-type": "application/json" },
body: JSON.stringify({ subscription: subscription.toJSON() })
})).ok;
}
/** A missing skip-days setting means a skipped prompt never comes back on its own. */
function isDismissed(dismissedAt, skipDays) {
if (dismissedAt === null) return false;
if (skipDays === null) return true;
return Date.now() - dismissedAt < Math.max(skipDays, 1) * 24 * 60 * 60 * 1e3;
}
function readDismissedAt() {
try {
const stored = Number(localStorage.getItem(DISMISSED_AT_KEY));
return Number.isFinite(stored) && stored > 0 ? stored : null;
} catch {
return null;
}
}
/**
* Answers the service worker, which routes a notification click to the
* installed app when it is open, and keeps the app icon's badge right.
*/
function listenToWorker() {
const worker = navigator.serviceWorker;
const standalone = isStandalone();
if (standalone) worker.controller?.postMessage({ type: "pwa-standalone-opened" });
const onMessage = (event) => {
if (event.data === "is-this-standalone") {
event.ports[0]?.postMessage(standalone ? "yes" : "no");
return;
}
if (event.data?.type === "softr-pwa-redirect" && typeof event.data.url === "string") {
const target = new URL(event.data.url, window.location.href);
if (target.origin === window.location.origin) window.location.assign(target.href);
}
};
const onVisible = () => {
if (document.visibilityState === "visible") worker.controller?.postMessage("reset-badge-count");
};
const onInstallOffered = () => worker.controller?.postMessage({ type: "pwa-uninstalled" });
worker.addEventListener("message", onMessage);
document.addEventListener("visibilitychange", onVisible);
window.addEventListener("beforeinstallprompt", onInstallOffered);
onVisible();
return () => {
worker.removeEventListener("message", onMessage);
document.removeEventListener("visibilitychange", onVisible);
window.removeEventListener("beforeinstallprompt", onInstallOffered);
};
}
function decodeBase64Url(value) {
const base64 = value.replace(/-/g, "+").replace(/_/g, "/").padEnd(Math.ceil(value.length / 4) * 4, "=");
const binary = atob(base64);
const bytes = new Uint8Array(binary.length);
for (let index = 0; index < binary.length; index++) bytes[index] = binary.charCodeAt(index);
return bytes;
}
//#endregion
export { pushMiddleware, usePushNotifications };