Connected apps with 3rd-party data hosts jsr.io/@civility
README.md

Internal: not meant to be used by applications directly

@civility/errors #

Shared error codes, response envelopes, and the CivilityApiError class used across every @civility/* package.

If you're writing an app against a Civility server, you probably only interact with this package through CivilityApiError — raised by @civility/cloud on failed requests and by SyncErrorEvent on background sync failures.

Install #

// deno.json
{
  "imports": {
    "@civility/errors": "jsr:@civility/errors@^0.10.0"
  }
}

Handling errors on the client #

@civility/cloud throws CivilityApiError from every SyncApi method and includes one on SyncErrorEvent.error. Branch on code or domain:

import { CivilityApiError } from '@civility/errors'

try {
  await synced.login(email, password)
} catch (e) {
  if (e instanceof CivilityApiError) {
    if (e.code === 'auth.invalid_credentials') showLoginError()
    else if (e.domain === 'quota') showUpgradePrompt()
    else if (e.domain === 'sync') showRetry()
    else throw e
  }
}

CivilityApiError exposes:

Field Type Notes
code ErrorCode Domain-prefixed string, e.g. 'auth.invalid_credentials'.
httpStatus number HTTP status from the server, or 0 for pre-request errors.
message string Human-readable; safe to surface for debugging.
messageKey string? Stable i18n key for this message variant, when sent.
details unknown Domain-specific payload (validation issues, quota info…).
domain ErrorDomain Getter returning the prefix ('auth', 'sync', …).

Writing a server route #

@civility/hono re-exports thin wrappers (ok(c, ...) / err(c, ...)) that wrap Hono's c.json() with the envelope builders from this package. If you're building a server route outside Hono, import the builders directly:

import { err, ok } from '@civility/errors'

if (!user) {
  return Response.json(err('auth.invalid_credentials', 'Bad creds'), {
    status: 401,
  })
}
return Response.json(ok({ user }))

Error codes #

Every code is a domain.specifier string. Known codes live in the ErrorCodes registry and autocomplete. The table below is generated from codes.ts by deno task docs — edit the registry (and its descriptions in docs.ts), not the table.

Code HTTP Use when
auth.invalid_credentials 401 Login failed — wrong email/password.
auth.session_expired 401 Token was valid but expired.
auth.email_not_verified 403 User must verify email before this action.
auth.user_exists 409 Signup collided with an existing account.
auth.unauthorized 401 Request is missing or has an invalid token.
auth.token_required 400 A required header/token was missing from request.
auth.user_not_found 404 Lookup by user id returned nothing.
auth.invite_required 403 Signup needs an invite (closed beta) — none sent.
auth.invite_invalid 403 Invite token unknown, expired, revoked, or used.
auth.mfa_required 403 Action needs the user's MFA second factor first.
auth.magic_link_expired 401 Passwordless sign-in link is invalid or expired.
auth.csrf_origin_mismatch 403 Cookie-authed mutation from a disallowed origin.
sync.push_conflict 409 Server rejected a push because of a conflict.
sync.history_pruned 410 Client's watermark is below changes the server has pruned; full re-sync required.
sync.app_not_found 404 App id does not exist on this server.
sync.token_not_found 404 Sync token has been deleted or never existed.
sync.share_not_found 404 Public share is unknown, revoked, or on a different app.
sync.method_not_allowed 405 HTTP method not valid for the endpoint.
sync.request_timeout 408 Client aborted the request after the timeout.
sync.network_error 0 fetch() failed before a response was received.
sync.archive_unsupported 400 Account archive was written in a format this server cannot read.
sync.archive_incomplete 422 Account archive is missing its manifest, or a part is short — it was truncated.
sync.archive_in_progress 409 An account archive is already being built or applied; only one runs at a time.
validation.schema_mismatch 422 Payload failed schema validation.
validation.invalid_patch 422 JSON Patch could not be applied.
validation.missing_field 400 Required field missing from request body.
validation.invalid_request 400 Request body malformed for this endpoint.
quota.storage_exceeded 413 User's storage limit reached.
quota.db_exceeded 429 User's change-log (database) quota reached.
quota.blob_exceeded 429 User's blob storage quota reached.
quota.rate_limited 429 Too many requests in a window.
quota.blob_too_large 413 Single blob exceeds maxBlobSizeBytes.
permission.insufficient_scope 403 Token lacks required read/write/delete level.
permission.app_not_authorized 403 App has not been granted access to this data.
permission.grant_not_found 404 Cross-app grant does not exist or was revoked.
permission.active_grants 409 App still has active grants; delete blocked unless forced.
blob.not_found 404 Blob hash not present on server.
blob.upload_failed 500 Upload to object storage failed server-side.
blob.download_failed 500 Download from object storage failed server-side.
blob.invalid_hash 400 Hash format rejected (must be sha256:<hex>).
blob.empty_body 400 Upload request had no body.
blob.url_unavailable 500 Signed/CDN URL could not be produced.
sharing.type_unresolved 422 Shared type document could not be resolved.
sharing.grant_not_found 404 Share grant unknown or already revoked.
sharing.not_supported 501 Cross-app sharing unavailable for this app/server.
services.no_supported_mode 400 No execution mode is available for this service on this host.
services.grant_denied 403 The app lacks a grant covering this service.
services.quota_exceeded 429 A per-grant or per-credential quota is used up for the period.
services.credential_missing 401 No credential resolved for the requested service.
services.credential_unwrap 400 The proxy could not open the sealed credential.
services.input_invalid 400 Input failed the service's declared schema.
services.upstream_error 502 The upstream provider failed or was unreachable.
services.egress_denied 403 Requested host is outside the service's allowed egress.
services.rate_limited 429 Too many invocations — retry after a delay.
internal.server_error 500 Uncaught server error — bug or runtime failure.
internal.unknown 500 Client could not parse a non-standard error body.

Package-specific codes are allowed under any known domain prefix without being added to the registry — err('sync.custom_condition', '...') type-checks. The canonical set above is what servers should emit by default.

Two helpers derive from a code string:

  • domainOf(code) → the domain half ('auth', 'sync', …).
  • httpStatusFor(code) → the registry's default HTTP status, or 500 for codes not in the registry.

Response envelopes #

Every Civility server response is one of:

interface SuccessResponse<T> {
  status: 'success'
  message: string
  data: T
}

interface ErrorResponse {
  status: 'error'
  code: ErrorCode
  message: string
  messageKey?: string // stable i18n key for this message variant
  details?: unknown
}

Use isErrorResponse(body) as a type guard when dealing with a raw JSON body.

messageKey lets clients localise a specific message variant without matching on the English message — code is the coarse branch key; messageKey disambiguates when one code is emitted with several different messages. Routes opt in via the fourth argument of err(code, message, details, messageKey).

  • @civility/cloud — client orchestrator; raises CivilityApiError and dispatches SyncErrorEvent.
  • @civility/hono — server framework; every route returns one of the envelopes defined here.