-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.mjs
More file actions
2047 lines (1760 loc) · 68.6 KB
/
index.mjs
File metadata and controls
2047 lines (1760 loc) · 68.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Microdata API - A vanilla JavaScript library for working with HTML Microdata
*
* This library provides extraction, rendering, synchronization, and validation
* of schema.org and other microdata within the DOM.
*/
// Import external html-template library
import { HTMLTemplate } from 'https://jamesaduncan.github.io/html-template/index.mjs';
/**
* MicrodataItem - Represents a single microdata item with live DOM binding
*
* @class MicrodataItem
* @description Provides a proxy-based interface for accessing and manipulating microdata properties
* with automatic DOM synchronization. Supports JSON-LD compatible property access.
*
* @example
* // Access microdata from an element
* const person = document.getElementById('person').microdata;
* console.log(person.name); // "John Doe"
* person.email = "john@example.com"; // Updates DOM
*
* @example
* // Convert to JSON-LD
* const jsonld = person.toJSON();
* // { "@type": "Person", "@context": "https://schema.org/", "name": "John Doe", ... }
*/
class MicrodataItem {
/**
* Creates a new MicrodataItem instance
* @param {HTMLElement} element - DOM element with itemscope attribute
* @throws {Error} If element is missing or lacks itemscope attribute
*/
constructor(element) {
if (!element || !element.hasAttribute('itemscope')) {
throw new Error('MicrodataItem requires an element with itemscope attribute');
}
this._element = element;
this._itemrefElements = this._resolveItemref();
// Create handler object to maintain reference
const handler = {
get: (target, prop) => {
// Handle special JSON-LD properties
if (prop === '@type') {
const itemtype = target._element.getAttribute('itemtype');
if (!itemtype) return undefined;
// Trim whitespace and extract the type from the URL (last part after /)
const trimmedType = itemtype.trim();
if (!trimmedType) return undefined;
const parts = trimmedType.split('/');
return parts[parts.length - 1];
}
if (prop === '@context') {
const itemtype = target._element.getAttribute('itemtype');
if (!itemtype) return undefined;
// Trim whitespace and extract the context (everything before the last /)
const trimmedType = itemtype.trim();
if (!trimmedType) return undefined;
const lastSlash = trimmedType.lastIndexOf('/');
return lastSlash > 0 ? trimmedType.substring(0, lastSlash + 1) : undefined;
}
if (prop === '@id') {
// @id should just be the HTML id attribute value
return target._element.id || undefined;
}
// Handle methods and private properties
if (typeof prop === 'string' && (prop.startsWith('_') || typeof target[prop] === 'function')) {
return target[prop];
}
// Handle Symbol properties (for iteration)
if (typeof prop === 'symbol') {
return target[prop];
}
// Handle regular properties
return target._getProperty(prop);
},
set: (target, prop, value) => {
// Prevent setting special properties
if (prop === '@type' || prop === '@context' || prop === '@id') {
return false;
}
// Handle private properties
if (typeof prop === 'string' && prop.startsWith('_')) {
target[prop] = value;
return true;
}
// Set regular properties
return target._setProperty(prop, value);
},
has: (target, prop) => {
// Check for special properties
if (prop === '@type' || prop === '@context' || prop === '@id') {
return true;
}
// Check for methods and private properties
if (typeof prop === 'string' && (prop.startsWith('_') || typeof target[prop] === 'function')) {
return prop in target;
}
// Check for regular properties
return target._hasProperty(prop);
},
ownKeys: (target) => {
const keys = ['@type', '@context', '@id'];
const propNames = target._getAllPropertyNames();
return [...keys, ...propNames];
},
getOwnPropertyDescriptor: (target, prop) => {
if (prop === '@type' || prop === '@context' || prop === '@id' || target._hasProperty(prop)) {
return {
enumerable: true,
configurable: true,
value: handler.get(target, prop)
};
}
return undefined;
}
};
return new Proxy(this, handler);
}
_resolveItemref() {
const refs = [];
const itemref = this._element.getAttribute('itemref');
if (!itemref) return refs;
// Split by whitespace and resolve each ID, handling duplicates
const ids = itemref.trim().split(/\s+/);
const seen = new Set();
for (const id of ids) {
if (seen.has(id)) continue; // Skip duplicate IDs
seen.add(id);
const element = document.getElementById(id);
if (element) {
refs.push(element);
}
// Silently skip non-existent IDs
}
return refs;
}
_getPropertyElements(name) {
const elements = [];
// Search within the item element and itemref elements
const searchRoots = [this._element, ...this._itemrefElements];
for (const root of searchRoots) {
// For itemref elements, check if the element itself has the itemprop
if (root !== this._element && root.hasAttribute('itemprop')) {
const itemprops = root.getAttribute('itemprop').trim().split(/\s+/);
if (itemprops.includes(name)) {
elements.push(root);
}
}
// Search within the element (but not within nested itemscopes)
const walker = document.createTreeWalker(
root,
NodeFilter.SHOW_ELEMENT,
{
acceptNode: (node) => {
// Check if it has the itemprop we're looking for
if (node.hasAttribute('itemprop')) {
const itemprops = node.getAttribute('itemprop').trim().split(/\s+/);
if (itemprops.includes(name)) {
return NodeFilter.FILTER_ACCEPT;
}
}
// Skip if we're inside a nested itemscope (unless it has our itemprop)
if (node !== root && node.hasAttribute('itemscope')) {
return NodeFilter.FILTER_REJECT;
}
return NodeFilter.FILTER_SKIP;
}
}
);
let node;
while (node = walker.nextNode()) {
elements.push(node);
}
}
return elements;
}
_getProperty(name) {
const elements = this._getPropertyElements(name);
if (elements.length === 0) {
return undefined;
}
if (elements.length === 1) {
return this._extractValue(elements[0]);
}
// Multiple elements means array
return elements.map(el => this._extractValue(el));
}
_setProperty(name, value) {
const elements = this._getPropertyElements(name);
if (Array.isArray(value)) {
// Update existing elements
elements.forEach((el, index) => {
if (index < value.length) {
this._setValue(el, value[index]);
}
});
// Create new elements if needed
if (value.length > elements.length) {
for (let i = elements.length; i < value.length; i++) {
this._createPropertyElement(name, value[i]);
}
}
// Remove excess elements
if (value.length < elements.length) {
for (let i = value.length; i < elements.length; i++) {
elements[i].remove();
}
}
} else {
// Setting single value
if (elements.length > 0) {
this._setValue(elements[0], value);
// Remove extra elements if setting single value
for (let i = 1; i < elements.length; i++) {
elements[i].remove();
}
} else {
// Create new element
this._createPropertyElement(name, value);
}
}
return true;
}
_createPropertyElement(name, value) {
const element = document.createElement('span');
element.setAttribute('itemprop', name);
this._setValue(element, value);
this._element.appendChild(element);
return element;
}
_hasProperty(name) {
return this._getPropertyElements(name).length > 0;
}
_getAllPropertyNames() {
const names = new Set();
// Collect from main element and itemref elements
const searchRoots = [this._element, ...this._itemrefElements];
for (const root of searchRoots) {
// Check itemref elements themselves
if (root !== this._element && root.hasAttribute('itemprop')) {
const itemprops = root.getAttribute('itemprop').trim().split(/\s+/);
itemprops.forEach(prop => names.add(prop));
}
// Search within elements
const walker = document.createTreeWalker(
root,
NodeFilter.SHOW_ELEMENT,
{
acceptNode: (node) => {
if (node.hasAttribute('itemprop')) {
return NodeFilter.FILTER_ACCEPT;
}
// Skip nested itemscopes
if (node !== root && node.hasAttribute('itemscope')) {
return NodeFilter.FILTER_REJECT;
}
return NodeFilter.FILTER_SKIP;
}
}
);
let node;
while (node = walker.nextNode()) {
const itemprops = node.getAttribute('itemprop').trim().split(/\s+/);
itemprops.forEach(prop => names.add(prop));
}
}
return Array.from(names);
}
_extractValue(element) {
// Handle nested microdata items
if (element.hasAttribute('itemscope')) {
return new MicrodataItem(element);
}
// Handle various element types
if (element.hasAttribute('content')) {
return element.getAttribute('content');
}
if ((element.tagName === 'A' || element.tagName === 'LINK') && element.hasAttribute('href')) {
// Return the href attribute value (which may be relative)
// rather than element.href (which is always absolute)
return element.getAttribute('href');
}
if (element.tagName === 'IMG' && element.hasAttribute('src')) {
return element.src;
}
if (element.tagName === 'TIME' && element.hasAttribute('datetime')) {
return element.getAttribute('datetime');
}
// Handle form elements
if (element.tagName === 'INPUT' || element.tagName === 'TEXTAREA' || element.tagName === 'SELECT') {
return element.value;
}
// Default to text content
return element.textContent.trim();
}
_setValue(element, value) {
// Handle nested microdata items
if (element.hasAttribute('itemscope')) {
// Cannot directly set nested items - silently skip
return;
}
// Handle various element types
if (element.hasAttribute('content')) {
element.setAttribute('content', value);
} else if (element.tagName === 'A' && element.hasAttribute('href')) {
element.href = value;
} else if (element.tagName === 'IMG' && element.hasAttribute('src')) {
element.src = value;
} else if (element.tagName === 'TIME' && element.hasAttribute('datetime')) {
element.setAttribute('datetime', value);
} else if (element.tagName === 'INPUT') {
// Use setAttribute so MutationObserver can detect the change
element.setAttribute('value', value);
element.value = value; // Also set the property for immediate display
} else if (element.tagName === 'TEXTAREA' || element.tagName === 'SELECT') {
// For textarea and select, just set the value property
element.value = value;
} else {
// Default to text content
element.textContent = value;
}
}
/**
* Converts the microdata item to JSON-LD format
* @returns {Object} JSON-LD representation of the microdata item
*/
toJSON() {
const json = {
'@type': this['@type'],
'@context': this['@context']
};
const id = this['@id'];
if (id) {
json['@id'] = id;
}
// Add all properties
const props = this._getAllPropertyNames();
for (const prop of props) {
const value = this._getProperty(prop);
if (value !== undefined) {
json[prop] = Array.isArray(value)
? value.map(v => v instanceof MicrodataItem ? v.toJSON() : v)
: value instanceof MicrodataItem ? value.toJSON() : value;
}
}
return json;
}
}
/**
* MicrodataCollection - Collection that supports both array and object access
*
* @class MicrodataCollection
* @extends Array
* @description Provides a hybrid array/object interface for accessing microdata items.
* Items can be accessed by numeric index or by element ID.
*
* @example
* // Access by index
* const firstPerson = document.microdata[0];
*
* // Access by ID
* const specificPerson = document.microdata['person-123'];
*
* // Use array methods
* document.microdata.forEach(item => console.log(item.name));
*/
class MicrodataCollection extends Array {
constructor() {
super();
return new Proxy(this, {
get: (target, prop) => {
// Try numeric/array access first
if (prop in target || typeof prop === 'symbol') {
return target[prop];
}
// Try to find by element ID
if (typeof prop === 'string') {
const item = target.find(item => {
if (item._element && item._element.id === prop) {
return true;
}
return false;
});
if (item) {
return item;
}
}
return undefined;
},
has: (target, prop) => {
// Check array properties and indices
if (prop in target) {
return true;
}
// Check if we have an item with this ID
if (typeof prop === 'string') {
return target.some(item => item._element && item._element.id === prop);
}
return false;
},
ownKeys: (target) => {
// Get all properties including non-configurable ones
const keys = Reflect.ownKeys(target);
// Add IDs of items that have them
for (const item of target) {
if (item._element && item._element.id) {
keys.push(item._element.id);
}
}
return keys;
},
getOwnPropertyDescriptor: (target, prop) => {
// Handle numeric indices
if (prop in target) {
return Object.getOwnPropertyDescriptor(target, prop);
}
// Handle named access by ID
if (typeof prop === 'string') {
const hasItem = target.some(item => item._element && item._element.id === prop);
if (hasItem) {
return {
enumerable: true,
configurable: true,
value: target[prop]
};
}
}
return undefined;
}
});
}
_addItem(item) {
this.push(item);
}
_removeItem(item) {
const index = this.indexOf(item);
if (index > -1) {
this.splice(index, 1);
}
}
_clear() {
this.length = 0;
}
_isTopLevel(element) {
// Check if this element is nested within another itemscope
let parent = element.parentElement;
while (parent && parent !== document.body) {
if (parent.hasAttribute('itemscope')) {
return false;
}
parent = parent.parentElement;
}
return true;
}
}
// Global collection instance
const microdataCollection = new MicrodataCollection();
/**
* MicrodataObserver - Monitors DOM changes and updates the global collection
* @private
*/
class MicrodataObserver {
constructor(collection) {
this.collection = collection;
this.observer = null;
this.itemElementMap = new WeakMap();
}
start() {
// Initial scan
this._scanDocument();
// Set up mutation observer
this.observer = new MutationObserver((mutations) => {
this._handleMutations(mutations);
});
this.observer.observe(document.body, {
childList: true,
subtree: true,
attributes: true,
attributeFilter: ['itemscope', 'itemtype', 'itemid', 'itemref', 'itemprop', 'value'],
attributeOldValue: true
});
}
stop() {
if (this.observer) {
this.observer.disconnect();
this.observer = null;
}
}
_scanDocument() {
// Find all top-level microdata items
const items = document.querySelectorAll('[itemscope]');
for (const element of items) {
if (this.collection._isTopLevel(element)) {
const item = new MicrodataItem(element);
this.collection._addItem(item);
this.itemElementMap.set(element, item);
}
}
}
_handleMutations(mutations) {
const addedElements = new Set();
const removedElements = new Set();
const modifiedElements = new Set();
for (const mutation of mutations) {
if (mutation.type === 'childList') {
// Handle added nodes
for (const node of mutation.addedNodes) {
if (node.nodeType === Node.ELEMENT_NODE) {
this._collectMicrodataElements(node, addedElements);
}
}
// Handle removed nodes
for (const node of mutation.removedNodes) {
if (node.nodeType === Node.ELEMENT_NODE) {
this._collectMicrodataElements(node, removedElements);
}
}
} else if (mutation.type === 'attributes') {
// Handle attribute changes on itemscope elements
if (mutation.target.hasAttribute('itemscope')) {
modifiedElements.add(mutation.target);
}
}
}
// Process removed elements
for (const element of removedElements) {
const item = this.itemElementMap.get(element);
if (item) {
this.collection._removeItem(item);
this.itemElementMap.delete(element);
}
}
// Process added elements
for (const element of addedElements) {
if (this.collection._isTopLevel(element) && !this.itemElementMap.has(element)) {
const item = new MicrodataItem(element);
this.collection._addItem(item);
this.itemElementMap.set(element, item);
}
}
// Note: Modified elements keep their existing MicrodataItem instance
// The Proxy will reflect any changes automatically
}
_collectMicrodataElements(root, collection) {
if (root.hasAttribute('itemscope')) {
collection.add(root);
}
const items = root.querySelectorAll('[itemscope]');
for (const item of items) {
collection.add(item);
}
}
}
// Initialize observer
const observer = new MicrodataObserver(microdataCollection);
// Auto-start when DOM is ready
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', () => observer.start());
} else {
observer.start();
}
/**
* Add microdata property to HTMLElement prototype
* @memberof HTMLElement.prototype
* @property {MicrodataItem|null} microdata - The MicrodataItem associated with this element
*/
Object.defineProperty(HTMLElement.prototype, 'microdata', {
get() {
if (!this.hasAttribute('itemscope')) {
return null;
}
// Check if we already have an item for this element
let item = observer.itemElementMap.get(this);
if (item) {
return item;
}
// Create new item
item = new MicrodataItem(this);
observer.itemElementMap.set(this, item);
return item;
},
configurable: true,
enumerable: false
});
/**
* Add microdata collection to Document prototype
* @memberof Document.prototype
* @property {MicrodataCollection} microdata - Collection of all top-level microdata items
*/
Object.defineProperty(Document.prototype, 'microdata', {
get() {
return microdataCollection;
},
configurable: true,
enumerable: false
});
/**
* Utility function to extract data from various object types
* @param {MicrodataItem|HTMLFormElement|Element|Object} obj - Object to extract data from
* @returns {Object} Extracted data as plain object
* @private
*/
function extractMicrodataData(obj) {
if (obj instanceof MicrodataItem) {
const json = obj.toJSON();
// @id is now just the element id, no manipulation needed
return json;
}
if (obj instanceof HTMLFormElement) {
// Extract form data with enhanced support for all form elements
const data = {};
// Process all form elements
const elements = obj.elements;
for (let i = 0; i < elements.length; i++) {
const element = elements[i];
if (!element.name) continue;
const name = element.name;
let value;
switch (element.type) {
case 'checkbox':
if (element.checked) {
value = element.value || 'on';
// Handle checkbox groups for arrays
if (name.endsWith('[]')) {
const baseName = name.slice(0, -2);
if (!data[baseName]) data[baseName] = [];
data[baseName].push(value);
} else {
if (data[name]) {
// Convert to array if multiple checkboxes with same name
if (!Array.isArray(data[name])) {
data[name] = [data[name]];
}
data[name].push(value);
} else {
data[name] = value;
}
}
}
break;
case 'radio':
if (element.checked) {
data[name] = element.value;
}
break;
case 'select-multiple':
const selectedOptions = [];
for (let j = 0; j < element.options.length; j++) {
if (element.options[j].selected) {
selectedOptions.push(element.options[j].value);
}
}
if (selectedOptions.length > 0) {
data[name] = selectedOptions;
}
break;
case 'file':
// Skip file inputs for now
break;
default:
if (element.value) {
data[name] = element.value;
}
}
}
return data;
}
if (obj instanceof Element && obj.hasAttribute('itemscope')) {
const item = new MicrodataItem(obj);
return item.toJSON();
}
// Plain object
return obj;
}
/**
* Schema Loading and Caching System
*/
const schemaCache = new Map();
const schemaLoadingPromises = new Map();
/**
* Base Schema class - Factory that returns appropriate subclass
*
* @class Schema
* @description Factory class for creating and loading schema definitions.
* Automatically returns the appropriate subclass (SchemaOrgSchema or RustyBeamNetSchema)
* based on the schema URL.
*
* @example
* // Load a schema
* const personSchema = await Schema.load('https://schema.org/Person');
*
* // Validate an object
* const isValid = personSchema.validate(myPersonObject);
*
* // Create schema instance directly
* const schema = new Schema('https://schema.org/Person');
*/
class Schema {
constructor(url, data = null) {
// Factory pattern - return appropriate subclass
if (new.target === Schema) {
if (url.includes('rustybeam.net/schema/')) {
return new RustyBeamNetSchema(url, data);
}
return new SchemaOrgSchema(url, data);
}
this.url = url;
this.data = data;
this.loaded = false;
}
/**
* Loads a schema from cache or network
* @param {string} url - Schema URL
* @returns {Promise<Schema>} Loaded schema instance
* @static
*/
static async load(url) {
// Check cache first
if (schemaCache.has(url)) {
return schemaCache.get(url);
}
// Check if already loading
if (schemaLoadingPromises.has(url)) {
return schemaLoadingPromises.get(url);
}
// Start loading
const loadPromise = Schema._loadSchema(url)
.then(data => {
const schema = Schema._createSchemaInstance(url, data);
schema.loaded = true;
schemaCache.set(url, schema);
schemaLoadingPromises.delete(url);
return schema;
})
.catch(err => {
schemaLoadingPromises.delete(url);
throw err;
});
schemaLoadingPromises.set(url, loadPromise);
return loadPromise;
}
/**
* Manually cache a schema (useful for testing)
* @param {Schema} schema - Schema instance to cache
* @static
*/
static cache(schema) {
if (schema && schema.url) {
schemaCache.set(schema.url, schema);
}
}
static async _loadSchema(url) {
try {
const response = await fetch(url, {
headers: {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'
}
});
if (!response.ok) {
throw new Error(`Failed to load schema: ${response.status} ${response.statusText}`);
}
const html = await response.text();
// Parse HTML to extract schema
const parser = new DOMParser();
const doc = parser.parseFromString(html, 'text/html');
return Schema._extractSchemaFromDocument(doc);
} catch (err) {
throw new Error(`Failed to load schema from ${url}: ${err.message}`);
}
}
static _extractSchemaFromDocument(doc) {
// Different extraction logic for different schema providers
// Look for microdata schemas in the document
const schemaItem = doc.querySelector('[itemtype*="Schema"]');
if (!schemaItem && doc.querySelector('[itemtype*="schema.org"]')) {
// This is a schema.org definition page
// Extract property definitions from the page structure
const properties = {};
// Schema.org uses a table format for properties
const propRows = doc.querySelectorAll('table.definition-table tbody tr');
for (const row of propRows) {
const propName = row.querySelector('th.prop-nam code')?.textContent;
const propTypes = Array.from(row.querySelectorAll('td.prop-ect a')).map(a => a.textContent);
const propDesc = row.querySelector('td.prop-desc')?.textContent;
if (propName) {
properties[propName] = {
name: propName,
types: propTypes,
description: propDesc
};
}
}
return { properties };
}
if (schemaItem) {
// Create a temporary MicrodataItem to extract the data
const tempItem = new MicrodataItem(schemaItem);
const data = tempItem.toJSON();
// For RustyBeam.net schemas, properties might be separate items
// Look for Property items that are children or siblings
const propertyItems = doc.querySelectorAll('[itemtype*="/Property"]');
if (propertyItems.length > 0 && (!data.properties || Object.keys(data.properties).length === 0)) {
data.properties = {};
for (const propItem of propertyItems) {
const propMicrodata = new MicrodataItem(propItem);
const propData = propMicrodata.toJSON();
if (propData.name) {
data.properties[propData.name] = propData;
}
}
}
return data;
}
return {};
}
static _createSchemaInstance(url, data) {
// Determine schema type based on URL or data structure
if (url.includes('rustybeam.net/schema/') ||
(data['@context'] && data['@context'].includes('rustybeam.net'))) {
return new RustyBeamNetSchema(url, data);
}
// Default to Schema.org
return new SchemaOrgSchema(url, data);
}
/**
* Clears the schema cache
* @static
*/
static clearCache() {
schemaCache.clear();
}
/**
* Instance method to load this schema
* @returns {Promise<boolean>} Whether the schema loaded successfully
*/
async load() {
// To be overridden by subclasses
throw new Error('load() must be implemented by subclass');
}
/**
* Validates an object against the schema
* @param {Object} obj - Object to validate
* @returns {boolean|Object} False if validation fails, otherwise returns the validated microdata object
*/
validate(obj) {
throw new Error('validate() must be implemented by subclass');
}
}
/**
* Schema.org implementation
* @class SchemaOrgSchema