@haddowg/json-api-client 1.25.0 → 1.27.0

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/dist/index.cjs CHANGED
@@ -1,106 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- //#region src/errors.ts
3
- /**
4
- * Thrown by the always-on light structural guards when a parsed response is not a
5
- * JSON:API document, or a `data`/`included` member is not a resource object carrying `type`+`id`.
6
- * Distinct from {@link JsonApiError} (a non-2xx server response): this signals the wire shape the
7
- * runtime relies on was violated, not an application error the server reported. The opt-in
8
- * per-field validator throws its engine's own error type, never this one.
9
- */
10
- var StructuralGuardError = class extends Error {
11
- constructor(message) {
12
- super(message);
13
- this.name = "StructuralGuardError";
14
- }
15
- };
16
- /**
17
- * Thrown for any non-2xx JSON:API response. Carries the parsed error document plus
18
- * expressive status matchers and pointer-grouping helpers.
19
- *
20
- * `C` types each error object's `code` (see {@link JsonApiErrorObject}). It is a compile-time
21
- * hint only: the runtime never checks a code against it.
22
- */
23
- var JsonApiError = class extends Error {
24
- status;
25
- errors;
26
- constructor(status, errors, message) {
27
- super(message ?? `JSON:API request failed with status ${status}`);
28
- this.name = "JsonApiError";
29
- this.status = status;
30
- this.errors = errors;
31
- }
32
- hasStatus(status) {
33
- return this.status === status;
34
- }
35
- is4xx() {
36
- return this.status >= 400 && this.status < 500;
37
- }
38
- is5xx() {
39
- return this.status >= 500 && this.status < 600;
40
- }
41
- isBadRequest() {
42
- return this.status === 400;
43
- }
44
- isUnauthorized() {
45
- return this.status === 401;
46
- }
47
- isForbidden() {
48
- return this.status === 403;
49
- }
50
- isNotFound() {
51
- return this.status === 404;
52
- }
53
- isNotAcceptable() {
54
- return this.status === 406;
55
- }
56
- isConflict() {
57
- return this.status === 409;
58
- }
59
- isUnsupportedMediaType() {
60
- return this.status === 415;
61
- }
62
- isUnprocessable() {
63
- return this.status === 422;
64
- }
65
- /** Alias of {@link isUnprocessable} — the JSON:API validation status. */
66
- isValidationError() {
67
- return this.status === 422;
68
- }
69
- isRateLimited() {
70
- return this.status === 429;
71
- }
72
- /**
73
- * Group errors by user-facing input path (falls back to the raw pointer, then the
74
- * query parameter). The payoff for form/validation UX — 422 `source.pointer`s are
75
- * remapped to the flat shape the caller actually supplied.
76
- */
77
- byPath() {
78
- const out = {};
79
- for (const e of this.errors) {
80
- const key = e.path ?? e.source?.pointer ?? e.source?.parameter ?? "_";
81
- (out[key] ??= []).push(e);
82
- }
83
- return out;
84
- }
85
- };
86
- /**
87
- * True when `err` is a {@link JsonApiError} and any of its error objects carries `code`. Takes
88
- * any string, so it also matches codes the server never documented. A generated client exports a
89
- * `hasErrorCode` bound to its server's `ErrorCode` union, which rejects a misspelt code at
90
- * compile time; reach for this one only to match an undocumented code.
91
- */
92
- function hasErrorCode(err, code) {
93
- return err instanceof JsonApiError && err.errors.some((e) => e.code === code);
94
- }
95
- /**
96
- * The first error object in `err` carrying `code`, or `undefined` when `err` is not a
97
- * {@link JsonApiError} or none of its errors carries it. Takes any string; a generated client
98
- * exports a `findError` bound to its documented codes and their `meta`, which types the result.
99
- */
100
- function findError(err, code) {
101
- return err instanceof JsonApiError ? err.errors.find((e) => e.code === code) : void 0;
102
- }
103
- //#endregion
2
+ const require_validate = require("./validate-DMRQn0XN.cjs");
104
3
  //#region src/types.ts
105
4
  /** The JSON:API media type. */
106
5
  const JSON_API_MEDIA_TYPE = "application/vnd.api+json";
@@ -272,7 +171,7 @@ async function send(ctx, req, responseType, seeOther = false) {
272
171
  if (ctx.headers && sendHeaders) mergeHeaders(headers, await ctx.headers());
273
172
  const res = await ctx.transport(transportReq);
274
173
  if (res.status >= 200 && res.status < 300 || seeOther && res.status === 303) return res;
275
- throw new JsonApiError(res.status, parseErrors(res.body));
174
+ throw new require_validate.JsonApiError(res.status, parseErrors(res.body));
276
175
  }
277
176
  /** Whether a raw body goes to the transport as is rather than through `JSON.stringify`. */
278
177
  function isRawBody(body) {
@@ -362,6 +261,10 @@ function toAccepted(target, res) {
362
261
  value: true,
363
262
  enumerable: false
364
263
  });
