@opengeospatial/jsonld-ui-utils 0.4.12 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -23,11 +23,22 @@ function _interopNamespaceDefault(e) {
23
23
 
24
24
  var N3__namespace = /*#__PURE__*/_interopNamespaceDefault(N3);
25
25
 
26
- const jsonFetch = async (url) => {
27
- const response = await fetch(url, {
28
- headers: { 'Accept': 'application/json' },
29
- });
30
- return await response.json();
26
+ const jsonFetch = async (url, timeout) => {
27
+ const controller = new AbortController();
28
+ const timer = setTimeout(() => controller.abort(), timeout);
29
+ try {
30
+ const response = await fetch(url, {
31
+ headers: { 'Accept': 'application/json' },
32
+ signal: controller.signal,
33
+ });
34
+ if (!response.ok) {
35
+ throw new Error(`HTTP error ${response.status} loading context ${url}`);
36
+ }
37
+ return await response.json();
38
+ }
39
+ finally {
40
+ clearTimeout(timer);
41
+ }
31
42
  };
32
43
  const mergeContexts = (definitions) => {
33
44
  const mergePair = (a, b) => {
@@ -53,49 +64,78 @@ const mergeContexts = (definitions) => {
53
64
  return currentContext;
54
65
  };
55
66
  const urlCache = new Map();
56
- async function loadContext(context) {
57
- const walk = async (definition, refChain) => {
67
+ const resolveUrl = (url, baseUrl) => {
68
+ try {
69
+ return new URL(url, baseUrl).toString();
70
+ }
71
+ catch (_a) {
72
+ return url;
73
+ }
74
+ };
75
+ /**
76
+ * Loads a context without merging its entries. Remote references are replaced by their contents,
77
+ * including the scoped contexts of term definitions, which are modified in place.
78
+ */
79
+ async function loadContextEntries(context, options = {}) {
80
+ const { requestTimeout = 10000 } = options;
81
+ const walk = async (definition, refChain, baseUrl) => {
58
82
  for (const [key, value] of Object.entries(definition)) {
59
83
  if (key === '@context') {
84
+ const entries = await load(value, refChain, baseUrl);
60
85
  // @ts-ignore
61
- definition[key] = await load(value, refChain);
86
+ definition[key] = entries.length === 1 ? entries[0] : entries;
62
87
  }
63
88
  else if (typeof value === 'object' && value !== null) {
64
- await walk(value, refChain);
89
+ await walk(value, refChain, baseUrl);
65
90
  }
66
91
  }
67
92
  };
68
- const load = async (context, refChain) => {
69
- if (context === null || typeof context === 'undefined') {
70
- return {};
93
+ const load = async (context, refChain, baseUrl) => {
94
+ if (context === undefined) {
95
+ return [];
96
+ }
97
+ if (context === null) {
98
+ return [null];
71
99
  }
72
100
  if (Array.isArray(context)) {
73
- // fetch and merge
74
- const contextEntries = await Promise.all(context.map(e => load(e, refChain)));
75
- return mergeContexts(contextEntries);
101
+ return (await Promise.all(context.map(e => load(e, refChain, baseUrl)))).flat();
76
102
  }
77
- else if (typeof context === 'object') {
78
- await walk(context, refChain);
79
- return context;
103
+ if (typeof context === 'object') {
104
+ await walk(context, refChain, baseUrl);
105
+ return [context];
80
106
  }
81
- else {
82
- if (refChain === null || refChain === void 0 ? void 0 : refChain.includes(context)) {
83
- throw new Error('Circular dependencies found: ' + refChain.join(' -> ') + ' -> ' + context);
84
- }
85
- const newRefChain = Array.isArray(refChain) ? refChain === null || refChain === void 0 ? void 0 : refChain.slice() : [];
86
- newRefChain.push(context);
87
- if (!urlCache.has(context)) {
88
- urlCache.set(context, jsonFetch(context).then(obj => load(obj['@context'], newRefChain)));
89
- }
90
- return urlCache.get(context);
107
+ const url = resolveUrl(context, baseUrl);
108
+ if (refChain === null || refChain === void 0 ? void 0 : refChain.includes(url)) {
109
+ throw new Error('Circular dependencies found: ' + refChain.join(' -> ') + ' -> ' + url);
110
+ }
111
+ const newRefChain = [...(refChain !== null && refChain !== void 0 ? refChain : []), url];
112
+ if (!urlCache.has(url)) {
113
+ // Relative references inside a remote context are resolved against that context's own URL
114
+ const request = jsonFetch(url, requestTimeout).then(async (obj) => {
115
+ const entries = await load(obj['@context'], newRefChain, url);
116
+ // @base is ignored in remote contexts
117
+ return entries.map(entry => {
118
+ if (!entry) {
119
+ return entry;
120
+ }
121
+ const { '@base': _, ...loaded } = entry;
122
+ return loaded;
123
+ });
124
+ });
125
+ // Failures are not cached, so that they can be retried
126
+ request.catch(() => urlCache.delete(url));
127
+ urlCache.set(url, request);
91
128
  }
129
+ return urlCache.get(url);
92
130
  };
93
- if (typeof context === 'object' && context !== null && '@context' in context) {
94
- return load(context['@context']);
95
- }
96
- else {
97
- return load(context);
98
- }
131
+ return load(context, undefined, options.baseUrl);
132
+ }
133
+ async function loadContext(context, options = {}) {
134
+ const unwrapped = typeof context === 'object' && context !== null && '@context' in context
135
+ ? context['@context']
136
+ : context;
137
+ const entries = await loadContextEntries(unwrapped, options);
138
+ return mergeContexts(entries.map(entry => entry !== null && entry !== void 0 ? entry : {}));
99
139
  }
100
140
 
101
141
  const ns = (base) => (local) => `${base}${local}`;
@@ -120,9 +160,106 @@ const descriptionPredicates = [
120
160
  RDFS('comment'),
121
161
  ];
122
162
 
163
+ // Limits how many HTTP requests run at once, across all lookups
164
+ let active = 0;
165
+ const waiting = [];
166
+ function startWaiting() {
167
+ while (waiting.length && active < waiting[0].limit) {
168
+ active++;
169
+ waiting.shift().start();
170
+ }
171
+ }
172
+ /**
173
+ * Runs a task holding one request slot. The task must pass the signal to fetch() and include reading
174
+ * the response body, so that the slot is held (and the timeout applies) until the request is done.
175
+ */
176
+ async function withRequestSlot(task, { limit, timeout, priority = false }) {
177
+ await new Promise(start => {
178
+ // Priority requests queue up behind earlier priority ones, ahead of everything else
179
+ const firstNormal = priority ? waiting.findIndex(entry => !entry.priority) : -1;
180
+ waiting.splice(firstNormal < 0 ? waiting.length : firstNormal, 0, { limit: Math.max(1, limit), priority, start });
181
+ startWaiting();
182
+ });
183
+ const controller = new AbortController();
184
+ const timer = setTimeout(() => controller.abort(), timeout);
185
+ try {
186
+ return await task(controller.signal);
187
+ }
188
+ finally {
189
+ clearTimeout(timer);
190
+ active--;
191
+ startWaiting();
192
+ }
193
+ }
194
+
195
+ // Collects URIs into one DESCRIBE query per endpoint. A batch is sent when the first of these happens:
196
+ // it is full, no earlier lookup is pending (so nothing else can join soon), or MAX_WAIT has passed.
197
+ const MAX_WAIT = 500;
198
+ const batches = {};
199
+ let pendingLookups = 0;
200
+ let idleCheckScheduled = false;
201
+ // Deferred, so that URIs arriving in the same burst end up in the same batch
202
+ function scheduleIdleCheck() {
203
+ if (idleCheckScheduled) {
204
+ return;
205
+ }
206
+ idleCheckScheduled = true;
207
+ setTimeout(() => {
208
+ idleCheckScheduled = false;
209
+ if (!pendingLookups) {
210
+ Object.values(batches).forEach(batch => batch.send());
211
+ }
212
+ }, 0);
213
+ }
214
+ /** Tracks the lookup stages that run before SPARQL, and can therefore still feed a batch */
215
+ async function trackLookup(lookup) {
216
+ pendingLookups++;
217
+ try {
218
+ return await lookup();
219
+ }
220
+ finally {
221
+ pendingLookups--;
222
+ scheduleIdleCheck();
223
+ }
224
+ }
225
+ // Characters not allowed inside <...> in SPARQL: one such URI would break the query for its whole batch
226
+ const isQueryableIri = (uri) => /^[a-z][a-z0-9+.-]*:[^\u0000- <>"{}|^`\\]*$/i.test(uri);
227
+ function createBatch(endpoint, sendQuery) {
228
+ const uris = [];
229
+ let resolve;
230
+ const result = new Promise(r => resolve = r);
231
+ const batch = {
232
+ uris,
233
+ result,
234
+ send() {
235
+ clearTimeout(timer);
236
+ delete batches[endpoint];
237
+ resolve(sendQuery(`DESCRIBE ${uris.map(uri => `<${uri}>`).join(' ')}`));
238
+ },
239
+ };
240
+ const timer = setTimeout(batch.send, MAX_WAIT);
241
+ return batch;
242
+ }
243
+ /** Resolves with the response to the query that included this URI */
244
+ function describeInBatch(endpoint, uri, batchSize, sendQuery) {
245
+ var _a;
246
+ const batch = (_a = batches[endpoint]) !== null && _a !== void 0 ? _a : (batches[endpoint] = createBatch(endpoint, sendQuery));
247
+ batch.uris.push(uri);
248
+ if (batch.uris.length >= batchSize) {
249
+ batch.send();
250
+ }
251
+ else {
252
+ scheduleIdleCheck();
253
+ }
254
+ return batch.result;
255
+ }
256
+
123
257
  const defaultFetchResourceOptions = {
124
258
  labelPredicates,
125
259
  descriptionPredicates,
260
+ maxConcurrentRequests: 6,
261
+ sparqlBatchSize: 50,
262
+ requestTimeout: 10000,
126
263
  };
127
264
  const fetchResourceCache = {};
128
265
  const requestCache = {};
@@ -202,8 +339,11 @@ function parseTurtle(text, baseIRI, contentType) {
202
339
  });
203
340
  }
204
341
  async function parseJsonLd(text, baseIRI) {
205
- const jsonldMod = await import('jsonld');
206
- if (!jsonldMod) {
342
+ var _a;
343
+ // jsonld is CommonJS: a dynamic import usually exposes it as the default export
344
+ const imported = await import('jsonld');
345
+ const jsonldMod = (_a = imported.default) !== null && _a !== void 0 ? _a : imported;
346
+ if (!(jsonldMod === null || jsonldMod === void 0 ? void 0 : jsonldMod.toRDF)) {
207
347
  throw new Error('jsonld peer dependency is not available');
208
348
  }
209
349
  const doc = JSON.parse(text);
@@ -222,39 +362,41 @@ async function parseRdfXml(text, baseIRI) {
222
362
  });
223
363
  }
224
364
  const toArray = (val) => !val ? [] : Array.isArray(val) ? val : [val];
225
- const getSparqlQuery = (uri) => `DESCRIBE <${uri}>`;
226
- const fetchAndParse = async (fetchFn, baseIRI) => {
227
- var _a;
228
- let response;
365
+ const fetchAndParse = async (url, init, baseIRI, options, priority = false) => {
229
366
  try {
230
- response = await fetchFn();
231
- if (!response.ok) {
367
+ // The slot covers reading the body, but not parsing it
368
+ const received = await withRequestSlot(async (signal) => {
369
+ var _a;
370
+ const response = await fetch(url, { ...init, signal });
371
+ if (!response.ok) {
372
+ return null;
373
+ }
374
+ return {
375
+ contentType: ((_a = response.headers.get('content-type')) === null || _a === void 0 ? void 0 : _a.split(';')[0].trim()) || 'text/turtle',
376
+ text: await response.text(),
377
+ };
378
+ }, { limit: options.maxConcurrentRequests, timeout: options.requestTimeout, priority });
379
+ if (!received) {
232
380
  return null;
233
381
  }
234
- }
235
- catch (_b) {
236
- return null;
237
- }
238
- const contentType = ((_a = response.headers.get('content-type')) === null || _a === void 0 ? void 0 : _a.split(';')[0].trim()) || 'text/turtle';
239
- const text = await response.text();
240
- try {
382
+ const { contentType, text } = received;
241
383
  if (N3_CONTENT_TYPES.has(contentType)) {
242
- return parseTurtle(text, baseIRI, contentType);
384
+ return await parseTurtle(text, baseIRI, contentType);
243
385
  }
244
386
  if (contentType === 'application/ld+json') {
245
- return parseJsonLd(text, baseIRI);
387
+ return await parseJsonLd(text, baseIRI);
246
388
  }
247
389
  if (contentType === 'application/rdf+xml') {
248
- return parseRdfXml(text, baseIRI);
390
+ return await parseRdfXml(text, baseIRI);
249
391
  }
250
392
  }
251
- catch (_c) {
393
+ catch (_a) {
252
394
  }
253
395
  return null;
254
396
  };
255
- const fetchAndParseDocument = (docUrl, fetchFn, baseIRI = docUrl) => {
397
+ const fetchAndParseDocument = (docUrl, options, baseIRI = docUrl) => {
256
398
  if (!(docUrl in requestCache)) {
257
- requestCache[docUrl] = fetchAndParse(fetchFn, baseIRI);
399
+ requestCache[docUrl] = fetchAndParse(docUrl, { headers: { 'Accept': ACCEPT_HEADER } }, baseIRI, options);
258
400
  }
259
401
  return requestCache[docUrl];
260
402
  };
@@ -281,17 +423,20 @@ const findResourceInStore = async (storePromise, uri, options) => {
281
423
  }
282
424
  return null;
283
425
  };
284
- const actualFetchResource = async (uri, options) => {
426
+ // Direct dereferencing and RAINBOW proxies: one request per URI (or per document)
427
+ const lookupByRequest = async (uri, options) => {
285
428
  const docUrl = uri.includes('#') ? uri.split('#')[0] : uri;
286
- // 1. Direct (cached by document URL so hash siblings share one request).
429
+ // 1. Direct, only for HTTP(S) URIs (cached by document URL so hash siblings share one request).
287
430
  // On an https:// page, an http:// URI is tried as https:// first (the http:// request would be blocked).
288
431
  let result = null;
289
- const httpsDocUrl = toHttpsIfMixedContent(docUrl);
290
- if (httpsDocUrl) {
291
- result = await findResourceInStore(fetchAndParseDocument(httpsDocUrl, () => fetch(httpsDocUrl, { headers: { 'Accept': ACCEPT_HEADER } }), docUrl), uri, options);
292
- }
293
- if (!result) {
294
- result = await findResourceInStore(fetchAndParseDocument(docUrl, () => fetch(docUrl, { headers: { 'Accept': ACCEPT_HEADER } })), uri, options);
432
+ if (/^https?:/i.test(uri)) {
433
+ const httpsDocUrl = toHttpsIfMixedContent(docUrl);
434
+ if (httpsDocUrl) {
435
+ result = await findResourceInStore(fetchAndParseDocument(httpsDocUrl, options, docUrl), uri, options);
436
+ }
437
+ if (!result) {
438
+ result = await findResourceInStore(fetchAndParseDocument(docUrl, options), uri, options);
439
+ }
295
440
  }
296
441
  // 2. Rainbow proxies (in order) — not supported for hash URIs
297
442
  const isHashUri = uri.includes('#');
@@ -301,20 +446,23 @@ const actualFetchResource = async (uri, options) => {
301
446
  }
302
447
  const rainbowURL = new URL(instance);
303
448
  rainbowURL.searchParams.set('uri', uri);
304
- const rainbowUrlStr = rainbowURL.toString();
305
- result = await findResourceInStore(fetchAndParseDocument(rainbowUrlStr, () => fetch(rainbowUrlStr, { headers: { 'Accept': ACCEPT_HEADER } })), uri, options);
449
+ result = await findResourceInStore(fetchAndParseDocument(rainbowURL.toString(), options), uri, options);
306
450
  }
307
- // 3. SPARQL endpoints (in order) — each DESCRIBE is unique per URI, no request cache
451
+ return result;
452
+ };
453
+ const sparqlQuery = (endpoint, options) => (query) => fetchAndParse(endpoint, {
454
+ method: 'POST',
455
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'text/turtle, application/n-triples' },
456
+ body: new URLSearchParams({ query }).toString(),
457
+ }, endpoint, options, true);
458
+ const actualFetchResource = async (uri, options) => {
459
+ let result = await trackLookup(() => lookupByRequest(uri, options));
460
+ // 3. SPARQL endpoints (in order), batching URIs into shared DESCRIBE queries
308
461
  for (const endpoint of [...toArray(options.fallbackSparqlEndpoints), ...toArray(options.fallbackSparqlEndpoint)]) {
309
- if (result) {
462
+ if (result || !isQueryableIri(uri)) {
310
463
  break;
311
464
  }
312
- const formBody = new URLSearchParams({ query: getSparqlQuery(uri) });
313
- result = await findResourceInStore(fetchAndParse(() => fetch(endpoint, {
314
- method: 'POST',
315
- headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'text/turtle, application/n-triples' },
316
- body: formBody.toString(),
317
- }), uri), uri, options);
465
+ result = await findResourceInStore(describeInBatch(endpoint, uri, options.sparqlBatchSize, sparqlQuery(endpoint, options)), uri, options);
318
466
  }
319
467
  if (!result) {
320
468
  throw new Error(`No label data found for <${uri}>`);
@@ -329,175 +477,253 @@ async function fetchResource(uri, options = {}) {
329
477
  return fetchResourceCache[uri];
330
478
  }
331
479
 
480
+ const has = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key);
481
+ function pushContext(stack, context) {
482
+ if (Array.isArray(context)) {
483
+ return context.reduce(pushContext, stack);
484
+ }
485
+ if (context === null) {
486
+ return [];
487
+ }
488
+ return typeof context === 'object' ? [...stack, context] : stack;
489
+ }
490
+ // Each @base is resolved against the previous one, starting at the document's base URL
491
+ function resolveBase(stack, baseUrl) {
492
+ return stack.reduce((base, context) => {
493
+ if (!has(context, '@base')) {
494
+ return base;
495
+ }
496
+ const value = context['@base'];
497
+ if (value === null) {
498
+ return null;
499
+ }
500
+ try {
501
+ return new URL(value, base !== null && base !== void 0 ? base : undefined).toString();
502
+ }
503
+ catch (_a) {
504
+ return null;
505
+ }
506
+ }, baseUrl);
507
+ }
508
+ // Innermost value of a context entry; undefined if no context in the stack declares it
509
+ function findEntry(stack, key) {
510
+ for (let i = stack.length - 1; i >= 0; i--) {
511
+ if (has(stack[i], key)) {
512
+ return stack[i][key];
513
+ }
514
+ }
515
+ return undefined;
516
+ }
517
+ /** Term definition in object form; null if the term is explicitly unmapped, undefined if unknown */
518
+ function findTerm(term, stack) {
519
+ const entry = findEntry(stack, term);
520
+ if (typeof entry === 'string') {
521
+ return { '@id': entry };
522
+ }
523
+ if (entry && typeof entry === 'object') {
524
+ return entry['@id'] === null ? null : entry;
525
+ }
526
+ return entry === null ? null : undefined;
527
+ }
528
+ /** The keyword (`@id`, `@type`...) that a key stands for, either directly or through an alias */
529
+ function asKeyword(key, stack) {
530
+ var _a;
531
+ if (key.startsWith('@')) {
532
+ return key;
533
+ }
534
+ const id = (_a = findTerm(key, stack)) === null || _a === void 0 ? void 0 : _a['@id'];
535
+ return (id === null || id === void 0 ? void 0 : id.startsWith('@')) ? id : null;
536
+ }
537
+ function expandIri(value, stack, options, seen = new Set()) {
538
+ var _a, _b, _c;
539
+ if (value.startsWith('@')) {
540
+ return value;
541
+ }
542
+ const expandTerm = (term) => expandIri(term, stack, { vocab: true }, seen);
543
+ if (options.vocab && !seen.has(value)) {
544
+ const definition = findTerm(value, stack);
545
+ if (definition === null) {
546
+ return null;
547
+ }
548
+ const id = (_a = definition === null || definition === void 0 ? void 0 : definition['@reverse']) !== null && _a !== void 0 ? _a : definition === null || definition === void 0 ? void 0 : definition['@id'];
549
+ if (id && id !== value) {
550
+ seen.add(value);
551
+ return expandTerm(id);
552
+ }
553
+ }
554
+ const colon = value.indexOf(':');
555
+ if (colon > -1) {
556
+ const prefix = value.substring(0, colon);
557
+ const localPart = value.substring(colon + 1);
558
+ if (prefix === '_') {
559
+ return null;
560
+ }
561
+ if (!localPart.startsWith('//') && !seen.has(prefix) && findTerm(prefix, stack)) {
562
+ const expandedPrefix = expandIri(prefix, stack, { vocab: true }, new Set(seen));
563
+ if (expandedPrefix) {
564
+ return `${expandedPrefix}${localPart}`;
565
+ }
566
+ }
567
+ if (/^[a-z][a-z0-9+.-]*:/i.test(value)) {
568
+ return value;
569
+ }
570
+ }
571
+ if (options.vocab) {
572
+ const vocab = findEntry(stack, '@vocab');
573
+ if (vocab) {
574
+ const expandedVocab = vocab.includes(':') ? vocab : ((_c = (_b = findTerm(vocab, stack)) === null || _b === void 0 ? void 0 : _b['@id']) !== null && _c !== void 0 ? _c : vocab);
575
+ return `${expandedVocab}${value}`;
576
+ }
577
+ }
578
+ if (options.base) {
579
+ const base = resolveBase(stack, options.baseUrl);
580
+ try {
581
+ return base ? new URL(value, base).toString() : null;
582
+ }
583
+ catch (_d) {
584
+ return null;
585
+ }
586
+ }
587
+ return null;
588
+ }
589
+
332
590
  const defaultAugmentOptions = {
333
591
  replaceElements: true,
334
592
  ...defaultFetchResourceOptions,
335
593
  };
336
- function createPropertiesTable(feature, container, options = {
594
+ const defaultTableOptions = {
337
595
  propertiesField: 'properties',
338
- }) {
339
- const createLevel = (parent, value, addHeaders = false) => {
340
- if (Array.isArray(value)) {
341
- for (const entry of value) {
342
- const newElem = createLevel(parent, entry);
343
- newElem.classList.add('array-entry');
596
+ maxDepth: 15,
597
+ maxElements: 100,
598
+ };
599
+ // Never cut by maxElements, since augment() needs them (e.g. for type-scoped contexts). Contexts are
600
+ // not known when rendering, so only the usual aliases of @id and @type can be recognized.
601
+ const ALWAYS_SHOWN = new Set(['@id', '@type', 'id', 'type']);
602
+ const RDF_TYPE = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type';
603
+ const plural = (count, singular, pluralForm = `${singular}s`) => `${count} ${count === 1 ? singular : pluralForm}`;
604
+ const isObject = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
605
+ // {"@list": [...]} and {"@set": [...]} are displayed as plain arrays
606
+ const unwrapContainer = (value) => {
607
+ if (isObject(value)) {
608
+ const keys = Object.keys(value);
609
+ if (keys.length === 1 && (keys[0] === '@list' || keys[0] === '@set')) {
610
+ return value[keys[0]];
611
+ }
612
+ }
613
+ return value;
614
+ };
615
+ // An object holding nothing but @graph (and possibly @context) just wraps its contents, typically to
616
+ // have a top-level array next to @context. With anything else, as in a named graph, @graph has meaning.
617
+ const isGraphWrapper = (value) => isObject(value) && '@graph' in value && Object.keys(value).every(k => k === '@graph' || k === '@context');
618
+ const appendSpan = (parent, className, text) => {
619
+ const span = document.createElement('span');
620
+ span.classList.add(className);
621
+ span.textContent = text;
622
+ parent.appendChild(span);
623
+ return span;
624
+ };
625
+ // @context entries found in the data, kept out of the DOM for augment() to apply. Each table has the
626
+ // ones to apply to it in order: its own, preceded by those of any @graph wrappers it replaced.
627
+ const embeddedContexts = new WeakMap();
628
+ function createPropertiesTable(feature, container, options = {}) {
629
+ const { propertiesField, maxDepth, maxElements } = { ...defaultTableOptions, ...options };
630
+ const createLevel = (parent, rawValue, depth, addHeaders = false, wrapperContexts = []) => {
631
+ const value = unwrapContainer(rawValue);
632
+ if (isGraphWrapper(value)) {
633
+ const contexts = '@context' in value ? [...wrapperContexts, value['@context']] : wrapperContexts;
634
+ createLevel(parent, value['@graph'], depth, addHeaders, contexts);
635
+ return;
636
+ }
637
+ if (isObject(value) && '@value' in value) {
638
+ // Value object: a single literal, plus its language or datatype
639
+ createLevel(parent, value['@value'], depth);
640
+ for (const [keyword, className] of [['@language', 'literal-language'], ['@type', 'literal-datatype']]) {
641
+ if (keyword in value) {
642
+ appendSpan(parent, className, String(value[keyword]));
643
+ }
344
644
  }
345
- return parent;
346
- }
347
- else if (value === null || typeof value === 'undefined' || typeof value !== 'object') {
348
- const span = document.createElement('span');
349
- span.classList.add('literal-value');
350
- span.textContent = '' + value;
351
- parent.appendChild(span);
352
- return span;
353
- }
354
- else {
355
- const table = document.createElement('table');
356
- table.classList.add('object-table');
357
- if (addHeaders) {
358
- table.innerHTML = '<thead><tr><th>Property</th><th>Value</th></tr></thead>';
645
+ return;
646
+ }
647
+ if (value === null || typeof value !== 'object') {
648
+ appendSpan(parent, 'literal-value', '' + value);
649
+ return;
650
+ }
651
+ const isArray = Array.isArray(value);
652
+ const entries = isArray
653
+ ? value.map((v, i) => [String(i), v])
654
+ : Object.entries(value).filter(([k]) => k !== '@context');
655
+ if (isArray && !entries.length) {
656
+ return;
657
+ }
658
+ if (depth > maxDepth && entries.length) {
659
+ appendSpan(parent, 'truncated-value', isArray ? plural(entries.length, 'item') : plural(entries.length, 'property', 'properties'));
660
+ return;
661
+ }
662
+ const table = document.createElement('table');
663
+ table.classList.add(isArray ? 'array-table' : 'object-table');
664
+ const contexts = !isArray && '@context' in value ? [...wrapperContexts, value['@context']] : wrapperContexts;
665
+ if (contexts.length) {
666
+ embeddedContexts.set(table, contexts);
667
+ }
668
+ if (addHeaders && !isArray) {
669
+ table.innerHTML = '<thead><tr><th>Property</th><th>Value</th></tr></thead>';
670
+ }
671
+ const tbody = document.createElement('tbody');
672
+ const addCell = (row, ...classNames) => {
673
+ const cell = document.createElement('td');
674
+ cell.classList.add(...classNames);
675
+ row.appendChild(cell);
676
+ return cell;
677
+ };
678
+ let remaining = maxElements - (isArray ? 0 : entries.filter(([k]) => ALWAYS_SHOWN.has(k)).length);
679
+ const shown = entries.filter(([k]) => (!isArray && ALWAYS_SHOWN.has(k)) || remaining-- > 0);
680
+ for (const [k, v] of shown) {
681
+ const row = document.createElement('tr');
682
+ if (isArray) {
683
+ createLevel(addCell(row, 'array-value', 'array-entry'), v, depth + 1);
359
684
  }
360
- const tbody = document.createElement('tbody');
361
- Object.entries(value).forEach(([k, v]) => {
362
- const row = document.createElement('tr');
363
- const keyCell = document.createElement('td');
364
- keyCell.classList.add('object-property');
685
+ else {
686
+ const keyCell = addCell(row, 'object-property');
365
687
  keyCell.setAttribute('data-property', k);
366
688
  keyCell.textContent = k;
367
- row.appendChild(keyCell);
368
- const valueCell = document.createElement('td');
369
- valueCell.classList.add('object-value');
370
- createLevel(valueCell, v);
371
- row.appendChild(valueCell);
372
- tbody.appendChild(row);
373
- });
374
- table.appendChild(tbody);
375
- parent.appendChild(table);
376
- return table;
689
+ createLevel(addCell(row, 'object-value'), v, depth + 1);
690
+ }
691
+ tbody.appendChild(row);
377
692
  }
693
+ const hidden = entries.length - shown.length;
694
+ if (hidden) {
695
+ const row = document.createElement('tr');
696
+ const cell = addCell(row, isArray ? 'array-value' : 'truncated-cell');
697
+ if (!isArray) {
698
+ cell.colSpan = 2;
699
+ }
700
+ appendSpan(cell, 'truncated-value', isArray
701
+ ? plural(hidden, 'more item')
702
+ : plural(hidden, 'more property', 'more properties'));
703
+ tbody.appendChild(row);
704
+ }
705
+ table.appendChild(tbody);
706
+ parent.appendChild(table);
378
707
  };
379
708
  const wrapper = document.createElement('div');
380
709
  wrapper.classList.add('object-properties');
381
710
  container.appendChild(wrapper);
382
- if (options.propertiesField) {
383
- createLevel(wrapper, feature[options.propertiesField], true);
384
- }
385
- else {
386
- createLevel(wrapper, feature, true);
387
- }
711
+ createLevel(wrapper, propertiesField ? feature[propertiesField] : feature, 1, true);
388
712
  }
389
713
  async function augment(rootElem, context, options = {}) {
390
714
  const mergedOptions = { ...defaultAugmentOptions, ...options };
391
- const resolveTerm = (term, contextStack, useVocab = true, useBase = false) => {
392
- if (term.indexOf('://') !== -1) {
393
- return { '@id': term };
394
- }
395
- let closestVocab = null;
396
- let closestBase = null;
397
- for (let i = contextStack.length - 1; i >= 0; i--) {
398
- if (term in contextStack[i]) {
399
- let resolvedTerm = contextStack[i][term];
400
- let resolvedId;
401
- if (resolvedTerm === null || typeof resolvedTerm === 'undefined' || typeof resolvedTerm === 'boolean'
402
- || Array.isArray(resolvedTerm)) {
403
- continue;
404
- }
405
- if (typeof resolvedTerm === 'string') {
406
- if (resolvedTerm === '@type') {
407
- return { '@id': 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type' };
408
- }
409
- resolvedId = resolvedTerm;
410
- resolvedTerm = { '@id': resolvedTerm };
411
- }
412
- else if (typeof resolvedTerm === 'object' && '@id' in resolvedTerm && typeof resolvedTerm['@id'] === 'string') {
413
- resolvedId = resolvedTerm['@id'];
414
- }
415
- else {
416
- continue;
417
- }
418
- const idx = resolvedId.indexOf(':');
419
- if (idx > -1) {
420
- const prefix = resolvedId.substring(0, idx);
421
- const localPart = resolvedId.substring(idx + 1);
422
- if (localPart.startsWith('//')) {
423
- // Full URI -> return
424
- return resolvedTerm;
425
- }
426
- const resolvedPrefix = resolveTerm(prefix, contextStack);
427
- if (resolvedPrefix !== null && '@id' in resolvedPrefix && typeof resolvedPrefix['@id'] === 'string') {
428
- // Prefix found and resolved
429
- resolvedTerm['@id'] = `${resolvedPrefix['@id']}${localPart}`;
430
- }
431
- return resolvedTerm;
432
- }
433
- }
434
- if (closestVocab === null && contextStack[i]['@vocab']) {
435
- closestVocab = contextStack[i]['@vocab'];
436
- }
437
- if (closestBase === null && contextStack[i]['@base']) {
438
- closestBase = contextStack[i]['@base'];
439
- }
440
- }
441
- if (term.indexOf(':') === -1) {
442
- if (useVocab && closestVocab) {
443
- return { '@id': `${closestVocab}${term}` };
444
- }
445
- if (useBase && closestBase) {
446
- return { '@id': `${closestBase}${term}` };
447
- }
448
- }
449
- else {
450
- const idx = term.indexOf(':');
451
- const prefix = term.substring(0, idx);
452
- const localPart = term.substring(idx + 1);
453
- if (!localPart.startsWith('//')) {
454
- const resolvedPrefix = resolveTerm(prefix, contextStack);
455
- if (resolvedPrefix !== null && '@id' in resolvedPrefix && typeof resolvedPrefix['@id'] === 'string') {
456
- return { '@id': `${resolvedPrefix['@id']}${localPart}` };
457
- }
458
- }
459
- }
460
- return null;
461
- };
462
- const findPropertyChildren = (elem) => {
463
- const walker = document.createTreeWalker(elem, NodeFilter.SHOW_ELEMENT, {
464
- acceptNode(node) {
465
- const nodeElem = node;
466
- if (node !== elem && nodeElem.classList.contains('object-value')) {
467
- return NodeFilter.FILTER_REJECT;
468
- }
469
- if (nodeElem.classList.contains('object-property')) {
470
- return NodeFilter.FILTER_ACCEPT;
471
- }
472
- return NodeFilter.FILTER_SKIP;
473
- },
474
- });
475
- const result = [];
476
- let cur;
477
- while ((cur = walker.nextNode())) {
478
- result.push(cur);
715
+ const { baseUrl } = mergedOptions;
716
+ // Object tables, and array tables that have contexts of their own
717
+ const isNode = (elem) => elem.classList.contains('object-table') || embeddedContexts.has(elem);
718
+ // Outermost such tables below an element (looking through other arrays and wrappers)
719
+ const findTables = (elem) => Array.from(elem.children).flatMap(child => isNode(child) ? [child] : findTables(child));
720
+ // Literal values of a cell, not including those that belong to nested objects
721
+ const findLiterals = (elem) => Array.from(elem.children).flatMap(child => {
722
+ if (child.classList.contains('literal-value')) {
723
+ return [child];
479
724
  }
480
- return result;
481
- };
482
- const findLiteralChildren = (elem) => {
483
- const result = [];
484
- const walker = document.createTreeWalker(elem, NodeFilter.SHOW_ELEMENT, {
485
- acceptNode(node) {
486
- const nodeElem = node;
487
- if (nodeElem.classList.contains('object-property') || nodeElem.classList.contains('object-value')) {
488
- return NodeFilter.FILTER_REJECT;
489
- }
490
- if (nodeElem.classList.contains('literal-value')) {
491
- result.push(nodeElem);
492
- return NodeFilter.FILTER_REJECT;
493
- }
494
- return NodeFilter.FILTER_SKIP;
495
- },
496
- });
497
- while (walker.nextNode()) {
498
- }
499
- return result;
500
- };
725
+ return child.classList.contains('object-table') ? [] : findLiterals(child);
726
+ });
501
727
  const updateElement = (elem, resourceUri, replaceElements = true) => {
502
728
  elem.setAttribute('data-uri', resourceUri);
503
729
  elem.classList.add('resource-loading');
@@ -536,41 +762,106 @@ async function augment(rootElem, context, options = {}) {
536
762
  elem.appendChild(link);
537
763
  }
538
764
  };
539
- const augmentInner = (elem, contextStack) => {
765
+ const linkLiterals = (valueElem, stack, expandOptions) => {
766
+ for (const literalElem of findLiterals(valueElem)) {
767
+ const iri = expandIri(literalElem.textContent.trim(), stack, { ...expandOptions, baseUrl });
768
+ if (iri && !iri.startsWith('@')) {
769
+ updateElement(literalElem, iri, mergedOptions.replaceElements);
770
+ }
771
+ }
772
+ };
773
+ // The stack with an embedded context on top, if it can be loaded
774
+ const pushEmbedded = async (stack, context) => {
775
+ try {
776
+ // Loading modifies the context, which belongs to the caller's data
777
+ const copy = JSON.parse(JSON.stringify(context));
778
+ const entries = await loadContextEntries(copy, { baseUrl, requestTimeout: mergedOptions.requestTimeout });
779
+ return entries.reduce(pushContext, stack);
780
+ }
781
+ catch (e) {
782
+ console.warn(`Error loading embedded context: ${e}`, { cause: e });
783
+ return stack;
784
+ }
785
+ };
786
+ const augmentNode = async (table, inheritedStack) => {
540
787
  var _a;
541
- const propElems = findPropertyChildren(elem);
542
- for (const propElem of propElems) {
543
- let propertyName = null;
544
- propertyName = propElem.getAttribute('data-property');
545
- if (!propertyName) {
546
- propertyName = propElem.textContent.trim();
788
+ let stack = inheritedStack;
789
+ // Only waits when there is something to load
790
+ for (const context of (_a = embeddedContexts.get(table)) !== null && _a !== void 0 ? _a : []) {
791
+ stack = await pushEmbedded(stack, context);
792
+ }
793
+ if (table.classList.contains('array-table')) {
794
+ await Promise.all(findTables(table).map(child => augmentNode(child, stack)));
795
+ return;
796
+ }
797
+ const children = [];
798
+ const rows = Array.from(table.querySelectorAll(':scope > tbody > tr')).flatMap(row => {
799
+ const propElem = row.querySelector(':scope > .object-property');
800
+ if (!propElem) {
801
+ return [];
547
802
  }
548
- const resolvedProperty = resolveTerm(propertyName, contextStack);
549
- let newContextStack = contextStack;
550
- const valueElem = (_a = propElem.parentElement) === null || _a === void 0 ? void 0 : _a.querySelector('.object-value');
551
- if (resolvedProperty && '@id' in resolvedProperty && typeof resolvedProperty['@id'] === 'string') {
552
- const propertyUri = resolvedProperty['@id'];
553
- updateElement(propElem, propertyUri, mergedOptions.replaceElements);
554
- if ('@context' in resolvedProperty) {
555
- newContextStack = [...contextStack, resolvedProperty['@context']];
803
+ return [{
804
+ propElem,
805
+ valueElem: row.querySelector(':scope > .object-value'),
806
+ name: propElem.getAttribute('data-property') || propElem.textContent.trim(),
807
+ }];
808
+ });
809
+ // Type-scoped contexts apply to this node only, in lexicographical order of the types
810
+ const types = rows
811
+ .filter(({ name }) => asKeyword(name, stack) === '@type')
812
+ .flatMap(({ valueElem }) => valueElem ? findLiterals(valueElem) : [])
813
+ .map(elem => elem.textContent.trim())
814
+ .sort();
815
+ const nodeStack = types.reduce((result, type) => {
816
+ var _a;
817
+ const scoped = (_a = findTerm(type, stack)) === null || _a === void 0 ? void 0 : _a['@context'];
818
+ return scoped === undefined ? result : pushContext(result, scoped);
819
+ }, stack);
820
+ for (const { propElem, valueElem, name } of rows) {
821
+ const keyword = asKeyword(name, nodeStack);
822
+ let childStack = stack;
823
+ if (keyword === '@type') {
824
+ // Types are resolved before applying their scoped contexts
825
+ if (valueElem) {
826
+ linkLiterals(valueElem, stack, { vocab: true, base: true });
556
827
  }
557
- if (resolvedProperty['@type'] === '@id' && valueElem) {
558
- const literalElems = findLiteralChildren(valueElem);
559
- literalElems.forEach(literalElem => {
560
- const resolvedLiteral = resolveTerm(literalElem.textContent.trim(), newContextStack, false, true);
561
- if (resolvedLiteral && '@id' in resolvedLiteral && typeof resolvedLiteral['@id'] === 'string') {
562
- const resourceUri = resolvedLiteral['@id'];
563
- updateElement(literalElem, resourceUri, mergedOptions.replaceElements);
564
- }
565
- });
828
+ updateElement(propElem, RDF_TYPE, mergedOptions.replaceElements);
829
+ }
830
+ else if (keyword === '@id') {
831
+ if (valueElem) {
832
+ linkLiterals(valueElem, nodeStack, { base: true });
833
+ }
834
+ }
835
+ else if (keyword) {
836
+ // Other keywords (@graph, @reverse, @nest...) keep the current context
837
+ childStack = nodeStack;
838
+ }
839
+ else {
840
+ const definition = findTerm(name, nodeStack);
841
+ const propertyUri = expandIri(name, nodeStack, { vocab: true });
842
+ if (propertyUri) {
843
+ updateElement(propElem, propertyUri, mergedOptions.replaceElements);
844
+ }
845
+ if ((definition === null || definition === void 0 ? void 0 : definition['@context']) !== undefined) {
846
+ childStack = pushContext(stack, definition['@context']);
847
+ }
848
+ const coercion = definition === null || definition === void 0 ? void 0 : definition['@type'];
849
+ if (valueElem && (coercion === '@id' || coercion === '@vocab')) {
850
+ const valueStack = (definition === null || definition === void 0 ? void 0 : definition['@context']) === undefined
851
+ ? nodeStack : pushContext(nodeStack, definition['@context']);
852
+ linkLiterals(valueElem, valueStack, { vocab: coercion === '@vocab', base: true });
566
853
  }
567
854
  }
568
855
  if (valueElem) {
569
- augmentInner(valueElem, newContextStack);
856
+ children.push(...findTables(valueElem).map(child => augmentNode(child, childStack)));
570
857
  }
571
858
  }
859
+ await Promise.all(children);
572
860
  };
573
- augmentInner(rootElem, [context]);
861
+ const rootStack = pushContext([], context !== null && context !== void 0 ? context : {});
862
+ const rootTables = isNode(rootElem)
863
+ ? [rootElem] : findTables(rootElem);
864
+ await Promise.all(rootTables.map(table => augmentNode(table, rootStack)));
574
865
  }
575
866
 
576
867
  const WGS84_EPSG_CODES = new Set([4326, 4979]);
@@ -781,7 +1072,8 @@ const POPUP_CSS = `
781
1072
  word-break: normal;
782
1073
  overflow-wrap: normal;
783
1074
  }
784
- .${POPUP_CLASS} .leaflet-popup-content .object-value {
1075
+ .${POPUP_CLASS} .leaflet-popup-content .object-value,
1076
+ .${POPUP_CLASS} .leaflet-popup-content .array-value {
785
1077
  min-width: 0;
786
1078
  max-width: none;
787
1079
  word-break: normal;
@@ -893,7 +1185,7 @@ function recenterOnResize(popup) {
893
1185
  });
894
1186
  }
895
1187
  async function createJsonLDGeoJSONLayer(L, data, options = {}) {
896
- const { ldContext, popupOptions = {}, augmentOptions = {}, onEachFeature: userOnEachFeature, coordRefSys: coordRefSysOverride, proj4: proj4Override, crsAttribution = true, ...geoJSONOptions } = options;
1188
+ const { ldContext, popupOptions = {}, augmentOptions = {}, baseUrl, maxDepth, maxElements, onEachFeature: userOnEachFeature, coordRefSys: coordRefSysOverride, proj4: proj4Override, crsAttribution = true, ...geoJSONOptions } = options;
897
1189
  let geoData = data;
898
1190
  const crsInfo = coordRefSysOverride
899
1191
  ? detectCrs({ coordRefSys: coordRefSysOverride })
@@ -923,7 +1215,10 @@ async function createJsonLDGeoJSONLayer(L, data, options = {}) {
923
1215
  if (!feature.properties || Object.keys(feature.properties).length === 0)
924
1216
  return;
925
1217
  const container = document.createElement('div');
926
- createPropertiesTable(feature, container);
1218
+ createPropertiesTable(feature, container, {
1219
+ ...(maxDepth !== undefined ? { maxDepth } : {}),
1220
+ ...(maxElements !== undefined ? { maxElements } : {}),
1221
+ });
927
1222
  injectPopupCss();
928
1223
  const className = [POPUP_CLASS, popupOptions.className].filter(Boolean).join(' ');
929
1224
  // Large default maxWidth: the popup adapts to the table's natural width; the CSS cap (a share
@@ -936,8 +1231,8 @@ async function createJsonLDGeoJSONLayer(L, data, options = {}) {
936
1231
  const contextsToMerge = [dataContext, ldContext].filter(v => v != null);
937
1232
  if (contextsToMerge.length > 0) {
938
1233
  const contextArg = contextsToMerge.length === 1 ? contextsToMerge[0] : contextsToMerge;
939
- loadContext(contextArg).then((resolvedContext) => {
940
- augment(container, resolvedContext, augmentOptions);
1234
+ loadContext(contextArg, { baseUrl }).then((resolvedContext) => {
1235
+ augment(container, resolvedContext, { baseUrl, ...augmentOptions });
941
1236
  });
942
1237
  }
943
1238
  },