@haddowg/json-api-client 1.30.0 → 1.32.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/ajv.cjs CHANGED
@@ -1,5 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_validate = require("./validate-B2Dtn9dI.cjs");
2
+ const require_validate = require("./validate-B9cyfO3p.cjs");
3
3
  //#region src/ajv.ts
4
4
  /**
5
5
  * Thrown by the ajv adapter when a wire resource fails its per-type schema. Aggregates every
package/dist/ajv.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- import { n as SchemaMap, o as Validator } from "./validate-ugcQVpb0.cjs";
1
+ import { n as SchemaMap, o as Validator } from "./validate-DyNfTJ52.cjs";
2
2
  import { ValidateFunction } from "ajv";
3
3
 
4
4
  //#region src/ajv.d.ts
package/dist/ajv.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { n as SchemaMap, o as Validator } from "./validate-ugcQVpb0.mjs";
1
+ import { n as SchemaMap, o as Validator } from "./validate-DyNfTJ52.mjs";
2
2
  import { ValidateFunction } from "ajv";
3
3
 
4
4
  //#region src/ajv.d.ts
package/dist/ajv.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { r as sparseSchema } from "./validate-CtXB1MGk.mjs";
1
+ import { r as sparseSchema } from "./validate-BuPAPJMi.mjs";
2
2
  //#region src/ajv.ts
3
3
  /**
4
4
  * Thrown by the ajv adapter when a wire resource fails its per-type schema. Aggregates every
package/dist/index.cjs CHANGED
@@ -1,5 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_validate = require("./validate-B2Dtn9dI.cjs");
2
+ const require_validate = require("./validate-B9cyfO3p.cjs");
3
3
  //#region src/request-stamp.ts
4
4
  /**
5
5
  * Request stamps: when the request behind a result started, relative to every other request made in
@@ -596,7 +596,7 @@ function materialiseDocument(doc, ctx, linkage, primaryType, paginatorOverride)
596
596
  if (doc.jsonapi !== void 0) env.jsonapi = doc.jsonapi;
597
597
  if (doc.meta !== void 0) env.meta = doc.meta;
598
598
  if (doc.links !== void 0) env.links = doc.links;
599
- const index = buildIndex(doc.included);
599
+ const index = buildIndex(doc.included, linkage ? void 0 : doc.data);
600
600
  const nodes = /* @__PURE__ */ new Map();
601
601
  const build = (raw) => buildNode(raw, env, index, nodes, ctx);
602
602
  const data = doc.data;
@@ -611,11 +611,18 @@ function materialiseDocument(doc, ctx, linkage, primaryType, paginatorOverride)
611
611
  return build(raw);
612
612
  }
613
613
  }
614
- /** Index `included` by `type:id` so relationship linkage can be hydrated. */
615
- function buildIndex(included) {
614
+ /**
615
+ * Index `included` and the primary resources by `type:id` so relationship linkage can be hydrated.
616
+ * A server never repeats a primary resource in `included`, so a member that links back to one
617
+ * (`tracks.album` on an album) is found only among the primary data.
618
+ */
619
+ function buildIndex(included, primary) {
616
620
  const index = /* @__PURE__ */ new Map();
617
- if (!included) return index;
618
- for (const raw of included) if (isObject$2(raw) && typeof raw["type"] === "string" && typeof raw["id"] === "string") index.set(key(raw["type"], raw["id"]), raw);
621
+ const add = (raw) => {
622
+ if (isObject$2(raw) && typeof raw["type"] === "string" && typeof raw["id"] === "string") index.set(key(raw["type"], raw["id"]), raw);
623
+ };
624
+ for (const raw of included ?? []) add(raw);
625
+ for (const raw of Array.isArray(primary) ? primary : [primary]) add(raw);
619
626
  return index;
620
627
  }
621
628
  const key = (type, id) => `${type}:${id}`;
@@ -633,6 +640,8 @@ function buildNode(raw, env, index, nodes, ctx) {
633
640
  id: raw.id
634
641
  };
635
642
  nodes.set(id, node);
643
+ const cycleViews = [];
644
+ UNFINISHED.set(node, cycleViews);
636
645
  if (raw.attributes) for (const [k, v] of Object.entries(raw.attributes)) node[k] = v;
637
646
  const rels = raw.relationships ?? {};
638
647
  const resType = ctx.descriptor[raw.type];
@@ -642,8 +651,78 @@ function buildNode(raw, env, index, nodes, ctx) {
642
651
  node[name] = hydrateRelation(rel, relDesc?.cardinality, resolvePaginator(relatedPaginator(relDesc, ctx)), env, index, nodes, ctx);
643
652
  }
644
653
  attachResourceEnvelope(node, raw, env, rels, require_validate.nestedFieldset(ctx.fields?.[raw.type]));
654
+ UNFINISHED.delete(node);
655
+ for (const view of cycleViews) readLateRelations(view, node);
645
656
  return node;
646
657
  }
