gnomonlearn

RFC-0029 · tRPC Schema Adapter

Versioned draft snapshot

RFCs, reference catalogs, and evidence reflect Spec 3b2e3e7a114fb826b1445d39a48756b8fff629cd. Counts and pending/status notes belong to that snapshot. Read the dated project update for later progress.

Source repositories are private during staging. Links marked “repository access required” need access to the linked repository.

Status Draft corpus. Reference catalogs and RDF projections have generation drift checks; Gnomon proofs and projection semantics remain unverified for release.

View the generated reference catalog →

Read design questions and decisions →


Reference catalog: the diagnostics, linked-RFC graph, defined terms, and normative-rule index for this RFC are in the reference catalog, generated from the structured Lean module. This document carries the prose: design rationale, entity-shape definitions in context, and migration notes.


1. Purpose

This RFC defines the gnomon.io.trpc module — the tRPC schema adapter. When a client declaration uses spec: trpc("./server/trpc"), the compiler invokes this adapter at build time to extract router type information via the TypeScript compiler API and generate typed gnomon operations.

tRPC is an end-to-end typesafe RPC framework whose schema lives entirely in TypeScript type signatures — there is no separate schema document. The adapter bridges this by acting as a TypeScript type consumer: it resolves the exported AppRouter type (or a named alternative) at compile time without executing any runtime code, then translates the procedure type graph into gnomon OperationDefinition and TypeDefinition values per RFC-0024 §6.

// Example usage
imports {
  gnomon.io.http: "^1.0.0"
  gnomon.io.trpc: "^1.0.0"
}

client APIServer {
  meaning: "Internal API server via tRPC."
  spec: trpc("./server/trpc")
  baseUrl: "$API_BASE_URL"
  auth: bearer-token
}

After adaptation, APIServer.usersGetById, APIServer.postsCreate, and so on are available in execute {} blocks and saga steps.


2. Adapter Function Signature

// Exported by gnomon.io.trpc; called via spec: trpc(arg)
// importPath is a TypeScript module specifier resolved relative to the declaring .gnm file
function trpc(importPath: string): SpecImport

importPath is a TypeScript module specifier — the same string you would write in a TypeScript import statement. Examples:

  • "./server/trpc" — relative path, resolved from the declaring .gnm file’s directory
  • "@acme/api" — package reference, resolved via the project’s tsconfig.json paths or node_modules

The adapter MUST look for an exported type named AppRouter in the resolved module. If the module exports a differently named router type, the specifier MAY include an explicit export name using a # fragment: "./server/trpc#MyRouter". If no fragment is given and AppRouter is not found, the adapter MUST fall back to the first exported type that is assignable to AnyRouter from the @trpc/server package. If no router type is found by any of these strategies, the adapter MUST emit M29901 (error).


3. Procedure Type Mapping

tRPC routers consist of procedures of three kinds. Each procedure MUST become one gnomon operation.

tRPC procedure kindgnomon operation semanticsNotes
queryRead-only operationSafe to call from execute {} or query blocks; no side effects declared
mutationSide-effecting operationIntended for execute {} blocks within action declarations
subscriptionStreaming operation returning Stream<T>Integrates with RFC-0020 reactive query model

The adapter MUST set the mode field of the OperationDefinition to "unary" for query and mutation procedures, and "streaming" for subscription procedures.


4. Input Validator Introspection

tRPC procedures declare their input via an input validator — typically a Zod, Valibot, or Arktype schema, or a raw TypeScript type. The adapter MUST attempt to extract the input schema statically for each of these cases.

4.1 Zod schemas

If the procedure’s .input() call is detected as a Zod schema (the adapter checks for the _def structure and ZodType brand in the type graph), the adapter MUST resolve the Zod type to an gnomon input schema by recursive descent:

Zod typegnomon type
z.string()Text
z.string().datetime()Timestamp
z.number()Decimal
z.number().int()Integer
z.boolean()Boolean
z.date()Timestamp
z.array(T)List<T>
z.object({...})Inline record; fields expanded into input schema
z.union([...]) / z.discriminatedUnion(...)variant
z.optional(T) / .nullable()Optional field
z.unknown() / z.any()JSON (no warning; intentional escape hatch)

4.2 Valibot schemas

The adapter MUST detect Valibot schemas by the presence of the _types brand on the schema type. Type mapping MUST follow the same structure as §4.1, applied to the equivalent Valibot schema constructors (v.string(), v.object({...}), etc.).

4.3 Arktype schemas

The adapter MUST detect Arktype schemas by the infer and inferIn type brands. The inferred TypeScript type MUST be extracted and MUST be mapped via the TypeScript→gnomon type mapping defined in §5.