264
+ Object.defineProperty(value, "meta", {
265
+ value: res.document?.meta,
266
+ enumerable: false
267
+ });
365
268
  Object.defineProperty(value, "$poll", {
366
269
  value: (options) => poll(target, contentLocation, metaJob, retryAfter, options),
367
270
  enumerable: false
@@ -464,82 +367,6 @@ function resolvePaginator(paginator, page) {
464
367
  };
465
368
  }
466
369
  //#endregion
467
- //#region src/validate.ts
468
- /** Whether a `validate` option is the schema-driven config (vs a bare validator function). */
469
- function isConfig(option) {
470
- return typeof option === "object" && option !== null && !Array.isArray(option);
471
- }
472
- /**
473
- * Normalise the `validate?` option to a single per-resource validator. The config form looks the
474
- * schema up by `resource.type` and skips a type with no schema (the seam stays graceful for a
475
- * partially-covered bundle); the bare-function form calls the validator with `schema = undefined`,
476
- * delegating the whole decision to the caller. Returns `undefined` when validation is off.
477
- */
478
- function resolveValidator(option) {
479
- if (option === void 0) return;
480
- if (isConfig(option)) {
481
- const { schemas, validator } = option;
482
- return { validate(resource) {
483
- const schema = schemas[resource.type];
484
- if (schema !== void 0) validator(resource, schema);
485
- } };
486
- }
487
- return { validate(resource) {
488
- option(resource, void 0);
489
- } };
490
- }
491
- const isObject$3 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
492
- /**
493
- * The light structural guards every parsed response passes through (ADR 0004): assert the body
494
- * is a JSON:API document and that each `data`/`included` member carries a string `type` (and,
495
- * for a full resource, an `id`). This is the always-on, engine-free floor — it never duplicates
496
- * the opt-in per-field validation; it only proves the envelope invariant the runtime relies on.
497
- *
498
- * A primary-`data` resource and every `included` resource must carry `type`+`id`. A relationship
499
- * endpoint's primary data is pure resource-identifier linkage, which also carries `type`+`id`, so
500
- * the same guard holds; `linkage` is accepted for symmetry with the materialiser but the assertion
501
- * is identical (an identifier is `type`+`id`). `data: null` (an empty to-one) and a missing
502
- * `data` (a meta-only document) are valid and pass.
503
- */
504
- function assertJsonApiDocument(body) {
505
- if (!isObject$3(body)) throw new StructuralGuardError("Response body is not a JSON:API document (expected an object)");
506
- if (!("data" in body) && !("meta" in body)) throw new StructuralGuardError("Response body is not a JSON:API document (missing top-level \"data\" or \"meta\")");
507
- const data = body["data"];
508
- if (Array.isArray(data)) data.forEach((member, i) => assertResource(member, `data[${i}]`));
509
- else if (data !== null && data !== void 0) assertResource(data, "data");
510
- const included = body["included"];
511
- if (included !== void 0) {
512
- if (!Array.isArray(included)) throw new StructuralGuardError("Response \"included\" is not an array");
513
- included.forEach((member, i) => assertResource(member, `included[${i}]`));
514
- }
515
- }
516
- /** Assert a single member is a resource object/identifier carrying string `type` + `id`. */
517
- function assertResource(member, at) {
518
- if (!isObject$3(member)) throw new StructuralGuardError(`${at} is not a JSON:API resource object`);
519
- if (typeof member["type"] !== "string") throw new StructuralGuardError(`${at} is missing a string "type"`);
520
- if (typeof member["id"] !== "string") throw new StructuralGuardError(`${at} (type "${member["type"]}") is missing a string "id"`);
521
- }
522
- /**
523
- * Run the opt-in validator over every wire resource in a document's `data` + `included`, each
524
- * against its per-type schema. Called only when a validator is configured (off by default). The
525
- * structural guards have already proven each member carries `type`+`id`, so the cast is sound.
526
- */
527
- function validateDocument(body, validator) {
528
- const data = body.data;
529
- if (Array.isArray(data)) for (const member of data) validateResourceMember(member, validator);
530
- else if (data !== null && data !== void 0) validateResourceMember(data, validator);
531
- if (body.included !== void 0) for (const member of body.included) validator.validate(member);
532
- }
533
- /**
534
- * Validate a `data` member, but only when it is a full RESOURCE OBJECT. A relationship-linkage
535
- * endpoint's `data` is bare resource IDENTIFIERS (`type`+`id`[+`meta`], no `attributes`/
536
- * `relationships`); the per-type schema describes the resource object, so running it over an
537
- * identifier would spuriously fail. The structural guard already covered the identifier shape.
538
- */
539
- function validateResourceMember(member, validator) {
540
- if (isObject$3(member) && ("attributes" in member || "relationships" in member)) validator.validate(member);
541
- }
542
- //#endregion
543
370
  //#region src/materialise.ts
544
371
  const isObject$2 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
545
372
  const define = (target, key, value) => {
@@ -587,8 +414,8 @@ const relationTotal = (rel) => {
587
414
  * top-level collection read (statically-known); both override the sniff-from-`data[0]` fallback.
588
415
  */
589
416
  function materialise(doc, ctx, linkage = false, primaryType, paginatorOverride) {
590
- assertJsonApiDocument(doc);
591
- if (ctx.validate !== void 0) validateDocument(doc, ctx.validate);
417
+ require_validate.assertJsonApiDocument(doc);
418
+ if (ctx.validate !== void 0) require_validate.validateDocument(doc, ctx.validate, ctx.fields);
592
419
  const env = {};
593
420
  if (doc.jsonapi !== void 0) env.jsonapi = doc.jsonapi;
594
421
  if (doc.meta !== void 0) env.meta = doc.meta;
@@ -638,7 +465,7 @@ function buildNode(raw, env, index, nodes, ctx) {
638
465
  const relDesc = resType?.relations[name];
639
466
  node[name] = hydrateRelation(rel, relDesc?.cardinality, resolvePaginator(relatedPaginator(relDesc, ctx)), env, index, nodes, ctx);
640
467
  }
641
- attachResourceEnvelope(node, raw, env, rels);
468
+ attachResourceEnvelope(node, raw, env, rels, require_validate.nestedFieldset(ctx.fields?.[raw.type]));
642
469
  return node;
643
470
  }
644
471
  /**
@@ -668,13 +495,14 @@ function resolveMember(member, env, index, nodes, ctx, relationEdge) {
668
495
  if (included) return buildEdgeView(buildNode(included, env, index, nodes, ctx), member, relationEdge);
669
496
  return buildIdentifierView(member, relationEdge);
670
497
  }
671
- /** Attach the resource-level `$`-accessors ($meta/$links/$self/$document/$raw/$rel/$count). */
672
- function attachResourceEnvelope(node, raw, env, rels) {
498
+ /** Attach the resource-level `$`-accessors ($meta/$links/$self/$document/$raw/$nestedFieldset/$rel/$count). */
499
+ function attachResourceEnvelope(node, raw, env, rels, selection) {
673
500
  defineGetter(node, "$meta", () => raw.meta);
674
501
  defineGetter(node, "$links", () => raw.links);
675
502
  defineGetter(node, "$self", () => linkHref(raw.links?.self));
676
503
  defineGetter(node, "$document", () => env);
677
504
  defineGetter(node, "$raw", () => raw);
505
+ defineGetter(node, "$nestedFieldset", () => selection);
678
506
  define(node, "$rel", (name) => {
679
507
  const rel = rels[name];
680
508
  if (!rel) return void 0;
@@ -703,6 +531,7 @@ function buildEdgeView(node, member, relationEdge) {
703
531
  "$self",
704
532
  "$document",
705
533
  "$raw",
534
+ "$nestedFieldset",
706
535
  "$rel",
707
536
  "$count"
708
537
  ]) delegate(view, node, k);
@@ -870,6 +699,17 @@ function relatedPaginatorKind(relation, ctx) {
870
699
  //#region src/serialize-write.ts
871
700
  /** Per-edge writable pivot data, supplied on a to-many member as the `$pivot` key. */
872
701
  const PIVOT_KEY = "$pivot";
702
+ /** The resource object's own `meta`, supplied in a write input as the `$meta` key. */
703
+ const META_KEY = "$meta";
704
+ /**
705
+ * The key an error on the request document's top-level `meta`, sent as a write's `meta` option, is
706
+ * grouped under: `$meta` names the resource object's, so the document's is `$documentMeta`.
707
+ */
708
+ const DOCUMENT_META_KEY = "$documentMeta";
709
+ /** The flat path of a pointer into the request document's top-level `meta`, else `undefined`. */
710
+ function documentMetaPath(segments) {
711
+ return segments[0] === "meta" ? [DOCUMENT_META_KEY, ...segments.slice(1)].join(".") : void 0;
712
+ }
873
713
  /** The reserved input keys never routed to attributes/relationships. */
874
714
  const RESERVED_INPUT = /* @__PURE__ */ new Set(["type", "id"]);
875
715
  const isObject$1 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
@@ -885,7 +725,8 @@ const isObject$1 = (v) => typeof v === "object" && v !== null && !Array.isArray(
885
725
  *
886
726
  * `data.type` is always the accessor `type`. `data.id` is written from `opts.id` (an update),
887
727
  * else from `input.id` only when the type's `clientId` policy allows it (omitted when
888
- * `forbidden`, passed through when `optional`/`required`).
728
+ * `forbidden`, passed through when `optional`/`required`). A `$meta` object is the resource
729
+ * object's `meta`.
889
730
  */
890
731
  function toDocument(descriptor, type, input, opts) {
891
732
  const resource = descriptor[type];
@@ -897,6 +738,10 @@ function toDocument(descriptor, type, input, opts) {
897
738
  const relationships = {};
898
739
  for (const [keyName, value] of Object.entries(input)) {
899
740
  if (RESERVED_INPUT.has(keyName)) continue;
741
+ if (keyName === META_KEY) {
742
+ if (isObject$1(value)) data.meta = value;
743
+ continue;
744
+ }
900
745
  const relation = relations[keyName];
901
746
  if (relation !== void 0) relationships[keyName] = { data: coerceLinkage(value, relation.cardinality) };
902
747
  else attributes[keyName] = value;
@@ -906,6 +751,16 @@ function toDocument(descriptor, type, input, opts) {
906
751
  return { data };
907
752
  }
908
753
  /**
754
+ * A write document with the top-level `meta` a call's options carry, or the document as it is
755
+ * when they carry none.
756
+ */
757
+ function withTopLevelMeta(doc, meta) {
758
+ return meta === void 0 ? doc : {
759
+ ...doc,
760
+ meta
761
+ };
762
+ }
763
+ /**
909
764
  * Build a relationship-mutation document `{ data: <linkage> }` for the
910
765
  * `/{type}/{id}/relationships/{rel}` endpoints, coercing the caller's refs by cardinality:
911
766
  *
@@ -966,6 +821,8 @@ const describe = (value) => value === null ? "null" : Array.isArray(value) ? "an
966
821
  * - `/data/id` -> `id` (client-id create conflict)
967
822
  * - `/data/attributes/releaseInfo/label` -> `releaseInfo.label` (nested map)
968
823
  * - `/data/relationships/orderedTracks/data/0/meta/pivot/position` -> `orderedTracks[0].$pivot.position`
824
+ * - `/data/meta/source` -> `$meta.source`
825
+ * - `/meta/idempotencyKey` -> `$documentMeta.idempotencyKey`
969
826
  *
970
827
  * Pivot values nest under a member's `meta.pivot` (symmetric with reads — see
971
828
  * `JsonPointerBuilder::forLinkageMeta`), so a `meta/pivot/<field>` tail on
@@ -978,7 +835,8 @@ const describe = (value) => value === null ? "null" : Array.isArray(value) ? "an
978
835
  */
979
836
  function remapPointer(descriptor, type, pointer) {
980
837
  const segments = pointer.split("/").filter((s) => s !== "");
981
- if (segments[0] !== "data") return pointer;
838
+ if (segments[0] !== "data") return documentMetaPath(segments) ?? pointer;
839
+ if (segments[1] === "meta") return [META_KEY, ...segments.slice(2)].join(".");
982
840
  if (segments[1] === "attributes") return remapAttribute(segments.slice(2));
983
841
  if (segments[1] === "id") return "id";
984
842
  if (segments[1] === "relationships") return remapRelationship(descriptor[type]?.relations ?? {}, segments.slice(2));
@@ -1027,11 +885,12 @@ function remapRelationship(relations, rest) {
1027
885
  * to the relation name (drop the `relationships/<name>` prefix) rather than treating
1028
886
  * `relationships` as a linkage sub-segment.
1029
887
  *
1030
- * A non-`data` pointer is returned verbatim.
888
+ * A pointer into the top-level `meta` becomes `$documentMeta.<member>`, and any other non-`data`
889
+ * pointer is returned verbatim.
1031
890
  */
1032
891
  function remapRelationshipPointer(rel, hasPivot, pointer) {
1033
892
  const segments = pointer.split("/").filter((s) => s !== "");
1034
- if (segments[0] !== "data") return pointer;
893
+ if (segments[0] !== "data") return documentMetaPath(segments) ?? pointer;
1035
894
  const tail = segments[1] === "relationships" ? segments.slice(3) : segments.slice(1);
1036
895
  return remapRelationship({ [rel]: { pivot: hasPivot } }, [rel, ...tail]);
1037
896
  }
@@ -1055,25 +914,44 @@ function withRemappedRelationshipPaths(error, rel, hasPivot) {
1055
914
  return mapErrors(error, (pointer) => ({ path: remapRelationshipPointer(rel, hasPivot, pointer) }));
1056
915
  }
1057
916
  /**
917
+ * Give each error on the request document's top-level `meta` its `$documentMeta.<member>` path,
918
+ * for a request whose other members the client didn't build, such as a bespoke action document or
919
+ * a meta-only one. Every other error is passed through unchanged. The original error is not
920
+ * mutated.
921
+ */
922
+ function withRemappedDocumentMetaPaths(error) {
923
+ const remapped = error.errors.map((e) => {
924
+ const path = e.source?.pointer === void 0 ? void 0 : documentMetaPath(e.source.pointer.split("/").filter((s) => s !== ""));
925
+ return path === void 0 ? e : {
926
+ ...e,
927
+ path
928
+ };
929
+ });
930
+ return new require_validate.JsonApiError(error.status, remapped, error.message);
931
+ }
932
+ /**
1058
933
  * Invert an atomic-batch error's `source.pointer` to `(opIndex, flatPath)`: an atomic 422
1059
934
  * points at `/atomic:operations/{n}/data/...`, so strip the `atomic:operations/{n}` prefix to
1060
935
  * the op index, resolve that op's wire type (`typeForOp`), and delegate the remaining `/data`
1061
936
  * tail to the same {@link remapPointer} a standalone write uses (so the flat path is identical
1062
- * — `title`, `releaseInfo.label`, `artist`, …). A pointer without the atomic prefix is remapped
937
+ * — `title`, `releaseInfo.label`, `artist`, …). A relationship op's tail is remapped under its
938
+ * relation, as a standalone relationship write's is, when `relationForOp` names one. A pointer
939
+ * without the atomic prefix is remapped
1063
940
  * verbatim under the (whole-batch) document at op index `undefined`. The original error is not
1064
941
  * mutated.
1065
942
  */
1066
- function withRemappedAtomicPaths(error, descriptor, typeForOp) {
943
+ function withRemappedAtomicPaths(error, descriptor, typeForOp, relationForOp) {
1067
944
  return mapErrors(error, (pointer) => {
1068
945
  const segments = pointer.split("/").filter((s) => s !== "");
1069
946
  if (segments[0] !== "atomic:operations" || segments[1] === void 0) return { path: pointer };
1070
947
  const opIndex = Number(segments[1]);
1071
948
  if (!Number.isInteger(opIndex)) return { path: pointer };
1072
949
  const type = typeForOp(opIndex);
950
+ const relation = relationForOp?.(opIndex);
1073
951
  const tail = `/${segments.slice(2).join("/")}`;
1074
952
  return {
1075
953
  opIndex,
1076
- path: type === void 0 ? tail : remapPointer(descriptor, type, tail)
954
+ path: relation !== void 0 ? remapRelationshipPointer(relation.rel, relation.hasPivot, tail) : type === void 0 ? tail : remapPointer(descriptor, type, tail)
1077
955
  };
1078
956
  });
1079
957
  }
@@ -1092,10 +970,22 @@ function mapErrors(error, remap) {
1092
970
  opIndex
1093
971
  };
1094
972
  });
1095
- return new JsonApiError(error.status, remapped, error.message);
973
+ return new require_validate.JsonApiError(error.status, remapped, error.message);
1096
974
  }
1097
975
  //#endregion
1098
976
  //#region src/atomic.ts
977
+ /** The wire `op` each relationship verb records: `replace` and `set` both update the relationship. */
978
+ const RELATIONSHIP_OPS = {
979
+ add: "add",
980
+ remove: "remove",
981
+ replace: "update",
982
+ set: "update"
983
+ };
984
+ /** An operation with its `meta` added when the caller sent any. */
985
+ const withOperationMeta = (operation, opts) => opts?.meta === void 0 ? operation : {
986
+ ...operation,
987
+ meta: opts.meta
988
+ };
1099
989
  const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
1100
990
  /** The deterministic local id for the create at `opIndex` (stable + human-readable). */
1101
991
  const lidFor = (opIndex) => `atomic-${opIndex}`;
@@ -1103,15 +993,41 @@ async function runAtomic(request, materialiseCtx, descriptor, path, build) {
1103
993
  const operations = [];
1104
994
  /** The wire type of each op, by index — drives the error-pointer remap. */
1105
995
  const typeByOp = [];
996
+ /** The relation each relationship op writes, by index, which its pointers are remapped under. */
997
+ const relationByOp = /* @__PURE__ */ new Map();
998
+ const relationship = (verb, { type, identity }, name, members, opts) => {
999
+ const opIndex = operations.length;
1000
+ const { data } = toRelationshipDocument(members, verb === "set" ? "one" : "many");
1001
+ operations.push(withOperationMeta({
1002
+ op: RELATIONSHIP_OPS[verb],
1003
+ ref: {
1004
+ type,
1005
+ ...identity,
1006
+ relationship: name
1007
+ },
1008
+ data
1009
+ }, opts));
1010
+ typeByOp.push(type);
1011
+ relationByOp.set(opIndex, {
1012
+ rel: name,
1013
+ hasPivot: descriptor[type]?.relations[name]?.pivot === true
1014
+ });
1015
+ return {
1016
+ type,
1017
+ relationship: name,
1018
+ kind: "relationship",
1019
+ opIndex
1020
+ };
1021
+ };
1106
1022
  const returned = build({
1107
- create(input) {
1023
+ create(input, ...[opts]) {
1108
1024
  const opIndex = operations.length;
1109
1025
  const lid = lidFor(opIndex);
1110
1026
  const data = atomicResourceData(descriptor, input, { lid });
1111
- operations.push({
1027
+ operations.push(withOperationMeta({
1112
1028
  op: "add",
1113
1029
  data
1114
- });
1030
+ }, opts));
1115
1031
  typeByOp.push(input.type);
1116
1032
  return {
1117
1033
  type: input.type,
@@ -1120,18 +1036,18 @@ async function runAtomic(request, materialiseCtx, descriptor, path, build) {
1120
1036
  opIndex
1121
1037
  };
1122
1038
  },
1123
- update(input) {
1039
+ update(input, ...[opts]) {
1124
1040
  const opIndex = operations.length;
1125
1041
  const identity = input.id !== void 0 ? { id: input.id } : { lid: input.lid };
1126
1042
  const data = atomicResourceData(descriptor, input, identity);
1127
- operations.push({
1043
+ operations.push(withOperationMeta({
1128
1044
  op: "update",
1129
1045
  ref: {
1130
1046
  type: input.type,
1131
1047
  ...identity
1132
1048
  },
1133
1049
  data
1134
- });
1050
+ }, opts));
1135
1051
  typeByOp.push(input.type);
1136
1052
  return {
1137
1053
  type: input.type,
@@ -1139,21 +1055,32 @@ async function runAtomic(request, materialiseCtx, descriptor, path, build) {
1139
1055
  opIndex
1140
1056
  };
1141
1057
  },
1142
- delete(ref) {
1058
+ delete(ref, ...[opts]) {
1143
1059
  const opIndex = operations.length;
1144
- const { type, identity } = toRef(ref);
1145
- operations.push({
1060
+ const { type, identity } = toRef(ref, "atomic delete");
1061
+ operations.push(withOperationMeta({
1146
1062
  op: "remove",
1147
1063
  ref: {
1148
1064
  type,
1149
1065
  ...identity
1150
1066
  }
1151
- });
1067
+ }, opts));
1152
1068
  typeByOp.push(type);
1153
1069
  return {
1154
1070
  kind: "delete",
1155
1071
  opIndex
1156
1072
  };
1073
+ },
1074
+ rel(ref, name) {
1075
+ const target = toRef(ref, "atomic rel");
1076
+ if (typeof name !== "string") throw new TypeError("atomic rel requires a relationship name");
1077
+ const verb = (v) => (members, ...[opts]) => relationship(v, target, name, members, opts);
1078
+ return {
1079
+ add: verb("add"),
1080
+ remove: verb("remove"),
1081
+ replace: verb("replace"),
1082
+ set: verb("set")
1083
+ };
1157
1084
  }
1158
1085
  });
1159
1086
  const req = {
@@ -1166,10 +1093,10 @@ async function runAtomic(request, materialiseCtx, descriptor, path, build) {
1166
1093
  try {
1167
1094
  doc = await execute(request, req);
1168
1095
  } catch (error) {
1169
- if (error instanceof JsonApiError) throw withRemappedAtomicPaths(error, descriptor, (opIndex) => typeByOp[opIndex]);
1096
+ if (error instanceof require_validate.JsonApiError) throw withRemappedAtomicPaths(error, descriptor, (opIndex) => typeByOp[opIndex], (opIndex) => relationByOp.get(opIndex));
1170
1097
  throw error;
1171
1098
  }
1172
- const results = parseResults(doc, materialiseCtx);
1099
+ const results = parseResults(doc, materialiseCtx, (opIndex) => relationByOp.has(opIndex));
1173
1100
  if (!(Array.isArray(returned) && returned.every((h) => h !== null && typeof h === "object" && "opIndex" in h))) return results;
1174
1101
  return returned.map((handle) => handle.kind === "delete" ? void 0 : results[handle.opIndex]);
1175
1102
  }
@@ -1191,13 +1118,14 @@ function atomicResourceData(descriptor, input, identity) {
1191
1118
  return out;
1192
1119
  }
1193
1120
  /**
1194
- * Coerce a remove ref (an identifier, a materialised resource, or a same-batch `{type,lid}`
1121
+ * Coerce an op's target ref (an identifier, a materialised resource, or a same-batch `{type,lid}`
1195
1122
  * handle) to `{ type, identity }` — `identity` an `id` or a `lid`; throws if neither is present.
1123
+ * `what` names the operation in the error.
1196
1124
  */
1197
- function toRef(ref) {
1198
- if (!isObject(ref)) throw new TypeError("atomic delete requires an identifier `{ type, id }` or `{ type, lid }`");
1125
+ function toRef(ref, what) {
1126
+ if (!isObject(ref)) throw new TypeError(`${what} requires an identifier \`{ type, id }\` or \`{ type, lid }\``);
1199
1127
  const { type, id, lid } = ref;
1200
- if (typeof type !== "string") throw new TypeError("atomic delete requires a `type`");
1128
+ if (typeof type !== "string") throw new TypeError(`${what} requires a \`type\``);
1201
1129
  if (typeof id === "string") return {
1202
1130
  type,
1203
1131
  identity: { id }
@@ -1206,15 +1134,19 @@ function toRef(ref) {
1206
1134
  type,
1207
1135
  identity: { lid }
1208
1136
  };
1209
- throw new TypeError("atomic delete requires an `id` or a `lid`");
1137
+ throw new TypeError(`${what} requires an \`id\` or a \`lid\``);
1210
1138
  }
1211
- /** Parse `{ "atomic:results": [...] }` positionally, materialising each result's `data`. An absent results array (an all-`204` batch) yields `[]`. */
1212
- function parseResults(doc, ctx) {
1139
+ /**
1140
+ * Parse `{ "atomic:results": [...] }` positionally, materialising each result's `data`: a
1141
+ * relationship op's as linkage, any other's as a resource. An absent results array (an all-`204`
1142
+ * batch) yields `[]`.
1143
+ */
1144
+ function parseResults(doc, ctx, isLinkage) {
1213
1145
  const results = doc?.["atomic:results"];
1214
1146
  if (!Array.isArray(results)) return [];
1215
- return results.map((result) => {
1147
+ return results.map((result, opIndex) => {
1216
1148
  const entry = isObject(result) ? result : {};
1217
- const out = { data: entry["data"] === void 0 ? void 0 : materialise({ data: entry["data"] }, ctx) };
1149
+ const out = { data: entry["data"] === void 0 ? void 0 : materialise({ data: entry["data"] }, ctx, isLinkage(opIndex)) };
1218
1150
  if (isObject(entry["meta"])) out.meta = entry["meta"];
1219
1151
  return out;
1220
1152
  });
@@ -1372,7 +1304,14 @@ async function run(ctx, type, operation, vars, query, linkage = false, relationF
1372
1304
  const paginator = operation === "fetchMany" ? ctx.descriptor[type]?.paginator : relation !== void 0 ? relatedPaginator(relation, ctx.materialise) : void 0;
1373
1305
  const primaryType = operation === "fetchMany" ? type : void 0;
1374
1306
  const paginatorOverride = paginator === void 0 ? void 0 : resolvePaginator(paginator, query?.page);
1375
- return doc === void 0 ? void 0 : materialise(doc, ctx.materialise, linkage, primaryType, paginatorOverride);
1307
+ return doc === void 0 ? void 0 : materialise(doc, withFields(ctx.materialise, query?.fields), linkage, primaryType, paginatorOverride);
1308
+ }
1309
+ /** The materialise context for a response to a request that sent `fields`. */
1310
+ function withFields(ctx, fields) {
1311
+ return fields === void 0 ? ctx : {
1312
+ ...ctx,
1313
+ fields
1314
+ };
1376
1315
  }
1377
1316
  /**
1378
1317
  * The filter vocabulary a read's `filter` is matched against: the type's for its collection read.
@@ -1496,10 +1435,10 @@ async function runWrite(ctx, spec) {
1496
1435
  try {
1497
1436
  res = await executeResponse(ctx.request, req);
1498
1437
  } catch (error) {
1499
- if (error instanceof JsonApiError) throw spec.remap(error);
1438
+ if (error instanceof require_validate.JsonApiError) throw spec.remap(error);
1500
1439
  throw error;
1501
1440
  }
1502
- const complete = (doc) => doc === void 0 ? void 0 : materialise(doc, ctx.materialise, spec.linkage ?? false);
1441
+ const complete = (doc) => doc === void 0 ? void 0 : spec.metaOnly === true && !("data" in doc) ? doc.meta : materialise(doc, withFields(ctx.materialise, spec.query?.fields), spec.linkage ?? false);
1503
1442
  if (res.status === 202 && spec.accepted !== void 0) return answerAccepted(ctx, spec.accepted, res, complete, spec.wait);
1504
1443
  return complete(res.document);
1505
1444
  }
@@ -1520,7 +1459,8 @@ async function runWrite(ctx, spec) {
1520
1459
  *
1521
1460
  * The response is shaped by the action's `output`: `document` materialises into the resource /
1522
1461
  * collection view, `meta` returns the document's top-level `meta`, `none` resolves `undefined` (a
1523
- * `204` / no body). An action declaring a `location` returns the URL of a location document as an
1462
+ * `204` / no body). A `metaResult` action returns the top-level `meta` of a document with no
1463
+ * `data`. An action declaring a `location` returns the URL of a location document as an
1524
1464
  * `ActionLocation` and never follows it. An action declaring `rawOutput` answers in the media type
1525
1465
  * the caller picks with `options.accept`: JSON:API as above, or a `string`, a `Blob` or
1526
1466
  * `ArrayBuffer`, or parsed JSON by the media type's kind. A collection action that takes filters
@@ -1554,10 +1494,17 @@ async function runAction(ctx, action, vars, input, options = {}) {
1554
1494
  req.contentType = sentContentType(media.mediaType, media.kind, req.body);
1555
1495
  } else if (action.input === "document") if (action.inputType !== void 0) {
1556
1496
  const inputType = action.inputType;
1557
- req.body = toDocument(ctx.descriptor, inputType, input ?? {});
1497
+ req.body = withTopLevelMeta(toDocument(ctx.descriptor, inputType, input ?? {}), options.meta);
1558
1498
  remap = (error) => withRemappedPaths(error, ctx.descriptor, inputType);
1559
- } else req.body = input;
1560
- else if (action.input === "raw") {
1499
+ } else {
1500
+ req.body = typeof input === "object" && input !== null ? withTopLevelMeta(input, options.meta) : input;
1501
+ remap = withRemappedDocumentMetaPaths;
1502
+ }
1503
+ else if (action.input === "none" && options.meta !== void 0) {
1504
+ req.body = { meta: options.meta };
1505
+ req.contentType = JSON_API_MEDIA_TYPE;
1506
+ remap = withRemappedDocumentMetaPaths;
1507
+ } else if (action.input === "raw") {
1561
1508
  req.body = encodeFields(action.contentType ?? "*/*", void 0, input);
1562
1509
  req.contentType = sentContentType(action.contentType ?? "*/*", void 0, req.body);
1563
1510
  req.raw = true;
@@ -1583,7 +1530,7 @@ async function runAction(ctx, action, vars, input, options = {}) {
1583
1530
  }
1584
1531
  return complete(res.document);
1585
1532
  } catch (error) {
1586
- if (remap !== void 0 && error instanceof JsonApiError) throw remap(error);
1533
+ if (remap !== void 0 && error instanceof require_validate.JsonApiError) throw remap(error);
1587
1534
  throw error;
1588
1535
  }
1589
1536
  }
@@ -1595,7 +1542,7 @@ function actionValue(ctx, action, doc) {
1595
1542
  if (action.output === "location") throw new Error("The action answered without the location document it declares.");
1596
1543
  }
1597
1544
  if (action.output === "none" || action.output === "location" || doc === void 0) return;
1598
- if (action.output === "meta") return doc.meta;
1545
+ if (action.output === "meta" || action.metaResult === true && !("data" in doc)) return doc.meta;
1599
1546
  return materialise(doc, ctx.materialise);
1600
1547
  }
1601
1548
  /**
@@ -1720,14 +1667,15 @@ function relationshipAccessor(ctx, type, owner, rel) {
1720
1667
  const relation = ctx.descriptor[type]?.relations[rel];
1721
1668
  const cardinality = relation?.cardinality ?? "many";
1722
1669
  const hasPivot = relation?.pivot === true;
1723
- const mutate = (method, refs) => runWrite(ctx, {
1670
+ const mutate = (verb, method, refs, opts) => runWrite(ctx, {
1724
1671
  type,
1725
1672
  operation: "fetchRelationship",
1726
1673
  vars,
1727
1674
  method,
1728
- body: toRelationshipDocument(refs, cardinality),
1675
+ body: withTopLevelMeta(toRelationshipDocument(refs, cardinality), opts?.meta),
1729
1676
  linkage: true,
1730
- remap: (error) => withRemappedRelationshipPaths(error, rel, hasPivot)
1677
+ remap: (error) => withRemappedRelationshipPaths(error, rel, hasPivot),
1678
+ metaOnly: relation?.mutationMeta?.[verb] !== void 0
1731
1679
  });
1732
1680
  const advertises = (verb) => {
1733
1681
  const mutations = relation?.mutations;
@@ -1738,10 +1686,10 @@ function relationshipAccessor(ctx, type, owner, rel) {
1738
1686
  if (readable && relation?.relationship !== false) accessor["get"] = (query) => run(ctx, type, "fetchRelationship", vars, query, true, rel);
1739
1687
  if (readable && relation?.related !== false) accessor["related"] = (query) => run(ctx, type, "fetchRelated", vars, query, false, rel);
1740
1688
  if (cardinality === "many") {
1741
- if (advertises("add")) accessor["add"] = (refs) => mutate("POST", refs);
1742
- if (advertises("remove")) accessor["remove"] = (refs) => mutate("DELETE", refs);
1743
- if (advertises("replace")) accessor["replace"] = (refs) => mutate("PATCH", refs);
1744
- } else if (advertises("set")) accessor["set"] = (ref) => mutate("PATCH", ref);
1689
+ if (advertises("add")) accessor["add"] = (refs, opts) => mutate("add", "POST", refs, opts);
1690
+ if (advertises("remove")) accessor["remove"] = (refs, opts) => mutate("remove", "DELETE", refs, opts);
1691
+ if (advertises("replace")) accessor["replace"] = (refs, opts) => mutate("replace", "PATCH", refs, opts);
1692
+ } else if (advertises("set")) accessor["set"] = (ref, opts) => mutate("set", "PATCH", ref, opts);
1745
1693
  return accessor;
1746
1694
  }
1747
1695
  /**
@@ -1770,7 +1718,7 @@ function runUpdate(ctx, type, vars, id, patch, opts) {
1770
1718
  operation: "update",
1771
1719
  vars,
1772
1720
  method: "PATCH",
1773
- body: toDocument(ctx.descriptor, type, patch, { id }),
1721
+ body: withTopLevelMeta(toDocument(ctx.descriptor, type, patch, { id }), opts?.meta),
1774
1722
  query: writeQuery(opts),
1775
1723
  remap: (error) => withRemappedPaths(error, ctx.descriptor, type),
1776
1724
  accepted: ctx.descriptor[type]?.accepted?.update,
@@ -1796,13 +1744,14 @@ function resourceHandle(ctx, type, id) {
1796
1744
  id,
1797
1745
  get: (query) => run(ctx, type, "fetchOne", vars, query),
1798
1746
  update: (patch, opts) => runUpdate(ctx, type, vars, id, patch, opts),
1799
- delete: () => runWrite(ctx, {
1747
+ delete: (opts) => runWrite(ctx, {
1800
1748
  type,
1801
1749
  operation: "delete",
1802
1750
  vars,
1803
1751
  method: "DELETE",
1804
- body: void 0,
1805
- remap: (error) => withRemappedPaths(error, ctx.descriptor, type)
1752
+ body: opts?.meta === void 0 ? void 0 : { meta: opts.meta },
1753
+ remap: (error) => withRemappedPaths(error, ctx.descriptor, type),
1754
+ metaOnly: ctx.descriptor[type]?.documentMeta?.delete !== void 0
1806
1755
  }),
1807
1756
  rel: (name) => relationshipAccessor(ctx, type, vars, name),
1808
1757
  actions: actionsAccessor(ctx, type, "resource", vars)
@@ -1837,7 +1786,7 @@ function typeAccessor(ctx, type) {
1837
1786
  operation: "create",
1838
1787
  vars: {},
1839
1788
  method: "POST",
1840
- body: toDocument(ctx.descriptor, type, input),
1789
+ body: withTopLevelMeta(toDocument(ctx.descriptor, type, input), opts?.meta),
1841
1790
  query: writeQuery(opts),
1842
1791
  remap: (error) => withRemappedPaths(error, ctx.descriptor, type),
1843
1792
  accepted: ctx.descriptor[type]?.accepted?.create,
@@ -1862,7 +1811,7 @@ function createClient(descriptor, options) {
1862
1811
  ...options.headers !== void 0 ? { headers: options.headers } : {},
1863
1812
  ...options.allowCrossOriginLinks !== void 0 ? { allowCrossOriginLinks: options.allowCrossOriginLinks } : {}
1864
1813
  };
1865
- const validator = resolveValidator(options.validate);
1814
+ const validator = require_validate.resolveValidator(options.validate);
1866
1815
  const ctx = {
1867
1816
  request,
1868
1817
  descriptor,
@@ -1875,7 +1824,7 @@ function createClient(descriptor, options) {
1875
1824
  link: true,
1876
1825
  ...signal !== void 0 ? { signal } : {}
1877
1826
  });
1878
- return doc === void 0 ? void 0 : materialise(doc, ctx.materialise, linkage, void 0, paginator);
1827
+ return doc === void 0 ? void 0 : materialise(doc, withFields(ctx.materialise, require_validate.fieldsOfUrl(url)), linkage, void 0, paginator);
1879
1828
  },
1880
1829
  ...validator !== void 0 ? { validate: validator } : {}
1881
1830
  }
@@ -1934,17 +1883,17 @@ exports.ATOMIC_MEDIA_TYPE = ATOMIC_MEDIA_TYPE;
1934
1883
  exports.CANONICAL_PAGE_KEYS = CANONICAL_PAGE_KEYS;
1935
1884
  exports.HANDLE_RESERVED = HANDLE_RESERVED;
1936
1885
  exports.JSON_API_MEDIA_TYPE = JSON_API_MEDIA_TYPE;
1937
- exports.JsonApiError = JsonApiError;
1886
+ exports.JsonApiError = require_validate.JsonApiError;
1938
1887
  exports.PollTimeoutError = PollTimeoutError;
1939
- exports.StructuralGuardError = StructuralGuardError;
1940
- exports.assertJsonApiDocument = assertJsonApiDocument;
1888
+ exports.StructuralGuardError = require_validate.StructuralGuardError;
1889
+ exports.assertJsonApiDocument = require_validate.assertJsonApiDocument;
1941
1890
  exports.createClient = createClient;
1942
1891
  exports.execute = execute;
1943
1892
  exports.executeRaw = executeRaw;
1944
1893
  exports.executeResponse = executeResponse;
1945
1894
  exports.fetchTransport = fetchTransport;
1946
- exports.findError = findError;
1947
- exports.hasErrorCode = hasErrorCode;
1895
+ exports.findError = require_validate.findError;
1896
+ exports.hasErrorCode = require_validate.hasErrorCode;
1948
1897
  exports.isAccepted = isAccepted;
1949
1898
  exports.isActionLocation = isActionLocation;
1950
1899
  exports.isPolymorphic = isPolymorphic;
@@ -1952,6 +1901,7 @@ exports.listFilterMatcher = listFilterMatcher;
1952
1901
  exports.loadAll = loadAll;
1953
1902
  exports.materialise = materialise;
1954
1903
  exports.mediaType = mediaType;
1904
+ exports.nestedFieldset = require_validate.nestedFieldset;
1955
1905
  exports.parseRetryAfter = parseRetryAfter;
1956
1906
  exports.readActionLocation = readActionLocation;
1957
1907
  exports.relatedPaginator = relatedPaginator;
@@ -1959,12 +1909,16 @@ exports.relatedPaginatorKind = relatedPaginatorKind;
1959
1909
  exports.remapPointer = remapPointer;
1960
1910
  exports.remapRelationshipPointer = remapRelationshipPointer;
1961
1911
  exports.resolvePaginator = resolvePaginator;
1962
- exports.resolveValidator = resolveValidator;
1912
+ exports.resolveValidator = require_validate.resolveValidator;
1963
1913
  exports.runAtomic = runAtomic;
1964
1914
  exports.serializeQuery = serializeQuery;
1915
+ exports.sparseSchema = require_validate.sparseSchema;
1916
+ exports.sparseSchemas = require_validate.sparseSchemas;
1965
1917
  exports.toDocument = toDocument;
1966
1918
  exports.toRelationshipDocument = toRelationshipDocument;
1967
- exports.validateDocument = validateDocument;
1919
+ exports.validateDocument = require_validate.validateDocument;
1968
1920
  exports.withRemappedAtomicPaths = withRemappedAtomicPaths;
1921
+ exports.withRemappedDocumentMetaPaths = withRemappedDocumentMetaPaths;
1969
1922
  exports.withRemappedPaths = withRemappedPaths;
1970
1923
  exports.withRemappedRelationshipPaths = withRemappedRelationshipPaths;
1924
+ exports.withTopLevelMeta = withTopLevelMeta;