@apify/validations 0.1.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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2018 Apify Technologies s.r.o.
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,24 @@
1
+ # Apify shared library
2
+
3
+ [![Build Status](https://github.com/apify/apify-shared-js/actions/workflows/test_and_release.yaml/badge.svg?branch=master)](https://github.com/apify/apify-shared-js/actions/workflows/test_and_release.yaml)
4
+
5
+ package | version
6
+ --------|--------
7
+ `@apify/consts` | [![NPM version](https://img.shields.io/npm/v/@apify/consts.svg)](https://www.npmjs.com/package/@apify/consts)
8
+ `@apify/datastructures` | [![NPM version](https://img.shields.io/npm/v/@apify/datastructures.svg)](https://www.npmjs.com/package/@apify/datastructures)
9
+ `@apify/git` | [![NPM version](https://img.shields.io/npm/v/@apify/git.svg)](https://www.npmjs.com/package/@apify/git)
10
+ `@apify/hubspot_client` | [![NPM version](https://img.shields.io/npm/v/@apify/hubspot_client.svg)](https://www.npmjs.com/package/@apify/hubspot_client)
11
+ `@apify/input_schema` | [![NPM version](https://img.shields.io/npm/v/@apify/input_schema.svg)](https://www.npmjs.com/package/@apify/input_schema)
12
+ `@apify/input_secrets` | [![NPM version](https://img.shields.io/npm/v/@apify/input_secrets.svg)](https://www.npmjs.com/package/@apify/input_secrets)
13
+ `@apify/image_proxy_client` | [![NPM version](https://img.shields.io/npm/v/@apify/image_proxy_client.svg)](https://www.npmjs.com/package/@apify/image_proxy_client)
14
+ `@apify/json_schemas` | [![NPM version](https://img.shields.io/npm/v/@apify/json_schemas.svg)](https://www.npmjs.com/package/@apify/json_schemas)
15
+ `@apify/log` | [![NPM version](https://img.shields.io/npm/v/@apify/log.svg)](https://www.npmjs.com/package/@apify/log)
16
+ `@apify/markdown` | [![NPM version](https://img.shields.io/npm/v/@apify/markdown.svg)](https://www.npmjs.com/package/@apify/markdown)
17
+ `@apify/payment_qr_codes` | [![NPM version](https://img.shields.io/npm/v/@apify/payment_qr_codes.svg)](https://www.npmjs.com/package/@apify/payment_qr_codes)
18
+ `@apify/pseudo_url` | [![NPM version](https://img.shields.io/npm/v/@apify/pseudo_url.svg)](https://www.npmjs.com/package/@apify/pseudo_url)
19
+ `@apify/utilities` | [![NPM version](https://img.shields.io/npm/v/@apify/utilities.svg)](https://www.npmjs.com/package/@apify/utilities)
20
+ `@apify/timeout` | [![NPM version](https://img.shields.io/npm/v/@apify/timeout.svg)](https://www.npmjs.com/package/@apify/timeout)
21
+
22
+ Internal utilities and constants shared across <a href="https://www.apify.com">Apify</a> projects.
23
+ Unless you work at Apify ([interested?](https://apify.com/jobs)), you shouldn't use this package directly,
24
+ as things might break for you any time without deprecation warning.
package/index.d.ts ADDED
@@ -0,0 +1 @@
1
+ export * from './validation.js';
package/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export * from './validation.js';
2
+ //# sourceMappingURL=index.js.map
package/index.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,iBAAiB,CAAC","sourcesContent":["export * from './validation.js';\n"]}
package/package.json ADDED
@@ -0,0 +1,55 @@
1
+ {
2
+ "name": "@apify/validations",
3
+ "version": "0.1.0",
4
+ "description": "Zod-based argument validation with human-readable errors, shared across Apify projects.",
5
+ "type": "module",
6
+ "main": "./index.js",
7
+ "types": "./index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./index.d.ts",
11
+ "default": "./index.js"
12
+ },
13
+ "./package.json": "./package.json"
14
+ },
15
+ "keywords": [
16
+ "apify"
17
+ ],
18
+ "author": {
19
+ "name": "Apify",
20
+ "email": "support@apify.com",
21
+ "url": "https://apify.com"
22
+ },
23
+ "license": "Apache-2.0",
24
+ "repository": {
25
+ "type": "git",
26
+ "url": "git+https://github.com/apify/apify-shared-js"
27
+ },
28
+ "bugs": {
29
+ "url": "https://github.com/apify/apify-shared-js/issues"
30
+ },
31
+ "homepage": "https://apify.com",
32
+ "scripts": {
33
+ "build": "pnpm clean && pnpm compile && pnpm copy",
34
+ "clean": "node ../../scripts/clean.ts",
35
+ "compile": "tsc -p tsconfig.build.json",
36
+ "copy": "node ../../scripts/copy.ts"
37
+ },
38
+ "publishConfig": {
39
+ "access": "public"
40
+ },
41
+ "dependencies": {
42
+ "zod": "^4.0.0"
43
+ },
44
+ "engines": {
45
+ "node": ">=22"
46
+ },
47
+ "lerna": {
48
+ "command": {
49
+ "publish": {
50
+ "assets": []
51
+ }
52
+ }
53
+ },
54
+ "gitHead": "90c4e8868f43e971fa1996239abd4f75de558b8e"
55
+ }
@@ -0,0 +1,32 @@
1
+ import { z } from 'zod';
2
+ /**
3
+ * Thrown when an argument fails schema validation.
4
+ *
5
+ * Its `message` is a human-readable sentence naming the offending field and the
6
+ * value it received (rather than a raw JSON dump). The structured
7
+ * {@link https://zod.dev | zod} issues are available on `issues`, and the
8
+ * original `ZodError` on `cause`, for programmatic inspection.
9
+ */
10
+ export declare class ArgumentValidationError extends Error {
11
+ /** Structured issues from the underlying schema check. */
12
+ readonly issues: z.ZodError['issues'];
13
+ /** The raw zod error that triggered this. */
14
+ readonly cause: z.ZodError;
15
+ constructor(error: z.ZodError, value: unknown, label?: string);
16
+ }
17
+ /**
18
+ * Parses `value` with `schema`, returning the typed result (with schema defaults applied).
19
+ * Throws {@link ArgumentValidationError} on failure.
20
+ *
21
+ * The optional `label` names the interface being validated and is appended to every error line
22
+ * (e.g. ``… at `maxRequestRetries` in `BasicCrawlerOptions` ``).
23
+ * @internal
24
+ */
25
+ export declare function parseArgument<TValue, TSchema extends z.ZodType>(value: TValue, schema: TSchema, label?: string): TValue & z.output<TSchema>;
26
+ /**
27
+ * Matches any non-null object, arrays included — the same values the old `ow.object`
28
+ * accepted. A `z.custom()` predicate rather than an object schema, so parsing returns
29
+ * the value itself instead of a copy.
30
+ * @internal
31
+ */
32
+ export declare const objectSchema: z.ZodCustom<object, object>;
package/validation.js ADDED
@@ -0,0 +1,151 @@
1
+ import { z } from 'zod';
2
+ /** Formats a zod issue path like `groups[0]` or `countryCode`. */
3
+ function formatIssuePath(path) {
4
+ let out = '';
5
+ for (const key of path) {
6
+ if (typeof key === 'number')
7
+ out += `[${key}]`;
8
+ else
9
+ out += out ? `.${String(key)}` : String(key);
10
+ }
11
+ return out;
12
+ }
13
+ /** Reads the value at `path` from the validated input, to include in the error. */
14
+ function valueAtPath(root, path) {
15
+ let current = root;
16
+ for (const key of path) {
17
+ if (current === null || typeof current !== 'object')
18
+ return undefined;
19
+ current = current[key];
20
+ }
21
+ return current;
22
+ }
23
+ /** Names the runtime type of `value` the way zod's own messages do (`null`, `array`, `string`, …). */
24
+ function describeType(value) {
25
+ if (value === null)
26
+ return 'null';
27
+ if (Array.isArray(value))
28
+ return 'array';
29
+ return typeof value;
30
+ }
31
+ /** The bare custom-schema messages that stop at the expected type, e.g. `Invalid input: expected number`. */
32
+ const BARE_EXPECTED_TYPE_MESSAGE = /^Invalid input: expected (an array of .+|a typed array|an object|object|array|function|number|string|boolean)$/;
33
+ /** Longest received string rendered in an error; the rest is elided. */
34
+ const MAX_RENDERED_STRING_LENGTH = 200;
35
+ /** Renders a primitive received value for an error; skips objects/Dates (noisy). */
36
+ function describeReceived(value) {
37
+ switch (typeof value) {
38
+ case 'string':
39
+ // An empty string would render as bare backticks — make it visible.
40
+ if (value === '')
41
+ return "''";
42
+ return value.length > MAX_RENDERED_STRING_LENGTH
43
+ ? `${value.slice(0, MAX_RENDERED_STRING_LENGTH)}… (${value.length - MAX_RENDERED_STRING_LENGTH} more characters)`
44
+ : value;
45
+ case 'number':
46
+ case 'boolean':
47
+ case 'bigint':
48
+ return String(value);
49
+ default:
50
+ return undefined;
51
+ }
52
+ }
53
+ /** Renders the received side of a sentence: ``received the string `abc` ``, `received NaN`, `received array`. */
54
+ function describeReceivedClause(value) {
55
+ if (typeof value === 'number' && Number.isNaN(value))
56
+ return 'received NaN';
57
+ if (value === '')
58
+ return 'received an empty string';
59
+ const rendered = describeReceived(value);
60
+ return rendered === undefined
61
+ ? `received ${describeType(value)}`
62
+ : `received the ${describeType(value)} \`${rendered}\``;
63
+ }
64
+ /** Renders one issue as a line each; a union expands into a line per failed arm. */
65
+ function formatIssue(issue, root, basePath) {
66
+ const path = [...basePath, ...issue.path];
67
+ // A union's own message is a bare "Invalid input" — the useful part is in `errors`,
68
+ // whose paths are relative to the union, hence passing `path` down as the base.
69
+ if (issue.code === 'invalid_union') {
70
+ return issue.errors.flatMap((arm) => arm.flatMap((nested) => formatIssue(nested, root, path)));
71
+ }
72
+ const location = path.length ? ` at \`${formatIssuePath(path)}\`` : '';
73
+ const value = valueAtPath(root, path);
74
+ const rendered = describeReceived(value);
75
+ // ow named the received type ("expected `number` but received type `string`"). The received value is
76
+ // folded into that clause (``received the string `3` ``) rather than dangling after the location: our
77
+ // custom schemas stop at the expected type, so the clause is appended; zod's built-in messages already
78
+ // end with `, received <type>`, so that tail is replaced with the enriched one.
79
+ let { message } = issue;
80
+ let got = '';
81
+ const bareExpected = BARE_EXPECTED_TYPE_MESSAGE.exec(message);
82
+ const zodReceived = /, received (\S+)$/.exec(message);
83
+ // `arrayOf` messages name the element type — their expected runtime type is `array`.
84
+ const expectedType = bareExpected?.[1].startsWith('an array of') ? 'array' : bareExpected?.[1];
85
+ if (bareExpected && expectedType !== (Number.isNaN(value) ? 'NaN' : describeType(value))) {
86
+ message += `, ${describeReceivedClause(value)}`;
87
+ }
88
+ else if (zodReceived && zodReceived[1] === describeType(value) && rendered !== undefined) {
89
+ message = `${message.slice(0, zodReceived.index)}, ${describeReceivedClause(value)}`;
90
+ }
91
+ else if (rendered !== undefined && !message.endsWith(`received ${rendered}`)) {
92
+ // Messages that never name a received type (regex, min/max, enums) keep the plain value suffix.
93
+ got = `, got \`${rendered}\``;
94
+ }
95
+ return [`${message}${location}${got}`];
96
+ }
97
+ /**
98
+ * Formats a `ZodError` as a plain, human-readable message that names the
99
+ * offending field *and* the value it received (e.g. ``must match pattern
100
+ * /^[A-Z]{2}$/ at `countryCode`, got `CZE` ``) — closer to the old `ow` errors
101
+ * than zod's default, which omits the received value.
102
+ */
103
+ function formatZodError(error, root, label) {
104
+ const lines = error.issues.flatMap((issue) => formatIssue(issue, root, []));
105
+ // The label names the validated interface, the way ow's errors ended with "in object `X`".
106
+ return (label ? lines.map((line) => `${line} in \`${label}\``) : lines).join('\n');
107
+ }
108
+ /**
109
+ * Thrown when an argument fails schema validation.
110
+ *
111
+ * Its `message` is a human-readable sentence naming the offending field and the
112
+ * value it received (rather than a raw JSON dump). The structured
113
+ * {@link https://zod.dev | zod} issues are available on `issues`, and the
114
+ * original `ZodError` on `cause`, for programmatic inspection.
115
+ */
116
+ export class ArgumentValidationError extends Error {
117
+ /** Structured issues from the underlying schema check. */
118
+ issues;
119
+ /** The raw zod error that triggered this. */
120
+ cause;
121
+ constructor(error, value, label) {
122
+ super(formatZodError(error, value, label), { cause: error });
123
+ this.name = 'ArgumentValidationError';
124
+ this.issues = error.issues;
125
+ this.cause = error;
126
+ }
127
+ }
128
+ /**
129
+ * Parses `value` with `schema`, returning the typed result (with schema defaults applied).
130
+ * Throws {@link ArgumentValidationError} on failure.
131
+ *
132
+ * The optional `label` names the interface being validated and is appended to every error line
133
+ * (e.g. ``… at `maxRequestRetries` in `BasicCrawlerOptions` ``).
134
+ * @internal
135
+ */
136
+ export function parseArgument(value, schema, label) {
137
+ const result = schema.safeParse(value);
138
+ if (!result.success)
139
+ throw new ArgumentValidationError(result.error, value, label);
140
+ return result.data;
141
+ }
142
+ /**
143
+ * Matches any non-null object, arrays included — the same values the old `ow.object`
144
+ * accepted. A `z.custom()` predicate rather than an object schema, so parsing returns
145
+ * the value itself instead of a copy.
146
+ * @internal
147
+ */
148
+ export const objectSchema = z.custom((value) => typeof value === 'object' && value !== null, {
149
+ error: 'Invalid input: expected object',
150
+ });
151
+ //# sourceMappingURL=valid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ACvB,CAAC;CACJ;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,aAAa,CACzB,KAAa,EACb,MAAe,EACf,KAAc;IAEd,MAAM,MAAM,GAAG,MAAM,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;IACvC,IAAI,CAAC,MAAM,CAAC,OAAO;QAAE,MAAM,IAAI,uBAAuB,CAAC,MAAM,CAAC,KAAK,EAAE,KAAK,EAAE,KAAK,CAAC,CAAC;IACnF,OAAO,MAAM,CAAC,IAAkC,CAAC;AACrD,CAAC;AAED;;;;;GAKG;AACH,MAAM,CAAC,MAAM,YAAY,GAAG,CAAC,CAAC,MAAM,CAAS,CAAC,KAAK,EAAE,EAAE,CAAC,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,EAAE;IACjG,KAAK,EAAE,gCAAgC;CAC1C,CAAC,CAAC","sourcesContent":["import { z } from 'zod';\n\n/** Formats a zod issue path like `groups[0]` or `countryCode`. */\nfunction formatIssuePath(path: readonly PropertyKey[]): string {\n let out = '';\n for (const key of path) {\n if (typeof key === 'number') out += `[${key}]`;\n else out += out ? `.${String(key)}` : String(key);\n }\n return out;\n}\n\n/** Reads the value at `path` from the validated input, to include in the error. */\nfunction valueAtPath(root: unknown, path: readonly PropertyKey[]): unknown {\n let current = root;\n for (const key of path) {\n if (current === null || typeof current !== 'object') return undefined;\n current = (current as Record<PropertyKey, unknown>)[key];\n }\n return current;\n}\n\n/** Names the runtime type of `value` the way zod's own messages do (`null`, `array`, `string`, …). */\nfunction describeType(value: unknown): string {\n if (value === null) return 'null';\n if (Array.isArray(value)) return 'array';\n return typeof value;\n}\n\n/** The bare custom-schema messages that stop at the expected type, e.g. `Invalid input: expected number`. */\nconst BARE_EXPECTED_TYPE_MESSAGE =\n /^Invalid input: expected (an array of .+|a typed array|an object|object|array|function|number|string|boolean)$/;\n\n/** Longest received string rendered in an error; the rest is elided. */\nconst MAX_RENDERED_STRING_LENGTH = 200;\n\n/** Renders a primitive received value for an error; skips objects/Dates (noisy). */\nfunction describeReceived(value: unknown): string | undefined {\n switch (typeof value) {\n case 'string':\n // An empty string would render as bare backticks — make it visible.\n if (value === '') return \"''\";\n return value.length > MAX_RENDERED_STRING_LENGTH\n ? `${value.slice(0, MAX_RENDERED_STRING_LENGTH)}… (${value.length - MAX_RENDERED_STRING_LENGTH} more characters)`\n : value;\n case 'number':\n case 'boolean':\n case 'bigint':\n return String(value);\n default:\n return undefined;\n }\n}\n\n/** Renders the received side of a sentence: ``received the string `abc` ``, `received NaN`, `received array`. */\nfunction describeReceivedClause(value: unknown): string {\n if (typeof value === 'number' && Number.isNaN(value)) return 'received NaN';\n if (value === '') return 'received an empty string';\n const rendered = describeReceived(value);\n return rendered === undefined\n ? `received ${describeType(value)}`\n : `received the ${describeType(value)} \\`${rendered}\\``;\n}\n\n/** Renders one issue as a line each; a union expands into a line per failed arm. */\nfunction formatIssue(issue: z.ZodError['issues'][number], root: unknown, basePath: readonly PropertyKey[]): string[] {\n const path = [...basePath, ...issue.path];\n // A union's own message is a bare \"Invalid input\" — the useful part is in `errors`,\n // whose paths are relative to the union, hence passing `path` down as the base.\n if (issue.code === 'invalid_union') {\n return issue.errors.flatMap((arm) => arm.flatMap((nested) => formatIssue(nested, root, path)));\n }\n\n const location = path.length ? ` at \\`${formatIssuePath(path)}\\`` : '';\n const value = valueAtPath(root, path);\n const rendered = describeReceived(value);\n\n // ow named the received type (\"expected `number` but received type `string`\"). The received value is\n // folded into that clause (``received the string `3` ``) rather than dangling after the location: our\n // custom schemas stop at the expected type, so the clause is appended; zod's built-in messages already\n // end with `, received <type>`, so that tail is replaced with the enriched one.\n let { message } = issue;\n let got = '';\n const bareExpected = BARE_EXPECTED_TYPE_MESSAGE.exec(message);\n const zodReceived = /, received (\\S+)$/.exec(message);\n // `arrayOf` messages name the element type — their expected runtime type is `array`.\n const expectedType = bareExpected?.[1].startsWith('an array of') ? 'array' : bareExpected?.[1];\n if (bareExpected && expectedType !== (Number.isNaN(value as number) ? 'NaN' : describeType(value))) {\n message += `, ${describeReceivedClause(value)}`;\n } else if (zodReceived && zodReceived[1] === describeType(value) && rendered !== undefined) {\n message = `${message.slice(0, zodReceived.index)}, ${describeReceivedClause(value)}`;\n } else if (rendered !== undefined && !message.endsWith(`received ${rendered}`)) {\n // Messages that never name a received type (regex, min/max, enums) keep the plain value suffix.\n got = `, got \\`${rendered}\\``;\n }\n\n return [`${message}${location}${got}`];\n}\n\n/**\n * Formats a `ZodError` as a plain, human-readable message that names the\n * offending field *and* the value it received (e.g. ``must match pattern\n * /^[A-Z]{2}$/ at `countryCode`, got `CZE` ``) — closer to the old `ow` errors\n * than zod's default, which omits the received value.\n */\nfunction formatZodError(error: z.ZodError, root: unknown, label?: string): string {\n const lines = error.issues.flatMap((issue) => formatIssue(issue, root, []));\n // The label names the validated interface, the way ow's errors ended with \"in object `X`\".\n return (label ? lines.map((line) => `${line} in \\`${label}\\``) : lines).join('\\n');\n}\n\n/**\n * Thrown when an argument fails schema validation.\n *\n * Its `message` is a human-readable sentence naming the offending field and the\n * value it received (rather than a raw JSON dump). The structured\n * {@link https://zod.dev | zod} issues are available on `issues`, and the\n * original `ZodError` on `cause`, for programmatic inspection.\n */\nexport class ArgumentValidationError extends Error {\n /** Structured issues from the underlying schema check. */\n readonly issues: z.ZodError['issues'];\n\n /** The raw zod error that triggered this. */\n override readonly cause: z.ZodError;\n\n constructor(error: z.ZodError, value: unknown, label?: string) {\n super(formatZodError(error, value, label), { cause: error });\n this.name = 'ArgumentValidationError';\n this.issues = error.issues;\n this.cause = error;\n }\n}\n\n/**\n * Parses `value` with `schema`, returning the typed result (with schema defaults applied).\n * Throws {@link ArgumentValidationError} on failure.\n *\n * The optional `label` names the interface being validated and is appended to every error line\n * (e.g. ``… at `maxRequestRetries` in `BasicCrawlerOptions` ``).\n * @internal\n */\nexport function parseArgument<TValue, TSchema extends z.ZodType>(\n value: TValue,\n schema: TSchema,\n label?: string,\n): TValue & z.output<TSchema> {\n const result = schema.safeParse(value);\n if (!result.success) throw new ArgumentValidationError(result.error, value, label);\n return result.data as TValue & z.output<TSchema>;\n}\n\n/**\n * Matches any non-null object, arrays included — the same values the old `ow.object`\n * accepted. A `z.custom()` predicate rather than an object schema, so parsing returns\n * the value itself instead of a copy.\n * @internal\n */\nexport const objectSchema = z.custom<object>((value) => typeof value === 'object' && value !== null, {\n error: 'Invalid input: expected object',\n});\n"]}