1 // 📧🏷️ Étiquette ∷ model.js
2 // ====================================================================
4 // Copyright © 2023 Lady [@ Lady’s Computer].
6 // This Source Code Form is subject to the terms of the Mozilla Public
7 // License, v. 2.0. If a copy of the MPL was not distributed with this
8 // file, You can obtain one at <https://mozilla.org/MPL/2.0/>.
10 import { identity
} from "./deps.js";
11 import { Storage
} from "./memory.js";
12 import { taggingDiscoveryContext
} from "./names.js";
13 import schema
from "./schema.js";
18 * `Tag`s are not assigned identifiers and do not have side·effects on
19 * other tags in the `TagSystem` until they are persisted with
20 * `::persist`, at which point changes to their relationships are
23 * `Tag`s are also not kept up‐to‐date, but persisting an outdated
24 * `Tag` will *not* undo subsequent changes.
26 * ※ This class is not itself directly exposed, although bound
27 * versions of it are via `TagSystem::Tag`.
30 /** The `TagSystem` this `Tag` belongs to. */
33 /** The `Storage` managed by this `Tag`’s `TagSystem`. */
36 /** The schema in use for this `Tag`. */
40 * The 30‐bit W·R·M·G base32 identifier with leading checksum which
41 * has been assigned to this `Tag`.
43 * Will be `null` if this `Tag` has not been persisted. Otherwise,
44 * the format is `cxx-xxxx` (`c` = checksum; `x` = digit).
48 /** The kind of this `Tag`. */
52 * The data which was attached to this `Tag` the last time it was
53 * persisted or retrieved from storage.
55 * Diffing with this will reveal changes.
57 #persistedData
= null;
59 /** The current (modified) data associated with this `Tag`. */
63 * Adds the provided label(s) to this `Tag` as the provided
64 * predicate, then returns this `Tag`.
66 #addLabel(predicate
, ...labels
) {
67 const values
= this.#data
[predicate
];
68 for (const $ of labels
) {
69 // Iterate over each provided label and attempt to add it.
70 const literal
= langString($);
77 * Adds the provided tags to the list of tags that this `Tag` is
78 * related to by the provided predicate, then returns this `Tag`.
80 * Arguments may be string identifiers or objects with an
81 * `.identifier` property.
83 #addTag(predicate
, ...tags
) {
84 const storage
= this.#storage
;
85 const values
= this.#data
[predicate
];
86 for (const $ of tags
) {
87 // Iterate over each tag and attempt to state the predicate.
88 const identifier
= toIdentifier($);
89 if (identifier
== null) {
90 // ☡ The current tag has no identifier.
92 `Cannot state ${predicate} of Tag: Identifier must not be nullish.`,
94 } else if (values
.has(identifier
)) {
95 // Short‐circuit: The identifier has already been stated with
99 // The current tag has an identifier, but it hasn’t been stated
100 // with this predicate yet.
101 const tag
= storage
.get(identifier
);
103 // ☡ The current tag has not been persisted to this `Tag`’s
105 throw new RangeError(
106 `Cannot state ${predicate} of Tag: Identifier is not persisted: ${identifier}.`,
108 } else if (!this.#isTagInStorage(tag
)) {
109 // ☡ The current tag is not a tag in the correct tag system.
111 `Cannot state ${predicate} of Tag: Tags must be from the same Tag System, but got: ${identifier}.`,
114 !isObjectPredicateOK(
121 // ☡ This tag and the current tag form an invalid pair for
124 `Cannot state ${predicate} of Tag: Not valid for domain and range: ${this.#kind}, ${tag.#kind}.`,
127 // The current tag is a tag in the correct tag system; add
129 values
.add(identifier
);
137 * Removes the provided string label(s) from this `Tag` as the
138 * provided predicate, then returns this `Tag`.
140 #deleteLabel(predicate
, ...labels
) {
141 const values
= this.#data
[predicate
];
142 for (const $ of labels
) {
143 // Iterate over each provided label and attempt to remove it.
144 const literal
= langString($);
145 values
.delete(literal
);
151 * Removes the provided tags from the list of tags that this `Tag` is
152 * related to by the provided predicate, then returns this `Tag`.
154 * Arguments may be string identifiers or objects with an
155 * `.identifier` property.
157 #deleteTag(predicate
, ...tags
) {
158 const values
= this.#data
[predicate
];
159 for (const $ of tags
) {
160 // Iterate over the provided tags and delete them.
161 values
.delete(toIdentifier($));
167 * Returns whether or not the provided value is a tag which shares a
168 * storage with this tag.
170 * Sharing a storage also implies sharing a `TagSystem`.
174 // Try to compare the provided value’s internal store with
175 // the provided storage.
176 return $.#storage
== this.#storage
;
178 // The provided value was not a `Tag`.
184 * Yields the labels of this `Tag` according to the provided
187 *#yieldLabels(predicate
) {
188 yield* this.#data
[predicate
];
192 * Yields the tags that this `Tag` is related to by the provided
195 *#yieldTags(predicate
) {
196 const storage
= this.#storage
;
197 for (const identifier
of this.#data
[predicate
]) {
198 // Iterate over the tags in this predicate and yield them if
200 const tag
= storage
.get(identifier
);
202 !this.#isTagInStorage(tag
) || !isObjectPredicateOK(
209 // The tag no longer appears in storage or is not compatible;
210 // perhaps it was deleted.
213 // The tag exists and is constructable from storage.
220 * Yields the tags that this `Tag` is related to by the provided
221 * predicate, figured transitively.
223 *#yieldTransitiveTags(transitivePredicate
, basePredicate
) {
224 const storage
= this.#storage
;
225 const encountered
= new Set();
226 let pending
= new Set(this.#data
[basePredicate
]);
227 while (pending
.size
> 0) {
228 // Loop until all tags of the predicate have been encountered.
229 const processing
= pending
;
231 for (const identifier
of processing
) {
232 // Iterate over the tags and yield them if possible.
233 if (!encountered
.has(identifier
)) {
234 // The tag has not been encountered before.
235 encountered
.add(identifier
);
236 const tag
= storage
.get(identifier
);
238 !this.#isTagInStorage(tag
) || !isObjectPredicateOK(
245 // The tag no longer appears in storage or is not
246 // compatible; perhaps it was deleted.
249 // The tag exists and is constructable from storage.
251 for (const transitive
of tag
.#data
[basePredicate
]) {
252 // Iterate over the nested tags of the current tag and
253 // add them to pending as needed.
254 if (!encountered
.has(transitive
)) {
255 // The nested tag has not been encountered yet.
256 pending
.add(transitive
);
258 // The nested tag has already been encountered.
264 // The tag has already been encountered.
272 * Constructs a new `Tag` of the provided kind and with the provided
275 * ※ The first two arguments of this constructor are bound when
276 * generating the value of `TagSystem::Tag`. It isn’t possible to
277 * access this constructor in its unbound form from outside this
280 * ☡ This constructor throws if the provided kind is not supported.
282 constructor(system
, storage
, schema
, kind
= "Tag", prefLabel
= "") {
283 this.#system
= system
;
284 this.#storage
= storage
;
285 this.#schema
= schema
;
286 const kindString
= `${kind}`;
287 if (!(kindString
in schema
.classes
)) {
288 // The provided kind is not supported.
289 throw new RangeError(
290 `Cannot construct Tag: Unrecognized kind: ${kind}.`,
293 // The provided kind is one of the recognized tag kinds.
294 this.#kind
= kindString
;
295 this.#data
.prefLabel
= prefLabel
;
300 * Returns a new `Tag` constructor for the provided system, storage,
301 * schema, created with an appropriate prototype for the properties
304 * ※ This function is not exposed.
306 static For(system
, storage
, schema
) {
309 transitiveProperties
,
312 const constructor = function (...$s
) {
313 return Reflect
.construct(
315 [system
, storage
, schema
, ...$s
],
319 Object
.defineProperties(constructor, {
320 name
: { value
: "TagSystem::Tag" },
324 value
: Object
.create(
326 Object
.fromEntries(Array
.from(
328 for (const key
in objectProperties
) {
329 // Iterate over each object property and yield any
330 // necessary method definitions.
334 } = objectProperties
[key
];
335 if (key
in transitiveProperties
) {
336 // The current key indicates a transitive property.
338 // Transitive property methods are added by their
339 // nontransitive subproperties.
342 // The current key does not indicate a transitive
344 yield [`${key}Tags`, function* () {
345 yield* this.#yieldTags(key
);
347 if (inverseOf
== null) {
348 // The current key does not indicate an inverse
349 // property, so add and delete methods are also
351 const cased
= key
[0].toUpperCase() +
353 yield [`add${cased}Tag`, function (...tags
) {
354 return this.#addTag(key
, ...tags
);
356 yield [`delete${cased}Tag`, function (...tags
) {
357 return this.#deleteTag(key
, ...tags
);
360 // The current key indicates an inverse property,
361 // so no add and delete methods are necessary.
365 subPropertyOf
!= null &&
366 subPropertyOf
in transitiveProperties
368 // The current key indicates a subproperty of a
369 // transitive property; its method is also added.
370 yield [`${subPropertyOf}Tags`, function* () {
371 yield* this.#yieldTransitiveTags(
377 // The current key does not indicate a subproperty
378 // of a transitive property.
383 for (const key
in dataProperties
) {
384 // Iterate over each data property and yield any
385 // necessary method definitions.
386 if (key
!= "prefLabel") {
387 // The current key is not `"prefLabel"`.
388 const cased
= key
[0].toUpperCase() +
390 yield [`${key}s`, function* () {
391 yield* this.#yieldLabels(key
);
393 yield [`add${cased}`, function (...labels
) {
394 return this.#addLabel(key
, ...labels
);
396 yield [`delete${cased}`, function (...labels
) {
397 return this.#deleteLabel(key
, ...labels
);
400 // The current key is `"prefLabel"`. This is a
401 // special case which is not handled by the schema.
406 ([key
, value
]) => [key
, {
409 value
: Object
.defineProperty(value
, "name", {
419 return new TagConstructor(constructor, system
, storage
, schema
);
423 * Assigns the provided data and identifier to the provided tag.
425 * ☡ This function throws if the provided tag is not a `Tag`.
427 * ※ This function is not exposed.
429 static assignData(tag
, data
, identifier
) {
430 tag
.#identifier
= `${identifier}`;
431 tag
.#persistedData
= tagData(data
);
432 tag
.#data
= tagData(data
);
437 * Returns the `TagSystem` that the provided value belongs to.
439 * ※ This function can be used to check if the provided value has
440 * private tag features.
442 * ※ This function is not exposed.
444 static getSystem($) {
445 return !(#system
in Object($)) ? null : $.#system
;
449 // Overwrite the default `::constructor` method to instead give the
450 // actual (bound) constructor which was used to generate a given
452 Object
.defineProperties(this.prototype, {
457 // All `Tag`s are constructed via the `.Tag` constructor
458 // available in their `TagSystem`; return it.
459 return this.#system
.Tag
;
466 /** Returns the authority (domain) name for this `Tag`. */
467 get authorityName() {
468 return this.#system
.authorityName
;
471 /** Returns the identifier of this `Tag`. */
473 return this.#identifier
;
476 /** Returns the I·R·I for this `Tag`. */
478 const { identifier
, iriSpace
} = this;
479 return identifier
== null ? null : `${iriSpace}${identifier}`;
482 /** Returns the I·R·I space for this `Tag`. */
484 return this.#system
.iriSpace
;
487 /** Returns the kind of this `Tag`. */
493 * Persist this `Tag` to storage and return an ActivityStreams
494 * serialization of a Tag Activity representing any changes, or
495 * `null` if no changes were made.
497 * If the second argument is `true`, the `Tag` will be persisted but
498 * no serialization will be made. This is somewhat more efficient.
500 * ※ Persistence can imply side‐effects on other objects, which are
501 * not noted explicitly in the activity. For example, marking a tag
502 * as broader than another causes the other tag to reciprocally be
503 * marked as narrower.
505 * ※ Inverse object properties will never appear in the predicates
506 * of generated activities.
508 persist(silent
= false) {
509 const system
= this.#system
;
510 const storage
= this.#storage
;
513 transitiveProperties
,
516 const persistedData
= this.#persistedData
;
517 const data
= this.#data
;
519 for (const [key
, value
] of Object
.entries(data
)) {
520 // Iterate over each entry of the tag data and create a diff
521 // with the last persisted information.
523 objectProperties
[key
]?.inverseOf
!= null ||
524 silent
&& key
in dataProperties
526 // The current property is one which is skipped in diffs.
528 // In a silent persist, this includes any literal terms.
531 // The current property should be diffed.
532 const persisted
= persistedData
?.[key
] ?? null;
533 if (persisted
== null) {
534 // There is no persisted data for the current property yet.
537 new: value
instanceof Set
541 } else if (value
instanceof Set
) {
542 // The current property is set‐valued.
543 const oldValues
= new Set(persisted
);
544 const newValues
= new Set(value
);
545 for (const existing
of persisted
) {
546 // Iterate over each persisted property and either remove
547 // it from the list of new values or add it to the list of
549 if (value
.has(existing
)) {
550 // The value is in both the old and new version of the
552 oldValues
.delete(existing
);
553 newValues
.delete(existing
);
555 // The value is not shared.
559 diffs
[key
] = { old
: oldValues
, new: newValues
};
561 `${value}` != `${persisted}` ||
562 value
.language
!= persisted
.language
564 // The current property is (optionally language‐tagged)
565 // string‐valued and the value changed.
567 old
: new Set([persisted
]),
568 new: new Set([value
]),
571 // The current property did not change.
572 diffs
[key
] = { old
: new Set(), new: new Set() };
576 const identifier
= this.#identifier
;
577 if (identifier
!= null) {
578 // This `Tag` has already been persisted; use its existing
579 // identifier and persist.
580 storage
.set(identifier
, this);
582 // This `Tag` has not been persisted yet; save the new
583 // identifier after persisting.
584 this.#identifier
= storage
.add(this);
586 const persistedIdentifier
= this.#identifier
;
587 this.#persistedData
= tagData(data
); // cloning here is necessary
588 for (const inverse
in objectProperties
) {
589 // Iterate over each non‐transitive inverse property and update
590 // it based on its inverse on the corresponding tags if possible.
591 const term
= objectProperties
[inverse
].inverseOf
;
592 if (term
== null || term
in transitiveProperties
) {
593 // The current property is not the inverse of an non‐transitive
597 // The current property is the inverse of a non‐transitive
599 for (const referencedIdentifier
of diffs
[term
].old
) {
600 // Iterate over the removed tags and remove this `Tag` from
601 // their inverse property.
602 const referenced
= storage
.get(referencedIdentifier
);
604 // Try removing this `Tag`.
605 referenced
.#data
[inverse
].delete(persistedIdentifier
);
606 storage
.set(referencedIdentifier
, referenced
);
608 // Removal failed, possibly because the other tag was
613 for (const referencedIdentifier
of diffs
[term
].new) {
614 const referenced
= storage
.get(referencedIdentifier
);
616 // Try adding this `Tag`.
617 referenced
.#data
[inverse
].add(persistedIdentifier
);
618 storage
.set(referencedIdentifier
, referenced
);
620 // Adding failed, possibly because the other tag was deleted.
627 // This is a silent persist.
630 // This is not a silent persist; an activity needs to be
631 // generated if a change was made.
633 "@context": taggingDiscoveryContext
,
636 identifier
== null ? "Create" : "Update",
638 context
: `${system.iri}`,
639 object
: `${this.iri}`,
640 endTime
: new Date().toISOString(),
646 const { unstates
, states
} = statements
;
647 if (identifier
== null) {
648 // This is a Create activity.
649 states
.push({ predicate
: "a", object
: `${this.kind}` });
651 // This is an Update activity.
658 }] of Object
.entries(diffs
)
660 // Iterate over the diffs of each term and state/unstate
662 for (const oldValue
of oldValues
) {
663 // Iterate over removals and unstate them.
664 if (term
in dataProperties
) {
665 // This is a literal term; push it.
668 object
: { ...oldValue
},
671 // This is a named term; attempt to get its I·R·I and
674 // Attempt to resolve the value and push the change.
675 const tag
= storage
.get(oldValue
);
676 if (!this.#isTagInStorage(tag
)) {
677 // The value did not resolve to a tag in storage.
680 // The value resolved; push its I·R·I.
687 // Value resolution failed for some reason; perhaps the
693 for (const newValue
of newValues
) {
694 // Iterate over additions and state them.
695 if (term
in dataProperties
) {
696 // This is a literal term; push it.
699 object
: { ...newValue
},
702 // This is a named term; attempt to get its I·R·I and
705 // Attempt to resolve the value and push the change.
706 const tag
= storage
.get(newValue
);
707 if (!this.#isTagInStorage(tag
)) {
708 // The value did not resolve to a tag in storage.
711 // The value resolved; push its I·R·I.
718 // Value resolution failed for some reason; perhaps the
725 if (unstates
.length
== 0) {
726 // Nothing was unstated.
727 delete statements
.unstates
;
729 // Things were stated.
732 if (states
.length
== 0) {
733 // Nothing was stated.
734 delete statements
.states
;
736 // Things were stated.
743 !Object
.hasOwn(activity
, "states") &&
744 !Object
.hasOwn(activity
, "unstates")
746 // No meaningful changes were actually persisted.
749 // There were meaningful changes persisted regarding this `Tag`.
755 /** Returns the preferred label for this `Tag`. */
757 return this.#data
.prefLabel
;
760 /** Sets the preferred label of this `Tag` to the provided label. */
762 this.#data
.prefLabel
= langString($);
765 /** Returns the Tag U·R·I for this `Tag`. */
767 const { identifier
} = this;
768 return identifier
== null
770 : `tag:${this.taggingEntity}:${identifier}`;
773 /** Returns the tagging entity (domain and date) for this `Tag`. */
774 get taggingEntity() {
775 return this.#system
.taggingEntity
;
778 /** Returns the string form of the preferred label of this `Tag`. */
780 return `${this.#data.prefLabel}`;
784 * Returns a new object whose enumerable own properties contain the
785 * data from this object needed for storage.
787 * ※ This method is not really intended for public usage.
789 [Storage
.toObject
]() {
790 const data
= this.#data
;
791 return Object
.assign(Object
.create(null), {
800 * A `Tag` constructor function.
802 * This class extends the identity function, meaning that the object
803 * provided as the constructor is used verbatim (with new private
806 * ※ The instance methods of this class are provided as static
807 * methods on the superclass which all `Tag` constructors inherit
810 * ※ This class is not exposed.
815 * The exposed constructor function from which all `Tag` constructors
818 * ☡ This constructor always throws.
822 const tagConstructorBehaviours
= Object
.create(null);
824 TagConstructor
: class extends identity
{
826 * The `TagSystem` used for `Tag`s constructed by this
831 /** The `Storage` managed by this constructor’s `TagSystem`. */
834 /** The schema in use for this constructor. */
838 * Constructs a new `Tag` constructor by adding the appropriate
839 * private fields to the provided constructor, setting its
840 * prototype, and then returning it.
842 * ※ This constructor does not modify the `name` or `prototype`
843 * properties of the provided constructor.
845 * ※ See `Tag.For`, where this constructor is used.
847 constructor(constructor, system
, storage
, schema
) {
849 Object
.setPrototypeOf(this, TagSuper
);
850 this.#system
= system
;
851 this.#storage
= storage
;
852 this.#schema
= schema
;
856 // Define the superclass constructor which all `Tag`
857 // constructors will inherit from.
858 const superclass
= tagConstructorBehaviours
.TagSuper
=
860 throw new TypeError("Tags must belong to a System.");
862 const { prototype: methods
} = this;
863 delete methods
.constructor;
864 Object
.defineProperty(superclass
, "prototype", {
867 value
: Tag
.prototype,
870 Object
.defineProperties(
872 Object
.getOwnPropertyDescriptors(methods
),
877 * Yields the tags in the `TagSystem` associated with this
881 const system
= this.#system
;
882 const storage
= this.#storage
;
883 for (const instance
of storage
.values()) {
884 // Iterate over the entries and yield the ones which are
885 // `Tag`s in this `TagSystem`.
886 if (Tag
.getSystem(instance
) == system
) {
887 // The current instance is a `Tag` in this `TagSystem`.
890 // The current instance is not a `Tag` in this
898 * Returns a new `Tag` resolved from the provided I·R·I.
900 * ☡ This function throws if the I·R·I is not in the `.iriSpace`
901 * of the `TagSystem` associated with this constructor.
903 * ※ If the I·R·I is not recognized, this function returns
907 const system
= this.#system
;
908 const storage
= this.#storage
;
909 const name
= `${iri}`;
910 const prefix
= `${system.iriSpace}`;
911 if (!name
.startsWith(prefix
)) {
912 // The I·R·I does not begin with the expected prefix.
913 throw new RangeError(
914 `I·R·I did not begin with the expected prefix: ${iri}`,
917 // The I·R·I begins with the expected prefix.
918 const identifier
= name
.substring(prefix
.length
);
920 // Attempt to resolve the identifier.
921 const instance
= storage
.get(identifier
);
922 return Tag
.getSystem(instance
) == system
? instance
: null;
924 // Do not throw for bad identifiers.
931 * Returns a new `Tag` resolved from the provided identifier.
933 * ☡ This function throws if the identifier is invalid.
935 * ※ If the identifier is valid but not recognized, this
936 * function returns `null`.
938 fromIdentifier(identifier
) {
939 const system
= this.#system
;
940 const storage
= this.#storage
;
941 const instance
= storage
.get(identifier
);
942 return Tag
.getSystem(instance
) == system
? instance
: null;
946 * Returns a new `Tag` resolved from the provided Tag U·R·I.
948 * ☡ This function throws if the provided Tag U·R·I does not
949 * match the tagging entity of this constructor’s `TagSystem`.
951 * ※ If the specific component of the Tag U·R·I is not
952 * recognized, this function returns `null`.
955 const system
= this.#system
;
956 const storage
= this.#storage
;
957 const tagName
= `${tagURI}`;
958 const tagPrefix
= `tag:${system.taggingEntity}:`;
959 if (!tagName
.startsWith(tagPrefix
)) {
960 // The Tag U·R·I does not begin with the expected prefix.
961 throw new RangeError(
962 `Tag U·R·I did not begin with the expected prefix: ${tagURI}`,
965 // The I·R·I begins with the expected prefix.
966 const identifier
= tagName
.substring(tagPrefix
.length
);
968 // Attempt to resolve the identifier.
969 const instance
= storage
.get(identifier
);
970 return Tag
.getSystem(instance
) == system
? instance
: null;
972 // Do not throw for bad identifiers.
979 * Yields the tag identifiers in the `TagSystem` associated with
983 const system
= this.#system
;
984 const storage
= this.#storage
;
985 for (const [identifier
, instance
] of storage
.entries()) {
986 // Iterate over the entries and yield the ones which are
987 // `Tag`s in this `TagSystem`.
988 if (Tag
.getSystem(instance
) == system
) {
989 // The current instance is a `Tag` in this `TagSystem`.
992 // The current instance is not a `Tag` in this `TagSystem`.
999 * Returns a new `Tag` constructed from the provided data and
1000 * with the provided identifier.
1002 * ※ This function is not really intended for public usage.
1004 [Storage
.toInstance
](data
, identifier
) {
1005 const tag
= new this(data
.kind
);
1006 return Tag
.assignData(tag
, data
, identifier
);
1009 TagSuper
: tagConstructorBehaviours
.TagSuper
,
1015 * Returns whether the provided schema, subject class, object
1016 * property, and object class are consistent.
1018 * This is hardly a full reasoner; it is tuned to the abilites and
1019 * needs of this module.
1021 isObjectPredicateOK
,
1023 const cachedClassAndSuperclasses
= new WeakMap();
1024 const cachedClassRestrictions
= new WeakMap();
1025 const cachedPredicateRestrictions
= new WeakMap();
1027 const classAndSuperclasses
= function* (
1030 touched
= new Set(),
1032 if (baseClass
== "Thing" || touched
.has(baseClass
)) {
1036 touched
.add(baseClass
);
1037 const subClassOf
= classes
[baseClass
]?.subClassOf
?? "Thing";
1039 const superclass
of (
1040 typeof subClassOf
== "string"
1042 : Array
.from(subClassOf
)
1043 ).filter(($) => typeof $ == "string")
1045 yield* classAndSuperclasses(classes
, superclass
, touched
);
1050 const getClassAndSuperclasses
= (schema
, baseClass
) => {
1051 const schemaCache
= cachedClassAndSuperclasses
.get(schema
);
1052 const cached
= schemaCache
?.[baseClass
];
1053 if (cached
!= null) {
1056 const { classes
} = schema
;
1057 const result
= [...classAndSuperclasses(classes
, baseClass
)];
1059 schemaCache
[baseClass
] = result
;
1061 cachedClassRestrictions
.set(
1063 Object
.assign(Object
.create(null), { [baseClass
]: result
}),
1070 const getClassRestrictions
= (schema
, domain
) => {
1071 const schemaCache
= cachedClassRestrictions
.get(schema
);
1072 const cached
= schemaCache
?.[domain
];
1073 if (cached
!= null) {
1076 const { classes
} = schema
;
1077 const restrictions
= Object
.create(null);
1078 const subClassOf
= classes
[domain
]?.subClassOf
?? "Thing";
1080 const superclass
of (
1081 typeof subClassOf
== "string"
1083 : Array
.from(subClassOf
)
1084 ).filter(($) => Object($) === $)
1086 const { onProperty
, allValuesFrom
} = superclass
;
1087 restrictions
[onProperty
] = processSpace(allValuesFrom
);
1090 schemaCache
[domain
] = restrictions
;
1092 cachedClassRestrictions
.set(
1094 Object
.assign(Object
.create(null), {
1095 [domain
]: restrictions
,
1099 return restrictions
;
1103 const getPredicateRestrictions
= (schema
, predicate
) => {
1104 const schemaCache
= cachedPredicateRestrictions
.get(schema
);
1105 const cached
= schemaCache
?.[predicate
];
1106 if (cached
!= null) {
1109 const { objectProperties
} = schema
;
1110 const restrictions
= [
1111 ...predicateRestrictions(objectProperties
, predicate
),
1113 (result
, { domainIntersection
, rangeIntersection
}) => {
1114 result
.domainIntersection
.push(...domainIntersection
);
1115 result
.rangeIntersection
.push(...rangeIntersection
);
1118 Object
.assign(Object
.create(null), {
1119 domainIntersection
: [],
1120 rangeIntersection
: [],
1124 schemaCache
[predicate
] = restrictions
;
1126 cachedPredicateRestrictions
.set(
1128 Object
.assign(Object
.create(null), {
1129 [predicate
]: restrictions
,
1133 return restrictions
;
1137 const processSpace
= (space
) =>
1138 Object(space
) === space
1143 Object(subspace
) === subspace
1144 ? Array
.from(subspace
.unionOf
)
1147 : [Array
.from(space
.unionOf
)]
1150 const predicateRestrictions
= function* (
1153 touched
= new Set(),
1155 if (predicate
== "Property" || touched
.has(predicate
)) {
1158 const { domain
, range
, subPropertyOf
} =
1159 objectProperties
[predicate
];
1160 yield Object
.assign(Object
.create(null), {
1161 domainIntersection
: processSpace(domain
?? "Thing"),
1162 rangeIntersection
: processSpace(range
?? "Thing"),
1164 touched
.add(predicate
);
1166 const superproperty
of (
1167 subPropertyOf
== null
1169 : typeof subPropertyOf
== "string"
1171 : Array
.from(subPropertyOf
)
1174 yield* predicateRestrictions(
1184 isObjectPredicateOK
: (
1190 const { objectProperties
} = schema
;
1191 const predicateDefinition
= objectProperties
[predicate
];
1192 const isInverse
= "inverseOf" in predicateDefinition
;
1193 const usedPredicate
= isInverse
1194 ? predicateDefinition
.inverseOf
1196 const domain
= isInverse
? objectClass
: subjectClass
;
1197 const domains
= new Set(getClassAndSuperclasses(schema
, domain
));
1198 const ranges
= new Set(getClassAndSuperclasses(
1200 isInverse
? subjectClass
: objectClass
,
1202 const predicateRestrictions
= getPredicateRestrictions(
1206 const { domainIntersection
} = predicateRestrictions
;
1207 const rangeIntersection
= [
1208 ...predicateRestrictions
.rangeIntersection
,
1210 for (const domain
of domains
) {
1211 const classRestrictionOnPredicate
=
1212 getClassRestrictions(schema
, domain
)[usedPredicate
];
1213 if (classRestrictionOnPredicate
!= null) {
1214 yield* classRestrictionOnPredicate
;
1221 return domainIntersection
.every((domainUnion
) =>
1222 domainUnion
.some((domain
) =>
1223 domain
== "Thing" || domains
.has(domain
)
1226 rangeIntersection
.every((rangeUnion
) =>
1227 rangeUnion
.some((range
) =>
1228 range
== "Thing" || ranges
.has(range
)
1237 * Returns the provided value converted into a `String` object with
1238 * `.["@value"]` and `.["@language"]` properties.
1240 * The same object will be returned for every call with an equivalent
1243 * TODO: Ideally this would be extracted more fully into an R·D·F
1246 * ※ This function is not exposed.
1251 * Returns the language string object corresponding to the provided
1252 * value and language.
1254 const getLangString
= (value
, language
= "") => {
1255 const valueMap
= languageMap
[language
] ??= Object
.create(null);
1256 const literal
= valueMap
[value
]?.deref();
1257 if (literal
!= null) {
1258 // There is already an object corresponding to the provided value
1262 // No object already exists corresponding to the provided value
1263 // and language; create one.
1264 const result
= Object
.preventExtensions(
1265 Object
.create(String
.prototype, {
1271 enumerable
: !!language
,
1272 value
: language
|| null,
1274 language
: { enumerable
: false, get: getLanguage
},
1275 toString
: { enumerable
: false, value
: toString
},
1276 valueOf
: { enumerable
: false, value
: valueOf
},
1279 const ref
= new WeakRef(result
);
1280 langStringRegistry
.register(result
, { ref
, language
, value
});
1281 valueMap
[value
] = ref
;
1286 /** Returns the `.["@language"]` of this object. */
1287 const getLanguage
= Object
.defineProperty(
1289 return this["@language"] || null;
1292 { value
: "get language" },
1296 * A `FinalizationRegistry` for language string objects.
1298 * This simply cleans up the corresponding `WeakRef` in the language
1301 const langStringRegistry
= new FinalizationRegistry(
1302 ({ ref
, language
, value
}) => {
1303 const valueMap
= languageMap
[language
];
1304 if (valueMap
?.[value
] === ref
) {
1305 delete valueMap
[value
];
1313 * An object whose own values are an object mapping values to
1314 * language string objects for the language specified by the key.
1316 const languageMap
= Object
.create(null);
1318 /** Returns the `.["@value"]` of this object. */
1319 const toString = function () {
1320 return this["@value"];
1324 * Returns this object if it has a `.["@language"]`; otherwise, its
1327 const valueOf = function () {
1328 return this["@language"] ? this : this["@value"];
1338 `${$["@language"] ?? ""}`,
1340 : getLangString(`${$["@value"]}`)
1342 ? getLangString(`${$}`, `${$.language ?? ""}`)
1343 : getLangString(`${$}`)
1344 : getLangString(`${$ ?? ""}`),
1349 * Returns a normalized tag data object derived from the provided
1352 * ※ The properties of this function need to match the term names used
1353 * in the ActivityStreams serialization.
1355 * ※ This function is not exposed.
1357 const tagData
= ($) => {
1358 const data
= Object($);
1360 // prefLabel intentionally not set here
1370 let prefLabel
= langString(data
.prefLabel
);
1371 return Object
.preventExtensions(Object
.create(null, {
1374 get: () => prefLabel
,
1376 prefLabel
= langString($);
1383 ? Array
.from(altLabel
, langString
)
1391 ? Array
.from(hiddenLabel
, langString
)
1399 ? Array
.from(broader
, toIdentifier
)
1407 ? Array
.from(narrower
, toIdentifier
)
1415 ? Array
.from(inCanon
, toIdentifier
)
1423 ? Array
.from(hasInCanon
, toIdentifier
)
1431 ? Array
.from(involves
, toIdentifier
)
1439 ? Array
.from(involvedIn
, toIdentifier
)
1447 * Returns an identifier corresponding to the provided object.
1449 * This is either the value of its `.identifier` or its string value.
1451 * ※ This function is not exposed.
1453 const toIdentifier
= ($) =>
1456 : Object($) === $ && "identifier" in $
1461 * A tag system, with storage.
1463 * The `::Tag` constructor available on any `TagSystem` instance can be
1464 * used to create new `Tag`s within the system.
1466 export class TagSystem
{
1467 /** The cached bound `Tag` constructor for this `TagSystem`. */
1470 /** The domain of this `TagSystem`. */
1473 /** The date of this `TagSystem`. */
1476 /** The identifier of this `TagSystem`. */
1479 /** The internal `Storage` of this `TagSystem`. */
1480 #storage
= new Storage();
1483 * Constructs a new `TagSystem` with the provided domain and date.
1485 * Only actual, lowercased domain names are allowed for the domain,
1486 * and the date must be “full” (include month and day components).
1487 * This is for alignment with general best practices for Tag URI’s.
1489 * ☡ This constructor throws if provided with an invalid date.
1491 constructor(domain
, date
, identifier
= "") {
1492 const domainString
= `${domain}`;
1493 const dateString
= `${date}`;
1494 this.#identifier
= `${identifier}`;
1496 // If the identifier is a valid storage I·D, reserve it.
1497 this.#storage
.delete(this.#identifier
);
1499 // The identifier is not a valid storage I·D, so no worries.
1503 !/^[a-z](?:[\da-z-]*[\da-z])?(?:\.[a-z](?:[\da-z-]*[\da-z])?)*$/u
1506 // ☡ The domain is invalid.
1507 throw new RangeError(`Invalid domain: ${domain}.`);
1509 !/^\d{4}-\d{2}-\d{2}$/u.test(dateString
) ||
1510 dateString
!= new Date(dateString
).toISOString().split("T")[0]
1512 // ☡ The date is invalid.
1513 throw new RangeError(`Invalid date: ${date}.`);
1515 // The domain and date are 🆗.
1516 this.#domain
= domainString
;
1517 this.#date
= dateString
;
1522 * Returns a bound constructor for constructing `Tags` in this
1526 if (this.#Tag
!= null) {
1527 // A bound constructor has already been generated; return it.
1530 // No bound constructor has been created yet.
1531 const storage
= this.#storage
;
1532 return this.#Tag
= Tag
.For(this, storage
, schema
);
1536 /** Returns the authority name (domain) for this `TagSystem`. */
1537 get authorityName() {
1538 return this.#domain
;
1541 /** Returns the date of this `TagSystem`, as a string. */
1547 * Yields the entities in this `TagSystem`.
1549 * ※ Entities can hypothetically be anything. If you specifically
1550 * want the `Tag`s, use `::Tag.all` instead.
1553 yield* this.#storage
.values();
1557 * Returns the identifier of this `TagSystem`.
1559 * ※ Often this is just the empty string.
1562 return this.#identifier
;
1565 /** Yields the identifiers in use in this `TagSystem`. */
1567 yield* this.#storage
.keys();
1570 /** Returns the I·R·I for this `TagSystem`. */
1572 return `${this.iriSpace}${this.identifier}`;
1576 * Returns the prefix used for I·R·I’s of `Tag`s in this `TagSystem`.
1579 return `https://${this.authorityName}/tag:${this.taggingEntity}:`;
1582 /** Returns the Tag U·R·I for this `TagSystem`. */
1584 return `tag:${this.taggingEntity}:${this.identifier}`;
1588 * Returns the tagging entity (domain and date) for this `TagSystem`.
1590 get taggingEntity() {
1591 return `${this.authorityName},${this.date}`;