# Reference

Every export of every `@aozumi/fold` entry point (v0.1.0), one line each.

App code may import only `@aozumi/fold/server` (in `server/`) and `@aozumi/fold/client` (in `client/`). The other entry points are used by the CLI and by Fold hosts. They are listed for completeness. For CLI commands, claiming, and domains, see [CLI](/fold/cli/).

## @aozumi/fold/server

Definition:

- `fold(definition)`: defines the app. Keys: `name`, `favicon`, `auth`, `schema`, `queries`, `mutations`, `actions`, `endpoints`. See [Fold API](/fold/fold-api/).
- `query(handler)`: a read-only, live handler `(ctx: QueryServerContext, ...args) => result`.
- `mutation(handler)`: a transactional write handler `(ctx: ServerContext, ...args) => result`.
- `action(handler)`: a one-shot read-only handler `(ctx: ActionServerContext, ...args) => result`.
- `endpoint(route, handler)`: an HTTP route; `route` is `{ method, path, readOnly? }`, handler is `(ctx, req: EndpointRequest) => response`.
- `json(value, options?)`: JSON `EndpointResponse`; options `{ status?, headers? }`.
- `text(value, options?)`: plain-text `EndpointResponse`.
- `empty(options?)`: `EndpointResponse` with no body.
- `redirect(url, options?)`: redirect `EndpointResponse`.
- `createAuthContext(auth)`: builds an `AuthContext` from a raw auth value; Fold calls this for you.

Schema:

- `table(fields)`: a `TableDefinition`; chain `.index(name, fields)`.
- `string()`: string field.
- `number()`: finite number field.
- `boolean()`: boolean field.
- `id(tableName)`: field holding a row ID of `tableName`.
- `userId()`: field holding a Fold user ID; follows guests to their account.

Types:

- `Field`: a field builder result, with `.optional()` and `.default(value)`.
- `TableDefinition`: a table: `fields`, `indexes`, `index()`.
- `Schema`: `Record<string, TableDefinition>`.
- `DefaultSchema`: `Schema`.
- `Id<TTable>`: a string ID branded with its table name.
- `PaginationOptions`: `{ cursor: string | null; numItems: number }`.
- `PaginationResult<T>`: `{ page: T[]; continueCursor: string | null; isDone: boolean }`.
- `AuthContext`: `Auth` plus `requireIdentity()` and `requireSignedIn()`.
- `QueryServerContext<TDb>`: `{ auth, db, env, log }` with a read database.
- `ServerContext<TDb>`: the same with a write database.
- `ActionServerContext<TDb>`: same as `QueryServerContext`.
- `DbContext`: `ReadDatabase`.
- `MutationDbContext`: `WriteDatabase`.
- `LogContext`: `{ info, warn, error }`, each `(message: string, data?: unknown) => void`.
- `FoldAuth<TSchema>`: `{ requireSignIn?: boolean; onGuestUpgrade?: (ctx, upgrade) => void | Promise<void> }`.
- `GuestUpgrade`: `{ guestUserId: string; userId: string }`.
- `FoldFavicon`: `string` (a path to the favicon file).
- `SchemaQueries<TSchema>`, `SchemaMutations<TSchema>`, `SchemaActions<TSchema>`: handler maps typed for a schema.
- `EndpointRoute`: `{ method; path; readOnly? }`, where `path` starts with `/`.
- `EndpointHeaders`: `{ get(name); has(name); entries() }`.
- `EndpointRequest`: `{ method, path, url, headers, query, text(), json<T>(), bytes() }`.
- `EndpointResponse`: `{ kind: "response"; status; headers; body }`.
- `EndpointResponseOptions`: `{ status?; headers? }`.
- `EndpointDefinition`: what `endpoint()` returns.
- `Fold<TDefinition>`: what `fold()` returns; pass `typeof app` to `createClient`.
- `SchemaOf<T>`, `ReadDatabaseOf<T>`, `WriteDatabaseOf<T>`: the schema and database types of a fold definition.
- `QueryName<T>`, `QueryArgs<T, N>`, `QueryResult<T, N>`: query names, argument tuple, and result of a fold definition.
- `MutationName<T>`, `MutationArgs<T, N>`, `MutationResult<T, N>`: the same for mutations.
- `ActionName<T>`, `ActionArgs<T, N>`, `ActionResult<T, N>`: the same for actions.

