@clipboard-health/contract-core 4.6.16 → 4.7.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/README.md CHANGED
@@ -7,6 +7,8 @@ Shared Zod schemas for Clipboard's contracts.
7
7
  - [Install](#install)
8
8
  - [Usage](#usage)
9
9
  - [Zod schemas](#zod-schemas)
10
+ - [Typed JSON:API error extensions](#typed-jsonapi-error-extensions)
11
+ - [Custom error documents](#custom-error-documents)
10
12
  - [Local development commands](#local-development-commands)
11
13
 
12
14
  ## Install
@@ -17,6 +19,111 @@ npm install @clipboard-health/contract-core
17
19
 
18
20
  ## Usage
19
21
 
22
+ ### Typed JSON:API error extensions
23
+
24
+ `apiError` and `apiErrors` keep their existing required fields and strip undeclared members.
25
+ Opt in to `source` and typed per-error `meta` with Zod's `.extend()`. `apiErrorsWith(errorSchema)`
26
+ builds a document from that error schema, retaining the default limit of 0–100 errors. Extend the
27
+ document separately for top-level `meta`; metadata stays at the location its consumer reads.
28
+
29
+ ```ts
30
+ import { apiError, apiErrorsWith, apiErrorSource } from "@clipboard-health/contract-core";
31
+ import { z } from "zod";
32
+
33
+ const stepUpErrors = apiErrorsWith(
34
+ apiError.extend({
35
+ source: apiErrorSource.optional(),
36
+ meta: z.object({ stepUpMethod: z.enum(["otp", "password"]) }),
37
+ }),
38
+ );
39
+
40
+ const documentErrors = apiErrorsWith(
41
+ apiError.extend({
42
+ source: apiErrorSource.optional(),
43
+ meta: z.object({ reason: z.literal("homeHealthBookingRequired") }).optional(),
44
+ }),
45
+ ).extend({
46
+ meta: z.object({ unmetPrerequisites: z.array(z.string()).min(1) }).optional(),
47
+ });
48
+
49
+ type StepUpErrorDocument = z.infer<typeof stepUpErrors>;
50
+ type DocumentErrorDocument = z.infer<typeof documentErrors>;
51
+ ```
52
+
53
+ `apiErrorSource` declares optional string `pointer`, `parameter`, and `header` members. An empty
54
+ pointer addresses the whole document. Unknown source and metadata members are still stripped.
55
+ Required versus optional metadata, error-code narrowing, and stricter array bounds belong to the
56
+ route's schema. Use `.optional()` explicitly for optional metadata.
57
+
58
+ For example, admin uses source pointers to label invalid fields, home-health clients read
59
+ `errors[].meta.stepUpMethod`, and documents clients read `errors[].meta.reason` and top-level
60
+ `meta.unmetPrerequisites`. Ordinary routes keep using `apiErrors` without accepting these extensions.
61
+ Source extensions also accept the source objects produced by `ServiceError.toJsonApi()`; no runtime
62
+ dependency on `ServiceError` is needed. Declaring an extension does not itself install a server
63
+ renderer: that renderer must preserve the declared source and metadata instead of parsing them
64
+ through bare `apiErrors` again.
65
+
66
+ ### Custom error documents
67
+
68
+ `customError({ status, body })` is an escape hatch for a consumer that needs an existing body that
69
+ cannot be represented by typed JSON:API extensions. Prefer `apiErrors` or `apiErrorsWith` otherwise.
70
+ For example, the payout-settings PATCH consumer reads a top-level `message` alongside JSON:API
71
+ errors:
72
+
73
+ ```ts
74
+ import { apiErrors, customError } from "@clipboard-health/contract-core";
75
+ import { z } from "zod";
76
+
77
+ const payoutSettingsError = customError({
78
+ status: 422,
79
+ body: apiErrors.extend({ message: z.string() }),
80
+ });
81
+
82
+ // In an oRPC contract's error map:
83
+ const errors = { UNPROCESSABLE_CONTENT: payoutSettingsError };
84
+
85
+ // Handler error data has this envelope; it is not the HTTP response body:
86
+ const data = {
87
+ body: { message: "Payout settings cannot be updated", errors: [] },
88
+ headers: { "retry-after": "30" },
89
+ };
90
+ ```
91
+
92
+ The returned `{ status, data }` declaration implements Standard Schema v1. Its validator checks the
93
+ `{ body, headers? }` envelope and the body schema synchronously, so body schemas can't use async
94
+ refinements; Zod throws if they do. Issue paths are relative to the input, such as
95
+ `["body", "message"]`. On success it
96
+ marks a response containing the **original body**, not Zod's parsed output: extra fields, key order,
97
+ and values survive; transforms, coercions, defaults, and stripping are not applied to that body.
98
+ This is deliberately not a sanitizing parser. Only put caller-safe data in the original body and
99
+ trusted, string-valued response headers in `headers`. Status validation remains the transport's
100
+ responsibility, matching backend-main's existing helper.
101
+
102
+ Server and documentation adapters use the package-root readers:
103
+
104
+ - `getCustomErrorResponse({ data })` returns `{ body, headers? }` only for a marked, validated
105
+ response; ordinary `{ body }` data is not recognized. Render this body with the declared HTTP
106
+ status only after the transport has classified the error as declared and valid. Do not send
107
+ undeclared or invalid errors through this escape hatch.
108
+ - `getCustomErrorBodySchema({ schema })` returns the original Zod body schema for a custom
109
+ declaration's `data`, so an OpenAPI generator documents the actual HTTP body rather than the
110
+ transport envelope. Other schemas return `undefined`.
111
+
112
+ Both readers use the versioned `Symbol.for("@clipboard-health/contract-core/custom-error/v1")`
113
+ protocol, with `"schema"` and `"response"` brands, rather than class identity. Recognition and repeated
114
+ validation work across duplicate package instances and the CommonJS and ESM builds in one JavaScript
115
+ realm. The symbol is an in-process interoperability marker, not an authentication boundary; serialized
116
+ JSON is not a marked response. Backend-main can re-export these three helpers without changing
117
+ their signatures.
118
+
119
+ The brand is set at runtime only. Public types are the exported `CustomErrorDeclaration`,
120
+ `CustomErrorBodySchema`, `CustomErrorResponse`, and `CustomErrorDocument` interfaces, so a
121
+ consumer can emit declarations for an exported contract that uses `customError`.
122
+
123
+ These APIs are tested with Zod 3.25.76, not Zod 4; other Zod versions are not covered by this
124
+ validation suite. The existing Zod 3 peer range is unchanged. The package root has no Node.js,
125
+ Nest, Express, or oRPC runtime imports; `@standard-schema/spec` is imported only as a type.
126
+
20
127
  ### Zod schemas
21
128
 
22
129
  #### Comma-separated array schema
package/esm/src/index.js CHANGED
@@ -1,2 +1,3 @@
1
1
  export * from "./lib/schemas/index.js";
2
+ export { customError, getCustomErrorBodySchema, getCustomErrorResponse, } from "./lib/customError.js";
2
3
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../packages/contract-core/src/index.ts"],"names":[],"mappings":"AAAA,cAAc,eAAe,CAAC"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../packages/contract-core/src/index.ts"],"names":[],"mappings":"AAAA,cAAc,eAAe,CAAC;AAC9B,OAAO,EACL,WAAW,EACX,wBAAwB,EACxB,sBAAsB,GAKvB,MAAM,mBAAmB,CAAC"}
@@ -0,0 +1,82 @@
1
+ import { z } from "zod";
2
+ /**
3
+ * Marks custom error schemas and responses across copies of this package, such as its CommonJS and
4
+ * ESM builds loaded together. It's set at runtime only, so public types never name it.
5
+ */
6
+ const CUSTOM_ERROR = Symbol.for("@clipboard-health/contract-core/custom-error/v1");
7
+ const errorDocumentSchema = z.object({
8
+ body: z.unknown(),
9
+ headers: z.record(z.string()).optional(),
10
+ });
11
+ export function customError(params) {
12
+ const { status, body } = params;
13
+ return { status, data: createBodySchema(body) };
14
+ }
15
+ export function getCustomErrorResponse(params) {
16
+ const { data } = params;
17
+ return isCustomErrorResponse(data) ? data.document : undefined;
18
+ }
19
+ export function getCustomErrorBodySchema(params) {
20
+ const { schema } = params;
21
+ return isCustomErrorBodySchema(schema) ? schema.bodySchema : undefined;
22
+ }
23
+ function createBodySchema(bodySchema) {
24
+ return brand({
25
+ bodySchema,
26
+ "~standard": {
27
+ version: 1,
28
+ vendor: "clipboard-custom-error",
29
+ validate: (input) => {
30
+ const isResponse = isCustomErrorResponse(input);
31
+ // Issue paths are relative to the validated input, which wraps a marked response's fields.
32
+ const documentPath = isResponse ? ["document"] : [];
33
+ const document = errorDocumentSchema.safeParse(isResponse ? input.document : input);
34
+ if (!document.success) {
35
+ return {
36
+ issues: prefixIssuePaths({ issues: document.error.issues, prefix: documentPath }),
37
+ };
38
+ }
39
+ const result = bodySchema.safeParse(document.data.body);
40
+ if (!result.success) {
41
+ return {
42
+ issues: prefixIssuePaths({
43
+ issues: result.error.issues,
44
+ prefix: [...documentPath, "body"],
45
+ }),
46
+ };
47
+ }
48
+ return {
49
+ value: createResponse({
50
+ body: document.data.body,
51
+ ...(document.data.headers ? { headers: document.data.headers } : {}),
52
+ }),
53
+ };
54
+ },
55
+ },
56
+ }, "schema");
57
+ }
58
+ function createResponse(document) {
59
+ return brand({ document }, "response");
60
+ }
61
+ function brand(value, kind) {
62
+ return Object.defineProperty(value, CUSTOM_ERROR, { value: kind, enumerable: false });
63
+ }
64
+ function prefixIssuePaths(params) {
65
+ const { issues, prefix } = params;
66
+ return issues.map((issue) => ({ ...issue, path: [...prefix, ...issue.path] }));
67
+ }
68
+ function isCustomErrorResponse(data) {
69
+ return (typeof data === "object" &&
70
+ data !== null &&
71
+ CUSTOM_ERROR in data &&
72
+ data[CUSTOM_ERROR] === "response" &&
73
+ "document" in data);
74
+ }
75
+ function isCustomErrorBodySchema(schema) {
76
+ return (typeof schema === "object" &&
77
+ schema !== null &&
78
+ CUSTOM_ERROR in schema &&
79
+ schema[CUSTOM_ERROR] === "schema" &&
80
+ "bodySchema" in schema);
81
+ }
82
+ //# sourceMappingURL=customError.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"customError.js","sourceRoot":"","sources":["../../../../../../packages/contract-core/src/lib/customError.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB;;;GAGG;AACH,MAAM,YAAY,GAAG,MAAM,CAAC,GAAG,CAAC,iDAAiD,CAAC,CAAC;AA0BnF,MAAM,mBAAmB,GAAG,CAAC,CAAC,MAAM,CAAC;IACnC,IAAI,EAAE,CAAC,CAAC,OAAO,EAAE;IACjB,OAAO,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,CAAC,QAAQ,EAAE;CACzC,CAAC,CAAC;AAEH,MAAM,UAAU,WAAW,CAAwC,MAGlE;IACC,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,GAAG,MAAM,CAAC;IAChC,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,gBAAgB,CAAC,IAAI,CAAC,EAAE,CAAC;AAClD,CAAC;AAED,MAAM,UAAU,sBAAsB,CAAC,MAAyB;IAC9D,MAAM,EAAE,IAAI,EAAE,GAAG,MAAM,CAAC;IACxB,OAAO,qBA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,CAC9B,MAAe;IAEf,OAAO,CACL,OAAO,MAAM,KAAK,QAAQ;QAC1B,MAAM,KAAK,IAAI;QACf,YAAY,IAAI,MAAM;QACtB,MAAM,CAAC,YAAY,CAAC,KAAK,QAAQ;QACjC,YAAY,IAAI,MAAM,CACvB,CAAC;AACJ,CAAC"}
@@ -16,4 +16,14 @@ export const apiError = z.object({
16
16
  export const apiErrors = z.object({
17
17
  errors: apiError.array().min(0).max(100),
18
18
  });
19
+ export const apiErrorSource = z.object({
20
+ pointer: z.string().optional(),
21
+ parameter: z.string().optional(),
22
+ header: z.string().optional(),
23
+ });
24
+ export function apiErrorsWith(error) {
25
+ return apiErrors.extend({
26
+ errors: error.array().min(0).max(100),
27
+ });
28
+ }
19
29
  //# sourceMappingURL=apiError.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"apiError.js","sourceRoot":"","sources":["../../../../../../../packages/contract-core/src/lib/schemas/apiError.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAElD;;GAEG;AACH,MAAM,CAAC,MAAM,QAAQ,GAAG,CAAC,CAAC,MAAM,CAAC;IAC/B,IAAI,EAAE,cAAc;IACpB,MAAM,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;IAC7B,EAAE,EAAE,cAAc;IAClB,MAAM,EAAE,cAAc;IACtB,KAAK,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;CAC7B,CAAC,CAAC;AAEH;;GAEG;AACH,MAAM,CAAC,MAAM,SAAS,GAAG,CAAC,CAAC,MAAM,CAAC;IAChC,MAAM,EAAE,QAAQ,CAAC,KAAK,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC;CACzC,CAAC,CAAC"}
1
+ {"version":3,"file":"apiError.js","sourceRoot":"","sources":["../../../../../../../packages/contract-core/src/lib/schemas/apiError.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAElD;;GAEG;AACH,MAAM,CAAC,MAAM,QAAQ,GAAG,CAAC,CAAC,MAAM,CAAC;IAC/B,IAAI,EAAE,cAAc;IACpB,MAAM,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;IAC7B,EAAE,EAAE,cAAc;IAClB,MAAM,EAAE,cAAc;IACtB,KAAK,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;CAC7B,CAAC,CAAC;AAEH;;GAEG;AACH,MAAM,CAAC,MAAM,SAAS,GAAG,CAAC,CAAC,MAAM,CAAC;IAChC,MAAM,EAAE,QAAQ,CAAC,KAAK,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC;CACzC,CAAC,CAAC;AAEH,MAAM,CAAC,MAAM,cAAc,GAAG,CAAC,CAAC,MAAM,CAAC;IACrC,OAAO,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;IAC9B,SAAS,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;IAChC,MAAM,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;CAC9B,CAAC,CAAC;AAEH,MAAM,UAAU,aAAa,CAA0C,KAAkB;IACvF,OAAO,SAAS,CAAC,MAAM,CAAC;QACtB,MAAM,EAAE,KAAK,CAAC,KAAK,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC;KACtC,CAAC,CAAC;AACL,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@clipboard-health/contract-core",
3
- "version": "4.6.16",
3
+ "version": "4.7.0",
4
4
  "description": "Shared Zod schemas for Clipboard's contracts.",
5
5
  "keywords": [
6
6
  "contract",
@@ -23,6 +23,7 @@
23
23
  "access": "public"
24
24
  },
25
25
  "dependencies": {
26
+ "@standard-schema/spec": "1.1.0",
26
27
  "tslib": "2.8.1"
27
28
  },
28
29
  "devDependencies": {
package/src/index.d.ts CHANGED
@@ -1 +1,2 @@
1
1
  export * from "./lib/schemas";
2
+ export { customError, getCustomErrorBodySchema, getCustomErrorResponse, type CustomErrorBodySchema, type CustomErrorDeclaration, type CustomErrorDocument, type CustomErrorResponse, } from "./lib/customError";
package/src/index.js CHANGED
@@ -1,5 +1,10 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getCustomErrorResponse = exports.getCustomErrorBodySchema = exports.customError = void 0;
3
4
  const tslib_1 = require("tslib");
4
5
  tslib_1.__exportStar(require("./lib/schemas"), exports);
6
+ var customError_1 = require("./lib/customError");
7
+ Object.defineProperty(exports, "customError", { enumerable: true, get: function () { return customError_1.customError; } });
8
+ Object.defineProperty(exports, "getCustomErrorBodySchema", { enumerable: true, get: function () { return customError_1.getCustomErrorBodySchema; } });
9
+ Object.defineProperty(exports, "getCustomErrorResponse", { enumerable: true, get: function () { return customError_1.getCustomErrorResponse; } });
5
10
  //# sourceMappingURL=index.js.map
package/src/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../packages/contract-core/src/index.ts"],"names":[],"mappings":";;;AAAA,wDAA8B"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../packages/contract-core/src/index.ts"],"names":[],"mappings":";;;;AAAA,wDAA8B;AAC9B,iDAQ2B;AAPzB,0GAAA,WAAW,OAAA;AACX,uHAAA,wBAAwB,OAAA;AACxB,qHAAA,sBAAsB,OAAA"}
@@ -0,0 +1,30 @@
1
+ import type { StandardSchemaV1 } from "@standard-schema/spec";
2
+ import { z } from "zod";
3
+ /** A custom error response: its original body and optional response headers. */
4
+ export interface CustomErrorDocument<Body = unknown> {
5
+ body: Body;
6
+ headers?: Record<string, string>;
7
+ }
8
+ /** The validated value of a custom error schema. Read it with `getCustomErrorResponse`. */
9
+ export interface CustomErrorResponse {
10
+ readonly document: CustomErrorDocument;
11
+ }
12
+ /** The Standard Schema a `customError` declaration validates its error data with. */
13
+ export interface CustomErrorBodySchema<BodySchema extends z.ZodType<unknown>> extends StandardSchemaV1<CustomErrorDocument<z.input<BodySchema>>, CustomErrorResponse> {
14
+ readonly bodySchema: BodySchema;
15
+ }
16
+ /** A custom error declaration, for a contract's error map. */
17
+ export interface CustomErrorDeclaration<BodySchema extends z.ZodType<unknown>> {
18
+ status: number;
19
+ data: CustomErrorBodySchema<BodySchema>;
20
+ }
21
+ export declare function customError<BodySchema extends z.ZodType<unknown>>(params: {
22
+ status: number;
23
+ body: BodySchema;
24
+ }): CustomErrorDeclaration<BodySchema>;
25
+ export declare function getCustomErrorResponse(params: {
26
+ data: unknown;
27
+ }): CustomErrorDocument | undefined;
28
+ export declare function getCustomErrorBodySchema(params: {
29
+ schema: unknown;
30
+ }): z.ZodType<unknown> | undefined;
@@ -0,0 +1,87 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.customError = customError;
4
+ exports.getCustomErrorResponse = getCustomErrorResponse;
5
+ exports.getCustomErrorBodySchema = getCustomErrorBodySchema;
6
+ const zod_1 = require("zod");
7
+ /**
8
+ * Marks custom error schemas and responses across copies of this package, such as its CommonJS and
9
+ * ESM builds loaded together. It's set at runtime only, so public types never name it.
10
+ */
11
+ const CUSTOM_ERROR = Symbol.for("@clipboard-health/contract-core/custom-error/v1");
12
+ const errorDocumentSchema = zod_1.z.object({
13
+ body: zod_1.z.unknown(),
14
+ headers: zod_1.z.record(zod_1.z.string()).optional(),
15
+ });
16
+ function customError(params) {
17
+ const { status, body } = params;
18
+ return { status, data: createBodySchema(body) };
19
+ }
20
+ function getCustomErrorResponse(params) {
21
+ const { data } = params;
22
+ return isCustomErrorResponse(data) ? data.document : undefined;
23
+ }
24
+ function getCustomErrorBodySchema(params) {
25
+ const { schema } = params;
26
+ return isCustomErrorBodySchema(schema) ? schema.bodySchema : undefined;
27
+ }
28
+ function createBodySchema(bodySchema) {
29
+ return brand({
30
+ bodySchema,
31
+ "~standard": {
32
+ version: 1,
33
+ vendor: "clipboard-custom-error",
34
+ validate: (input) => {
35
+ const isResponse = isCustomErrorResponse(input);
36
+ // Issue paths are relative to the validated input, which wraps a marked response's fields.
37
+ const documentPath = isResponse ? ["document"] : [];
38
+ const document = errorDocumentSchema.safeParse(isResponse ? input.document : input);
39
+ if (!document.success) {
40
+ return {
41
+ issues: prefixIssuePaths({ issues: document.error.issues, prefix: documentPath }),
42
+ };
43
+ }
44
+ const result = bodySchema.safeParse(document.data.body);
45
+ if (!result.success) {
46
+ return {
47
+ issues: prefixIssuePaths({
48
+ issues: result.error.issues,
49
+ prefix: [...documentPath, "body"],
50
+ }),
51
+ };
52
+ }
53
+ return {
54
+ value: createResponse({
55
+ body: document.data.body,
56
+ ...(document.data.headers ? { headers: document.data.headers } : {}),
57
+ }),
58
+ };
59
+ },
60
+ },
61
+ }, "schema");
62
+ }
63
+ function createResponse(document) {
64
+ return brand({ document }, "response");
65
+ }
66
+ function brand(value, kind) {
67
+ return Object.defineProperty(value, CUSTOM_ERROR, { value: kind, enumerable: false });
68
+ }
69
+ function prefixIssuePaths(params) {
70
+ const { issues, prefix } = params;
71
+ return issues.map((issue) => ({ ...issue, path: [...prefix, ...issue.path] }));
72
+ }
73
+ function isCustomErrorResponse(data) {
74
+ return (typeof data === "object" &&
75
+ data !== null &&
76
+ CUSTOM_ERROR in data &&
77
+ data[CUSTOM_ERROR] === "response" &&
78
+ "document" in data);
79
+ }
80
+ function isCustomErrorBodySchema(schema) {
81
+ return (typeof schema === "object" &&
82
+ schema !== null &&
83
+ CUSTOM_ERROR in schema &&
84
+ schema[CUSTOM_ERROR] === "schema" &&
85
+ "bodySchema" in schema);
86
+ }
87
+ //# sourceMappingURL=customError.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"customError.js","sourceRoot":"","sources":["../../../../../packages/contract-core/src/lib/customError.ts"],"names":[],"mappings":";;;;;AACA,6BAAwB;AAExB;;;GAGG;AACH,MAAM,YAAY,GAAG,MAAM,CAAC,GAAG,CAAC,iDAAiD,CAAC,CAAC;AA0BnF,MAAM,mBAAmB,GAAG,OAAC,CAAC,MAAM,CAAC;IACnC,IAAI,EAAE,OAAC,CAAC,OAAO,EAAE;IACjB,OAAO,EAAE,OAAC,CAAC,MAAM,CAAC,OAAC,CAAC,MAAM,EAAE,CAAC,CAAC,QAAQ,EAAE;CACzC,CAAC,CAAC;AAEH,qBAAmE,MAGlE;IACC,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,GAAG,MAAM,CAAC;IAChC,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,gBAAgB,CAAC,IAAI,CAAC,EAAE,CAAC;AAClD,CAAC;AAED,gCAAuC,MAAyB;IAC9D,MAAM,EAAE,IAAI,EAAE,GAAG,MAAM,CAAC;IACxB,OAAO,qBAAqB,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,SAAS,CAAC;AACjE,CAAC;AAED,kCAAyC,MAExC;IACC,MAAM,EAAE,MAAM,EAAE,GAAG,MAAM,CAAC;IAC1B,OAAO,uBAAuB,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC,CAAC,SAAS,CAAC;AACzE,CAAC;AAED,SAAS,gBAAgB,CACvB,UAAsB;IAEtB,OAAO,KAAK,CACV;QACE,UAAU;QACV,WAAW,EAAE;YACX,OAAO,EAAE,CAAC;YACV,MAAM,EAAE,wBAAwB;YAChC,QAAQ,EAAE,CAAC,KAAK,EAAE,EAAE;gBAClB,MAAM,UAAU,GAAG,qBAAqB,CAAC,KAAK,CAAC,CAAC;gBAChD,2FAA2F;gBAC3F,MAAM,YAAY,GAAG,UAAU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,MAAM,CAAC,cAAc,CAAC,KAAK,EAAE,YAAY,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,UAAU,EAAE,KAAK,EAAE,CAAC,CAAC;AACxF,CAAC;AAED,SAAS,gBAAgB,CAAC,MAGzB;IACC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,GAAG,MAAM,CAAC;IAClC,OAAO,MAAM,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,EAAE,GAAG,KAAK,EAAE,IAAI,EAAE,CAAC,GAAG,MAAM,EAAE,GAAG,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC;AACjF,CAAC;AAED,SAAS,qBAAqB,CAAC,IAAa;IAC1C,OAAO,CACL,OAAO,IAAI,KAAK,QAAQ;QACxB,IAAI,KAAK,IAAI;QACb,YAAY,IAAI,IAAI;QACpB,IAAI,CAAC,YAAY,CAAC,KAAK,UAAU;QACjC,UAAU,IAAI,IAAI,CACnB,CAAC;AACJ,CAAC;AAED,SAAS,uBAAuB,CAC9B,MAAe;IAEf,OAAO,CACL,OAAO,MAAM,KAAK,QAAQ;QAC1B,MAAM,KAAK,IAAI;QACf,YAAY,IAAI,MAAM;QACtB,MAAM,CAAC,YAAY,CAAC,KAAK,QAAQ;QACjC,YAAY,IAAI,MAAM,CACvB,CAAC;AACJ,CAAC"}
@@ -61,6 +61,26 @@ export declare const apiErrors: z.ZodObject<{
61
61
  title?: string | undefined;
62
62
  }[];
63
63
  }>;
64
+ export declare const apiErrorSource: z.ZodObject<{
65
+ pointer: z.ZodOptional<z.ZodString>;
66
+ parameter: z.ZodOptional<z.ZodString>;
67
+ header: z.ZodOptional<z.ZodString>;
68
+ }, "strip", z.ZodTypeAny, {
69
+ pointer?: string | undefined;
70
+ parameter?: string | undefined;
71
+ header?: string | undefined;
72
+ }, {
73
+ pointer?: string | undefined;
74
+ parameter?: string | undefined;
75
+ header?: string | undefined;
76
+ }>;
77
+ export declare function apiErrorsWith<ErrorSchema extends z.ZodType<ApiError>>(error: ErrorSchema): z.ZodObject<{} & {
78
+ errors: z.ZodArray<ErrorSchema, "many">;
79
+ }, "strip", z.ZodTypeAny, {
80
+ errors: ErrorSchema["_output"][];
81
+ }, {
82
+ errors: ErrorSchema["_input"][];
83
+ }>;
64
84
  /**
65
85
  * @see {@link https://jsonapi.org/format/#error-objects Error Objects}
66
86
  */
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.apiErrors = exports.apiError = void 0;
3
+ exports.apiErrorSource = exports.apiErrors = exports.apiError = void 0;
4
+ exports.apiErrorsWith = apiErrorsWith;
4
5
  const zod_1 = require("zod");
5
6
  const nonEmptyString_1 = require("./nonEmptyString");
6
7
  /**
@@ -19,4 +20,14 @@ exports.apiError = zod_1.z.object({
19
20
  exports.apiErrors = zod_1.z.object({
20
21
  errors: exports.apiError.array().min(0).max(100),
21
22
  });
23
+ exports.apiErrorSource = zod_1.z.object({
24
+ pointer: zod_1.z.string().optional(),
25
+ parameter: zod_1.z.string().optional(),
26
+ header: zod_1.z.string().optional(),
27
+ });
28
+ function apiErrorsWith(error) {
29
+ return exports.apiErrors.extend({
30
+ errors: error.array().min(0).max(100),
31
+ });
32
+ }
22
33
  //# sourceMappingURL=apiError.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"apiError.js","sourceRoot":"","sources":["../../../../../../packages/contract-core/src/lib/schemas/apiError.ts"],"names":[],"mappings":";;;AAAA,6BAAwB;AAExB,qDAAkD;AAElD;;GAEG;AACU,QAAA,QAAQ,GAAG,OAAC,CAAC,MAAM,CAAC;IAC/B,IAAI,EAAE,+BAAc;IACpB,MAAM,EAAE,OAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;IAC7B,EAAE,EAAE,+BAAc;IAClB,MAAM,EAAE,+BAAc;IACtB,KAAK,EAAE,OAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;CAC7B,CAAC,CAAC;A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