Skip to Content
upserve

Public API

Find exported functions, integration options and extension contract semantics.

All core imports below come from @neplex/upserve. Providers, adapters and SQLite are separate packages so you only install what you use. Runtime configuration fields are listed in the configuration reference.

createUpserve

createUpserve(config: UpserveConfig): Upserve

Creates a real Hono application with .fetch, .request, .route and the normal Hono methods. It doesn't start a listener. Use the quick start for a complete Node.js example or embedding to mount it.

Upserve adds two trusted server-side methods:

MethodWhat it does
refresh(application: string): Promise<void>Forces release-list and provider-resource revalidation; rejects during a cooldown or on failure
invalidate(application: string): Promise<void>Waits for the pending list load, then deletes the resolved release-list entry

Both reject unknown application IDs with UpserveError("missing", ...). Neither is an HTTP administration endpoint. Refresh doesn't clear all adapter manifests; see cache refresh behavior.

defineConfig, defineProvider, defineAdapter and defineCache

Each helper accepts an object satisfying its public contract and returns the same object with its inferred type. Use them for autocomplete and to catch missing methods without implementing a base class.

HelperContractExample
defineConfig(config)UpserveConfigConfiguration
defineProvider(provider)ProviderCatalog provider
defineAdapter(adapter)AdapterVersion adapter
defineCache(cache)CacheStoreCounted cache

They don't perform extra runtime wrapping or sandbox plugin code.

memoryCache

memoryCache(maxEntries = 1000): CacheStore

Creates a process-local least-recently-used store. maxEntries must be a positive integer. Reads and writes clone values so callers can't mutate stored entries. The limit counts metadata entries, not bytes. Restarting the process loses the data.

sqliteCache

Import sqliteCache from @neplex/upserve-sqlite.

sqliteCache(filename: string): CacheStore & { close(): void }

Opens a Node SQLite metadata database in WAL mode. Create its parent directory first and close it after HTTP work drains. Entries survive restarts; old rows aren't automatically pruned. See the persistent cache example.

Version helpers

FunctionResult
validVersion(version: string): booleanTests a semantic version without coercing an arbitrary tag
newer(candidate: string, current: string): booleanReturns whether the candidate has greater semantic-version precedence; throws invalid if either version is invalid
compareVersions(a: string, b: string): numberDescending sort comparator for semantic versions; pass valid versions
versions.ts
import { compareVersions, newer, validVersion } from "@neplex/upserve";

validVersion("1.2.0"); // true
newer("1.2.0", "1.1.0"); // true

const versions = ["1.9.0", "1.10.0"].sort(compareVersions);

console.log(versions); // ["1.10.0", "1.9.0"]

Build metadata doesn't change precedence. Tags and provider IDs shouldn't be passed as versions.

readText

readText(response: Response, maxBytes = 1024 * 1024): Promise<string>

Reads UTF-8 metadata up to a byte limit, cancels on overflow and releases its stream reader. It returns an empty string when there's no body. Use it before parsing untrusted metadata; don't use it for installers.

findAssetByUrl

findAssetByUrl(assets: readonly Asset[], url: string): Asset | undefined

Finds the asset whose canonical url or one of its aliases identifies a manifest URL. URLs are compared after parsing, so host case and default ports don't matter while paths and queries must match exactly. It returns undefined for relative or credential-bearing input, for no match, and when more than one asset matches. Use it in adapters instead of comparing asset.url directly, then link clients to services.assetUrl().

UpserveError

new UpserveError(code, message, retryAt?)

PropertyTypeMeaning
code"configuration", "auth", "rate_limit", "network", "invalid" or "missing"Failure category
messagestringSafe operational explanation; don't include credentials or raw source bodies
retryAtnumber (optional)Earliest refresh time as absolute epoch milliseconds

An auth error clears the affected cached entry. Other failures can preserve previously validated data within its stale window. See HTTP errors for the client mapping.

Integration factories

GitHubOptions

github(options: GitHubOptions): Provider from @neplex/upserve-github.

The GitHub guide lists all deployment options, requirements and defaults. These additional options support deterministic testing:

OptionTypeRequiredDefaultPurpose
fetchtypeof fetchNoGlobal fetchSupply recorded API responses without real requests
sleep(ms: number) => Promise<void>NoTimer-based delayControl retry backoff
random() => numberNoMath.randomSupply jitter from zero to one

TauriOptions

tauri(options?: TauriOptions): Adapter from @neplex/upserve-tauri.

OptionTypeRequiredDefaultMeaning
manifeststringNo"latest.json"Manifest asset name in the selected release

See Tauri for endpoint and manifest requirements.

ElectronOptions

electron(options?: ElectronOptions): Adapter from @neplex/upserve-electron.

OptionTypeRequiredDefaultMeaning
channelsRecord<string, string>Nostable maps to latest; others use their nameMaps URL channels to YAML filename prefixes

For example, electron({ channels: { prerelease: "beta" } }) serves beta.yml on the prerelease channel. This doesn't replace application channel predicates. See Electron.

AndroidOptions

android(options?: AndroidOptions): Adapter from @neplex/upserve-android.

