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.

298 lines (290 loc) • 12.6 kB
import { createMiddleware } from "@tanstack/react-start"; import { isNotFound, isRedirect } from "@tanstack/react-router"; //#region src/boot-error.ts /** * Catches errors thrown before the router renders, in request middleware or SSR * setup, where a route's `errorComponent` cannot reach. Without it the browser * gets a bare JSON 500 and the real message only reaches the terminal. * * Compose it as a dependency of the outermost request middleware, so that it * wraps everything registered after it. */ function bootErrorMiddleware() { return createMiddleware({ type: "request" }).server(async ({ next, handlerType }) => { try { return await next(); } catch (error) { if (handlerType === "serverFn" || error instanceof Response || isRedirect(error) || isNotFound(error)) throw error; console.error("[@softr/sdk] boot error:", error); return new Response(errorPage(error), { status: 500, headers: { "content-type": "text/html; charset=utf-8" } }); } }); } /** * Faults of the dev server rather than the app: a module graph swapped under a render already in * flight, so React's dispatcher or a split chunk belongs to a generation that is gone. The next * request reads the settled graph and succeeds, which is why these clear on their own — and why * showing one is worse than useless. The page invites the reader to copy it to the agent, and an * agent handed a phantom spends a repair round looking for it in code that is correct. */ const TRANSIENT = [/Cannot read properties of (?:null|undefined) \(reading 'use[A-Z]/, /Failed to fetch dynamically imported module/]; function isTransientBootError(message) { return TRANSIENT.some((pattern) => pattern.test(message)); } function errorPage(error) { if (process.env.NODE_ENV === "production") return page("Something went wrong", "This page couldn’t be shown. Try again in a moment, and if it keeps happening, reach out to the owner of this app.", { note: "If you are the owner, you can check what happened in Studio." }); const cause = error instanceof Error ? error.cause : void 0; const root = cause instanceof Error ? cause : error; const message = root instanceof Error ? root.message : String(root); const stack = root instanceof Error ? root.stack : void 0; return page("This app crashed", "The app stopped before it could start. The technical details below show where it failed and can be copied to the agent to help fix the issue.", { note: "These details are only shown because the app is running in development mode.", autoRetry: isTransientBootError(message), detail: `<pre class="message">${escapeHtml(message)}</pre>`, actions: stack ? `<button type="button" id="toggle" aria-expanded="true" aria-controls="panel"> <svg class="chevron" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m9 18 6-6-6-6"/></svg> Technical details </button>` : "", panel: stack ? `<div class="stack" id="panel"> <pre id="stack">${escapeHtml(stack)}</pre> <button type="button" id="copy" aria-label="Copy stack trace"> <svg class="copy" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect width="14" height="14" x="8" y="8" rx="2" ry="2"/><path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"/></svg> <svg class="check" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6 9 17l-5-5"/></svg> </button> </div> <script> const toggle = document.getElementById('toggle') const panel = document.getElementById('panel') const stack = document.getElementById('stack') const setOpen = (open) => { toggle.setAttribute('aria-expanded', String(open)) panel.hidden = !open } setOpen(false) toggle.addEventListener('click', () => { setOpen(toggle.getAttribute('aria-expanded') === 'false') }) const copyStack = async () => { try { await navigator.clipboard.writeText(stack.textContent) return true } catch { getSelection().selectAllChildren(stack) return document.execCommand('copy') } } document.getElementById('copy').addEventListener('click', async (event) => { const button = event.currentTarget if (!(await copyStack())) return button.dataset.copied = '' setTimeout(() => delete button.dataset.copied, 1500) }) <\/script>` : "" }); } function page(title, description, { note = "", detail = "", actions = "", panel = "", autoRetry = false } = {}) { return `<!doctype html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>${escapeHtml(title)}</title> <style> /* Mirrors the shadcn tokens the templates ship. Theme follows the OS here, because a stored choice needs the app to be running. */ :root { color-scheme: light dark; --background: oklch(1 0 0); --foreground: oklch(0.145 0 0); --card: oklch(1 0 0); --muted: oklch(0.97 0 0); --muted-foreground: oklch(0.556 0 0); --border: oklch(0.922 0 0); --input: oklch(0.922 0 0); --input-fill: oklch(1 0 0); --input-fill-hover: oklch(0.97 0 0); --primary: oklch(0.205 0 0); --primary-foreground: oklch(0.985 0 0); --destructive: oklch(0.577 0.245 27.325); --radius: 0.625rem; } @media (prefers-color-scheme: dark) { :root { --background: oklch(0.145 0 0); --foreground: oklch(0.985 0 0); --card: oklch(0.205 0 0); --muted: oklch(0.269 0 0); --muted-foreground: oklch(0.708 0 0); --border: oklch(1 0 0 / 10%); --input: oklch(1 0 0 / 15%); --input-fill: oklch(1 0 0 / 4.5%); --input-fill-hover: oklch(1 0 0 / 7.5%); --primary: oklch(0.922 0 0); --primary-foreground: oklch(0.205 0 0); --destructive: oklch(0.704 0.191 22.216); } } * { box-sizing: border-box } body { margin: 0; min-height: 100dvh; display: grid; place-items: center; /* Without an explicit minmax the column sizes to main's max-width and overflows narrow viewports. */ grid-template-columns: minmax(0, 1fr); padding: 1.5rem; background: var(--background); color: var(--foreground); font: 0.875rem/1.5 Inter, ui-sans-serif, system-ui, sans-serif; overflow-wrap: anywhere; } main { width: 100%; max-width: 36rem; display: flex; flex-direction: column; gap: 1.25rem; padding: 1.5rem; border-radius: calc(var(--radius) + 4px); background: var(--card); box-shadow: 0 0 0 1px color-mix(in oklch, var(--foreground) 10%, transparent); } .alert { display: flex; align-items: center; justify-content: center; width: 2.5rem; height: 2.5rem; border-radius: var(--radius); background: color-mix(in oklch, var(--destructive) 12%, transparent); color: var(--destructive); } .alert svg { width: 1.25rem; height: 1.25rem } h1 { margin: 0; font-size: 1rem; font-weight: 500; line-height: 1.375 } p { margin: 0.375rem 0 0; color: var(--muted-foreground) } p.note { margin-top: 0.75rem; opacity: 0.65 } pre { margin: 0; padding: 0.75rem; border-radius: var(--radius); background: var(--muted); font: 0.75rem/1.6 ui-monospace, SFMono-Regular, Menlo, monospace; max-height: 16rem; overflow: auto; } pre.message { font-size: 0.8125rem; white-space: pre-wrap } .actions { display: flex; flex-wrap: wrap; gap: 0.5rem } .actions button { display: inline-flex; align-items: center; gap: 0.375rem; height: 2rem; padding: 0 0.75rem; border-radius: var(--radius); font: inherit; font-weight: 500; cursor: pointer; user-select: none; } .actions button svg { width: 0.875rem; height: 0.875rem } #toggle { padding-left: 0.5rem; border: 1px solid var(--input); background: var(--input-fill); color: inherit; } #toggle:hover { background: var(--input-fill-hover) } .chevron { transition: transform 150ms } #toggle[aria-expanded='true'] .chevron { transform: rotate(90deg) } .stack { position: relative } .stack pre { padding-right: 2.75rem } #copy { position: absolute; top: 0.375rem; right: 0.375rem; display: inline-flex; align-items: center; justify-content: center; width: 1.75rem; height: 1.75rem; padding: 0; /* Opaque, so the stack trace underneath never shows through the icon. */ border: 1px solid var(--input); border-radius: calc(var(--radius) - 2px); background: var(--card); color: var(--muted-foreground); cursor: pointer; } #copy:hover { background: color-mix(in oklch, var(--card), var(--foreground) 6%); color: var(--foreground); } #copy svg { width: 0.875rem; height: 0.875rem } #copy .check, #copy[data-copied] .copy { display: none } #copy[data-copied] .check { display: block } .retry { border: 1px solid transparent; background: var(--primary); color: var(--primary-foreground); } /* Mixed with the card rather than faded, so it stays opaque. */ .retry:hover { background: color-mix(in oklch, var(--primary) 80%, var(--card)) } </style> </head> <body> <main${autoRetry ? " hidden" : ""}> <div class="alert"> <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3"/><path d="M12 9v4"/><path d="M12 17h.01"/></svg> </div> <div> <h1>${escapeHtml(title)}</h1> <p>${escapeHtml(description)}</p> ${note ? `<p class="note">${escapeHtml(note)}</p>` : ""} </div> ${detail} <div class="actions"> <button type="button" class="retry" onclick="location.reload()"> <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"/><path d="M21 3v5h-5"/><path d="M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"/><path d="M8 16H3v5"/></svg> Try again </button> ${actions} </div> ${panel} </main> ${autoRetry ? RETRY_SCRIPT : ""} </body> </html>`; } /** * One reload, then the page reveals itself. The reload is what the reader would have done by hand, * so a fault that clears is never seen; a fault that survives it shows the same page it always did. * Session storage is what remembers the attempt, and a preview frame may refuse it — then there is * no way to count, and the honest move is to show the error rather than risk reloading forever. */ const RETRY_SCRIPT = `<noscript><style>main[hidden] { display: flex !important }</style></noscript> <script> (() => { const KEY = 'softr:boot-retry' const reveal = () => { document.querySelector('main').hidden = false } let store = null try { store = sessionStorage } catch { /* blocked in this frame */ } if (!store) return reveal() const now = Date.now() if (now - Number(store.getItem(KEY) ?? 0) < 15000) { store.removeItem(KEY) return reveal() } store.setItem(KEY, String(now)) // A beat, so the reload lands after the dev server has finished rebuilding rather than during. setTimeout(() => location.reload(), 500) })() <\/script>`; function escapeHtml(value) { return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;"); } //#endregion export { bootErrorMiddleware };