4.4 Raw TypeScript types

If the procedure’s input is declared as a raw TypeScript interface or type alias (without a validator library), the adapter MUST extract the type through the TS compiler API and MUST apply the TypeScript→gnomon mapping in §5.

4.5 Unanalyzable validators

If the adapter cannot resolve the input schema — for example, because the validator is constructed dynamically, imported from a path that cannot be followed statically, or uses runtime-dependent logic — the adapter MUST emit M29900 (warning) and MUST type the input as JSON. The operation MUST still be generated; callers are responsible for providing a correctly shaped value.


5. Output Type Mapping

The procedure’s output type MUST be extracted from the TypeScript compiler’s inferred return type of the procedure handler, after stripping the Promise<> wrapper if present.

The TypeScript→gnomon type mapping is:

TypeScript typegnomon type
stringText
numberDecimal
booleanBoolean
DateTimestamp
null / undefinedOptional modifier on the containing field
T[]List<T>
Named interface or type aliasTypeDefinition registered as <ClientName>.<TypeName>
Record<string, T>List<{ key: Text, value: T }>
unknown / anyJSON with M29902 warning
voidvoid in the returns slot

Union types (A | B) MUST be mapped to gnomon variant. If the union is a simple optional (T | undefined or T | null), it MUST map to an optional field rather than a variant.

If the output type cannot be mapped, the adapter MUST emit M29902 (warning) and MUST use JSON as the return type.


6. Nested Router Support

tRPC routers may be nested: a root router can include sub-routers, which may themselves include sub-routers. The adapter MUST flatten the tree into a set of operation names by concatenating segment names in camelCase.

Examples:

tRPC router pathGenerated gnomon operation name
router.users.getByIdusersGetById
router.posts.comments.createpostsCommentsCreate
router.healthCheckhealthCheck

The depth of nesting is not limited. Naming conflicts (two paths producing the same operation name) MUST be detected by the adapter and MUST emit M29901 (error, treated as a duplicate name).


7. Error Code Mapping

tRPC errors are represented as TRPCError instances with a code field. The adapter MUST map these codes to gnomon error classes and MUST inject them into the errors {} block of each generated operation.

tRPC error codegnomon error classRationale
UNAUTHORIZEDterminalAuth failure; retrying without new credentials will not help
FORBIDDENterminalPermission failure; retry will not resolve
NOT_FOUNDterminalResource does not exist
BAD_REQUESTterminalCaller error; must fix input
CONFLICTterminalState conflict; retrying the same request will not help
PRECONDITION_FAILEDterminalPrecondition not met
PAYLOAD_TOO_LARGEterminalInput size issue
METHOD_NOT_SUPPORTEDterminalProtocol error
UNPROCESSABLE_CONTENTterminalValidation failure
TOO_MANY_REQUESTStransientRate-limited; retry after delay
CLIENT_CLOSED_REQUESTignoreClient aborted; treat as no-op
INTERNAL_SERVER_ERRORtransientMay recover on retry
TIMEOUTtransientTransient infrastructure issue
NOT_IMPLEMENTEDterminalEndpoint does not exist
PARSE_ERRORterminalRequest malformed

Authors MAY override any of these defaults in the errors {} block on the parent client declaration.


8. Wire Protocol Mapping

This section specifies how gnomon operations generated by gnomon.io.trpc are executed over the wire. The base HTTP transport layer is provided by gnomon.io.http; see RFC-0025 §2 for transport-level details including connection pooling, TLS, and retry transport.

8.1 tRPC Version Support

Implementations MUST support the tRPC v10+ wire protocol — specifically, the @trpc/server v10 protocol, which uses JSON payloads over HTTP/1.1 or HTTP/2. tRPC v9 and earlier MUST NOT be used; if the server is detected as running a pre-v10 protocol (identifiable by the response envelope shape), the runtime MUST emit M29904 (error).

8.2 Procedure URL Path

Implementations MUST construct the procedure URL by joining the client’s baseUrl with the router path and procedure name:

<base-url>/<router-path>/<procedure-name>

The router-path is derived from the nested router structure by joining router segment names with /. The procedure-name is the final leaf name of the procedure within its containing router.

Examples (given baseUrl: "https://api.example.com/trpc"):

Gnomon operation nametRPC router pathWire URL
usersGetByIdusers.getByIdhttps://api.example.com/trpc/users/getById
postsCommentsCreateposts.comments.createhttps://api.example.com/trpc/posts/comments/create
healthCheckhealthCheckhttps://api.example.com/trpc/healthCheck

8.3 HTTP Method Mapping

