@rjsf/validator-ata 6.6.1

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.
Files changed (53) hide show
  1. package/README.md +94 -0
  2. package/dist/compileSchemaValidators.cjs +110 -0
  3. package/dist/compileSchemaValidators.cjs.map +7 -0
  4. package/dist/compileSchemaValidators.esm.js +79 -0
  5. package/dist/compileSchemaValidators.esm.js.map +7 -0
  6. package/dist/index.cjs +461 -0
  7. package/dist/index.cjs.map +7 -0
  8. package/dist/validator-ata.esm.js +450 -0
  9. package/dist/validator-ata.esm.js.map +7 -0
  10. package/dist/validator-ata.umd.js +422 -0
  11. package/lib/compileSchemaValidators.d.ts +16 -0
  12. package/lib/compileSchemaValidators.js +21 -0
  13. package/lib/compileSchemaValidators.js.map +1 -0
  14. package/lib/compileSchemaValidatorsCode.d.ts +13 -0
  15. package/lib/compileSchemaValidatorsCode.js +80 -0
  16. package/lib/compileSchemaValidatorsCode.js.map +1 -0
  17. package/lib/createAtaInstance.d.ts +27 -0
  18. package/lib/createAtaInstance.js +68 -0
  19. package/lib/createAtaInstance.js.map +1 -0
  20. package/lib/createPrecompiledValidator.d.ts +15 -0
  21. package/lib/createPrecompiledValidator.js +17 -0
  22. package/lib/createPrecompiledValidator.js.map +1 -0
  23. package/lib/customizeValidator.d.ts +8 -0
  24. package/lib/customizeValidator.js +9 -0
  25. package/lib/customizeValidator.js.map +1 -0
  26. package/lib/index.d.ts +7 -0
  27. package/lib/index.js +7 -0
  28. package/lib/index.js.map +1 -0
  29. package/lib/precompiledValidator.d.ts +89 -0
  30. package/lib/precompiledValidator.js +107 -0
  31. package/lib/precompiledValidator.js.map +1 -0
  32. package/lib/processRawValidationErrors.d.ts +28 -0
  33. package/lib/processRawValidationErrors.js +137 -0
  34. package/lib/processRawValidationErrors.js.map +1 -0
  35. package/lib/tsconfig.tsbuildinfo +1 -0
  36. package/lib/types.d.ts +63 -0
  37. package/lib/types.js +2 -0
  38. package/lib/types.js.map +1 -0
  39. package/lib/validator.d.ts +85 -0
  40. package/lib/validator.js +154 -0
  41. package/lib/validator.js.map +1 -0
  42. package/package.json +113 -0
  43. package/src/compileSchemaValidators.ts +30 -0
  44. package/src/compileSchemaValidatorsCode.ts +92 -0
  45. package/src/createAtaInstance.ts +81 -0
  46. package/src/createPrecompiledValidator.ts +29 -0
  47. package/src/customizeValidator.ts +16 -0
  48. package/src/index.ts +8 -0
  49. package/src/precompiledValidator.ts +188 -0
  50. package/src/processRawValidationErrors.ts +197 -0
  51. package/src/tsconfig.json +15 -0
  52. package/src/types.ts +71 -0
  53. package/src/validator.ts +231 -0
