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.

239 lines (237 loc) • 8.19 kB
import { logger } from "./logger.js"; import { softrApiUrl } from "./softr-api.js"; import { fetch } from "./fetch.js"; import { sessionConfig } from "./auth/config.js"; import { readCached } from "./cache.js"; import { z } from "zod"; import { Fragment, createElement, useEffect, useMemo, useState, useSyncExternalStore } from "react"; import { createMiddleware } from "@tanstack/react-start"; //#region src/pwa.ts const MANIFEST_PATH = "/manifest.webmanifest"; const ICON_PATH = "/apple-touch-icon.png"; const INSTALL_PATH = "/_softr/pwa.json"; const STANDALONE_QUERY = "(display-mode: standalone)"; const TTL_MS = 6e4; const CACHE_CONTROL = "public, max-age=60"; const pwaSchema = z.object({ manifest: z.record(z.string(), z.unknown()), install: z.object({ name: z.string(), iconUrl: z.string() }), startupImages: z.array(z.object({ media: z.string(), href: z.string() })).default([]) }); const iosHeadSchema = pwaSchema.pick({ startupImages: true }).extend({ name: z.string() }); let cached; /** The app's PWA, or `null` when it is not installable right now. */ function readPwa() { return readCached("the PWA settings", TTL_MS, () => cached, (entry) => cached = entry, fetchPwa); } async function fetchPwa() { const { applicationId } = sessionConfig(); const response = await fetch(`${softrApiUrl("SOFTR_PLATFORM_API_URL")}/v1/vibe/applications/${applicationId}/pwa`, { headers: { accept: "application/json" } }); if (response.status === 404) return null; if (!response.ok) throw new Error(`The platform answered ${response.status}`); return pwaSchema.parse(await response.json()); } /** * Serves the app's web app manifest, its home screen icon, and what an install * button needs to know, from the app's own origin. Every other request passes * through untouched. * * Answers 404, never an error page, when the app is not installable: a browser * silently drops a manifest it cannot parse, so a 500 there would be invisible. */ function pwaMiddleware() { return createMiddleware({ type: "request" }).server(async ({ next, pathname }) => { if (pathname !== MANIFEST_PATH && pathname !== ICON_PATH && pathname !== INSTALL_PATH) return next(); const pwa = await readPwa(); if (pwa === null) return new Response(null, { status: 404 }); if (pathname === MANIFEST_PATH) return new Response(JSON.stringify(pwa.manifest), { headers: { "content-type": "application/manifest+json", "cache-control": CACHE_CONTROL } }); if (pathname === INSTALL_PATH) return Response.json({ ...pwa.install, startupImages: pwa.startupImages }, { headers: { "cache-control": CACHE_CONTROL } }); try { const iconResponse = await fetch(pwa.install.iconUrl); if (!iconResponse.ok) return new Response(null, { status: 404 }); return new Response(iconResponse.body, { headers: { "content-type": "image/png", "cache-control": CACHE_CONTROL } }); } catch (error) { logger.warn("Could not fetch the PWA icon:", error); return new Response(null, { status: 404 }); } }); } let pendingInstallInfo; /** * What `/_softr/pwa.json` answers, or `null` when it does not. Callers that ask * while a request is in flight share it; the next caller after it settles asks again. */ function fetchInstallInfo() { pendingInstallInfo ??= globalThis.fetch(INSTALL_PATH, { headers: { accept: "application/json" } }).then((response) => response.ok ? response.json() : null).catch(() => null).finally(() => { pendingInstallInfo = void 0; }); return pendingInstallInfo; } /** * The tags that make the app installable: its manifest, its home screen icon, * and, while the app is installable, the name and launch screens iOS shows. * Render it once, in `<head>` in the root route's `RootDocument`. * * @example * function RootDocument({ children }: { children: React.ReactNode }) { * return ( * <html lang="en"> * <head> * <HeadContent /> * <SoftrPwaHead /> * </head> * <body> * {children} * <Scripts /> * </body> * </html> * ) * } */ function SoftrPwaHead() { const [iosHead, setIosHead] = useState(null); useEffect(() => { if (detectPlatform() !== "ios") return; let cancelled = false; fetchInstallInfo().then((installInfo) => { const parsed = iosHeadSchema.safeParse(installInfo); if (!parsed.success || cancelled) return; setIosHead(parsed.data); }); return () => { cancelled = true; }; }, []); return createElement(Fragment, null, createElement("link", { rel: "manifest", href: MANIFEST_PATH }), createElement("link", { rel: "apple-touch-icon", href: ICON_PATH }), ...iosHead === null ? [] : [createElement("meta", { key: "capable", name: "apple-mobile-web-app-capable", content: "yes" }), createElement("meta", { key: "title", name: "apple-mobile-web-app-title", content: iosHead.name })], ...(iosHead?.startupImages ?? []).map((image) => createElement("link", { key: image.href, rel: "apple-touch-startup-image", media: image.media, href: image.href }))); } function isInstallPromptEvent(event) { return "prompt" in event && typeof event.prompt === "function" && "userChoice" in event; } let offeredPrompt = null; const offerListeners = /* @__PURE__ */ new Set(); function setOfferedPrompt(next) { offeredPrompt = next; for (const listener of offerListeners) listener(); } if (typeof window !== "undefined") { window.addEventListener("beforeinstallprompt", (event) => { if (!isInstallPromptEvent(event)) return; setOfferedPrompt(event); }); window.addEventListener("appinstalled", () => setOfferedPrompt(null)); } const installSchema = pwaSchema.shape.install; /** * Whether to offer installing the app, and on which platform. Render an * install button only while this says `available`: it is unavailable while * loading, when the builder has not turned the PWA on, when Softr has switched * it off, and when the app already runs installed. * * @example * function InstallButton() { * const install = usePwaInstall() * if (!install.available) return null * return ( * <button * onClick={() => * install.install * ? install.install().catch(() => openSteps(install.platform)) * : openSteps(install.platform) * } * > * Install {install.name} * </button> * ) * } */ function usePwaInstall() { const [install, setInstall] = useState({ available: false }); const offered = useSyncExternalStore((listener) => { offerListeners.add(listener); return () => offerListeners.delete(listener); }, () => offeredPrompt, () => null); useEffect(() => { if (isStandalone()) return; let cancelled = false; const standaloneQuery = window.matchMedia(STANDALONE_QUERY); const hide = () => { cancelled = true; setInstall({ available: false }); }; const hideOnceStandalone = () => { if (standaloneQuery.matches) hide(); }; standaloneQuery.addEventListener("change", hideOnceStandalone); window.addEventListener("appinstalled", hide); fetchInstallInfo().then((installInfo) => { const parsed = installSchema.safeParse(installInfo); if (!parsed.success || cancelled) return; setInstall({ available: true, platform: detectPlatform(), ...parsed.data }); }); return () => { cancelled = true; standaloneQuery.removeEventListener("change", hideOnceStandalone); window.removeEventListener("appinstalled", hide); }; }, []); return useMemo(() => { if (!install.available || offered === null) return install; return { ...install, install: async () => { await offered.prompt(); setOfferedPrompt(null); return (await offered.userChoice).outcome; } }; }, [install, offered]); } function detectPlatform() { const userAgent = navigator.userAgent; if (/iPhone|iPad|iPod/.test(userAgent) || /Macintosh/.test(userAgent) && navigator.maxTouchPoints > 1) return "ios"; if (/Android/.test(userAgent)) return "android"; return "desktop"; } function isStandalone() { return window.matchMedia(STANDALONE_QUERY).matches || "standalone" in navigator && navigator.standalone === true; } //#endregion export { SoftrPwaHead, detectPlatform, isStandalone, pwaMiddleware, usePwaInstall };