Implementations MUST map tRPC procedure kinds to HTTP methods as follows:

tRPC procedure kindHTTP method
queryGET
mutationPOST
subscriptionGET (initial handshake; upgraded per RFC-0020)

8.4 Request Envelope

Query procedures: Input MUST be serialized to JSON and encoded as the input URL search parameter:

GET <base-url>/<path>?input=<JSON-encoded-input>

If the input is undefined or the procedure takes no input, the input parameter MUST be omitted.

Mutation procedures: Input MUST be sent as a JSON request body using the tRPC v10 envelope format:

{ "json": <input> }

The Content-Type header MUST be set to application/json.

8.5 Response Envelope

Success responses: The server MUST return HTTP 200 with a JSON body in the following shape:

{ "result": { "data": { "json": <output> } } }

The runtime MUST extract result.data.json as the operation’s return value and MUST map it to the declared returns type.

Error responses: The server MUST return a non-2xx HTTP status (typically 400 or 500) with a JSON body in the following shape:

{ "error": { "json": { "message": <msg>, "code": <code> } } }

The runtime MUST extract error.json.code and MUST map it to the gnomon error class using the table in §7. If error.json.code is not present or is unrecognized, the runtime MUST treat the error as INTERNAL_SERVER_ERROR → transient.

8.6 Batch Requests

Implementations SHOULD support tRPC batch requests, which allow multiple procedure calls to be sent in a single HTTP round-trip. If batch support is implemented:

  • The batch request MUST include the ?batch=1 URL search parameter.
  • Multiple procedure inputs MUST be encoded as a JSON object keyed by integer index: ?input={"0":<input0>,"1":<input1>} for GET batches, or as an array [<body0>, <body1>] for POST batches.
  • The server response for a batched request MUST be a JSON array where each element is either a success envelope or an error envelope (as defined in §8.5), indexed to match the request order.
  • Batch size MUST be limited to 10 procedures per request; implementations MUST split larger batches automatically.

9. Build-Time Extraction

The adapter MUST NOT import or execute any tRPC router code. It MUST operate exclusively on TypeScript type information obtained from the TypeScript compiler API (ts.createProgram).

9.1 TypeScript configuration

The adapter MUST locate tsconfig.json by searching upward from the declaring .gnm file’s directory. If no tsconfig.json is found, the adapter MUST emit M29903 (error) and MUST halt.

The adapter MUST create a ts.Program using the found tsconfig.json as the compiler options source. The program MUST be created with noEmit: true (overriding any emit settings in the project’s config) to avoid writing output files.

9.2 Type graph traversal

Given the resolved AppRouter type, the adapter MUST traverse the type graph depth-first:

  1. For each property of the router type, determine if it is a procedure (query, mutation, subscription) or a nested router.
  2. For procedures, extract the _def.inputs and _def.output type parameters via the TS compiler API.
  3. For nested routers, recurse with the accumulated name prefix.

The traversal MUST be purely over types; no JavaScript evaluation may occur.

9.3 Lockfile and caching

The adapter MUST compute a specHash as the SHA-256 of a canonical JSON representation of the extracted type graph (operation names, input schemas, output schemas). This hash MUST be stored in gnomon.lock. On subsequent builds, if the hash matches, the adapter MUST skip re-extraction and MUST use the cached operation set.

Because the type graph depends on the TypeScript source, changes to the router file or any transitively imported file that affect the AppRouter type will change the hash. The adapter SHOULD NOT attempt to perform fine-grained dependency tracking; it MUST re-extract whenever the hash changes.


10. Diagnostic Codes

This RFC owns the M29xxx diagnostic code range.

CodeDescriptionSeverity
M29900tRPC procedure has an unanalyzable input validator; input typed as JSONWarning
M29901tRPC router type not found at the specified import pathError
M29902tRPC procedure output type cannot be mapped to an gnomon type; return typed as JSONWarning
M29903tsconfig.json not found; TypeScript type resolution failedError
M29904tRPC server is running a pre-v10 wire protocol; v10+ is requiredError

11. Failure Mode Summary

CodeDescriptionSeverity
M29900Unanalyzable input validator (JSON fallback)Warning
M29901Router type not found at import pathError
M29902Output type unmappable (JSON fallback)Warning
M29903tsconfig.json not foundError
M29904Pre-v10 tRPC wire protocol detectedError
M24420Spec unreachable, no lockfile entry (from RFC-0024)Error
M24421Spec unreachable, using lockfile cache (from RFC-0024)Info
M24422Adapter produced zero operations (from RFC-0024)Warning
M24423Generated type name conflicts with existing type (from RFC-0024)Error