Skip to content

@ts-pf/mvc-kit

Opt-in mvc-kit helpers for a ts-pf client. Inject disposeSignal on every call and map VALIDATION issues (from an asResult error or a failed task) onto FormModel.setErrors — you still write Resource methods and still call useLocal / useSingleton yourself.

Agent skill: skills/ts-pf-mvc-kit/. Sync with npx skills experimental_sync -y.

This package does not wrap Resource, add React hooks, generate a Service, or fold into @ts-pf/client. Pass the client from createClient<typeof contract>(link) or createClient<Contract>(link) with a generated Contract from @ts-pf/codegen. Requires mvc-kit 4.9+ (>=4.9.0 <5).

import { createClient } from '@ts-pf/client'
import { FetchLink } from '@ts-pf/client-http'
import { bindClient, issuesToFieldErrors } from '@ts-pf/mvc-kit'
import { Resource, type DedupeConfig } from 'mvc-kit'
import type { InferContractInputs, InferContractOutputs } from '@ts-pf/contract'
import type { contract } from './contract'
export const client = createClient<typeof contract>(new FetchLink({ url: '/rpc' }))
type Planet = InferContractOutputs<typeof contract>['planet']['find']
class PlanetsResource extends Resource<Planet> {
static DEDUPE: DedupeConfig<PlanetsResource> = {
loadAll: true,
loadById: (id) => id,
}
private rpc = bindClient(client, this)
protected onInit() {
if (this.length === 0) this.loadAll()
}
async loadAll() {
this.reset(await this.rpc.planet.list())
}
async loadById(id: number) {
this.upsert(await this.rpc.planet.find({ id }))
}
async create(input: InferContractInputs<typeof contract>['planet']['create']) {
const row = await this.rpc.planet.create(input)
this.add(row)
return row
}
}

createClient / FetchLink stay yours: Fetch interceptors, codec, and headers on FetchLink; call plugins (RetryPlugin, …) on createClient. bindClient only injects { signal: host.disposeSignal } at call time. A caller-provided { signal } wins.

App tsconfigs should use moduleResolution: "bundler" (Vite’s default) or "nodenext" when subclassing mvc-kit Resource. Node16 does not inherit Resource members onto subclasses.

Resource methods throw. mvc-kit classifies the thrown PFError as-is:

resource.async.loadById.errorCode === 'NOT_FOUND' // not 'not_found'
resource.async.loadById.cause // the PFError; .data is on the instance

taskIssues(task) reads the VALIDATION issues off a failed task. It returns [] unless task.cause is a PFError with code VALIDATION. mvc-kit updates the task after the method’s promise settles, so read it from the caller (a View, or a method that awaited the tracked one), not inside the method that threw:

import { issuesToFieldErrors, taskIssues } from '@ts-pf/mvc-kit'
// View: derive field messages while rendering
const fieldErrors = issuesToFieldErrors(taskIssues(vm.async.submit))
// ViewModel: after the tracked call rejects
await this.submit().catch(() => {
this.form.setErrors(issuesToFieldErrors(taskIssues(this.async.submit)))
})

Do not wrap PFError in CodedError or HttpError. mvc-kit classifies by code only when status is a finite number, and PFError.status is transport metadata (the HTTP response status over FetchLink; undefined on message links, after a stream has started, and for declared errors without a status), so bindClient hands mvc-kit a copy with status: 400 whenever the transport did not carry one. HTTP failures and localFailure (status: 0) pass through as-is. CodedError is mvc-kit’s class if you throw by hand without that envelope.

Do not throw error.toJSON() — the JSON object has no status, so 4.9 will classify it as 'unknown'.

asResult is for ViewModel branching (forms). Async tracking keys off throw. If a Resource method asResults and does not rethrow, async.method.error stays null.

import { asResult } from '@ts-pf/client'
import { issuesToFieldErrors } from '@ts-pf/mvc-kit'
const result = await asResult(this.rpc.planet.create(input))
if (!result.ok && result.error.code === 'VALIDATION') {
this.form.setErrors(issuesToFieldErrors(result.error.data.issues))
// rethrow if you also want vm.async.submit.errorCode === 'VALIDATION'
}

