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