@crud-api/schema 0.0.0-stage → 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/dist/writes.js ADDED
@@ -0,0 +1,180 @@
1
+ // Writes on `@schema`: the checks of a schema Resource (D141), of the written schema (D142), derivation (D146), the
2
+ // Collection it describes (D145) and the Data sources with their own schema (D148).
3
+ import { CrudError, isPlainObject, isSlug } from "@crud-api/core";
4
+ import { children, compile, EstypeError } from "@estype/core";
5
+ import { SCHEMA_COLLECTION } from "./collection.js";
6
+ import { jsonTree } from "./json-tree.js";
7
+ import { SUPPORTED_DIALECTS } from "./vocabulary.js";
8
+ /** SCHEMA_RESOURCE_FIELDS: the Fields of a schema Resource (`_meta` is Metadata's). */
9
+ const FIELDS = new Set(["_id", "validation", "schema", "_meta"]);
10
+ /** The writes whose Resource a patch produced: their failures are INVALID_PATCH (D141). */
11
+ const PATCHES = new Set(["patchById", "patchByQuery"]);
12
+ const DELETES = new Set(["deleteById", "deleteByQuery"]);
13
+ /** D141: on `@schema` the extension reads `schema` itself, so `$schema`, `$ref`, `$defs` and `$id` are not FIELDS_NO_PREFIXES. */
14
+ export const ownsSchema = (path) => path[0] === "schema";
15
+ /** Every schema object of a schema, itself included, through the subschema positions of JSON Schema 2020-12. */
16
+ function* subschemas(schema) {
17
+ if (!isPlainObject(schema))
18
+ return;
19
+ yield schema;
20
+ for (const child of children(schema))
21
+ yield* subschemas(child.schema);
22
+ }
23
+ /** SCHEMA_DIALECT: a supported dialect URI, also with an empty fragment. */
24
+ const supported = (dialect) => SUPPORTED_DIALECTS.includes(dialect.endsWith("#") ? dialect.slice(0, -1) : dialect);
25
+ /**
26
+ * D142, in this order: the dialect of every `$schema` (SCHEMA_DIALECT, NEGOTIATION), the meta-schema of the dialect and
27
+ * both vocabularies (SCHEMA_META_SCHEMA, SCHEMA_VOCABULARY), the ESType compilation (SCHEMA_META_SCHEMA), `refCollection`
28
+ * only with `estype: rel` (SCHEMA_REF_COLLECTION), an explicit type for `_id` (SCHEMA_ID_FIELD, S59, S60), no `_meta`
29
+ * (SCHEMA_NO_META_FIELD) and last the compilation of the ESType result by the validator (SCHEMA_META_SCHEMA, D143
30
+ * amended). These failures are INVALID_INPUT, as the rules name it, whatever produced the Resource.
31
+ */
32
+ function checkWrittenSchema(schema, validator) {
33
+ for (const node of subschemas(schema)) {
34
+ const dialect = node.$schema;
35
+ if (typeof dialect === "string" && !supported(dialect)) {
36
+ throw new CrudError("NEGOTIATION", `the schema dialect ${dialect} is not supported`, { rule: "SCHEMA_DIALECT", data: { supported: [...SUPPORTED_DIALECTS] } });
37
+ }
38
+ }
39
+ const errors = validator.checkSchema(schema);
40
+ if (errors.length > 0) {
41
+ throw new CrudError("INVALID_INPUT", `the schema does not conform to its meta-schema: ${errors[0]?.error ?? ""}`, { rule: "SCHEMA_META_SCHEMA", data: { errors } });
42
+ }
43
+ let compiled;
44
+ try {
45
+ compiled = compile(schema);
46
+ }
47
+ catch (error) {
48
+ if (!(error instanceof EstypeError))
49
+ throw error;
50
+ throw new CrudError("INVALID_INPUT", `the schema cannot be compiled by ESType: ${error.message}`, {
51
+ rule: "SCHEMA_META_SCHEMA",
52
+ data: { estypeCode: error.code, path: [...error.path] },
53
+ });
54
+ }
55
+ for (const node of subschemas(schema)) {
56
+ if (Object.hasOwn(node, "refCollection") && node.estype !== "rel") {
57
+ throw new CrudError("INVALID_INPUT", "refCollection is only allowed with estype rel", { rule: "SCHEMA_REF_COLLECTION" });
58
+ }
59
+ }
60
+ const properties = isPlainObject(schema) && isPlainObject(schema.properties) ? schema.properties : undefined;
61
+ const id = properties !== undefined && Object.hasOwn(properties, "_id") ? properties._id : undefined;
62
+ if (!isPlainObject(id) || !Object.hasOwn(id, "type")) {
63
+ throw new CrudError("INVALID_INPUT", "the schema must describe the _id Field with an explicit type (properties._id.type)", { rule: "SCHEMA_ID_FIELD" });
64
+ }
65
+ const required = isPlainObject(schema) && Array.isArray(schema.required) ? schema.required : [];
66
+ if (Object.hasOwn(properties, "_meta") || required.includes("_meta")) {
67
+ throw new CrudError("INVALID_INPUT", "the schema must not describe the _meta Field", { rule: "SCHEMA_NO_META_FIELD" });
68
+ }
69
+ // D143 amended: the validator compiles the schema now, so that a schema it cannot compile (an unresolvable `$ref`, an
70
+ // invalid `pattern`, a `$ref` cycle, an `$id` clash) is refused here instead of making its Collection unwritable.
71
+ try {
72
+ validator.compile(compiled);
73
+ }
74
+ catch (error) {
75
+ // Ajv's MissingRefError keeps the name Error: the class name tells it apart.
76
+ const reason = error instanceof Error ? error.constructor.name || error.name : typeof error;
77
+ const detail = error instanceof Error ? error.message : String(error);
78
+ throw new CrudError("INVALID_INPUT", `the schema cannot be compiled by the validator: ${detail}`, { rule: "SCHEMA_META_SCHEMA", data: { reason } });
79
+ }
80
+ }
81
+ /** SCHEMA_DB_TYPE_INFER: top-level properties without `dbType` get the one the Data source infers; a new tree. */
82
+ function inferDbTypes(schema, infer) {
83
+ if (!isPlainObject(schema.properties))
84
+ return schema;
85
+ const properties = {};
86
+ for (const [name, property] of Object.entries(schema.properties)) {
87
+ let value = property;
88
+ if (isPlainObject(property) && !Object.hasOwn(property, "dbType")) {
89
+ const dbType = infer(property);
90
+ if (dbType !== undefined)
91
+ value = { ...property, dbType };
92
+ }
93
+ Object.defineProperty(properties, name, { value, writable: true, enumerable: true, configurable: true });
94
+ }
95
+ return { ...schema, properties };
96
+ }
97
+ /**
98
+ * `beforeWrite` on `@schema`: the Resource the write stores, `{ _id, validation, schema }` plus Metadata's `_meta`.
99
+ * D141, in this order: `_id` given (SCHEMA_CREATE_ID, SCHEMA_CLONE_ID), a Slug (SCHEMA_COLLECTION), no other Field
100
+ * (SCHEMA_RESOURCE_FIELDS); then the Collection (D145), derivation (D146), `schema` and `validation`
101
+ * (SCHEMA_RESOURCE_FIELDS); then D142 and D148.
102
+ */
103
+ export async function writeSchema(env, validator, input, ctx) {
104
+ const { operation, next } = input;
105
+ const patched = PATCHES.has(operation) || (operation === "clone" && input.patch !== undefined);
106
+ const code = patched ? "INVALID_PATCH" : "INVALID_INPUT";
107
+ // SCHEMA_CREATE_ID, SCHEMA_CLONE_ID: the ID is the Slug of the described Collection, so the Server never makes one.
108
+ if (!Object.hasOwn(next, "_id") || next._id === undefined) {
109
+ const clone = operation === "clone";
110
+ throw new CrudError("INVALID_INPUT", clone ? "clone on @schema needs the Resource ID of the copy, the Slug of the target Collection" : "a schema Resource needs its _id, the Slug of the Collection it describes", {
111
+ rule: clone ? "SCHEMA_CLONE_ID" : "SCHEMA_CREATE_ID",
112
+ });
113
+ }
114
+ const id = next._id;
115
+ if (typeof id !== "string" || !isSlug(id)) {
116
+ throw new CrudError(code, `the _id of a schema Resource must be the Slug of a Collection, not ${JSON.stringify(id)}`, { rule: "SCHEMA_COLLECTION" });
117
+ }
118
+ for (const field of Object.keys(next)) {
119
+ if (!FIELDS.has(field))
120
+ throw new CrudError(code, `a schema Resource has no Field ${field} (only _id, validation, schema and _meta)`, { rule: "SCHEMA_RESOURCE_FIELDS" });
121
+ }
122
+ // D145: SCHEMA_COLLECTION_MISSING, unless the data provider creates Collections (SCHEMA_COLLECTION_CREATE, done in
123
+ // the virtual provider's write, D140).
124
+ const { provider } = env;
125
+ if ((await provider.collection(id, {})) === null && !(provider.capabilities().implicitCollections && provider.createCollection !== undefined)) {
126
+ throw new CrudError("NOT_FOUND", `Collection ${id} not found`, { rule: "SCHEMA_COLLECTION_MISSING", target: "collection" });
127
+ }
128
+ // D146: derivation, only when the Client asks for it (SCHEMA_DERIVE_EXPLICIT).
129
+ let value = next.schema;
130
+ let present = Object.hasOwn(next, "schema");
131
+ if (input.params.derive === true) {
132
+ if (present)
133
+ throw new CrudError("INVALID_INPUT", "a request with derive must not include schema", { rule: "SCHEMA_DERIVE_NO_SCHEMA" });
134
+ const derived = (await provider.schema?.deriveSchema?.(id, {})) ?? null;
135
+ if (derived === null)
136
+ throw new CrudError("UNSUPPORTED", `the schema of ${id} cannot be derived from the Data source`, { rule: "SCHEMA_DERIVE_UNSUPPORTED" });
137
+ value = derived;
138
+ present = true;
139
+ }
140
+ // SCHEMA_RESOURCE_FIELDS: `null` is how the Server represents no schema (SCHEMA_NULL), never a value a Client
141
+ // writes; deleting is how a schema is removed. The value becomes a JSON tree without escaping (D141).
142
+ const schema = present ? jsonTree(value, ctx.codec) : undefined;
143
+ if (typeof schema !== "boolean" && !isPlainObject(schema)) {
144
+ throw new CrudError(code, "schema must be a JSON Schema: an object or a boolean", { rule: "SCHEMA_RESOURCE_FIELDS" });
145
+ }
146
+ const sent = Object.hasOwn(next, "validation") ? next.validation : undefined;
147
+ if (sent !== undefined && sent !== "strict" && sent !== "lenient") {
148
+ throw new CrudError(code, "validation must be strict or lenient", { rule: "SCHEMA_RESOURCE_FIELDS" });
149
+ }
150
+ checkWrittenSchema(schema, validator); // D142
151
+ // D148: Data sources with their own schema.
152
+ const hooks = provider.schema;
153
+ const own = hooks !== undefined && (await hooks.ownSchema(id, {}));
154
+ if (own && (env.system !== provider || !env.system.capabilities().transactions || env.system.transaction === undefined)) {
155
+ throw new CrudError("UNSUPPORTED", `the schema of ${id} and the schema of its Data source cannot change together atomically`, { rule: "SCHEMA_SOURCE_APPLY" });
156
+ }
157
+ for (const node of subschemas(schema)) {
158
+ const dbType = node.dbType;
159
+ if (typeof dbType === "string" && hooks?.acceptsDbType(dbType, node) !== true) {
160
+ throw new CrudError("SCHEMA_INCOMPATIBLE", `the Data source does not accept the dbType ${dbType}`, { rule: "SCHEMA_DB_TYPE_CLIENT", data: { dbType } });
161
+ }
162
+ }
163
+ const stored = own && hooks !== undefined && isPlainObject(schema) ? inferDbTypes(schema, (field) => hooks.inferDbType(field)) : schema;
164
+ const forced = own || env.forceStrict; // SCHEMA_FORCED_STRICT
165
+ if (forced && sent === "lenient") {
166
+ ctx.warn({ code: "VALIDATION_FORCED", message: `the schema of ${id} is stored with validation strict`, id });
167
+ }
168
+ const validation = forced ? "strict" : (sent ?? "lenient"); // SCHEMA_VALIDATION_DEFAULT
169
+ return { ...next, validation, schema: stored };
170
+ }
171
+ /** SCHEMA_SOURCE_DELETE (D148): deleting the schema of a Collection whose Data source has its own schema is UNSUPPORTED. */
172
+ export async function checkDelete(env, input) {
173
+ if (input.collection !== SCHEMA_COLLECTION || !DELETES.has(input.operation) || input.current === null)
174
+ return;
175
+ const id = input.current._id;
176
+ const hooks = env.provider.schema;
177
+ if (typeof id === "string" && hooks !== undefined && (await hooks.ownSchema(id, {}))) {
178
+ throw new CrudError("UNSUPPORTED", `the Data source of ${id} enforces its own schema, so its schema cannot be deleted`, { rule: "SCHEMA_SOURCE_DELETE" });
179
+ }
180
+ }
package/package.json CHANGED
@@ -1,6 +1,61 @@
1
1
  {
2
2
  "name": "@crud-api/schema",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Schema extension of the CRUD API reference implementation: a JSON Schema per Collection, validation of written Resources, the CRUD Schema vocabulary and the ESType vocabulary",
5
+ "keywords": [
6
+ "crud",
7
+ "api",
8
+ "schema",
9
+ "json-schema",
10
+ "estype",
11
+ "validation",
12
+ "lingodata"
13
+ ],
14
+ "homepage": "https://lingodata.3gr.am/crud/",
15
+ "bugs": {
16
+ "url": "https://github.com/lingodata/crud/issues"
17
+ },
18
+ "repository": {
19
+ "type": "git",
20
+ "url": "git+https://github.com/lingodata/crud.git",
21
+ "directory": "packages/schema"
22
+ },
23
+ "license": "Apache-2.0",
24
+ "author": "Gustavo Gondim",
25
+ "type": "module",
26
+ "sideEffects": false,
27
+ "exports": {
28
+ ".": {
29
+ "types": "./dist/index.d.ts",
30
+ "default": "./dist/index.js"
31
+ },
32
+ "./package.json": "./package.json"
33
+ },
34
+ "types": "./dist/index.d.ts",
35
+ "files": [
36
+ "dist",
37
+ "README.md",
38
+ "LICENSE"
39
+ ],
40
+ "engines": {
41
+ "node": ">=24"
42
+ },
43
+ "publishConfig": {
44
+ "access": "public"
45
+ },
46
+ "dependencies": {
47
+ "@crud-api/core": "^0.5.0",
48
+ "@estype/ajv": "^0.2.0",
49
+ "@estype/core": "^0.2.0",
50
+ "@unquery/core": "^0.2.0",
51
+ "ajv": "^8.20.0"
52
+ },
53
+ "peerDependencies": {
54
+ "@ecson/core": "^0.2.0"
55
+ },
56
+ "devDependencies": {
57
+ "@crud-api/memory": "^0.5.0",
58
+ "@crud-api/metadata": "^0.1.3",
59
+ "@crud-api/relationships": "^0.1.1"
60
+ }
61
+ }