@fabrika/app 0.9.0-dev.13 → 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 +3 -2
- package/skill/references/app-setup.md +17 -9
- package/skill/references/endpoint.md +15 -2
- package/skill/references/errors.md +7 -6
- package/skill/references/jobs.md +10 -0
- package/skill/references/relations.md +145 -21
- package/skill/references/table-and-migration.md +4 -1
- package/skill/references/webhooks-links-connectors.md +2 -1
- package/src/build-contract-child.ts +16 -0
- package/src/build.ts +48 -2
- package/src/bun.ts +10 -0
- package/src/client/contract.ts +6 -4
- package/src/cloudflare/application.ts +3 -0
- package/src/contract/artifact-schema.ts +367 -299
- package/src/contract/attachment.ts +4 -3
- package/src/contract/build.ts +76 -18
- package/src/contract/compile.ts +3 -2
- package/src/contract/context.ts +2 -3
- package/src/contract/define.ts +19 -6
- package/src/contract/group.ts +18 -8
- package/src/contract/index.ts +1 -1
- package/src/contract/kit.ts +4 -3
- package/src/contract/problems.ts +4 -0
- package/src/contract/schema-shape.ts +14 -2
- package/src/contract/token.ts +4 -3
- package/src/disk-assets.ts +15 -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 +118 -17
- package/src/implement/capability.ts +82 -12
- package/src/implement/dispatch.ts +265 -45
- package/src/implement/egress.ts +410 -9
- package/src/implement/faults.ts +1 -0
- package/src/implement/implement.ts +23 -3
- package/src/implement/invocation.ts +10 -9
- package/src/implement/project.ts +3 -1
- package/src/implement/tokens.ts +3 -2
- package/src/implement/types.ts +33 -10
- package/src/implement/webhook.ts +8 -0
- package/src/jobs/runner.ts +7 -2
- 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/source-map-path.ts +21 -0
- package/src/testing/caller.ts +20 -9
- package/src/testing/kit.ts +3 -3
- package/src/testing/membership.ts +9 -5
- 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 +16 -6
- package/types/src/contract/group.d.ts +14 -7
- package/types/src/contract/index.d.ts +1 -1
- package/types/src/contract/kit.d.ts +4 -5
- 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 +12 -0
- package/types/src/implement/capability.d.ts +14 -5
- package/types/src/implement/dispatch.d.ts +9 -1
- package/types/src/implement/egress.d.ts +36 -1
- package/types/src/implement/faults.d.ts +1 -0
- package/types/src/implement/implement.d.ts +19 -3
- package/types/src/implement/invocation.d.ts +3 -3
- package/types/src/implement/project.d.ts +2 -1
- package/types/src/implement/types.d.ts +17 -8
- package/types/src/jobs/runner.d.ts +3 -0
- 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/source-map-path.d.ts +4 -0
- package/types/src/testing/caller.d.ts +6 -1
- package/types/src/testing/kit.d.ts +2 -3
- package/types/src/testing/membership.d.ts +1 -1
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
|
|
|
@@ -215,13 +227,24 @@ export type HandlersOf<C, Snap = unknown> =
|
|
|
215
227
|
/** An `any` comes from an error elsewhere in the handler; reporting it here too would only add noise. */
|
|
216
228
|
export type IsAny<T> = 0 extends 1 & T ? true : false
|
|
217
229
|
|
|
218
|
-
/**
|
|
230
|
+
/**
|
|
231
|
+
* Fields of `R` that the output `O` does not declare. Each member of a union `R` is paired with `O` on its own, and a
|
|
232
|
+
* member that fits one branch of a union `O` has none.
|
|
233
|
+
*/
|
|
219
234
|
export type ExtraKeys<R, O> = IsAny<R> extends true ? never
|
|
220
|
-
: true extends (O extends unknown ? ([ExtraKeysOf<R, O>] extends [never] ? true : false) : never) ? never
|
|
221
|
-
|
|
235
|
+
: R extends unknown ? true extends (O extends unknown ? ([ExtraKeysOf<R, O>] extends [never] ? true : false) : never) ? never
|
|
236
|
+
: ExtraKeysOf<R, O>
|
|
237
|
+
: never
|
|
238
|
+
|
|
239
|
+
/**
|
|
240
|
+
* Optional keys that can hold only `undefined`: TypeScript adds them when it widens object literals of different
|
|
241
|
+
* shapes to one type (`{ x } | { x, y }` read as `{ x, y?: undefined }`). They carry no value, and projection drops them.
|
|
242
|
+
*/
|
|
243
|
+
type EmptyKeys<R> = { [K in keyof R]-?: object extends Pick<R, K> ? ([Exclude<R[K], undefined>] extends [never] ? K : never) : never }[keyof R]
|
|
222
244
|
|
|
223
245
|
type ExtraKeysOf<R, O> = R extends readonly (infer RE)[] ? (O extends readonly (infer OE)[] ? ExtraKeys<RE, OE> : never)
|
|
224
|
-
: R extends object
|
|
246
|
+
: R extends object
|
|
247
|
+
? O extends object ? Exclude<keyof R, keyof O | EmptyKeys<R>> | { [Q in keyof R & keyof O]: ExtraKeys<R[Q], O[Q]> }[keyof R & keyof O]
|
|
225
248
|
: never
|
|
226
249
|
: never
|
|
227
250
|
|
package/src/implement/webhook.ts
CHANGED
|
@@ -110,6 +110,14 @@ export function webhookBindings(site: BindingSite): (name: string) => WebhookBin
|
|
|
110
110
|
return APP_BINDING_SCOPE
|
|
111
111
|
}
|
|
112
112
|
if (webhook.boundTo.kind === 'dimension' && grant.kind === 'ref' && grant.dimension === webhook.boundTo.dimension) {
|
|
113
|
+
// A binding outlives every statement, so it takes no reach that a statement re-reads: a relation row, a
|
|
114
|
+
// member reveal or a secondary path may end before the next delivery.
|
|
115
|
+
if (grant.relations.length > 0 || grant.revealing.length > 0 || grant.paths.length > 0) {
|
|
116
|
+
throw new CapabilityRefusedError(
|
|
117
|
+
'conditional_binding',
|
|
118
|
+
`${site.site}: webhook '${webhook.name}' binds only with a Ref an IAM grant holds, and it was handed one held through a relation, a member reveal or a secondary path`,
|
|
119
|
+
)
|
|
120
|
+
}
|
|
113
121
|
return { type: grant.dimension, value: grant.id }
|
|
114
122
|
}
|
|
115
123
|
const wanted = webhook.boundTo.kind === 'app' ? 'an app capability (ctx.app)' : `a Ref of ${webhook.boundTo.dimension}`
|
package/src/jobs/runner.ts
CHANGED
|
@@ -34,7 +34,7 @@ import {
|
|
|
34
34
|
type Within,
|
|
35
35
|
} from '../implement/capability'
|
|
36
36
|
import { admitInvocation, type InvocationAdmission } from '../implement/dispatch'
|
|
37
|
-
import { runAsSite } from '../implement/egress'
|
|
37
|
+
import { type PublicEgressRules, runAsSite, siteEgress } from '../implement/egress'
|
|
38
38
|
import { failureCode, type FailureReason, failureReason, type HandlerErrorSink, reveal } from '../implement/failures'
|
|
39
39
|
import { ServerFault } from '../implement/faults'
|
|
40
40
|
import type { ContractDatabase } from '../implement/implement'
|
|
@@ -274,6 +274,8 @@ interface RunnerContext {
|
|
|
274
274
|
/** The environment's signed tokens: `ctx.tokens` of a job that declares `signs`. */
|
|
275
275
|
readonly tokens: SignedTokens | null
|
|
276
276
|
readonly url: AppUrl
|
|
277
|
+
/** What a job that declares `egress: 'public'` reaches; such a job reaches nothing without it. */
|
|
278
|
+
readonly publicEgress: PublicEgressRules | null
|
|
277
279
|
}
|
|
278
280
|
|
|
279
281
|
export interface JobBindingInput {
|
|
@@ -310,6 +312,8 @@ export interface JobBindingInput {
|
|
|
310
312
|
readonly tokens?: SignedTokens
|
|
311
313
|
/** `ctx.url`: absolute links to the application's own procedures; without it every link is refused. */
|
|
312
314
|
readonly url?: AppUrl
|
|
315
|
+
/** The rules of public egress, which `boot` reads from the environment; without them a public job reaches nothing. */
|
|
316
|
+
readonly publicEgress?: PublicEgressRules
|
|
313
317
|
}
|
|
314
318
|
|
|
315
319
|
interface BoundFrameworkJob {
|
|
@@ -420,6 +424,7 @@ export function bindJobs(input: JobBindingInput, problems: string[]): BoundJobs
|
|
|
420
424
|
mail: input.mail,
|
|
421
425
|
tokens: input.tokens ?? null,
|
|
422
426
|
url: input.url ?? appUrl(input.artifact, null),
|
|
427
|
+
publicEgress: input.publicEgress ?? null,
|
|
423
428
|
// A job's kicks run only after the job is bound, so `kick` below is defined by then.
|
|
424
429
|
kick: (name: string) => kick(name),
|
|
425
430
|
})
|
|
@@ -1252,7 +1257,7 @@ async function attemptOnce(
|
|
|
1252
1257
|
if (site === null) {
|
|
1253
1258
|
await job.handler({ ctx })
|
|
1254
1259
|
} else {
|
|
1255
|
-
await runAsSite(`job '${job.name}'`, site.egress, async () => await job.handler({ ctx }))
|
|
1260
|
+
await runAsSite(`job '${job.name}'`, siteEgress(site.egress, context.publicEgress), async () => await job.handler({ ctx }))
|
|
1256
1261
|
}
|
|
1257
1262
|
kicked.recorder = kicks
|
|
1258
1263
|
}).then(() => null, (error: unknown) => {
|
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 }
|