Content
Database
Tables go in server/<name>.sql.ts with the module prefix. The module's pnpm db:generate (drizzle-kit, its own
drizzle.config.ts) writes its migrations into its own migrations/; they are applied with a separate history
table (__drizzle_migrations_<name>), so core and modules never conflict. The admin role applies them on start
(MIGRATE_ON_START=true), core first. Modules load at start-up: a module that fails its checks stops the server
instead of half-loading.
Collections from modules
A module can add content types with collections (slugs prefixed <name>-, e.g. commerce-products).
They get versions, permissions and admin screens like any collection (Collections), and tables
of their own, generated like core's:
shade-module collections → server/collections.generated.sql.ts (pnpm collections in commerce)
pnpm db:generate → a migration creating them, next to its other tables
The module declares them in its manifest, db: { tables, migrationsFolder, collectionTables } (the generated file's
export), and lists the file in its drizzle.config.ts schema; validateModule refuses a collection without its
tables. The loader registers them for the content service (registerCollectionTables in
shade/features/entries/server/model.ts), so entries, versions and publishing work on them as on core's; the
module's own code queries them from the generated file. Keep transactional records (orders, submissions, stock) in
hand-written db.tables instead: they are not content, are never versioned and never published.
json fields and their checks
A collection keeps a document of a module's own (a layout, a configuration) in a json field:
{ kind: 'json', name: 'layout', label: 'Layout', check: 'shop:layout' }. The value is any JSON (the website
module keeps a page's node tree this way, with its check website:tree); the module named
in check decides it, with a check it registers in its manifest:
import type { FieldCheck } from '@shadestack/module-sdk/server'
const layout: FieldCheck = {
check: async (value, context, stored) => {
const issues = []
// … read `value`, put what is wrong in `issues` as { path, message }, `path` within the value ('rows.0.title')
if (context.mode === 'publish' && !hasRows(value)) issues.push({ path: '', message: 'Add a row first' })
return { value: tidied(value), issues }
},
empty: () => ({ rows: [] }),
// Optional: what changed between two versions, for the version history, reviews and AI changes.
changes: (before, after, { locale }) => ({
changes: rowsChanged(before, after).map(row => ({ kind: 'changed', label: { message: 'Row', key: 'shop.changes.row' }, excerpt: row.title })),
more: 0
})
}
export default defineModule({ name: 'shop', /* … */ fieldChecks: { layout } })
- SHADE runs the check at every create, save, restore and publish of an entry holding the field, in groups and
repeaters too, on every route, and stores the
valueit gives back. Any issue refuses the write with VALIDATION, under the field's path (data.layout.rows.0.title). A missing value is the check'sempty(). context(FieldCheckContext) says where it runs:ctx(the caller's context made for the module),db(the save's database, or the publish's transaction),collection,entryId(null for a new entry),data(the entry's other values as written: an item template's collection),path,mode(draft, orpublishfor what goes live) andstage(savefor someone's change,publishfor a version saved before going live).stored()reads the field's value as it is stored now (undefined for a new entry and when publishing), to compare a change with: the website module holds builders and content editors to their role and keeps embeds unchanged for whoever may not add them this way. A publish runs the check twice (in its precheck and in its transaction), so keep slow work out of it.changes(before, after, { locale }), when the check has it, says what changed between two stored values of the field (a missing one isempty()) for a person: SHADE compares versions on the server and shows what it gives as it is, in the version history, reviews and AI changes (ValueChanges): at most 200 changes, each{ kind, label, excerpt?, details? }(kindisadded,removed,movedorchanged;excerpta few of the part's words, inlocalewhere the value has them),morefor how many were left out, and an optionalnoteshown under them. Every text is aChangeText,{ message, key?, params? }: said by its key from the module's admin texts (<plugin>.…) when there is one, else asmessage. An answer of another shape fails the comparison. Withoutchanges, or while the module is off, the field is shown as changed as a whole. The website module lists a page's tree node by node this way.- Deny by default: a field whose check no installed module registers, or whose module is switched off, can't be saved or published. A module's own collection that names one of its checks it doesn't have fails the load.
- Media (
{ mediaId }) and links to entries ({ kind: 'entry', collection, id }) anywhere in the value are found: a missing one refuses the save, and media in use can't be deleted. A file of any type is taken: if a place takes only some (an image), the check looks the file's type up (findMediaTypes(db, ids)) and refuses the others. - What a check may look up besides, with the database alone, since it holds for whoever saves: a data source by name
(
findDataSource(name), one that exists and is on) and what its settings refuse (dataSourceParameterIssues(source, parameters)), the published forms of some ids (findPublishedForms(db, ids)), and a module's visitor route (findVisitorRoute(plugin, method, path)). The website module checks a page's bindings, loops and forms with them. - No
requiredordefaultValue(the check decides), never translated, and for collections only: settings and data source parameters may not hold one.valueType: jsonValueType<Layout>('Layout', '../shared/layout')types its column in the tablesshade-module collectionswrites (fromas seen fromserver/) and the value inEntryData(Layout | null). The admin's entry form shows how much the field holds, read only: edit it in a screen or panel of the module's own.
Text of json fields in search
Core searches the text of entries (decision 0008 point 12; Search). A json field is opaque
to it, so the module whose check the field names says what text it holds, with searchText beside fieldChecks:
import type { SearchText } from '@shadestack/module-sdk/server'
const layout: SearchText = (value, { language }) => rowsOf(value).map(row => row.title[language] ?? '').join(' ')
export default defineModule({ name: 'shop', /* … */ fieldChecks: { layout: layoutCheck }, searchText: { layout } })
- The key is the name of one of the module's own
fieldChecks; the function gets the field's stored value and the language code, and gives the words as one string. It is called for each language of the site. - It runs as a thread task (
searchText:<name>) with a time (5 seconds) and a memory (128 MB) budget, so it gets plain data and no context, and a slow or failing one leaves the field out of the index and is logged. Trusted modules only. - A json field is searched with the weight
C, or the field's ownsearch('A'to'D'). Without asearchTextthe field is not searched. A change to asearchText(a module installed or switched on with one) builds the collection's index again. - Fields have
search: 'A' | 'B' | 'C' | 'D' | falsetoo: the weight in ranking. Without it the title countsA, text and slugsB, textarea and rich textC, and the rest is not searched. Only fields that hold text take a weight.
Save checks
saveChecks: { '<own collection>': check }: a module's rules for saving its collections' entries beyond what fields
say (the website module keeps the site's own paths free and one template per collection). check(tx, entry, ctx)
runs in the save's transaction on every write path (create, save, restore), with the saving caller's context made
for the module (its actor, and the module's own code: reportError and actAsModule work in it); it returns
issues ({ path, message }, path naming a field; SHADE puts it under data.) or throws. What it writes in tx is
undone with a save it refuses. publishChecks does the same on publishing, on every route that publishes
(the entry routes, and the modules that publish for a person: a schedule, a review, a release). Both hold the entry's row locked while they run: keep what locks a
row every publish needs (the website module's compiled styles) for last.
Slow work a publish check needs goes in publishPrechecks: { '<own collection>': precheck } instead
(PublishPrecheck): precheck({ id, versionId, data }, ctx) runs before the publish's transaction (a release's: before
its one transaction), on the version about to be published, with the caller's context made for the module and no
lock or transaction held, so a check that runs or waits long (the website module's accessibility check in a worker
thread) blocks nobody. What it returns reaches the collection's publish checks as entry.prechecked; they decide in
the transaction. When the entry was saved in between and the publish named no version, SHADE refuses with CONFLICT
(and a release whose items changed meanwhile); what else the result depends on is the check's to compare, and to
refuse with conflict(…) when it changed (the website module compares the whole input it checked).
versionsAwaitingPublish(db, collection, id) gives the versions of an entry waiting to go live: those that any module
names in its manifest's keptVersions (experimental), each published as it was kept. keptVersions is
{ tables, versions }. versions: (db, collection, entryId?) => SQLWrapper is a select of one column, versionId
(lowercase text), of the versions the module waits to publish: the editorial module gives those of its open releases,
pending schedules and pending reviews. Version retention runs that select as core's content inside its own delete, so
tables names the module's own tables it reads (from its db.tables): row-level security opens those, and no other,
to content for reading. List every table the select reads: in one it doesn't list, content sees no rows, so the
versions found only through it are not kept and the purge deletes them.
Version retention keeps them too. What a module keeps beside an entry's versions must stay while one of them has it:
the website module keeps a node's local styles while its working copy, its published version or one of these has the node.
Publishing several at once
publishMany(ctx, items, { note?, around? }) (experimental) publishes and unpublishes entries in one transaction, all or
nothing. Each item is a PublishManyItem: { key, collection, id, action: 'publish' | 'unpublish', versionId? }. SHADE
runs each publish's prechecks first, then one transaction in which every item is a savepoint, skipping what is already in
the wanted state. When any item fails, it throws a validation error with one issue per failing item (its path the
item's key, the message <title>: <reason>), and nothing goes live. Rebuilds wait for the commit. Each item's own
publish permission is checked, as the context's actor. A module that has rows of its own to guard passes
around(tx, publish): it locks and checks them, calls publish(), then writes its outcome in the same transaction.
lockLatestVersion (experimental) reads an entry's latest version with its row locked, to keep a version only while it
is still the latest (the row-lock rule above stays the caller's).
The content API: read models and site data
read: { routes, site } adds a module's read models under its own prefix, /api/v1/content/<name>,
served like core's (a read or build token, the same body limit, CORS and caching):
routes:{ path, summary, query?, handler(ctx, { params, query }) }; the path is under the prefix, which SHADE adds from the module's name: a route/pagesof the moduleshopisGET /api/v1/content/shop/pages, and nothing of it is served without the prefix, so two modules never meet. A module named like one of core's read routes (site,media,data,collections,module-sites) serves none. Where several routes match a path (/:slugand/latest), the first declared serves it. The handler answers JSON or aResponseof its own (text/css,text/plain,application/xml, JSON), sent with its status when that is a 2xx or a 4xx (its "not found"), with SHADE's headers only; a redirect or any other status is a 500. Give aResponseits body as a string or bytes;site: { keys, read(ctx, locale) }: keys it adds toGET /api/v1/content/site, in a language; never one of core's (settings,plugins,consent, …) nor another module's. Only the declared keys are taken.
Both run as the module's reader (moduleReader): the module's own actor, reading only. It reads what its uses
list and what is published on the site, never writes and never another module's drafts, whoever's token called it.
They run in a read-only transaction, which is their ctx.db: not even SQL of their own made by mistake writes, and
SHADE runs a statement before theirs, so a SET TRANSACTION READ WRITE of their own fails. What they read of the
module's own tables is the module's to decide: serve only what a site may show.
readModuleModel(ctx, path, query) (SDK testing) answers a read model as the API would, for tests, by its path under
/api/v1/content with the module's prefix (readModuleModel(ctx, '/shop/pages')). The website module serves its pages
(/api/v1/content/website/pages, /pages/by-slug, /preview), /redirects, /theme.css and /styles.css this
way, and adds its keys theme, fontFaces, navigation, footer and links to the site data: navigation and
footer are the website module's, not part of core's PublishedSiteData.
Where entries live: the paths part
paths: { addresses, itemPaths }. An address source (<name>.<source>: covers(collection), list(ctx, languages), optional paths(…) for links and moved(…) after a publish) says where the entries of some collections live on the site, in every
public language. itemPaths(db, collection, locale) gives the address of the items of a collection with item pages,
for data sources and links. After a publish or an unpublish SHADE compares where entries with an address are with
where they were (public_paths), remembers it, and writes the event paths.addresses.moved ({ moves, live }),
which a module hears in on.
SHADE keeps what the sources answer in that address index: each address with its title, noindex and dates, and
whether it is public now. publicAddresses (read models, redirects, the sitemap, forms' page of origin) reads the
index in one query rather than calling every source, so the website's /pages answers 20,000 addresses in about
85 ms. The sources are read by the follow, as the system, not by whoever asked. The index is as fresh as the last
follow:
- an entry's publish, unpublish or delete, and a save in a collection without drafts, is in it once the worker has handled the event, normally within seconds;
- a module switched on or off is followed the same way, every address again;
- a worker follows every address when it starts, and every rebuild before it builds;
- the worker follows every address again every 15 minutes, which catches what no event tells (a language made public, a changed collection after a deploy).
A module that is switched off leaves the list at once. A follow of every address that finds a moved address asks for a rebuild.
A source with thousands of entries should give moved(ctx, languages, entry): the addresses a publish of entry may
have moved, in every public language. For an item's publish that is the item's own addresses, and for a publish that
moves none of the source's entries it is an empty list. Return null when only reading everything can say, as for a
template page whose item path moves every item. Without moved, SHADE reads the source's whole list after every
publish. When another entry already holds one of the paths, SHADE reads every address anyway, so who keeps a path is
decided as before.
Previews
createPreviewToken(ctx, { subject, versionId, locale? }) signs a token with the API's secret, naming the module;
readPreviewToken(ctx, token) gives its claims back to that module only, in code SHADE called as it, or null. Core
keeps only these generic preview links: the website editor's canvas protocol (EditorToCanvasMessage,
CanvasToEditorMessage, CANVAS_PROTOCOL_VERSION) is @shadestack/tree/canvas's, not the SDK's.
adminFrames(ctx) gives the origins the admin may frame (its Content-Security-Policy's frame-src), from the
module's settings: the website module's Preview address. Only http(s) origins count.
Previews of a set of versions (experimental). A module that groups entries, such as the editorial module's releases,
names the set in the manifest's previewSets: (ctx, subject) => { name, items: [{ collection, id, action, versionId }] } | null.
It runs as the link's maker at every read, so the module checks its own read action there; null means the set is gone
and the link has expired. createSetPreview(ctx, { subject, frontendId?, locale?, share? }) makes the link for the
context's module, listSetPreviewShares(ctx, subject) lists its share links and revokePreviewShare revokes one (its
maker may, or the module after its own manage check). The frontend reads it as kind: 'set' (The API).
Rebuilding the frontends
SHADE's rebuild trigger gathers every request for a rebuild into one burst (30 seconds of quiet, at most 2 minutes),
then calls the other frontends' webhooks and each rebuild target of a module that is on: rebuild(ctx, { reasons, requestedById }), run as the plugin, its errors reported, never thrown on. requestRebuild(ctx, reason) asks for one
after a change of the module's own (the theme, a redirect); the reason is named after the module. An editor's change
may ask; a read token may not; the module's own actor needs rebuild.request in uses. What a rebuild target asks
for itself is dropped, so rebuilds never loop.
Media a module uses
mediaUsers(db, mediaId) gives where the module uses a media item beyond its collections' fields ({ title, locations, live? }: the website module's theme fonts). The media library lists it as a use, refuses to delete the
item while it is used and rebuilds the site when a live one changes.
Slow checks on publish
A check that needs slow work, such as the website module's accessibility check (@shadestack/a11y's
checkAccessibility, 30 seconds at most), runs it as one of the module's
thread tasks, in a worker thread with a budget. Run it from a publish
precheck (publishPrechecks), never from a publish check: in the publish's transaction a run waiting for a thread
would hold a pooled connection and the entry's row lock for up to its budget. The check in the transaction then uses
the precheck's result. reportError(ctx, error, scope) records what went wrong inside the module's own check (a run
past its budget, one that failed) in the error log as package:<name>. reportError(ctx, error, scope, { level: 'warning' })
records something that went wrong while the work around it went on (a courtesy message that could not go out): it is
listed and counted like an error, but never fires the new-error alert and never makes your module unhealthy (ErrorLevel).
Content services
Module code reads and writes core's content through core's own services, from
@shadestack/module-sdk/server. Each checks the permission of ctx.actor, validates its input, writes in a
transaction and records an audit entry, as it does for an editor:
- entries:
listEntries(ctx, slug, query),getEntry(ctx, slug, id),createEntry(ctx, slug, { data }),saveEntry(ctx, slug, id, { data, baseVersionId }),publishEntry(ctx, slug, id, {}),unpublishEntry(ctx, slug, id),deleteEntry(ctx, slug, id); - media:
listMedia(ctx, query),getMedia(ctx, id),uploadMedia(ctx, { filename, data }); - a drawing (experimental):
svgToPng(svg, { width, height })draws an SVG the module made as a PNG, 1 to 4096 pixels a side, with the image library SHADE already runs. The SVG must pass the same check an SVG upload does (no links but to a#fragment, no script), or it is refused with VALIDATION. Text is drawn with the server's fonts, so draw text as outlines for an image that looks the same everywhere. The website's generated social image uses it.
The trash. deleteEntry moves an entry to the trash: it is unpublished and
the services above leave it out until it is restored, as a draft, or deleted forever. The event entries.entry.deleted is written when it goes
there. A module that reads its own collections' tables leaves trashed entries out with notInTrash(collection, idColumn),
an SQL condition for its query, or finds them among ids with trashedEntryIds(db, collection, ids). A trashed entry
keeps its unique values (a slug, a partial unique index) until it is deleted forever, so a check that finds one can
say it is in the trash.
In a transaction. To keep what a service writes together with your own change (an order's invoice file, a
booking's reminder, an order event), give it your context on that transaction: inTransaction(ctx, async (txCtx) => …) runs the work in one, with txCtx.db as the transaction, and withDb(ctx, tx) puts a context on a transaction you
already have. Both keep the context the module's own and its lazy parts lazy; never copy a context ({ ...ctx }).
afterCommit(txCtx, step) runs a step of yours once the change is kept, and never when it rolls back: for telling
others about it. emit and sendRealtimeUpdate use it, so call them inside the change's inTransaction: the
worker and the pages hear of it right after the commit. They refuse a transaction you opened yourself
(ctx.db.transaction(…)), as SHADE can't know when that one commits; a nested inTransaction is a savepoint whose
steps wait for the outer commit. Your schedules already run in one of SHADE's transactions.
recordAudit(tx, ctx, entry) refuses a handle that isn't a transaction as well: record the entry in the transaction
of the change it is about, so it exists exactly when the change was kept. A read or an export that only records an
entry opens one for it: await inTransaction(ctx, inTx => recordAudit(inTx.db, ctx, entry)).
A rule over several rows. Two writes at the same moment each read the rows before the other commits, so a rule
that spans rows of your tables (no redirect loops, one template per collection) can break. Where a unique index can
say the rule, use one (a collection's indexes, or your own table's): it holds against every writer. Where it can't,
lockKey(ctx, key) holds your module's own lock key until the transaction ctx.db is on ends: take it first in
every transaction that writes what the rule covers, then read, check and write, and the second waits until the first
is over. It needs a transaction (inTransaction, or withDb(ctx, tx) in a check core gives tx) and the context
SHADE gave your code; its keys are your module's own (package:<name>:<key>), so it never waits on SHADE's locks or
another module's.
await inTransaction(ctx, async (txCtx) => {
await lockKey(txCtx, 'redirects')
// read the redirects, check for a loop, write
})
// A job: runs as the module, so the manifest lists 'collections.website-posts.create'.
run: async (ctx) => {
await createEntry(ctx, 'posts', { data: { title: 'Weekly digest', slug: `digest-${week}` } })
}
In a session route the same call acts as the editor, with their rights; in a job, a public or account route, a payment
handler or a hook (every hook and on handler runs as the module, decision 0014) as the module, with its uses. A refusal is FORBIDDEN (403 from a route). Core's tables stay out of the SDK.
A data source gets the context of whoever asked for it, whose rights may not reach the module's collection (a read
token of the site). To read as the module itself, with exactly its uses, it passes actAsModule(ctx):
// The manifest lists 'collections.shop-products.read'.
dataSources: [{
name: 'shop.products',
label: 'shop.sources.products',
parameters: [],
item: [{ kind: 'text', name: 'title', label: 'Title' }],
resolve: async (ctx) => {
const products = await listEntries(actAsModule(ctx), 'shop-products', { status: 'published' })
return products.items.map(product => ({ id: product.id, data: { title: product.data.title }, media: {}, links: {} }))
}
}]
actAsModule only ever gives the actor of the module core called, never another module's. Which module that is, is
core's own record of the contexts it made, not ctx.plugin: it throws for a context core didn't make (a copy such as
{ ...ctx }, or one you made up) and for one whose ctx.plugin you changed. Pass the ctx you were given; the same
context on a transaction (withDb, inTransaction, below) is fine. Don't use it for work an
editor started (session routes): there the editor's context keeps the editor to their own
rights. Its writes and refusals are the module's, audited as package:<name>.
listPublicEntries still reads published entries for the site.
When you need only where published entries live, not their content, use listPublishedSummaries(ctx, collection, { locale, ids, fields }) (experimental). It gives each entry's id, slug, title, publishedAt and updatedAt, and the
plain fields you name by their path, such as seo.noindex, in one query per collection and language. A translation
that is missing falls back to the default language. It reads no relations, media or links, so a list of thousands of
addresses stays one read. It follows the same rules as listPublicEntries: the collection needs publicApi, the
caller its read action, and a field the public API hides is refused, not left out.
Form submissions
Forms are the official forms module's (Forms), not core's. Core has no form
builder, no forms manifest part and no forms capability. A module that wants leads hears the event the forms module
raises for each submission, forms.submission.received, with an on entry in its manifest and the usual
events between modules:
export default defineModule({
name: 'crm',
// …
capabilities: { subscribe: {} },
on: {
'forms.submission.received': async (ctx, event) => {
const { form, answers } = event.data
if (form.key !== 'quote') return
const email = answers.find(answer => answer.role === 'email')?.value
await pushLead(ctx, { form: form.key, email, answers })
}
}
})
event.datais{ id, form: { id, key, version }, language, answers: [{ key, kind, role, value }], consent }. Filter onform.key;roleis the field's purpose (such asemail). Each published version of a form has a JSON Schema of its answers.- Whatever your module keeps of a submission is personal data: list it in
personalData(witherase), so people can ask for it and have it erased. - Connecting a form to one module at a time, sending a submission again and a webhook with a form's answers come after 0.1.0.
- Gone from the SDK:
findPublishedForms,listPublishedForms,readPublishedForm,PublishedForm,PublishedFormFieldandModuleFormSubmission.isSpam,SpamCheckFieldsandSPAM_CHECK_RATE_LIMIT(the spam check the forms module uses, see Routes) are stable.