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.

499 lines (497 loc) • 20.9 kB
import { panic } from "../assertions.js"; //#region src/codegen/datasource-types.ts /** * `LOCATION` is in the field type enum and nowhere else. It has no subtype on the record model * and no conversion branch, so the API drops a write to one without an error. */ const UNWRITABLE_TYPES = new Set(["LOCATION"]); /** * A `readonly` field is dropped from a write on every path, silently rather than with an * error, so leaving one out of the write type costs nothing and says so at the call site. */ function isWritable(field) { return !field.readonly && !UNWRITABLE_TYPES.has(field.type); } /** * Renders a write type, a create, an update and a read type per datasource, then * `SoftrDatasources`. * * The caller wraps it. Pass the whole project: a linked record resolves against the other * datasources in `datasources`. * * Only the interface belongs inside `declare module "@softr/sdk"`. The per-datasource types go * at the file's top level, because an augmentation merges an interface but collides on a type * alias, and an alias declared there becomes an SDK export that a future SDK release would * duplicate. * * The output references value aliases it does not define: `IsoDate`, `IsoDateTime`, * `IsoTime`, `EmailAddress`, `PhoneNumber`, `HttpUrl`, `LinkedRecord`, `LinkedRecordInput`, * `WorkspaceUser`, `Attachment`, `AttachmentInput`, `SelectChoice` and `SelectChoiceInput`. They are the same for every project, so they belong * in the SDK, which does not export them yet. Until it does, the caller declares them at the * top of the generated file. An augmentation body cannot pick them up from the module it * augments: unqualified names there do not resolve against the augmented module's scope. */ function renderDatasourceTypes(datasources) { const context = { datasources: byId(datasources), names: typeNames(datasources) }; return { datasourceTypes: datasources.map((datasource) => renderDatasource(datasource, context)).join("\n\n"), interfaces: renderRegistry(datasources, context) }; } function byId(datasources) { return new Map(datasources.map((datasource) => [datasource.id, datasource])); } /** * The registered datasource a `LINKED_RECORD`'s `linkedTableId` names. That id is the underlying * table's own id, kept as `tableId`, while `datasources` is keyed by registration id. The * registration id is the fallback, in case a link names that one instead. */ function linkedDatasource(linkedTableId, datasources) { for (const datasource of datasources.values()) if (datasource.tableId === linkedTableId) return datasource; return datasources.get(linkedTableId); } /** * A TypeScript name per datasource, derived from its own name, with the id standing in wherever * the name cannot: two datasources can share a name, and a name can be blank or hold nothing an * identifier can keep. The id is unique by construction, so it settles both. */ function typeNames(datasources) { const bases = /* @__PURE__ */ new Map(); const seen = /* @__PURE__ */ new Map(); for (const datasource of datasources) { const base = pascalCase(datasource.name) || pascalCase(datasource.id); if (base === "") panic(`Datasource ${datasource.id} has no usable name`); bases.set(datasource.id, base); seen.set(base, (seen.get(base) ?? 0) + 1); } const names = /* @__PURE__ */ new Map(); for (const [id, base] of bases) names.set(id, seen.get(base) === 1 ? base : `${base}_${pascalCase(id)}`); return names; } /** Empty when the value holds nothing an identifier can keep. */ function pascalCase(value) { const joined = value.split(/[^A-Za-z0-9]+/).filter((word) => word.length > 0).map((word) => word[0].toUpperCase() + word.slice(1)).join(""); return /^[0-9]/.test(joined) ? `DS${joined}` : joined; } function renderDatasource(datasource, context) { const name = nameOf(datasource.id, context); const write = datasource.fields.filter(isWritable).map((field) => indent(doc(fieldDoc(field, datasource, context, "write")) + "\n" + writeMember(field, context))).join("\n\n"); const record = datasource.fields.map((field) => indent(doc(fieldDoc(field, datasource, context, "read")) + "\n" + readMember(field, context))).join("\n\n"); return [ `type ${name}Write = {`, write, "};", "", `type ${name}Create = ${name}Write;`, "", `type ${name}Update = ${name}Write;`, "", `type ${name}Read = {`, record, "};" ].join("\n"); } /** * A write is optional and nullable throughout. Optional because the API requires no field on a * create and merges an update key by key; nullable because `null` is how an update clears a * field. On a create `null` reaches for the field's default instead. */ function writeMember(field, context) { return `${key(field.id)}?:${spaced(orNull(multiple(field, writeValue(field, context))))};`; } /** A union that broke onto its own lines already starts with a newline. */ function spaced(value) { return value.startsWith("\n") ? value : ` ${value}`; } /** * A read is present and nullable. Every field carries a value, `null` when it is empty, so * there is nothing to make optional. * * The exceptions are the two the API fills in instead of emptying: a multiple field is an * array, empty rather than null, and a `CHECKBOX` is a boolean, false rather than null. */ function readMember(field, context) { const nullable = !field.allowMultipleEntries && field.type !== "CHECKBOX"; const value = multiple(field, readValue(field, context)); return `${key(field.id)}:${spaced(nullable ? orNull(value) : value)};`; } /** Keeps a union that already broke onto its own lines from growing a trailing member. */ function orNull(value) { return value.startsWith("\n") ? `${value}\n | null` : `${value} | null`; } function multiple(field, value) { if (!field.allowMultipleEntries) return value; return value.startsWith("\n") ? `Array<${value}\n>` : `Array<${value}>`; } /** * The value a field accepts on a write. * * The API takes more than this. A bare string stands in for a `SELECT` or a `LINKED_RECORD` * and becomes its own id, a numeric string parses as a number, and an array sent to a * single-entry field keeps only its first element with no error. Each of those loses data * quietly, so the type admits only the shape that cannot. */ function writeValue(shape, context) { switch (shape.type) { case "SINGLE_LINE_TEXT": case "LONG_TEXT": case "ADDRESS": case "BUTTON": case "RECORD_ID": case "CREATED_BY": case "UPDATED_BY": return "string"; case "URL": return "HttpUrl"; case "EMAIL": return "EmailAddress"; case "PHONE": return "PhoneNumber"; case "CHECKBOX": return "boolean"; case "NUMBER": case "CURRENCY": case "PERCENT": case "PROGRESS": case "DURATION": case "RATING": case "COUNT": case "AUTONUMBER": return "number"; case "DATETIME": return datePrecision(shape.options) === "DATE" ? "IsoDate" : "IsoDateTime"; case "CREATED_AT": case "UPDATED_AT": return "IsoDateTime"; case "TIME": return "IsoTime"; case "DATE_RANGE": return "{ from: IsoDate; to: IsoDate }"; case "SELECT": return "SelectChoiceInput"; case "ATTACHMENT": return "AttachmentInput"; case "LINKED_RECORD": return "LinkedRecordInput"; case "USER": return "WorkspaceUser"; case "FORMULA": case "LOOKUP": case "ROLLUP": return writeValue(returnedShape(shape), context); default: return panic(`${shape.type} has no write shape`); } } /** A read differs from a write only where the API returns a different shape than it takes. */ function readValue(shape, context) { switch (shape.type) { case "ATTACHMENT": return "Attachment"; case "SELECT": return selectValue(shape.options); case "LINKED_RECORD": return linkedRecord(shape.options, context); case "LOCATION": return "string"; case "FORMULA": case "LOOKUP": case "ROLLUP": return readValue(returnedShape(shape), context); default: return writeValue(shape, context); } } /** * A computed field is typed by what it returns, which the metadata nests under `options`. * The nesting is recursive on the wire, so a lookup through a lookup resolves. * * `FORMULA`, `LOOKUP` and `ROLLUP` all declare `returnedField` as required, so a missing one * is malformed metadata. `options` is absent for a returned type that has none. * * Whether the value is an array follows `allowMultipleEntries` like every other type, so the * shape resolved here is the scalar one. */ function returnedShape(shape) { const returned = option(shape.options, "returnedField"); if (!isValueShape(returned)) return panic(`${shape.type} has no returnedField`); return { type: returned.type, options: returned.options ?? null }; } /** A choice reads back with the label the field holds for it, so each member is one pair. */ function selectValue(options) { const choices = choiceEntries(options); if (choices === null) return "SelectChoice"; return union(choices.map(({ id, label }) => `{ id: ${quote(id)}; label: ${quote(label)} }`)); } function datePrecision(options) { const precision = option(options, "precision"); return typeof precision === "string" ? precision : null; } function choiceEntries(options) { const choices = option(options, "choices"); if (!Array.isArray(choices)) return null; const entries = []; for (const choice of choices) { if (typeof choice !== "object" || choice === null) continue; const { id, label } = choice; if (typeof id === "string" && typeof label === "string") entries.push({ id, label }); } return entries.length === 0 ? null : entries; } /** Wraps a union onto its own lines once there is more than one member, so it stays legible. */ function union(members) { if (members.length === 1) return members[0]; return "\n" + members.map((member) => ` | ${member}`).join("\n"); } function linkedRecord(options, context) { const linkedTableId = option(options, "linkedTableId"); if (typeof linkedTableId !== "string") return "LinkedRecord"; const linked = linkedDatasource(linkedTableId, context.datasources); if (linked === void 0 || linked.primaryFieldId === "") return "LinkedRecord"; return `LinkedRecord<NonNullable<${`${nameOf(linked.id, context)}Read[${quote(linked.primaryFieldId)}]`}>>`; } /** `SoftrUserProperties`, each alias typed as its field reads. */ function renderUserProperties(properties, datasources) { const context = { datasources: byId(datasources), names: typeNames(datasources) }; return [ "interface SoftrUserProperties {", ...Object.entries(properties).map(([alias, field]) => indent(readMember({ ...field, id: alias }, context))), "}" ].join("\n"); } function renderRegistry(datasources, context) { return [ "interface SoftrDatasources {", datasources.map((datasource) => { const name = nameOf(datasource.id, context); return indent([ `${key(datasource.id)}: {`, ` name: ${quote(datasource.name)};`, ` primaryField: ${quote(datasource.primaryFieldId)};`, ` read: ${name}Read;`, ` create: ${name}Create;`, ` update: ${name}Update;`, ` fieldTypes: {`, ...datasource.fields.map((field) => ` ${key(field.id)}: ${fieldTypeLiteral(field)};`), ` };`, `};` ].join("\n")); }).join("\n"), "}" ].join("\n"); } /** * A field's declared type, which is what the SDK picks a filter chain from. The type name * goes out verbatim, with one exception: a `DATETIME` at `DATE` precision goes out as * `DATE`, because the two accept different chart buckets and the raw type name does not * tell them apart. The chain each one gets is the SDK's policy, so changing it does not * mean regenerating every app. * * `[]` is a suffix inside the literal rather than a TypeScript array, because the type name * and the multiplicity are one fact about the column here, not a value shape. */ function fieldTypeLiteral(field) { const shape = resolvedShape(field); const type = shape.type === "DATETIME" && datePrecision(shape.options) === "DATE" ? "DATE" : shape.type; return quote(field.allowMultipleEntries ? `${type}[]` : type); } /** A computed field is its returned shape, all the way down, exactly as {@link readValue} does. */ function resolvedShape(shape) { switch (shape.type) { case "FORMULA": case "LOOKUP": case "ROLLUP": return resolvedShape(returnedShape(shape)); default: return shape; } } /** * The block above a member: the field's own name and its DSv2 type, then whichever tags apply. * * The two sides differ only in the value they describe. A read builds `@example` against the * read type, and carries `@readonly`, `@lookup` and `@formula`, none of which can reach a write * type a readonly field is already absent from. */ function fieldDoc(field, datasource, context, side) { const read = side === "read"; const lines = [`Name: ${field.name}`, `Underlying type: ${underlyingType(field)}`]; const tags = []; if (field.defaultValue !== null && field.defaultValue !== void 0) tags.push(`@default ${JSON.stringify(field.defaultValue)}`); const scalar = read ? readExample(field, context.datasources) : scalarExample(field); if (scalar !== null) tags.push(`@example ${field.allowMultipleEntries ? `[${scalar}]` : scalar}`); tags.push(...shapeTags(field)); if (field.id === datasource.primaryFieldId) tags.push("@primaryField"); if (read && field.readonly) tags.push("@readonly"); if (field.required) tags.push("@required"); if (field.createOnly) tags.push("@createOnly"); if (read) { const lookup = lookupTag(field, datasource, context); if (lookup !== null) tags.push(lookup); tags.push(...formulaTag(field) ?? []); } return tags.length === 0 ? lines : [ ...lines, "", ...tags ]; } /** * The bounds a value has to respect, as opposed to the ones Studio only draws with. A * `DATETIME` is excluded from `@precision` by the type of the option: it holds `"DATE"`. */ function shapeTags(field) { const tags = []; const maxLength = option(field.options, "maxLength"); if (typeof maxLength === "number") tags.push(`@maxLength ${maxLength}`); const precision = option(field.options, "precision"); if (typeof precision === "number") tags.push(`@precision ${precision}`); const isoCode = option(field.options, "isoCode"); if (typeof isoCode === "string") tags.push(`@currency ${isoCode}`); return tags; } /** Where a lookup reads from, as the link on this datasource and the field at the far end. */ function lookupTag(field, datasource, context) { if (field.type !== "LOOKUP") return null; const linkId = option(field.options, "linkedRecordFieldId"); const targetId = option(field.options, "lookupFieldId"); const link = datasource.fields.find((candidate) => candidate.id === linkId); if (link === void 0) return null; const linkedTableId = option(link.options, "linkedTableId"); const target = (typeof linkedTableId === "string" ? linkedDatasource(linkedTableId, context.datasources) : void 0)?.fields.find((candidate) => candidate.id === targetId); if (target === void 0) return null; return `@lookup ${link.name} -> ${target.name}`; } /** The DSv2 type, with a computed field's wrapper spelled out down to what it resolves to. */ function underlyingType(field) { const chain = typeChain(field); return field.allowMultipleEntries ? `${chain}[]` : chain; } function typeChain(shape) { switch (shape.type) { case "FORMULA": case "LOOKUP": case "ROLLUP": return `${shape.type} -> ${typeChain(returnedShape(shape))}`; default: return shape.type; } } /** * A formula's expression, split across continuation lines under the tag. * * An expression carrying the comment terminator loses the tag rather than being rewritten: the * point of the tag is to reproduce the expression exactly. */ function formulaTag(field) { if (field.type !== "FORMULA") return null; const formula = option(field.options, "formula"); if (typeof formula !== "string" || formula.includes("*/")) return null; const pad = " ".repeat(9); const [first, ...rest] = formula.split("\n"); return [`@formula ${first}`, ...rest.map((line) => line === "" ? "" : pad + line)]; } /** Stands in for any id in an example. The real ones are in the member type below it. */ const BLANK_ID = "00000000-0000-0000-0000-000000000000"; /** The read counterpart of {@link scalarExample}, wherever the API returns a different shape. */ function readExample(shape, datasources) { switch (shape.type) { case "SELECT": { const choices = choiceEntries(shape.options); return `{ id: '${BLANK_ID}', label: '${choices === null ? "text" : choices[0].label}' }`; } case "LINKED_RECORD": return `{ id: '${BLANK_ID}', label: ${linkedLabelExample(shape.options, datasources)} }`; case "ATTACHMENT": return `{ id: '${BLANK_ID}', filename: 'file.pdf', type: 'application/pdf', url: 'https://example.com/file.pdf', expiresAt: '2026-03-14T09:30:00.000Z' }`; case "LOCATION": return "'text'"; case "FORMULA": case "LOOKUP": case "ROLLUP": return readExample(returnedShape(shape), datasources); default: return scalarExample(shape); } } /** * The label a read carries, resolved the way {@link linkedRecord} resolves its type: the linked * table's primary field. `null` wherever that resolution fails, which says nothing about a table * this app cannot see and inhabits every `LinkedRecord<T>` label. */ function linkedLabelExample(options, datasources) { const linkedTableId = option(options, "linkedTableId"); if (typeof linkedTableId !== "string") return "null"; const linked = linkedDatasource(linkedTableId, datasources); const primary = linked?.fields.find((field) => field.id === linked.primaryFieldId); if (linked === void 0 || primary === void 0) return "null"; const rest = new Map(datasources); rest.delete(linked.id); const scalar = readExample(primary, rest); if (scalar === null) return "null"; return primary.allowMultipleEntries ? `[${scalar}]` : scalar; } /** A literal showing the shape a write takes, or `null` where the shape is not settled. */ function scalarExample(shape) { switch (shape.type) { case "SINGLE_LINE_TEXT": case "LONG_TEXT": case "ADDRESS": case "BUTTON": case "RECORD_ID": return "'text'"; case "EMAIL": return "'name@example.com'"; case "PHONE": return "'+15551234567'"; case "URL": return "'https://example.com'"; case "NUMBER": case "CURRENCY": case "PERCENT": case "PROGRESS": case "COUNT": case "AUTONUMBER": return String(numberExample(shape.options)); case "DURATION": return "3600000"; case "RATING": { const max = option(shape.options, "max"); return String(typeof max === "number" ? max : 5); } case "CHECKBOX": return "true"; case "DATETIME": return datePrecision(shape.options) === "DATE" ? "'2026-03-14'" : "'2026-03-14T09:30:00.000Z'"; case "TIME": return "'09:30:00'"; case "SELECT": return choiceEntries(shape.options) === null ? null : `{ id: '${BLANK_ID}' }`; case "LINKED_RECORD": return `{ id: '${BLANK_ID}' }`; case "ATTACHMENT": return "{ url: 'https://example.com/file.pdf' }"; case "USER": return `{ id: '${BLANK_ID}', name: 'text', email: 'name@example.com', avatarUrl: null }`; case "DATE_RANGE": return "{ from: '2026-03-14', to: '2026-03-21' }"; default: return null; } } /** A number inside the field's own bounds, at the field's own precision. */ function numberExample(options) { const min = option(options, "min"); const max = option(options, "max"); const precision = option(options, "precision"); const low = typeof min === "number" ? min : null; const high = typeof max === "number" ? max : null; const base = low !== null && high !== null ? (low + high) / 2 : low !== null ? low + 8.5 : high ?? 8.5; return Number(base.toFixed(typeof precision === "number" ? precision : 1)); } function option(options, name) { return options === null ? void 0 : options[name]; } function isValueShape(value) { if (typeof value !== "object" || value === null) return false; return typeof value.type === "string"; } function nameOf(datasourceId, context) { return context.names.get(datasourceId) ?? panic(`No type name for datasource ${datasourceId}`); } /** * Always quoted, even where an identifier would do. Find All References on a field id at a * `defineQuery` call site matches string literals and quoted property names, so a bare key is * invisible to it and the id no longer navigates here. */ function key(name) { return quote(name); } function quote(value) { return JSON.stringify(value); } function doc(lines) { return [ "/**", ...lines.map((line) => line === "" ? " *" : ` * ${safe(line)}`), " */" ].join("\n"); } /** A formula or a field name can contain the comment terminator. */ function safe(line) { return line.replaceAll("*/", "* /"); } function indent(block) { return block.split("\n").map((line) => line === "" ? line : ` ${line}`).join("\n"); } //#endregion export { choiceEntries, fieldTypeLiteral, isWritable, linkedDatasource, option, readExample, renderDatasourceTypes, renderUserProperties, resolvedShape, scalarExample, underlyingType };