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.

171 lines (169 loc) • 7.14 kB
import { assert, requireDefined } from "./assertions.js"; import { asSignedOutVisitor } from "./auth/session.js"; import { readSoftrContext } from "./auth/context.js"; import { exportRecords } from "./datasource/record.js"; import { guardedPageOf } from "./route/route.js"; import { getRouterInstance } from "@tanstack/react-start"; //#region src/search-engines.ts /** The sitemap protocol's limit for one file. */ const MAX_ENTRIES = 5e4; /** How long a sitemap stays cached before the next request builds it again. */ const CACHE_SECONDS = 1440 * 60; /** App workers cannot use the default cache, so the sitemap has a named cache of its own. */ const CACHE_NAME = "softr-sitemap"; const TRAINING_CRAWLERS = [ ["Amazonbot"], ["Applebot-Extended"], ["Bytespider"], ["CCBot"], ["ClaudeBot"], ["Diffbot"], ["Google-Extended"], ["GPTBot"], ["omgili"], ["anthropic-ai"], ["Claude-Web"], ["cohere-ai"], ["MistralAI-Training"], ["meta-externalagent"], ["GoogleOther"], ["AwarioSmartBot", "AwarioRssBot"], ["Google-CloudVertexBot"], ["QualifiedBot"], ["Cotoyogi"], ["ICC-Crawler"], ["atlassian-bot"], ["FishBot"], ["BorderxBot"], ["NavuBot"], ["WARDBot"], ["magpie-crawler"], ["KimiBot"], ["CitibotSiteCrawler"] ]; /** * Answers `/robots.txt`: search engines may crawl the app, AI training crawlers * may not, and the `Sitemap:` line points to the app's `/sitemap.xml`. An * app's own `public/robots.txt` wins over this route. * * @example * // src/routes/robots[.]txt.ts * export const Route = createFileRoute("/robots.txt")({ * server: { handlers: { GET: robotsTxt() } }, * }) */ function robotsTxt() { return () => { const groups = [ "User-agent: *\nContent-Signal: search=yes,ai-train=no,use=reference\nAllow: /", ...TRAINING_CRAWLERS.map((agents) => `${agents.map((agent) => `User-agent: ${agent}`).join("\n")}\nDisallow: /`), `Sitemap: ${visitorOrigin()}/sitemap.xml` ]; return new Response(`${groups.join("\n\n")}\n`, { headers: { "Content-Type": "text/plain; charset=utf-8" } }); }; } /** * Answers `/sitemap.xml` with the app's public pages and one page per public * record. It reads the records as a signed-out visitor and keeps the file for * a day, so search engines get only public records and the datasource is read * at most once a day per region. A new publish starts a new file. * * Without `pages`, it lists each page that every visitor can open, from the * app's routes: a page whose `guardRoute` and those of its layouts admit * signed-out and signed-in visitors, with no path parameter, and that does not * turn `searchEngineIndexing` off. A page whose `beforeLoad` is not * `guardRoute` alone, such as one that calls `assertRouteAccess`, is left out. * So is a page whose `searchEngineIndexing` is a function, because the * sitemap cannot know what it gives for each record. * A record path is then listed only when its page passes the same check. * * @example * // src/routes/sitemap[.]xml.ts * export const Route = createFileRoute("/sitemap.xml")({ * server: { * handlers: { * GET: sitemapXml({ * records: [{ * query: bikesQuery, * path: (bike) => `/bikes/${bike.id}`, * lastModified: (bike) => bike.fields.updatedAt ?? bike.fields.createdAt, * }], * }), * }, * }, * }) */ function sitemapXml(sources) { return async () => { const origin = visitorOrigin(); const cache = typeof caches !== "undefined" ? await caches.open(CACHE_NAME) : null; const key = new Request(`${origin}/sitemap.xml?build=${typeof __SOFTR_BUILD_ID__ === "undefined" ? "dev" : __SOFTR_BUILD_ID__}`); const stored = await cache?.match(key); if (stored !== void 0) return new Response(stored.body, stored); let pages = sources.pages; let router = null; if (pages === void 0) { const routes = await getRouterInstance(); pages = Object.keys(routes.routesByPath).filter((path) => !/[$*]/.test(path) && opensToEveryone(routes, path)); router = routes; } const entries = pages.map((path) => ({ path })); for (const { query, path, lastModified } of sources.records ?? []) { if (entries.length >= MAX_ENTRIES) break; const { records } = await asSignedOutVisitor(async () => await exportRecords(query).limit(MAX_ENTRIES - entries.length)); for (const record of records) { const recordPath = path(record); if (router !== null && !opensToEveryone(router, recordPath)) continue; const changed = lastModified?.(record); const date = changed instanceof Date ? changed : typeof changed === "string" && changed !== "" ? new Date(changed) : void 0; entries.push({ path: recordPath, lastModified: date === void 0 || Number.isNaN(date.getTime()) ? void 0 : date.toISOString() }); } } const xml = `<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n${entries.slice(0, MAX_ENTRIES).map(({ path, lastModified }) => { assert(path.startsWith("/"), `A sitemap path starts with "/", got "${path}"`); return ` <url><loc>${(origin + path.toWellFormed().replace(/[^\x21-\x7e]+/g, encodeURI)).replace(/[&<>"']/g, (char) => `&#${char.charCodeAt(0)};`)}</loc>${lastModified === void 0 ? "" : `<lastmod>${lastModified}</lastmod>`}</url>`; }).join("\n")}\n</urlset>\n`; const response = new Response(xml, { headers: { "Content-Type": "application/xml; charset=utf-8", "Cache-Control": `max-age=${CACHE_SECONDS}` } }); if (cache !== null) await cache.put(key, response.clone()); return response; }; } /** The address the visitor opened the app at, as `softrAuthMiddleware` resolved it for this request. */ function visitorOrigin() { return requireDefined(readSoftrContext().origin, "softrAuthMiddleware sets the origin on every request"); } /** * True when `path` is a page that every visitor can open and search engines may list. Its route renders a page, and * each guard from the root down admits signed-out and signed-in visitors, with no custom group. The nearest page that * sets `searchEngineIndexing` sets it to `true`, or no page sets it. A function value is not known here, so it leaves the * page out. * * A `beforeLoad` that is not a guard checks access in a way this cannot read, so its page is left out. A missing page * is the safe mistake. */ function opensToEveryone(router, path) { const [branch, params, route] = router.getMatchedRoutes(path); if (route === void 0 || params["**"] !== void 0) return false; if (route.options.component === void 0 && route.lazyFn === void 0) return false; let indexing; for (const { isRoot, options } of branch) { const page = guardedPageOf(options.beforeLoad); if (page === void 0) { if (options.beforeLoad !== void 0 && !isRoot) return false; continue; } const { userGroupTypes, customGroups = [] } = page.visibility; const audiences = userGroupTypes; if (!audiences.includes("NON_LOGGED_IN_USERS") || !audiences.includes("LOGGED_IN_USERS") || customGroups.length > 0) return false; indexing = page.searchEngineIndexing ?? indexing; } return indexing === void 0 || indexing === true; } //#endregion export { robotsTxt, sitemapXml };