@softr/sdk
Version:
The SDK for building Softr apps on TanStack Start. It lets an app interact with Softr: auth, datasources, workflows and integrations.
383 lines (381 loc) • 13.7 kB
JavaScript
import { assert, panic, requireDefined } from "../assertions.js";
import { softrApiUrl } from "../softr-api.js";
import { fetch } from "../fetch.js";
import { softrConfig } from "../softr-config.js";
import { readUserTimezone } from "../cookies.js";
import { readFreshUser, readSessionToken, readStandInUser } from "../auth/session.js";
import { andGroups, buildFilterCriteria, buildOrderBy, dealiasFilterCriteria, dealiasOrderBy } from "./filter.js";
import { andAll, makeFieldSet, makeSortSet } from "./fields.js";
import { filterForVisitor, readsVisitor } from "./enforced-filter.js";
import { isDatasourceAction } from "../action.js";
import { readSoftrContext } from "../auth/context.js";
import { getRequestHeader, getRequestUrl } from "@tanstack/react-start/server";
//#region src/datasource/record.ts
const MAX_RECORD_COUNT = 100;
const dsUrl = (actionId) => {
const applicationId = process.env.SOFTR_APPLICATION_ID;
if (!applicationId) panic("SOFTR_APPLICATION_ID is not set.");
return `${softrApiUrl("SOFTR_DATASOURCE_API_URL")}/v1/datasource/vibe/applications/${applicationId}/actions/${actionId}`;
};
/**
* The datasource API wants to know which page made the call, and rejects a call without it.
*
* A call from the browser has a Referer on this app's origin, and that Referer names the page.
* A page load has the previous page as its Referer: Studio, or none for a pasted link.
* There the page is the request itself, so we send the request URL.
*/
function refererHeader() {
const page = getRequestUrl({
xForwardedHost: true,
xForwardedProto: true
});
const referer = getRequestHeader("referer");
return { Referer: referer !== void 0 && URL.parse(referer)?.origin === page.origin ? referer : page.href };
}
async function describeFailure(res) {
const body = await res.json().catch(() => null);
const message = typeof body === "object" && body !== null && "message" in body ? body.message : null;
return typeof message === "string" && message.length > 0 ? `${res.status} ${message}` : `${res.status}`;
}
/**
* Queries a list of records from the datasource.
*
* @example
* const { records, total, nextOffset } = await ds
* .list(posts)
* .where((q) => q.publishedAt.lte(today))
* .orderBy((q) => q.publishedAt.desc)
* .limit(50)
*/
function listRecords(query) {
const aliases = Object.keys(resolveTarget(query, "read").select);
const args = {
filters: [],
orderBy: []
};
let page;
const run = () => page ??= executeList(query, args);
const builder = {
[Symbol.toStringTag]: "RecordListing",
where(build) {
args.filters.push(build(makeFieldSet(aliases)));
return builder;
},
orderBy(build) {
const sorting = build(makeSortSet(aliases));
args.orderBy.push(...Array.isArray(sorting) ? sorting : [sorting]);
return builder;
},
limit(count) {
args.limit = count;
return builder;
},
offset(offset) {
args.offset = offset;
return builder;
},
then(onfulfilled, onrejected) {
return run().then(onfulfilled, onrejected);
},
catch(onrejected) {
return run().catch(onrejected);
},
finally(onfinally) {
return run().finally(onfinally);
}
};
return builder;
}
async function executeList(query, args) {
const target = resolveTarget(query, "read");
const { actionId, select } = target;
const count = Math.min(args.limit ?? 20, MAX_RECORD_COUNT);
const offset = args.offset ?? null;
const filterCriteria = await readFilterCriteria(target, args.filters);
if (filterCriteria === null) return {
records: [],
total: 0,
nextOffset: null
};
const sortingOption = args.orderBy.length ? dealiasOrderBy(buildOrderBy(args.orderBy), select) : void 0;
const res = await fetch(`${dsUrl(actionId)}/records`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-User-Timezone": readUserTimezone() ?? "UTC",
Authorization: `Bearer ${readSessionToken()}`,
...refererHeader()
},
body: JSON.stringify({
options: { userLocale: "en-US" },
filterCriteria,
sortingOption,
pagingOption: {
offset,
count
}
})
});
if (!res.ok) throw new Error(`datasource list failed for "${actionId}": ${await describeFailure(res)}`);
const payload = await res.json();
const nextOffset = payload.offset < payload.total ? payload.offset : null;
return {
records: payload.items.map((item) => ({
id: item.id,
fields: aliasFields(item.fields, select)
})),
total: payload.total,
nextOffset
};
}
/**
* Gets a single record by ID.
*
* @example
* const record = await ds
* .get(posts, { id: "record-id" })
* .where((q) => q.publishedAt.lte(today))
*
* A filter may also be provided to narrow down
*
* @example
* const record = await ds
* .get(posts, { id: "record-id" })
* .where((q) => q.publishedAt.lte(today))
*/
function getRecord(query, options) {
const aliases = Object.keys(resolveTarget(query, "read").select);
const filters = [];
let record;
const run = () => record ??= executeGet(query, options.id, filters);
const builder = {
[Symbol.toStringTag]: "RecordFetch",
where(build) {
filters.push(build(makeFieldSet(aliases)));
return builder;
},
then(onfulfilled, onrejected) {
return run().then(onfulfilled, onrejected);
},
catch(onrejected) {
return run().catch(onrejected);
},
finally(onfinally) {
return run().finally(onfinally);
}
};
return builder;
}
async function executeGet(query, id, filters) {
assert(id, "a record id must not be empty");
const target = resolveTarget(query, "read");
const { actionId, select } = target;
const filterCriteria = await readFilterCriteria(target, filters);
if (filterCriteria === null) return null;
const res = await fetch(`${dsUrl(actionId)}/records/${id}`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-User-Timezone": readUserTimezone() ?? "UTC",
Authorization: `Bearer ${readSessionToken()}`,
...refererHeader()
},
body: JSON.stringify({
options: { userLocale: "en-US" },
filterCriteria
})
});
if (!res.ok) throw new Error(`datasource get failed for action "${actionId}": ${await describeFailure(res)}`);
const contentLength = res.headers.get("Content-Length");
if (contentLength && parseInt(contentLength, 10) === 0) return null;
const record = await res.json();
return {
id: record.id,
fields: aliasFields(record.fields, select)
};
}
/**
* Creates a record and returns it.
*
* @example
* const record = await ds.create(newPost, {
* data: { title: "Cafes", publishedAt: today },
* })
*/
async function createRecord(action, options) {
const { actionId, select } = resolveTarget(action, "create");
const data = options.data;
const rawFields = dealiasData(data, select);
const res = await fetch(`${dsUrl(actionId)}/records/new`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-User-Timezone": readUserTimezone() ?? "UTC",
Authorization: `Bearer ${readSessionToken()}`,
...refererHeader()
},
body: JSON.stringify({ fields: rawFields })
});
if (!res.ok) throw new Error(`datasource create failed for action "${actionId}": ${await describeFailure(res)}`);
const record = await res.json();
return {
id: record.id,
fields: aliasFields(record.fields, select)
};
}
/**
* Updates a record by ID and returns it. Only the fields in `data` change.
*
* @example
* const record = await ds.update(editPost, {
* id: "record-id",
* data: { title: "Cafes" },
* })
*/
async function updateRecord(action, options) {
if (!options.id) throw new Error(`datasource update: id must not be empty`);
const target = resolveTarget(action, "update");
const { actionId, select } = target;
await requireFilterMatch(target, options.id, "update");
const data = options.data;
const rawFields = dealiasData(data, select);
const res = await fetch(`${dsUrl(actionId)}/records/${options.id}`, {
method: "PATCH",
headers: {
"Content-Type": "application/json",
"X-User-Timezone": readUserTimezone() ?? "UTC",
Authorization: `Bearer ${readSessionToken()}`,
...refererHeader()
},
body: JSON.stringify({ fields: rawFields })
});
if (!res.ok) throw new Error(`datasource update failed for action "${actionId}": ${await describeFailure(res)}`);
const record = await res.json();
return {
id: record.id,
fields: aliasFields(record.fields, select)
};
}
/**
* Deletes a record by ID.
*
* @example
* await ds.delete(removePost, { id: "record-id" })
*/
async function deleteRecord(action, options) {
const target = resolveTarget(action, "delete");
const { actionId } = target;
await requireFilterMatch(target, options.id, "delete");
const res = await fetch(`${dsUrl(actionId)}/records/${options.id}`, {
method: "DELETE",
headers: {
"X-User-Timezone": readUserTimezone() ?? "UTC",
Authorization: `Bearer ${readSessionToken()}`,
...refererHeader()
}
});
if (!res.ok) throw new Error(`datasource delete failed for action "${actionId}": ${await describeFailure(res)}`);
}
function resolveTarget(subject, operation) {
const declaredBy = operation === "read" ? "defineQuery" : "defineMutation";
assert(isDatasourceAction(subject), () => `Expected an action from ${declaredBy} but got ${JSON.stringify(subject)}`);
const action = subject;
assert(action.resource.operation === operation, () => `action "${action.id}" is declared as ${action.resource.operation}, not ${operation}`);
return {
actionId: action.id,
select: action.resource.fields ?? {},
filterFields: action.resource.filterFields,
filter: action.resource.filter
};
}
/**
* The id suffix of the READ action that app-sync declares for each mutation with a filter.
*
* Never change it. App-sync ships with the pod, and an app keeps the SDK version it pinned, so the
* two can differ in age and still must agree.
*/
const FILTER_CHECK_SUFFIX = "__check";
/**
* Before an update or a delete, reads the record through the mutation's filter. It reads with the
* READ action that app-sync declares for the mutation, because the datasource refuses a read through
* a write action. A record that does not match throws "not found", and the caller sends no write.
*
* The record can still change between this read and the write. Another request can change a field
* that the filter reads, and a date token can pass midnight. Only the fields that the filter
* compares with a user token stay out of reach of this mutation, because `defineMutation` keeps
* them out of `fields`.
*/
async function requireFilterMatch(target, id, operation) {
if (target.filter === void 0) return;
const check = {
actionId: `${target.actionId}${FILTER_CHECK_SUFFIX}`,
select: {},
filterFields: target.filterFields,
filter: target.filter
};
const notFound = () => /* @__PURE__ */ new Error(`datasource ${operation} failed for action "${target.actionId}": record "${id}" not found`);
const filterCriteria = await readFilterCriteria(check, [], readFreshUser);
if (filterCriteria === null) throw notFound();
const res = await fetch(`${dsUrl(check.actionId)}/records/${id}`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-User-Timezone": readUserTimezone() ?? "UTC",
Authorization: `Bearer ${readSessionToken()}`,
...refererHeader()
},
body: JSON.stringify({
options: { userLocale: "en-US" },
filterCriteria
})
});
if (res.status === 404) throw notFound();
if (!res.ok) throw new Error(`datasource ${operation} failed for action "${target.actionId}": ${await describeFailure(res)}`);
if (await res.text() === "") throw notFound();
}
/**
* The filter a read sends: the query's enforced filter, with its tokens, AND the `where`
* filters. `null` when the enforced filter matches no rows for this visitor. The read then sends
* no request and returns nothing.
*/
async function readFilterCriteria(target, filters, readUser = async () => readStandInUser() ?? readSoftrContext().user) {
const groups = [];
const enforced = target.filter?.filterConditionGroup;
if (enforced !== void 0) {
const forVisitor = readsVisitor(enforced) ? filterForVisitor(enforced, toVisitor(await readUser())) : enforced;
if (forVisitor === null) return null;
groups.push(dealias(forVisitor, requireDefined(target.filterFields, "an action with a filter declares filterFields")));
}
const requested = filters.length ? buildFilterCriteria(andAll(filters)).filterConditionGroup : void 0;
if (requested !== void 0) groups.push(dealias(requested, target.select));
if (groups.length === 0) return {};
return { filterConditionGroup: groups.length === 1 ? groups[0] : andGroups(groups) };
function dealias(group, aliases) {
return requireDefined(dealiasFilterCriteria({ filterConditionGroup: group }, aliases).filterConditionGroup);
}
}
function toVisitor(user) {
if (user === null) return null;
const properties = user.properties;
const aliasOf = new Map(Object.entries(softrConfig().user?.properties ?? {}).map(([alias, fieldId]) => [fieldId, alias]));
return {
email: user.email,
field(key) {
const alias = aliasOf.get(key);
assert(alias !== void 0, () => `the enforced filter reads USER:::${key}, a field that softr.json does not declare under user.properties`);
return properties[alias];
}
};
}
function aliasFields(fields, aliases) {
const result = {};
for (const [alias, fieldId] of Object.entries(aliases)) result[alias] = fields[fieldId] ?? null;
return result;
}
function dealiasData(data, select) {
const result = {};
for (const [alias, value] of Object.entries(data)) result[select[alias] ?? alias] = value;
return result;
}
//#endregion
export { createRecord, deleteRecord, describeFailure, dsUrl, getRecord, listRecords, readFilterCriteria, refererHeader, resolveTarget, updateRecord };