To show a declared error’s data, read it with asResult, keep it in state, and rethrow. A task’s cause is unknown, so the contract types are only available at the call. Here apply declares RateLimited: { status: 429, data: z.object({ retryAfterMs: z.number() }) }, and the ViewModel’s state has retryAfterMs: number | null:

async submit(input: ApplyInput) {
this.set({ retryAfterMs: null })
const result = await asResult(this.rpc.apply(input))
if (!result.ok) {
if (result.error.code === 'RateLimited') {
this.set({ retryAfterMs: result.error.data.retryAfterMs }) // number
}
throw result.error // async.submit.errorCode === 'RateLimited'
}
return result.data
}

The client does not validate data, the same as outputs. The ts-pf server validates it against the declared schema when the procedure (its handler or middleware) throws the error. A PFError thrown outside the procedure (in a server call interceptor, HandlerPlugin.onRequest / onContext, or the context function) is sent without that check.

FormModel knows only top-level fields, so an issue is keyed by the first segment of its path: ['address', 'city'] lands on address, and the first issue per field wins. When a nested object or array row has its own FormModel, pass at to keep only the issues under that path, keyed relative to it.

Give each form only keys it has as fields. mvc-kit counts an error set with setErrors toward valid, and clears it only when that field is edited. An error on a key the form has no field for keeps the form invalid, with nothing on screen, until clearErrors(), commit(), or reset(). So drop the sub-forms’ keys before the parent’s call:

const issues = result.error.data.issues
const { address, items, ...own } = issuesToFieldErrors(issues)
this.form.setErrors(own)
this.addressForm.setErrors(issuesToFieldErrors(issues, { at: ['address'] }))
this.rowForms.forEach((row, i) =>
row.setErrors(issuesToFieldErrors(issues, { at: ['items', i] })),
)

Pass nothing. bindClient injects host.disposeSignal. Dispose/unmount aborts the in-flight call. FetchLink maps abort to PFError { code: 'INTERNAL', local: true, status: 0, cause: AbortError }. mvc-kit walks cause one level and swallows it — no error flash.

For Pending / offline-kit, pass the provided signal so it wins:

this.pending.enqueue(id, 'create', (signal) =>
this.rpc.planet.create(input, { signal }).then((row) => {
this.add(row)
}),
)

Do not pass this.disposeSignal into Pending’s execute. Do not list Pending writes in static DEDUPE (joined reads must close over the host signal, which is the default).

No helper in v1. Feed owns the cursor; Resource upserts rows:

const page = await this.rpc.planet.listPage({ cursor: this.feed.cursor })
this.planets.upsert(...page.items)
this.feed.setResult(page)

Same contracts, opt-in codec on the link you already own:

import { StreamCodec } from '@ts-pf/stream'
const client = createClient<typeof contract>(
new FetchLink({ url: '/rpc', codec: new StreamCodec() }),
)
const items = await this.rpc.planet.describe({ id })
for await (const item of items) {
this.upsert(item)
}

Cancel is the injected signal. There is no Stream→Feed helper.

Channel is a reconnecting inbound event bus. It is not RPC-over-WebSocket (@ts-pf/message-client WsLink) and not SseCodec (POST that streams then ends).

One line; do not bindClient that path — the outbox owns the signal:

send: (entry, signal) => client.todo.create(entry.payload, { signal })

Entity id is string. Procedure-shaped non-CRUD writes do not belong there.

  • bindClient, DisposeSignalHost
  • issuesToFieldErrors(issues, { at? }), IssuesToFieldErrorsOptions
  • taskIssues(task): the VALIDATION issues on an mvc-kit TaskState’s cause, else []
  • TanStack Query / queryOptions / query keys
  • createResources / fromProcedure (one procedure is not a Resource)
  • Pass-through Service (call the client from the Resource)
  • Wrapping useLocal / useSingleton
  • Channel / WsLink wrapper
  • Retry (RetryPlugin on createClient)
  • Mapping NOT_FOUND → 'not_found'
  • instanceof HttpError for RPC
  • Walking app instead of the contract