Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions .changeset/flat-included-services.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
---
"@thomasfosterau/effect-jsonapi": minor
---

A flat group's include surface now types its documents end to end (#595).

- **`Group.flat` / `Group.flatReadOnly` keep the surface's `included` union in their success schemas.** It used to be inferred while the surface type was still generic, which widened it to `Schema.Top`: every endpoint's decoding services became `unknown`, so a typed `Client.make` method required `unknown`, and `effect/cli` commands built on one failed to type-check. A flat group without a surface is unchanged.
- **`Assemble` and `ResourceHandlers` type `included` by the include registry.** `Assemble.ResourceDocument`, `CollectionDocument` and `UnpaginatedCollectionDocument` gain a trailing `I` parameter, the `included` members' type, defaulting to `ResourceLike`. `Assemble.resource` / `collection` / `unpaginatedCollection` set it from their `targets` through the new `Assemble.TargetsIncluded<Targets>`: what the loaders return, or `never` with no registry. `ResourceHandlers.readOnly` / `make` handlers get the same type, with writes typed `never`. A family's handlers then satisfy a group whose `included` is the surface's precise union, with no cast. Declare the registry with `satisfies Handlers.IncludeTargets` so the loaders' types stay visible; an annotated registry keeps the loose `ResourceLike`.
- **Migration:** drop any `Schema.Codec<…, never, never>` cast around a flat group's documents, and any cast on handler output. Code that names a document's exact type from a call with no registry sees `included?: ReadonlyArray<never>` instead of `ReadonlyArray<WireResource<ResourceLike>>`, which is still assignable to the old type.
92 changes: 69 additions & 23 deletions src/Assemble.ts
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,25 @@ export type WireResource<R extends ResourceLike> = Document.Wire<R> & {
readonly links?: { readonly self?: string };
};

/**
* The type of the `included` members a walk through `Targets` resolves to:
* what the registry's loaders return (`Handlers.IncludeTargetResource`).
* With no registry nothing is walked, so nothing can be included: `never`,
* which is also what lets such a document (a write's, say) satisfy a success
* schema whose `included` is an include surface's precise union (#595). A
* registry whose loaders' types aren't visible (annotated as
* `Handlers.IncludeTargets` rather than checked with `satisfies`) gives the
* loose {@link ResourceLike}.
*
* @since 0.22.0
* @category type-level
*/
export type TargetsIncluded<Targets extends Handlers.IncludeTargets> = [Targets] extends [never]
? never
: [Extract<Handlers.IncludeTargetResource<Targets>, ResourceLike>] extends [never]
? ResourceLike
: Extract<Handlers.IncludeTargetResource<Targets>, ResourceLike>;