658
+ /** Nodes still being built, each with the per-edge views a relation cycle copied of it so far. */
659
+ const UNFINISHED = /* @__PURE__ */ new WeakMap();
660
+ /** A back-reference's relations that read through to its node; a property, read on every walk. */
661
+ const LATE = Symbol("late relations");
662
+ /** Nodes some back-reference reads relations through to. */
663
+ const READ_THROUGH = /* @__PURE__ */ new WeakSet();
664
+ /**
665
+ * A relation cycle copied `view` of `node` before the node's later relations were set. Each one it
666
+ * missed reads the node's slot as linkage: the view sits past the end of its include path, and a
667
+ * hydrated value would close the cycle. Non-enumerable, so a spread, `JSON.stringify` and a cache
668
+ * walk meet no cycle.
669
+ */
670
+ function readLateRelations(view, node) {
671
+ const late = /* @__PURE__ */ new Set();
672
+ for (const name of Object.keys(node)) if (!Object.hasOwn(view, name)) {
673
+ late.add(name);
674
+ defineGetter(view, name, () => linkageOf(node[name]));
675
+ }
676
+ if (late.size > 0) {
677
+ Object.defineProperty(view, LATE, { value: late });
678
+ READ_THROUGH.add(node);
679
+ }
680
+ }
681
+ /** Each slot value's linkage, so a back-reference reads the same value until its node's changes. */
682
+ const LINKAGE = /* @__PURE__ */ new WeakMap();
683
+ /** A relation slot's value as linkage: identifier views, in an array keeping the slot's envelope. */
684
+ function linkageOf(slot) {
685
+ if (typeof slot !== "object" || slot === null) return slot;
686
+ if (LINKAGE.has(slot)) return LINKAGE.get(slot);
687
+ const value = Array.isArray(slot) ? withSlotEnvelope(slot, slot.map(identifierOf)) : identifierOf(slot);
688
+ LINKAGE.set(slot, value);
689
+ return value;
690
+ }
691
+ function identifierOf(member) {
692
+ if (!isObject$2(member) || typeof member["type"] !== "string" || typeof member["id"] !== "string") return member;
693
+ const meta = member.$edge?.meta;
694
+ return buildIdentifierView({
695
+ type: member["type"],
696
+ id: member["id"],
697
+ ...meta !== void 0 ? { meta } : {}
698
+ });
699
+ }
700
+ /** `members` carrying `slot`'s non-index members (`$page`, `$links`, `$next()` and the rest). */
701
+ function withSlotEnvelope(slot, members) {
702
+ for (const name of Reflect.ownKeys(slot)) if (name !== "length" && !(typeof name === "string" && /^\d+$/.test(name))) Object.defineProperty(members, name, Object.getOwnPropertyDescriptor(slot, name));
703
+ return members;
704
+ }
705
+ /**
706
+ * The relations of `view` that read through to its node as linkage (a back-reference a relation
707
+ * cycle built before the node's later relations were set), or `undefined`. A cache layer leaves
708
+ * these slots alone: they follow the node.
709
+ * @internal
710
+ */
711
+ function lateRelationsOf(view) {
712
+ return view[LATE];
713
+ }
714
+ /**
715
+ * Tell the client a cache layer wrote relation `name` of the cached copy `copy`: a node that
716
+ * back-references read the relation through to takes the value too, so they read it.
717
+ * @internal
718
+ */
719
+ function relationWritten(copy, name, value) {
720
+ let at = SOURCES.get(copy);
721
+ while (at !== void 0) {
722
+ if (READ_THROUGH.has(at)) at[name] = value;
723
+ at = SOURCES.get(at);
724
+ }
725
+ }
647
726
  /**
648
727
  * Resolve one relationship's value: an included member hydrates to a per-edge view, a
649
728
  * linked-but-not-included member stays an identifier, an empty to-one is `null`, and a
@@ -704,8 +783,10 @@ function attachResourceEnvelope(node, raw, env, rels, selection) {
704
783
  */
