@opengeospatial/jsonld-ui-utils 0.4.12 → 0.5.0

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,241 @@ 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
+ const appendSpan = (parent, className, text) => {
616
+ const span = document.createElement('span');
617
+ span.classList.add(className);
618
+ span.textContent = text;
619
+ parent.appendChild(span);
620
+ return span;
621
+ };
622
+ // @context entries found in the data, kept out of the DOM for augment() to apply
623
+ const embeddedContexts = new WeakMap();
624
+ function createPropertiesTable(feature, container, options = {}) {
625
+ const { propertiesField, maxDepth, maxElements } = { ...defaultTableOptions, ...options };
626
+ const createLevel = (parent, rawValue, depth, addHeaders = false) => {
627
+ const value = unwrapContainer(rawValue);
628
+ if (isObject(value) && '@value' in value) {
629
+ // Value object: a single literal, plus its language or datatype
630
+ createLevel(parent, value['@value'], depth);
631
+ for (const [keyword, className] of [['@language', 'literal-language'], ['@type', 'literal-datatype']]) {
632
+ if (keyword in value) {
633
+ appendSpan(parent, className, String(value[keyword]));
634
+ }
344
635
  }
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>';
636
+ return;
637
+ }
638
+ if (value === null || typeof value !== 'object') {
639
+ appendSpan(parent, 'literal-value', '' + value);
640
+ return;
641
+ }
642
+ const isArray = Array.isArray(value);
643
+ const entries = isArray
644
+ ? value.map((v, i) => [String(i), v])
645
+ : Object.entries(value).filter(([k]) => k !== '@context');
646
+ if (isArray && !entries.length) {
647
+ return;
648
+ }
649
+ if (depth > maxDepth && entries.length) {
650
+ appendSpan(parent, 'truncated-value', isArray ? plural(entries.length, 'item') : plural(entries.length, 'property', 'properties'));
651
+ return;
652
+ }
653
+ const table = document.createElement('table');
654
+ table.classList.add(isArray ? 'array-table' : 'object-table');
655
+ if (!isArray && '@context' in value) {
656
+ embeddedContexts.set(table, value['@context']);
657
+ }
658
+ if (addHeaders && !isArray) {
659
+ table.innerHTML = '<thead><tr><th>Property</th><th>Value</th></tr></thead>';
660
+ }
661
+ const tbody = document.createElement('tbody');
662
+ const addCell = (row, ...classNames) => {
663
+ const cell = document.createElement('td');
664
+ cell.classList.add(...classNames);
665
+ row.appendChild(cell);
666
+ return cell;
667
+ };
668
+ let remaining = maxElements - (isArray ? 0 : entries.filter(([k]) => ALWAYS_SHOWN.has(k)).length);
669
+ const shown = entries.filter(([k]) => (!isArray && ALWAYS_SHOWN.has(k)) || remaining-- > 0);
670
+ for (const [k, v] of shown) {
671
+ const row = document.createElement('tr');
672
+ if (isArray) {
673
+ createLevel(addCell(row, 'array-value', 'array-entry'), v, depth + 1);
359
674
  }
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');
675
+ else {
676
+ const keyCell = addCell(row, 'object-property');
365
677
  keyCell.setAttribute('data-property', k);
366
678
  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;
679
+ createLevel(addCell(row, 'object-value'), v, depth + 1);
680
+ }
681
+ tbody.appendChild(row);
682
+ }
683
+ const hidden = entries.length - shown.length;
684
+ if (hidden) {
685
+ const row = document.createElement('tr');
686
+ const cell = addCell(row, isArray ? 'array-value' : 'truncated-cell');
687
+ if (!isArray) {
688
+ cell.colSpan = 2;
689
+ }
690
+ appendSpan(cell, 'truncated-value', isArray
691
+ ? plural(hidden, 'more item')
692
+ : plural(hidden, 'more property', 'more properties'));
693
+ tbody.appendChild(row);
377
694
  }
695
+ table.appendChild(tbody);
696
+ parent.appendChild(table);
378
697
  };
379
698
  const wrapper = document.createElement('div');
380
699
  wrapper.classList.add('object-properties');
381
700
  container.appendChild(wrapper);
382
- if (options.propertiesField) {
383
- createLevel(wrapper, feature[options.propertiesField], true);
384
- }
385
- else {
386
- createLevel(wrapper, feature, true);
387
- }
701
+ createLevel(wrapper, propertiesField ? feature[propertiesField] : feature, 1, true);
388
702
  }
389
703
  async function augment(rootElem, context, options = {}) {
390
704
  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);