/**
* The `jsonapi` member every assembled document carries.
*
Expand All @@ -135,15 +154,18 @@ export const JSONAPI_MEMBER = { version: "1.1" } as const;

/**
* A single-resource document as {@link resource} assembles it, with the
* `jsonapi` member always present. `included` is the loose {@link ResourceLike}
* because the walk resolves through an untyped-by-type registry.
* `jsonapi` member always present. `I` is the `included` members' type:
* {@link resource} sets it to what the include registry's loaders return
* ({@link TargetsIncluded}), so a document is assignable to a success schema
* whose `included` is the include surface's precise union (#595). Written by
* hand, it defaults to the loose {@link ResourceLike}.
*
* @since 0.16.0
* @category models
*/
export interface ResourceDocument<R extends ResourceLike> {
export interface ResourceDocument<R extends ResourceLike, I extends ResourceLike = ResourceLike> {
readonly data: WireResource<R> & { readonly meta?: { readonly [key: string]: unknown } };
readonly included?: ReadonlyArray<WireResource<ResourceLike>>;
readonly included?: ReadonlyArray<WireResource<I>>;
readonly links?: { readonly self?: string };
readonly meta?: { readonly [key: string]: unknown };
readonly jsonapi: typeof JSONAPI_MEMBER;
Expand All @@ -156,11 +178,11 @@ export interface ResourceDocument<R extends ResourceLike> {
* @since 0.16.0
* @category models
*/
export interface CollectionDocument<R extends ResourceLike> {
export interface CollectionDocument<R extends ResourceLike, I extends ResourceLike = ResourceLike> {
readonly data: ReadonlyArray<
WireResource<R> & { readonly meta?: { readonly [key: string]: unknown } }
>;
readonly included?: ReadonlyArray<WireResource<ResourceLike>>;
readonly included?: ReadonlyArray<WireResource<I>>;
readonly links: Handlers.LinksValue;
readonly meta: { readonly totalCount: number; readonly [key: string]: unknown };
readonly jsonapi: typeof JSONAPI_MEMBER;
Expand Down Expand Up @@ -193,9 +215,10 @@ export type UnpaginatedCollectionDocument<
Self extends string | undefined = undefined,
// oxlint-disable-next-line effect/prefer-option-over-null -- a type-level switch on the `meta` option's type, not a runtime value: `undefined` selects the document with no `meta`
M extends Handlers.MetaValue | undefined = undefined,
I extends ResourceLike = ResourceLike,
> = {
readonly data: ReadonlyArray<WireResource<R> & { readonly meta?: Handlers.MetaValue }>;
readonly included?: ReadonlyArray<WireResource<ResourceLike>>;
readonly included?: ReadonlyArray<WireResource<I>>;
readonly jsonapi: typeof JSONAPI_MEMBER;
} & ([Self] extends [undefined]
? unknown
Expand Down Expand Up @@ -409,8 +432,10 @@ export interface Options<V = unknown, Targets extends Handlers.IncludeTargets =
export interface CollectionOptions<
V = unknown,
Targets extends Handlers.IncludeTargets = never,
X extends ResourceLike = never,
> extends Options<V, Targets> {
readonly included?: ReadonlyArray<ResourceLike> | undefined;
/** Members the caller already resolved; `X` is their type, part of the document's `included` type. */
readonly included?: ReadonlyArray<X> | undefined;
}

/**
Expand All @@ -437,7 +462,8 @@ export interface UnpaginatedCollectionOptions<
Self extends string | undefined = undefined,
// oxlint-disable-next-line effect/prefer-option-over-null -- inferred from the `meta` option as passed; an `Option` there would stop a caller forwarding its own optional `meta`
M extends Handlers.MetaValue | undefined = undefined,
> extends CollectionOptions<V, Targets> {
X extends ResourceLike = never,
> extends CollectionOptions<V, Targets, X> {
/**
* The collection's own absolute URL, emitted as the document's
* `links.self`. Supplied by the handler, as {@link Pagination.baseUrl} is,
Expand Down Expand Up @@ -841,7 +867,7 @@ export const resource = <
resource: R,
options: Options<V, Targets> = {},
): Effect.Effect<
ResourceDocument<R>,
ResourceDocument<R, TargetsIncluded<Targets>>,
IncludeError | Handlers.IncludeTargetError<Targets>,
Handlers.IncludeTargetServices<Targets>
> => {
Expand All @@ -857,7 +883,10 @@ export const resource = <
),
onResource: onResourceFor(options),
});
return { ...built, jsonapi: JSONAPI_MEMBER } as unknown as ResourceDocument<R>;
return { ...built, jsonapi: JSONAPI_MEMBER } as unknown as ResourceDocument<
R,
TargetsIncluded<Targets>
>;
}),
);
};
Expand All @@ -883,9 +912,9 @@ const withoutEmptyIncluded = <T extends { readonly included?: ReadonlyArray<unkn
* own `self` (with the query it carries) and the caller's own `meta`, or
* nothing — and the document type `D` that difference produces.
*/
const assembleCollection = <D, V, Targets extends Handlers.IncludeTargets>(
const assembleCollection = <D, V, Targets extends Handlers.IncludeTargets, X extends ResourceLike>(
resources: ReadonlyArray<ResourceLike>,
options: CollectionOptions<V, Targets>,
options: CollectionOptions<V, Targets, X>,
top: {
readonly meta?: Handlers.MetaValue;
readonly links?: Handlers.LinksValue;
Expand Down Expand Up @@ -993,19 +1022,24 @@ export const collection = <
R extends ResourceLike,
V = unknown,
Targets extends Handlers.IncludeTargets = never,
X extends ResourceLike = never,
>(
resources: ReadonlyArray<R>,
pagination: Pagination,
options: CollectionOptions<V, Targets> = {},
options: CollectionOptions<V, Targets, X> = {},
): Effect.Effect<
CollectionDocument<R>,
CollectionDocument<R, TargetsIncluded<Targets> | X>,
IncludeError | Handlers.IncludeTargetError<Targets>,
Handlers.IncludeTargetServices<Targets>
> =>
assembleCollection<CollectionDocument<R>, V, Targets>(resources, options, {
meta: { totalCount: pagination.totalCount },
links: paginationLinks(pagination),
});
assembleCollection<CollectionDocument<R, TargetsIncluded<Targets> | X>, V, Targets, X>(
resources,
options,
{
meta: { totalCount: pagination.totalCount },
links: paginationLinks(pagination),
},
);

/**
* Assembles a JSON:API document around a whole, **unpaginated** collection —
Expand Down Expand Up @@ -1087,13 +1121,19 @@ export const unpaginatedCollection = <
Self extends string | undefined = undefined,
// oxlint-disable-next-line effect/prefer-option-over-null -- see `UnpaginatedCollectionOptions`: inferred from the `meta` option as passed
const M extends Handlers.MetaValue | undefined = undefined,
X extends ResourceLike = never,
>(
resources: ReadonlyArray<R>,
options: UnpaginatedCollectionOptions<V, Targets, Self, M> = {},
options: UnpaginatedCollectionOptions<V, Targets, Self, M, X> = {},
): Effect.Effect<
// `Self` is widened to `string`, so a literal `self` doesn't leak into the
// type; `M` is not, since the document emits that very value.
UnpaginatedCollectionDocument<R, Self extends string ? string : undefined, M>,
UnpaginatedCollectionDocument<
R,
Self extends string ? string : undefined,
M,
TargetsIncluded<Targets> | X
>,
IncludeError | Handlers.IncludeTargetError<Targets>,
Handlers.IncludeTargetServices<Targets>
> => {
Expand All @@ -1104,9 +1144,15 @@ export const unpaginatedCollection = <
? { self: options.self }
: { self: options.self, query: options.query };
return assembleCollection<
UnpaginatedCollectionDocument<R, Self extends string ? string : undefined, M>,
UnpaginatedCollectionDocument<
R,
Self extends string ? string : undefined,
M,
TargetsIncluded<Targets> | X
>,
V,
Targets
Targets,
X
>(resources, options, options.meta === undefined ? links : { ...links, meta: options.meta });
};

Expand Down
13 changes: 11 additions & 2 deletions src/Endpoint.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4480,6 +4480,15 @@ export interface FlatDocumentOptions<Included extends Schema.Top, TM extends Sch
readonly toManyMeta?: TM | undefined;
}

// `never` is what a flat group without an include surface passes as
// `Included` (the `included` of no surface, #595). It reads as `Schema.Top`,
// the unconstrained `included` such a group always declared, so only a group
// that has a surface gets the narrower type, and the handlers typed against a
// surface-less group still match.
type IncludedOrNone<Included extends Schema.Top> = [Included] extends [never]
? Schema.Top
: Included;

/**
* The `success:` document of a flat `get` / `create` / `update`: a
* single-resource data document over the **wire** form of `resource`
Expand Down Expand Up @@ -4513,7 +4522,7 @@ export const ResourceDocument = <
>(
resource: S,
options?: FlatDocumentOptions<Included, TM>,
): DataDocument<WireSchema<S, TM>, WireSchema<Included, TM>> =>
): DataDocument<WireSchema<S, TM>, WireSchema<IncludedOrNone<Included>, TM>> =>
asJsonApi(
DataDocument(
wire(resource, { toManyMeta: options?.toManyMeta }),
Expand Down Expand Up @@ -4672,7 +4681,7 @@ export const FlatCollectionDocument = <
>(
resource: S,
options?: FlatDocumentOptions<Included, TM>,
): CollectionDocument<WireSchema<S, TM>, WireSchema<Included, TM>> =>
): CollectionDocument<WireSchema<S, TM>, WireSchema<IncludedOrNone<Included>, TM>> =>
asJsonApi(
CollectionDocument(
wire(resource, { toManyMeta: options?.toManyMeta }),
Expand Down
18 changes: 16 additions & 2 deletions src/Group.ts
Original file line number Diff line number Diff line change
Expand Up @@ -344,6 +344,14 @@ const SHARED_FLAT_OPTIONS = {
sort: false,
} as const;

// The `included` union of a flat group's surface, or `never` without one. Named
// so the document constructors below receive it as an explicit type argument:
// inferred from `options.include?.included` while `Surface` is still generic,
// it widened to the constraint's `Schema.Top`, whose `DecodingServices` are
// `unknown`, so every endpoint's success schema, and a typed client's methods,
// asked for `unknown` services (#595).
type SurfaceIncluded<Surface extends AnySurface | undefined> = NonNullable<Surface>["included"];

const flatWire = <
R extends Schema.Top,
List extends Query.FlatListStruct,
Expand All @@ -356,8 +364,14 @@ const flatWire = <
const included = options.include?.included;
const toManyMeta = options.toManyMeta;
return {
document: Endpoint.ResourceDocument(options.resource, { included, toManyMeta }),
collection: Endpoint.FlatCollectionDocument(options.resource, { included, toManyMeta }),
document: Endpoint.ResourceDocument<R, SurfaceIncluded<Surface>, TM>(options.resource, {
included,
toManyMeta,
}),
collection: Endpoint.FlatCollectionDocument<R, SurfaceIncluded<Surface>, TM>(options.resource, {
included,
toManyMeta,
}),
listQuery: Query.flatList(options.list, { filters: options.filters }),
};
};
Expand Down
8 changes: 4 additions & 4 deletions src/ResourceHandlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -376,14 +376,14 @@ export type ReadOnlyHandlers<
readonly list: (request: {
readonly query: TQuery;
}) => Effect.Effect<
Assemble.CollectionDocument<TResource>,
Assemble.CollectionDocument<TResource, Assemble.TargetsIncluded<Targets>>,
ReadError<E, Targets>,
R | RV | RL | Handlers.IncludeTargetServices<Targets>
>;
readonly get: (
request: GetRequest<TId>,
) => Effect.Effect<
Assemble.ResourceDocument<TResource>,
Assemble.ResourceDocument<TResource, Assemble.TargetsIncluded<Targets>>,
ReadError<E, Targets>,
R | RV | RC | Handlers.IncludeTargetServices<Targets>
>;
Expand Down Expand Up @@ -418,15 +418,15 @@ export type CrudHandlers<
readonly create: (request: {
readonly payload: TCreate;
}) => Effect.Effect<
Assemble.ResourceDocument<TResource> | Committed,
Assemble.ResourceDocument<TResource, never> | Committed,
E | ET,
R | RV | RC | RT | Exclude<RW, Tx>
>;
readonly update: (request: {
readonly params: { readonly id: TId };
readonly payload: TUpdate;
}) => Effect.Effect<
Assemble.ResourceDocument<TResource> | Committed,
Assemble.ResourceDocument<TResource, never> | Committed,
E | ET | ApiError.Conflict,
R | RV | RC | RT | Exclude<RW, Tx>
>;
Expand Down
Loading
Loading