705
784
  function buildEdgeView(node, member, relationEdge, pick) {
706
785
  const view = {};
707
- if (pick === void 0) Object.assign(view, node);
708
- else for (const [k, v] of Object.entries(node)) if (k === "type" || k === "id" || pick(k)) view[k] = v;
786
+ if (pick === void 0) {
787
+ Object.assign(view, node);
788
+ UNFINISHED.get(node)?.push(view);
789
+ } else for (const [k, v] of Object.entries(node)) if (k === "type" || k === "id" || pick(k)) view[k] = v;
709
790
  SOURCES.set(view, node);
710
791
  for (const k of [
711
792
  "$meta",
@@ -715,8 +796,10 @@ function buildEdgeView(node, member, relationEdge, pick) {
715
796
  "$raw",
716
797
  "$nestedFieldset"
717
798
  ]) delegate(view, node, k);
718
- const rel = node.$rel;
719
- define(view, "$rel", typeof rel === "function" ? rel.bind(node) : () => void 0);
799
+ define(view, "$rel", (name) => {
800
+ const rel = node.$rel;
801
+ return typeof rel === "function" ? rel.call(node, name) : void 0;
802
+ });
720
803
  attachOverlayAccessors(view);
721
804
  attachEdgeEnvelope(view, member, false, relationEdge);
722
805
  return view;
@@ -944,6 +1027,63 @@ function relatedPaginatorKind(relation, ctx) {
944
1027
  return resolvePaginator(relatedPaginator(relation, ctx)).kind;
945
1028
  }
946
1029
  //#endregion
1030
+ //#region src/input-validation.ts
1031
+ /**
1032
+ * Thrown by a create or update whose input fails the schema `validateInput` holds for it, before
1033
+ * any request is sent. `fieldErrors(error)` takes it as it takes a server's 422.
1034
+ */
1035
+ var InputValidationError = class extends Error {
1036
+ type;
1037
+ operation;
1038
+ issues;
1039
+ /** The failing operation's index in an atomic batch. */
1040
+ opIndex;
1041
+ constructor(type, operation, issues, opIndex) {
1042
+ const first = issues[0]?.message;
1043
+ super(`The ${type} ${operation} input${opIndex === void 0 ? "" : ` of atomic operation ${opIndex}`} is invalid` + (first === void 0 ? "" : `: ${first}`) + (issues.length > 1 ? ` (and ${issues.length - 1} more)` : ""));
1044
+ this.name = "InputValidationError";
1045
+ this.type = type;
1046
+ this.operation = operation;
1047
+ this.issues = issues;
1048
+ if (opIndex !== void 0) this.opIndex = opIndex;
1049
+ }
1050
+ };
1051
+ /**
1052
+ * The {@link InputValidationError} `check`'s input fails its schema in `schemas` with, or
1053
+ * `undefined` when it passes or has no schema. A Promise only for a schema that validates
1054
+ * asynchronously.
1055
+ */
1056
+ function inputFailure(schemas, check) {
1057
+ const schema = schemas?.[check.type]?.[check.operation];
1058
+ if (schema === void 0) return;
1059
+ const failure = (result) => result.issues === void 0 ? void 0 : new InputValidationError(check.type, check.operation, result.issues, check.opIndex);
1060
+ const result = schema["~standard"].validate(check.input);
1061
+ return result instanceof Promise ? result.then(failure) : failure(result);
1062
+ }
1063
+ /**
1064
+ * Run `write` once `check`'s input passes its schema, else reject with the
1065
+ * {@link InputValidationError}. A write with no schema, or a schema that validates synchronously,
1066
+ * starts in this tick.
1067
+ */
1068
+ function withInputCheck(schemas, check, write) {
1069
+ const proceed = (failure) => failure === void 0 ? write() : Promise.reject(failure);
1070
+ const failure = inputFailure(schemas, check);
1071
+ return failure instanceof Promise ? failure.then(proceed) : proceed(failure);
1072
+ }
1073
+ //#endregion
1074
+ //#region src/input-path.ts
1075
+ /**
1076
+ * The flat input-path key format: `.` between names, `[n]` for a to-many member's index, as in
1077
+ * `orderedTracks[0].$pivot.position`. `byPath()` and `fieldErrors()` key errors by it.
1078
+ */
1079
+ function joinInputPath(segments) {
1080
+ return segments.map((segment, i) => typeof segment === "number" ? `[${segment}]` : i === 0 ? segment : `.${segment}`).join("");
1081
+ }
1082
+ /** The segments of a flat input-path key: `a[0].b` is `['a', 0, 'b']`. */
1083
+ function splitInputPath(key) {
1084
+ return Array.from(key.matchAll(/([^.[\]]+)|\[(\d+)\]/g), ([, name, index]) => index === void 0 ? name : Number(index));
1085
+ }
1086
+ //#endregion
947
1087
  //#region src/serialize-write.ts
948
1088
  /** Per-edge writable pivot data, supplied on a to-many member as the `$pivot` key. */
949
1089
  const PIVOT_KEY = "$pivot";
@@ -956,7 +1096,11 @@ const META_KEY = "$meta";
956
1096
  const DOCUMENT_META_KEY = "$documentMeta";
957
1097
  /** The flat path of a pointer into the request document's top-level `meta`, else `undefined`. */
958
1098
  function documentMetaPath(segments) {
959
- return segments[0] === "meta" ? [DOCUMENT_META_KEY, ...segments.slice(1)].join(".") : void 0;
1099
+ return segments[0] === "meta" ? pointerPath([DOCUMENT_META_KEY, ...segments.slice(1)]) : void 0;
1100
+ }
1101
+ /** Pointer segments as a flat input path, a numeric segment indexing an array: `tags[0]`. */
1102
+ function pointerPath(segments) {
1103
+ return joinInputPath(segments.map((s) => /^\d+$/.test(s) ? Number(s) : s));
960
1104
  }
961
1105
  /** The reserved input keys never routed to attributes/relationships. */
962
1106
  const RESERVED_INPUT = /* @__PURE__ */ new Set(["type", "id"]);
@@ -1084,16 +1228,12 @@ const describe = (value) => value === null ? "null" : Array.isArray(value) ? "an
1084
1228
  function remapPointer(descriptor, type, pointer) {
1085
1229
  const segments = pointer.split("/").filter((s) => s !== "");
1086
1230
  if (segments[0] !== "data") return documentMetaPath(segments) ?? pointer;
1087
- if (segments[1] === "meta") return [META_KEY, ...segments.slice(2)].join(".");
1088
- if (segments[1] === "attributes") return remapAttribute(segments.slice(2));
1231
+ if (segments[1] === "meta") return pointerPath([META_KEY, ...segments.slice(2)]);
1232
+ if (segments[1] === "attributes") return pointerPath(segments.slice(2));
1089
1233
  if (segments[1] === "id") return "id";
1090
1234
  if (segments[1] === "relationships") return remapRelationship(descriptor[type]?.relations ?? {}, segments.slice(2));
1091
1235
  return pointer;
1092
1236
  }
1093
- /** `[releaseInfo, label]` -> `releaseInfo.label`; a bare `[title]` -> `title`. */
1094
- function remapAttribute(rest) {
1095
- return rest.join(".");
1096
- }
1097
1237
  /**
1098
1238
  * Remap a relationship pointer's tail (everything after `relationships/`, or — for a
1099
1239
  * relationship-endpoint document — the relation name spliced ahead of the `data` tail). The
@@ -1106,17 +1246,17 @@ function remapRelationship(relations, rest) {
1106
1246
  const name = rest[0];
1107
1247
  if (name === void 0) return "data/relationships";
1108
1248
  const hasPivot = relations[name]?.pivot === true;
1109
- let path = name;
1249
+ const path = [name];
1110
1250
  for (let i = 1; i < rest.length; i++) {
1111
1251
  const seg = rest[i];
1112
1252
  if (seg === "data") continue;
1113
- if (/^\d+$/.test(seg)) path += `[${seg}]`;
1253
+ if (/^\d+$/.test(seg)) path.push(Number(seg));
1114
1254
  else if (seg === "meta" && hasPivot && rest[i + 1] === "pivot") {
1115
- path += ".$pivot";
1255
+ path.push("$pivot");
1116
1256
  i++;
1117
- } else path += `.${seg}`;
1257
+ } else path.push(seg);
1118
1258
  }
1119
- return path;
1259
+ return joinInputPath(path);
1120
1260
  }
1121
1261
  /**
1122
1262
  * Invert a relationship-MUTATION error's `source.pointer` to the caller's flat path, for the
@@ -1237,8 +1377,10 @@ const withOperationMeta = (operation, opts) => opts?.meta === void 0 ? operation
1237
1377
  const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
1238
1378
  /** The deterministic local id for the create at `opIndex` (stable + human-readable). */
1239
1379
  const lidFor = (opIndex) => `atomic-${opIndex}`;
1240
- async function runAtomic(request, materialiseCtx, descriptor, path, build) {
1380
+ async function runAtomic(request, materialiseCtx, descriptor, path, build, inputSchemas) {
1241
1381
  const operations = [];
1382
+ /** Each create and update input, checked against `inputSchemas` before the batch is sent. */
1383
+ const checks = [];
1242
1384
  /** The wire type of each op, by index — drives the error-pointer remap. */
1243
1385
  const typeByOp = [];
1244
1386
  /** The relation each relationship op writes, by index, which its pointers are remapped under. */
@@ -1272,6 +1414,13 @@ async function runAtomic(request, materialiseCtx, descriptor, path, build) {
1272
1414
  const opIndex = operations.length;
1273
1415
  const lid = lidFor(opIndex);
1274
1416
  const data = atomicResourceData(descriptor, input, { lid });
1417
+ const { type: _type, ...fields } = input;
1418
+ checks.push({
1419
+ type: input.type,
1420
+ operation: "create",
1421
+ input: fields,
1422
+ opIndex
1423
+ });
1275
1424
  operations.push(withOperationMeta({
1276
1425
  op: "add",
1277
1426
  data
@@ -1288,6 +1437,14 @@ async function runAtomic(request, materialiseCtx, descriptor, path, build) {
1288
1437
  const opIndex = operations.length;
1289
1438
  const identity = input.id !== void 0 ? { id: input.id } : { lid: input.lid };
1290
1439
  const data = atomicResourceData(descriptor, input, identity);
1440
+ const { type: _type, lid: _lid, ...fields } = input;
1441
+ const { id: _id, ...patch } = fields;
1442
+ checks.push({
1443
+ type: input.type,
1444
+ operation: "update",
1445
+ input: descriptor[input.type]?.singleton === true ? fields : patch,
1446
+ opIndex
1447
+ });
1291
1448
  operations.push(withOperationMeta({
1292
1449
  op: "update",
1293
1450
  ref: {
@@ -1331,6 +1488,10 @@ async function runAtomic(request, materialiseCtx, descriptor, path, build) {
1331
1488
  };
1332
1489
  }
1333
1490
  });
1491
+ for (const check of checks) {
1492
+ const failure = await inputFailure(inputSchemas, check);
1493
+ if (failure !== void 0) throw failure;
1494
+ }
1334
1495
  const req = {
1335
1496
  method: "POST",
1336
1497
  path,
@@ -1962,7 +2123,11 @@ const HANDLE_RESERVED = /* @__PURE__ */ new Set([
1962
2123
  * the one the body carries.
1963
2124
  */
1964
2125
  function runUpdate(ctx, type, vars, id, patch, opts) {
1965
- return runWrite(ctx, {
2126
+ return withInputCheck(ctx.inputSchemas, {
2127
+ type,
2128
+ operation: "update",
2129
+ input: patch
2130
+ }, () => runWrite(ctx, {
1966
2131
  type,
1967
2132
  operation: "update",
1968
2133
  vars,
@@ -1972,7 +2137,7 @@ function runUpdate(ctx, type, vars, id, patch, opts) {
1972
2137
  remap: (error) => withRemappedPaths(error, ctx.descriptor, type),
1973
2138
  accepted: ctx.descriptor[type]?.accepted?.update,
1974
2139
  wait: waitOptions(opts?.wait)
1975
- });
2140
+ }));
1976
2141
  }
1977
2142
  /**
1978
2143
  * Wrap a handle's verbs in a Proxy resolving each relation not shadowed by a reserved member to
@@ -2030,7 +2195,11 @@ function typeAccessor(ctx, type) {
2030
2195
  return {
2031
2196
  list: (query) => run(ctx, type, "fetchMany", {}, query),
2032
2197
  get: (id, query) => run(ctx, type, "fetchOne", { id }, query),
2033
- create: (input, opts) => runWrite(ctx, {
2198
+ create: (input, opts) => withInputCheck(ctx.inputSchemas, {
2199
+ type,
2200
+ operation: "create",
2201
+ input
2202
+ }, () => runWrite(ctx, {
2034
2203
  type,
2035
2204
  operation: "create",
2036
2205
  vars: {},
@@ -2040,7 +2209,7 @@ function typeAccessor(ctx, type) {
2040
2209
  remap: (error) => withRemappedPaths(error, ctx.descriptor, type),
2041
2210
  accepted: ctx.descriptor[type]?.accepted?.create,
2042
2211
  wait: waitOptions(opts?.wait)
2043
- }),
2212
+ })),
2044
2213
  id: (id) => resourceHandle(ctx, type, id),
2045
2214
  actions: actionsAccessor(ctx, type, "collection", {})
2046
2215
  };
@@ -2064,6 +2233,7 @@ function createClient(descriptor, options) {
2064
2233
  const ctx = {
2065
2234
  request,
2066
2235
  descriptor,
2236
+ ...options.validateInput !== void 0 ? { inputSchemas: options.validateInput } : {},
2067
2237
  materialise: {
2068
2238
  descriptor,
2069
2239
  navigate: async (url, linkage = false, paginator, signal) => {
@@ -2081,7 +2251,7 @@ function createClient(descriptor, options) {
2081
2251
  const atomicDescriptor = options.atomic ?? null;
2082
2252
  const atomic = (build) => {
2083
2253
  if (atomicDescriptor === null) throw new Error("This API does not expose an Atomic Operations endpoint");
2084
- return runAtomic(request, ctx.materialise, descriptor, atomicDescriptor.path, build);
2254
+ return runAtomic(request, ctx.materialise, descriptor, atomicDescriptor.path, build, ctx.inputSchemas);
2085
2255
  };
2086
2256
  const accessors = /* @__PURE__ */ new Map();
2087
2257
  return new Proxy(Object.create(null), {
@@ -2101,6 +2271,52 @@ function createClient(descriptor, options) {
2101
2271
  });
2102
2272
  }
2103
2273
  //#endregion
2274
+ //#region src/field-errors.ts
2275
+ function fieldErrors(error) {
2276
+ if (error instanceof InputValidationError) return group(error.issues.map((issue) => fromIssue(issue, error.opIndex)));
2277
+ if (!(error instanceof require_validate.JsonApiError) || !error.is4xx()) return;
2278
+ const issues = error.errors.map(toFieldError);
2279
+ return issues.some((issue) => issue.key !== "") ? group(issues) : void 0;
2280
+ }
2281
+ function group(issues) {
2282
+ const fields = {};
2283
+ const form = [];
2284
+ for (const issue of issues) if (issue.key === "") form.push(issue);
2285
+ else (fields[issue.key] ??= []).push(issue);
2286
+ return {
2287
+ fields,
2288
+ form,
2289
+ issues,
2290
+ first: (path) => fields[path]?.[0]?.message,
2291
+ messages: (path) => fields[path]?.map((issue) => issue.message) ?? [],
2292
+ op: (index) => group(issues.filter((issue) => issue.opIndex === index))
2293
+ };
2294
+ }
2295
+ function toFieldError(error) {
2296
+ const key = error.path === void 0 || error.path.startsWith("/") ? "" : error.path;
2297
+ return {
2298
+ message: require_validate.errorText(error, true) ?? "Invalid",
2299
+ path: splitInputPath(key),
2300
+ key,
2301
+ ...error.code === void 0 ? {} : { code: error.code },
2302
+ ...error.opIndex === void 0 ? {} : { opIndex: error.opIndex },
2303
+ error
2304
+ };
2305
+ }
2306
+ function fromIssue(issue, opIndex) {
2307
+ const path = (issue.path ?? []).map((segment) => {
2308
+ const key = typeof segment === "object" ? segment.key : segment;
2309
+ return typeof key === "number" ? key : String(key);
2310
+ });
2311
+ const key = joinInputPath(path);
2312
+ return {
2313
+ message: issue.message,
2314
+ path,
2315
+ key,
2316
+ ...opIndex === void 0 ? {} : { opIndex }
2317
+ };
2318
+ }
2319
+ //#endregion
2104
2320
  //#region src/load-all.ts
2105
2321
  /**
2106
2322
  * Follow `next` links from a first page until the last, and return every member in one plain
@@ -2127,10 +2343,96 @@ async function loadAll(first, options = {}) {
2127
2343
  return all;
2128
2344
  }
2129
2345
  //#endregion
2346
+ //#region src/mock.ts
2347
+ /** The members a linkage member carries beside its identity, which never become attributes. */
2348
+ const MEMBER_KEYS = /* @__PURE__ */ new Set([
2349
+ "type",
2350
+ "id",
2351
+ "meta",
2352
+ "$pivot"
2353
+ ]);
2354
+ /**
2355
+ * Build a materialised resource from its plain data, as a read returns it: the relations the data
2356
+ * nests hydrate, the identifiers stay identifiers, and each member's `$pivot` lands on its linkage
2357
+ * `meta.pivot`, so `$pivot`, `$edge`, `$rel` and `$count` all work. For tests and stories; the
2358
+ * generated client binds it to its descriptor and types it.
2359
+ */
2360
+ function mockResource(descriptor, data) {
2361
+ return materialise(mockDocument(descriptor, data), mockContext(descriptor));
2362
+ }
2363
+ /** {@link mockResource} for a collection of type `type`, as a list read returns it. */
2364
+ function mockCollection(descriptor, type, data) {
2365
+ return materialise(mockDocument(descriptor, data), mockContext(descriptor), false, type);
2366
+ }
2367
+ function mockContext(descriptor) {
2368
+ return {
2369
+ descriptor,
2370
+ navigate: () => Promise.reject(/* @__PURE__ */ new Error("A mock resource has no server to follow its links to."))
2371
+ };
2372
+ }
2373
+ /** The JSON:API document plain data stands for: the primary data, and every nested resource in `included`. */
2374
+ function mockDocument(descriptor, data) {
2375
+ const primary = /* @__PURE__ */ new Set();
2376
+ const included = /* @__PURE__ */ new Map();
2377
+ const toResource = (value) => {
2378
+ const relations = descriptor[value.type]?.relations ?? {};
2379
+ const attributes = {};
2380
+ const relationships = {};
2381
+ for (const [key, member] of Object.entries(value)) {
2382
+ if (key === "type" || key === "id") continue;
2383
+ if (key in relations) {
2384
+ if (member !== void 0) relationships[key] = { data: linkageOf(member) };
2385
+ } else if (key !== "meta" && key !== "$pivot") attributes[key] = member;
2386
+ }
2387
+ return {
2388
+ type: value.type,
2389
+ id: value.id,
2390
+ ...Object.keys(attributes).length > 0 ? { attributes } : {},
2391
+ ...Object.keys(relationships).length > 0 ? { relationships } : {},
2392
+ ...value["meta"] !== void 0 ? { meta: value["meta"] } : {}
2393
+ };
2394
+ };
2395
+ const linkageOf = (value) => {
2396
+ if (value === null) return null;
2397
+ if (Array.isArray(value)) return value.map((member) => identifierOf(member));
2398
+ return identifierOf(value);
2399
+ };
2400
+ const identifierOf = (member) => {
2401
+ const id = `${member.type}:${member.id}`;
2402
+ if (isFullResource(member) && !primary.has(id) && !included.has(id)) {
2403
+ included.set(id, {});
2404
+ included.set(id, toResource(member));
2405
+ }
2406
+ const pivot = member.$pivot;
2407
+ const meta = member["meta"];
2408
+ const linkageMeta = pivot === void 0 ? meta : {
2409
+ ...meta,
2410
+ pivot
2411
+ };
2412
+ return {
2413
+ type: member.type,
2414
+ id: member.id,
2415
+ ...linkageMeta !== void 0 ? { meta: linkageMeta } : {}
2416
+ };
2417
+ };
2418
+ const list = Array.isArray(data) ? data : [data];
2419
+ for (const value of list) primary.add(`${value.type}:${value.id}`);
2420
+ const resources = list.map(toResource);
2421
+ return {
2422
+ data: Array.isArray(data) ? resources : resources[0],
2423
+ ...included.size > 0 ? { included: [...included.values()] } : {}
2424
+ };
2425
+ }
2426
+ /** Whether a relation member carries more than its identity, so it stands for an included resource. */
2427
+ function isFullResource(member) {
2428
+ return Object.keys(member).some((key) => !MEMBER_KEYS.has(key));
2429
+ }
2430
+ //#endregion
2130
2431
  exports.ATOMIC_EXT = ATOMIC_EXT;
2131
2432
  exports.ATOMIC_MEDIA_TYPE = ATOMIC_MEDIA_TYPE;
2132
2433
  exports.CANONICAL_PAGE_KEYS = CANONICAL_PAGE_KEYS;
2133
2434
  exports.HANDLE_RESERVED = HANDLE_RESERVED;
2435
+ exports.InputValidationError = InputValidationError;
2134
2436
  exports.JSON_API_MEDIA_TYPE = JSON_API_MEDIA_TYPE;
2135
2437
  exports.JsonApiError = require_validate.JsonApiError;
2136
2438
  exports.PollTimeoutError = PollTimeoutError;
@@ -2142,17 +2444,23 @@ exports.execute = execute;
2142
2444
  exports.executeRaw = executeRaw;
2143
2445
  exports.executeResponse = executeResponse;
2144
2446
  exports.fetchTransport = fetchTransport;
2447
+ exports.fieldErrors = fieldErrors;
2145
2448
  exports.findError = require_validate.findError;
2146
2449
  exports.hasErrorCode = require_validate.hasErrorCode;
2147
2450
  exports.identifierViewOf = identifierViewOf;
2451
+ exports.inputFailure = inputFailure;
2148
2452
  exports.isAccepted = isAccepted;
2149
2453
  exports.isActionLocation = isActionLocation;
2150
2454
  exports.isMaterialised = isMaterialised;
2151
2455
  exports.isPolymorphic = isPolymorphic;
2456
+ exports.lateRelationsOf = lateRelationsOf;
2152
2457
  exports.listFilterMatcher = listFilterMatcher;
2153
2458
  exports.loadAll = loadAll;
2154
2459
  exports.materialise = materialise;
2155
2460
  exports.mediaType = mediaType;
2461
+ exports.mockCollection = mockCollection;
2462
+ exports.mockDocument = mockDocument;
2463
+ exports.mockResource = mockResource;
2156
2464
  exports.nestedFieldset = require_validate.nestedFieldset;
2157
2465
  exports.nextPageParams = nextPageParams;
2158
2466
  exports.nextRequestStamp = nextRequestStamp;
@@ -2161,6 +2469,7 @@ exports.prevPageParams = prevPageParams;
2161
2469
  exports.readActionLocation = readActionLocation;
2162
2470
  exports.relatedPaginator = relatedPaginator;
2163
2471
  exports.relatedPaginatorKind = relatedPaginatorKind;
2472
+ exports.relationWritten = relationWritten;
2164
2473
  exports.remapPointer = remapPointer;
2165
2474
  exports.remapRelationshipPointer = remapRelationshipPointer;
2166
2475
  exports.requestStampOf = requestStampOf;
@@ -2174,6 +2483,7 @@ exports.sparseSchemas = require_validate.sparseSchemas;
2174
2483
  exports.toDocument = toDocument;
2175
2484
  exports.toRelationshipDocument = toRelationshipDocument;
2176
2485
  exports.validateDocument = require_validate.validateDocument;
2486
+ exports.withInputCheck = withInputCheck;
2177
2487
  exports.withRemappedAtomicPaths = withRemappedAtomicPaths;
2178
2488
  exports.withRemappedDocumentMetaPaths = withRemappedDocumentMetaPaths;
2179
2489
  exports.withRemappedPaths = withRemappedPaths;