OptionTypeRequiredDefaultMeaning
manifeststringNo"latest-android.json"Manifest asset name
transform(input: unknown) => AndroidManifestNoUse parsed inputTranslates another format before validation
compatible(manifest: AndroidManifest, request: Request) => booleanNoNo extra eligibility checkReturning false suppresses the offer with 204

AndroidManifest is also exported by this package. Its fields and validation rules are in the Android manifest reference. minimumVersion and versionCode aren't automatic selection rules.

generic

generic(): Adapter from @neplex/upserve-generic takes no options. Its response format is documented in custom applications.

Extension contracts

The following types are exported from the core. Official integrations implement these same contracts.

Release and Asset

Release fieldTypeRequiredMeaning
idstringYesStable provider identity
tagstringYesOriginal upstream reference
versionstringYesValid semantic version
prereleasebooleanYesChannel-selection flag
assetsAsset[]YesKnown manifests and downloadable files, up to 1,000
draft, yankedbooleanNoExclude the release when true
notesstringNoRelease notes
publishedAtstringNoRFC 3339 timestamp
metadataunknownNoSerializable source-specific information; omitted from generic responses

An Asset has required id: string, name: string, size: number and url: string, plus optional contentType: string and aliases: string[]. Size is a nonnegative integer in bytes. IDs and names must each be unique within a release. Providers must validate URLs for their delivery policy; the core's URL-shape check isn't a source-specific security policy.

aliases lists other upstream URLs that identify the same asset, such as a provider API URL embedded in manifests. A provider must verify that each alias belongs to the same upstream asset before returning it. The core accepts at most eight per asset, requires HTTPS without credentials or fragments, and rejects a release where an alias identifies a different asset. Aliases are used only for matching: redirects and open() always use the canonical url and id, and Upserve never fetches an alias.

The core accepts at most 10,000 releases, filters drafts/yanked entries and sorts by version. Adapter manifests have additional validation requirements.

Provider

MemberSignatureResponsibility
namestringIdentify the integration
scopestringIdentify a nonsecret configuration/credential generation
privateboolean (optional)Require authorization and streamed downloads when true
releases(context: ResourceContext) => Promise<Release[]>Return validated source data or throw
open(asset: Asset, request: Request, context: ResourceContext) => Promise<Response>Open only the known asset and preserve supported HTTP semantics
redirect(asset: Asset) => string (optional)Return a validated public download destination
verifyWebhook(request: Request, body: Uint8Array) => Promise<boolean> (optional)Authenticate a bounded webhook body before refresh

A provider with verifyWebhook gets /webhooks/:application. The official GitHub provider exposes that method even without a secret; verification then rejects every delivery. See the provider tutorial for implementation and testing.

ResourceContext

MemberSignatureMeaning
signalAbortSignalCancellation/deadline for the operation
cached<T>(identity: string, load: (previous: T | undefined) => Promise<T>) => Promise<T>Cache and coalesce a resource inside the application's provider scope

Validate inside load before returning. Provider resources have no stale-on-error fallback of their own; the outer release list can still supply stale data. Release lookup gets a 120-second outer deadline; adapter manifest loading gets 30 seconds. Providers should honor the signal and bound their own requests too.

Adapter

Adapter requires name: string and register(app: Hono, services: AdapterServices): void. Register relative routes under the application's channel router. Names and route prefixes should avoid collisions. See the adapter tutorial.

AdapterServices

MemberSignatureMeaning
configAppConfigThis application's configuration
channelsstring[]Configured channel names
releases(channel: string) => Promise<Release[]>Filtered releases, newest first
latest(channel: string) => Promise<Release | undefined>First selected release
manifest<T>(release: Release, name: string, parse: (text: string) => T) => Promise<T>Read a known asset, validate before caching and parse on each use
assetUrl(context: Context, release: Release, asset: Asset) => stringBuild a server delivery URL including a parent mount path
deliver(request: Request, release: Release, asset: Asset) => Promise<Response>Apply redirects or streaming to a known release asset

Context is Hono's request context. Manifest bodies are limited to 1 MiB through readText() by default. A parse failure becomes an invalid error and doesn't replace previously validated text. Don't return invalid data from the parser.

CacheStore and CacheEntry

CacheStore methodReturn typeMeaning
get(key: string)Promise<CacheEntry | undefined>Return an independent entry or no entry
set(key: string, entry: CacheEntry)Promise<void>Atomically save the complete entry
delete(key: string)Promise<void>Remove that exact key

CacheEntry contains value: unknown, freshUntil: number, staleUntil: number optional retryAt: number and optional error and optional due. Timestamps are absolute epoch milliseconds. An undefined value can record a failed cold load and its cooldown. error is the CacheFailure code (an UpserveErrorCode or "internal") of the failure that started the cooldown; requests during the cooldown report that code without contacting the upstream. Only the code is stored. Entries without it, including those written by earlier versions, report rate_limit during their cooldown. due is set when an authenticated webhook asks for a refresh: the next load of that entry, in any process sharing the store, also revalidates provider resources. A successful load clears it. Preserve it rather than interpreting it as fresh empty data.

CachePolicy, AppConfig and UpserveConfig are documented in configuration options. See the cache tutorial for storage semantics and restart tests. The internal coordinator and validation schemas aren't public exports.

On this page