package/README.md ADDED
@@ -0,0 +1,94 @@
1
+ [![Apache 2.0 License][license-shield]][license-url]
2
+
3
+ <br />
4
+ <p align="center">
5
+ <a href="https://github.com/rjsf-team/react-jsonschema-form">
6
+ <h3 align="center">@rjsf/validator-ata</h3>
7
+ </a>
8
+
9
+ <p align="center">
10
+ <a href="https://github.com/ata-core/ata-validator">ata-validator</a> based validator plugin for <a href="https://github.com/rjsf-team/react-jsonschema-form/"><code>react-jsonschema-form</code></a>.
11
+ <br />
12
+ <a href="https://rjsf-team.github.io/react-jsonschema-form/docs/"><strong>Explore the docs »</strong></a>
13
+ <br />
14
+ <br />
15
+ <a href="https://rjsf-team.github.io/react-jsonschema-form/">View Playground</a>
16
+ ·
17
+ <a href="https://github.com/rjsf-team/react-jsonschema-form/issues">Report Bug</a>
18
+ ·
19
+ <a href="https://github.com/rjsf-team/react-jsonschema-form/issues">Request Feature</a>
20
+ </p>
21
+ </p>
22
+
23
+ ## Table of Contents
24
+
25
+ - [About](#about)
26
+ - [Installation](#installation)
27
+ - [Usage](#usage)
28
+ - [Customization](#customization)
29
+ - [Differences from validator-ajv8](#differences-from-validator-ajv8)
30
+
31
+ ## About
32
+
33
+ `@rjsf/validator-ata` plugs [`ata-validator`](https://github.com/ata-core/ata-validator) into `react-jsonschema-form` as a drop-in alternative to `@rjsf/validator-ajv8`. The public API mirrors `validator-ajv8` so swapping is a one-line change in the validator import. Error format, custom-format hook, custom validation, and error transformation all work the same way.
34
+
35
+ ata is a JSON Schema validator that targets Draft 2020-12 (98.5% spec compliance, 95.3% schemasafe pass rate) and is Standard Schema compliant. Its differentiators relative to AJV: pattern checks are RE2-backed (no ReDoS surface), and schemas can be compiled at build time for environments where bundle size or CSP restricts runtime codegen.
36
+
37
+ ## Installation
38
+
39
+ ```bash
40
+ npm install @rjsf/validator-ata ata-validator
41
+ ```
42
+
43
+ `ata-validator` is a peer of this package; install it alongside.
44
+
45
+ ## Usage
46
+
47
+ ```ts
48
+ import Form from '@rjsf/core';
49
+ import validator from '@rjsf/validator-ata';
50
+
51
+ <Form schema={schema} validator={validator} />;
52
+ ```
53
+
54
+ ### Customization
55
+
56
+ ```ts
57
+ import { customizeValidator } from '@rjsf/validator-ata';
58
+
59
+ const validator = customizeValidator({
60
+ customFormats: {
61
+ 'phone-us': /\(?\d{3}\)?[\s-]?\d{3}[\s-]?\d{4}$/,
62
+ 'area-code': /\d{3}/,
63
+ },
64
+ ataOptionsOverrides: {
65
+ verbose: true,
66
+ },
67
+ });
68
+ ```
69
+
70
+ `customizeValidator` accepts:
71
+
72
+ - **`customFormats`** — same shape as `validator-ajv8`. Values may be a `RegExp`, an anchored regex source string, or a `(value: string) => boolean` predicate.
73
+ - **`ataOptionsOverrides`** — plain `ata-validator` options spread on top of the defaults; use this to flip `coerceTypes`, `removeAdditional`, `verbose`, or `abortEarly`.
74
+ - **`additionalMetaSchemas`** — extra schemas registered via `Validator#addSchema` for cross-schema `$ref` resolution.
75
+ - **`extenderFn`** — hook applied against a freshly-built `Validator` (e.g. for adding additional formats or schemas in one place).
76
+ - **`suppressDuplicateFiltering`** — passthrough to the RJSF error processor; same semantics as in `validator-ajv8`.
77
+
78
+ A `Localizer` may be supplied as the second argument. ata error objects use the same field names as AJV (`keyword`, `instancePath`, `schemaPath`, `params`, `message`, `parentSchema`), so localizers that mutate `message` in place port across without changes. The pre-quote dance that the AJV validator runs against `ajv-i18n` is intentionally not replicated here — ata's error params are frozen, and the existing locale catalogues for AJV are not portable to ata's keyword set.
79
+
80
+ ## Differences from validator-ajv8
81
+
82
+ The `ValidatorType` contract is identical, and the shared `@rjsf/utils` schema test suite passes against this validator with the deltas below. Behavior outside of this list mirrors `validator-ajv8`.
83
+
84
+ - **Precompiled validators** are not yet wired through. The `compileSchemaValidators` and `createPrecompiledValidator` entrypoints exposed by `validator-ajv8` are slated for a follow-up release that adapts ata's `bundleStandalone` codegen to the RJSF-expected `ValidatorFunctions` shape.
85
+ - **`ajvOptionsOverrides`, `ajvFormatOptions`, `AjvClass`** have no equivalents and are intentionally not accepted. `ataOptionsOverrides` replaces the first; built-in formats are always installed and don't require an opt-in flag.
86
+ - **`isValid` and `rawValidation` deep-clone `formData` before passing it to ata**. ata's default-applier writes `default` values into the input object during validation, while AJV treats validation as a pure operation. The clone preserves the AJV contract RJSF expects when probing data through repeated `isValid` calls (oneOf/anyOf option resolution).
87
+ - **Custom-keyword extensions** (e.g. `ajv-errors`, `ajv-merge-patch`) have no ata-side counterpart yet. Schemas using these keywords will validate (ata silently ignores unknown keywords) but the extension semantics are not applied.
88
+
89
+ ## Contributing
90
+
91
+ See the monorepo [CONTRIBUTING.md](../../CONTRIBUTING.md). Issues and PRs welcome on either the validator package or [ata-validator](https://github.com/ata-core/ata-validator) itself.
92
+
93
+ [license-shield]: https://img.shields.io/badge/license-Apache%202.0-blue
94
+ [license-url]: https://github.com/rjsf-team/react-jsonschema-form/blob/main/LICENSE.md
@@ -0,0 +1,110 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/compileSchemaValidators.ts
31
+ var compileSchemaValidators_exports = {};
32
+ __export(compileSchemaValidators_exports, {
33
+ compileSchemaValidatorsCode: () => compileSchemaValidatorsCode,
34
+ default: () => compileSchemaValidators
35
+ });
36
+ module.exports = __toCommonJS(compileSchemaValidators_exports);
37
+ var import_fs = __toESM(require("fs"), 1);
38
+
39
+ // src/compileSchemaValidatorsCode.ts
40
+ var import_utils = require("@rjsf/utils");
41
+ var import_ata_validator2 = require("ata-validator");
42
+
43
+ // src/createAtaInstance.ts
44
+ var import_ata_validator = require("ata-validator");
45
+ var import_isObject = __toESM(require("lodash/isObject"), 1);
46
+ var COLOR_FORMAT_REGEX = /^(#?([0-9A-Fa-f]{3}){1,2}\b|aqua|black|blue|fuchsia|gray|green|lime|maroon|navy|olive|orange|purple|red|silver|teal|white|yellow|(rgb\(\s*\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b\s*,\s*\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b\s*,\s*\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b\s*\))|(rgb\(\s*(\d?\d%|100%)+\s*,\s*(\d?\d%|100%)+\s*,\s*(\d?\d%|100%)+\s*\)))$/;
47
+ var DATA_URL_FORMAT_REGEX = /^data:([a-z]+\/[a-z0-9-+.]+)?;(?:name=(.*);)?base64,(.*)$/;
48
+
49
+ // src/compileSchemaValidatorsCode.ts
50
+ function compileSchemaValidatorsCode(schema, options = {}) {
51
+ const schemaMaps = (0, import_utils.schemaParser)(schema);
52
+ const keys = Object.keys(schemaMaps);
53
+ const schemas = Object.values(schemaMaps);
54
+ const { customFormats, ataOptionsOverrides = {} } = options;
55
+ const regexFormats = {
56
+ color: COLOR_FORMAT_REGEX,
57
+ "data-url": DATA_URL_FORMAT_REGEX
58
+ };
59
+ if (customFormats) {
60
+ for (const [name, check] of Object.entries(customFormats)) {
61
+ if (typeof check === "function") {
62
+ throw new Error(
63
+ `@rjsf/validator-ata: custom format "${name}" is a function, which is not supported by the precompiled validator; provide a RegExp or string pattern instead`
64
+ );
65
+ }
66
+ regexFormats[name] = typeof check === "string" ? new RegExp(check) : check;
67
+ }
68
+ }
69
+ const formats = {};
70
+ for (const [name, re] of Object.entries(regexFormats)) {
71
+ formats[name] = new Function("value", `return ${re.toString()}.test(value)`);
72
+ }
73
+ const bundle = import_ata_validator2.Validator.bundleStandalone(schemas, {
74
+ format: "cjs",
75
+ verbose: ataOptionsOverrides.verbose !== false,
76
+ formats
77
+ });
78
+ const entries = keys.map((key, index) => ` ${JSON.stringify(key)}: wrap(validators[${index}], ${JSON.stringify(key)}),`).join("\n");
79
+ return [
80
+ "const validators = (function () {",
81
+ " const module = { exports: {} };",
82
+ bundle,
83
+ " return module.exports;",
84
+ "})();",
85
+ "function wrap(fn, key) {",
86
+ " function validate(data) {",
87
+ " if (typeof fn !== 'function') {",
88
+ ` throw new Error('@rjsf/validator-ata: schema "' + key + '" was not compiled to a standalone validator');`,
89
+ " }",
90
+ " const result = fn(data);",
91
+ " validate.errors = result.valid ? null : result.errors;",
92
+ " return result.valid;",
93
+ " }",
94
+ " return validate;",
95
+ "}",
96
+ "module.exports = {",
97
+ entries,
98
+ "};",
99
+ ""
100
+ ].join("\n");
101
+ }
102
+
103
+ // src/compileSchemaValidators.ts
104
+ function compileSchemaValidators(schema, output, options = {}) {
105
+ console.log("parsing the schema");
106
+ const moduleCode = compileSchemaValidatorsCode(schema, options);
107
+ console.log(`writing ${output}`);
108
+ import_fs.default.writeFileSync(output, moduleCode);
109
+ }
110
+ //# sourceMappingURL=compileSchemaValidators.cjs.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/compileSchemaValidators.ts", "../src/compileSchemaValidatorsCode.ts", "../src/createAtaInstance.ts"],
4
+ "sourcesContent": ["import { RJSFSchema, StrictRJSFSchema } from '@rjsf/utils';\nimport fs from 'fs';\n\nimport { compileSchemaValidatorsCode } from './compileSchemaValidatorsCode';\nimport { CustomValidatorOptionsType } from './types';\n\nexport { compileSchemaValidatorsCode };\n\n/** The function used to compile a schema into an output file in the form that allows it to be used as a precompiled\n * validator. The main reasons for using a precompiled validator is reducing code size, improving validation speed and,\n * most importantly, avoiding dynamic code compilation when prohibited by a browser's Content Security Policy. For more\n * information about ata standalone compilation see the ata-validator documentation.\n *\n * @param schema - The schema to be compiled into a set of precompiled validators functions\n * @param output - The name of the file into which the precompiled validator functions will be generated\n * @param [options={}] - The set of `CustomValidatorOptionsType` information used to alter the ata validator used for\n * compiling the schema. They are the same options that are passed to the `customizeValidator()` function in\n * order to modify the behavior of the regular ata-based validator.\n */\nexport default function compileSchemaValidators<S extends StrictRJSFSchema = RJSFSchema>(\n schema: S,\n output: string,\n options: CustomValidatorOptionsType = {},\n) {\n console.log('parsing the schema');\n\n const moduleCode = compileSchemaValidatorsCode(schema, options);\n console.log(`writing ${output}`);\n fs.writeFileSync(output, moduleCode);\n}\n", "import { RJSFSchema, StrictRJSFSchema, schemaParser } from '@rjsf/utils';\nimport { Validator } from 'ata-validator';\n\nimport { COLOR_FORMAT_REGEX, DATA_URL_FORMAT_REGEX } from './createAtaInstance';\nimport { CustomValidatorOptionsType } from './types';\n\n/** Compiles a schema into a precompiled validator module. ata's\n * `bundleStandalone` emits `module.exports = [fn, ...]`, one validator per\n * schema in order, where each `fn(data)` returns `{ valid, errors }`. This wraps\n * that array into the `{ [id]: (data) => boolean }`-with-`errors` map that\n * `createPrecompiledValidator` consumes, keyed the same way `schemaParser` keys\n * the schemas so the precompiled validator can look each one up.\n *\n * @param schema - The schema to compile\n * @param [options={}] - The `CustomValidatorOptionsType` used to build the validator\n */\nexport function compileSchemaValidatorsCode<S extends StrictRJSFSchema = RJSFSchema>(\n schema: S,\n options: CustomValidatorOptionsType = {},\n) {\n const schemaMaps = schemaParser(schema);\n const keys = Object.keys(schemaMaps);\n const schemas = Object.values(schemaMaps);\n\n const { customFormats, ataOptionsOverrides = {} } = options;\n\n // Format checkers are serialized into the standalone module via Function#toString,\n // so they must carry no closure references or build-time instrumentation (a plain\n // arrow over the source file picks up coverage counters). Building each from its\n // regex via `new Function` produces a function whose source is exactly its body.\n const regexFormats: Record<string, RegExp> = {\n color: COLOR_FORMAT_REGEX,\n 'data-url': DATA_URL_FORMAT_REGEX,\n };\n if (customFormats) {\n for (const [name, check] of Object.entries(customFormats)) {\n if (typeof check === 'function') {\n // A function checker would be serialized via toString, which is unsafe in a\n // precompiled bundle: transpilers, minifiers, and coverage tools rewrite the\n // body and leave references that do not exist in the generated module. Only\n // RegExp/string patterns can be embedded reliably here.\n throw new Error(\n `@rjsf/validator-ata: custom format \"${name}\" is a function, which is not supported by the precompiled validator; provide a RegExp or string pattern instead`,\n );\n }\n regexFormats[name] = typeof check === 'string' ? new RegExp(check) : check;\n }\n }\n const formats: Record<string, (value: string) => boolean> = {};\n for (const [name, re] of Object.entries(regexFormats)) {\n // `new Function` rather than a fat-arrow on purpose: ata serializes these format\n // checkers into the standalone bundle via Function#toString. A fat-arrow would\n // close over `re` and emit `re.test(value)`, leaving `re` undefined in the\n // generated module. Building it from a string inlines the regex literal into the\n // body, so the bundled output stays self-contained.\n // eslint-disable-next-line no-new-func\n formats[name] = new Function('value', `return ${re.toString()}.test(value)`) as (value: string) => boolean;\n }\n\n const bundle = Validator.bundleStandalone(schemas, {\n format: 'cjs',\n verbose: ataOptionsOverrides.verbose !== false,\n formats,\n });\n\n const entries = keys\n .map((key, index) => ` ${JSON.stringify(key)}: wrap(validators[${index}], ${JSON.stringify(key)}),`)\n .join('\\n');\n\n return [\n 'const validators = (function () {',\n ' const module = { exports: {} };',\n bundle,\n ' return module.exports;',\n '})();',\n 'function wrap(fn, key) {',\n ' function validate(data) {',\n \" if (typeof fn !== 'function') {\",\n \" throw new Error('@rjsf/validator-ata: schema \\\"' + key + '\\\" was not compiled to a standalone validator');\",\n ' }',\n ' const result = fn(data);',\n ' validate.errors = result.valid ? null : result.errors;',\n ' return result.valid;',\n ' }',\n ' return validate;',\n '}',\n 'module.exports = {',\n entries,\n '};',\n '',\n ].join('\\n');\n}\n", "import { Validator, type ValidatorOptions } from 'ata-validator';\nimport isObject from 'lodash/isObject';\n\nimport type { AtaFormatChecker, CustomValidatorOptionsType } from './types';\n\n/** Default options applied to every ata `Validator` constructed for RJSF.\n * `verbose: true` keeps `parentSchema` available on errors, which the RJSF\n * error transformer uses to recover field titles. The remainder match\n * `@rjsf/validator-ajv8`'s defaults (`allErrors`-equivalent behavior is\n * ata's default).\n */\nexport const ATA_CONFIG: ValidatorOptions = {\n verbose: true,\n} as const;\n\n/** Color names + hex + `rgb()` regex source. Mirrors the pattern shipped by\n * `@rjsf/validator-ajv8` so RJSF schemas using `format: 'color'` keep\n * working when swapped to validator-ata.\n */\nexport const COLOR_FORMAT_REGEX =\n /^(#?([0-9A-Fa-f]{3}){1,2}\\b|aqua|black|blue|fuchsia|gray|green|lime|maroon|navy|olive|orange|purple|red|silver|teal|white|yellow|(rgb\\(\\s*\\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\b\\s*,\\s*\\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\b\\s*,\\s*\\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\b\\s*\\))|(rgb\\(\\s*(\\d?\\d%|100%)+\\s*,\\s*(\\d?\\d%|100%)+\\s*,\\s*(\\d?\\d%|100%)+\\s*\\)))$/;\n\n/** RFC 2397 data URL with required mime type and base64 marker, matching\n * the shape used by `@rjsf/validator-ajv8`.\n */\nexport const DATA_URL_FORMAT_REGEX = /^data:([a-z]+\\/[a-z0-9-+.]+)?;(?:name=(.*);)?base64,(.*)$/;\n\n/** Coerces the user-supplied custom format value into the `(value: string)\n * => boolean` shape expected by ata. Strings are treated as RegExp source\n * (anchored at both ends if not already), RegExps are converted to a `.test`\n * call, functions pass through.\n */\nfunction asFormatChecker(spec: string | RegExp | AtaFormatChecker): AtaFormatChecker {\n if (typeof spec === 'function') {\n return spec;\n }\n const re = spec instanceof RegExp ? spec : new RegExp(spec);\n return (value: string) => re.test(value);\n}\n\n/** Builds a fresh `ata-validator` `Validator` for a given schema with all\n * RJSF-aware defaults and user customizations applied.\n *\n * The factory exists so that the validator class can construct one\n * `Validator` per schema-id (ata is schema-bound, unlike AJV's single\n * instance with a schema registry) while keeping the option translation\n * in one place.\n */\nexport default function createAtaInstance(schema: object, options: CustomValidatorOptionsType = {}): Validator {\n const { customFormats, ataOptionsOverrides, additionalMetaSchemas, extenderFn } = options;\n\n const formats: Record<string, AtaFormatChecker> = {\n color: asFormatChecker(COLOR_FORMAT_REGEX),\n 'data-url': asFormatChecker(DATA_URL_FORMAT_REGEX),\n };\n if (isObject(customFormats)) {\n for (const [name, spec] of Object.entries(customFormats!)) {\n formats[name] = asFormatChecker(spec);\n }\n }\n\n const validatorOptions: ValidatorOptions = {\n ...ATA_CONFIG,\n ...ataOptionsOverrides,\n formats,\n };\n\n let validator = new Validator(schema, validatorOptions);\n\n if (Array.isArray(additionalMetaSchemas)) {\n for (const meta of additionalMetaSchemas) {\n validator.addSchema(meta);\n }\n }\n\n if (typeof extenderFn === 'function') {\n validator = extenderFn(validator);\n }\n\n return validator;\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,gBAAe;;;ACDf,mBAA2D;AAC3D,IAAAA,wBAA0B;;;ACD1B,2BAAiD;AACjD,sBAAqB;AAkBd,IAAM,qBACX;AAKK,IAAM,wBAAwB;;;ADT9B,SAAS,4BACd,QACA,UAAsC,CAAC,GACvC;AACA,QAAM,iBAAa,2BAAa,MAAM;AACtC,QAAM,OAAO,OAAO,KAAK,UAAU;AACnC,QAAM,UAAU,OAAO,OAAO,UAAU;AAExC,QAAM,EAAE,eAAe,sBAAsB,CAAC,EAAE,IAAI;AAMpD,QAAM,eAAuC;AAAA,IAC3C,OAAO;AAAA,IACP,YAAY;AAAA,EACd;AACA,MAAI,eAAe;AACjB,eAAW,CAAC,MAAM,KAAK,KAAK,OAAO,QAAQ,aAAa,GAAG;AACzD,UAAI,OAAO,UAAU,YAAY;AAK/B,cAAM,IAAI;AAAA,UACR,uCAAuC,IAAI;AAAA,QAC7C;AAAA,MACF;AACA,mBAAa,IAAI,IAAI,OAAO,UAAU,WAAW,IAAI,OAAO,KAAK,IAAI;AAAA,IACvE;AAAA,EACF;AACA,QAAM,UAAsD,CAAC;AAC7D,aAAW,CAAC,MAAM,EAAE,KAAK,OAAO,QAAQ,YAAY,GAAG;AAOrD,YAAQ,IAAI,IAAI,IAAI,SAAS,SAAS,UAAU,GAAG,SAAS,CAAC,cAAc;AAAA,EAC7E;AAEA,QAAM,SAAS,gCAAU,iBAAiB,SAAS;AAAA,IACjD,QAAQ;AAAA,IACR,SAAS,oBAAoB,YAAY;AAAA,IACzC;AAAA,EACF,CAAC;AAED,QAAM,UAAU,KACb,IAAI,CAAC,KAAK,UAAU,KAAK,KAAK,UAAU,GAAG,CAAC,qBAAqB,KAAK,MAAM,KAAK,UAAU,GAAG,CAAC,IAAI,EACnG,KAAK,IAAI;AAEZ,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,EAAE,KAAK,IAAI;AACb;;;ADxEe,SAAR,wBACL,QACA,QACA,UAAsC,CAAC,GACvC;AACA,UAAQ,IAAI,oBAAoB;AAEhC,QAAM,aAAa,4BAA4B,QAAQ,OAAO;AAC9D,UAAQ,IAAI,WAAW,MAAM,EAAE;AAC/B,YAAAC,QAAG,cAAc,QAAQ,UAAU;AACrC;",
6
+ "names": ["import_ata_validator", "fs"]
7
+ }
@@ -0,0 +1,79 @@
1
+ // src/compileSchemaValidators.ts
2
+ import fs from "fs";
3
+
4
+ // src/compileSchemaValidatorsCode.ts
5
+ import { schemaParser } from "@rjsf/utils";
6
+ import { Validator as Validator2 } from "ata-validator";
7
+
8
+ // src/createAtaInstance.ts
9
+ import { Validator } from "ata-validator";
10
+ import isObject from "lodash/isObject";
11
+ var COLOR_FORMAT_REGEX = /^(#?([0-9A-Fa-f]{3}){1,2}\b|aqua|black|blue|fuchsia|gray|green|lime|maroon|navy|olive|orange|purple|red|silver|teal|white|yellow|(rgb\(\s*\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b\s*,\s*\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b\s*,\s*\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b\s*\))|(rgb\(\s*(\d?\d%|100%)+\s*,\s*(\d?\d%|100%)+\s*,\s*(\d?\d%|100%)+\s*\)))$/;
12
+ var DATA_URL_FORMAT_REGEX = /^data:([a-z]+\/[a-z0-9-+.]+)?;(?:name=(.*);)?base64,(.*)$/;
13
+
14
+ // src/compileSchemaValidatorsCode.ts
15
+ function compileSchemaValidatorsCode(schema, options = {}) {
16
+ const schemaMaps = schemaParser(schema);
17
+ const keys = Object.keys(schemaMaps);
18
+ const schemas = Object.values(schemaMaps);
19
+ const { customFormats, ataOptionsOverrides = {} } = options;
20
+ const regexFormats = {
21
+ color: COLOR_FORMAT_REGEX,
22
+ "data-url": DATA_URL_FORMAT_REGEX
23
+ };
24
+ if (customFormats) {
25
+ for (const [name, check] of Object.entries(customFormats)) {
26
+ if (typeof check === "function") {
27
+ throw new Error(
28
+ `@rjsf/validator-ata: custom format "${name}" is a function, which is not supported by the precompiled validator; provide a RegExp or string pattern instead`
29
+ );
30
+ }
31
+ regexFormats[name] = typeof check === "string" ? new RegExp(check) : check;
32
+ }
33
+ }
34
+ const formats = {};
35
+ for (const [name, re] of Object.entries(regexFormats)) {
36
+ formats[name] = new Function("value", `return ${re.toString()}.test(value)`);
37
+ }
38
+ const bundle = Validator2.bundleStandalone(schemas, {
39
+ format: "cjs",
40
+ verbose: ataOptionsOverrides.verbose !== false,
41
+ formats
42
+ });
43
+ const entries = keys.map((key, index) => ` ${JSON.stringify(key)}: wrap(validators[${index}], ${JSON.stringify(key)}),`).join("\n");
44
+ return [
45
+ "const validators = (function () {",
46
+ " const module = { exports: {} };",
47
+ bundle,
48
+ " return module.exports;",
49
+ "})();",
50
+ "function wrap(fn, key) {",
51
+ " function validate(data) {",
52
+ " if (typeof fn !== 'function') {",
53
+ ` throw new Error('@rjsf/validator-ata: schema "' + key + '" was not compiled to a standalone validator');`,
54
+ " }",
55
+ " const result = fn(data);",
56
+ " validate.errors = result.valid ? null : result.errors;",
57
+ " return result.valid;",
58
+ " }",
59
+ " return validate;",
60
+ "}",
61
+ "module.exports = {",
62
+ entries,
63
+ "};",
64
+ ""
65
+ ].join("\n");
66
+ }
67
+
68
+ // src/compileSchemaValidators.ts
69
+ function compileSchemaValidators(schema, output, options = {}) {
70
+ console.log("parsing the schema");
71
+ const moduleCode = compileSchemaValidatorsCode(schema, options);
72
+ console.log(`writing ${output}`);
73
+ fs.writeFileSync(output, moduleCode);
74
+ }
75
+ export {
76
+ compileSchemaValidatorsCode,
77
+ compileSchemaValidators as default
78
+ };
79
+ //# sourceMappingURL=compileSchemaValidators.esm.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/compileSchemaValidators.ts", "../src/compileSchemaValidatorsCode.ts", "../src/createAtaInstance.ts"],
4
+ "sourcesContent": ["import { RJSFSchema, StrictRJSFSchema } from '@rjsf/utils';\nimport fs from 'fs';\n\nimport { compileSchemaValidatorsCode } from './compileSchemaValidatorsCode';\nimport { CustomValidatorOptionsType } from './types';\n\nexport { compileSchemaValidatorsCode };\n\n/** The function used to compile a schema into an output file in the form that allows it to be used as a precompiled\n * validator. The main reasons for using a precompiled validator is reducing code size, improving validation speed and,\n * most importantly, avoiding dynamic code compilation when prohibited by a browser's Content Security Policy. For more\n * information about ata standalone compilation see the ata-validator documentation.\n *\n * @param schema - The schema to be compiled into a set of precompiled validators functions\n * @param output - The name of the file into which the precompiled validator functions will be generated\n * @param [options={}] - The set of `CustomValidatorOptionsType` information used to alter the ata validator used for\n * compiling the schema. They are the same options that are passed to the `customizeValidator()` function in\n * order to modify the behavior of the regular ata-based validator.\n */\nexport default function compileSchemaValidators<S extends StrictRJSFSchema = RJSFSchema>(\n schema: S,\n output: string,\n options: CustomValidatorOptionsType = {},\n) {\n console.log('parsing the schema');\n\n const moduleCode = compileSchemaValidatorsCode(schema, options);\n console.log(`writing ${output}`);\n fs.writeFileSync(output, moduleCode);\n}\n", "import { RJSFSchema, StrictRJSFSchema, schemaParser } from '@rjsf/utils';\nimport { Validator } from 'ata-validator';\n\nimport { COLOR_FORMAT_REGEX, DATA_URL_FORMAT_REGEX } from './createAtaInstance';\nimport { CustomValidatorOptionsType } from './types';\n\n/** Compiles a schema into a precompiled validator module. ata's\n * `bundleStandalone` emits `module.exports = [fn, ...]`, one validator per\n * schema in order, where each `fn(data)` returns `{ valid, errors }`. This wraps\n * that array into the `{ [id]: (data) => boolean }`-with-`errors` map that\n * `createPrecompiledValidator` consumes, keyed the same way `schemaParser` keys\n * the schemas so the precompiled validator can look each one up.\n *\n * @param schema - The schema to compile\n * @param [options={}] - The `CustomValidatorOptionsType` used to build the validator\n */\nexport function compileSchemaValidatorsCode<S extends StrictRJSFSchema = RJSFSchema>(\n schema: S,\n options: CustomValidatorOptionsType = {},\n) {\n const schemaMaps = schemaParser(schema);\n const keys = Object.keys(schemaMaps);\n const schemas = Object.values(schemaMaps);\n\n const { customFormats, ataOptionsOverrides = {} } = options;\n\n // Format checkers are serialized into the standalone module via Function#toString,\n // so they must carry no closure references or build-time instrumentation (a plain\n // arrow over the source file picks up coverage counters). Building each from its\n // regex via `new Function` produces a function whose source is exactly its body.\n const regexFormats: Record<string, RegExp> = {\n color: COLOR_FORMAT_REGEX,\n 'data-url': DATA_URL_FORMAT_REGEX,\n };\n if (customFormats) {\n for (const [name, check] of Object.entries(customFormats)) {\n if (typeof check === 'function') {\n // A function checker would be serialized via toString, which is unsafe in a\n // precompiled bundle: transpilers, minifiers, and coverage tools rewrite the\n // body and leave references that do not exist in the generated module. Only\n // RegExp/string patterns can be embedded reliably here.\n throw new Error(\n `@rjsf/validator-ata: custom format \"${name}\" is a function, which is not supported by the precompiled validator; provide a RegExp or string pattern instead`,\n );\n }\n regexFormats[name] = typeof check === 'string' ? new RegExp(check) : check;\n }\n }\n const formats: Record<string, (value: string) => boolean> = {};\n for (const [name, re] of Object.entries(regexFormats)) {\n // `new Function` rather than a fat-arrow on purpose: ata serializes these format\n // checkers into the standalone bundle via Function#toString. A fat-arrow would\n // close over `re` and emit `re.test(value)`, leaving `re` undefined in the\n // generated module. Building it from a string inlines the regex literal into the\n // body, so the bundled output stays self-contained.\n // eslint-disable-next-line no-new-func\n formats[name] = new Function('value', `return ${re.toString()}.test(value)`) as (value: string) => boolean;\n }\n\n const bundle = Validator.bundleStandalone(schemas, {\n format: 'cjs',\n verbose: ataOptionsOverrides.verbose !== false,\n formats,\n });\n\n const entries = keys\n .map((key, index) => ` ${JSON.stringify(key)}: wrap(validators[${index}], ${JSON.stringify(key)}),`)\n .join('\\n');\n\n return [\n 'const validators = (function () {',\n ' const module = { exports: {} };',\n bundle,\n ' return module.exports;',\n '})();',\n 'function wrap(fn, key) {',\n ' function validate(data) {',\n \" if (typeof fn !== 'function') {\",\n \" throw new Error('@rjsf/validator-ata: schema \\\"' + key + '\\\" was not compiled to a standalone validator');\",\n ' }',\n ' const result = fn(data);',\n ' validate.errors = result.valid ? null : result.errors;',\n ' return result.valid;',\n ' }',\n ' return validate;',\n '}',\n 'module.exports = {',\n entries,\n '};',\n '',\n ].join('\\n');\n}\n", "import { Validator, type ValidatorOptions } from 'ata-validator';\nimport isObject from 'lodash/isObject';\n\nimport type { AtaFormatChecker, CustomValidatorOptionsType } from './types';\n\n/** Default options applied to every ata `Validator` constructed for RJSF.\n * `verbose: true` keeps `parentSchema` available on errors, which the RJSF\n * error transformer uses to recover field titles. The remainder match\n * `@rjsf/validator-ajv8`'s defaults (`allErrors`-equivalent behavior is\n * ata's default).\n */\nexport const ATA_CONFIG: ValidatorOptions = {\n verbose: true,\n} as const;\n\n/** Color names + hex + `rgb()` regex source. Mirrors the pattern shipped by\n * `@rjsf/validator-ajv8` so RJSF schemas using `format: 'color'` keep\n * working when swapped to validator-ata.\n */\nexport const COLOR_FORMAT_REGEX =\n /^(#?([0-9A-Fa-f]{3}){1,2}\\b|aqua|black|blue|fuchsia|gray|green|lime|maroon|navy|olive|orange|purple|red|silver|teal|white|yellow|(rgb\\(\\s*\\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\b\\s*,\\s*\\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\b\\s*,\\s*\\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\b\\s*\\))|(rgb\\(\\s*(\\d?\\d%|100%)+\\s*,\\s*(\\d?\\d%|100%)+\\s*,\\s*(\\d?\\d%|100%)+\\s*\\)))$/;\n\n/** RFC 2397 data URL with required mime type and base64 marker, matching\n * the shape used by `@rjsf/validator-ajv8`.\n */\nexport const DATA_URL_FORMAT_REGEX = /^data:([a-z]+\\/[a-z0-9-+.]+)?;(?:name=(.*);)?base64,(.*)$/;\n\n/** Coerces the user-supplied custom format value into the `(value: string)\n * => boolean` shape expected by ata. Strings are treated as RegExp source\n * (anchored at both ends if not already), RegExps are converted to a `.test`\n * call, functions pass through.\n */\nfunction asFormatChecker(spec: string | RegExp | AtaFormatChecker): AtaFormatChecker {\n if (typeof spec === 'function') {\n return spec;\n }\n const re = spec instanceof RegExp ? spec : new RegExp(spec);\n return (value: string) => re.test(value);\n}\n\n/** Builds a fresh `ata-validator` `Validator` for a given schema with all\n * RJSF-aware defaults and user customizations applied.\n *\n * The factory exists so that the validator class can construct one\n * `Validator` per schema-id (ata is schema-bound, unlike AJV's single\n * instance with a schema registry) while keeping the option translation\n * in one place.\n */\nexport default function createAtaInstance(schema: object, options: CustomValidatorOptionsType = {}): Validator {\n const { customFormats, ataOptionsOverrides, additionalMetaSchemas, extenderFn } = options;\n\n const formats: Record<string, AtaFormatChecker> = {\n color: asFormatChecker(COLOR_FORMAT_REGEX),\n 'data-url': asFormatChecker(DATA_URL_FORMAT_REGEX),\n };\n if (isObject(customFormats)) {\n for (const [name, spec] of Object.entries(customFormats!)) {\n formats[name] = asFormatChecker(spec);\n }\n }\n\n const validatorOptions: ValidatorOptions = {\n ...ATA_CONFIG,\n ...ataOptionsOverrides,\n formats,\n };\n\n let validator = new Validator(schema, validatorOptions);\n\n if (Array.isArray(additionalMetaSchemas)) {\n for (const meta of additionalMetaSchemas) {\n validator.addSchema(meta);\n }\n }\n\n if (typeof extenderFn === 'function') {\n validator = extenderFn(validator);\n }\n\n return validator;\n}\n"],
5
+ "mappings": ";AACA,OAAO,QAAQ;;;ACDf,SAAuC,oBAAoB;AAC3D,SAAS,aAAAA,kBAAiB;;;ACD1B,SAAS,iBAAwC;AACjD,OAAO,cAAc;AAkBd,IAAM,qBACX;AAKK,IAAM,wBAAwB;;;ADT9B,SAAS,4BACd,QACA,UAAsC,CAAC,GACvC;AACA,QAAM,aAAa,aAAa,MAAM;AACtC,QAAM,OAAO,OAAO,KAAK,UAAU;AACnC,QAAM,UAAU,OAAO,OAAO,UAAU;AAExC,QAAM,EAAE,eAAe,sBAAsB,CAAC,EAAE,IAAI;AAMpD,QAAM,eAAuC;AAAA,IAC3C,OAAO;AAAA,IACP,YAAY;AAAA,EACd;AACA,MAAI,eAAe;AACjB,eAAW,CAAC,MAAM,KAAK,KAAK,OAAO,QAAQ,aAAa,GAAG;AACzD,UAAI,OAAO,UAAU,YAAY;AAK/B,cAAM,IAAI;AAAA,UACR,uCAAuC,IAAI;AAAA,QAC7C;AAAA,MACF;AACA,mBAAa,IAAI,IAAI,OAAO,UAAU,WAAW,IAAI,OAAO,KAAK,IAAI;AAAA,IACvE;AAAA,EACF;AACA,QAAM,UAAsD,CAAC;AAC7D,aAAW,CAAC,MAAM,EAAE,KAAK,OAAO,QAAQ,YAAY,GAAG;AAOrD,YAAQ,IAAI,IAAI,IAAI,SAAS,SAAS,UAAU,GAAG,SAAS,CAAC,cAAc;AAAA,EAC7E;AAEA,QAAM,SAASC,WAAU,iBAAiB,SAAS;AAAA,IACjD,QAAQ;AAAA,IACR,SAAS,oBAAoB,YAAY;AAAA,IACzC;AAAA,EACF,CAAC;AAED,QAAM,UAAU,KACb,IAAI,CAAC,KAAK,UAAU,KAAK,KAAK,UAAU,GAAG,CAAC,qBAAqB,KAAK,MAAM,KAAK,UAAU,GAAG,CAAC,IAAI,EACnG,KAAK,IAAI;AAEZ,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,EAAE,KAAK,IAAI;AACb;;;ADxEe,SAAR,wBACL,QACA,QACA,UAAsC,CAAC,GACvC;AACA,UAAQ,IAAI,oBAAoB;AAEhC,QAAM,aAAa,4BAA4B,QAAQ,OAAO;AAC9D,UAAQ,IAAI,WAAW,MAAM,EAAE;AAC/B,KAAG,cAAc,QAAQ,UAAU;AACrC;",
6
+ "names": ["Validator", "Validator"]
7
+ }