## @aozumi/fold/client

Data:

- `createClient<typeof app>(options?)`: typed client with `useQuery`, `useMutation`, `useAction`, `usePaginatedQuery`, `storage`; options `{ optimistic?: boolean }`. See [Client](/fold/client/).
- `useQuery<TResult, TArgs>(name, args?)`: untyped live query; `undefined` until the first result.
- `useMutation<TArgs, TResult>(name)`: untyped mutation caller.
- `useAction<TArgs, TResult>(name)`: untyped action caller.
- `usePaginatedQuery<TResult, TArgs>(name, args, { initialNumItems? })`: untyped paginated query.
- `storage`: `{ upload(file, { public? }), delete(key) }`; hosted storage is coming soon. See [Storage](/fold/storage/).

Auth:

- `useAuth()`: current `AuthValue`.
- `SignInWithGoogle(props)`: sign-in button component.
- `signInWithGoogle(options?)`: starts Google sign-in; returns `Promise<{ bundle, url }>` and navigates.
- `signOut()`: ends the session; `Promise<void>`.
- `getIdentity()`: `{ userId: string | null; token?: string; expired?: boolean }`.
- `retryAuth()`: retries a failed session check; `Promise<void>`.
- `canAccessApp()`: `true` when the session is ready and meets `requireSignIn`.
- `decodeIdentityClaims(token)`: reads an identity token's claims without verifying it; `IdentityClaims | null`.

Routing:

- `Router`: router root component.
- `Routes`: renders the first matching `Route`.
- `Route`: `{ path, element }`; supports `:param` and `*`.
- `Link`: client-side link; `{ to, replace?, ...anchor props }`.
- `navigate(to, { replace? })`: navigate from code.
- `useNavigate()`: returns `navigate`.
- `useLocation()`: `{ pathname, search, hash, href }`.
- `useParams<T>()`: route parameters.

Other:

- `ErrorBoundary`: catches render errors, including query errors; `{ children, fallback?(error, retry) }`.

Types:

- `FoldClient<TFold>`: the type `createClient` returns.
- `PaginatedQueryResult<T>`: `{ page, continueCursor, isDone, loadMore(), reset() }`.
- `AuthValue`: `Auth` plus `isLoading`, `requireSignIn`, `error?`.
- `IdentityClaims`: identity token claims.
- `ErrorBoundaryProps`: `ErrorBoundary` props.
- `StorageClient`: the `storage` object type.
- `UploadedObject`: `{ contentType, key, size, url }`.

## @aozumi/fold/auth

Identity verification and guest sessions, used by Fold hosts and the dev server.

- `DEFAULT_AUTH_BASE_URL`: `"https://auth.aozumi.dev"`.
- `Auth`, `GuestAuth`, `SignedInAuth`, `SignedOutAuth`: the auth value types (see [Auth](/fold/auth/)).
- `createGuestAuth(name)`: a named local test identity.
- `createSignedOutAuth()`: the signed-out value.
- `isGuestAuth(auth)`, `isSignedInAuth(auth)`: type guards.
- `requireSignedIn(auth)`: returns the signed-in auth or throws `Sign in to continue.`
- `toDisplayName(name)`, `toGuestName(name)`: name normalizers.
- `decodeIdentityClaims(token)`: unverified claims of an identity token.
- `authBaseUrlFromEnv(env?)`: the sign-in service URL for this process.
- `hostRequestOrigin(req, canonicalUrl?)`: the app origin of a Node request.
- `verifyIdentityToken(options)`: `SignedInAuth | null`.
- `verifyIdentityTokenOutcome(options)`: `IdentityVerification` with a status.
- `authFromUrl(options)`: resolves `Auth` from a request URL.
- `authOutcomeFromUrl(options)`: resolves an `AuthOutcome` from a request URL.
- `authOutcomeAllowsAccess(outcome, policy)`: whether an outcome passes `"public"` or `"whitelist"`.
- `IdentityVerification`, `AuthOutcome`, `AuthOutcomeStatus`: result types.
- `createGuestSession(options)`, `verifyGuestSession(options)`, `verifyGuestSessionInTransaction(options)`: guest session cookies.
- `clearGuestSessionCookie(options)`, `guestSessionCookieName(scope)`: guest cookie helpers.
- `isSameOriginGuestRequest({ headers, origin })`: same-origin check for guest cookies.
- `GuestSessionVerification`: result type.

