canica/server
Tables, queries, mutations, actions, endpoints and the services handlers use. Imported by server/index.ts and the rest of server/.
Functions and values
string number cents boolean idPattern id userId file emailId containsFile day literal array object structSchema validateFields isField fieldFromDesc addDays daysBetween weekday startOfWeek lastDays formatCents plural formatDate formatTime table schema query mutation hmacSha256 sameSignature Viewer Now Random Scheduler Files Email requireSignIn TaggedError NotFound InvalidArgs AlreadyExists Unauthenticated FetchFailed FileTooLarge StorageFull EmailLimitReached Unsubscribed NotARecipient api bearer header secret none ApiFailed IMAGE_WIDTHS
string functionsrc/server/fields.ts
A UTF-8 string. Chain .trim(), .min(n), .max(n), .pattern(re), .email(), .message(text).
const string = (): StringField => …number functionsrc/server/fields.ts
A finite float64. Chain .int(), .min(n), .max(n).
const number = (): NumberField => …cents functionsrc/server/fields.ts
Money as integer minor units (cents), more than 0 (an amount someone typed; for balances use number().int()). Stored and sent as an integer;
in forms the user types a decimal amount ("12.50" or "12,50") and the field gets 1250.
Display with (cents / 100).toLocaleString(undefined, { style: "currency", currency: "EUR" }).
const cents = (): NumberField => …boolean functionsrc/server/fields.ts
const boolean = (): BooleanField => …idPattern functionsrc/server/fields.ts
Ids look like todos_k3j2…. The prefix is checked when decoding args.
const idPattern = (table: string) => …id functionsrc/server/fields.ts
A reference to a row in table.
const id = <const Table extends string>(table: Table): IdField<Table> => …userId functionsrc/server/fields.ts
A reference to a Canica user (guest or signed in).
const userId = (): UserIdField => …file functionsrc/server/fields.ts
An uploaded file, stored as its id (Id<"_files">). Upload with useUpload() in the page, then pass the id to a
mutation that stores it here; queries turn it into a link with files.url(id). A file no row refers to is deleted
(24 h after its upload if it was never stored; at the next hourly cleanup once its row is deleted or changed).
const file = (): FileField => …emailId functionsrc/server/fields.ts
An email's id (EmailId), e.g. a query's argument: query({ id: emailId() }, …) that returns its status.
const emailId = (): EmailIdField => …containsFile functionsrc/server/fields.ts
Whether a field (or a field inside an array/object) is a file().
const containsFile = (d: FieldDesc): boolean => …day functionsrc/server/fields.ts
A calendar day without time or timezone, as "YYYY-MM-DD" (validated as a real date).
Sorts correctly as text, so it can be indexed and range-queried.
const day = (): DayField => …literal functionsrc/server/fields.ts
One of a fixed set of string/number/boolean values. Indexable.
const literal = <const L extends ReadonlyArray<string | number | boolean>>(...values: L): LiteralField<L[number]> => …array functionsrc/server/fields.ts
An array of values. Stored as JSON; cannot be indexed. Chain .min(n), .max(n), .nonEmpty().
const array = <F extends AnyField>(item: F): ArrayField<FieldType<F>> => …object functionsrc/server/fields.ts
A nested object. Stored as JSON; cannot be indexed.
const object = <const Fields extends Record<string, AnyField>>(fields: Fields): PlainField<Simplify<ObjectType<Fields>>> => …structSchema functionsrc/server/fields.ts
Builds the Effect Schema struct for a record of fields.
const structSchema = (fields: Record<string, AnyField>): Schema.Top => …validateFields functionsrc/server/fields.ts
Validate raw against fields. Missing required values become "Required";
a field's .message(...) replaces its validation messages.
const validateFields = (
fields: Record<string, AnyField>,
raw: unknown,
): { readonly ok: true; readonly value: unknown } | { readonly ok: false; readonly issues: Array<{ path: Array<string | number>; message: string }> } => …isField functionsrc/server/fields.ts
function isField(u: unknown): u is AnyFieldfieldFromDesc functionsrc/server/fields.ts
Rebuild a field from its desc (e.g. a schema sent by canica deploy to the running app).
function fieldFromDesc(d: FieldDesc): AnyFieldaddDays functionsrc/server/days.ts
addDays("2026-03-01", -1) → "2026-02-28".
const addDays = (day: string, n: number): string => …daysBetween functionsrc/server/days.ts
Whole days from a to b (daysBetween("2026-01-01", "2026-01-08") → 7).
const daysBetween = (a: string, b: string): number => …weekday functionsrc/server/days.ts
Day of the week, 0 = Monday … 6 = Sunday.
const weekday = (day: string): number => …startOfWeek functionsrc/server/days.ts
The Monday (or Sunday with { weekStartsOn: 0 }) of day's week.
const startOfWeek = (day: string, options?: { readonly weekStartsOn?: 0 | 1 }): string => …lastDays functionsrc/server/days.ts
The n days ending at day, oldest first (lastDays(today, 7) = this past week).
const lastDays = (day: string, n: number): ReadonlyArray<string> => …formatCents functionsrc/server/days.ts
Money in cents as text: formatCents(1250, "EUR") → "€12.50" (in the user's locale on the client).
const formatCents = (cents: number, currency: string, locale?: string): string => …plural functionsrc/server/days.ts
"1 voter", "3 voters", "0 cards". Irregular plurals: plural(n, "person", "people").
const plural = (n: number, singular: string, pluralForm: string = `${singular}s`): string => …formatDate functionsrc/server/days.ts
An unambiguous date for an epoch ms: "Oct 12, 2026" (in the user's locale on the client).
const formatDate = (ms: number, locale?: string): string => …formatTime functionsrc/server/days.ts
A message-style time: "10:42" today, "Yesterday 10:42", "Mon 10:42" this week, else "Oct 12, 10:42".
now comes from useNow("minute") on the client.
const formatTime = (ms: number, now: number, locale?: string): string => …table functionsrc/server/table.ts
Declare a table. Every row also gets id, createdAt and updatedAt.
const table = <const F extends Fields>(fields: F): TableDef<F, {}, never> => …schema functionsrc/server/app.ts
Declare the tables. Returns the Drizzle tables, the Db service and app.
export const { app, Db, tables } = schema({
todos: table({ text: string(), owner: userId() }).index("by_owner", ["owner"]),
})
function schema<const S extends SchemaDef>(tables: S): Schema<S>query constsrc/server/app.ts
Define a reactive, read-only handler.
const query: QueryBuildermutation constsrc/server/app.ts
Define a transactional write.
const mutation: MutationBuilderhmacSha256 functionsrc/server/hmac.ts
Webhook signatures, for endpoints (server code may not touch crypto itself). Stripe, GitHub, Slack and most
others sign the raw body with HMAC-SHA256 and a shared secret:
const body = yield* request.text()
const expected = yield* hmacSha256(ctx.secrets.GITHUB_WEBHOOK_SECRET, body)
if (!sameSignature(`sha256=${expected}`, request.headers.get("x-hub-signature-256"))) return new Response("Bad signature", { status: 401 })
const hmacSha256 = (key: string | undefined, message: string | Uint8Array, encoding: "hex" | "base64" = "hex"): Effect.Effect<string> => …sameSignature functionsrc/server/hmac.ts
Whether two signatures are the same, in time that does not depend on where they differ. A missing one is not.
const sameSignature = (a: string | null | undefined, b: string | null | undefined): boolean => …Viewer constsrc/server/services.ts
The current user. const viewer = yield* Viewer
const Viewer = Context.Service<CanicaViewer, ViewerShape>("canica/Viewer")Now constsrc/server/services.ts
The time the mutation started, in epoch ms. Mutations only. const now = yield* Now
const Now = Context.Service<CanicaNow, number>("canica/Now")Random constsrc/server/services.ts
Randomness for mutations (invite codes, shuffles, tokens). const random = yield* Random
const Random = Context.Service<CanicaRandom, RandomShape>("canica/Random")Scheduler constsrc/server/services.ts
Schedule work for later (mutations; actions use ctx.scheduler). (yield* Scheduler).runAfter(60_000, "remind", { todo })
const Scheduler = Context.Service<CanicaScheduler, SchedulerShape>("canica/Scheduler")Files constsrc/server/services.ts
Uploaded files: const files = yield* Files, then files.url(todo.image) in a query.
const Files = Context.Service<CanicaFiles, FilesShape>("canica/Files")Email constsrc/server/services.ts
Send email to the app's users, from mutations and actions: yield* (yield* Email).send("listShared", { to, props });
follow it with yield* (yield* Email).status(id) (in a query: live).
Templates live in server/emails.tsx (email() from canica/email) and go in app({ emails }).
const Email = Context.Service<CanicaEmail, EmailShape>("canica/Email")requireSignIn constsrc/server/auth.ts
The current user, who must be signed in (guests fail with Unauthenticated).
addNote: mutation({ text: string() }, function* ({ text }) {
const me = yield* requireSignIn
…
})
const requireSignIn: Effect.Effect<SignedInViewer, Unauthenticated, CanicaViewer>TaggedError constsrc/server/errors.ts
Typed errors. return yield* new MyError({...}) inside a handler fails it
with that error; the client receives { _tag: "MyError", ...fields } and
every query/mutation type includes it automatically.
class TooManyTodos extends TaggedError("TooManyTodos")<{ max: number }> {}
class Forbidden extends TaggedError("Forbidden") {} // no fields: new Forbidden()
const TaggedError: <Tag extends string>(tag: Tag) => ErrorClass<Tag>NotFound classsrc/server/errors.ts
The row does not exist.
class NotFound extends TaggedError("NotFound")<{ readonly table: string; readonly id: string }> {
override get message() {
return `No ${this.table} row with id ${this.id}`
}
}InvalidArgs classsrc/server/errors.ts
The arguments did not match the handler's schema. Every operation can fail with this.
class InvalidArgs extends TaggedError("InvalidArgs")<{ readonly message: string; readonly issues: ReadonlyArray<Issue> }> {}AlreadyExists classsrc/server/errors.ts
A .unique(...) index already has a row with these values.
class AlreadyExists extends TaggedError("AlreadyExists")<{ readonly table: string; readonly index: string }> {
override get message() {
return `A ${this.table} row with the same ${this.index} already exists`
}
}Unauthenticated classsrc/server/errors.ts
The operation requires a signed-in account.
class Unauthenticated extends TaggedError("Unauthenticated") {}FetchFailed classsrc/server/errors.ts
ctx.fetch could not reach the server (DNS, connection, timeout); ctx.fetchJson and ctx.fetchText also fail
with it on an HTTP error status (status), and fetchJson on a body that does not match the schema.
class FetchFailed extends TaggedError("FetchFailed")<{ readonly url: string; readonly status?: number; readonly message: string }> {}FileTooLarge classsrc/server/errors.ts
An upload (or ctx.files.store) is bigger than the app allows for one file.
class FileTooLarge extends TaggedError("FileTooLarge")<{ readonly maxBytes: number; readonly message: string }> {}StorageFull classsrc/server/errors.ts
The app's file storage is full (its limit on the platform's free plan).
class StorageFull extends TaggedError("StorageFull")<{ readonly message: string }> {}EmailLimitReached classsrc/server/errors.ts
(yield* Email).send(…) refused: the app sent its most emails today (per: "app", the free plan's 100), or this
person got their most from it today (per: "recipient", 10). Nothing was queued; try again after 00:00 UTC.
class EmailLimitReached extends TaggedError("EmailLimitReached")<{ readonly per: "app" | "recipient"; readonly limit: number; readonly message: string }> {}Unsubscribed classsrc/server/errors.ts
The recipient unsubscribed from this app's emails (the link in every email's footer). Nothing was queued.
class Unsubscribed extends TaggedError("Unsubscribed")<{ readonly message: string }> {}NotARecipient classsrc/server/errors.ts
The recipient cannot get this app's emails. Nothing was queued. reason:
not-signed-in: not a person who signed in to the app with Google (a verified address)sign-in-again: they did, but not since the app keeps the sign-in service's proof (an account from before v0.55, or a session carried over from before v0.58): signing in again stores it, then emails gono-access: the app's access no longer lets them in
self: the recipient is the person who asked (their own email): the message says "you", and canica/ui's
ActionStatus (or EmailNeedsSignIn) offers the sign-in that fixes it.
class NotARecipient extends TaggedError("NotARecipient")<{
readonly reason: "not-signed-in" | "sign-in-again" | "no-access"
readonly self: boolean
readonly message: string
}> {}api functionsrc/server/apis.ts
Declare an external API in server/apis.ts, then run canica apis:
export const github = api({
openapi: "https://raw.githubusercontent.com/github/rest-api-description/main/descriptions/api.github.com/api.github.com.json",
operations: ["issues/list-for-repo", "issues/create"],
auth: bearer(secret("GITHUB_TOKEN")),
})
const api = (config: ApiConfig): ApiDeclaration => …bearer functionsrc/server/apis.ts
Authorization: Bearer <secret>.
const bearer = (value: SecretRef): ApiAuth => …header functionsrc/server/apis.ts
<name>: <secret>, e.g. header("x-api-key", secret("WEATHER_KEY")).
const header = (name: string, value: SecretRef): ApiAuth => …secret functionsrc/server/apis.ts
secret("GITHUB_TOKEN"): the value of canica secrets set GITHUB_TOKEN (.canica/secrets in dev).
const secret = (name: string): SecretRef => …none constsrc/server/apis.ts
No credential (a public API).
const none: ApiAuthApiFailed classsrc/server/apis.ts
The API could not be used: unreachable, an HTTP status its spec does not declare, a response that does not match
the spec, or a host not allowed. status is set when there was a response.
class ApiFailed extends TaggedError("ApiFailed")<{
readonly api: string
readonly operation: string
readonly status?: number
readonly message: string
}> {}IMAGE_WIDTHS constsrc/core/image-sizes.ts
The widths images are resized to (CSS pixels × 2 for sharp screens, snapped up to one of these).
const IMAGE_WIDTHS = [160, 320, 640, 1280] as constTypes
Id UserId Storage Presence FieldDef FieldDesc AnyField FieldType StringField NumberField BooleanField IdField UserIdField FileId FileField EmailId EmailIdField DayField LiteralField ArrayField PlainField Simplify TableDef Database Row DrizzleTable App AnyApp Schema QueryDef MutationDef ArgsOf QueriesOf MutationsOf ActionsOf AppApisOf ActionDef ActionCtx ActionFiles FileContent ActionBuilder CronDef ArgsType SuccessType ErrorType EmailDef EmailsOf EmailProps EndpointDef EndpointRequest EndpointResult EndpointMethod EndpointBuilder ViewerShape Profile RandomShape SchedulerShape FilesShape FileMeta EmailShape EmailState EmailStatus EmailFailure QueryServices MutationServices ActionServices SignedInViewer AuthConfig AccessLevel UiMode LucideIconName ApiAuth ApiConfig ApiDeclaration ApiError ApiOperation ApiStubs ApisOf BoundApi SecretRef Serialized Issue ImageSize ImageWidth FileUrlOptions
Id typesrc/server/fields.ts
A row id tagged with its table. Id<"todos"> is not assignable to Id<"users">.
type Id<Table extends string> = string & { readonly [IdBrand]: Table }UserId typesrc/server/fields.ts
A Canica user reference (guest or signed in).
type UserId = string & { readonly [UserIdBrand]: "UserId" }Storage typesrc/server/fields.ts
type Storage = "text" | "real" | "integer" | "json"Presence typesrc/server/fields.ts
type Presence = "required" | "optional" | "default"FieldDef interfacesrc/server/fields.ts
interface FieldDef<T, P extends Presence = "required"> {
readonly "~canica/field": true
readonly "~type": T
readonly "~presence": P
readonly kind: string
readonly storage: Storage
readonly schema: Schema.Top
readonly presence: P
readonly defaultValue?: unknown
/** Replaces every validation message of this field (forms and `InvalidArgs`). */
readonly errorMessage?: string
/** For `id("table")` fields: the referenced table. */
readonly table?: string
/** For `id("table")` fields: what happens to this row when the referenced row is deleted. */
readonly onDeleteAction?: "cascade"
/** For `userId()` fields. */
readonly isUserId?: boolean
/** For `file()` fields: the column holds an uploaded file's id (garbage collection scans these). */
readonly isFile?: boolean
/** For `cents()` fields: forms read "12.50" as 1250. */
readonly money?: boolean
/** For `literal(...)` fields: the allowed values. */
readonly values?: ReadonlyArray<string | number | boolean>
/** For `array(...)` fields: the item field. */
readonly item?: AnyField
/** How the field was built, as JSON (`fieldFromDesc` rebuilds it): deploys check data against a new schema with it. */
readonly desc: FieldDesc
}FieldDesc interfacesrc/server/fields.ts
A field as data: the builder, its args, then the chained calls.
interface FieldDesc {
readonly b: string
readonly a: ReadonlyArray<unknown>
readonly ops: ReadonlyArray<readonly [string, ...Array<unknown>]>
}AnyField typesrc/server/fields.ts
type AnyField = FieldDef<any, Presence>FieldType typesrc/server/fields.ts
type FieldType<F> = F extends FieldDef<infer T, any> ? T : neverStringField interfacesrc/server/fields.ts
interface StringField<P extends Presence = "required"> extends Common<string, P, StringSelf> {
/** Trim surrounding whitespace before validating. */
trim(): StringField<P>
min(length: number, message?: string): StringField<P>
max(length: number, message?: string): StringField<P>
/** Must match the pattern. */
pattern(regex: RegExp, message?: string): StringField<P>
/** Must look like an email address. */
email(message?: string): StringField<P>
/** Non-empty after any trim. */
nonEmpty(message?: string): StringField<P>
/** Lowercase the value (after trim). Handy for codes, emails and case-insensitive unique keys. */
lower(): StringField<P>
/** Uppercase the value (after trim). */
upper(): StringField<P>
}NumberField interfacesrc/server/fields.ts
interface NumberField<P extends Presence = "required"> extends Common<number, P, NumberSelf> {
int(message?: string): NumberField<P>
min(value: number, message?: string): NumberField<P>
max(value: number, message?: string): NumberField<P>
}BooleanField interfacesrc/server/fields.ts
interface BooleanField<P extends Presence = "required"> extends Common<boolean, P, BooleanSelf> {}IdField interfacesrc/server/fields.ts
interface IdField<Table extends string, P extends Presence = "required"> extends Common<Id<Table>, P, IdSelf<Table>> {
/**
* Delete this row when the referenced row is deleted. The table needs an
* index whose first field is this one.
*/
onDelete(action: "cascade"): IdField<Table, P>
}UserIdField interfacesrc/server/fields.ts
interface UserIdField<P extends Presence = "required"> extends Common<UserId, P, UserIdSelf> {}FileId typesrc/server/fields.ts
The id of an uploaded file (file() fields, useUpload(), files.url(id)).
type FileId = Id<"_files">FileField interfacesrc/server/fields.ts
interface FileField<P extends Presence = "required"> extends Common<FileId, P, FileSelf> {}EmailId typesrc/server/fields.ts
The id of a queued email: what (yield* Email).send(…) returns; (yield* Email).status(id) reads its state.
type EmailId = Id<"_emails">EmailIdField interfacesrc/server/fields.ts
interface EmailIdField<P extends Presence = "required"> extends Common<EmailId, P, EmailIdSelf> {}DayField interfacesrc/server/fields.ts
interface DayField<P extends Presence = "required"> extends Common<string, P, DaySelf> {}LiteralField interfacesrc/server/fields.ts
interface LiteralField<T, P extends Presence = "required"> extends Common<T, P, LiteralSelf<T>> {}ArrayField interfacesrc/server/fields.ts
interface ArrayField<T, P extends Presence = "required"> extends Common<ReadonlyArray<T>, P, ArraySelf<T>> {
/** At least `n` items. */
min(n: number, message?: string): ArrayField<T, P>
/** At most `n` items. */
max(n: number, message?: string): ArrayField<T, P>
/** At least one item. */
nonEmpty(message?: string): ArrayField<T, P>
}PlainField interfacesrc/server/fields.ts
interface PlainField<T, P extends Presence = "required"> extends Common<T, P, PlainSelf<T>> {}Simplify typesrc/server/fields.ts
type Simplify<T> = { [K in keyof T]: T[K] } & {}TableDef interfacesrc/server/table.ts
interface TableDef<F extends Fields = Fields, I extends Indexes = {}, U extends string = never> {
readonly "~canica/table": true
readonly fields: F
readonly indexes: I
/** Names of indexes declared with `.unique(...)`. */
readonly uniques: ReadonlyArray<U>
/** Unique indexes that compare text case-insensitively. */
readonly nocase: ReadonlyArray<string>
/**
* Declare an index (SQL `CREATE INDEX`, with an implicit `createdAt, id` suffix). Add one for the columns
* your queries filter on (`where(eq(todos.owner, …))`), so reads stay fast as tables grow.
*/
index<const N extends string, const IF extends ReadonlyArray<IndexableFields<F>>>(
name: N,
fields: IF,
): TableDef<F, Simplify<I & { readonly [K in N]: IF }>, U>
/**
* Declare a unique index: no two rows may have the same values for these fields.
* Check first in the mutation (`select … where`) and fail with your own error; a violation is a defect.
* `{ caseInsensitive: true }` treats "Ana" and "ana" as the
* same value (ASCII letters) while storing what the user typed.
*/
unique<const N extends string, const IF extends ReadonlyArray<IndexableFields<F>>>(
name: N,
fields: IF,
options?: { readonly caseInsensitive?: boolean },
): TableDef<F, Simplify<I & { readonly [K in N]: IF }>, U | N>
}Database interfacesrc/server/db.ts
const db = yield* Db: Drizzle's query builder (https://orm.drizzle.team/docs/select), synchronous and
reactive. Import conditions from canica/server (eq, and, desc, …).
interface Database {
/** `yield* db.select().from(todos).where(eq(todos.owner, viewer.userId)).orderBy(desc(todos.createdAt)).limit(50)` */
readonly select: ReadDb["select"]
readonly selectDistinct: ReadDb["selectDistinct"]
/** Mutations only. `yield* db.insert(todos).values({ text, owner }).returning()` */
readonly insert: WriteDb["insert"]
/** Mutations only. `yield* db.update(todos).set({ done: true }).where(eq(todos.id, id))` */
readonly update: WriteDb["update"]
/** Mutations only. Rows pointing here with `.onDelete("cascade")` go too. */
readonly delete: WriteDb["delete"]
/** The row with this id, or fails with `NotFound`. */
get<R extends { readonly id: string }>(table: SQLiteTable & { readonly $inferSelect: R }, id: R["id"]): Effect.Effect<R, NotFound>
/** Number of rows (matching `where`). */
count(table: AnyDrizzleTable, where?: SQL): Effect.Effect<number>
}Row typesrc/server/db.ts
A row of a table: type Todo = Row<typeof todos>.
type Row<T extends { readonly $inferSelect: unknown }> = T["$inferSelect"]DrizzleTable typesrc/server/db.ts
The Drizzle table of a Canica table (tables.todos).
type DrizzleTable<Name extends string, T extends AnyTable> = SQLiteTableWithColumns<{
name: Name
schema: undefined
columns: BuildColumns<Name, ColumnsOf<Name, T>, "sqlite">
dialect: "sqlite"
isAlias: false
}>App interfacesrc/server/app.ts
interface App<
S extends SchemaDef = SchemaDef,
Q = Record<string, QueryDef>,
M = Record<string, MutationDef>,
I = Record<string, MutationDef>,
Act = Record<string, ActionDef>,
Ap = Record<string, BoundApi>,
Em = Record<string, EmailDef>,
> {
readonly "~canica/app": true
/** `app({ access })`, default "signedIn": who may use it unless the platform says otherwise (`canica access`). */
readonly access: AccessLevel
readonly name: string
/** `name` as the app gave it (undefined: the build names it after canica.json or package.json). */
readonly givenName?: string
/** `app({ icon })`: a Lucide icon's name (the build draws it). */
readonly icon?: string
readonly installPrompt: boolean
/** `app({ ui })`, default "canica". */
readonly ui: UiMode
readonly schema: S
/** The Drizzle tables (internal: engine, fixtures). */
readonly tables: Readonly<Record<string, unknown>>
readonly queries: Q
readonly mutations: M
readonly internal: I
readonly actions: Act
/** `app({ apis })`, bound to their generated clients. */
readonly apis: Ap
readonly crons: Readonly<Record<string, CronDef>>
/** `app({ endpoints })`, by name. */
readonly endpoints: Readonly<Record<string, EndpointDef>>
readonly auth: AuthConfig
/** `app({ emails })`: the email templates. */
readonly emails: Em
}AnyApp typesrc/server/app.ts
type AnyApp = App<SchemaDef, Record<string, QueryDef>, Record<string, MutationDef>, Record<string, MutationDef>, Record<string, ActionDef>, Record<string, BoundApi>, Record<string, EmailDef>>Schema interfacesrc/server/app.ts
interface Schema<S extends SchemaDef> {
/** The tables, for queries: `const { todos } = tables` then `db.select().from(todos)`. */
readonly tables: DrizzleTables<S>
/** The database: `const db = yield* Db`. */
readonly Db: Context.Service<CanicaDb, Database>
/** Put the queries and mutations together. `export default` the result from `server/index.ts`. */
app<
Q extends Record<string, QueryDef> = {},
M extends Record<string, MutationDef> = {},
I extends Record<string, MutationDef> = {},
Act extends Record<string, ActionDef> = {},
Ap extends Record<string, BoundApi> = {},
Em extends Record<string, EmailDef> = {},
>(config: AppConfig<Q, M, I, Act, Ap, Em>): App<S, Q, M, I, Act, Ap, Em>
}QueryDef interfacesrc/server/app.ts
interface QueryDef<Args = any, A = any, E = any> {
readonly kind: "query"
readonly args: ArgsFields
readonly handler: (args: any) => Generator<any, any, any>
readonly "~types"?: { readonly args: Args; readonly success: A; readonly error: E }
}MutationDef interfacesrc/server/app.ts
interface MutationDef<Args = any, A = any, E = any> {
readonly kind: "mutation"
readonly args: ArgsFields
readonly handler: (args: any) => Generator<any, any, any>
readonly "~types"?: { readonly args: Args; readonly success: A; readonly error: E }
}ArgsOf typesrc/server/app.ts
type ArgsOf<F extends ArgsFields> = Simplify<
{ readonly [K in ArgsRequired<F>]: FieldType<F[K]> } & { readonly [K in ArgsOptional<F>]?: FieldType<F[K]> }
>QueriesOf typesrc/server/app.ts
type QueriesOf<T> = T extends App<any, infer Q, any, any, any, any> ? Q : neverMutationsOf typesrc/server/app.ts
type MutationsOf<T> = T extends App<any, any, infer M, any, any, any> ? M : neverActionsOf typesrc/server/app.ts
The actions clients may call (not action.internal).
type ActionsOf<T> = T extends App<any, any, any, any, infer Act, any> ? { [K in keyof Act as Act[K] extends { readonly internal: true } ? never : K]: Act[K] } : neverAppApisOf typesrc/server/app.ts
The app's apis (bound declarations).
type AppApisOf<T> = T extends App<any, any, any, any, any, infer Ap> ? Ap : neverActionDef interfacesrc/server/app.ts
interface ActionDef<Args = any, A = any, E = any, Internal extends boolean = boolean> {
readonly kind: "action"
/** Clients and agents cannot call it (crons, the scheduler, other actions and `canica run` can). */
readonly internal: Internal
readonly args: ArgsFields
readonly handler: (ctx: ActionCtx<any, any, any>, args: any) => Generator<any, any, any>
readonly "~types"?: { readonly args: Args; readonly success: A; readonly error: E }
}ActionCtx interfacesrc/server/app.ts
What an action gets: the viewer, the clock, the network, secrets, the app's APIs, queries and mutations.
interface ActionCtx<Q = Record<string, QueryDef>, M = Record<string, MutationDef>, Ap = Record<string, BoundApi>> {
/** Who called it (a scheduled job: who scheduled it; a cron: the system user). */
readonly viewer: ViewerShape
/** The time, in epoch ms. */
now(): number
/** `ctx.secrets.GITHUB_TOKEN`: `CANICA_SECRET_GITHUB_TOKEN` in production, `.env` or `.canica/secrets` in dev. A missing one is a bug. */
readonly secrets: Readonly<Record<string, string>>
/**
* The APIs of `app({ apis })` (declared in `server/apis.ts`, generated by `canica apis`), typed by their OpenAPI
* spec: `yield* ctx.apis.github.issuesListForRepo({ owner, repo, state: "open" })`. Canica adds the credential
* (only for the API's hosts) and checks responses against the spec. Fails with `ApiFailed` or the statuses the
* spec declares (`IssuesListForRepo404`, with its `body`).
*/
readonly apis: ApisOf<Ap>
/**
* GET (or `init`) a URL and decode its JSON with a field (`array(object({ title: string() }))`) or an Effect
* Schema. Fails with `FetchFailed` when unreachable, on an HTTP error status (`status`) or when the body does not match.
*/
fetchJson<F extends AnyField>(url: string | URL, schema: F, init?: RequestInit): Effect.Effect<FieldType<F>, FetchFailed>
fetchJson<A>(url: string | URL, schema: Schema.Decoder<A>, init?: RequestInit): Effect.Effect<A, FetchFailed>
/**
* GET (or `init`) a URL and read its body as text (HTML, CSV, plain text). Fails with `FetchFailed` when
* unreachable or on an HTTP error status (`status`).
*/
fetchText(url: string | URL, init?: RequestInit): Effect.Effect<string, FetchFailed>
/** The raw network, for what `apis`, `fetchJson` and `fetchText` do not cover (tests stub it). Fails with `FetchFailed` when unreachable; check `res.ok`. */
fetch(input: string | URL, init?: RequestInit): Effect.Effect<Response, FetchFailed>
/** Run a query once, as `viewer` (not live). Fails with its typed errors. */
runQuery<N extends keyof Q & string>(name: N, ...args: OptionalArgs<ArgsType<Q[N]>>): Effect.Effect<SuccessType<Q[N]>, ErrorType<Q[N]>>
/** Run a mutation (public or internal) in its own transaction, as `viewer`. Fails with its typed errors. */
runMutation<N extends keyof M & string>(name: N, ...args: OptionalArgs<ArgsType<M[N]>>): Effect.Effect<SuccessType<M[N]>, ErrorType<M[N]>>
/** Run another action, as `viewer`. Its result and errors are untyped: prefer a shared generator function. */
runAction(name: string, args?: Record<string, unknown>): Effect.Effect<unknown, { readonly _tag: string; readonly message?: string }>
/** `ctx.scheduler.runAfter(ms, name, args)`. */
readonly scheduler: SchedulerShape
/** `ctx.files.store(blob, { name })` → id, `ctx.files.get(id)` → Blob, `meta`, `url`. */
readonly files: ActionFiles
}ActionFiles interfacesrc/server/app.ts
Files in actions: save bytes from elsewhere, read a file, link to it.
interface ActionFiles {
/**
* Save a file (a `Blob`, bytes or a fetched `Response`) as the action's viewer; then store the id with a mutation
* (`ctx.runMutation("setImage", { id, image })`), or it is deleted after 24 h. A `Response` with an error status
* fails with `FetchFailed`. Counts against the app's file limits like an upload.
*/
store(
data: Blob | ArrayBuffer | Uint8Array | Response,
options: { readonly name: string; readonly type?: string },
): Effect.Effect<FileId, FileTooLarge | StorageFull | FetchFailed>
/** The file: its name, type, size and bytes (`.text()` reads them as UTF-8; pass `.bytes` as a fetch body). */
get(id: FileId): Effect.Effect<FileContent, NotFound>
/** Name, type, size and upload time. */
meta(id: FileId): Effect.Effect<FileMeta, NotFound>
/** A signed link, like `files.url` in a query. */
url(id: FileId, options?: FileUrlOptions): string
}FileContent interfacesrc/server/app.ts
A file read in an action.
interface FileContent extends FileMeta {
readonly bytes: Uint8Array
/** The bytes as UTF-8 text. */
text(): string
}ActionBuilder interfacesrc/server/app.ts
interface ActionBuilder<Q, M, Ap = {}, Internal extends boolean = false> {
/**
* Work with the outside world: network calls, secrets, then a mutation to save the result. Not transactional,
* not live, no `Db`: pages see what it saved through their live queries.
*
* ```ts
* syncIssues: action({ owner: string(), repo: string() }, function* (ctx, { owner, repo }) {
* const issues = yield* ctx.apis.github.issuesListForRepo({ owner, repo, state: "open" })
* return yield* ctx.runMutation("saveIssues", { repo, titles: issues.map((i) => i.title) })
* })
* ```
*/
<A, Eff extends Effect.Effect<any, any, any> = never>(
handler: ((ctx: ActionCtx<Q, M, Ap>) => Generator<Eff, A, any>) & Capability<Eff, ActionServices, "Actions">,
): ActionDef<{}, A, ErrorOf<Eff>, Internal>
<const F extends ArgsFields, A, Eff extends Effect.Effect<any, any, any> = never>(
args: F,
handler: ((ctx: ActionCtx<Q, M, Ap>, args: ArgsOf<F>) => Generator<Eff, A, any>) & Capability<Eff, ActionServices, "Actions">,
): ActionDef<ArgsOf<F>, A, ErrorOf<Eff>, Internal>
}CronDef interfacesrc/server/app.ts
A job that runs every every ("15 minutes", "1 hour", "1 day") as the system user.
interface CronDef<N extends string = string> {
readonly every: Duration.Input
/** A mutation or action, public or internal. */
readonly run: N
readonly args?: Record<string, unknown>
}ArgsType typesrc/server/app.ts
type ArgsType<D> = D extends { readonly "~types"?: { readonly args: infer A } } ? A : neverSuccessType typesrc/server/app.ts
type SuccessType<D> = D extends { readonly "~types"?: { readonly success: infer A } } ? A : neverErrorType typesrc/server/app.ts
type ErrorType<D> = D extends { readonly "~types"?: { readonly error: infer E } } ? E : neverEmailDef interfacesrc/server/app.ts
An email template (email({ props, subject, preview }, (props) => <Text>…</Text>) from canica/email). The
component is only the body: Canica adds the app's name and icon above it and the unsubscribe footer below.
interface EmailDef<P = any> {
readonly kind: "email"
/** The props' fields (validated on every send, like mutation args). */
readonly props: ArgsFields
/** The subject line, from the props. */
readonly subject: (props: any) => string
/** Sample props: the dev outbox, `canica emails` and the storyboard render the template with them. */
readonly preview: Readonly<Record<string, unknown>>
/** The body: a React Email element from the props. */
readonly component: (props: any) => unknown
/** @internal Renders the body to HTML and plain text (set by `email()`, which brings the renderer). */
readonly "~render": (props: any) => { readonly html: string; readonly text: string }
readonly "~types"?: { readonly props: P }
}EmailsOf typesrc/server/app.ts
The app's email templates (app({ emails })).
type EmailsOf<T> = T extends App<any, any, any, any, any, any, infer Em> ? Em : neverEmailProps typesrc/server/app.ts
The props a template takes.
type EmailProps<D> = D extends { readonly "~types"?: { readonly props: infer P } } ? P : neverEndpointDef interfacesrc/server/app.ts
interface EndpointDef {
readonly kind: "endpoint"
readonly method: EndpointMethod
readonly path: string
readonly handler: (ctx: ActionCtx<any, any, any>, request: EndpointRequest) => Generator<any, EndpointResult, any>
}EndpointRequest interfacesrc/server/app.ts
The request an endpoint answers. The body is read once, by whichever of text, bytes or json comes first.
interface EndpointRequest<P extends string = string> {
readonly method: EndpointMethod
readonly url: URL
/** The `:name` segments of the endpoint's path: `/api/orders/:id` → `params.id`. */
readonly params: string extends P ? Readonly<Record<string, string>> : { readonly [K in PathParams<P>]: string }
/** The query string: `query.get("page")`. */
readonly query: URLSearchParams
readonly headers: Headers
/** The body as text (a webhook's signature is computed over it). Fails with `InvalidArgs` over 1 MB. */
text(): Effect.Effect<string, InvalidArgs>
/** The body as bytes. Fails with `InvalidArgs` over 1 MB. */
bytes(): Effect.Effect<Uint8Array, InvalidArgs>
/**
* The body as JSON, checked like mutation args: `yield* request.json({ email: string(), amount: cents() })`, or
* one field (`array(object({ … }))`). Fails with `InvalidArgs` (the endpoint answers 400) when it is not JSON or
* does not match.
*/
json<F extends AnyField>(field: F): Effect.Effect<FieldType<F>, InvalidArgs>
json<const F extends ArgsFields>(fields: F): Effect.Effect<ArgsOf<F>, InvalidArgs>
}EndpointResult typesrc/server/app.ts
What an endpoint returns: a Response as is; undefined → 204; anything else → 200 with it as JSON. A typed
error answers JSON { error: { _tag, … } }: 400 for InvalidArgs, 404 for NotFound, 422 for the app's own;
a bug answers 500.
type EndpointResult = Response | Record<string, unknown> | ReadonlyArray<unknown> | string | number | boolean | null | undefined | voidEndpointMethod typesrc/server/app.ts
type EndpointMethod = (typeof ENDPOINT_METHODS)[number]EndpointBuilder typesrc/server/app.ts
endpoint.post("/api/stripe", function* (ctx, request) { … }): an HTTP route at https://<app>.canica.run/api/…
for webhooks and other servers. Anyone may call it (whatever access says) and it runs as the system user, like
a cron: check who is calling yourself (a signature or a token against ctx.secrets). ctx is an action's.
type EndpointBuilder<Q, M, Ap> = {
readonly [K in Lowercase<EndpointMethod>]: <const P extends `/api/${string}`>(path: P, handler: EndpointHandler<Q, M, Ap, P>) => EndpointDef
}ViewerShape interfacesrc/server/services.ts
interface ViewerShape {
/** Stable id for this person. Guests get one automatically; it stays the same when a guest signs in. */
readonly userId: UserId
/** A browser session without an account. */
readonly isGuest: boolean
/** Signed in with an account (Google, or the dev provider locally). A guest is not signed in. */
readonly isSignedIn: boolean
/** Name, email and picture from the provider, when signed in. */
readonly profile?: Profile
}Profile interfacesrc/server/services.ts
What a sign-in provider tells about a person. Display only: never authorize on it.
interface Profile {
readonly name?: string
readonly email?: string
readonly picture?: string
}RandomShape interfacesrc/server/services.ts
interface RandomShape {
/** Integer in [min, max]. */
readonly int: (min: number, max: number) => number
/** Random string, e.g. an invite code. Default alphabet avoids look-alike characters. */
readonly string: (length: number, alphabet?: string) => string
readonly uuid: () => string
}SchedulerShape interfacesrc/server/services.ts
interface SchedulerShape {
/**
* Run a mutation or action (public or internal) after `ms`, as the same user. From a mutation the job is
* saved with its writes: it only runs if the mutation commits. Args are checked now (and typed, like
* `ctx.runMutation`).
*/
runAfter<N extends keyof Jobs & string>(ms: number, name: N, ...args: JobArgs<N>): void
}FilesShape interfacesrc/server/services.ts
interface FilesShape {
/**
* A link to the file for whoever gets this query's result: `/_canica/files/<id>?e=…&s=…`, signed, valid until the
* next full hour plus one (the same link all hour, so live queries do not churn and browsers cache it; pages that
* stay open get a fresh one). Only people who can read the row get the link: no link, no access.
*
* Images: `files.url(id, { size: "thumb" })` (320 px wide), `"medium"` (640), `"large"` (1280), or `{ width }`
* (snapped up to 160/320/640/1280): WebP, resized once and kept. The page may ask any smaller width of the list
* (`<Thumbnail>` does, at twice its size on screen); the original needs `size: "full"` (the default). Not an
* image (or not resizable: SVG, AVIF…): the file as is.
*/
url(id: FileId, options?: FileUrlOptions): string
/** Name, type, size and upload time; fails with `NotFound` when there is no such file (or it was deleted). */
meta(id: FileId): Effect.Effect<FileMeta, NotFound>
/** Delete the file now (mutations only; when the mutation commits). Files no row refers to are also deleted by themselves. */
delete(id: FileId): Effect.Effect<void, never, CanicaWrite>
}FileMeta interfacesrc/server/services.ts
What Canica knows about an uploaded file.
interface FileMeta {
readonly id: FileId
/** The name it was uploaded with (as the person's computer called it). */
readonly name: string
/** Its media type as uploaded ("image/png"); served as a download unless it is a safe type to show. */
readonly type: string
/** Bytes. */
readonly size: number
/** When it was uploaded (epoch ms). */
readonly uploadedAt: number
}EmailShape interfacesrc/server/services.ts
interface EmailShape {
/**
* Email one of the app's users with a template of `app({ emails })`. `to` is a user id: Canica sends to the address
* Google verified when they signed in to this app. In a mutation it is queued with its writes and sent after it
* commits (a rolled-back mutation sends nothing); in an action it is queued at once. Returns the email's id (for
* `status(id)`). Fails (and queues nothing) with `NotARecipient` (never signed in here with Google, signed in before
* the app kept sign-in proofs: `reason: "sign-in-again"`, or the app's
* access no longer lets them in), `Unsubscribed` (they used the footer's link) or `EmailLimitReached` (the app's
* daily emails, or this person's).
*/
send<N extends keyof Emails & string>(
template: N,
options: SendOptions<string extends keyof Emails ? Record<string, unknown> : EmailProps<Emails[N]>>,
): Effect.Effect<EmailId, EmailLimitReached | Unsubscribed | NotARecipient, CanicaSend>
/**
* Where an email is now (queued → sending → sent | failed). In a query it is live: the page updates as
* the email moves. Fails with `NotFound` for an unknown id (or one older than 30 days). Anyone who has the id can
* read it: check `status.to` before showing it.
*/
status(id: EmailId): Effect.Effect<EmailStatus, NotFound>
}EmailState typesrc/server/services.ts
Where an email is: queued (waiting for its turn, or for its next try), sending (with the platform's relay now),
sent (the platform took it), or failed (see reason; not tried again). The same everywhere: deployed, on the
dev server and in tests (where nothing leaves: the dev outbox shows it).
type EmailState = "queued" | "sending" | "sent" | "failed"EmailStatus interfacesrc/server/services.ts
What (yield* Email).status(id) tells about one email.
interface EmailStatus {
readonly id: EmailId
readonly template: string
/** The recipient (check it is the viewer before showing it to them). */
readonly to: UserId
readonly state: EmailState
/** Why it failed (`state: "failed"`); null otherwise. */
readonly reason: EmailFailure | null
/** The last problem in words: why it failed, or why the last try did not go through (a `queued` email being retried). */
readonly message: string | null
/** Tries so far (a try that could not reach the relay is tried again, up to 6 times over about a day). */
readonly attempts: number
/** When it was queued (epoch ms). */
readonly queuedAt: number
}EmailFailure typesrc/server/services.ts
Why an email failed: the person unsubscribed, is not-a-recipient any more (access, no sign-in proof), the
daily limit, the address bounced, they complained (marked it as spam), the app is suspended from sending,
sending is off on the platform, the body was invalid, the template is gone or failed to render, or the
relay could not take it (after its last try).
type EmailFailure = "unsubscribed" | "not-a-recipient" | "limit" | "bounced" | "complained" | "suspended" | "off" | "invalid" | "template" | "relay"QueryServices typesrc/server/services.ts
type QueryServices = CanicaDb | CanicaViewer | CanicaFiles | CanicaEmailMutationServices typesrc/server/services.ts
type MutationServices = QueryServices | CanicaWrite | CanicaNow | CanicaRandom | CanicaScheduler | CanicaSendActionServices typesrc/server/services.ts
Actions have no database (they call queries and mutations through ctx); Viewer works, e.g. requireSignIn, and Email.
type ActionServices = CanicaViewer | CanicaEmail | CanicaSendSignedInViewer interfacesrc/server/auth.ts
A viewer known to be signed in.
interface SignedInViewer extends ViewerShape {
readonly isSignedIn: true
readonly isGuest: false
readonly profile: Profile
}
const SignedInViewer: Effect.Effect<SignedInViewer, never, CanicaViewer>AuthConfig interfacesrc/server/app.ts
interface AuthConfig {
/**
* @deprecated Apps require signing in by default now (`app({ access: "signedIn" })`): remove it. Kept so older
* apps still load; it cannot be combined with `access: "public"`.
*/
readonly requireSignIn?: boolean
/**
* Public apps only (guests sign in there): runs (as a mutation, in the same transaction) when a guest signs in to
* an account that already existed, before Canica moves the guest's `userId()` fields to the account. Use it to
* merge rows that would conflict (e.g. a unique "one profile per user"). Args: `{ guestUserId, userId }`.
*
* ```ts
* onGuestUpgrade: mutation({ guestUserId: userId(), userId: userId() }, function* ({ guestUserId, userId }) { … })
* ```
*/
readonly onGuestUpgrade?: MutationDef<{ readonly guestUserId: UserId; readonly userId: UserId }, unknown, unknown>
}AccessLevel typesrc/server/app.ts
Who may use the app: signedIn (the default: anyone signed in with a Google account), org (the app's
organization: its members and its Workspace domain), private (the owner and the people they add) or public
(anyone, guests without an account too). Deployed, canica access can change it; canica access reset goes back
to this value.
type AccessLevel = "public" | "signedIn" | "org" | "private"UiMode typesrc/server/app.ts
Whose components draw the app: canica/ui's ("canica", the default) or the app's own ("own"). See app({ ui }).
type UiMode = "canica" | "own"LucideIconName typesrc/server/lucide-names.ts
A Lucide icon's name (https://lucide.dev/icons), e.g. "list-checks".
type LucideIconName =
| "a-arrow-down"
| "a-arrow-up"
| "a-large-small"
| "accessibility"
| "activity"
| "activity-square"
| "ad"
| "air-vent"
| "airplay"
| "alarm-check"
| "alarm-clock"
| "alarm-clock-check"
| "alarm-clock-minus"
| "alarm-clock-off"
| "alarm-clock-plus"
| "alarm-minus"
| "alarm-plus"
| "alarm-smoke"
| "album"
| "alert-circle"
| "alert-octagon"
| "alert-triangle"
| "align-center"
| "align-center-horizontal"
| "align-center-vertical"
| "align-end-horizontal"
| "align-end-vertical"
| "align-horizontal-distribute-center"
| "align-horizontal-distribute-end"
| "align-horizontal-distribute-start"
| "align-horizontal-justify-center"
| "align-horizontal-justify-end"
| "align-horizontal-justify-start"
| "align-horizontal-space-around"
| "align-horizontal-space-between"
| "align-justify"
| "align-left"
| "align-right"
| "align-start-horizontal"
| "align-start-vertical"
| "align-vertical-distribute-center"
| "align-vertical-distribute-end"
| "align-vertical-distribute-start"
| "align-vertical-justify-center"
| "align-vertical-justify-end"
| "align-vertical-justify-start"
| "align-vertical-space-around"
| "align-vertical-space-between"
| "ambulance"
| "ampersand"
| "ampersands"
| "amphora"
| "anchor"
| "angle"
| "angry"
| "annoyed"
| "antenna"
| "anvil"
| "aperture"
// …ApiAuth typesrc/server/apis.ts
How requests prove who the app is.
type ApiAuth =
| { readonly type: "none" }
| { readonly type: "bearer"; readonly secret: SecretRef }
| { readonly type: "header"; readonly name: string; readonly secret: SecretRef }ApiConfig interfacesrc/server/apis.ts
interface ApiConfig {
/** The OpenAPI (or Swagger 2) document: an https URL, or a path relative to the app (JSON or YAML). */
readonly openapi: string
/** The operationIds to keep (`"issues/list-for-repo"`, or its camelCase name). Keep bundles small. */
readonly operations?: ReadonlyArray<string>
/** Keep every operation with one of these tags (with or instead of `operations`). */
readonly tags?: ReadonlyArray<string>
/** `none` (default), `bearer(secret("NAME"))` or `header("x-api-key", secret("NAME"))`. */
readonly auth?: ApiAuth
/** Instead of the spec's first server, e.g. a GitHub Enterprise host. */
readonly baseUrl?: string
/** Hosts the credential may be sent to (redirects elsewhere go without it). Default: the base URL's host. */
readonly hosts?: ReadonlyArray<string>
}ApiDeclaration interfacesrc/server/apis.ts
interface ApiDeclaration extends ApiConfig {
readonly "~canica/api": true
readonly auth: ApiAuth
}ApiError interfacesrc/server/apis.ts
A status the spec declares for this operation (IssuesListForRepo404), with its body as the spec types it.
interface ApiError<Tag extends string, Body> extends Cause.YieldableError {
readonly _tag: Tag
readonly api: string
readonly operation: string
readonly status: number
readonly body: Body
readonly "~fields"?: { readonly api: string; readonly operation: string; readonly status: number; readonly body: Body }
}ApiOperation typesrc/server/apis.ts
One operation: path, query and header parameters by name, the request body as payload.
type ApiOperation<Args, A, E> = {} extends Args ? (args?: Args) => Effect.Effect<A, E> : (args: Args) => Effect.Effect<A, E>ApiStubs typesrc/server/apis.ts
What tests answer for an operation: its value, or a Response decoded as the API's would be (typed errors too).
type ApiStubs<Ap> = {
readonly [K in keyof Ap]?: Ap[K] extends BoundApi<infer Ops>
? {
readonly [O in keyof Ops]?: Ops[O] extends (...args: infer P) => Effect.Effect<infer A, any>
? (args: NonNullable<P[0]>) => A | Response | Promise<A | Response>
: never
}
: never
}ApisOf typesrc/server/apis.ts
The operations of app({ apis }), as actions see them in ctx.apis.
type ApisOf<Ap> = { readonly [K in keyof Ap]: Ap[K] extends BoundApi<infer Ops> ? Ops : never }BoundApi interfacesrc/server/apis.ts
A declaration bound to its generated client (server/apis.gen/index.ts); pass them as app({ apis }).
interface BoundApi<Ops = Record<string, (args?: any) => Effect.Effect<any, any>>> {
readonly "~canica/boundApi": true
readonly name: string
readonly declaration: ApiDeclaration
readonly generated: GeneratedApi
/** The operations for one engine (its network, secrets and test stubs). */
readonly connect: (runtime: ApiRuntime) => Record<string, (args?: any) => Effect.Effect<any, any>>
readonly "~ops"?: Ops
}SecretRef interfacesrc/server/apis.ts
A secret by name (canica secrets set NAME): read when a request is sent, never shown to the app's code.
interface SecretRef {
readonly "~canica/secret": string
}Serialized typesrc/server/errors.ts
A plain-object view of a typed error, exactly as the client receives it.
type Serialized<E> = E extends { readonly _tag: infer T; readonly "~fields"?: infer A }
? Simplify<{ readonly _tag: T; readonly message?: string } & Readonly<A>>
: E extends { readonly _tag: infer T }
? { readonly _tag: T; readonly message?: string }
: neverIssue interfacesrc/server/errors.ts
interface Issue {
/** Where the problem is, e.g. `["options", 2]`. Empty for the whole value. */
readonly path: ReadonlyArray<string | number>
readonly message: string
}ImageSize typesrc/core/image-sizes.ts
Named sizes: thumb 320 px wide, medium 640, large 1280, full the original file.
type ImageSize = "thumb" | "medium" | "large" | "full"ImageWidth typesrc/core/image-sizes.ts
type ImageWidth = (typeof IMAGE_WIDTHS)[number]FileUrlOptions interfacesrc/core/image-sizes.ts
interface FileUrlOptions {
/** `"thumb"` (320 px wide), `"medium"` (640), `"large"` (1280) or `"full"` (the original, the default). */
readonly size?: ImageSize
/** A width in pixels instead, snapped up to 160, 320, 640 or 1280 (larger: 1280). */
readonly width?: number
}Re-exported
From drizzle-orm, as they are: and, or, not, eq, ne, gt, gte, lt, lte, inArray, notInArray, isNull, isNotNull, between, like, asc, desc, count, sum, max, min, sql.