@fedify/vocab-tools 2.5.0-dev.2664 → 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/dist/mod.cjs +822 -99
- package/dist/mod.d.cts +3 -3
- package/dist/mod.d.ts +3 -3
- package/dist/mod.js +822 -99
- package/package.json +19 -2
- package/deno.json +0 -32
- package/src/__snapshots__/class.test.ts.deno.snap +0 -169445
- package/src/__snapshots__/class.test.ts.node.snap +0 -169443
- package/src/__snapshots__/class.test.ts.snap +0 -169445
- package/src/class.test.ts +0 -302
- package/src/class.ts +0 -486
- package/src/codec.test.ts +0 -479
- package/src/codec.ts +0 -703
- package/src/constructor.ts +0 -464
- package/src/deep-clone.ts +0 -175
- package/src/field.ts +0 -46
- package/src/fs.test.ts +0 -31
- package/src/fs.ts +0 -21
- package/src/generate.ts +0 -24
- package/src/inspector.ts +0 -116
- package/src/mod.ts +0 -8
- package/src/property-array.ts +0 -198
- package/src/property.ts +0 -754
- package/src/schema.test.ts +0 -391
- package/src/schema.ts +0 -439
- package/src/schema.yaml +0 -336
- package/src/type.ts +0 -738
- package/tsconfig.check.json +0 -12
- package/tsdown.config.ts +0 -28
package/dist/mod.js
CHANGED
|
@@ -7,7 +7,7 @@ import { parse } from "yaml";
|
|
|
7
7
|
import { pascalCase } from "es-toolkit";
|
|
8
8
|
//#region deno.json
|
|
9
9
|
var name = "@fedify/vocab-tools";
|
|
10
|
-
var version = "2.5.0-dev.
|
|
10
|
+
var version = "2.5.0-dev.2710+c394b8f2";
|
|
11
11
|
//#endregion
|
|
12
12
|
//#region src/type.ts
|
|
13
13
|
const HEURISTICS_CONTEXTS = [
|
|
@@ -548,7 +548,17 @@ function getEncoder(typeUri, types, variable, optionsVariable, compact = false)
|
|
|
548
548
|
...(${optionsVariable}),
|
|
549
549
|
format: undefined,
|
|
550
550
|
context: undefined,
|
|
551
|
-
|
|
551
|
+
// @ts-ignore: an internal option
|
|
552
|
+
_embedding: true,
|
|
553
|
+
})` : `await encodeNestedVocabularyValue(
|
|
554
|
+
${optionsVariable},
|
|
555
|
+
${variable},
|
|
556
|
+
() => ${variable}.toJsonLd({
|
|
557
|
+
...(${optionsVariable}),
|
|
558
|
+
// @ts-ignore: an internal option
|
|
559
|
+
_embedding: true,
|
|
560
|
+
}),
|
|
561
|
+
)`;
|
|
552
562
|
throw new Error(`Unknown type: ${typeUri}`);
|
|
553
563
|
}
|
|
554
564
|
function getTypeGuard(typeUri, types, variable) {
|
|
@@ -574,7 +584,14 @@ function getDecoder(typeUri, types, variable, optionsVariable, baseUrlVariable)
|
|
|
574
584
|
if (typeUri in scalarTypes) return scalarTypes[typeUri].decoder(variable, baseUrlVariable);
|
|
575
585
|
if (typeUri in types) return `await ${types[typeUri].name}.fromJsonLd(
|
|
576
586
|
${variable},
|
|
577
|
-
{
|
|
587
|
+
{
|
|
588
|
+
...${optionsVariable},
|
|
589
|
+
baseUrl: ${baseUrlVariable},
|
|
590
|
+
// @ts-ignore: an internal option
|
|
591
|
+
_retainsRawProperties: true,
|
|
592
|
+
// @ts-ignore: an internal option
|
|
593
|
+
_expanded: true,
|
|
594
|
+
}
|
|
578
595
|
)`;
|
|
579
596
|
throw new Error(`Unknown type: ${typeUri}`);
|
|
580
597
|
}
|
|
@@ -744,6 +761,701 @@ async function loadSchemaFiles(dir) {
|
|
|
744
761
|
return Object.fromEntries(entries);
|
|
745
762
|
}
|
|
746
763
|
//#endregion
|
|
764
|
+
//#region src/raw-property.ts
|
|
765
|
+
/**
|
|
766
|
+
* Emits the body of a loop that encodes the values of a property into the
|
|
767
|
+
* shape that `toJsonLd({ format: "expand" })` passes to `jsonld.expand()`.
|
|
768
|
+
* The loop pushes encoded values into a local `array`, and expects the
|
|
769
|
+
* current value in `v` and the encoding options in `options`.
|
|
770
|
+
* @param property The property to encode.
|
|
771
|
+
* @param types The type schemas.
|
|
772
|
+
* @param signedValueScope The expression of the signed-value scope whose
|
|
773
|
+
* placeholders should replace retained signed values,
|
|
774
|
+
* or `undefined` to encode them as they are.
|
|
775
|
+
* @returns The code of the loop body.
|
|
776
|
+
*/
|
|
777
|
+
function* generateExpandedPropertyElement(property, types, signedValueScope) {
|
|
778
|
+
yield `
|
|
779
|
+
let element = (
|
|
780
|
+
`;
|
|
781
|
+
const scalar = areAllScalarTypes(property.range, types);
|
|
782
|
+
if (!scalar) {
|
|
783
|
+
if (signedValueScope != null) yield `retainedSignedValueRef(v, ${signedValueScope}) ?? (`;
|
|
784
|
+
yield "v instanceof URL ? { \"@id\": formatIri(v) } : ";
|
|
785
|
+
}
|
|
786
|
+
for (const code of getEncoders(property.range, types, "v", "options")) yield code;
|
|
787
|
+
if (!scalar && signedValueScope != null) yield ")";
|
|
788
|
+
yield `
|
|
789
|
+
);
|
|
790
|
+
if (Array.isArray(element)) {
|
|
791
|
+
if (element.length < 1) continue;
|
|
792
|
+
if (element.length == 1) element = element[0];
|
|
793
|
+
}
|
|
794
|
+
if (typeof element === "undefined") continue;
|
|
795
|
+
`;
|
|
796
|
+
if (isNonFunctionalProperty(property) && property.container === "graph") yield `array.push({ "@graph": element });`;
|
|
797
|
+
else yield `array.push(element);`;
|
|
798
|
+
}
|
|
799
|
+
/**
|
|
800
|
+
* Emits module-private support for the raw property functions, shared by all
|
|
801
|
+
* generated classes, and the public functions themselves.
|
|
802
|
+
*/
|
|
803
|
+
function generateRawPropertyHelpers() {
|
|
804
|
+
return `
|
|
805
|
+
type RawPropertyEncoder = (
|
|
806
|
+
object: object,
|
|
807
|
+
options: { format: "expand"; contextLoader?: DocumentLoader },
|
|
808
|
+
) => Promise<unknown>;
|
|
809
|
+
|
|
810
|
+
interface RawPropertyDescriptor {
|
|
811
|
+
readonly canonicalIri: string;
|
|
812
|
+
readonly encode: RawPropertyEncoder;
|
|
813
|
+
}
|
|
814
|
+
|
|
815
|
+
// Unknown properties retained while decoding, keyed by the decoded object:
|
|
816
|
+
const retainedRawProperties = new WeakMap<object, RetainedRawProperties>();
|
|
817
|
+
|
|
818
|
+
// Encoders of the properties each generated class declares, keyed by the
|
|
819
|
+
// class's prototype and then by the property IRIs, including aliases:
|
|
820
|
+
const rawPropertyDescriptors = new Map<
|
|
821
|
+
object,
|
|
822
|
+
ReadonlyMap<string, RawPropertyDescriptor>
|
|
823
|
+
>();
|
|
824
|
+
|
|
825
|
+
function getRawPropertyDescriptor(
|
|
826
|
+
object: object,
|
|
827
|
+
iri: string,
|
|
828
|
+
): RawPropertyDescriptor | undefined {
|
|
829
|
+
let prototype: object | null = globalThis.Object.getPrototypeOf(object);
|
|
830
|
+
while (prototype != null) {
|
|
831
|
+
const descriptor = rawPropertyDescriptors.get(prototype)?.get(iri);
|
|
832
|
+
if (descriptor != null) {
|
|
833
|
+
// A subclass can declare the property again without an alias that only
|
|
834
|
+
// a superclass declares, so the property's own IRI is looked up again
|
|
835
|
+
// to take the encoder of the most derived class:
|
|
836
|
+
return descriptor.canonicalIri === iri
|
|
837
|
+
? descriptor
|
|
838
|
+
: (getRawPropertyDescriptor(object, descriptor.canonicalIri) ??
|
|
839
|
+
descriptor);
|
|
840
|
+
}
|
|
841
|
+
prototype = globalThis.Object.getPrototypeOf(prototype);
|
|
842
|
+
}
|
|
843
|
+
return undefined;
|
|
844
|
+
}
|
|
845
|
+
|
|
846
|
+
function copyRawProperties(source: object, destination: object): void {
|
|
847
|
+
const retained = retainedRawProperties.get(source);
|
|
848
|
+
if (retained == null) retainedRawProperties.delete(destination);
|
|
849
|
+
else retainedRawProperties.set(destination, retained);
|
|
850
|
+
}
|
|
851
|
+
|
|
852
|
+
// Objects that were given the document they were received as, or whose values
|
|
853
|
+
// changed after decoding, which that document no longer describes:
|
|
854
|
+
const receivedJsonLd = new WeakSet<object>();
|
|
855
|
+
|
|
856
|
+
// Retains the unknown properties of the node a preprocessor made a value of,
|
|
857
|
+
// such as an Image of a Link, by the class of that value, since the value was
|
|
858
|
+
// not decoded from the node by that class:
|
|
859
|
+
function retainPreprocessedRawProperties(value: unknown, node: unknown): void {
|
|
860
|
+
if (
|
|
861
|
+
value == null || typeof value !== "object" || node == null ||
|
|
862
|
+
typeof node !== "object" || globalThis.Array.isArray(node)
|
|
863
|
+
) {
|
|
864
|
+
return;
|
|
865
|
+
}
|
|
866
|
+
const known = new Set<string>();
|
|
867
|
+
let prototype: object | null = globalThis.Object.getPrototypeOf(value);
|
|
868
|
+
while (prototype != null) {
|
|
869
|
+
for (const iri of rawPropertyDescriptors.get(prototype)?.keys() ?? []) {
|
|
870
|
+
known.add(iri);
|
|
871
|
+
}
|
|
872
|
+
prototype = globalThis.Object.getPrototypeOf(prototype);
|
|
873
|
+
}
|
|
874
|
+
const retained = retainRawProperties(node as Record<string, unknown>, known);
|
|
875
|
+
if (retained != null) retainedRawProperties.set(value, retained);
|
|
876
|
+
}
|
|
877
|
+
|
|
878
|
+
function skipReceivedJsonLd(value: unknown): void {
|
|
879
|
+
if (value != null && typeof value === "object") receivedJsonLd.add(value);
|
|
880
|
+
}
|
|
881
|
+
|
|
882
|
+
function invalidateCachedJsonLd(object: object): void {
|
|
883
|
+
(object as unknown as { _cachedJsonLd?: unknown })._cachedJsonLd =
|
|
884
|
+
undefined;
|
|
885
|
+
receivedJsonLd.add(object);
|
|
886
|
+
}
|
|
887
|
+
|
|
888
|
+
// The received documents of embedded objects that have their own context,
|
|
889
|
+
// keyed by the expanded nodes they became while the outermost object was
|
|
890
|
+
// decoded:
|
|
891
|
+
type ReceivedDocuments = WeakMap<object, object>;
|
|
892
|
+
|
|
893
|
+
// Collects the embedded documents of a received document, at any depth: the
|
|
894
|
+
// objects with their own context other than the outermost node, under keys
|
|
895
|
+
// other than keywords, also inside arrays and @set, @list, and @graph. Value
|
|
896
|
+
// objects and graph objects never become embedded objects, and the marker
|
|
897
|
+
// would change what they mean, so they are left out, as far as their keys
|
|
898
|
+
// tell: an object with @graph and nothing but @context, @id, and @index is a
|
|
899
|
+
// graph object. One with other keys is marked, whatever they are aliases of,
|
|
900
|
+
// as the comparison of the expansions catches a marker that made a node of a
|
|
901
|
+
// graph object:
|
|
902
|
+
function collectEmbeddedDocuments(root: object): object[] {
|
|
903
|
+
const outermost = globalThis.Array.isArray(root) ? root[0] : root;
|
|
904
|
+
const documents: object[] = [];
|
|
905
|
+
const pending: unknown[] = [root];
|
|
906
|
+
while (pending.length > 0) {
|
|
907
|
+
const value = pending.pop();
|
|
908
|
+
if (globalThis.Array.isArray(value)) {
|
|
909
|
+
// A loop, as spreading a long array into arguments overflows the stack:
|
|
910
|
+
for (const element of value) pending.push(element);
|
|
911
|
+
continue;
|
|
912
|
+
}
|
|
913
|
+
if (value == null || typeof value !== "object") continue;
|
|
914
|
+
if (
|
|
915
|
+
value !== outermost && "@context" in value && !("@value" in value) &&
|
|
916
|
+
(!("@graph" in value) ||
|
|
917
|
+
globalThis.Object.keys(value).some((key) =>
|
|
918
|
+
key !== "@context" && key !== "@graph" && key !== "@id" &&
|
|
919
|
+
key !== "@index"
|
|
920
|
+
)) &&
|
|
921
|
+
!("@set" in value) && !("@list" in value)
|
|
922
|
+
) {
|
|
923
|
+
documents.push(value);
|
|
924
|
+
}
|
|
925
|
+
for (const [key, child] of globalThis.Object.entries(value)) {
|
|
926
|
+
if (
|
|
927
|
+
!key.startsWith("@") || key === "@set" || key === "@list" ||
|
|
928
|
+
key === "@graph"
|
|
929
|
+
) {
|
|
930
|
+
pending.push(child);
|
|
931
|
+
}
|
|
932
|
+
}
|
|
933
|
+
}
|
|
934
|
+
return documents;
|
|
935
|
+
}
|
|
936
|
+
|
|
937
|
+
// Copies a document without recursion, copying the replacements of the
|
|
938
|
+
// objects in the map instead of the objects. The replacements are copied in
|
|
939
|
+
// turn, so that objects nested in them are replaced as well:
|
|
940
|
+
function replaceInDocument(
|
|
941
|
+
document: object,
|
|
942
|
+
replacements: ReadonlyMap<object, object>,
|
|
943
|
+
): unknown {
|
|
944
|
+
const root: unknown = globalThis.Array.isArray(document) ? [] : {};
|
|
945
|
+
const pending: [object, Record<string, unknown> | unknown[]][] = [
|
|
946
|
+
[replacements.get(document) ?? document, root as Record<string, unknown>],
|
|
947
|
+
];
|
|
948
|
+
while (pending.length > 0) {
|
|
949
|
+
const [source, target] = pending.pop()!;
|
|
950
|
+
for (const [key, child] of globalThis.Object.entries(source)) {
|
|
951
|
+
let copy: unknown = child;
|
|
952
|
+
if (child != null && typeof child === "object") {
|
|
953
|
+
copy = globalThis.Array.isArray(child) ? [] : {};
|
|
954
|
+
pending.push([
|
|
955
|
+
replacements.get(child) ?? child,
|
|
956
|
+
copy as Record<string, unknown>,
|
|
957
|
+
]);
|
|
958
|
+
}
|
|
959
|
+
if (globalThis.Array.isArray(target)) target.push(copy);
|
|
960
|
+
// An own __proto__ member, as JSON.parse() makes, would otherwise set
|
|
961
|
+
// the prototype of the copy instead:
|
|
962
|
+
else {
|
|
963
|
+
globalThis.Object.defineProperty(target, key, {
|
|
964
|
+
value: copy,
|
|
965
|
+
writable: true,
|
|
966
|
+
enumerable: true,
|
|
967
|
+
configurable: true,
|
|
968
|
+
});
|
|
969
|
+
}
|
|
970
|
+
}
|
|
971
|
+
}
|
|
972
|
+
return root;
|
|
973
|
+
}
|
|
974
|
+
|
|
975
|
+
// Tells whether two JSON values are the same, without recursion, as expanded
|
|
976
|
+
// documents can nest values deeply. The order of object keys does not
|
|
977
|
+
// matter, while the order of array elements does:
|
|
978
|
+
function isSameJsonValue(a: unknown, b: unknown): boolean {
|
|
979
|
+
const pending: [unknown, unknown][] = [[a, b]];
|
|
980
|
+
while (pending.length > 0) {
|
|
981
|
+
const [x, y] = pending.pop()!;
|
|
982
|
+
if (x === y) continue;
|
|
983
|
+
if (
|
|
984
|
+
x == null || y == null || typeof x !== "object" || typeof y !== "object"
|
|
985
|
+
) {
|
|
986
|
+
return false;
|
|
987
|
+
}
|
|
988
|
+
if (globalThis.Array.isArray(x)) {
|
|
989
|
+
if (!globalThis.Array.isArray(y) || x.length !== y.length) return false;
|
|
990
|
+
for (let i = 0; i < x.length; i++) pending.push([x[i], y[i]]);
|
|
991
|
+
continue;
|
|
992
|
+
}
|
|
993
|
+
if (globalThis.Array.isArray(y)) return false;
|
|
994
|
+
const xKeys = globalThis.Object.keys(x);
|
|
995
|
+
if (xKeys.length !== globalThis.Object.keys(y).length) return false;
|
|
996
|
+
for (const key of xKeys) {
|
|
997
|
+
if (!globalThis.Object.hasOwn(y, key)) return false;
|
|
998
|
+
pending.push([
|
|
999
|
+
(x as Record<string, unknown>)[key],
|
|
1000
|
+
(y as Record<string, unknown>)[key],
|
|
1001
|
+
]);
|
|
1002
|
+
}
|
|
1003
|
+
}
|
|
1004
|
+
return true;
|
|
1005
|
+
}
|
|
1006
|
+
|
|
1007
|
+
// Expands a received document, and tells which expanded node each embedded
|
|
1008
|
+
// document with its own context became. Each such document gets a property
|
|
1009
|
+
// with a random IRI as its marker before the expansion, so that JSON-LD
|
|
1010
|
+
// processing itself, with every context as it applies, tells where each
|
|
1011
|
+
// document ends up; the markers are taken out of the expanded document right
|
|
1012
|
+
// after, and the decoders never see them. If a document cannot take the
|
|
1013
|
+
// marker, e.g., as it is a value object under an alias of @value, the document
|
|
1014
|
+
// is expanded as it is, and no embedded object gets its received document:
|
|
1015
|
+
async function expandReceivedJsonLd(
|
|
1016
|
+
json: unknown,
|
|
1017
|
+
contextLoader: DocumentLoader,
|
|
1018
|
+
): Promise<{ expanded: unknown[]; documents?: ReceivedDocuments }> {
|
|
1019
|
+
// Both expansions below take the contexts that one of them loaded, so that
|
|
1020
|
+
// a context is not loaded twice, and cannot fail the second time:
|
|
1021
|
+
const loads = new Map<string, Promise<RemoteDocument>>();
|
|
1022
|
+
const sharedLoader: DocumentLoader = (url, loaderOptions) => {
|
|
1023
|
+
let load = loads.get(url);
|
|
1024
|
+
if (load == null) {
|
|
1025
|
+
load = contextLoader(url, loaderOptions);
|
|
1026
|
+
loads.set(url, load);
|
|
1027
|
+
load.catch(() => loads.delete(url));
|
|
1028
|
+
}
|
|
1029
|
+
return load;
|
|
1030
|
+
};
|
|
1031
|
+
const options = { documentLoader: sharedLoader, keepFreeFloatingNodes: true };
|
|
1032
|
+
// A document under an alias of @nest merges into the node around it, marker
|
|
1033
|
+
// and all, so that node would be taken for the document; any context that
|
|
1034
|
+
// mentions @nest, which few do, makes the document be expanded without
|
|
1035
|
+
// markers. Only contexts count, not, e.g., a content that reads @nest:
|
|
1036
|
+
const mentionsNest = (value: unknown): boolean => {
|
|
1037
|
+
// A loader can return a document as a JSON string, which jsonld.js parses;
|
|
1038
|
+
// one that cannot be parsed counts as a mention, so that no marker is
|
|
1039
|
+
// put in a document that this cannot tell about:
|
|
1040
|
+
if (typeof value === "string") {
|
|
1041
|
+
try {
|
|
1042
|
+
value = globalThis.JSON.parse(value);
|
|
1043
|
+
} catch {
|
|
1044
|
+
return true;
|
|
1045
|
+
}
|
|
1046
|
+
}
|
|
1047
|
+
// Without recursion, as a document can nest values deeply, e.g., under a
|
|
1048
|
+
// term that its context maps to nothing. An object met again on its own
|
|
1049
|
+
// path, i.e., a cycle, counts as a mention, so that no marker is put in it
|
|
1050
|
+
// and jsonld.js rejects the cycle as it would without markers; one shared
|
|
1051
|
+
// by several paths is scanned once:
|
|
1052
|
+
const pending: { item: unknown; exit?: object; context?: boolean }[] = [
|
|
1053
|
+
{ item: value },
|
|
1054
|
+
];
|
|
1055
|
+
const onPath = new WeakSet<object>();
|
|
1056
|
+
// An object can be reached both outside and inside a context, and only
|
|
1057
|
+
// a scan inside one tells whether it mentions @nest:
|
|
1058
|
+
const scannedInContext = new WeakSet<object>();
|
|
1059
|
+
const scannedOutside = new WeakSet<object>();
|
|
1060
|
+
while (pending.length > 0) {
|
|
1061
|
+
const { item, exit, context } = pending.pop()!;
|
|
1062
|
+
if (exit != null) {
|
|
1063
|
+
onPath.delete(exit);
|
|
1064
|
+
(context ? scannedInContext : scannedOutside).add(exit);
|
|
1065
|
+
continue;
|
|
1066
|
+
}
|
|
1067
|
+
if (context && item === "@nest") return true;
|
|
1068
|
+
if (
|
|
1069
|
+
item == null || typeof item !== "object" ||
|
|
1070
|
+
scannedInContext.has(item) || (!context && scannedOutside.has(item))
|
|
1071
|
+
) {
|
|
1072
|
+
continue;
|
|
1073
|
+
}
|
|
1074
|
+
if (onPath.has(item)) return true;
|
|
1075
|
+
onPath.add(item);
|
|
1076
|
+
pending.push({ item: undefined, exit: item, context });
|
|
1077
|
+
if (globalThis.Array.isArray(item)) {
|
|
1078
|
+
for (const element of item) pending.push({ item: element, context });
|
|
1079
|
+
continue;
|
|
1080
|
+
}
|
|
1081
|
+
for (const [key, child] of globalThis.Object.entries(item)) {
|
|
1082
|
+
if (context && key === "@nest") return true;
|
|
1083
|
+
pending.push({ item: child, context: context || key === "@context" });
|
|
1084
|
+
}
|
|
1085
|
+
}
|
|
1086
|
+
return false;
|
|
1087
|
+
};
|
|
1088
|
+
const candidates = json != null && typeof json === "object" &&
|
|
1089
|
+
!mentionsNest(json)
|
|
1090
|
+
? collectEmbeddedDocuments(json)
|
|
1091
|
+
: [];
|
|
1092
|
+
// The embedded objects get the documents as they are in one copy of the
|
|
1093
|
+
// whole document, rather than a copy each, which would copy a document as
|
|
1094
|
+
// many times as there are documents around it:
|
|
1095
|
+
const received = candidates.length > 0 ? copyJsonValue(json) : undefined;
|
|
1096
|
+
const documents = received == null ? [] : collectEmbeddedDocuments(received);
|
|
1097
|
+
if (documents.length < 1) {
|
|
1098
|
+
return {
|
|
1099
|
+
expanded: await jsonld.expand(json as Record<string, unknown>, options),
|
|
1100
|
+
};
|
|
1101
|
+
}
|
|
1102
|
+
// An IRI that a context cannot know, and that cannot be a compact IRI, as
|
|
1103
|
+
// its suffix after the scheme starts with //. Some runtimes do not make
|
|
1104
|
+
// random values everywhere, e.g., Cloudflare Workers outside handlers, in
|
|
1105
|
+
// which case the document is expanded without markers:
|
|
1106
|
+
let token: string;
|
|
1107
|
+
try {
|
|
1108
|
+
token = globalThis.crypto.randomUUID();
|
|
1109
|
+
} catch {
|
|
1110
|
+
return {
|
|
1111
|
+
expanded: await jsonld.expand(json as Record<string, unknown>, options),
|
|
1112
|
+
};
|
|
1113
|
+
}
|
|
1114
|
+
const marker = "https://fedify.dev/ns/received#" + token;
|
|
1115
|
+
const replacements = new Map<object, object>();
|
|
1116
|
+
for (const [index, document] of documents.entries()) {
|
|
1117
|
+
replacements.set(document, {
|
|
1118
|
+
...document,
|
|
1119
|
+
[marker]: globalThis.String(index),
|
|
1120
|
+
});
|
|
1121
|
+
}
|
|
1122
|
+
// Only a document that cannot take its marker makes the document be
|
|
1123
|
+
// expanded again without markers; a context that fails to load fails the
|
|
1124
|
+
// decoding as it would without them:
|
|
1125
|
+
let loadFailed = false;
|
|
1126
|
+
let nestLoaded = false;
|
|
1127
|
+
const markedOptions = {
|
|
1128
|
+
...options,
|
|
1129
|
+
documentLoader: (async (url, loaderOptions) => {
|
|
1130
|
+
try {
|
|
1131
|
+
const loaded = await sharedLoader(url, loaderOptions);
|
|
1132
|
+
if (mentionsNest(loaded.document)) nestLoaded = true;
|
|
1133
|
+
return loaded;
|
|
1134
|
+
} catch (error) {
|
|
1135
|
+
loadFailed = true;
|
|
1136
|
+
throw error;
|
|
1137
|
+
}
|
|
1138
|
+
}) as DocumentLoader,
|
|
1139
|
+
};
|
|
1140
|
+
let expanded: unknown[];
|
|
1141
|
+
try {
|
|
1142
|
+
expanded = await jsonld.expand(
|
|
1143
|
+
replaceInDocument(received as object, replacements) as Record<
|
|
1144
|
+
string,
|
|
1145
|
+
unknown
|
|
1146
|
+
>,
|
|
1147
|
+
markedOptions,
|
|
1148
|
+
);
|
|
1149
|
+
} catch (error) {
|
|
1150
|
+
if (loadFailed) throw error;
|
|
1151
|
+
getLogger(["fedify", "vocab"]).debug(
|
|
1152
|
+
"Failed to mark the embedded documents of {json}: {error}",
|
|
1153
|
+
{ json, error },
|
|
1154
|
+
);
|
|
1155
|
+
return {
|
|
1156
|
+
expanded: await jsonld.expand(json as Record<string, unknown>, options),
|
|
1157
|
+
};
|
|
1158
|
+
}
|
|
1159
|
+
const nodes: ReceivedDocuments = new WeakMap();
|
|
1160
|
+
// Whether two documents became one node, as one under an alias of @nest
|
|
1161
|
+
// merged into the node around it, which leaves the expansion as it would be
|
|
1162
|
+
// without markers but would give that node the wrong document:
|
|
1163
|
+
let merged = false;
|
|
1164
|
+
// Takes the markers out, also from JSON literals, which keep the documents
|
|
1165
|
+
// in them as they are:
|
|
1166
|
+
const pending: { value: unknown; literal: boolean }[] = [
|
|
1167
|
+
{ value: expanded, literal: false },
|
|
1168
|
+
];
|
|
1169
|
+
while (pending.length > 0) {
|
|
1170
|
+
const { value, literal } = pending.pop()!;
|
|
1171
|
+
if (globalThis.Array.isArray(value)) {
|
|
1172
|
+
// A loop, as spreading a long array into arguments overflows the stack:
|
|
1173
|
+
for (const element of value) pending.push({ value: element, literal });
|
|
1174
|
+
continue;
|
|
1175
|
+
}
|
|
1176
|
+
if (value == null || typeof value !== "object") continue;
|
|
1177
|
+
const object = value as Record<string, unknown>;
|
|
1178
|
+
if (marker in object) {
|
|
1179
|
+
const mark = object[marker];
|
|
1180
|
+
const index = literal
|
|
1181
|
+
? undefined
|
|
1182
|
+
: (globalThis.Array.isArray(mark)
|
|
1183
|
+
? (mark[0] as { "@value"?: unknown } | undefined)?.["@value"]
|
|
1184
|
+
: undefined);
|
|
1185
|
+
delete object[marker];
|
|
1186
|
+
if (!literal && globalThis.Array.isArray(mark) && mark.length > 1) {
|
|
1187
|
+
merged = true;
|
|
1188
|
+
break;
|
|
1189
|
+
}
|
|
1190
|
+
if (typeof index === "string") {
|
|
1191
|
+
const document = documents[globalThis.Number(index)];
|
|
1192
|
+
if (document != null) nodes.set(object, document);
|
|
1193
|
+
}
|
|
1194
|
+
}
|
|
1195
|
+
if (!literal && object["@type"] === "@json") {
|
|
1196
|
+
pending.push({ value: object["@value"], literal: true });
|
|
1197
|
+
continue;
|
|
1198
|
+
}
|
|
1199
|
+
for (const [key, child] of globalThis.Object.entries(object)) {
|
|
1200
|
+
if (literal || key !== "@value") pending.push({ value: child, literal });
|
|
1201
|
+
}
|
|
1202
|
+
}
|
|
1203
|
+
// A marker can change what a document expands to in more ways than can be
|
|
1204
|
+
// told before expanding it, e.g., a key of an index map that reads @context
|
|
1205
|
+
// is no context, and a graph object with a marker is a node, so the
|
|
1206
|
+
// document is expanded without markers as well, and the markers' mapping is
|
|
1207
|
+
// used only if both expansions are the same:
|
|
1208
|
+
const unmarked = await jsonld.expand(
|
|
1209
|
+
json as Record<string, unknown>,
|
|
1210
|
+
options,
|
|
1211
|
+
);
|
|
1212
|
+
if (merged || nestLoaded || !isSameJsonValue(expanded, unmarked)) {
|
|
1213
|
+
return { expanded: unmarked };
|
|
1214
|
+
}
|
|
1215
|
+
return { expanded, documents: nodes };
|
|
1216
|
+
}
|
|
1217
|
+
|
|
1218
|
+
// Gives an embedded object the document it was received as, which toJsonLd()
|
|
1219
|
+
// has to return as is, as a proof can cover it. The object is decoded from the
|
|
1220
|
+
// whole document, since an embedded document alone cannot rebuild what its
|
|
1221
|
+
// parents' contexts contributed to it:
|
|
1222
|
+
function keepReceivedJsonLd(
|
|
1223
|
+
object: unknown,
|
|
1224
|
+
node: unknown,
|
|
1225
|
+
options: unknown,
|
|
1226
|
+
): void {
|
|
1227
|
+
const documents = (options as { _receivedDocuments?: ReceivedDocuments })
|
|
1228
|
+
._receivedDocuments;
|
|
1229
|
+
if (
|
|
1230
|
+
documents == null || node == null || typeof node !== "object" ||
|
|
1231
|
+
object == null || typeof object !== "object" ||
|
|
1232
|
+
!(RAW_PROPERTY_PROTOCOL in object) || receivedJsonLd.has(object) ||
|
|
1233
|
+
// Decoding dropped some of the document as malformed, which the document
|
|
1234
|
+
// would bring back:
|
|
1235
|
+
(object as unknown as { _shouldCacheJsonLd?: boolean })
|
|
1236
|
+
._shouldCacheJsonLd === false
|
|
1237
|
+
) {
|
|
1238
|
+
return;
|
|
1239
|
+
}
|
|
1240
|
+
// A graph object with nothing else is decoded from its first node, as
|
|
1241
|
+
// expansion would take that node out of it:
|
|
1242
|
+
const graph = (node as { "@graph"?: unknown })["@graph"];
|
|
1243
|
+
const decodedNode = globalThis.Object.keys(node).length === 1 &&
|
|
1244
|
+
globalThis.Array.isArray(graph) && graph[0] != null &&
|
|
1245
|
+
typeof graph[0] === "object"
|
|
1246
|
+
? graph[0]
|
|
1247
|
+
: node;
|
|
1248
|
+
const document = documents.get(decodedNode);
|
|
1249
|
+
if (document == null) return;
|
|
1250
|
+
receivedJsonLd.add(object);
|
|
1251
|
+
(object as unknown as { _cachedJsonLd?: unknown })._cachedJsonLd = document;
|
|
1252
|
+
embeddedReceivedJsonLd.add(document);
|
|
1253
|
+
}
|
|
1254
|
+
|
|
1255
|
+
// The documents that embedded objects were received as, which they keep as
|
|
1256
|
+
// their cached JSON-LD. Such a document can rely on what the documents around
|
|
1257
|
+
// it define, e.g., terms of their contexts and their base IRIs, so a parent
|
|
1258
|
+
// that encodes its values anew encodes such an object from its values instead;
|
|
1259
|
+
// the object's own toJsonLd() still returns the document as is, as a proof can
|
|
1260
|
+
// cover it. The documents rather than the objects are kept, as a cache can be
|
|
1261
|
+
// copied to another object, e.g., by @fedify/testing:
|
|
1262
|
+
const embeddedReceivedJsonLd = new WeakSet<object>();
|
|
1263
|
+
|
|
1264
|
+
async function readRawProperty(
|
|
1265
|
+
object: object,
|
|
1266
|
+
request: RawPropertyRequest,
|
|
1267
|
+
contextLoader: DocumentLoader,
|
|
1268
|
+
): Promise<readonly unknown[]> {
|
|
1269
|
+
const retained = retainedRawProperties.get(object);
|
|
1270
|
+
for (const iri of request.candidates) {
|
|
1271
|
+
const descriptor = getRawPropertyDescriptor(object, iri);
|
|
1272
|
+
if (descriptor != null) {
|
|
1273
|
+
const value = await descriptor.encode(
|
|
1274
|
+
object,
|
|
1275
|
+
createRawPropertyEncodingOptions(request.stack, contextLoader),
|
|
1276
|
+
);
|
|
1277
|
+
return value === undefined ? [] : await expandRawPropertyValue(
|
|
1278
|
+
descriptor.canonicalIri,
|
|
1279
|
+
value,
|
|
1280
|
+
contextLoader,
|
|
1281
|
+
);
|
|
1282
|
+
}
|
|
1283
|
+
if (retained != null && globalThis.Object.hasOwn(retained, iri)) {
|
|
1284
|
+
return retained[iri];
|
|
1285
|
+
}
|
|
1286
|
+
}
|
|
1287
|
+
return [];
|
|
1288
|
+
}
|
|
1289
|
+
|
|
1290
|
+
/**
|
|
1291
|
+
* Gets the values of a property of a vocabulary object in expanded JSON-LD,
|
|
1292
|
+
* looking the property up by its full IRI. This works for properties that
|
|
1293
|
+
* have no typed accessor as well as for those that do.
|
|
1294
|
+
*
|
|
1295
|
+
* *Raw* means untyped expanded JSON-LD values, such as
|
|
1296
|
+
* \`{ "@value": "Hello" }\` or \`{ "@id": "https://example.com/" }\`, as
|
|
1297
|
+
* opposed to the values that typed accessors return. It does not mean the
|
|
1298
|
+
* received document:
|
|
1299
|
+
*
|
|
1300
|
+
* - For a property that the object's class has no accessor for, the result
|
|
1301
|
+
* is the values retained when the object was decoded by \`fromJsonLd()\`.
|
|
1302
|
+
* Objects constructed locally have none.
|
|
1303
|
+
* - For a property that the class has an accessor for, including a
|
|
1304
|
+
* redundant alias of such a property, the result is the current typed
|
|
1305
|
+
* values encoded back into expanded JSON-LD. It reflects \`clone()\`
|
|
1306
|
+
* replacements and objects fetched by dereferencing accessors, and it can
|
|
1307
|
+
* differ from the received values: for example, values that failed to
|
|
1308
|
+
* decode are missing, and lexical forms such as date-times are
|
|
1309
|
+
* normalized. When a later release adds an accessor for a property,
|
|
1310
|
+
* the result for that property switches from the retained values to the
|
|
1311
|
+
* encoded ones.
|
|
1312
|
+
*
|
|
1313
|
+
* The values are not verified in any way, and IRIs in them are never
|
|
1314
|
+
* dereferenced. Validate them before use, as with any other data received
|
|
1315
|
+
* from a remote server. The result is a deep copy, so modifying it does not
|
|
1316
|
+
* affect the object.
|
|
1317
|
+
*
|
|
1318
|
+
* The IRI is matched as given, and then as normalized by the WHATWG URL
|
|
1319
|
+
* parser. Prefixes are never expanded: \`"as:content"\` is a valid IRI with
|
|
1320
|
+
* the \`as:\` scheme, so it normally matches nothing. An IRI whose scheme is
|
|
1321
|
+
* not \`http:\` or \`https:\` is therefore logged as a warning under the
|
|
1322
|
+
* \`["fedify", "vocab"]\` category.
|
|
1323
|
+
*
|
|
1324
|
+
* \`\`\`typescript ignore
|
|
1325
|
+
* const values = await getRawPropertyValues(
|
|
1326
|
+
* note,
|
|
1327
|
+
* "https://w3id.org/quantpub#structuredUrl",
|
|
1328
|
+
* );
|
|
1329
|
+
* for (const value of values) {
|
|
1330
|
+
* if ("@id" in value && typeof value["@id"] === "string") {
|
|
1331
|
+
* console.log(new URL(value["@id"]));
|
|
1332
|
+
* }
|
|
1333
|
+
* }
|
|
1334
|
+
* \`\`\`
|
|
1335
|
+
*
|
|
1336
|
+
* @param object The vocabulary object to read. It can be an object of any
|
|
1337
|
+
* module generated by \`@fedify/vocab-tools\`.
|
|
1338
|
+
* @param propertyIri The full IRI of the property.
|
|
1339
|
+
* @returns The values of the property, or an empty array if it has none.
|
|
1340
|
+
* @throws {TypeError} If \`propertyIri\` is not an absolute IRI, e.g., an
|
|
1341
|
+
* empty string, a JSON-LD keyword such as \`"@id"\`, a
|
|
1342
|
+
* blank node identifier, a term, or a relative
|
|
1343
|
+
* reference; if \`object\` is not a generated vocabulary
|
|
1344
|
+
* object; or if encoding the values of a known property
|
|
1345
|
+
* meets a cycle of objects.
|
|
1346
|
+
* @since 2.5.0
|
|
1347
|
+
*/
|
|
1348
|
+
export function getRawPropertyValues(
|
|
1349
|
+
object: VocabularyObject,
|
|
1350
|
+
propertyIri: string | URL,
|
|
1351
|
+
): Promise<RawPropertyValue[]> {
|
|
1352
|
+
return readRawPropertyValues(object, propertyIri, "getRawPropertyValues");
|
|
1353
|
+
}
|
|
1354
|
+
|
|
1355
|
+
/**
|
|
1356
|
+
* Gets the first value of a property of a vocabulary object in expanded
|
|
1357
|
+
* JSON-LD, looking the property up by its full IRI. It is equivalent to
|
|
1358
|
+
* \`(await getRawPropertyValues(object, propertyIri))[0] ?? null\`; see
|
|
1359
|
+
* {@link getRawPropertyValues} for how the values are obtained.
|
|
1360
|
+
*
|
|
1361
|
+
* It does not throw when the property has multiple values. JSON-LD does not
|
|
1362
|
+
* order the values of a property unless it is a list, so the first value is
|
|
1363
|
+
* not more significant than the others. A list property has a single value,
|
|
1364
|
+
* the \`{ "@list": [...] }\` object.
|
|
1365
|
+
*
|
|
1366
|
+
* @param object The vocabulary object to read. It can be an object of any
|
|
1367
|
+
* module generated by \`@fedify/vocab-tools\`.
|
|
1368
|
+
* @param propertyIri The full IRI of the property.
|
|
1369
|
+
* @returns The first value of the property, or \`null\` if it has none.
|
|
1370
|
+
* @throws {TypeError} In the same cases as {@link getRawPropertyValues}.
|
|
1371
|
+
* @since 2.5.0
|
|
1372
|
+
*/
|
|
1373
|
+
export async function getRawPropertyValue(
|
|
1374
|
+
object: VocabularyObject,
|
|
1375
|
+
propertyIri: string | URL,
|
|
1376
|
+
): Promise<RawPropertyValue | null> {
|
|
1377
|
+
const values = await readRawPropertyValues(
|
|
1378
|
+
object,
|
|
1379
|
+
propertyIri,
|
|
1380
|
+
"getRawPropertyValue",
|
|
1381
|
+
);
|
|
1382
|
+
return values[0] ?? null;
|
|
1383
|
+
}
|
|
1384
|
+
`;
|
|
1385
|
+
}
|
|
1386
|
+
/**
|
|
1387
|
+
* Collects the full IRIs of the properties that the given class decodes,
|
|
1388
|
+
* including inherited properties and redundant aliases.
|
|
1389
|
+
*/
|
|
1390
|
+
function getKnownPropertyIris(typeUri, types) {
|
|
1391
|
+
const iris = /* @__PURE__ */ new Set();
|
|
1392
|
+
for (const property of getAllProperties(typeUri, types)) {
|
|
1393
|
+
iris.add(property.uri);
|
|
1394
|
+
if (property.redundantProperties != null) for (const alias of property.redundantProperties) iris.add(alias.uri);
|
|
1395
|
+
}
|
|
1396
|
+
return [...iris].sort();
|
|
1397
|
+
}
|
|
1398
|
+
/**
|
|
1399
|
+
* Emits a static block that registers the encoders of the properties the
|
|
1400
|
+
* given class declares, keeping them and their private-field access out of
|
|
1401
|
+
* the declaration files. A root class also installs the method through which
|
|
1402
|
+
* the raw property functions reach these encoders and the retained unknown
|
|
1403
|
+
* properties.
|
|
1404
|
+
*/
|
|
1405
|
+
async function* generateRawPropertyDescriptors(typeUri, types) {
|
|
1406
|
+
const type = types[typeUri];
|
|
1407
|
+
if (type.extends != null && type.properties.length < 1) return;
|
|
1408
|
+
yield "static {\n";
|
|
1409
|
+
if (type.extends == null) yield `
|
|
1410
|
+
globalThis.Object.defineProperty(this.prototype, RAW_PROPERTY_PROTOCOL, {
|
|
1411
|
+
value: function (
|
|
1412
|
+
this: ${type.name},
|
|
1413
|
+
request: RawPropertyRequest,
|
|
1414
|
+
): Promise<readonly unknown[]> {
|
|
1415
|
+
return readRawProperty(
|
|
1416
|
+
this,
|
|
1417
|
+
request,
|
|
1418
|
+
this.#contextLoader ?? getDocumentLoader(),
|
|
1419
|
+
);
|
|
1420
|
+
},
|
|
1421
|
+
configurable: true,
|
|
1422
|
+
enumerable: false,
|
|
1423
|
+
writable: true,
|
|
1424
|
+
});
|
|
1425
|
+
`;
|
|
1426
|
+
if (type.properties.length > 0) yield `
|
|
1427
|
+
const descriptors = new Map<string, RawPropertyDescriptor>();
|
|
1428
|
+
let descriptor: RawPropertyDescriptor;
|
|
1429
|
+
`;
|
|
1430
|
+
for (const property of type.properties) {
|
|
1431
|
+
let element = "";
|
|
1432
|
+
for (const code of generateExpandedPropertyElement(property, types)) element += code;
|
|
1433
|
+
yield `
|
|
1434
|
+
descriptor = {
|
|
1435
|
+
canonicalIri: ${JSON.stringify(property.uri)},
|
|
1436
|
+
${element.includes("await") ? "" : "// oxlint-disable-next-line require-await"}
|
|
1437
|
+
async encode(
|
|
1438
|
+
object: object,
|
|
1439
|
+
options: { format: "expand"; contextLoader?: DocumentLoader },
|
|
1440
|
+
): Promise<unknown> {
|
|
1441
|
+
const array: unknown[] = [];
|
|
1442
|
+
for (const v of (object as ${type.name}).${await getFieldName(property.uri)}) {
|
|
1443
|
+
`;
|
|
1444
|
+
yield element;
|
|
1445
|
+
yield `
|
|
1446
|
+
}
|
|
1447
|
+
if (array.length < 1) return undefined;
|
|
1448
|
+
return ${isNonFunctionalProperty(property) && property.container === "list" ? `{ "@list": array }` : "array"};
|
|
1449
|
+
},
|
|
1450
|
+
};
|
|
1451
|
+
descriptors.set(${JSON.stringify(property.uri)}, descriptor);
|
|
1452
|
+
`;
|
|
1453
|
+
for (const alias of property.redundantProperties ?? []) yield `descriptors.set(${JSON.stringify(alias.uri)}, descriptor);\n`;
|
|
1454
|
+
}
|
|
1455
|
+
if (type.properties.length > 0) yield "rawPropertyDescriptors.set(this.prototype, descriptors);\n";
|
|
1456
|
+
yield "}\n";
|
|
1457
|
+
}
|
|
1458
|
+
//#endregion
|
|
747
1459
|
//#region src/codec.ts
|
|
748
1460
|
function* generatePreprocessorBlock(property, rangeTypeName, variable, baseUrlExpr, moduleVarNames) {
|
|
749
1461
|
if (property.preprocessors == null || property.preprocessors.length === 0) return;
|
|
@@ -766,12 +1478,15 @@ function* generatePreprocessorBlock(property, rangeTypeName, variable, baseUrlEx
|
|
|
766
1478
|
if (_result instanceof Error) throw _result;
|
|
767
1479
|
if (_result !== undefined) {
|
|
768
1480
|
_handled = _result as ${rangeTypeName};
|
|
1481
|
+
retainPreprocessedRawProperties(_handled, v);
|
|
769
1482
|
}
|
|
770
1483
|
}
|
|
771
1484
|
`;
|
|
772
1485
|
}
|
|
773
1486
|
yield `
|
|
774
1487
|
if (_handled !== undefined) {
|
|
1488
|
+
// The document does not describe what a preprocessor made of it:
|
|
1489
|
+
skipReceivedJsonLd(_handled);
|
|
775
1490
|
${variable}.push(_handled);
|
|
776
1491
|
continue;
|
|
777
1492
|
}
|
|
@@ -796,7 +1511,17 @@ async function* generateEncoder(typeUri, types) {
|
|
|
796
1511
|
contextLoader?: DocumentLoader,
|
|
797
1512
|
context?: string | Record<string, string> | (string | Record<string, string>)[],
|
|
798
1513
|
} = {}): Promise<unknown> {
|
|
799
|
-
if (
|
|
1514
|
+
if (
|
|
1515
|
+
options.format == null &&
|
|
1516
|
+
this._cachedJsonLd != null &&
|
|
1517
|
+
// A parent encoding its values anew does not embed the document this
|
|
1518
|
+
// object was received in, which can rely on what was around it there:
|
|
1519
|
+
!(
|
|
1520
|
+
"_embedding" in options &&
|
|
1521
|
+
options._embedding &&
|
|
1522
|
+
embeddedReceivedJsonLd.has(this._cachedJsonLd)
|
|
1523
|
+
)
|
|
1524
|
+
) {
|
|
800
1525
|
return this._cachedJsonLd;
|
|
801
1526
|
}
|
|
802
1527
|
if (options.format !== "compact" && options.context != null) {
|
|
@@ -909,24 +1634,8 @@ async function* generateEncoder(typeUri, types) {
|
|
|
909
1634
|
yield `
|
|
910
1635
|
array = [];
|
|
911
1636
|
for (const v of this.${await getFieldName(property.uri)}) {
|
|
912
|
-
let element = (
|
|
913
1637
|
`;
|
|
914
|
-
|
|
915
|
-
yield "retainedSignedValueRef(v, signedValues.scope) ?? (";
|
|
916
|
-
yield "v instanceof URL ? { \"@id\": formatIri(v) } : ";
|
|
917
|
-
}
|
|
918
|
-
for (const code of getEncoders(property.range, types, "v", "options")) yield code;
|
|
919
|
-
if (!areAllScalarTypes(property.range, types)) yield ")";
|
|
920
|
-
yield `
|
|
921
|
-
);
|
|
922
|
-
if (Array.isArray(element)) {
|
|
923
|
-
if (element.length < 1) continue;
|
|
924
|
-
if (element.length == 1) element = element[0];
|
|
925
|
-
}
|
|
926
|
-
if (typeof element === "undefined") continue;
|
|
927
|
-
`;
|
|
928
|
-
if (isNonFunctionalProperty(property) && property.container === "graph") yield `array.push({ "@graph": element });`;
|
|
929
|
-
else yield `array.push(element);`;
|
|
1638
|
+
yield* generateExpandedPropertyElement(property, types, "signedValues.scope");
|
|
930
1639
|
yield `;
|
|
931
1640
|
}
|
|
932
1641
|
if (array.length > 0) {
|
|
@@ -1038,6 +1747,8 @@ async function* generateEncoder(typeUri, types) {
|
|
|
1038
1747
|
async function* generateDecoder(typeUri, types, moduleVarNames) {
|
|
1039
1748
|
const type = types[typeUri];
|
|
1040
1749
|
yield `
|
|
1750
|
+
static readonly #knownRawPropertyIris: ReadonlySet<string> = new Set(${JSON.stringify(getKnownPropertyIris(typeUri, types))});
|
|
1751
|
+
|
|
1041
1752
|
/**
|
|
1042
1753
|
* Converts a JSON-LD structure to an object of this type.
|
|
1043
1754
|
* @param json The JSON-LD structure to convert.
|
|
@@ -1116,6 +1827,27 @@ async function* generateDecoder(typeUri, types, moduleVarNames) {
|
|
|
1116
1827
|
let values: Record<string, any[]> & { "@id"?: string };
|
|
1117
1828
|
let expanded: unknown[];
|
|
1118
1829
|
if (
|
|
1830
|
+
"_expanded" in options &&
|
|
1831
|
+
options._expanded &&
|
|
1832
|
+
typeof json === "object" &&
|
|
1833
|
+
!Array.isArray(json)
|
|
1834
|
+
) {
|
|
1835
|
+
// An embedded value, which its parent has expanded already; expanding
|
|
1836
|
+
// it again would make other nodes than the ones the received documents
|
|
1837
|
+
// are known by. This comes before _fromSubclass, which an embedded
|
|
1838
|
+
// value inherits from a superclass decoding its parent:
|
|
1839
|
+
// Expansion takes the first node out of a graph object that has nothing
|
|
1840
|
+
// else, which an expanded value can still be:
|
|
1841
|
+
const graph = globalThis.Object.keys(json).length === 1 &&
|
|
1842
|
+
Array.isArray((json as { "@graph"?: unknown })["@graph"])
|
|
1843
|
+
? (json as { "@graph": unknown[] })["@graph"]
|
|
1844
|
+
: undefined;
|
|
1845
|
+
values =
|
|
1846
|
+
// deno-lint-ignore no-explicit-any
|
|
1847
|
+
(graph == null ? json : graph[0] ?? {}) as
|
|
1848
|
+
(Record<string, any[]> & { "@id"?: string });
|
|
1849
|
+
expanded = [values];
|
|
1850
|
+
} else if (
|
|
1119
1851
|
"_fromSubclass" in options &&
|
|
1120
1852
|
options._fromSubclass &&
|
|
1121
1853
|
typeof json === "object" &&
|
|
@@ -1129,10 +1861,15 @@ async function* generateDecoder(typeUri, types, moduleVarNames) {
|
|
|
1129
1861
|
values = {};
|
|
1130
1862
|
expanded = [values];
|
|
1131
1863
|
} else {
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1864
|
+
const received = await expandReceivedJsonLd(
|
|
1865
|
+
json,
|
|
1866
|
+
options.contextLoader ?? getDocumentLoader(),
|
|
1867
|
+
);
|
|
1868
|
+
expanded = received.expanded;
|
|
1869
|
+
if (received.documents != null) {
|
|
1870
|
+
options = { ...options, _receivedDocuments: received.documents } as
|
|
1871
|
+
typeof options;
|
|
1872
|
+
}
|
|
1136
1873
|
values =
|
|
1137
1874
|
// deno-lint-ignore no-explicit-any
|
|
1138
1875
|
(expanded[0] ?? {}) as (Record<string, any[]> & { "@id"?: string });
|
|
@@ -1182,12 +1919,19 @@ async function* generateDecoder(typeUri, types, moduleVarNames) {
|
|
|
1182
1919
|
);
|
|
1183
1920
|
`;
|
|
1184
1921
|
else yield `
|
|
1185
|
-
|
|
1922
|
+
// A shallow copy, as the received documents of embedded objects are known
|
|
1923
|
+
// by the expanded nodes they became:
|
|
1924
|
+
const superValues = { ...values };
|
|
1186
1925
|
delete superValues["@type"];
|
|
1187
1926
|
const instance = await super.fromJsonLd(superValues, {
|
|
1188
1927
|
...options,
|
|
1189
1928
|
// @ts-ignore: an internal option
|
|
1190
1929
|
_fromSubclass: true,
|
|
1930
|
+
// The values are the subclass's, not an embedded value:
|
|
1931
|
+
_expanded: false,
|
|
1932
|
+
// The subclass retains the unknown properties, since only it knows all
|
|
1933
|
+
// properties of the object:
|
|
1934
|
+
_retainsRawProperties: false,
|
|
1191
1935
|
});
|
|
1192
1936
|
if (!(instance instanceof ${type.name})) {
|
|
1193
1937
|
throw new TypeError("Unexpected type: " + instance.constructor.name);
|
|
@@ -1263,6 +2007,7 @@ async function* generateDecoder(typeUri, types, moduleVarNames) {
|
|
|
1263
2007
|
if (!this._shouldCacheDecodedJsonLd(decoded)) {
|
|
1264
2008
|
shouldCacheJsonLd = false;
|
|
1265
2009
|
}
|
|
2010
|
+
keepReceivedJsonLd(decoded, v, options);
|
|
1266
2011
|
${variable}.push(decoded);
|
|
1267
2012
|
`;
|
|
1268
2013
|
yield `
|
|
@@ -1271,6 +2016,16 @@ async function* generateDecoder(typeUri, types, moduleVarNames) {
|
|
|
1271
2016
|
`;
|
|
1272
2017
|
}
|
|
1273
2018
|
yield `
|
|
2019
|
+
if (
|
|
2020
|
+
!("_retainsRawProperties" in options) ||
|
|
2021
|
+
options._retainsRawProperties !== false
|
|
2022
|
+
) {
|
|
2023
|
+
const retained = retainRawProperties(
|
|
2024
|
+
values,
|
|
2025
|
+
${type.name}.#knownRawPropertyIris,
|
|
2026
|
+
);
|
|
2027
|
+
if (retained != null) retainedRawProperties.set(instance, retained);
|
|
2028
|
+
}
|
|
1274
2029
|
instance._shouldCacheJsonLd = shouldCacheJsonLd;
|
|
1275
2030
|
if (
|
|
1276
2031
|
shouldCacheJsonLd &&
|
|
@@ -1484,6 +2239,10 @@ async function* generateCloner(typeUri, types) {
|
|
|
1484
2239
|
* See the [vocabulary manual](https://fedify.dev/manual/vocab#immutability)
|
|
1485
2240
|
* for details, including how cached JSON-LD affects serialization.
|
|
1486
2241
|
*
|
|
2242
|
+
* Unknown properties retained when this instance was decoded are shared
|
|
2243
|
+
* with the clone, so \`getRawPropertyValues()\` returns them for the clone
|
|
2244
|
+
* as well, even if the clone replaces other values.
|
|
2245
|
+
*
|
|
1487
2246
|
* A clone never inherits a signed JSON-LD representation retained by
|
|
1488
2247
|
* \`signObject()\`: the clone may differ from the document that the proof
|
|
1489
2248
|
* covers, so embedding the original secured JSON in a parent document
|
|
@@ -1523,6 +2282,7 @@ async function* generateCloner(typeUri, types) {
|
|
|
1523
2282
|
options
|
|
1524
2283
|
);
|
|
1525
2284
|
copyPortableProvenance(this, clone);
|
|
2285
|
+
copyRawProperties(this, clone);
|
|
1526
2286
|
`;
|
|
1527
2287
|
else yield `const clone = super.clone(values, options) as unknown as ${type.name};`;
|
|
1528
2288
|
for (const property of type.properties) {
|
|
@@ -1621,9 +2381,10 @@ async function* generateDeepCloner(typeUri, types) {
|
|
|
1621
2381
|
* Each copied object retains its own default loaders, tracer, verifier
|
|
1622
2382
|
* and base URL. Options override defaults only on the root instance.
|
|
1623
2383
|
* This method does not fetch or serialize objects. Cached JSON-LD and
|
|
1624
|
-
* retained signed representations are not copied
|
|
1625
|
-
*
|
|
1626
|
-
*
|
|
2384
|
+
* retained signed representations are not copied, and original formatting
|
|
2385
|
+
* is not preserved. Unknown properties retained when an object was decoded
|
|
2386
|
+
* are shared with its copy, so \`getRawPropertyValues()\` returns them for
|
|
2387
|
+
* the copy as well. Sign the copy again if it needs a valid proof.
|
|
1627
2388
|
*
|
|
1628
2389
|
* Trust and portable provenance follow clone() rules at every level.
|
|
1629
2390
|
* Historical referrers within the graph are copied without replacements;
|
|
@@ -1933,13 +2694,6 @@ async function* generateProperty(type, property, types, moduleVarNames) {
|
|
|
1933
2694
|
const override = emitOverride(type.uri, types, property);
|
|
1934
2695
|
const trustOwner = type.trustEmbeddedObjects === false ? "null" : "this.id";
|
|
1935
2696
|
const doc = `\n/** ${property.description.replaceAll("\n", "\n * ")}\n */\n`;
|
|
1936
|
-
const cachedPropertyBaseUrl = `(options as { baseUrl?: URL }).baseUrl ??
|
|
1937
|
-
this._baseUrl ??
|
|
1938
|
-
(this.id != null &&
|
|
1939
|
-
(this.id.protocol === "http:" ||
|
|
1940
|
-
this.id.protocol === "https:")
|
|
1941
|
-
? this.id
|
|
1942
|
-
: undefined)`;
|
|
1943
2697
|
if (areAllScalarTypes(property.range, types)) {
|
|
1944
2698
|
if (hasSingularAccessor(property)) {
|
|
1945
2699
|
yield doc;
|
|
@@ -2228,7 +2982,10 @@ async function* generateProperty(type, property, types, moduleVarNames) {
|
|
|
2228
2982
|
baseUrl,
|
|
2229
2983
|
});
|
|
2230
2984
|
if (_result instanceof Error) throw _result;
|
|
2231
|
-
if (_result !== undefined)
|
|
2985
|
+
if (_result !== undefined) {
|
|
2986
|
+
retainPreprocessedRawProperties(_result, _pp_obj);
|
|
2987
|
+
return _result as ${getTypeNames(property.range, types)};
|
|
2988
|
+
}
|
|
2232
2989
|
}
|
|
2233
2990
|
`;
|
|
2234
2991
|
}
|
|
@@ -2350,40 +3107,11 @@ async function* generateProperty(type, property, types, moduleVarNames) {
|
|
|
2350
3107
|
if (isUnverifiedPortableClaim(fetched)) return fetched;
|
|
2351
3108
|
this.${await getFieldName(property.uri)}[0] = fetched;
|
|
2352
3109
|
this.${await getFieldName(property.uri, "#_trust")}.add(0);
|
|
2353
|
-
this
|
|
3110
|
+
invalidateCachedJsonLd(this);
|
|
2354
3111
|
recordPortableReferrer(this, fetched, ${JSON.stringify(property.uri)});
|
|
2355
3112
|
return fetched;
|
|
2356
3113
|
}
|
|
2357
3114
|
`;
|
|
2358
|
-
if (property.compactName != null) yield `
|
|
2359
|
-
if (
|
|
2360
|
-
this._cachedJsonLd != null &&
|
|
2361
|
-
typeof this._cachedJsonLd === "object" &&
|
|
2362
|
-
"@context" in this._cachedJsonLd &&
|
|
2363
|
-
${JSON.stringify(property.compactName)} in this._cachedJsonLd
|
|
2364
|
-
) {
|
|
2365
|
-
const prop = this._cachedJsonLd[
|
|
2366
|
-
${JSON.stringify(property.compactName)}];
|
|
2367
|
-
const doc = Array.isArray(prop) ? prop[0] : prop;
|
|
2368
|
-
if (doc != null && typeof doc === "object" && "@context" in doc) {
|
|
2369
|
-
try {
|
|
2370
|
-
v = await this.#${property.singularName}_fromJsonLd(doc, {
|
|
2371
|
-
...options,
|
|
2372
|
-
// Keep the parent default for embedded objects.
|
|
2373
|
-
verifyPortableObject: this._verifyPortableObject,
|
|
2374
|
-
baseUrl: ${cachedPropertyBaseUrl},
|
|
2375
|
-
});
|
|
2376
|
-
} catch (error) {
|
|
2377
|
-
if (!options.suppressError) throw error;
|
|
2378
|
-
getLogger(["fedify", "vocab"]).debug(
|
|
2379
|
-
"Failed to parse embedded value of {property}: {error}",
|
|
2380
|
-
{ property: ${JSON.stringify(property.uri)}, error },
|
|
2381
|
-
);
|
|
2382
|
-
return null;
|
|
2383
|
-
}
|
|
2384
|
-
}
|
|
2385
|
-
}
|
|
2386
|
-
`;
|
|
2387
3115
|
yield `
|
|
2388
3116
|
if (v?.id != null &&
|
|
2389
3117
|
((${type.trustEmbeddedObjects === false ? "" : "this.id != null && "}!isTrustedIriOrigin(options, v.id, ${trustOwner})) ||
|
|
@@ -2508,41 +3236,12 @@ async function* generateProperty(type, property, types, moduleVarNames) {
|
|
|
2508
3236
|
}
|
|
2509
3237
|
vs[i] = fetched;
|
|
2510
3238
|
this.${await getFieldName(property.uri, "#_trust")}.add(i);
|
|
2511
|
-
this
|
|
3239
|
+
invalidateCachedJsonLd(this);
|
|
2512
3240
|
recordPortableReferrer(this, fetched, ${JSON.stringify(property.uri)});
|
|
2513
3241
|
yield fetched;
|
|
2514
3242
|
continue;
|
|
2515
3243
|
}
|
|
2516
3244
|
`;
|
|
2517
|
-
if (property.compactName != null) yield `
|
|
2518
|
-
if (
|
|
2519
|
-
this._cachedJsonLd != null &&
|
|
2520
|
-
typeof this._cachedJsonLd === "object" &&
|
|
2521
|
-
"@context" in this._cachedJsonLd &&
|
|
2522
|
-
${JSON.stringify(property.compactName)} in this._cachedJsonLd
|
|
2523
|
-
) {
|
|
2524
|
-
const prop = this._cachedJsonLd[
|
|
2525
|
-
${JSON.stringify(property.compactName)}];
|
|
2526
|
-
const obj = Array.isArray(prop) ? prop[i] : prop;
|
|
2527
|
-
if (obj != null && typeof obj === "object" && "@context" in obj) {
|
|
2528
|
-
try {
|
|
2529
|
-
v = await this.#${property.singularName}_fromJsonLd(obj, {
|
|
2530
|
-
...options,
|
|
2531
|
-
// Keep the parent default for embedded objects.
|
|
2532
|
-
verifyPortableObject: this._verifyPortableObject,
|
|
2533
|
-
baseUrl: ${cachedPropertyBaseUrl},
|
|
2534
|
-
});
|
|
2535
|
-
} catch (error) {
|
|
2536
|
-
if (!options.suppressError) throw error;
|
|
2537
|
-
getLogger(["fedify", "vocab"]).debug(
|
|
2538
|
-
"Failed to parse embedded value of {property} at index {index}: {error}",
|
|
2539
|
-
{ property: ${JSON.stringify(property.uri)}, index: i, error },
|
|
2540
|
-
);
|
|
2541
|
-
continue;
|
|
2542
|
-
}
|
|
2543
|
-
}
|
|
2544
|
-
}
|
|
2545
|
-
`;
|
|
2546
3245
|
yield `
|
|
2547
3246
|
if (v?.id != null &&
|
|
2548
3247
|
((${type.trustEmbeddedObjects === false ? "" : "this.id != null && "}!isTrustedIriOrigin(options, v.id, ${trustOwner})) ||
|
|
@@ -2815,6 +3514,17 @@ const PORTABLE_DEREFERENCE_IMPORTS = [
|
|
|
2815
3514
|
"rejectMalformedCompatibleReference",
|
|
2816
3515
|
"warnUnverifiableEmbeddedObject"
|
|
2817
3516
|
].join(",\n ");
|
|
3517
|
+
const RAW_PROPERTY_IMPORTS = [
|
|
3518
|
+
"copyJsonValue",
|
|
3519
|
+
"createRawPropertyEncodingOptions",
|
|
3520
|
+
"encodeNestedVocabularyValue",
|
|
3521
|
+
"expandRawPropertyValue",
|
|
3522
|
+
"RAW_PROPERTY_PROTOCOL",
|
|
3523
|
+
"type RawPropertyRequest",
|
|
3524
|
+
"readRawPropertyValues",
|
|
3525
|
+
"retainRawProperties",
|
|
3526
|
+
"type RetainedRawProperties"
|
|
3527
|
+
].join(",\n ");
|
|
2818
3528
|
const SIGNED_REPRESENTATION_IMPORTS = [
|
|
2819
3529
|
"enterSignedValueScope",
|
|
2820
3530
|
"resolveSignedValues",
|
|
@@ -2841,7 +3551,9 @@ const RUNTIME_IMPORTS = [
|
|
|
2841
3551
|
"parseIri",
|
|
2842
3552
|
"parseJsonLdId",
|
|
2843
3553
|
"type PortableObjectVerifier",
|
|
2844
|
-
"type
|
|
3554
|
+
"type RawPropertyValue",
|
|
3555
|
+
"type RemoteDocument",
|
|
3556
|
+
"type VocabularyObject"
|
|
2845
3557
|
].join(",\n ");
|
|
2846
3558
|
/**
|
|
2847
3559
|
* Sorts the given types topologically so that the base types come before the
|
|
@@ -2871,7 +3583,7 @@ async function* generateClass(typeUri, types, moduleVarNames) {
|
|
|
2871
3583
|
if (type.extends) {
|
|
2872
3584
|
const baseType = types[type.extends];
|
|
2873
3585
|
yield `export class ${type.name} extends ${baseType.name} {\n`;
|
|
2874
|
-
} else yield `export class ${type.name} {\n`;
|
|
3586
|
+
} else yield `export class ${type.name} implements VocabularyObject {\n`;
|
|
2875
3587
|
if (type.extends == null) yield `
|
|
2876
3588
|
readonly #documentLoader?: DocumentLoader;
|
|
2877
3589
|
readonly #contextLoader?: DocumentLoader;
|
|
@@ -2887,6 +3599,14 @@ async function* generateClass(typeUri, types, moduleVarNames) {
|
|
|
2887
3599
|
#shouldCacheJsonLd = true;
|
|
2888
3600
|
readonly id: URL | null;
|
|
2889
3601
|
|
|
3602
|
+
/**
|
|
3603
|
+
* Marks this object as a {@link VocabularyObject}. It is always \`true\`.
|
|
3604
|
+
* @since 2.5.0
|
|
3605
|
+
*/
|
|
3606
|
+
get "~fedify.vocab"(): true {
|
|
3607
|
+
return true;
|
|
3608
|
+
}
|
|
3609
|
+
|
|
2890
3610
|
protected get _documentLoader(): DocumentLoader | undefined {
|
|
2891
3611
|
return this.#documentLoader;
|
|
2892
3612
|
}
|
|
@@ -2955,6 +3675,7 @@ async function* generateClass(typeUri, types, moduleVarNames) {
|
|
|
2955
3675
|
for await (const code of generateCloner(typeUri, types)) yield code;
|
|
2956
3676
|
for await (const code of generateDeepCloner(typeUri, types)) yield code.replace(/[ \t]+$/gm, "");
|
|
2957
3677
|
for await (const code of generateDeepCloneDescriptor(typeUri, types)) yield code.replace(/[ \t]+$/gm, "");
|
|
3678
|
+
for await (const code of generateRawPropertyDescriptors(typeUri, types)) yield code.replace(/[ \t]+$/gm, "");
|
|
2958
3679
|
for await (const code of generateProperties(typeUri, types, moduleVarNames)) yield code;
|
|
2959
3680
|
for await (const code of generateEncoder(typeUri, types)) yield code;
|
|
2960
3681
|
for await (const code of generateDecoder(typeUri, types, moduleVarNames)) yield code;
|
|
@@ -3031,6 +3752,7 @@ async function* generateClasses(types) {
|
|
|
3031
3752
|
yield `import {\n ${RUNTIME_IMPORTS}\n} from "@fedify/vocab-runtime";\n`;
|
|
3032
3753
|
yield `import {\n ${INTERNAL_RUNTIME_IMPORTS}\n} from "@fedify/vocab-runtime/internal/jsonld-cache";\n`;
|
|
3033
3754
|
yield `import {\n ${PORTABLE_DEREFERENCE_IMPORTS}\n} from "@fedify/vocab-runtime/internal/portable-dereference";\n`;
|
|
3755
|
+
yield `import {\n ${RAW_PROPERTY_IMPORTS}\n} from "@fedify/vocab-runtime/internal/raw-property";\n`;
|
|
3034
3756
|
yield `import {\n ${SIGNED_REPRESENTATION_IMPORTS}\n} from "@fedify/vocab-runtime/internal/signed-representation";\n`;
|
|
3035
3757
|
yield `import {
|
|
3036
3758
|
isTemporalDuration,
|
|
@@ -3055,6 +3777,7 @@ function inspectIri(iri: URL): string {
|
|
|
3055
3777
|
`;
|
|
3056
3778
|
yield generatePropertyArrayHelpers();
|
|
3057
3779
|
yield generateDeepCloneHelpers();
|
|
3780
|
+
yield generateRawPropertyHelpers();
|
|
3058
3781
|
yield `
|
|
3059
3782
|
function isValidLanguageTag(language: string): boolean {
|
|
3060
3783
|
try {
|