479
- }
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()) {
705
+ const { baseUrl } = mergedOptions;
706
+ // Outermost object tables below an element (looking through arrays and wrappers)
707
+ const findTables = (elem) => Array.from(elem.children).flatMap(child => child.classList.contains('object-table') ? [child] : findTables(child));
708
+ // Literal values of a cell, not including those that belong to nested objects
709
+ const findLiterals = (elem) => Array.from(elem.children).flatMap(child => {
710
+ if (child.classList.contains('literal-value')) {
711
+ return [child];
498
712
  }
499
- return result;
500
- };
713
+ return child.classList.contains('object-table') ? [] : findLiterals(child);
714
+ });
501
715
  const updateElement = (elem, resourceUri, replaceElements = true) => {
502
716
  elem.setAttribute('data-uri', resourceUri);
503
717
  elem.classList.add('resource-loading');
@@ -536,41 +750,99 @@ async function augment(rootElem, context, options = {}) {
536
750
  elem.appendChild(link);
537
751
  }
538
752
  };
539
- const augmentInner = (elem, contextStack) => {
540
- 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();
753
+ const linkLiterals = (valueElem, stack, expandOptions) => {
754
+ for (const literalElem of findLiterals(valueElem)) {
755
+ const iri = expandIri(literalElem.textContent.trim(), stack, { ...expandOptions, baseUrl });
756
+ if (iri && !iri.startsWith('@')) {
757
+ updateElement(literalElem, iri, mergedOptions.replaceElements);
547
758
  }
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']];
759
+ }
760
+ };
761
+ // The stack with the object's own context on top, if it has a loadable one
762
+ const pushEmbedded = async (stack, context) => {
763
+ try {
764
+ // Loading modifies the context, which belongs to the caller's data
765
+ const copy = JSON.parse(JSON.stringify(context));
766
+ const entries = await loadContextEntries(copy, { baseUrl, requestTimeout: mergedOptions.requestTimeout });
767
+ return entries.reduce(pushContext, stack);
768
+ }
769
+ catch (e) {
770
+ console.warn(`Error loading embedded context: ${e}`, { cause: e });
771
+ return stack;
772
+ }
773
+ };
774
+ const augmentNode = async (table, inheritedStack) => {
775
+ const embedded = embeddedContexts.get(table);
776
+ // Only wait when there is something to load
777
+ const stack = embedded === undefined ? inheritedStack : await pushEmbedded(inheritedStack, embedded);
778
+ const children = [];
779
+ const rows = Array.from(table.querySelectorAll(':scope > tbody > tr')).flatMap(row => {
780
+ const propElem = row.querySelector(':scope > .object-property');
781
+ if (!propElem) {
782
+ return [];
783
+ }
784
+ return [{
785
+ propElem,
786
+ valueElem: row.querySelector(':scope > .object-value'),
787
+ name: propElem.getAttribute('data-property') || propElem.textContent.trim(),
788
+ }];
789
+ });
790
+ // Type-scoped contexts apply to this node only, in lexicographical order of the types
791
+ const types = rows
792
+ .filter(({ name }) => asKeyword(name, stack) === '@type')
793
+ .flatMap(({ valueElem }) => valueElem ? findLiterals(valueElem) : [])
794
+ .map(elem => elem.textContent.trim())
795
+ .sort();
796
+ const nodeStack = types.reduce((result, type) => {
797
+ var _a;
798
+ const scoped = (_a = findTerm(type, stack)) === null || _a === void 0 ? void 0 : _a['@context'];
799
+ return scoped === undefined ? result : pushContext(result, scoped);
800
+ }, stack);
801
+ for (const { propElem, valueElem, name } of rows) {
802
+ const keyword = asKeyword(name, nodeStack);
803
+ let childStack = stack;
804
+ if (keyword === '@type') {
805
+ // Types are resolved before applying their scoped contexts
806
+ if (valueElem) {
807
+ linkLiterals(valueElem, stack, { vocab: true, base: true });
556
808
  }
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
- });
809
+ updateElement(propElem, RDF_TYPE, mergedOptions.replaceElements);
810
+ }
811
+ else if (keyword === '@id') {
812
+ if (valueElem) {
813
+ linkLiterals(valueElem, nodeStack, { base: true });
814
+ }
815
+ }
816
+ else if (keyword) {
817
+ // Other keywords (@graph, @reverse, @nest...) keep the current context
818
+ childStack = nodeStack;
819
+ }
820
+ else {
821
+ const definition = findTerm(name, nodeStack);
822
+ const propertyUri = expandIri(name, nodeStack, { vocab: true });
823
+ if (propertyUri) {
824
+ updateElement(propElem, propertyUri, mergedOptions.replaceElements);
825
+ }
826
+ if ((definition === null || definition === void 0 ? void 0 : definition['@context']) !== undefined) {
827
+ childStack = pushContext(stack, definition['@context']);
828
+ }
829
+ const coercion = definition === null || definition === void 0 ? void 0 : definition['@type'];
830
+ if (valueElem && (coercion === '@id' || coercion === '@vocab')) {
831
+ const valueStack = (definition === null || definition === void 0 ? void 0 : definition['@context']) === undefined
832
+ ? nodeStack : pushContext(nodeStack, definition['@context']);
833
+ linkLiterals(valueElem, valueStack, { vocab: coercion === '@vocab', base: true });
566
834
  }
567
835
  }
568
836
  if (valueElem) {
569
- augmentInner(valueElem, newContextStack);
837
+ children.push(...findTables(valueElem).map(child => augmentNode(child, childStack)));
570
838
  }
571
839
  }
