@fabrika/app 0.9.0-dev.14 → 0.9.0-dev.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +14 -9
- package/skill/SKILL.md +2 -2
- package/skill/references/app-setup.md +10 -9
- package/skill/references/endpoint.md +8 -1
- package/src/build-contract-child.ts +16 -0
- package/src/build.ts +48 -2
- package/src/client/contract.ts +6 -4
- package/src/cloudflare/application.ts +3 -0
- package/src/contract/artifact-schema.ts +355 -301
- package/src/contract/attachment.ts +4 -3
- package/src/contract/compile.ts +3 -2
- package/src/contract/context.ts +2 -3
- package/src/contract/define.ts +17 -5
- package/src/contract/group.ts +8 -7
- package/src/contract/index.ts +1 -1
- package/src/contract/kit.ts +2 -2
- package/src/contract/problems.ts +4 -0
- package/src/contract/schema-shape.ts +14 -2
- package/src/contract/token.ts +4 -3
- package/src/from-row.ts +12 -6
- package/src/implement/approved.ts +57 -0
- package/src/implement/attachment.ts +2 -1
- package/src/implement/boot.ts +90 -12
- package/src/implement/dispatch.ts +14 -10
- package/src/implement/egress.ts +7 -6
- package/src/implement/faults.ts +1 -0
- package/src/implement/project.ts +3 -1
- package/src/implement/tokens.ts +3 -2
- package/src/implement/types.ts +18 -6
- package/src/react/hooks.ts +12 -11
- package/src/react/provider.tsx +2 -1
- package/src/react/types.ts +2 -2
- package/src/schema/builder.ts +146 -0
- package/src/schema/data-schema.ts +365 -0
- package/src/schema/index.ts +18 -0
- package/src/schema/replay.ts +623 -0
- package/src/testing/kit.ts +3 -3
- package/types/src/build-contract-child.d.ts +1 -0
- package/types/src/build.d.ts +16 -1
- package/types/src/client/contract.d.ts +3 -4
- package/types/src/cloudflare/application.d.ts +2 -0
- package/types/src/contract/artifact-schema.d.ts +8 -0
- package/types/src/contract/attachment.d.ts +3 -2
- package/types/src/contract/context.d.ts +2 -3
- package/types/src/contract/define.d.ts +14 -5
- package/types/src/contract/group.d.ts +5 -6
- package/types/src/contract/index.d.ts +1 -1
- package/types/src/contract/kit.d.ts +2 -3
- package/types/src/contract/problems.d.ts +1 -0
- package/types/src/contract/schema-shape.d.ts +3 -2
- package/types/src/contract/token.d.ts +3 -3
- package/types/src/from-row.d.ts +9 -5
- package/types/src/implement/approved.d.ts +11 -0
- package/types/src/implement/boot.d.ts +6 -0
- package/types/src/implement/faults.d.ts +1 -0
- package/types/src/implement/project.d.ts +2 -1
- package/types/src/implement/types.d.ts +4 -5
- package/types/src/react/hooks.d.ts +4 -5
- package/types/src/react/types.d.ts +2 -2
- package/types/src/schema/builder.d.ts +45 -0
- package/types/src/schema/data-schema.d.ts +124 -0
- package/types/src/schema/index.d.ts +3 -0
- package/types/src/schema/replay.d.ts +27 -0
- package/types/src/testing/kit.d.ts +2 -3
|
@@ -76,8 +76,10 @@ import {
|
|
|
76
76
|
import type { RequestExecutionContext } from '../fetch'
|
|
77
77
|
import { FileWork, type StoredFileKinds, storedFilesHandle } from '../files/kinds'
|
|
78
78
|
import { FileDownload, fileResponse, withFileTreatment } from '../files/treatment'
|
|
79
|
+
import { zodSchemaOf } from '../schema/data-schema'
|
|
79
80
|
import { namesSourceMap } from '../source-map-path'
|
|
80
81
|
import { abortedBody, bootstrapPath, bootstrapResponse, readBodyInTime, withBootstrap } from './anonymous'
|
|
82
|
+
import { approvedInput, approvedOutput } from './approved'
|
|
81
83
|
import { attachmentResponse } from './attachment'
|
|
82
84
|
import { boundedStream, type Deadline, deadline, handlerSignal, readBoundedBytes } from './bounded'
|
|
83
85
|
import type { BrowserConfig } from './browser-config'
|
|
@@ -160,8 +162,6 @@ export interface InvocationGate {
|
|
|
160
162
|
|
|
161
163
|
const invocationGate = new AsyncLocalStorage<InvocationGate>()
|
|
162
164
|
|
|
163
|
-
const UNGATED: InvocationAdmission = Object.freeze({ signal: new AbortController().signal, track: () => {}, release: () => {} })
|
|
164
|
-
|
|
165
165
|
/** Runs `work` with `gate` admitting every invocation it starts, the background work it hands on included. */
|
|
166
166
|
export function runGated<T>(gate: InvocationGate, work: () => T): T {
|
|
167
167
|
return invocationGate.run(gate, work)
|
|
@@ -170,7 +170,11 @@ export function runGated<T>(gate: InvocationGate, work: () => T): T {
|
|
|
170
170
|
/** Admits an invocation of `kind` at the current event's gate; outside an object every invocation is admitted, uncounted. */
|
|
171
171
|
export function admitInvocation(kind: InvocationKind): InvocationAdmission | null {
|
|
172
172
|
const gate = invocationGate.getStore()
|
|
173
|
-
|
|
173
|
+
if (gate !== undefined) {
|
|
174
|
+
return gate.admit(kind)
|
|
175
|
+
}
|
|
176
|
+
// One per call: workerd refuses an `AbortController` at a module's top level and ties a signal to its request.
|
|
177
|
+
return Object.freeze({ signal: new AbortController().signal, track: () => {}, release: () => {} })
|
|
174
178
|
}
|
|
175
179
|
|
|
176
180
|
/** How long a refused caller waits before it tries again, in seconds. */
|
|
@@ -793,7 +797,7 @@ export class ContractRuntime {
|
|
|
793
797
|
if (served.input === null) {
|
|
794
798
|
throw new ServerFault('contract_inconsistent', `'${served.row.id}' takes files and declares no input`)
|
|
795
799
|
}
|
|
796
|
-
return strictInput(served.row, served.input, { ...multipart.json, ...files })
|
|
800
|
+
return strictInput(served.row, approvedInput(served.row, served.input), { ...multipart.json, ...files })
|
|
797
801
|
}
|
|
798
802
|
|
|
799
803
|
/**
|
|
@@ -815,7 +819,7 @@ export class ContractRuntime {
|
|
|
815
819
|
if (file !== null) {
|
|
816
820
|
return attachmentResponse(served.row.id, file, served.output, result)
|
|
817
821
|
}
|
|
818
|
-
return outputResponse(served.row, served.output, result, request, carried)
|
|
822
|
+
return outputResponse(served.row, approvedOutput(served.row, served.output), result, request, carried)
|
|
819
823
|
}
|
|
820
824
|
|
|
821
825
|
/** A POST's `query`, parsed from the URL, each signed token in it verified; `undefined` without one. */
|
|
@@ -1535,7 +1539,7 @@ export class ContractRuntime {
|
|
|
1535
1539
|
const output = served.row.output
|
|
1536
1540
|
const answer = output !== null && isFileShape(output)
|
|
1537
1541
|
? await this.#fileKinds(served.row.id).download(work, served.row.id, output.kind, result)
|
|
1538
|
-
: outputResponse(served.row, served.output, result, request, carried)
|
|
1542
|
+
: outputResponse(served.row, approvedOutput(served.row, served.output), result, request, carried)
|
|
1539
1543
|
outcome = 'committing'
|
|
1540
1544
|
await commitAnswer(invocation, signal, answer)
|
|
1541
1545
|
return answer
|
|
@@ -1602,7 +1606,7 @@ export class ContractRuntime {
|
|
|
1602
1606
|
if (served.scheme === 'github-sha256' && !githubAccounts(payload).includes(binding.account)) {
|
|
1603
1607
|
throw new ForbiddenError('The delivery names another account than its binding accepts')
|
|
1604
1608
|
}
|
|
1605
|
-
const input = strictInput(served.row, served.input, stripped(served, payload))
|
|
1609
|
+
const input = strictInput(served.row, approvedInput(served.row, served.input), stripped(served, payload))
|
|
1606
1610
|
const bound = served.boundTo.kind === 'app' ? APP_BINDING_SCOPE.type : served.boundTo.dimension
|
|
1607
1611
|
if (binding.scope.type !== bound) {
|
|
1608
1612
|
throw new ServerFault(
|
|
@@ -1822,7 +1826,7 @@ function holdsOnChain(perms: PermissionEntry[], action: string, dimension: strin
|
|
|
1822
1826
|
* request's verified tokens carry: a URL among them is a target the application signed.
|
|
1823
1827
|
*/
|
|
1824
1828
|
function outputResponse(row: EndpointRow, schema: Schema, result: unknown, request: Request, carried: ReadonlySet<string>): Response {
|
|
1825
|
-
const output = z.safeParse(schema, projectSchema(row.id, schema, result))
|
|
1829
|
+
const output = z.safeParse(zodSchemaOf(schema), projectSchema(row.id, schema, result))
|
|
1826
1830
|
if (!output.success) {
|
|
1827
1831
|
throw new ServerFault('output_refused', `'${row.id}' returned a value its output schema refuses`)
|
|
1828
1832
|
}
|
|
@@ -1945,7 +1949,7 @@ function stripped(served: Extract<ServedEndpoint, { kind: 'webhook' }>, payload:
|
|
|
1945
1949
|
|
|
1946
1950
|
/** `value` parsed with the endpoint's strict input schema; a refusal is a 400 naming each issue. */
|
|
1947
1951
|
function strictInput(row: EndpointRow, schema: Schema, value: unknown): Readonly<Record<string, unknown>> {
|
|
1948
|
-
const parsed = z.safeParse(schema, value)
|
|
1952
|
+
const parsed = z.safeParse(zodSchemaOf(schema), value)
|
|
1949
1953
|
if (!parsed.success) {
|
|
1950
1954
|
const issues = parsed.error.issues.map((issue) => ({ path: issue.path.map(String).join('.'), code: issue.code, message: issue.message }))
|
|
1951
1955
|
const first = issues[0]
|
|
@@ -2025,7 +2029,7 @@ async function readInput(
|
|
|
2025
2029
|
}
|
|
2026
2030
|
return {}
|
|
2027
2031
|
}
|
|
2028
|
-
return strictInput(served.row, served.input, body)
|
|
2032
|
+
return strictInput(served.row, approvedInput(served.row, served.input), body)
|
|
2029
2033
|
}
|
|
2030
2034
|
|
|
2031
2035
|
/**
|
package/src/implement/egress.ts
CHANGED
|
@@ -144,8 +144,8 @@ export function platformCall<T>(work: () => T): T {
|
|
|
144
144
|
return scope.exit(work)
|
|
145
145
|
}
|
|
146
146
|
|
|
147
|
-
/** A hop's `init`: the standard fields, and Bun's `decompress`, which another runtime ignores. */
|
|
148
|
-
type HopInit = RequestInit & { readonly decompress?: boolean }
|
|
147
|
+
/** A hop's `init`: the standard fields, and Bun's `decompress` and `tls`, which another runtime ignores. */
|
|
148
|
+
type HopInit = RequestInit & { readonly decompress?: boolean; readonly tls?: { readonly serverName: string } }
|
|
149
149
|
|
|
150
150
|
type Fetch = (input: string, init: HopInit) => Promise<Response>
|
|
151
151
|
|
|
@@ -325,8 +325,9 @@ async function follow(send: Fetch, site: string, rules: PublicEgressRules, reque
|
|
|
325
325
|
signal: AbortSignal.any([signal, dropped.signal]),
|
|
326
326
|
// Bun decompresses natively and unbounded: the guard asks for `identity` and reads the bytes as they came.
|
|
327
327
|
decompress: false,
|
|
328
|
-
// Bun pools connections by address and port: a
|
|
329
|
-
|
|
328
|
+
// Bun checks the certificate against `serverName`, not `Host`, and pools connections by address and port: a
|
|
329
|
+
// pooled one was checked against another name's certificate.
|
|
330
|
+
...(address === null ? {} : { keepalive: false, tls: { serverName: normalizedHost(url.hostname) } }),
|
|
330
331
|
})
|
|
331
332
|
const location = REDIRECTS.has(response.status) ? response.headers.get('location') : null
|
|
332
333
|
if (location === null || mode === 'manual') {
|
|
@@ -397,8 +398,8 @@ function pinnedUrl(url: URL, address: string): string {
|
|
|
397
398
|
}
|
|
398
399
|
|
|
399
400
|
/**
|
|
400
|
-
* A hop's headers: for a pinned hop, `Host` names the checked host, which Bun sends
|
|
401
|
-
*
|
|
401
|
+
* A hop's headers: for a pinned hop, `Host` names the checked host, which Bun sends; `follow` names it as the TLS
|
|
402
|
+
* `serverName` too (`public-egress-pinning.test.ts` holds the pinned Bun release to both).
|
|
402
403
|
*/
|
|
403
404
|
function hopHeaders(headers: Headers, url: URL, address: string | null): Headers {
|
|
404
405
|
const hop = new Headers(headers)
|
package/src/implement/faults.ts
CHANGED
|
@@ -35,6 +35,7 @@ export const SERVER_FAULTS = {
|
|
|
35
35
|
attachment_size: 'the encoded attachment is larger than it declares (maxBytes); no body was sent',
|
|
36
36
|
redirect_refused:
|
|
37
37
|
"the handler redirected to a target that is neither its own origin's path, an origin its redirect() lists, nor a URL a verified token of the request carries",
|
|
38
|
+
schema_unapproved: 'a schema the application evaluated has another shape than its approved contract holds for the endpoint',
|
|
38
39
|
token_claims_refused: "the claims a site signed are not what the token purpose's claims schema admits",
|
|
39
40
|
token_keys_missing: 'a site signed a token, and the environment holds no token key',
|
|
40
41
|
url_unbuildable:
|
package/src/implement/project.ts
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
// schema then validates what is left, so an undeclared field is dropped rather than leaked or refused.
|
|
3
3
|
|
|
4
4
|
import { z } from 'zod/v4'
|
|
5
|
+
import { type DataSchema, zodSchemaOf } from '../schema/data-schema'
|
|
5
6
|
|
|
6
7
|
/** No branch of a union accepts the value, whatever it is reduced to. */
|
|
7
8
|
export class ProjectionRefusedError extends Error {
|
|
@@ -17,7 +18,8 @@ function isRecord(value: unknown): value is Record<string, unknown> {
|
|
|
17
18
|
* in declaration order, whose schema accepts the value reduced to that branch. Anything else is left for
|
|
18
19
|
* validation.
|
|
19
20
|
*/
|
|
20
|
-
export function project(
|
|
21
|
+
export function project(declared: z.core.$ZodType | DataSchema, value: unknown): unknown {
|
|
22
|
+
const schema = zodSchemaOf(declared)
|
|
21
23
|
if (schema instanceof z.core.$ZodObject) {
|
|
22
24
|
if (!isRecord(value)) {
|
|
23
25
|
return value
|
package/src/implement/tokens.ts
CHANGED
|
@@ -10,6 +10,7 @@ import { createHmac, timingSafeEqual } from 'node:crypto'
|
|
|
10
10
|
import { z } from 'zod/v4'
|
|
11
11
|
import type { Schema } from '../contract/define'
|
|
12
12
|
import { BadRequestError } from '../errors'
|
|
13
|
+
import { zodSchemaOf } from '../schema/data-schema'
|
|
13
14
|
import { CapabilityRefusedError } from './capability'
|
|
14
15
|
import { ServerFault } from './faults'
|
|
15
16
|
|
|
@@ -107,7 +108,7 @@ export class SignedTokens {
|
|
|
107
108
|
`${site} signed a '${purpose}' token for ${String(days)} days; the purpose allows 1 to ${declared.maxDays}`,
|
|
108
109
|
)
|
|
109
110
|
}
|
|
110
|
-
const parsed = z.safeParse(declared.claims, claims)
|
|
111
|
+
const parsed = z.safeParse(zodSchemaOf(declared.claims), claims)
|
|
111
112
|
if (!parsed.success) {
|
|
112
113
|
throw new ServerFault('token_claims_refused', `${site} signed a '${purpose}' token whose claims its schema refuses`)
|
|
113
114
|
}
|
|
@@ -143,7 +144,7 @@ export class SignedTokens {
|
|
|
143
144
|
if (body.x <= Math.floor(this.#now() / 1000)) {
|
|
144
145
|
throw new BadRequestError('The signed token has expired')
|
|
145
146
|
}
|
|
146
|
-
const claims = z.safeParse(declared.claims, body.c)
|
|
147
|
+
const claims = z.safeParse(zodSchemaOf(declared.claims), body.c)
|
|
147
148
|
if (!claims.success || !isRecord(claims.data)) {
|
|
148
149
|
throw invalid()
|
|
149
150
|
}
|
package/src/implement/types.ts
CHANGED
|
@@ -1,10 +1,22 @@
|
|
|
1
1
|
// The handler types `implement` checks against the contract: one handler per declared procedure, nothing else, each
|
|
2
2
|
// with the context its access form grants and returning only the fields its output declares.
|
|
3
3
|
|
|
4
|
-
import type { z } from 'zod/v4'
|
|
5
4
|
import type { ConnectSnapshot } from '../contract/connect'
|
|
6
5
|
import type { SurfaceSection } from '../contract/declaration'
|
|
7
|
-
import type {
|
|
6
|
+
import type {
|
|
7
|
+
Export,
|
|
8
|
+
InputOf,
|
|
9
|
+
InputSchema,
|
|
10
|
+
LinkMount,
|
|
11
|
+
MemberAccess,
|
|
12
|
+
Procedure,
|
|
13
|
+
RoleOf,
|
|
14
|
+
RpcMount,
|
|
15
|
+
Schema,
|
|
16
|
+
SchemaInput,
|
|
17
|
+
SchemaOutput,
|
|
18
|
+
WebhookMount,
|
|
19
|
+
} from '../contract/define'
|
|
8
20
|
import type { JobHandlersOf } from '../jobs/types'
|
|
9
21
|
import type { AppCapability, Ref, Within } from './capability'
|
|
10
22
|
import type { ConnectResult } from './connect'
|
|
@@ -116,7 +128,7 @@ export type HandlerInput<I, Acc> = IsAny<Acc> extends true ? InputOf<I>
|
|
|
116
128
|
/** `In` without the fields `F`, read-only: the only copy of each removed id a handler has is the checked capability. */
|
|
117
129
|
type Without<In, F> = { readonly [K in keyof In as K extends F ? never : K]: In[K] }
|
|
118
130
|
|
|
119
|
-
export type Handler<In, Ctx, O extends Schema> = (args: { readonly input: In; readonly ctx: Ctx }) =>
|
|
131
|
+
export type Handler<In, Ctx, O extends Schema> = (args: { readonly input: In; readonly ctx: Ctx }) => SchemaInput<O> | Promise<SchemaInput<O>>
|
|
120
132
|
|
|
121
133
|
// ── Connectors: `ctx.connect` in the handlers an import's `usedBy` names, typed by the vendored snapshot ────────
|
|
122
134
|
|
|
@@ -134,8 +146,8 @@ type ImportedProcedures<C, K> = K extends keyof ImportsOf<C>
|
|
|
134
146
|
: never
|
|
135
147
|
|
|
136
148
|
/** A connector call never throws for the owner's answer: it resolves to a typed outcome. */
|
|
137
|
-
export type ConnectCall<I, O extends Schema> = [I] extends [InputSchema] ? (input:
|
|
138
|
-
: (input?: Record<never, never>) => Promise<ConnectResult<
|
|
149
|
+
export type ConnectCall<I, O extends Schema> = [I] extends [InputSchema] ? (input: SchemaInput<I>) => Promise<ConnectResult<SchemaOutput<O>>>
|
|
150
|
+
: (input?: Record<never, never>) => Promise<ConnectResult<SchemaOutput<O>>>
|
|
139
151
|
|
|
140
152
|
type ConnectorOf<S, P extends string> = {
|
|
141
153
|
readonly [Path in P]: S extends
|
|
@@ -180,7 +192,7 @@ type LinkHandlers<D extends string, T> = {
|
|
|
180
192
|
* stable key. It runs at least once per delivery: a failed run is run again on GitHub's redelivery.
|
|
181
193
|
*/
|
|
182
194
|
export type WebhookHandler<B extends string, Acts extends string, I> = (args: {
|
|
183
|
-
readonly input:
|
|
195
|
+
readonly input: SchemaOutput<I>
|
|
184
196
|
readonly ctx: RequestContext<WebhookPrincipal> & { readonly refs: { readonly [A in Acts]: Ref<B, A> }; readonly delivery: WebhookDelivery }
|
|
185
197
|
}) => void | Promise<void>
|
|
186
198
|
|
package/src/react/hooks.ts
CHANGED
|
@@ -5,7 +5,8 @@
|
|
|
5
5
|
import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react'
|
|
6
6
|
import { z } from 'zod/v4'
|
|
7
7
|
import type { AttachmentProcedure, DownloadedFile, DownloadInput, FileProcedure } from '../client/contract'
|
|
8
|
-
import type { Schema } from '../contract/define'
|
|
8
|
+
import type { Schema, SchemaOutput } from '../contract/define'
|
|
9
|
+
import { zodOf } from '../schema/data-schema'
|
|
9
10
|
import { type FabrikaError, toFabrikaError } from './errors'
|
|
10
11
|
import { parentOf, prefixOf, useFabrika } from './provider'
|
|
11
12
|
import type { PagesEntry, QueryEntry } from './store'
|
|
@@ -29,8 +30,8 @@ const IDLE = Object.freeze({ status: 'idle', data: undefined, error: null, fetch
|
|
|
29
30
|
const NO_ENTRY = { subscribe: () => () => {}, snapshot: null }
|
|
30
31
|
|
|
31
32
|
/** An answer the cache holds, read back through the output schema; a value it refuses is an error, never a cast. */
|
|
32
|
-
function readBack<O extends Schema>(schema: O, value: unknown): { readonly ok: true; readonly data:
|
|
33
|
-
const parsed = z.safeParse(schema, value)
|
|
33
|
+
function readBack<O extends Schema>(schema: O, value: unknown): { readonly ok: true; readonly data: SchemaOutput<O> } | { readonly ok: false } {
|
|
34
|
+
const parsed = z.safeParse(zodOf(schema), value)
|
|
34
35
|
return parsed.success ? { ok: true, data: parsed.data } : { ok: false }
|
|
35
36
|
}
|
|
36
37
|
|
|
@@ -58,17 +59,17 @@ export interface QueryOptions {
|
|
|
58
59
|
export function useQuery<O extends Schema>(
|
|
59
60
|
procedure: TypedProcedure<Record<never, never> | undefined, O>,
|
|
60
61
|
input?: typeof skip,
|
|
61
|
-
): QueryState<
|
|
62
|
+
): QueryState<SchemaOutput<O>>
|
|
62
63
|
export function useQuery<I, O extends Schema>(
|
|
63
64
|
procedure: TypedProcedure<I, O>,
|
|
64
65
|
input: I | typeof skip,
|
|
65
66
|
options?: QueryOptions,
|
|
66
|
-
): QueryState<
|
|
67
|
+
): QueryState<SchemaOutput<O>>
|
|
67
68
|
export function useQuery<I, O extends Schema>(
|
|
68
69
|
procedure: TypedProcedure<I, O>,
|
|
69
70
|
input?: I | typeof skip,
|
|
70
71
|
options: QueryOptions = {},
|
|
71
|
-
): QueryState<
|
|
72
|
+
): QueryState<SchemaOutput<O>> {
|
|
72
73
|
const fabrika = useFabrika('useQuery')
|
|
73
74
|
const target = useMemo(() => fabrika.target(procedure, 'useQuery'), [fabrika, procedure])
|
|
74
75
|
if (target.node.procedure?.type === 'mutation') throw new Error(`useQuery: '${target.id}' is a mutation; use useMutation`)
|
|
@@ -80,7 +81,7 @@ export function useQuery<I, O extends Schema>(
|
|
|
80
81
|
const snapshot = useSyncExternalStore((listener) => source.subscribe(listener), () => source.snapshot, () => source.snapshot)
|
|
81
82
|
useLoad(entry)
|
|
82
83
|
const refetch = useCallback(() => entry?.load() ?? Promise.resolve(), [entry])
|
|
83
|
-
const state = useMemo((): QueryState<
|
|
84
|
+
const state = useMemo((): QueryState<SchemaOutput<O>> => {
|
|
84
85
|
if (snapshot === null) return IDLE
|
|
85
86
|
const fetching = snapshot.fetching
|
|
86
87
|
if (snapshot.status === 'loading') return { status: 'loading', data: undefined, error: null, fetching, refetch }
|
|
@@ -92,7 +93,7 @@ export function useQuery<I, O extends Schema>(
|
|
|
92
93
|
? { status: 'loading', data: undefined, error: null, fetching, refetch }
|
|
93
94
|
: { status: 'success', data, error: null, fetching, refetch }
|
|
94
95
|
}, [snapshot, procedure, refetch])
|
|
95
|
-
const previous = useRef<
|
|
96
|
+
const previous = useRef<SchemaOutput<O> | undefined>(undefined)
|
|
96
97
|
useEffect(() => {
|
|
97
98
|
if (state.status === 'success') previous.current = state.data
|
|
98
99
|
}, [state])
|
|
@@ -246,11 +247,11 @@ function useRun<I, T>(run: (input: I) => Promise<T>, after: () => Promise<void>,
|
|
|
246
247
|
*/
|
|
247
248
|
export function useMutation<I, O extends Schema>(
|
|
248
249
|
procedure: TypedProcedure<I, O>,
|
|
249
|
-
options: MutationOptions<
|
|
250
|
-
): MutationState<InputArgument<I>,
|
|
250
|
+
options: MutationOptions<SchemaOutput<O>> = {},
|
|
251
|
+
): MutationState<InputArgument<I>, SchemaOutput<O>> {
|
|
251
252
|
const fabrika = useFabrika('useMutation')
|
|
252
253
|
const target = useMemo(() => fabrika.target(procedure, 'useMutation'), [fabrika, procedure])
|
|
253
|
-
const run = useCallback(async (input: InputArgument<I>): Promise<
|
|
254
|
+
const run = useCallback(async (input: InputArgument<I>): Promise<SchemaOutput<O>> => {
|
|
254
255
|
const read = readBack(procedure.output, await target.run(input ?? undefined))
|
|
255
256
|
if (!read.ok) throw new Error(`'${target.id}' answered a value its output schema refuses`)
|
|
256
257
|
return read.data
|
package/src/react/provider.tsx
CHANGED
|
@@ -10,6 +10,7 @@ import { attachmentAt, type ClientNode, clientNodeOf, type DownloadedFile, downl
|
|
|
10
10
|
import { startErrorReporting } from '../client/error-reporting'
|
|
11
11
|
import { RpcError, type RpcFetch } from '../client/transport'
|
|
12
12
|
import { BROWSER_CONFIG_FILE, joinPath, PAGE_CALLER_FILE } from '../contract/defaults'
|
|
13
|
+
import { zodSchemaOf } from '../schema/data-schema'
|
|
13
14
|
import { type FabrikaError, toFabrikaError } from './errors'
|
|
14
15
|
import { QueryStore, type StoreTarget } from './store'
|
|
15
16
|
|
|
@@ -80,7 +81,7 @@ function issuesOf(error: z.core.$ZodError): readonly { readonly path: string; re
|
|
|
80
81
|
function validated(node: ClientNode, input: unknown): unknown {
|
|
81
82
|
const schema = node.procedure?.input ?? null
|
|
82
83
|
if (schema === null) return input
|
|
83
|
-
const parsed = z.safeParse(schema, input ?? {})
|
|
84
|
+
const parsed = z.safeParse(zodSchemaOf(schema), input ?? {})
|
|
84
85
|
if (parsed.success) return input
|
|
85
86
|
const issues = issuesOf(parsed.error)
|
|
86
87
|
const first = issues[0]
|
package/src/react/types.ts
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
// schema parses it.
|
|
3
3
|
|
|
4
4
|
import type { z } from 'zod/v4'
|
|
5
|
-
import type { Schema } from '../contract/define'
|
|
5
|
+
import type { Schema, SchemaOutput } from '../contract/define'
|
|
6
6
|
|
|
7
7
|
/** A query or mutation of a client that `createClient` built. */
|
|
8
8
|
export type ClientProcedure = ((input: never) => Promise<unknown>) & { readonly output: Schema }
|
|
@@ -25,7 +25,7 @@ export type TypedProcedure<I, O extends Schema> = ((input: I) => Promise<unknown
|
|
|
25
25
|
export type InputArgument<I> = undefined extends I ? I | void : I
|
|
26
26
|
|
|
27
27
|
/** The answer, as the procedure's output schema parses it. */
|
|
28
|
-
export type ProcedureResult<F extends ClientProcedure> =
|
|
28
|
+
export type ProcedureResult<F extends ClientProcedure> = SchemaOutput<F['output']>
|
|
29
29
|
|
|
30
30
|
/** The answer of a cursor list: `{ items, next }`. */
|
|
31
31
|
export interface PageAnswer<Item> {
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
// The `z` of `@fabrika/app/schema`: the contract subset of zod's API, each factory recording its call as a
|
|
2
|
+
// `DataSchema`. A schema's type is the zod type the same call would return, so `z.infer` reads as zod's own.
|
|
3
|
+
|
|
4
|
+
import type { z as zod } from 'zod/v4'
|
|
5
|
+
import {
|
|
6
|
+
type AnySchema,
|
|
7
|
+
DataEnum,
|
|
8
|
+
DataObject,
|
|
9
|
+
DataSchema,
|
|
10
|
+
type DataShapeInput,
|
|
11
|
+
type Message,
|
|
12
|
+
type UuidOptions,
|
|
13
|
+
type ZodList,
|
|
14
|
+
type ZodOf,
|
|
15
|
+
type ZodShape,
|
|
16
|
+
} from './data-schema'
|
|
17
|
+
|
|
18
|
+
type Primitive = string | number | boolean | null
|
|
19
|
+
|
|
20
|
+
export type DatetimeOptions = string | {
|
|
21
|
+
readonly message?: string
|
|
22
|
+
readonly error?: string
|
|
23
|
+
readonly offset?: boolean
|
|
24
|
+
readonly local?: boolean
|
|
25
|
+
readonly precision?: number | null
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export type TimeOptions = string | { readonly message?: string; readonly error?: string; readonly precision?: number | null }
|
|
29
|
+
|
|
30
|
+
/** What a schema admits once parsed, as `zod`'s `z.output`. */
|
|
31
|
+
export type output<S> = zod.output<ZodOf<S>>
|
|
32
|
+
/** What a schema takes before parsing, as `zod`'s `z.input`. */
|
|
33
|
+
export type input<S> = zod.input<ZodOf<S>>
|
|
34
|
+
export type { output as infer }
|
|
35
|
+
|
|
36
|
+
function factory<T extends zod.ZodType>(name: string, args: readonly unknown[]): DataSchema<T> {
|
|
37
|
+
return new DataSchema<T>(name, false, null, args)
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function string(params?: Message): DataSchema<zod.ZodString> {
|
|
41
|
+
return factory('string', [params])
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function number(params?: Message): DataSchema<zod.ZodNumber> {
|
|
45
|
+
return factory('number', [params])
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function int(params?: Message): DataSchema<zod.ZodInt> {
|
|
49
|
+
return factory('int', [params])
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function boolean(params?: Message): DataSchema<zod.ZodBoolean> {
|
|
53
|
+
return factory('boolean', [params])
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function _null(params?: Message): DataSchema<zod.ZodNull> {
|
|
57
|
+
return factory('null', [params])
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export function uuid(params?: UuidOptions): DataSchema<zod.ZodUUID> {
|
|
61
|
+
return factory('uuid', [params])
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export function email(params?: Message): DataSchema<zod.ZodEmail> {
|
|
65
|
+
return factory('email', [params])
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function url(params?: Message): DataSchema<zod.ZodURL> {
|
|
69
|
+
return factory('url', [params])
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export function literal<const L extends Primitive | readonly Primitive[]>(
|
|
73
|
+
value: L,
|
|
74
|
+
params?: Message,
|
|
75
|
+
): DataSchema<zod.ZodLiteral<L extends readonly Primitive[] ? L[number] : L>> {
|
|
76
|
+
return factory('literal', [value, params])
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function _enum<const E extends readonly string[] | zod.core.util.EnumLike>(
|
|
80
|
+
values: E,
|
|
81
|
+
params?: Message,
|
|
82
|
+
): DataEnum<E extends readonly string[] ? zod.core.util.ToEnum<E[number]> : E> {
|
|
83
|
+
return new DataEnum<E extends readonly string[] ? zod.core.util.ToEnum<E[number]> : E>('enum', false, null, [values, params])
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export function strictObject<S extends DataShapeInput>(shape: S, params?: Message): DataObject<ZodShape<S>, zod.core.$strict> {
|
|
87
|
+
return new DataObject<ZodShape<S>, zod.core.$strict>('strictObject', false, null, [shape, params])
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export function array<E extends AnySchema>(element: E, params?: Message): DataSchema<zod.ZodArray<ZodOf<E>>> {
|
|
91
|
+
return factory('array', [element, params])
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export function tuple<const I extends readonly AnySchema[], R extends AnySchema = never>(
|
|
95
|
+
items: I,
|
|
96
|
+
rest?: R | Message,
|
|
97
|
+
params?: Message,
|
|
98
|
+
): DataSchema<zod.ZodTuple<Extract<ZodList<I>, zod.core.util.TupleItems>, [R] extends [never] ? null : ZodOf<R>>> {
|
|
99
|
+
return factory('tuple', [items, rest, params])
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export function union<const O extends readonly AnySchema[]>(
|
|
103
|
+
options: O,
|
|
104
|
+
params?: Message,
|
|
105
|
+
): DataSchema<zod.ZodUnion<Extract<ZodList<O>, readonly zod.core.SomeType[]>>> {
|
|
106
|
+
return factory('union', [options, params])
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export function discriminatedUnion<const O extends readonly [AnySchema, ...AnySchema[]]>(
|
|
110
|
+
discriminator: string,
|
|
111
|
+
options: O,
|
|
112
|
+
params?: Message,
|
|
113
|
+
): DataSchema<
|
|
114
|
+
zod.ZodDiscriminatedUnion<Extract<ZodList<O>, readonly [zod.core.$ZodTypeDiscriminable, ...zod.core.$ZodTypeDiscriminable[]]>>
|
|
115
|
+
> {
|
|
116
|
+
return factory('discriminatedUnion', [discriminator, options, params])
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export function record<K extends AnySchema, V extends AnySchema>(
|
|
120
|
+
key: K,
|
|
121
|
+
value: V,
|
|
122
|
+
params?: Message,
|
|
123
|
+
): DataSchema<zod.ZodRecord<Extract<ZodOf<K>, zod.core.$ZodRecordKey>, ZodOf<V>>> {
|
|
124
|
+
return factory('record', [key, value, params])
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
export function optional<S extends AnySchema>(inner: S): DataSchema<zod.ZodOptional<ZodOf<S>>> {
|
|
128
|
+
return factory('optional', [inner])
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
export function nullable<S extends AnySchema>(inner: S): DataSchema<zod.ZodNullable<ZodOf<S>>> {
|
|
132
|
+
return factory('nullable', [inner])
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function isoFactory<T extends zod.ZodType>(name: string, params: unknown): DataSchema<T> {
|
|
136
|
+
return new DataSchema<T>(name, true, null, [params])
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
export const iso = Object.freeze({
|
|
140
|
+
date: (params?: Message): DataSchema<zod.ZodISODate> => isoFactory('date', params),
|
|
141
|
+
datetime: (params?: DatetimeOptions): DataSchema<zod.ZodISODateTime> => isoFactory('datetime', params),
|
|
142
|
+
time: (params?: TimeOptions): DataSchema<zod.ZodISOTime> => isoFactory('time', params),
|
|
143
|
+
duration: (params?: Message): DataSchema<zod.ZodISODuration> => isoFactory('duration', params),
|
|
144
|
+
})
|
|
145
|
+
|
|
146
|
+
export { _enum as enum, _null as null }
|