@fedify/vocab-tools 2.5.0-dev.2758 → 2.5.0-dev.2766

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