@crud-api/schema 0.0.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/schema.js ADDED
@@ -0,0 +1,98 @@
1
+ // The Schema extension (specs/schema, design 7.4): a JSON Schema per Collection, kept as the Resources of the reserved
2
+ // Collection `@schema` (D139, D140).
3
+ import { CrudError } from "@crud-api/core";
4
+ import { SCHEMA_COLLECTION, schemaProvider } from "./collection.js";
5
+ import { readSchema } from "./reads.js";
6
+ import { ownedByRegistered, validateWrite } from "./validate.js";
7
+ import { ajvValidator } from "./validator.js";
8
+ import { checkDelete, ownsSchema, writeSchema } from "./writes.js";
9
+ /** The specification version this package implements. */
10
+ export const SCHEMA_VERSION = "0.1.0";
11
+ const OPTION_NAMES = new Set(["validator", "forceStrict"]);
12
+ function checkOptions(options) {
13
+ if (typeof options !== "object" || options === null || Array.isArray(options))
14
+ throw new TypeError("schema(): options must be an object");
15
+ for (const name of Object.keys(options))
16
+ if (!OPTION_NAMES.has(name))
17
+ throw new TypeError(`schema(): unknown option ${name}`);
18
+ const { validator, forceStrict } = options;
19
+ if (validator !== undefined) {
20
+ const v = validator;
21
+ if (typeof v !== "object" || v === null || typeof v.checkSchema !== "function" || typeof v.compile !== "function") {
22
+ throw new TypeError("schema(): validator must have the methods checkSchema and compile (SchemaValidator)");
23
+ }
24
+ if (v.regExp !== undefined && typeof v.regExp !== "function")
25
+ throw new TypeError("schema(): validator.regExp must be a function (pattern, flags) => RegExpLike");
26
+ }
27
+ if (forceStrict !== undefined && typeof forceStrict !== "boolean")
28
+ throw new TypeError("schema(): forceStrict must be a boolean");
29
+ }
30
+ const onSchema = (collection) => collection === SCHEMA_COLLECTION;
31
+ /** D146: the "Derive" Parameter of `create` and `replace` on `@schema` (SCHEMA_DERIVE). */
32
+ const DERIVE = Object.freeze({
33
+ name: "derive",
34
+ operations: Object.freeze(["create", "replaceById", "replaceByQuery"]),
35
+ check(value) {
36
+ if (typeof value !== "boolean")
37
+ throw new CrudError("INVALID_INPUT", "derive must be a boolean", { rule: "SCHEMA_DERIVE" });
38
+ },
39
+ appliesTo: onSchema,
40
+ });
41
+ /** D144: the compiled schemas of a read on `@schema`, as an annotation; set by Protocols (HTTP_SCHEMA_RAW, MCP_SCHEMA_INPUT). */
42
+ const COMPILED = Object.freeze({
43
+ name: "compiled",
44
+ operations: Object.freeze(["get", "list"]),
45
+ check(value) {
46
+ if (value !== true)
47
+ throw new CrudError("INVALID_INPUT", "compiled can only be true");
48
+ },
49
+ appliesTo: onSchema,
50
+ });
51
+ /**
52
+ * The Schema extension: pass it to `createCrudServer({ extensions: [schema(), metadata()] })`, before Relationships
53
+ * and Metadata (D139). It needs the system storage of design 6.10 and a data provider that lists its Collections
54
+ * (SCHEMA_LIST_ALL). One instance serves one Server.
55
+ */
56
+ export function schema(options = {}) {
57
+ checkOptions(options);
58
+ const validator = options.validator ?? ajvValidator();
59
+ const forceStrict = options.forceStrict ?? false;
60
+ let env;
61
+ let virtual;
62
+ const attached = () => {
63
+ if (env === undefined)
64
+ throw new Error("the schema extension is not attached to a Server");
65
+ return env;
66
+ };
67
+ return {
68
+ name: "schema",
69
+ spec: "schema",
70
+ versions: [SCHEMA_VERSION],
71
+ requires: ["metadata"],
72
+ // Schema converts values (to `Rel` among others) before Relationships strips `data`, and Metadata hashes the
73
+ // converted stored form (D139).
74
+ before: ["relationships", "metadata"],
75
+ needsSystemStorage: true,
76
+ reservedCollections: [SCHEMA_COLLECTION],
77
+ errorCodes: ["SCHEMA_INCOMPATIBLE"],
78
+ warningCodes: ["SCHEMA_VIOLATION", "VALIDATION_FORCED"],
79
+ parameters: [DERIVE, COMPILED],
80
+ validator,
81
+ attach(server) {
82
+ if (env !== undefined)
83
+ throw new Error("this schema extension is already attached to a Server: create one per Server");
84
+ if (server.system === null)
85
+ throw new Error("the schema extension needs the system storage of design 6.10");
86
+ if (server.provider.listCollections === undefined) {
87
+ throw new Error(`the schema extension needs a data provider that lists its Collections (SCHEMA_LIST_ALL); ${server.provider.name} has no listCollections`);
88
+ }
89
+ env = Object.freeze({ provider: server.provider, system: server.system, codec: server.codec, forceStrict });
90
+ virtual = schemaProvider(env);
91
+ },
92
+ reservedProvider: (collection) => (onSchema(collection) ? virtual : undefined),
93
+ ownedValues: async (input, ctx) => (onSchema(input.collection) ? ownsSchema : ownedByRegistered(attached(), validator, input.collection, ctx)), // D141, D147.1
94
+ beforeWrite: (input, ctx) => (onSchema(input.collection) ? writeSchema(attached(), validator, input, ctx) : validateWrite(attached(), validator, input, ctx)), // D141, D147
95
+ precondition: (input) => checkDelete(attached(), input),
96
+ afterRead: (input, ctx) => readSchema(attached(), input, ctx),
97
+ };
98
+ }
@@ -0,0 +1,32 @@
1
+ import { type BeforeWriteInput, type HookCtx, type OwnedValues, type Representation, type Resource } from "@crud-api/core";
2
+ import type { Codec } from "@ecson/core";
3
+ import { type SchemaEnv } from "./collection.ts";
4
+ import type { OutputUnit, SchemaValidator } from "./validator.ts";
5
+ /** D147.1: `ownedValues` on a data Collection: the values under a subschema with `estype` of its registered schema. */
6
+ export declare function ownedByRegistered(env: SchemaEnv, validator: SchemaValidator, collection: string, ctx: HookCtx): Promise<OwnedValues | null>;
7
+ /**
8
+ * D157.2: the validation and the conversion of D147 (items 2 and 3) of `value` against any schema, without the strict or
9
+ * lenient policy: the validation tree (a JSON tree for `input: "json"`, the ECSON tree for `"ecson"`), the `refCollection`
10
+ * second pass, the ESType conversion and, with `convertDbType`, the `dbType` conversion of the values without `estype`.
11
+ * `units` is every violation; `value` is the converted copy when there is no unit, else `value` as received. Throws what
12
+ * ESType or the validator throw for a schema they refuse: check it first with `checkSchemaDefinition`. `validateWrite`
13
+ * runs the same steps on the registered schema, which it prepares once per operation.
14
+ */
15
+ export declare function checkValue(schema: unknown, value: Resource, options: {
16
+ validator: SchemaValidator;
17
+ codec: Codec;
18
+ input: Representation;
19
+ convertDbType?: (dbType: string, value: unknown) => unknown;
20
+ }): {
21
+ units: OutputUnit[];
22
+ value: Resource;
23
+ };
24
+ /**
25
+ * D147: `beforeWrite` on a data Collection with a registered schema. The Resource, without `_meta`
26
+ * (SCHEMA_VALIDATE_WRITES), is validated as received (SCHEMA_ESTYPE_VALIDATE) against the schema compiled by ESType,
27
+ * then converted (SCHEMA_VALUE_CONVERSION, SCHEMA_VALUE_NO_ESTYPE). `strict`: any unit fails the write with
28
+ * INVALID_INPUT (SCHEMA_STRICT); `lenient`: one SCHEMA_VIOLATION Warning per unit (SCHEMA_LENIENT, S67), and every
29
+ * value is written converted, except those that cannot be, which are written as received (S64). Without a registered
30
+ * schema: unchanged.
31
+ */
32
+ export declare function validateWrite(env: SchemaEnv, validator: SchemaValidator, input: BeforeWriteInput, ctx: HookCtx): Promise<Resource>;
@@ -0,0 +1,259 @@
1
+ // D147: validation and conversion of the Resources written to a data Collection with a registered schema
2
+ // (SCHEMA_VALIDATE_WRITES, SCHEMA_ESTYPE_VALIDATE, SCHEMA_VALUE_CONVERSION, SCHEMA_VALUE_NO_ESTYPE, SCHEMA_STRICT,
3
+ // SCHEMA_LENIENT, SCHEMA_REF_COLLECTION, SCHEMA_VIOLATION_DETAILS; S64 to S67).
4
+ import { checkFieldNames, CrudError, isPlainObject, isSlug, jsonTree } from "@crud-api/core";
5
+ import { compile, toPointer } from "@estype/core";
6
+ import { SCHEMA_COLLECTION } from "./collection.js";
7
+ import { createCollectingConverter } from "./convert.js";
8
+ import { ownedValues, patternTest } from "./owned.js";
9
+ import { registeredSchema } from "./reads.js";
10
+ /** The key of `HookCtx.local` that caches what validating against a registered schema needs, by Collection (D138). */
11
+ const CACHE = "@crud-api/schema validation";
12
+ /** True when some object inside `value` has the member `name`. */
13
+ function hasMember(value, name) {
14
+ if (Array.isArray(value))
15
+ return value.some((element) => hasMember(element, name));
16
+ if (!isPlainObject(value))
17
+ return false;
18
+ return Object.hasOwn(value, name) || Object.values(value).some((member) => hasMember(member, name));
19
+ }
20
+ /** A schema prepared for `check`: compiled by ESType and by the validator, with its converter (throws for a schema they refuse). */
21
+ function prepare(schema, validator, codec, validation) {
22
+ const matches = patternTest(validator.regExp);
23
+ const compiled = compile(schema);
24
+ return {
25
+ validation,
26
+ schema,
27
+ compiled,
28
+ validate: validator.compile(compiled),
29
+ convert: createCollectingConverter(schema, { codec, matches }),
30
+ matches,
31
+ owned: ownedValues(schema, matches),
32
+ refCollection: hasMember(schema, "refCollection"),
33
+ };
34
+ }
35
+ /** The registered schema of a data Collection, prepared for validation, or null without one (SCHEMA_NULL). */
36
+ async function registered(env, validator, collection, ctx) {
37
+ if (collection === SCHEMA_COLLECTION || !isSlug(collection))
38
+ return null; // other reserved Collections are not described
39
+ let cache = ctx.local.get(CACHE);
40
+ if (cache === undefined) {
41
+ cache = new Map();
42
+ ctx.local.set(CACHE, cache);
43
+ }
44
+ const cached = cache.get(collection);
45
+ if (cached !== undefined)
46
+ return cached;
47
+ const resource = await registeredSchema(env, collection, ctx);
48
+ let prepared = null;
49
+ if (resource !== null && (typeof resource.schema === "boolean" || isPlainObject(resource.schema))) {
50
+ const schema = resource.schema;
51
+ try {
52
+ prepared = prepare(schema, validator, env.codec, resource.validation === "strict" ? "strict" : "lenient");
53
+ }
54
+ catch (error) {
55
+ // D147 amended: a schema stored before D143 compiled it at write time, seeded, or that a custom validator refuses.
56
+ // The Server is at fault, not the Client's Resource; nothing is written.
57
+ throw new CrudError("INTERNAL", `the registered schema of ${collection} cannot be compiled, so no Resource of it can be validated`, {
58
+ rule: "SCHEMA_VALIDATE_WRITES",
59
+ cause: error,
60
+ });
61
+ }
62
+ }
63
+ cache.set(collection, prepared);
64
+ return prepared;
65
+ }
66
+ /** D147.1: `ownedValues` on a data Collection: the values under a subschema with `estype` of its registered schema. */
67
+ export async function ownedByRegistered(env, validator, collection, ctx) {
68
+ return (await registered(env, validator, collection, ctx))?.owned ?? null;
69
+ }
70
+ /**
71
+ * S66: the `keywordLocation` of a conversion failure, since no keyword of the compiled schema fails: the location of the
72
+ * subschema with `estype` reached by following `properties`, `patternProperties` (the first matching pattern),
73
+ * `additionalProperties`, `prefixItems` and `items` from the instance path, plus `/estype`; where the path leaves those
74
+ * keywords (a `$ref`, an `anyOf`), the last subschema reached, without `/estype`.
75
+ */
76
+ function estypeLocation(compiled, path, matches) {
77
+ let node = compiled;
78
+ const segments = [];
79
+ for (const segment of path) {
80
+ if (!isPlainObject(node))
81
+ break;
82
+ if (typeof segment === "string") {
83
+ if (isPlainObject(node.properties) && Object.hasOwn(node.properties, segment)) {
84
+ segments.push("properties", segment);
85
+ node = node.properties[segment];
86
+ continue;
87
+ }
88
+ const pattern = isPlainObject(node.patternProperties) ? Object.keys(node.patternProperties).find((p) => matches(p, segment)) : undefined;
89
+ if (pattern !== undefined) {
90
+ segments.push("patternProperties", pattern);
91
+ node = node.patternProperties[pattern];
92
+ continue;
93
+ }
94
+ if (isPlainObject(node.additionalProperties)) {
95
+ segments.push("additionalProperties");
96
+ node = node.additionalProperties;
97
+ continue;
98
+ }
99
+ }
100
+ else {
101
+ if (Array.isArray(node.prefixItems) && segment < node.prefixItems.length) {
102
+ segments.push("prefixItems", segment);
103
+ node = node.prefixItems[segment];
104
+ continue;
105
+ }
106
+ if (isPlainObject(node.items)) {
107
+ segments.push("items");
108
+ node = node.items;
109
+ continue;
110
+ }
111
+ }
112
+ break;
113
+ }
114
+ if (isPlainObject(node) && Object.hasOwn(node, "estype"))
115
+ segments.push("estype");
116
+ return toPointer(segments);
117
+ }
118
+ /** Sets an own enumerable member, also one named `__proto__`. */
119
+ function define(target, key, value) {
120
+ Object.defineProperty(target, key, { value, writable: true, enumerable: true, configurable: true });
121
+ }
122
+ /**
123
+ * SCHEMA_VALUE_NO_ESTYPE (D147.3): the values of `properties` chains (no arrays) whose subschema has `dbType` and no
124
+ * `estype`, converted by the data provider; a failure adds a unit at `.../dbType` and leaves the value as it is. A new
125
+ * object along the changed paths; `value` is never changed.
126
+ */
127
+ function convertDbTypes(node, value, convert, at, units) {
128
+ if (!isPlainObject(node) || !isPlainObject(node.properties) || !isPlainObject(value))
129
+ return value;
130
+ let out;
131
+ for (const name of Object.keys(node.properties)) {
132
+ const sub = node.properties[name];
133
+ if (!Object.hasOwn(value, name) || !isPlainObject(sub) || Object.hasOwn(sub, "estype"))
134
+ continue;
135
+ const before = value[name];
136
+ let after = before;
137
+ if (typeof sub.dbType === "string") {
138
+ try {
139
+ after = convert(sub.dbType, before);
140
+ }
141
+ catch (error) {
142
+ if (!(error instanceof CrudError))
143
+ throw error;
144
+ units.push({ instanceLocation: toPointer([...at, name]), keywordLocation: toPointer(["properties", ...at.flatMap((n) => [n, "properties"]), name, "dbType"]), error: error.message });
145
+ }
146
+ }
147
+ else {
148
+ after = convertDbTypes(sub, before, convert, [...at, name], units);
149
+ }
150
+ if (after !== before) {
151
+ out ??= { ...value };
152
+ define(out, name, after);
153
+ }
154
+ }
155
+ return out ?? value;
156
+ }
157
+ const unitKey = (unit) => JSON.stringify([unit.instanceLocation, unit.keywordLocation, unit.error]);
158
+ /**
159
+ * D147.3 (SCHEMA_VALUE_CONVERSION, S64, S66): the ESType conversion of `body`, one unit per value that cannot be
160
+ * converted, each such value kept as received and every other value converted. D147 amended: one pass of the collecting
161
+ * converter, linear in the size of the body whatever the number of failures; a path is reported once.
162
+ */
163
+ function convertEach(target, body, units) {
164
+ const { value, failures } = target.convert(body);
165
+ const seen = new Set();
166
+ for (const { path, error } of failures) {
167
+ const key = JSON.stringify(path);
168
+ if (seen.has(key))
169
+ continue;
170
+ seen.add(key);
171
+ units.push({ instanceLocation: toPointer(path), keywordLocation: estypeLocation(target.compiled, path, target.matches), error: error.message });
172
+ }
173
+ return value;
174
+ }
175
+ /**
176
+ * D147.2 and D147.3 without the policy: the units of `body` against a prepared schema (validation as received, the
177
+ * second pass of `refCollection`, then the conversion failures), and `body` converted, every value that cannot be
178
+ * converted kept as received (S64).
179
+ */
180
+ function check(target, body, options) {
181
+ const { codec } = options;
182
+ // D147.2: the validation tree is the value as received: a JSON tree for a plain JSON Subject, else its ECSON tree.
183
+ const units = target.validate(options.input === "json" ? jsonTree(body, codec) : codec.encode(body));
184
+ // D147.3: conversion of the values with `estype`, then of those with `dbType` only (each failing one left as received).
185
+ const conversion = [];
186
+ let result = convertEach(target, body, conversion);
187
+ const { convertDbType } = options;
188
+ if (convertDbType !== undefined)
189
+ result = convertDbTypes(target.schema, result, convertDbType, [], conversion);
190
+ if (target.refCollection) {
191
+ // SCHEMA_REF_COLLECTION, S65: `refCollection` sits in the plain branch of the compiled schema, so every reference is
192
+ // checked through the plain form of the converted value, whatever form it arrived in (a `{ "$rel": ... }` of a plain
193
+ // JSON body is a `Rel` once converted); a value that could not be converted is checked as received.
194
+ const seen = new Set(units.map(unitKey));
195
+ for (const unit of target.validate(codec.toPlain(result))) {
196
+ if (unit.keywordLocation.endsWith("/refCollection") && !seen.has(unitKey(unit))) {
197
+ seen.add(unitKey(unit));
198
+ units.push(unit);
199
+ }
200
+ }
201
+ }
202
+ units.push(...conversion);
203
+ return { units, converted: result };
204
+ }
205
+ /**
206
+ * D157.2: the validation and the conversion of D147 (items 2 and 3) of `value` against any schema, without the strict or
207
+ * lenient policy: the validation tree (a JSON tree for `input: "json"`, the ECSON tree for `"ecson"`), the `refCollection`
208
+ * second pass, the ESType conversion and, with `convertDbType`, the `dbType` conversion of the values without `estype`.
209
+ * `units` is every violation; `value` is the converted copy when there is no unit, else `value` as received. Throws what
210
+ * ESType or the validator throw for a schema they refuse: check it first with `checkSchemaDefinition`. `validateWrite`
211
+ * runs the same steps on the registered schema, which it prepares once per operation.
212
+ */
213
+ export function checkValue(schema, value, options) {
214
+ const { units, converted } = check(prepare(schema, options.validator, options.codec, "strict"), value, options);
215
+ return { units, value: units.length === 0 ? converted : value };
216
+ }
217
+ /**
218
+ * D147: `beforeWrite` on a data Collection with a registered schema. The Resource, without `_meta`
219
+ * (SCHEMA_VALIDATE_WRITES), is validated as received (SCHEMA_ESTYPE_VALIDATE) against the schema compiled by ESType,
220
+ * then converted (SCHEMA_VALUE_CONVERSION, SCHEMA_VALUE_NO_ESTYPE). `strict`: any unit fails the write with
221
+ * INVALID_INPUT (SCHEMA_STRICT); `lenient`: one SCHEMA_VIOLATION Warning per unit (SCHEMA_LENIENT, S67), and every
222
+ * value is written converted, except those that cannot be, which are written as received (S64). Without a registered
223
+ * schema: unchanged.
224
+ */
225
+ export async function validateWrite(env, validator, input, ctx) {
226
+ const { next } = input;
227
+ const target = await registered(env, validator, input.collection, ctx);
228
+ if (target === null)
229
+ return next;
230
+ const hasMeta = Object.hasOwn(next, "_meta");
231
+ const { _meta: meta, ...body } = next;
232
+ const id = typeof next._id === "string" ? next._id : undefined;
233
+ const hooks = env.provider.schema;
234
+ const { units, converted: result } = check(target, body, {
235
+ codec: ctx.codec,
236
+ input: ctx.input,
237
+ ...(hooks !== undefined ? { convertDbType: (dbType, value) => hooks.convertValue(dbType, value) } : {}),
238
+ });
239
+ if (units.length > 0) {
240
+ if (target.validation === "strict") {
241
+ throw new CrudError("INVALID_INPUT", `the Resource${id === undefined ? "" : ` ${id}`} does not conform to the schema of ${input.collection}: ${units[0]?.error ?? ""}`, {
242
+ rule: "SCHEMA_STRICT",
243
+ data: { errors: units, ...(id === undefined ? {} : { id }) },
244
+ });
245
+ }
246
+ for (const unit of units) {
247
+ ctx.warn({ code: "SCHEMA_VIOLATION", message: unit.error, instance: unit.instanceLocation, keyword: unit.keywordLocation, ...(id === undefined ? {} : { id }) });
248
+ }
249
+ }
250
+ const written = result;
251
+ // D147.6: an owned value that was not converted is checked as any other value (FIELDS_NAMES, FIELDS_NO_PREFIXES).
252
+ if (target.owned !== null)
253
+ checkFieldNames(written, input.patch === undefined ? "INVALID_INPUT" : "INVALID_PATCH");
254
+ if (!hasMeta)
255
+ return written;
256
+ const withMeta = { ...written };
257
+ define(withMeta, "_meta", meta);
258
+ return withMeta;
259
+ }
@@ -0,0 +1,52 @@
1
+ /**
2
+ * SCHEMA_VIOLATION_DETAILS: an output unit of the `basic` output format of JSON Schema (Core 12.4.2): where in the
3
+ * instance, where in the schema and what failed. `keywordLocation` is a JSON Pointer into the schema that was used.
4
+ */
5
+ export interface OutputUnit {
6
+ readonly instanceLocation: string;
7
+ readonly keywordLocation: string;
8
+ readonly error: string;
9
+ }
10
+ /** A compiled regular expression: only `test` is used. */
11
+ export interface RegExpLike {
12
+ test(text: string): boolean;
13
+ }
14
+ /**
15
+ * D143 amended: a regular expression engine, `(pattern, flags) => RegExpLike`, the shape of Ajv's `code.regExp`. It
16
+ * throws for a pattern it cannot compile. The patterns come from the schemas Clients write (`pattern`,
17
+ * `patternProperties`), so a linear engine (for example `re2`) keeps a backtracking pattern from blocking the Server.
18
+ */
19
+ export type RegExpEngine = (pattern: string, flags: string) => RegExpLike;
20
+ /** The engine of ECMAScript, `new RegExp(pattern, flags)`: backtracking. */
21
+ export declare const defaultRegExp: RegExpEngine;
22
+ /**
23
+ * D143: the validator behind the Schema extension (D5): the Server never imports a JSON Schema library for anything
24
+ * else, so a Server can bring its own. `ajvValidator()` is the default.
25
+ */
26
+ export interface SchemaValidator {
27
+ /** SCHEMA_META_SCHEMA: the units of a written schema against the dialect and both vocabularies; `[]` when valid. */
28
+ checkSchema(schema: unknown): OutputUnit[];
29
+ /**
30
+ * A validation function for a schema already compiled by ESType; units of the `basic` output format, `[]` when valid.
31
+ * Throws for a schema it cannot compile: a written schema is then refused (SCHEMA_META_SCHEMA, D143 amended).
32
+ */
33
+ compile(compiled: unknown): (instance: unknown) => OutputUnit[];
34
+ /**
35
+ * D143 amended: the regular expression engine of the validator; the extension matches `patternProperties` with it
36
+ * too (owned values, conversion). Default `defaultRegExp`.
37
+ */
38
+ readonly regExp?: RegExpEngine;
39
+ }
40
+ /** Options of `ajvValidator` (D143 amended). */
41
+ export interface AjvValidatorOptions {
42
+ /** The regular expression engine for `pattern` and `patternProperties`, given to Ajv as `code.regExp`; default `defaultRegExp`. */
43
+ readonly regExp?: RegExpEngine;
44
+ }
45
+ /**
46
+ * D143: the Ajv default of `SchemaValidator`. One `Ajv2020` (`allErrors`, not strict, schemas not registered by their
47
+ * `$id`, no logging, own properties only so that `required: ["__proto__"]` holds) with the ESType plugin, the vocabulary
48
+ * meta-schema and the internal meta-schema of `checkSchema`; the keywords `dbType` (an annotation) and `refCollection`.
49
+ * Validation functions are cached by the canonical JSON of the compiled schema, 64 at most, the oldest removed first.
50
+ * D143 amended: `options.regExp` is the engine of `pattern` and `patternProperties`.
51
+ */
52
+ export declare function ajvValidator(options?: AjvValidatorOptions): SchemaValidator;
@@ -0,0 +1,138 @@
1
+ // D143: the validator seam of the Schema extension and its Ajv default (D5, SCHEMA_META_SCHEMA, SCHEMA_VIOLATION_DETAILS).
2
+ import { estype } from "@estype/ajv";
3
+ import { Ajv2020 } from "ajv/dist/2020.js";
4
+ import { CHECK_META_SCHEMA, CHECK_SCHEMA_URI, vocabularyMetaSchema } from "./vocabulary.js";
5
+ /** The engine of ECMAScript, `new RegExp(pattern, flags)`: backtracking. */
6
+ export const defaultRegExp = (pattern, flags) => new RegExp(pattern, flags);
7
+ /** How many validation functions `ajvValidator` keeps; the oldest is removed beyond it (D143). */
8
+ const CACHE_LIMIT = 64;
9
+ /** The JSON of a value with the members of every object in order, so equal schemas have the same text. */
10
+ function canonicalJson(value) {
11
+ if (Array.isArray(value))
12
+ return `[${value.map(canonicalJson).join(",")}]`;
13
+ if (typeof value === "object" && value !== null) {
14
+ const members = Object.keys(value)
15
+ .sort()
16
+ .map((name) => `${JSON.stringify(name)}:${canonicalJson(value[name])}`);
17
+ return `{${members.join(",")}}`;
18
+ }
19
+ return JSON.stringify(value) ?? "null";
20
+ }
21
+ /** SCHEMA_VIOLATION_DETAILS: the units of Ajv errors; `schemaPath` without its `#`, duplicates removed, order kept. */
22
+ function units(errors) {
23
+ const seen = new Set();
24
+ const result = [];
25
+ for (const error of errors ?? []) {
26
+ const unit = {
27
+ instanceLocation: error.instancePath,
28
+ keywordLocation: error.schemaPath.replace(/^#/, ""),
29
+ error: error.message ?? `must pass "${error.keyword}" keyword validation`,
30
+ };
31
+ const key = JSON.stringify(unit);
32
+ if (seen.has(key))
33
+ continue;
34
+ seen.add(key);
35
+ result.push(unit);
36
+ }
37
+ return result;
38
+ }
39
+ const isCollectionObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value) && Object.hasOwn(value, "collection");
40
+ /**
41
+ * SCHEMA_REF_COLLECTION: validates the plain form of a reference. A collection object, or each one of an array, has
42
+ * `collection` equal to the keyword. URIs, Link header strings and link objects are external references and pass
43
+ * (the keyword names an internal Collection); whether the Resource exists is not checked here.
44
+ */
45
+ const refCollection = (expected, data) => {
46
+ const items = Array.isArray(data) ? data : [data];
47
+ const wrong = items.find((item) => isCollectionObject(item) && item.collection !== expected);
48
+ if (wrong === undefined)
49
+ return true;
50
+ refCollection.errors = [
51
+ { keyword: "refCollection", message: `must refer to the collection ${JSON.stringify(expected)}`, params: { refCollection: expected } },
52
+ ];
53
+ return false;
54
+ };
55
+ /** Ajv's `code.regExp`: the engine, with a `toString` per source (Ajv shares compiled expressions by it) and `code`. */
56
+ function ajvRegExp(engine) {
57
+ const wrapped = (pattern, flags) => {
58
+ const re = engine(pattern, flags);
59
+ const like = { test: (text) => re.test(text), toString: () => `/${pattern}/${flags}` };
60
+ return like;
61
+ };
62
+ return Object.assign(wrapped, { code: "regExp" });
63
+ }
64
+ /**
65
+ * D143: the Ajv default of `SchemaValidator`. One `Ajv2020` (`allErrors`, not strict, schemas not registered by their
66
+ * `$id`, no logging, own properties only so that `required: ["__proto__"]` holds) with the ESType plugin, the vocabulary
67
+ * meta-schema and the internal meta-schema of `checkSchema`; the keywords `dbType` (an annotation) and `refCollection`.
68
+ * Validation functions are cached by the canonical JSON of the compiled schema, 64 at most, the oldest removed first.
69
+ * D143 amended: `options.regExp` is the engine of `pattern` and `patternProperties`.
70
+ */
71
+ export function ajvValidator(options = {}) {
72
+ const regExp = options.regExp ?? defaultRegExp;
73
+ if (typeof regExp !== "function")
74
+ throw new TypeError("ajvValidator(): regExp must be a function (pattern, flags) => RegExpLike");
75
+ const code = options.regExp === undefined ? {} : { code: { regExp: ajvRegExp(regExp) } };
76
+ const ajv = estype(new Ajv2020({ allErrors: true, strict: false, addUsedSchema: false, logger: false, ownProperties: true, ...code }));
77
+ ajv.addKeyword({ keyword: "dbType", schemaType: "string" });
78
+ ajv.addKeyword({ keyword: "refCollection", schemaType: "string", validate: refCollection, errors: true });
79
+ ajv.addMetaSchema(structuredClone(vocabularyMetaSchema));
80
+ ajv.addMetaSchema(structuredClone(CHECK_META_SCHEMA));
81
+ const check = ajv.getSchema(CHECK_SCHEMA_URI);
82
+ if (check === undefined)
83
+ throw new Error("the meta-schema of the Schema extension is not registered");
84
+ const cache = new Map();
85
+ // Removes a schema from Ajv's cache. `removeSchema` also removes what is registered under the root `$id` of the
86
+ // removed schema (through the ESType plugin, of its compiled form); the schemas of this validator are never
87
+ // registered by `$id`, so what is there (a meta-schema, the definitions document) is put back. A boolean schema has
88
+ // nothing to remove.
89
+ const forget = (schema) => {
90
+ if (typeof schema !== "object" || schema === null)
91
+ return;
92
+ const id = schema.$id;
93
+ const keys = typeof id === "string" ? [id, id.replace(/#$/, "")] : [];
94
+ const saved = keys.map((key) => [key, ajv.schemas[key], ajv.refs[key]]);
95
+ ajv.removeSchema(schema);
96
+ for (const [key, registered, ref] of saved) {
97
+ if (registered !== undefined)
98
+ ajv.schemas[key] = registered;
99
+ if (ref !== undefined)
100
+ ajv.refs[key] = ref;
101
+ }
102
+ };
103
+ return {
104
+ checkSchema(schema) {
105
+ check(schema);
106
+ return units(check.errors);
107
+ },
108
+ compile(compiled) {
109
+ const key = canonicalJson(compiled);
110
+ const cached = cache.get(key);
111
+ if (cached !== undefined)
112
+ return cached.validate;
113
+ // A copy, so that a later change of the caller's schema never reaches the function (nor the Ajv cache key).
114
+ const schema = JSON.parse(key);
115
+ let fn;
116
+ try {
117
+ fn = ajv.compile(schema);
118
+ }
119
+ catch (error) {
120
+ forget(schema); // Ajv keeps the schema of a failed compilation
121
+ throw error;
122
+ }
123
+ const validate = (instance) => (fn(instance) ? [] : units(fn.errors));
124
+ cache.set(key, { schema, validate });
125
+ if (cache.size > CACHE_LIMIT) {
126
+ const [oldest] = cache.keys();
127
+ if (oldest !== undefined) {
128
+ const evicted = cache.get(oldest)?.schema;
129
+ if (evicted !== undefined)
130
+ forget(evicted);
131
+ cache.delete(oldest);
132
+ }
133
+ }
134
+ return validate;
135
+ },
136
+ regExp,
137
+ };
138
+ }
@@ -0,0 +1,23 @@
1
+ /** SCHEMA_VOCABULARY: URI of the vocabulary of the keywords `refCollection` and `dbType` (provisional). */
2
+ export declare const VOCABULARY_URI = "https://lingodata.dev/crud/schema/vocab/0.1";
3
+ /** SCHEMA_VOCABULARY: URI of the meta-schema of the vocabulary (provisional). */
4
+ export declare const META_SCHEMA_URI = "https://lingodata.dev/crud/schema/meta/0.1";
5
+ /** The 2020-12 meta-schema, the dialect of a `schema` without `$schema` (SCHEMA_DIALECT). */
6
+ export declare const JSON_SCHEMA_2020_12 = "https://json-schema.org/draft/2020-12/schema";
7
+ /** SCHEMA_DIALECT: the dialects a Server accepts in `$schema`, JSON Schema 2020-12 and the ESType dialect (D142). */
8
+ export declare const SUPPORTED_DIALECTS: readonly string[];
9
+ /** `$id` of the internal meta-schema that `checkSchema` validates against (not a published URI). */
10
+ export declare const CHECK_SCHEMA_URI = "urn:crud-api:schema:check";
11
+ /**
12
+ * SCHEMA_VOCABULARY, SCHEMA_META_SCHEMA, SCHEMA_REF_COLLECTION: the meta-schema of the vocabulary. `refCollection` is a
13
+ * Slug, `dbType` a non-empty string. Like the ESType vocabulary meta-schema it is meant to be combined with the
14
+ * dialect through `$dynamicAnchor: "meta"` (see `CHECK_META_SCHEMA`), and declares the vocabulary with `false` so that a
15
+ * validator that does not know it still processes the schemas that use it (JSON Schema Core 8.1.2).
16
+ */
17
+ export declare const vocabularyMetaSchema: Readonly<Record<string, unknown>>;
18
+ /**
19
+ * D143, SCHEMA_META_SCHEMA: the meta-schema `checkSchema` validates a written `schema` against. Every subschema is
20
+ * checked against 2020-12 and both vocabularies, because the three schemas it combines reach their subschemas with
21
+ * `$dynamicRef: "#meta"`, which resolves to this one (the dynamic anchor of the outermost schema).
22
+ */
23
+ export declare const CHECK_META_SCHEMA: Readonly<Record<string, unknown>>;
@@ -0,0 +1,52 @@
1
+ // The CRUD Schema vocabulary (SCHEMA_VOCABULARY, section 1.4) and the meta-schemas built from it (SCHEMA_META_SCHEMA, D142).
2
+ import { DIALECT_URI, META_SCHEMA_URI as ESTYPE_META_SCHEMA_URI } from "@estype/core";
3
+ /** SCHEMA_VOCABULARY: URI of the vocabulary of the keywords `refCollection` and `dbType` (provisional). */
4
+ export const VOCABULARY_URI = "https://lingodata.dev/crud/schema/vocab/0.1";
5
+ /** SCHEMA_VOCABULARY: URI of the meta-schema of the vocabulary (provisional). */
6
+ export const META_SCHEMA_URI = "https://lingodata.dev/crud/schema/meta/0.1";
7
+ /** The 2020-12 meta-schema, the dialect of a `schema` without `$schema` (SCHEMA_DIALECT). */
8
+ export const JSON_SCHEMA_2020_12 = "https://json-schema.org/draft/2020-12/schema";
9
+ /** SCHEMA_DIALECT: the dialects a Server accepts in `$schema`, JSON Schema 2020-12 and the ESType dialect (D142). */
10
+ export const SUPPORTED_DIALECTS = Object.freeze([JSON_SCHEMA_2020_12, DIALECT_URI]);
11
+ /** `$id` of the internal meta-schema that `checkSchema` validates against (not a published URI). */
12
+ export const CHECK_SCHEMA_URI = "urn:crud-api:schema:check";
13
+ /** A Slug of Base section 2.6 (COLLECTION_SLUG), as the pattern of a meta-schema. */
14
+ const SLUG_PATTERN = "^[a-zA-Z0-9_-]+$";
15
+ function deepFreeze(value) {
16
+ if (typeof value === "object" && value !== null && !Object.isFrozen(value)) {
17
+ Object.freeze(value);
18
+ for (const member of Object.values(value))
19
+ deepFreeze(member);
20
+ }
21
+ return value;
22
+ }
23
+ /**
24
+ * SCHEMA_VOCABULARY, SCHEMA_META_SCHEMA, SCHEMA_REF_COLLECTION: the meta-schema of the vocabulary. `refCollection` is a
25
+ * Slug, `dbType` a non-empty string. Like the ESType vocabulary meta-schema it is meant to be combined with the
26
+ * dialect through `$dynamicAnchor: "meta"` (see `CHECK_META_SCHEMA`), and declares the vocabulary with `false` so that a
27
+ * validator that does not know it still processes the schemas that use it (JSON Schema Core 8.1.2).
28
+ */
29
+ export const vocabularyMetaSchema = deepFreeze({
30
+ $schema: JSON_SCHEMA_2020_12,
31
+ $id: META_SCHEMA_URI,
32
+ $vocabulary: { [VOCABULARY_URI]: false },
33
+ $dynamicAnchor: "meta",
34
+ title: "CRUD Schema vocabulary meta-schema",
35
+ type: ["object", "boolean"],
36
+ properties: {
37
+ refCollection: { type: "string", pattern: SLUG_PATTERN },
38
+ dbType: { type: "string", minLength: 1 },
39
+ },
40
+ });
41
+ /**
42
+ * D143, SCHEMA_META_SCHEMA: the meta-schema `checkSchema` validates a written `schema` against. Every subschema is
43
+ * checked against 2020-12 and both vocabularies, because the three schemas it combines reach their subschemas with
44
+ * `$dynamicRef: "#meta"`, which resolves to this one (the dynamic anchor of the outermost schema).
45
+ */
46
+ export const CHECK_META_SCHEMA = deepFreeze({
47
+ $schema: JSON_SCHEMA_2020_12,
48
+ $id: CHECK_SCHEMA_URI,
49
+ $dynamicAnchor: "meta",
50
+ title: "JSON Schema 2020-12 with the ESType and CRUD Schema vocabularies",
51
+ allOf: [{ $ref: JSON_SCHEMA_2020_12 }, { $ref: ESTYPE_META_SCHEMA_URI }, { $ref: META_SCHEMA_URI }],
52
+ });