@fedify/vocab-tools 2.5.0-dev.2750 → 2.5.0-dev.2761
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/mod.cjs +582 -241
- package/dist/mod.js +582 -241
- package/package.json +2 -2
package/dist/mod.js
CHANGED
|
@@ -1,13 +1,128 @@
|
|
|
1
1
|
import { open, readFile, readdir } from "node:fs/promises";
|
|
2
|
-
import { encodeBase58 } from "byte-encodings/base58";
|
|
3
2
|
import { Validator } from "@cfworker/json-schema";
|
|
4
3
|
import { join, posix } from "node:path";
|
|
5
4
|
import { fileURLToPath } from "node:url";
|
|
6
5
|
import { parse } from "yaml";
|
|
6
|
+
import { encodeBase58 } from "byte-encodings/base58";
|
|
7
7
|
import { pascalCase } from "es-toolkit";
|
|
8
|
-
//#region
|
|
9
|
-
|
|
10
|
-
|
|
8
|
+
//#region src/fs.ts
|
|
9
|
+
/**
|
|
10
|
+
* Recursively read a directory, yielding the paths of all files. File paths
|
|
11
|
+
* are relative to the directory, and directories are not yielded.
|
|
12
|
+
* @param dir The directory to read.
|
|
13
|
+
* @returns An async iterable of file paths.
|
|
14
|
+
*/
|
|
15
|
+
async function* readDirRecursive(dir) {
|
|
16
|
+
for (const entry of await readdir(dir, { withFileTypes: true })) if (entry.isDirectory()) {
|
|
17
|
+
const path = join(dir, entry.name);
|
|
18
|
+
for await (const subentry of readDirRecursive(path)) yield join(entry.name, subentry);
|
|
19
|
+
} else yield entry.name;
|
|
20
|
+
}
|
|
21
|
+
//#endregion
|
|
22
|
+
//#region src/schema.ts
|
|
23
|
+
/**
|
|
24
|
+
* Type guard to check if a property is not functional (has pluralName).
|
|
25
|
+
*/
|
|
26
|
+
function isNonFunctionalProperty(property) {
|
|
27
|
+
return property.functional !== true;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Type guard to check if a property has singular accessor.
|
|
31
|
+
*/
|
|
32
|
+
function hasSingularAccessor(property) {
|
|
33
|
+
if (property.functional === true) return true;
|
|
34
|
+
return isNonFunctionalProperty(property) && property.singularAccessor === true;
|
|
35
|
+
}
|
|
36
|
+
const XSD_STRING_URI = "http://www.w3.org/2001/XMLSchema#string";
|
|
37
|
+
const XSD_DECIMAL_URI = "http://www.w3.org/2001/XMLSchema#decimal";
|
|
38
|
+
const FEDIFY_VOCAB_ENTITY_TYPE_URI = "fedify:vocabEntityType";
|
|
39
|
+
/**
|
|
40
|
+
* Validates schema combinations that cannot be represented safely by the
|
|
41
|
+
* generated code.
|
|
42
|
+
*
|
|
43
|
+
* In particular, `xsd:string` and `xsd:decimal` cannot coexist in the same
|
|
44
|
+
* property range because both are represented as runtime strings, which makes
|
|
45
|
+
* JSON-LD serialization ambiguous and order-dependent.
|
|
46
|
+
*
|
|
47
|
+
* @param types The loaded type schemas to validate.
|
|
48
|
+
* @throws {TypeError} Thrown when an unsupported range combination is found.
|
|
49
|
+
*/
|
|
50
|
+
function validateTypeSchemas(types) {
|
|
51
|
+
for (const type of Object.values(types)) for (const property of type.properties) {
|
|
52
|
+
const hasString = property.range.includes(XSD_STRING_URI);
|
|
53
|
+
const hasDecimal = property.range.includes(XSD_DECIMAL_URI);
|
|
54
|
+
if (hasString && hasDecimal) throw new TypeError(`The property ${type.name}.${property.singularName} cannot have both xsd:string and xsd:decimal in its range because the generated encoder cannot disambiguate them at runtime.`);
|
|
55
|
+
if (property.range.includes(FEDIFY_VOCAB_ENTITY_TYPE_URI) && property.range.length > 1) throw new TypeError(`The property ${type.name}.${property.singularName} cannot mix fedify:vocabEntityType with other range types because the generated decoder cannot disambiguate entity type references from ordinary IRIs.`);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* An error that occurred while loading a schema file.
|
|
60
|
+
*/
|
|
61
|
+
var SchemaError = class extends Error {
|
|
62
|
+
/**
|
|
63
|
+
* The path of the schema file.
|
|
64
|
+
*/
|
|
65
|
+
path;
|
|
66
|
+
/**
|
|
67
|
+
* Constructs a new `SchemaError`.
|
|
68
|
+
* @param path The path of the schema file.
|
|
69
|
+
* @param message The error message.
|
|
70
|
+
*/
|
|
71
|
+
constructor(path, message) {
|
|
72
|
+
super(message);
|
|
73
|
+
this.path = path;
|
|
74
|
+
}
|
|
75
|
+
};
|
|
76
|
+
async function loadSchemaValidator() {
|
|
77
|
+
const thisFile = import.meta.url;
|
|
78
|
+
const schemaFile = new URL(posix.join(posix.dirname(thisFile), "schema.yaml"));
|
|
79
|
+
let content;
|
|
80
|
+
if (schemaFile.protocol !== "file:") content = await (await fetch(schemaFile)).text();
|
|
81
|
+
else content = await readFile(fileURLToPath(schemaFile), { encoding: "utf-8" });
|
|
82
|
+
return new Validator(parse(content));
|
|
83
|
+
}
|
|
84
|
+
let schemaValidator = void 0;
|
|
85
|
+
async function loadSchema(path) {
|
|
86
|
+
const schema = parse(await readFile(path, { encoding: "utf-8" }));
|
|
87
|
+
if (schemaValidator == null) schemaValidator = await loadSchemaValidator();
|
|
88
|
+
const result = schemaValidator.validate(schema);
|
|
89
|
+
const errors = [];
|
|
90
|
+
if (result.valid) return schema;
|
|
91
|
+
for (const e of result.errors) errors.push(new SchemaError(path, `${path}:${e.instanceLocation}: ${e.error}`));
|
|
92
|
+
throw new AggregateError(errors, "Invalid schema data");
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Loads all schema files in the directory.
|
|
96
|
+
* @param dir The path of the directory to load schema files from.
|
|
97
|
+
* @returns A map from the qualified URI of a type to its {@link TypeSchema}.
|
|
98
|
+
* @throws {@link AggregateError} if any schema file is invalid. It contains
|
|
99
|
+
* all {@link SchemaError}s of the invalid schema files.
|
|
100
|
+
*/
|
|
101
|
+
async function loadSchemaFiles(dir) {
|
|
102
|
+
if (typeof dir !== "string") throw new TypeError("Expected a directory path in string");
|
|
103
|
+
const result = {};
|
|
104
|
+
const errors = [];
|
|
105
|
+
for await (const relPath of readDirRecursive(dir)) {
|
|
106
|
+
if (!relPath.match(/\.ya?ml$/i)) continue;
|
|
107
|
+
if (relPath.match(/(^|[/\\])schema.yaml$/i)) continue;
|
|
108
|
+
const path = join(dir, relPath);
|
|
109
|
+
let schema;
|
|
110
|
+
try {
|
|
111
|
+
schema = await loadSchema(path);
|
|
112
|
+
} catch (e) {
|
|
113
|
+
if (e instanceof AggregateError && e.errors.length > 0 && e.errors[0] instanceof SchemaError) {
|
|
114
|
+
errors.push(...e.errors);
|
|
115
|
+
continue;
|
|
116
|
+
}
|
|
117
|
+
throw e;
|
|
118
|
+
}
|
|
119
|
+
result[schema.uri] = schema;
|
|
120
|
+
}
|
|
121
|
+
if (errors.length > 0) throw new AggregateError(errors, "Failed to load schema files");
|
|
122
|
+
const entries = Object.entries(result);
|
|
123
|
+
entries.sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
|
|
124
|
+
return Object.fromEntries(entries);
|
|
125
|
+
}
|
|
11
126
|
//#endregion
|
|
12
127
|
//#region src/type.ts
|
|
13
128
|
const HEURISTICS_CONTEXTS = [
|
|
@@ -608,20 +723,185 @@ function getDataCheck(typeUri, types, variable) {
|
|
|
608
723
|
}
|
|
609
724
|
throw new Error(`Unknown type: ${typeUri}`);
|
|
610
725
|
}
|
|
611
|
-
function* getDecoders(typeUris, types, variable, optionsVariable, baseUrlVariable) {
|
|
612
|
-
for (const typeUri of typeUris) {
|
|
613
|
-
yield getDataCheck(typeUri, types, variable);
|
|
614
|
-
yield " ? ";
|
|
615
|
-
yield getDecoder(typeUri, types, variable, optionsVariable, baseUrlVariable);
|
|
616
|
-
yield " : ";
|
|
617
|
-
}
|
|
618
|
-
yield "undefined";
|
|
619
|
-
}
|
|
620
726
|
function emitOverride$1(typeUri, types) {
|
|
621
727
|
if (types[typeUri].extends == null) return "";
|
|
622
728
|
return "override";
|
|
623
729
|
}
|
|
624
730
|
//#endregion
|
|
731
|
+
//#region src/property-decoder.ts
|
|
732
|
+
function* generatePreprocessorBlock(property, rangeTypeName, variable, baseUrlExpr, moduleVarNames) {
|
|
733
|
+
if (property.preprocessors == null || property.preprocessors.length === 0) return;
|
|
734
|
+
yield `
|
|
735
|
+
{
|
|
736
|
+
let _handled: ${rangeTypeName} | undefined;
|
|
737
|
+
`;
|
|
738
|
+
for (const pp of property.preprocessors) {
|
|
739
|
+
const varName = moduleVarNames.get(pp.module);
|
|
740
|
+
if (varName == null) throw new Error(`Preprocessor module "${pp.module}" is not registered in the generated imports. Ensure all preprocessor modules used in property schemas are available.`);
|
|
741
|
+
yield `
|
|
742
|
+
if (_handled === undefined) {
|
|
743
|
+
const _result = await ${varName}[${JSON.stringify(pp.function)}](v, {
|
|
744
|
+
documentLoader: options.documentLoader,
|
|
745
|
+
contextLoader: options.contextLoader,
|
|
746
|
+
tracerProvider: options.tracerProvider,
|
|
747
|
+
verifyPortableObject: options.verifyPortableObject,
|
|
748
|
+
baseUrl: ${baseUrlExpr},
|
|
749
|
+
// Child decoding must validate the supplied expanded values before
|
|
750
|
+
// JSON-LD expansion can discard malformed input.
|
|
751
|
+
...(isRawPropertyWrite(options)
|
|
752
|
+
? { _rawPropertyWrite: true, _expanded: true }
|
|
753
|
+
: {}),
|
|
754
|
+
});
|
|
755
|
+
if (_result instanceof Error) throw _result;
|
|
756
|
+
if (_result !== undefined) {
|
|
757
|
+
_handled = (isRawPropertyWrite(options) && _result != null &&
|
|
758
|
+
typeof _result === "object" && RAW_PROPERTY_PROTOCOL in _result
|
|
759
|
+
? await isolatePreprocessedRawPropertyObject(_result, v) : _result) as ${rangeTypeName};
|
|
760
|
+
if (!isRawPropertyWrite(options)) retainPreprocessedRawProperties(_handled, v);
|
|
761
|
+
}
|
|
762
|
+
}
|
|
763
|
+
`;
|
|
764
|
+
}
|
|
765
|
+
yield `
|
|
766
|
+
if (_handled !== undefined) {
|
|
767
|
+
// The document does not describe what a preprocessor made of it:
|
|
768
|
+
skipReceivedJsonLd(_handled);
|
|
769
|
+
${variable}.push(_handled);
|
|
770
|
+
continue;
|
|
771
|
+
}
|
|
772
|
+
}
|
|
773
|
+
`;
|
|
774
|
+
}
|
|
775
|
+
/** Scalar decoders may normalize metadata, but cannot keep node payloads. */
|
|
776
|
+
function checkedDecoderInput(typeUri, types) {
|
|
777
|
+
const check = getDataCheck(typeUri, types, "v");
|
|
778
|
+
if (typeUri in types) return check;
|
|
779
|
+
return `(${check}) && (!isRawPropertyWrite(options) || "@value" in v ||
|
|
780
|
+
globalThis.Object.keys(v).every(key => key === "@id" || key === "@type" || key === "@index"))`;
|
|
781
|
+
}
|
|
782
|
+
/** Emits the shared ordinary/strict property decoder loop. */
|
|
783
|
+
function* generatePropertyDecoder(property, types, variable, arrayVariable, moduleVarNames, cacheCheck) {
|
|
784
|
+
if (!isNonFunctionalProperty(property) || property.container !== "list") yield `
|
|
785
|
+
if (isRawPropertyWrite(options) && ${arrayVariable}?.some(
|
|
786
|
+
(value: unknown) => value != null && typeof value === "object" && "@list" in value)) {
|
|
787
|
+
throw new TypeError("This known property does not support a list container.");
|
|
788
|
+
}
|
|
789
|
+
`;
|
|
790
|
+
yield `
|
|
791
|
+
if (isRawPropertyWrite(options) && ${arrayVariable}?.length === 1 &&
|
|
792
|
+
"@list" in ${arrayVariable}[0] && ${arrayVariable}[0]["@list"].length === 0) {
|
|
793
|
+
throw new TypeError("An empty known list cannot be represented; use an empty values array to remove the property.");
|
|
794
|
+
}
|
|
795
|
+
`;
|
|
796
|
+
let itemsExpression = `${arrayVariable}.length === 1 && "@list" in ${arrayVariable}[0]
|
|
797
|
+
? ${arrayVariable}[0]["@list"]
|
|
798
|
+
: ${arrayVariable}`;
|
|
799
|
+
if (isNonFunctionalProperty(property) && property.container === "graph") itemsExpression = `(${itemsExpression}).flatMap((item: unknown) => {
|
|
800
|
+
if (item != null && typeof item === "object" && "@graph" in item &&
|
|
801
|
+
Array.isArray((item as { "@graph": unknown })["@graph"])) {
|
|
802
|
+
const graph = (item as { "@graph": unknown[] })["@graph"];
|
|
803
|
+
if (isRawPropertyWrite(options) && globalThis.Object.keys(item).some(
|
|
804
|
+
key => key !== "@graph" && key !== "@index")) {
|
|
805
|
+
throw new TypeError("The known graph container cannot represent wrapper data.");
|
|
806
|
+
}
|
|
807
|
+
if (isRawPropertyWrite(options) && graph.length === 0) {
|
|
808
|
+
throw new TypeError("An empty known graph cannot be represented; use an empty values array to remove the property.");
|
|
809
|
+
}
|
|
810
|
+
return graph;
|
|
811
|
+
}
|
|
812
|
+
return [item];
|
|
813
|
+
})`;
|
|
814
|
+
yield `
|
|
815
|
+
for (
|
|
816
|
+
const v of ${arrayVariable} == null
|
|
817
|
+
? []
|
|
818
|
+
: ${itemsExpression}
|
|
819
|
+
) {
|
|
820
|
+
if (v == null) {
|
|
821
|
+
if (isRawPropertyWrite(options)) throw new TypeError("Cannot decode a supplied raw property value.");
|
|
822
|
+
continue;
|
|
823
|
+
}
|
|
824
|
+
`;
|
|
825
|
+
yield `
|
|
826
|
+
if (isRawPropertyWrite(options) && typeof v === "object" && "@graph" in v) {
|
|
827
|
+
throw new TypeError("This known property cannot represent a remaining graph wrapper.");
|
|
828
|
+
}
|
|
829
|
+
`;
|
|
830
|
+
const propertyBaseUrl = "options.baseUrl";
|
|
831
|
+
yield* generatePreprocessorBlock(property, getTypeNames(property.range, types), variable, propertyBaseUrl, moduleVarNames);
|
|
832
|
+
if (!areAllScalarTypes(property.range, types)) yield `
|
|
833
|
+
if (typeof v === "object" && "@id" in v && !("@type" in v)
|
|
834
|
+
&& globalThis.Object.keys(v).length === 1) {
|
|
835
|
+
if (v["@id"].startsWith("_:")) {
|
|
836
|
+
if (isRawPropertyWrite(options)) throw new TypeError("Cannot decode a blank node reference.");
|
|
837
|
+
continue;
|
|
838
|
+
}
|
|
839
|
+
${variable}.push(parseIri(v["@id"], ${propertyBaseUrl}));
|
|
840
|
+
continue;
|
|
841
|
+
}
|
|
842
|
+
`;
|
|
843
|
+
if (property.range.length === 1) {
|
|
844
|
+
yield `if (isRawPropertyWrite(options) && !(`;
|
|
845
|
+
yield checkedDecoderInput(property.range[0], types);
|
|
846
|
+
if (property.range[0] in types) yield ` || (typeof v === "object" && !("@value" in v) && !("@list" in v) && !("@type" in v))`;
|
|
847
|
+
yield `)) throw new TypeError("Cannot decode a supplied raw property value.");`;
|
|
848
|
+
}
|
|
849
|
+
yield `
|
|
850
|
+
const decoded =
|
|
851
|
+
`;
|
|
852
|
+
const lenient = property.range.length == 1 && skipsUnparsable(property.range[0]);
|
|
853
|
+
if (property.range.length == 1) {
|
|
854
|
+
if (lenient) {
|
|
855
|
+
yield checkedDecoderInput(property.range[0], types);
|
|
856
|
+
yield " ? ";
|
|
857
|
+
}
|
|
858
|
+
yield getDecoder(property.range[0], types, "v", "options", propertyBaseUrl);
|
|
859
|
+
if (lenient) yield " : undefined";
|
|
860
|
+
} else {
|
|
861
|
+
for (const typeUri of property.range) {
|
|
862
|
+
yield checkedDecoderInput(typeUri, types);
|
|
863
|
+
yield " ? ";
|
|
864
|
+
yield getDecoder(typeUri, types, "v", "options", propertyBaseUrl);
|
|
865
|
+
yield " : ";
|
|
866
|
+
}
|
|
867
|
+
yield "undefined";
|
|
868
|
+
}
|
|
869
|
+
yield `
|
|
870
|
+
;
|
|
871
|
+
`;
|
|
872
|
+
yield `
|
|
873
|
+
if (typeof decoded === "undefined") {
|
|
874
|
+
if (isRawPropertyWrite(options)) throw new TypeError("Cannot decode a supplied raw property value.");
|
|
875
|
+
shouldCacheJsonLd = false;
|
|
876
|
+
continue;
|
|
877
|
+
}
|
|
878
|
+
`;
|
|
879
|
+
yield `
|
|
880
|
+
if (isRawPropertyWrite(options) && !(${getTypeGuards(property.range, types, "decoded")})) {
|
|
881
|
+
throw new TypeError("Decoded raw property value is outside the property's range.");
|
|
882
|
+
}
|
|
883
|
+
`;
|
|
884
|
+
if (cacheCheck != null) yield `
|
|
885
|
+
if (!${cacheCheck}) {
|
|
886
|
+
shouldCacheJsonLd = false;
|
|
887
|
+
}
|
|
888
|
+
`;
|
|
889
|
+
yield `
|
|
890
|
+
keepReceivedJsonLd(decoded, v, options);
|
|
891
|
+
${variable}.push(decoded);
|
|
892
|
+
`;
|
|
893
|
+
yield `\n }\n`;
|
|
894
|
+
if (!isNonFunctionalProperty(property)) yield `
|
|
895
|
+
if (isRawPropertyWrite(options) && ${variable}.length > 1) {
|
|
896
|
+
throw new TypeError("A functional property accepts at most one value.");
|
|
897
|
+
}
|
|
898
|
+
`;
|
|
899
|
+
}
|
|
900
|
+
//#endregion
|
|
901
|
+
//#region deno.json
|
|
902
|
+
var name = "@fedify/vocab-tools";
|
|
903
|
+
var version = "2.5.0-dev.2761+03854982";
|
|
904
|
+
//#endregion
|
|
625
905
|
//#region src/field.ts
|
|
626
906
|
async function getFieldName(propertyUri, prefix = "#") {
|
|
627
907
|
const hashedUri = await crypto.subtle.digest("SHA-1", new TextEncoder().encode(propertyUri));
|
|
@@ -642,125 +922,6 @@ async function* generateFields(typeUri, types) {
|
|
|
642
922
|
for (const property of type.properties) yield await generateField(property, types);
|
|
643
923
|
}
|
|
644
924
|
//#endregion
|
|
645
|
-
//#region src/fs.ts
|
|
646
|
-
/**
|
|
647
|
-
* Recursively read a directory, yielding the paths of all files. File paths
|
|
648
|
-
* are relative to the directory, and directories are not yielded.
|
|
649
|
-
* @param dir The directory to read.
|
|
650
|
-
* @returns An async iterable of file paths.
|
|
651
|
-
*/
|
|
652
|
-
async function* readDirRecursive(dir) {
|
|
653
|
-
for (const entry of await readdir(dir, { withFileTypes: true })) if (entry.isDirectory()) {
|
|
654
|
-
const path = join(dir, entry.name);
|
|
655
|
-
for await (const subentry of readDirRecursive(path)) yield join(entry.name, subentry);
|
|
656
|
-
} else yield entry.name;
|
|
657
|
-
}
|
|
658
|
-
//#endregion
|
|
659
|
-
//#region src/schema.ts
|
|
660
|
-
/**
|
|
661
|
-
* Type guard to check if a property is not functional (has pluralName).
|
|
662
|
-
*/
|
|
663
|
-
function isNonFunctionalProperty(property) {
|
|
664
|
-
return property.functional !== true;
|
|
665
|
-
}
|
|
666
|
-
/**
|
|
667
|
-
* Type guard to check if a property has singular accessor.
|
|
668
|
-
*/
|
|
669
|
-
function hasSingularAccessor(property) {
|
|
670
|
-
if (property.functional === true) return true;
|
|
671
|
-
return isNonFunctionalProperty(property) && property.singularAccessor === true;
|
|
672
|
-
}
|
|
673
|
-
const XSD_STRING_URI = "http://www.w3.org/2001/XMLSchema#string";
|
|
674
|
-
const XSD_DECIMAL_URI = "http://www.w3.org/2001/XMLSchema#decimal";
|
|
675
|
-
const FEDIFY_VOCAB_ENTITY_TYPE_URI = "fedify:vocabEntityType";
|
|
676
|
-
/**
|
|
677
|
-
* Validates schema combinations that cannot be represented safely by the
|
|
678
|
-
* generated code.
|
|
679
|
-
*
|
|
680
|
-
* In particular, `xsd:string` and `xsd:decimal` cannot coexist in the same
|
|
681
|
-
* property range because both are represented as runtime strings, which makes
|
|
682
|
-
* JSON-LD serialization ambiguous and order-dependent.
|
|
683
|
-
*
|
|
684
|
-
* @param types The loaded type schemas to validate.
|
|
685
|
-
* @throws {TypeError} Thrown when an unsupported range combination is found.
|
|
686
|
-
*/
|
|
687
|
-
function validateTypeSchemas(types) {
|
|
688
|
-
for (const type of Object.values(types)) for (const property of type.properties) {
|
|
689
|
-
const hasString = property.range.includes(XSD_STRING_URI);
|
|
690
|
-
const hasDecimal = property.range.includes(XSD_DECIMAL_URI);
|
|
691
|
-
if (hasString && hasDecimal) throw new TypeError(`The property ${type.name}.${property.singularName} cannot have both xsd:string and xsd:decimal in its range because the generated encoder cannot disambiguate them at runtime.`);
|
|
692
|
-
if (property.range.includes(FEDIFY_VOCAB_ENTITY_TYPE_URI) && property.range.length > 1) throw new TypeError(`The property ${type.name}.${property.singularName} cannot mix fedify:vocabEntityType with other range types because the generated decoder cannot disambiguate entity type references from ordinary IRIs.`);
|
|
693
|
-
}
|
|
694
|
-
}
|
|
695
|
-
/**
|
|
696
|
-
* An error that occurred while loading a schema file.
|
|
697
|
-
*/
|
|
698
|
-
var SchemaError = class extends Error {
|
|
699
|
-
/**
|
|
700
|
-
* The path of the schema file.
|
|
701
|
-
*/
|
|
702
|
-
path;
|
|
703
|
-
/**
|
|
704
|
-
* Constructs a new `SchemaError`.
|
|
705
|
-
* @param path The path of the schema file.
|
|
706
|
-
* @param message The error message.
|
|
707
|
-
*/
|
|
708
|
-
constructor(path, message) {
|
|
709
|
-
super(message);
|
|
710
|
-
this.path = path;
|
|
711
|
-
}
|
|
712
|
-
};
|
|
713
|
-
async function loadSchemaValidator() {
|
|
714
|
-
const thisFile = import.meta.url;
|
|
715
|
-
const schemaFile = new URL(posix.join(posix.dirname(thisFile), "schema.yaml"));
|
|
716
|
-
let content;
|
|
717
|
-
if (schemaFile.protocol !== "file:") content = await (await fetch(schemaFile)).text();
|
|
718
|
-
else content = await readFile(fileURLToPath(schemaFile), { encoding: "utf-8" });
|
|
719
|
-
return new Validator(parse(content));
|
|
720
|
-
}
|
|
721
|
-
let schemaValidator = void 0;
|
|
722
|
-
async function loadSchema(path) {
|
|
723
|
-
const schema = parse(await readFile(path, { encoding: "utf-8" }));
|
|
724
|
-
if (schemaValidator == null) schemaValidator = await loadSchemaValidator();
|
|
725
|
-
const result = schemaValidator.validate(schema);
|
|
726
|
-
const errors = [];
|
|
727
|
-
if (result.valid) return schema;
|
|
728
|
-
for (const e of result.errors) errors.push(new SchemaError(path, `${path}:${e.instanceLocation}: ${e.error}`));
|
|
729
|
-
throw new AggregateError(errors, "Invalid schema data");
|
|
730
|
-
}
|
|
731
|
-
/**
|
|
732
|
-
* Loads all schema files in the directory.
|
|
733
|
-
* @param dir The path of the directory to load schema files from.
|
|
734
|
-
* @returns A map from the qualified URI of a type to its {@link TypeSchema}.
|
|
735
|
-
* @throws {@link AggregateError} if any schema file is invalid. It contains
|
|
736
|
-
* all {@link SchemaError}s of the invalid schema files.
|
|
737
|
-
*/
|
|
738
|
-
async function loadSchemaFiles(dir) {
|
|
739
|
-
if (typeof dir !== "string") throw new TypeError("Expected a directory path in string");
|
|
740
|
-
const result = {};
|
|
741
|
-
const errors = [];
|
|
742
|
-
for await (const relPath of readDirRecursive(dir)) {
|
|
743
|
-
if (!relPath.match(/\.ya?ml$/i)) continue;
|
|
744
|
-
if (relPath.match(/(^|[/\\])schema.yaml$/i)) continue;
|
|
745
|
-
const path = join(dir, relPath);
|
|
746
|
-
let schema;
|
|
747
|
-
try {
|
|
748
|
-
schema = await loadSchema(path);
|
|
749
|
-
} catch (e) {
|
|
750
|
-
if (e instanceof AggregateError && e.errors.length > 0 && e.errors[0] instanceof SchemaError) {
|
|
751
|
-
errors.push(...e.errors);
|
|
752
|
-
continue;
|
|
753
|
-
}
|
|
754
|
-
throw e;
|
|
755
|
-
}
|
|
756
|
-
result[schema.uri] = schema;
|
|
757
|
-
}
|
|
758
|
-
if (errors.length > 0) throw new AggregateError(errors, "Failed to load schema files");
|
|
759
|
-
const entries = Object.entries(result);
|
|
760
|
-
entries.sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
|
|
761
|
-
return Object.fromEntries(entries);
|
|
762
|
-
}
|
|
763
|
-
//#endregion
|
|
764
925
|
//#region src/raw-property.ts
|
|
765
926
|
/**
|
|
766
927
|
* Emits the body of a loop that encodes the values of a property into the
|
|
@@ -809,7 +970,135 @@ type RawPropertyEncoder = (
|
|
|
809
970
|
|
|
810
971
|
interface RawPropertyDescriptor {
|
|
811
972
|
readonly canonicalIri: string;
|
|
973
|
+
readonly aliases: readonly string[];
|
|
812
974
|
readonly encode: RawPropertyEncoder;
|
|
975
|
+
decode(values: readonly unknown[], options: RawPropertyDecodeOptions): Promise<unknown[]>;
|
|
976
|
+
assign(object: object, values: unknown[]): void;
|
|
977
|
+
validate(object: object): void;
|
|
978
|
+
}
|
|
979
|
+
|
|
980
|
+
interface RawPropertyDecodeOptions {
|
|
981
|
+
documentLoader?: DocumentLoader;
|
|
982
|
+
contextLoader?: DocumentLoader;
|
|
983
|
+
tracerProvider?: TracerProvider;
|
|
984
|
+
verifyPortableObject?: PortableObjectVerifier;
|
|
985
|
+
baseUrl?: URL;
|
|
986
|
+
_rawPropertyWrite?: boolean;
|
|
987
|
+
}
|
|
988
|
+
|
|
989
|
+
function isRawPropertyWrite(options: object): boolean {
|
|
990
|
+
return "_rawPropertyWrite" in options && options._rawPropertyWrite === true;
|
|
991
|
+
}
|
|
992
|
+
|
|
993
|
+
const rawPropertyBrands = new Map<object, (object: object) => void>();
|
|
994
|
+
|
|
995
|
+
const publishedRawProperties = new WeakMap<object, ReadonlySet<string>>();
|
|
996
|
+
|
|
997
|
+
function publishSuppliedRawProperties(object: unknown, node: unknown): void {
|
|
998
|
+
if (object == null || typeof object !== "object" || node == null || typeof node !== "object") return;
|
|
999
|
+
const retained = retainedRawProperties.get(object);
|
|
1000
|
+
publishedRawProperties.set(object, new Set(globalThis.Object.keys(node).filter(
|
|
1001
|
+
key => retained != null && globalThis.Object.hasOwn(retained, key),
|
|
1002
|
+
)));
|
|
1003
|
+
}
|
|
1004
|
+
|
|
1005
|
+
function publishedRawPropertyValues(object: object): Record<string, unknown[]> {
|
|
1006
|
+
const values: Record<string, unknown[]> = {};
|
|
1007
|
+
const retained = retainedRawProperties.get(object);
|
|
1008
|
+
for (const iri of publishedRawProperties.get(object) ?? []) {
|
|
1009
|
+
if (retained != null && globalThis.Object.hasOwn(retained, iri)) {
|
|
1010
|
+
values[iri] = copyJsonValue(retained[iri]) as unknown[];
|
|
1011
|
+
}
|
|
1012
|
+
}
|
|
1013
|
+
return values;
|
|
1014
|
+
}
|
|
1015
|
+
|
|
1016
|
+
function rawPropertySlots(object: object): RawPropertyDescriptor[] {
|
|
1017
|
+
const slots = new Set<RawPropertyDescriptor>();
|
|
1018
|
+
let prototype: object | null = globalThis.Object.getPrototypeOf(object);
|
|
1019
|
+
while (prototype != null) {
|
|
1020
|
+
for (const descriptor of rawPropertyDescriptors.get(prototype)?.values() ?? []) slots.add(descriptor);
|
|
1021
|
+
prototype = globalThis.Object.getPrototypeOf(prototype);
|
|
1022
|
+
}
|
|
1023
|
+
return [...slots];
|
|
1024
|
+
}
|
|
1025
|
+
|
|
1026
|
+
async function isolatePreprocessedRawPropertyObject(source: object, node: unknown): Promise<object> {
|
|
1027
|
+
const method = (source as Record<symbol, unknown>)[RAW_PROPERTY_WRITE_PROTOCOL];
|
|
1028
|
+
if (typeof method !== "function") throw new TypeError("The preprocessor returned a vocabulary object without raw write support.");
|
|
1029
|
+
return await method.call(source, [], node) as object;
|
|
1030
|
+
}
|
|
1031
|
+
|
|
1032
|
+
function isolateRawPropertyObject(source: object): object {
|
|
1033
|
+
const descriptor = getDeepCloneDescriptor(source);
|
|
1034
|
+
if (descriptor == null) throw new TypeError("Unsupported generated vocabulary object.");
|
|
1035
|
+
const result = descriptor.create(source);
|
|
1036
|
+
if (result == null || typeof result !== "object" || result === source ||
|
|
1037
|
+
globalThis.Object.getPrototypeOf(result) !== globalThis.Object.getPrototypeOf(source)) {
|
|
1038
|
+
throw new TypeError("clone() must return a fresh instance with the same prototype.");
|
|
1039
|
+
}
|
|
1040
|
+
let prototype: object | null = globalThis.Object.getPrototypeOf(source);
|
|
1041
|
+
while (prototype != null) {
|
|
1042
|
+
rawPropertyBrands.get(prototype)?.(result);
|
|
1043
|
+
prototype = globalThis.Object.getPrototypeOf(prototype);
|
|
1044
|
+
}
|
|
1045
|
+
// Each closure checks the private brand, including shadowed superclass slots.
|
|
1046
|
+
for (const slot of rawPropertySlots(source)) slot.validate(result);
|
|
1047
|
+
copyPortableProvenance(source, result);
|
|
1048
|
+
copyRawProperties(source, result);
|
|
1049
|
+
invalidateCachedJsonLd(result);
|
|
1050
|
+
clearRetainedSignedRepresentation(result);
|
|
1051
|
+
return result;
|
|
1052
|
+
}
|
|
1053
|
+
|
|
1054
|
+
async function writeRawProperties(
|
|
1055
|
+
source: object,
|
|
1056
|
+
entries: readonly RawPropertyWriteEntry[],
|
|
1057
|
+
options: RawPropertyDecodeOptions,
|
|
1058
|
+
): Promise<object> {
|
|
1059
|
+
const retained = retainedRawProperties.get(source);
|
|
1060
|
+
const destinations = new Set<string>();
|
|
1061
|
+
const resolved = entries.map(entry => {
|
|
1062
|
+
let iri = entry.candidates[entry.candidates.length - 1];
|
|
1063
|
+
let descriptor: RawPropertyDescriptor | undefined;
|
|
1064
|
+
for (const candidate of entry.candidates) {
|
|
1065
|
+
descriptor = getRawPropertyDescriptor(source, candidate);
|
|
1066
|
+
if (descriptor != null || (retained != null && globalThis.Object.hasOwn(retained, candidate))) {
|
|
1067
|
+
iri = descriptor?.canonicalIri ?? candidate;
|
|
1068
|
+
break;
|
|
1069
|
+
}
|
|
1070
|
+
}
|
|
1071
|
+
if (destinations.has(iri)) throw new TypeError("Duplicate raw property destination: " + iri);
|
|
1072
|
+
destinations.add(iri);
|
|
1073
|
+
return { iri, descriptor, values: entry.values };
|
|
1074
|
+
});
|
|
1075
|
+
// All source state is captured before the first decoder can suspend.
|
|
1076
|
+
const result = isolateRawPropertyObject(source);
|
|
1077
|
+
const unknown: Record<string, readonly unknown[]> = { ...retained };
|
|
1078
|
+
const published = new Set(publishedRawProperties.get(source));
|
|
1079
|
+
const slots = rawPropertySlots(source);
|
|
1080
|
+
const decoded: { iri: string; descriptor: RawPropertyDescriptor; values: unknown[] }[] = [];
|
|
1081
|
+
for (const entry of resolved) {
|
|
1082
|
+
if (entry.descriptor != null) {
|
|
1083
|
+
decoded.push({ iri: entry.iri, descriptor: entry.descriptor, values:
|
|
1084
|
+
entry.values.length === 0 ? [] : await entry.descriptor.decode(entry.values, options) });
|
|
1085
|
+
} else if (entry.values.length === 0) {
|
|
1086
|
+
delete unknown[entry.iri];
|
|
1087
|
+
published.delete(entry.iri);
|
|
1088
|
+
} else {
|
|
1089
|
+
unknown[entry.iri] = entry.values;
|
|
1090
|
+
published.add(entry.iri);
|
|
1091
|
+
}
|
|
1092
|
+
}
|
|
1093
|
+
for (const entry of decoded) {
|
|
1094
|
+
for (const slot of slots) {
|
|
1095
|
+
if (slot.canonicalIri === entry.iri) slot.assign(result, []);
|
|
1096
|
+
}
|
|
1097
|
+
entry.descriptor.assign(result, entry.values);
|
|
1098
|
+
}
|
|
1099
|
+
retainedRawProperties.set(result, globalThis.Object.freeze(unknown));
|
|
1100
|
+
publishedRawProperties.set(result, published);
|
|
1101
|
+
return result;
|
|
813
1102
|
}
|
|
814
1103
|
|
|
815
1104
|
// Unknown properties retained while decoding, keyed by the decoded object:
|
|
@@ -843,7 +1132,34 @@ function getRawPropertyDescriptor(
|
|
|
843
1132
|
return undefined;
|
|
844
1133
|
}
|
|
845
1134
|
|
|
1135
|
+
function rawPropertyInputValues(
|
|
1136
|
+
object: object,
|
|
1137
|
+
canonicalIri: string,
|
|
1138
|
+
values: Record<string, unknown>,
|
|
1139
|
+
): unknown {
|
|
1140
|
+
const canonical = values[canonicalIri];
|
|
1141
|
+
if (globalThis.Array.isArray(canonical) && canonical.length > 0) return canonical;
|
|
1142
|
+
// Schema order, from the effective declaration to its ancestors, decides
|
|
1143
|
+
// alias precedence. Supplied object key order must never change decoding.
|
|
1144
|
+
let prototype: object | null = globalThis.Object.getPrototypeOf(object);
|
|
1145
|
+
while (prototype != null) {
|
|
1146
|
+
const descriptor = rawPropertyDescriptors.get(prototype)?.get(canonicalIri);
|
|
1147
|
+
if (descriptor?.canonicalIri === canonicalIri) {
|
|
1148
|
+
for (const iri of descriptor.aliases) {
|
|
1149
|
+
const value = values[iri];
|
|
1150
|
+
if (globalThis.Array.isArray(value) && value.length > 0 &&
|
|
1151
|
+
getRawPropertyDescriptor(object, iri)?.canonicalIri === canonicalIri) return value;
|
|
1152
|
+
}
|
|
1153
|
+
}
|
|
1154
|
+
prototype = globalThis.Object.getPrototypeOf(prototype);
|
|
1155
|
+
}
|
|
1156
|
+
return canonical;
|
|
1157
|
+
}
|
|
1158
|
+
|
|
846
1159
|
function copyRawProperties(source: object, destination: object): void {
|
|
1160
|
+
const published = publishedRawProperties.get(source);
|
|
1161
|
+
if (published == null) publishedRawProperties.delete(destination);
|
|
1162
|
+
else publishedRawProperties.set(destination, published);
|
|
847
1163
|
const retained = retainedRawProperties.get(source);
|
|
848
1164
|
if (retained == null) retainedRawProperties.delete(destination);
|
|
849
1165
|
else retainedRawProperties.set(destination, retained);
|
|
@@ -1092,7 +1408,9 @@ async function expandReceivedJsonLd(
|
|
|
1092
1408
|
// The embedded objects get the documents as they are in one copy of the
|
|
1093
1409
|
// whole document, rather than a copy each, which would copy a document as
|
|
1094
1410
|
// many times as there are documents around it:
|
|
1095
|
-
|
|
1411
|
+
// Distinct decoded children expose their cached documents through toJsonLd(),
|
|
1412
|
+
// so repeated source references must become independently mutable copies here.
|
|
1413
|
+
const received = candidates.length > 0 ? copyJsonValue(json, false, false) : undefined;
|
|
1096
1414
|
const documents = received == null ? [] : collectEmbeddedDocuments(received);
|
|
1097
1415
|
if (documents.length < 1) {
|
|
1098
1416
|
return {
|
|
@@ -1287,6 +1605,55 @@ async function readRawProperty(
|
|
|
1287
1605
|
return [];
|
|
1288
1606
|
}
|
|
1289
1607
|
|
|
1608
|
+
/**
|
|
1609
|
+
* Returns a fresh copy with one expanded JSON-LD property replaced or removed.
|
|
1610
|
+
* Known properties use their typed decoder; unknown properties are explicitly
|
|
1611
|
+
* published on serialization. Unrelated received extensions remain read-only.
|
|
1612
|
+
* The required values argument removes the property when null, undefined, or
|
|
1613
|
+
* empty. Hidden verification evidence is not inherited by the copy.
|
|
1614
|
+
* @param object The generated vocabulary object to copy.
|
|
1615
|
+
* @param propertyIri The full property IRI.
|
|
1616
|
+
* @param values Expanded JSON-LD values, or a removal value.
|
|
1617
|
+
* @returns A new object of the same concrete type.
|
|
1618
|
+
* @throws {TypeError} For malformed inputs or unrepresentable known values.
|
|
1619
|
+
* @since 2.5.0
|
|
1620
|
+
*/
|
|
1621
|
+
export function withRawProperty<T extends VocabularyObject>(
|
|
1622
|
+
object: T,
|
|
1623
|
+
propertyIri: string | URL,
|
|
1624
|
+
values: readonly RawPropertyValue[] | null | undefined,
|
|
1625
|
+
): Promise<T> {
|
|
1626
|
+
if (arguments.length < 3) return Promise.reject(new TypeError("withRawProperty() requires a values argument."));
|
|
1627
|
+
return writeRawPropertyValues(object, [[propertyIri, values]], "withRawProperty");
|
|
1628
|
+
}
|
|
1629
|
+
|
|
1630
|
+
/**
|
|
1631
|
+
* Atomically replaces or removes expanded JSON-LD properties in a fresh copy.
|
|
1632
|
+
* Inputs are snapshotted before asynchronous decoding. Duplicate destinations,
|
|
1633
|
+
* including known aliases, reject the entire batch. Empty batches still copy.
|
|
1634
|
+
* See {@link withRawProperty} for publication and verification behavior.
|
|
1635
|
+
* @param object The generated vocabulary object to copy.
|
|
1636
|
+
* @param entries A record or iterable of property IRI and value pairs.
|
|
1637
|
+
* @returns A new object of the same concrete type.
|
|
1638
|
+
* @throws {TypeError} For malformed inputs, duplicates, or unrepresentable values.
|
|
1639
|
+
* @since 2.5.0
|
|
1640
|
+
*/
|
|
1641
|
+
export function withRawProperties<T extends VocabularyObject>(
|
|
1642
|
+
object: T,
|
|
1643
|
+
entries: Readonly<Record<string, readonly RawPropertyValue[] | null | undefined>>,
|
|
1644
|
+
): Promise<T>;
|
|
1645
|
+
export function withRawProperties<T extends VocabularyObject>(
|
|
1646
|
+
object: T,
|
|
1647
|
+
entries: Iterable<readonly [string | URL, readonly RawPropertyValue[] | null | undefined]>,
|
|
1648
|
+
): Promise<T>;
|
|
1649
|
+
export function withRawProperties<T extends VocabularyObject>(
|
|
1650
|
+
object: T,
|
|
1651
|
+
entries: Readonly<Record<string, readonly RawPropertyValue[] | null | undefined>> |
|
|
1652
|
+
Iterable<readonly [string | URL, readonly RawPropertyValue[] | null | undefined]>,
|
|
1653
|
+
): Promise<T> {
|
|
1654
|
+
return writeRawPropertyValues(object, entries, "withRawProperties");
|
|
1655
|
+
}
|
|
1656
|
+
|
|
1290
1657
|
/**
|
|
1291
1658
|
* Gets the values of a property of a vocabulary object in expanded JSON-LD,
|
|
1292
1659
|
* looking the property up by its full IRI. This works for properties that
|
|
@@ -1299,7 +1666,8 @@ async function readRawProperty(
|
|
|
1299
1666
|
*
|
|
1300
1667
|
* - For a property that the object's class has no accessor for, the result
|
|
1301
1668
|
* is the values retained when the object was decoded by \`fromJsonLd()\`.
|
|
1302
|
-
* Objects constructed locally have none
|
|
1669
|
+
* Objects constructed locally have none unless raw values were explicitly
|
|
1670
|
+
* written with {@link withRawProperty} or {@link withRawProperties}.
|
|
1303
1671
|
* - For a property that the class has an accessor for, including a
|
|
1304
1672
|
* redundant alias of such a property, the result is the current typed
|
|
1305
1673
|
* values encoded back into expanded JSON-LD. It reflects \`clone()\`
|
|
@@ -1402,11 +1770,35 @@ function getKnownPropertyIris(typeUri, types) {
|
|
|
1402
1770
|
* the raw property functions reach these encoders and the retained unknown
|
|
1403
1771
|
* properties.
|
|
1404
1772
|
*/
|
|
1405
|
-
async function* generateRawPropertyDescriptors(typeUri, types) {
|
|
1773
|
+
async function* generateRawPropertyDescriptors(typeUri, types, moduleVarNames) {
|
|
1406
1774
|
const type = types[typeUri];
|
|
1407
1775
|
if (type.extends != null && type.properties.length < 1) return;
|
|
1408
1776
|
yield "static {\n";
|
|
1409
1777
|
if (type.extends == null) yield `
|
|
1778
|
+
rawPropertyBrands.set(this.prototype, (object: object) => {
|
|
1779
|
+
void (object as ${type.name}).#documentLoader;
|
|
1780
|
+
});
|
|
1781
|
+
globalThis.Object.defineProperty(this.prototype, RAW_PROPERTY_WRITE_PROTOCOL, {
|
|
1782
|
+
value: async function (this: ${type.name}, entries: readonly RawPropertyWriteEntry[], preprocessedNode?: unknown): Promise<object> {
|
|
1783
|
+
// Reading these private fields also validates the root private brand.
|
|
1784
|
+
const options = {
|
|
1785
|
+
documentLoader: this.#documentLoader,
|
|
1786
|
+
contextLoader: this.#contextLoader,
|
|
1787
|
+
tracerProvider: this.#tracerProvider,
|
|
1788
|
+
verifyPortableObject: this.#verifyPortableObject,
|
|
1789
|
+
baseUrl: this.#_baseUrl,
|
|
1790
|
+
_rawPropertyWrite: true,
|
|
1791
|
+
};
|
|
1792
|
+
const result = await writeRawProperties(this, entries, options);
|
|
1793
|
+
if (preprocessedNode != null) {
|
|
1794
|
+
retainPreprocessedRawProperties(result, preprocessedNode);
|
|
1795
|
+
publishSuppliedRawProperties(result, preprocessedNode);
|
|
1796
|
+
}
|
|
1797
|
+
return result;
|
|
1798
|
+
},
|
|
1799
|
+
configurable: true,
|
|
1800
|
+
writable: true,
|
|
1801
|
+
});
|
|
1410
1802
|
globalThis.Object.defineProperty(this.prototype, RAW_PROPERTY_PROTOCOL, {
|
|
1411
1803
|
value: function (
|
|
1412
1804
|
this: ${type.name},
|
|
@@ -1430,9 +1822,26 @@ async function* generateRawPropertyDescriptors(typeUri, types) {
|
|
|
1430
1822
|
for (const property of type.properties) {
|
|
1431
1823
|
let element = "";
|
|
1432
1824
|
for (const code of generateExpandedPropertyElement(property, types)) element += code;
|
|
1825
|
+
const decoder = [...generatePropertyDecoder(property, types, await getFieldName(property.uri, ""), "inputValues", moduleVarNames)].join("");
|
|
1433
1826
|
yield `
|
|
1434
1827
|
descriptor = {
|
|
1435
1828
|
canonicalIri: ${JSON.stringify(property.uri)},
|
|
1829
|
+
aliases: ${JSON.stringify((property.redundantProperties ?? []).map((alias) => alias.uri))},
|
|
1830
|
+
validate(object: object): void { void (object as ${type.name}).${await getFieldName(property.uri)}; },
|
|
1831
|
+
assign(object: object, values: unknown[]): void {
|
|
1832
|
+
(object as ${type.name}).${await getFieldName(property.uri)} = values as never;
|
|
1833
|
+
${areAllScalarTypes(property.range, types) ? "" : `(object as ${type.name}).${await getFieldName(property.uri, "#_trust")} = new Set();`}
|
|
1834
|
+
},
|
|
1835
|
+
${decoder.includes("await") ? "" : "// oxlint-disable-next-line require-await"}
|
|
1836
|
+
async decode(input: readonly unknown[], options: RawPropertyDecodeOptions): Promise<unknown[]> {
|
|
1837
|
+
${await generateField(property, types, "const ")}
|
|
1838
|
+
// deno-lint-ignore no-explicit-any
|
|
1839
|
+
const inputValues = input as any[];
|
|
1840
|
+
let shouldCacheJsonLd = true;
|
|
1841
|
+
${decoder}
|
|
1842
|
+
void shouldCacheJsonLd;
|
|
1843
|
+
return ${await getFieldName(property.uri, "")};
|
|
1844
|
+
},
|
|
1436
1845
|
${element.includes("await") ? "" : "// oxlint-disable-next-line require-await"}
|
|
1437
1846
|
async encode(
|
|
1438
1847
|
object: object,
|
|
@@ -1457,42 +1866,6 @@ async function* generateRawPropertyDescriptors(typeUri, types) {
|
|
|
1457
1866
|
}
|
|
1458
1867
|
//#endregion
|
|
1459
1868
|
//#region src/codec.ts
|
|
1460
|
-
function* generatePreprocessorBlock(property, rangeTypeName, variable, baseUrlExpr, moduleVarNames) {
|
|
1461
|
-
if (property.preprocessors == null || property.preprocessors.length === 0) return;
|
|
1462
|
-
yield `
|
|
1463
|
-
{
|
|
1464
|
-
let _handled: ${rangeTypeName} | undefined;
|
|
1465
|
-
`;
|
|
1466
|
-
for (const pp of property.preprocessors) {
|
|
1467
|
-
const varName = moduleVarNames.get(pp.module);
|
|
1468
|
-
if (varName == null) throw new Error(`Preprocessor module "${pp.module}" is not registered in the generated imports. Ensure all preprocessor modules used in property schemas are available.`);
|
|
1469
|
-
yield `
|
|
1470
|
-
if (_handled === undefined) {
|
|
1471
|
-
const _result = await ${varName}[${JSON.stringify(pp.function)}](v, {
|
|
1472
|
-
documentLoader: options.documentLoader,
|
|
1473
|
-
contextLoader: options.contextLoader,
|
|
1474
|
-
tracerProvider: options.tracerProvider,
|
|
1475
|
-
verifyPortableObject: options.verifyPortableObject,
|
|
1476
|
-
baseUrl: ${baseUrlExpr},
|
|
1477
|
-
});
|
|
1478
|
-
if (_result instanceof Error) throw _result;
|
|
1479
|
-
if (_result !== undefined) {
|
|
1480
|
-
_handled = _result as ${rangeTypeName};
|
|
1481
|
-
retainPreprocessedRawProperties(_handled, v);
|
|
1482
|
-
}
|
|
1483
|
-
}
|
|
1484
|
-
`;
|
|
1485
|
-
}
|
|
1486
|
-
yield `
|
|
1487
|
-
if (_handled !== undefined) {
|
|
1488
|
-
// The document does not describe what a preprocessor made of it:
|
|
1489
|
-
skipReceivedJsonLd(_handled);
|
|
1490
|
-
${variable}.push(_handled);
|
|
1491
|
-
continue;
|
|
1492
|
-
}
|
|
1493
|
-
}
|
|
1494
|
-
`;
|
|
1495
|
-
}
|
|
1496
1869
|
async function* generateEncoder(typeUri, types) {
|
|
1497
1870
|
const type = types[typeUri];
|
|
1498
1871
|
yield `
|
|
@@ -1541,7 +1914,8 @@ async function* generateEncoder(typeUri, types) {
|
|
|
1541
1914
|
`;
|
|
1542
1915
|
if (isCompactableType(typeUri, types)) {
|
|
1543
1916
|
yield `
|
|
1544
|
-
if (options.format == null && this.isCompactable()
|
|
1917
|
+
if (options.format == null && this.isCompactable() &&
|
|
1918
|
+
(publishedRawProperties.get(this)?.size ?? 0) === 0) {
|
|
1545
1919
|
`;
|
|
1546
1920
|
if (type.extends == null) yield "const result: Record<string, unknown> = {};";
|
|
1547
1921
|
else {
|
|
@@ -1618,7 +1992,7 @@ async function* generateEncoder(typeUri, types) {
|
|
|
1618
1992
|
// deno-lint-ignore no-unused-vars prefer-const
|
|
1619
1993
|
let array: unknown[];
|
|
1620
1994
|
`;
|
|
1621
|
-
if (type.extends == null) yield "const values: Record<string, unknown[] | string> =
|
|
1995
|
+
if (type.extends == null) yield "const values: Record<string, unknown[] | string> = publishedRawPropertyValues(this);";
|
|
1622
1996
|
else yield `
|
|
1623
1997
|
const baseValues = await super.toJsonLd({
|
|
1624
1998
|
...options,
|
|
@@ -1685,7 +2059,7 @@ async function* generateEncoder(typeUri, types) {
|
|
|
1685
2059
|
let compacted = await jsonld.compact(
|
|
1686
2060
|
values,
|
|
1687
2061
|
docContext,
|
|
1688
|
-
{ documentLoader: options.contextLoader },
|
|
2062
|
+
{ documentLoader: options.contextLoader, keepFreeFloatingNodes: true },
|
|
1689
2063
|
);
|
|
1690
2064
|
`;
|
|
1691
2065
|
if (hasExtraContexts) yield `
|
|
@@ -1698,6 +2072,7 @@ async function* generateEncoder(typeUri, types) {
|
|
|
1698
2072
|
docContext = [...currentContexts, ...additionalContexts];
|
|
1699
2073
|
compacted = await jsonld.compact(values, docContext, {
|
|
1700
2074
|
documentLoader: options.contextLoader,
|
|
2075
|
+
keepFreeFloatingNodes: true,
|
|
1701
2076
|
});
|
|
1702
2077
|
}
|
|
1703
2078
|
}
|
|
@@ -1716,9 +2091,11 @@ async function* generateEncoder(typeUri, types) {
|
|
|
1716
2091
|
compacted.${compactName} != null) {
|
|
1717
2092
|
if (Array.isArray(compacted.${compactName})) {
|
|
1718
2093
|
for (const element of compacted.${compactName}) {
|
|
1719
|
-
element
|
|
2094
|
+
if (element != null && typeof element === "object") {
|
|
2095
|
+
element["@context"] = docContext;
|
|
2096
|
+
}
|
|
1720
2097
|
}
|
|
1721
|
-
} else {
|
|
2098
|
+
} else if (typeof compacted.${compactName} === "object") {
|
|
1722
2099
|
compacted.${compactName}["@context"] = docContext;
|
|
1723
2100
|
}
|
|
1724
2101
|
}
|
|
@@ -1842,6 +2219,9 @@ async function* generateDecoder(typeUri, types, moduleVarNames) {
|
|
|
1842
2219
|
Array.isArray((json as { "@graph"?: unknown })["@graph"])
|
|
1843
2220
|
? (json as { "@graph": unknown[] })["@graph"]
|
|
1844
2221
|
: undefined;
|
|
2222
|
+
if (isRawPropertyWrite(options) && graph != null) {
|
|
2223
|
+
throw new TypeError("A remaining graph wrapper cannot be represented by the typed decoder.");
|
|
2224
|
+
}
|
|
1845
2225
|
values =
|
|
1846
2226
|
// deno-lint-ignore no-explicit-any
|
|
1847
2227
|
(graph == null ? json : graph[0] ?? {}) as
|
|
@@ -1874,6 +2254,11 @@ async function* generateDecoder(typeUri, types, moduleVarNames) {
|
|
|
1874
2254
|
// deno-lint-ignore no-explicit-any
|
|
1875
2255
|
(expanded[0] ?? {}) as (Record<string, any[]> & { "@id"?: string });
|
|
1876
2256
|
}
|
|
2257
|
+
if (isRawPropertyWrite(options) &&
|
|
2258
|
+
("@graph" in values || "@included" in values || "@reverse" in values ||
|
|
2259
|
+
globalThis.Object.keys(values).some(key => key.startsWith("_:")))) {
|
|
2260
|
+
throw new TypeError("The supplied node contains structural data that the typed decoder cannot represent.");
|
|
2261
|
+
}
|
|
1877
2262
|
const id = parseJsonLdId(values["@id"], options.baseUrl);
|
|
1878
2263
|
if (id != null && options.baseUrl == null) {
|
|
1879
2264
|
options = { ...options, baseUrl: id };
|
|
@@ -1899,7 +2284,7 @@ async function* generateDecoder(typeUri, types, moduleVarNames) {
|
|
|
1899
2284
|
}
|
|
1900
2285
|
`;
|
|
1901
2286
|
yield `
|
|
1902
|
-
let cacheJsonLd = !("_fromSubclass" in options) || !options._fromSubclass
|
|
2287
|
+
let cacheJsonLd = !isRawPropertyWrite(options) && (!("_fromSubclass" in options) || !options._fromSubclass)
|
|
1903
2288
|
? normalizeJsonLdIris(
|
|
1904
2289
|
expanded,
|
|
1905
2290
|
PORTABLE_IRI_KEYS,
|
|
@@ -1941,78 +2326,28 @@ async function* generateDecoder(typeUri, types, moduleVarNames) {
|
|
|
1941
2326
|
let shouldCacheJsonLd = instance._shouldCacheJsonLd;
|
|
1942
2327
|
`;
|
|
1943
2328
|
for (const property of type.properties) {
|
|
2329
|
+
yield `if (!isRawPropertyWrite(options) ||
|
|
2330
|
+
getRawPropertyDescriptor(instance, ${JSON.stringify(property.uri)}) ===
|
|
2331
|
+
rawPropertyDescriptors.get(${type.name}.prototype)?.get(${JSON.stringify(property.uri)})) {`;
|
|
1944
2332
|
const variable = await getFieldName(property.uri, "");
|
|
1945
2333
|
yield await generateField(property, types, "const ");
|
|
1946
2334
|
const arrayVariable = `${variable}__array`;
|
|
2335
|
+
const propertyValues = property.uri === "https://w3id.org/fep/ef61/gateways" ? "getPortableActorGateways(values) as typeof values[string]" : `values[${JSON.stringify(property.uri)}]`;
|
|
1947
2336
|
yield `
|
|
1948
|
-
let ${arrayVariable} =
|
|
2337
|
+
let ${arrayVariable} = isRawPropertyWrite(options)
|
|
2338
|
+
? rawPropertyInputValues(instance, ${JSON.stringify(property.uri)}, values) as typeof values[string]
|
|
2339
|
+
: ${propertyValues};
|
|
1949
2340
|
`;
|
|
1950
2341
|
if (property.redundantProperties != null) for (const prop of property.redundantProperties) yield `
|
|
1951
|
-
if (
|
|
2342
|
+
if (!isRawPropertyWrite(options) &&
|
|
2343
|
+
(${arrayVariable} == null || ${arrayVariable}.length < 1)) {
|
|
1952
2344
|
${arrayVariable} = values[${JSON.stringify(prop.uri)}];
|
|
1953
2345
|
}
|
|
1954
2346
|
`;
|
|
1955
|
-
|
|
1956
|
-
? ${arrayVariable}[0]["@list"]
|
|
1957
|
-
: ${arrayVariable}`;
|
|
1958
|
-
if (isNonFunctionalProperty(property) && property.container === "graph") itemsExpression = `(${itemsExpression}).flatMap((item: unknown) =>
|
|
1959
|
-
item != null && typeof item === "object" && "@graph" in item &&
|
|
1960
|
-
Array.isArray((item as { "@graph": unknown })["@graph"])
|
|
1961
|
-
? (item as { "@graph": unknown[] })["@graph"]
|
|
1962
|
-
: [item]
|
|
1963
|
-
)`;
|
|
2347
|
+
yield* generatePropertyDecoder(property, types, variable, arrayVariable, moduleVarNames, "this._shouldCacheDecodedJsonLd(decoded)");
|
|
1964
2348
|
yield `
|
|
1965
|
-
for (
|
|
1966
|
-
const v of ${arrayVariable} == null
|
|
1967
|
-
? []
|
|
1968
|
-
: ${itemsExpression}
|
|
1969
|
-
) {
|
|
1970
|
-
if (v == null) continue;
|
|
1971
|
-
`;
|
|
1972
|
-
const propertyBaseUrl = "options.baseUrl";
|
|
1973
|
-
yield* generatePreprocessorBlock(property, getTypeNames(property.range, types), variable, propertyBaseUrl, moduleVarNames);
|
|
1974
|
-
if (!areAllScalarTypes(property.range, types)) yield `
|
|
1975
|
-
if (typeof v === "object" && "@id" in v && !("@type" in v)
|
|
1976
|
-
&& globalThis.Object.keys(v).length === 1) {
|
|
1977
|
-
if (v["@id"].startsWith("_:")) continue;
|
|
1978
|
-
${variable}.push(parseIri(v["@id"], ${propertyBaseUrl}));
|
|
1979
|
-
continue;
|
|
1980
|
-
}
|
|
1981
|
-
`;
|
|
1982
|
-
yield `
|
|
1983
|
-
const decoded =
|
|
1984
|
-
`;
|
|
1985
|
-
const lenient = property.range.length == 1 && skipsUnparsable(property.range[0]);
|
|
1986
|
-
if (property.range.length == 1) {
|
|
1987
|
-
if (lenient) {
|
|
1988
|
-
yield getDataCheck(property.range[0], types, "v");
|
|
1989
|
-
yield " ? ";
|
|
1990
|
-
}
|
|
1991
|
-
yield getDecoder(property.range[0], types, "v", "options", propertyBaseUrl);
|
|
1992
|
-
if (lenient) yield " : undefined";
|
|
1993
|
-
} else {
|
|
1994
|
-
const decoders = getDecoders(property.range, types, "v", "options", propertyBaseUrl);
|
|
1995
|
-
for (const code of decoders) yield code;
|
|
1996
|
-
}
|
|
1997
|
-
yield `
|
|
1998
|
-
;
|
|
1999
|
-
`;
|
|
2000
|
-
yield `
|
|
2001
|
-
if (typeof decoded === "undefined") {
|
|
2002
|
-
shouldCacheJsonLd = false;
|
|
2003
|
-
continue;
|
|
2004
|
-
}
|
|
2005
|
-
`;
|
|
2006
|
-
yield `
|
|
2007
|
-
if (!this._shouldCacheDecodedJsonLd(decoded)) {
|
|
2008
|
-
shouldCacheJsonLd = false;
|
|
2009
|
-
}
|
|
2010
|
-
keepReceivedJsonLd(decoded, v, options);
|
|
2011
|
-
${variable}.push(decoded);
|
|
2012
|
-
`;
|
|
2013
|
-
yield `
|
|
2014
|
-
}
|
|
2015
2349
|
instance.${await getFieldName(property.uri)} = ${variable};
|
|
2350
|
+
}
|
|
2016
2351
|
`;
|
|
2017
2352
|
}
|
|
2018
2353
|
yield `
|
|
@@ -2026,9 +2361,10 @@ async function* generateDecoder(typeUri, types, moduleVarNames) {
|
|
|
2026
2361
|
);
|
|
2027
2362
|
if (retained != null) retainedRawProperties.set(instance, retained);
|
|
2028
2363
|
}
|
|
2364
|
+
if (isRawPropertyWrite(options)) publishSuppliedRawProperties(instance, values);
|
|
2029
2365
|
instance._shouldCacheJsonLd = shouldCacheJsonLd;
|
|
2030
2366
|
if (
|
|
2031
|
-
shouldCacheJsonLd &&
|
|
2367
|
+
shouldCacheJsonLd && !isRawPropertyWrite(options) &&
|
|
2032
2368
|
(!("_fromSubclass" in options) || !options._fromSubclass)
|
|
2033
2369
|
) {
|
|
2034
2370
|
try {
|
|
@@ -2240,7 +2576,8 @@ async function* generateCloner(typeUri, types) {
|
|
|
2240
2576
|
* for details, including how cached JSON-LD affects serialization.
|
|
2241
2577
|
*
|
|
2242
2578
|
* Unknown properties retained when this instance was decoded are shared
|
|
2243
|
-
* with the clone,
|
|
2579
|
+
* with the clone, together with the set of explicitly published raw
|
|
2580
|
+
* properties, so \`getRawPropertyValues()\` returns them for the clone
|
|
2244
2581
|
* as well, even if the clone replaces other values.
|
|
2245
2582
|
*
|
|
2246
2583
|
* A clone never inherits a signed JSON-LD representation retained by
|
|
@@ -3536,12 +3873,16 @@ const RAW_PROPERTY_IMPORTS = [
|
|
|
3536
3873
|
"encodeNestedVocabularyValue",
|
|
3537
3874
|
"expandRawPropertyValue",
|
|
3538
3875
|
"RAW_PROPERTY_PROTOCOL",
|
|
3876
|
+
"RAW_PROPERTY_WRITE_PROTOCOL",
|
|
3877
|
+
"type RawPropertyWriteEntry",
|
|
3878
|
+
"writeRawPropertyValues",
|
|
3539
3879
|
"type RawPropertyRequest",
|
|
3540
3880
|
"readRawPropertyValues",
|
|
3541
3881
|
"retainRawProperties",
|
|
3542
3882
|
"type RetainedRawProperties"
|
|
3543
3883
|
].join(",\n ");
|
|
3544
3884
|
const SIGNED_REPRESENTATION_IMPORTS = [
|
|
3885
|
+
"clearRetainedSignedRepresentation",
|
|
3545
3886
|
"enterSignedValueScope",
|
|
3546
3887
|
"resolveSignedValues",
|
|
3547
3888
|
"retainedSignedValueRef"
|
|
@@ -3691,7 +4032,7 @@ async function* generateClass(typeUri, types, moduleVarNames) {
|
|
|
3691
4032
|
for await (const code of generateCloner(typeUri, types)) yield code;
|
|
3692
4033
|
for await (const code of generateDeepCloner(typeUri, types)) yield code.replace(/[ \t]+$/gm, "");
|
|
3693
4034
|
for await (const code of generateDeepCloneDescriptor(typeUri, types)) yield code.replace(/[ \t]+$/gm, "");
|
|
3694
|
-
for await (const code of generateRawPropertyDescriptors(typeUri, types)) yield code.replace(/[ \t]+$/gm, "");
|
|
4035
|
+
for await (const code of generateRawPropertyDescriptors(typeUri, types, moduleVarNames)) yield code.replace(/[ \t]+$/gm, "");
|
|
3695
4036
|
for await (const code of generateProperties(typeUri, types, moduleVarNames)) yield code;
|
|
3696
4037
|
for await (const code of generateEncoder(typeUri, types)) yield code;
|
|
3697
4038
|
for await (const code of generateDecoder(typeUri, types, moduleVarNames)) yield code;
|