]> Lady’s Gitweb - Etiquette/blob - model.js
d64f6c4218889f7cab3c60dbc215fec884fe6ead
[Etiquette] / model.js
1 // 📧🏷️ Étiquette ∷ model.js
2 // ====================================================================
3 //
4 // Copyright © 2023 Lady [@ Lady’s Computer].
5 //
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/>.
9
10 import { identity } from "./deps.js";
11 import { Storage } from "./memory.js";
12 import { taggingDiscoveryContext } from "./names.js";
13 import schema from "./schema.js";
14
15 /**
16 * A tag.
17 *
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
21 * applied.
22 *
23 * `Tag`s are also not kept up‐to‐date, but persisting an outdated
24 * `Tag` will *not* undo subsequent changes.
25 *
26 * ※ This class is not itself directly exposed, although bound
27 * versions of it are via `TagSystem::Tag`.
28 */
29 class Tag {
30 /** The `TagSystem` this `Tag` belongs to. */
31 #system;
32
33 /** The `Storage` managed by this `Tag`’s `TagSystem`. */
34 #storage;
35
36 /** The schema in use for this `Tag`. */
37 #schema;
38
39 /**
40 * The 30‐bit W·R·M·G base32 identifier with leading checksum which
41 * has been assigned to this `Tag`.
42 *
43 * Will be `null` if this `Tag` has not been persisted. Otherwise,
44 * the format is `cxx-xxxx` (`c` = checksum; `x` = digit).
45 */
46 #identifier = null;
47
48 /** The kind of this `Tag`. */
49 #kind = "Tag";
50
51 /**
52 * The data which was attached to this `Tag` the last time it was
53 * persisted or retrieved from storage.
54 *
55 * Diffing with this will reveal changes.
56 */
57 #persistedData = null;
58
59 /** The current (modified) data associated with this `Tag`. */
60 #data = tagData();
61
62 /**
63 * Adds the provided label(s) to this `Tag` as the provided
64 * predicate, then returns this `Tag`.
65 */
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($);
71 values.add(literal);
72 }
73 return this;
74 }
75
76 /**
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`.
79 *
80 * Arguments may be string identifiers or objects with an
81 * `.identifier` property.
82 */
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.
91 throw new TypeError(
92 `Cannot state ${predicate} of Tag: Identifier must not be nullish.`,
93 );
94 } else if (values.has(identifier)) {
95 // Short‐circuit: The identifier has already been stated with
96 // this predicate.
97 /* do nothing */
98 } else {
99 // The current tag has an identifier, but it hasn’t been stated
100 // with this predicate yet.
101 const tag = storage.get(identifier);
102 if (tag == null) {
103 // ☡ The current tag has not been persisted to this `Tag`’s
104 // storage.
105 throw new RangeError(
106 `Cannot state ${predicate} of Tag: Identifier is not persisted: ${identifier}.`,
107 );
108 } else if (!this.#isTagInStorage(tag)) {
109 // ☡ The current tag is not a tag in the correct tag system.
110 throw new TypeError(
111 `Cannot state ${predicate} of Tag: Tags must be from the same Tag System, but got: ${identifier}.`,
112 );
113 } else if (
114 !isObjectPredicateOK(
115 this.#schema,
116 this.#kind,
117 predicate,
118 tag.#kind,
119 )
120 ) {
121 // ☡ This tag and the current tag form an invalid pair for
122 // this predicate.
123 throw new TypeError(
124 `Cannot state ${predicate} of Tag: Not valid for domain and range: ${this.#kind}, ${tag.#kind}.`,
125 );
126 } else {
127 // The current tag is a tag in the correct tag system; add
128 // its identifier.
129 values.add(identifier);
130 }
131 }
132 }
133 return this;
134 }
135
136 /**
137 * Removes the provided string label(s) from this `Tag` as the
138 * provided predicate, then returns this `Tag`.
139 */
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);
146 }
147 return this;
148 }
149
150 /**
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`.
153 *
154 * Arguments may be string identifiers or objects with an
155 * `.identifier` property.
156 */
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($));
162 }
163 return this;
164 }
165
166 /**
167 * Returns whether or not the provided value is a tag which shares a
168 * storage with this tag.
169 *
170 * Sharing a storage also implies sharing a `TagSystem`.
171 */
172 #isTagInStorage($) {
173 try {
174 // Try to compare the provided value’s internal store with
175 // the provided storage.
176 return $.#storage == this.#storage;
177 } catch {
178 // The provided value was not a `Tag`.
179 return false;
180 }
181 }
182
183 /**
184 * Yields the labels of this `Tag` according to the provided
185 * predicate.
186 */
187 *#yieldLabels(predicate) {
188 yield* this.#data[predicate];
189 }
190
191 /**
192 * Yields the tags that this `Tag` is related to by the provided
193 * predicate.
194 */
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
199 // possible.
200 const tag = storage.get(identifier);
201 if (
202 !this.#isTagInStorage(tag) || !isObjectPredicateOK(
203 this.#schema,
204 this.#kind,
205 predicate,
206 tag.#kind,
207 )
208 ) {
209 // The tag no longer appears in storage or is not compatible;
210 // perhaps it was deleted.
211 /* do nothing */
212 } else {
213 // The tag exists and is constructable from storage.
214 yield tag;
215 }
216 }
217 }
218
219 /**
220 * Yields the tags that this `Tag` is related to by the provided
221 * predicate, figured transitively.
222 */
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;
230 pending = new Set();
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);
237 if (
238 !this.#isTagInStorage(tag) || !isObjectPredicateOK(
239 this.#schema,
240 this.#kind,
241 transitivePredicate,
242 tag.#kind,
243 )
244 ) {
245 // The tag no longer appears in storage or is not
246 // compatible; perhaps it was deleted.
247 /* do nothing */
248 } else {
249 // The tag exists and is constructable from storage.
250 yield tag;
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);
257 } else {
258 // The nested tag has already been encountered.
259 /* do nothing */
260 }
261 }
262 }
263 } else {
264 // The tag has already been encountered.
265 /* do nothing */
266 }
267 }
268 }
269 }
270
271 /**
272 * Constructs a new `Tag` of the provided kind and with the provided
273 * preferred label.
274 *
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
278 * module.
279 *
280 * ☡ This constructor throws if the provided kind is not supported.
281 */
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}.`,
291 );
292 } else {
293 // The provided kind is one of the recognized tag kinds.
294 this.#kind = kindString;
295 this.#data.prefLabel = prefLabel;
296 }
297 }
298
299 /**
300 * Returns a new `Tag` constructor for the provided system, storage,
301 * schema, created with an appropriate prototype for the properties
302 * so defined.
303 *
304 * ※ This function is not exposed.
305 */
306 static For(system, storage, schema) {
307 const {
308 objectProperties,
309 transitiveProperties,
310 dataProperties,
311 } = schema;
312 const constructor = function (...$s) {
313 return Reflect.construct(
314 Tag,
315 [system, storage, schema, ...$s],
316 new.target,
317 );
318 };
319 Object.defineProperties(constructor, {
320 name: { value: "TagSystem::Tag" },
321 prototype: {
322 configurable: false,
323 enumerable: false,
324 value: Object.create(
325 Tag.prototype,
326 Object.fromEntries(Array.from(
327 function* () {
328 for (const key in objectProperties) {
329 // Iterate over each object property and yield any
330 // necessary method definitions.
331 const {
332 inverseOf,
333 subPropertyOf,
334 } = objectProperties[key];
335 if (key in transitiveProperties) {
336 // The current key indicates a transitive property.
337 //
338 // Transitive property methods are added by their
339 // nontransitive subproperties.
340 /* do nothing */
341 } else {
342 // The current key does not indicate a transitive
343 // property.
344 yield [`${key}Tags`, function* () {
345 yield* this.#yieldTags(key);
346 }];
347 if (inverseOf == null) {
348 // The current key does not indicate an inverse
349 // property, so add and delete methods are also
350 // added.
351 const cased = key[0].toUpperCase() +
352 key.substring(1);
353 yield [`add${cased}Tag`, function (...tags) {
354 return this.#addTag(key, ...tags);
355 }];
356 yield [`delete${cased}Tag`, function (...tags) {
357 return this.#deleteTag(key, ...tags);
358 }];
359 } else {
360 // The current key indicates an inverse property,
361 // so no add and delete methods are necessary.
362 /* do nothing */
363 }
364 if (
365 subPropertyOf != null &&
366 subPropertyOf in transitiveProperties
367 ) {
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(
372 subPropertyOf,
373 key,
374 );
375 }];
376 } else {
377 // The current key does not indicate a subproperty
378 // of a transitive property.
379 /* do nothing */
380 }
381 }
382 }
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() +
389 key.substring(1);
390 yield [`${key}s`, function* () {
391 yield* this.#yieldLabels(key);
392 }];
393 yield [`add${cased}`, function (...labels) {
394 return this.#addLabel(key, ...labels);
395 }];
396 yield [`delete${cased}`, function (...labels) {
397 return this.#deleteLabel(key, ...labels);
398 }];
399 } else {
400 // The current key is `"prefLabel"`. This is a
401 // special case which is not handled by the schema.
402 /* do nothing */
403 }
404 }
405 }(),
406 ([key, value]) => [key, {
407 configurable: true,
408 enumerable: false,
409 value: Object.defineProperty(value, "name", {
410 value: key,
411 }),
412 writable: true,
413 }],
414 )),
415 ),
416 writable: false,
417 },
418 });
419 return new TagConstructor(constructor, system, storage, schema);
420 }
421
422 /**
423 * Assigns the provided data and identifier to the provided tag.
424 *
425 * ☡ This function throws if the provided tag is not a `Tag`.
426 *
427 * ※ This function is not exposed.
428 */
429 static assignData(tag, data, identifier) {
430 tag.#identifier = `${identifier}`;
431 tag.#persistedData = tagData(data);
432 tag.#data = tagData(data);
433 return tag;
434 }
435
436 /**
437 * Returns the `TagSystem` that the provided value belongs to.
438 *
439 * ※ This function can be used to check if the provided value has
440 * private tag features.
441 *
442 * ※ This function is not exposed.
443 */
444 static getSystem($) {
445 return !(#system in Object($)) ? null : $.#system;
446 }
447
448 static {
449 // Overwrite the default `::constructor` method to instead give the
450 // actual (bound) constructor which was used to generate a given
451 // `Tag`.
452 Object.defineProperties(this.prototype, {
453 constructor: {
454 configurable: true,
455 enumerable: false,
456 get() {
457 // All `Tag`s are constructed via the `.Tag` constructor
458 // available in their `TagSystem`; return it.
459 return this.#system.Tag;
460 },
461 set: undefined,
462 },
463 });
464 }
465
466 /** Returns the authority (domain) name for this `Tag`. */
467 get authorityName() {
468 return this.#system.authorityName;
469 }
470
471 /** Returns the identifier of this `Tag`. */
472 get identifier() {
473 return this.#identifier;
474 }
475
476 /** Returns the I·R·I for this `Tag`. */
477 get iri() {
478 const { identifier, iriSpace } = this;
479 return identifier == null ? null : `${iriSpace}${identifier}`;
480 }
481
482 /** Returns the I·R·I space for this `Tag`. */
483 get iriSpace() {
484 return this.#system.iriSpace;
485 }
486
487 /** Returns the kind of this `Tag`. */
488 get kind() {
489 return this.#kind;
490 }
491
492 /**
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.
496 *
497 * If the second argument is `true`, the `Tag` will be persisted but
498 * no serialization will be made. This is somewhat more efficient.
499 *
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.
504 *
505 * ※ Inverse object properties will never appear in the predicates
506 * of generated activities.
507 */
508 persist(silent = false) {
509 const system = this.#system;
510 const storage = this.#storage;
511 const {
512 objectProperties,
513 transitiveProperties,
514 dataProperties,
515 } = this.#schema;
516 const persistedData = this.#persistedData;
517 const data = this.#data;
518 const diffs = {};
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.
522 if (
523 objectProperties[key]?.inverseOf != null ||
524 silent && key in dataProperties
525 ) {
526 // The current property is one which is skipped in diffs.
527 //
528 // In a silent persist, this includes any literal terms.
529 /* do nothing */
530 } else {
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.
535 diffs[key] = {
536 old: new Set(),
537 new: value instanceof Set
538 ? new Set(value)
539 : new Set([value]),
540 };
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
548 // removed ones.
549 if (value.has(existing)) {
550 // The value is in both the old and new version of the
551 // data.
552 oldValues.delete(existing);
553 newValues.delete(existing);
554 } else {
555 // The value is not shared.
556 /* do nothing */
557 }
558 }
559 diffs[key] = { old: oldValues, new: newValues };
560 } else if (
561 `${value}` != `${persisted}` ||
562 value.language != persisted.language
563 ) {
564 // The current property is (optionally language‐tagged)
565 // string‐valued and the value changed.
566 diffs[key] = {
567 old: new Set([persisted]),
568 new: new Set([value]),
569 };
570 } else {
571 // The current property did not change.
572 diffs[key] = { old: new Set(), new: new Set() };
573 }
574 }
575 }
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);
581 } else {
582 // This `Tag` has not been persisted yet; save the new
583 // identifier after persisting.
584 this.#identifier = storage.add(this);
585 }
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
594 // property.
595 /* do nothing */
596 } else {
597 // The current property is the inverse of a non‐transitive
598 // property.
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);
603 try {
604 // Try removing this `Tag`.
605 referenced.#data[inverse].delete(persistedIdentifier);
606 storage.set(referencedIdentifier, referenced);
607 } catch {
608 // Removal failed, possibly because the other tag was
609 // deleted.
610 /* do nothing */
611 }
612 }
613 for (const referencedIdentifier of diffs[term].new) {
614 const referenced = storage.get(referencedIdentifier);
615 try {
616 // Try adding this `Tag`.
617 referenced.#data[inverse].add(persistedIdentifier);
618 storage.set(referencedIdentifier, referenced);
619 } catch {
620 // Adding failed, possibly because the other tag was deleted.
621 /* do nothing */
622 }
623 }
624 }
625 }
626 if (silent) {
627 // This is a silent persist.
628 return undefined;
629 } else {
630 // This is not a silent persist; an activity needs to be
631 // generated if a change was made.
632 const activity = {
633 "@context": taggingDiscoveryContext,
634 "@type": [
635 "TagActivity",
636 identifier == null ? "Create" : "Update",
637 ],
638 context: `${system.iri}`,
639 object: `${this.iri}`,
640 endTime: new Date().toISOString(),
641 ...(() => {
642 const statements = {
643 unstates: [],
644 states: [],
645 };
646 const { unstates, states } = statements;
647 if (identifier == null) {
648 // This is a Create activity.
649 states.push({ predicate: "a", object: `${this.kind}` });
650 } else {
651 // This is an Update activity.
652 /* do nothing */
653 }
654 for (
655 const [term, {
656 old: oldValues,
657 new: newValues,
658 }] of Object.entries(diffs)
659 ) {
660 // Iterate over the diffs of each term and state/unstate
661 // things as needed.
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.
666 unstates.push({
667 predicate: term,
668 object: { ...oldValue },
669 });
670 } else {
671 // This is a named term; attempt to get its I·R·I and
672 // push it.
673 try {
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.
678 /* do nothing */
679 } else {
680 // The value resolved; push its I·R·I.
681 unstates.push({
682 predicate: term,
683 object: tag.iri,
684 });
685 }
686 } catch {
687 // Value resolution failed for some reason; perhaps the
688 // tag was deleted.
689 /* do nothing */
690 }
691 }
692 }
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.
697 states.push({
698 predicate: term,
699 object: { ...newValue },
700 });
701 } else {
702 // This is a named term; attempt to get its I·R·I and
703 // push it.
704 try {
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.
709 /* do nothing */
710 } else {
711 // The value resolved; push its I·R·I.
712 states.push({
713 predicate: term,
714 object: tag.iri,
715 });
716 }
717 } catch {
718 // Value resolution failed for some reason; perhaps the
719 // tag was deleted.
720 /* do nothing */
721 }
722 }
723 }
724 }
725 if (unstates.length == 0) {
726 // Nothing was unstated.
727 delete statements.unstates;
728 } else {
729 // Things were stated.
730 /* do nothing */
731 }
732 if (states.length == 0) {
733 // Nothing was stated.
734 delete statements.states;
735 } else {
736 // Things were stated.
737 /* do nothing */
738 }
739 return statements;
740 })(),
741 };
742 if (
743 !Object.hasOwn(activity, "states") &&
744 !Object.hasOwn(activity, "unstates")
745 ) {
746 // No meaningful changes were actually persisted.
747 return null;
748 } else {
749 // There were meaningful changes persisted regarding this `Tag`.
750 return activity;
751 }
752 }
753 }
754
755 /** Returns the preferred label for this `Tag`. */
756 get prefLabel() {
757 return this.#data.prefLabel;
758 }
759
760 /** Sets the preferred label of this `Tag` to the provided label. */
761 set prefLabel($) {
762 this.#data.prefLabel = langString($);
763 }
764
765 /** Returns the Tag U·R·I for this `Tag`. */
766 get tagURI() {
767 const { identifier } = this;
768 return identifier == null
769 ? null
770 : `tag:${this.taggingEntity}:${identifier}`;
771 }
772
773 /** Returns the tagging entity (domain and date) for this `Tag`. */
774 get taggingEntity() {
775 return this.#system.taggingEntity;
776 }
777
778 /** Returns the string form of the preferred label of this `Tag`. */
779 toString() {
780 return `${this.#data.prefLabel}`;
781 }
782
783 /**
784 * Returns a new object whose enumerable own properties contain the
785 * data from this object needed for storage.
786 *
787 * ※ This method is not really intended for public usage.
788 */
789 [Storage.toObject]() {
790 const data = this.#data;
791 return Object.assign(Object.create(null), {
792 ...data,
793 kind: this.#kind,
794 });
795 }
796 }
797
798 const {
799 /**
800 * A `Tag` constructor function.
801 *
802 * This class extends the identity function, meaning that the object
803 * provided as the constructor is used verbatim (with new private
804 * fields added).
805 *
806 * ※ The instance methods of this class are provided as static
807 * methods on the superclass which all `Tag` constructors inherit
808 * from.
809 *
810 * ※ This class is not exposed.
811 */
812 TagConstructor,
813
814 /**
815 * The exposed constructor function from which all `Tag` constructors
816 * inherit.
817 *
818 * ☡ This constructor always throws.
819 */
820 TagSuper,
821 } = (() => {
822 const tagConstructorBehaviours = Object.create(null);
823 return {
824 TagConstructor: class extends identity {
825 /**
826 * The `TagSystem` used for `Tag`s constructed by this
827 * constructor.
828 */
829 #system;
830
831 /** The `Storage` managed by this constructor’s `TagSystem`. */
832 #storage;
833
834 /** The schema in use for this constructor. */
835 #schema;
836
837 /**
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.
841 *
842 * ※ This constructor does not modify the `name` or `prototype`
843 * properties of the provided constructor.
844 *
845 * ※ See `Tag.For`, where this constructor is used.
846 */
847 constructor(constructor, system, storage, schema) {
848 super(constructor);
849 Object.setPrototypeOf(this, TagSuper);
850 this.#system = system;
851 this.#storage = storage;
852 this.#schema = schema;
853 }
854
855 static {
856 // Define the superclass constructor which all `Tag`
857 // constructors will inherit from.
858 const superclass = tagConstructorBehaviours.TagSuper =
859 function Tag() {
860 throw new TypeError("Tags must belong to a System.");
861 };
862 const { prototype: methods } = this;
863 delete methods.constructor;
864 Object.defineProperty(superclass, "prototype", {
865 configurable: false,
866 enumerable: false,
867 value: Tag.prototype,
868 writable: false,
869 });
870 Object.defineProperties(
871 superclass,
872 Object.getOwnPropertyDescriptors(methods),
873 );
874 }
875
876 /**
877 * Yields the tags in the `TagSystem` associated with this
878 * constructor.
879 */
880 *all() {
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`.
888 yield instance;
889 } else {
890 // The current instance is not a `Tag` in this
891 // `TagSystem`.
892 /* do nothing */
893 }
894 }
895 }
896
897 /**
898 * Returns a new `Tag` resolved from the provided I·R·I.
899 *
900 * ☡ This function throws if the I·R·I is not in the `.iriSpace`
901 * of the `TagSystem` associated with this constructor.
902 *
903 * ※ If the I·R·I is not recognized, this function returns
904 * `null`.
905 */
906 fromIRI(iri) {
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}`,
915 );
916 } else {
917 // The I·R·I begins with the expected prefix.
918 const identifier = name.substring(prefix.length);
919 try {
920 // Attempt to resolve the identifier.
921 const instance = storage.get(identifier);
922 return Tag.getSystem(instance) == system ? instance : null;
923 } catch {
924 // Do not throw for bad identifiers.
925 return null;
926 }
927 }
928 }
929
930 /**
931 * Returns a new `Tag` resolved from the provided identifier.
932 *
933 * ☡ This function throws if the identifier is invalid.
934 *
935 * ※ If the identifier is valid but not recognized, this
936 * function returns `null`.
937 */
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;
943 }
944
945 /**
946 * Returns a new `Tag` resolved from the provided Tag U·R·I.
947 *
948 * ☡ This function throws if the provided Tag U·R·I does not
949 * match the tagging entity of this constructor’s `TagSystem`.
950 *
951 * ※ If the specific component of the Tag U·R·I is not
952 * recognized, this function returns `null`.
953 */
954 fromTagURI(tagURI) {
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}`,
963 );
964 } else {
965 // The I·R·I begins with the expected prefix.
966 const identifier = tagName.substring(tagPrefix.length);
967 try {
968 // Attempt to resolve the identifier.
969 const instance = storage.get(identifier);
970 return Tag.getSystem(instance) == system ? instance : null;
971 } catch {
972 // Do not throw for bad identifiers.
973 return null;
974 }
975 }
976 }
977
978 /**
979 * Yields the tag identifiers in the `TagSystem` associated with
980 * this constructor.
981 */
982 *identifiers() {
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`.
990 yield identifier;
991 } else {
992 // The current instance is not a `Tag` in this `TagSystem`.
993 /* do nothing */
994 }
995 }
996 }
997
998 /**
999 * Returns a new `Tag` constructed from the provided data and
1000 * with the provided identifier.
1001 *
1002 * ※ This function is not really intended for public usage.
1003 */
1004 [Storage.toInstance](data, identifier) {
1005 const tag = new this(data.kind);
1006 return Tag.assignData(tag, data, identifier);
1007 }
1008 },
1009 TagSuper: tagConstructorBehaviours.TagSuper,
1010 };
1011 })();
1012
1013 const {
1014 /**
1015 * Returns whether the provided schema, subject class, object
1016 * property, and object class are consistent.
1017 *
1018 * This is hardly a full reasoner; it is tuned to the abilites and
1019 * needs of this module.
1020 */
1021 isObjectPredicateOK,
1022 } = (() => {
1023 const cachedClassAndSuperclasses = new WeakMap();
1024 const cachedClassRestrictions = new WeakMap();
1025 const cachedPredicateRestrictions = new WeakMap();
1026
1027 const classAndSuperclasses = function* (
1028 classes,
1029 baseClass,
1030 touched = new Set(),
1031 ) {
1032 if (baseClass == "Thing" || touched.has(baseClass)) {
1033 /* do nothing */
1034 } else {
1035 yield baseClass;
1036 touched.add(baseClass);
1037 const subClassOf = classes[baseClass]?.subClassOf ?? "Thing";
1038 for (
1039 const superclass of (
1040 typeof subClassOf == "string"
1041 ? [subClassOf]
1042 : Array.from(subClassOf)
1043 ).filter(($) => typeof $ == "string")
1044 ) {
1045 yield* classAndSuperclasses(classes, superclass, touched);
1046 }
1047 }
1048 };
1049
1050 const getClassAndSuperclasses = (schema, baseClass) => {
1051 const schemaCache = cachedClassAndSuperclasses.get(schema);
1052 const cached = schemaCache?.[baseClass];
1053 if (cached != null) {
1054 return cached;
1055 } else {
1056 const { classes } = schema;
1057 const result = [...classAndSuperclasses(classes, baseClass)];
1058 if (schemaCache) {
1059 schemaCache[baseClass] = result;
1060 } else {
1061 cachedClassRestrictions.set(
1062 schema,
1063 Object.assign(Object.create(null), { [baseClass]: result }),
1064 );
1065 }
1066 return result;
1067 }
1068 };
1069
1070 const getClassRestrictions = (schema, domain) => {
1071 const schemaCache = cachedClassRestrictions.get(schema);
1072 const cached = schemaCache?.[domain];
1073 if (cached != null) {
1074 return cached;
1075 } else {
1076 const { classes } = schema;
1077 const restrictions = Object.create(null);
1078 const subClassOf = classes[domain]?.subClassOf ?? "Thing";
1079 for (
1080 const superclass of (
1081 typeof subClassOf == "string"
1082 ? [subClassOf]
1083 : Array.from(subClassOf)
1084 ).filter(($) => Object($) === $)
1085 ) {
1086 const { onProperty, allValuesFrom } = superclass;
1087 restrictions[onProperty] = processSpace(allValuesFrom);
1088 }
1089 if (schemaCache) {
1090 schemaCache[domain] = restrictions;
1091 } else {
1092 cachedClassRestrictions.set(
1093 schema,
1094 Object.assign(Object.create(null), {
1095 [domain]: restrictions,
1096 }),
1097 );
1098 }
1099 return restrictions;
1100 }
1101 };
1102
1103 const getPredicateRestrictions = (schema, predicate) => {
1104 const schemaCache = cachedPredicateRestrictions.get(schema);
1105 const cached = schemaCache?.[predicate];
1106 if (cached != null) {
1107 return cached;
1108 } else {
1109 const { objectProperties } = schema;
1110 const restrictions = [
1111 ...predicateRestrictions(objectProperties, predicate),
1112 ].reduce(
1113 (result, { domainIntersection, rangeIntersection }) => {
1114 result.domainIntersection.push(...domainIntersection);
1115 result.rangeIntersection.push(...rangeIntersection);
1116 return result;
1117 },
1118 Object.assign(Object.create(null), {
1119 domainIntersection: [],
1120 rangeIntersection: [],
1121 }),
1122 );
1123 if (schemaCache) {
1124 schemaCache[predicate] = restrictions;
1125 } else {
1126 cachedPredicateRestrictions.set(
1127 schema,
1128 Object.assign(Object.create(null), {
1129 [predicate]: restrictions,
1130 }),
1131 );
1132 }
1133 return restrictions;
1134 }
1135 };
1136
1137 const processSpace = (space) =>
1138 Object(space) === space
1139 ? "length" in space
1140 ? Array.from(
1141 space,
1142 (subspace) =>
1143 Object(subspace) === subspace
1144 ? Array.from(subspace.unionOf)
1145 : [subspace],
1146 )
1147 : [Array.from(space.unionOf)]
1148 : [[space]];
1149
1150 const predicateRestrictions = function* (
1151 objectProperties,
1152 predicate,
1153 touched = new Set(),
1154 ) {
1155 if (predicate == "Property" || touched.has(predicate)) {
1156 /* do nothing */
1157 } else {
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"),
1163 });
1164 touched.add(predicate);
1165 for (
1166 const superproperty of (
1167 subPropertyOf == null
1168 ? ["Property"]
1169 : typeof subPropertyOf == "string"
1170 ? [subPropertyOf]
1171 : Array.from(subPropertyOf)
1172 )
1173 ) {
1174 yield* predicateRestrictions(
1175 objectProperties,
1176 superproperty,
1177 touched,
1178 );
1179 }
1180 }
1181 };
1182
1183 return {
1184 isObjectPredicateOK: (
1185 schema,
1186 subjectClass,
1187 predicate,
1188 objectClass,
1189 ) => {
1190 const { objectProperties } = schema;
1191 const predicateDefinition = objectProperties[predicate];
1192 const isInverse = "inverseOf" in predicateDefinition;
1193 const usedPredicate = isInverse
1194 ? predicateDefinition.inverseOf
1195 : predicate;
1196 const domain = isInverse ? objectClass : subjectClass;
1197 const domains = new Set(getClassAndSuperclasses(schema, domain));
1198 const ranges = new Set(getClassAndSuperclasses(
1199 schema,
1200 isInverse ? subjectClass : objectClass,
1201 ));
1202 const predicateRestrictions = getPredicateRestrictions(
1203 schema,
1204 usedPredicate,
1205 );
1206 const { domainIntersection } = predicateRestrictions;
1207 const rangeIntersection = [
1208 ...predicateRestrictions.rangeIntersection,
1209 ...function* () {
1210 for (const domain of domains) {
1211 const classRestrictionOnPredicate =
1212 getClassRestrictions(schema, domain)[usedPredicate];
1213 if (classRestrictionOnPredicate != null) {
1214 yield* classRestrictionOnPredicate;
1215 } else {
1216 /* do nothing */
1217 }
1218 }
1219 }(),
1220 ];
1221 return domainIntersection.every((domainUnion) =>
1222 domainUnion.some((domain) =>
1223 domain == "Thing" || domains.has(domain)
1224 )
1225 ) &&
1226 rangeIntersection.every((rangeUnion) =>
1227 rangeUnion.some((range) =>
1228 range == "Thing" || ranges.has(range)
1229 )
1230 );
1231 },
1232 };
1233 })();
1234
1235 const {
1236 /**
1237 * Returns the provided value converted into a `String` object with
1238 * `.["@value"]` and `.["@language"]` properties.
1239 *
1240 * The same object will be returned for every call with an equivalent
1241 * value.
1242 *
1243 * TODO: Ideally this would be extracted more fully into an R·D·F
1244 * library.
1245 *
1246 * ※ This function is not exposed.
1247 */
1248 langString,
1249 } = (() => {
1250 /**
1251 * Returns the language string object corresponding to the provided
1252 * value and language.
1253 */
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
1259 // and language.
1260 return literal;
1261 } else {
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, {
1266 "@value": {
1267 enumerable: true,
1268 value,
1269 },
1270 "@language": {
1271 enumerable: !!language,
1272 value: language || null,
1273 },
1274 language: { enumerable: false, get: getLanguage },
1275 toString: { enumerable: false, value: toString },
1276 valueOf: { enumerable: false, value: valueOf },
1277 }),
1278 );
1279 const ref = new WeakRef(result);
1280 langStringRegistry.register(result, { ref, language, value });
1281 valueMap[value] = ref;
1282 return result;
1283 }
1284 };
1285
1286 /** Returns the `.["@language"]` of this object. */
1287 const getLanguage = Object.defineProperty(
1288 function () {
1289 return this["@language"] || null;
1290 },
1291 "name",
1292 { value: "get language" },
1293 );
1294
1295 /**
1296 * A `FinalizationRegistry` for language string objects.
1297 *
1298 * This simply cleans up the corresponding `WeakRef` in the language
1299 * map.
1300 */
1301 const langStringRegistry = new FinalizationRegistry(
1302 ({ ref, language, value }) => {
1303 const valueMap = languageMap[language];
1304 if (valueMap?.[value] === ref) {
1305 delete valueMap[value];
1306 } else {
1307 /* do nothing */
1308 }
1309 },
1310 );
1311
1312 /**
1313 * An object whose own values are an object mapping values to
1314 * language string objects for the language specified by the key.
1315 */
1316 const languageMap = Object.create(null);
1317
1318 /** Returns the `.["@value"]` of this object. */
1319 const toString = function () {
1320 return this["@value"];
1321 };
1322
1323 /**
1324 * Returns this object if it has a `.["@language"]`; otherwise, its
1325 * `.["@value"]`.
1326 */
1327 const valueOf = function () {
1328 return this["@language"] ? this : this["@value"];
1329 };
1330
1331 return {
1332 langString: ($) =>
1333 Object($) === $
1334 ? "@value" in $
1335 ? "@language" in $
1336 ? getLangString(
1337 `${$["@value"]}`,
1338 `${$["@language"] ?? ""}`,
1339 )
1340 : getLangString(`${$["@value"]}`)
1341 : "language" in $
1342 ? getLangString(`${$}`, `${$.language ?? ""}`)
1343 : getLangString(`${$}`)
1344 : getLangString(`${$ ?? ""}`),
1345 };
1346 })();
1347
1348 /**
1349 * Returns a normalized tag data object derived from the provided
1350 * object.
1351 *
1352 * ※ The properties of this function need to match the term names used
1353 * in the ActivityStreams serialization.
1354 *
1355 * ※ This function is not exposed.
1356 */
1357 const tagData = ($) => {
1358 const data = Object($);
1359 const {
1360 // prefLabel intentionally not set here
1361 altLabel,
1362 hiddenLabel,
1363 broader,
1364 narrower,
1365 inCanon,
1366 hasInCanon,
1367 involves,
1368 involvedIn,
1369 } = data;
1370 let prefLabel = langString(data.prefLabel);
1371 return Object.preventExtensions(Object.create(null, {
1372 prefLabel: {
1373 enumerable: true,
1374 get: () => prefLabel,
1375 set: ($) => {
1376 prefLabel = langString($);
1377 },
1378 },
1379 altLabel: {
1380 enumerable: true,
1381 value: new Set(
1382 altLabel != null
1383 ? Array.from(altLabel, langString)
1384 : undefined,
1385 ),
1386 },
1387 hiddenLabel: {
1388 enumerable: true,
1389 value: new Set(
1390 hiddenLabel != null
1391 ? Array.from(hiddenLabel, langString)
1392 : undefined,
1393 ),
1394 },
1395 broader: {
1396 enumerable: true,
1397 value: new Set(
1398 broader != null
1399 ? Array.from(broader, toIdentifier)
1400 : undefined,
1401 ),
1402 },
1403 narrower: {
1404 enumerable: true,
1405 value: new Set(
1406 narrower != null
1407 ? Array.from(narrower, toIdentifier)
1408 : undefined,
1409 ),
1410 },
1411 inCanon: {
1412 enumerable: true,
1413 value: new Set(
1414 inCanon != null
1415 ? Array.from(inCanon, toIdentifier)
1416 : undefined,
1417 ),
1418 },
1419 hasInCanon: {
1420 enumerable: true,
1421 value: new Set(
1422 hasInCanon != null
1423 ? Array.from(hasInCanon, toIdentifier)
1424 : undefined,
1425 ),
1426 },
1427 involves: {
1428 enumerable: true,
1429 value: new Set(
1430 involves != null
1431 ? Array.from(involves, toIdentifier)
1432 : undefined,
1433 ),
1434 },
1435 involvedIn: {
1436 enumerable: true,
1437 value: new Set(
1438 involvedIn != null
1439 ? Array.from(involvedIn, toIdentifier)
1440 : undefined,
1441 ),
1442 },
1443 }));
1444 };
1445
1446 /**
1447 * Returns an identifier corresponding to the provided object.
1448 *
1449 * This is either the value of its `.identifier` or its string value.
1450 *
1451 * ※ This function is not exposed.
1452 */
1453 const toIdentifier = ($) =>
1454 $ == null
1455 ? null
1456 : Object($) === $ && "identifier" in $
1457 ? $.identifier
1458 : `${$}`;
1459
1460 /**
1461 * A tag system, with storage.
1462 *
1463 * The `::Tag` constructor available on any `TagSystem` instance can be
1464 * used to create new `Tag`s within the system.
1465 */
1466 export class TagSystem {
1467 /** The cached bound `Tag` constructor for this `TagSystem`. */
1468 #Tag = null;
1469
1470 /** The domain of this `TagSystem`. */
1471 #domain;
1472
1473 /** The date of this `TagSystem`. */
1474 #date;
1475
1476 /** The identifier of this `TagSystem`. */
1477 #identifier;
1478
1479 /** The internal `Storage` of this `TagSystem`. */
1480 #storage = new Storage();
1481
1482 /**
1483 * Constructs a new `TagSystem` with the provided domain and date.
1484 *
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.
1488 *
1489 * ☡ This constructor throws if provided with an invalid date.
1490 */
1491 constructor(domain, date, identifier = "") {
1492 const domainString = `${domain}`;
1493 const dateString = `${date}`;
1494 this.#identifier = `${identifier}`;
1495 try {
1496 // If the identifier is a valid storage I·D, reserve it.
1497 this.#storage.delete(this.#identifier);
1498 } catch {
1499 // The identifier is not a valid storage I·D, so no worries.
1500 /* do nothing */
1501 }
1502 if (
1503 !/^[a-z](?:[\da-z-]*[\da-z])?(?:\.[a-z](?:[\da-z-]*[\da-z])?)*$/u
1504 .test(domainString)
1505 ) {
1506 // ☡ The domain is invalid.
1507 throw new RangeError(`Invalid domain: ${domain}.`);
1508 } else if (
1509 !/^\d{4}-\d{2}-\d{2}$/u.test(dateString) ||
1510 dateString != new Date(dateString).toISOString().split("T")[0]
1511 ) {
1512 // ☡ The date is invalid.
1513 throw new RangeError(`Invalid date: ${date}.`);
1514 } else {
1515 // The domain and date are 🆗.
1516 this.#domain = domainString;
1517 this.#date = dateString;
1518 }
1519 }
1520
1521 /**
1522 * Returns a bound constructor for constructing `Tags` in this
1523 * `TagSystem`.
1524 */
1525 get Tag() {
1526 if (this.#Tag != null) {
1527 // A bound constructor has already been generated; return it.
1528 return this.#Tag;
1529 } else {
1530 // No bound constructor has been created yet.
1531 const storage = this.#storage;
1532 return this.#Tag = Tag.For(this, storage, schema);
1533 }
1534 }
1535
1536 /** Returns the authority name (domain) for this `TagSystem`. */
1537 get authorityName() {
1538 return this.#domain;
1539 }
1540
1541 /** Returns the date of this `TagSystem`, as a string. */
1542 get date() {
1543 return this.#date;
1544 }
1545
1546 /**
1547 * Yields the entities in this `TagSystem`.
1548 *
1549 * ※ Entities can hypothetically be anything. If you specifically
1550 * want the `Tag`s, use `::Tag.all` instead.
1551 */
1552 *entities() {
1553 yield* this.#storage.values();
1554 }
1555
1556 /**
1557 * Returns the identifier of this `TagSystem`.
1558 *
1559 * ※ Often this is just the empty string.
1560 */
1561 get identifier() {
1562 return this.#identifier;
1563 }
1564
1565 /** Yields the identifiers in use in this `TagSystem`. */
1566 *identifiers() {
1567 yield* this.#storage.keys();
1568 }
1569
1570 /** Returns the I·R·I for this `TagSystem`. */
1571 get iri() {
1572 return `${this.iriSpace}${this.identifier}`;
1573 }
1574
1575 /**
1576 * Returns the prefix used for I·R·I’s of `Tag`s in this `TagSystem`.
1577 */
1578 get iriSpace() {
1579 return `https://${this.authorityName}/tag:${this.taggingEntity}:`;
1580 }
1581
1582 /** Returns the Tag U·R·I for this `TagSystem`. */
1583 get tagURI() {
1584 return `tag:${this.taggingEntity}:${this.identifier}`;
1585 }
1586
1587 /**
1588 * Returns the tagging entity (domain and date) for this `TagSystem`.
1589 */
1590 get taggingEntity() {
1591 return `${this.authorityName},${this.date}`;
1592 }
1593 }
This page took 0.218223 seconds and 3 git commands to generate.