@fedify/vocab-tools 2.5.0-dev.2687 → 2.5.0-dev.2710

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/src/schema.ts DELETED
@@ -1,444 +0,0 @@
1
- import { type Schema as JsonSchema, Validator } from "@cfworker/json-schema";
2
- import { readFile } from "node:fs/promises";
3
- import { join, posix as url } from "node:path";
4
- import { fileURLToPath } from "node:url";
5
- import { parse } from "yaml";
6
- import { readDirRecursive } from "./fs.ts";
7
-
8
- /**
9
- * The qualified URI of a type. It is used as the range of a property.
10
- */
11
- export type TypeUri =
12
- | `https://${string}`
13
- | `http://${string}`
14
- | `fedify:${string}`;
15
-
16
- /**
17
- * The schema of a type. It is used to generate a class.
18
- */
19
- export interface TypeSchema {
20
- /**
21
- * The type name. It is used as the name of the generated class.
22
- */
23
- name: string;
24
-
25
- /**
26
- * The qualified URI of the type.
27
- */
28
- uri: TypeUri;
29
-
30
- /**
31
- * The qualified URIs of the base type of the type (if any).
32
- */
33
- extends?: TypeUri;
34
-
35
- /**
36
- * The type name used in the compacted JSON-LD document. It is used as the
37
- * value of the `type` field.
38
- */
39
- compactName?: string;
40
-
41
- /**
42
- * Marks the type an entity type rather than a value type. Turning on this
43
- * flag will make property accessors for the type asynchronous, so that they
44
- * can load the values of the properties from the remote server.
45
- *
46
- * The extended subtypes must have the consistent value of this flag.
47
- */
48
- entity: boolean;
49
-
50
- /**
51
- * Whether this type's id can establish same-origin trust for its own
52
- * embedded entity-valued properties. Defaults to true. Set to false for
53
- * metadata whose id does not identify an independently fetched resource.
54
- * Locally constructed and explicitly trusted values remain trusted.
55
- */
56
- trustEmbeddedObjects?: boolean;
57
-
58
- /**
59
- * Whether the type omits `@type` in JSON-LD serialization. When `true`,
60
- * the generated `toJsonLd()` method will not emit `@type` (or `type` in
61
- * compact form) in the serialized JSON-LD. The generated `fromJsonLd()`
62
- * method will still accept `@type` if present for backward compatibility.
63
- *
64
- * This is useful for types that are not real vocabulary types but rather
65
- * anonymous object structures (e.g., `Endpoints`, `Source` in ActivityStreams).
66
- */
67
- typeless?: boolean;
68
-
69
- /**
70
- * The description of the type. It is used as the doc comment of
71
- * the generated class.
72
- */
73
- description: string;
74
-
75
- /**
76
- * The possible properties of the type.
77
- */
78
- properties: PropertySchema[];
79
-
80
- /**
81
- * The default JSON-LD context of the type. It is used as the default
82
- * context of the generated `toJsonLd()` method.
83
- */
84
- defaultContext: Context;
85
- }
86
-
87
- export interface PropertySchemaBase {
88
- /**
89
- * Synonyms read after the canonical property, in declaration order.
90
- * Deserialization selects the first non-empty raw value set before decoding
91
- * its values and containers; it never merges synonyms or retries invalid
92
- * values. Serialization writes all synonyms by default.
93
- */
94
- redundantProperties?: {
95
- /** The qualified URI of the synonym. */
96
- uri: string;
97
-
98
- /** The synonym's key in the default compact JSON-LD context. */
99
- compactName?: string;
100
- }[];
101
-
102
- /**
103
- * Whether serialization writes every synonym or only the canonical property.
104
- * Defaults to `"all"`. This does not change deserialization precedence or
105
- * the existing cache of parsed JSON-LD documents.
106
- */
107
- redundantPropertiesWrite?: "all" | "canonical";
108
-
109
- /**
110
- * A context URL added to the default serialization context when this
111
- * property's expanded IRI appears in the compacted document. Explicit
112
- * caller contexts are unchanged. Populated properties with this option
113
- * use the JSON-LD processor instead of compact serialization heuristics.
114
- */
115
- extraContext?: string;
116
-
117
- /**
118
- * The singular form of the property name. It is used as the name of the
119
- * generated property accessors.
120
- */
121
- singularName: string;
122
-
123
- /**
124
- * The qualified URI of the property.
125
- */
126
- uri: string;
127
-
128
- /**
129
- * The property name used in the compacted JSON-LD document. It is used as
130
- * the key of the property.
131
- */
132
- compactName?: string;
133
-
134
- /**
135
- * The qualified URI of the superproperty of the property (if any).
136
- * It means that the property is a specialization of the referenced property.
137
- */
138
- subpropertyOf?: string;
139
-
140
- /**
141
- * The description of the property. It is used as the doc comment of
142
- * the generated property accessors.
143
- */
144
- description: string;
145
-
146
- /**
147
- * Whether the enclosed object should have its own context when the document
148
- * is compacted.
149
- */
150
- embedContext?: {
151
- /**
152
- * The compact name of the property that contains the context.
153
- */
154
- compactName: string;
155
-
156
- /**
157
- * Whether the embedded context should be the same as the context of
158
- * the enclosing document.
159
- */
160
- inherit: true;
161
- };
162
-
163
- /**
164
- * Preprocessors for this property. Each preprocessor receives an expanded
165
- * JSON-LD property value and may return a vocabulary object matching the
166
- * property's declared range, `undefined` when it did not handle the value,
167
- * or an `Error` when it recognized the value but failed while converting it.
168
- *
169
- * `module` is resolved from the generated vocabulary source file
170
- * and imported statically at the top of the generated file.
171
- */
172
- preprocessors?: PropertyPreprocessorSchema[];
173
- }
174
-
175
- /**
176
- * A schema for a property preprocessor that normalizes wire-level values
177
- * before the generated range decoder runs.
178
- */
179
- export interface PropertyPreprocessorSchema {
180
- /**
181
- * Module specifier resolved from the generated vocabulary source file.
182
- */
183
- module: string;
184
-
185
- /**
186
- * The name of the exported function in the module.
187
- */
188
- function: string;
189
- }
190
-
191
- export type PropertySchemaTyping =
192
- | {
193
- /**
194
- * Whether the property value has `@type` field. If `true`, the `range` must
195
- * have only one element.
196
- */
197
- untyped?: false;
198
-
199
- /**
200
- * The qualified URIs of all possible types of the property values.
201
- */
202
- range: [TypeUri] | [TypeUri, ...TypeUri[]];
203
- }
204
- | {
205
- /**
206
- * Whether the property value has `@type` field. If `true`, the `range` must
207
- * have only one element.
208
- */
209
- untyped: true;
210
-
211
- /**
212
- * The qualified URIs of all possible types of the property values.
213
- */
214
- range: [TypeUri];
215
- };
216
-
217
- /**
218
- * The schema of a property. It is used to generate property accessors of
219
- * a class.
220
- */
221
- export type PropertySchema =
222
- | (PropertySchemaBase &
223
- PropertySchemaTyping & {
224
- /**
225
- * Marks the property that it can have only one value. Turning on this
226
- * flag will generate only singular property accessors, so `pluralName`
227
- * and `singularAccessor` should not be specified.
228
- */
229
- functional?: false;
230
-
231
- /**
232
- * The plural form of the property name. It is used as the name of the
233
- * generated property accessors.
234
- */
235
- pluralName: string;
236
-
237
- /**
238
- * Whether to generate singular property accessors. Regardless of this
239
- * flag, plural property accessors are generated (unless `functional` is
240
- * turned on).
241
- */
242
- singularAccessor?: boolean;
243
-
244
- /**
245
- * The container type of the property values. It can be unspecified.
246
- */
247
- container?: "graph" | "list";
248
- })
249
- | (PropertySchemaBase &
250
- PropertySchemaTyping & {
251
- /**
252
- * Marks the property that it can have only one value. Turning on this
253
- * flag will generate only singular property accessors, so `pluralName`
254
- * and `singularAccessor` should not be specified.
255
- */
256
- functional: true;
257
- });
258
-
259
- /**
260
- * A JSON-LD context, which is placed in the `@context` property of a JSON-LD
261
- * document.
262
- */
263
- export type Context = Uri | EmbeddedContext | (Uri | EmbeddedContext)[];
264
-
265
- type Uri = "http://{string}" | "https://{string}";
266
- type EmbeddedContext = Record<string, TermDefinition>;
267
- type TermDefinition =
268
- | Uri
269
- | Record<string, Uri | "@id">
270
- | ContainerTermDefinition;
271
-
272
- /**
273
- * A term definition that carries a JSON-LD `@container` keyword.
274
- *
275
- * The JSON Schema in *schema.yaml* enforces this shape conditionally whenever
276
- * an embedded context term has `@container`; the TypeScript union cannot
277
- * express the conditional and serves only as a guide.
278
- */
279
- interface ContainerTermDefinition {
280
- "@id": string;
281
- "@type"?: Uri | "@id";
282
- "@container": "@set" | "@list";
283
- }
284
-
285
- /**
286
- * Type guard to check if a property is not functional (has pluralName).
287
- */
288
- export function isNonFunctionalProperty(
289
- property: PropertySchema,
290
- ): property is PropertySchemaBase &
291
- PropertySchemaTyping & {
292
- functional?: false;
293
- pluralName: string;
294
- singularAccessor?: boolean;
295
- container?: "graph" | "list";
296
- } {
297
- return property.functional !== true;
298
- }
299
-
300
- /**
301
- * Type guard to check if a property has singular accessor.
302
- */
303
- export function hasSingularAccessor(property: PropertySchema): boolean {
304
- if (property.functional === true) return true;
305
- return (
306
- isNonFunctionalProperty(property) && property.singularAccessor === true
307
- );
308
- }
309
-
310
- const XSD_STRING_URI = "http://www.w3.org/2001/XMLSchema#string";
311
- const XSD_DECIMAL_URI = "http://www.w3.org/2001/XMLSchema#decimal";
312
- const FEDIFY_VOCAB_ENTITY_TYPE_URI = "fedify:vocabEntityType";
313
-
314
- /**
315
- * Validates schema combinations that cannot be represented safely by the
316
- * generated code.
317
- *
318
- * In particular, `xsd:string` and `xsd:decimal` cannot coexist in the same
319
- * property range because both are represented as runtime strings, which makes
320
- * JSON-LD serialization ambiguous and order-dependent.
321
- *
322
- * @param types The loaded type schemas to validate.
323
- * @throws {TypeError} Thrown when an unsupported range combination is found.
324
- */
325
- export function validateTypeSchemas(types: Record<string, TypeSchema>): void {
326
- for (const type of Object.values(types)) {
327
- for (const property of type.properties) {
328
- const hasString = property.range.includes(XSD_STRING_URI);
329
- const hasDecimal = property.range.includes(XSD_DECIMAL_URI);
330
- if (hasString && hasDecimal) {
331
- throw new TypeError(
332
- `The property ${type.name}.${property.singularName} cannot have ` +
333
- `both xsd:string and xsd:decimal in its range because the ` +
334
- `generated encoder cannot disambiguate them at runtime.`,
335
- );
336
- }
337
- if (
338
- property.range.includes(FEDIFY_VOCAB_ENTITY_TYPE_URI) &&
339
- property.range.length > 1
340
- ) {
341
- throw new TypeError(
342
- `The property ${type.name}.${property.singularName} cannot mix ` +
343
- `fedify:vocabEntityType with other range types because the ` +
344
- `generated decoder cannot disambiguate entity type references ` +
345
- `from ordinary IRIs.`,
346
- );
347
- }
348
- }
349
- }
350
- }
351
-
352
- /**
353
- * An error that occurred while loading a schema file.
354
- */
355
- export class SchemaError extends Error {
356
- /**
357
- * The path of the schema file.
358
- */
359
- readonly path: string;
360
-
361
- /**
362
- * Constructs a new `SchemaError`.
363
- * @param path The path of the schema file.
364
- * @param message The error message.
365
- */
366
- constructor(path: string, message?: string) {
367
- super(message);
368
- this.path = path;
369
- }
370
- }
371
-
372
- async function loadSchemaValidator(): Promise<Validator> {
373
- const thisFile = import.meta.url;
374
- const schemaFile = new URL(url.join(url.dirname(thisFile), "schema.yaml"));
375
- let content: string;
376
- if (schemaFile.protocol !== "file:") {
377
- const response = await fetch(schemaFile);
378
- content = await response.text();
379
- } else {
380
- content = await readFile(fileURLToPath(schemaFile), { encoding: "utf-8" });
381
- }
382
- const schemaObject = parse(content);
383
- return new Validator(schemaObject as JsonSchema);
384
- }
385
-
386
- let schemaValidator: Validator | undefined = undefined;
387
-
388
- async function loadSchema(path: string): Promise<TypeSchema> {
389
- const content = await readFile(path, { encoding: "utf-8" });
390
- const schema = parse(content);
391
- if (schemaValidator == null) schemaValidator = await loadSchemaValidator();
392
- const result = schemaValidator.validate(schema);
393
- const errors: SchemaError[] = [];
394
- if (result.valid) return schema as TypeSchema;
395
- for (const e of result.errors) {
396
- errors.push(
397
- new SchemaError(path, `${path}:${e.instanceLocation}: ${e.error}`),
398
- );
399
- }
400
- throw new AggregateError(errors, "Invalid schema data");
401
- }
402
-
403
- /**
404
- * Loads all schema files in the directory.
405
- * @param dir The path of the directory to load schema files from.
406
- * @returns A map from the qualified URI of a type to its {@link TypeSchema}.
407
- * @throws {@link AggregateError} if any schema file is invalid. It contains
408
- * all {@link SchemaError}s of the invalid schema files.
409
- */
410
- export async function loadSchemaFiles(
411
- dir: string,
412
- ): Promise<Record<string, TypeSchema>> {
413
- if (typeof dir !== "string") {
414
- throw new TypeError("Expected a directory path in string");
415
- }
416
- const result: Record<string, TypeSchema> = {};
417
- const errors: SchemaError[] = [];
418
- for await (const relPath of readDirRecursive(dir)) {
419
- if (!relPath.match(/\.ya?ml$/i)) continue;
420
- if (relPath.match(/(^|[/\\])schema.yaml$/i)) continue;
421
- const path = join(dir, relPath);
422
- let schema: TypeSchema;
423
- try {
424
- schema = await loadSchema(path);
425
- } catch (e) {
426
- if (
427
- e instanceof AggregateError &&
428
- e.errors.length > 0 &&
429
- e.errors[0] instanceof SchemaError
430
- ) {
431
- errors.push(...e.errors);
432
- continue;
433
- }
434
- throw e;
435
- }
436
- result[schema.uri] = schema;
437
- }
438
- if (errors.length > 0) {
439
- throw new AggregateError(errors, "Failed to load schema files");
440
- }
441
- const entries = Object.entries(result);
442
- entries.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
443
- return Object.fromEntries(entries);
444
- }