## @aozumi/fold/database

The database engine behind `ctx.db`. App code uses it only through `ctx.db`; the schema builders are re-exported by `./server`.

- Table API classes: `ReadTableApi`, `WriteTableApi`, `QueryBuilder`; `createReadDatabaseApi`, `createWriteDatabaseApi`.
- Query types: `QueryOrder`, `RangeOperator`, `RangeClause`, `IndexRange`, `SerializedQueryPlan`, `QueryTerminal`, `DatabaseOperation`, `DatabaseExecutor`, `PaginationOptions`, `PaginationResult`.
- Row types: `Row`, `RowMetadata`, `RowOf`, `ReadDatabase`, `WriteDatabase`, `ReadDatabaseFor`, `WriteDatabaseFor`.
- Schema builders: `table`, `string`, `number`, `boolean`, `id`, `userId`.
- Schema types: `ScalarValue`, `FieldKind`, `Field`, `AnyField`, `FieldType`, `FieldHasDefault`, `FieldIsOptional`, `TableColumns`, `InsertColumns`, `IndexDefinition`, `TableDefinition`, `Schema`, `SerializedField`, `SerializedTable`, `SerializedSchema`, `DatabaseManifest`.
- Schema constants: `DATABASE_API_VERSION` (1), `INDEX_CODEC_VERSION` (1), `BUILTIN_CREATION_INDEX` (`"by_creation"`), `MAX_INDEX_KEY_BYTES` (2048), `METADATA_FIELDS`.
- Schema helpers: `serializeSchema`, `isFieldKind`, `fullIndexFields`, `indexesForTable`, `indexForTable`, `fieldForTable`, `validateDatabaseString`, `validateScalar`, `validateFieldValue`, `resolveFieldValue`, `valueForRowField`, `materializeRowDefaults`.
- Sessions: `DatabaseSession`, `DatabaseReadLimits`, `DEFAULT_DATABASE_LIMITS`, `DatabaseReadOutcome`.
- Stores: `FoldStore`, `FoldReadTransaction`, `FoldWriteTransaction`, `FoldReadOptions`, `MemoryFoldStore`, `StoredRow`, `StoredGuestSession`, `IndexEntry`, `RowIndexEntry`, `IndexScanRequest`, `IndexCountRequest`, `IndexScanResult`, `TransactionLimits`, `DatabaseMetrics`, `assertTransactionDeadline`.
- Change journal: `FoldRowChange`, `FoldChangeResetReason`, `FoldChangeTransaction`, `FoldChangesPage`, `FoldChangesOptions`, `FOLD_CHANGE_JOURNAL_LIMITS`, `assertFoldChangeVersion`, `foldChangePageSize`.
- Index keys: `encodeIndexTuple`, `compareIndexKeys`, `prefixUpperBound`, `indexKeyToBase64`, `indexKeyFromBase64`.
- Cursors: `CursorPayload`, `queryFingerprint`, `encodeCursor`, `decodeCursor`.
- Export: `scanDatabaseExportPage`, `databaseExportPageLimit`, `isDatabaseExportCursorError`, `DatabaseExportCursorError`, `DatabaseExportSchemaChangedError`, `DatabaseExportPage`, `DatabaseExportPageRequest`, `DATABASE_EXPORT_PAGE_SIZE` (500), `DATABASE_EXPORT_PAGE_SIZE_MAX` (1000), `DATABASE_BACKUP_VERSION` (1), `DATABASE_EXPORT_CONSISTENCY`, `DATABASE_EXPORT_ROW_ORDER`, `DATABASE_EXPORT_TABLE_ORDER`.

## @aozumi/fold/storage

The host side of file storage. Hosted storage is coming soon.

