@vitavision/forms 0.6.5 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -29,6 +29,8 @@
29
29
  * reported nowhere near the field that caused it.
30
30
  */
31
31
 
32
+ import { labelFor, resolveSchema } from "./schemaNode";
33
+
32
34
  /** The subset of JSON Schema that pydantic (or an equivalent generator) emits for an options model. */
33
35
  export type SchemaNode = {
34
36
  type?: string;
@@ -108,51 +110,18 @@ export type FieldSpec = {
108
110
  range: string | null;
109
111
  };
110
112
 
111
- const DEFS_PREFIX = "#/$defs/";
112
-
113
- /**
114
- * Follow a `$ref` into `$defs`.
115
- *
116
- * The merge order matters and is the opposite of the obvious one. Pydantic writes the
117
- * field's `default` and `description` *beside* the `$ref`, while the target carries the
118
- * enum's own `title` and sometimes its own docstring as a `description`. The field's
119
- * statement about itself wins; the type's is the fallback.
120
- */
121
- function deref(node: SchemaNode, defs: Record<string, SchemaNode> | undefined): SchemaNode {
122
- if (node.$ref === undefined) return node;
123
- if (!node.$ref.startsWith(DEFS_PREFIX)) return node;
124
-
125
- const target = defs?.[node.$ref.slice(DEFS_PREFIX.length)];
126
- if (target === undefined) return node;
127
-
128
- const rest: SchemaNode = { ...node };
129
- delete rest.$ref;
130
- return { ...target, ...rest };
131
- }
132
-
133
- /**
134
- * Look through pydantic's `str | None` encoding to the type that carries the meaning.
135
- *
136
- * An optional string arrives as `anyOf: [{type: "string"}, {type: "null"}]`, and treating
137
- * that as an unrecognised node would give every nullable option a JSON textarea.
138
- */
139
- function unwrap(node: SchemaNode): SchemaNode {
140
- if (!node.anyOf) return node;
141
- const meaningful = node.anyOf.filter((branch) => branch.type !== "null");
142
- return meaningful.length === 1 ? { ...node, ...meaningful[0] } : node;
143
- }
144
-
145
113
  /**
146
- * The node that says what this field *is*.
114
+ * The node that says what this field *is*, looked through `$ref` and "or null" encodings
115
+ * by the same resolver `SchemaValueForm` reads schemas with (see `schemaNode.ts`).
147
116
  *
148
- * Dereferenced on both sides of the unwrap because either can hold the `$ref`: a plain
149
- * `ColorMode` is a bare `$ref`, while an `Optional[ColorMode]` hides one inside `anyOf`.
117
+ * Both sides of the null-unwrap can hold the `$ref`: a plain `ColorMode` is a bare
118
+ * `$ref`, while an `Optional[ColorMode]` hides one inside `anyOf`.
150
119
  */
151
- function resolve(node: SchemaNode, defs: Record<string, SchemaNode> | undefined): SchemaNode {
152
- return deref(unwrap(deref(node, defs)), defs);
120
+ function resolve(node: SchemaNode, root: OptionsSchema): SchemaNode {
121
+ return resolveSchema(node, root).schema;
153
122
  }
154
123
 
155
- function kindOf(resolved: SchemaNode): FieldKind {
124
+ function kindOf(resolved: SchemaNode, root: OptionsSchema): FieldKind {
156
125
  // Before `type`, always: a `Literal` carries both, and the closed set is the stronger
157
126
  // statement of the two.
158
127
  if (Array.isArray(resolved.enum) && resolved.enum.length > 0) {
@@ -161,7 +130,7 @@ function kindOf(resolved: SchemaNode): FieldKind {
161
130
  if (resolved.type === "boolean") return "boolean";
162
131
  if (resolved.type === "integer" || resolved.type === "number") return "number";
163
132
  if (resolved.type === "string") return "text";
164
- if (resolved.type === "array" && unwrap(resolved.items ?? {}).type === "string") {
133
+ if (resolved.type === "array" && resolve(resolved.items ?? {}, root).type === "string") {
165
134
  return "string-list";
166
135
  }
167
136
  return "json";
@@ -202,26 +171,6 @@ function isPrimary(node: SchemaNode, resolved: SchemaNode): boolean {
202
171
  /** Raw control state: what the operator chose, not what will be sent. */
203
172
  export type RawValues = Record<string, string | boolean>;
204
173
 
205
- /**
206
- * Humanise `normal_dirs` into `Normal dirs`.
207
- *
208
- * Pydantic emits a `title` for every field whether or not anyone wrote one, and its
209
- * generated form is Title Case — `Csv Path`, `Defect Type From Dir` — which reads like a
210
- * spreadsheet header rather than a form label. So a title is used only when it is *not*
211
- * the one pydantic would have generated, which is exactly when a human chose it.
212
- *
213
- * Read from the *unresolved* node on purpose. Dereferencing pulls in the enum class's own
214
- * title, so a resolved `color` field would be labelled "ColorMode".
215
- */
216
- function labelFor(name: string, node: SchemaNode): string {
217
- const words = name.split("_");
218
- const generated = words.map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join(" ");
219
- if (node.title && node.title !== generated) return node.title;
220
-
221
- const spaced = words.join(" ");
222
- return spaced.charAt(0).toUpperCase() + spaced.slice(1);
223
- }
224
-
225
174
  /**
226
175
  * A value as a person reads it: scalars as themselves, anything structured as JSON rather
227
176
  * than `[object Object]`.
@@ -285,11 +234,9 @@ function stepOf(resolved: SchemaNode): number | "any" | undefined {
285
234
  */
286
235
  export function describeFields(schema: OptionsSchema): FieldSpec[] {
287
236
  const required = new Set(schema.required ?? []);
288
- const defs = schema.$defs;
289
-
290
237
  return Object.entries(schema.properties ?? {}).map(([name, node]) => {
291
- const resolved = resolve(node, defs);
292
- const kind = kindOf(resolved);
238
+ const resolved = resolve(node, schema);
239
+ const kind = kindOf(resolved, schema);
293
240
  const numeric =
294
241
  (kind === "choice" || kind === "choice-inline") &&
295
242
  (resolved.type === "integer" || resolved.type === "number");
@@ -0,0 +1,253 @@
1
+ /**
2
+ * The schema-normalisation both forms stand on: follow a `$ref`, look through the
3
+ * "or null" encodings, and name a field.
4
+ *
5
+ * `SchemaForm` (a flat "unset vs override" form) and `SchemaValueForm` (a full-value
6
+ * editor) differ in what they do with a schema, not in how they read one. Every shape that
7
+ * needs a decision — pydantic's `anyOf: [T, null]`, schemars' `type: ["T", "null"]`, a
8
+ * `$ref` with the field's own `default` and `description` written beside it — is decided
9
+ * here, once, so the two forms cannot drift into disagreeing about what a node *is*.
10
+ */
11
+
12
+ /**
13
+ * The subset of JSON Schema (draft 2020-12, as schemars and pydantic emit it) the forms
14
+ * read. Keywords the forms do not read are simply absent: a real schema carries `$schema`,
15
+ * `title` and `format` on the root and the form ignores what it does not know.
16
+ *
17
+ * A schema imported from a `.json` file is assignable as it is; a loosely typed one needs
18
+ * a cast (`as unknown as JsonSchema`).
19
+ */
20
+ export interface JsonSchema {
21
+ /** A reference, normally into `$defs` (`#/$defs/Name`). */
22
+ $ref?: string | undefined;
23
+ /** Where a nested struct or an enum lands: schemars and pydantic never inline those. */
24
+ $defs?: Record<string, JsonSchema> | undefined;
25
+ /** The draft-07 spelling of `$defs`. */
26
+ definitions?: Record<string, JsonSchema> | undefined;
27
+ /** One type, or several (`["integer", "null"]` is a nullable integer). */
28
+ type?: string | string[] | undefined;
29
+ /** A human name. On a field it is a label; on a `$defs` entry it is a type name. */
30
+ title?: string | undefined;
31
+ /** Rustdoc or a docstring: Markdown, possibly several paragraphs. */
32
+ description?: string | undefined;
33
+ /** What applies when the field is absent. */
34
+ default?: unknown;
35
+ /** The one value allowed. */
36
+ const?: unknown;
37
+ /** The closed set of values allowed. */
38
+ enum?: unknown[] | undefined;
39
+ /** Rust integer and float widths: `uint`, `uint32`, `double`, … */
40
+ format?: string | undefined;
41
+ /** An object's fields, in schema order. */
42
+ properties?: Record<string, JsonSchema> | undefined;
43
+ /** The fields that must be present. */
44
+ required?: string[] | undefined;
45
+ /** `false` closes an object; a schema types a map's values. */
46
+ additionalProperties?: JsonSchema | boolean | undefined;
47
+ /** An array's element schema. */
48
+ items?: JsonSchema | boolean | undefined;
49
+ /** A tuple's per-position schemas. */
50
+ prefixItems?: JsonSchema[] | undefined;
51
+ /** The fewest elements. */
52
+ minItems?: number | undefined;
53
+ /** The most elements. */
54
+ maxItems?: number | undefined;
55
+ /** Exactly one of these (serde enums). */
56
+ oneOf?: JsonSchema[] | undefined;
57
+ /** At least one of these (`Option<T>` is `[T, null]`). */
58
+ anyOf?: JsonSchema[] | undefined;
59
+ /** All of these; the forms read only the one-entry form older schemars wrapped a `$ref` in. */
60
+ allOf?: JsonSchema[] | undefined;
61
+ /** Inclusive lower bound. */
62
+ minimum?: number | undefined;
63
+ /** Inclusive upper bound. */
64
+ maximum?: number | undefined;
65
+ /** Exclusive lower bound. */
66
+ exclusiveMinimum?: number | undefined;
67
+ /** Exclusive upper bound. */
68
+ exclusiveMaximum?: number | undefined;
69
+ /** The step a number moves in. */
70
+ multipleOf?: number | undefined;
71
+ /** The quantity's unit (`px`, `mm`): a vitavision extension, written by the Rust configs. */
72
+ "x-unit"?: string | undefined;
73
+ /** The schema's own answer to "does the caller have to think about this?" (`SchemaForm`). */
74
+ "x-primary"?: boolean | undefined;
75
+ }
76
+
77
+ /** A node after its `$ref` and its "or null" encoding have been looked through. */
78
+ export interface ResolvedSchema<T extends JsonSchema = JsonSchema> {
79
+ /** The node that says what the value *is*: no `$ref`, and no null branch left to see. */
80
+ schema: T;
81
+ /** True when `null` was an accepted value of the node as written. */
82
+ nullable: boolean;
83
+ }
84
+
85
+ /** Enough hops for any real schema; a `$ref` cycle ends here instead of looping. */
86
+ const MAX_HOPS = 16;
87
+
88
+ function isObject(value: unknown): value is Record<string, unknown> {
89
+ return typeof value === "object" && value !== null && !Array.isArray(value);
90
+ }
91
+
92
+ /**
93
+ * Follow a JSON Pointer `$ref` (`#`, `#/$defs/Name`, `#/definitions/Name`) from the root.
94
+ *
95
+ * @param ref - The `$ref` string. Only same-document references (`#…`) resolve.
96
+ * @param root - The document the pointer starts from.
97
+ * @returns The schema it points at, or `undefined` for an external reference, a path that
98
+ * does not exist, or a target that is not a schema object.
99
+ */
100
+ export function resolveRef(ref: string, root: JsonSchema): JsonSchema | undefined {
101
+ if (ref === "#") return root;
102
+ if (!ref.startsWith("#/")) return undefined;
103
+
104
+ let current: unknown = root;
105
+ for (const raw of ref.slice(2).split("/")) {
106
+ let segment = raw;
107
+ try {
108
+ segment = decodeURIComponent(raw);
109
+ } catch {
110
+ // A malformed escape is taken literally.
111
+ }
112
+ segment = segment.replaceAll("~1", "/").replaceAll("~0", "~");
113
+ if (!isObject(current) || !Object.hasOwn(current, segment)) return undefined;
114
+ current = current[segment];
115
+ }
116
+ return isObject(current) ? current : undefined;
117
+ }
118
+
119
+ /**
120
+ * Follow one `$ref`, keeping what the field says about itself.
121
+ *
122
+ * The merge order matters and is the opposite of the obvious one. schemars and pydantic
123
+ * write the field's `default` and `description` *beside* the `$ref`, while the target
124
+ * carries the type's own `title` and docstring. The field's statement about itself wins;
125
+ * the type's is the fallback.
126
+ *
127
+ * @param node - A node that may carry a `$ref`.
128
+ * @param root - The document holding `$defs`.
129
+ * @returns The node merged over its target, or `node` itself when there is nothing to
130
+ * follow (no `$ref`, or one that points at nothing).
131
+ */
132
+ export function derefNode<T extends JsonSchema>(node: T, root: JsonSchema): T {
133
+ if (node.$ref === undefined) return node;
134
+ const target = resolveRef(node.$ref, root);
135
+ if (target === undefined) return node;
136
+
137
+ const rest: JsonSchema = { ...node };
138
+ delete rest.$ref;
139
+ // The merge of a schema over a schema is a schema of the same family as `node`.
140
+ return { ...target, ...rest } as T;
141
+ }
142
+
143
+ function isNullSchema(branch: JsonSchema): boolean {
144
+ return branch.type === "null" || (Object.hasOwn(branch, "const") && branch.const === null);
145
+ }
146
+
147
+ /**
148
+ * Look through the "or null" encodings: `type: ["T", "null"]`, an `enum` that lists `null`,
149
+ * and an `anyOf` / `oneOf` with a `{ type: "null" }` branch.
150
+ *
151
+ * An optional string arrives as `anyOf: [{type: "string"}, {type: "null"}]`; treating that
152
+ * as an unrecognised node would give every nullable option a JSON textarea. When exactly
153
+ * one branch is left it is merged into the node (the node's own siblings win); when several
154
+ * are, they stay as the node's `anyOf` / `oneOf`.
155
+ *
156
+ * @param node - The node to look through.
157
+ * @returns The node without its null alternative, and whether it had one.
158
+ */
159
+ export function stripNullable<T extends JsonSchema>(node: T): ResolvedSchema<T> {
160
+ let out: JsonSchema = node;
161
+ let nullable = false;
162
+
163
+ if (Array.isArray(out.type) && out.type.includes("null")) {
164
+ const rest = out.type.filter((type) => type !== "null");
165
+ const [only] = rest;
166
+ if (only !== undefined) {
167
+ out = { ...out, type: rest.length === 1 ? only : rest };
168
+ nullable = true;
169
+ }
170
+ }
171
+
172
+ if (out.enum?.includes(null) === true) {
173
+ out = { ...out, enum: out.enum.filter((entry) => entry !== null) };
174
+ nullable = true;
175
+ }
176
+
177
+ for (const key of ["anyOf", "oneOf"] as const) {
178
+ const branches = out[key];
179
+ if (branches === undefined || !branches.some(isNullSchema)) continue;
180
+ const remaining = branches.filter((branch) => !isNullSchema(branch));
181
+ const [only] = remaining;
182
+ if (only === undefined) continue;
183
+ nullable = true;
184
+ if (remaining.length === 1) {
185
+ const rest: JsonSchema = { ...out };
186
+ delete rest[key];
187
+ out = { ...only, ...rest };
188
+ } else {
189
+ out = { ...out, [key]: remaining };
190
+ }
191
+ }
192
+
193
+ // Unchanged stays identical, so a caller can tell whether anything happened.
194
+ return { schema: (nullable ? out : node) as T, nullable };
195
+ }
196
+
197
+ /** `allOf: [X]` is how older schemars wrapped a `$ref` that needed siblings. */
198
+ function unwrapAllOf<T extends JsonSchema>(node: T): T {
199
+ const [only] = node.allOf ?? [];
200
+ if (only === undefined || node.allOf?.length !== 1) return node;
201
+ const rest: JsonSchema = { ...node };
202
+ delete rest.allOf;
203
+ return { ...only, ...rest } as T;
204
+ }
205
+
206
+ /**
207
+ * The node that says what a field *is*: `$ref` followed, `allOf: [X]` unwrapped and the
208
+ * "or null" encoding looked through, repeatedly, because each can hide the next (a `$ref`
209
+ * to an enum inside `anyOf: [{$ref}, null]`).
210
+ *
211
+ * @param node - A property or item schema as written.
212
+ * @param root - The document holding `$defs` (defaults to `node`, for a root schema).
213
+ * @returns The resolved node and whether `null` was among its accepted values. The field's
214
+ * own `default` and `description`, written beside a `$ref`, are kept.
215
+ */
216
+ export function resolveSchema<T extends JsonSchema>(node: T, root: JsonSchema = node): ResolvedSchema<T> {
217
+ let current = node;
218
+ let nullable = false;
219
+
220
+ for (let hop = 0; hop < MAX_HOPS; hop++) {
221
+ const followed = unwrapAllOf(derefNode(current, root));
222
+ const stripped = stripNullable(followed);
223
+ nullable ||= stripped.nullable;
224
+ const done = stripped.schema === current;
225
+ current = stripped.schema;
226
+ if (done) break;
227
+ }
228
+ return { schema: current, nullable };
229
+ }
230
+
231
+ /**
232
+ * Humanise `normal_dirs` into `Normal dirs`, and use a title only when a human chose it.
233
+ *
234
+ * pydantic emits a `title` for every field whether or not anyone wrote one, and its
235
+ * generated form is Title Case — `Csv Path`, `Defect Type From Dir` — which reads like a
236
+ * spreadsheet header rather than a form label. So a title is used only when it is *not*
237
+ * the one pydantic would have generated, which is exactly when a human chose it.
238
+ *
239
+ * Read from the *unresolved* node on purpose. Dereferencing pulls in the type's own title,
240
+ * so a resolved `color` field would be labelled "ColorMode".
241
+ *
242
+ * @param name - The property key.
243
+ * @param node - The property's schema as written (not resolved).
244
+ * @returns The label.
245
+ */
246
+ export function labelFor(name: string, node: JsonSchema): string {
247
+ const words = name.split("_");
248
+ const generated = words.map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join(" ");
249
+ if (node.title && node.title !== generated) return node.title;
250
+
251
+ const spaced = words.join(" ");
252
+ return spaced.charAt(0).toUpperCase() + spaced.slice(1);
253
+ }