@haddowg/json-api-client 1.28.0 → 1.30.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.
@@ -13,6 +13,19 @@ var StructuralGuardError = class extends Error {
13
13
  }
14
14
  };
15
15
  /**
16
+ * The default {@link JsonApiError} message: the generic status line, then the first error object's
17
+ * `title` (else its `detail`) when it has one, then `" (and N more)"` for the further error
18
+ * objects. The wording matches the PHP client's.
19
+ */
20
+ function describeErrors(status, errors) {
21
+ let message = `JSON:API request failed with status ${status}`;
22
+ const first = errors[0];
23
+ const words = first === void 0 ? void 0 : first.title ?? first.detail;
24
+ if (typeof words === "string" && words !== "") message += `: ${words}`;
25
+ if (errors.length > 1) message += ` (and ${errors.length - 1} more)`;
26
+ return message;
27
+ }
28
+ /**
16
29
  * Thrown for any non-2xx JSON:API response. Carries the parsed error document plus
17
30
  * expressive status matchers and pointer-grouping helpers.
18
31
  *
@@ -23,7 +36,7 @@ var JsonApiError = class extends Error {
23
36
  status;
24
37
  errors;
25
38
  constructor(status, errors, message) {
26
- super(message ?? `JSON:API request failed with status ${status}`);
39
+ super(message ?? describeErrors(status, errors));
27
40
  this.name = "JsonApiError";
28
41
  this.status = status;
29
42
  this.errors = errors;
@@ -13,6 +13,19 @@ var StructuralGuardError = class extends Error {
13
13
  }
14
14
  };
15
15
  /**
16
+ * The default {@link JsonApiError} message: the generic status line, then the first error object's
17
+ * `title` (else its `detail`) when it has one, then `" (and N more)"` for the further error
18
+ * objects. The wording matches the PHP client's.
19
+ */
20
+ function describeErrors(status, errors) {
21
+ let message = `JSON:API request failed with status ${status}`;
22
+ const first = errors[0];
23
+ const words = first === void 0 ? void 0 : first.title ?? first.detail;
24
+ if (typeof words === "string" && words !== "") message += `: ${words}`;
25
+ if (errors.length > 1) message += ` (and ${errors.length - 1} more)`;
26
+ return message;
27
+ }
28
+ /**
16
29
  * Thrown for any non-2xx JSON:API response. Carries the parsed error document plus
17
30
  * expressive status matchers and pointer-grouping helpers.
18
31
  *
@@ -23,7 +36,7 @@ var JsonApiError = class extends Error {
23
36
  status;
24
37
  errors;
25
38
  constructor(status, errors, message) {
26
- super(message ?? `JSON:API request failed with status ${status}`);
39
+ super(message ?? describeErrors(status, errors));
27
40
  this.name = "JsonApiError";
28
41
  this.status = status;
29
42
  this.errors = errors;
@@ -415,4 +428,4 @@ function validateResourceMember(member, validator, fields) {
415
428
  //#endregion
416
429
  export { validateDocument as a, JsonApiError as c, hasErrorCode as d, sparseSchemas as i, StructuralGuardError as l, resolveValidator as n, fieldsOfUrl as o, sparseSchema as r, nestedFieldset as s, assertJsonApiDocument as t, findError as u };
417
430
 
418
- //# sourceMappingURL=validate-BvO7NhkT.mjs.map
431
+ //# sourceMappingURL=validate-CtXB1MGk.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"validate-CtXB1MGk.mjs","names":[],"sources":["../src/errors.ts","../src/nested-fieldset.ts","../src/validate.ts"],"sourcesContent":["/**\n * A single JSON:API error object (spec: error objects).\n *\n * `C` is the server's documented error-code union (a generated client's `ErrorCode`). `code` is\n * typed `C | (string & {})`: editors suggest the documented codes, yet any other string still\n * fits, because the catalogue is open and a server may send a code it never documented.\n */\nexport interface JsonApiErrorObject<C extends string = string> {\n id?: string\n status?: string\n code?: C | (string & {})\n title?: string\n detail?: string\n source?: { pointer?: string; parameter?: string; header?: string }\n meta?: Record<string, unknown>\n /**\n * The user-facing input path, remapped from `source.pointer` for write errors\n * (e.g. `/data/attributes/title` -> `title`). Populated by the runtime, which\n * built the envelope and therefore knows the inverse mapping. See docs/errors.md.\n */\n path?: string\n /**\n * The zero-based index of the failing operation within an atomic batch, parsed from a\n * `source.pointer` carrying an `/atomic:operations/{n}` prefix. Populated only for atomic\n * errors; `path` then holds the flat path within that operation's input.\n */\n opIndex?: number\n}\n\n/**\n * Thrown by the always-on light structural guards when a parsed response is not a\n * JSON:API document, or a `data`/`included` member is not a resource object carrying `type`+`id`.\n * Distinct from {@link JsonApiError} (a non-2xx server response): this signals the wire shape the\n * runtime relies on was violated, not an application error the server reported. The opt-in\n * per-field validator throws its engine's own error type, never this one.\n */\nexport class StructuralGuardError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'StructuralGuardError'\n }\n}\n\n/**\n * The default {@link JsonApiError} message: the generic status line, then the first error object's\n * `title` (else its `detail`) when it has one, then `\" (and N more)\"` for the further error\n * objects. The wording matches the PHP client's.\n */\nfunction describeErrors(status: number, errors: readonly JsonApiErrorObject[]): string {\n let message = `JSON:API request failed with status ${status}`\n const first = errors[0]\n const words = first === undefined ? undefined : (first.title ?? first.detail)\n if (typeof words === 'string' && words !== '') {\n message += `: ${words}`\n }\n if (errors.length > 1) {\n message += ` (and ${errors.length - 1} more)`\n }\n return message\n}\n\n/**\n * Thrown for any non-2xx JSON:API response. Carries the parsed error document plus\n * expressive status matchers and pointer-grouping helpers.\n *\n * `C` types each error object's `code` (see {@link JsonApiErrorObject}). It is a compile-time\n * hint only: the runtime never checks a code against it.\n */\nexport class JsonApiError<C extends string = string> extends Error {\n readonly status: number\n readonly errors: JsonApiErrorObject<C>[]\n\n constructor(status: number, errors: JsonApiErrorObject<C>[], message?: string) {\n super(message ?? describeErrors(status, errors))\n this.name = 'JsonApiError'\n this.status = status\n this.errors = errors\n }\n\n hasStatus(status: number): boolean {\n return this.status === status\n }\n\n is4xx(): boolean {\n return this.status >= 400 && this.status < 500\n }\n\n is5xx(): boolean {\n return this.status >= 500 && this.status < 600\n }\n\n isBadRequest(): boolean {\n return this.status === 400\n }\n\n isUnauthorized(): boolean {\n return this.status === 401\n }\n\n isForbidden(): boolean {\n return this.status === 403\n }\n\n isNotFound(): boolean {\n return this.status === 404\n }\n\n isNotAcceptable(): boolean {\n return this.status === 406\n }\n\n isConflict(): boolean {\n return this.status === 409\n }\n\n isUnsupportedMediaType(): boolean {\n return this.status === 415\n }\n\n isUnprocessable(): boolean {\n return this.status === 422\n }\n\n /** Alias of {@link isUnprocessable} — the JSON:API validation status. */\n isValidationError(): boolean {\n return this.status === 422\n }\n\n isRateLimited(): boolean {\n return this.status === 429\n }\n\n /**\n * Group errors by user-facing input path (falls back to the raw pointer, then the\n * query parameter). The payoff for form/validation UX — 422 `source.pointer`s are\n * remapped to the flat shape the caller actually supplied.\n */\n byPath(): Record<string, JsonApiErrorObject<C>[]> {\n const out: Record<string, JsonApiErrorObject<C>[]> = {}\n for (const e of this.errors) {\n const key = e.path ?? e.source?.pointer ?? e.source?.parameter ?? '_'\n ;(out[key] ??= []).push(e)\n }\n return out\n }\n}\n\n/**\n * True when `err` is a {@link JsonApiError} and any of its error objects carries `code`. Takes\n * any string, so it also matches codes the server never documented. A generated client exports a\n * `hasErrorCode` bound to its server's `ErrorCode` union, which rejects a misspelt code at\n * compile time; reach for this one only to match an undocumented code.\n */\nexport function hasErrorCode(err: unknown, code: string): err is JsonApiError {\n return err instanceof JsonApiError && err.errors.some((e) => e.code === code)\n}\n\n/**\n * {@link hasErrorCode} restricted to one server's documented codes. A generated client binds it:\n * `export const hasErrorCode = hasErrorCodeRuntime as ErrorCodeGuard<ErrorCode>`. The cast is\n * needed because `JsonApiError<string>` doesn't assign to `JsonApiError<ErrorCode>`.\n */\nexport type ErrorCodeGuard<C extends string> = (err: unknown, code: C) => err is JsonApiError<C>\n\n/**\n * An error object carrying the documented code `K`, its `meta` typed when the server declares\n * one for the code. `M` is a generated client's `ErrorMetaByCode`; a code it does not list\n * keeps the untyped `meta`.\n */\nexport type CodedErrorObject<K extends string, M = {}> = JsonApiErrorObject<K> & {\n code: K\n} & (K extends keyof M ? { meta: M[K] } : {})\n\n/**\n * The first error object in `err` carrying `code`, or `undefined` when `err` is not a\n * {@link JsonApiError} or none of its errors carries it. Takes any string; a generated client\n * exports a `findError` bound to its documented codes and their `meta`, which types the result.\n */\nexport function findError(err: unknown, code: string): JsonApiErrorObject | undefined {\n return err instanceof JsonApiError ? err.errors.find((e) => e.code === code) : undefined\n}\n\n/**\n * {@link findError} restricted to one server's documented codes, with each code's declared\n * `meta`. A generated client binds it:\n * `export const findError = findErrorRuntime as ErrorFinder<ErrorCode, ErrorMetaByCode>`.\n */\nexport type ErrorFinder<C extends string, M = {}> = <K extends C>(\n err: unknown,\n code: K,\n) => CodedErrorObject<K, M> | undefined\n","/**\n * The keys a sparse fieldset selected of each attribute it narrowed, under the Nested Fieldsets\n * profile (https://haddowg.github.io/json-api/profiles/nested-fieldsets/): attribute name -> the\n * paths `fields[type]=<attribute>.<path>` named, in request order, each once. A path into a nested\n * object, such as `geo.lat`, names one key per level, and a path through a list names its items\n * `*`, such as `*.sku`. An attribute the fieldset also lists whole\n * is left out, and so is a path whose key the fieldset also lists whole, since the server renders\n * those whole. A path ending in `*` names the list itself, so `lines.*` lists `lines` whole and\n * `shipping.parcels.*` selects `parcels` whole. Empty when nothing was narrowed.\n */\nexport type NestedFieldset = Readonly<Record<string, readonly string[]>>\n\nconst NONE: NestedFieldset = Object.freeze({})\n\n/**\n * The {@link NestedFieldset} of one type's `fields[type]` members. The path is everything after the\n * first full stop, as the server reads it, and a member with an empty key at any level selects\n * nothing.\n */\nexport function nestedFieldset(listed: readonly string[] | undefined): NestedFieldset {\n if (listed === undefined) {\n return NONE\n }\n const members = listed.map(listItself)\n const whole = new Set(members.filter((member) => !member.includes('.')))\n const out: Record<string, string[]> = {}\n for (const member of members) {\n const dot = member.indexOf('.')\n if (dot <= 0) {\n continue\n }\n const attribute = member.slice(0, dot)\n if (whole.has(attribute)) {\n continue\n }\n const path = member.slice(dot + 1)\n if (path.split('.').includes('')) {\n continue\n }\n const paths = (out[attribute] ??= [])\n if (!paths.includes(path)) {\n paths.push(path)\n }\n }\n for (const [attribute, paths] of Object.entries(out)) {\n out[attribute] = paths.filter(\n (path) => !paths.some((other) => other !== path && path.startsWith(`${other}.`)),\n )\n }\n return Object.keys(out).length === 0 ? NONE : out\n}\n\n/** A member ending in `.*` with the wildcard dropped, since it names the list itself. */\nfunction listItself(member: string): string {\n let out = member\n while (out.endsWith('.*')) {\n out = out.slice(0, -2)\n }\n return out\n}\n\n/**\n * The `fields[type]` members a request URL carries, by type, for a link the client follows as\n * given, such as a `next` page, whose query it didn't build.\n */\nexport function fieldsOfUrl(url: string): Record<string, string[]> | undefined {\n let params: URLSearchParams\n try {\n params = new URL(url, 'http://link.invalid').searchParams\n } catch {\n return undefined\n }\n let out: Record<string, string[]> | undefined\n params.forEach((value, name) => {\n const type = /^fields\\[(.+)\\]$/.exec(name)?.[1]\n if (type !== undefined) {\n ;(out ??= {})[type] = value === '' ? [] : value.split(',')\n }\n })\n return out\n}\n","import { StructuralGuardError } from './errors'\nimport { nestedFieldset } from './nested-fieldset'\nimport type { Document } from './request'\n\n/**\n * A wire resource as it appears in a document's `data`/`included` — a JSON:API resource\n * object (or bare identifier). The structural guards assert `type` (and, where required,\n * `id`); the opt-in validator sees the whole object to check the rest against its schema.\n */\nexport interface WireResource {\n type: string\n id?: string\n [key: string]: unknown\n}\n\n/**\n * What the request a resource answered tells a validator. `fields` is the sparse fieldset the\n * request sent for the resource's type, `fields[type]`, absent when it sent none.\n */\nexport interface ValidationContext {\n readonly fields?: readonly string[]\n}\n\n/**\n * The opt-in per-resource validator: validate one wire `resource` against its JSON `schema`\n * (the bundle's per-type resource-object schema). The engine is the user's — throw (or\n * aggregate-then-throw) on an invalid resource; return for a valid one. With the bare-function\n * seam form there is no per-type schema, so `schema` is `undefined` and the function owns the\n * whole decision. With the schema-driven form, `schema` is already relaxed for the request's\n * sparse fieldset (see {@link sparseSchema}). `context` carries that fieldset either way, so a\n * bare validator can relax its own schema.\n */\nexport type Validator = (\n resource: WireResource,\n schema: unknown,\n context?: ValidationContext,\n) => void\n\n/** A per-type JSON Schema map (the codegen-emitted `schemas` constant), keyed by JSON:API type. */\nexport type SchemaMap = Readonly<Record<string, unknown>>\n\n/**\n * The schema-driven validation seam: a per-type `schemas` map plus a `validator` engine. Each\n * wire resource is validated against `schemas[resource.type]`; a type with no schema is skipped.\n */\nexport interface ValidationConfig {\n schemas: SchemaMap\n validator: Validator\n}\n\n/**\n * The `validate?` option on {@link ClientOptions}: either the schema-driven {@link ValidationConfig}\n * (the common case — the codegen-emitted `schemas` map + an engine adapter) or a bare\n * {@link Validator} that owns schema lookup itself (it is called per resource with `schema` =\n * `undefined`). Absent => no per-field validation (zero overhead, no engine dependency).\n */\nexport type ValidationOption = ValidationConfig | Validator\n\n/**\n * A normalised validator: resolve a resource's schema (or `undefined`) and validate it. `fields`\n * is the request's sparse fieldset for the resource's type, when it sent one.\n */\nexport interface ResolvedValidator {\n validate(resource: WireResource, fields?: readonly string[]): void\n}\n\n/** Whether a `validate` option is the schema-driven config (vs a bare validator function). */\nfunction isConfig(option: ValidationOption): option is ValidationConfig {\n return typeof option === 'object' && option !== null && !Array.isArray(option)\n}\n\n/**\n * Normalise the `validate?` option to a single per-resource validator. The config form looks the\n * schema up by `resource.type` and skips a type with no schema (the seam stays graceful for a\n * partially-covered bundle); the bare-function form calls the validator with `schema = undefined`,\n * delegating the whole decision to the caller. Returns `undefined` when validation is off.\n */\nexport function resolveValidator(\n option: ValidationOption | undefined,\n): ResolvedValidator | undefined {\n if (option === undefined) {\n return undefined\n }\n if (isConfig(option)) {\n const { schemas, validator } = option\n const sparse = sparseSchemas()\n return {\n validate(resource, fields) {\n const schema = schemas[resource.type]\n // A type the bundle does not cover is skipped, not failed — partial coverage is allowed.\n if (schema === undefined) {\n return\n }\n if (fields === undefined) {\n validator(resource, schema)\n } else {\n validator(resource, sparse(schema, fields), { fields })\n }\n },\n }\n }\n return {\n validate(resource, fields) {\n if (fields === undefined) {\n option(resource, undefined)\n } else {\n option(resource, undefined, { fields })\n }\n },\n }\n}\n\n/**\n * A cache of {@link sparseSchema} results, by schema and fieldset, so each pair is relaxed once.\n * A schema with no fieldset comes back as it is.\n */\nexport function sparseSchemas(): (\n schema: unknown,\n fields: readonly string[] | undefined,\n) => unknown {\n const cache = new WeakMap<object, Map<string, unknown>>()\n return (schema, fields) => {\n if (fields === undefined || !isObject(schema)) {\n return schema\n }\n let bySet = cache.get(schema)\n if (bySet === undefined) {\n bySet = new Map()\n cache.set(schema, bySet)\n }\n const key = fields.join(',')\n if (!bySet.has(key)) {\n bySet.set(key, sparseSchema(schema, fields))\n }\n return bySet.get(key)\n }\n}\n\n/**\n * The members one object level of a sparse fieldset selects: `keep`, the keys it renders, and\n * `children`, the keys it narrows further, a list's items under `*`.\n */\ninterface Narrowing {\n keep: ReadonlySet<string>\n children: ReadonlyMap<string, Narrowing>\n}\n\n/** The {@link Narrowing} of key paths relative to one level, such as `b`, `c.d` or `*.sku`. */\nfunction narrowingOf(paths: readonly string[]): Narrowing {\n const keep = new Set<string>()\n const whole = new Set<string>()\n const deeper = new Map<string, string[]>()\n for (const path of paths) {\n const dot = path.indexOf('.')\n const head = dot < 0 ? path : path.slice(0, dot)\n keep.add(head)\n if (dot < 0) {\n whole.add(head)\n } else {\n const rest = deeper.get(head) ?? []\n rest.push(path.slice(dot + 1))\n deeper.set(head, rest)\n }\n }\n const children = new Map<string, Narrowing>()\n for (const [head, rest] of deeper) {\n if (!whole.has(head)) {\n children.set(head, narrowingOf(rest))\n }\n }\n return { keep, children }\n}\n\n/**\n * One {@link Narrowing} for a schema several keys share, such as a map's `additionalProperties`:\n * a key stays required only when every sharer renders it, and a key one sharer narrows is narrowed.\n */\nfunction merged(narrowings: readonly Narrowing[]): Narrowing {\n if (narrowings.length === 1) {\n return narrowings[0]!\n }\n const keep = new Set(\n [...narrowings[0]!.keep].filter((key) => narrowings.every((n) => n.keep.has(key))),\n )\n const grouped = new Map<string, Narrowing[]>()\n for (const narrowing of narrowings) {\n for (const [key, child] of narrowing.children) {\n grouped.set(key, [...(grouped.get(key) ?? []), child])\n }\n }\n const children = new Map<string, Narrowing>()\n for (const [key, group] of grouped) {\n children.set(key, merged(group))\n }\n return { keep, children }\n}\n\n/** The schema a local `$ref` such as `#/$defs/Address` points at within `root`. */\nfunction resolveRef(root: Record<string, unknown>, ref: string): unknown {\n if (!ref.startsWith('#')) {\n return undefined\n }\n let node: unknown = root\n for (const raw of ref.slice(1).split('/').slice(1)) {\n const segment = decodeURIComponent(raw).replace(/~1/g, '/').replace(/~0/g, '~')\n node = isObject(node) ? node[segment] : undefined\n }\n return node\n}\n\n/** `schema` with `narrowing` applied: its `required` cut to what the level renders, its narrowed keys relaxed in turn. */\nfunction narrowed(\n root: Record<string, unknown>,\n schema: unknown,\n narrowing: Narrowing,\n depth = 0,\n): unknown {\n if (!isObject(schema) || depth > 64) {\n return schema\n }\n if (typeof schema['$ref'] === 'string') {\n const { $ref: ref, ...siblings } = schema\n const target = resolveRef(root, ref as string)\n if (isObject(target)) {\n return narrowed(root, { ...target, ...siblings }, narrowing, depth + 1)\n }\n }\n const out: Record<string, unknown> = { ...schema }\n // The member naming a union's variant renders whatever the selection, so it stays required and\n // its `const` still tells the narrowed variants apart.\n const discriminator = isObject(out['discriminator']) ? out['discriminator']['propertyName'] : null\n const branchNarrowing =\n typeof discriminator === 'string'\n ? { keep: new Set([...narrowing.keep, discriminator]), children: narrowing.children }\n : narrowing\n for (const key of ['anyOf', 'oneOf', 'allOf'] as const) {\n const branches = out[key]\n if (Array.isArray(branches)) {\n out[key] = branches.map((branch) => narrowed(root, branch, branchNarrowing, depth + 1))\n }\n }\n // Without a discriminator, narrowed variants can no longer be told apart by their required\n // members, so a value may match more than one of them.\n if (Array.isArray(out['oneOf']) && typeof discriminator !== 'string') {\n const { oneOf, ...rest } = out\n return out['anyOf'] === undefined\n ? narrowedLevel(root, { ...rest, anyOf: oneOf }, narrowing, depth)\n : narrowedLevel(\n root,\n { ...rest, allOf: [...((rest['allOf'] as unknown[]) ?? []), { anyOf: oneOf }] },\n narrowing,\n depth,\n )\n }\n return narrowedLevel(root, out, narrowing, depth)\n}\n\n/** The rest of {@link narrowed}: one level's own `required` and keys. */\nfunction narrowedLevel(\n root: Record<string, unknown>,\n out: Record<string, unknown>,\n narrowing: Narrowing,\n depth: number,\n): unknown {\n const required = out['required']\n if (Array.isArray(required)) {\n out['required'] = required.filter((key) => typeof key === 'string' && narrowing.keep.has(key))\n }\n const properties = isObject(out['properties']) ? { ...out['properties'] } : undefined\n const patterns = isObject(out['patternProperties']) ? out['patternProperties'] : undefined\n const shared = new Map<string, Narrowing[]>()\n const share = (target: string, child: Narrowing): void => {\n shared.set(target, [...(shared.get(target) ?? []), child])\n }\n for (const [key, child] of narrowing.children) {\n if (key === '*') {\n if (isObject(out['items'])) {\n out['items'] = narrowed(root, out['items'], child, depth + 1)\n }\n continue\n }\n if (properties !== undefined && key in properties) {\n properties[key] = narrowed(root, properties[key], child, depth + 1)\n continue\n }\n const matching = Object.keys(patterns ?? {}).filter((pattern) => matches(pattern, key))\n if (matching.length > 0) {\n matching.forEach((pattern) => share(`pattern:${pattern}`, child))\n } else if (isObject(out['additionalProperties'])) {\n share('additional', child)\n }\n }\n if (properties !== undefined) {\n out['properties'] = properties\n }\n if (patterns !== undefined) {\n const next = { ...patterns }\n for (const pattern of Object.keys(patterns)) {\n const group = shared.get(`pattern:${pattern}`)\n if (group !== undefined) {\n next[pattern] = narrowed(root, patterns[pattern], merged(group), depth + 1)\n }\n }\n out['patternProperties'] = next\n }\n const additional = shared.get('additional')\n if (additional !== undefined) {\n out['additionalProperties'] = narrowed(\n root,\n out['additionalProperties'],\n merged(additional),\n depth + 1,\n )\n }\n return out\n}\n\n/** Whether a `patternProperties` pattern matches `key`; an unreadable pattern matches nothing. */\nfunction matches(pattern: string, key: string): boolean {\n try {\n return new RegExp(pattern, 'u').test(key)\n } catch {\n return false\n }\n}\n\n/**\n * A resource object schema relaxed for a response to a request whose sparse fieldset for the type\n * named `members`. An attribute or relation the fieldset leaves out is no longer required, and an\n * attribute it narrows to some of its keys, such as `address.city`, `location.geo.lat` or\n * `lines.*.sku`, requires only the keys selected at each level along those paths. A member the\n * fieldset also lists whole is left as declared, as the server renders it whole. Everything else\n * in the schema is kept, so a selected value is still checked, but for its `$id`: the copy is a\n * schema of its own.\n */\nexport function sparseSchema(schema: unknown, members: readonly string[]): unknown {\n if (!isObject(schema)) {\n return schema\n }\n const selection = nestedFieldset(members)\n const selected = new Set([\n // `lines.*` names the list itself, as `lines` does.\n ...members\n .map((member) => member.replace(/(?:\\.\\*)+$/, ''))\n .filter((member) => member !== '' && !member.includes('.')),\n ...Object.keys(selection),\n ])\n const children = new Map<string, Narrowing>()\n for (const [attribute, paths] of Object.entries(selection)) {\n children.set(attribute, narrowingOf(paths))\n }\n // The resource object keeps its own required members, but `attributes` and `relationships`\n // may be left out when the fieldset empties them.\n const required = Array.isArray(schema['required']) ? (schema['required'] as unknown[]) : []\n const out = narrowed(schema, schema, {\n keep: new Set(\n required.filter(\n (key): key is string =>\n typeof key === 'string' && key !== 'attributes' && key !== 'relationships',\n ),\n ),\n children: new Map([\n ['attributes', { keep: selected, children }],\n ['relationships', { keep: selected, children: new Map() }],\n ]),\n }) as Record<string, unknown>\n // An engine keying schemas by `$id` can then hold the copy beside the whole schema.\n delete out['$id']\n return out\n}\n\nconst isObject = (v: unknown): v is Record<string, unknown> =>\n typeof v === 'object' && v !== null && !Array.isArray(v)\n\n/**\n * The light structural guards every parsed response passes through (ADR 0004): assert the body\n * is a JSON:API document and that each `data`/`included` member carries a string `type` (and,\n * for a full resource, an `id`). This is the always-on, engine-free floor — it never duplicates\n * the opt-in per-field validation; it only proves the envelope invariant the runtime relies on.\n *\n * A primary-`data` resource and every `included` resource must carry `type`+`id`. A relationship\n * endpoint's primary data is pure resource-identifier linkage, which also carries `type`+`id`, so\n * the same guard holds; `linkage` is accepted for symmetry with the materialiser but the assertion\n * is identical (an identifier is `type`+`id`). `data: null` (an empty to-one) and a missing\n * `data` (a meta-only document) are valid and pass.\n */\nexport function assertJsonApiDocument(body: unknown): asserts body is Document {\n if (!isObject(body)) {\n throw new StructuralGuardError('Response body is not a JSON:API document (expected an object)')\n }\n // A JSON:API document must carry at least one of `data`, `errors`, or `meta`. An error\n // document never reaches here (a non-2xx throws a JsonApiError upstream), so the guard\n // requires a `data` or `meta` top-level member.\n if (!('data' in body) && !('meta' in body)) {\n throw new StructuralGuardError(\n 'Response body is not a JSON:API document (missing top-level \"data\" or \"meta\")',\n )\n }\n const data = body['data']\n if (Array.isArray(data)) {\n data.forEach((member, i) => assertResource(member, `data[${i}]`))\n } else if (data !== null && data !== undefined) {\n assertResource(data, 'data')\n }\n const included = body['included']\n if (included !== undefined) {\n if (!Array.isArray(included)) {\n throw new StructuralGuardError('Response \"included\" is not an array')\n }\n included.forEach((member, i) => assertResource(member, `included[${i}]`))\n }\n}\n\n/** Assert a single member is a resource object/identifier carrying string `type` + `id`. */\nfunction assertResource(member: unknown, at: string): void {\n if (!isObject(member)) {\n throw new StructuralGuardError(`${at} is not a JSON:API resource object`)\n }\n if (typeof member['type'] !== 'string') {\n throw new StructuralGuardError(`${at} is missing a string \"type\"`)\n }\n if (typeof member['id'] !== 'string') {\n throw new StructuralGuardError(`${at} (type \"${member['type']}\") is missing a string \"id\"`)\n }\n}\n\n/**\n * Run the opt-in validator over every wire resource in a document's `data` + `included`, each\n * against its per-type schema. Called only when a validator is configured (off by default). The\n * structural guards have already proven each member carries `type`+`id`, so the cast is sound.\n */\nexport function validateDocument(\n body: Document,\n validator: ResolvedValidator,\n fields?: Readonly<Record<string, readonly string[]>>,\n): void {\n const data = body.data\n if (Array.isArray(data)) {\n for (const member of data) {\n validateResourceMember(member, validator, fields)\n }\n } else if (data !== null && data !== undefined) {\n validateResourceMember(data, validator, fields)\n }\n if (body.included !== undefined) {\n // `included` always holds full resource objects.\n for (const member of body.included) {\n const resource = member as WireResource\n validator.validate(resource, fields?.[resource.type])\n }\n }\n}\n\n/**\n * Validate a `data` member, but only when it is a full RESOURCE OBJECT. A relationship-linkage\n * endpoint's `data` is bare resource IDENTIFIERS (`type`+`id`[+`meta`], no `attributes`/\n * `relationships`); the per-type schema describes the resource object, so running it over an\n * identifier would spuriously fail. The structural guard already covered the identifier shape.\n */\nfunction validateResourceMember(\n member: unknown,\n validator: ResolvedValidator,\n fields: Readonly<Record<string, readonly string[]>> | undefined,\n): void {\n if (isObject(member) && ('attributes' in member || 'relationships' in member)) {\n const resource = member as WireResource\n validator.validate(resource, fields?.[resource.type])\n }\n}\n"],"mappings":";;;;;;;;AAoCA,IAAa,uBAAb,cAA0C,MAAM;CAC9C,YAAY,SAAiB;EAC3B,MAAM,OAAO;EACb,KAAK,OAAO;CACd;AACF;;;;;;AAOA,SAAS,eAAe,QAAgB,QAA+C;CACrF,IAAI,UAAU,uCAAuC;CACrD,MAAM,QAAQ,OAAO;CACrB,MAAM,QAAQ,UAAU,KAAA,IAAY,KAAA,IAAa,MAAM,SAAS,MAAM;CACtE,IAAI,OAAO,UAAU,YAAY,UAAU,IACzC,WAAW,KAAK;CAElB,IAAI,OAAO,SAAS,GAClB,WAAW,SAAS,OAAO,SAAS,EAAE;CAExC,OAAO;AACT;;;;;;;;AASA,IAAa,eAAb,cAA6D,MAAM;CACjE;CACA;CAEA,YAAY,QAAgB,QAAiC,SAAkB;EAC7E,MAAM,WAAW,eAAe,QAAQ,MAAM,CAAC;EAC/C,KAAK,OAAO;EACZ,KAAK,SAAS;EACd,KAAK,SAAS;CAChB;CAEA,UAAU,QAAyB;EACjC,OAAO,KAAK,WAAW;CACzB;CAEA,QAAiB;EACf,OAAO,KAAK,UAAU,OAAO,KAAK,SAAS;CAC7C;CAEA,QAAiB;EACf,OAAO,KAAK,UAAU,OAAO,KAAK,SAAS;CAC7C;CAEA,eAAwB;EACtB,OAAO,KAAK,WAAW;CACzB;CAEA,iBAA0B;EACxB,OAAO,KAAK,WAAW;CACzB;CAEA,cAAuB;EACrB,OAAO,KAAK,WAAW;CACzB;CAEA,aAAsB;EACpB,OAAO,KAAK,WAAW;CACzB;CAEA,kBAA2B;EACzB,OAAO,KAAK,WAAW;CACzB;CAEA,aAAsB;EACpB,OAAO,KAAK,WAAW;CACzB;CAEA,yBAAkC;EAChC,OAAO,KAAK,WAAW;CACzB;CAEA,kBAA2B;EACzB,OAAO,KAAK,WAAW;CACzB;;CAG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AS,QAAQ,SAAS,KAAA,GACnC,eAAe,MAAM,MAAM;CAE7B,MAAM,WAAW,KAAK;CACtB,IAAI,aAAa,KAAA,GAAW;EAC1B,IAAI,CAAC,MAAM,QAAQ,QAAQ,GACzB,MAAM,IAAI,qBAAqB,uCAAqC;EAEtE,SAAS,SAAS,QAAQ,MAAM,eAAe,QAAQ,YAAY,EAAE,EAAE,CAAC;CAC1E;AACF;;AAGA,SAAS,eAAe,QAAiB,IAAkB;CACzD,IAAI,CAAC,SAAS,MAAM,GAClB,MAAM,IAAI,qBAAqB,GAAG,GAAG,mCAAmC;CAE1E,IAAI,OAAO,OAAO,YAAY,UAC5B,MAAM,IAAI,qBAAqB,GAAG,GAAG,4BAA4B;CAEnE,IAAI,OAAO,OAAO,UAAU,UAC1B,MAAM,IAAI,qBAAqB,GAAG,GAAG,UAAU,OAAO,QAAQ,4BAA4B;AAE9F;;;;;;AAOA,SAAgB,iBACd,MACA,WACA,QACM;CACN,MAAM,OAAO,KAAK;CAClB,IAAI,MAAM,QAAQ,IAAI,GACpB,KAAK,MAAM,UAAU,MACnB,uBAAuB,QAAQ,WAAW,MAAM;MAE7C,IAAI,SAAS,QAAQ,SAAS,KAAA,GACnC,uBAAuB,MAAM,WAAW,MAAM;CAEhD,IAAI,KAAK,aAAa,KAAA,GAEpB,KAAK,MAAM,UAAU,KAAK,UAAU;EAClC,MAAM,WAAW;EACjB,UAAU,SAAS,UAAU,SAAS,SAAS,KAAK;CACtD;AAEJ;;;;;;;AAQA,SAAS,uBACP,QACA,WACA,QACM;CACN,IAAI,SAAS,MAAM,MAAM,gBAAgB,UAAU,mBAAmB,SAAS;EAC7E,MAAM,WAAW;EACjB,UAAU,SAAS,UAAU,SAAS,SAAS,KAAK;CACtD;AACF"}
@@ -133,6 +133,25 @@ interface RelationDescriptor {
133
133
  * on write inputs and is left out of the read view, `fields` and the relationship reads.
134
134
  */
135
135
  writeOnly?: boolean;
136
+ /**
137
+ * `true` when a create must send this relation, as the create request's
138
+ * `relationships.required` lists it. A create input then requires it. Absent means optional,
139
+ * as every relation is on an update.
140
+ */
141
+ requiredOnCreate?: boolean;
142
+ /**
143
+ * The writes that refuse `null` for this to-one, as a required relation that is not nullable
144
+ * does: `create`, `update` or both. A write input in one of them takes a reference, never
145
+ * `null`. Absent means every write takes `null`, which clears the relation.
146
+ */
147
+ nonNullOn?: readonly ('create' | 'update')[];
148
+ /**
149
+ * The writes that refuse an empty linkage for this to-many, as a required relation's do, or
150
+ * one bounded by `minItems` of 1 or more: `create`, `update` or both. A write input in one of
151
+ * them takes a non-empty list. A create also takes one for a relation {@link requiredOnCreate}
152
+ * marks. Absent means every write takes `[]`.
153
+ */
154
+ nonEmptyOn?: readonly ('create' | 'update')[];
136
155
  /**
137
156
  * The relation's segment in its related and relationship paths, when it differs from the
138
157
  * relation's name (`/articles/{id}/published-by` for `publisher`). Absent means the name.
@@ -502,6 +521,14 @@ interface ResourceDescriptor {
502
521
  paths: Readonly<Record<string, string>>;
503
522
  paginator: PaginatorDescriptor;
504
523
  clientId: ClientIdPolicy;
524
+ /**
525
+ * The attributes a read renders that a create can't supply (the server sets them: read-only on
526
+ * create, or absent from the create document). Absent when every read attribute is creatable, or
527
+ * for a type with no create.
528
+ */
529
+ serverOnly?: readonly string[];
530
+ /** The attributes whose read value may be `null`. Absent when none may be. */
531
+ nullable?: readonly string[];
505
532
  /**
506
533
  * `true` for a singleton type, which serves each caller one resource at a path with no `{id}`
507
534
  * (`/inbox`). Its {@link paths} are those of the single read, the update, and the related and
@@ -881,6 +908,25 @@ type PageParamsOf<P extends Page> = PaginatorKind extends P['kind'] ? Readonly<R
881
908
  } ? {
882
909
  kind: A;
883
910
  } : unknown);
911
+ /**
912
+ * The `page` params for the page after `list`, read from its `next` link, or `undefined` on the
913
+ * last page (or before anything has loaded). Works the same for every strategy, because the
914
+ * server's link already carries the right parameters: counts come back as numbers, cursors as
915
+ * strings, under the wire keys the strategy uses, with the menu arm's `kind` when the link names
916
+ * one. Feed the result back as the `page` of the next read:
917
+ *
918
+ * ```ts
919
+ * const next = nextPageParams(albums)
920
+ * if (next) albums = await client.albums.list({ page: next })
921
+ * ```
922
+ */
923
+ declare function nextPageParams<P extends Page>(list: {
924
+ readonly $page: P;
925
+ } | undefined): PageParamsOf<P> | undefined;
926
+ /** The `page` params for the page before `list`, from its `prev` link. See {@link nextPageParams}. */
927
+ declare function prevPageParams<P extends Page>(list: {
928
+ readonly $page: P;
929
+ } | undefined): PageParamsOf<P> | undefined;
884
930
  //#endregion
885
931
  //#region src/nested-fieldset.d.ts
886
932
  /**
@@ -901,6 +947,46 @@ type NestedFieldset = Readonly<Record<string, readonly string[]>>;
901
947
  */
902
948
  declare function nestedFieldset(listed: readonly string[] | undefined): NestedFieldset;
903
949
  //#endregion
950
+ //#region src/types.d.ts
951
+ /** The JSON:API media type. */
952
+ declare const JSON_API_MEDIA_TYPE = "application/vnd.api+json";
953
+ /** The Atomic Operations extension URI. */
954
+ declare const ATOMIC_EXT = "https://jsonapi.org/ext/atomic";
955
+ /**
956
+ * The media-type parameters a request opts into: extension URIs (`ext`) and/or profile URIs
957
+ * (`profile`). Each is rendered as a space-joined, quoted media-type parameter per RFC 6839 /
958
+ * the JSON:API spec (`ext="<uri> <uri>"`, `profile="<uri> <uri>"`).
959
+ */
960
+ interface MediaTypeParams {
961
+ ext?: readonly string[] | undefined;
962
+ profiles?: readonly string[] | undefined;
963
+ }
964
+ /**
965
+ * Compose the JSON:API media type with any opted-in `ext`/`profile` parameters. Each parameter
966
+ * is a space-joined, double-quoted URI list, in the canonical order `ext` then `profile` so the
967
+ * output is deterministic (stable for caching/assertions). Empty/absent lists are omitted; with
968
+ * neither, the bare {@link JSON_API_MEDIA_TYPE} is returned (no behaviour change for a plain
969
+ * request). Used for both `Accept` and (when a body is present) `Content-Type`.
970
+ */
971
+ declare function mediaType(params?: MediaTypeParams): string;
972
+ /**
973
+ * The media type for an Atomic Operations request/response: the JSON:API media type carrying
974
+ * the atomic `ext` parameter. Sent as both `Content-Type` and `Accept` on a `client.atomic`
975
+ * batch (per the JSON:API atomic extension).
976
+ */
977
+ declare const ATOMIC_MEDIA_TYPE: string;
978
+ /** A resource identifier: the shape a non-included but linked relation takes. */
979
+ interface ResourceIdentifier<TType extends string = string> {
980
+ type: TType;
981
+ id: string;
982
+ meta?: Record<string, unknown>;
983
+ }
984
+ /** A local id reference used inside an atomic transaction (`{ type, lid }`). */
985
+ interface LocalIdentifier<TType extends string = string> {
986
+ type: TType;
987
+ lid: string;
988
+ }
989
+ //#endregion
904
990
  //#region src/materialise.d.ts
905
991
  /** A trimmed, by-reference top-level envelope shared by every resource from one response. */
906
992
  interface DocumentEnvelope {
@@ -936,6 +1022,35 @@ interface Edge<Meta extends Record<string, unknown> = Record<string, unknown>> {
936
1022
  links?: Record<string, unknown>;
937
1023
  meta?: Meta;
938
1024
  }
1025
+ /**
1026
+ * A member a cache layer (an optimistic draft in `@haddowg/json-api-query`) predicted for a
1027
+ * relation but couldn't show yet, because no copy of it fits the slot: its identifier, and the
1028
+ * member the write supplied when it supplied more than an identifier (a row the user picked, or a
1029
+ * new resource's create input), so a placeholder can show what is known of it.
1030
+ */
1031
+ interface PendingMember<TType extends string = string> extends ResourceIdentifier<TType> {
1032
+ /** The member the write supplied, when it carried more than its identifier. */
1033
+ readonly member?: Readonly<Record<string, unknown>>;
1034
+ }
1035
+ /**
1036
+ * Where an optimistic create was placed in a list: first (`'start'`), last (`'end'`), or before
1037
+ * the member at an index of the list (of the page, in an infinite query's pages).
1038
+ */
1039
+ type PendingPlacement = 'start' | 'end' | number;
1040
+ /**
1041
+ * A create a cache layer placed in a list but couldn't show as a member, because the row it can
1042
+ * build from the create's input doesn't hold everything the list's members promise (an attribute
1043
+ * only the server sets, or an included resource that isn't cached). `input` is what the write sent
1044
+ * (`I` types it where the create input's type is known), `id` the id the row carries (the one sent,
1045
+ * or a temporary id swapped for the server's once the write succeeds), and `at` where in the list
1046
+ * it belongs.
1047
+ */
1048
+ interface PendingCreate<I = Readonly<Record<string, unknown>>, TType extends string = string> {
1049
+ readonly type: TType;
1050
+ readonly id: string;
1051
+ readonly at: PendingPlacement;
1052
+ readonly input: I;
1053
+ }
939
1054
  /** The uniform shape `$rel(name)` returns. */
940
1055
  interface RelationView {
941
1056
  data?: unknown;
@@ -961,11 +1076,24 @@ interface ResourceEnvelope {
961
1076
  * `undefined`. Read from the raw relationship, so it works when the relation carries no data.
962
1077
  */
963
1078
  $count(name: string): number | undefined;
1079
+ /**
1080
+ * `'pending'` while a cache layer holds an unconfirmed optimistic change to this resource (an
1081
+ * attribute it predicted, or a change to one of its relations), else `undefined`.
1082
+ */
1083
+ readonly $optimistic: 'pending' | undefined;
1084
+ /**
1085
+ * The members a cache layer predicted for relation `name` but couldn't show yet, because no copy
1086
+ * of them fits the slot, each carrying the member the write supplied when it supplied one. Empty
1087
+ * when there are none.
1088
+ */
1089
+ $pending(name: string): readonly PendingMember[];
964
1090
  }
965
1091
  /** Edge-local accessors carried by a materialised related VALUE (per-edge view). */
966
1092
  interface EdgeEnvelope {
967
1093
  readonly $edge: Edge | undefined;
968
1094
  readonly $pivot: Record<string, unknown> | undefined;
1095
+ /** `'pending'` while a cache layer holds an unconfirmed optimistic change to this member. */
1096
+ readonly $optimistic: 'pending' | undefined;
969
1097
  }
970
1098
  /** Relationship-level accessors carried by an augmented to-many array. */
971
1099
  interface ArrayEnvelope {
@@ -1023,6 +1151,43 @@ interface RawRelationship {
1023
1151
  links?: Record<string, unknown>;
1024
1152
  meta?: Record<string, unknown>;
1025
1153
  }
1154
+ /**
1155
+ * What a cache layer (such as `@haddowg/json-api-query`'s optimistic drafts) reports about the
1156
+ * materialised values it holds, consulted by `$optimistic`, `$pending()` and `$count`. Each call
1157
+ * gets the value the accessor was read on followed by the values it reads through to (a per-edge
1158
+ * view, then the node it views), so a layer that recorded any of them answers for all.
1159
+ *
1160
+ * @internal
1161
+ */
1162
+ interface MaterialisedOverlay {
1163
+ /** `'pending'` when the layer holds an unconfirmed change to any of `targets`. */
1164
+ optimistic(targets: readonly object[]): 'pending' | undefined;
1165
+ /** The members of relation `name` the layer predicted for `targets` but couldn't show. */
1166
+ pending(targets: readonly object[], name: string): readonly PendingMember[];
1167
+ /**
1168
+ * The creates the layer placed in the collection `targets` (an augmented array, then what it
1169
+ * reads through to) but couldn't show as members. Absent: none.
1170
+ */
1171
+ creates?(targets: readonly object[]): readonly PendingCreate[];
1172
+ /**
1173
+ * The total the collection `targets` reports, given the `raw` total its response carried
1174
+ * (`$page.meta.total`, and a top-level collection's `$meta.total`). Absent: the raw total.
1175
+ */
1176
+ total?(targets: readonly object[], raw: number): number;
1177
+ /**
1178
+ * The count `targets` report for relation `name`, given the `raw` count the response carried.
1179
+ * `name` is `undefined` when the target is the to-many array itself (its own `$count`).
1180
+ */
1181
+ count(targets: readonly object[], name: string | undefined, raw: number | undefined): number | undefined;
1182
+ }
1183
+ /**
1184
+ * Install the cache layer's {@link MaterialisedOverlay}, or remove it with `undefined`. One layer is
1185
+ * installed at a time; without one, `$optimistic` is `undefined`, `$pending()` is empty and `$count`
1186
+ * is the response's count.
1187
+ *
1188
+ * @internal
1189
+ */
1190
+ declare function setMaterialisedOverlay(next: MaterialisedOverlay | undefined): void;
1026
1191
  /**
1027
1192
  * Materialise a JSON:API document into a hydrated graph (ADR 0002):
1028
1193
  *
@@ -1049,6 +1214,38 @@ interface RawRelationship {
1049
1214
  * top-level collection read (statically-known); both override the sniff-from-`data[0]` fallback.
1050
1215
  */
1051
1216
  declare function materialise(doc: Document, ctx: MaterialiseContext, linkage?: boolean, primaryType?: string, paginatorOverride?: ResolvedPaginator | PaginatorKind): unknown;
1217
+ /**
1218
+ * Whether `value` is a top-level result `materialise` built: a resource, a collection or a linkage
1219
+ * value, including the pages `$next()` and `$prev()` re-materialise. A plain copy of one, such as
1220
+ * data that went through `JSON.stringify` on a server and back, has lost its `$`-accessors and
1221
+ * answers `false`, which is how a hydrated cache entry is told from a fresh read.
1222
+ */
1223
+ declare function isMaterialised(value: unknown): value is object;
1224
+ /** The linkage member a per-edge or identifier view is built for: its identity and its meta. */
1225
+ interface EdgeMember {
1226
+ type: string;
1227
+ id: string;
1228
+ meta?: Record<string, unknown>;
1229
+ }
1230
+ /**
1231
+ * A per-edge view over `node` for the membership `member` describes, as `materialise` builds one
1232
+ * for an included member: it copies `node`'s own enumerable members (those `pick` keeps, when
1233
+ * given; `type` and `id` always), reads its resource-level `$`-accessors through to `node`, and
1234
+ * owns its `$edge`/`$pivot` from `member.meta`. `node` may be any resource value, a materialised
1235
+ * one or a plain object; accessors it lacks read as `undefined`.
1236
+ *
1237
+ * For a cache layer placing a member in a slot (`@haddowg/json-api-query`'s optimistic drafts).
1238
+ *
1239
+ * @internal
1240
+ */
1241
+ declare function edgeViewOf(node: object, member: EdgeMember, pick?: (key: string) => boolean): object;
1242
+ /**
1243
+ * An identifier view for `member`, as `materialise` builds one for a linked member that isn't
1244
+ * included: `{ type, id, meta? }` with its `$edge`/`$pivot`.
1245
+ *
1246
+ * @internal
1247
+ */
1248
+ declare function identifierViewOf(member: EdgeMember): object;
1052
1249
  /**
1053
1250
  * A to-many relation's paginator. The relation's OWN related/relationship endpoint may
1054
1251
  * paginate differently than the related type's top-level collection (D6a), so prefer the
@@ -1062,46 +1259,6 @@ declare function relatedPaginator(relation: RelationDescriptor | undefined, ctx:
1062
1259
  /** The kind a relation's related read answers with when it sends no `page`. See {@link relatedPaginator}. */
1063
1260
  declare function relatedPaginatorKind(relation: RelationDescriptor | undefined, ctx: MaterialiseContext): PaginatorKind;
1064
1261
  //#endregion
1065
- //#region src/types.d.ts
1066
- /** The JSON:API media type. */
1067
- declare const JSON_API_MEDIA_TYPE = "application/vnd.api+json";
1068
- /** The Atomic Operations extension URI. */
1069
- declare const ATOMIC_EXT = "https://jsonapi.org/ext/atomic";
1070
- /**
1071
- * The media-type parameters a request opts into: extension URIs (`ext`) and/or profile URIs
1072
- * (`profile`). Each is rendered as a space-joined, quoted media-type parameter per RFC 6839 /
1073
- * the JSON:API spec (`ext="<uri> <uri>"`, `profile="<uri> <uri>"`).
1074
- */
1075
- interface MediaTypeParams {
1076
- ext?: readonly string[] | undefined;
1077
- profiles?: readonly string[] | undefined;
1078
- }
1079
- /**
1080
- * Compose the JSON:API media type with any opted-in `ext`/`profile` parameters. Each parameter
1081
- * is a space-joined, double-quoted URI list, in the canonical order `ext` then `profile` so the
1082
- * output is deterministic (stable for caching/assertions). Empty/absent lists are omitted; with
1083
- * neither, the bare {@link JSON_API_MEDIA_TYPE} is returned (no behaviour change for a plain
1084
- * request). Used for both `Accept` and (when a body is present) `Content-Type`.
1085
- */
1086
- declare function mediaType(params?: MediaTypeParams): string;
1087
- /**
1088
- * The media type for an Atomic Operations request/response: the JSON:API media type carrying
1089
- * the atomic `ext` parameter. Sent as both `Content-Type` and `Accept` on a `client.atomic`
1090
- * batch (per the JSON:API atomic extension).
1091
- */
1092
- declare const ATOMIC_MEDIA_TYPE: string;
1093
- /** A resource identifier: the shape a non-included but linked relation takes. */
1094
- interface ResourceIdentifier<TType extends string = string> {
1095
- type: TType;
1096
- id: string;
1097
- meta?: Record<string, unknown>;
1098
- }
1099
- /** A local id reference used inside an atomic transaction (`{ type, lid }`). */
1100
- interface LocalIdentifier<TType extends string = string> {
1101
- type: TType;
1102
- lid: string;
1103
- }
1104
- //#endregion
1105
1262
  //#region src/atomic.d.ts
1106
1263
  /**
1107
1264
  * A reference to a resource for an `update`/`remove` op: a bare identifier (or a materialised
@@ -1323,7 +1480,18 @@ type Collection<T, P = Page, M = Record<string, unknown> | undefined> = Readonly
1323
1480
  readonly $meta: M;
1324
1481
  $next(options?: NavigateOptions): Promise<Collection<T, P, M> | undefined>;
1325
1482
  $prev(options?: NavigateOptions): Promise<Collection<T, P, M> | undefined>;
1483
+ /**
1484
+ * The creates a cache layer (an optimistic draft in `@haddowg/json-api-query`) placed in this
1485
+ * list but couldn't show as members yet, each with the input it was created from, its id, and
1486
+ * where in the list it belongs. Empty when there are none. Declared optional so a hand-built
1487
+ * collection needn't carry it; a materialised one always does.
1488
+ */
1489
+ $pending?(): readonly PendingCreate<Readonly<Record<string, unknown>>, MemberTypeOf<T>>[];
1326
1490
  };
1491
+ /** The `type` of a collection's members, or `string` where they don't say. */
1492
+ type MemberTypeOf<T> = T extends {
1493
+ readonly type: infer X extends string;
1494
+ } ? X : string;
1327
1495
  /**
1328
1496
  * A to-many relationship value: a {@link Collection} that also carries `$count`, the
1329
1497
  * relationship's `meta.total` when the read counted it.
@@ -1339,6 +1507,11 @@ type RelationCollection<T, P = Page> = Collection<T, P> & RelationArrayEnvelope;
1339
1507
  interface EdgeMembers<Pivot = Record<string, unknown>, Meta extends Record<string, unknown> = Record<string, unknown>> {
1340
1508
  readonly $edge: Edge<Meta> | undefined;
1341
1509
  readonly $pivot: Pivot | undefined;
1510
+ /**
1511
+ * `'pending'` while a cache layer (an optimistic draft in `@haddowg/json-api-query`) holds an
1512
+ * unconfirmed change to this member, else `undefined`.
1513
+ */
1514
+ readonly $optimistic?: 'pending' | undefined;
1342
1515
  }
1343
1516
  /**
1344
1517
  * The resource-level `$`-accessors on a materialised resource object. `Links` types `$links`: the
@@ -1359,6 +1532,18 @@ interface ResourceAccessors<Links = ResourceLinks, Meta = Record<string, unknown
1359
1532
  */
1360
1533
  readonly $nestedFieldset: NestedFieldset;
1361
1534
  $rel(name: string): RelationView | undefined;
1535
+ /**
1536
+ * `'pending'` while a cache layer (an optimistic draft in `@haddowg/json-api-query`) holds an
1537
+ * unconfirmed change to this resource: an attribute it predicted, or a change to one of its
1538
+ * relations. `undefined` otherwise.
1539
+ */
1540
+ readonly $optimistic?: 'pending' | undefined;
1541
+ /**
1542
+ * The members a cache layer predicted for relation `name` but couldn't show yet, because no
1543
+ * cached copy of them fits the slot. Each is the member's identifier, carrying under `member`
1544
+ * what the write supplied of it when that was more than an identifier. Empty when there are none.
1545
+ */
1546
+ $pending(name: string): readonly PendingMember[];
1362
1547
  }
1363
1548
  /** Every wire type declared by the descriptor `D`. */
1364
1549
  type TypeName<D extends ApiDescriptor> = Extract<keyof D, string>;
@@ -1372,6 +1557,8 @@ type WriteOnlyRelationName<D extends ApiDescriptor, T extends TypeName<D>> = { [
1372
1557
  type ReadableRelationName<D extends ApiDescriptor, T extends TypeName<D>> = Exclude<RelationName<D, T>, WriteOnlyRelationName<D, T>>;
1373
1558
  /** The attribute object for type `T`, from the generated attributes map `A` (falls back to `{}`). */
1374
1559
  type AttributesOf<A, T> = T extends keyof A ? A[T] : Record<string, never>;
1560
+ /** The read attributes of type `T` from the read-types map `A` (the generated `Attributes`). */
1561
+ type ReadAttributesOf<A, T> = AttributesOf<A, T>;
1375
1562
  /**
1376
1563
  * The read-types map a client threads to its results: the attribute map `A`, carrying the
1377
1564
  * per-type declared links map `L` so every type that takes `A` reaches them without another
@@ -2272,17 +2459,39 @@ type LinkageRef<TType extends string> = (ResourceIdentifier<TType> & {
2272
2459
  });
2273
2460
  /** A linkage ref distributed over a (possibly polymorphic) union of related types. */
2274
2461
  type LinkageRefOf<TType extends string> = TType extends string ? LinkageRef<TType> : never;
2462
+ /** A create or an update, the writes a relation's `requiredOnCreate` and `nonNullOn` name. */
2463
+ type WriteContext = 'create' | 'update';
2464
+ /** Whether relation `R` of type `T` refuses `null` in write `C`, per its `nonNullOn`. */
2465
+ type RefusesNull<D extends ApiDescriptor, T extends TypeName<D>, R extends RelationName<D, T>, C extends WriteContext> = D[T]['relations'][R] extends {
2466
+ nonNullOn: readonly (infer On)[];
2467
+ } ? C extends On ? true : false : false;
2468
+ /**
2469
+ * Whether to-many relation `R` of type `T` refuses an empty linkage in write `C`: per its
2470
+ * `nonEmptyOn`, or on a create for a relation a create must send.
2471
+ */
2472
+ type RefusesEmpty<D extends ApiDescriptor, T extends TypeName<D>, R extends RelationName<D, T>, C extends WriteContext> = D[T]['relations'][R] extends {
2473
+ nonEmptyOn: readonly (infer On)[];
2474
+ } ? C extends On ? true : RequiredOnCreate<D, T, R, C> : RequiredOnCreate<D, T, R, C>;
2475
+ type RequiredOnCreate<D extends ApiDescriptor, T extends TypeName<D>, R extends RelationName<D, T>, C extends WriteContext> = C extends 'create' ? D[T]['relations'][R] extends {
2476
+ requiredOnCreate: true;
2477
+ } ? true : false : false;
2275
2478
  /**
2276
2479
  * The relationship VALUE accepted in a create/update input slot, by cardinality:
2277
- * to-one accepts a single ref or `null` (clear); to-many accepts an array of refs, each with an
2278
- * optional `$pivot` typed from the relation's `writePivot`.
2480
+ * to-one accepts a single ref or `null` (clear), unless the relation refuses `null` in write
2481
+ * `C`; to-many accepts an array of refs, non-empty where the relation refuses an empty one in
2482
+ * write `C`, each with an optional `$pivot` typed from the relation's `writePivot`.
2279
2483
  */
2280
- type RelationInput<D extends ApiDescriptor, T extends TypeName<D>, R extends RelationName<D, T>> = IsMany<D, T, R> extends true ? readonly WriteRef<D, T, R>[] : LinkageRefOf<RelatedType<D, T, R>> | null;
2484
+ type RelationInput<D extends ApiDescriptor, T extends TypeName<D>, R extends RelationName<D, T>, C extends WriteContext> = IsMany<D, T, R> extends true ? RefusesEmpty<D, T, R, C> extends true ? readonly [WriteRef<D, T, R>, ...WriteRef<D, T, R>[]] : readonly WriteRef<D, T, R>[] : RefusesNull<D, T, R, C> extends true ? LinkageRefOf<RelatedType<D, T, R>> : LinkageRefOf<RelatedType<D, T, R>> | null;
2485
+ /** Whether write `C` must send relation `R`: only a create, and only one `requiredOnCreate`. */
2486
+ type RequiresRelation<D extends ApiDescriptor, T extends TypeName<D>, R, C extends WriteContext> = C extends 'create' ? D[T]['relations'][R & keyof D[T]['relations']] extends {
2487
+ requiredOnCreate: true;
2488
+ } ? R : never : never;
2281
2489
  /**
2282
- * The relationship slots of type `T` as optional write input keys (one per declared relation,
2283
- * write-only ones included).
2490
+ * The relationship slots of type `T` as write input keys for write `C` (one per declared
2491
+ * relation, write-only ones included): required for a relation the write must send, optional
2492
+ * otherwise.
2284
2493
  */
2285
- type RelationInputs<D extends ApiDescriptor, T extends TypeName<D>> = { -readonly [R in keyof D[T]['relations'] as Extract<R, string>]?: RelationInput<D, T, Extract<R, string>> };
2494
+ type RelationInputs<D extends ApiDescriptor, T extends TypeName<D>, C extends WriteContext> = { -readonly [R in keyof D[T]['relations'] as Extract<RequiresRelation<D, T, R, C>, string>]-?: RelationInput<D, T, Extract<R, string>, C> } & { -readonly [R in keyof D[T]['relations'] as Exclude<Extract<R, string>, RequiresRelation<D, T, R, C>>]?: RelationInput<D, T, Extract<R, string>, C> };
2286
2495
  /** The `{ create; update }` write-attribute pair for type `T` (or an open pair when `T` is absent from `W`). */
2287
2496
  type WritePair<W, T> = T extends keyof W ? W[T] : {
2288
2497
  create: Record<string, unknown>;
@@ -2312,14 +2521,14 @@ type CreateId<D extends ApiDescriptor, T extends TypeName<D>> = D[T]['clientId']
2312
2521
  * slots, plus an `id` keyed by the client-id policy. The runtime builds the JSON:API
2313
2522
  * envelope (routing keys to attributes/relationships via the descriptor).
2314
2523
  */
2315
- type CreateInput<D extends ApiDescriptor, W, T extends TypeName<D>, Op extends 'create' | 'atomicCreate' = 'create'> = CreateAttributesOf<W, T> & RelationInputs<D, T> & CreateId<D, T> & {
2524
+ type CreateInput<D extends ApiDescriptor, W, T extends TypeName<D>, Op extends 'create' | 'atomicCreate' = 'create'> = CreateAttributesOf<W, T> & RelationInputs<D, T, 'create'> & CreateId<D, T> & {
2316
2525
  /** The resource object's `meta`, sent as `data.meta`. */$meta?: ResourceWriteMeta<D, T, Op>;
2317
2526
  };
2318
2527
  /**
2319
2528
  * The flat input to `client.<type>.id(id).update(patch)`: the type's update attributes (all
2320
2529
  * optional) + relation slots. The id rides the handle, never the input.
2321
2530
  */
2322
- type UpdateInput<D extends ApiDescriptor, W, T extends TypeName<D>, Op extends 'update' | 'atomicUpdate' = 'update'> = UpdateAttributesOf<W, T> & RelationInputs<D, T> & {
2531
+ type UpdateInput<D extends ApiDescriptor, W, T extends TypeName<D>, Op extends 'update' | 'atomicUpdate' = 'update'> = UpdateAttributesOf<W, T> & RelationInputs<D, T, 'update'> & {
2323
2532
  /** The resource object's `meta`, sent as `data.meta`. */$meta?: ResourceWriteMeta<D, T, Op>;
2324
2533
  };
2325
2534
  /**
@@ -3077,6 +3286,8 @@ interface ExecutedResponse {
3077
3286
  status: number;
3078
3287
  headers: Record<string, string>;
3079
3288
  document: Document | undefined;
3289
+ /** The stamp taken as the request started; the document carries it too. */
3290
+ stamp: number;
3080
3291
  }
3081
3292
  /**
3082
3293
  * Execute a request as {@link execute} does, keeping the response's status and headers. With
@@ -3190,5 +3401,5 @@ declare function assertJsonApiDocument(body: unknown): asserts body is Document;
3190
3401
  */
3191
3402
  declare function validateDocument(body: Document, validator: ResolvedValidator, fields?: Readonly<Record<string, readonly string[]>>): void;
3192
3403
  //#endregion
3193
- export { DocumentMeta as $, LinkObject as $n, PaginatorRole as $r, ResourceObjectView as $t, TransportResponse as A, AtomicOperationArgs as An, ActionDescriptor as Ar, RelatedIncludedType as At, Client as B, runAtomic as Bn, ClientIdPolicy as Br, RelationPageParams as Bt, ClientOptions as C, ActionLocation as Cn, Accepted as Cr, NestedFieldsetMember as Ct, JsonApiTransport as D, AtomicCreateInput as Dn, parseRetryAfter as Dr, ReadResult as Dt, createClient as E, AtomicCreateHandle as En, isAccepted as Er, PivotInput as Et, ActionCallOptions as F, AtomicRelationshipRecorder as Fn, AdditionalMembersDescriptor as Fr, RelatedQueryRelation as Ft, CountedRelationName as G, MediaTypeParams as Gn, InputMedia as Gr, RelationshipAccessor as Gt, CollectionMeta as H, ATOMIC_MEDIA_TYPE as Hn, DocumentMetaDescriptor as Hr, RelationReadQuery as Ht, ActionsAccessor as I, AtomicResult as In, ApiDescriptor as Ir, RelatedReadRelatedQuery as It, DefaultActionTypes as J, ArrayEnvelope as Jn, MenuDescriptor as Jr, RequiresRequestMeta as Jt, CreateInput as K, ResourceIdentifier as Kn, InputMediaKind as Kr, RelationshipMembers as Kt, AtomicResultOf as L, AtomicResults as Ln, ApiExamples as Lr, RelationCollection as Lt, AcceptedJob as M, AtomicRef as Mn, ActionLocationDescriptor as Mr, RelatedQuery as Mt, AcceptedMeta as N, AtomicRelationshipArgs as Nn, ActionOutput as Nr, RelatedQueryEntry as Nt, TransportRawBody as O, AtomicDeleteHandle as On, AcceptedDescriptor as Or, ReadableRelationName as Ot, AcceptedOf as P, AtomicRelationshipHandle as Pn, ActionScope as Pr, RelatedQueryParam as Pt, DeleteResult as Q, Link as Qn, PaginatorKind as Qr, ResourceMetaOf as Qt, BinaryBody as R, AtomicUpdateHandle as Rn, AtomicDescriptor as Rr, RelationFilterQuery as Rt, serializeQuery as S, WriteResult as Sn, resolvePaginator as Sr, MutationVerb as St, HeadersInit as T, readActionLocation as Tn, PollTimeoutError as Tr, OptionsArg as Tt, CountAccessor as U, JSON_API_MEDIA_TYPE as Un, DocumentMetaOperation as Ur, RelationRequestMetaOf as Ut, Collection as V, ATOMIC_EXT as Vn, CountableDescriptor as Vr, RelationPaginator as Vt, CountToken as W, LocalIdentifier as Wn, FilterFamilyDescriptor as Wr, RelationSortQuery as Wt, DefaultWriteAttributes as X, Edge as Xn, OperationExamples as Xr, ResourceCountToken as Xt, DefaultAttributes as Y, DocumentEnvelope as Yn, MetaLiteral as Yr, ResourceAccessors as Yt, DeleteArgs as Z, EdgeEnvelope as Zn, PaginatorDescriptor as Zr, ResourceHandle as Zt, RawResponseType as _, WaitedWriteResult as _n, PageOf as _r, LooseRelatedQueryEntry as _t, ValidationOption as a, RelatedQueryOperation as ai, SortQuery as an, ResourceLinks as ar, FilterQuery as at, executeRaw as b, WritableRelationName as bn, ResolvedPaginator as br, MetaOption as bt, assertJsonApiDocument as c, RequestMetaOperation as ci, TypeAccessor as cn, relatedPaginatorKind as cr, IncludePath as ct, sparseSchemas as d, ResourceExamples as di, TypedRelatedReadQuery as dn, CANONICAL_PAGE_KEYS as dr, IncludedType as dt, PaginatorStrategy as ei, ResourceWriteMeta as en, MaterialiseContext as er, EdgeMembers as et, validateDocument as f, ResourceMetaDescriptor as fi, TypedRelationReadQuery as fn, ExactPageParams as fr, IsSingleton as ft, JsonApiRequest as g, WaitValue as gn, PageMeta as gr, LooseRelatedQuery as gt, JsonApiContext as h, isPolymorphic as hi, WaitOptions as hn, PageLinks as hr, ListPageParams as ht, ValidationContext as i, RelatedQueryDescriptor as ii, SingletonUpdateInput as in, ResourceEnvelope as ir, FilterKey as it, fetchTransport as j, AtomicRecorder as jn, ActionInput as jr, RelatedMeta as jt, TransportRequest as k, AtomicHandle as kn, AcceptedOperation as kr, RelatedIncludedResource as kt, resolveValidator as l, ResourceCountOperation as li, TypeName as ln, NestedFieldset as lr, IncludedRelations as lt, ExecutedResponse as m, StrategyDescriptor as mi, UpdateMethod as mn, PageKeys as mr, ListFilterMember as mt, SchemaMap as n, RawMediaKind as ni, SingleReadQuery as nn, RelationArrayEnvelope as nr, FieldSelectionMap as nt, Validator as o, RelationDescriptor as oi, SortToken as on, materialise as or, HydratedMember as ot, Document as p, SortFamilyDescriptor as pi, UpdateInput as pn, Page as pr, LinkageRef as pt, CreateMethod as q, mediaType as qn, MediaExamples as qr, RequestMetaOf as qt, ValidationConfig as r, RawOutputMedia as ri, SingletonAccessor as rn, RelationView as rr, FieldsMap as rt, WireResource as s, RelationMutations as si, TakesVerb as sn, relatedPaginator as sr, IdentifierMember as st, ResolvedValidator as t, PivotDescriptor as ti, ResourceWriteOperation as tn, NavigateOptions as tr, ErrorCodeOf as tt, sparseSchema as u, ResourceDescriptor as ui, TypedReadQuery as un, nestedFieldset as ur, IncludedResource as ut, ReadQuery as v, WithDocumentMeta as vn, PageParams as vr, MemberName as vt, HANDLE_RESERVED as w, isActionLocation as wn, PollOptions as wr, OperationMeta as wt, executeResponse as x, WriteOptions as xn, TypedPage as xr, MutationMetaOf as xt, execute as y, WithLinks as yn, PageParamsOf as yr, MetaObject as yt, BinaryResponseType as z, AtomicUpdateInput as zn, Cardinality as zr, RelationName as zt };
3194
- //# sourceMappingURL=validate-Dj6pkoNM.d.mts.map
3404
+ export { DeleteResult as $, MaterialiseContext as $n, ApiExamples as $r, ResourceAccessors as $t, TransportResponse as A, StrategyDescriptor as Ai, readActionLocation as An, PageMeta as Ar, ReadAttributesOf as At, Client as B, AtomicRelationshipRecorder as Bn, PollOptions as Br, RelatedReadRelatedQuery as Bt, ClientOptions as C, RelationMutations as Ci, WithLinks as Cn, NestedFieldset as Cr, MutationMetaOf as Ct, JsonApiTransport as D, ResourceExamples as Di, WriteResult as Dn, Page as Dr, OptionsArg as Dt, createClient as E, ResourceDescriptor as Ei, WritePivotOf as En, ExactPageParams as Er, OperationMeta as Et, ActionCallOptions as F, AtomicOperationArgs as Fn, TypedPage as Fr, RelatedMeta as Ft, CountedRelationName as G, runAtomic as Gn, AcceptedOperation as Gr, RelationPaginator as Gt, CollectionMeta as H, AtomicResults as Hn, isAccepted as Hr, RelationFilterQuery as Ht, ActionsAccessor as I, AtomicRecorder as In, nextPageParams as Ir, RelatedQuery as It, CreateMethod as J, Edge as Jn, ActionLocationDescriptor as Jr, RelationSortQuery as Jt, CreateAttributesOf as K, ArrayEnvelope as Kn, ActionDescriptor as Kr, RelationReadQuery as Kt, AtomicResultOf as L, AtomicRef as Ln, prevPageParams as Lr, RelatedQueryEntry as Lt, AcceptedJob as M, AtomicCreateInput as Mn, PageParams as Mr, ReadableRelationName as Mt, AcceptedMeta as N, AtomicDeleteHandle as Nn, PageParamsOf as Nr, RelatedIncludedResource as Nt, TransportRawBody as O, ResourceMetaDescriptor as Oi, ActionLocation as On, PageKeys as Or, PivotFieldsOf as Ot, AcceptedOf as P, AtomicHandle as Pn, ResolvedPaginator as Pr, RelatedIncludedType as Pt, DeleteArgs as Q, LinkObject as Qn, ApiDescriptor as Qr, RequiresRequestMeta as Qt, BinaryBody as R, AtomicRelationshipArgs as Rn, resolvePaginator as Rr, RelatedQueryParam as Rt, serializeQuery as S, RelationDescriptor as Si, WithDocumentMeta as Sn, mediaType as Sr, MetaOption as St, HeadersInit as T, ResourceCountOperation as Ti, WriteOptions as Tn, CANONICAL_PAGE_KEYS as Tr, NestedFieldsetMember as Tt, CountAccessor as U, AtomicUpdateHandle as Un, parseRetryAfter as Ur, RelationName as Ut, Collection as V, AtomicResult as Vn, PollTimeoutError as Vr, RelationCollection as Vt, CountToken as W, AtomicUpdateInput as Wn, AcceptedDescriptor as Wr, RelationPageParams as Wt, DefaultAttributes as X, EdgeMember as Xn, ActionScope as Xr, RelationshipMembers as Xt, DefaultActionTypes as Y, EdgeEnvelope as Yn, ActionOutput as Yr, RelationshipAccessor as Yt, DefaultWriteAttributes as Z, Link as Zn, AdditionalMembersDescriptor as Zr, RequestMetaOf as Zt, RawResponseType as _, PivotDescriptor as _i, UpdateInput as _n, ATOMIC_MEDIA_TYPE as _r, LooseRelatedQuery as _t, ValidationOption as a, DocumentMetaOperation as ai, ResourceWriteOperation as an, RelationArrayEnvelope as ar, FilterKey as at, executeRaw as b, RelatedQueryDescriptor as bi, WaitValue as bn, MediaTypeParams as br, MemberTypeOf as bt, assertJsonApiDocument as c, InputMediaKind as ci, SingletonUpdateInput as cn, ResourceLinks as cr, IdentifierMember as ct, sparseSchemas as d, MetaLiteral as di, TakesVerb as dn, isMaterialised as dr, IncludedResource as dt, AtomicDescriptor as ei, ResourceCountToken as en, MaterialisedOverlay as er, DocumentMeta as et, validateDocument as f, OperationExamples as fi, TypeAccessor as fn, materialise as fr, IncludedType as ft, JsonApiRequest as g, PaginatorStrategy as gi, TypedRelationReadQuery as gn, ATOMIC_EXT as gr, ListPageParams as gt, JsonApiContext as h, PaginatorRole as hi, TypedRelatedReadQuery as hn, setMaterialisedOverlay as hr, ListFilterMember as ht, ValidationContext as i, DocumentMetaDescriptor as ii, ResourceWriteMeta as in, PendingPlacement as ir, FieldsMap as it, fetchTransport as j, isPolymorphic as ji, AtomicCreateHandle as jn, PageOf as jr, ReadResult as jt, TransportRequest as k, SortFamilyDescriptor as ki, isActionLocation as kn, PageLinks as kr, PivotInput as kt, resolveValidator as l, MediaExamples as li, SortQuery as ln, edgeViewOf as lr, IncludePath as lt, ExecutedResponse as m, PaginatorKind as mi, TypedReadQuery as mn, relatedPaginatorKind as mr, LinkageRef as mt, SchemaMap as n, ClientIdPolicy as ni, ResourceMetaOf as nn, PendingCreate as nr, ErrorCodeOf as nt, Validator as o, FilterFamilyDescriptor as oi, SingleReadQuery as on, RelationView as or, FilterQuery as ot, Document as p, PaginatorDescriptor as pi, TypeName as pn, relatedPaginator as pr, IsSingleton as pt, CreateInput as q, DocumentEnvelope as qn, ActionInput as qr, RelationRequestMetaOf as qt, ValidationConfig as r, CountableDescriptor as ri, ResourceObjectView as rn, PendingMember as rr, FieldSelectionMap as rt, WireResource as s, InputMedia as si, SingletonAccessor as sn, ResourceEnvelope as sr, HydratedMember as st, ResolvedValidator as t, Cardinality as ti, ResourceHandle as tn, NavigateOptions as tr, EdgeMembers as tt, sparseSchema as u, MenuDescriptor as ui, SortToken as un, identifierViewOf as ur, IncludedRelations as ut, ReadQuery as v, RawMediaKind as vi, UpdateMethod as vn, JSON_API_MEDIA_TYPE as vr, LooseRelatedQueryEntry as vt, HANDLE_RESERVED as w, RequestMetaOperation as wi, WritableRelationName as wn, nestedFieldset as wr, MutationVerb as wt, executeResponse as x, RelatedQueryOperation as xi, WaitedWriteResult as xn, ResourceIdentifier as xr, MetaObject as xt, execute as y, RawOutputMedia as yi, WaitOptions as yn, LocalIdentifier as yr, MemberName as yt, BinaryResponseType as z, AtomicRelationshipHandle as zn, Accepted as zr, RelatedQueryRelation as zt };
3405
+ //# sourceMappingURL=validate-ugcQVpb0.d.cts.map