840
+ await Promise.all(children);
572
841
  };
573
- augmentInner(rootElem, [context]);
842
+ const rootStack = pushContext([], context !== null && context !== void 0 ? context : {});
843
+ const rootTables = rootElem.classList.contains('object-table')
844
+ ? [rootElem] : findTables(rootElem);
845
+ await Promise.all(rootTables.map(table => augmentNode(table, rootStack)));
574
846
  }
575
847
 
576
848
  const WGS84_EPSG_CODES = new Set([4326, 4979]);
@@ -781,7 +1053,8 @@ const POPUP_CSS = `
781
1053
  word-break: normal;
782
1054
  overflow-wrap: normal;
783
1055
  }
784
- .${POPUP_CLASS} .leaflet-popup-content .object-value {
1056
+ .${POPUP_CLASS} .leaflet-popup-content .object-value,
1057
+ .${POPUP_CLASS} .leaflet-popup-content .array-value {
785
1058
  min-width: 0;
786
1059
  max-width: none;
787
1060
  word-break: normal;
@@ -893,7 +1166,7 @@ function recenterOnResize(popup) {
893
1166
  });
894
1167
  }
895
1168
  async function createJsonLDGeoJSONLayer(L, data, options = {}) {
896
- const { ldContext, popupOptions = {}, augmentOptions = {}, onEachFeature: userOnEachFeature, coordRefSys: coordRefSysOverride, proj4: proj4Override, crsAttribution = true, ...geoJSONOptions } = options;
1169
+ const { ldContext, popupOptions = {}, augmentOptions = {}, baseUrl, maxDepth, maxElements, onEachFeature: userOnEachFeature, coordRefSys: coordRefSysOverride, proj4: proj4Override, crsAttribution = true, ...geoJSONOptions } = options;
897
1170
  let geoData = data;
898
1171
  const crsInfo = coordRefSysOverride
899
1172
  ? detectCrs({ coordRefSys: coordRefSysOverride })
@@ -923,7 +1196,10 @@ async function createJsonLDGeoJSONLayer(L, data, options = {}) {
923
1196
  if (!feature.properties || Object.keys(feature.properties).length === 0)
924
1197
  return;
925
1198
  const container = document.createElement('div');
926
- createPropertiesTable(feature, container);
1199
+ createPropertiesTable(feature, container, {
1200
+ ...(maxDepth !== undefined ? { maxDepth } : {}),
1201
+ ...(maxElements !== undefined ? { maxElements } : {}),
1202
+ });
927
1203
  injectPopupCss();
928
1204
  const className = [POPUP_CLASS, popupOptions.className].filter(Boolean).join(' ');
929
1205
  // Large default maxWidth: the popup adapts to the table's natural width; the CSS cap (a share
@@ -936,8 +1212,8 @@ async function createJsonLDGeoJSONLayer(L, data, options = {}) {
936
1212
  const contextsToMerge = [dataContext, ldContext].filter(v => v != null);
937
1213
  if (contextsToMerge.length > 0) {
938
1214
  const contextArg = contextsToMerge.length === 1 ? contextsToMerge[0] : contextsToMerge;
939
- loadContext(contextArg).then((resolvedContext) => {
940
- augment(container, resolvedContext, augmentOptions);
1215
+ loadContext(contextArg, { baseUrl }).then((resolvedContext) => {
1216
+ augment(container, resolvedContext, { baseUrl, ...augmentOptions });
941
1217
  });
942
1218
  }
943
1219
  },