- Limits: `STORAGE_MAX_FILE_BYTES` (5 MiB), `STORAGE_MAX_OWNER_BYTES` (100 MiB), `STORAGE_LIST_SCAN_MAX_OBJECTS` (10000), `STORAGE_BLOCKED_CONTENT_TYPES`.
- Requests: `handleStorageRequest`, `parseStorageRoute`, `StorageRequest`, `StorageRoute`, `StorageRequester`, `StorageHttpResult`.
- Providers: `StorageProvider`, `MemoryStorageProvider`, `StoragePutOptions`, `StorageObjectHead`, `StorageReadResult`, `StorageListOptions`, `StorageObjectSummary`, `StorageVisibility`.
- Keys: `ownerStoragePrefix`, `deployStoragePrefix`, `deployStorageObjectKey`, `newObjectId`.
- Listing and deletion: `listDeployStorageObjects`, `deleteStorageObject`, `DeployStorageObject`, `DeployStorageListing`.
- Content checks: `detectBlockedContent`.
- Errors: `StorageError` (with `code` and `status`), `StorageErrorCode`.
- Ledger: `StorageLedger`, `StorageLedgerUsage`, `StorageReservation`, `StorageReserveInput`, `storageLedgerUsage`.

## @aozumi/fold/anonymous

Artifact building and validation for anonymous deploys.

- Build: `createAnonymousArtifact`, `createClaimedArtifact`, `AnonymousCompilerError`.
- Validate: `validateAnonymousArtifact`, `validateAnonymousDeployPayload`, `validateServerEnvValues`, `validateServerEnvPayload`.
- Records: `prepareAnonymousInsert`, `prepareAnonymousPatch`.
- Limits: `DEFAULT_ANONYMOUS_LIMITS`, `SERVER_ENV_LIMITS`, `stateRowsLimitForLimits`, `mutationTransactionOptions`.
- Constants: `ANONYMOUS_ARTIFACT_FORMAT`, `ANONYMOUS_ARTIFACT_MEDIA_TYPE`, `ANONYMOUS_FETCH_DIAGNOSTIC`, `FOLD_CONFIG_FILE` (`"fold.json"`), `SERVER_ENV_FILE` (`".env.fold.server"`), `FOLD_VERSION`, `MAX_STABLE_JSON_DEPTH`.
- Helpers: `stableStringify`, `sha256`, `byteLength`, `parseTtlSeconds`, `createDeployId`, `createReportId`, `createClaimToken`, `createSlug`, `hashClaimToken`.
- Types: `AnonymousSourceArtifact`, `ClaimedSourceArtifact`, `FoldArtifact`, `ArtifactFavicon`, `FoldSchema`, `DeployTarget`, `QueryDefinition`, `MutationDefinition`, `ServerAuth`, `ServerIr`.

## @aozumi/fold/runtime

- `StateCell`: in-memory database cell used by the dev server.
- `LogBuffer`: bounded log buffer that creates `Logger`s.
- `Logger`, `LogEntry`, `LogLevel`: log types.
- `Row`, `DatabaseAuthorization`: database types.

## @aozumi/fold/source-store

- `MemorySourceStore`: in-memory fold source files.
- `createMemorySourceStoreFromDirectory(dir)`: loads a fold directory.
- `shouldSkipSourceEntry(entry)`: which files a build ignores.
- `sourcePathJoin(...parts)`, `sourcePathDirname(path)`: source path helpers.
- `SourceFiles`, `SourceStoreLike`: types.

## @aozumi/fold/cli

- `runCli(argv?)`: runs the CLI.
- `reportCliError(error)`: prints a CLI error.
- `buildFold(options)`: builds a fold.
- `startDevServer(options)`: starts the dev server programmatically.

## @aozumi/fold/command

- `cliPackageSpec`: `"@aozumi/fold"`.
- `cliCommand`: `"npx @aozumi/fold"`.
- `defaultHostedAppBaseDomain`: `"aozumi.site"`.

## @aozumi/fold/release

- `FOLD_RELEASE_CHANNEL`: `"production"`.
- `FOLD_DEPLOY_API_URL`: `"https://api.aozumi.dev"`.
- `FOLD_APP_BASE_DOMAIN`: `"aozumi.site"`.

## @aozumi/fold/subscription

- `subscriptionIdFromWireArgs(name, args)`: the subscription ID of a query call.

## @aozumi/fold/version

- `FOLD_VERSION`: the package version string.
