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.

415 lines (413 loc) • 14.9 kB
import { assert, requireDefined } from "../assertions.js"; import { choiceEntries, fieldTypeLiteral, isWritable, linkedDatasource, option, readExample, resolvedShape, scalarExample, underlyingType } from "./datasource-types.js"; //#region src/codegen/datasource-docs.ts const DOC_NOTE = "> This document is generated automatically when a change is made in the datasource."; const INDEX_NOTE = "> These documents are generated automatically when a change is made in a datasource."; function renderDatasourceDoc(datasource, context) { return [ `# ${datasourceLabel(datasource)}`, "", ...summary(datasource, context), "", DOC_NOTE, "", "## Field reference", "", ...orderedFields(datasource).flatMap((field) => [...renderField(field, datasource, context), ""]), ...renderExamples(datasource, context.datasources) ].join("\n"); } function renderUserPropertiesDoc(users, context) { const aliases = Object.entries(users.properties); assert(aliases.length > 0, "Expected user properties to document, but got none"); const [first] = requireDefined(aliases[0]); const registered = linkedDatasource(users.tableId, context.datasources); const types = /* @__PURE__ */ new Set(); const sampled = aliases.filter(([, field]) => { const type = fieldTypeLiteral(field); if (types.has(type)) return false; types.add(type); return true; }); return [ "# User properties", "", `Users datasource: ${displayName(users.name) || users.tableId}` + (registered === void 0 ? "" : ` \nRegistered as: [${datasourceLabel(registered)}](./datasources/${requireDefined(context.fileNames.get(registered.id))}) (${registered.id})`), "", "> This document is generated automatically when softr.json's `user.properties` or the users table changes.", "", "Each alias below is declared in softr.json under `user.properties`, and read as `user.properties.<alias>`.", "", "## Field reference", "", ...aliases.flatMap(([alias, field]) => { const linkedId = option(field.options, "linkedTableId"); const linked = typeof linkedId === "string" ? linkedDatasource(linkedId, context.datasources) : void 0; return [ `### ${alias}`, "", `- Field: ${displayName(field.name)}`, `- ID: ${field.id}`, `- Type: ${fieldTypeLiteral(field).slice(1, -1)}`, ...optionLines(field), ...choiceLines(field), ...typeof linkedId !== "string" ? [] : linked === void 0 ? [`- Links to: ${linkedId}, not registered`] : [`- Links to: [${datasourceLabel(linked)}](./datasources/${requireDefined(context.fileNames.get(linked.id))}) (${linked.id})`], "" ]; }), "## Read shape", "", "In a component:", "", "```tsx", "import { useCurrentUser } from '@softr/sdk'", "", "const user = useCurrentUser()", "if (user === null) return null", "", ...sampled.map(([alias, field]) => `user.properties.${alias} // ${fieldTypeLiteral(field).slice(1, -1)}`), "```", "", "In a route's `beforeLoad`, to send a visitor elsewhere. It guards navigation only, not data:", "", "```tsx", "import { createFileRoute, redirect } from '@tanstack/react-router'", "import { assertRouteAccess, definePage, pageHead } from '@softr/sdk'", "", "const pageSettings = definePage({ visibility: { userGroupTypes: ['LOGGED_IN_USERS'] }, title: 'Example' })", "", "export const Route = createFileRoute('/example')({", " beforeLoad: (opts) => {", " assertRouteAccess(pageSettings, opts)", ` if (opts.context.user.properties.${first} == null) throw redirect({ to: '/' })`, " },", " head: pageHead(pageSettings),", "})", "```", "", "In a server function, called from a route's `loader`. The handler checks the visitor itself:", "", "```tsx", "import { createFileRoute } from '@tanstack/react-router'", "import { createServerFn } from '@tanstack/react-start'", "import { definePage, guardRoute, pageHead } from '@softr/sdk'", "", `const get${pascalCase(first)} = createServerFn().handler(async ({ context }) => {`, " if (!context.user) throw new Error('Not signed in')", ` return context.user.properties.${first}`, "})", "", "const pageSettings = definePage({ visibility: { userGroupTypes: ['LOGGED_IN_USERS'] }, title: 'Example' })", "", "export const Route = createFileRoute('/example')({", " beforeLoad: guardRoute(pageSettings),", ` loader: () => get${pascalCase(first)}(),`, " head: pageHead(pageSettings),", " component: Example,", "})", "", "function Example() {", ` const ${first} = Route.useLoaderData()`, " // ...", "}", "```", "" ].join("\n"); } /** Two trailing spaces are a markdown hard break, which keeps the block one paragraph. */ function summary(datasource, context) { const lines = [`Datasource ID: ${datasource.id}`]; const related = relatedLinks(datasource, context); if (related.length > 0) { const label = related.length === 1 ? "datasource" : "datasources"; lines.push(`Related ${label}: ${related.join(", ")}`); } return lines.map((line, index) => index === lines.length - 1 ? line : `${line} `); } function relatedLinks(datasource, context) { const seen = /* @__PURE__ */ new Set(); const links = []; for (const field of datasource.fields) { const linkedId = option(field.options, "linkedTableId"); if (typeof linkedId !== "string" || seen.has(linkedId)) continue; seen.add(linkedId); const linked = linkedDatasource(linkedId, context.datasources); if (linked === void 0 || linked.id === datasource.id) continue; links.push(docLink(linked, context)); } return links; } function docLink(datasource, context) { const file = requireDefined(context.fileNames.get(datasource.id), `No doc file name for datasource ${datasource.id}`); return `[${datasourceLabel(datasource)}](./${file})`; } function renderDatasourceIndex(datasources, context) { const heading = [ "# Datasources", "", INDEX_NOTE, "" ]; if (datasources.length === 0) return [ ...heading, "This app has no registered datasources.", "" ].join("\n"); return [ ...heading, "Datasources available in this app:", "", ...datasources.map((datasource) => { const file = requireDefined(context.fileNames.get(datasource.id), `No doc file name for datasource ${datasource.id}`); return `- ${datasourceLabel(datasource)} (${datasource.id}), [${file}](./${file})`; }), "" ].join("\n"); } function orderedFields(datasource) { const primary = datasource.fields.filter((field) => field.id === datasource.primaryFieldId); const rest = datasource.fields.filter((field) => field.id !== datasource.primaryFieldId); return [...primary, ...rest]; } function renderField(field, datasource, context) { return [ displayName(field.name), "", ...detail(field, datasource, context) ]; } /** The options that change what a value means or what a valid one looks like, and no others. */ const DETAILED_OPTIONS = [ { key: "isoCode", label: "Currency" }, { key: "precision", label: "Precision" }, { key: "min", label: "Min" }, { key: "max", label: "Max" }, { key: "format", label: "Format" } ]; function detail(field, datasource, context) { const lines = [`- ID: ${field.id}`, `- Type: ${fieldTypeLiteral(field).slice(1, -1)}`]; if (field.id === datasource.primaryFieldId) lines.push("- Primary field"); const chain = underlyingType(field); if (chain.includes("->")) lines.push(`- Resolves: ${chain}`); lines.push(...optionLines(field)); lines.push(...choiceLines(field)); lines.push(...linkLine(field, context)); const applied = flags(field); if (applied.length > 0) lines.push(`- Flags: ${applied.join(", ")}`); if (field.defaultValue !== null && field.defaultValue !== void 0) lines.push(`- Default: ${code(JSON.stringify(field.defaultValue))}`); lines.push(...formulaLines(field)); lines.push(`- Example: ${code(readValueExample(field, context.datasources))}`); return lines; } function flags(field) { const applied = []; if (field.required) applied.push("required"); if (!isWritable(field)) applied.push("readonly"); if (field.createOnly) applied.push("createOnly"); if (field.aiOnly === true) applied.push("aiOnly"); return applied; } function optionLines(field) { const { options } = resolvedShape(field); return DETAILED_OPTIONS.flatMap(({ key, label }) => { const value = option(options, key); if (value === null || value === void 0) return []; assert(typeof value !== "object", `Option ${key} on field ${field.id} is not a scalar`); return [`- ${label}: ${String(value)}`]; }); } function linkLine(field, context) { const linkedId = option(field.options, "linkedTableId"); if (typeof linkedId !== "string") return []; const linked = linkedDatasource(linkedId, context.datasources); if (linked === void 0) return [`- Links to: ${linkedId}, not registered`]; return [`- Links to: ${docLink(linked, context)} (${linked.id})`]; } function choiceLines(field) { const choices = choiceEntries(resolvedShape(field).options); if (choices === null) return []; return ["- Choices:", ...choices.map(({ id, label }) => ` - ${id} ${displayName(label)}`)]; } function formulaLines(field) { const formula = option(field.options, "formula"); if (typeof formula !== "string" || formula.includes("```")) return []; return [ "- Formula:", " ```", ...formula.split("\n").map((line) => ` ${line}`), " ```" ]; } function exampleFieldKeys(datasource) { const keys = /* @__PURE__ */ new Map(); const used = /* @__PURE__ */ new Set(); for (const field of datasource.fields) { const base = camelCase(field.name) || camelCase(field.id) || "field"; let key = base; let suffix = 1; while (used.has(key)) { suffix += 1; key = `${base}${suffix}`; } used.add(key); keys.set(field.id, key); } return keys; } function renderExamples(datasource, datasources) { const keys = exampleFieldKeys(datasource); const keyOf = (field) => requireDefined(keys.get(field.id), `No example key for field ${field.id} on datasource ${datasource.id}`); const queryId = camelCase(datasource.name) || camelCase(datasource.id); assert(queryId !== "", `Datasource ${datasource.id} has no usable name`); const name = pascalCase(datasource.name) || pascalCase(datasource.id); const sampled = exampleFields(datasource); const read = [ "## Read shape", "", "```ts", "import { createServerFn } from '@tanstack/react-start'", "import { defineQuery } from '@softr/sdk'", "import { ds } from '@softr/sdk/server'", "", `const ${queryId} = defineQuery({`, ` id: ${quoted(queryId)},`, ` datasourceId: ${quoted(datasource.id)},`, " fields: {", ...sampled.map((field) => ` ${keyOf(field)}: ${quoted(field.id)}, // ${fieldTypeLiteral(field).slice(1, -1)}`), " },", " permissions: { userGroupTypes: ['NON_LOGGED_IN_USERS', 'LOGGED_IN_USERS'] },", "})", "", `const list${name} = createServerFn().handler(async () => {`, ` return await ds.list(${queryId})`, "})", "```", "", "```ts", "const fields = {", ...sampled.map((field) => ` ${keyOf(field)}: ${readValueExample(field, datasources)},`), "}", "```" ]; const writable = sampled.filter(isWritableExample); if (writable.length === 0) return [...read, ""]; const mutationId = `create${name}`; const write = [ "## Write shape", "", "```ts", "import { createServerFn } from '@tanstack/react-start'", "import { defineMutation } from '@softr/sdk'", "import { ds } from '@softr/sdk/server'", "", `const ${mutationId} = defineMutation({`, ` id: ${quoted(mutationId)},`, ` datasourceId: ${quoted(datasource.id)},`, " operation: 'create',", " fields: {", ...writable.map((field) => ` ${keyOf(field)}: ${quoted(field.id)},`), " },", " permissions: { userGroupTypes: ['LOGGED_IN_USERS'] },", "})", "", `const add${name} = createServerFn({ method: 'POST' }).handler(async () =>`, ` ds.create(${mutationId}, {`, " data: {", ...writable.map((field) => ` ${keyOf(field)}: ${writeValueExample(field)},`), " },", " }),", ")", "```", "" ]; return [ ...read, "", ...write ]; } /** * The first field of every type the datasource has, because two fields of one type show one * shape. `SELECT` and `SELECT[]` are two types, so both appear, and `orderedFields` puts the * primary field first, so it is always the first of its own type. */ function exampleFields(datasource) { const types = /* @__PURE__ */ new Set(); return orderedFields(datasource).filter((field) => { const type = fieldTypeLiteral(field); if (types.has(type)) return false; types.add(type); return true; }); } function isWritableExample(field) { return isWritable(field) && field.aiOnly !== true; } function readValueExample(field, datasources) { const choice = firstChoice(field); if (choice !== null) return exampleLiteral(field, `{ id: ${quoted(choice.id)}, label: ${quoted(choice.label)} }`); return exampleLiteral(field, readExample(field, datasources)); } function writeValueExample(field) { const choice = firstChoice(field); if (choice !== null) return exampleLiteral(field, `{ id: ${quoted(choice.id)} }`); return exampleLiteral(field, scalarExample(field)); } function datasourceLabel(datasource) { return displayName(datasource.name) || datasource.id; } /** A wider delimiter, because a value carrying a label can carry a backtick of its own. */ function code(value) { return value.includes("`") ? `\`\` ${value} \`\`` : `\`${value}\``; } /** Names and labels arrive verbatim from the API, where a line break forges a row. */ function displayName(name) { return name.replace(/\s+/g, " ").trim(); } function quoted(value) { return `'${value.replace(/\\/g, "\\\\").replace(/'/g, "\\'").replace(/\n/g, "\\n").replace(/\r/g, "\\r")}'`; } function exampleLiteral(field, scalar) { if (field.allowMultipleEntries) return scalar === null ? "[]" : `[${scalar}]`; return scalar ?? "null"; } /** * A choice id the datasource declares, which is what the generated read type accepts. Read from * the resolved shape, because the read type resolves a computed field the same way. */ function firstChoice(field) { const shape = resolvedShape(field); if (shape.type !== "SELECT") return null; const choices = choiceEntries(shape.options); return choices === null ? null : choices[0]; } function camelCase(value) { const parts = words(value); if (parts.length === 0) return ""; const joined = parts.map((word, index) => index === 0 ? word[0].toLowerCase() + word.slice(1) : word[0].toUpperCase() + word.slice(1)).join(""); return /^[0-9]/.test(joined) ? `f${joined}` : joined; } function pascalCase(value) { const joined = words(value).map((word) => word[0].toUpperCase() + word.slice(1)).join(""); return /^[0-9]/.test(joined) ? `F${joined}` : joined; } function words(value) { return value.split(/[^A-Za-z0-9]+/).filter((word) => word.length > 0); } //#endregion export { DOC_NOTE, renderDatasourceDoc, renderDatasourceIndex, renderUserPropertiesDoc };